Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(terminal): size an emoji followed by VS16 as two cells, like the writer does (#1182)
priitkustalab1f56a74e628
diff --git a/CLAUDE.md b/CLAUDE.mdindex e360f84aa..f832c8d10 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1522,6 +1522,23 @@ clamp** (`src/shared/scrollback.ts`, re-clamped inside the host for older clientsession) where tmux stores only used cells, and nothing above the renderer's cap is ever shown.tmux's `history-limit` keeps the raw value.+### Character widths — one table for every emulator (`@shared/terminal-width`)++Every xterm in the stack sizes characters through `activateTerminalWidths`: the renderer's+terminals (`renderer/terminal/unicode-width.ts`, which explains the move off Unicode 6) and the+Windows session host's headless emulator, which is what a reattaching viewer is repainted from.+The table is Unicode 11 plus one rule xterm's tables lack: **a one-cell emoji followed by VS16+(U+FE0F) is two cells**, as are the keycap sequences (`1️⃣`). The program writing to the pane+(`string-width` in every Node agent CLI) and tmux (`variation-selector-always-wide`, on by default)+both count those pairs as two cells; xterm counted one, and every repaint by absolute position after+such a character landed a column short and left stale text behind. Measured with claude-hud's+`⏱️` status line, which read `113` for `11%` and `2h 327` for `2h 32m`. VS15 is deliberately left+alone (`string-width` sizes `⭐︎` by its base, as xterm already does), and so is an ASCII base+with VS16 alone (`1️` is not an RGI emoji) and the unqualified keycap `1⃣` (one cell, as tmux sizes+it; some `string-width` releases say two). Known xterm limitation: in insert mode (IRM) a widened+join overwrites the next cell instead of shifting the line. Agreement is the goal, not a particular+number: change the table in that one module, never in one emulator.+## Terminal node lifecycle (gotchas)`src/renderer/nodes/TerminalNode.tsx` is the trickiest file:diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex d80d6a928..bb092ff53 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -534,6 +534,12 @@ anything else. Board-level fields survive every transform — `pullLinks` is onefeature, and a host that never negotiated it answers `{names}` — which a consumer must read as"named, not described", never as "detached" or "no processes".+- **Every xterm sizes characters through `activateTerminalWidths` (`src/shared/terminal-width.ts`).**+ The renderer's terminals and the session host's emulator must agree with each other, with tmux and+ with the agent CLIs about how many cells a character takes, or a repaint by cursor position leaves+ stale text behind (an emoji + VS16 did exactly that). Change widths there, never in one emulator,+ and test them on a real `@xterm/headless` terminal rather than on the provider's return values.+- **Finding a Windows executable is not the same as being able to spawn it.** A PATH lookup maycorrectly resolve an npm CLI to `<name>.cmd`, but Node's `execFile`/`spawn` cannot execute thatshim directly. For short-lived app-owned subprocesses, pass the resolved path and argv throughdiff --git a/src/renderer/terminal/unicode-width.test.ts b/src/renderer/terminal/unicode-width.test.tsindex 78ce8abb3..192869094 100644--- a/src/renderer/terminal/unicode-width.test.ts+++ b/src/renderer/terminal/unicode-width.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from 'vitest'import type { Terminal } from '@xterm/xterm'import { activateUnicode11 } from './unicode-width'+import { TERMINAL_WIDTH_VERSION } from '@shared/terminal-width'/*** These tests pin the FACT the 2026-08-05 emoji fix rests on, not the plumbing.@@ -52,13 +53,13 @@ function stubTerminal(): { term: Terminal; provider: () => WidthProvider; versio}describe('activateUnicode11', () => {- it('puts the terminal on the Unicode 11 table', () => {+ it('puts the terminal on the shared table (Unicode 11 + the VS16 rule)', () => {const t = stubTerminal()activateUnicode11(t.term)- expect(t.provider().version).toBe('11')+ expect(t.provider().version).toBe(TERMINAL_WIDTH_VERSION)// Registering the provider is not enough — xterm keeps using the ACTIVE version, so a missing// assignment here would leave every terminal on the old widths with no other symptom.- expect(t.version()).toBe('11')+ expect(t.version()).toBe(TERMINAL_WIDTH_VERSION)})describe('the widths the emoji fix depends on', () => {diff --git a/src/renderer/terminal/unicode-width.ts b/src/renderer/terminal/unicode-width.tsindex 6590b17cd..a1f9495e8 100644--- a/src/renderer/terminal/unicode-width.ts+++ b/src/renderer/terminal/unicode-width.ts@@ -1,5 +1,5 @@-import { Unicode11Addon } from '@xterm/addon-unicode11'import type { Terminal } from '@xterm/xterm'+import { activateTerminalWidths, type UnicodeTerminal } from '@shared/terminal-width'/*** Put xterm on the SAME character-width table as everything else in the stack.@@ -42,14 +42,16 @@ import type { Terminal } from '@xterm/xterm'* realistic case is the one this fixes; a host that misaligns AFTER this change is the case to* report, and the fix there is that host's tmux, not a return to Unicode 6.*+ * The table is Unicode 11 plus one rule for emoji followed by VS16 (`@shared/terminal-width`, where+ * the reasoning lives); the Windows session host's emulator loads the same table.+ ** Applies to every renderer, so it is loaded at terminal construction rather than anywhere near* glyphgrid. Failure is non-fatal by design: a terminal on the old table renders as it did* yesterday, which is far better than a terminal that does not open.*/export function activateUnicode11(term: Terminal): void {try {- term.loadAddon(new Unicode11Addon())- term.unicode.activeVersion = '11'+ activateTerminalWidths(term as unknown as UnicodeTerminal)} catch (err) {console.warn('[terminal] could not activate Unicode 11 widths; staying on xterm’s default', err)}diff --git a/src/session-host/terminal-emulator-width.test.ts b/src/session-host/terminal-emulator-width.test.tsnew file mode 100644index 000000000..b61d526d7--- /dev/null+++ b/src/session-host/terminal-emulator-width.test.ts@@ -0,0 +1,27 @@+/**+ * The session host's emulator is what a reattaching viewer is repainted from, so it must size+ * characters the way the viewer and the pane's program do (`@shared/terminal-width`).+ *+ * MUTATION: remove the `activateTerminalWidths(this.term)` call in terminal-emulator.ts → the+ * emulator sizes the stopwatch + VS16 as one cell, its buffer holds "111%", and this reddens.+ */+import { describe, expect, it } from 'vitest'+import { Terminal } from '@xterm/headless'+import { TerminalEmulator } from './terminal-emulator'+import { activateTerminalWidths } from '../shared/terminal-width'++// U+23F1 STOPWATCH + U+FE0F VS16 (invisible, hence the escapes): claude-hud's status line prefix.+const STOPWATCH_EMOJI = '\u{23f1}\u{fe0f}'++describe('the session host emulator width table', () => {+ it('replays a VS16 emoji status line the way the program painted it', async () => {+ const emu = new TerminalEmulator({ cols: 40, rows: 4, scrollback: 100 })+ await emu.write(`${STOPWATCH_EMOJI} 100%\x1b[1;4H11%\x1b[K`)+ const viewer = new Terminal({ cols: 40, rows: 4, allowProposedApi: true })+ activateTerminalWidths(viewer)+ await new Promise<void>((r) => viewer.write(emu.serialize(), r))+ expect(viewer.buffer.active.getLine(0)!.translateToString(true)).toBe(`${STOPWATCH_EMOJI} 11%`)+ emu.dispose()+ viewer.dispose()+ })+})diff --git a/src/session-host/terminal-emulator.ts b/src/session-host/terminal-emulator.tsindex 92170e0b1..995806bc7 100644--- a/src/session-host/terminal-emulator.ts+++ b/src/session-host/terminal-emulator.ts@@ -1,6 +1,7 @@import { Terminal, type ITerminalAddon } from '@xterm/headless'import { SerializeAddon } from '@xterm/addon-serialize'import { clampEmulatorScrollback } from '../shared/scrollback'+import { activateTerminalWidths } from '../shared/terminal-width'// @xterm/addon-serialize's published types are written against @xterm/xterm's (browser) Terminal,// which has a superset of DOM-specific members @xterm/headless's Terminal lacks. The addon only@@ -44,6 +45,14 @@ export class TerminalEmulator {scrollback: this.defaultScrollback,allowProposedApi: true})+ // The renderer's width table, not xterm's Unicode 6 default: this buffer is what a reattaching+ // viewer is repainted from, so a character it sizes differently from the viewer (an emoji, an+ // emoji + VS16) shifts every later column of that line in the repaint.+ try {+ activateTerminalWidths(this.term)+ } catch {+ // Fail open: xterm's default table, exactly as before the shared table existed.+ }this.serializer = new SerializeAddon()this.term.loadAddon(this.serializer as unknown as ITerminalAddon)}diff --git a/src/shared/terminal-width.test.ts b/src/shared/terminal-width.test.tsnew file mode 100644index 000000000..16351679d--- /dev/null+++ b/src/shared/terminal-width.test.ts@@ -0,0 +1,124 @@+/**+ * The VS16 rule, asserted on a REAL xterm (the headless build the session host runs), never on the+ * provider's return values alone: what matters is where the cursor lands and what a repaint by+ * absolute position leaves on screen, because that is what the user saw go wrong.+ *+ * Code points are written as escapes on purpose: U+FE0F is invisible, and a literal one in this+ * file cannot be told apart from its absence.+ *+ * MUTATION: make `withEmojiPresentation` return `base.charProperties(cp, preceding)` unchanged →+ * the claude-hud repaint, the cursor and the chunk-split cases redden. Drop the keycap branch →+ * the keycap case reddens. Drop the `isKeycapBase` branch → the ASCII + VS16 case reddens (an+ * ASCII digit would then count as an emoji base).+ */+import { describe, expect, it, vi } from 'vitest'+import { Terminal } from '@xterm/headless'+import {+ activateTerminalWidths,+ TERMINAL_WIDTH_VERSION,+ withEmojiPresentation,+ type WidthProvider+} from './terminal-width'++const VS16 = '\u{fe0f}'+const VS15 = '\u{fe0e}'+const KEYCAP = '\u{20e3}'+const STOPWATCH = '\u{23f1}'++function terminal(): Terminal {+ const term = new Terminal({ cols: 40, rows: 4, allowProposedApi: true })+ activateTerminalWidths(term)+ return term+}++const write = (term: Terminal, ...chunks: string[]): Promise<void> =>+ chunks.reduce<Promise<void>>((p, c) => p.then(() => new Promise((r) => term.write(c, r))), Promise.resolve())++const line = (term: Terminal, y = 0): string =>+ term.buffer.active.getLine(y)!.translateToString(true)++/** Columns the cursor advanced after writing `text` at the start of an empty line. */+async function cells(text: string): Promise<number> {+ const term = terminal()+ await write(term, text)+ return term.buffer.active.cursorX+}++describe('the shared terminal width table', () => {+ it('is the active table once activated', () => {+ expect(terminal().unicode.activeVersion).toBe(TERMINAL_WIDTH_VERSION)+ })++ it('repaints the claude-hud status line without leaving a stale digit behind', async () => {+ // The writer believes the stopwatch + VS16 spans columns 1-2, so the value starts at column 4.+ // It paints 100%, then repaints 11% at the SAME absolute column and erases to the end of the+ // line. On a table that sizes the pair as one cell the repaint lands one column short and the+ // screen reads "111%" (the field report: `113` for `11%`).+ const term = terminal()+ await write(term, `${STOPWATCH}${VS16} 100%`, '\x1b[1;4H11%\x1b[K')+ expect(line(term)).toBe(`${STOPWATCH}${VS16} 11%`)+ })++ it('gives a text-default emoji followed by VS16 two cells', async () => {+ // stopwatch, warning sign, heavy check mark, copyright sign+ for (const emoji of [STOPWATCH, '\u{26a0}', '\u{2714}', '\u{a9}']) {+ expect([emoji, await cells(`${emoji}${VS16}`)]).toEqual([emoji, 2])+ }+ })++ it('still widens it when VS16 arrives in a later write than its base', async () => {+ const term = terminal()+ await write(term, STOPWATCH, VS16, 'x')+ expect(term.buffer.active.cursorX).toBe(3)+ })++ it('leaves every other width as it was', async () => {+ const STAR = '\u{2b50}'+ expect(await cells(STOPWATCH)).toBe(1) // the same emoji without VS16+ expect(await cells(STAR)).toBe(2) // already wide; VS16 adds nothing+ expect(await cells(`${STAR}${VS16}`)).toBe(2)+ expect(await cells(`${STAR}${VS15}`)).toBe(2) // VS15 is not this rule's business+ expect(await cells(`A${VS16}`)).toBe(1) // not an emoji+ expect(await cells(`1${VS16}`)).toBe(1) // an ASCII base with VS16 alone is not an RGI emoji+ expect(await cells('\u{65e5}')).toBe(2) // CJK+ expect(await cells('abc')).toBe(3)+ })++ it('gives a keycap sequence two cells', async () => {+ expect(await cells(`1${VS16}${KEYCAP}`)).toBe(2)+ expect(await cells(`#${VS16}${KEYCAP}`)).toBe(2)+ expect(await cells(`1${KEYCAP}`)).toBe(1) // unqualified: one cell, as tmux sizes it+ })+})++// charProperties runs once per printed character, so plain ASCII must never pay for the emoji+// regex: on ~20 MB of ASCII the regex alone slowed parsing by ~75%. MUTATION: drop the+// `cp < 0xa9` fast path → the spy below is called and this test reddens.+describe('the width wrapper on plain text', () => {+ // A base table that answers "one fresh cell" for everything, so every code point reaches the+ // part of the wrapper that would ask the regex.+ const base: WidthProvider = {+ version: 'stub',+ wcwidth: () => 1,+ charProperties: () => 1 << 1+ }++ it('never runs the emoji regex for a character below U+00A9', () => {+ const provider = withEmojiPresentation(base)+ const spy = vi.spyOn(RegExp.prototype, 'test')+ try {+ for (let cp = 0x20; cp < 0xa9; cp++) {+ if (cp >= 0x7f && cp < 0xa0) continue+ provider.charProperties(cp, 0)+ }+ expect(spy).not.toHaveBeenCalled()+ } finally {+ spy.mockRestore()+ }+ })++ it('still marks U+00A9 as an emoji base, so the fast path stops short of it', async () => {+ expect(await cells(`\u{a9}${VS16}`)).toBe(2)+ })+})+diff --git a/src/shared/terminal-width.ts b/src/shared/terminal-width.tsnew file mode 100644index 000000000..b834827e0--- /dev/null+++ b/src/shared/terminal-width.ts@@ -0,0 +1,119 @@+import { Unicode11Addon } from '@xterm/addon-unicode11'++/**+ * The character-width table every xterm instance in the stack uses: the renderer's terminals AND+ * the Windows session host's headless emulator. One definition, because the whole point is that+ * they agree with each other and with the program writing to the pane.+ *+ * It is Unicode 11 (`@xterm/addon-unicode11`, see `renderer/terminal/unicode-width.ts` for why)+ * plus ONE rule xterm's tables do not have: **an emoji followed by VARIATION SELECTOR-16 (U+FE0F)+ * is two cells wide.**+ *+ * Many emoji have TEXT presentation by default (`⏱ U+23F1`, `⚠ U+26A0`, `✔ U+2714`, `© U+00A9`)+ * and are one cell in every wcwidth table. Appending VS16 asks for the emoji presentation, and+ * everyone else the bytes pass through then counts the pair as two cells:+ *+ * - the agent CLIs measure with `string-width`, which gives every RGI emoji sequence width 2 —+ * and `⏱️` (U+23F1 U+FE0F) is one;+ * - tmux treats VS16 as wide by default (server option `variation-selector-always-wide`, on).+ *+ * xterm's tables read VS16 as a zero-width combining mark and keep the pair at ONE cell. The writer+ * then repaints by ABSOLUTE cursor position one column further right than xterm believes the text+ * ends, so a shorter value painted over a longer one leaves the old tail behind. That is the+ * claude-hud status line reading `113` for `11%` and `2h 327` for `2h 32m` in a nodeterm pane: the+ * line starts with `⏱️`, and every character after it was one column off.+ *+ * Measured on the claude-hud line through real ConPTY on Windows 11 (ConPTY passes the bytes+ * through; the shift is xterm's). Only VS16 is widened. VS15 (U+FE0E, "text please") is left+ * alone: `string-width` still sizes a `⭐︎` by the base character's East Asian Width, which is+ * what xterm already does.+ *+ * Keycaps are the one sequence whose base is ASCII: `1️⃣` (`1` U+FE0F U+20E3) is an RGI emoji and+ * two cells for the CLIs and for tmux, while `1` U+FE0F alone is not an RGI emoji and stays one+ * cell. So an ASCII base is NOT widened by VS16, and the keycap mark U+20E3 widens a `[0-9#*]` ++ * VS16 pair instead. The unqualified keycap `1⃣` (no VS16) stays one cell, as it is for tmux; some+ * `string-width` releases (4.x, and 8.2+) count it as two, so a CLI on one of those still+ * disagrees about that one form — it is rare in practice, and a POSIX pane is painted by tmux.+ *+ * Known limitation, inherited from xterm: in insert mode (IRM, `CSI 4 h`) xterm places a widened+ * join without shifting the rest of the line, so the cell the second column lands on is+ * overwritten. Before this table that case was already a column out of step with the writer; no+ * agent CLI or tmux repaint that we know of prints emoji in insert mode.+ */+export const TERMINAL_WIDTH_VERSION = '11-vs16'++/** The provider shape xterm's `Terminal.unicode.register` takes (5.5 and headless 6 alike). */+export interface WidthProvider {+ readonly version: string+ wcwidth(codepoint: number): 0 | 1 | 2+ charProperties(codepoint: number, preceding: number): number+}++/** The part of a Terminal (browser or headless) this needs. */+export interface UnicodeTerminal {+ unicode: { register(provider: WidthProvider): void; activeVersion: string }+}++const VS16 = 0xfe0f+const KEYCAP = 0x20e3++// xterm's packed char-properties value (`UnicodeService.createPropertyValue`): bit 0 = joins the+// preceding cell, bits 1-2 = width, bits 3+ = a provider-defined state. The state is how this+// provider remembers what the preceding character was; xterm hands it back unchanged as+// `preceding`, across write chunks too (`parser.precedingJoinState`).+const pack = (state: number, width: number, join: boolean): number =>+ ((state & 0xffffff) << 3) | ((width & 3) << 1) | (join ? 1 : 0)+const widthOf = (v: number): number => (v >> 1) & 3+const stateOf = (v: number): number => v >> 3++/** A one-cell emoji that VS16 turns into a two-cell one. */+const STATE_EMOJI_BASE = 1+/** `[0-9#*]`: not widened by VS16, but a keycap base. */+const STATE_KEYCAP_BASE = 2+/** `[0-9#*]` + VS16: the keycap mark that follows makes it two cells. */+const STATE_KEYCAP_VS16 = 3++// Below U+00A9 the only Emoji-property characters are the keycap bases, handled before this is asked.+const EMOJI = /^\p{Emoji}$/u+const isKeycapBase = (cp: number): boolean => (cp >= 0x30 && cp <= 0x39) || cp === 0x23 || cp === 0x2a++/** Wrap a width table with the VS16 rule above. Every other answer is the base table's. */+export function withEmojiPresentation(base: WidthProvider): WidthProvider {+ return {+ version: TERMINAL_WIDTH_VERSION,+ wcwidth: (cp) => base.wcwidth(cp),+ charProperties(cp, preceding) {+ const prev = stateOf(preceding)+ if (cp === VS16 && widthOf(preceding) === 1) {+ if (prev === STATE_EMOJI_BASE) return pack(0, 2, true)+ if (prev === STATE_KEYCAP_BASE) return pack(STATE_KEYCAP_VS16, 1, true)+ }+ if (cp === KEYCAP && prev === STATE_KEYCAP_VS16 && widthOf(preceding) === 1) return pack(0, 2, true)+ const value = base.charProperties(cp, preceding)+ // Only a fresh one-cell character can start a sequence; a join keeps the base's answer.+ if ((value & 1) !== 0 || widthOf(value) !== 1) return value+ if (isKeycapBase(cp)) return pack(STATE_KEYCAP_BASE, 1, false)+ // Hot path: this runs per printed character. No code point below © (U+00A9) other than the+ // keycap bases has the Emoji property, so plain text never pays for the regex below.+ if (cp < 0xa9) return value+ if (EMOJI.test(String.fromCodePoint(cp))) return pack(STATE_EMOJI_BASE, 1, false)+ return value+ }+ }+}++/** The Unicode 11 table, taken from the addon that owns it (its only export is the addon). */+function unicode11(): WidthProvider {+ let provider: WidthProvider | null = null+ new Unicode11Addon().activate({+ unicode: { register: (p: WidthProvider) => (provider = p) }+ } as unknown as Parameters<Unicode11Addon['activate']>[0])+ if (!provider) throw new Error('@xterm/addon-unicode11 registered no width provider')+ return provider+}++/** Put a terminal on the shared width table. Throws if it cannot; callers decide how to degrade. */+export function activateTerminalWidths(term: UnicodeTerminal): void {+ term.unicode.register(withEmojiPresentation(unicode11()))+ term.unicode.activeVersion = TERMINAL_WIDTH_VERSION+}