Skip to content

Commit 95e50d3

Browse files
steipetePeter Steinberger
andauthored
fix(terminal): measure unicode display width consistently (#117062)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent d8ba00f commit 95e50d3

5 files changed

Lines changed: 207 additions & 103 deletions

File tree

‎packages/terminal-core/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@
103103
"dependencies": {
104104
"@clack/prompts": "1.7.0",
105105
"@openclaw/normalization-core": "workspace:*",
106-
"chalk": "6.0.0"
106+
"chalk": "6.0.0",
107+
"string-width": "8.2.2"
107108
}
108109
}

‎packages/terminal-core/src/ansi.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,59 @@ describe("terminal ansi helpers", () => {
193193
expect(visibleWidth("a\u001B[31\u0001mb")).toBe(2);
194194
});
195195

196+
it.each([
197+
["halfwidth voiced kana", "バ", 2],
198+
["halfwidth semi-voiced kana", "パ", 2],
199+
["halfwidth kana with a prolonged sound", "ヴー", 3],
200+
["zero-width space", "\u200B", 0],
201+
["zero-width non-joiner", "\u200C", 0],
202+
["word joiner", "\u2060", 0],
203+
["function application", "\u2061", 0],
204+
["soft hyphen", "\u00AD", 0],
205+
["zero-width no-break space", "\uFEFF", 0],
206+
["Hindi spacing mark", "का", 2],
207+
["repeated leading Hangul jamo", "ᄀᄀ", 4],
208+
["repeated Hangul jamo with a vowel", "ᄀ가", 4],
209+
["Hangul leading filler", "\u115F", 2],
210+
["Hangul vowel filler", "\u1160", 0],
211+
["Hangul compatibility filler", "\u3164", 2],
212+
["halfwidth Hangul filler", "\uFFA0", 1],
213+
["Hangul filler with a vowel", "\u115F\u1161", 2],
214+
["Hangul leading and vowel fillers", "\u115F\u1160", 2],
215+
["Hangul compatibility filler with a combining mark", "\u3164\u0301", 2],
216+
["halfwidth Hangul filler with a voiced mark", "\uFFA0\uFF9E", 2],
217+
["lone high surrogate", "\uD800", 1],
218+
["lone low surrogate", "\uDC00", 1],
219+
["well-formed emoji surrogate pair", "\uD83D\uDE00", 2],
220+
])("measures %s with Unicode terminal-width rules", (_label, text, width) => {
221+
expect(visibleWidth(text)).toBe(width);
222+
});
223+
224+
it("measures malformed UTF-16 by Node's rendered replacement cells", () => {
225+
for (const input of ["\uD800", "\uDC00", "表\uD800\t", "\u001B[31m\uDC00\u001B[0m"]) {
226+
const rendered = Buffer.from(input, "utf8").toString("utf8");
227+
expect(visibleWidth(input)).toBe(visibleWidth(rendered));
228+
}
229+
});
230+
231+
it("preserves the executed width of tabs", () => {
232+
expect(visibleWidth("\t")).toBe(1);
233+
expect(visibleWidth("a\tb")).toBe(3);
234+
expect(visibleWidth("a\u001B[31\tmb")).toBe(3);
235+
expect(visibleWidth("a\u009B31\tmb")).toBe(3);
236+
});
237+
238+
it("keeps malformed ANSI ownership with OpenClaw's canonical scanner", () => {
239+
expect(visibleWidth("\u001B")).toBe(0);
240+
expect(visibleWidth("\u009B")).toBe(0);
241+
expect(visibleWidth("\u009D")).toBe(0);
242+
expect(visibleWidth("\u001B[")).toBe(0);
243+
expect(visibleWidth("\u001B]visible")).toBe("]visible".length);
244+
expect(visibleWidth("\u009Dvisible")).toBe("visible".length);
245+
// Removing CSI must not let another ANSI grammar reinterpret joined bytes as OSC.
246+
expect(visibleWidth("\u001B\u001B[0m]visible\u0007after")).toBe("]visibleafter".length);
247+
});
248+
196249
it("keeps emoji zwj sequences as single graphemes", () => {
197250
expect(splitGraphemes("👨‍👩‍👧‍👦")).toEqual(["👨‍👩‍👧‍👦"]);
198251
expect(visibleWidth("👨‍👩‍👧‍👦")).toBe(2);
@@ -229,9 +282,32 @@ describe("terminal ansi helpers", () => {
229282
// never emitted half-width, so the result never exceeds the budget.
230283
expect(truncateToVisibleWidth("表文", 2)).toBe("表");
231284
expect(truncateToVisibleWidth("表", 1)).toBe("");
285+
expect(truncateToVisibleWidth("バ", 1)).toBe("");
286+
expect(truncateToVisibleWidth("バ", 2)).toBe("バ");
287+
expect(truncateToVisibleWidth("का", 1)).toBe("");
288+
expect(truncateToVisibleWidth("ᄀᄀ", 3)).toBe("");
289+
expect(truncateToVisibleWidth("👨‍👩‍👧‍👦", 1)).toBe("");
290+
expect(truncateToVisibleWidth("🇬🇧", 1)).toBe("");
291+
expect(truncateToVisibleWidth("\u200B表", 1)).toBe("\u200B");
292+
expect(truncateToVisibleWidth("a\tb", 2)).toBe("a\t");
293+
expect(truncateToVisibleWidth("\u115F\u1161", 1)).toBe("");
294+
expect(truncateToVisibleWidth("\u3164".repeat(30), 1)).toBe("");
295+
expect(truncateToVisibleWidth("\u3164".repeat(30), 2)).toBe("\u3164");
296+
expect(truncateToVisibleWidth("\uFFA0\uFF9E", 1)).toBe("");
297+
expect(truncateToVisibleWidth("\uD800".repeat(30), 5)).toBe("\uD800".repeat(5));
298+
expect(truncateToVisibleWidth("表\uDC00\t", 3)).toBe("表\uDC00");
232299
expect(visibleWidth(truncateToVisibleWidth("📸📸", 1))).toBeLessThanOrEqual(1);
233300
});
234301

302+
it("keeps complete graphemes and zero-width prefixes at either truncation edge", () => {
303+
expect(truncateToVisibleWidth("abcd", 3)).toBe("abc");
304+
expect(truncateToVisibleWidth("表文字", 5)).toBe("表文");
305+
expect(truncateToVisibleWidth("👨‍👩‍👧‍👦📸", 3)).toBe("👨‍👩‍👧‍👦");
306+
expect(truncateToVisibleWidth("a\u200Bb", 1)).toBe("a\u200B");
307+
expect(truncateToVisibleWidth("abc\u200B", 2)).toBe("ab");
308+
expect(truncateToVisibleWidth("\u200Babc", 2)).toBe("\u200Bab");
309+
});
310+
235311
it("preserves ANSI sequences when truncating styled text", () => {
236312
// Trailing reset is retained even when its grapheme is dropped, so the cell
237313
// does not bleed styling into surrounding padding.

‎packages/terminal-core/src/ansi.ts‎

Lines changed: 99 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import stringWidth from "string-width";
12
import {
23
ANSI_COMPAT_CONTROL_SEQUENCE_PATTERN,
34
ANSI_OSC_INTRODUCER_PATTERN,
@@ -179,102 +180,27 @@ export function sanitizeForLog(v: string): string {
179180
return stripAnsi(v).replace(controlCharsRegex, "");
180181
}
181182

182-
function isZeroWidthCodePoint(codePoint: number): boolean {
183-
return (
184-
(codePoint <= 0x1f && codePoint !== 0x09) ||
185-
(codePoint >= 0x7f && codePoint <= 0x9f) ||
186-
(codePoint >= 0x0300 && codePoint <= 0x036f) ||
187-
(codePoint >= 0x1ab0 && codePoint <= 0x1aff) ||
188-
(codePoint >= 0x1dc0 && codePoint <= 0x1dff) ||
189-
(codePoint >= 0x20d0 && codePoint <= 0x20ff) ||
190-
(codePoint >= 0xfe20 && codePoint <= 0xfe2f) ||
191-
(codePoint >= 0xfe00 && codePoint <= 0xfe0f) ||
192-
codePoint === 0x200d
193-
);
194-
}
195-
196-
function isFullWidthCodePoint(codePoint: number): boolean {
197-
if (codePoint < 0x1100) {
198-
return false;
199-
}
200-
return (
201-
codePoint <= 0x115f ||
202-
codePoint === 0x2329 ||
203-
codePoint === 0x232a ||
204-
(codePoint >= 0x2e80 && codePoint <= 0x3247 && codePoint !== 0x303f) ||
205-
(codePoint >= 0x3250 && codePoint <= 0x4dbf) ||
206-
(codePoint >= 0x4e00 && codePoint <= 0xa4c6) ||
207-
(codePoint >= 0xa960 && codePoint <= 0xa97c) ||
208-
(codePoint >= 0xac00 && codePoint <= 0xd7a3) ||
209-
(codePoint >= 0xf900 && codePoint <= 0xfaff) ||
210-
(codePoint >= 0xfe10 && codePoint <= 0xfe19) ||
211-
(codePoint >= 0xfe30 && codePoint <= 0xfe6b) ||
212-
(codePoint >= 0xff01 && codePoint <= 0xff60) ||
213-
(codePoint >= 0xffe0 && codePoint <= 0xffe6) ||
214-
(codePoint >= 0x1aff0 && codePoint <= 0x1aff3) ||
215-
(codePoint >= 0x1aff5 && codePoint <= 0x1affb) ||
216-
(codePoint >= 0x1affd && codePoint <= 0x1affe) ||
217-
(codePoint >= 0x1b000 && codePoint <= 0x1b2ff) ||
218-
(codePoint >= 0x1f200 && codePoint <= 0x1f251) ||
219-
(codePoint >= 0x20000 && codePoint <= 0x3fffd)
220-
);
221-
}
222-
223-
const rgiEmojiPattern = new RegExp("^\\p{RGI_Emoji}$", "v");
224-
const emojiPresentationPattern = /\p{Emoji_Presentation}/u;
225-
const regionalIndicatorPattern = /\p{Regional_Indicator}/u;
226-
const unqualifiedKeycapPattern = /^[#*0-9]\u20E3$/u;
227-
const extendedPictographicPattern = /\p{Extended_Pictographic}/gu;
228-
229-
function isWideEmojiGrapheme(grapheme: string): boolean {
230-
const isRgiEmoji = rgiEmojiPattern.test(grapheme);
231-
// RGI recognizes paired flags while keeping a lone regional indicator narrow.
232-
if (regionalIndicatorPattern.test(grapheme)) {
233-
return isRgiEmoji;
234-
}
235-
if (
236-
emojiPresentationPattern.test(grapheme) ||
237-
isRgiEmoji ||
238-
unqualifiedKeycapPattern.test(grapheme)
239-
) {
240-
return true;
241-
}
242-
// Minimally qualified ZWJ sequences still shape as one wide emoji in terminals.
243-
return (
244-
grapheme.includes("\u200D") && (grapheme.match(extendedPictographicPattern)?.length ?? 0) >= 2
245-
);
246-
}
247-
248-
function graphemeWidth(grapheme: string): number {
249-
if (!grapheme) {
250-
return 0;
251-
}
252-
if (isWideEmojiGrapheme(grapheme)) {
253-
return 2;
254-
}
255-
256-
let sawPrintable = false;
257-
for (const char of grapheme) {
258-
const codePoint = char.codePointAt(0);
259-
if (codePoint == null) {
260-
continue;
261-
}
262-
if (isZeroWidthCodePoint(codePoint)) {
263-
continue;
264-
}
265-
if (isFullWidthCodePoint(codePoint)) {
266-
return 2;
267-
}
268-
sawPrintable = true;
183+
function textWidth(text: string): number {
184+
// POSIX renders these default-ignorable Hangul fillers as wide/halfwidth cells;
185+
// same-shaping representatives and well-formed surrogates preserve terminal output.
186+
const printable = /[\u115F\u3164\uFFA0\uD800-\uDFFF]/u.test(text)
187+
? text
188+
.replace(/[\uD800-\uDFFF]/gu, "\uFFFD")
189+
.replaceAll("\u115F", "\u1100")
190+
.replaceAll("\u3164", "\u3131")
191+
.replaceAll("\uFFA0", "\uFF8A")
192+
: text;
193+
// OpenClaw owns ANSI parsing; upstream must not reinterpret malformed sequences.
194+
let width = stringWidth(printable, { countAnsiEscapeCodes: true });
195+
// Tabs execute inside CSI too; string-width intentionally treats them as zero-width.
196+
for (let index = text.indexOf("\t"); index !== -1; index = text.indexOf("\t", index + 1)) {
197+
width += 1;
269198
}
270-
return sawPrintable ? 1 : 0;
199+
return width;
271200
}
272201

273202
export function visibleWidth(input: string): number {
274-
return splitGraphemes(stripAnsi(input)).reduce(
275-
(sum, grapheme) => sum + graphemeWidth(grapheme),
276-
0,
277-
);
203+
return textWidth(stripAnsi(input));
278204
}
279205

280206
/**
@@ -288,7 +214,9 @@ export function truncateToVisibleWidth(input: string, maxWidth: number): string
288214
if (maxWidth <= 0) {
289215
return "";
290216
}
291-
if (visibleWidth(input) <= maxWidth) {
217+
const plainInput = stripAnsi(input);
218+
const inputWidth = textWidth(plainInput);
219+
if (inputWidth <= maxWidth) {
292220
return input;
293221
}
294222
let out = "";
@@ -301,20 +229,89 @@ export function truncateToVisibleWidth(input: string, maxWidth: number): string
301229
if (budgetSpent) {
302230
return;
303231
}
304-
for (const grapheme of splitGraphemes(segment)) {
305-
const width = graphemeWidth(grapheme);
306-
if (used + width > maxWidth) {
307-
budgetSpent = true;
308-
return;
309-
}
310-
out += grapheme;
232+
const remaining = maxWidth - used;
233+
const width = segment === plainInput ? inputWidth : textWidth(segment);
234+
if (width <= remaining) {
235+
out += segment;
311236
used += width;
237+
return;
238+
}
239+
240+
const graphemes = splitGraphemes(segment);
241+
let offset = 0;
242+
const offsets = [offset];
243+
for (const grapheme of graphemes) {
244+
offset += grapheme.length;
245+
offsets.push(offset);
246+
}
247+
let start = 0;
248+
let fittedWidth = 0;
249+
if (remaining <= width / 2) {
250+
let end = Math.max(
251+
1,
252+
Math.min(graphemes.length - 1, Math.floor((remaining * graphemes.length) / width)),
253+
);
254+
let stride = 1;
255+
// Estimate the cell boundary first; gallop handles uneven/zero-width clusters.
256+
while (end < graphemes.length) {
257+
const candidateWidth = textWidth(segment.slice(0, offsets[end]));
258+
if (candidateWidth > remaining) {
259+
break;
260+
}
261+
start = end;
262+
fittedWidth = candidateWidth;
263+
end = Math.min(graphemes.length, end + stride);
264+
stride *= 2;
265+
}
266+
while (start + 1 < end) {
267+
const middle = Math.floor((start + end) / 2);
268+
const candidateWidth = textWidth(segment.slice(0, offsets[middle]));
269+
if (candidateWidth <= remaining) {
270+
start = middle;
271+
fittedWidth = candidateWidth;
272+
} else {
273+
end = middle;
274+
}
275+
}
276+
} else {
277+
const overflow = width - remaining;
278+
let tooShort = 0;
279+
let removed = Math.min(graphemes.length, 1);
280+
let removedWidth = width;
281+
// Near-end cuts search short complete-grapheme suffixes, not repeated full prefixes.
282+
while (removed < graphemes.length) {
283+
removedWidth = textWidth(segment.slice(offsets[graphemes.length - removed]));
284+
if (removedWidth >= overflow) {
285+
break;
286+
}
287+
tooShort = removed;
288+
removed = Math.min(graphemes.length, removed * 2);
289+
}
290+
if (removed === graphemes.length) {
291+
removedWidth = width;
292+
}
293+
while (tooShort + 1 < removed) {
294+
const middle = Math.floor((tooShort + removed) / 2);
295+
const candidateWidth = textWidth(segment.slice(offsets[graphemes.length - middle]));
296+
if (candidateWidth >= overflow) {
297+
removed = middle;
298+
removedWidth = candidateWidth;
299+
} else {
300+
tooShort = middle;
301+
}
302+
}
303+
start = graphemes.length - removed;
304+
fittedWidth = width - removedWidth;
312305
}
306+
out += segment.slice(0, offsets[start]);
307+
used += fittedWidth;
308+
budgetSpent = true;
313309
};
314310
for (const segment of splitAnsiSegments(input)) {
315311
if (segment.kind === "ansi") {
316-
const widthControls = segment.controls.filter((control) => graphemeWidth(control) > 0);
317-
const controlWidth = widthControls.reduce((sum, control) => sum + graphemeWidth(control), 0);
312+
// CSI retains only C0/DEL controls; TAB is the sole visible-width member.
313+
const widthControls = segment.controls.filter((control) => control === "\t");
314+
const controlWidth = widthControls.length;
318315
if (!budgetSpent && used + controlWidth <= maxWidth) {
319316
out += segment.value;
320317
used += controlWidth;

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/cli/cron-cli/shared.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,33 @@ describe("printCronList", () => {
129129
expect(output).not.toContain(injectedMarker);
130130
});
131131

132+
it.each([
133+
["halfwidth voiced kana", `${"x".repeat(23)}バ`, `${"x".repeat(21)}...`],
134+
["halfwidth semi-voiced kana", `${"x".repeat(23)}パ`, `${"x".repeat(21)}...`],
135+
["zero-width space", `${"x".repeat(23)}\u200B`, `${"x".repeat(23)}\u200B `],
136+
["word joiner", `${"x".repeat(23)}\u2060`, `${"x".repeat(23)}\u2060 `],
137+
["zero-width no-break space", `${"x".repeat(23)}\uFEFF`, `${"x".repeat(23)}\uFEFF `],
138+
["leading zero-width non-joiner", `\u200C${"x".repeat(23)}`, `\u200C${"x".repeat(23)} `],
139+
["Hindi spacing mark", `${"x".repeat(23)}का`, `${"x".repeat(21)}...`],
140+
["repeated Hangul jamo", `${"x".repeat(22)}ᄀ가`, `${"x".repeat(21)}...`],
141+
["Hangul leading filler", `${"x".repeat(23)}\u115F`, `${"x".repeat(21)}...`],
142+
["Hangul compatibility filler", `${"x".repeat(23)}\u3164`, `${"x".repeat(21)}...`],
143+
["halfwidth Hangul filler", `${"x".repeat(23)}\uFFA0`, `${"x".repeat(23)}\uFFA0`],
144+
["zero-width Hangul vowel filler", `${"x".repeat(23)}\u1160`, `${"x".repeat(23)}\u1160 `],
145+
["lone high surrogate", `${"x".repeat(23)}\uD800`, `${"x".repeat(23)}\uD800`],
146+
["lone low surrogate", `${"x".repeat(23)}\uDC00`, `${"x".repeat(23)}\uDC00`],
147+
])("aligns the %s name cell without relying on its width helper", (_label, name, expected) => {
148+
const { logs, runtime } = createRuntimeLogCapture();
149+
printCronList([createBaseJob({ name })], runtime);
150+
151+
const [header = "", row = ""] = logs;
152+
const nameColumn = header.indexOf("Name");
153+
const scheduleColumn = row.indexOf("at ");
154+
expect(nameColumn).toBeGreaterThan(-1);
155+
expect(scheduleColumn).toBeGreaterThan(nameColumn);
156+
expect(row.slice(nameColumn, scheduleColumn - 1)).toBe(expected);
157+
});
158+
132159
it("sanitizes and bounds named-session targets", () => {
133160
const { logs, runtime } = createRuntimeLogCapture();
134161
const injectedMarker = "cron-target-injection";

0 commit comments

Comments
 (0)