@yanzc/claude-pro 0.9.3 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yanzc/claude-pro",
3
- "version": "0.9.3",
3
+ "version": "0.9.5",
4
4
  "description": "claude-pro: a command line coding agent for the codex-gateway. Full access with no permission prompts; file edits are checkpointed and can be rewound.",
5
5
  "type": "module",
6
6
  "repository": {
package/src/commands.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
- import { c, padEnd, truncate } from './ui/ansi.js';
5
+ import { c, glyphs, padEnd, truncate } from './ui/ansi.js';
6
6
  import { SelectDialog } from './ui/dialogs.js';
7
7
  import { renderTodos, resultLines, formatTokens, formatDuration } from './ui/render.js';
8
8
  import { loadConfig, settingsFiles, configEntries, writeConfigSetting, unsetConfigSetting, rememberChoice, applyRememberedChoices, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
@@ -663,7 +663,7 @@ export function buildCommands(app) {
663
663
  const fill = Math.min(barW, Math.round((used / window) * barW));
664
664
  const mark = Math.min(barW - 1, Math.round((threshold / window) * barW));
665
665
  let bar = '';
666
- for (let i = 0; i < barW; i++) bar += i < fill ? c.claude('█') : i === mark ? c.yellow('┃') : c.dim('░');
666
+ for (let i = 0; i < barW; i++) bar += i < fill ? c.claude('█') : i === mark ? c.yellow('┃') : c.dim(glyphs.track);
667
667
  out([
668
668
  `${bar} ${c.bold(formatTokens(used))} / ${formatTokens(window)} tokens (${Math.round((used / window) * 100)}%)`,
669
669
  c.dim(`System prompt ~${formatTokens(sys)} · Tools ~${formatTokens(tools)} · Messages ~${formatTokens(msgs)} (${a.messages.length})`),
package/src/ui/ansi.js CHANGED
@@ -96,16 +96,77 @@ function inRanges(cp, ranges) {
96
96
  return false;
97
97
  }
98
98
 
99
- // Some Windows conhosts render symbols such as ·, … and ↓ in two cells even in UTF-8. Use the cursor
100
- // advances measured at startup instead of guessing from the code page (or changing the user's console settings).
99
+ // East Asian Ambiguous characters (UAX #11: the Basic Multilingual Plane, without combining marks and the private
100
+ // use area). A terminal gives them one cell or two depending on its font and settings: the Windows console with a
101
+ // Chinese, Japanese or Korean font draws those its font has full-width glyphs for (“ ” — … · × ° ① → ■ α Я) in
102
+ // two cells and the others (é, box drawing) in one, whatever the code page. So their widths are measured where
103
+ // that matters (see queryCursorRow in screen.js), not looked up. (Ranges end where a block does: neighbours in a
104
+ // block mostly have the same width, which is what measuring them together relies on.)
105
+ const AMBIGUOUS = [
106
+ [0xa1, 0xa1], [0xa4, 0xa4], [0xa7, 0xa8], [0xaa, 0xaa], [0xae, 0xae], [0xb0, 0xb4], [0xb6, 0xba], [0xbc, 0xbf],
107
+ [0xc6, 0xc6], [0xd0, 0xd0], [0xd7, 0xd8], [0xde, 0xe1], [0xe6, 0xe6], [0xe8, 0xea], [0xec, 0xed], [0xf0, 0xf0],
108
+ [0xf2, 0xf3], [0xf7, 0xfa], [0xfc, 0xfc], [0xfe, 0xfe], [0x101, 0x101], [0x111, 0x111], [0x113, 0x113],
109
+ [0x11b, 0x11b], [0x126, 0x127], [0x12b, 0x12b], [0x131, 0x133], [0x138, 0x138], [0x13f, 0x142], [0x144, 0x144],
110
+ [0x148, 0x14b], [0x14d, 0x14d], [0x152, 0x153], [0x166, 0x167], [0x16b, 0x16b], [0x1ce, 0x1ce], [0x1d0, 0x1d0],
111
+ [0x1d2, 0x1d2], [0x1d4, 0x1d4], [0x1d6, 0x1d6], [0x1d8, 0x1d8], [0x1da, 0x1da], [0x1dc, 0x1dc], [0x251, 0x251],
112
+ [0x261, 0x261], [0x2c4, 0x2c4], [0x2c7, 0x2c7], [0x2c9, 0x2cb], [0x2cd, 0x2cd], [0x2d0, 0x2d0], [0x2d8, 0x2db],
113
+ [0x2dd, 0x2dd], [0x2df, 0x2df], [0x391, 0x3a1], [0x3a3, 0x3a9], [0x3b1, 0x3c1], [0x3c3, 0x3c9], [0x401, 0x401],
114
+ [0x410, 0x44f], [0x451, 0x451], [0x2010, 0x2010], [0x2013, 0x2016], [0x2018, 0x2019], [0x201c, 0x201d],
115
+ [0x2020, 0x2022], [0x2024, 0x2027], [0x2030, 0x2030], [0x2032, 0x2033], [0x2035, 0x2035], [0x203b, 0x203b],
116
+ [0x203e, 0x203e], [0x2074, 0x2074], [0x207f, 0x207f], [0x2081, 0x2084], [0x20ac, 0x20ac], [0x2103, 0x2103],
117
+ [0x2105, 0x2105], [0x2109, 0x2109], [0x2113, 0x2113], [0x2116, 0x2116], [0x2121, 0x2122], [0x2126, 0x2126],
118
+ [0x212b, 0x212b], [0x2153, 0x2154], [0x215b, 0x215e], [0x2160, 0x216b], [0x2170, 0x2179], [0x2189, 0x2189],
119
+ [0x2190, 0x2199], [0x21b8, 0x21b9], [0x21d2, 0x21d2], [0x21d4, 0x21d4], [0x21e7, 0x21e7], [0x2200, 0x2200], [0x2202, 0x2203],
120
+ [0x2207, 0x2208], [0x220b, 0x220b], [0x220f, 0x220f], [0x2211, 0x2211], [0x2215, 0x2215], [0x221a, 0x221a],
121
+ [0x221d, 0x2220], [0x2223, 0x2223], [0x2225, 0x2225], [0x2227, 0x222c], [0x222e, 0x222e], [0x2234, 0x2237],
122
+ [0x223c, 0x223d], [0x2248, 0x2248], [0x224c, 0x224c], [0x2252, 0x2252], [0x2260, 0x2261], [0x2264, 0x2267],
123
+ [0x226a, 0x226b], [0x226e, 0x226f], [0x2282, 0x2283], [0x2286, 0x2287], [0x2295, 0x2295], [0x2299, 0x2299],
124
+ [0x22a5, 0x22a5], [0x22bf, 0x22bf], [0x2312, 0x2312], [0x2460, 0x24e9], [0x24eb, 0x24ff], [0x2500, 0x254b],
125
+ [0x2550, 0x2573], [0x2580, 0x258f], [0x2592, 0x2595], [0x25a0, 0x25a1], [0x25a3, 0x25a9], [0x25b2, 0x25b3], [0x25b6, 0x25b7],
126
+ [0x25bc, 0x25bd], [0x25c0, 0x25c1], [0x25c6, 0x25c8], [0x25cb, 0x25cb], [0x25ce, 0x25d1], [0x25e2, 0x25e5],
127
+ [0x25ef, 0x25ef], [0x2605, 0x2606], [0x2609, 0x2609], [0x260e, 0x260f], [0x261c, 0x261c], [0x261e, 0x261e],
128
+ [0x2640, 0x2640], [0x2642, 0x2642], [0x2660, 0x2661], [0x2663, 0x2665], [0x2667, 0x266a], [0x266c, 0x266d],
129
+ [0x266f, 0x266f], [0x269e, 0x269f], [0x26bf, 0x26bf], [0x26c6, 0x26cd], [0x26cf, 0x26d3], [0x26d5, 0x26e1],
130
+ [0x26e3, 0x26e3], [0x26e8, 0x26e9], [0x26eb, 0x26f1], [0x26f4, 0x26f4], [0x26f6, 0x26f9], [0x26fb, 0x26fc],
131
+ [0x26fe, 0x26ff], [0x273d, 0x273d], [0x2776, 0x277f], [0x2b56, 0x2b59], [0x3248, 0x324f], [0xfffd, 0xfffd],
132
+ ];
133
+
134
+ // Those characters as strings of neighbours: each range, in pieces of at most `max` characters.
135
+ export function ambiguousGroups(max) {
136
+ const groups = [];
137
+ for (const [from, to] of AMBIGUOUS) {
138
+ for (let cp = from; cp <= to; cp += max) {
139
+ let text = '';
140
+ for (let k = cp; k <= Math.min(to, cp + max - 1); k++) text += String.fromCodePoint(k);
141
+ groups.push(text);
142
+ }
143
+ }
144
+ return groups;
145
+ }
146
+
147
+ // The widths this terminal was measured to give characters (see queryCursorRow): [[character, cells], ...]. They
148
+ // come before the tables above, which is what makes the program's layout and the terminal's agree where the
149
+ // terminal draws a symbol such as ·, … or “ in two cells.
101
150
  const terminalWidths = new Map();
102
151
  export function setTerminalWidths(widths) {
103
152
  terminalWidths.clear();
104
153
  for (const [char, width] of widths) {
105
154
  if (width === 1 || width === 2) terminalWidths.set(char.codePointAt(0), width);
106
155
  }
156
+ Object.assign(glyphs, terminalWidths.get(0xb7) === 2 ? FONT_GLYPHS : GLYPHS);
107
157
  }
108
158
 
159
+ // The interface's symbols that not every terminal can draw, by what they are for. The Windows console that sizes
160
+ // characters by its Chinese font (the one that draws · in two cells) has no glyph for some of them and draws an
161
+ // empty box two cells wide instead, over the character behind it, and it draws a round corner half a cell to the
162
+ // right, so that a left one stands under the border's line, not at its end. There they are characters that
163
+ // font has; their widths differ (※ and ⊙ take two cells), so what is drawn with them is measured, not counted.
164
+ // `lineGap` is what stands between a border's line and coloured text behind it: that console draws ─ two cells
165
+ // wide, and the last one of a line covers a space that differs from it only in colour.
166
+ const GLYPHS = { topLeft: '╭', topRight: '╮', bottomLeft: '╰', bottomRight: '╯', clock: '◷', restart: '↻', update: '⇣', find: '⌕', track: '░', pointer: '❯', lineGap: ' ' };
167
+ const FONT_GLYPHS = { topLeft: '┌', topRight: '┐', bottomLeft: '└', bottomRight: '┘', clock: '⊙', restart: '※', update: '↓', find: '/', track: '─', pointer: '>', lineGap: ' ' };
168
+ export const glyphs = { ...GLYPHS };
169
+
109
170
  export function codePointWidth(cp) {
110
171
  if (cp < 32 || (cp >= 0x7f && cp < 0xa0)) return 0;
111
172
  if (inRanges(cp, ZERO)) return 0;
package/src/ui/dialogs.js CHANGED
@@ -1,19 +1,19 @@
1
1
  // Modal dialogs rendered in the live region: selection menus (questions, the model and session pickers, /rewind),
2
2
  // with a typed answer of their own when they offer "Other".
3
3
 
4
- import { c, padEnd, stringWidth, truncate, wordWrap } from './ansi.js';
4
+ import { c, glyphs, padEnd, stringWidth, truncate, wordWrap } from './ansi.js';
5
5
  import { Editor } from './editor.js';
6
6
 
7
7
  function box(lines, width, color) {
8
8
  const w = Math.max(20, width - 1);
9
9
  const inner = w - 4;
10
- const out = [color('╭' + '─'.repeat(w - 2) + '╮')];
10
+ const out = [color(glyphs.topLeft + '─'.repeat(w - 2) + glyphs.topRight)];
11
11
  for (const l of lines) {
12
12
  for (const part of stringWidth(l) > inner ? wordWrap(l, inner) : [l]) {
13
13
  out.push(color('│') + ' ' + padEnd(part, inner) + ' ' + color('│'));
14
14
  }
15
15
  }
16
- out.push(color('╰' + '─'.repeat(w - 2) + '╯'));
16
+ out.push(color(glyphs.bottomLeft + '─'.repeat(w - 2) + glyphs.bottomRight));
17
17
  return out;
18
18
  }
19
19
 
@@ -112,7 +112,7 @@ export class SelectDialog {
112
112
  const o = this.options[i];
113
113
  const sel = i === this.selected;
114
114
  const mark = this.multi ? (this.checked.has(i) ? c.green('[✔] ') : '[ ] ') : '';
115
- const label = `${sel ? '❯' : ' '} ${i + 1}. ${mark}${o.label}`;
115
+ const label = `${sel ? glyphs.pointer : ' '} ${i + 1}. ${mark}${o.label}`;
116
116
  lines.push(sel ? this.color(truncate(label, inner)) : truncate(label, inner));
117
117
  if (o.description) lines.push(c.dim(' ' + truncate(o.description, inner - 6)));
118
118
  }
package/src/ui/editor.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // The prompt input box: multi-line editing, history, paste handling and completions.
2
2
 
3
- import { c, graphemes, graphemeWidth, stringWidth, truncate, padEnd } from './ansi.js';
3
+ import { c, glyphs, graphemes, graphemeWidth, stringWidth, truncate, padEnd } from './ansi.js';
4
4
 
5
5
  const PASTE_THRESHOLD_CHARS = 800;
6
6
  const PASTE_THRESHOLD_LINES = 8;
@@ -27,11 +27,12 @@ export function shownQuotes(text) {
27
27
 
28
28
  // "╭─ left ───── right ─╮", the parts cut short to fit (the start of the directory goes first).
29
29
  export function topBorder(boxW, color, title) {
30
- const plain = () => color('╭' + '─'.repeat(boxW - 2) + '╮');
30
+ const plain = () => color(glyphs.topLeft + '─'.repeat(boxW - 2) + glyphs.topRight);
31
31
  if (!title || (!title.left && !title.right)) return plain();
32
32
  const room = boxW - 6; // the corners, a dash at each end and a space each side of a part
33
33
  const right = title.right ? truncate(title.right, Math.max(0, Math.floor(room / 3))).replace(/\x1b\[0m$/, '') : '';
34
- const rightW = right ? stringWidth(right) + 2 : 0;
34
+ const rightPart = right ? `${glyphs.lineGap}${right} ` : '';
35
+ const rightW = stringWidth(rightPart);
35
36
  let left = title.left || '';
36
37
  const leftRoom = room - rightW - (right && left ? 1 : 0) - 2;
37
38
  if (leftRoom < 4) left = '';
@@ -42,10 +43,9 @@ export function topBorder(boxW, color, title) {
42
43
  }
43
44
  if (!left && !right) return plain();
44
45
  const leftPart = left ? ` ${left} ` : '';
45
- const rightPart = right ? ` ${right} ` : '';
46
46
  const dashes = boxW - 4 - stringWidth(leftPart) - stringWidth(rightPart);
47
47
  if (dashes < 1) return plain();
48
- return color('╭─') + c.dim(leftPart) + color('─'.repeat(dashes)) + (right ? c.blue(rightPart) : '') + color('─╮');
48
+ return color(glyphs.topLeft + '─') + c.dim(leftPart) + color('─'.repeat(dashes)) + (right ? c.blue(rightPart) : '') + color('─' + glyphs.topRight);
49
49
  }
50
50
 
51
51
  // Start of the line the cursor is on. (lastIndexOf with a negative start still looks at index 0, so a
@@ -615,7 +615,7 @@ export class Editor {
615
615
  const below = laid.length - top - shown;
616
616
  const hidden = [top ? `↑ ${top} more rows` : '', below ? `↓ ${below} more rows` : ''].filter(Boolean).join(' · ');
617
617
  const label = hidden && boxW > stringWidth(hidden) + 6 ? ` ${hidden} ` : '';
618
- lines.push(color('╰─') + c.dim(label) + color('─'.repeat(boxW - 3 - stringWidth(label)) + '╯'));
618
+ lines.push(color(glyphs.bottomLeft + '─') + c.dim(label) + color('─'.repeat(boxW - 3 - stringWidth(label)) + glyphs.bottomRight));
619
619
  // `text`: where the text is in `lines` (its first row, how many, the column it starts at), for the mouse
620
620
  return { lines, cursor: active ? { row: r - top + 1, col: 4 + col } : null, text: { row: 1, rows: shown, col: 4 } };
621
621
  }
package/src/ui/repl.js CHANGED
@@ -6,7 +6,7 @@ import path from 'node:path';
6
6
  import os from 'node:os';
7
7
  import readline from 'node:readline';
8
8
  import { spawn } from 'node:child_process';
9
- import { c, ESC, stringWidth, stripAnsi, truncate, padEnd, wordWrap } from './ansi.js';
9
+ import { c, ESC, glyphs, stringWidth, stripAnsi, truncate, padEnd, wordWrap } from './ansi.js';
10
10
  import { Screen, queryCursorRow, mouseFilter } from './screen.js';
11
11
  import { Editor, topBorder, shownQuotes } from './editor.js';
12
12
  import { SelectDialog } from './dialogs.js';
@@ -1132,7 +1132,7 @@ export class App {
1132
1132
  this.seedOutput = [line];
1133
1133
  return;
1134
1134
  }
1135
- this.screen.log(c.dim(`↻ Restarted${state.reason ? `: ${state.reason}` : ''}${state.continueWith ? ' · continuing' : ''}`), '');
1135
+ this.screen.log(c.dim(`${glyphs.restart} Restarted${state.reason ? `: ${state.reason}` : ''}${state.continueWith ? ' · continuing' : ''}`), '');
1136
1136
  }
1137
1137
 
1138
1138
  // The turn that goes on after a restart: the note for the model, and what the user had queued meanwhile.
@@ -1293,7 +1293,7 @@ export class App {
1293
1293
  const row = (s) => c.claude('│') + ' ' + padEnd(truncate(s, inner), inner) + ' ' + c.claude('│');
1294
1294
  const model = cfg.model;
1295
1295
  const lines = [
1296
- c.claude('╭' + '─'.repeat(w - 2) + '╮'),
1296
+ c.claude(glyphs.topLeft + '─'.repeat(w - 2) + glyphs.topRight),
1297
1297
  row(`${c.claude('✻')} Welcome to ${c.bold(APP_NAME)}! ${c.dim(`v${VERSION} · a command line coding agent`)}`),
1298
1298
  row(''),
1299
1299
  row(c.dim(' /help for help, /status for your current setup')),
@@ -1301,7 +1301,7 @@ export class App {
1301
1301
  row(c.dim(` cwd: ${this.cwd}`)),
1302
1302
  row(c.dim(` model: ${model.label}${cfg.effort ? ` · effort ${cfg.effort}` : ''} · ${formatTokens(model.contextWindow)} context`)),
1303
1303
  row(c.dim(` backend: ${cfg.endpointLabel}`)),
1304
- c.claude('╰' + '─'.repeat(w - 2) + '╯'),
1304
+ c.claude(glyphs.bottomLeft + '─'.repeat(w - 2) + glyphs.bottomRight),
1305
1305
  ];
1306
1306
  lines.push('', c.dim(' Full access: every tool runs immediately, nothing is ever asked. File edits are checkpointed;'), c.dim(' /rewind puts files and/or the conversation back (shell-command changes are not tracked).'));
1307
1307
  if (!gatewayLogin(cfg.gatewayUrl)) lines.push('', c.yellow(` ⚠ Not logged in to the gateway ${cfg.gatewayUrl}. Run /login.`));
@@ -1769,8 +1769,8 @@ export class App {
1769
1769
  const content = f.selected && shown ? c.inverse(shown) : shown;
1770
1770
  const lines = [
1771
1771
  topBorder(boxW, c.yellow, title),
1772
- c.yellow('│') + ' ' + c.yellow('⌕') + ' ' + padEnd(content, textW) + ' ' + c.yellow('│'),
1773
- c.yellow('╰' + '─'.repeat(boxW - 2) + '╯'),
1772
+ c.yellow('│') + ' ' + c.yellow(glyphs.find) + ' ' + padEnd(content, textW) + ' ' + c.yellow('│'),
1773
+ c.yellow(glyphs.bottomLeft + '─'.repeat(boxW - 2) + glyphs.bottomRight),
1774
1774
  ];
1775
1775
  return { lines, cursor: { row: 1, col: 4 + stringWidth(before) } };
1776
1776
  }
@@ -2418,7 +2418,8 @@ export class App {
2418
2418
  // ---------------------------------------------------------------- live region
2419
2419
 
2420
2420
  spinnerLine() {
2421
- const frame = SPINNER[Math.floor(Date.now() / 120) % SPINNER.length];
2421
+ // (as wide as the widest frame: where the terminal draws some of them in two cells, the text behind moved back and forth)
2422
+ const frame = padEnd(SPINNER[Math.floor(Date.now() / 120) % SPINNER.length], Math.max(...SPINNER.map(stringWidth)));
2422
2423
  if (this.rateWait) {
2423
2424
  const w = this.rateWait;
2424
2425
  const left = humanDuration(w.resumeAt - Date.now()); // the same wording as the notice above it
@@ -2531,7 +2532,7 @@ export class App {
2531
2532
  // cache use.
2532
2533
  cacheClock() {
2533
2534
  const clock = this.agent?.cache.clock();
2534
- return !clock ? '' : clock.cold ? c.red('◷') : c.dim(`◷ ${clock.minutes}m`);
2535
+ return !clock ? '' : clock.cold ? c.red(glyphs.clock) : c.dim(`${glyphs.clock} ${clock.minutes}m`);
2535
2536
  }
2536
2537
 
2537
2538
  footer(w) {
@@ -2541,7 +2542,7 @@ export class App {
2541
2542
  else if (flash) left = (flash.kind === 'warn' ? c.yellow : c.dim)(' ' + truncate(flash.text, w - 4));
2542
2543
  else if (this.screen.full && this.screen.selection) left = c.dim(' ctrl+c to copy · ctrl+q to quote it in your message');
2543
2544
  else if (this.editor.selection) left = c.dim(' ctrl+c to copy · esc to clear');
2544
- else if (this.restartRequest) left = c.dim(' ↻ restarting when this turn ends');
2545
+ else if (this.restartRequest) left = c.dim(` ${glyphs.restart} restarting when this turn ends`);
2545
2546
  else if (this.editor.mode === 'bash') left = c.magenta(' ! for bash mode');
2546
2547
  else if (this.editor.mode === 'memory') left = c.blue(' # to memorize');
2547
2548
  else left = c.dim(' ? for shortcuts');
@@ -2549,9 +2550,9 @@ export class App {
2549
2550
  left += c.dim(' · ') + c.green(`⇄ ${this.remote.viewers} watching`);
2550
2551
  }
2551
2552
  if (!flash) {
2552
- if (this.updating) left += c.dim(' · ') + c.blue(`⇣ updating ${APP_NAME} to ${this.updating}…`);
2553
- else if (this.updateRestart && this.sourceChanged && !this.restartRequest) left += c.dim(' · ') + c.blue(`↻ ${this.updateRestart} installed: restarts ${this.working() ? 'when the work is done' : 'now'}`);
2554
- else if (this.sourceChanged && !this.sourceChangedInTurn && !this.restartRequest && !this.reloading && !this.working() && this.sourceQuietAt > Date.now()) left += c.dim(' · ') + c.dim('↻ source changed: restarts once it is left alone (/restart: now)');
2553
+ if (this.updating) left += c.dim(' · ') + c.blue(`${glyphs.update} updating ${APP_NAME} to ${this.updating}…`);
2554
+ else if (this.updateRestart && this.sourceChanged && !this.restartRequest) left += c.dim(' · ') + c.blue(`${glyphs.restart} ${this.updateRestart} installed: restarts ${this.working() ? 'when the work is done' : 'now'}`);
2555
+ else if (this.sourceChanged && !this.sourceChangedInTurn && !this.restartRequest && !this.reloading && !this.working() && this.sourceQuietAt > Date.now()) left += c.dim(' · ') + c.dim(`${glyphs.restart} source changed: restarts once it is left alone (/restart: now)`);
2555
2556
  else if (this.pendingUpdate) left += c.dim(' · ') + c.dim(`update ${this.pendingUpdate} ready · ${this.updateWaitingFor ? `installs when @${this.updateWaitingFor.split(',')[0]} is idle` : 'installs when idle'}`);
2556
2557
  }
2557
2558
  const cfg = this.config;
package/src/ui/screen.js CHANGED
@@ -29,7 +29,7 @@
29
29
  // of a restart) goes on right below the output.
30
30
 
31
31
  import { PassThrough } from 'node:stream';
32
- import { ESC, wrapLine, termWidth, truncate, stringWidth, stripAnsi, graphemes, graphemeWidth, setTerminalWidths } from './ansi.js';
32
+ import { ESC, wrapLine, termWidth, truncate, stringWidth, stripAnsi, graphemes, graphemeWidth, setTerminalWidths, ambiguousGroups } from './ansi.js';
33
33
 
34
34
  const SYNC_START = '\x1b[?2026h';
35
35
  const SYNC_END = '\x1b[?2026l';
@@ -137,17 +137,45 @@ export function mouseFilter(stdin, onMouse) {
137
137
  return out;
138
138
  }
139
139
  const CPR = /\x1b\[(\d+);(\d+)R/g; // the terminal's answer to DSR 6: row;column
140
- const WIDTH_PROBES = process.platform === 'win32' ? Array.from('·…↑↓←→↻⇣⏎◷⇄•◦⏺⎿✻✢✳✶✽✉⚠') : [];
141
-
142
- // Ask the terminal where the cursor is (DSR 6): resolves with its row (1-based), or null when it does not answer.
143
- // On Windows, also measure the UI symbols whose width varies between conhosts/fonts. All probes start at column
144
- // one, fit on this row, and are erased before restoring the cursor. Run before anything else reads raw `stdin`;
145
- // keys typed meanwhile are put back byte for byte, without the terminal's replies.
140
+ // Windows: the symbols the interface is drawn with are measured at start-up (see queryCursorRow), as its terminals
141
+ // do not agree on their widths. The first FONT_SIZED of them are East Asian Ambiguous characters: a terminal that
142
+ // draws one of those in two cells sizes all such characters by its font, and is asked about all of them.
143
+ const UI_PROBES = process.platform === 'win32' ? Array.from('·…↑↓←→↻⇣⏎◷⇄•◦⏺⎿✻✢✳✶✽✉⚠') : [];
144
+ const FONT_SIZED = 6;
145
+ const AMBIGUOUS_TIMEOUT_MS = 1500; // some 200 to 400 answers: 0.2 ms each in the Windows 11 console, 0.5 on a server
146
+
147
+ // Ask the terminal where the cursor is (DSR 6): resolves with its row (1-based), or null when it does not answer
148
+ // within `timeout`. Run before anything else reads `stdin`, with the terminal in raw mode; what else arrives
149
+ // meanwhile (keys typed during start-up) is put back for the key reader, byte for byte.
150
+ //
151
+ // On Windows the widths of characters are measured too (setTerminalWidths): each one is written at the start of the
152
+ // cursor's row and the cursor's column asked for, and the row is erased afterwards. The interface's own symbols
153
+ // first; then, only where the terminal sizes ambiguous characters by its font (the console with a Chinese font: ·
154
+ // … “ ” — × ① in two cells), all of those: text with them in it was wrapped and padded as if they took one cell,
155
+ // which broke rows in two and left the footer on screen twice. Those are some 800 characters, so neighbours are
156
+ // written together first: one answer does for all of them when they are all one cell wide or all two, which most
157
+ // are, and only the others are then asked about one by one. A batch that is not answered whole in time is not used.
146
158
  export function queryCursorRow(stdin, out, timeout = 300) {
147
159
  return new Promise((resolve) => {
148
160
  let buf = Buffer.alloc(0);
149
- let timer = null, probing = false, finished = false;
161
+ let timer = null, finished = false, batch = 0;
162
+ const sent = []; // what was written to be measured (a character, or neighbours), in the order of the answers
163
+ let answered = 0; // how many of them have an answer: counted when a whole batch is in
150
164
  const replies = () => [...buf.toString('latin1').matchAll(CPR)];
165
+ const cells = (matches, i) => Number(matches[1 + i][2]) - 1;
166
+ // The width of each character of `text`, which took `n` cells: 0 when they are not all one or all two cells wide.
167
+ const uniform = (text, n) => (n === text.length ? 1 : n === 2 * text.length ? 2 : 0);
168
+ // What to measure next, decided by the answers so far.
169
+ const next = (matches) => {
170
+ batch++;
171
+ if (batch === 1) return UI_PROBES.length && !(out.columns && out.columns < 3) ? UI_PROBES : [];
172
+ if (batch === 2) {
173
+ if (!UI_PROBES.slice(0, FONT_SIZED).some((_, i) => cells(matches, i) === 2)) return [];
174
+ return ambiguousGroups(Math.max(1, Math.min(40, Math.floor(((out.columns || 80) - 2) / 2)))); // a piece fits the row at two cells each
175
+ }
176
+ if (batch === 3) return sent.flatMap((text, i) => (text.length > 1 && !uniform(text, cells(matches, i)) ? [...text] : []));
177
+ return [];
178
+ };
151
179
  const done = () => {
152
180
  if (finished) return;
153
181
  finished = true;
@@ -156,30 +184,39 @@ export function queryCursorRow(stdin, out, timeout = 300) {
156
184
  stdin.pause();
157
185
  const matches = replies();
158
186
  const first = matches[0];
159
- if (probing) {
160
- const widths = matches.slice(1).map((m, i) => [WIDTH_PROBES[i], Number(m[2]) - 1]);
161
- if (matches.length === WIDTH_PROBES.length + 1 && matches.every((m) => m[1] === first[1]) && widths.every(([, w]) => w === 1 || w === 2)) setTerminalWidths(widths);
162
- try { out.write('\r' + ESC.right(Number(first[2]) - 1) + ESC.showCursor + SYNC_END); } catch { /* terminal closed */ }
187
+ if (sent.length) {
188
+ const answers = matches.slice(1, 1 + answered);
189
+ // (an answer from another row: the screen moved meanwhile, and nothing that was measured is trusted)
190
+ if (answers.every((m) => m[1] === first[1])) {
191
+ const widths = [];
192
+ answers.forEach((m, i) => {
193
+ const width = uniform(sent[i], Number(m[2]) - 1);
194
+ if (width) for (const char of sent[i]) widths.push([char, width]);
195
+ });
196
+ setTerminalWidths(widths);
197
+ }
198
+ try { out.write('\r' + ESC.right(Number(first[2]) - 1) + ESC.showCursor + SYNC_END); } catch { /* the terminal is gone */ }
163
199
  }
164
200
  // latin1 keeps a one-to-one mapping of bytes, including keys/pastes split in the middle of a UTF-8 character.
165
201
  const rest = Buffer.from(buf.toString('latin1').replace(CPR, ''), 'latin1');
166
202
  if (rest.length) stdin.unshift(rest);
167
203
  resolve(first ? Number(first[1]) : null);
168
204
  };
205
+ const measure = (texts, ms) => {
206
+ const start = sent.length ? '' : SYNC_START + ESC.hideCursor;
207
+ sent.push(...texts);
208
+ clearTimeout(timer);
209
+ timer = setTimeout(done, ms);
210
+ try { out.write(start + texts.map((text) => '\r' + text + '\x1b[6n').join('') + '\r\x1b[K'); } catch { done(); }
211
+ };
169
212
  const onData = (d) => {
170
213
  buf = Buffer.concat([buf, Buffer.isBuffer(d) ? d : Buffer.from(String(d), 'utf8')]);
171
214
  const matches = replies();
172
- if (!matches.length) return;
173
- if (!WIDTH_PROBES.length || (out.columns && out.columns < 3)) { done(); return; }
174
- if (probing) {
175
- if (matches.length >= WIDTH_PROBES.length + 1) done();
176
- return;
177
- }
178
- probing = true;
179
- clearTimeout(timer);
180
- timer = setTimeout(done, timeout);
181
- const probes = WIDTH_PROBES.map((char) => '\r' + char + '\x1b[6n').join('');
182
- try { out.write(SYNC_START + ESC.hideCursor + probes + '\r\x1b[K'); } catch { done(); }
215
+ if (matches.length < 1 + sent.length) return; // the first answer is the cursor's position
216
+ answered = sent.length;
217
+ const more = next(matches);
218
+ if (more.length) measure(more, batch === 1 ? timeout : AMBIGUOUS_TIMEOUT_MS);
219
+ else done();
183
220
  };
184
221
  timer = setTimeout(done, timeout);
185
222
  stdin.on('data', onData);