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(pty): joinOnly and sizeVote create options for watch-only viewers

reviewc4c2b33074ce
diff --git a/src/core/pty-join-only.test.ts b/src/core/pty-join-only.test.ts
new file mode 100644
index 000000000..fe4121da4
--- /dev/null
+++ b/src/core/pty-join-only.test.ts
@@ -0,0 +1,237 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import { IPC } from '../shared/ipc'
+import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'
+
+/**
+ * A hosted-relay VIEWER may watch a terminal but never start one, and never constrains the shared
+ * pty's size. The relay access policy expresses both as create options (`joinOnly`, `sizeVote:
+ * false`); this suite pins what `PtyManager` does with them. Harness copied from
+ * pty-coattach.test.ts: a mocked `node-pty` that records each spawn and each resize, so "spawned
+ * nothing" is `spawned.length === 0` and "the pty kept its size" is "no resize was pushed".
+ */
+
+/** One fake pty per spawn, recorded so a test can assert "exactly one spawn" and push output. */
+interface FakePty {
+ onDataCb?: (d: string) => void
+ onExitCb?: (e: { exitCode: number }) => void
+ writes: string[]
+ resizes: Array<{ cols: number; rows: number }>
+ killed: boolean
+}
+const spawned: FakePty[] = []
+
+// Pin the persistence backend (see src/core/__fixtures__/no-session-host.ts): without this, a
+// checkout that ran `npm run build` would take the session-host branch instead of the mock below.
+vi.mock('./session-host-backend', async () =>
+ (await import('./__fixtures__/no-session-host')).noSessionHost()
+)
+
+vi.mock('node-pty', () => ({
+ spawn: (_file: string, _args: string[], _opts: unknown) => {
+ const p: FakePty = { writes: [], resizes: [], killed: false }
+ spawned.push(p)
+ return {
+ onData: (cb: (d: string) => void) => {
+ p.onDataCb = cb
+ },
+ onExit: (cb: (e: { exitCode: number }) => void) => {
+ p.onExitCb = cb
+ },
+ write: (d: string) => p.writes.push(d),
+ resize: (cols: number, rows: number) => p.resizes.push({ cols, rows }),
+ pause: () => {},
+ resume: () => {},
+ kill: () => {
+ p.killed = true
+ },
+ pid: 1234
+ }
+ }
+}))
+
+// A machine with pty devices to spare, always (same reason as pty-coattach.test.ts).
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
+const OWNER = 1
+const VIEWER = 2
+
+let fake: FakePlatform
+
+beforeEach(() => {
+ spawned.length = 0
+ fake = fakePlatform()
+ initPlatform(fake)
+ vi.useFakeTimers()
+})
+afterEach(() => {
+ vi.useRealTimers()
+ resetPlatformForTests()
+})
+
+/** The default manager: no tmux (init() never runs in unit tests), so a session is a plain shell. */
+async function manager() {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.registerIpc()
+ return m
+}
+
+/**
+ * A manager whose sessions are tmux-BACKED, with the `has-session` probe answering `exists`. The
+ * tmux path is forced (as pty-coattach.test.ts does) and every tmux subprocess the spawn path would
+ * run is stubbed, so no real tmux socket is touched.
+ */
+async function tmuxManager(exists: boolean) {
+ const m = await manager()
+ ;(m as unknown as { tmuxPath: string }).tmuxPath = '/usr/bin/tmux'
+ vi.spyOn(
+ m as unknown as { tmuxSessionExists: (k: string) => Promise<boolean> },
+ 'tmuxSessionExists'
+ ).mockResolvedValue(exists)
+ // The warm-reattach stale-cwd probe runs `tmux display-message`; answer "not stale".
+ vi.spyOn(
+ m as unknown as { paneCwdStale: (k: string) => Promise<boolean> },
+ 'paneCwdStale'
+ ).mockResolvedValue(false)
+ return m
+}
+
+const create = (clientId: number, options: Partial<PtyCreateOptions>) =>
+ fake.handlers[IPC.ptyCreate](clientId, {
+ cols: 80,
+ rows: 24,
+ persistKey: 'n1',
+ ...options
+ }) as Promise<PtyCreateResult>
+const kill = (clientId: number, sessionId: string) =>
+ fake.senderListeners[IPC.ptyKill](clientId, sessionId)
+const sizesSent = (sessionId: string) =>
+ fake.sent.filter((s) => s.channel === IPC.ptySize(sessionId))
+
+const REFUSED: PtyCreateResult = { sessionId: '', fresh: false, unavailable: 'join-only' }
+
+describe('joinOnly: a viewer may watch a terminal but never start one', () => {
+ it('refuses when no session exists and spawns nothing', async () => {
+ await manager()
+ expect(await create(VIEWER, { joinOnly: true })).toEqual(REFUSED)
+ expect(spawned).toHaveLength(0)
+ })
+
+ it('refuses when tmux says the session is gone, and spawns no tmux client', async () => {
+ await tmuxManager(false)
+ expect(await create(VIEWER, { joinOnly: true })).toEqual(REFUSED)
+ expect(spawned).toHaveLength(0)
+ })
+
+ it('refuses a create with no persistKey (there is nothing it could ever reattach to)', async () => {
+ await manager()
+ expect(await create(VIEWER, { joinOnly: true, persistKey: undefined })).toEqual(REFUSED)
+ expect(spawned).toHaveLength(0)
+ })
+
+ it('joins a live session (co-attach)', async () => {
+ await manager()
+ const a = await create(OWNER, {})
+ const b = await create(VIEWER, { joinOnly: true })
+ expect(b.sessionId).toBe(a.sessionId)
+ expect(b.fresh).toBe(false)
+ expect(b.unavailable).toBeUndefined()
+ expect(spawned).toHaveLength(1) // the owner's pty — the viewer subscribed to it
+ })
+
+ it("joins the owner's spawn when it races it (the in-flight barrier, not a refusal)", async () => {
+ await manager()
+ const [a, b] = await Promise.all([create(OWNER, {}), create(VIEWER, { joinOnly: true })])
+ expect(b.sessionId).toBe(a.sessionId)
+ expect(b.unavailable).toBeUndefined()
+ expect(spawned).toHaveLength(1)
+ })
+
+ it('warm-reattaches a tmux session that is still running', async () => {
+ await tmuxManager(true)
+ const res = await create(VIEWER, { joinOnly: true })
+ expect(res.unavailable).toBeUndefined()
+ expect(res.sessionId).not.toBe('')
+ expect(res.fresh).toBe(false)
+ expect(spawned).toHaveLength(1) // a tmux CLIENT onto the existing session, not a new session
+ })
+
+ it('a refusal leaves nothing behind: the owner still opens the node normally afterwards', async () => {
+ await manager()
+ expect(await create(VIEWER, { joinOnly: true })).toEqual(REFUSED)
+ const a = await create(OWNER, {})
+ expect(a.sessionId).not.toBe('')
+ expect(a.fresh).toBe(true)
+ expect(spawned).toHaveLength(1)
+ })
+
+ it('an absent joinOnly still spawns (the non-viewer path is unchanged)', async () => {
+ await manager()
+ const a = await create(OWNER, {})
+ expect(a.sessionId).not.toBe('')
+ expect(a.fresh).toBe(true)
+ expect(a.unavailable).toBeUndefined()
+ expect(spawned).toHaveLength(1)
+ })
+})
+
+describe('sizeVote: false — a viewer never constrains the shared pty size', () => {
+ it('never shrinks the shared pty', async () => {
+ await manager()
+ const a = await create(OWNER, { cols: 120, rows: 40 })
+ await create(VIEWER, { cols: 40, rows: 10, sizeVote: false })
+ // The pty was spawned at 120x40 and nothing was pushed since: it still runs at the owner's size.
+ expect(spawned[0].resizes).toEqual([])
+ expect(a.sessionId).not.toBe('')
+ })
+
+ it('control: the same join WITHOUT sizeVote:false does shrink it (smallest subscriber wins)', async () => {
+ await manager()
+ await create(OWNER, { cols: 120, rows: 40 })
+ await create(VIEWER, { cols: 40, rows: 10 })
+ expect(spawned[0].resizes.at(-1)).toEqual({ cols: 40, rows: 10 })
+ })
+
+ it('is still a subscriber: it is told the authoritative size and receives output', async () => {
+ await manager()
+ const { sessionId } = await create(OWNER, { cols: 120, rows: 40 })
+ fake.sent.length = 0
+ await create(VIEWER, { cols: 40, rows: 10, sizeVote: false })
+
+ const sent = sizesSent(sessionId)
+ expect(sent.map((s) => s.to)).toEqual([VIEWER]) // the owner already renders 120x40
+ expect(sent[0].args[0]).toEqual({ cols: 120, rows: 40 })
+
+ spawned[0].onDataCb?.('hello')
+ vi.advanceTimersByTime(20) // FLUSH_MS coalescing window
+ const data = fake.sent.filter((s) => s.channel === IPC.ptyData(sessionId))
+ expect(data.map((s) => s.to).sort()).toEqual([OWNER, VIEWER])
+ })
+
+ it('when the only voter leaves, the pty keeps its size rather than taking the viewer’s', async () => {
+ await manager()
+ const { sessionId } = await create(OWNER, { cols: 120, rows: 40 })
+ await create(VIEWER, { cols: 40, rows: 10, sizeVote: false })
+ kill(OWNER, sessionId)
+ expect(spawned[0].killed).toBe(false) // the viewer still watches
+ expect(spawned[0].resizes).toEqual([])
+ })
+
+ it('a viewer that warm-reattached holds no vote once the owner joins', async () => {
+ // The viewer's create is the first in this process, so it SPAWNS the tmux client (at its own
+ // grid — the pty needs some size). That must not seed a vote: when the owner then co-attaches,
+ // the pty takes the owner's size instead of staying pinned at the viewer's small window.
+ await tmuxManager(true)
+ const v = await create(VIEWER, { cols: 40, rows: 10, joinOnly: true, sizeVote: false })
+ expect(v.fresh).toBe(false)
+ const a = await create(OWNER, { cols: 120, rows: 40 })
+ expect(a.sessionId).toBe(v.sessionId)
+ expect(spawned).toHaveLength(1)
+ expect(spawned[0].resizes.at(-1)).toEqual({ cols: 120, rows: 40 })
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 46922b011..034edfd8f 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -2147,7 +2147,10 @@ export class PtyManager {
// tell it otherwise. applySize() then either shrinks the pty to it (it is the new smallest) or
// sends it the authoritative size to render + letterbox.
const size = normalizeSize(options.cols, options.rows)
- existing.sizes.set(sub, size)
+ // A non-voting view (`sizeVote: false`, a hosted-relay viewer) stays out of the min, exactly
+ // like a parked subscriber: it still gets output, and `shown` makes applySize tell it the
+ // authoritative size to render.
+ if (options.sizeVote !== false) existing.sizes.set(sub, size)
existing.shown.set(sub, size)
const before = existing.appliedSize
this.applySize(existingId, existing)
@@ -2283,6 +2286,12 @@ export class PtyManager {
: tmuxBacked
? !(await this.tmuxSessionExists(options.persistKey as string))
: true
+ // A join-only create (hosted-relay viewer) must never start a session: only a reattach to one
+ // that already exists is allowed. `fresh` here is "nothing to reattach to" — and for a node
+ // that would land on the session-host backend it is a placeholder `true` (that backend's
+ // attach-or-create IS its probe, see above), so a join-only create is refused there too rather
+ // than sent a round trip that could create. Fails closed: a viewer never starts anything.
+ if (options.joinOnly && fresh) return { sessionId: '', fresh: false, unavailable: 'join-only' }
// Ensure the login-shell PATH is resolved (prewarmed in init(); usually already settled)
// so the session env below picks it up — awaiting keeps the event loop free either way.
await resolveShellPath()
@@ -3452,8 +3461,12 @@ export class PtyManager {
? new NativeWindowsPane(proc, { ...options, scrollback: settings.tmuxScrollback })
: undefined,
subscribers: spawnSub === null ? new Set<SubKey>() : new Set<SubKey>([spawnSub]),
+ // A non-voting view (`sizeVote: false`) that got here — a hosted-relay viewer's warm tmux
+ // reattach — spawns the client at its own grid (the pty needs SOME size) but seeds no vote,
+ // the same rule `join` applies: otherwise the owner co-attaching later would stay pinned at
+ // min(owner, viewer), i.e. the viewer's small window would still shrink everyone's terminal.
sizes:
- spawnSub === null
+ spawnSub === null || options.sizeVote === false
? new Map<SubKey | null, PtySize>()
: new Map<SubKey | null, PtySize>([[spawnSub, spawnSize]]),
shown:
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 06638515b..e3687079b 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -3304,6 +3304,13 @@ export function TerminalNode({
// the near-side guard above produces, retry included.
if (unavailable) {
const refusal = ptyRefusal(unavailable)
+ // A hosted-relay VIEWER opened a terminal nobody has running. Nothing failed and nothing
+ // is offline, so neither overlay applies — "Try again" would only respawn into the same
+ // refusal. Say why the pane is empty and stop; "Refresh terminal" re-asks on demand.
+ if (unavailable === 'join-only') {
+ if (!disposed) term.write(`\r\n\x1b[90m[${refusal.message}]\x1b[0m\r\n`)
+ return
+ }
setCo(
termKey,
refusal.connectionLost
diff --git a/src/shared/pty-refusal.test.ts b/src/shared/pty-refusal.test.ts
index 934a709fe..b4853129e 100644
--- a/src/shared/pty-refusal.test.ts
+++ b/src/shared/pty-refusal.test.ts
@@ -9,4 +9,12 @@ describe('PTY refusal presentation', () => {
it('retains reconnect behavior for an SSH refusal', () => {
expect(ptyRefusal('ssh')).toEqual({ connectionLost: true, message: 'not connected — nothing was started locally' })
})
+ // A hosted-relay viewer asked to watch a terminal nobody has open. Nothing is disconnected: read
+ // as `connectionLost`, the card modal would report an SSH drop and kick the reconnector for it.
+ it('a join-only refusal is not a lost connection, and says why nothing is shown', () => {
+ expect(ptyRefusal('join-only')).toEqual({
+ connectionLost: false,
+ message: 'this terminal is not running — a viewer can only watch terminals that are already open'
+ })
+ })
})
diff --git a/src/shared/pty-refusal.ts b/src/shared/pty-refusal.ts
index 15892a33a..261654814 100644
--- a/src/shared/pty-refusal.ts
+++ b/src/shared/pty-refusal.ts
@@ -11,5 +11,13 @@ export function ptyRefusal(unavailable: NonNullable<PtyCreateResult['unavailable
connectionLost: false
}
}
+ // A hosted-relay viewer asked for a terminal nobody has open. Nothing is disconnected — read as a
+ // lost connection it would report an SSH drop and kick the reconnector for a healthy project.
+ if (unavailable === 'join-only') {
+ return {
+ message: 'this terminal is not running — a viewer can only watch terminals that are already open',
+ connectionLost: false
+ }
+ }
return { message: 'not connected — nothing was started locally', connectionLost: true }
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f7c955e82..19a860026 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -170,6 +170,17 @@ export interface PtyCreateOptions {
* "not connected" overlay and re-spawns when the master is back.
*/
requireRemote?: boolean
+ /**
+ * Hosted-relay VIEWERS may watch a terminal but never start one: refuse a create that would spawn
+ * a NEW session (`unavailable: 'join-only'`), while a co-attach join or a warm tmux reattach still
+ * proceeds. Set only by the relay access policy (src/core/relay/access-policy.ts).
+ */
+ joinOnly?: boolean
+ /**
+ * `false`: this view never constrains the shared pty's size (a viewer's small window must not
+ * shrink everyone's terminal). It is still a subscriber and is told the authoritative size.
+ */
+ sizeVote?: false
}
/** A tmux pane's cursor, as tmux reports it: 0-based column/row within the pane, plus whether the
@@ -348,8 +359,11 @@ export interface PtyCreateResult {
* managed account whose home is missing refuses rather than spawning against the system login
* (§5 property 4). Remote managed Codex accounts refuse unknown/unsafe ids or unresolved/unsafe homes.
* System SSH Codex may attach before remote home discovery. Nothing spawned on refusal.
+ *
+ * `'join-only'`: `PtyCreateOptions.joinOnly` was set (a hosted-relay viewer) and there was no
+ * running session to join or reattach to, so nothing was started. Not a lost connection.
*/
- unavailable?: 'ssh' | 'codex-account'
+ unavailable?: 'ssh' | 'codex-account' | 'join-only'
}
/** Payload of `pty:recycled` — see IPC.ptyRecycled and `recycleAction` in the renderer. */