jcode icon indicating copy to clipboard operation
jcode copied to clipboard

TUI input and scrolling degrade in long sessions due to render-path work and mixed terminal readers

Open apierron opened this issue 4 months ago • 8 comments

Summary

Terminal interactivity can degrade substantially in longer Jcode sessions. Typing becomes delayed, mouse-wheel scrolling causes excessive redraw work, and fragmented mouse reports can appear as text in the composer.

I reproduced this on macOS using a real PTY. The underlying problems are in shared Jcode TUI code rather than macOS-specific application code.

Symptoms

• Input latency grows as the conversation becomes longer. • Scrolling can cause large bursts of terminal output and high CPU usage. • Input may fall back to redraw-tick latency instead of waking immediately. • Mouse-wheel bursts can trigger a full repaint for every packet. • Raw SGR mouse fragments such as [<65;50;24M can leak into the composer.

Reproduction evidence

On the broken build, a real PTY input probe missed 32 of 40 keystrokes and had approximately 169 ms median latency.

With the proposed fix:

• 40 of 40 keystrokes were delivered. • Median latency was 0.254 ms. • P95 latency was 0.438 ms. • Under eight CPU burners, all 40 keystrokes were still delivered. • A 96-byte burst completed in 0.635 ms with only three draws.

The severity depends on terminal timing and conversation size, but the problematic code paths are deterministic.

Root causes

The investigation found three independent causes:

  1. Cache-hit telemetry performed transcript-linear byte estimation during rendering. This turns a nominal cache hit into work proportional to conversation size.

  2. Memory sidecar discovery performed credential and model resolution on the render path.

  3. Jcode mixed Crossterm’s asynchronous EventStream with synchronous poll and read calls. This violates Crossterm’s single-reader requirement and can split terminal packets. Removing the synchronous drain without replacing its coalescing also caused one full repaint per queued wheel or keyboard event.

The input reader also needed to preserve partially consumed Escape sequences across cancellation inside Tokio select calls. Otherwise a redraw or bus event could cancel the read and lose part of the terminal packet.

Proposed fix

I prepared an isolated branch with three commits:

https://github.com/apierron/jcode/tree/fix/tui-terminal-interactivity-lag

Comparison against upstream:

https://github.com/1jehuang/jcode/compare/master…apierron:fix/tui-terminal-interactivity-lag

Commits:

• be511853: Keep cache-hit metrics constant-time. • f057724a: Move sidecar discovery off the render path. • 8c530734: Use one bounded, cancellation-safe terminal reader and coalesce ready input before redrawing.

The branch changes only TUI code, adds no dependencies, and separates the three root causes into independent commits.

Validation

• Eight terminal-reader tests pass, covering ordering, cancellation, Escape deadlines, bounded lossless backpressure, prompt wakeups, coalescing, and task shutdown. • Three focused render-path and cache tests pass. • Formatting, Cargo check, and the Jcode TUI build pass. • The changed files match the previously runtime-tested build. • An independent review found no blocking correctness or scope issues. • The full TUI suite still has existing environment and global-state failures, but the fix branch introduces no branch-only failures compared with the same suite on upstream master.

Platform scope

This was reproduced on macOS, but most of the problem is not macOS-specific:

• Transcript-linear cache work is platform-independent. • Blocking sidecar discovery during rendering is platform-independent. • The mixed-reader violation exists in shared, non-platform-gated Jcode code. • Fragmented SGR mouse reports are a Unix and Crossterm behavior, so the raw mouse-text symptom is most likely on macOS and Linux. • Terminal implementation and OS scheduling can change how severe the lag appears.

I have not run the final branch through equivalent real-terminal measurements on Linux or Windows, so identical reproduction there is not yet confirmed.

apierron avatar Jul 22 '26 02:07 apierron

Thanks for the deep investigation and the prepared branch. The three root causes (transcript-linear cache-hit telemetry, sidecar discovery on the render path, mixed sync/async terminal readers) are plausible and the measurements are compelling. Since the terminal-reader rework touches core input handling across platforms, this needs maintainer review rather than an automated merge. Flagged for @1jehuang to review your branch fix/tui-terminal-interactivity-lag — opening it as a PR against master would make review easier.


— Jcode agent (automated triage), on behalf of @1jehuang

1jehuang avatar Jul 22 '26 10:07 1jehuang

Confirmed the raw mouse-text symptom on Linux (Debian 13), jcode v0.55.0, Ghostty over SSH.

The composer received fragments such as [<34;60;35M; the apparent alignment/render corruption was downstream wrapping from those injected SGR 1006 mouse reports. The current practical workaround is:

[display]
mouse_capture = false

A full client exit is important: jcode's exec handoff can preserve mouse=1 across a live reload. Exit every jcode TUI client, run reset in the affected terminal, then start jcode again. This eliminated the leaked packets in the repro.

Trade-off: jcode-specific mouse clicking/wheel scrolling may be unavailable; keyboard scrolling still works. This should be useful until the single-reader/cancellation-safe input fix is merged and released.

0p9b avatar Jul 23 '26 16:07 0p9b

Fix ready on fork (cannot open PR — collaborators-only)

Upstream appears to restrict PR creation to collaborators (Only collaborators can create PRs), so this can't be submitted via the normal fork → PR flow.

Branch

https://github.com/srineshr1/jcode/tree/fix/tui-terminal-interactivity-lag

Compare: https://github.com/1jehuang/jcode/compare/master...srineshr1:fix/tui-terminal-interactivity-lag

Commit: 7d09bbd6 — fix(tui): restore input latency in long sessions (fixes #540)

What it does (matches the three root causes in this issue)

  1. Constant-time cache-hit metrics — reuse stored prepared_bytes instead of re-walking the transcript on every hit.
  2. Sidecar discovery off the render path — no Sidecar::new() / credential+model resolution during paint; only in background gather_memory_info_inner.
  3. Single cancellation-safe terminal reader — new terminal_events::EventStream as sole Crossterm reader; reassemble fragmented SGR mouse reports; drop sync poll/read drain; coalesce ready input (up to 32) before redraw.

Based on the investigation/branch notes from @apierron, rebased onto current master.

Validation

  • cargo check -p jcode-tui
  • cargo build -p jcode-tui
  • 11 focused tests (8 terminal-reader + sidecar-off-render-path + no-sync-reader + full-prep cache hit bytes)

Happy to adjust if you want a different packaging (cherry-picks, maintainer-authored PR, collaborator invite, etc.).

srineshr1 avatar Jul 24 '26 10:07 srineshr1

Re-measured on v0.56.34-dev (Linux, real PTY, 120x40) to see what is left after the render/input work that landed since this was filed.

What is fixed

Keystroke delivery and latency. Your report measured 32 of 40 keystrokes missed at ~169 ms median. Current build, 40 keystrokes fed one at a time through a forked PTY:

condition wakes median p95 max
idle machine 40/40 0.035 ms 0.366 ms 329 ms (first keystroke only)
8 CPU burners 40/40 2.230 ms 5.680 ms 6.306 ms

No drops in either condition, and the p95 under 8 burners is ~30x better than your idle-case median on the broken build. The 329 ms max is a one-off on the very first keystroke (initial layout), not steady state.

Relevant changes: handle_terminal_event in crates/jcode-tui/src/tui/app/local.rs now drains up to 32 queued events per wake instead of one-per-redraw-tick, Event::Mouse(Moved) returns early without a redraw, and 66b3e621c fix(perf): suppress retry and redraw amplification plus 950512306 perf(tui): attribute slow render phases cut the render-path work.

Small scroll bursts no longer amplify. A 96-byte wheel burst (8 SGR reports in a single write) produced 1 draw / 328 bytes, against an idle baseline of 1 draw / 41 bytes over the same 2 s window. That matches the "96-byte burst, three draws" target in your proposed fix.

What is still open

1. Large wheel bursts still amplify badly. Scaling the same test to 960 bytes (80 SGR reports in one write) produced 139 draws / 3280 bytes in 2 s, versus 1 draw at 96 bytes. That is superlinear: 10x the input for ~139x the draws. So the per-packet repaint is coalesced at small burst sizes but not at the sizes a fast/inertial wheel or a trackpad actually generates. This is the remaining half of the original complaint and is worth a scroll-event coalescing pass that collapses queued scroll deltas into one viewport update per frame.

2. No guard against SGR mouse fragments reaching the composer. I could not reproduce the [<65;50;24M leak here (splitting one report across two writes 300 ms apart did not surface it), but there is also no defense: apply_terminal_event forwards Event::Key straight to handle_key_press_event, and insert_input_text in crates/jcode-tui/src/tui/app/input.rs accepts whatever arrives with no filtering of control/CSI sequence remnants. Whether a fragment becomes text depends entirely on how crossterm's parser resynchronizes on a torn read, which is terminal- and timing-dependent, consistent with you seeing it and me not. A cheap belt-and-braces fix is to drop CSI-fragment-shaped runs at the composer insertion boundary.

Suggest keeping this open scoped to those two items and dropping the latency/keystroke-loss part, which now measures clean.

Probe scripts are throwaway PTY harnesses; happy to contribute them as a committed bench if useful.

1jehuang avatar Jul 25 '26 02:07 1jehuang

Correction to my previous comment. I need to retract the "large wheel bursts still amplify badly" finding. It was a measurement artifact, and the code is behaving correctly.

I had counted read() wakeups on the PTY and treated each as a repaint. That is wrong. Measured against a genuine full repaint (forced via TIOCSWINSZ + SIGWINCH) for scale:

condition reads total bytes bytes/read
idle 2s 0 0 -
one full repaint 7 4642 663
960 B wheel burst (80 SGR reports) 239 4298 18

At ~18 bytes per write these are tiny incremental cursor/line updates, not full repaints. The entire 80-notch burst emits 0.93x the bytes of a single repaint, so the total terminal work is less than one screen redraw. The many small writes are the intended smooth-scroll momentum animation: enqueue_mouse_scroll coalesces notches into mouse_scroll_queue (clamped at MOUSE_SCROLL_MAX_QUEUE = 30), and mouse_scroll_drain_amount eases it out at 3 → 2 → 1 lines per frame. That is a deliberate feel decision, correctly implemented, and my "139x draws for 10x input" framing compared a per-frame animation step against a per-burst repaint. Apples to oranges. Apologies for the noise.

I also checked the thing users actually feel, namely whether scroll momentum starves typing. It does not. Typing 20 keystrokes during an active 80-notch momentum animation:

  • 20/20 delivered
  • median 0.063 ms, p95 0.081 ms, max 0.115 ms

So on current master I can find no remaining scroll-performance problem, and no reproducible input degradation.

Revised status of this issue: the keystroke loss and latency you reported (32/40 missed, ~169 ms median) are fixed and measure clean, and the scroll-burst concern does not reproduce. The one genuinely open item from my audit is the missing SGR-fragment guard: nothing filters CSI-sequence remnants at the composer insertion boundary (insert_input_text in crates/jcode-tui/src/tui/app/input.rs), so whether a torn mouse report leaks as text depends on how crossterm resynchronizes. I could not reproduce the leak, which is consistent with it being terminal- and timing-dependent, so it is a hardening opportunity rather than a confirmed live bug.

Suggest either closing this as fixed, or narrowing it to the fragment guard alone.

1jehuang avatar Jul 25 '26 03:07 1jehuang

The remaining item is now fixed: e2bfa6388 adds the missing SGR-fragment guard.

strip_terminal_control_sequences runs at insert_input_text, the single boundary every composer insertion path shares (typing, paste, Shift+Enter, drag-drop), so nothing needs to be remembered per call site. It removes ESC-introduced sequences, 8-bit CSI introducers, truncated escapes, and stray C0 controls while preserving tab and newline.

The interesting design constraint was avoiding a cure worse than the disease. A naive "strip anything CSI-shaped" rule would eat array[0], since [0] is a valid CSI body plus final byte. So a bare run, one whose ESC was consumed by the torn read, is only stripped when it is unmistakably a terminal report: [, at least one parameter byte drawn from digits/;/<, and a final byte from the set the modes we actually enable emit (M/m mouse, ~ bracketed paste, R cursor position, I/O focus). Missing a remnant is cosmetic; eating a user's characters is not, so the rule errs toward keeping text.

Tests cover both directions:

  • 13 remnant cases strip to empty, including [<65;50;24M, [<65;50;24m, [200~, [201~, [12;40R, [1I, [1O, the 8-bit introducer form, and a truncated \x1b[<65;5.
  • 16 real-text cases are preserved verbatim: array[0], list[1] = list[2], [TODO] fix this, fn f(v: Vec<u8>) -> [u8; 4], match x { [a, b] => a + b }, [12;40], bare [, ], emoji/accents, and more.
  • Non-suspicious input still returns Cow::Borrowed, so the common path does not allocate.

cargo test -p jcode-tui --lib input and ... paste are green (155 tests), and I diffed the full --lib failure set against a stashed baseline: zero failures unique to this change (the ~20 pre-existing failures on this tree belong to unrelated in-flight work, and two of them incidentally pass with this change applied).

With this landed, everything I could substantiate on this issue is addressed: keystroke loss and latency measure clean, the scroll-burst concern was my measurement error and is retracted above, and the fragment leak is now structurally prevented rather than left to parser luck. Suggest closing. Happy to reopen if you still see input degradation on a current build, ideally with the terminal and a rough session size.

1jehuang avatar Jul 25 '26 03:07 1jehuang

I found a separate long-session render-cache defect in v0.81.4 that is specific to display.pin_todos = true; this does not contradict the input and mouse fixes already discussed above.

render_message_into returns early for a pinned todo tool message before appending that message's segment boundary. The segment/hash table is then one entry shorter than display_messages. After the first todo call, append-only prefix reuse compares the wrong message boundaries and falls back to preparing the full transcript on every frame.

Measured on one day of local logs:

  • 3,513 of 3,780 slow frames were affected
  • 347 seconds of aggregate prepare time
  • median prepare time rose from 43 ms to 204 ms as transcripts grew
  • 4 of 4 inspected sessions froze their reusable prefix at the first todo index

The minimal local fix keeps the todo card visually suppressed but records a zero-line segment boundary. A regression named pinned_todo_tool_keeps_prefix_cache_boundaries_aligned passes, as does the full default-thread jcode-tui --lib suite.

This can be handled as a narrow follow-up under this issue or split into a dedicated pin_todos cache issue.

ianalitis avatar Sep 02 '26 02:09 ianalitis

Windows confirmation is now filed as #1527 (jcode v0.88.0, Windows 11 build 26200, Orca ADE 1.4.212 embedded xterm.js/ConPTY terminal).

akhan157 avatar Sep 26 '26 22:09 akhan157