SwiftFlutterTerminalShellby

Two Terminal Reliability Traps: Mosh Failable Init and tmux Scroll Misbehaving

Fixing a force-unwrapped Mosh key crash in Shellby (fd0e73e), plus three terminal emulation lessons from TK-INPUT-03/04/06: why answering capability queries wrong beats silence, soft-keyboard LF vs CR in raw mode, and xterm.dart wheel codes 68/69 in tmux.

Working on a cross-platform SSH client like Shellby teaches you that terminal failures rarely come from the happy path. They come from silent assumptions about malformed inputs and terminal-to-app handshakes.

Two separate sets of fixes tell that story well: turning MoshEngine and MoshSession into failable initializers (fd0e73e), and untangling soft-keyboard newlines, capability queries, and mouse wheel codes inside tmux (TK-INPUT-03, 04, and 06).

Never Force-Unwrap a Remote Mosh Key

MoshCryptoSession(base64Key:sendDirection:) was already written as a failable initializer (init?): if the key isn’t valid base64 of the right length, it returns nil. Yet the wrapper MoshEngine called it with a force-unwrap:

let crypto = MoshCryptoSession(base64Key: key, sendDirection: .toServer)!

Any malformed or tampered MOSH CONNECT <port> <key> response crashed the app on the spot.

Commit fd0e73e converted both MoshEngine.init? and MoshSession.init? to failable initializers and updated all three callers:

  1. The connectivity probe in ConnectionService: on nil, stop the temporary remote server via Self.stopProbeServer(pid:session:) and throw MoshBootstrapError.startFailed.
  2. The main connection flow in ConnectionService: on nil, kill the spawned mosh-server PID over bootstrapSSH, disconnect bootstrapSSH, and throw.
  3. Sources/shellby-cli/main.swift: print the error and exit with code 2.

When a lower layer exposes init? specifically because input crosses a trust boundary, swallowing it with ! turns a recoverable handshake failure into a crash.

Capability Queries: Answering Wrong Is Worse Than Silence

On the HarmonyOS/Flutter side (555647f, TK-INPUT-04), modern CLI agents—codex, claude code, gemini-cli built on crossterm, ratatui, and ink—send a burst of terminal queries at startup.

The rule we arrived at after capturing real pty traffic is simple: if you don’t answer, apps fall back on a timeout; if you answer wrong, they trust the lie.

  • CPR (ESC[6n) must be 1-based: Upstream xterm.dart answered ESC[0;0R. CLI agents use CPR both to check whether the cursor sits at column 0 and to measure character width (print an emoji, ask the column). Being off by 1 breaks both.
  • Never answer kitty keyboard capability (ESC[?u): Claiming support when you cannot emit CSI-u sequences leaves every keystroke broken.
  • Leave XTVERSION (ESC[>0q) unanswered: Falling back to conservative mode is safe.
  • Answer OSC 10/11: Returning the active foreground and background theme colors prevents agents from assuming a dark background on light themes.
  • Swallow DCS/SOS/PM/APC strings up to ST/BEL: Upstream xterm.dart had no handlers for these four, so tmux’s XTVERSION reply rendered literally as >|tmux 3.7c, and Sixel or kitty graphics dumped tens of kilobytes of raw pixels onto the screen.

Soft-Keyboard LF Breaks Raw-Mode TUIs

HarmonyOS 1.1.6 users hit a puzzling bug: Return worked fine at the shell prompt, then stopped working inside codex.

On a software keyboard, pressing Return isn’t a hardware key event—the IME inserts \n (0x0A) via TextInputPlugin.handleNewlineEvent, and xterm.dart forwarded it untouched. A shell in canonical mode accepts \n. A raw-mode TUI (as crossterm explicitly specifies) reads 0x0A as Ctrl+J, not Enter (0x0D / CR). Normalizing \n to \r inside TerminalSessionState.sendText fixed every IME path at once.

Apple had a cousin of the same bug: SwiftTerm’s normal Enter path uses returnByteSequence (\r), but when Meta is active it routes through send(txt:), emitting ESC LF instead of ESC CR. That is why iOS carries a dedicated ⌥⏎ key on the shortcut bar to emit ESC CR directly (TK-INPUT-05).

Wheel Codes 68/69 and How tmux Actually Routes Scroll

Another 1.1.6 report was: “set -g mouse on is set in tmux, and scrolling still does nothing.”

In X11 SGR mouse encoding, bit 6 (64) marks a scroll wheel event, and the low two bits carry the button index (0 for up, 1 for down), giving 64 and 65. xterm.dart 4.0.0 wrote 64 + 4 (68 and 69) instead—where bit 4 is the Shift modifier.

Sending Shift+Wheel misses tmux’s default WheelUpPane binding (68 left pane_in_mode=0; 64 triggered pane_in_mode=1). Fixing ShellbyMouseHandler stripped the stray Shift bit without forking xterm. On iOS and macOS, SwiftTerm wasn’t sending any wheel bytes in alternate screen at all—it kept handing gestures to an empty local scrollback—until e8bb368 added alternate-screen pan/wheel forwarding and TerminalKeyTests pinned encodeButton to 64/65.

Later, investigating “cannot scroll inside pi under tmux” (bf323b4, TK-INPUT-06) exposed one more trap. We briefly tried actively probing tmux with XTVERSION (ESC[>0q) at connect time—and reverted it immediately. Writing an app-to-terminal query into an SSH pty makes you impersonate user typing; remote bash rang \x07 and printed 0q right onto the prompt.

Testing tmux 3.7c directly by feeding sequences to an attached pty mapped out the real behavior:

Pane state tmux mouse Client sends Pane receives
Mouse subscribed + alt screen (pi fullscreen, vim mouse=a) off / on SGR 64 or 68 Passed through verbatim
No mouse + main screen (pi regular, plain shell) off SGR 64 Dropped; ESC[A passed through
No mouse + main screen on SGR 64 Enters copy-mode
No mouse + main screen on SGR 68 No response

Because pi’s default regular mode draws on the main screen without subscribing to mouse events and emits ESC[3J, tmux can only scroll stacked redraw frames via copy-mode. Switching to pi --tui-mode fullscreen lets the pane app subscribe directly, and tmux forwards wheel events regardless of set -g mouse.

Terminal reliability comes down to three defensive habits: never force-unwrap remote handshake keys, never inject synthetic queries onto a user’s SSH stream, and stay silent on capability queries you don’t fully implement.

✦

Comments

  • Loading…

Comments are reviewed before publishing; email is visible only to me.