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.

fix(presence): pin the sender-aware pty channels against a composed double-fire

enes1235b9a46f63
diff --git a/src/core/presence/hub.test.ts b/src/core/presence/hub.test.ts
index 8bfd06219..fc1b0896f 100644
--- a/src/core/presence/hub.test.ts
+++ b/src/core/presence/hub.test.ts
@@ -408,6 +408,23 @@ describe('caps on client-supplied ids (focus / project)', () => {
})
})
+ // The typing badge's nodeId is reflected exactly like focus — and it is just as client-supplied:
+ // it is the session's persistKey, which the client chose at `pty:create`. Uncapped, a scripted
+ // client could open a session under a multi-KB node id and have the hub re-broadcast that string
+ // to every peer twice a second, for as long as it holds a key down.
+ it('caps the typing nodeId at REF_MAX_LEN code points, in the table AND in the broadcast diff', () => {
+ const hub = new PresenceHub()
+ hub.join(1, 'browser')
+
+ hub.noteTyping(1, 'x'.repeat(REF_MAX_LEN + 5_000))
+ expect(hub.peers()[0].typing?.nodeId).toBe('x'.repeat(REF_MAX_LEN))
+ expect(diffs().at(-1)).toMatchObject({
+ op: 'update',
+ clientId: 1,
+ patch: { typing: { nodeId: 'x'.repeat(REF_MAX_LEN) } }
+ })
+ })
+
it('caps by code point (the shared truncation rule), never splitting an emoji', () => {
const hub = new PresenceHub()
hub.join(1, 'browser')
diff --git a/src/core/presence/hub.ts b/src/core/presence/hub.ts
index 8092a295a..7d73a2a68 100644
--- a/src/core/presence/hub.ts
+++ b/src/core/presence/hub.ts
@@ -277,20 +277,27 @@ export class PresenceHub {
/** Someone wrote into a node's terminal. Throttled to 1 broadcast / TYPING_THROTTLE_MS per
* (client, node) — a keystroke storm must not become a broadcast storm. The badge's ~2s decay
* is the renderer's job (TYPING_DECAY_MS): the hub keeps no timers.
- * Stage 2 calls this from the sender-aware pty:write handler; nothing calls it in Stage 1. */
+ * Stage 2 calls this from the sender-aware pty:write handler; nothing calls it in Stage 1.
+ *
+ * `nodeId` is a REFLECTED ref like focus/projectId — it is re-broadcast to every peer (up to
+ * twice a second, per node) — and it is no more trusted than they are: it is the session's
+ * persistKey, which the client chose at `pty:create`. So it goes through the same truncation
+ * rule (capCodePoints/REF_MAX_LEN). Capping is done FIRST, so the throttle key and the
+ * broadcast payload can never disagree about which node this is. */
noteTyping(clientId: ClientId, nodeId: string): void {
const peer = this.table.get(clientId)
if (!peer || !nodeId) return
+ const id = capCodePoints(nodeId, REF_MAX_LEN)
const now = Date.now()
// The throttle key is (client, node) ALONE — never the peer's *current* typing badge. Someone
// writing alternately into two nodes (agent + shell) would never match `peer.typing.nodeId`,
// so every keystroke would broadcast to every peer. Each node keeps its own window; a
// different node is a different key and so still re-fires immediately.
- const key = `${clientId}:${nodeId}`
+ const key = `${clientId}:${id}`
const last = this.lastTyping.get(key) ?? 0
if (last && now - last < TYPING_THROTTLE_MS) return
this.lastTyping.set(key, now)
- const typing = { nodeId, at: now }
+ const typing = { nodeId: id, at: now }
peer.typing = typing
this.emit({ op: 'update', clientId, patch: { typing } })
}
diff --git a/src/core/pty-manager-platform.test.ts b/src/core/pty-manager-platform.test.ts
index 8a073b54f..ae1b29d7c 100644
--- a/src/core/pty-manager-platform.test.ts
+++ b/src/core/pty-manager-platform.test.ts
@@ -28,4 +28,27 @@ describe('PtyManager platform registration', () => {
expect(fake.handlers[ch] ?? fake.listeners[ch] ?? fake.senderListeners[ch], ch).toBeDefined()
}
})
+
+ // THE WORST REGRESSION IN THIS FILE, AND THE ONE NOTHING ELSE CATCHES.
+ //
+ // `on` and `onWithSender` COMPOSE on the same channel — on BOTH shells. Electron registers two
+ // separate `ipcMain.on`s; ServerPlatform keeps one ordered registry and invokes every entry. So
+ // a merge that resurrects the old `platform().on(IPC.ptyWrite, …)` line NEXT TO the sender-aware
+ // one does not error, does not typecheck-fail, and does not fail any behavioural test (they all
+ // invoke the sender map, and the fake keeps the two maps apart) — it just runs the handler TWICE:
+ // every keystroke, every paste, every user, doubled into the pty (`lls s`). Resize and flow are
+ // barely better: a doubled resize is a second full-pane tmux redraw, a doubled flow cast
+ // double-counts the pause the client owes.
+ //
+ // Hence this: the four migrated channels must have NO plain listener at all. If you are here
+ // because this went red, you added a second registration for a channel that already has a
+ // sender-aware one — delete it, don't relax the assertion.
+ it('registers the sender-aware pty channels EXACTLY ONCE (no composed plain listener)', async () => {
+ const { PtyManager } = await import('./pty-manager')
+ new PtyManager().registerIpc()
+ for (const ch of [IPC.ptyWrite, IPC.ptyResize, IPC.ptyFlow, IPC.ptyKill]) {
+ expect(fake.senderListeners[ch], ch).toBeDefined()
+ expect(fake.listeners[ch], ch).toBeUndefined()
+ }
+ })
})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 8eb1ab64d..cc1966219 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -255,10 +255,22 @@ interface Session {
/** The size currently pushed into the pty (seeded from the spawn's cols/rows). Guards against
* re-resizing the tmux client to the size it already has — that is a full-pane redraw. */
appliedSize?: PtySize
- /** The node id this session was created for, whether or not it is tmux-persisted — the key of
- * the `byPersistKey` co-attach index (`persistKey` below is only set for PERSISTED sessions,
- * because it also gates scrollback snapshots). Undefined for a relay-served (detached) pty,
- * which is deliberately not indexed. */
+ /**
+ * The node id (persistKey) this session was created for — set WHENEVER the caller supplied one,
+ * with no further conditions. It is not an index and it is not a persistence flag; it is just
+ * "which canvas node is this", which is exactly what a typing badge needs to point at (`write`).
+ *
+ * It exists because the two ids below are each conditional, and their conditions leave a hole:
+ * `indexKey` is unset for a DETACHED (relay-served) pty — a phone — and `persistKey` is unset
+ * when the session isn't persisted, which for a local session means tmux is off. Turn tmux off
+ * and a phone's session has NEITHER, so a phone's typing would be silently unbadgeable while a
+ * co-attached desktop peer's still lit up — a degenerate config, but a confusing, invisible
+ * degrade rather than an honest one. This field is unconditional, so it has no such hole.
+ */
+ nodeId?: string
+ /** The node id this session is CO-ATTACH-INDEXED under (`byPersistKey`) — set only for a session
+ * a second client may join, i.e. NOT for a relay-served (detached) pty, which is deliberately
+ * not indexed. See `nodeId` above for the plain "which node is this". */
indexKey?: string
/** Detached sinks: when set, output/exit ALSO go to these callbacks (relay host). */
onData?: (data: string) => void
@@ -267,7 +279,8 @@ interface Session {
buf: string[]
bufBytes: number
flushTimer: ReturnType<typeof setTimeout> | null
- /** Node id this session persists under (when tmux-backed) — used for scrollback snapshots. */
+ /** Node id this session PERSISTS under (only when tmux-backed / remote) — it gates scrollback
+ * snapshots and tmux kill/capture, so it must stay conditional. See `nodeId` above. */
persistKey?: string
/** When set, the session runs on a remote host via ssh; kill/capture target the REMOTE tmux. */
sshRemote?: NonNullable<PtyCreateOptions['sshRemote']>
@@ -897,6 +910,7 @@ export class PtyManager {
// A detached (relay-served) pty is left unseeded: its first `resize` must reach the pty,
// exactly as before, because its sink never reports a size at create time.
appliedSize: clientId === null ? undefined : spawnSize,
+ nodeId: options.persistKey,
indexKey: options.persistKey && !sinks ? options.persistKey : undefined,
onData: sinks?.onData,
onExit: sinks?.onExit,
@@ -1062,10 +1076,12 @@ export class PtyManager {
* 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.
+ * sessionId. `session.nodeId` is that id, and it is unconditional (see the field): the two
+ * conditional ids next to it, `indexKey` and `persistKey`, each go missing in a case the other
+ * covers — but with tmux OFF a relay-served (phone) session has NEITHER, and reading them here
+ * would leave a phone's typing silently unbadgeable while a co-attached desktop peer's still lit.
+ * A session created with no persistKey (a scratch pty) has no node id at all, 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
@@ -1079,9 +1095,8 @@ export class PtyManager {
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)
+ if (clientId !== null && session.nodeId && presenceHub.peerCount() > 1)
+ presenceHub.noteTyping(clientId, session.nodeId)
session.proc.write(data)
}
diff --git a/src/core/pty-typing.test.ts b/src/core/pty-typing.test.ts
index 236efaa7c..f275c7552 100644
--- a/src/core/pty-typing.test.ts
+++ b/src/core/pty-typing.test.ts
@@ -80,6 +80,25 @@ describe('typing attribution', () => {
expect(noteTyping).not.toHaveBeenCalled()
})
+ // A phone's session is DETACHED (relay-served): it is deliberately absent from the co-attach
+ // index, so it has no `indexKey`. With tmux ALSO off it isn't persisted either, so it has no
+ // `persistKey` — and reading only those two would leave the phone with no node id at all, i.e.
+ // its typing silently unbadgeable while a co-attached desktop peer's ring still lit. The session
+ // carries an unconditional `nodeId` precisely so that degenerate config degrades honestly.
+ it('attributes a DETACHED (relay/phone) session with tmux off — it still has a node id', async () => {
+ presenceHub.join(ALICE, 'desktop')
+ presenceHub.join(BOB, 'phone')
+ const noteTyping = vi.spyOn(presenceHub, 'noteTyping')
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager() // never init()'d → tmuxPath null → tmux off
+ const sessionId = mgr.createDetached(
+ { cols: 80, rows: 24, persistKey: 'node-phone' },
+ { onData: () => {}, onExit: () => {} }
+ )
+ mgr.write(BOB, sessionId, 'x')
+ expect(noteTyping.mock.calls).toEqual([[BOB, 'node-phone']])
+ })
+
// 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