Skip to content

fix(terminal): count emoji and sequences in cells as herdr does - #273

Merged
devswha merged 4 commits into
mainfrom
fix/terminal-unicode-widths
Oct 1, 2026
Merged

devswha merged 4 commits into
mainfrom
fix/terminal-unicode-widths

Conversation

@devswha

@devswha devswha commented Oct 1, 2026

Copy link
Copy Markdown
Owner

Change

Fixes the emoji part of #268. herdr lays out its grid with current Unicode widths. Its attach
stream relies on the browser's xterm moving the cursor exactly as far as herdr does. xterm
defaults to Unicode 6 widths, which disagree on most emoji:

After each such emoji the rest of the line shifted: the next letter overlapped the emoji, and
stray characters from the previous frame stayed behind. Agents print ✅ ⚠️ 🚀 all the time.

src/lib/terminalWidths.ts registers a Unicode provider that matches herdr's widths. It builds
on @xterm/addon-unicode-graphemes, which adds Unicode 15 widths and joins emoji sequences into
one cell. That addon disagrees with herdr in three places, and the provider corrects each one:

addon herdr correction
spacing marks (Thai SARA AM in น้ำ, Devanagari का) joined into the letter's cell a cell of their own a spacing mark starts a new cell, as it does under Unicode 6 today
Unicode 14 and 15 emoji (🫠 🫡 🫨 🩷) 1 cell (its tables predate them) 2 an emoji the browser marks as emoji-presentation is handled like a known 2-cell emoji (U+1F600), so it joins sequences the same way
invisible format characters (ZWSP, LRM, RLO, word joiner, Hangul filler) 1 cell 0 joins the cell before it, like ZWNJ

The addon's providers are reached only through terminal.unicode.register. To get one,
herdrWidthProvider() activates the addon on an object that only collects what it registers;
the addon touches nothing else. Each code point is classified once and cached, and code points
below U+034F skip the check entirely.

About the addon version. @xterm/addon-unicode-graphemes exists only as 0.4.0, released
together with xterm 6.0. It declares no peer dependency. It relies on charProperties, which
xterm 5.5 already has, and the property encoding is the same in 5.5. Both the headless and the
browser runs below use our @xterm/xterm 5.5.0. The 0.8.0 addon-unicode11 was also tried: it
still disagreed on 15 of the 62 samples (VS16, ZWJ, skin tones, keycaps, Unicode 12+).

Validation

  • herdr's widths, measured. Each of 62 samples was printed in a herdr 0.9 pane, followed by a
    DSR query (ESC[6n). herdr's emulator answers with its cursor column. The samples were then
    replayed in xterm 5.5 headless. Disagreements with herdr:

    xterm with disagreements
    Unicode 6 (today) 17
    addon-unicode11 15
    addon-unicode-graphemes 19
    this provider 2

    The 2 left are a + U+FE0F (a VS16 after a letter that isn't emoji) and a lone combining
    mark at column 0. Unicode 6 gets both of these wrong today too.

  • src/lib/terminalWidths.test.ts checks 16 of those herdr answers against the provider in a
    real xterm Terminal, plus a test that 👨‍👩‍👧 stays whole in one cell with the next letter at
    column 2. bun run typecheck, bun run build, bun run test:unit (715 pass) and
    generate:types --check all pass.

  • Browser (desktop Chrome and the iOS 27 simulator), on a pane in an isolated herdr session:

    • 🤖ab, 🥰ab🫠cd, 👨‍👩‍👧x🇰🇷y and 😀👍✅x now line up with herdr.
    • The family emoji draws as a single glyph, and the closing | set with ESC[36G stays in its
      column. Before, the ZWJ row shifted it one column right and left a stray d after 🫠.
  • Cost: on a pane printing mixed CJK, emoji-free lines as fast as flow control allows, Chrome
    script time over 8s went from 0.60s to 0.64s.

  • Size: the addon adds 34KB to the bundle, 15KB gzipped.

Independent of #272. Both add a line to the changelog, at different places, so they merge in
either order.

@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: devswha/herdr-web-ui/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 756922a6-a145-4ea8-a54b-13e9dc71a473

📥 Commits

Reviewing files that changed from the base of the PR and between c08f952 and 5bffdc7.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock, !bun.lock
📒 Files selected for processing (2)
  • CHANGELOG.md
  • src/components/PaneTerminal.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Summary

Summary by CodeRabbit

  • Bug Fixes
    • Improved terminal alignment for emoji, emoji sequences, and text in Thai and Indic scripts.
    • Invisible characters are now counted consistently, helping keep terminal content in the correct positions.
    • Unicode characters that combine or occupy multiple terminal cells are handled more consistently, reducing shifted or overwritten text.

Walkthrough

The terminal now uses a custom xterm Unicode width provider that applies corrections to match herdr. PaneTerminal activates the provider, and tests compare cursor positions with herdr reference counts.

Changes

Terminal width matching

Layer / File(s) Summary
Custom Unicode width provider
package.json, src/lib/terminalWidths.ts
Adds the grapheme addon dependency and a provider that corrects widths and character properties for newer emoji, spacing marks, and invisible characters.
Terminal activation and validation
src/components/PaneTerminal.tsx, src/lib/terminalWidths.test.ts, CHANGELOG.md
PaneTerminal registers and selects the custom provider. Tests compare cursor positions with herdr reference counts, and the changelog describes the rendering corrections.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~12 minutes

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: yoonwoo-ha

Merge Risk: ⚪ Minimal · up to 5bffd

This change aims to align terminal cell placement for emoji and other Unicode text. No actionable failure is established, so it appears mergeable with normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 5bffd

The change is confined to browser terminal rendering and does not add command privileges or a new network interface. No introduced security vulnerability was established. Remaining uncertainty concerns dependency compatibility and the effect of corrected rendering on existing secret-prompt detection.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Attacker-influenced PTY text can reach the new measurement callbacks through terminal rendering. Provider state and its classification cache are per construction, bounding the directly observed changed state to individual browser terminal instances rather than a shared server store.

Trust Boundaries and Controls

  • observed — The addon is activated on a collector exposing the Unicode registration interface rather than the live terminal. The application’s returned provider exposes width and character-property callbacks; socket input and link opening remain separate component paths.
  • inferred — The secret-input safeguard has an indirect dependency on rendering: secretPrompt examines reconstructed screen lines and a column-based continuation heuristic. The PR leaves that detector unchanged, but equivalence across newly corrected widths and wrapping remains unverified rather than established as safe or vulnerable.

Resilience and Maintainability Implications

  • inferred — A provider-construction failure can interrupt local terminal initialization before cleanup registration, but it occurs before the socket is created or attached. The inspected path therefore does not demonstrate a stranded privileged connection or insecure fallback.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 3 files. (1 skipped: 1… 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 clearly and concisely describes the main change: matching herdr cell widths for emoji and emoji sequences in the terminal.
Description check ✅ Passed The description includes the required Change and Validation sections. It explains the problem, resulting behavior, implementation, test coverage, browser validation, performance impact, and bundle-siz…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 3 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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

@devswha

devswha commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Checked together with #272: this branch merges into fix/terminal-wide-glyph-centering with no conflict. The import now sits beside the other terminal helpers, so the two PRs no longer touch adjacent lines. On the merged tree, typecheck passes, test:unit passes (725 tests) and the build succeeds. Either PR can merge first.

devswha added a commit that referenced this pull request Oct 1, 2026
…iPhone (#272)

## Change

Fixes the main part of #268. On an iPhone, Korean in the terminal looked
spread apart. The
cell grid is built from Menlo's 0.6em width, so two cells are 1.2em. iOS
has no font that draws
Hangul wider than 0.87em. xterm's DOM renderer fills the leftover 0.33em
with `letter-spacing`
after each glyph, so every syllable sat at the left edge of its cells
with a 4.4px gap after it
(at 13px). Japanese kana and kanji had the same problem, and Chinese had
a 2.7px gap.

`src/lib/terminalGlyphs.ts` adjusts each span the DOM renderer draws:

- **Enlarge narrow wide glyphs.** A glyph in two cells that fills less
than 90% of them is drawn
larger, up to 1.2×, until it fills 90%. On iPhone Hangul goes from 72%
of its slot to 87%;
  1em Han glyphs go to 90%. A glyph in one cell is never enlarged.
- **Center the glyph.** The spacing that is left is split before and
after the glyph. Padding
moves the text right, and a negative margin takes that back so the next
span keeps its column.
A `clip-path` trims the trailing half, so a background, an underline or
a block cursor stays on
  its own cells.
- **Compose decomposed text (NFC).** iOS Safari draws only the first of
two stacked marks on a
decomposed letter (`e` + U+0302 + U+0301), so Vietnamese from a Mac file
name showed `Tiêng` for
`Tiếng`. Text with combining marks, and decomposed Hangul, is now shown
composed. Copy reads
xterm's buffer, not the DOM, so it still returns the bytes the pane
wrote.
- **Draw text symbols as text.** iOS draws some symbols that are text by
default as a color
emoji, about two cells wide inside their one cell. ⏺, the bullet before
every Claude Code
message, became a blue square over the next character. Such a symbol,
when it overflows its
cell, now gets U+FE0E (text presentation). Its spacing is then measured
again.

The renderer rebuilds a row's spans on every render, and also on link
hover, which fires no render
event. A `MutationObserver` on `.xterm-rows` therefore catches every
span, and it runs before the
frame paints. Glyph widths come from a canvas `measureText`, cached per
character and font.

What doesn't change:
- Spacing up to 1px, or a glyph that already fills 90%, is left as
drawn. That covers CJK on Linux
  Chrome, where a 1em glyph fills 93%, so the desktop looks the same.
- A glyph wider than its cells, such as an emoji, is otherwise left to
run over, as in a native
terminal. Shrinking emoji to fit was tried and dropped: with xterm's
current Unicode 6 widths,
most emoji have one cell and came out tiny. The emoji problems in #268
come from those widths
  and are fixed in #273.

## Validation

- `bun run typecheck`, `bun run build`, `bun run test:unit` (708 pass).
The new
`src/lib/terminalGlyphs.test.ts` covers the fit math with the measured
iPhone numbers, the
Linux no-op, the one-cell glyph that is centered but never enlarged, the
cases that are left
alone, NFC for stacked marks and decomposed Hangul, and which symbols
get U+FE0E.
- iOS 27 simulator, Safari, 13px, against a pane in an isolated herdr
session. Before:
`다 람 쥐` (a gap after every syllable). After: syllables evenly spaced and
almost touching.
- Korean, Japanese and Chinese rows still line up with the `|` borders.
- A background run (`ESC[44m`) covers exactly its cells, and an
underline runs continuously.
  - Bold Hangul fits the same way.
  - Decomposed Vietnamese shows every mark (`Tiếng`, `ắ ằ ẳ ặ`).
- `⏺ ✻ ✔ ⎿ ●` shows ⏺ as a text circle in its own cell. Before, it was a
blue emoji
    covering `✻`.
  Screenshots were taken locally; I can attach them.
- Desktop Chrome (Linux): screenshots before and after look the same.
- Cost, measured on a pane printing mixed Korean, Japanese, Chinese and
Vietnamese lines as fast
as the flow control allows (Chrome, 8s window): script time 0.60s before
and about 0.8s after,
and total task time 3.1s before and about 3.3s after. Normal output
costs nothing measurable.
- Not checked: macOS Safari. Safari WebDriver could not open a window
over SSH. macOS uses the same
  Menlo and Apple SD Gothic Neo, so the same fix should apply there.
@devswha
devswha merged commit c49c167 into main Oct 1, 2026
11 checks passed
@devswha
devswha deleted the fix/terminal-unicode-widths branch October 1, 2026 14:56
devswha added a commit that referenced this pull request Oct 1, 2026
Release v0.3.40: moves the Unreleased notes under 0.3.40 and bumps
`package.json` and `herdr-plugin.toml`.

What's in it:
- Fixes from #249, #251, #252, #263, #264, #265, #267.
- The iPhone CJK and text-symbol fix (#272).
- Emoji cell widths matching herdr (#273).

Every changelog entry already ends with its PR link. All these PRs are
by @devswha, so no credits to add.

No remote bundle change: `REMOTE_BUNDLE_VERSION` stays 9. The Windows PC
part of #264 and #265 reaches a PC with the next remote bundle, as its
changelog entry says.
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.

1 participant