Fixing the Vim Bottom Gap in xterm.js and Tauri: Why SIGWINCH Timing Matters

While developing CocoTerminal—an SSH terminal client built on Tauri 2.x, React, and xterm.js—I ran into a baffling visual bug:

Whenever you connect to an SSH host and launch vim, htop, or nano, an empty gap sits at the bottom of the screen. The status bar fails to dock to the bottom edge. Yet, the instant you maximize and restore the window, the gap vanishes completely.

This post documents the deep-dive investigation into CSS flex layouts, xterm.js FitAddon mechanics, and how an asynchronous signal delivery race condition caused vim to drop window resize events during cold launches.


🚨 Problem Manifestation

  • Launching full-screen TUI utilities (vim, htop, less, tmux) over SSH leaves an unpainted blank band at the bottom of the viewport.
  • Content occupies fewer rows than the terminal element visibly offers.
  • Triggering any window resize event (maximizing, restoring, or dragging a window border by 1 pixel) immediately fixes the layout.

That “resizing fixes it” behavior was the single biggest clue that the underlying rendering pipeline was functional, but falling out of sync during initialization.


🔬 Technical Background

How xterm.js FitAddon Computes Geometry

The FitAddon.fit() method calculates terminal dimensions using the following pipeline:

  1. Reads clientWidth and clientHeight of the wrapping DOM container.
  2. Divides these dimensions by the font’s measured character bounding box to derive integer cols and rows.
  3. Calls terminal.resize(cols, rows) on the frontend.
  4. Emits a window_change SSH channel packet to the remote backend PTY, which dispatches a SIGWINCH signal to the child process.

If fit() fires before the DOM container has resolved its final geometry (meaning clientHeight is temporarily truncated), the resulting rows count will be too small. Vim then renders only that smaller subset of rows, leaving the rest of the canvas vacant.

Deeply Nested Flexbox Hierarchy

In modern desktop UIs, layout complexity compounds quickly. Our terminal was embedded inside an 8-level nested flex hierarchy with conditional panel toggling:

1
2
3
4
5
6
7
8
html/body/root (height: 100%)
└── .app-body (display: flex)
└── .app-main (flex-direction: column)
└── .app-terminal-area (flex: 1)
└── <div style="display: block/none"> ← Tab switching
└── SplitTerminal
└── .terminal-pane-root
└── <div class="xterm">

Because DOM reflows and flex layout calculations propagate asynchronously, fit() often executed during intermediate rendering states.


❌ Failed Attempts

Attempt 1: Fixed Delay fit()

1
setTimeout(() => fit.fit(), 200);

Why it failed: 200ms is an arbitrary guess. On high-load machines or slower virtual displays, reflows took longer, leaving the gap intact.

Attempt 2: Reacting to Visibility Props

1
2
3
4
useEffect(() => {
if (!visible) return;
setTimeout(() => fit.fit(), 50);
}, [visible]);

Why it failed: This resolved tab-switching issues (e.g., coming back from an SFTP view to the terminal), but did nothing for the initial cold launch of vim inside an already active session.

Attempt 3: Progressive fitUntilStable via requestAnimationFrame

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function fitUntilStable(fit, term, sessionId, onResizeFn) {
let prevCols = -1, prevRows = -1, stableCount = 0, round = 0;

function doFit() {
if (round++ >= 15) return;
void rootContainer.offsetHeight; // Force DOM reflow
fit.fit();
const { cols, rows } = term;

if (cols !== prevCols || rows !== prevRows) {
prevCols = cols; prevRows = rows; stableCount = 0;
onResizeFn(sessionId, cols, rows);
} else if (++stableCount >= 3) {
return; // Dimensions stabilized across 3 consecutive frames
}
requestAnimationFrame(doFit);
}

doFit();
}

Why it failed: Forcing reflows and tracking frame-to-frame stability significantly improved things, but users still reported sporadic bottom gaps when launching vim.


💥 The Real Root Cause: SIGWINCH Timing in vim

When Attempt 3 failed to eradicate the bug, I stepped back and analyzed the entire IPC chain:

1
Frontend fit() → Computes rows=35 → SSH window_change → Remote PTY → SIGWINCH → vim

fitUntilStable was actually working correctly! It reliably computed the true cols/rows and transmitted the updated dimensions to the backend PTY.

The failure was on the receiving end:

When vim received that initial SIGWINCH, it was still running its startup initialization routines (typically taking 100–300ms over remote links), and had not yet entered its event loop.

While the Linux kernel delivered SIGWINCH to the vim process, vim’s internal state machine was not yet ready to process layout recalculations. The redraw was discarded or postponed.

This explained every confusing symptom:

Behavior Reason
Initial vim launch has gap Vim drops or defers the first SIGWINCH while bootstrapping
Maximize / restore fixes it Triggers a fresh SIGWINCH after vim is fully listening
Typing any key fixes it Keystrokes wake vim’s event loop, prompting an internal bounds check
Manual window drag fixes it Dispatches a second SIGWINCH to an active event loop

✅ The Solution: Delayed Compensatory Resize

The fix was straightforward: once the animation frame stability loop finishes, schedule a single compensatory resize 500ms later.

By then, vim has completed its startup routines and is sitting stably in its event loop. The second SIGWINCH is processed immediately, triggering a clean, full-height redraw:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function fitUntilStable(fit, term, sessionId, onResizeFn) {
const MAX_ROUNDS = 15;
let round = 0, prevCols = -1, prevRows = -1, stableCount = 0;

function doFit() {
if (round >= MAX_ROUNDS) {
scheduleDelayedResize();
return;
}

// Force reflow and clear xterm-viewport fixed styling
void rootContainer?.offsetHeight;
const viewport = termElement?.querySelector('.xterm-viewport') as HTMLElement;
if (viewport?.style.height) viewport.style.height = '';

try { fit.fit(); } catch { return; }
const { cols, rows } = term;
round++;

if (cols !== prevCols || rows !== prevRows) {
prevCols = cols;
prevRows = rows;
stableCount = 0;
onResizeFn?.(sessionId, cols, rows)?.catch(() => {});
} else if (++stableCount >= 3) {
// 🔑 Key fix: schedule delayed catch-up after layout stabilizes
scheduleDelayedResize();
return;
}
requestAnimationFrame(doFit);
}

// Vim may drop early SIGWINCH during startup; re-dispatch after 500ms
function scheduleDelayedResize() {
if (!sessionId || !onResizeFn) return;
setTimeout(() => {
try { fit.fit(); } catch { return; }
const { cols, rows } = term;
if (cols > 0 && rows > 0) {
onResizeFn(sessionId, cols, rows)?.catch(() => {});
}
}, 500);
}

doFit();
}

Why 500ms?

  • Long enough to exceed vim’s process initialization (~50ms locally, ~200–400ms over latent SSH connections).
  • Short enough to avoid visible flicker (perceptible redraw jumps typically occur only after 800ms+).

📋 Takeaways

Never assume that because a signal was sent, the receiver was in a valid state to process it.

Frontend developers often assume IPC and OS signals are strictly serialized and honored. In terminal applications, child processes undergo initialization phases where POSIX signals can be dropped without warning.

Adding a short compensatory delay once layout geometry stabilizes is a reliable, battle-tested pattern across any xterm.js or Electron/Tauri terminal emulator running full-screen TUI apps like vim, nano, and htop.