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(presence): attribute pty:write to the sending client (typing badge)
enes76beacbc14a2
diff --git a/src/core/presence/hub.ts b/src/core/presence/hub.tsindex 086147705..8092a295a 100644--- a/src/core/presence/hub.ts+++ b/src/core/presence/hub.ts@@ -300,6 +300,13 @@ export class PresenceHub {return [...this.table.values()].map(copyPeer)}+ /** How many UIs are connected. Lets a caller skip work that only matters to OTHER people: the+ * pty:write path uses it to not report typing while the user is alone (a badge nobody but the+ * typist would receive — and their own is never drawn). See PtyManager.write. */+ peerCount(): number {+ return this.table.size+ }+/** Wire the presence channels into the shell. Idempotent on purpose: the shell's listener* registry does not dedup identical function references, so a second registration would make* every cast fire (and broadcast) twice. */diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.tsindex 643b32dc4..e0ec9864c 100644--- a/src/core/pty-coattach.test.ts+++ b/src/core/pty-coattach.test.ts@@ -84,6 +84,10 @@ describe('terminal co-attach: one PTY, N subscribers', () => {// so it can only be returned by that client (or by its departure).const flow = (clientId: number, sessionId: string, resume: boolean) =>fake.senderListeners[IPC.ptyFlow](clientId, sessionId, resume)+ // pty:write is sender-aware as well: with one pty and N subscribers, a keystroke has to carry WHO+ // typed it — that is what badges the node as "X is typing" (see pty-typing.test.ts).+ const write = (clientId: number, sessionId: string, data: string) =>+ fake.senderListeners[IPC.ptyWrite](clientId, sessionId, data)it('a second client on the same persistKey subscribes instead of spawning', async () => {await manager()@@ -157,8 +161,8 @@ describe('terminal co-attach: one PTY, N subscribers', () => {await manager()const { sessionId } = await create(ALICE)await create(BOB)- fake.listeners[IPC.ptyWrite](sessionId, 'a')- fake.listeners[IPC.ptyWrite](sessionId, 'b')+ write(ALICE, sessionId, 'a')+ write(BOB, sessionId, 'b')expect(spawned[0].writes).toEqual(['a', 'b'])})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex cd9406470..8eb1ab64d 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -27,6 +27,7 @@ import { machOArch, archMismatch } from './macho-arch'import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'import { claudeConfigDirFor } from './claude-config-dir'import { AUTH_ENV_STRIP, accountTmuxEnvArgs, remoteAccountConfigDirAbs } from './claude-accounts-core'+import { presenceHub } from './presence/hub'// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which// kills the tmux server) can still replay recent output on cold restart. A final snapshot also@@ -409,8 +410,13 @@ export class PtyManager {(senderId, options: PtyCreateOptions): Promise<PtyCreateResult> =>this.create(senderId, options))- platform().on(IPC.ptyWrite, (sessionId: string, data: string) =>- this.write(sessionId, data)+ // Sender-aware: with co-attach, a keystroke arriving here is no longer self-evidently "the one+ // user's" — WHO typed it is what lights the "X is typing" ring on everyone else's canvas (see+ // `write`). Registered ONLY here: `on` and `onWithSender` compose on the same channel, so+ // leaving the old plain listener in place would write every keystroke into the pty TWICE.+ platform().onWithSender(+ IPC.ptyWrite,+ (senderId: number, sessionId: string, data: string) => this.write(senderId, sessionId, data))// Sender-aware: a size is only meaningful with the client it belongs to — the pty runs at the// smallest one (`resize`). Registered ONLY here: `on` and `onWithSender` compose on the same@@ -1045,8 +1051,38 @@ export class PtyManager {}}- write(sessionId: string, data: string): void {- this.sessions.get(sessionId)?.proc.write(data)+ /**+ * Input from ONE client into the (possibly shared) session.+ *+ * ATTRIBUTION IS SERVER-SIDE, never client-declared: the sender is already identified by the+ * transport (Electron's webContents id, the Server Edition's uiId, the relay HostSession's+ * peer ClientId), so nobody can type as somebody else — and a phone typing over the relay lights+ * up the "X is typing" badge on every canvas with no client-side change at all. `clientId` is+ * `null` for a client the transport cannot name (a relay-served pty whose session has no presence+ * peer): its input still reaches the pty, it is just not badged.+ *+ * The badge is reported per NODE — the node id, which is what the canvas draws — never per+ * sessionId. Both `indexKey` and `persistKey` ARE that node id; they differ only in which+ * sessions carry them (`indexKey` is unset for a relay-served pty, which is deliberately not in+ * the co-attach index, and `persistKey` is unset when tmux is off), so take whichever is there.+ * A session with neither has no node id, and so nothing to badge.+ *+ * The hub throttles the broadcast (1 per 500 ms per client+node), so PtyManager does no+ * throttling of its own — but it does skip presence entirely when the user is ALONE: with one+ * peer in the table the only recipient would be the typist, whose own badge is never drawn, so a+ * solo keystroke burst must not cost a presence fan-out. The single-user path stays exactly the+ * old `sessions.get(id)?.proc.write(data)`.+ *+ * No locking — concurrent writers interleave characters in the one tmux session. That is the+ * documented v1 behavior (docs/team-presence.md, "No locking"); the badge IS the warning.+ */+ write(clientId: ClientId | null, sessionId: string, data: string): void {+ const session = this.sessions.get(sessionId)+ if (!session) return+ const nodeId = session.indexKey ?? session.persistKey+ if (clientId !== null && nodeId && presenceHub.peerCount() > 1)+ presenceHub.noteTyping(clientId, nodeId)+ session.proc.write(data)}/**diff --git a/src/core/pty-typing.test.ts b/src/core/pty-typing.test.tsnew file mode 100644index 000000000..236efaa7c--- /dev/null+++ b/src/core/pty-typing.test.ts@@ -0,0 +1,108 @@+// TYPING ATTRIBUTION — who wrote into which node's terminal (docs/team-presence.md).+//+// Stage 2 makes a terminal co-attachable, so a keystroke arriving at the pty is no longer+// self-evidently "the one user's". `pty:write` is therefore registered SENDER-AWARE, and the+// sending client is stamped onto the node id (the session's persistKey) via presenceHub.noteTyping+// — that is the whole "X is typing" ring. Attribution is server-side: the transport already knows+// who the sender is (webContents id / uiId / relay HostSession), so no client can claim to be+// someone else, and a phone typing over the relay is attributed with zero client-side change.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { presenceHub } from './presence/hub'+import { IPC } from '../shared/ipc'++vi.mock('node-pty', () => ({+ spawn: () => ({+ onData: () => {},+ onExit: () => {},+ write: () => {},+ resize: () => {},+ pause: () => {},+ resume: () => {},+ kill: () => {},+ pid: 1+ })+}))++const ALICE = 7+const BOB = 9++describe('typing attribution', () => {+ let fake: FakePlatform+ beforeEach(() => {+ fake = fakePlatform()+ initPlatform(fake)+ })+ afterEach(() => {+ // Leave the peers we joined: the hub is a process-wide singleton, so a test that left a peer+ // behind would change the next test's peer count (and so its typing behavior).+ presenceHub.leave(ALICE)+ presenceHub.leave(BOB)+ vi.restoreAllMocks()+ resetPlatformForTests()+ })++ const write = (clientId: number, sessionId: string, data: string): void =>+ fake.senderListeners[IPC.ptyWrite](clientId, sessionId, data)++ it('stamps the SENDING client on every pty:write, keyed by the node id (persistKey)', async () => {+ presenceHub.join(ALICE, 'desktop')+ presenceHub.join(BOB, 'browser')+ const noteTyping = vi.spyOn(presenceHub, 'noteTyping')+ const { PtyManager } = await import('./pty-manager')+ new PtyManager().registerIpc()+ const { sessionId } = (await fake.handlers[IPC.ptyCreate](ALICE, {+ cols: 80,+ rows: 24,+ persistKey: 'node-42'+ })) as { sessionId: string }++ write(ALICE, sessionId, 'l')+ write(BOB, sessionId, 's') // a second person typing into the same shell+ expect(noteTyping.mock.calls).toEqual([+ [ALICE, 'node-42'],+ [BOB, 'node-42']+ ])+ })++ it('does not attribute a write to a session with no node id (no persistKey → nothing to badge)', async () => {+ presenceHub.join(ALICE, 'desktop')+ presenceHub.join(BOB, 'browser')+ const noteTyping = vi.spyOn(presenceHub, 'noteTyping')+ const { PtyManager } = await import('./pty-manager')+ new PtyManager().registerIpc()+ const { sessionId } = (await fake.handlers[IPC.ptyCreate](ALICE, { cols: 80, rows: 24 })) as {+ sessionId: string+ }+ write(ALICE, sessionId, 'x')+ expect(noteTyping).not.toHaveBeenCalled()+ })++ // The single-user path pays NOTHING for a feature that exists for a second person: with one peer+ // in the table the only recipient of a typing badge is the typist, whose own badge is never drawn.+ // Calling noteTyping anyway would fan a presence:peer diff out to the renderer twice a second, for+ // every keystroke burst, for the person working alone — which is everybody, most of the time.+ it('does not touch presence at all while the user is ALONE (no peer to badge)', async () => {+ presenceHub.join(ALICE, 'desktop')+ const noteTyping = vi.spyOn(presenceHub, 'noteTyping')+ const { PtyManager } = await import('./pty-manager')+ new PtyManager().registerIpc()+ const { sessionId } = (await fake.handlers[IPC.ptyCreate](ALICE, {+ cols: 80,+ rows: 24,+ persistKey: 'node-42'+ })) as { sessionId: string }++ fake.sent.length = 0+ write(ALICE, sessionId, 'l')+ expect(noteTyping).not.toHaveBeenCalled()+ expect(fake.sent).toEqual([])++ // …and the moment somebody else joins, the very next keystroke is attributed.+ presenceHub.join(BOB, 'browser')+ write(ALICE, sessionId, 's')+ expect(noteTyping.mock.calls).toEqual([[ALICE, 'node-42']])+ })+})diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex 046a4bf3a..a2a4395f1 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -60,7 +60,9 @@ export interface HostPtyManager {): string/** Current visible screen of a node's tmux session, for the attach snapshot. */captureSnapshot(persistKey: string): Promise<string>- write(sessionId: string, data: string): void+ /** `clientId` identifies WHO typed (the bridged phone's presence peer), so the keystroke can be+ * attributed to it — null when this session has no peer, which just means it is not badged. */+ write(clientId: number | null, sessionId: string, data: string): void/** `clientId` is null for a relay-served (detached) pty — see `kill` below. */resize(clientId: number | null,@@ -151,7 +153,13 @@ export function createHostHandlers(// Produce the marker-delimited "projects" blob for the `projects.list` RPC (workspace.json +// live tmux session names + agent-status.json — the same bytes the iOS SSH browse path reads).// Read-only, takes no client params. Default = empty so the 4-arg security tests still compile.- listProjects: () => Promise<string> = async () => ''+ listProjects: () => Promise<string> = async () => '',+ // The presence ClientId of the phone this host serves (null until it bridges / if it has no+ // presence slot). Read per frame, never captured: the slot is joined at onPeerReady, and the+ // session's PhonePresence outlives none of it. It makes the phone's keystrokes attributable —+ // the "X is typing" badge for a relay peer costs the iOS app exactly nothing, because the sender+ // is the identified HostSession, not something the client claims.+ getClientId: () => number | null = () => null): HostHandlers {// streamId -> Stream. PTY callbacks close over their own `streamId` directly, so no// reverse (sessionId -> streamId) index is needed.@@ -347,7 +355,7 @@ export function createHostHandlers(const stream = streams.get(frame.streamId)if (!stream) returnif (frame.op === OP.Input) {- pty.write(stream.sessionId, textDecoder.decode(frame.payload))+ pty.write(getClientId(), stream.sessionId, textDecoder.decode(frame.payload))return}if (frame.op === OP.Resize) {@@ -587,6 +595,12 @@ export interface HostSessionOptions {* Optional: omit for host sessions that don't serve project browse (defaults to an empty blob).*/listProjects?: () => Promise<string>+ /**+ * The presence ClientId of the phone this session bridges (its PhonePresence slot), so its+ * keystrokes are attributed to it in the typing badge. Optional: a host session without a+ * presence slot serves input exactly as before, unbadged.+ */+ getClientId?: () => number | null/*** A peer completed the E2EE handshake and awaits an approval decision. The caller inspects the* session (sas / peerPublicKeyB64) and either approves immediately (pin-once) or prompts the@@ -700,7 +714,8 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {socket,fsOps,() => rootsFromCanvas(opts.getLatestCanvas()),- opts.listProjects ?? (async () => '')+ opts.listProjects ?? (async () => ''),+ opts.getClientId ?? (() => null))canvasSync = createHostCanvasSync(socket, opts.applyMutation)unsubCanvas = opts.subscribeCanvas(() => scheduleBroadcast())@@ -777,6 +792,8 @@ export function initRemoteHost(subscribeCanvas,applyMutation: (mutation) => send(IPC.remoteHostApplyMutation, mutation),listProjects,+ // Typing attribution: this session's input frames are this phone's keystrokes.+ getClientId: () => phone.id(),// 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 cursorlessdiff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.tsindex 770437665..fadd9cb33 100644--- a/src/main/remote/standing-host.ts+++ b/src/main/remote/standing-host.ts@@ -273,6 +273,8 @@ export function initStandingHost(subscribeCanvas,applyMutation: (mutation: CanvasMutation) => send(IPC.remoteHostApplyMutation, mutation),listProjects,+ // Typing attribution: this pooled session's input frames are ITS phone's keystrokes.+ getClientId: () => pooled.presence.id(),onPeerReady: () => void onPeerReady(pooled),onClose: () => {clearApproval(pooled)diff --git a/test/remote/host-handlers.test.ts b/test/remote/host-handlers.test.tsindex 256b29217..4fc68e7c4 100644--- a/test/remote/host-handlers.test.ts+++ b/test/remote/host-handlers.test.ts@@ -33,7 +33,8 @@ function fakePty() {calls.push({ method: 'captureSnapshot', args: [persistKey] })return snapshot},- write: (sessionId, data) => calls.push({ method: 'write', args: [sessionId, data] }),+ write: (clientId, sessionId, data) =>+ calls.push({ method: 'write', args: [clientId, sessionId, data] }),resize: (clientId, sessionId, cols, rows) =>calls.push({ method: 'resize', args: [clientId, sessionId, cols, rows] }),// A relay-served (detached) pty has no ClientId: its pause is owed by the host's sink (null).@@ -178,11 +179,25 @@ describe('createHostHandlers', () => {h.onFrame({ op: OP.Input, streamId: 1, seq: 0, payload: new TextEncoder().encode('ls\n') })h.onFrame({ op: OP.Resize, streamId: 1, seq: 0, payload: resizePayload(120, 40) })- expect(pty.calls).toContainEqual({ method: 'write', args: ['pty-1', 'ls\n'] })+ // No presence slot wired (getClientId defaults to null) → the input still reaches the pty, it+ // is simply not attributed to a typing peer.+ expect(pty.calls).toContainEqual({ method: 'write', args: [null, 'pty-1', 'ls\n'] })// clientId null: the relay-served pty's size is recorded against its sink, not a UI client.expect(pty.calls).toContainEqual({ method: 'resize', args: [null, 'pty-1', 120, 40] })})+ it('attributes an OP.Input frame to the bridged phone (typing badge, no iOS change needed)', async () => {+ const pty = fakePty()+ const sock = fakeSocket()+ // The phone's presence ClientId, read per frame from its PhonePresence slot (joined on bridge).+ const h = createHostHandlers(pty.mgr, sock.socket, undefined, undefined, undefined, () => 1_000_001)+ await openViaAttach(h)++ h.onFrame({ op: OP.Input, streamId: 1, seq: 0, payload: new TextEncoder().encode('ls\n') })++ expect(pty.calls).toContainEqual({ method: 'write', args: [1_000_001, 'pty-1', 'ls\n'] })+ })+it('ignores frames for unknown streams', () => {const pty = fakePty()const sock = fakeSocket()