Skip to content

feat(tui): reopen past sessions and see which ones need you - #5237

Closed
kovtcharov wants to merge 3 commits into
amd:feat/tui-minimal-claude-stylefrom
kovtcharov:claude/tui-session-resume-623d01
Closed

kovtcharov wants to merge 3 commits into
amd:feat/tui-minimal-claude-stylefrom
kovtcharov:claude/tui-session-resume-623d01

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Quitting the terminal UI used to lose the conversation from view: you couldn't list past sessions, reopen one, or tell that a session was stuck on a permission prompt. Now /sessions and gaia tui --resume list recent sessions with title, age and status (running, waiting on you, done, failed). Sessions waiting on you come first, and eval and scheduled runs are hidden unless you ask for them. Reopening a session redraws its transcript and restarts the agent on its saved history, so GAIA remembers the conversation, not just the screen.

Builds on #5155 (this PR targets its branch and will retarget to main when it merges); lands after v0.25.0. Agent UI counterpart: #5221.

Closes #5230

Not covered yet: a GAIA installed from the Agent Hub or by the desktop installer talks to the TUI through the background service, which keeps no sessions. There, /sessions and --resume say so instead of showing an empty list. Supporting it needs the HTTP sidecar to persist sessions too, which is a follow-up.

🔍 Technical details
  • Store: reuses the flagship stdio agent's existing per-session transcript (~/.gaia/tui/history/<id>.sqlite3, --history-file). With the new --session-kind, the agent also writes <id>.json (title, kind, status, pid, turns) and <id>.jsonl (one readable line per finished turn) beside it. The Agent UI database isn't used: the TUI flagship never wrote to it.
  • Open vs. closed: the agent holds a lock on <id>.lock for its whole life. A session counts as open while that lock is held, not while its pid is alive, because a killed window releases the lock and a reused pid can't fake it. Reopening a session claims it immediately, and a second window trying to open it is refused.
  • Contract: tests/fixtures/stdio/gaia_stdio_wire.json → session_index, checked by both the Python and Go tests; described in spec §10.4.
  • Failures: a listing write that fails is logged and shown as a status line. It never costs the user's turn and never hangs exit.
  • UI: the list is its own component (ui/sessions). chat/model.go changed only by two cases in submit. The help panel's / row was shortened to two lines so the panel still fits 40 rows without scrolling.

Test plan

  • go vet ./... and go test ./... in tui/, including golden frames for the list at 100 and 40 columns, all kinds, empty, and under NO_COLOR
  • pytest on test_session_index.py, test_stdio.py, test_stdio_wire_contract.py, test_transport_dispatch.py and tests/unit/test_amd_gaia_urls.py (173 passed); black, isort and flake8 clean on the touched Python files
  • Live drive (driving-the-tui, Windows Terminal, stdio flagship from this checkout, isolated memory): told it a codeword, hit a permission prompt (the index read waiting), denied it, quit mid-conversation, relaunched with --resume, picked the session, and it answered the codeword from the reopened history. Also checked --resume=<prefix> directly, /sessions at 40 columns, and refusal of a session open in another window.
  • Cross-process lock on Windows with real processes: the Go probe sees the Python agent's lock, a second agent is refused, a hard kill releases the lock, and reopening marks the dead turn failed
  • Re-drive the full TUI flow after the review fixes (pick-before-chat for bare --resume). This machine's embedded Lemonade was swapped to an older version mid-session, so the readiness gate blocked it; covered by root unit tests meanwhile

Quitting the terminal UI used to lose the conversation from view: there was no
way to list past sessions, reopen one, or tell that one was paused on a
permission prompt. /sessions and `gaia tui --resume[=<id>]` now list recent
sessions with title, age and status (waiting on you first; eval and scheduled
runs hidden unless asked for), and reopening one redraws its transcript and
restarts the agent on its saved history, so the model remembers it too.

- The flagship stdio agent already keeps each session's model transcript in
  ~/.gaia/tui/history/<id>.sqlite3. With --session-kind it now also keeps
  <id>.json (title, kind, status, pid, turns) and <id>.jsonl (one readable line
  per finished turn) beside it, and holds <id>.lock for its life. The lock, not
  the pid, marks a session open: it dies with the process and a reused pid
  cannot fake it. Layout pinned in tests/fixtures/stdio/gaia_stdio_wire.json.
- A failed listing write is logged and reported on the wire; it never costs
  the user's turn or hangs exit.
- Bare --resume shows the list before the first chat opens, and the chat keeps
  receiving events while the list covers it mid-session.
- A flagship running through the background service (hub/installer build)
  keeps no sessions yet; /sessions and --resume say so.

Closes amd#5230
@github-actions github-actions Bot added documentation Documentation changes tests Test changes tui Go terminal UI (gaia-tui) labels Oct 16, 2026
@kovtcharov

kovtcharov commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor Author

The red "Unit Tests (macOS, py3.12)" is a pre-existing flake in an unrelated test, not this change: 1 of 22,202 tests failed, test_stream_reader_abandon.py::test_stop_ends_the_reader_and_its_socket[headers_then_silence]. Re-running it needs a maintainer (this account cannot re-run jobs on amd/gaia).

🔍 Technical details

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

You can now list past terminal sessions, see which one is stuck on a permission prompt, and reopen one with the agent's memory intact. The design holds up: a lock file decides whether a session is open, a crashed turn is shown as stopped mid-turn, and a failed write to the session listing never costs the user a turn. Nothing blocks a merge. One thing to fix:

  • GAIA_HISTORY_FILE no longer works under the TUI. The SDK docs tell users to set it to resume a transcript. The TUI now passes its own history file to every flagship launch, so the variable is ignored without any message. Either honour it, or fail loudly and update that doc paragraph.

Real-world evidence

N/A: no evidence bundle was produced for this run. The PR body reports a live Windows Terminal session: remembering a codeword across --resume, a session stuck on a permission prompt listed as waiting, and refusal of a session already open in another window. The author's own re-check of the "pick first" flow for bare --resume after the review fixes is still unchecked (blocked by a local Lemonade version swap). Here I ran go test on every changed Go package and all passed. The Python tests couldn't run because pytest isn't on this runner. For the UI flow, this verdict rests on static review plus the author's report.

🔍 Technical details

🟡 GAIA_HISTORY_FILE is ignored when launched from the TUI (tui/internal/client/factory.go:160, tui/internal/ui/root/sessions.go sessionLaunch)
--history-file defaults to os.environ.get("GAIA_HISTORY_FILE") (stdio.py:1513), so an explicit flag wins. sessionLaunch now always mints an id and passes --history-file, so a user following docs/sdk/core/agent-system.mdx:866 ("Set GAIA_HISTORY_FILE=… to explicitly resume the same transcript") gets a fresh session and no error. That's a silent fallback under CLAUDE.md's fail-loudly rule. Pick one fix:

  • honour the env var in sessionLaunch. A non-hex stem can't be listed, so in that case launch without --session-kind.
  • refuse it at startup with a pointer to --resume, and update that doc paragraph to match.

🟢 IndexedOut.write can drop an event on a non-JSON line (session_index.py:459)
json.loads runs outside guarded, which only catches OSError. A non-JSON line would raise ValueError before self._out.write(data), losing exactly the terminal event the docstring promises to keep. Today every writer goes through _write, so this can't fire yet, but the guard costs nothing:

                try:
                    event = json.loads(line)
                except ValueError:
                    logger.warning("session listing skipped a non-JSON line on the wire")
                    continue
                guarded(self._index, partial(self._index.observe, event), self._out)

🟢 --resume= (empty value) silently starts a new session (tui/internal/cli/root.go:205)
resumeArg == "" means "off", so --resume= (for example from a script with an empty variable) launches a fresh chat with no warning. Consider rejecting it when cmd.Flags().Changed("resume") is true and the value is empty.

🟢 Probing the lock can briefly block a reopen (tui/internal/daemon/lock.go FileHeld)
FileHeld takes and drops the lock. An agent starting on that session at that instant fails its non-blocking lock and refuses to start with "open in another window". The window is microseconds and the message is recoverable, so this is a note, not a fix request.

Strengths

  • The rule for whether a session is open (lock, not pid) is the same on both sides and was checked against each other: flock on Unix, and byte-0 LockFileEx against msvcrt.locking on Windows. A cross-process test proves a hard kill releases the lock.
  • One wire fixture pins the file layout for both the Python and Go tests, and every reader error tells the user what to do ("delete it to drop the session; its transcript is kept").
  • The session list is its own component, and the root model holds startup until the pick for bare --resume, so no warm-up is spent on a chat that's about to be replaced. Golden frames cover 40 and 100 columns and NO_COLOR.

…esume

GAIA_HISTORY_FILE pinned the flagship's transcript before this PR and was then
silently overridden by the TUI's own --history-file. It is honoured again: a
file the session list can reopen (<id>.sqlite3 in the session store) stays
listed, any other path is kept unlisted with a note in the chat saying why, and
--resume refuses to run while the variable is set.

- An empty --resume= (a script's unset variable) is refused instead of starting
  a new session.
- The agent retries its session lock briefly, so the TUI probing whether a
  session is open can never turn a free session away.
- A non-JSON line on the wire is logged and still reaches the host, never
  dropped by the session listing.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Addressed the review in ee73f55: all four suggestions are taken, none disputed.

  • GAIA_HISTORY_FILE works under the TUI again. Every launch uses the file it names, as before this PR. It is listed in /sessions when it is a session file the list can reopen (<id>.sqlite3 in the session store); any other path is kept but unlisted, and the chat says why. --resume refuses to run while the variable is set. The SDK doc paragraph, the TUI guide and the CLI reference now say this.
  • Empty --resume= is refused with the working forms, instead of starting a new session.
  • Lock probe race: the agent now waits out a brief hold on its session lock before refusing, so the TUI checking whether a session is open can't turn a free one away.
  • Non-JSON line on the wire: logged and still passed to the host, never dropped.

The macOS unit-test red is the unrelated test_stream_reader_abandon flake explained above; this push re-runs it.

🔍 Technical details
  • sessionLaunch returns a plan (file, id, kind, notice). A pinned file is listed only when its stem passes sessionstore.ValidID and its folder os.SameFiles the store; otherwise it launches with --history-file alone. ForAgent now accepts a history file without a kind, and still refuses a kind without a file. An explicit /sessions pick wins over the pin mid-session.
  • _hold_lock retries LK_NBLCK/LOCK_NB with the same 10 × 20 ms budget as the index write.
  • Tests: root (store file listed, elsewhere and odd-named unlisted with notice, pick wins), client (unlisted args), CLI (resumeFromFlag), launch (--resume + pin refused), Python (non-JSON passthrough, lock waited out). go test ./..., go vet ./..., and pytest on the touched paths (175 passed) are green locally.

kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
Before: after the daemon restarted on a new port, Cancel, Respond,
Confirm and the full-access toggle in the TUI failed with "connection
refused", which says nothing about what happened. After: the TUI finds
the restarted daemon and says plainly that the restart ended the agent
session and nothing was sent; the next message starts a fresh session
there. A run cannot be carried over, because the daemon stops its
sidecars on shutdown and the next one starts fresh. Lands after v0.25.0.

Sending a new message already re-read `instance.json` (through
`EnsureAgent`) before this change. What was broken was every call made
against the session the TUI already held.

Reproduced by `TestCancelAfterADaemonRestartSaysTheRunEnded` and
`TestDoDoesNotCarryARunScopedCallToARestartedDaemon`: on main the first
fails with "connection refused", and the second can't compile because
main has no way to tell run-scoped calls apart. Both pass here.

## Test plan
- [x] `go vet ./...` clean; `go test -p 1 ./internal/daemon/
./internal/client/ ./internal/ui/preflight/` passes
- [x] Run-scoped calls (cancel, answer, confirmation, follow-up,
permission decision, full access) are never sent to a restarted daemon;
the client still learns the new instance
- [x] Other relayed calls ensure the agent on the restarted daemon, then
replay
(`TestDoEnsuresTheAgentBeforeReplayingARelayCallToARestartedDaemon`)
- [x] A call whose connection drops after a daemon received it is never
replayed (`TestDoNeverReplaysARequestThatReachedTheDaemon`)
- [x] A replacement that fails its checks keeps its typed
`VersionError`/`StaleError` in the chain, plus the original failure
- [x] Live, real TUI against a fake daemon that, like the real one, has
no sidecar after a restart (isolated homes): `/full-access confirm`
after the restart said "GAIA's daemon restarted, which ended the agent
session this belonged to. Nothing was sent", and the restarted daemon
received no `/bypass`. The next message ensured the agent and was
answered. Main says "actively refused it".

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

- `Client.Do` re-reads `instance.json` only on a dial failure
(`*net.OpError` with `Op == "dial"`, reachable through the new
`RequestError.Unwrap`). The new instance goes through the same `verify`
and `CheckVersion` as attach.
- `Request.RunScoped` marks calls about state in a running sidecar. They
return `DaemonRestartedError` together with the new instance. Other
`/v1/<agent>/…` calls run `ensureOn` (split out of `EnsureAgent`, with
its agents-floor check) on the new daemon first.
- A restart on the same port shows up as a rotated token (401) rather
than a refused connection; that path takes the same step, so it is
covered too (`TestDoDoesNotCarryARunScopedCallAcrossASamePortRestart`).
- `SSEClient.do` keeps whichever instance answered, so the six calls
that used to drop it also follow a plain token rotation.
- The client test fake answers 503 "no running sidecar" after a restart
until the agent is ensured, the way the real daemon does.
- The log names the dial's own failure (refused, timed out,
unreachable).
- No overlap with amd#5264/amd#5282 (daemon close) or amd#5237 (sessions).
</details>
Keeps both [Unreleased] CHANGELOG entries and points the --resume reference at
the guide's new home, docs/guides/tui.mdx.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Synced with #5155's branch in c77acd3 (it had moved on and conflicted): both [Unreleased] CHANGELOG entries are kept, and the --resume reference now links to the guide's new home, docs/guides/tui.mdx. Go tests and vet, pytest on the touched paths (175 passed), and the internal doc-link check are green locally.

The one red check, "Test GAIA CLI on Linux (Full Integration)", isn't caused by this PR. Since ubuntu-latest moved to Ubuntu 26.04 on Oct 20, the Lemonade PPA has no build for it, so apt installs Ubuntu's own lemonade-server 10.2.0 and the job's version check fails (dpkg reports 10.2.0-0ubuntu2 but … reports 10.2.0). main fixed it in #5416 by pinning the job to ubuntu-24.04, and main has passed since. That fix reaches this PR once #5155's branch picks up main again. Merging main in here would pull unrelated commits into this diff.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Superseded by #7165, which re-lands this work on main without depending on #5155.

@kovtcharov kovtcharov closed this Nov 11, 2026
kovtcharov-amd added a commit to lakshyab20/gaia that referenced this pull request Nov 12, 2026
Quitting the terminal UI loses the conversation from view: you can't
list past sessions, reopen one, or tell that a session is stuck on a
permission prompt. Now `/sessions` and `gaia-tui --resume` list recent
sessions with title, age and status (running, waiting on you, done,
failed). Sessions waiting on you come first, and eval and scheduled runs
stay hidden unless asked for. Reopening a session redraws its transcript
and restarts the agent on its saved history, so GAIA remembers the
conversation, not just the screen.

Closes amd#5230. Replaces amd#5237, which was stacked on the still-open amd#5155;
this works on main without it.

**Not covered yet:** a flagship installed as an Agent Hub binary runs
through the background service, which keeps no sessions. There,
`/sessions` and `--resume` say so instead of showing an empty list. The
terminal installers' agent and a source checkout run over stdio and are
covered.

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

- **Store:** reuses the per-session transcript the stdio agent already
keeps (`~/.gaia/tui/history/<id>.sqlite3`). With `--session-kind`, the
agent also writes `<id>.json` (title, kind, status, pid, turns) and
`<id>.jsonl` (one readable line per finished turn) beside it, so the TUI
lists and redraws sessions without reading SQLite.
- **Open vs. closed:** the agent holds `<id>.lock` for its whole life,
and the TUI tests that lock (`filelock.Held`) rather than the pid. A
killed window releases it, and a reused pid can't fake it. Reopening
claims the session at once, and a second window is refused.
- **Contract:** `tests/fixtures/stdio/gaia_stdio_wire.json` →
`session_index`, checked by both the Python and Go tests; described in
spec §10.4.
- **`GAIA_HISTORY_FILE`** still pins every launch. It's listed only when
it's a session file the list can reopen, and `--resume` refuses to run
while it's set.
- **Failures:** a listing write that fails is logged and shown as a
status line. It never costs a turn and never hangs exit.
- **UI:** the list is its own component (`ui/sessions`). `chat/model.go`
gains only two `case`s in `submit`; `/sessions` joins the help panel's
Commands block, so the panel still fits 40 rows.
</details>

## Test plan

- [x] `go test ./...` and `go vet ./...` in `tui/` with an isolated
`GAIA_HOME`/`GAIA_TUI_HOME` and Lemonade pointed at an unused port,
including golden frames for the list at 100 and 40 columns, all kinds,
empty, and under NO_COLOR
- [x] `pytest` on `test_session_index.py`, `test_stdio.py` and
`test_stdio_wire_contract.py` (163 passed); black, isort and flake8
clean; internal doc links pass
- [x] Live drive on Windows (this branch's `gaia-tui`, this checkout's
stdio agent, isolated memory):
- told it a codeword, and hit a write prompt while the session read
`waiting`, then denied it
  - quit mid-conversation; the session closed cleanly
- wiped memory, relaunched with bare `--resume`: the list opened before
any chat, the session reopened with its transcript, and it answered the
codeword from the reopened history (memory held nothing before the
question)
- [ ] Reopen a session on macOS and Linux

---------

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

documentation Documentation 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