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): serialize a watcher's size sync per session, and report a session's current size

reviewc2d307af752e
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 9e60fcc81..bfa9d238d 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -4607,28 +4607,76 @@ export class PtyManager {
* for anything that is not a watcher's own client, an unreadable size, or a session that went away
* during the read. With the production conf (`status off`) the window IS the client size, so a
* client of the window's size leaves the window where it is.
+ *
+ * SERIALIZED per session (controller ruling R24): the link host calls it before every keyframe and
+ * on a timer, and two links can watch one node, so calls overlap — and two reads racing each other
+ * could be applied out of order, leaving the client at the OLDER size. So one read is in flight per
+ * session, and every caller that arrives meanwhile shares ONE queued rerun that reads after it: the
+ * latest read is the one applied last. Never rejects.
*/
- async syncWatcherClientSize(sessionId: string): Promise<boolean> {
- const session = this.sessions.get(sessionId)
- if (!session?.watcherClient || !session.persistKey) return false
- const size = await this.readWindowSize(session.persistKey, session.sshRemote)
- if (!size || this.sessions.get(sessionId) !== session) return false
- if (session.appliedSize?.cols !== size.cols || session.appliedSize?.rows !== size.rows) {
- try {
- session.proc.resize(size.cols, size.rows)
- } catch {
- return false // the client already exited
+ syncWatcherClientSize(sessionId: string): Promise<boolean> {
+ const slot = this.watcherSizeSyncs.get(sessionId)
+ if (!slot) return this.startWatcherSizeSync(sessionId)
+ // Starts only once the read in flight settled, so its answer can never land after this one.
+ slot.rerun ??= slot.current.then(() => this.startWatcherSizeSync(sessionId))
+ return slot.rerun
+ }
+
+ /** One `syncWatcherClientSize` read per session at a time; `rerun` is the one queued behind it. */
+ private readonly watcherSizeSyncs = new Map<string, { current: Promise<boolean>; rerun: Promise<boolean> | null }>()
+
+ private startWatcherSizeSync(sessionId: string): Promise<boolean> {
+ const current = this.syncWatcherClientSizeOnce(sessionId)
+ const slot = { current, rerun: null as Promise<boolean> | null }
+ this.watcherSizeSyncs.set(sessionId, slot)
+ // Registered BEFORE any rerun's `.then`, so it runs first: with a rerun queued the slot stays until
+ // the rerun replaces it; with none, the session has no sync in flight any more.
+ void current.finally(() => {
+ if (this.watcherSizeSyncs.get(sessionId) === slot && !slot.rerun) this.watcherSizeSyncs.delete(sessionId)
+ })
+ return current
+ }
+
+ private async syncWatcherClientSizeOnce(sessionId: string): Promise<boolean> {
+ try {
+ const session = this.sessions.get(sessionId)
+ if (!session?.watcherClient || !session.persistKey) return false
+ const size = await this.readWindowSize(session.persistKey, session.sshRemote)
+ if (!size || this.sessions.get(sessionId) !== session) return false
+ if (session.appliedSize?.cols !== size.cols || session.appliedSize?.rows !== size.rows) {
+ try {
+ session.proc.resize(size.cols, size.rows)
+ } catch {
+ return false // the client already exited
+ }
+ session.appliedSize = size
}
- session.appliedSize = size
- }
- 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, size)
- this.send(subClient(sub), channel, size)
+ // The same per-subscriber `pty:size` applySize sends (a live link's viewer renders exactly this).
+ 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, size)
+ this.send(subClient(sub), channel, size)
+ }
+ return true
+ } catch {
+ return false
}
- return true
+ }
+
+ /**
+ * The size a session runs at NOW: the backend's authoritative size (the session host's answer),
+ * else the size pushed into its pty. What a live link's `watch:meta` reports for the session a viewer
+ * just joined (controller ruling R25): for a co-attached watcher that is the owner's pty size; for a
+ * watcher's OWN client it is the window size the client was spawned at and `syncWatcherClientSize`
+ * keeps it at — a client `watchSizeFor` cannot see (it is hidden from every persistKey lookup). A
+ * copy; null for a session this manager does not know, or one that has no size yet.
+ */
+ sessionSize(sessionId: string): { cols: number; rows: number } | null {
+ const session = this.sessions.get(sessionId)
+ const size = session?.backendSize ?? session?.appliedSize
+ return size ? { cols: size.cols, rows: size.rows } : null
}
/**
diff --git a/src/core/pty-watch-join.test.ts b/src/core/pty-watch-join.test.ts
index 52a716fab..7f23bcfee 100644
--- a/src/core/pty-watch-join.test.ts
+++ b/src/core/pty-watch-join.test.ts
@@ -513,6 +513,57 @@ describe('syncWatcherClientSize', () => {
expect(spawned[0].resizes).toEqual([])
})
+ // Controller ruling R24: the link host syncs on every keyframe AND on a 10 s timer, and two links can
+ // watch one node, so calls overlap. Two reads racing each other could land out of order and leave the
+ // client at the OLDER size. So one read is in flight per session, and callers that arrive meanwhile
+ // share ONE queued rerun, which reads after it (the latest read is applied last).
+ it('serializes per session: one read in flight, callers meanwhile share ONE rerun, the later read applied last', async () => {
+ const m = await tmuxManager(['nt-n1'])
+ const w = await m.joinAsWatcher(WATCHER, WATCH) // spawned at the window, 120x39
+ const answers: Array<(v: unknown) => void> = []
+ readOf(m).mockClear()
+ readOf(m).mockImplementation(() => new Promise((r) => answers.push(r)))
+ const first = m.syncWatcherClientSize(w.sessionId)
+ const second = m.syncWatcherClientSize(w.sessionId)
+ const third = m.syncWatcherClientSize(w.sessionId)
+ expect(second).toBe(third) // one queued rerun, shared
+ await vi.advanceTimersByTimeAsync(0)
+ expect(readOf(m)).toHaveBeenCalledTimes(1) // nothing reads beside the one in flight
+ answers[0]({ cols: 100, rows: 30 })
+ expect(await first).toBe(true)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(readOf(m)).toHaveBeenCalledTimes(2) // the rerun reads only once the first settled
+ answers[1]({ cols: 200, rows: 50 })
+ expect(await second).toBe(true)
+ expect(spawned[0].resizes).toEqual([{ cols: 100, rows: 30 }, { cols: 200, rows: 50 }])
+ // Settled: the next call starts a fresh read at once.
+ readOf(m).mockResolvedValue({ cols: 200, rows: 50 })
+ expect(await m.syncWatcherClientSize(w.sessionId)).toBe(true)
+ expect(readOf(m)).toHaveBeenCalledTimes(3)
+ })
+
+ it('serialization is per session: another session reads at the same time', async () => {
+ const m = await tmuxManager(['nt-n1', 'nt-n2'])
+ const a = await m.joinAsWatcher(WATCHER, WATCH)
+ const b = await m.joinAsWatcher(WATCHER, { persistKey: 'n2', viewerId: 'watch-s2' })
+ readOf(m).mockClear()
+ readOf(m).mockImplementation(() => new Promise(() => {}))
+ void m.syncWatcherClientSize(a.sessionId)
+ void m.syncWatcherClientSize(b.sessionId)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(readOf(m).mock.calls.map((c) => c[0])).toEqual(['n1', 'n2'])
+ })
+
+ it('a read that throws settles the slot: the next call reads again', async () => {
+ const m = await tmuxManager(['nt-n1'])
+ const w = await m.joinAsWatcher(WATCHER, WATCH)
+ readOf(m).mockRejectedValueOnce(new Error('boom'))
+ expect(await m.syncWatcherClientSize(w.sessionId)).toBe(false)
+ readOf(m).mockResolvedValue({ cols: 130, rows: 40 })
+ expect(await m.syncWatcherClientSize(w.sessionId)).toBe(true)
+ expect(spawned[0].resizes).toEqual([{ cols: 130, rows: 40 }])
+ })
+
it('an SSH watcher client is synced from the HOST read', async () => {
const m = await tmuxManager([])
vi.spyOn(
@@ -529,6 +580,45 @@ describe('syncWatcherClientSize', () => {
})
})
+// Controller ruling R25: the size a live link's `watch:meta` reports is the JOINED session's current
+// size. For a watcher's own client that is the size it runs at (the window's, read at spawn and kept by
+// the sync) — `watchSizeFor` cannot see that client (it is invisible to every persistKey lookup) and
+// would answer a stale released size or nothing.
+describe('sessionSize', () => {
+ it("is the owner's pty size for a co-attached watcher, and follows the owner's resize", async () => {
+ const m = await manager()
+ const own = await create(OWNER, { cols: 120, rows: 40 })
+ const w = await m.joinAsWatcher(WATCHER, WATCH)
+ expect(w.sessionId).toBe(own.sessionId)
+ expect(m.sessionSize(w.sessionId)).toEqual({ cols: 120, rows: 40 })
+ fake.senderListeners[IPC.ptyResize](OWNER, own.sessionId, 100, 30)
+ expect(m.sessionSize(w.sessionId)).toEqual({ cols: 100, rows: 30 })
+ })
+
+ it("is a watcher's OWN client's size — the window's, read at spawn and kept by the sync", async () => {
+ const m = await tmuxManager(['nt-n1'])
+ const w = await m.joinAsWatcher(WATCHER, WATCH) // caller said 40x10; spawned at the window, 120x39
+ expect(m.sessionSize(w.sessionId)).toEqual({ cols: 120, rows: 39 })
+ expect(m.watchSizeFor('n1')).toBeUndefined() // what the old wiring would have reported: nothing
+ ;(m as unknown as { readWindowSize: ReturnType<typeof vi.fn> }).readWindowSize.mockResolvedValue({ cols: 200, rows: 50 })
+ await m.syncWatcherClientSize(w.sessionId)
+ expect(m.sessionSize(w.sessionId)).toEqual({ cols: 200, rows: 50 })
+ })
+
+ it('is null for a session this manager does not know', async () => {
+ const m = await manager()
+ expect(m.sessionSize('no-such-session')).toBeNull()
+ })
+
+ it('hands back a copy, not the live size record', async () => {
+ const m = await manager()
+ const own = await create(OWNER, { cols: 120, rows: 40 })
+ const size = m.sessionSize(own.sessionId)!
+ size.cols = 1
+ expect(m.sessionSize(own.sessionId)).toEqual({ cols: 120, rows: 40 })
+ })
+})
+
describe('watchSizeFor', () => {
it('is the size the live pty runs at, whatever the watcher reported', async () => {
const m = await manager()