forestui icon indicating copy to clipboard operation
forestui copied to clipboard

Ctrl+A and mouse intermittently stop reaching tmux while forestui runs; plus two confirmed terminal-handling defects

Open flipbit03 opened this issue 3 months ago • 0 comments

Revision note. An earlier version of this issue claimed the terminal wedge was caused by forestui leaking terminal modes on abnormal exit. That causal claim was wrong and has been retracted — see "Retracted theory". The reporting user pointed out that forestui is still running when the wedge happens, so nothing had exited and nothing had leaked. What remains is: two independently confirmed code defects, and one open investigation with a leading hypothesis. Please do not treat the wedge as explained.

What this issue contains

  1. Defect A (confirmed) — TERMINAL_MODES_OFF is reachable from exactly one code path. Fix regardless of anything else.
  2. Defect B (confirmed) — Ctrl+letter fires plain-letter bindings.
  3. Open investigation — a user's terminal intermittently stops responding to the tmux prefix and mouse. Leading hypothesis is forestui's use of ?1003h, but this is not proven.

Defects A and B are safe to fix now. The investigation needs data capture from the reporting user before anyone implements against it.


The user-visible problem (unexplained)

Reported verbatim:

"in the tmux window which is currently bugged, it's like Ctrl does nothing. C-a is usually my leader key, but I have a forestui instance running, which has a set up as a shortcut. I'm hitting C-a in that window and it's actually actuating the a shortcut in forestui. It's like I disabled all tmux' keys/mouse."

"I can't C-a <space> and switch windows, I can't click on tmux panes, I can't switch them, it's like tmux is dead there... reopening a new connection and hitting forestui (same as tmux a if the session exists) gets me into the same shared context, BUT NOW IT'S BACK TO WORKING."

Characteristics:

  • forestui is still running when it happens. It did not crash. The user quit it normally with q afterwards.
  • Plain unmodified keys work. Ctrl-modified keys are not intercepted by tmux and fall through to the application.
  • Mouse is dead for tmux — no pane clicks, no window-tab clicks.
  • The tmux session is healthy. A fresh SSH connection attaching to the same session works immediately.
  • Intermittent. Correlates with sessions where Claude Code is in use, but Claude Code never crashed either.

Workaround that resolved it

Pasted into the shell of the wedged pane (after quitting forestui with q):

printf '\033[<u\033[>4;0m\033[?1000l\033[?1002l\033[?1003l\033[?1006l\033[?1016l'

User confirmed: "your magic string UNBUGGED that screen... and that was it, working again."

Two caveats on interpreting this. The keyboard-protocol halves (\033[<u, \033[>4;0m) are almost certainly no-ops — see "Ruled out". And it is not established whether quitting forestui with q alone would have fixed it; the user did both, in that order, so the printf may have been unnecessary.


Environment

forestui installed binary 2.6.1; both defects present on current main
repo HEAD when investigated eccfaa7 — Name each Claude session after the tmux tab it runs in (#50)
tmux 3.4, mouse on, prefix C-a, extended-keys off, repeat-time 1000
user's tmux binding bind C-a send-prefix (relevant to one hypothesis below)
terminal xterm-256color over SSH
OS Linux x86_64

Defect A (confirmed): TERMINAL_MODES_OFF is reachable from one path only

src/main.rs:

// line 176-177
const TERMINAL_MODES_ON: &str  = "\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h\x1b[?1004h";
const TERMINAL_MODES_OFF: &str = "\x1b[?1004l\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l";

// line 121
async fn run(self_update: bool) -> anyhow::Result<()> {
    ...
    let mut terminal = ratatui::init();   // line 126
    enable_mouse();                       // line 127  ← modes ON, unconditionally

    let outcome = loop { ... };           // the only exit that cleans up

    disable_mouse();                      // line 151  ← ONLY reachable here
    ratatui::restore();                   // line 152
    outcome
}

Verified by grep over src/main.rs and src/app/mod.rs for set_hook, panic, SIGTERM, signal, ctrlc: no panic hook, no signal handler, no Drop guard anywhere.

The subtle part: ratatui::init() installs its own panic hook, but it only calls ratatui::restore() — LeaveAlternateScreen + disable_raw_mode. It knows nothing about TERMINAL_MODES_OFF. After a panic the screen looks correctly restored while all five modes remain set, with no visible sign.

Paths that skip cleanup: any panic; SIGTERM/SIGHUP (tmux pane killed, window closed, kill-pane); SIGKILL. The reporting user routinely has ~39 forestui processes alive at once during testing, constantly started and killed.

The existing test at src/main.rs:223-228 pins the contents of both constants but cannot catch that OFF is unreachable from most paths.

This is a real defect worth fixing on its own merits. It is not, however, an explanation for the user's wedge — see the retraction below.

Proposed fix for Defect A

  1. RAII guard replacing the bare enable_mouse()/disable_mouse() pair — covers normal exit, early return, ? propagation, and unwinding panics:

    struct TerminalModes;
    impl TerminalModes {
        fn enable() -> Self { print!("{TERMINAL_MODES_ON}"); flush(); Self }
    }
    impl Drop for TerminalModes {
        fn drop(&mut self) { print!("{TERMINAL_MODES_OFF}"); flush(); }
    }
    
  2. Chained panic hook — Drop does not run under panic = "abort", and ordering against ratatui's hook matters. Capture the existing hook, emit TERMINAL_MODES_OFF, then delegate. Check Cargo.toml for the release panic strategy and note it in the PR.

  3. SIGTERM/SIGHUP handler — emit OFF, restore default disposition, re-raise so exit status stays honest. This is the case that fires when a tmux pane or window is killed.

  4. Self-heal on startup — SIGKILL can never be handled, so emit TERMINAL_MODES_OFF immediately before TERMINAL_MODES_ON in enable(). Cheap, idempotent, makes any residue non-sticky. Worth doing regardless.

Tests worth adding: that Drop emits OFF; that startup emits OFF before ON; and extend src/main.rs:223 to assert every mode in ON has a matching disable in OFF, so a future added mode can't slip through.


Defect B (confirmed): Ctrl+letter fires plain-letter bindings

src/app/keys.rs:

// line 35 — the ONLY modifier check in the whole handler
if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
    self.request_quit();
    return;
}
...
// line 125-127
if let KeyCode::Char(binding) = key.code {
    self.run_binding(binding);
}

Any Ctrl+letter runs the plain-letter binding: Ctrl+A opens Add Repository, Ctrl+W adds a worktree, Ctrl+Q quits. This is how the user first noticed something was wrong — their tmux prefix C-a visibly opened a modal.

Suggested fix: require key.modifiers to be free of CONTROL/ALT before run_binding, keeping the Ctrl+C special case. Note run_binding is also called from src/app/mouse.rs:295 for footer clicks — that call site passes a char directly and must keep working.

This is a symptom amplifier, not the cause of the wedge.


Open investigation: what actually wedges the terminal

Leading hypothesis — ?1003h any-motion reporting

forestui requests five modes; Claude Code, running the same terminal stack in an adjacent pane, requests two. Verified by grepping both binaries:

binary mouse modes requested
forestui (installed 2.6.1) ?1000h ?1002h ?1003h ?1006h ?1004h
Claude Code 2.1.239 ?1000h ?1006h only
Mode Meaning Cost
?1000h button press/release one sequence per click
?1002h button-drag sequences while dragging
?1003h any-event (motion) a sequence for every pointer movement, no button held
?1006h SGR extended coordinates changes encoding of the above
?1004h focus in/out ESC[I/ESC[O on every focus change

?1003h is by far the heaviest mode in the set, and forestui is the only program in this user's stack that requests it. Claude Code gets everything it needs from ?1000h+?1006h because it does not do hover.

Why this is now the leading hypothesis: it operates while forestui is alive and running, which is the constraint the user's counter-evidence imposes. Every other theory so far required forestui to have exited. This one does not — the flood is live-state, present exactly when forestui is on screen, which is exactly when the user reports the wedge.

Plausible mechanism (unproven): a constant stream of motion reports in SGR encoding either saturates or desynchronizes tmux's input parsing for that client, so a single-byte keystroke like Ctrl+A (0x01) gets consumed as part of a mouse report instead of matching the prefix binding. Plain keys typed in the gaps still get through — consistent with the user being able to press q but never Ctrl+A.

?1003h is deliberate, not accidental: the comment at src/main.rs:155-170 explains it is what makes hover highlighting possible, since without it the terminal never reports a bare pointer move. So this is a real trade-off, not an obvious deletion. But it is worth asking whether hover is worth a permanent motion flood inside tmux, and whether ?1002h (drag-only, what most TUIs use, and closer to what Claude Code does) is sufficient. A/B-ing this is probably the single cheapest way to confirm or kill the hypothesis.

Competing hypothesis — client stuck in the prefix key table

The user's tmux config has bind C-a send-prefix. If the client were stuck in the prefix key table, then pressing C-a matches that binding and sends a literal 0x01 to the pane — where forestui, via Defect B, runs the a binding. That would explain the prefix, the F-key bindings, and the mouse all failing at once from a single piece of per-client state.

Evidence against: a mid-wedge dump showed client_key_table = root on both the wedged and working clients. Either this hypothesis is wrong, or the sample was taken after the state cleared. Recorded so it is not re-derived from scratch.

Also consider — expected tmux behavior, not a bug

With mouse on, tmux forwards mouse events to a pane whose application has requested mouse tracking, rather than acting on them itself. So "I cannot click panes or window tabs" may be correct tmux behavior while forestui has focus, and only the Ctrl+A half is anomalous. Worth separating these two symptoms before assuming one cause explains both.


Retracted theory (do not re-investigate)

The original version of this issue claimed Defect A caused the wedge: forestui exits abnormally, leaks the five modes onto the user's terminal, terminal stays stranded. Retracted. The reporting user pointed out that forestui is still running when the wedge occurs, so nothing exited and nothing leaked. A second flaw: the theory also assumed forestui's ?1003h reaches the outer terminal, when tmux — being a terminal emulator — intercepts a pane's mode requests and tracks them per-pane.

Defect A is still real. It is just not the explanation.


Ruled out (do not re-investigate)

tmux misconfiguration / user error. Two clients attached to the same server, one wedged and one working, dumped identically:

client /dev/pts/3 (WEDGED)              client /dev/pts/2 (WORKING)
  key_table:    root                      key_table:    root
  readonly:     0                         readonly:     0
  control:      0                         control:      0
  flags:        attached,focused,UTF-8    flags:        attached,UTF-8
  termfeatures: bpaste,ccolour,clipboard, termfeatures: bpaste,ccolour,clipboard,
                cstyle,focus,RGB,title                  cstyle,focus,RGB,title

diff of tmux show-options -t <session> between the two sessions: zero differences. Globally prefix C-a, key-table root, mouse on. No stray set key-table off, no read-only attach.

Kitty keyboard protocol / modifyOtherKeys. Grepped both binaries for CSI > N u, CSI < u, CSI > 4 ; N m: zero hits in either. Neither program touches the keyboard protocol. This was an early hypothesis and it was wrong.

Claude Code as the cause. It requests only ?1000h+?1006h, with symmetric cleanup, and never ?1003h. The user's correlation is indirect: forestui launches their Claude sessions, so a forestui is always present and instances churn around those sessions.


Data to capture before implementing against the investigation

Ask the reporting user to run these while wedged, before touching anything.

From the working terminal:

tmux list-clients -F '#{client_name} table=#{client_key_table} prefix_held=#{client_prefix} flags=#{client_flags}'
pgrep -a forestui | head          # confirm it really is still running

In the wedged pane:

cat -v      # 1. wiggle the mouse   2. press Ctrl+A   3. Ctrl+C to exit
  • Mouse wiggle spews ^[[<35;80;12M-style sequences → motion reporting is live, consistent with the ?1003h hypothesis.
  • Ctrl+A prints ^A → the terminal is sending 0x01 and tmux is dropping it, which points at parser desync rather than an encoding change.
  • client_key_table reading anything other than root → the competing hypothesis wins instead.

Then, as a targeted A/B: build forestui with ?1003h removed from TERMINAL_MODES_ON (accepting the loss of hover), have the user run that build for a few days, and see whether the wedge recurs.


Acceptance criteria

Defect A — implement now:

  • [ ] Killing forestui with SIGTERM leaves the terminal with mouse and focus reporting off.
  • [ ] A panic in forestui leaves the terminal with mouse and focus reporting off.
  • [ ] After a SIGKILL, the next forestui launch restores the terminal to a sane state.
  • [ ] Tests cover OFF-on-drop, OFF-before-ON, and ON/OFF symmetry.

Defect B — implement now:

  • [ ] Ctrl+letter no longer triggers plain-letter bindings.
  • [ ] Footer clicks via src/app/mouse.rs:295 still work.

Investigation — do not close on the basis of A and B:

  • [ ] Data captured from the reporting user while wedged.
  • [ ] ?1003h hypothesis confirmed or killed, ideally by an A/B build.
  • [ ] Only then: a decision on whether hover is worth ?1003h, or whether ?1002h suffices.

flipbit03 avatar Aug 22 '26 13:08 flipbit03