Keep terminal input wrapping aligned with pane width (#6939)

* Keep terminal PTY columns synced after visible resize

Co-authored-by: Orca <help@stably.ai>

* Address terminal resize review feedback

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-06-30 15:08:01 -07:00
committed by GitHub
co-authored by Orca
parent b8d7bf0570
commit 34fcf3af67
6 changed files with 751 additions and 138 deletions
@@ -611,6 +611,7 @@ describe('connectPanePty', () => {
signal: vi.fn(),
listSessions: vi.fn().mockResolvedValue([]),
getSize: vi.fn().mockResolvedValue(null),
reportGeometry: vi.fn(),
getMainBufferSnapshot: vi.fn().mockResolvedValue(null),
getForegroundProcess: vi.fn().mockResolvedValue(null),
hasChildProcesses: vi.fn().mockResolvedValue(false),
@@ -11218,6 +11219,7 @@ describe('connectPanePty', () => {
binding: { noteVisibilityResume: () => void }
transport: MockTransport
deps: ReturnType<typeof createDeps>
pane: ReturnType<typeof createPane>
}> {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-pane-2')
@@ -11232,7 +11234,59 @@ describe('connectPanePty', () => {
const binding = connectPanePty(pane as never, manager as never, deps as never) as unknown as {
noteVisibilityResume: () => void
}
return { binding, transport, deps }
return { binding, transport, deps, pane }
}
function installObservedPane(pane: ReturnType<typeof createPane>): {
trigger: () => void
restore: () => void
} {
const originalResizeObserver = globalThis.ResizeObserver
const originalElement = globalThis.Element
const hadResizeObserver = 'ResizeObserver' in globalThis
const hadElement = 'Element' in globalThis
type ResizeObserverCallbackLike = ConstructorParameters<typeof ResizeObserver>[0]
class MockElement extends EventTarget {
dataset: Record<string, string> = {}
classList = { contains: (className: string) => className === 'pane' }
querySelectorAll(): MockElement[] {
return []
}
}
class MockResizeObserver {
static instances: MockResizeObserver[] = []
observe = vi.fn()
disconnect = vi.fn()
constructor(private readonly callback: ResizeObserverCallbackLike) {
MockResizeObserver.instances.push(this)
}
trigger(): void {
this.callback([], this as never)
}
}
globalThis.Element = MockElement as never
globalThis.ResizeObserver = MockResizeObserver as never
pane.container = new MockElement() as unknown as HTMLElement
return {
trigger: () => MockResizeObserver.instances[0]?.trigger(),
restore: () => {
if (hadResizeObserver) {
globalThis.ResizeObserver = originalResizeObserver
} else {
Reflect.deleteProperty(globalThis, 'ResizeObserver')
}
if (hadElement) {
globalThis.Element = originalElement
} else {
Reflect.deleteProperty(globalThis, 'Element')
}
}
}
}
it('re-asserts the current size when the PTY drifted from xterm', async () => {
@@ -11247,6 +11301,115 @@ describe('connectPanePty', () => {
expect(transport.resize).toHaveBeenCalledWith(120, 40)
})
it('re-asserts after observed pane geometry changes while visible', async () => {
const pane = createPane(2)
const observer = installObservedPane(pane)
try {
vi.mocked(window.api.pty.getSize).mockResolvedValue({ cols: 200, rows: 40 })
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-pane-2')
transportFactoryQueue.push(transport)
const manager = createManager(2)
const deps = createDeps({
restoredLeafId: LEAF_2,
paneTransportsRef: { current: new Map([[1, createMockTransport('pty-pane-1')]]) }
})
pane.terminal.cols = 82
pane.terminal.rows = 40
connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks()
transport.resize.mockClear()
vi.mocked(window.api.pty.getSize).mockClear()
observer.trigger()
await flushAsyncTicks()
expect(window.api.pty.getSize).toHaveBeenCalledWith('pty-pane-2')
expect(transport.resize).toHaveBeenCalledWith(82, 40)
} finally {
observer.restore()
}
})
it('reports desktop geometry without resizing while a mobile-fit override is active', async () => {
const { setFitOverride } = await import('@/lib/pane-manager/mobile-fit-overrides')
const pane = createPane(2)
const observer = installObservedPane(pane)
try {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-pane-2')
transportFactoryQueue.push(transport)
const manager = createManager(2)
const deps = createDeps({
restoredLeafId: LEAF_2,
paneTransportsRef: { current: new Map([[1, createMockTransport('pty-pane-1')]]) }
})
pane.fitAddon = {
...pane.fitAddon,
proposeDimensions: vi.fn(() => ({ cols: 101, rows: 33 }))
} as never
connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks()
setFitOverride('pty-pane-2', 'mobile-fit', 40, 30)
transport.resize.mockClear()
vi.mocked(window.api.pty.getSize).mockClear()
vi.mocked(window.api.pty.reportGeometry).mockClear()
observer.trigger()
await flushAsyncTicks()
expect(window.api.pty.getSize).not.toHaveBeenCalled()
expect(window.api.pty.reportGeometry).toHaveBeenCalledWith('pty-pane-2', 101, 33)
expect(transport.resize).not.toHaveBeenCalled()
} finally {
setFitOverride('pty-pane-2', 'desktop-fit', 0, 0)
observer.restore()
}
})
it('skips observed desktop reassertion while mobile owns the PTY without a fit override', async () => {
const { setDriverForPty } = await import('@/lib/pane-manager/mobile-driver-state')
const pane = createPane(2)
const observer = installObservedPane(pane)
try {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-pane-2')
transportFactoryQueue.push(transport)
const manager = createManager(2)
const deps = createDeps({
restoredLeafId: LEAF_2,
paneTransportsRef: { current: new Map([[1, createMockTransport('pty-pane-1')]]) }
})
const fit = vi.fn()
pane.fitAddon = {
...pane.fitAddon,
fit,
proposeDimensions: vi.fn(() => ({ cols: 130, rows: 50 }))
} as never
connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks()
setDriverForPty('pty-pane-2', { kind: 'mobile', clientId: 'phone-1' })
transport.resize.mockClear()
fit.mockClear()
vi.mocked(window.api.pty.getSize).mockClear()
vi.mocked(window.api.pty.reportGeometry).mockClear()
observer.trigger()
await flushAsyncTicks()
expect(window.api.pty.getSize).not.toHaveBeenCalled()
expect(window.api.pty.reportGeometry).not.toHaveBeenCalled()
expect(transport.resize).not.toHaveBeenCalled()
expect(fit).not.toHaveBeenCalled()
} finally {
setDriverForPty('pty-pane-2', { kind: 'idle' })
observer.restore()
}
})
it('does NOT re-assert when the PTY already matches xterm (no spurious SIGWINCH)', async () => {
vi.mocked(window.api.pty.getSize).mockResolvedValue({ cols: 120, rows: 40 })
const { binding, transport } = await connectResumablePane()
@@ -11269,6 +11432,51 @@ describe('connectPanePty', () => {
expect(transport.resize).toHaveBeenCalledWith(120, 40)
})
it('queues re-asserted resizes while pane resize holds are active', async () => {
const originalCustomEvent = globalThis.CustomEvent
class MockCustomEvent<T> extends Event {
detail: T
constructor(type: string, init: { detail: T }) {
super(type)
this.detail = init.detail
}
}
globalThis.CustomEvent = MockCustomEvent as unknown as typeof CustomEvent
try {
const { holdPtyResizesForPaneSubtrees, queuePanePtyResizeIfHeld } =
await import('@/lib/pane-manager/pane-pty-resize-hold')
vi.mocked(window.api.pty.getSize).mockResolvedValue({ cols: 80, rows: 24 })
const { binding, transport, pane } = await connectResumablePane()
await flushAsyncTicks()
Object.defineProperty(pane.container, 'classList', {
configurable: true,
value: { contains: (className: string) => className === 'pane' }
})
Object.defineProperty(pane.container, 'querySelectorAll', {
configurable: true,
value: () => []
})
const release = holdPtyResizesForPaneSubtrees([pane.container])
// Prove this fixture is using the same held pane element before the
// production reassertion overwrites the queued placeholder size.
expect(queuePanePtyResizeIfHeld(pane.container, 1, 1)).toBe(true)
transport.resize.mockClear()
binding.noteVisibilityResume()
await flushAsyncTicks()
expect(transport.resize).not.toHaveBeenCalled()
release.flush()
expect(transport.resize).toHaveBeenCalledTimes(1)
expect(transport.resize).toHaveBeenCalledWith(120, 40)
} finally {
globalThis.CustomEvent = originalCustomEvent
}
})
it('skips remote-runtime PTYs (their size lives outside the local ptySizes map)', async () => {
const getSize = vi.mocked(window.api.pty.getSize)
getSize.mockClear()
@@ -1,5 +1,6 @@
/* oxlint-disable max-lines */
import type { PaneManager, ManagedPane } from '@/lib/pane-manager/pane-manager'
import type { ManagedPaneInternal } from '@/lib/pane-manager/pane-manager-types'
import type { IDisposable } from '@xterm/xterm'
import {
detectAgentStatusFromTitle,
@@ -25,9 +26,11 @@ import { shouldSeedCacheTimerOnInitialTitle } from './cache-timer-seeding'
import { shouldReconcileDeadSession } from './terminal-dead-session-reconcile'
import type { PtyConnectionDeps } from './pty-connection-types'
import { safeFit } from '@/lib/pane-manager/pane-tree-ops'
import { requestStablePaneFit } from '@/lib/pane-manager/pane-fit-resize-observer'
import { getFitOverrideForPty, bindPanePtyId } from '@/lib/pane-manager/mobile-fit-overrides'
import { isPtyLocked } from '@/lib/pane-manager/mobile-driver-state'
import { reconcilePtySizeAcrossFrames, type PtySizeReconcileHandle } from './pty-size-reconcile'
import { createPtySizeReassertion } from './pty-size-reassertion'
import { isPaneReplaying, replayIntoTerminal, replayIntoTerminalAsync } from './replay-guard'
import {
nativeWindowsRewriteNeedsFollowupRenderRefresh,
@@ -2205,6 +2208,9 @@ export function connectPanePty(
if (shouldSuppressDesktopPtyResize()) {
return
}
if (queuePanePtyResizeIfHeld(pane.container, cols, rows)) {
return
}
transport.resize(cols, rows)
}
@@ -2221,38 +2227,43 @@ export function connectPanePty(
if (suppressSnapshotReplayPtyResize) {
return
}
if (!isRendererPtyResizeAuthoritative()) {
return
}
if (shouldSuppressDesktopPtyResize()) {
return
}
if (queuePanePtyResizeIfHeld(pane.container, cols, rows)) {
return
}
transport.resize(cols, rows)
forwardPtyResize(cols, rows)
})
// Why: while a mobile-fit override is active, the onResize listener above
// and the matching server-side gate both correctly drop pty:resize so the
// PTY stays parked at phone dims. But the server still needs to learn the
// real desktop pane geometry — otherwise resolveDesktopRestoreTarget falls
// back to the PTY's spawn default (e.g. 80×24 for a hidden tab) and Take
// Back leaves the terminal partially restored. This observer measures the
// pane container as a side-channel, computes proposed cols/rows the way
// safeFit would, and reports it via pty:reportGeometry — a measurement-
// only IPC that updates lastRendererSizes and non-null subscriber
// baselines without resizing the PTY. We only fire while an override is
// active because the normal pty:resize path covers all other cases. See
// docs/mobile-fit-hold.md.
// Why: renderer resize forwarding is fire-and-forget. A visible pane can
// finish with xterm at the right grid while the PTY silently kept an older
// grid, so Codex keeps composing against stale columns. Fit first so xterm's
// normal onResize can send, then read applied PTY size and repair only drift.
const ptySizeReassertion = createPtySizeReassertion({
isDisposed: () => disposed,
getPtyId: () => transport.getPtyId(),
isRemotePtyId: isRemoteRuntimePtyId,
shouldSuppressDesktopResize: () => shouldSuppressDesktopPtyResize(),
fit: () => safeFit(pane),
getTerminalDimensions: () => ({ cols: pane.terminal.cols, rows: pane.terminal.rows }),
getAppliedSize: (ptyId) => window.api.pty.getSize(ptyId),
forwardResize: forwardPtyResize
})
// Why: observe the outer pane as the layout signal for both desktop drift
// healing and mobile take-back. Normal desktop panes compare xterm against
// the PTY's applied size; mobile-fit panes only report desktop geometry so
// the parked phone-sized PTY is not resized. See docs/mobile-fit-hold.md.
let pendingGeometryReportRaf: number | null = null
const reportPaneGeometry = (): void => {
const handleObservedPaneGeometry = (): void => {
pendingGeometryReportRaf = null
const currentPtyId = transport.getPtyId()
if (!currentPtyId) {
return
}
if (!getFitOverrideForPty(currentPtyId)) {
const fitOverride = getFitOverrideForPty(currentPtyId)
if (!fitOverride) {
if (shouldSuppressDesktopPtyResize()) {
return
}
requestStablePaneFit(pane as ManagedPaneInternal, () =>
ptySizeReassertion.request({ fit: false })
)
return
}
let proposed: { cols: number; rows: number } | undefined
@@ -2277,7 +2288,7 @@ export function connectPanePty(
if (pendingGeometryReportRaf !== null) {
return
}
pendingGeometryReportRaf = requestAnimationFrame(reportPaneGeometry)
pendingGeometryReportRaf = requestAnimationFrame(handleObservedPaneGeometry)
})
// Why: pane.xtermContainer is created later in pane-lifecycle's
// attachWebgl/initial-fit path; pane.container is always present at the
@@ -2343,56 +2354,6 @@ export function connectPanePty(
})
}
// Why: the renderer forwards resizes fire-and-forget and dedupes on the size
// it *last sent*, so a resize dropped main-side (it was hidden, a suppression
// window, or a provider no-op) leaves xterm and the PTY silently diverged —
// and a later same-cols layout fires no onResize, so it never self-corrects
// ("resizing sometimes doesn't fix it"). On becoming visible, re-fit and
// compare xterm against the PTY's ACTUAL size (not what we think we sent); if
// they truly differ, re-assert. Gated on real drift so we emit no spurious
// SIGWINCH (which would jar alt-screen TUIs) on an already-synced resume.
let reassertingPtySizeOnResume = false
const reassertPtySizeOnResume = (): void => {
const ptyId = transport.getPtyId()
// Skip parked/mobile-driven PTYs before the async size read: their drift
// from desktop xterm dims is intentional until mobile hands control back.
if (
disposed ||
reassertingPtySizeOnResume ||
!ptyId ||
isRemoteRuntimePtyId(ptyId) ||
shouldSuppressDesktopPtyResize()
) {
return
}
reassertingPtySizeOnResume = true
void window.api.pty
.getSize(ptyId)
.then((actual) => {
// The pane may have been disposed or rebound to a different PTY during
// the async hop; bail if this reconcile no longer owns it.
if (disposed || transport.getPtyId() !== ptyId) {
return
}
safeFit(pane)
const cols = pane.terminal.cols
const rows = pane.terminal.rows
if (cols <= 0 || rows <= 0) {
return
}
// Re-assert only on genuine divergence from the PTY's applied size (a
// null read = unknown id, treated as "cannot confirm synced" so we
// forward once). forwardPtyResize owns the authoritative/mobile gating.
if (!actual || actual.cols !== cols || actual.rows !== rows) {
forwardPtyResize(cols, rows)
}
})
.catch(() => {})
.finally(() => {
reassertingPtySizeOnResume = false
})
}
// Defer PTY spawn/attach to next frame so FitAddon has time to calculate
// the correct terminal dimensions from the laid-out container.
const cancelScheduledConnectFrame = (): void => {
@@ -4696,7 +4657,7 @@ export function connectPanePty(
// Why: re-assert the PTY size on resume so a resize that was dropped while
// this pane was hidden self-heals on show, instead of waiting for a manual
// resize that may never change xterm's column count.
reassertPtySizeOnResume()
ptySizeReassertion.request()
},
reconcileIfSessionDead,
dispose() {
@@ -4705,6 +4666,7 @@ export function connectPanePty(
// rAF so a torn-down pane cannot keep fitting/resizing after disposal.
ptySizeReconcileHandle?.cancel()
ptySizeReconcileHandle = null
ptySizeReassertion.dispose()
if (terminalKeyTargetSupportsEvents) {
terminalKeyTarget.removeEventListener('keydown', onTerminalKeyDown, { capture: true })
}
@@ -0,0 +1,241 @@
import { describe, expect, it, vi } from 'vitest'
import { createPtySizeReassertion } from './pty-size-reassertion'
async function flushAsyncTicks(count = 3): Promise<void> {
for (let index = 0; index < count; index += 1) {
await Promise.resolve()
}
}
describe('createPtySizeReassertion', () => {
it('forwards the measured terminal size when the applied PTY size drifted', async () => {
const forwardResize = vi.fn()
const reassertion = createPtySizeReassertion({
isDisposed: () => false,
getPtyId: () => 'pty-1',
isRemotePtyId: () => false,
shouldSuppressDesktopResize: () => false,
fit: vi.fn(),
getTerminalDimensions: () => ({ cols: 82, rows: 30 }),
getAppliedSize: vi.fn(async () => ({ cols: 120, rows: 30 })),
forwardResize
})
reassertion.request()
await flushAsyncTicks()
expect(forwardResize).toHaveBeenCalledWith(82, 30)
})
it('does not forward when the applied PTY size already matches xterm', async () => {
const forwardResize = vi.fn()
const reassertion = createPtySizeReassertion({
isDisposed: () => false,
getPtyId: () => 'pty-1',
isRemotePtyId: () => false,
shouldSuppressDesktopResize: () => false,
fit: vi.fn(),
getTerminalDimensions: () => ({ cols: 82, rows: 30 }),
getAppliedSize: vi.fn(async () => ({ cols: 82, rows: 30 })),
forwardResize
})
reassertion.request()
await flushAsyncTicks()
expect(forwardResize).not.toHaveBeenCalled()
})
it('fits and reads xterm dimensions before reading the applied PTY size', async () => {
const calls: string[] = []
const reassertion = createPtySizeReassertion({
isDisposed: () => false,
getPtyId: () => 'pty-1',
isRemotePtyId: () => false,
shouldSuppressDesktopResize: () => false,
fit: vi.fn(() => {
calls.push('fit')
}),
getTerminalDimensions: vi.fn(() => {
calls.push('measure')
return { cols: 82, rows: 30 }
}),
getAppliedSize: vi.fn(async () => {
calls.push('read-applied')
return { cols: 82, rows: 30 }
}),
forwardResize: vi.fn()
})
reassertion.request()
await flushAsyncTicks()
expect(calls).toEqual(['fit', 'measure', 'read-applied'])
})
it('does not duplicate the resize when fit already triggered xterm onResize', async () => {
const forwardResize = vi.fn()
const reassertion = createPtySizeReassertion({
isDisposed: () => false,
getPtyId: () => 'pty-1',
isRemotePtyId: () => false,
shouldSuppressDesktopResize: () => false,
fit: vi.fn(() => {
forwardResize(82, 30)
}),
getTerminalDimensions: () => ({ cols: 82, rows: 30 }),
getAppliedSize: vi.fn(async () => ({ cols: 82, rows: 30 })),
forwardResize
})
reassertion.request()
await flushAsyncTicks()
expect(forwardResize).toHaveBeenCalledTimes(1)
expect(forwardResize).toHaveBeenCalledWith(82, 30)
})
it('can verify current dimensions without fitting again', async () => {
const fit = vi.fn()
const forwardResize = vi.fn()
const reassertion = createPtySizeReassertion({
isDisposed: () => false,
getPtyId: () => 'pty-1',
isRemotePtyId: () => false,
shouldSuppressDesktopResize: () => false,
fit,
getTerminalDimensions: () => ({ cols: 82, rows: 30 }),
getAppliedSize: vi.fn(async () => ({ cols: 120, rows: 30 })),
forwardResize
})
reassertion.request({ fit: false })
await flushAsyncTicks()
expect(fit).not.toHaveBeenCalled()
expect(forwardResize).toHaveBeenCalledWith(82, 30)
})
it('skips remote and suppressed PTYs', async () => {
const getAppliedSize = vi.fn(async () => ({ cols: 120, rows: 30 }))
const remote = createPtySizeReassertion({
isDisposed: () => false,
getPtyId: () => 'remote:terminal-1',
isRemotePtyId: () => true,
shouldSuppressDesktopResize: () => false,
fit: vi.fn(),
getTerminalDimensions: () => ({ cols: 82, rows: 30 }),
getAppliedSize,
forwardResize: vi.fn()
})
const suppressed = createPtySizeReassertion({
isDisposed: () => false,
getPtyId: () => 'pty-1',
isRemotePtyId: () => false,
shouldSuppressDesktopResize: () => true,
fit: vi.fn(),
getTerminalDimensions: () => ({ cols: 82, rows: 30 }),
getAppliedSize,
forwardResize: vi.fn()
})
remote.request()
suppressed.request()
await flushAsyncTicks()
expect(getAppliedSize).not.toHaveBeenCalled()
})
it('coalesces overlapping requests and runs again after an in-flight check resolves', async () => {
let resolveFirst: (value: { cols: number; rows: number }) => void = () => {}
const getAppliedSize = vi
.fn<() => Promise<{ cols: number; rows: number } | null>>()
.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveFirst = resolve
})
)
.mockResolvedValue({ cols: 120, rows: 30 })
const forwardResize = vi.fn()
const reassertion = createPtySizeReassertion({
isDisposed: () => false,
getPtyId: () => 'pty-1',
isRemotePtyId: () => false,
shouldSuppressDesktopResize: () => false,
fit: vi.fn(),
getTerminalDimensions: () => ({ cols: 82, rows: 30 }),
getAppliedSize,
forwardResize
})
reassertion.request()
reassertion.request()
reassertion.request()
reassertion.request()
expect(getAppliedSize).toHaveBeenCalledTimes(1)
resolveFirst({ cols: 120, rows: 30 })
await flushAsyncTicks()
expect(getAppliedSize).toHaveBeenCalledTimes(2)
expect(forwardResize).toHaveBeenCalledTimes(1)
})
it('does not forward a stale target when a newer request is pending', async () => {
let targetCols = 100
let resolveFirst: (value: { cols: number; rows: number }) => void = () => {}
const getAppliedSize = vi
.fn<() => Promise<{ cols: number; rows: number } | null>>()
.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveFirst = resolve
})
)
.mockResolvedValue({ cols: 90, rows: 40 })
const forwardResize = vi.fn()
const reassertion = createPtySizeReassertion({
isDisposed: () => false,
getPtyId: () => 'pty-1',
isRemotePtyId: () => false,
shouldSuppressDesktopResize: () => false,
fit: vi.fn(),
getTerminalDimensions: () => ({ cols: targetCols, rows: 40 }),
getAppliedSize,
forwardResize
})
reassertion.request()
targetCols = 120
reassertion.request()
resolveFirst({ cols: 120, rows: 40 })
await flushAsyncTicks()
expect(forwardResize).toHaveBeenCalledTimes(1)
expect(forwardResize).toHaveBeenCalledWith(120, 40)
expect(forwardResize).not.toHaveBeenCalledWith(100, 40)
})
it('forwards once when applied-size readback fails', async () => {
const forwardResize = vi.fn()
const reassertion = createPtySizeReassertion({
isDisposed: () => false,
getPtyId: () => 'pty-1',
isRemotePtyId: () => false,
shouldSuppressDesktopResize: () => false,
fit: vi.fn(),
getTerminalDimensions: () => ({ cols: 82, rows: 30 }),
getAppliedSize: vi.fn(async () => {
throw new Error('unavailable')
}),
forwardResize
})
reassertion.request()
await flushAsyncTicks()
expect(forwardResize).toHaveBeenCalledTimes(1)
expect(forwardResize).toHaveBeenCalledWith(82, 30)
})
})
@@ -0,0 +1,107 @@
export type PtySizeReassertionDimensions = { cols: number; rows: number }
export type PtySizeReassertionOptions = {
isDisposed: () => boolean
getPtyId: () => string | null
isRemotePtyId: (ptyId: string) => boolean
shouldSuppressDesktopResize: () => boolean
fit: () => void
getTerminalDimensions: () => PtySizeReassertionDimensions
getAppliedSize: (ptyId: string) => Promise<PtySizeReassertionDimensions | null>
forwardResize: (cols: number, rows: number) => void
}
export type PtySizeReassertion = {
request: (requestOptions?: { fit?: boolean }) => void
dispose: () => void
}
function dimensionsAreUsable(dimensions: PtySizeReassertionDimensions): boolean {
return dimensions.cols > 0 && dimensions.rows > 0
}
function dimensionsMatch(
left: PtySizeReassertionDimensions | null,
right: PtySizeReassertionDimensions
): boolean {
return left !== null && left.cols === right.cols && left.rows === right.rows
}
export function createPtySizeReassertion(options: PtySizeReassertionOptions): PtySizeReassertion {
let disposed = false
let inFlight = false
let pending = false
let pendingFit = false
const canQuery = (ptyId: string | null): ptyId is string => {
if (disposed || options.isDisposed() || !ptyId) {
return false
}
return !options.isRemotePtyId(ptyId) && !options.shouldSuppressDesktopResize()
}
const run = (shouldFit: boolean): void => {
const ptyId = options.getPtyId()
if (!canQuery(ptyId)) {
return
}
if (shouldFit) {
options.fit()
}
const target = options.getTerminalDimensions()
if (!dimensionsAreUsable(target)) {
return
}
inFlight = true
const forwardIfDrifted = (actual: PtySizeReassertionDimensions | null): void => {
if (options.getPtyId() !== ptyId || !canQuery(ptyId)) {
return
}
// Why: a queued request means a newer layout observation should re-measure
// before we send this older target back to the PTY.
if (pending) {
return
}
if (dimensionsMatch(actual, target)) {
return
}
options.forwardResize(target.cols, target.rows)
}
void options
.getAppliedSize(ptyId)
// Why: when readback is unavailable, one guarded resize is safer than
// silently leaving the visible desktop pane at an unverified PTY size.
.then(forwardIfDrifted, () => forwardIfDrifted(null))
.finally(() => {
inFlight = false
if (pending && !disposed) {
const shouldFitPending = pendingFit
pending = false
pendingFit = false
run(shouldFitPending)
}
})
}
return {
request: (requestOptions) => {
if (disposed || options.isDisposed()) {
return
}
const shouldFit = requestOptions?.fit !== false
if (inFlight) {
pending = true
pendingFit ||= shouldFit
return
}
run(shouldFit)
},
dispose: () => {
disposed = true
pending = false
pendingFit = false
}
}
}
@@ -2,7 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ManagedPaneInternal, ScrollState } from './pane-manager-types'
import {
attachPaneFitResizeObserver,
detachPaneFitResizeObserver
detachPaneFitResizeObserver,
requestStablePaneFit
} from './pane-fit-resize-observer'
type ResizeObserverCallbackLike = ConstructorParameters<typeof ResizeObserver>[0]
@@ -141,6 +142,38 @@ describe('attachPaneFitResizeObserver', () => {
expect(pane.fitAddon.fit).toHaveBeenCalledTimes(1)
})
it('waits through a transient grid wobble before notifying settled callbacks', () => {
const proposed = [
{ cols: 80, rows: 24 },
{ cols: 81, rows: 24 },
{ cols: 81, rows: 24 }
]
const onSettled = vi.fn()
const pane = createPane(() => proposed.shift() ?? { cols: 81, rows: 24 })
requestStablePaneFit(pane, onSettled)
flushAnimationFrames()
expect(pane.fitAddon.fit).not.toHaveBeenCalled()
expect(onSettled).not.toHaveBeenCalled()
flushAnimationFrames()
expect(pane.fitAddon.fit).toHaveBeenCalledTimes(1)
expect(onSettled).toHaveBeenCalledTimes(1)
})
it('notifies settled callbacks when the terminal already matches the stable grid', () => {
const onSettled = vi.fn()
const pane = createPane(() => ({ cols: 79, rows: 24 }))
requestStablePaneFit(pane, onSettled)
flushAnimationFrames()
expect(pane.fitAddon.fit).not.toHaveBeenCalled()
expect(onSettled).toHaveBeenCalledTimes(1)
})
it('skips observer fits while the terminal has no visible geometry', () => {
const pane = createPane(() => ({ cols: 80, rows: 24 }), {
rect: { width: 0, height: 0 }
@@ -1,4 +1,4 @@
import type { ManagedPaneInternal } from './pane-manager-types'
import type { ManagedPane, ManagedPaneInternal } from './pane-manager-types'
import { safeFit } from './pane-tree-ops'
type ProposedDimensions = {
@@ -6,9 +6,34 @@ type ProposedDimensions = {
rows: number
}
const MAX_STABILITY_FRAMES = 8
type StableFitPane = ManagedPane &
Partial<Pick<ManagedPaneInternal, 'xtermContainer' | 'pendingObservedFitRafId'>>
function getProposedDimensions(pane: ManagedPaneInternal): ProposedDimensions | null {
const MAX_STABILITY_FRAMES = 8
const pendingStableFitRafIds = new WeakMap<StableFitPane, number>()
const stableFitCallbacks = new WeakMap<StableFitPane, Set<() => void>>()
function getPendingObservedFitRafId(pane: StableFitPane): number | null {
return pane.pendingObservedFitRafId ?? pendingStableFitRafIds.get(pane) ?? null
}
function setPendingObservedFitRafId(pane: StableFitPane, id: number | null): void {
if ('pendingObservedFitRafId' in pane) {
pane.pendingObservedFitRafId = id
return
}
if (id === null) {
pendingStableFitRafIds.delete(pane)
} else {
pendingStableFitRafIds.set(pane, id)
}
}
function getFitElement(pane: StableFitPane): HTMLElement {
return pane.xtermContainer ?? pane.container
}
function getProposedDimensions(pane: StableFitPane): ProposedDimensions | null {
try {
return pane.fitAddon.proposeDimensions() ?? null
} catch {
@@ -20,15 +45,100 @@ function dimensionsEqual(a: ProposedDimensions | null, b: ProposedDimensions | n
return a?.cols === b?.cols && a?.rows === b?.rows
}
function terminalDimensionsEqual(pane: ManagedPaneInternal, dims: ProposedDimensions): boolean {
function terminalDimensionsEqual(pane: StableFitPane, dims: ProposedDimensions): boolean {
return pane.terminal.cols === dims.cols && pane.terminal.rows === dims.rows
}
function hasVisibleFitGeometry(pane: ManagedPaneInternal): boolean {
const rect = pane.xtermContainer.getBoundingClientRect?.()
function hasVisibleFitGeometry(pane: StableFitPane): boolean {
const rect = getFitElement(pane).getBoundingClientRect?.()
return !rect || (rect.width > 0 && rect.height > 0)
}
function addStableFitCallback(pane: StableFitPane, callback: (() => void) | undefined): void {
if (!callback) {
return
}
const callbacks = stableFitCallbacks.get(pane) ?? new Set()
callbacks.add(callback)
stableFitCallbacks.set(pane, callbacks)
}
function flushStableFitCallbacks(pane: StableFitPane): void {
const callbacks = stableFitCallbacks.get(pane)
if (!callbacks) {
return
}
stableFitCallbacks.delete(pane)
for (const callback of callbacks) {
callback()
}
}
function finishStableFit(pane: StableFitPane, shouldFit: boolean): void {
setPendingObservedFitRafId(pane, null)
if (shouldFit) {
safeFit(pane)
}
flushStableFitCallbacks(pane)
}
export function requestStablePaneFit(pane: StableFitPane, onSettled?: () => void): void {
addStableFitCallback(pane, onSettled)
if (getPendingObservedFitRafId(pane) !== null) {
return
}
if (!hasVisibleFitGeometry(pane)) {
stableFitCallbacks.delete(pane)
return
}
// Why: keep xterm fit work off the divider pointermove hot path and let
// the browser coalesce drag-driven size changes the same way Superset does.
//
// Windows can report a short-lived one-column anchor/scrollbar wobble when
// the right sidebar is open. Requiring a stable proposed grid before fitting
// prevents Codex from receiving a rapid SIGWINCH loop and visibly vibrating.
let previous = getProposedDimensions(pane)
let frameCount = 0
const waitForStableGrid = (): void => {
setPendingObservedFitRafId(
pane,
requestAnimationFrame(() => {
if (!hasVisibleFitGeometry(pane)) {
setPendingObservedFitRafId(pane, null)
stableFitCallbacks.delete(pane)
return
}
const next = getProposedDimensions(pane)
frameCount += 1
if (!next) {
finishStableFit(pane, true)
return
}
if (terminalDimensionsEqual(pane, next)) {
finishStableFit(pane, false)
return
}
if (dimensionsEqual(previous, next)) {
finishStableFit(pane, true)
return
}
previous = next
if (frameCount >= MAX_STABILITY_FRAMES) {
finishStableFit(pane, true)
return
}
waitForStableGrid()
})
)
}
waitForStableGrid()
}
export function attachPaneFitResizeObserver(pane: ManagedPaneInternal): void {
detachPaneFitResizeObserver(pane)
@@ -37,57 +147,7 @@ export function attachPaneFitResizeObserver(pane: ManagedPaneInternal): void {
}
const observer = new ResizeObserver(() => {
if (pane.pendingObservedFitRafId !== null) {
return
}
if (!hasVisibleFitGeometry(pane)) {
return
}
// Why: keep xterm fit work off the divider pointermove hot path and let
// the browser coalesce drag-driven size changes the same way Superset does.
//
// Windows can report a short-lived one-column anchor/scrollbar wobble when
// the right sidebar is open. Requiring a stable proposed grid before fitting
// prevents Codex from receiving a rapid SIGWINCH loop and visibly vibrating.
let previous = getProposedDimensions(pane)
let frameCount = 0
const waitForStableGrid = (): void => {
pane.pendingObservedFitRafId = requestAnimationFrame(() => {
if (!hasVisibleFitGeometry(pane)) {
pane.pendingObservedFitRafId = null
return
}
const next = getProposedDimensions(pane)
frameCount += 1
if (!next) {
pane.pendingObservedFitRafId = null
safeFit(pane)
return
}
if (terminalDimensionsEqual(pane, next)) {
pane.pendingObservedFitRafId = null
return
}
if (dimensionsEqual(previous, next)) {
pane.pendingObservedFitRafId = null
safeFit(pane)
return
}
previous = next
if (frameCount >= MAX_STABILITY_FRAMES) {
pane.pendingObservedFitRafId = null
safeFit(pane)
return
}
waitForStableGrid()
})
}
waitForStableGrid()
requestStablePaneFit(pane)
})
observer.observe(pane.xtermContainer)
@@ -98,8 +158,10 @@ export function detachPaneFitResizeObserver(pane: ManagedPaneInternal): void {
pane.fitResizeObserver?.disconnect()
pane.fitResizeObserver = null
if (pane.pendingObservedFitRafId !== null) {
cancelAnimationFrame(pane.pendingObservedFitRafId)
pane.pendingObservedFitRafId = null
const pendingObservedFitRafId = getPendingObservedFitRafId(pane)
if (pendingObservedFitRafId !== null) {
cancelAnimationFrame(pendingObservedFitRafId)
setPendingObservedFitRafId(pane, null)
}
stableFitCallbacks.delete(pane)
}