docs/multi-endpoint.md

Multiple endpoints, navigation and background monitoring

EzAgent can keep multiple independently authenticated SSH endpoints live. A runtime is identified by saved profile ID and exact host, port, account and socket path. Each owns its manager/client generation, workspace/CWD scopes, chat and action owners, uncertain operations, image intake, drafts and reading state. Identical leaf IDs on different endpoints are not interchangeable. No credentials are cached for reconnect.

Return, switch and disconnect

The launcher and ongoing notification return to the last live workspace. Back from chat opens the Connections dashboard without disconnecting. The sidebar connection picker switches to an already connected endpoint without signing in again; connecting another endpoint does not disconnect the current one. Dashboard rows show transport state, current workspace and the last available Inbox count. Counts are metadata snapshots, not proof that the server is reachable right now. Connection details shows a selectable Service node ID only when that exact endpoint's current service connection supplies a nonempty value. It identifies the service conversation database, not the SSH host or a trust credential; it is not saved and is omitted when disconnected or unavailable.

Workspace returns and notification destinations are read-first: they do not open the keyboard merely because the restored chat is idle or unloaded. Explicit composer taps and deliberate session-row selection retain their normal keyboard behavior.

A saved profile is not a live transport. Editing/deleting it never changes an existing connection's address or sessions. Live endpoints whose saved address has changed or been removed remain separately visible only while live. An explicit reconnect always targets the captured endpoint, never a newly edited address by profile ID alone. The browsing CWD scopes selection/drafts; it does not move a server session. Saved profiles may provide an initial CWD, but live dropdown choices and added directories are endpoint-owned RAM state, retained through quick switches and lost on app reload. Reopening a live endpoint does not overwrite that choice with a saved profile value. Inbox is endpoint-global by default, with an optional Current directory presentation filter. Required leaf discovery publishes as soon as it succeeds; optional root/CWD grouping never keeps Inbox loading or blocks its next refresh. Until that discovery's root mapping is available, unmapped leaves appear under Unknown working directory. A late mapping enriches only its own still-current successful leaf snapshot, never a newer refresh, another directory/tab, a hidden/detached sidebar or a replacement connection. At most one optional sidebar root lookup remains outstanding per connection generation; later leaf refreshes continue independently while it is pending. Failed leaves retain the prior snapshot and their error; roots cannot turn that into success. No elapsed RPC deadline is added. Grouping is presentation only, not authority to navigate: opening a leaf still requires the exact endpoint/root resolution below. Full session browsing always uses an explicit nonblank directory. Opening a session or notification resolves the exact persisted root CWD through an exact-leaf leaf_stats reply (or a same-generation authoritative root cache for a warm notification) and selects that scope atomically with the intended leaf, without briefly restoring another remembered leaf. The subscription owner sends update_cwd with both the default CWD and leaf ID; it does not mutate the persisted root. Exact remembered chat selection is a nonsecret reconnect convenience within that scope. Pending versus consumed notification destinations are modeled separately from the launch Intent: rotation does not revive a consumed destination. A newer Intent or live-row selection retires an older attempt's auto-navigation, not its explicitly admitted transport. Already-connected rows remain navigable while another endpoint is authenticating. After disconnect, the row is only a saved reconnect bookmark: no latched cleanup warning, old Inbox count or Current workspace designation. An edited/deleted old address does not leave a disconnected runtime-only row. A failed or timed-out drain still completes that particular disconnect future exceptionally, with a safe message; the manager does not store or replay it on the dashboard, chat recreation or a new connection. A late cleanup result cannot retire a newer connection. Failure does not prove remote cleanup succeeded and never authorizes automatic retries or aborting ordinary remote agents.

An explicit Disconnect action observes its own completion. If cleanup fails or times out, a short Android text toast reports that remote cleanup could not be confirmed, including when Chat has closed or the action came from the ongoing notification. Disconnect all starts every endpoint independently and reports one combined failure after all drains settle. Successful disconnects are quiet. This is transient, best-effort platform feedback, not a retained row flag, notification log or replay on launcher entry/rotation/reconnect. Process death can prevent final feedback; neither the result nor presentation triggers an automatic retry.

Disconnect closes only that endpoint after its owned-helper cleanup, without an elapsed drain deadline. Disconnect all initiates the same cleanup independently on every endpoint. Neither stops remote agents, settles Inbox entries, clears drafts nor replays unknown operations. The single foreground service remains until the final endpoint disconnects.

Process death loses RAM drafts, reading positions, live requests and transports. Remembered endpoint/selection data is only a destination for explicit reconnect. When no live endpoint remains (including after an app update/reload), the launcher quietly shows the disconnected saved connections, without an explanatory Snackbar or a special reconnect-destination badge. A saved notification destination likewise waits quietly for an explicit connection; its exact session still requires endpoint verification and root-derived scope resolution before navigation. Actual connection failures and unavailable explicit destinations retain their actionable feedback. There is no silent reconnect, service resurrection, cached unlocked key or saved account password. Biometric/PIN keys require fresh configured unlock; Skip remains without an extra ceremony. Changed host keys still fail closed. Concurrent same-host trust prompts capture the exact pin/revision they showed: stale first-use consent cannot replace a conflicting intervening pin, and stale Forget cannot delete a newer pin. Concurrent identical first-use trust is harmless and idempotent. Fresh unlock still follows trust; no prompt retains credentials.

Unexpected disconnect diagnostics

An unexpected disconnect shows a one-line cause and a Details action in chat and on its saved connection row. Details include the observation time, SSH session state sampled before cleanup, the detected layer, and safe protocol diagnostics when available (such as a recognized event name and an exact schema rule). Copy details copies only this bounded diagnostic text, not raw frames, message payloads, credentials or exception contents. The report is memory-only and is cleared by a new connection attempt, explicit disconnect or process exit.

  • SSH/network connection lost: the SSH session was disconnected at observation. This does not identify whether SSH itself, a VPN or the underlying network failed.
  • EzAgent service connection closed: the SSH session was still connected but its EzAgent socket/forwarding stream ended or failed. This is not proof that the whole service stopped; SSH can also detect an underlying network outage later.
  • Application protocol failure / Client application failure: framing/schema validation or an internal client callback/worker failed. A truncated frame alone does not prove a service bug. Ordinary provider-retry informational messages do not close the client connection.
  • Cause unknown: there is insufficient evidence to assign a layer.
  • Android local shutdown: the required foreground connection service could not start, its foreground notification publication failed, or Android destroyed it unexpectedly. The client fails closed and retires affected connections rather than leaving hidden SSH transports running. Details preserve a fixed typed local reason, not raw Android exception messages. This is distinct from explicit user Disconnect and does not establish a remote service or network failure. A failing service lifetime is guarded before synchronous disconnect publication; delayed starts/state callbacks cannot republish or resurrect that lifetime. Process death itself cannot guarantee a final in-memory report or notification.

The loss notification uses the same summary. Its body opens the app without reconnecting; its explicit Reconnect action and the Details dialog's Reconnect button use the ordinary fresh connection/credential flow for that exact saved endpoint. After connection, normal metadata polling and visible-feed reconciliation resume. No pending prompts, aborts or other operations are replayed, and no VPN/network repair or automatic reconnect is attempted.

Visible conversation versus background

Only the resumed chat owns a leaf feed. Pausing it (including external speech capture, voice settings, backgrounding and rotation) releases the feed, cancels queued history and recovery work and rejects late read callbacks. A pending switch ACK is not forgotten: it is serialized through a subsequent drop, even if it arrives after pause. An ambiguous switch failure also retains the possible feeds until drop. A typed leaf_not_found rejection proves an obsolete candidate is not current, so the bounded sweep continues to the other possible feed. An ambiguous network failure retains uncertainty instead of retiring candidates or spinning retries. Recovery-body requests still queued on a manager worker have independent thread-safe admission revoked when hidden/superseded; already submitted reads can finish but cannot publish hidden content. Returning resubscribes/reconciles the selected leaf. Sidebar discovery runs every ten seconds only while the chat is resumed; it stops on pause. Already admitted RPCs may finish, but they cannot start hidden transcript hydration/recovery work.

Endpoint switching keeps RAM composers, images, reading choices and pending-operation ownership. Activities and image shares capture their endpoint instead of consulting a mutable global connection in later callbacks. A voice result is discarded after an endpoint-switch round trip, but ordinary external recognition still returns through the established guarded voice/send pipeline. Settings, TTS and speech provider choices are unchanged. Backgrounding is never a request to abort server work.

One shared metadata clock

The service owns one 120,000 ms timer. Every tick starts asynchronous sessions.list requests for all connected endpoints in the same pass, with no per-endpoint staggering, synchronous waiting, leaf opening or subscriptions. Each request explicitly sends the empty cwd to request all directories on that endpoint, together with parent_leaf, session_origin, alert_time and alert_idle. list_leaves does not inherit the hello directory. This endpoint-global metadata read is independent of the visible Inbox's Current directory filter and never means global full-session browsing. Monitoring does not change foreground browsing or its filter. It does not fetch all roots or their configuration merely to warm navigation; target directories can be resolved on demand. A pending endpoint is skipped without blocking any peer. Connected RPCs have no elapsed/inactivity or monitor-owner deadline: the ticket stays pending until its result, actual failure, or cancellation/retirement. Later ticks and explicit refreshes join a still-owned pending request, not duplicate it. Heartbeats are informative, not required lease renewals. Fresh connection and visible app return also request immediate metadata refresh. See request waiting policy.

Metadata caches, counts and callbacks belong to an exact endpoint and connection generation. A generation change invalidates the cache and retires queued work; changing the browsing directory does neither. Already admitted reads from a retired generation cannot publish into its replacement. Each endpoint retains an independent global snapshot and alert ledger: identical leaf IDs on different SSH endpoints never share monitoring authority. Backend deduplication across distinct endpoint runtimes is deferred; server_id is not a unique backend identity and is not used to merge monitoring authority.

Doze, device sleep, OS process termination and user force-stop can delay/stop monitoring. There is no permanent CPU wake lock, exact-alarm promise or out-of-process monitor. The service's background monitor performs only metadata monitoring alongside SSH maintenance. The visibility gates above suppress transcript history/streaming/recovery and detached workflow UI polling. Existing operation/settings/cleanup ownership is retained so acknowledgements and teardown can settle safely without elapsed cutoffs; this is not periodic background transcript polling or permission to replay a request.

Notifications

Connection permission is requested by the existing explicit connect UI. Declining it or disabling a notification channel does not pretend delivery succeeded or silently close other connections: the dashboard remains the authoritative local status surface. Android may show foreground-service visibility through system UI even with permission denied. Notification preferences can be changed in Android's application settings.

  • SSH connections: quiet ongoing count/names, last-workspace navigation and explicit Disconnect all. Removing the final connection removes only this ongoing notification.
  • Inbox alerts: separate channel, endpoint/session identity, per-endpoint group and exact endpoint/leaf destination. The title is <connection> · <session title>; the text is the session's root directory, shortened from the start (for example …/Projects/EzAgentAndroid) with the full path in the expanded text, and never the leaf id. The notification is posted at once; a directory already known to the app (root cache or Inbox grouping) is included immediately, otherwise one exact-leaf leaf_stats read for that alert refreshes it silently. If that read fails the title-only notification remains. Each posted notification carries its alert instance (the alert time) in non-visible extras. A late directory answer updates only the notification that still shows the same instance; it never re-posts one that was already withdrawn and never overwrites a newer alert for the same session. (A user swipe between that check and the update cannot be excluded with public Android APIs.) Tapping the notification dismisses it. Viewing a session clears its notification, but does not settle remote metadata. The group summary remains while other alerts exist. Exact-destination verification is endpoint-global, then exact-leaf leaf_stats resolves the target's persisted root_cwd without a full root inventory. The reply must match the intended persistent leaf and contain a valid absolute CWD. Navigation atomically selects that scope and leaf; it never opens a neighbor or restores an intermediate remembered leaf. A destination outside the previous browsing CWD is valid on the same endpoint. A missing leaf/root or blank root CWD fails closed. Notifications are navigation only: they do not move roots, settle metadata, or mix endpoints.
  • Connection lost: separate durable endpoint-specific notification when unexpected transport loss is detected while the service is alive, at most once per generation. Deliberate Disconnect/replacement cleanup is quiet. Other endpoints stay connected. The loss notification survives the last endpoint/service stopping. Opening it never authenticates automatically. Process death/force-stop cannot guarantee a final alert. It is withdrawn by endpoint key, so a notice posted by an earlier process is also cleared, as soon as that endpoint starts connecting again, on an explicit disconnect of that endpoint or Disconnect all, and when its saved profile is deleted. Tapping it dismisses it. The service stopping while the endpoint is still lost does not clear it. The endpoint key includes host, port, user and socket, so saving an edited profile whose key changes withdraws every notification of the old key (loss notice, Inbox children and group summary), which nothing else could reach any more. Deleting a profile withdraws all of its notifications likewise. A save that keeps the key, and any other profile's notifications, are left alone.

Inbox eligibility reuses InboxProjection: only persistent leaves with a valid alert_time strictly before the current clock are due; alert_idle alone is not an alert. The first successful metadata snapshot for an exact endpoint establishes a quiet baseline for already-due alerts. Future schedules in that snapshot remain eligible when they mature. Thereafter a newly due session or different due timestamp is eligible once. Each leaf/timestamp snapshot is deduplicated using SHA-256 fingerprints in nonsecret local state retained across reconnect/service/process restarts. Both in-memory and persistent ledgers are keyed by exact endpoint identity, independent of browsing CWD. Directory changes and Inbox presentation-filter changes do not retire the ledger, reset its baseline or replay alerts. Connection retirement rejects stale-generation snapshots; reconnect obtains fresh endpoint-global metadata. No compatibility reader or migration of former development CWD-scoped ledgers is provided. The complete current due set is protected from eviction; a separate history retains 2,048 retired snapshots. An unchanged current set therefore stays quiet even above 2,048 entries. Old absent snapshots evicted from retired history can become eligible if they later reappear. Monitoring accepts at most 65,536 leaf records per snapshot; an oversized response is rejected wholesale without installing a partial baseline or evicting current alerts. A failed refresh marks retained metadata unavailable: the dashboard shows Inbox unavailable, omits the old count, and does not mature stale cached alerts while waiting for a successful refresh. This does not itself disconnect SSH. The count bound is distinct from the JSONL frame bound; see connection stability and discovery limits for the remaining unpaginated-inventory risk. This explicitly bounds current-set storage while preserving individual changed/new and clock-matured eligibility throughout the supported range. Viewing, temporary absence within retained history and reconnect do not reset deduplication. A disabled channel/permission consumes eligibility without later replaying an alert flood; changing notification settings is not a remote acknowledgement. No notification action sends prompts, settles work or changes trust.

Inbox notifications follow the current alert set. After every successful metadata scan of an endpoint, each of that endpoint's notifications whose leaf no longer has a due alert (settled, snoozed or deleted here or from another client such as the TUI) is withdrawn, and the group summary with the last one. Matching uses the exact endpoint prefix, so another endpoint's notifications are never touched. A failed or unavailable refresh withdraws nothing. In-app handling withdraws at once instead of waiting for the next poll: an acknowledged settle or snooze (menu, swipe, batch), and an acknowledged prompt or steer sent from this app to that session. That withdrawal is bound to the alert instance that was showing for the endpoint and session when the action began (captured when the settle, snooze or send is initiated, not at acknowledgement). At acknowledgement it cancels only if the notification now showing is still that instance, so a delayed acknowledgement cannot cancel a newer alert for the same session. If nothing was showing when the action began nothing is withdrawn; the post-scan reconciliation retires alerts that are no longer due. Opening a session, including through the notification, clears whatever is showing at once; typing, focusing the composer and scrolling do not.

Validation is deterministic controller/registry/held-transport and actual Activity/service unit coverage. OEM background policy, real-device notification presentation, audio, TalkBack and large-font acceptance require separate device checks.