docs/pkg/tui.md

pkg/tui interactive terminal client

pkg/tui owns interactive presentation, UI-local state, and adaptation of daemon events to the selected leaf. It does not own daemon lifecycle, wire schemas, persisted sessions, or AgentHub trust setup.

Structural model

text
1typed JSONL events
2 -> selected-leaf and generation filter
3 -> canonical conversation projection
4 -> page controllers
5 -> terminal rendering
6
7local YAML -> preferences and recency only

The daemon owns sessions, turns, questions, and workflow metadata. The TUI keeps a projection of that state for one selected leaf. Controllers fetch missing content and reject stale replies. Views render the accepted projection. They do not decide protocol or persistence semantics.

UI-local state includes focus, selection, collapse state, geometry, temporary Hide choices, and recency. It can change presentation. It cannot create daemon facts.

Connection runtime

connection_runtime.go owns the socket TUI's single active app and the connection-manager handoff. The manager in connection_picker.go edits only connectionPreferences inside tui.yaml. Loading invalid preferences fails closed; it must not select the zero-value Local default after a load error. Built-in Local availability, Local autolaunch, and the startup default are independent controls. Explicit command-line destinations bypass startup defaults.

Switching joins the old app's ordinary shutdown before constructing its replacement. It does not abort server work, replay requests, or retain background connections. Nonempty composers and unresolved submission/directory work block a switch. Temporary destinations never write connection or leaf/CWD recency; ordinary sidebar presentation preferences remain shared.

Custom local sockets use the same no-autolaunch path as SSH. The frontend owns hello; internal/remotedestination owns the raw SSH stream and exact child. Auto socket discovery uses a separate fixed remote command to read the remote runtime path. It may be unavailable under restricted SSH policies. The startup UI supplies cancellable masked authentication prompts through OpenSSH askpass, not through the daemon. Secrets are never profile or session state.

Client.HelloAck() exposes the installed connection's received acknowledgement, including the optional service NodeID. OnHelloAck preserves the same identity for callback consumers. The client does not supply a node ID or display it in the UI.

The connection name appears in the sidebar border. The CWD row opens the live directory picker. Client usage describes the interactive options and their scripted counterparts.

Remote model availability

Model pickers refresh remote availability and show canonical browser refs, including nested upstream IDs. Redundant default-source prefixes are hidden; explicit refs remain visible when an ordinary ref would select a different route. Current-row markers and thinking metadata use the destination's effective configuration to match existing explicitly prefixed selections. Discovery does not rewrite saved or inherited draft refs, and typed /model accepts the equivalent explicit ref without adding aliases to picker or completion lists. If optional projection discovery fails, exact-ref lookup remains available. Entries flagged unavailable or not-found have unknown capabilities, not confirmed lack of thinking support. Draft model selection and the session editor preserve the current thinking intent for those entries. The editor labels it as retained with unknown capabilities and does not offer it as a validated option. Runtime route resolution remains authoritative.

A pending draft model picker has its own presentation generation and cancellable wait. Changing pages, opening another context/completion menu, replacing the request or shutting down retires that wait. Late replies cannot open a popup over a newer view even if the draft and leaf generation are unchanged.

Local port forwarding

Chat renders validated tunnel destinations beside Markdown link labels. Clicking a tunnel link or selecting one with Tab or Shift+Tab while chat has focus and pressing Enter opens verification directly. Ctrl+T remains an optional chooser. The TUI shows a separate verification dialog before starting any work and returns to the same chat after acceptance or decline. After approval, tunnelManager borrows the existing frontend RPC for asynchronous discovery and loopback binding. It owns a bounded collection of independent listeners and joins their setup and cleanup on exit. Entries are local to the app, not a chat or leaf. /tunnels lists active and pending entries and retained setup failures; selecting one shows its source, service, local URL and status, with a stop or cancel action. Inbox also shows live entries without creating leaf records or changing metadata. Active Inbox rows prioritize the stable ID and assigned localhost:PORT; starting rows say the relay is unassigned, and stopping rows retain their state. Filtering still matches full URLs, source ports, paths, service names and states. Ctrl+T remains an optional link chooser. Late setup results are closed rather than published after cancellation. The adapter does not own the frontend connection. See the tunnel guide for user instructions and limits.

Sidebar

The sidebar keeps its bordered leaf info box at the top, showing usage, CWD, leaf ID and thinking level. The CWD status shows the folder name, such as cwd: dunnet ▾, for local and remote sessions; parent paths do not displace it. Remote sessions retain their server identity. The directory picker and Inbox headings still show full paths. Below it is a centered, borderless Inbox / Sessions / Commands selector, followed by one shared / filter input with an empty-only hint for the selected section. The selected list has a border and fills the remaining height. The info box remains visible in all three sections. Selected tabs are black on white; other tabs are white on dark gray. Deliberate Inbox and Sessions choices save sidebar_tab in shared tui.yaml; Commands does not replace that preference. Startup restores it before the first refresh, including an empty Inbox. With no saved preference, the first successful refresh selects Inbox if it has any eligible entries, otherwise Sessions. Later refreshes keep the selected section. Running clients do not adopt another client's tab changes, even through save acknowledgements. Tab cycles through the selector, filter and visible list. Left/Right or h/l on the selector change sections; Enter or Down moves to the filter. Filter Enter or Down focuses the selected list, Up returns to the selector, and Escape clears the filter. Left/Right also change sections directly from an empty filter, keeping focus there. When the filter contains text, those keys move the cursor normally. The focused selector tab is bold. Clicking or tapping a tab changes the section immediately.

On the main chat screen, bare Ctrl+Left/Right with a completely empty composer selects Inbox / Sessions / Commands in visual order, stopping at either end without wrapping. It shows the sidebar if hidden, focuses the destination list and reveals its keyboard cursor, including at a clamped end. Ordinary arrows then move the cursor immediately. Changing sections never opens a thread or runs a command. Plain selector Left/Right and h/l still wrap.

With Inbox visible and selected, bare Ctrl+Up/Down opens the thread above/below the currently open thread in the filtered Inbox order, not the highlighted row. It selects and reveals the destination without moving keyboard focus or changing alert metadata. Navigation stops at the first/last thread without reopening it. If the current thread is absent, including a welcome draft, Ctrl+Up opens the top thread and Ctrl+Down opens the bottom. An empty Inbox does nothing; other sections and a hidden sidebar do not provide this thread navigation.

These Ctrl+arrow shortcuts work from the composer, chat and sidebar controls. Any composer text, including spaces or newlines, leaves existing editing intact. A focused nonempty sidebar filter and other editable fields keep their keys. Extra modifiers, including Ctrl+Shift, are not shortcut matches. Popups, completion menus and full-screen pages keep their existing key ownership.

The sidebar lists keep three independent states: the keyboard cursor, the open session, and the scroll viewport. The cursor is black on white only while the list has focus. Blurring the list removes the cursor highlight but remembers its position; focusing the list restores the highlight. The open session stays bold regardless of focus, with a ◀ drawn in a reserved final column inside the border, separate from clipped or horizontally scrolled text. Neither cue implies the other. If the open session is outside the visible list, no other row receives its marker.

A single click or tap focuses the list and highlights a row without opening it or running a command, even when that row was already highlighted. Two taps on the same entry within 500 ms activate it once; the taps can land in different columns. Enter also activates the cursor row. Clicks elsewhere, keyboard input, scrolling, filter changes and section changes cancel a pending double-tap. Session disclosure arrows expand or collapse with one tap and never open a session. Border and blank-area taps only focus the list.

The mouse wheel moves the viewport without changing the cursor, selecting a session or taking focus. The cursor and open session may scroll out of view. Keyboard cursor movement brings the cursor into view; redraws do not. The initially restored session is revealed once after layout. Ordinary list refreshes preserve the top visible entry where possible and clamp the old offset if that entry disappears.

Inbox includes active and pending local tunnel entries, plus persistent leaves across the active connection whose metadata alert_time parses as RFC3339 and is strictly before the current time. Leaves are grouped under exact working directory paths. The current directory comes first, other paths are alphabetical, and Unknown working directory comes last when root metadata is unavailable. Long path headings wrap to the sidebar width. Within each group, leaves are flat and sorted by alert timestamp, newest first; parent trees cannot reorder them. Search matches session names and models and omits headings with no matching leaves. Tunnels remain listed once under a separate Tunnels heading after the directory groups, with their existing metadata search.

The first Inbox row shows Scope: All directories by default. Enter or two taps on that row toggles to Current directory and back. Scope only filters the presentation, not metadata discovery, and remains in memory for the active connection without changing shared preferences. Headings have no activation, context actions or open-session marker. Ctrl+Up/Down skips headings, the scope control and tunnels. Opening a leaf in another directory changes the client's working directory and selected leaf together; it does not move a root or clear alert metadata. Sessions remains current-directory filtered with its ordinary tree grouping and recency order. Until global metadata first loads, Inbox uses the legacy current-directory leaf list.

The metadata projection requests alert_time and alert_idle; alert_idle does not affect Inbox membership. Selecting a session does not clear either key. The periodic refresh re-evaluates cached timestamps and fetches metadata every 10 seconds, so future alerts appear after they mature without requiring another session event. Usage remains available through /usage and Commands.

/settle removes the current session's alert_time and opens a welcome draft after acknowledgement. /unsettle sets it to now. /snooze <time> sets a future deadline. The sidebar Snooze action and bare /snooze open the same preset popup with 1m, 5m, 30m, 1hr, and 1day. Choosing a preset applies it immediately; Escape cancels without changing metadata. The popup never changes the composer draft. Other times can be entered directly with /snooze <time>. Examples include 1hr, in 30 minutes, please remind me in 2min, tomorrow 9am, Friday at noon, local calendar dates and RFC3339 timestamps. These explicit Inbox commands change only alert_time and leave alert_idle untouched. If the leaf is running with idle notification armed, becoming idle still consumes alert_idle and replaces alert_time with now, even after a settle or snooze. Interactive composer submissions arm the idle alert with one public update_leaf_meta call; the arming rules and the steer caveat are in session.md. Immediate prompt or steer submission errors set alert_time to now only when idle notification was armed for that attempt or session and remains enabled. An arming failure is visible and does not count as a successful arm. Accepted runs use the daemon's normal idle/error conversion, without a duplicate client attention write. Failed text remains associated with its origin in client RAM; another view is never replaced. Alert-write failures are reported separately and do not undo an accepted message. A metadata timeout is reported for that attempt only. Later submissions and explicit Inbox actions send their current metadata changes normally, without replaying the old write or carrying its error forward. A successful write produces no warning about an earlier timeout; a new failure is still reported. An empty Inbox is valid and does not trigger selection, a new draft, or restoration of old alert metadata. Sending stays in the thread unless the user navigates.

Snooze first parses whole-input basic intervals, dates and clocks locally, including simple reminder prefixes. It never guesses from a clock substring. Unfamiliar wording or units, including prose containing a clock, use the reusable runBackgroundRequest worker with the resolved small model on a fresh temporary leaf, without changing the selected session or inheriting its conversation. The request has a short system instruction and the complete original input; tools, plugins and triggers are disabled. The model must return only {"at":"RFC3339 timestamp with timezone"} or {"after_seconds":3600} on success, or {"error":"human-readable reason"} when uncertain. Each form requires exactly one key, without duplicates; the error reason must be a nonblank string. Shared JSON extraction handles response wrappers. Snooze validation rejects non-object responses, invalid fields and nonfuture times. Go computes interval deadlines from the command's reference time; the model does not do timestamp arithmetic. Model uncertainty appears as Snooze model: ... in the error memo, distinct from request failures and invalid model responses. None of these failures changes Inbox metadata or retries the model, and no time is invented.

Background requests have bounded execution and cleanup. Cancellation aborts and deletes their temporary leaves where possible; cleanup failures are errors. Inbox actions and automatic submission notifications share one metadata write lane per leaf. Enter reserves notification intent before asynchronous command classification; a newly created draft reserves its leaf when the ID becomes known. Reservation alone does not supersede an Inbox action, so /help cannot cancel a pending snooze. Explicit settle, unsettle and snooze commands activate intent before resolving their arguments; automatic notifications activate it at the write boundary. New active intent cancels superseded parsing and skips older attention changes that have not reached write admission. A superseded idle arm still enables alert_idle, but does not remove newer alert_time attention. Already-admitted writes retain their bounded acknowledgement wait. A newer RPC attempt starts after that wait returns, including on timeout. A timeout does not cancel the server operation or establish its execution order relative to later requests, but it does not permanently block that leaf's metadata writes. Each admitted metadata write has an independent 10-second context and the API's 5-second inactivity watchdog. Matching RPC heartbeats renew the inactivity wait, but not the caller's deadline. Rejected-send policy reads use the same 10-second context and 5-second inactivity watchdog. Explicit argument resolution has a one-minute budget. These bounds do not impose a single deadline on a handoff waiting behind earlier writes.

Editor ownership releases at Prompt/Steer ACK or NACK, not notification completion. A new handoff may await a prior metadata acknowledgement in its worker; typing, navigation and other leaves remain usable. Late notification errors remain separate from send errors and accepted retry text. Shutdown cancels unresolved explicit actions and joins admitted writes and owned submission workers before closing the application connection.

Local and remote sessions

Welcome drafts

/new, Ctrl+N and New Session immediately open an explicit client-local draft, not a permanent empty thread. The history frame word-wraps the welcome text to its available width, then centers the resulting block in both dimensions on every draw, including after resize. Wide panes show two lines; phone-sized panes wrap the question onto additional lines instead of clipping it:

text
1Welcome to ez-agent!
2What do you want to work on today?

The sidebar displays ???? for the draft's leaf ID. Selection and recency never contain a helper ID. Entering a draft clears this CWD's remembered real selection. Startup restores only the exact remembered persistent chat if it still exists. No remembered chat, a missing chat, or an exit from a draft opens the welcome view even when other chats exist. Explicit session selection remains deliberate. Draft text and settings do not persist across exit. Successful deletion of the current chat also opens a draft; deleting another chat leaves selection alone. Settle/delete failures stay in the current chat, and late acknowledgements cannot replace a newer leaf selection. A highlighted neighboring sidebar row is not a chat selection.

Draft model and thinking choices inherit the prior chat's choices as /new did. Model, thinking and mode changes stay in RAM. Ctrl+E, /edit, and Edit Session open the existing editor for the draft's model, thinking, tools, plugins, filetypes, and triggers. Discovery reads use the helper, but edits stay local to the draft. Closing and reopening the editor preserves choices and composer text; a new draft resets configuration choices to CWD defaults. Successful routine changes do not add history boxes. One client-owned temporary helper supports initial discovery, provider completions and explicit user macros through the existing typed APIs. It is created on demand with the exact connection CWD, is_temp: true and autosubscribe: false, without session-origin or Inbox metadata. It is reused across drafts and remains available after real-chat creation. Sessions and Inbox exclude it. Remote paths stay opaque; the client never scans local files to complete a remote CWD. Model/thinking completion uses draft choices, not helper settings. Discovery replies and completion replies retain generation/text guards.

Mode discovery may call builtin.setmode --mode on the helper, but selecting a mode does not mutate helper settings. Mode choices are a client snapshot scoped to the connection, endpoint and exact opaque CWD. Same-CWD switches, /new, draft-to-real handoff and transient discovery errors retain that snapshot. There is no per-Enter mode-list refresh. Failed initial macro or mode lookup retries on the existing 10-second refresh tick while the snapshot remains unloaded. One initial attempt is in flight per exact scope, including across same-scope navigation. Scope changes and shutdown invalidate it; already-admitted helper RPCs keep their bounded acknowledgement ownership. Navigation still refreshes the current leaf's macro inventory after the shared initial attempt. There is no finite retry budget or immediate retry on Enter. A tick skips an in-flight attempt; after failure, a later tick admits the next attempt. Discovery keeps the API's 5-second macro-inventory and 10-second mode-list reply timeouts; on-demand helper creation has its own 10-second acknowledgement bound. These are per-operation bounds, not a whole-discovery deadline. Loaded mode snapshots are not refreshed by periodic ticks. Before initial discovery completes, repeated unresolved slash invocations are visibly rejected with their text retained, without launching probes or messages, rather than silently becoming prompts. Exact /build remains a mode shortcut when discovered; /build foo keeps ordinary prompt semantics. Built-in, macro and skill precedence is unchanged. Live reconfiguration consistency and cross-client mode-cache synchronization are not provided. Cached choices can receive an ordinary service rejection; the client does not attempt rollback or recovery. User macros otherwise run normally on the helper. Their explicit results, including NoOp, and real errors appear as one concise status message without replacing the centered welcome or accumulating chat-history boxes. Empty-conversation macro behavior belongs to the handlers, not to a TUI macro prohibition.

The first confirmed message captures editor revision/text and freezes all draft settings. One creation/setup attempt runs at a time. A newly persisted leaf can appear in Sessions before its creation reply. If a confirmed submission already owns that leaf, draft setup waits for its ACK or NACK, then claims the released leaf. Neither confirmation loses ownership, including during shutdown. The TUI creates a persistent leaf with model/thinking and autosubscribe: false, acknowledges user-session metadata and the chosen mode, then applies the complete editor configuration in one acknowledged update. Explicitly empty selections remain empty. Setup retries reuse the created leaf and frozen choices. After setup succeeds, it selects the leaf through the normal switch/snapshot path only if the user is still in that draft. Otherwise it completes the captured message off-screen without changing selection, subscription, recency or the new composer. The original leaf's canonical head supplies the parent, never the currently selected projection. Invalid inherited models retain the existing default-model fallback. Creation failure preserves the composer and settings; partial setup failure retains the created leaf for retry rather than creating another. Only errors known to precede storage creation permit retry, such as invalid-model rejection. Generic service errors can follow persistence and are treated as uncertain, just like a lost creation reply, so another Enter cannot create a duplicate. Prompt failure keeps the real chat selected if it is still current; otherwise its error and retry text remain with the origin without replacing the new view. First-send ownership survives that transition and prompt failures, including slash-prefixed text. Repeated Enter cannot clear or resubmit the same pending confirmation. The editor clears only after accepted submission when the originating view, revision and exact text still match.

Enter reserves the visual thread or draft before asynchronous slash/provider classification. That origin owns classification, creation/setup, original-head resolution, alert arming and the Prompt/Steer ACK or NACK. Repeated Enter on that origin cannot launch another probe or handoff, even after editing; other leaves remain usable. Typing does not confirm a second message. Navigation and shutdown do not cancel or retarget owned work. Presentation guards prevent old callbacks from clearing later edits, selecting an old leaf, or displaying errors in another thread. Rejection releases the lock and retains the captured text for retry. An unchanged retry keeps its confirmed classification even if macro/skill inventory changes. Editing after the attempt resolves permits new classification; a later deliberate identical message is not deduplicated. No automatic next-Inbox or new-draft action follows sending. A crash between creation and sending can still leave an ordinary empty chat; there is no atomic backend operation.

The helper owner is scoped to one connection and exact CWD. Shutdown stops new confirmation admission. Already-owned classification, setup and terminal callbacks use the run owner's UI dispatch lane, which remains available through the submission join even after the client stops admitting ordinary protocol and presentation callbacks. Owned draft provider queries keep their captured helper through that join; ordinary completion queries remain closed. It joins those handoffs, then cancels remaining helper callers and deletes only this client's helper with a bounded acknowledgement. A final UI barrier drains queued submission results before RPC close and dispatcher shutdown. This lane does not admit new submissions or remove presentation guards. Admitted creation retains acknowledgement ownership through cancellation so its known ID can still be deleted. Completion's UI deadline does not cancel the helper's bounded RPC acknowledgement waiter. If that lifecycle deadline expires, cleanup reports uncertainty even when helper deletion succeeds. A work timeout does not disable later operations on the known helper ID. Only uncertain creation refuses another creation attempt. Cleanup is idempotent and retains its result. Failed or uncertain cleanup is returned as an exit error. External SIGINT or SIGTERM can close a Hub tunnel before helper deletion; shutdown reports the resulting transport or cleanup error. Terminal Ctrl-C and /quit use the joined TUI shutdown path. If the helper cannot be created, off-screen sent draft text may be lost after navigation. This broken-connection case has bounded error reporting, not durable draft recovery or retries of uncertain creation. Daemon startup cleanup handles temporary leaves left by a crash or transport loss.

Shutdown joins creation/setup and admitted prompt workers before helper deletion and connection close. Creation/setup retains the existing RPC reply budgets, which can total 40 seconds: two 10-second creation attempts for invalid-model fallback, 5 seconds for metadata, 10 seconds for mode setup, and 5 seconds for editor configuration. Prompt/steer and helper operations retain their own RPC reply bounds. These workers can overlap; there is no new global shutdown deadline. Transport recovery and connection drain retain their existing bounds.

Choosing a working directory

/cwd opens a live directory picker. The sidebar's CWD row opens the same picker. For keyboard-only access, select Commands in the sidebar, search for cwd or directory, and activate Working Directory with Enter. The CWD status row is not a separate Tab stop. Recent directories come from ListCwdDetails, with chat counts, active chat counts and last activity when the daemon supplies them. Directories with active chats sort first, then each group sorts by newest activity. Missing or invalid timestamps sort last within their group; equal timestamps use exact-path alphabetical order. The current directory is marked, not pinned above the sort. Activity lines are indented two spaces. Activity refreshes every five seconds while the picker is open, preserving the selected path when rows reorder. The selected full path appears below the list; Tab moves between the list and absolute-path entry. Enter chooses a directory, Ctrl-R refreshes, and Escape cancels.

/cwd /absolute/path chooses a directory directly. Path bytes after the command's single separator are passed unchanged, including spaces, quotes, repeated separators and dot segments. There is no shell parsing, variable expansion, client-side stat or directory creation. Local and remote connections use the same RPC. The daemon is authoritative for path acceptance.

A directory-only choice calls UpdateCwd with an empty leaf ID, so it changes only the connection's browsing CWD and never relocates an existing root. Opening an Inbox item in another CWD first resolves its exact leaf_stats.root_cwd, then uses UpdateCwd(cwd, leafID) to change directory and subscription together. The client serializes this with other feed selections and buffers replay until the new projection is installed; it does not send a second switch_leaf. A missing or invalid directory fails closed rather than using the group label or current connection default. An unconfirmed directory change, with or without a leaf selection, blocks sending until reconnect. On success for a directory-only choice, the session browsers use that CWD and the TUI opens an empty draft with fresh directory defaults. Send or clear any typed composer first. Pending submissions and draft-creation retries also block a change rather than losing their work. The old CWD helper stops admitting work and joins acknowledged operations before deletion and replacement. Replies from the previous UI generation cannot update the new draft. The change is non-dismissible while its acknowledgement is pending; Ctrl-C still uses the joined shutdown path. After helper cleanup, each update RPC has a hard acknowledgement deadline that matching heartbeats cannot extend, bounding its shutdown join. An explicit rejection keeps the old browsing CWD. A timeout or mismatched acknowledgement leaves the connection's CWD unconfirmed; the TUI does not claim it stayed unchanged or allow further sending. A helper creation rejected before storage, including an invalid starting CWD, does not require cleanup and does not block choosing another directory. An uncertain creation or helper cleanup failure still blocks the change and asks for a restart.

Transport and startup

After JSONL hello, the TUI behaves the same over a local Unix socket or an AgentHub application stream. Session operations, addons, workflow visualization, completion, editing, and cache cleanup use the same typed client. Do not add a remote command allowlist, alternate event map, or transport-specific RPCs.

Only setup identity, native transport status, and the local recency key may differ. The client UX extends those boundaries in place.

Local recency maps CWD to leaf. Remote recency maps exact authenticated endpoint fingerprint plus exact remote CWD to leaf, with an optional last CWD per endpoint. Explicit --cwd wins. With no remote CWD, startup stops before hello. Remote CWD is opaque locally and recency grants no trust. Locked YAML updates must preserve local recency, other endpoint/CWD entries, and shared visual preferences. Do not migrate the unshipped remote_last_session tuple.

Startup retains protocol callbacks while validating a remembered leaf or opening the initial draft. Its separate native disconnect watcher reaches the joined shutdown owner even if an outstanding setup RPC fails before the reader publishes loss. No Enter/Esc dismissal or successful layout promotion is required for transport failure to stop startup. Shutdown keeps the UI dispatcher alive for visible drain feedback, then joins transport, reader and startup producers before terminal finalization. Joined remote classification takes precedence over a setup RPC error, preserving known resource pressure and otherwise reporting fixed generic failure.

Both shipped TUI entry points pass the command's signal-cancelled context into the lifecycle. Parent-only SIGINT/SIGTERM reaches borrowed dashboard cancellation and exact-child join in local as well as remote mode. Healthy intentional /quit or keyboard Ctrl-C returns success after joined shutdown. The TUI removes only the local jsonlpipe.ErrClosed sentinel branch during owned shutdown; a joined native failure, pressure, failed drain or malformed transport remains a failure. Passive disconnect results are not normalized as intentional quits.

Bounded shared convenience state

One background worker per client saves tui.yaml. Navigation and sidebar changes enqueue updates without waiting for file locks, encoding, writes or syncs on the UI thread. Saves run serially; pending changes to the same selection or preferences coalesce to the latest value. Each save still reloads under the shared file lock and changes only its owned fields, preserving other clients' updates. Results and errors return through UI dispatch. Shutdown stops admission and drains accepted saves outside the UI thread; a stalled filesystem can delay exit, but not navigation. Abrupt termination can lose a queued convenience-state update.

tui.yaml stores recency and visual preferences, not sessions or trust. The limits in persistence_bounds.go are 4 MiB for input and encoded output, 16 KiB per decoded scalar, 4096 entries per map, and 8192 entries across recency maps, including endpoint maps. These allow thousands of workspaces while keeping reads, map growth and serialization finite. Local mutations normalize only their own CWD key. Remote endpoint/CWD pairs remain exact opaque values. Other local, remote and preference entries are not filtered or canonicalized.

Before YAML tree construction, a borrowing scan admits at most 131072 conservative lexical units and 16 combined levels of block/flow nesting. persistence_yaml.go tracks compact block markers by column, including same-line chains and collection-valued keys. It counts decoded scalar bytes without constructing strings: double-quoted Unicode escapes charge their UTF-8 width, doubled single quotes charge one byte, and multiline plain/quoted/block values retain one budget through folding and chomping. Indentation and scalar content are separate, including spaces retained on space-only block lines. Pending whitespace, properties and directives also have finite byte ceilings. Before typed decoding, the tree must fit 32768 expanded nodes, depth 16 and the collection/scalar ceilings, including aliases and ignored fields. Cyclic or excessive alias expansion fails. Input must be UTF-8 and contain one document. Encoding first counts actual escaped output, then allocates the bounded result; its source complexity must also pass read admission. Bookmark listing counts its quoted output before emitting anything, with a separate 16 MiB ceiling.

Updates reload under the shared OS lock and admit insertions before map growth. Stale-leaf cleanup removes only its requested leaf and now-empty endpoint map from the private transaction copy before admitting the remembered CWD, so the projected net count decides capacity. Updates then write a private temporary file, flush it and atomically replace the state file. Oversized or malformed input is not rewritten, even for Forget. No automatic pruning, eviction or session deletion occurs. An over-limit mutation reports an error and leaves the prior file and UI snapshot intact. A failure after rename returns the committed state with an explicit error, so the controller applies that state but still reports the persistence failure.

Unix operations are relative to an opened, current-user-owned directory. Deliberate directory symlink relocation remains supported; state and lock symlinks, nonregular files, foreign owners and multiple links fail closed. The directory and lock are secured to 0700/0600; an existing state file must already be 0600. Nonblocking opens prevent a substituted FIFO from hanging a read. Reads have a fixed byte ceiling and reject observed in-place changes; atomic replacement leaves a complete old or new snapshot. Lock identity is checked after acquisition and again before commit.

Windows uses directory-handle-relative native opens, rename and cleanup, with handle-based regular/disk-file, reparse-point, single-link, owner and protected owner-only ACL checks. Open locks deny deletion; read handles deny in-place writes. Existing nonprivate Windows ACLs fail closed rather than being migrated. Sharing conflicts may fail an operation. Windows has no directory-fsync promise. On both platforms the boundary excludes malicious same-user or privileged writers, who can already modify the client's private files.

Client-local terminal handoff

While Hub is unreleased, internal/hubfeature.Enabled controls whether /hub appears in the built-in registry, Commands reference and slash completion. The marker policy is described in the client guide. Disabled dispatch reserves the exact /hub token and reports fixed unavailable guidance without a dashboard lookup, terminal handoff, RPC, macro or model prompt. Invalid and prose invocations retain the no-argument grammar and go to normal prompt handling rather than a colliding macro or mode.

When enabled, /hub is a UI-local action in both modes. local_hub.go uses internal/hubfeature.Executable to resolve only the real client's regular, executable sibling ez-agent-hub and invokes --config with the client's inherited cwd and environment. The dashboard alone owns its Hub administration connection and offline rules. No EzAgent RPC or remote target is passed to it.

The existing runStartup lifecycle supplies a cancellable handoff context and uses tview.Suspend on the UI lane. Protocol callbacks stay in the existing ordered dispatcher while the dashboard owns the terminal. Return restores that terminal before queued callbacks run. The application client, leaf, generation, CWD and recency are not reset. A native disconnect signal closes before its queued UI callback, allowing the child to be canceled while that lane is occupied. Lifecycle shutdown cancels borrowed work before waiting for visible drain feedback. Child cancellation kills and joins that exact process; only after Suspend resumes may the existing shutdown stop/finalize the screen.

The enable policy and dashboard lookup are separate, though both currently use the same sibling detection. Lookup is repeated at launch-time preflight. Missing or unusable siblings fail before borrowing. Start and exit errors return through terminal restoration and render a localHub memo. --config never becomes a normal Hub daemon launch or another application API client.

Access source and usage

The daemon's optional access_source sets the existing composer border title: provider/model [Local], [OpenAI Sub], [Muse Sub], or [API Key], with green, orange for either subscription, or light-pink title text. Mode text stays before the model. The label is always present in that one title line; narrow screens clip it naturally rather than wrapping, collapsing it, or adding a row. Absent and unfamiliar values display neutral [Unknown]; unusable connections display neutral [Unavailable]. Focus, selection, and error styling remain separate from the source color.

The session editor exposes the full source. /usage and the sidebar's Usage action open a read-only, wrapping, scrollable Usage page at any time, including during execution. Ctrl+E or /edit during a run opens this page instead of the mutable session editor, with a memo explaining why. The page describes the captured source while running. Idle and unloaded leaves use known configuration or cached discovery information, falling back to the remembered source for the same resolved model. Remote labels come from the host, never consumer credentials or model names. The editing warning appears only while running. OpenAI subscription details say Using ChatGPT plan and show Manage usage: https://chatgpt.com/settings/usage. A daemon-supplied muse_subscription displays Muse subscription, without that ChatGPT link or manage action. Recognizing this value does not itself detect a Muse subscription; the daemon must supply the source. The page uses the daemon's captured active source while running; no mutation controls are present. Opening /usage renders local session state only. It does not submit an inference prompt, request OpenAI quota data, or refresh credentials. Manage usage opens only the fixed settings URL in the system browser. Turn counts use singular 1 turn. Narrow terminals can wrap and scroll the full disclosure and usage URL. Escape restores the prior page and focus.

On the read-only Usage page, U / Manage usage and its clickable footer action open the fixed ChatGPT usage URL in the system browser for an OpenAI subscription source. It is the primary OpenAI subscription action, with the full URL also visible for remote or browser-less terminals. Other access sources do not show that ChatGPT action.

The UI does not infer a source from model names, key presence, or endpoints. Accepted complete leaf snapshots replace its source, including neutral values. Leaf switches and disconnects clear it; fresh subscription replay restores it. Stats accepted by the per-leaf connection/visit/itr gates also refresh the computed source, even when the tip is unchanged and a live snapshot is already known. This picks up idle authorization changes without history reconciliation. Stale stats cannot replace a newer source, and stats do not take ownership of lifecycle or head state.

Durable UI invariants

  • Leaf ID plus app generation identifies the active visit. Queued callbacks and async results from an earlier visit must not apply after a switch.
  • leaf_updated is a complete replacement snapshot. Empty, zero, nil, and pending_questions: [] clear prior projection state.
  • The accepted snapshot's pending_questions is the sole source of the current project-config trust box. Repository text is never rendered as trusted security instruction; Hide is process-local and keyed by exact revision.
  • Connection-local positive Itr participates in the per-leaf snapshot watermark. It is neither a correlation ID nor cross-connection ordering.
  • Client serializes leaf switches and rechecks intended leaf after acknowledgement. Leaf-bearing events are filtered before UI admission and again when their callback runs.
  • Dynamic terminal content is escaped at the presentation boundary. RPC values retain raw data. Width calculations use terminal cells, not byte/rune counts.
  • Try Again and Edit operate only on reconciled canonical turns and send the exact current tip. Local warning/error memos never gain rewind actions.
  • Sent service error turns remain canonical history. Assistant exit_message presentation follows service/agent.
  • Sessions/tree/workflow views consume structured metadata and ordinary parent edges. They do not parse names or Workflow identity keys for semantics.
  • Async page results use the UI dispatcher and generation checks. Head hydration keeps the old view until one validated replacement can swap in a single redraw.
  • Internal macros are hidden from menus/suggestions but remain directly invocable by name.

Detailed coalescing, gap recovery, rendering geometry, workflow polling, and editor behavior belong to the purpose-named code and tests, not this overview.

Session trigger attachments

The session editor lists and toggles on_background attachments alongside on_preplugin, on_assistant, on_success, on_error, and on_idle. on_success and on_error remain per-model-run outcomes, even with background work remaining. on_background means model processing has stopped while provider-owned background activity remains; on_idle means real quiescence. These notifications do not end the TUI's persistent leaf subscription.

Background attachments load from active_background_triggers; an absent or invalid value inherits the leaf's effective defaults.triggers.on_background. Explicit [] or null stays disabled. Toggle writes resolve the same effective selection, so adding a macro preserves inherited attachments. Toggling the last attachment off writes an explicit [], not a missing configuration key. A failed effective-config lookup reports an error instead of overwriting inheritance. Internal macros appear only when attached at the start of that editor visit, and remain visible during the visit after being toggled off. A successful toggle invalidates older refreshes; replies from closed or replaced visits cannot change the view. User-invocable macro filtering remains based on on_user.

New session model selection

Ctrl+N, /new, and the New Session action keep the current model and thinking level when that model is still configured. If the daemon rejects the inherited model with invalid_model, the TUI retries once without a model or thinking override. The daemon then uses the configured default for the current working directory and that model's default thinking level. Startup session creation uses the same fallback. Other errors, including an invalid configured default, are reported without further retries. The old session is not changed.

Running progress

The transient progress block delays its first appearance by 250 ms to avoid flashing near-instant work. On a forward turn change while the leaf is running or background, an already-visible block can remain for up to 2.5 seconds while live producers refresh their targets. Further empty snapshots do not extend this grace period. A replacement keeps the block and its manual collapse state. Outside a turn handoff, empty snapshots remove it immediately. Idle or aborting state, rewind, and leaf switching also remove it immediately, including during a handoff. This is display-only smoothing; it does not retain or revive expired daemon progress.

Assistant response badges

Assistant headings show friendly names from stored other_meta.response_labels as uppercase badges, for example Assistant [BLUE] or Assistant [RED]. Multiple names appear in list order, including generic provider-neutral names. Badge text is escaped as a single-line field. Missing, null, empty, or malformed label data adds no badge, and the chosen model alias never supplies an inferred badge.

Badges appear when the canonical assistant turn metadata arrives and survive history reloads. They do not alter answer text, add a selection control, or change the configured model identity. OpenAI's response-reported Blue/Red mapping belongs to the provider adapter, not the renderer.

Typed user turns

The renderer hides a leading mode tag for mode-only, type-only, and combined forms. Tagged steer turns show You [DRAFT - STEER] while draft and You [STEER] once sent, retaining any mode label. The pending-turn flag alone does not cause decoration before the plugin writes the tag. Existing draft/sent updates redraw the heading.

Background bash completion user turns use the internal other_meta convention to show background → command (<id>) with existing collapsible tool-result styling. The metadata supplies origin and task identity; message prose or a type tag alone does not. The underlying source remains the stored user turn.

Background leaf state keeps ordinary idle editing and prompt eligibility. The session list uses yellow-green for background. The status bar keeps the active spinner and elapsed counter, replacing only the running label with background. The service supplies continuous timing across running/background transitions, including when a client reconnects. Model processing resumes on the same clock; the active view ends when both model work and background tasks have ended. This is presentation only: messages submitted during background wait are ordinary turns, not steers. Model processing and aborting retain their existing precedence and editing checks.

Ordinary tool-result Details keeps retained command captures as references. Opening a background completion's Details additionally starts an asynchronous lookup, never normal rendering. It walks stored parent turns to the startup result identified by the trusted task ID, then uses that result's occurrence-aware assistant-call pairing to recover the original Bash or Ruby arguments. The recorded output reference selects the bash: or ruby: capture directory; historical Ruby captures retain their bash: names. In local mode, the output section reads the last 100 lines from the retained capture under the service-advertised state directory. Reads are limited to a 256 KiB suffix, with an explicit notice when that cannot supply the full preview. Remote mode never uses the advertised directory as a client-local path; capture output is marked unavailable while original-call history remains available over the existing RPC. Local capture reads allow symlinks in the service-advertised state directory, then validate the resolved directory path. The state root and managed capture directories must be owner-controlled. Managed capture directories and the regular capture file are opened without following symlinks or blocking on special files. Platforms without that safe-open implementation show an unavailable notice rather than fall back to path-based reads. Missing history or expired output also produces an unavailable notice without hiding the stored completion. Closing or replacing the details view cancels the lookup, and updates recheck the connection and leaf generation. Reopening reloads it; the extra output and recovered arguments are UI-only and are included when copying the details, not added to the model's completion turn.

Neighboring contracts

Delayed agent_end or prompt_completed from an earlier model run cannot clear an active newer stream or revert its tip. The TUI uses published leaf state for that decision and releases only the matching request correlation. A completion for another request cannot clear the current request.