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 link.lock. Runs today’s Link (relay socket, peers, Noise) and a HubServer on hub.sock. Holds session id 1 for its own session. Owns pairing, forget, the window.

Member

A pi whose acquireLinkLock returned held by a live holder whose lock names a socket. Runs a HubClient: attaches, sends its records and controls up, receives the phone’s records for its session down. Has no relay socket and no peers.

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

attach

member → hub

{ v, cwd, name?, pid, opened_at } — the member’s SessionInfo minus the id

attached

hub → member

{ v, session } — the id, monotonic from 2 for the hub’s lifetime (1 is the hub’s), never reused

hub

hub → member

{ peers, members } — how many phones are ready and the live member ids in id order; sent on attach and on every change (a peer readied or dropped, a member joined or left). The member registers its RemoteAnswerer while peers ≥ 1 and unregisters at 0 — so pi-modes' remoteAttached() stays true only when a phone can answer; peerCount() reads it; the election ranks by position in members

record

both

up { json, peer? }: a session-frame record the hub seals under the member’s id — to the one peer named by peer (a response, #154), else to every ready peer; down { json, peer }: a phone’s command for this member, plaintext, with the routing id of the phone that sent it, which the member echoes on its response

control

member → hub

{ json } — state (cached per member for greet) or idle; broadcast on session 0

status

member → hub

{ json } — the member’s setStatus record; cached for greet; sent on its session frame

forget / forgot

member → hub / hub → member

{ device_id } / { device_id, found } — the hub forgets live (Link.forget) and answers, so the member’s terminal prints the result and a paired device is dropped now, not at the next restart

close

member → hub

{} — the member is leaving; the hub announces session_ended and retires the id

bye

hub → member

{ reason } — the hub is going down; members begin the handover

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).

What does not change

The wire. The relay. pairing.ts, qr.ts, commands.ts (dispatch runs in the member’s own pi against its own session). Open/Close from the phone stay refused. The identity file and trust list stay one per box; a member reads them for forget through the hub, not from disk.

Scope

Files

File Change

packages/pi-remote/hub.ts

new: HubServer — net.createServer on hub.sock (dir 0700, socket chmod 0600 after listen), JSON-lines framing, members map (id → { socket, info, state?, status? }), id allocation, attach/record/control/status/forget/close handling, bye on stop, sessions() for hello, stateOf(id)/statusOf(id) for greet, forward(id, json) down

packages/pi-remote/member.ts

new: HubClient — connect/attach, SessionLink + RemoteAnswerer, the election and re-attach loop, notices

packages/pi-remote/link.ts

LinkDeps.session() → sessions(), activity(id), status(id); broadcast(rec, session, peer?); onCommand unchanged for the hub’s own id; a forward(session, json, peer) hook for member sessions; onPeersChanged(n) so the hub can publish hub; stop calls the hub’s bye first

packages/pi-remote/commands.ts

handleCommand(cmd, host, reply): the length bound, the refusal in both forms, answer through dispatch — moved out of Peer.onCommand, used by both roles

packages/pi-remote/peer.ts

THIS_SESSION removed; the peer knows the hub’s own id and the member id set through deps; receiveRecord routes per Forwarding; greet per session

packages/pi-remote/identity.ts

LinkHolder.sock (optional on read); readLinkHolder; HUB_SOCKET = "hub.sock"; link.wanted as a map keyed by cwd; link.log rotation stays the hub’s — a member logs its lifecycle lines to link.<pid>.log, so two processes never rotate one file. Erratum (2026-09-21): link.wanted.d/ - one file per cwd, no read-modify-write across processes (cold-review catch); and one link.log for all, each append reopening it, rotation by whichever process sees the size - a per-pid log would hide a handover’s two halves from each other.

packages/pi-remote/index.ts

role choice on the lock result; state.sessionId; SessionLink in place of Link; session_shutdown and stop through the role’s stop; the status line names the role ("hub, 2 members" / "member of the pi in cwd")

packages/pi-remote/config.ts

nothing new: no knob — the constants are pi-remote’s

packages/pi-remote/package.json

0.8.0

docs/modules/ROOT/pages/remote.adoc

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 idle scope, the old-version cases

CHANGELOG.adoc

== Unreleased, === Added

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 HubServer starts at 1 again;

  • an attach with a missing field drops that connection with a log line; a line over MAX_LINE_BYTES is skipped and logged and the connection stays;

  • a record claiming another session, or a control of a type not allowed, is dropped and logged: the connection’s id is the only id;

  • forget from a member reaches the hub’s Link.forget and forgot { found } comes back;

  • hub { peers, members } arrives on attach and on each change; the member’s answerer is registered only while peers ≥ 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’s dir, name, opened_at on attach and session_ended on leave, to every ready peer;

  • hello.sessions lists the hub and every member in id order; greet replays each member’s cached state and status;

  • a member’s record reaches 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 ask puts askRequest on every phone under its id; the ui_response from one resolves it and the others receive idle; settle sends idle; inFlight() lists it until then.

Handover (member.test.ts, fake timers):

  • the hub’s stop sends bye, removes the socket, releases the lock — in that order (a member reading the lock at bye finds 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; stop ends the loop;

  • link.wanted per cwd: two sessions wanted, one stop, 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 hub.peers ≥ 1, so the broker never offers it an ask nobody can answer, and remoteAttached() is honest

idle and waiting carry no session on the wire

silent (UX)

a member’s idle closes every session’s sheet on the phone; today’s single-session box never showed it. Said on the remote page and on pivot #102 - a session on idle is the wire’s to add

An old pi-remote as hub or member

fail-closed

no sock → today’s refusal; an old member never attaches (it refuses itself); no protocol negotiation needed pre-1.0

JSON-lines framing on a large record

silent (drop)

MAX_LINE_BYTES; fitForWire still bounds what reaches the phone

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

  1. Branch feat/local-hub; commit this plan; nav entry under Active.

  2. identity.ts (lock gains sock) + tests; hub.ts + tests; member.ts + tests.

  3. link.ts/peer.ts per-session routing and greet + tests; index.ts role choice; the #150 test replaced.

  4. remote.adoc, CHANGELOG, 0.8.0; validate green; MR Closes #186; merge; one line on #186 with the SHA; a note on pivot #102 that the box side is published, with the local path, the hub/status/forget messages the ADR did not list, and the idle scope; plan Status → Done, nav → Archive; release cut (0.57.0).

Edit this page · latest