Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(presence): interactive relay host joins its bridged phone as a peer

enes703c6355fc72
diff --git a/src/main/remote/host-service.presence.test.ts b/src/main/remote/host-service.presence.test.ts
new file mode 100644
index 000000000..9df56f07b
--- /dev/null
+++ b/src/main/remote/host-service.presence.test.ts
@@ -0,0 +1,194 @@
+// Interactive-host presence wiring: the phone a `initRemoteHost` session bridges over the relay is
+// a `kind:'phone'` peer, exactly like the one the standing host bridges (standing-host.test.ts).
+// EVERY end path of that session — the relay socket dropping, the human rejecting the device,
+// `remote:host:stop`, and a fresh `remote:host:start` that supersedes the live session — must reach
+// presenceHub.leave() exactly once. A missed leave is a permanent ghost peer in everyone's facepile;
+// a double leave frees the peer's color while it is still on screen.
+//
+// electron + the relay socket are mocked; what's under test is initRemoteHost's own bookkeeping.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from '../../core/platform'
+import { fakePlatform } from '../../core/platform-fake'
+import { presenceHub } from '../../core/presence/hub'
+import type { RelaySocket } from './relay-socket'
+
+const ipc: Record<string, (e: unknown, msg: unknown) => void> = {}
+const handlers: Record<string, (e: unknown, ...args: unknown[]) => unknown> = {}
+
+vi.mock('electron', () => ({
+ app: { isPackaged: true, getPath: () => '/tmp/nodeterm-presence-test' },
+ safeStorage: { isEncryptionAvailable: () => false },
+ ipcMain: {
+ on: (ch: string, fn: (e: unknown, msg: unknown) => void) => {
+ ipc[ch] = fn
+ },
+ handle: (ch: string, fn: (e: unknown, ...args: unknown[]) => unknown) => {
+ handlers[ch] = fn
+ }
+ }
+}))
+vi.mock('../../core/pty-manager', () => ({ PtyManager: class {} }))
+vi.mock('../../core/license', () => ({
+ isPremium: () => true,
+ getStoredEntitlement: () => 'entitlement'
+}))
+vi.mock('./host-canvas-hub', () => ({
+ initHostCanvasHub: () => {},
+ currentCanvas: () => null,
+ subscribeCanvas: () => () => {}
+}))
+
+// One fake relay socket per connectHostSession() call: we drive onReady (peer bridged) / onClose
+// (transport dropped) by hand, and count close() calls. Like the real relay-socket, an intentional
+// close() is FINAL and does NOT call back into onClose.
+interface FakeRelay {
+ opts: { onReady(): void; onClose(): void }
+ closed: number
+}
+const relays: FakeRelay[] = []
+
+vi.mock('./relay-socket', () => ({
+ connectRelay: (opts: { onReady(): void; onClose(): void }): RelaySocket => {
+ const entry: FakeRelay = { opts, closed: 0 }
+ relays.push(entry)
+ return {
+ respond: () => {},
+ sendFrame: () => true,
+ notify: () => true,
+ sas: () => '12345',
+ peerPublicKeyB64: () => 'phone-pub',
+ close: () => {
+ entry.closed += 1
+ }
+ } as unknown as RelaySocket
+ }
+}))
+
+import { initRemoteHost } from './host-service'
+import { IPC } from '../../shared/ipc'
+
+const sentToWin: Array<{ channel: string; args: unknown[] }> = []
+
+function makeHost(): void {
+ const win = {
+ isDestroyed: () => false,
+ webContents: {
+ send: (channel: string, ...args: unknown[]) => sentToWin.push({ channel, args })
+ }
+ }
+ initRemoteHost(win as never, {} as never)
+}
+
+/** Run `remote:host:start` (mints a token, connects the relay session). */
+async function start(): Promise<void> {
+ await handlers[IPC.remoteHostStart](null)
+}
+
+/** The pending-approval id the host just surfaced to the human (SAS dialog). */
+function pendingApprovalId(): string {
+ const msg = sentToWin.filter((s) => s.channel === IPC.remoteHostPeerPending).at(-1)
+ return (msg?.args[0] as { id: string }).id
+}
+
+function phones(): number {
+ return presenceHub.peers().filter((p) => p.kind === 'phone').length
+}
+
+beforeEach(() => {
+ initPlatform(fakePlatform())
+ relays.length = 0
+ sentToWin.length = 0
+ for (const key of Object.keys(ipc)) delete ipc[key]
+ for (const key of Object.keys(handlers)) delete handlers[key]
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => ({
+ ok: true,
+ json: async () => ({ pairingId: 'p', pairingToken: 'tok', exp: 0 })
+ }))
+ )
+})
+
+afterEach(() => {
+ for (const p of presenceHub.peers()) presenceHub.leave(p.clientId)
+ vi.unstubAllGlobals()
+ resetPlatformForTests()
+})
+
+describe('interactive host presence peers', () => {
+ it('a bridged phone joins as a cursorless peer and leaves when the socket drops', async () => {
+ makeHost()
+ await start()
+ expect(relays).toHaveLength(1)
+ expect(phones()).toBe(0) // connected, but nobody has bridged yet
+
+ relays[0].opts.onReady()
+ const peer = presenceHub.peers().find((p) => p.kind === 'phone')
+ expect(peer).toBeDefined()
+ expect(peer?.cursor).toBeNull() // a phone has no mouse — never fabricate one
+ expect(peer?.name).toBe('Phone')
+ expect(peer!.clientId).toBeGreaterThanOrEqual(1_000_000) // relay id range
+
+ relays[0].opts.onClose()
+ expect(phones()).toBe(0)
+ })
+
+ it('leaves the hub when the human rejects the device (close() never fires onClose)', async () => {
+ makeHost()
+ await start()
+ relays[0].opts.onReady()
+ expect(phones()).toBe(1)
+
+ ipc[IPC.remoteHostReject](null, { id: pendingApprovalId() })
+ expect(relays[0].closed).toBe(1)
+ expect(phones()).toBe(0)
+ })
+
+ it('leaves the hub on remote:host:stop (an intentional close, no onClose)', async () => {
+ makeHost()
+ await start()
+ relays[0].opts.onReady()
+ expect(phones()).toBe(1)
+
+ await handlers[IPC.remoteHostStop](null)
+ expect(relays[0].closed).toBe(1)
+ expect(phones()).toBe(0)
+ })
+
+ it('a restart supersedes the live session: the old phone leaves, the new one is its own peer', async () => {
+ makeHost()
+ await start()
+ relays[0].opts.onReady()
+ const first = presenceHub.peers().find((p) => p.kind === 'phone')!.clientId
+
+ // A second start() tears the old session down (intentional close → no onClose) before connecting.
+ await start()
+ expect(relays).toHaveLength(2)
+ expect(phones()).toBe(0) // the superseded session's phone is gone
+
+ relays[1].opts.onReady()
+ const second = presenceHub.peers().find((p) => p.kind === 'phone')!.clientId
+ expect(second).not.toBe(first)
+ expect(phones()).toBe(1)
+
+ await handlers[IPC.remoteHostStop](null)
+ expect(phones()).toBe(0)
+ })
+
+ it('a bridged peer leaves exactly once even if close() and onClose() both fire', async () => {
+ makeHost()
+ await start()
+ relays[0].opts.onReady()
+ const id = presenceHub.peers().find((p) => p.kind === 'phone')!.clientId
+
+ await handlers[IPC.remoteHostStop](null) // → close() → leave
+ relays[0].opts.onClose() // a late transport close still arrives → must be a no-op
+ expect(phones()).toBe(0)
+
+ // The id must not be recycled onto some other peer by a double-leave.
+ presenceHub.join(id, 'phone')
+ expect(phones()).toBe(1)
+ presenceHub.leave(id)
+ })
+})
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 0bc20c6cf..18d1aa1e1 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -35,6 +35,7 @@ import { encodeOffer } from './pairing'
import { sanitizeClientMutation } from './canvas-sync'
import { connectRelay, type RelaySocket, type RpcRequest } from './relay-socket'
import { initHostCanvasHub, currentCanvas, subscribeCanvas } from './host-canvas-hub'
+import { createPhonePresence, type PhonePresence } from './phone-presence'
// Default relay endpoint; `NODETERM_RELAY_URL` overrides it (mirrors license.ts's API_BASE /
// CHECKOUT_URL env-override pattern — used both as the dev gate and for local testing).
@@ -709,6 +710,9 @@ export function initRemoteHost(
): void {
initHostCanvasHub()
let session: HostSession | null = null
+ // The live session's presence slot (the bridged phone's peer). Paired with `session` and replaced
+ // with it, so a superseded session's late callbacks can never touch the new session's peer.
+ let presence: PhonePresence | null = null
// A fresh id per pending approval. The approve/reject IPC channels are SHARED with the standing
// phone host, and a single "Approve" click broadcasts to both listeners — so each acts only on
// an event carrying ITS OWN pending id, never on one meant for the other host.
@@ -718,6 +722,18 @@ export function initRemoteHost(
if (!win.isDestroyed()) win.webContents.send(channel, ...args)
}
+ // Tear the live session down. Used by EVERY intentional end path (stop, reject, and a `start`
+ // that supersedes a live session): relay-socket treats close() as final and does NOT fire
+ // onClose, so the presence leave has to happen here as well as in onClose. PhonePresence.leave()
+ // is exactly-once, so whichever path runs second is a no-op and the peer never leaves twice.
+ function endSession(): void {
+ presence?.leave()
+ presence = null
+ session?.close()
+ session = null
+ pendingApprovalId = null
+ }
+
ipcMain.handle(IPC.remoteHostStart, async (): Promise<{ offer: string }> => {
if (!isPremium()) {
throw new Error('Remote access requires nodeterm Pro.')
@@ -731,12 +747,15 @@ export function initRemoteHost(
}
// Already hosting → tear the old session down before starting a fresh one.
- session?.close()
- session = null
+ endSession()
const keys = await loadOrCreateKeyPair()
const { pairingToken } = await mintPairingToken(entitlement)
+ // This session's presence slot, captured by its own callbacks (never read through `presence`,
+ // which by then may belong to a newer session).
+ const phone = createPhonePresence()
+ presence = phone
session = connectHostSession({
url: RELAY_URL,
token: pairingToken,
@@ -748,10 +767,14 @@ export function initRemoteHost(
listProjects,
// Interactive host: surface the SAS + a fresh pending id so the human can verify + approve.
onPeerReady: (s) => {
+ // Team presence: a bridged relay client is a peer. It has no mouse, so it stays cursorless
+ // and appears in the facepile only — see docs/team-presence.md ("Peers may have no cursor").
+ phone.join()
pendingApprovalId = randomUUID()
send(IPC.remoteHostPeerPending, { sas: s.sas(), id: pendingApprovalId })
},
onClose: () => {
+ phone.leave()
pendingApprovalId = null
}
})
@@ -777,14 +800,10 @@ export function initRemoteHost(
ipcMain.on(IPC.remoteHostReject, (_e, msg: { id?: string } = {}) => {
if (!pendingApprovalId || msg?.id !== pendingApprovalId) return
pendingApprovalId = null
- if (session && !session.isApproved()) {
- session.close()
- session = null
- }
+ if (session && !session.isApproved()) endSession()
})
ipcMain.handle(IPC.remoteHostStop, () => {
- session?.close()
- session = null
+ endSession()
})
}
diff --git a/src/main/remote/phone-presence.ts b/src/main/remote/phone-presence.ts
new file mode 100644
index 000000000..ea7ea0b5c
--- /dev/null
+++ b/src/main/remote/phone-presence.ts
@@ -0,0 +1,45 @@
+// One bridged relay peer's slot in the presence table (docs/team-presence.md).
+//
+// Both relay hosts — the interactive one (host-service.ts `initRemoteHost`) and the standing one
+// (standing-host.ts) — bridge a phone over the relay, and a bridged phone is a peer: it shows up in
+// the facepile and on node chips. It has no mouse, so it stays CURSORLESS (the hub joins every peer
+// with `cursor: null`; nothing here ever fabricates one).
+//
+// The bookkeeping both hosts need is identical and easy to get wrong, so it lives here once:
+// - join() is idempotent — a listener that bridges is joined once, whatever re-fires onReady;
+// - leave() is EXACTLY-ONCE — the session-end paths are genuinely plural, because an INTENTIONAL
+// `session.close()` (device rejected, host stopped/restarted, idle-token refresh, Pro lapsed) is
+// final in relay-socket and deliberately does NOT fire `onClose`, while a socket that drops on
+// its own only fires `onClose`. Both must reach the hub, and a peer must never leave twice
+// (that would free its color for someone else while it is still on screen).
+// Nulling the id after the first leave is what makes the second call a no-op.
+
+import { allocateRelayClientId, presenceHub } from '../../core/presence/hub'
+import type { ClientId } from '../../shared/presence'
+
+export interface PhonePresence {
+ /** The phone bridged → it is a peer now. Idempotent. */
+ join(): void
+ /** This session ended (any path) → drop the peer. Exactly-once. */
+ leave(): void
+ /** Its ClientId while joined, else null. */
+ id(): ClientId | null
+}
+
+/** A presence slot for one bridged relay session. Join on bridge, leave on EVERY end path. */
+export function createPhonePresence(): PhonePresence {
+ let clientId: ClientId | null = null
+ return {
+ join() {
+ if (clientId !== null) return
+ clientId = allocateRelayClientId()
+ presenceHub.join(clientId, 'phone')
+ },
+ leave() {
+ if (clientId === null) return
+ presenceHub.leave(clientId)
+ clientId = null
+ },
+ id: () => clientId
+ }
+}
diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.ts
index f0697c2f1..770437665 100644
--- a/src/main/remote/standing-host.ts
+++ b/src/main/remote/standing-host.ts
@@ -23,8 +23,7 @@ import { IPC } from '../../shared/ipc'
import type { CanvasMutation, Settings } from '../../shared/types'
import { PtyManager } from '../../core/pty-manager'
import { getStoredEntitlement, isPremium } from '../../core/license'
-import { allocateRelayClientId, presenceHub } from '../../core/presence/hub'
-import type { ClientId } from '../../shared/presence'
+import { createPhonePresence, type PhonePresence } from './phone-presence'
import { publicKeyToB64 } from './e2ee'
import {
API_BASE,
@@ -108,8 +107,8 @@ export function initStandingHost(
session: HostSession
/** True once a client completed the handshake on this listener (it now serves that client). */
bridged: boolean
- /** This peer's presence ClientId, minted when it bridges (null while the listener is idle). */
- presenceId: ClientId | null
+ /** This session's presence slot: joined when a phone bridges, left on EVERY end path. */
+ presence: PhonePresence
/** Per-session pending approval (unknown device awaiting the human's SAS decision). */
approvalPub: string | null
approvalId: string | null
@@ -134,16 +133,11 @@ export function initStandingHost(
return n
}
- // Drop this session's presence peer, exactly once. Called from BOTH end paths, because they are
- // genuinely different: `onClose` fires when the relay socket drops on its own (client gone, relay
- // dropped us), while an INTENTIONAL `session.close()` (reject / idle-token refresh / stop()) is
- // final in relay-socket and deliberately does NOT fire onClose. Nulling the id makes the second
- // call a no-op, so a peer never leaves twice (and its color is never freed for someone else).
- function leavePresence(p: Pooled): void {
- if (p.presenceId === null) return
- presenceHub.leave(p.presenceId)
- p.presenceId = null
- }
+ // Presence is dropped from BOTH end paths, because they are genuinely different: `onClose` fires
+ // when the relay socket drops on its own (client gone, relay dropped us), while an INTENTIONAL
+ // `session.close()` (reject / idle-token refresh / stop()) is final in relay-socket and
+ // deliberately does NOT fire onClose. `PhonePresence.leave()` (shared with the interactive host)
+ // is exactly-once, so a peer never leaves twice (its color is never freed for someone else).
function clearApproval(p: Pooled): void {
if (p.approvalTimer) {
@@ -156,7 +150,7 @@ export function initStandingHost(
function removeFromPool(p: Pooled): void {
clearApproval(p)
- leavePresence(p)
+ p.presence.leave()
if (p.refreshTimer) {
clearTimeout(p.refreshTimer)
p.refreshTimer = null
@@ -214,8 +208,7 @@ export function initStandingHost(
pooled.bridged = true
// Team presence: a bridged relay client is a peer. It has no mouse, so it stays cursorless
// and appears in the facepile only — see docs/team-presence.md ("Peers may have no cursor").
- pooled.presenceId = allocateRelayClientId()
- presenceHub.join(pooled.presenceId, 'phone')
+ pooled.presence.join()
ensurePool() // this listener now serves a client → restore a warm one
}
const s = pooled.session
@@ -265,7 +258,7 @@ export function initStandingHost(
const pooled: Pooled = {
session: null as unknown as HostSession,
bridged: false,
- presenceId: null,
+ presence: createPhonePresence(),
approvalPub: null,
approvalId: null,
approvalTimer: null,
@@ -283,7 +276,7 @@ export function initStandingHost(
onPeerReady: () => void onPeerReady(pooled),
onClose: () => {
clearApproval(pooled)
- leavePresence(pooled)
+ pooled.presence.leave()
if (pooled.refreshTimer) {
clearTimeout(pooled.refreshTimer)
pooled.refreshTimer = null