Plan: the local hub — several pi sessions on one box reach the phone (#186)
Closes: #186. Branch: feat/local-hub. Status: Done (2026-09-21) — shipped as pi-remote 0.8.0
TL;DR
Today a second /remote-control on a box is refused: the relay keeps one
connection per box identity, so pi-remote takes a link lock (#150) and
every pi-remote calls itself session 1 (THIS_SESSION). pivot ADR-006
(accepted 2026-09-19) decides what a box is: a machine with one link, one
identity, one Noise session per phone — and several pi sessions reach the
phone through a local hub. The hub is pi-remote itself in the pi that
won the lock. Every other pi attaches to it over
<agentDir>/gadhs-pi-remote/hub.sock and is presented to the phone as
one more session of the same box, with an id the hub allocated. Frames
for session n are forwarded to member n as plaintext records; a
member’s records are sealed to the phone under n. When the hub’s pi
exits, the oldest member takes the lock and the others re-attach. The
wire does not change (@gadhs/pivot-wire 0.3.x); the phone already
renders a box with n sessions.
Design
Roles
| Role | What it is |
|---|---|
Hub |
The pi that acquired |
Member |
A pi whose |
index.ts keeps one state.link, typed as the interface both roles
implement (SessionLink: broadcast, broadcastControl, setStatus,
stop, phase, boxId, peerCount() for the status line, inFlight()
for the ui_prompt_start nudge filter, forget (async, answered),
openWindow/closeWindow/windowOpen). THIS_SESSION goes;
state.sessionId is the id the hub gave — 1 when this pi is the hub.
The command handling Peer.onCommand does today (the length bound, the
refusal in both forms, answer through dispatch) moves to one exported
function in commands.ts, handleCommand(cmd, host, reply), that the hub
runs for its own session and the member runs for records coming down —
one copy, not two.
The lock names the socket
LinkHolder gains sock: string; acquireLinkLock writes it;
readLock reads it as optional; readLinkHolder(agentDir) is exported
for members. A holder record without sock (an older pi-remote) is a hub
that cannot be joined: the refusal notice of today stands, word for word.
Before listen, a stale hub.sock left by a crashed hub is unlinked —
safe, because only the lock holder listens.
link.wanted becomes per cwd. Today one file holds one { cwd, since }
for the box (#179); with members, each session that turned the link on
wants it back after a reload. The file becomes a map keyed by cwd;
markLinkWanted/clearLinkWanted touch this cwd’s entry; restoreLink
restores when this cwd has one — as whichever role the lock then gives.
A stop or quit in one session no longer clears another’s wish.
The local protocol (pi-remote’s own; ADR-004)
JSON lines over the Unix socket, one object per line, t-tagged, v: 1
on attach/attached. A line over MAX_LINE_BYTES = 4 MiB is skipped
to its newline and logged; the connection stays. The hub trusts the
connection, not the fields: a member’s session id is the one the hub
assigned to that socket, whatever a record says; control from a
member is allowed only for state and idle (session in a state is
overwritten with the member’s id); anything else is dropped and logged.
Erratum (2026-09-21): and refused - the member’s own command refused
in both forms (#171) is a control the phone must see, and it names the
asking phone (peer on the control), as the hub’s own refusals do -
and waiting, the nudge for a prompt the phone cannot answer; found by
the member suite and the cold review.
t |
Direction | Body |
|---|---|---|
|
member → hub |
|
|
hub → member |
|
|
hub → member |
|
|
both |
up |
|
member → hub |
|
|
member → hub |
|
|
member → hub / hub → member |
|
|
member → hub |
|
|
hub → member |
|
The member runs fitForWire (#185) on every record before writing it
up, so a line is bounded by the wire’s bound plus framing; MAX_LINE_BYTES
is the safety cap behind it.
Forwarding at the hub
Peer.receiveRecord today: session 0 → control; session 1 → onCommand;
else dropped. Now: session 0 → control; the hub’s own id → onCommand as
today; a member’s id → record { session, json } down that member’s
socket, plaintext (the boundary is the user account and the 0600 socket,
the one the identity file already relies on); anything else → dropped and
logged, as today. ui_response for a member’s ask is just such a record:
the member’s pending map resolves it.
Up: a member’s record → peer.sendRecord(session, json) to the named
peer, else to every ready peer — through fitForWire again at the seal,
as every record is. A member’s control → broadcastControl. greet
(hello, then state and status)
becomes per session: hello.sessions lists the hub’s own SessionInfo
and every member’s, in id order; then, for each session with a cached
state, { t: "state", session, state }; then each cached status
record on its session frame. session_opened { info } on attach and
session_ended { session, reason } on leave go to every ready peer.
The member’s side
HubClient connects, sends attach, awaits attached, then is the
session’s SessionLink: broadcast(rec) → record; broadcastControl
→ control (a state record carries the member’s own id); the status
hook → status. It is also the session’s RemoteAnswerer (registered
while the hub reports peers ≥ 1, unregistered at 0 or on loss — the
same contract Peer keeps per device, held here once for all devices):
ask sends askRequest up as a record (broadcast: every phone shows
the sheet) and resolves on the ui_response that comes back down;
settle sends { t: "idle" } up; and on a win — the phone answered,
which the broker never settles — the member sends idle itself, so the
other phones' sheets close as they do today when Peer per device is
settled. inFlight() is the pending map, for the nudge filter.
Pairing on a member is answered in words, not forwarded: "pivot: the
link is held by the pi in cwd (pid n); pair from there" — the QR
belongs to the process that holds the identity’s socket.
Handover
The hub’s stop (a /remote-control stop, a session shutdown): bye
to every member, the server closed and the socket file removed, then the
lock released — in that order, so a member’s first poll finds the lock
free or the successor’s. The stop notice says so when members exist:
"pivot: link stopped here; the pi in cwd takes it over". A hub that
dies without bye leaves a dead-pid lock, which the existing takeover
handles.
A member that loses the socket (bye or EOF) runs the election: its
rank is its position in the last hub.members roster it received (0 for
the oldest survivor); wait HANDOVER_STEP_MS (150) × rank, capped at
HANDOVER_MAX_WAIT_MS (1 500); then acquireLinkLock. Acquired → become
the hub: start Link and HubServer, take id 1, mark the link wanted
(#179). Held → attach to the holder, re-reading the lock on every
retry (a bye can be read before the hub’s rmSync lands): retry the
connect every ATTACH_RETRY_MS (250) for ATTACH_WINDOW_MS (2 000)
while the new hub brings its socket up; a holder found dead, or one
whose socket refuses or has no sock, sends the member back to the
election; past the window, one notice ("pivot: lost the hub; still
trying") and the election repeats on the relay’s backoff curve (1 s →
30 s) until it lands or stop is called. Nothing is carried across: the
phone sees a reconnect and a new hello with new ids, which its
opened_at rule already treats as new sessions (ADR-006 § Handover;
out of scope by the ADR: ids and pending asks across a handover).
Scope
Files
| File | Change |
|---|---|
|
new: |
|
new: |
|
|
|
|
|
|
|
|
|
role choice on the lock result; |
|
nothing new: no knob — the constants are pi-remote’s |
|
0.8.0 |
|
the #150 paragraph rewritten (not appended to): one link per box, held by the hub; a section under First-class: "Several sessions on one box" — roles, what the phone sees, the handover blink, the plaintext-on-socket boundary, the |
|
|
Tests (vitest; real Unix sockets and the fake relay socket the suites already use; every case names its property)
Contract of the local protocol (hub.test.ts, member.test.ts):
-
the socket is created under the 0700 state dir with mode 0600, and the lock holder record names it;
-
ids: the hub is 1, members 2, 3; a member that leaves retires its id and the next is 4; a new
HubServerstarts at 1 again; -
an
attachwith a missing field drops that connection with a log line; a line overMAX_LINE_BYTESis skipped and logged and the connection stays; -
a
recordclaiming another session, or acontrolof a type not allowed, is dropped and logged: the connection’s id is the only id; -
forgetfrom a member reaches the hub’sLink.forgetandforgot { found }comes back; -
hub { peers, members }arrives on attach and on each change; the member’s answerer is registered only whilepeers ≥ 1(pinned through pi-modes'remoteAttached()).
What the phone sees (through Link with a fake relay socket and a real handshake, as link.test.ts does):
-
session_opened { info }with the member’sdir,name,opened_aton attach andsession_endedon leave, to every ready peer; -
hello.sessionslists the hub and every member in id order; greet replays each member’s cachedstateandstatus; -
a member’s
recordreaches the phone sealed under its own id; a phone’s command on session 3 reaches member 3 as the plaintext record with the phone’s routing id, and its response comes back under 3 to that phone only (a second ready phone sees nothing — #154’s per-peer answer); a command on a session nobody holds is dropped and logged; -
a member’s
askputsaskRequeston every phone under its id; theui_responsefrom one resolves it and the others receiveidle;settlesendsidle;inFlight()lists it until then.
Handover (member.test.ts, fake timers):
-
the hub’s
stopsendsbye, removes the socket, releases the lock — in that order (a member reading the lock atbyefinds the hub’s record; after stop, none); -
two members lose the hub: the roster’s first (member 2) acquires the lock at 0 ms and member 3 at 150 ms finds it held and attaches to 2’s socket, receiving a new id; after churn (ids 2, 5, 9 surviving) the ranks are 0, 1, 2, not the ids; both within
HANDOVER_MAX_WAIT_MS + ATTACH_WINDOW_MS; -
the successor’s socket not yet up: the attach retries every 250 ms, re-reading the lock, and succeeds when it appears; a holder found dead mid-window sends the member back to the election; past the window one notice and the backoff curve;
stopends the loop; -
link.wantedper cwd: two sessions wanted, onestop, the other still restores after a reload. -
a hub that died without
bye: the dead-pid takeover path elects as above.
Versions (index wiring): a live holder whose lock has no sock → today’s refusal notice, no attach attempted; a member whose hub is a newer pi-remote is an ordinary member.
Regression: the #150 refusal case becomes the attach case — the old test’s assertion ("refused, holder named") is replaced by "attached as session 2, holder’s socket used"; the old notice is kept for the no-sock holder.
Risks
| Risk | Direction | Mitigation |
|---|---|---|
The hub is a single point: its exit blinks every session on the phone |
visible |
bounded election (≤ 1.5 s) + attach window (≤ 2 s) + the phone’s own reconnect; said on the remote page (ADR-006 § Negative) |
Two members find a dead hub in the same instant and both take the lock |
fail-open (a relay fight) |
the ordered wait makes it need a crash and equal timing; the flap detector (#150) names it within three evictions, as today for two boxes |
Plaintext RPC records cross the socket |
silent |
0600 socket in the 0700 state dir, the identity file’s own boundary; stated on the page |
A member’s ask with no phone attached |
fail-closed |
the member’s answerer is registered only while |
|
silent (UX) |
a member’s |
An old pi-remote as hub or member |
fail-closed |
no |
JSON-lines framing on a large record |
silent (drop) |
|
Not in scope
Carrying ids or pending asks across a handover; Open from the phone;
a resident process; pi-server; pivot’s protocol page and phone gates
(pivot #102). A member’s session rename after attach (hello shows the
attach-time name; an issue if it matters).
Delivery
-
Branch
feat/local-hub; commit this plan; nav entry under Active. -
identity.ts(lock gainssock) + tests;hub.ts+ tests;member.ts+ tests. -
link.ts/peer.tsper-session routing and greet + tests;index.tsrole choice; the #150 test replaced. -
remote.adoc, CHANGELOG, 0.8.0;validategreen; MRCloses #186; merge; one line on #186 with the SHA; a note on pivot #102 that the box side is published, with the local path, thehub/status/forgetmessages the ADR did not list, and theidlescope; plan Status → Done, nav → Archive; release cut (0.57.0).