Skip to content

fix(mobile): render the terminal caret for main-buffer TUIs (Claude Code) - #11387

Merged
Jinwoo-H merged 4 commits into
stablyai:mainfrom
ye4241:fix/mobile-terminal-caret-cursor-initialized
Jul 30, 2026
Merged

Jinwoo-H merged 4 commits into
stablyai:mainfrom
ye4241:fix/mobile-terminal-caret-cursor-initialized

Conversation

@ye4241

@ye4241 ye4241 commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

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 cursorInactiveStyle from '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 on coreService.isCursorInitialized before they read cursorStyle / cursorInactiveStyle, and the mobile WebView never flips it.

isCursorInitialized flips true in exactly four places:

Path Mobile
Constructor, from showCursorImmediately defaults to false — never set
_handleTextAreaFocus xterm's textarea is deliberately inert
_keyDown / _keyPress on that textarea native TextInput owns keyboard focus
InputHandler, on DECSET/DECRST 1049 the only path left

So 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 — not cursorStyle — is what actually renders. In the WebGL RectangleRenderer.updateCursor, a bar is drawn dpr * cursorWidth device px wide, and the WebView then shrinks the whole surface with the fit scale() (min(1, innerWidth / termWidth), roughly 0.4 for a 120-column session on a phone). That leaves the caret about one physical pixel of blended color. block goes 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:

caret-before-after
  1. Before, idle composer — main as it stands today, after fix(mobile): keep terminal caret visible without focus #10101: no caret anywhere on the row.
  2. After, idle composer — a block caret sits on the placeholder's T.
  3. Before, after typing Test — the insertion point is invisible.
  4. After, after typing 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.ts to HEAD~1 for the "before" frames, letting Fast Refresh rebuild the WebView between shots. A physical-device capture is still worth adding, since the bar → block half is about subpixel rendering under the fit scale.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

mobile: pnpm lint, pnpm typecheck, oxfmt --check, and pnpm test (354 files, 2600 passed) are all clean.

Root pnpm test reports 8 pre-existing failures unrelated to this PR — they are window.localStorage / DOM-environment failures (e.g. browser-pane/markup/use-markup-draw-hint.test.ts) under the root config's environment: 'node'. Verified by running the same file on a clean upstream/main worktree with no changes applied, where it fails identically. The root Vitest include globs (src/**, config/scripts/**, tools/**, tests/e2e/**.unit.test.ts) do not cover mobile/, 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 asserts isCursorInitialized === true and isCursorHidden === false.
  • still lets a TUI hide the caret with DECTCEM — asserts \x1b[?25l still hides the caret, so this does not force a caret onto TUIs that intentionally hide it.

Removing only showCursorImmediately from the fix fails the new test with expected false to be true on isCursorInitialized, so the test captures the reported bug rather than restating the change.

One honest gap: the bar → block half is a GPU rasterization property and has no automated assertion. It rests on the updateCursor geometry above plus the screenshots.

AI Review Report

Reviewed with Claude Code. Risks checked and findings:

  • Cross-platform — the change is xterm constructor options inside the mobile WebView document, which iOS and Android share, so [Feature]: Show a clear cursor/caret in Android mobile terminal #7093 (Android, orca serve over Tailscale) is covered by the same fix. No shortcuts, labels, path handling, shell behavior, or Electron-specific code is touched; no metaKey/CmdOrCtrl or path-separator surface is involved. Desktop renderer paths are byte-identical.
  • Remote / SSH / local — client-side rendering only. No PTY, daemon, relay, snapshot, or rehydration path is touched, so local, remote-server, and SSH worktree sessions behave identically. Worth stating because both reporters were on remote runtimes; the missing caret was never a remote-transport problem.
  • Agent and provider neutrality — nothing keys off Claude Code. Any TUI that renders in the main buffer benefits, and alt-screen TUIs are unaffected since they already flipped the flag via 1049.
  • Behavior risk — showCursorImmediately: true means 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.
  • Performance — none. Two constructor-time constants; no per-frame or hot-path work, no new allocation, no added render passes.
  • Scope — cursorStyle is 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/xterm is 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

@ye4241
ye4241 marked this pull request as ready for review July 29, 2026 17:29
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Updates 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the mobile caret-rendering fix.
Description check ✅ Passed All required sections are present, and the summary, screenshots, testing, review, security, and notes are substantive.
Linked Issues check ✅ Passed The changes directly address #8313 by restoring visible caret rendering for mobile main-buffer TUIs and preserving caret hiding behavior.
Out of Scope Changes check ✅ Passed The diff stays focused on the caret fix and regression tests, with no obvious unrelated feature or refactor changes.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Comment on lines +34 to +44
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))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +35 to +39
const { coreService } = (
terminal as unknown as {
_core: { coreService: { isCursorHidden: boolean; isCursorInitialized: boolean } }
}
)._core

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This 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 isCursorInitialized, which is only flipped by paths that are all unreachable in the mobile WebView; showCursorImmediately: true is the option xterm provides for exactly this host scenario. The companion change from cursorInactiveStyle: 'bar' to 'block' prevents the caret from being rendered as a single sub-physical-pixel after the phone-fit CSS scale() transform.

  • terminal-webview-html.ts: Extracts the four cursor options into the exported MOBILE_TERMINAL_CARET_OPTIONS constant, adds showCursorImmediately: true, and changes cursorInactiveStyle to 'block'. The constant is injected verbatim into the WebView HTML via template literal, keeping the generated JS and the test in sync.
  • terminal-caret-rendering-oracle.test.ts (new): Runs a real xterm instance against the production options, verifying isCursorInitialized, DOM .xterm-cursor presence, DECTCEM hide, and full addEventListener/removeEventListener parity across both a single lifecycle and 25 repeated lifecycles — directly covering the memory-safety of the surface-replacement pattern used in production.

Confidence Score: 5/5

Two 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.

Important Files Changed

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]
Loading

Reviews (3): Last reviewed commit: "test(mobile): keep caret oracle teardown..." | Re-trigger Greptile

ye4241 and others added 3 commits July 29, 2026 18:35
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
@Jinwoo-H
Jinwoo-H force-pushed the fix/mobile-terminal-caret-cursor-initialized branch from 6a2f629 to d5eb97b Compare July 30, 2026 01:39

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
mobile/src/terminal/terminal-caret-rendering-oracle.test.ts (1)

164-172: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assertions in finally can mask the real failure and skip DOM cleanup.

If a body assertion fails, a failing expect here replaces the original error. Worse, container.remove() (Line 171) never runs when any preceding assertion throws, leaking nodes into sibling tests. Keep finally to 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.ts
  • mobile/src/terminal/terminal-webview-html.ts
  • mobile/src/terminal/terminal-webview-init-surface.test.ts

@ye4241

ye4241 commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai Good catch — applied in c26d22bb7. The finally block is now teardown only (terminal.dispose() + container.remove()), and the cleanup assertions moved after the try/finally. That stops a failing assertion from replacing the real body error and from stranding the container in the DOM for sibling tests.

The two Greptile P2 comments on terminal-webview-init-surface.test.ts were about the earlier caretGate helper, which no longer exists — both concerns are covered by terminal-caret-rendering-oracle.test.ts (real Terminal disposed in finally, a 25-cycle listener-release test, and explicit toBeDefined/typeof guards around the private _core.coreService access). Replied inline on both.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

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 || true

Length of output: 5042


@ye4241 Confirmed in c26d22bb7: the finally block is teardown-only, and the cleanup assertions now run after it. This preserves the original failure and guarantees container removal.

Also confirmed that caretGate no longer exists under mobile/src/terminal; the real-Terminal oracle and 25-cycle listener cleanup coverage are present. Thanks for the thorough follow-up.

🐇✅


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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Guarantee cleanup for failed lifecycle iterations.

If terminal.open() or the assertion throws, this loop skips terminal.dispose() and container.remove(), leaking state into later tests. Use the same try/finally cleanup 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

📥 Commits

Reviewing files that changed from the base of the PR and between d5eb97b and c26d22b.

📒 Files selected for processing (1)
  • mobile/src/terminal/terminal-caret-rendering-oracle.test.ts

@Jinwoo-H
Jinwoo-H merged commit 5cc21ad into stablyai:main Jul 30, 2026
1 check passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
nwparker added a commit that referenced this pull request Nov 13, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] No caret visible on Claude Code on iPhone

3 participants