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(pty): only a SUBSCRIBER may steer a shared session

enese561ff4d3c67
diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.ts
index 715d25f75..f3a775271 100644
--- a/src/core/pty-coattach.test.ts
+++ b/src/core/pty-coattach.test.ts
@@ -89,6 +89,9 @@ describe('terminal co-attach: one PTY, N subscribers', () => {
// 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)
+ // pty:resize is sender-aware: the pty runs at the smallest SUBSCRIBER's grid.
+ const resize = (clientId: number, sessionId: string, cols: number | null, rows: number | null) =>
+ fake.senderListeners[IPC.ptyResize](clientId, sessionId, cols, rows)
it('a second client on the same persistKey subscribes instead of spawning', async () => {
await manager()
@@ -335,6 +338,75 @@ describe('terminal co-attach: one PTY, N subscribers', () => {
expect(spawned[0].killed).toBe(true)
})
+ // ── Only a SUBSCRIBER may steer a shared session ─────────────────────────────────────────
+ // Session ids are sequential and guessable (`pty-1`, `pty-2`, …) and every one of these casts
+ // takes the id straight off the wire. Without a membership check, any authenticated client could
+ // pause, clamp or type into a terminal it never opened — and since `dropClient` only ever swept
+ // sessions the client was subscribed to, the pause/size it planted would outlive its tab and
+ // freeze (or pin at 1x1) the shared pty for every real viewer, permanently.
+ it('a non-subscriber cannot pause the shared pty', async () => {
+ await manager()
+ const { sessionId } = await create(ALICE)
+
+ flow(BOB, sessionId, false) // Bob never opened this node
+ expect(spawned[0].paused).toBe(false)
+ })
+
+ it('a non-subscriber cannot clamp the shared grid', async () => {
+ await manager()
+ const { sessionId } = await create(ALICE, 80, 24)
+ fake.sent.length = 0
+
+ resize(BOB, sessionId, 1, 1)
+ expect(spawned[0].resizes).toEqual([]) // Alice's terminal keeps its size
+ expect(fake.sent.filter((s) => s.channel === IPC.ptySize(sessionId))).toEqual([])
+ })
+
+ it('a non-subscriber cannot type into the shared pty', async () => {
+ await manager()
+ const { sessionId } = await create(ALICE)
+
+ write(BOB, sessionId, 'rm -rf /\n')
+ expect(spawned[0].writes).toEqual([])
+ })
+
+ it('a client that unsubscribed cannot keep steering the session it left', async () => {
+ await manager()
+ const { sessionId } = await create(ALICE)
+ await create(BOB)
+ kill(BOB, sessionId)
+
+ flow(BOB, sessionId, false)
+ write(BOB, sessionId, 'x')
+ resize(BOB, sessionId, 1, 1)
+ expect(spawned[0].paused).toBe(false)
+ expect(spawned[0].writes).toEqual([])
+ expect(spawned[0].resizes).toEqual([])
+ })
+
+ // Belt and braces for the invariant the check above establishes: NOTHING a client left behind may
+ // outlive it. dropClient sweeps every session, not just the ones it subscribes to, so even a
+ // pause/size planted by some other (internal) path is returned when the client goes away.
+ it('dropClient sweeps a pause the client owes on a session it never subscribed to', async () => {
+ const m = await manager()
+ const { sessionId } = await create(ALICE)
+ m.setFlow(BOB, sessionId, false) // planted through the internal API, not the wire
+ expect(spawned[0].paused).toBe(true)
+
+ m.dropClient(BOB)
+ expect(spawned[0].paused).toBe(false) // Alice's terminal is not frozen forever
+ })
+
+ it('dropClient sweeps a size the client owes on a session it never subscribed to', async () => {
+ const m = await manager()
+ const { sessionId } = await create(ALICE, 80, 24)
+ m.resize(BOB, sessionId, 1, 1)
+ expect(spawned[0].resizes.at(-1)).toEqual({ cols: 1, rows: 1 })
+
+ m.dropClient(BOB)
+ expect(spawned[0].resizes.at(-1)).toEqual({ cols: 80, rows: 24 }) // back to the real viewer
+ })
+
// ── Finding 3: the same-tick create race ────────────────────────────────────────────────
// create() awaits a `tmux has-session` subprocess + the shell-PATH probe between the index
// lookup and spawnSession's synchronous registration, so two clients opening the same node
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 8dfa0b224..0f89413b3 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -475,17 +475,19 @@ export class PtyManager {
// 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)
- )
+ platform().onWithSender(IPC.ptyWrite, (senderId: number, sessionId: string, data: string) => {
+ if (!this.subscribes(senderId, sessionId)) return
+ 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
// channel, so leaving the old plain listener in place would run the resize twice.
platform().onWithSender(
IPC.ptyResize,
- (senderId: number, sessionId: string, cols: number | null, rows: number | null) =>
+ (senderId: number, sessionId: string, cols: number | null, rows: number | null) => {
+ if (!this.subscribes(senderId, sessionId)) return
this.resize(senderId, sessionId, cols, rows)
+ }
)
// Sender-aware: a pause belongs to the client whose xterm backlog overflowed, and only that
// client (or its departure) can return it — see `Session.pausedBy`. Registered ONLY here:
@@ -493,14 +495,17 @@ export class PtyManager {
// run the flow change twice (and, with an unattributed sessionId, wrongly).
platform().onWithSender(
IPC.ptyFlow,
- (senderId: number, sessionId: string, resume: boolean) =>
+ (senderId: number, sessionId: string, resume: boolean) => {
+ if (!this.subscribes(senderId, sessionId)) return
this.setFlow(senderId, sessionId, resume)
+ }
)
// Sender-aware: with co-attach a kill detaches just THAT client, and the pty (and the tmux
// session behind it) survives while any other subscriber is still watching.
- platform().onWithSender(IPC.ptyKill, (senderId: number, sessionId: string) =>
+ platform().onWithSender(IPC.ptyKill, (senderId: number, sessionId: string) => {
+ if (!this.subscribes(senderId, sessionId)) return
this.kill(senderId, sessionId)
- )
+ })
// Sender-aware: the × permanently ends a session OTHER people may be watching, so the close
// event they get has to name WHO did it ("closed by <name>" — see `destroySession`).
// Registered ONLY here: `on` and `onWithSender` compose on the same channel, so a leftover
@@ -521,6 +526,26 @@ export class PtyManager {
)
}
+ /**
+ * Does this client actually WATCH this session? The membership check every wire-facing pty cast
+ * (write / resize / flow / kill) is gated on.
+ *
+ * Session ids are sequential and guessable (`pty-1`, `pty-2`, …) and each of those casts takes the
+ * id straight off the wire. Ungated, ANY authenticated client could steer a terminal it never
+ * opened: `pty:flow(pty-3, false)` pauses the shared pty (the producing process then blocks on a
+ * full pipe and every real viewer's terminal freezes), `pty:resize(pty-3, 1, 1)` pins everyone's
+ * grid at 1x1, `pty:write` types into someone else's shell. The invariant this establishes —
+ * EVERYTHING IN `pausedBy` / `sizes` BELONGS TO A SUBSCRIBER — is what makes `dropClient` a
+ * complete cleanup: a client can only ever owe what it subscribed for.
+ *
+ * The gate lives HERE, at the IPC seam, not inside the methods: the relay host calls
+ * `write`/`resize`/`kill`/`setFlow` directly for its DETACHED (sink-served) ptys, which have no
+ * subscribers by design, and that path is not off the wire.
+ */
+ private subscribes(clientId: ClientId, sessionId: string): boolean {
+ return this.sessions.get(sessionId)?.subscribers.has(clientId) ?? false
+ }
+
private async create(clientId: ClientId, options: PtyCreateOptions): Promise<PtyCreateResult> {
const key = options.persistKey
if (!key) return this.spawnNew(clientId, options)
@@ -1334,8 +1359,22 @@ export class PtyManager {
dropClient(clientId: ClientId): void {
// Snapshot the entries: kill() mutates `sessions` when a session falls to zero subscribers.
for (const [sessionId, session] of [...this.sessions]) {
- if (!session.subscribers.has(clientId)) continue
- this.kill(clientId, sessionId)
+ if (session.subscribers.has(clientId)) {
+ this.kill(clientId, sessionId)
+ continue
+ }
+ // NOT a subscriber — and yet it may still hold state here. Sweeping only the sessions a client
+ // subscribes to made the departure an INCOMPLETE cleanup: anything it owed elsewhere (a pause,
+ // a size) could never be returned, so a single entry left behind froze or clamped a shared pty
+ // for every real viewer, for the life of the core process. The wire casts are now gated on
+ // membership (`subscribes`), so this should find nothing; sweep unconditionally anyway — the
+ // invariant "nothing outlives its client" must not depend on every future caller remembering
+ // the gate.
+ const hadSize = session.sizes.delete(clientId)
+ const hadShown = session.shown.delete(clientId)
+ if (!hadSize && !hadShown && !session.pausedBy.has(clientId)) continue
+ this.releaseFlow(session, clientId)
+ this.applySize(sessionId, session)
}
}
diff --git a/src/core/pty-typing.test.ts b/src/core/pty-typing.test.ts
index f275c7552..825359a85 100644
--- a/src/core/pty-typing.test.ts
+++ b/src/core/pty-typing.test.ts
@@ -58,6 +58,9 @@ describe('typing attribution', () => {
rows: 24,
persistKey: 'node-42'
})) as { sessionId: string }
+ // Bob opens the same node — he CO-ATTACHES to Alice's session (one pty, two subscribers). He
+ // has to: only a subscriber may write into a shared session (see pty-coattach.test.ts).
+ await fake.handlers[IPC.ptyCreate](BOB, { cols: 80, rows: 24, persistKey: 'node-42' })
write(ALICE, sessionId, 'l')
write(BOB, sessionId, 's') // a second person typing into the same shell