Repository navigation
fix(mobile): render the terminal caret for main-buffer TUIs (Claude Code) - #11387
Conversation
📝 WalkthroughWalkthroughUpdates xterm initialization with shared mobile caret options, immediate cursor display, and block inactive cursor rendering. Extends terminal option assertions and adds tests for caret visibility, hiding through control sequences, DOM rendering, and event-listener cleanup across repeated terminal lifecycles. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
| const terminal = new Terminal(options as never) | ||
| const { coreService } = ( | ||
| terminal as unknown as { | ||
| _core: { coreService: { isCursorHidden: boolean; isCursorInitialized: boolean } } | ||
| } | ||
| )._core | ||
| return { | ||
| hidden: () => coreService.isCursorHidden, | ||
| initialized: () => coreService.isCursorInitialized, | ||
| write: (data) => new Promise<void>((resolve) => terminal.write(data, resolve)) | ||
| } |
There was a problem hiding this comment.
Real Terminal not disposed after each test
caretGate allocates a real @xterm/xterm Terminal but never calls terminal.dispose(). The object is kept alive by the closures returned to the test, so it leaks after each invocation. In happy-dom it probably does not cause failures today, but it grows unbounded memory across test runs and can mask teardown-related flakiness. Returning a dispose helper and calling it in afterEach, or using a module-level afterEach register inside caretGate, would fix this cleanly.
There was a problem hiding this comment.
Resolved by the rewrite in aefcc0ad6. The caretGate helper is gone — the caret gate is now exercised in mobile/src/terminal/terminal-caret-rendering-oracle.test.ts, where the real Terminal is disposed in a finally block. A second test additionally runs 25 construct/open/dispose cycles and asserts every registered event listener is released, so a leaked terminal would fail the suite rather than accumulate silently.
| const { coreService } = ( | ||
| terminal as unknown as { | ||
| _core: { coreService: { isCursorHidden: boolean; isCursorInitialized: boolean } } | ||
| } | ||
| )._core |
There was a problem hiding this comment.
Private xterm internal API access
terminal._core.coreService is not part of xterm's public surface. If xterm renames, restructures, or removes _core or coreService in a future patch, the access silently resolves to undefined, and .isCursorInitialized / .isCursorHidden return undefined rather than a boolean — making both toBe(true) and toBe(false) assertions pass regardless of the actual terminal state. Adding a vitest expect(coreService).toBeDefined() guard at the top of caretGate would make the fragility explicit and catch the breakage loudly when xterm is upgraded.
There was a problem hiding this comment.
Resolved by the rewrite in aefcc0ad6. The private-API access now lives in cursorCoreService() in mobile/src/terminal/terminal-caret-rendering-oracle.test.ts and is guarded exactly as suggested: _core, _core.coreService, and the boolean type of both isCursorHidden and isCursorInitialized each get their own labelled expect. An xterm upgrade that restructures _core fails loudly instead of letting toBe(true)/toBe(false) both pass on undefined.
Greptile SummaryThis PR fixes an invisible terminal caret on mobile for main-buffer TUIs (Claude Code, and any other app that never enters the alt screen via DECSET 1049). The root cause is that xterm's renderers gate every caret draw on
Confidence Score: 5/5Two constructor-time constants inside the mobile WebView document; no PTY, IPC, auth, or desktop path is touched. Safe to merge. The change is two option literals and one new option in a single WebView initializer. The root cause analysis is verified directly by the new oracle test. All three paths — alt-screen TUIs, DECTCEM hide, and listener cleanup across 25 lifecycles — are covered by tests. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| mobile/src/terminal/terminal-webview-html.ts | Extracts cursor options into MOBILE_TERMINAL_CARET_OPTIONS, adds showCursorImmediately: true to fix the isCursorInitialized gate, and changes cursorInactiveStyle from 'bar' to 'block' so the caret survives the phone-fit CSS scale. |
| mobile/src/terminal/terminal-caret-rendering-oracle.test.ts | New test file; uses a real xterm Terminal to verify isCursorInitialized, DOM caret presence, DECTCEM hide, and full listener-cleanup across both a single lifecycle and 25 repeated lifecycles. |
| mobile/src/terminal/terminal-webview-init-surface.test.ts | Adds showCursorImmediately to the stub type and updates the option-matching assertion to reflect cursorInactiveStyle: 'block' and showCursorImmediately: true. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Mobile WebView creates xterm Terminal] -->|showCursorImmediately: true| B[isCursorInitialized = true immediately]
A -->|Before this PR| C[isCursorInitialized = false]
B --> D{DECTCEM escape sequence?}
C --> E[Cursor gate never opened]
E --> F[No caret rendered]
D -->|ESC 25h SHOW| G[isCursorHidden = false]
D -->|ESC 25l HIDE| H[isCursorHidden = true]
G --> I{Terminal focused?}
H --> J[Caret hidden]
I -->|Yes - never on mobile| K[Render cursorStyle: bar]
I -->|No - always on mobile| L[Render cursorInactiveStyle: block]
L --> M[Full block cell - survives phone-fit CSS scale]
K --> N[bar - 1 physical px after 0.4x scale - invisible]
Reviews (3): Last reviewed commit: "test(mobile): keep caret oracle teardown..." | Re-trigger Greptile
The mobile WebView never flipped xterm's isCursorInitialized, which both renderers check before they ever read cursorStyle/cursorInactiveStyle. The native TextInput owns keyboard focus and xterm's textarea is inert, so the focus and keydown paths never fire, leaving DECSET 1049 as the only way to flip it. Alt-screen TUIs got a caret as a side effect; Claude Code, which redraws its composer in the main buffer, never did. Set showCursorImmediately so the caret does not depend on focus, and switch cursorInactiveStyle to block: mobile is permanently unfocused, so that option is what renders, and a bar is dpr device px wide and disappears under the fit scale() the WebView applies. Refs stablyai#8313, stablyai#7093
6a2f629 to
d5eb97b
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
mobile/src/terminal/terminal-caret-rendering-oracle.test.ts (1)
164-172: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssertions in
finallycan mask the real failure and skip DOM cleanup.If a body assertion fails, a failing
expecthere replaces the original error. Worse,container.remove()(Line 171) never runs when any preceding assertion throws, leaking nodes into sibling tests. Keepfinallyto teardown only and assert afterwards.♻️ Proposed restructure
} finally { terminal.dispose() - expect(container.querySelector('.xterm')).toBeNull() - const cleanup = listenerCleanup() - expect(cleanup.added).toBeGreaterThan(0) - expect(cleanup.removed).toBe(cleanup.added) - expect(cleanup.unreleased).toEqual([]) container.remove() } + + expect(container.querySelector('.xterm')).toBeNull() + const cleanup = listenerCleanup() + expect(cleanup.added).toBeGreaterThan(0) + expect(cleanup.removed).toBe(cleanup.added) + expect(cleanup.unreleased).toEqual([])
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7a3563a1-650e-4d6d-b3ea-fae61e873278
📥 Commits
Reviewing files that changed from the base of the PR and between 6a2f6294cba17a8fcc9a42ad36f62af1c24044f9 and d5eb97b.
📒 Files selected for processing (3)
mobile/src/terminal/terminal-caret-rendering-oracle.test.tsmobile/src/terminal/terminal-webview-html.tsmobile/src/terminal/terminal-webview-init-surface.test.ts
|
@coderabbitai Good catch — applied in The two Greptile P2 comments on |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -euo pipefail
git show --stat --oneline --decorate --no-renames c26d22bb7
git show --format=fuller --no-ext-diff --unified=35 c26d22bb7 -- \
mobile/src/terminal/terminal-caret-rendering-oracle.test.ts \
mobile/src/terminal/terminal-webview-init-surface.test.ts
printf '\n--- test file outline ---\n'
ast-grep outline mobile/src/terminal/terminal-caret-rendering-oracle.test.ts --items all --view expanded
printf '\n--- caretGate occurrences ---\n'
rg -n -C2 '\bcaretGate\b' mobile/src/terminal || trueLength of output: 5042
Also confirmed that 🐇✅ If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! You are interacting with an AI system. |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
mobile/src/terminal/terminal-caret-rendering-oracle.test.ts (1)
177-186: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winGuarantee cleanup for failed lifecycle iterations.
If
terminal.open()or the assertion throws, this loop skipsterminal.dispose()andcontainer.remove(), leaking state into later tests. Use the sametry/finallycleanup pattern as the preceding test.Proposed fix
- terminal.open(container) - terminal.dispose() - expect(container.querySelector('.xterm')).toBeNull() - container.remove() + try { + terminal.open(container) + } finally { + terminal.dispose() + container.remove() + } + expect(container.querySelector('.xterm')).toBeNull()
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 464a8ef4-82d6-4db9-9696-ad13b3685cec
📒 Files selected for processing (1)
mobile/src/terminal/terminal-caret-rendering-oracle.test.ts
…ode) (stablyai#11387) * fix(mobile): render the terminal caret for main-buffer TUIs The mobile WebView never flipped xterm's isCursorInitialized, which both renderers check before they ever read cursorStyle/cursorInactiveStyle. The native TextInput owns keyboard focus and xterm's textarea is inert, so the focus and keydown paths never fire, leaving DECSET 1049 as the only way to flip it. Alt-screen TUIs got a caret as a side effect; Claude Code, which redraws its composer in the main buffer, never did. Set showCursorImmediately so the caret does not depend on focus, and switch cursorInactiveStyle to block: mobile is permanently unfocused, so that option is what renders, and a bar is dpr device px wide and disappears under the fit scale() the WebView applies. Refs stablyai#8313, stablyai#7093 * test(mobile): prove main-buffer caret rendering * test(mobile): calibrate terminal listener cleanup * test(mobile): keep caret oracle teardown assertion-free --------- Co-authored-by: OrcaWin <[email protected]>
…st focus (#41736) * fix(terminal): draw the hardware cursor in remounted panes before first focus xterm withholds the cursor until its textarea gets a focus event or a keystroke. A remounted pane (reload, reattach) keeps DOM focus, so no event fires and TUIs that use the hardware cursor, like agy, show no cursor until the next keypress. Set showCursorImmediately so DECTCEM alone decides visibility, matching the mobile fix in #11387. * test(terminal): drop xterm-behavior cases and casts from cursor init test
Summary
The mobile terminal renders no caret for TUIs that draw in the main buffer — Claude Code being the one users hit every day. #10101 changed
cursorInactiveStylefrom'none'to'bar'and closed #8313 (iPhone) and #7093 (Android) on that basis, but that value is never reached: both the WebGL and DOM renderers gate every caret draw oncoreService.isCursorInitializedbefore they readcursorStyle/cursorInactiveStyle, and the mobile WebView never flips it.isCursorInitializedflips true in exactly four places:showCursorImmediatelyfalse— never set_handleTextAreaFocus_keyDown/_keyPresson that textareaTextInputowns keyboard focusInputHandler, on DECSET/DECRST 1049So alt-screen TUIs (vim, opencode) get a caret because entering the alt screen flips the flag as a side effect, and Claude Code — which redraws its composer in the main buffer and never emits 1049 — never gets one. That matches the reports exactly: #8313 notes the caret shows fine in Orca for macOS but never on iPhone or iPad.
This sets
showCursorImmediately: true, the option xterm provides for exactly this case: a host that owns focus itself.Second change:
cursorInactiveStyle'bar'→'block'. Because mobile is permanently unfocused,cursorInactiveStyle— notcursorStyle— is what actually renders. In the WebGLRectangleRenderer.updateCursor, abaris drawndpr * cursorWidthdevice px wide, and the WebView then shrinks the whole surface with the fitscale()(min(1, innerWidth / termWidth), roughly0.4for a 120-column session on a phone). That leaves the caret about one physical pixel of blended color.blockgoes through the glyph inversion path and fills the cell, so it survives the scale. Application cursor hiding (DECTCEM) is still honored either way, and there is a test for that.Screenshots
Claude Code v2.1.220 on an iPhone 17 Pro simulator (iOS 26.5). Two pairs, each the same composer row in the same session with only this fix toggled:
mainas it stands today, after fix(mobile): keep terminal caret visible without focus #10101: no caret anywhere on the row.T.Test— the insertion point is invisible.Test— the caret sits on the insertion point.The second pair is the case #8313 called out directly: with no caret you cannot tell where the next character lands, which is worst after moving the insertion point with arrow keys.
Captured by pointing Metro at this branch and reverting only
terminal-webview-html.tstoHEAD~1for the "before" frames, letting Fast Refresh rebuild the WebView between shots. A physical-device capture is still worth adding, since thebar→blockhalf is about subpixel rendering under the fit scale.Testing
pnpm lintpnpm typecheckpnpm testpnpm buildmobile:pnpm lint,pnpm typecheck,oxfmt --check, andpnpm test(354 files, 2600 passed) are all clean.Root
pnpm testreports 8 pre-existing failures unrelated to this PR — they arewindow.localStorage/ DOM-environment failures (e.g.browser-pane/markup/use-markup-draw-hint.test.ts) under the root config'senvironment: 'node'. Verified by running the same file on a cleanupstream/mainworktree with no changes applied, where it fails identically. The root Vitestincludeglobs (src/**,config/scripts/**,tools/**,tests/e2e/**.unit.test.ts) do not covermobile/, so this change cannot reach that suite.Why the existing test passed through the bug
The test #10101 added asserts the option literals on the object handed to
new Terminal(...), using a stub that never instantiates xterm. Changing an option value therefore always passes it, whether or not a caret is ever drawn. This PR keeps that surface-replacement coverage and additionally feeds the captured options to a real xterm, asserting the gate the renderers actually read:draws a caret for a main-buffer TUI that never enters the alt screen— replays a Claude-style main-buffer redraw (\x1b[?25h, erase, cursor positioning, no 1049) and assertsisCursorInitialized === trueandisCursorHidden === false.still lets a TUI hide the caret with DECTCEM— asserts\x1b[?25lstill hides the caret, so this does not force a caret onto TUIs that intentionally hide it.Removing only
showCursorImmediatelyfrom the fix fails the new test withexpected false to be trueonisCursorInitialized, so the test captures the reported bug rather than restating the change.One honest gap: the
bar→blockhalf is a GPU rasterization property and has no automated assertion. It rests on theupdateCursorgeometry above plus the screenshots.AI Review Report
Reviewed with Claude Code. Risks checked and findings:
orca serveover Tailscale) is covered by the same fix. No shortcuts, labels, path handling, shell behavior, or Electron-specific code is touched; nometaKey/CmdOrCtrlor path-separator surface is involved. Desktop renderer paths are byte-identical.showCursorImmediately: truemeans a freshly opened, still-empty terminal shows a caret at the home position immediately, which is what a real terminal does. DECTCEM suppression is unchanged and now has a regression test.cursorStyleis also set to'block'for consistency, though on mobile it is only read when xterm is focused, which does not happen today.Security Audit
No input handling, command execution, path handling, auth, secrets, dependency, or IPC surface changes. The diff is two option literals plus one added option in a WebView document, and one test file. No new dependencies (
@xterm/xtermis already a mobile dependency; the test imports it). No untrusted input is parsed — the escape sequences in the test are hardcoded constants — and nothing new is injected into the WebView HTML. No follow-up needed.Notes
main. The repro attempt on [Bug] No caret visible on Claude Code on iPhone #8313 was explicitly recorded as environment-blocked (no iOS device available), so the fix was never checked against a running app.TerminalSettingsPreview.tsx(its own comment states the preview is never focused) anddashboard-popout/preview-terminal-options.ts— setcursorInactiveStylebut likewise never setshowCursorImmediately, so they may sit behind the same gate. Left out to keep this PR to one topic.