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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(main): desktop window + relay phone peers join the presence hub
enes41b52c546559
diff --git a/src/core/presence/hub.test.ts b/src/core/presence/hub.test.tsindex adac1cc52..7b7ce9cb7 100644--- a/src/core/presence/hub.test.ts+++ b/src/core/presence/hub.test.ts@@ -396,6 +396,29 @@ describe('registerIpc', () => {})})+describe('shell adapters (desktop window + relay phone)', () => {+ it('a desktop window and a relay phone coexist as peers with distinct ids and colors', () => {+ const hub = new PresenceHub()+ const windowId = 1 // Electron webContents.id+ const phoneId = allocateRelayClientId()+ hub.join(windowId, 'desktop')+ hub.join(phoneId, 'phone')++ expect(phoneId).not.toBe(windowId)+ const [desk, phone] = hub.peers()+ expect(desk).toMatchObject({ kind: 'desktop', name: 'Someone', cursor: null })+ expect(phone).toMatchObject({ kind: 'phone', name: 'Phone', cursor: null })+ expect(desk.color).not.toBe(phone.color)++ // sendTo for a relay peer targets an id no shell can resolve — it must be a silent drop,+ // never a throw (Electron's webContents.fromId returns null; ServerPlatform has no sink).+ expect(() => hub.setChat(phoneId, 'from the phone')).not.toThrow()++ hub.leave(phoneId)+ expect(hub.peers().map((p) => p.kind)).toEqual(['desktop'])+ })+})+describe('allocateRelayClientId', () => {it('mints monotonic ids from a range that cannot collide with a UI id', () => {const a = allocateRelayClientId()diff --git a/src/main/index.ts b/src/main/index.tsindex 5b2fab993..6b26ff24f 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -9,6 +9,7 @@ import { PtyManager } from '../core/pty-manager'import { WorkspaceStore } from '../core/workspace-store'import { WorkspaceWatcher } from '../core/workspace-watcher'import { SettingsStore } from '../core/settings-store'+import { presenceHub } from '../core/presence/hub'import { SshStore } from './ssh-store'import { GitService } from '../core/git-service'import { generateCommitMessage, generateGroupName, generateTerminalName } from '../core/commit-message'@@ -237,6 +238,16 @@ function createWindow(): BrowserWindow {// Register as the live main window (send-time resolution via getMainWindow/sendToMain).setMainWindow(win)+ // Team presence: this window is one peer. With nobody else connected the renderer draws nothing+ // (≤1 peer = zero cost); it matters when a phone joins over the relay, or when this desktop+ // hosts. Its ClientId is the webContents id — the same id space sendTo/handleWithSender use.+ // `closed` (not `close` — which only hides the window on macOS) is the real departure.+ // (The id is captured up front: reading `win.webContents` after 'closed' throws — the window and+ // its webContents are destroyed by then.)+ const presenceId = win.webContents.id+ presenceHub.join(presenceId, 'desktop')+ win.on('closed', () => presenceHub.leave(presenceId))+win.on('ready-to-show', () => win.show())// macOS: closing the window hides it instead of destroying it. The app deliberately@@ -324,6 +335,7 @@ app.whenReady().then(async () => {ptyManager.registerIpc()workspaceStore.registerIpc()gitService.registerIpc()+ presenceHub.registerIpc()ipcMain.handle(IPC.commitGenerate, (_e, cwd: string) =>generateCommitMessage(cwd, settingsStore.get())diff --git a/src/main/remote/standing-host.test.ts b/src/main/remote/standing-host.test.tsnew file mode 100644index 000000000..484e0890d--- /dev/null+++ b/src/main/remote/standing-host.test.ts@@ -0,0 +1,182 @@+// Standing-host presence wiring: a bridged relay client (a phone) is a `kind:'phone'` peer, and+// EVERY end path for that session — the relay socket dropping, the human rejecting the device, an+// idle-token teardown, the host being disabled / the app quitting — must reach presenceHub.leave()+// exactly once. A missed leave is a permanent ghost cursor in everyone's facepile.+//+// electron + the relay/license/disk modules are mocked; what's under test is the standing host'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 { HostSession, HostSessionOptions } from './host-service'++const ipc: Record<string, (e: unknown, msg: unknown) => void> = {}++vi.mock('electron', () => ({+ ipcMain: {+ on: (ch: string, fn: (e: unknown, msg: unknown) => void) => {+ ipc[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: () => () => {}+}))+vi.mock('./approved-devices', () => ({+ loadApprovedDevices: async () => ({ pubkeys: [] as string[] }),+ saveApprovedDevices: async () => {}+}))+vi.mock('./e2ee', () => ({ publicKeyToB64: () => 'host-pub' }))++const sessions: Array<{ opts: HostSessionOptions; session: HostSession; closed: number }> = []++vi.mock('./host-service', () => ({+ API_BASE: 'https://api.test',+ RELAY_URL: 'wss://relay.test',+ relayAllowed: () => true,+ loadOrCreateKeyPair: async () => ({ publicKey: new Uint8Array(), secretKey: new Uint8Array() }),+ connectHostSession: (opts: HostSessionOptions): HostSession => {+ const entry = { opts, closed: 0, session: null as unknown as HostSession }+ entry.session = {+ approve: () => {},+ isApproved: () => false,+ sas: () => '12345',+ // A real relay socket close() is "intentional" and does NOT fire onClose — modelled here.+ peerPublicKeyB64: () => 'phone-pub',+ close: () => {+ entry.closed += 1+ }+ }+ sessions.push(entry)+ return entry.session+ }+}))++import { initStandingHost } from './standing-host'+import { IPC } from '../../shared/ipc'++/** Let the async connectOne() chain (token mint, keypair) settle. */+async function settle(): Promise<void> {+ for (let i = 0; i < 12; i++) await Promise.resolve()+}++function phones(): number {+ return presenceHub.peers().filter((p) => p.kind === 'phone').length+}++const sentToWin: Array<{ channel: string; args: unknown[] }> = []++function makeHost() {+ const win = {+ isDestroyed: () => false,+ webContents: {+ send: (channel: string, ...args: unknown[]) => sentToWin.push({ channel, args })+ }+ }+ return initStandingHost(win as never, {} as never, () => ({ phoneAccessEnabled: true }) as never)+}++/** 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+}++beforeEach(() => {+ initPlatform(fakePlatform())+ sessions.length = 0+ for (const key of Object.keys(ipc)) delete ipc[key]+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({+ ok: true,+ json: async () => ({ pairingToken: 'tok', hostId: 'host', exp: 0 })+ }))+ )+})++afterEach(() => {+ for (const p of presenceHub.peers()) presenceHub.leave(p.clientId)+ vi.unstubAllGlobals()+ resetPlatformForTests()+})++describe('standing host presence peers', () => {+ it('a bridged relay client joins as a cursorless phone peer and leaves when the socket drops', async () => {+ const host = makeHost()+ host.setEnabled(true)+ await settle()+ expect(sessions).toHaveLength(1)+ expect(phones()).toBe(0) // an idle (un-bridged) listener is nobody++ sessions[0].opts.onPeerReady(sessions[0].session)+ await settle()+ 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++ // Clean disconnect (relay socket dropped) → the peer leaves.+ sessions[0].opts.onClose()+ expect(phones()).toBe(0)++ host.stop()+ })++ it('leaves the hub when the human rejects the device (close() never fires onClose)', async () => {+ const host = makeHost()+ host.setEnabled(true)+ await settle()+ sessions[0].opts.onPeerReady(sessions[0].session)+ await settle()+ expect(phones()).toBe(1)++ // Reject → removeFromPool → session.close(). A real relay socket treats an intentional close+ // as final and does NOT call onClose, so the leave has to happen on this path too.+ ipc[IPC.remoteHostReject](null, { id: pendingApprovalId() })+ expect(sessions[0].closed).toBe(1)+ expect(phones()).toBe(0)++ host.stop()+ })++ it('leaves the hub when the host is disabled / the app quits (stop() tears the pool down)', async () => {+ const host = makeHost()+ host.setEnabled(true)+ await settle()+ sessions[0].opts.onPeerReady(sessions[0].session)+ await settle()+ expect(phones()).toBe(1)++ host.stop()+ expect(phones()).toBe(0)+ })++ it('a bridged peer leaves exactly once even if close() and onClose() both fire', async () => {+ const host = makeHost()+ host.setEnabled(true)+ await settle()+ sessions[0].opts.onPeerReady(sessions[0].session)+ await settle()+ const id = presenceHub.peers().find((p) => p.kind === 'phone')!.clientId++ host.stop() // → removeFromPool → close() → leave+ sessions[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/standing-host.ts b/src/main/remote/standing-host.tsindex 2594bd4b1..f0697c2f1 100644--- a/src/main/remote/standing-host.ts+++ b/src/main/remote/standing-host.ts@@ -23,6 +23,8 @@ 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 { publicKeyToB64 } from './e2ee'import {API_BASE,@@ -106,6 +108,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/** Per-session pending approval (unknown device awaiting the human's SAS decision). */approvalPub: string | nullapprovalId: string | null@@ -130,6 +134,17 @@ 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+ }+function clearApproval(p: Pooled): void {if (p.approvalTimer) {clearTimeout(p.approvalTimer)@@ -141,6 +156,7 @@ export function initStandingHost(function removeFromPool(p: Pooled): void {clearApproval(p)+ leavePresence(p)if (p.refreshTimer) {clearTimeout(p.refreshTimer)p.refreshTimer = null@@ -196,6 +212,10 @@ export function initStandingHost(async function onPeerReady(pooled: Pooled): Promise<void> {if (!pooled.bridged) {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')ensurePool() // this listener now serves a client → restore a warm one}const s = pooled.session@@ -245,6 +265,7 @@ export function initStandingHost(const pooled: Pooled = {session: null as unknown as HostSession,bridged: false,+ presenceId: null,approvalPub: null,approvalId: null,approvalTimer: null,@@ -262,6 +283,7 @@ export function initStandingHost(onPeerReady: () => void onPeerReady(pooled),onClose: () => {clearApproval(pooled)+ leavePresence(pooled)if (pooled.refreshTimer) {clearTimeout(pooled.refreshTimer)pooled.refreshTimer = null