docs/http-tunnels.md
HTTP tunnels
The Android client recognizes conversation Markdown links of the form
[Open dashboard](ez-agent://tunnel/localport/8080/dashboard). It displays the
destination beside the label. HTTP(S) loopback links also use the tunnel workflow:
they refer to the connected service's loopback, not this Android device. This
includes IPv4 127/8 and the potentially device-local 0/8 class, browser
numeric IPv4 aliases (decimal, octal, hex and abbreviated forms such as 127.1,
2130706433, 0 or 0x0), IPv6 ::1 and unspecified :: spellings,
IPv4-mapped 127/8 and 0/8, and case/escape/width-normalized localhost
with an optional trailing dot (including the reserved .localhost namespace).
Classification is bounded and DNS-free: other DNS names and private/LAN
addresses are not routed as loopback. Unspecified/bind-all address links follow
the same remote tunnel flow; the client does not rely on browser-specific
0.0.0.0 blocking. These aliases still use the provider's fixed 127.0.0.1
target, not arbitrary remote addresses.
Recognized but unsafe or ambiguous URLs enter tunnel validation and are rejected,
never handed to the phone browser as external links. Other HTTP(S) links keep
their existing browser confirmation; other custom schemes remain inert.
The original link address always remains visible in
chat. Starting or stopping a forward does not rewrite the canonical message;
the assigned local web URL is a separate, connection-owned runtime mapping.
Custom tunnel links produce HTTP URLs; web links retain HTTP or HTTPS.
Tap a tunnel link without a reusable mapping to open a compact bottom sheet titled
Open localhost:<port><path>? (Open https://localhost:<port><path>? for HTTPS links),
with via <service> beneath it and the caveat that other apps on this device can reach
the tunnel while it is open. Details expands, in place, the clicked link and the
loopback (and, for HTTPS, certificate) explanation; it is collapsed by default. Three
adjacent buttons end the sheet: Cancel, Start only and Open in browser (the
primary action). Cancel, Back and swipe-down start nothing. Start only discovers
the service's tunnel macro and binds an available IPv4 loopback port on the Android device
without opening another app. Open in browser starts the same tunnel, then opens its
assigned local web URL only after the listener is bound and active. Every new tunnel
requires a tap on one of the two start buttons.
Failed or cancelled setup never launches a browser. The open request is one-shot, scoped to
the captured connection and current UI; leaving the Activity or opening a new
confirmation discards a still-pending browser launch without stopping the forward.
Rendering, reviewing and cancelling links do not discover capabilities, open
listeners or contact the source server. The connected installation must provide the
ez-agent-tunnel capability.
The Inbox → Tunnels section appears at the top of the scrollable Inbox list only when there are entries to show. With none, its heading and rows are absent: there is no empty hint, management button or reserved space. It shows the viewed endpoint's starting, active, stopping and failed forwards, including those whose originating agents/chats are now in the background or unselected. Rows identify the service, source port/path and live local web mapping. They update directly from the endpoint's registry, without opening the owning chat or waiting for remote session discovery. Tunnels and ordinary due-session threads share one scrollable list, so many tunnels cannot pin a separate pane over the threads. Tap a tunnel row for its existing controls. There is no redundant Inbox management button; Options → HTTP tunnels opens the full list, including completed entries.
A link to an already starting or active forward reuses that mapping for the
same connected transport and source port, without another setup confirmation.
An active mapping opens the clicked destination immediately; a starting mapping
opens it once ready. Each click preserves its own path, query and fragment,
rather than reopening the first link's path. Stopped, failed, retired or other
endpoints' mappings are not reused. A new mapping still requires the explicit
confirmation above. If the service lacks tunnel.localport, setup fails visibly;
the client does not fall back to opening the phone's localhost.
Active details show the assigned local URL with explicit Open browser, Copy URL and Stop tunnel actions. HTTP(S) web links retain their scheme, including HTTPS certificate verification by the browser; the tunnel never silently downgrades HTTPS or bypasses certificate errors. Only HTTPS setup confirmations include the explanation of localhost certificate verification. Setup can be cancelled. Start-only setup never opens a browser or sends an HTTP request by itself; accepting the browser option explicitly authorizes opening the ready local URL. Successful setup does not prove the source server is running; the source is contacted when a local application connects.
The Tunnels section is local runtime state, not daemon leaf alerts. It does not depend on the selected leaf, due-alert membership, session search or the Inbox current-directory filter, and it does not write session metadata. Those filters and ordinary due-session semantics continue to apply to the session list below it. Switching endpoints shows only that endpoint's tunnels; it never retargets an existing entry or confirmation to a different connection.
Stop and listener failure revoke the assigned web mapping: dead local URLs are removed rather than left as destinations that another local process might later reuse. The original custom address in chat is unaffected. Cancellation during setup also promptly cancels a concurrently returned listener before waiting for main-loop presentation, while joined shutdown stays off the UI thread.
Forwards belong to the exact connected endpoint, not a chat or Activity. They survive chat switches, Activity recreation, endpoint switches and backgrounding while their owning connection remains alive. Disconnect, connection replacement, connection loss and process death stop them. Reconnecting never restores a forward or replays a request. Up to 32 entries are retained per endpoint; completed entries are reclaimed when needed. Across endpoints, at most 128 forwards can be setting up, active or cleaning up. Accepted TCP streams also have a separate process-wide limit of 128, including streams still cleaning up. Stop revokes listener admission promptly; Stopping remains visible until workers have finished, without blocking the UI.
Resource bounds and remaining work
These are admission ceilings, not a recommendation to run that many tunnels on a phone. Unlike the upstream Go client's goroutines, the current Java workers are OS threads:
| Work | Threads | Process-wide upper envelope |
|---|---|---|
| Listening forward | 1 acceptor + 1 cleanup reaper | 256 for 128 forwards |
| Accepted TCP stream | 1 protocol owner + 1 socket reader + 1 socket writer | 384 for 128 streams |
The combined envelope is about 640 tunnel worker threads, before the shared setup/close executors, SSH/RPC workers and the rest of the app. Streams retain their admission permit until all three workers have exited; stopping a listener does not immediately free its forward permit while cleanup is pending. Thread stacks, queued replies and protocol buffers also consume memory. Actual Android thread/memory limits may be reached before these ceilings. Use only the forwards needed and stop idle ones; a shared reaper and Android-specific admission sizing remain separate resource-policy work, not claims made by these bounds.
There is also no aggregate pending-tunnel-RPC budget. Each stream has a 1024-call ceiling, but those calls share the connection's pending-request map and FIFO writer with interactive RPCs. Many streams sending tiny frames can therefore increase memory use and chat latency even without large byte volume. Any aggregate policy needs coordination with the upstream tunnel provider and must preserve progress for ACK, reply-slot and terminal control traffic. A blocking semaphore around all macro calls could deadlock a stream instead of providing safe backpressure; no such Android-only cap is added here.
The Android registry's shared cleanup executor has four workers and 128 queue slots. Each forward schedules joined cleanup at most once. A forward may finish all of its workers autonomously and release its permit while its now-redundant close task is still queued. Replacement forwards can therefore leave more outstanding close tasks than held permits; the forward budget alone does not guarantee the close executor cannot reject. If it does reject, prompt cancellation still happens and the permit is released only by the forward's joined terminal signal; the UI neither joins workers nor starts fallback threads. Registry regressions cover capacity across registries, repeated Stop, queued and autonomous cleanup, and that rejection path.
Scope and security
- The remote target is IPv4
127.0.0.1on the tunnel provider's host, not the phone's localhost or an arbitrary remote hostname. The existing SSH connection carries ordinary JSONL macro calls; no additional remote command is executed. Recognized loopback aliases select this same fixed provider target; they do not request forwarding to a distinct IPv4 address or an IPv6 listener. - The client listener binds only IPv4 loopback on Android, not a Wi-Fi/LAN address. Other local applications can connect to it. Do not treat it as an app-private authentication boundary.
- The path is appended to the browser URL only. It does not restrict the
TCP tunnel or the paths a local application can request. Query strings and
fragments in custom links are rejected; HTTP(S) loopback web links preserve
their query and fragment. Percent escapes in paths are retained.
Only the canonical lowercase custom-link form is admitted; ambiguous
browser-normalized paths (dot segments, backslashes and leading
//) are inert. - HTTP is a convenient consumer of a byte-stream tunnel, not a special wire protocol or an HTTP proxy. WebSockets and other framed TCP protocols can use the same listener. There is no request-side half-close support, retransmission or automatic recovery of failed streams.
- Source connection/stream failure does not destroy the listener. A new local connection gets a new stream ID. A lost owning service connection does stop the listener. Macro errors are not displayed verbatim.
The Java library implements the existing upstream tunnel CSV rows, credit, consumption acknowledgements and macro reply slots. It does not add JSONL frame kinds or change the service contract. See the upstream tunnel adapter contract.
Wire regression fixtures
TunnelFrameGoldenTest checks Java encoding and decoding against fixed rows
produced by the actual upstream Go codec, rather than another Java peer. The
corpus covers all six pipe-frame kinds, unsigned sequence/ACK boundaries,
canonical CSV quoting, Unicode/byte-length limits, binary payloads and strict
malformed-row rejection. Java-only malformed UTF-16 inputs are tested separately
because they cannot appear in valid UTF-8 JSON fixtures. This supplements, not
replaces, real client/provider and Android forwarding tests.
The fixture resource records the upstream revision and SHA-256 hashes of its
codec, CSV helper and contract. Normal tests require neither Go nor a harness
checkout. For reproduction instructions and the exact provenance, see
ez-agent-lib/src/test/fixtures/tunnelcodec/.