docs/internal/frontend.md

Shared client frontend lifecycle

internal/frontend owns local endpoint resolution, daemon readiness, startup handshake, and joined connection shutdown. It also composes AgentHub setup before handing one authorized stream to the existing typed client and TUI. It does not own wire schemas, leaf filtering, event queues, or TUI presentation.

See CLI, TUI, ezagentapi, the JSONL catalog, and byte-offset stream assembly.

Entry points

NeedEntry point
Resolve local socket without side effectsResolveEndpoint
Ensure the default daemon is readyEnsureDaemon
Prepare legacy CLI startupPrepare
Connect a ready typed local clientConnect
Join connection shutdownClient.Close, then Client.Wait
Open client-only AgentHub stateprivate openDefaultHubClient
Compose Hub setup and remote TUIRunHubWithRemote
Hand an application stream to the typed clientConnectRemoteApplication

A supplied local socket is dialed directly and never autolaunched. RunHubWithRemote never probes, launches, or falls back to the local daemon.

The temporary unreleased-Hub gate belongs to internal/hubfeature, not this transport package. cmd/ez-agent checks its enable policy before Hub parsing, client state, offline bookmark actions, or connection setup. CLI help and TUI command visibility use the same policy. Normal distributions omit the sibling marker and have no config/environment override or separate build variant. Remote access needs no local Hub daemon; the executable marker is only opt-in release policy. Dashboard executable lookup is a separate operation used by pkg/tui/local_hub.go at launch-time preflight. Both currently share side-effect-free sibling detection, following the real client executable's symlinks, requiring a regular executable file, and never searching PATH. See AgentHub mode for user-facing behavior.

Native remote recovery observation

Client.TunnelStatusObserver() borrows the existing application handle's clienttransport.TunnelStatusObserver. It returns nil for local clients and plain direct handles without Hub observation. The handle's existing Close/Wait path remains the only transport owner. No Hub status enters EzAgent JSONL.

The TUI installs one cancellable watcher for its current connection epoch. Replacement cancels and joins the old watcher; Close and transport completion also join it. Queued updates recheck the epoch and cancellation before delivery. A watcher keeps at most one pending UI notification, which reads the latest snapshot when delivered. Intermediate pulses can coalesce. Dispatch and UI callbacks run outside observation and watcher locks, with no status history.

Recovering shows a native status-bar warning that the conversation may be stale. The displayed remaining milliseconds are explicitly the last observed duration, not a countdown or a fresh local grace deadline. Recovered clears the warning without reopening inner TLS or the application, resending hello, or changing CWD or leaf intent. Terminal/local failure can show before Joined, but observation never initiates teardown. The existing joined connection result ends the TUI. Only an accepted terminal/resource_limit or known local native cause establishes pressure. A generic terminal, missing notice or unknown loss stays generic failed. Fixed failure text survives terminal teardown through the TUI return error. The reader retains its current epoch's joined disconnect result before buffering the callback. Startup promotion uses that result before discarding callbacks, so failure before a normal layout exists cannot become a successful blank exit.

Frontend tests and TUI tests cover this internal integration. Shipped terminal interactions use the separate computer-use guide.

Visible joined shutdown

pkg/tui/remote.go:runStartup owns shutdown in both local and Hub modes. The first Ctrl-C, context cancellation or terminal input failure cancels startup and suppresses ordinary client callbacks. It queues a DRAINING screen on the UI lane and waits for the physical draw to complete before calling the installed client's Close. If terminal initialization fails or Run never starts, it skips the draw and still closes and joins the owner.

Close and the disconnect-reader join run outside UI callbacks and locks. The screen's spinner and dispatcher remain available during that wait. Then shutdown stops and joins animation and dispatcher work before stopping tview. Timer/widget cleanup runs on the UI lane, or after Run and dispatch have joined. A remote session handed to this lifecycle has no second deferred close owner.

Repeated Ctrl-C uses the same once-owned shutdown. It does not restart a deadline, issue a second Close or force-abort the transport. Hub feedback names the existing 30-second FIN-drain bound and 65-second recovery deadline. These are transport bounds, not a new TUI timeout or a countdown from a stale status observation. No service supervision, Hub wire fields or EzAgent JSONL semantics change.

A native failure found while ordinary callbacks are suppressed still survives through the joined reader result. Known pressure keeps its fixed pressure error; unknown loss stays generic failed. Terminal input failure is also a non-success return, even if caller cancellation races it.

TUI shutdown tests cover startup and active cancellation, feedback before a blocked close, in-flight UI work, repeats, animation during join and owner release. Select isolated terminal checks for affected interactions; they do not replace routed recovery regressions.

Before normal traffic

Local startup resolves, probes or explicitly starts when unavailable, waits for readiness, dials, and validates hello. Failed startup closes and joins the connection. The startup deadline is cleared after hello.

Hub startup prepares client-only identity, obtains a deliberate saved or new Hub target, performs admission when needed, reconnects exactly for the directory, selects or authorizes an endpoint, and opens a fresh application stream. Bare --hub always opens the chooser; an explicit alias, last, address, or new target is already deliberate. Alias and success-order mechanics live in hub_saved.go.

The saved chooser retains recognized-revoked rows and shows current accepted pins separately from Hub genesis and ordinary-success history. Bare --hub never chooses a sole row. readmit selects an exact numbered saved address and requires confirmation. An explicit alias, address or last resolving to a recognized-revoked entry offers this same action or cancellation instead of ordinary connect. The action first recovers an exact retained claimed credential; only when none exists does it request fresh claimant-locked JOIN WORDS. A retained nonapproved terminal decision offers recover, explicit fresh, or cancellation; fresh does not delete that old recovery record. Several matching retained claims require a numbered record choice. Fresh input is offered for multiple records only when all are completed nonapproved decisions, never while any approval is pending. The chooser labels pending claims, unanswered requests and completed nonapproved decisions separately. Existing unanswered requests require the same admission details. Neither a failed ordinary connection nor unknown transport loss automatically requests an invitation or records revocation. The transport checks for other nonterminal claimed selectors again after human input and binds fresh request preparation to that checked store revision; the frontend snapshot is not the enforcement boundary. Failure guidance keeps the pin/address and points to manual recovery. An authenticated invitation.NonApprovedError, from fresh admission or recovery, instead reports that the completed decision was saved, did not grant access and has no approval pending for that claim. It points to readmit to check the retained decision or explicitly enter a fresh invitation, without revealing rejection versus cancellation or describing a known decision as unknown transport loss. An existing local alias named readmit remains usable with explicit --hub readmit; the word is an action in the bare chooser.

Claimant-card pauses occur for admission, including explicit re-admission, and Add agent. Secret input borrows the terminal, disables echo, serializes prompts, restores the exact saved state on every exit, and flushes canceled input. Confirmation labels independent values as matched and candidate-derived values as diagnostic. Detailed ioctl and PTY evidence lives in hub_prompt.go and its tests.

Ordinary saved-Hub reconnect and endpoint approval recovery use a pre-install saved-authority decision. Explicit saved-Hub re-admission and its claim recovery keep the current pin instead and stop on a changed authority. The transport's separate legacy admission-recovery API still supports explicit successor review. For successor decisions, the frontend displays the complete old and new KEY CHECK words, check bytes and fingerprints, then requires approve or deny. Empty input, failed output, cancellation and deadlines cannot approve. Denial persists without changing the accepted pin. Same-authority operational certificate renewal requires no prompt. The backend rechecks the exact store revision before installation; the display never claims that trust was saved before that commit.

A numbered authorized endpoint uses its saved descriptor and never falls back to authorization after open failure. The chooser merges only exact matching private endpoint IDs and SPKIs with available, published, nonconflicted public rows and a valid, unexpired endpoint receipt. Unapproved identities are not numbered choices. Conflict rows are visible error entries with the endpoint ID, binding generation and up to two origin fingerprints, KEY CHECK tuples and bytes, but have no selection number. Production remote opening and availability come from verified publication, a usable binding and a current eligible route. Remote selection retains exact evidence through prepare/ready/tunnel; it never falls back to a local endpoint. The chooser enumerates saved descriptor IDs independently of discovery. Approved endpoints missing from the public list remain visible as offline. Discovered endpoints without a usable carrier remain unavailable. Recognized revocations remain visible as revoked even after the public tag expires or the client restarts. Expired approvals remain visible as local history, including when discovery is missing. Revoked takes precedence over expired, and neither status restores access when a public tag disappears. These rows have no selection number. Status explanations distinguish missing discovery, revocation, expiry, conflicting origins and unusable publication or carrier. Conflict guidance directs the intended owner's local administrator to stop cloned writable state and publish a higher binding; origin diagnostics are bounded to two and grant no trust. A newly approved descriptor replaces the old approval and revocation marker. Local bookmark list/select/forget controls are implemented separately from endpoint authorization and operate only on TUI convenience state, as described below. Shipped shell return, exit status, terminal restoration and reconnect belong to the process suites and selected computer-use checks. Add agent preserves authorization intent, including reauthorization when a stale descriptor exists. It matches four independently supplied endpoint KEY CHECK words and the mandatory check byte across direct and learned identities. Multiple complete tuple matches require an independently supplied complete fingerprint identifying exactly one match. Zero matches, conflicts, withdrawal, words-only collisions with a different check byte and tuple/fingerprint disagreement refuse without making a TLS connection. Local parse diagnostics identify malformed input and contradictory supplied forms; public directory diagnostics distinguish zero from multiple complete matches. They never quote input or expose invitation-secret or remote TLS details. The residual risk is a collision in both words and byte. A learned identity can be resolved for display but cannot start authorization or application open until a route exists. Several matching interrupted claims require explicit numbered selection.

Before each final ordinary reconnect hands off to endpoint TLS, the frontend reloads the exact private descriptor, even when the refreshed public tag window is empty. It rejects a recognized revocation, missing descriptor, or changed approval revision, secret, receipt, endpoint key or profile, and decodes the existing receipt's access expiry against effective client security time. Equality at expiry is ineligible; a persisted future floor prevents clock rollback from reviving access. Another client's recognition remains binding after the tag ages out; alias and first-use updates do not replace an approval. Explicit reauthorization may proceed without a usable old descriptor, but its final application reconnect must match the newly installed approval. Shared application open checks that same approval before gateway selection and again before loading the client TLS credential. Credential selection is bound to that exact approval in the store, with a post-file-load recheck of the approval and device reference. A same-second concurrent revocation or fresh grant fails before the credential returns; the loaded signer is released. The returned signer also checks the exact approval under the store mutation and file locks through signing, so a later committed revocation, descriptor removal or replacement grant cannot use an already loaded credential. There is no fallback to the ID-only endpoint TLS provider. Refusals return fixed errors without certificate, proof, receipt or secret disclosure. Scheduled expiry blocks a new open but does not terminate an already-open application.

The frontend passes --cwd unchanged and never interprets remote CWD locally. The TUI resolves explicit or remembered remote CWD before application startup, then loads leaf recency for the exact endpoint/CWD pair. With no CWD, startup stops before JSONL hello. Application open owns transport and authentication, not root, leaf, CWD, or session policy.

The shipped --hub --bookmarks, --select-bookmark <endpoint> --cwd <dir>, and --forget-bookmark <endpoint> --cwd <dir> actions stop in the command adapter before frontend startup. pkg/tui/remote_bookmark.go enumerates the existing RemoteLastCWD and RemoteLastLeafByCWD maps. Selection and forgetting use the same locked updateTUIState narrow transaction as ordinary recency writes. Selection changes only the exact endpoint's remembered CWD. Forgetting deletes only the exact pair and clears the remembered CWD only when it matches, with no implicit fallback. These actions do not access trust stores, remote session storage, or RPCs. A later normal Hub connection retains deliberate Hub/endpoint selection, then uses the same before-hello CWD lookup and ordinary stale-leaf policy. There is no second bookmark store or live remote chdir/discovery. On Windows, the daemon and TUI share final state-directory creation with a protected owner-only DACL. Existing directories must already satisfy that policy; neither creator rewrites a hostile ACL. The TUI still verifies its opened directory and file handles. Unix daemon directory creation remains ordinary MkdirAll with mode 0700, without changing existing permissions.

After open, AgentHub changes framing only. Local and remote paths use the same JSON values, RPCs, callbacks, CWD-scoped session behavior, and existing TUI. The chooser and transport-status UX extend in place; they do not add a pre-TUI session chooser or remote protocol mapping.

Editing invariants

  • Endpoint resolution has no launch policy; autolaunch applies only to the unavailable default daemon.
  • Readiness uses cancellation and bounded individual probes/hello attempts, not one package-wide deadline.
  • A malformed, failed, or not-ready startup closes and joins its owner. A not-ready hello returns to readiness waiting.
  • Close initiates shutdown; Wait also joins transport loops and callbacks.
  • ezagentapi owns correlation and connection-local Itr; CLI and TUI adapters own event-delivery policy.
  • Unsupported secret-input targets fail rather than echo. Writers remain borrowed and synchronous.

Code and tests

lifecycle.go owns local startup. AgentHub responsibilities are split among hub_client.go, hub_prompt.go, hub_admission.go, hub_saved.go, hub_endpoint.go, hub_application.go, and hub_run.go; tests sit beside them. startup_parity_test.go checks both typed entry paths. Platform compilation is covered by just vet-frontend-platforms. The direct-handshake review owns trust ordering and client transport owns recovery policy.

An empty verified directory displays a discovery-empty message, saved approval status rows, and Add agent. An independently supplied identity reaches the same zero-match resolver as an absent or suppressed target in a nonempty directory. Zero matches never solicit JOIN WORDS or dial endpoint TLS. Add agent can resolve a published learned remote identity and use its production routed invitation carrier. An unavailable carrier stops before endpoint TLS and JOIN WORDS; there is no direct fallback. Verification closes before explicit confirmation, then a fresh exact-pinned tunnel precedes claim preparation. A revoked descriptor can enter this explicit fresh authorization only with independently verified current identity and a published reachable carrier. Conflicts remain non-connectable and display only the supplied witness fingerprints, role-correct checks and binding generation. The client authorization contract owns exact recovery and transport ordering.

Common trust presentation

identity.Presentation supplies canonical role, fingerprint, KEY CHECK and byte values with explicit independent-match or candidate-diagnostic provenance. hub_identity.go owns one confirmation renderer. Its closed Hub and endpoint callers reject mismatched evidence, wrong roles and altered presentation values before output. Claimant, successor and conflict-origin views use the same canonical identity owner; signed successor continuity and directory origins remain evidence, not consent or independent endpoint authentication.

clienttransport.ProjectEndpoint owns status and ordinary-open eligibility for both descriptor merge and chooser output, with explicit effective security time. Offline, revoked, expired, conflicted and unavailable rows are not numbered application choices. Explicit Add agent is separate from ordinary open and needs an available, published, nonconflicted invitation carrier plus independent endpoint evidence. The frontend passes that evidence into EndpointAuthorizationRequest so the transport checks it before releasing the client certificate. Saved recovery retains its narrow credential and cannot turn an old revoked descriptor into ordinary authorization.

Verified confirmation records now include constructor-owned canonical SPKI and complete provenance. The screen validates every record field before output; substituted SPKI, ID/SPKI disagreement, short or fingerprint provenance changes, and altered aliased bytes fail with zero display output. Diagnostic ID-only records cannot masquerade as a verified transport binding.