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(session-host): size a shared session to its most recently active viewer (#914)

reviewddbee232c8f8
diff --git a/CLAUDE.md b/CLAUDE.md
index 47b5da05e..1d16ed130 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -864,6 +864,23 @@ unreachable there by construction; a Linux host is expected to have its own. Und
`scripts/build-tmux.mjs` writes its artifact. If tmux is unavailable from all three,
`PtyManager` still falls back to a plain shell; `TMUX`/`TMUX_PANE` are stripped from the child env to avoid nesting refusal.
+**A session-host session follows its most recently ACTIVE viewer, like tmux's `window-size
+latest`** (issue #914). Under tmux a relay-mirrored phone is its own tmux client, so dismissing its
+keyboard gives it its rows back; on the session host the phone and the desktop node share ONE
+client socket, and the old componentwise minimum held the phone to the desktop node's rows with an
+empty band and no explanation. `latestClaimSize` (`core/pty-size.ts`) picks the claim with the
+highest recency — bumped by an attach, a claim that CHANGES, and a write that is not an emulator's
+automatic answer (`core/terminal-reports.ts`; every attached xterm answers a DA/CPR/OSC query, and
+counting those would hand the session to whoever answered last). Three rules, each load-bearing:
+(1) a viewer that cannot adapt is a CEILING — today's phone ignores `OP.Resized`, and a pty wider
+than its screen wraps into garbage, so a relay sink is `bounding` unless `pty.attach` said
+`resizedFrames: true`; (2) the real size flows back to every viewer (`SessionHostPty.onSize` →
+`PtyManager.applyBackendSize` → `pty:size`, and `OP.Resized` to the sink), and a session-host
+`Session`'s `applySize` only VOTES; (3) the host's `geometry` push is NEGOTIATED at `hello`
+(`SESSION_HOST_FEATURES`) and sent only to sockets that asked — an older client reads every
+non-`data` push frame as an EXIT. Across app connections the host still takes the minimum. Full
+write-up: `docs/windows-session-host.md` → "Output ordering, flow ownership, and geometry".
+
### Cold restore (machine reboot)
tmux only survives an **app** restart — a **machine reboot kills the tmux server**, so every
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 82f705219..88a3e8417 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -282,6 +282,13 @@ lane unaffected.
sees the pane app's own bytes — see CLAUDE.md's "We have our own VT emulator" for the one place
that reasoning is inverted.
+- **A new session-host push frame must be negotiated at `hello`, never just sent.** An older
+ `SessionHostClient` treats EVERY push frame whose `type` is not `data` as an exit, and a
+ long-lived host routinely outlives the app that started it — so a frame the connection did not
+ opt into retires a live session. Add the capability to `SESSION_HOST_FEATURES`, send it only to
+ sockets that listed it (the `geometry` push of issue #914 is the worked example), and pin that
+ against the real bundled host as `session-host/geometry-host.test.ts` does.
+
- **Finding a Windows executable is not the same as being able to spawn it.** A PATH lookup may
correctly resolve an npm CLI to `<name>.cmd`, but Node's `execFile`/`spawn` cannot execute that
shim directly. For short-lived app-owned subprocesses, pass the resolved path and argv through
diff --git a/docs/windows-session-host.md b/docs/windows-session-host.md
index 2dfcdb92e..9427054e4 100644
--- a/docs/windows-session-host.md
+++ b/docs/windows-session-host.md
@@ -135,7 +135,7 @@ long-lived connection (no positional-FIFO fragility, unlike this app's tmux cont
| `attach` | `new-session -A` / `attach-session` | full, plus a screen the tmux path never needed (see below) |
| `hasSession` | `has-session -t <name>` | full (implemented; not on the hot create path — see below) |
| `write` | raw bytes on an attached client's stdin | full |
-| `resize` | ConPTY/pty resize + `refresh-client -C` | full; each view claims a size and the effective grid is the componentwise minimum |
+| `resize` | ConPTY/pty resize + `refresh-client -C` | full; each view claims a size, the app's grid follows its most recently active view (issue #914) |
| `pause` / `resume` | node-pty `pause()`/`resume()` | full; per-viewer in core and per-connection in the host (first pause / last resume) |
| `sendKeys` | `send-keys -l -- <text>` (+ `Enter`) | full — works with no attached client, exactly like tmux |
| `paneCommand` | `display-message -p '#{pane_current_command}'` | approximated — see `process-tree.ts` |
@@ -257,8 +257,37 @@ pause and geometry owner even though all of them share one `SessionHostClient` s
sends a pause only on the local 0→1 edge and a resume only on 1→0; the host then combines that one
connection-level ticket with other process sockets. Geometry follows the same shape: the client
reduces its live view claims, the host reduces all socket claims componentwise, and it resizes the
-PTY and headless terminal before serializing a warm screen. Detaching a smaller viewer recomputes
-the grid so remaining viewers can grow.
+PTY and headless terminal before serializing a warm screen. Detaching a viewer recomputes the grid.
+
+**The client's reduction is "most recently active", not "smallest" (issue #914).** Under tmux a
+phone mirroring a node is its own tmux client, and tmux's default `window-size latest` gives the
+window to whichever client was active last — so a phone that dismissed its keyboard got its rows
+back. Here the phone (a relay-served `SessionHostPty`) and the desktop node share ONE client
+socket, and the old componentwise minimum held the phone to the desktop node's rows with nothing on
+screen saying why. `latestClaimSize` (`core/pty-size.ts`) now picks the claim with the highest
+recency: an attach, a claim that CHANGES (a re-fit to the same size does not count, or every fit
+would steal the session), and a write that is not a terminal report (`core/terminal-reports.ts` —
+every attached xterm answers a DA/CPR/OSC query, and counting those would hand the session to
+whoever answered last). Three rules come with it:
+
+- **A viewer that cannot adapt is a ceiling.** Every renderer view renders the size it is told
+ (`pty:size`: letterbox a smaller grid, clip a larger one, as a tmux client does). The phone today
+ does not — it ignores `OP.Resized` — and a pty wider than its screen would wrap into garbage, so a
+ relay sink is `bounding` unless `pty.attach` carried `resizedFrames: true`, and the chosen size is
+ clamped componentwise to every bounding claim.
+- **The pty's real size flows back to every viewer.** `SessionHostPty.onSize` → `PtyManager`
+ `applyBackendSize` → `pty:size` to each view whose xterm is not already at it, and `OP.Resized`
+ (payload = `OP.Resize`'s, 2× uint16 LE) to the relay sink. A session-host `Session` only VOTES in
+ `applySize`; its views are corrected from the backend's answer, which the client sends after every
+ vote, changed or not.
+- **The host's `geometry` push is negotiated at hello, never assumed.** `hello` carries
+ `features: ['geometry']`; the host answers with the subset it speaks and pushes `geometry` frames
+ (and adds `geometry` to attach replies) ONLY on connections that asked. This is not caution: an
+ older client treats every push frame that is not `data` as an EXIT, so a geometry frame sent to it
+ retires a live session on the first resize (`session-host/geometry-host.test.ts` pins it against
+ the real bundled host). Against a host without the feature the client reports its own applied size,
+ which is exact while it is the host's only connection. Across connections (two apps on one host)
+ the HOST still takes the componentwise minimum.
The same name is also a generation boundary. Data and exit events contain a session name but no
generation id, so an exiting `HostSession` remains registered until its queued output, final exit
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 4764098c7..a1b210ae3 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -657,6 +657,17 @@ interface Session {
/** Detached sinks: when set, output/exit ALSO go to these callbacks (relay host). */
onData?: (data: string) => void
onExit?: (exitCode: number) => void
+ onSinkSize?: (size: PtySize) => void
+ sinkAdapts?: boolean
+ /** The size the relay sink is believed to render (its own last report, or the last size we told
+ * it). The sink analogue of `shown`. */
+ sinkShown?: PtySize
+ /** session-host only: the size the HOST says the shared pty runs at, which follows the most
+ * recently active viewer across every `Session` of the node (issue #914). Undefined until the
+ * backend has answered. */
+ backendSize?: PtySize
+ /** session-host only: whether `appliedSize` was pushed as a ceiling (see `DetachedSinks`). */
+ appliedBounding?: boolean
/** Pending output chunks, coalesced into one IPC message per flush. */
buf: string[]
bufBytes: number
@@ -718,6 +729,14 @@ interface Session {
export interface DetachedSinks {
onData(data: string): void
onExit(exitCode: number): void
+ /** The size the pty actually runs at, when that is not what this sink reported. Only a
+ * session-host session can disagree with its own viewer: it follows the most recently active
+ * viewer of the session, which may be a desktop node in another `Session` (issue #914). */
+ onSize?(size: PtySize): void
+ /** The sink's viewer renders whatever size `onSize` reports (letterbox or clip). False — every
+ * phone build today, which ignores the relay's `Resized` frame — makes the sink's own size a
+ * CEILING for the shared session: a viewer that cannot adapt would wrap a wider pty's output. */
+ adaptsToSize?: boolean
}
/**
@@ -3393,10 +3412,14 @@ 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,
+ // The spawn's claim went to the backend unbounded (a renderer view adapts to any size).
+ appliedBounding: false,
nodeId: options.persistKey,
indexKey: options.persistKey && !sinks ? options.persistKey : undefined,
onData: sinks?.onData,
onExit: sinks?.onExit,
+ onSinkSize: sinks?.onSize,
+ sinkAdapts: sinks?.adaptsToSize === true,
buf: [],
bufBytes: 0,
flushTimer: null,
@@ -3440,6 +3463,14 @@ export class PtyManager {
if (session.indexKey && !session.sessionHost && this.pendingRecycle.has(session.indexKey))
this.fireRecycled(session.indexKey, true)
+ const hostPty = useSessionHost ? (proc as unknown as Partial<SessionHostPty>) : null
+ if (typeof hostPty?.onSize === 'function') {
+ hostPty.onSize((size) => {
+ if (this.sessions.get(sessionId) !== session) return
+ this.applyBackendSize(sessionId, session, size)
+ })
+ }
+
proc.onData((data) => {
// A session-host attach can fail after the shim has already delivered startup bytes. Once
// rollback removes this exact generation, late callbacks must not recreate its flush timer
@@ -3632,6 +3663,10 @@ export class PtyManager {
// pty at whatever size it has. Resizing it to a default here would garble the parked xterms'
// buffers and the tmux pane behind them for no viewer's benefit.
if (!size) return
+ if (session.sessionHost) {
+ this.applySessionHostSize(sessionId, session, size)
+ return
+ }
if (session.appliedSize?.cols !== size.cols || session.appliedSize?.rows !== size.rows) {
session.appliedSize = size
try {
@@ -3653,6 +3688,62 @@ export class PtyManager {
}
}
+ /**
+ * `applySize` for a session-host session, where the size this `Session` asks for is only one vote
+ * (issue #914): the host follows the most recently active viewer across every `Session` of the
+ * node — this app's canvas node, its relay-served phone, another app — and reports back what the
+ * pty really runs at through `applyBackendSize`. So here we only VOTE; telling our views what
+ * they are showing is left to that answer, which the backend sends after every vote, changed or
+ * not. Min-over-views still decides this Session's vote, because the canvas node and the card
+ * modal share one claim exactly as they share one tmux client.
+ */
+ private applySessionHostSize(sessionId: string, session: Session, size: PtySize): void {
+ const bounding = session.sizes.has(null) && !session.sinkAdapts
+ if (
+ session.appliedSize?.cols !== size.cols ||
+ session.appliedSize?.rows !== size.rows ||
+ session.appliedBounding !== bounding
+ ) {
+ session.appliedSize = size
+ session.appliedBounding = bounding
+ try {
+ ;(session.proc as unknown as SessionHostPty).resize(size.cols, size.rows, bounding)
+ } catch {
+ // resize can throw if the proc already exited; ignore.
+ }
+ return
+ }
+ // Our vote did not move, so no answer is coming — but the view that reported may have just
+ // fitted itself to a size the pty is not running at. Correct it from the last answer we have.
+ if (session.backendSize) this.applyBackendSize(sessionId, session, session.backendSize)
+ }
+
+ /**
+ * The backend's answer: render exactly this. Every view whose xterm is not already at it is told
+ * over `pty:size` (it letterboxes a smaller grid and clips a larger one, as a tmux client does),
+ * and so is the relay sink, which forwards it to the phone as `OP.Resized`.
+ */
+ private applyBackendSize(sessionId: string, session: Session, size: PtySize): void {
+ session.backendSize = { cols: size.cols, rows: size.rows }
+ const channel = IPC.ptySize(sessionId)
+ for (const sub of session.subscribers) {
+ const shown = session.shown.get(sub)
+ if (shown && shown.cols === size.cols && shown.rows === size.rows) continue
+ session.shown.set(sub, session.backendSize)
+ this.send(subClient(sub), channel, session.backendSize)
+ }
+ if (session.onSinkSize && session.sizes.has(null)) {
+ const shown = session.sinkShown
+ if (shown && shown.cols === size.cols && shown.rows === size.rows) return
+ session.sinkShown = session.backendSize
+ try {
+ session.onSinkSize(session.backendSize)
+ } catch {
+ // A relay stream that has gone away must not break the desktop views' answer.
+ }
+ }
+ }
+
/** Buffer a chunk; flush immediately past the byte cap, otherwise on a short timer. */
private queueData(sessionId: string, session: Session, data: string): void {
session.outputSinceSnapshot = true
@@ -3887,6 +3978,8 @@ export class PtyManager {
} else {
const size = normalizeSize(cols, rows)
session.sizes.set(sub, size)
+ // The sink's viewer fits itself too; that fit is what it is rendering until told otherwise.
+ if (sub === null) session.sinkShown = size
// The view's own xterm fits itself locally (as it always has), so its fit — not the last
// authoritative size we sent it — is what it is rendering right now. If that fit isn't the
// effective size, applySize() below corrects it straight back.
diff --git a/src/core/pty-session-host.test.ts b/src/core/pty-session-host.test.ts
index b3835bd20..9ba1fc1e2 100644
--- a/src/core/pty-session-host.test.ts
+++ b/src/core/pty-session-host.test.ts
@@ -56,8 +56,13 @@ function fakeSessionHostPty(ready = Promise.resolve({ fresh: true })) {
let dataCb: ((data: string) => void) | undefined
let exitCb: ((e: { exitCode: number }) => void) | undefined
let attachErrorCb: ((error: Error) => void) | undefined
+ let sizeCb: ((size: { cols: number; rows: number }) => void) | undefined
return {
ready,
+ onSize: vi.fn((cb: (size: { cols: number; rows: number }) => void) => {
+ sizeCb = cb
+ }),
+ emitSize: (cols: number, rows: number) => sizeCb?.({ cols, rows }),
onData: vi.fn((cb: (data: string) => void) => {
dataCb = cb
}),
@@ -109,6 +114,77 @@ describe('PtyManager session-host contracts', () => {
return manager
}
+ describe('shared size follows the backend (issue #914)', () => {
+ function sizesSent(sessionId: string): Array<{ to: number | 'broadcast'; size: unknown }> {
+ return host.sent
+ .filter((message) => message.channel === IPC.ptySize(sessionId))
+ .map((message) => ({ to: message.to, size: message.args[0] }))
+ }
+
+ it('tells each view the size the host reports, once, and re-corrects a view that re-fits', async () => {
+ const shim = fakeSessionHostPty()
+ backend.create.mockReturnValue(shim)
+ const m = await makeManager()
+ m.registerIpc()
+ await host.handlers[IPC.ptyCreate](7, { cols: 80, rows: 24, persistKey: 'node-geo' })
+
+ // Another viewer of the session is the active one: the pty runs at ITS size.
+ shim.emitSize(100, 30)
+ shim.emitSize(100, 30)
+ expect(sizesSent('pty-1')).toEqual([{ to: 7, size: { cols: 100, rows: 30 } }])
+
+ // The view re-fits to its own grid. That is only a vote now — no local min broadcast — and
+ // the backend's answer (unchanged, the other viewer is still active) corrects it again.
+ m.resize(7, 'pty-1', 90, 20)
+ expect(shim.resize).toHaveBeenLastCalledWith(90, 20, false)
+ expect(sizesSent('pty-1')).toHaveLength(1)
+ shim.emitSize(100, 30)
+ expect(sizesSent('pty-1')).toEqual([
+ { to: 7, size: { cols: 100, rows: 30 } },
+ { to: 7, size: { cols: 100, rows: 30 } }
+ ])
+ })
+
+ it('re-sends the last answer when a view re-fits but the vote does not move', async () => {
+ const shim = fakeSessionHostPty()
+ backend.create.mockReturnValue(shim)
+ const m = await makeManager()
+ m.registerIpc()
+ await host.handlers[IPC.ptyCreate](7, { cols: 80, rows: 24, persistKey: 'node-geo-2' })
+ shim.emitSize(100, 30)
+ const resizes = shim.resize.mock.calls.length
+ // Same vote as the spawn size: nothing goes to the backend, so nothing would come back.
+ m.resize(7, 'pty-1', 80, 24)
+ expect(shim.resize.mock.calls.length).toBe(resizes)
+ expect(sizesSent('pty-1').at(-1)).toEqual({ to: 7, size: { cols: 100, rows: 30 } })
+ expect(sizesSent('pty-1')).toHaveLength(2)
+ })
+
+ it('makes a relay sink a ceiling unless it renders Resized, and forwards the answer to it', async () => {
+ const bounded = fakeSessionHostPty()
+ const adaptive = fakeSessionHostPty()
+ backend.create.mockReturnValueOnce(bounded).mockReturnValueOnce(adaptive)
+ const m = await makeManager()
+ const phoneSizes: unknown[] = []
+ const sid = m.createDetached(
+ { cols: 80, rows: 24, persistKey: 'node-phone' },
+ { onData: () => {}, onExit: () => {}, onSize: (size) => phoneSizes.push(size) }
+ )
+ m.resize(null, sid, 45, 40)
+ expect(bounded.resize).toHaveBeenLastCalledWith(45, 40, true)
+ bounded.emitSize(45, 30)
+ bounded.emitSize(45, 30)
+ expect(phoneSizes).toEqual([{ cols: 45, rows: 30 }])
+
+ const other = m.createDetached(
+ { cols: 80, rows: 24, persistKey: 'node-phone-2' },
+ { onData: () => {}, onExit: () => {}, adaptsToSize: true }
+ )
+ m.resize(null, other, 45, 40)
+ expect(adaptive.resize).toHaveBeenLastCalledWith(45, 40, false)
+ })
+ })
+
it('asks the session host whether a no-tmux persisted session exists', async () => {
const m = await makeManager()
backend.hasSession.mockResolvedValue(true)
diff --git a/src/core/pty-size.test.ts b/src/core/pty-size.test.ts
index 837244bc5..809cf5ecd 100644
--- a/src/core/pty-size.test.ts
+++ b/src/core/pty-size.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { effectiveSize } from './pty-size'
+import { effectiveSize, latestClaimSize } from './pty-size'
import { IPC } from '../shared/ipc'
describe('effectiveSize', () => {
@@ -43,3 +43,39 @@ describe('per-session channels', () => {
expect(IPC.ptyClosed('pty-1')).toBe('pty:closed:pty-1')
})
})
+
+describe('latestClaimSize (issue #914)', () => {
+ it('is null with no claims', () => {
+ expect(latestClaimSize([])).toBeNull()
+ })
+
+ it('gives the session to the most recently active claim, not the smallest', () => {
+ // A desktop node (short) and a phone that just dismissed its keyboard (tall).
+ const desktop = { cols: 120, rows: 30, recency: 1 }
+ const phone = { cols: 120, rows: 40, recency: 2 }
+ expect(latestClaimSize([desktop, phone])).toEqual({ cols: 120, rows: 40 })
+ expect(latestClaimSize([{ ...desktop, recency: 3 }, phone])).toEqual({ cols: 120, rows: 30 })
+ })
+
+ it('never grows the session past a viewer that cannot adapt to it', () => {
+ const phone = { cols: 45, rows: 40, recency: 1, bounding: true }
+ const desktop = { cols: 120, rows: 30, recency: 2 }
+ // Desktop is latest, but the phone would wrap a 120-column pty: cols clamp, rows follow desktop.
+ expect(latestClaimSize([phone, desktop])).toEqual({ cols: 45, rows: 30 })
+ // Phone latest: its own size, which is within its own ceiling.
+ expect(latestClaimSize([{ ...phone, recency: 3 }, desktop])).toEqual({ cols: 45, rows: 40 })
+ })
+
+ it('breaks a recency tie toward the later claim', () => {
+ expect(
+ latestClaimSize([
+ { cols: 80, rows: 24, recency: 0 },
+ { cols: 100, rows: 50, recency: 0 }
+ ])
+ ).toEqual({ cols: 100, rows: 50 })
+ })
+
+ it('floors and clamps exactly like effectiveSize', () => {
+ expect(latestClaimSize([{ cols: 90.9, rows: 0, recency: 1 }])).toEqual({ cols: 90, rows: 1 })
+ })
+})
diff --git a/src/core/pty-size.ts b/src/core/pty-size.ts
index e58ec81fc..6fecc24e2 100644
--- a/src/core/pty-size.ts
+++ b/src/core/pty-size.ts
@@ -33,3 +33,49 @@ export function effectiveSize(sizes: Iterable<PtySize>): PtySize | null {
rows: Number.isFinite(rows) ? Math.max(1, Math.floor(rows)) : 1
}
}
+
+/**
+ * One viewer's vote on a shared session's size, for `latestClaimSize`.
+ *
+ * `recency` orders the claims (higher = more recently active). `bounding` marks a viewer that
+ * cannot adapt to a grid other than its own — today the phone over the relay, whose app ignores
+ * the host's `Resized` frame. Such a viewer rendering a pty WIDER or TALLER than its own screen
+ * does not letterbox, it wraps and scrolls the other viewer's output into garbage, so its size is
+ * a ceiling for everyone rather than just a vote.
+ */
+export interface SizeClaim extends PtySize {
+ recency: number
+ bounding?: boolean
+}
+
+/**
+ * The size a session-host pty runs at when several viewers share it: the MOST RECENTLY ACTIVE
+ * viewer's size — tmux's `window-size latest`, which is what a tmux-backed session already does,
+ * because there the phone and the desktop are separate tmux clients (issue #914) — clamped
+ * componentwise to every `bounding` claim. Null when there are no claims.
+ *
+ * Why not the minimum any more: min is safe for every viewer, but it means a phone that dismisses
+ * its keyboard can never get its rows back while a shorter desktop node is attached, and nothing
+ * on the phone says why. The viewers that DO adapt (every renderer xterm, via `pty:size`) render a
+ * larger grid by clipping and a smaller one by letterboxing, exactly as a tmux client shows a
+ * window of another client's size — so "latest wins" costs them nothing but the clip.
+ *
+ * Ties go to the claim that comes LAST in iteration order (Map insertion order), so a caller that
+ * never bumps recency gets "most recently added" rather than an arbitrary pick.
+ */
+export function latestClaimSize(claims: Iterable<SizeClaim>): PtySize | null {
+ let latest: SizeClaim | null = null
+ let capCols = Infinity
+ let capRows = Infinity
+ for (const claim of claims) {
+ if (!latest || claim.recency >= latest.recency) latest = claim
+ if (claim.bounding) {
+ capCols = Math.min(capCols, claim.cols)
+ capRows = Math.min(capRows, claim.rows)
+ }
+ }
+ if (!latest) return null
+ return effectiveSize([
+ { cols: Math.min(latest.cols, capCols), rows: Math.min(latest.rows, capRows) }
+ ])
+}
diff --git a/src/core/session-host-client-flow.test.ts b/src/core/session-host-client-flow.test.ts
index 6db6099a2..b5d857425 100644
--- a/src/core/session-host-client-flow.test.ts
+++ b/src/core/session-host-client-flow.test.ts
@@ -474,7 +474,7 @@ describe('SessionHostClient subscriber flow and reconnect barriers', () => {
expect(delivered).toEqual(['COLD-PRE-ACK', 'POST-ACK'])
})
- it('uses componentwise local geometry, normalizes invalid axes, and grows when the limiting view leaves', async () => {
+ it('follows the most recently active view, normalizes invalid axes, and falls back when it leaves (issue #914)', async () => {
const { userDataDir, endpoint } = fixture('nodeterm-session-flow-geometry-')
// `narrow`'s attach co-attaches to the already-live generation `wide` created, so it reaches
// the host as `attachExisting` rather than a second `attach` — and `attachExisting` deliberately
@@ -484,7 +484,8 @@ describe('SessionHostClient subscriber flow and reconnect barriers', () => {
const resizeRequests: Array<{ cols: number; rows: number }> = []
const normalizedFirst = deferred<void>()
const normalizedSecond = deferred<void>()
- const grownAfterDetach = deferred<void>()
+ const wideLatest = deferred<void>()
+ const fellBackAfterDetach = deferred<void>()
const server = net.createServer((socket) => {
trackSocket(socket)
@@ -516,9 +517,12 @@ describe('SessionHostClient subscriber flow and reconnect barriers', () => {
} else if (request.cmd === 'resize') {
resizeRequests.push({ cols: request.cols, rows: request.rows })
socket.write(encodeFrame({ id: request.id, ok: true }))
- if (request.cols === 80 && request.rows === 1) normalizedFirst.resolve()
- if (request.cols === 90 && request.rows === 1) normalizedSecond.resolve()
- if (request.cols === 90 && request.rows === 40) grownAfterDetach.resolve()
+ if (request.cols === 120 && request.rows === 1) normalizedFirst.resolve()
+ if (request.cols === 90 && request.rows === 40) {
+ if (resizeRequests.length === 2) normalizedSecond.resolve()
+ else fellBackAfterDetach.resolve()
+ }
+ if (request.cols === 100 && request.rows === 20) wideLatest.resolve()
} else if (request.cmd === 'detach' || request.cmd === 'write') {
socket.write(encodeFrame({ id: request.id, ok: true }))
}
@@ -542,21 +546,29 @@ describe('SessionHostClient subscriber flow and reconnect barriers', () => {
500
)
await within(narrow.ready, 'narrow geometry attach')
+ // The newly attached view is the most recently active one, so the session takes ITS size —
+ // not the componentwise minimum (80x30) it used to, which is what left a phone that dismissed
+ // its keyboard stuck at a shorter desktop view's rows.
expect(attachClaims).toEqual([
{ cmd: 'attach', cols: 120, rows: 30 },
- { cmd: 'attachExisting', cols: 80, rows: 30 }
+ { cmd: 'attachExisting', cols: 80, rows: 40 }
])
+ // A CHANGED claim makes that view the active one; each axis still normalizes independently.
wide.resize(Number.NaN, -5)
await within(normalizedFirst.promise, 'NaN and negative geometry normalization')
narrow.resize(90.9, Number.POSITIVE_INFINITY)
await within(normalizedSecond.promise, 'fractional and infinite geometry normalization')
+ wide.resize(100, 20)
+ await within(wideLatest.promise, 'the resized view becomes the active one')
+ // The active view leaves: the session falls back to the one that was active before it.
wide.destroy()
- await within(grownAfterDetach.promise, 'geometry growth after limiting view detach')
+ await within(fellBackAfterDetach.promise, 'fallback to the previous view after detach')
expect(resizeRequests).toEqual([
- { cols: 80, rows: 1 },
- { cols: 90, rows: 1 },
+ { cols: 120, rows: 1 },
+ { cols: 90, rows: 40 },
+ { cols: 100, rows: 20 },
{ cols: 90, rows: 40 }
])
})
diff --git a/src/core/session-host-client-geometry.test.ts b/src/core/session-host-client-geometry.test.ts
new file mode 100644
index 000000000..513cae2c8
--- /dev/null
+++ b/src/core/session-host-client-geometry.test.ts
@@ -0,0 +1,290 @@
+// Issue #914: a session-host session follows its most recently ACTIVE viewer (tmux's
+// `window-size latest`) instead of the smallest one, and every viewer is told the size the pty
+// really runs at. These drive the real client against a fake host over a real socket.
+import fs from 'fs'
+import net from 'net'
+import os from 'os'
+import path from 'path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { sessionHostPaths } from '../session-host/paths'
+import {
+ SESSION_HOST_PROTOCOL_VERSION,
+ LineFramer,
+ encodeFrame,
+ type SessionHostRequest,
+ type SessionHostSpawnOptions
+} from '../session-host/protocol'
+import { SessionHostClient } from './session-host-client'
+import { SessionHostPty } from './session-host-pty'
+
+const openServers = new Set<net.Server>()
+const openSockets = new Set<net.Socket>()
+const tempDirs = new Set<string>()
+const livePtys = new Set<SessionHostPty>()
+const GENERATION = 'geometry-generation'
+
+function within<T>(promise: Promise<T>, label: string, ms = 2_500): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(`${label} did not finish within ${ms}ms`)), ms)
+ promise.then(
+ (value) => {
+ clearTimeout(timer)
+ resolve(value)
+ },
+ (error) => {
+ clearTimeout(timer)
+ reject(error)
+ }
+ )
+ })
+}
+
+/** Resolves once `check` holds, polled on the event loop. */
+async function until(check: () => boolean, label: string): Promise<void> {
+ const deadline = Date.now() + 2_500
+ while (!check()) {
+ if (Date.now() > deadline) throw new Error(`${label} never happened`)
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ }
+}
+
+function fixture(prefix: string): { userDataDir: string; endpoint: string } {
+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
+ tempDirs.add(userDataDir)
+ const paths = sessionHostPaths(userDataDir)
+ fs.writeFileSync(paths.tokenPath, 'a'.repeat(64))
+ fs.writeFileSync(
+ paths.statePath,
+ JSON.stringify({
+ pid: process.pid,
+ endpoint: paths.endpoint,
+ tokenPath: paths.tokenPath,
+ startedAt: Date.now(),
+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION
+ })
+ )
+ return { userDataDir, endpoint: paths.endpoint }
+}
+
+function spawnOptions(userDataDir: string, cols: number, rows: number): SessionHostSpawnOptions {
+ return { cwd: userDataDir, shell: process.execPath, args: [], env: {}, cols, rows }
+}
+
+type FakeHost = {
+ requests: SessionHostRequest[]
+ resizes: Array<{ cols: number; rows: number }>
+ writes: string[]
+ /** Push a frame to every connection (the client under test has exactly one). */
+ push(frame: unknown): void
+}
+
+/**
+ * A host that answers the protocol. `geometry` makes it a host that negotiated the feature: it
+ * advertises it at hello, returns `hostSize` in attach replies, and pushes a `geometry` event
+ * for every resize it applies.
+ */
+async function fakeHost(
+ endpoint: string,
+ opts: { geometry?: boolean; hostSize?: { cols: number; rows: number } } = {}
+): Promise<FakeHost> {
+ const sockets = new Set<net.Socket>()
+ const host: FakeHost = {
+ requests: [],
+ resizes: [],
+ writes: [],
+ push: (frame) => {
+ for (const socket of sockets) socket.write(encodeFrame(frame))
+ }
+ }
+ const server = net.createServer((socket) => {
+ sockets.add(socket)
+ openSockets.add(socket)
+ socket.once('close', () => {
+ sockets.delete(socket)
+ openSockets.delete(socket)
+ })
+ const framer = new LineFramer()
+ socket.on('data', (chunk: Buffer) => {
+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {
+ host.requests.push(request)
+ const reply = (result?: unknown): void => {
+ socket.write(encodeFrame({ id: request.id, ok: true, result }))
+ }
+ switch (request.cmd) {
+ case 'hello':
+ reply({
+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION,
+ ...(opts.geometry ? { features: ['geometry'] } : {})
+ })
+ break
+ case 'attach':
+ case 'attachExisting': {
+ const own =
+ request.cmd === 'attach'
+ ? { cols: request.spawn.cols, rows: request.spawn.rows }
+ : { cols: request.cols ?? 80, rows: request.rows ?? 24 }
+ reply({
+ fresh: request.cmd === 'attach',
+ generation: GENERATION,
+ ...(opts.geometry ? { geometry: opts.hostSize ?? own } : {})
+ })
+ break
+ }
+ case 'resize':
+ host.resizes.push({ cols: request.cols, rows: request.rows })
+ if (opts.geometry) {
+ host.push({
+ type: 'geometry',
+ name: request.name,
+ cols: request.cols,
+ rows: request.rows,
+ generation: GENERATION
+ })
+ }
+ reply()
+ break
+ case 'write':
+ host.writes.push(request.data)
+ reply()
+ break
+ default:
+ reply()
+ }
+ }
+ })
+ })
+ openServers.add(server)
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(endpoint, resolve)
+ })
+ return host
+}
+
+type View = { pty: SessionHostPty; sizes: Array<{ cols: number; rows: number }>; exits: number[] }
+
+async function view(
+ client: SessionHostClient,
+ userDataDir: string,
+ cols: number,
+ rows: number
+): Promise<View> {
+ const pty = new SessionHostPty(client, 'nt-geometry', spawnOptions(userDataDir, cols, rows), 100)
+ livePtys.add(pty)
+ const sizes: View['sizes'] = []
+ const exits: number[] = []
+ pty.onSize((size) => sizes.push(size))
+ pty.onExit(({ exitCode }) => exits.push(exitCode))
+ await within(pty.ready, `attach ${cols}x${rows}`)
+ return { pty, sizes, exits }
+}
+
+function last<T>(items: T[]): T | undefined {
+ return items[items.length - 1]
+}
+
+afterEach(async () => {
+ for (const pty of livePtys) pty.destroy()
+ livePtys.clear()
+ await new Promise((resolve) => setImmediate(resolve))
+ for (const socket of openSockets) socket.destroy()
+ openSockets.clear()
+ await Promise.all(
+ [...openServers].map(
+ (server) =>
+ new Promise<void>((resolve) => {
+ if (!server.listening) return resolve()
+ server.close(() => resolve())
+ })
+ )
+ )
+ openServers.clear()
+ for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true })
+ tempDirs.clear()
+})
+
+describe('SessionHostClient geometry (issue #914)', () => {
+ it('asks the host for the geometry feature at hello', async () => {
+ const { userDataDir, endpoint } = fixture('nt-geo-hello-')
+ const host = await fakeHost(endpoint)
+ const client = new SessionHostClient({ userDataDir })
+ await view(client, userDataDir, 80, 24)
+ const hello = host.requests.find((request) => request.cmd === 'hello')
+ expect(hello).toMatchObject({ features: ['geometry'] })
+ })
+
+ it('gives the session to a view that types, but not to one that only answers a query', async () => {
+ const { userDataDir, endpoint } = fixture('nt-geo-typing-')
+ const host = await fakeHost(endpoint)
+ const client = new SessionHostClient({ userDataDir })
+ const desktop = await view(client, userDataDir, 120, 30)
+ // The phone attaches last, so it is the most recently active view: the session takes its size.
+ const phone = await view(client, userDataDir, 80, 40)
+ expect(host.requests.filter((r) => r.cmd === 'attachExisting')).toMatchObject([
+ { cols: 80, rows: 40 }
+ ])
+
+ // xterm answering a device-attributes query is not the user: no resize. A resize it caused
+ // would be queued right behind the write, so give it room to arrive before judging.
+ desktop.pty.write('\x1b[?1;2c')
+ await until(() => host.writes.length === 1, 'the report reaches the host')
+ await new Promise((resolve) => setTimeout(resolve, 50))
+ expect(host.resizes).toEqual([])
+ // A keystroke is: the desktop view becomes active and the session follows it.
+ desktop.pty.write('x')
+ await until(() => host.resizes.length > 0, 'resize after the keystroke')
+ expect(host.writes).toEqual(['\x1b[?1;2c', 'x'])
+ expect(host.resizes).toEqual([{ cols: 120, rows: 30 }])
+ // Both views are told the new size — the phone's is not its own any more.
+ await until(() => last(phone.sizes)?.cols === 120, 'phone told the new size')
+ expect(last(phone.sizes)).toEqual({ cols: 120, rows: 30 })
+ expect(last(desktop.sizes)).toEqual({ cols: 120, rows: 30 })
+ })
+
+ it('never grows the session past a view that cannot adapt to it', async () => {
+ const { userDataDir, endpoint } = fixture('nt-geo-bounding-')
+ const host = await fakeHost(endpoint)
+ const client = new SessionHostClient({ userDataDir })
+ const desktop = await view(client, userDataDir, 120, 30)
+ const phone = await view(client, userDataDir, 45, 40)
+ // Same size, now marked as a ceiling: nothing moves yet.
+ phone.pty.resize(45, 40, true)
+ desktop.pty.write('x')
+ await until(() => host.resizes.length > 0, 'resize after the keystroke')
+ // The desktop is active, but a 120-column pty would wrap into garbage on the phone.
+ expect(host.resizes).toEqual([{ cols: 45, rows: 30 }])
+ })
+
+ it('reports its own applied size to every view on a host without the feature', async () => {
+ const { userDataDir, endpoint } = fixture('nt-geo-legacy-')
+ await fakeHost(endpoint)
+ const client = new SessionHostClient({ userDataDir })
+ const first = await view(client, userDataDir, 120, 30)
+ await until(() => first.sizes.length > 0, 'first view told its size')
+ expect(last(first.sizes)).toEqual({ cols: 120, rows: 30 })
+ await view(client, userDataDir, 80, 40)
+ await until(() => last(first.sizes)?.cols === 80, 'first view told the new size')
+ expect(last(first.sizes)).toEqual({ cols: 80, rows: 40 })
+ })
+
+ it('renders what the host says, and never reads a geometry frame as an exit', async () => {
+ const { userDataDir, endpoint } = fixture('nt-geo-aware-')
+ // The host is already running smaller than our claim — another app's viewer is attached.
+ const host = await fakeHost(endpoint, { geometry: true, hostSize: { cols: 70, rows: 20 } })
+ const client = new SessionHostClient({ userDataDir })
+ const only = await view(client, userDataDir, 120, 30)
+ await until(() => only.sizes.length > 0, 'told the host size')
+ expect(last(only.sizes)).toEqual({ cols: 70, rows: 20 })
+
+ host.push({ type: 'geometry', name: 'nt-geometry', cols: 50, rows: 15, generation: GENERATION })
+ await until(() => last(only.sizes)?.cols === 50, 'told the pushed size')
+ expect(last(only.sizes)).toEqual({ cols: 50, rows: 15 })
+ // A frame from another generation, or with a nonsense grid, changes nothing.
+ host.push({ type: 'geometry', name: 'nt-geometry', cols: 9, rows: 9, generation: 'other-generation' })
+ host.push({ type: 'geometry', name: 'nt-geometry', cols: -1, rows: 0, generation: GENERATION })
+ only.pty.write('y')
+ await until(() => host.writes.includes('y'), 'a later request round-trips')
+ expect(last(only.sizes)).toEqual({ cols: 50, rows: 15 })
+ expect(only.exits).toEqual([])
+ })
+})
diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.ts
index a9ea49aee..6aeb2d7fd 100644
--- a/src/core/session-host-client.ts
+++ b/src/core/session-host-client.ts
@@ -19,6 +19,7 @@ import {
} from '../session-host/existing-host-state'
import {
SESSION_HOST_PROTOCOL_VERSION,
+ SESSION_HOST_FEATURES,
LineFramer,
encodeFrame,
type SessionHostRequest,
@@ -26,6 +27,7 @@ import {
type SessionHostFrame,
type SessionHostSpawnOptions,
type AttachResult,
+ type HelloResult,
type HasSessionResult,
type PaneCommandResult,
type CaptureResult,
@@ -34,11 +36,18 @@ import {
type ListSessionsResult
} from '../session-host/protocol'
import { resolveSessionHostScript, spawnSessionHost } from './session-host-launcher'
+import { latestClaimSize, type SizeClaim } from './pty-size'
+import { isTerminalReport } from './terminal-reports'
import type { PreparedAgentLaunch } from './agent-launch'
export interface SessionSubscriber {
onData(data: string): void
onExit(exitCode: number): void
+ /** The size the shared pty actually runs at, which may not be this subscriber's own claim: the
+ * session follows its most recently active viewer (issue #914). Called whenever that may have
+ * changed for this subscriber — including after its own resize, even when the answer is the
+ * same, because its renderer has just fitted itself to its own size. Deduplicate downstream. */
+ onSize?(size: { cols: number; rows: number }): void
/** A previously confirmed attachment failed to restore. This is not an exit: the host's
* rejection is retained so the owning manager can retire only the affected generation. */
onAttachError?(error: Error): void
@@ -97,7 +106,12 @@ type ClientSessionState = {
protocolVersion?: 1 | 2
entries: Map<SessionSubscriber, SubscriberEntry>
pauseOwners: Set<SessionSubscriber>
- sizeClaims: Map<SessionSubscriber, TerminalSize>
+ /** Each subscriber's vote, with when it was last active and whether it can adapt to a grid
+ * that is not its own (see `latestClaimSize`). */
+ sizeClaims: Map<SessionSubscriber, SizeClaim>
+ /** What the HOST last said the pty runs at, on a connection that negotiated `geometry`. Null
+ * until it has answered; never consulted on a connection that did not negotiate it. */
+ hostGeometry: TerminalSize | null
bufferedData: BufferedFrame[]
/** Attaches that have actually reached their request phase. Only these may own data arriving
* before the correlated attach response; a merely queued replacement must not absorb bytes
@@ -227,6 +241,12 @@ function normalizeDimension(value: number, fallback: number): number {
export class SessionHostClient {
private socket: net.Socket | null = null
private negotiatedProtocolVersion: 1 | 2 | null = null
+ /** The current connection negotiated the `geometry` feature, so the host pushes the pty's real
+ * size. On a host that predates it, the size this client last requested IS the pty's size as
+ * long as this is the host's only connection — the common case, and the one issue #914 is. */
+ private hostGeometryEvents = false
+ /** Monotonic activity clock for `SizeClaim.recency`. */
+ private claimClock = 0
private nextId = 1
private readonly pending = new Map<number, PendingEntry>()
private readonly sessions = new Map<string, ClientSessionState>()
@@ -270,6 +290,7 @@ export class SessionHostClient {
entries: new Map(),
pauseOwners: new Set(),
sizeClaims: new Map(),
+ hostGeometry: null,
bufferedData: [],
preAckEntries: new Set(),
preAckExit: false,
@@ -313,21 +334,48 @@ export class SessionHostClient {
return false
}
+ /** The size this client asks the host for: its most recently active subscriber's, clamped to any
+ * subscriber that cannot adapt (issue #914 — see `latestClaimSize`). */
private effectiveSize(state: ClientSessionState): TerminalSize {
- let cols = Number.POSITIVE_INFINITY
- let rows = Number.POSITIVE_INFINITY
- for (const claim of state.sizeClaims.values()) {
- cols = Math.min(cols, claim.cols)
- rows = Math.min(rows, claim.rows)
- }
// Every entry receives a claim before it enters the map. This fallback only protects a
// teardown race from ever putting non-finite geometry on the wire.
- return {
- cols: Number.isFinite(cols) ? cols : 80,
- rows: Number.isFinite(rows) ? rows : 24
+ return latestClaimSize(state.sizeClaims.values()) ?? { cols: 80, rows: 24 }
+ }
+
+ /** Mark `sub` as the most recently active viewer and re-negotiate if that moves the size. */
+ private touchClaim(state: ClientSessionState, sub: SessionSubscriber): void {
+ const claim = state.sizeClaims.get(sub)
+ if (!claim) return
+ const before = this.effectiveSize(state)
+ claim.recency = ++this.claimClock
+ if (!sameSize(before, this.effectiveSize(state))) this.queueReconcile(state)
+ }
+
+ /** Tell every attached subscriber the size the pty runs at. On a geometry-aware connection that
+ * is the host's own answer; otherwise it is what this client last applied. */
+ private notifySize(state: ClientSessionState): void {
+ const size = this.hostGeometryEvents ? state.hostGeometry : state.appliedSize
+ if (!size) return
+ for (const entry of state.entries.values()) {
+ if (entry.phase !== 'attached') continue
+ try {
+ entry.sub.onSize?.({ cols: size.cols, rows: size.rows })
+ } catch {
+ // One subscriber must not stop its co-attached neighbours from learning the size.
+ }
}
}
+ /** Record a host-reported size, ignoring anything that is not a positive integer grid. */
+ private recordHostGeometry(state: ClientSessionState, geometry: unknown): boolean {
+ if (!this.hostGeometryEvents || !geometry || typeof geometry !== 'object') return false
+ const { cols, rows } = geometry as { cols?: unknown; rows?: unknown }
+ if (!Number.isInteger(cols) || !Number.isInteger(rows)) return false
+ if ((cols as number) <= 0 || (rows as number) <= 0) return false
+ state.hostGeometry = { cols: cols as number, rows: rows as number }
+ return true
+ }
+
private async ensureConnected(): Promise<void> {
// A newly authenticated socket is visible while its reconnect restoration is still running.
// The barrier wins over the raw socket check so no later request can overtake replay.
@@ -461,6 +509,7 @@ export class SessionHostClient {
const framer = new LineFramer()
const helloId = this.nextId++
let protocolVersion: 1 | 2 | null = null
+ let geometryEvents = false
const finish = (ok: boolean, trailing: SessionHostFrame[] = []): void => {
if (settled) return
settled = true
@@ -474,7 +523,7 @@ export class SessionHostClient {
failHandshake(new Error('session-host hello did not negotiate a protocol version'))
return
}
- this.attachSocket(socket, protocolVersion)
+ this.attachSocket(socket, protocolVersion, geometryEvents)
for (const frame of trailing) this.handleFrame(socket, frame)
} else {
try {
@@ -516,7 +565,8 @@ export class SessionHostClient {
id: helloId,
cmd: 'hello',
token,
- protocolVersion: SESSION_HOST_PROTOCOL_VERSION
+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION,
+ features: [...SESSION_HOST_FEATURES]
}),
(error) => {
if (error) failHandshake(asError(error))
@@ -567,6 +617,8 @@ export class SessionHostClient {
return
}
protocolVersion = negotiated
+ const features = (frame.result as HelloResult | undefined)?.features
+ geometryEvents = Array.isArray(features) && features.includes('geometry')
finish(true, frames.slice(index + 1))
} else {
failHandshake(new Error(`session-host hello rejected: ${frame.error}`))
@@ -586,9 +638,10 @@ export class SessionHostClient {
})
}
- private attachSocket(socket: net.Socket, protocolVersion: 1 | 2): void {
+ private attachSocket(socket: net.Socket, protocolVersion: 1 | 2, geometryEvents: boolean): void {
this.socket = socket
this.negotiatedProtocolVersion = protocolVersion
+ this.hostGeometryEvents = geometryEvents
this.everConnected = true
const framer = new LineFramer()
socket.on('data', (chunk: Buffer) => {
@@ -616,7 +669,10 @@ export class SessionHostClient {
if (wasCurrent) {
this.socket = null
this.negotiatedProtocolVersion = null
+ this.hostGeometryEvents = false
for (const state of this.sessions.values()) {
+ // The next connection re-learns the size from its own attach replies.
+ state.hostGeometry = null
if (state.appliedSocket !== socket) continue
state.appliedSocket = null
state.appliedAttached = false
@@ -691,6 +747,8 @@ export class SessionHostClient {
}
if (frame.type === 'data') {
this.deliverData(state, frame.data)
+ } else if (frame.type === 'geometry') {
+ if (this.recordHostGeometry(state, frame)) this.notifySize(state)
} else {
this.handleExit(state, frame.exitCode)
}
@@ -949,6 +1007,7 @@ export class SessionHostClient {
state.protocolVersion = protocolVersion
state.generation = result.generation ?? expectedGeneration
if (state.generation) this.sessionGenerations.set(state.name, state.generation)
+ this.recordHostGeometry(state, result.geometry)
this.applyAttachment(state, replaySocket, paused, size)
if (result.screen && state.appliedSocket === replaySocket) {
this.deliverData(state, RECONNECT_REPAINT_PREFIX + result.screen)
@@ -1058,6 +1117,7 @@ export class SessionHostClient {
state.releasePending = false
this.flushData(state)
}
+ this.notifySize(state)
}
private async reconcileState(state: ClientSessionState): Promise<void> {
@@ -1153,7 +1213,8 @@ export class SessionHostClient {
phase: 'attaching'
}
state.entries.set(sub, entry)
- state.sizeClaims.set(sub, initialSize)
+ // A new viewer is the most recently active one, exactly as a freshly attached tmux client is.
+ state.sizeClaims.set(sub, { ...initialSize, recency: ++this.claimClock })
return this.enqueueState(state, async () => {
if (this.sessions.get(name) !== state || state.entries.get(sub) !== entry) {
@@ -1248,6 +1309,7 @@ export class SessionHostClient {
state.protocolVersion = protocolVersion
state.generation = result.generation ?? expectedGeneration
if (state.generation) this.sessionGenerations.set(name, state.generation)
+ this.recordHostGeometry(state, result.geometry)
if (replacementToken && result.fresh) {
if (this.replacementTokens.get(name) === replacementToken) {
this.replacementTokens.delete(name)
@@ -1376,6 +1438,10 @@ export class SessionHostClient {
const state = this.sessions.get(name)
const entry = state?.entries.get(sub)
if (!state || !entry) return
+ // Typing makes a viewer the active one, as it does a tmux client. An emulator's automatic
+ // answer to a query does not: every attached xterm answers, and counting those would hand the
+ // session to whichever viewer answered last.
+ if (!isTerminalReport(data)) this.touchClaim(state, sub)
void this.enqueueState(state, async () => {
if (this.sessions.get(name) !== state || state.entries.get(sub) !== entry) return
try {
@@ -1387,14 +1453,34 @@ export class SessionHostClient {
})
}
- resize(name: string, sub: SessionSubscriber, cols: number, rows: number): void {
+ /**
+ * Update `sub`'s claim. A claim that actually CHANGES makes `sub` the most recently active viewer
+ * (a phone dismissing its keyboard is the case issue #914 is about); re-reporting the same size
+ * does not, or every re-fit would steal the session. `bounding` marks a viewer that cannot adapt
+ * to any grid but its own, which caps the size for everyone (see `latestClaimSize`).
+ */
+ resize(
+ name: string,
+ sub: SessionSubscriber,
+ cols: number,
+ rows: number,
+ bounding = false
+ ): void {
const state = this.sessions.get(name)
if (!state || !state.entries.has(sub)) return
- const previous = state.sizeClaims.get(sub) ?? { cols: 80, rows: 24 }
- state.sizeClaims.set(sub, {
+ const previous = state.sizeClaims.get(sub) ?? { cols: 80, rows: 24, recency: 0 }
+ const next: SizeClaim = {
cols: normalizeDimension(cols, previous.cols),
- rows: normalizeDimension(rows, previous.rows)
- })
+ rows: normalizeDimension(rows, previous.rows),
+ recency: previous.recency,
+ bounding
+ }
+ if (next.cols !== previous.cols || next.rows !== previous.rows) {
+ next.recency = ++this.claimClock
+ }
+ state.sizeClaims.set(sub, next)
+ // Always reconcile, even for an unchanged claim: it ends in `notifySize`, which is how a view
+ // that just fitted itself to its own size learns the pty is running at someone else's.
this.queueReconcile(state)
}
diff --git a/src/core/session-host-pty.ts b/src/core/session-host-pty.ts
index 5a5bf3910..92b089bdc 100644
--- a/src/core/session-host-pty.ts
+++ b/src/core/session-host-pty.ts
@@ -15,6 +15,7 @@ export class SessionHostPty {
private readonly dataCbs: Array<(data: string) => void> = []
private readonly exitCbs: Array<(e: { exitCode: number }) => void> = []
private readonly attachErrorCbs: Array<(error: Error) => void> = []
+ private readonly sizeCbs: Array<(size: { cols: number; rows: number }) => void> = []
private attachError: Error | null = null
private detached = false
@@ -42,6 +43,9 @@ export class SessionHostPty {
onExit: (exitCode) => {
for (const cb of this.exitCbs) cb({ exitCode })
},
+ onSize: (size) => {
+ for (const cb of this.sizeCbs) cb(size)
+ },
onAttachError: (error) => {
this.attachError = error
for (const cb of this.attachErrorCbs) cb(error)
@@ -65,6 +69,13 @@ export class SessionHostPty {
this.exitCbs.push(cb)
}
+ /** The size the shared pty actually runs at (issue #914). Not part of node-pty's `IPty`: a real
+ * pty is exactly the size it was last given, while this one follows whichever viewer of the
+ * session was most recently active, which may be a different process entirely. */
+ onSize(cb: (size: { cols: number; rows: number }) => void): void {
+ this.sizeCbs.push(cb)
+ }
+
/** Reconnect replay failed for a previously-confirmed generation. Late registration receives
* the stored error immediately so manager wiring cannot miss a fast rejection. */
onAttachError(cb: (error: Error) => void): void {
@@ -76,8 +87,10 @@ export class SessionHostPty {
this.client.write(this.name, this.sub, data)
}
- resize(cols: number, rows: number): void {
- this.client.resize(this.name, this.sub, cols, rows)
+ /** `bounding`: this pty's viewers cannot adapt to a grid other than their own, so the shared
+ * session must never grow past this claim (see `latestClaimSize`). */
+ resize(cols: number, rows: number, bounding = false): void {
+ this.client.resize(this.name, this.sub, cols, rows, bounding)
}
pause(): void {
diff --git a/src/core/terminal-reports.test.ts b/src/core/terminal-reports.test.ts
new file mode 100644
index 000000000..02a3d3c5d
--- /dev/null
+++ b/src/core/terminal-reports.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest'
+import { isTerminalReport } from './terminal-reports'
+
+describe('isTerminalReport', () => {
+ it.each([
+ ['primary DA', '\x1b[?1;2c'],
+ ['secondary DA', '\x1b[>0;276;0c'],
+ ['cursor position', '\x1b[24;80R'],
+ ['device status', '\x1b[0n'],
+ ['mode report', '\x1b[?2004;1$y'],
+ ['focus in', '\x1b[I'],
+ ['focus out', '\x1b[O'],
+ ['cell size', '\x1b[6;17;8t'],
+ ['kitty flags', '\x1b[?0u'],
+ ['OSC colour (BEL)', '\x1b]11;rgb:0000/0000/0000\x07'],
+ ['OSC colour (ST)', '\x1b]10;rgb:ffff/ffff/ffff\x1b\\'],
+ ['DCS reply', '\x1bP1$r0m\x1b\\'],
+ ['several replies in one write', '\x1b[?1;2c\x1b[24;80R\x1b]11;rgb:0/0/0\x07']
+ ])('%s is a report', (_label, data) => {
+ expect(isTerminalReport(data)).toBe(true)
+ })
+
+ it.each([
+ ['a letter', 'a'],
+ ['enter', '\r'],
+ ['ctrl-c', '\x03'],
+ ['arrow key', '\x1b[A'],
+ ['application-mode arrow', '\x1bOA'],
+ ['kitty key event', '\x1b[97;5u'],
+ ['SGR mouse press', '\x1b[<0;10;5M'],
+ ['bracketed paste', '\x1b[200~hello\x1b[201~'],
+ ['report followed by a keystroke', '\x1b[?1;2cx'],
+ ['empty write', '']
+ ])('%s is activity (or nothing)', (_label, data) => {
+ expect(isTerminalReport(data)).toBe(false)
+ })
+})
diff --git a/src/core/terminal-reports.ts b/src/core/terminal-reports.ts
new file mode 100644
index 000000000..d8ba42d5b
--- /dev/null
+++ b/src/core/terminal-reports.ts
@@ -0,0 +1,46 @@
+/**
+ * Is this pty write an automatic TERMINAL REPORT rather than something a person did?
+ *
+ * The session-host backend sizes a shared session to its most recently ACTIVE viewer (tmux's
+ * `window-size latest`, see `latestClaimSize` in pty-size.ts), and typing is one of the things that
+ * makes a viewer active. But xterm.js also writes to the pty on its own: when the app in the pane
+ * asks a question (device attributes, cursor position, a colour, a mode), EVERY attached emulator
+ * answers it. Counting those answers as activity would hand the session to whichever viewer happened
+ * to answer last — and an app that re-queries after SIGWINCH could then flip the size back and forth
+ * between viewers forever. tmux never has this problem because tmux itself answers those queries,
+ * not its clients.
+ *
+ * The match is on the WHOLE write: a chunk that is nothing but reports is a report; anything else
+ * (a keystroke, a paste, a mouse event) is activity. Deliberately conservative in one direction
+ * only: an ambiguous sequence that looks like a report (CSI 1;2R is both a cursor-position report
+ * and Shift+F3 on some keyboards) is treated as a report, because missing one activity bump costs
+ * nothing — the next keystroke bumps — while a false bump can move the whole session's size.
+ */
+const REPORT = new RegExp(
+ '^(?:' +
+ [
+ // Device attributes (primary / secondary / tertiary): CSI ? … c, CSI > … c, CSI = … c
+ '\\x1b\\[[?>=][0-9;]*c',
+ // Cursor position (CPR / DECXCPR): CSI r ; c R, CSI ? r ; c R
+ '\\x1b\\[\\??[0-9]+;[0-9]+(?:;[0-9]+)?R',
+ // Device status: CSI n n (e.g. CSI 0 n)
+ '\\x1b\\[\\??[0-9]+n',
+ // Mode reports (DECRPM): CSI [?] Pa ; Ps $ y
+ '\\x1b\\[\\??[0-9;]*\\$y',
+ // Focus in / out
+ '\\x1b\\[[IO]',
+ // Window / cell size reports: CSI 4|6|8 ; h ; w t
+ '\\x1b\\[[0-9]+;[0-9]+;[0-9]+t',
+ // Kitty keyboard flags report: CSI ? flags u (a key event has no `?`)
+ '\\x1b\\[\\?[0-9]*u',
+ // OSC replies (colour queries etc.), BEL- or ST-terminated
+ '\\x1b\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)',
+ // DCS replies (DECRQSS, XTGETTCAP), ST-terminated
+ '\\x1bP[^\\x1b]*\\x1b\\\\'
+ ].join('|') +
+ ')+$'
+)
+
+export function isTerminalReport(data: string): boolean {
+ return data.length > 0 && REPORT.test(data)
+}
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 7e1d60cca..ab2adf9f1 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -286,8 +286,23 @@ export function createHostHandlers(
// Build the output/exit sinks for a new stream: pipe PTY output into OP.Output frames (with
// relay backpressure -> setFlow pause/resume) and PTY exit into an OP.Error frame.
- function makeSinks(streamId: number, stream: Stream): DetachedSinks {
+ //
+ // `resizedFrames` is the client saying it renders `OP.Resized` — the size the shared pty really
+ // runs at, same payload layout as `OP.Resize` (2x uint16 LE cols, rows). Only a session-host
+ // session ever sends one (issue #914: it follows its most recently active viewer, which may be a
+ // desktop node). The frame is sent either way — a client that does not know it drops it — but
+ // a client that did NOT opt in is treated as unable to adapt, so the session never grows past
+ // its screen: output wider than the phone would wrap into garbage there rather than clip.
+ function makeSinks(streamId: number, stream: Stream, resizedFrames: boolean): DetachedSinks {
return {
+ adaptsToSize: resizedFrames,
+ onSize: (size) => {
+ const payload = new Uint8Array(4)
+ const view = new DataView(payload.buffer)
+ view.setUint16(0, Math.min(0xffff, Math.max(1, size.cols)), true)
+ view.setUint16(2, Math.min(0xffff, Math.max(1, size.rows)), true)
+ socket.sendFrame(OP.Resized, streamId, stream.seq++, payload)
+ },
onData: (data) => {
const bytes = textEncoder.encode(data)
const ok = socket.sendFrame(OP.Output, streamId, stream.seq++, bytes)
@@ -352,7 +367,7 @@ export function createHostHandlers(
const streamId = ++streamCounter
const stream: Stream = { sessionId: '', persistKey: nodeId, seq: 0, paused: false }
- const sinks = makeSinks(streamId, stream)
+ const sinks = makeSinks(streamId, stream, p.resizedFrames === true)
// Reserve the stream, then respond so the client can route Input/Resize frames; the snapshot
// + live attach then proceed. Capturing the screen is async (a tmux side-call).
diff --git a/src/main/remote/remote-security.test.ts b/src/main/remote/remote-security.test.ts
index 436e7e8e9..9176f113f 100644
--- a/src/main/remote/remote-security.test.ts
+++ b/src/main/remote/remote-security.test.ts
@@ -266,6 +266,44 @@ describe('pty.attach reports whether it had to CREATE the session', () => {
})
})
+// Issue #914: a session-host session follows its most recently active viewer, so the pty can run
+// at a size the phone did not ask for. The relay tells it with `OP.Resized` (same payload as
+// `OP.Resize`), and a phone that did not say it renders that frame is a ceiling for the session.
+describe('pty.attach forwards the real pty size as OP.Resized', () => {
+ function attachWith(params: Record<string, unknown>) {
+ const fakes = makeHostFakes()
+ const frames: Array<{ op: number; streamId: number; payload: Uint8Array }> = []
+ fakes.socket.sendFrame = (op, streamId, _seq, payload) => {
+ frames.push({ op, streamId, payload })
+ return true
+ }
+ const handlers = createHostHandlers(fakes.pty, fakes.socket, fakes.fs, () => ['/work'])
+ handlers.onRpc({ id: 'a', method: 'pty.attach', params: { nodeId: 'node-a', cols: 80, rows: 24, ...params } })
+ return { ...fakes, frames }
+ }
+ const sinksOf = async (pty: HostPtyManager) => {
+ await vi.waitFor(() => expect(pty.attachDetached).toHaveBeenCalled())
+ return (pty.attachDetached as ReturnType<typeof vi.fn>).mock.calls[0][1] as import('../../core/pty-manager').DetachedSinks
+ }
+
+ it('encodes the size as two little-endian uint16s on the stream', async () => {
+ const { pty, frames } = attachWith({})
+ const sinks = await sinksOf(pty)
+ sinks.onSize?.({ cols: 132, rows: 43 })
+ const resized = frames.filter((frame) => frame.op === OP.Resized)
+ expect(resized).toHaveLength(1)
+ expect(resized[0].streamId).toBe(1)
+ const view = new DataView(resized[0].payload.buffer)
+ expect([view.getUint16(0, true), view.getUint16(2, true)]).toEqual([132, 43])
+ })
+
+ it('treats a phone as able to adapt only when it says so', async () => {
+ expect((await sinksOf(attachWith({}).pty)).adaptsToSize).toBe(false)
+ expect((await sinksOf(attachWith({ resizedFrames: 'yes' }).pty)).adaptsToSize).toBe(false)
+ expect((await sinksOf(attachWith({ resizedFrames: true }).pty)).adaptsToSize).toBe(true)
+ })
+})
+
// Scrolling belongs to tmux (mouse on, alternate screen), and the phone cannot deliver the wheel
// itself — its emulator swallows the gesture — so it asks the host to write it into the stream's
// pty, which IS a tmux client. `lines` and the stream target both come off the wire.
diff --git a/src/session-host/geometry-host.test.ts b/src/session-host/geometry-host.test.ts
new file mode 100644
index 000000000..2ea801403
--- /dev/null
+++ b/src/session-host/geometry-host.test.ts
@@ -0,0 +1,225 @@
+// Issue #914 wiring test: drives the REAL bundled host over its real socket protocol. The rule it
+// exists for is the one a unit test of `session.ts` cannot see — a `geometry` push reaches ONLY a
+// connection that negotiated the feature at hello. An older client treats every push frame that is
+// not `data` as an EXIT, so leaking one to it would retire a live session on the first resize.
+import { afterEach, describe, expect, it } from 'vitest'
+import { spawn, type ChildProcess } from 'child_process'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'fs'
+import net, { type Socket } from 'net'
+import os from 'os'
+import path from 'path'
+import { build, type Plugin } from 'esbuild'
+import {
+ LineFramer,
+ SESSION_HOST_PROTOCOL_VERSION,
+ encodeFrame,
+ type SessionHostEvent,
+ type SessionHostFrame,
+ type SessionHostResponse,
+ type SessionHostSpawnOptions
+} from './protocol'
+import { sessionHostPaths, type SessionHostState } from './paths'
+
+function fakePtyPlugin(): Plugin {
+ return {
+ name: 'session-host-geometry-fake-pty',
+ setup(bundle) {
+ bundle.onResolve({ filter: /^node-pty$/ }, () => ({ path: 'node-pty', namespace: 'geo' }))
+ bundle.onLoad({ filter: /^node-pty$/, namespace: 'geo' }, () => ({
+ loader: 'js',
+ contents: `
+ export function spawn() {
+ let onExit
+ return {
+ pid: 4343,
+ onData() {},
+ onExit(cb) { onExit = cb },
+ write() {},
+ resize() {},
+ pause() {},
+ resume() {},
+ kill() { setTimeout(() => onExit?.({ exitCode: 0 }), 20) }
+ }
+ }
+ `
+ }))
+ }
+ }
+}
+
+async function waitForIdentity(dataDir: string): Promise<{ state: SessionHostState; token: string }> {
+ const paths = sessionHostPaths(dataDir)
+ for (let attempt = 0; attempt < 200; attempt++) {
+ try {
+ const state = JSON.parse(readFileSync(paths.statePath, 'utf8')) as SessionHostState
+ const token = readFileSync(paths.tokenPath, 'utf8').trim()
+ if (state.endpoint && token) return { state, token }
+ } catch {
+ /* publication is asynchronous by design; keep polling within the test bound */
+ }
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ }
+ throw new Error('session host did not publish its identity')
+}
+
+type Connection = {
+ socket: Socket
+ events: SessionHostEvent[]
+ request(frame: Record<string, unknown> & { id: number }): Promise<SessionHostResponse>
+}
+
+function connect(endpoint: string): Promise<Connection> {
+ return new Promise((resolve, reject) => {
+ const socket = net.connect(endpoint)
+ const framer = new LineFramer()
+ const events: SessionHostEvent[] = []
+ const waiters = new Map<number, (frame: SessionHostResponse) => void>()
+ socket.on('data', (chunk: Buffer) => {
+ for (const frame of framer.push<SessionHostFrame>(chunk.toString('utf8'))) {
+ if ('type' in frame) {
+ events.push(frame)
+ continue
+ }
+ waiters.get(frame.id)?.(frame)
+ waiters.delete(frame.id)
+ }
+ })
+ socket.once('error', reject)
+ socket.once('connect', () =>
+ resolve({
+ socket,
+ events,
+ request: (frame) =>
+ new Promise<SessionHostResponse>((done, fail) => {
+ const timer = setTimeout(() => fail(new Error(`timed out on ${frame.id}`)), 4_000)
+ waiters.set(frame.id, (response) => {
+ clearTimeout(timer)
+ done(response)
+ })
+ socket.write(encodeFrame(frame))
+ })
+ })
+ )
+ })
+}
+
+function waitForExit(child: ChildProcess): Promise<void> {
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()
+ return new Promise((resolve) => child.once('exit', () => resolve()))
+}
+
+const SPAWN: SessionHostSpawnOptions = {
+ cwd: '.',
+ shell: 'fake-shell',
+ args: [],
+ env: {},
+ cols: 80,
+ rows: 24
+}
+
+const cleanupPaths: string[] = []
+afterEach(() => {
+ for (const target of cleanupPaths.splice(0)) {
+ rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })
+ }
+})
+
+function geometryEvents(events: SessionHostEvent[]): Array<{ cols: number; rows: number }> {
+ return events.flatMap((event) =>
+ event.type === 'geometry' ? [{ cols: event.cols, rows: event.rows }] : []
+ )
+}
+
+describe('session-host geometry feature (issue #914)', () => {
+ it('pushes geometry only to the connection that negotiated it', async () => {
+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-geometry-'))
+ cleanupPaths.push(fixtureDir)
+ const dataDir = path.join(fixtureDir, 'user-data')
+ mkdirSync(dataDir)
+ const paths = sessionHostPaths(dataDir)
+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)
+ const bundlePath = path.join(fixtureDir, 'host.cjs')
+ await build({
+ absWorkingDir: process.cwd(),
+ entryPoints: ['src/session-host/host.ts'],
+ outfile: bundlePath,
+ bundle: true,
+ platform: 'node',
+ format: 'cjs',
+ plugins: [fakePtyPlugin()],
+ logLevel: 'silent'
+ })
+ const child = spawn(process.execPath, [bundlePath, dataDir], {
+ cwd: process.cwd(),
+ stdio: 'ignore',
+ windowsHide: true
+ })
+ const sockets: Socket[] = []
+ try {
+ const { state, token } = await waitForIdentity(dataDir)
+ const aware = await connect(state.endpoint)
+ const legacy = await connect(state.endpoint)
+ sockets.push(aware.socket, legacy.socket)
+
+ const awareHello = await aware.request({
+ id: 1,
+ cmd: 'hello',
+ token,
+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION,
+ features: ['geometry', 'not-a-feature']
+ })
+ expect(awareHello).toMatchObject({
+ ok: true,
+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION, features: ['geometry'] }
+ })
+ const legacyHello = await legacy.request({
+ id: 1,
+ cmd: 'hello',
+ token,
+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION
+ })
+ expect(legacyHello).toEqual({
+ id: 1,
+ ok: true,
+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }
+ })
+
+ const created = await aware.request({
+ id: 2,
+ cmd: 'attach',
+ name: 'geo',
+ spawn: SPAWN,
+ scrollback: 100
+ })
+ expect(created).toMatchObject({ ok: true, result: { geometry: { cols: 80, rows: 24 } } })
+
+ // The legacy connection joins with a smaller claim, which shrinks the pty (the host still
+ // takes the minimum across connections). Its own reply carries no geometry field…
+ const joined = await legacy.request({
+ id: 2,
+ cmd: 'attachExisting',
+ name: 'geo',
+ cols: 60,
+ rows: 20
+ })
+ expect(joined.ok).toBe(true)
+ expect((joined as { result?: Record<string, unknown> }).result).not.toHaveProperty('geometry')
+
+ // …while the aware subscriber is told what the pty now runs at.
+ const shrunk = await aware.request({ id: 3, cmd: 'resize', name: 'geo', cols: 50, rows: 10 })
+ expect(shrunk.ok).toBe(true)
+ await expect(legacy.request({ id: 3, cmd: 'ping' })).resolves.toMatchObject({ ok: true })
+ expect(geometryEvents(aware.events)).toEqual([
+ { cols: 60, rows: 20 },
+ { cols: 50, rows: 10 }
+ ])
+ // The pty resized twice while the legacy connection was a subscriber for the second one.
+ // It must have been sent nothing but data: to that client a geometry frame reads as EXIT.
+ expect(legacy.events.filter((event) => event.type !== 'data')).toEqual([])
+ } finally {
+ for (const socket of sockets) socket.destroy()
+ child.kill()
+ await waitForExit(child)
+ }
+ }, 30_000)
+})
diff --git a/src/session-host/host.ts b/src/session-host/host.ts
index 9e9e8678a..755a8e133 100644
--- a/src/session-host/host.ts
+++ b/src/session-host/host.ts
@@ -24,6 +24,8 @@ import {
type SessionHostRequest,
type SessionHostFrame,
type AttachResult,
+ type HelloResult,
+ SESSION_HOST_FEATURES,
type HasSessionResult,
type PaneCommandResult,
type CaptureResult,
@@ -327,6 +329,47 @@ async function main(): Promise<void> {
}
const generationCoordinator = new SessionGenerationCoordinator(sessions, cancelGraceExit)
+ /** Connections that negotiated the `geometry` feature at hello. Only these may ever receive a
+ * `geometry` push: an older client reads any non-`data` push frame as an exit (issue #914). */
+ const geometrySockets = new WeakSet<net.Socket>()
+
+ /** Tell every geometry-aware subscriber the size the pty now actually runs at. */
+ function publishGeometry(session: HostSession, geometry: { cols: number; rows: number }): void {
+ const line = encodeFrame({
+ type: 'geometry',
+ name: session.name,
+ cols: geometry.cols,
+ rows: geometry.rows,
+ generation: session.generation
+ } satisfies SessionHostFrame)
+ for (const sub of session.subscribers) {
+ if (geometrySockets.has(sub)) writeSessionHostFrame(sub, line, sessions.values())
+ }
+ }
+
+ /** The attach reply, plus the pty's current size for a geometry-aware connection — the answer
+ * that `geometry` pushes then keep current. */
+ function withGeometry(name: string, socket: net.Socket, result: AttachResult): AttachResult {
+ if (!geometrySockets.has(socket)) return result
+ const session = sessions.get(name)
+ if (!session || session.exited) return result
+ return { ...result, geometry: session.geometry }
+ }
+
+ /** A v2 hello's reply. Features are the intersection of what the client asked for and what this
+ * host speaks; a client that asked for nothing gets nothing and is never sent a frame it did not
+ * opt into. Only a v2 connection reaches here — a v1 hello's reply carries no result at all. */
+ function negotiateHello(req: SessionHostRequest, socket: net.Socket): HelloResult {
+ const requested = (req as { features?: unknown }).features
+ const features = Array.isArray(requested)
+ ? SESSION_HOST_FEATURES.filter((feature) => requested.includes(feature))
+ : []
+ if (features.includes('geometry')) geometrySockets.add(socket)
+ return features.length > 0
+ ? { protocolVersion: currentProtocolVersion(), features }
+ : { protocolVersion: currentProtocolVersion() }
+ }
+
function broadcast(session: HostSession, frame: SessionHostFrame): void {
const line = encodeFrame(frame)
for (const sub of session.subscribers) {
@@ -402,6 +445,7 @@ async function main(): Promise<void> {
}
function wireSession(session: HostSession): void {
+ session.onGeometryApplied = (geometry) => publishGeometry(session, geometry)
session.proc.onData((data) => {
// node-pty may flush a queued data callback after its exit callback. Once endSession has
// disposed the emulator and broadcast exit, no data may touch or appear after that boundary.
@@ -772,12 +816,15 @@ async function main(): Promise<void> {
): Promise<{ ok: true; result?: unknown } | { ok: false; error: string }> {
switch (req.cmd) {
case 'attach':
- return { ok: true, result: await handleAttach(req, socket) }
+ return { ok: true, result: withGeometry(req.name, socket, await handleAttach(req, socket)) }
case 'attachExisting':
if (clientProtocolVersion === 1) {
return { ok: false, error: 'attachExisting requires session-host protocol v2' }
}
- return { ok: true, result: await handleAttachExisting(req, socket) }
+ return {
+ ok: true,
+ result: withGeometry(req.name, socket, await handleAttachExisting(req, socket))
+ }
case 'hasSession':
{
const session = sessions.get(req.name)
@@ -973,11 +1020,7 @@ async function main(): Promise<void> {
encodeFrame(
clientProtocolVersion === 1
? { id: req.id, ok: true }
- : {
- id: req.id,
- ok: true,
- result: { protocolVersion: currentProtocolVersion() }
- }
+ : { id: req.id, ok: true, result: negotiateHello(req, socket) }
),
sessions.values()
)
@@ -1001,11 +1044,7 @@ async function main(): Promise<void> {
encodeFrame(
clientProtocolVersion === 1
? { id: req.id, ok: true }
- : {
- id: req.id,
- ok: true,
- result: { protocolVersion: currentProtocolVersion() }
- }
+ : { id: req.id, ok: true, result: negotiateHello(req, socket) }
),
sessions.values()
)
diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.ts
index 22fa713d1..14e17421f 100644
--- a/src/session-host/protocol.ts
+++ b/src/session-host/protocol.ts
@@ -48,7 +48,17 @@ export interface SessionHostSpawnOptions {
* same idiom `ControlModeClient` uses for tmux control-mode, minus the positional-FIFO fragility
* (JSON here carries its own id, so an out-of-order reply is still recoverable). */
export type SessionHostRequest =
- | { id: number; cmd: 'hello'; token: string; protocolVersion: number }
+ | {
+ id: number
+ cmd: 'hello'
+ token: string
+ protocolVersion: number
+ /** Additive capabilities this CLIENT understands, independent of the protocol version (which
+ * a long-lived host can only change by being replaced). The host answers with the subset it
+ * also speaks in `HelloResult.features`, and must never push a frame a connection did not
+ * opt into here: an older client reads ANY push frame that is not `data` as an exit. */
+ features?: SessionHostFeature[]
+ }
| {
id: number
cmd: 'attach'
@@ -134,6 +144,11 @@ export type SessionHostEvent =
exitCode: number
generation?: string
}
+ /** The size the host's pty now runs at, pushed whenever it changes (issue #914) — ONLY to a
+ * connection that negotiated the `geometry` feature at hello. That gate is not a nicety: an
+ * older client treats every non-`data` push frame as an exit and would retire a live session
+ * on the first resize. */
+ | { type: 'geometry'; name: string; cols: number; rows: number; generation?: string }
export type SessionHostFrame = SessionHostResponse | SessionHostEvent
@@ -150,7 +165,8 @@ export type SessionHostRequestBody = SessionHostRequest extends infer T
: never
export function isEventFrame(f: SessionHostFrame): f is SessionHostEvent {
- return (f as SessionHostEvent).type === 'data' || (f as SessionHostEvent).type === 'exit'
+ const type = (f as SessionHostEvent).type
+ return type === 'data' || type === 'exit' || type === 'geometry'
}
/** Result payload shapes, `result` on a successful response — documented here rather than typed
@@ -178,7 +194,20 @@ export interface AttachResult {
launchDialect?: SessionHostShellDialect
/** Sanitized outcome for an atomic cold-start launch; no rendered input is reflected. */
initialLaunchStatus?: 'executed' | 'already-executed'
+ /** The pty's size once this attach's own claim was applied. Present only for a connection that
+ * negotiated the `geometry` feature (issue #914). */
+ geometry?: { cols: number; rows: number }
}
+/** Additive, independently negotiated capabilities (see the `hello` request). */
+export type SessionHostFeature = 'geometry'
+export const SESSION_HOST_FEATURES: readonly SessionHostFeature[] = ['geometry']
+
+/** `result` of a v2 `hello`. `features` is absent from a host that predates feature negotiation. */
+export interface HelloResult {
+ protocolVersion: number
+ features?: SessionHostFeature[]
+}
+
export interface HasSessionResult {
exists: boolean
/** Required with exists:true in v2; legacy v1 hosts do not provide it. */
diff --git a/src/session-host/session.ts b/src/session-host/session.ts
index 0cbf81c37..2a13a88d0 100644
--- a/src/session-host/session.ts
+++ b/src/session-host/session.ts
@@ -152,6 +152,16 @@ export class HostSession {
* from the prior epoch can then observe cancellation instead of resurrecting a ghost socket. */
private readonly attachmentEpochs = new WeakMap<Socket, number>()
private appliedGeometry: Geometry
+ /** Told every time the pty is actually resized — the host pushes it to the connections that
+ * negotiated the `geometry` feature, so each viewer can render the size the pty really has
+ * instead of the one it asked for (issue #914). Called inside the emulator tail, after both
+ * actuators succeeded; it must not throw back into it. */
+ onGeometryApplied?: (geometry: Geometry) => void
+
+ /** The size the pty runs at right now. */
+ get geometry(): Geometry {
+ return { ...this.appliedGeometry }
+ }
/** Consecutive callers asking for the same effective target share one acknowledgement. If that
* actuator attempt fails, every waiter sees the failure; a later exact retry starts a new one. */
private pendingGeometry: { key: string; promise: Promise<void> } | null = null
@@ -699,6 +709,11 @@ export class HostSession {
this.proc.resize(target.cols, target.rows)
this.term.resize(target.cols, target.rows)
this.appliedGeometry = target
+ try {
+ this.onGeometryApplied?.({ ...target })
+ } catch {
+ // A notification failure must not turn a successful resize into a failed one.
+ }
})
const pending = { key, promise: reconciled }
this.pendingGeometry = pending