homeagent-runner 0.4.11 → 0.4.13

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.
@@ -1,6 +1,13 @@
1
1
  import { stripVTControlCharacters } from 'node:util';
2
+ import { emitKeypressEvents } from 'node:readline';
3
+ import { PassThrough } from 'node:stream';
4
+ import { TerminalInput } from './terminal-input.js';
2
5
  import { VERSION } from '../shared/protocol.js';
3
6
  import { logoPixels } from './logo.js';
7
+ export class TuiExitError extends Error {
8
+ }
9
+ export class TuiCancelError extends Error {
10
+ }
4
11
  const ESC = '\x1b[';
5
12
  const RESET = `${ESC}0m`;
6
13
  const BRAND = {
@@ -12,6 +19,8 @@ const BRAND = {
12
19
  red: '38;2;248;81;73',
13
20
  dim: '2',
14
21
  bold: '1',
22
+ hover: '1;38;2;240;245;255;48;2;43;53;72',
23
+ pressed: '1;38;2;255;255;255;48;2;7;85;255',
15
24
  };
16
25
  const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
17
26
  const SEGMENTS = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
@@ -58,6 +67,24 @@ function cardLayout(options) {
58
67
  function paint(text, code, color) {
59
68
  return color ? `${ESC}${code}m${text}${RESET}` : text;
60
69
  }
70
+ /** Shade exact terminal cells, preserving the styles of neighboring content. */
71
+ function shadeCells(line, column, width, style) {
72
+ const padded = line + ' '.repeat(Math.max(0, column + width - displayWidth(line)));
73
+ const parts = ['', '', ''];
74
+ let cell = 0;
75
+ for (const match of padded.matchAll(/\x1b\[[0-9;]*m|[^\x1b]+/g)) {
76
+ const text = match[0];
77
+ if (text.startsWith('\x1b')) {
78
+ parts[cell < column ? 0 : cell < column + width ? 1 : 2] += text;
79
+ continue;
80
+ }
81
+ for (const { segment } of SEGMENTS.segment(text)) {
82
+ parts[cell < column ? 0 : cell < column + width ? 1 : 2] += segment;
83
+ cell += cellWidth(segment);
84
+ }
85
+ }
86
+ return parts[0] + `${ESC}${style}m` + stripAnsi(parts[1]) + RESET + parts[2];
87
+ }
61
88
  /** Quadrant glyphs retain twice the horizontal detail of half-block pixels. */
62
89
  export function renderLogo(color, columns = 32) {
63
90
  const pixels = logoPixels[columns];
@@ -77,7 +104,7 @@ export function renderLogo(color, columns = 32) {
77
104
  }
78
105
  return lines;
79
106
  }
80
- /** Startup card shown by `homeagent run` in an interactive terminal. */
107
+ /** Legacy startup card retained for non-full-screen renderers and tests. */
81
108
  export function renderRunnerCard(info, options = {}) {
82
109
  const { width, indent } = cardLayout(options);
83
110
  const color = options.color ?? false;
@@ -126,6 +153,8 @@ export function renderRunnerCard(info, options = {}) {
126
153
  export function renderStatus(state, detail, color, frame = 0) {
127
154
  const dot = (glyph, code) => paint(glyph, code, color);
128
155
  switch (state) {
156
+ case 'unpaired':
157
+ return `${dot('○', BRAND.orange)} 尚未登录`;
129
158
  case 'connecting':
130
159
  return `${dot(SPINNER[frame % SPINNER.length], BRAND.orange)} ${paint('正在连接 Server…', BRAND.dim, color)}`;
131
160
  case 'connected':
@@ -136,6 +165,196 @@ export function renderStatus(state, detail, color, frame = 0) {
136
165
  return `${dot('■', BRAND.red)} 已停止`;
137
166
  }
138
167
  }
168
+ /** A fixed-size viewport; all external text is sanitized before it is styled. */
169
+ export function renderRunnerScreen(info, state, detail, logs, options = {}, frame = 0) {
170
+ const columns = Math.max(1, Math.floor(options.columns ?? 80));
171
+ const rows = Math.max(1, Math.floor(options.rows ?? 24));
172
+ const available = Math.max(0, columns - 1);
173
+ const color = options.color ?? false;
174
+ const lines = Array(rows).fill('');
175
+ const clean = {
176
+ version: safeText(info.version ?? VERSION), device: safeText(info.device),
177
+ server: safeText(info.server), config: safeText(info.config),
178
+ node: safeText(info.node), platform: safeText(info.platform), arch: safeText(info.arch),
179
+ };
180
+ const width = Math.max(0, Math.min(available, Math.floor(options.width ?? 96)));
181
+ const left = Math.max(0, Math.floor((available - width) / 2));
182
+ const hits = options.hitRegions ?? [];
183
+ hits.length = 0;
184
+ const region = (row, column, size, action, extra = {}) => {
185
+ const visibleWidth = Math.min(size, available - column);
186
+ if (row < 0 || row >= rows || visibleWidth <= 0)
187
+ return;
188
+ hits.push({ ...extra, x: column + 1, y: row + 1, width: visibleWidth, action });
189
+ };
190
+ const styled = (text, code = BRAND.dim) => paint(text, code, color);
191
+ const put = (row, text, column = left, limit = width) => {
192
+ if (row < 0 || row >= rows)
193
+ return;
194
+ lines[row] = ' '.repeat(column) + truncate(text, Math.max(0, limit));
195
+ };
196
+ const centered = (row, text) => {
197
+ const clipped = truncate(text, width);
198
+ put(row, clipped, left + Math.max(0, Math.floor((width - displayWidth(clipped)) / 2)), width);
199
+ };
200
+ const status = renderStatus(state, detail ? safeText(detail) : undefined, color, frame);
201
+ const title = styled('›', BRAND.blue) + ' ' + styled('HomeAgent Runner', BRAND.bold) +
202
+ styled(` v${clean.version ?? VERSION}`);
203
+ put(0, title);
204
+ if (rows < 8) {
205
+ if (rows > 1)
206
+ put(1, status);
207
+ if (rows > 2)
208
+ put(rows - 1, styled('Ctrl+C 停止'));
209
+ return lines;
210
+ }
211
+ put(1, styled(clean.config));
212
+ const bodyTop = 3;
213
+ const bodyBottom = rows - 4;
214
+ const bodyHeight = Math.max(0, bodyBottom - bodyTop);
215
+ const showLogo = width >= 72 && bodyHeight >= 20;
216
+ const logoWidth = width >= 92 && bodyHeight >= 28 ? 40 : 32;
217
+ const logo = showLogo ? renderLogo(color, logoWidth) : [];
218
+ const details = state === 'unpaired' ? [
219
+ styled('欢迎使用 HomeAgent', `${BRAND.bold};${BRAND.blue}`),
220
+ styled('连接你的机器,开始协作'),
221
+ '',
222
+ styled('尚未登录。请先登录并在浏览器中批准设备。'),
223
+ '',
224
+ styled('Enter 登录设备', BRAND.bold),
225
+ styled('s 设置 · c 选择配置 · q 退出'),
226
+ ] : [
227
+ styled('HomeAgent', `${BRAND.bold};${BRAND.blue}`),
228
+ styled('你的机器,你来掌控'),
229
+ '',
230
+ styled('设备 ') + clean.device,
231
+ styled('服务 ') + clean.server,
232
+ styled('环境 ') + `${clean.node} · ${clean.platform}/${clean.arch}`,
233
+ '',
234
+ status,
235
+ ];
236
+ const heroHeight = showLogo ? logo.length : Math.min(details.length, Math.max(1, bodyHeight - 3));
237
+ const activityRows = Math.max(0, Math.min(5, bodyHeight - heroHeight - 2));
238
+ const heroTop = bodyTop + Math.max(0, Math.floor((bodyHeight - heroHeight - activityRows - 2) / 2));
239
+ if (options.dialog) {
240
+ const dialog = options.dialog;
241
+ put(bodyTop, styled(safeText(dialog.title), `${BRAND.bold};${BRAND.blue}`));
242
+ let row = bodyTop + 2;
243
+ const descriptionBudget = dialog.kind === 'progress' ? Math.max(1, bodyHeight - 4)
244
+ : Math.max(1, Math.floor(bodyHeight / 3));
245
+ for (const message of dialog.description.slice(0, descriptionBudget)) {
246
+ put(row++, styled(safeText(message)));
247
+ }
248
+ row++;
249
+ if (dialog.kind === 'input') {
250
+ const segments = [...SEGMENTS.segment(dialog.value ?? '')].map(({ segment }) => segment);
251
+ const cursor = dialog.cursor ?? segments.length;
252
+ let start = 0;
253
+ while (start < cursor && displayWidth(segments.slice(start, cursor).join('')) > Math.max(1, width - 8))
254
+ start++;
255
+ const prefix = segments.slice(start, cursor).join('');
256
+ put(row, styled('› ', BRAND.blue) + safeText(prefix) + styled('▏', BRAND.blue) + safeText(segments.slice(cursor).join('')));
257
+ if (row < bodyBottom)
258
+ region(row, left + 2, Math.max(0, width - 2), 'input', { inputStart: start, inputCursor: cursor });
259
+ if (dialog.error)
260
+ put(row + 2, styled(safeText(dialog.error), BRAND.red));
261
+ }
262
+ else if (dialog.kind === 'select') {
263
+ const choices = dialog.choices ?? [];
264
+ const count = Math.max(0, bodyBottom - row - 1);
265
+ const selectedIndex = dialog.selected ?? 0;
266
+ let start = dialog.scroll ?? 0;
267
+ if (selectedIndex < start)
268
+ start = selectedIndex;
269
+ if (selectedIndex >= start + count)
270
+ start = selectedIndex - count + 1;
271
+ start = Math.max(0, Math.min(start, choices.length - count));
272
+ dialog.scroll = start;
273
+ choices.slice(start, start + count).forEach((choice, offset) => {
274
+ const selected = start + offset === (dialog.selected ?? 0);
275
+ const label = styled(selected ? '› ' : ' ', BRAND.blue) + styled(safeText(choice.label), selected ? '1;7' : BRAND.dim);
276
+ put(row + offset, label);
277
+ region(row + offset, left, width, 'choice', { choice: start + offset });
278
+ });
279
+ const selected = choices[dialog.selected ?? 0];
280
+ if (selected?.detail)
281
+ put(bodyBottom - 1, styled(safeText(selected.detail)));
282
+ if (choices.length > count && row > bodyTop + 1)
283
+ put(row - 1, styled(`滚轮 / ↑↓ 浏览 ${(dialog.selected ?? 0) + 1}/${choices.length}`));
284
+ }
285
+ else if (dialog.error)
286
+ put(Math.min(row, bodyBottom - 1), styled(safeText(dialog.error), BRAND.red));
287
+ }
288
+ else if (showLogo) {
289
+ const detailWidth = width - logoWidth - 4;
290
+ const offset = Math.max(0, Math.floor((logo.length - details.length) / 2));
291
+ logo.forEach((line, row) => {
292
+ put(heroTop + row, line + ' ' + truncate(details[row - offset] ?? '', detailWidth));
293
+ if (options.interactive && state === 'unpaired' && row - offset === 5) {
294
+ const labelWidth = displayWidth(details[5]);
295
+ if (labelWidth <= detailWidth)
296
+ region(heroTop + row, left + logoWidth + 4, labelWidth, 'login');
297
+ }
298
+ });
299
+ }
300
+ else {
301
+ details.slice(0, heroHeight).forEach((line, row) => {
302
+ centered(heroTop + row, line);
303
+ if (options.interactive && state === 'unpaired' && row === 5 && displayWidth(line) <= width) {
304
+ region(heroTop + row, left + Math.max(0, Math.floor((width - displayWidth(line)) / 2)), displayWidth(line), 'login');
305
+ }
306
+ });
307
+ }
308
+ if (!options.dialog && activityRows > 0) {
309
+ const activity = logs.flatMap(message => message.split(/\r?\n/).map(safeText).filter(line => line.trim()));
310
+ const start = bodyBottom - activityRows;
311
+ put(start, styled('最近活动'));
312
+ const visible = activity.slice(-Math.max(0, activityRows - 1));
313
+ if (visible.length === 0 && activityRows > 1)
314
+ visible.push('等待设备活动…');
315
+ visible.slice(0, activityRows - 1).forEach((message, row) => put(start + row + 1, styled('· ') + message));
316
+ }
317
+ put(rows - 3, styled('─'.repeat(width)));
318
+ put(rows - 2, status + styled(` · ${clean.device}`));
319
+ if (options.interactive) {
320
+ const buttons = options.dialog?.kind === 'input'
321
+ ? [['Enter 确认', 'confirm'], ['Esc 返回', 'back'], ['Ctrl+U 清空', 'clear'], ['Ctrl+C 退出', 'quit']]
322
+ : options.dialog?.kind === 'select'
323
+ ? [['Enter 确认', 'confirm'], ['Esc 返回', 'back'], ['Ctrl+C 退出', 'quit']]
324
+ : options.dialog?.kind === 'progress'
325
+ ? [
326
+ ...(options.dialog.hint?.includes('o 打开') ? [['o 打开登录页面', 'open']] : []),
327
+ ...(options.dialog.hint?.includes('Esc 取消') ? [['Esc 取消', 'back']] : []),
328
+ ['Ctrl+C 退出', 'quit'],
329
+ ]
330
+ : state === 'unpaired'
331
+ ? [['Enter 登录', 'login'], ['s 设置', 'settings'], ['c 选择配置', 'config'], ['q 退出', 'quit']]
332
+ : [['s 设置', 'settings'], ['a 活动', 'activity'], ['o 网页', 'web'], ['p 暂停/连接', 'toggle'], ['q 退出', 'quit']];
333
+ // Text selection can be re-enabled without leaving the application.
334
+ buttons.push([`m 鼠标${options.mouse === false ? '关' : '开'}`, 'mouse']);
335
+ let content = '';
336
+ for (const [label, action] of buttons) {
337
+ const text = `[${label}]`;
338
+ const column = left + displayWidth(content);
339
+ if (displayWidth(content + text) > width)
340
+ break;
341
+ region(rows - 1, column, displayWidth(text), action);
342
+ content += styled(text, action === 'login' || action === 'confirm' ? BRAND.blue : BRAND.dim) + ' ';
343
+ }
344
+ put(rows - 1, content);
345
+ }
346
+ else
347
+ put(rows - 1, styled('Ctrl+C 停止 · 项目与权限在网页端配置'));
348
+ if (options.pointer && options.mouse !== false) {
349
+ const target = hits.find(hit => hit.y === options.pointer.y &&
350
+ options.pointer.x >= hit.x && options.pointer.x < hit.x + hit.width);
351
+ if (target) {
352
+ const down = options.pressed?.action === target.action && options.pressed.choice === target.choice;
353
+ lines[target.y - 1] = shadeCells(lines[target.y - 1], target.x - 1, target.width, color ? (down ? BRAND.pressed : BRAND.hover) : (down ? '1;7' : '7'));
354
+ }
355
+ }
356
+ return lines;
357
+ }
139
358
  export function tuiEnabled(stream = process.stdout, env = process.env) {
140
359
  if (env.HOMEAGENT_TUI === '0' || env.HOMEAGENT_TUI === 'plain')
141
360
  return false;
@@ -164,36 +383,83 @@ export function truecolorEnabled(stream = process.stdout, env = process.env) {
164
383
  return true;
165
384
  return typeof stream.getColorDepth === 'function' && stream.getColorDepth() >= 24;
166
385
  }
167
- /** Keep the connection status on one line below the log stream. */
386
+ /** Own the alternate screen while running, restoring the shell on shutdown. */
168
387
  export class RunnerTui {
169
388
  info;
170
389
  options;
171
390
  timer;
172
391
  exitHandler;
392
+ resizeHandler;
173
393
  state = 'connecting';
174
394
  detail;
175
395
  retryAt;
176
396
  frame = 0;
177
- statusDrawn = false;
397
+ logs = [];
178
398
  started = false;
399
+ dialog;
400
+ pending;
401
+ progressCancel;
402
+ progressOpen;
403
+ progressCancelable = true;
404
+ keyHandler;
405
+ dataHandler;
406
+ keyboard;
407
+ terminalInput;
408
+ hitRegions = [];
409
+ pressed;
410
+ pointer;
411
+ wasRaw = false;
412
+ wasFlowing = false;
413
+ exitRequested = false;
414
+ mouseEnabled = false;
179
415
  constructor(info, options = {}) {
180
416
  this.info = info;
181
417
  this.options = options;
182
418
  }
183
419
  get stream() { return this.options.stream ?? process.stdout; }
184
420
  get color() { return this.options.color ?? truecolorEnabled(this.stream, process.env); }
185
- get indent() {
186
- return cardLayout({ ...this.options, columns: this.options.columns ?? this.stream.columns }).indent;
187
- }
421
+ get inputStream() { return this.options.input ?? process.stdin; }
188
422
  start() {
189
423
  if (this.started)
190
424
  return;
191
425
  this.started = true;
192
- const columns = this.options.columns ?? this.stream.columns ?? 80;
193
- this.stream.write(renderRunnerCard(this.info, { ...this.options, columns, color: this.color }).join('\n') + '\n\n');
194
- this.stream.write(`${ESC}?25l`);
195
- this.exitHandler = () => this.stream.write(`${ESC}?25h`);
426
+ this.stream.write(`${ESC}?1049h${ESC}?25l${ESC}2J${ESC}H`);
427
+ this.exitHandler = () => this.stop();
196
428
  process.on('exit', this.exitHandler);
429
+ this.resizeHandler = () => {
430
+ this.pressed = undefined;
431
+ this.pointer = undefined;
432
+ if (this.started)
433
+ this.draw();
434
+ };
435
+ this.stream.on?.('resize', this.resizeHandler);
436
+ if (this.options.interactive && this.inputStream.isTTY) {
437
+ const input = this.inputStream;
438
+ this.wasRaw = Boolean(input.isRaw);
439
+ this.wasFlowing = input.readableFlowing === true;
440
+ // A separate stream receives only keyboard frames. Raw mouse/paste
441
+ // reports never reach readline or turn into form text and shortcuts.
442
+ this.keyboard = new PassThrough();
443
+ emitKeypressEvents(this.keyboard);
444
+ input.setRawMode(true);
445
+ this.keyHandler = (text, key) => this.handleKey(text, key);
446
+ this.keyboard.on('keypress', this.keyHandler);
447
+ this.terminalInput = new TerminalInput({
448
+ keyboard: text => {
449
+ if (text === '\x1b')
450
+ this.handleKey('', { name: 'escape' });
451
+ else
452
+ this.keyboard?.write(text);
453
+ },
454
+ mouse: event => this.handleMouse(event),
455
+ paste: text => this.insertText(text),
456
+ });
457
+ this.dataHandler = chunk => this.terminalInput?.feed(chunk);
458
+ input.on('data', this.dataHandler);
459
+ input.resume();
460
+ this.mouseEnabled = this.options.mouse !== false && process.env.HOMEAGENT_MOUSE !== '0';
461
+ this.stream.write((this.mouseEnabled ? `${ESC}?1000h${ESC}?1003h${ESC}?1006h` : '') + `${ESC}?2004h`);
462
+ }
197
463
  this.draw();
198
464
  this.timer = setInterval(() => {
199
465
  this.frame += 1;
@@ -203,7 +469,7 @@ export class RunnerTui {
203
469
  this.timer.unref();
204
470
  }
205
471
  setState(state, detail) {
206
- if (state === 'stopped' && this.started) {
472
+ if (state === 'stopped' && this.started && !this.options.keepOpenOnStop) {
207
473
  this.stop();
208
474
  return;
209
475
  }
@@ -223,13 +489,287 @@ export class RunnerTui {
223
489
  this.draw();
224
490
  }
225
491
  log(message) {
226
- const text = message.split(/\r?\n/).map(safeText).join('\n') + '\n';
492
+ const entries = message.split(/\r?\n/).map(safeText);
227
493
  if (!this.started) {
228
- this.stream.write(text);
494
+ this.stream.write(entries.join('\n') + '\n');
495
+ return;
496
+ }
497
+ this.logs.push(...entries);
498
+ this.logs = this.logs.slice(-200);
499
+ this.draw();
500
+ }
501
+ updateInfo(info) {
502
+ Object.assign(this.info, info);
503
+ if (this.started)
504
+ this.draw();
505
+ }
506
+ async prompt(dialog, validate) {
507
+ if (this.exitRequested)
508
+ throw new TuiExitError('Exit requested');
509
+ if (this.pending || this.progressCancel)
510
+ throw new Error('Another interaction is already open');
511
+ this.dialog = dialog;
512
+ this.pressed = undefined;
513
+ this.pointer = undefined;
514
+ try {
515
+ return await new Promise((resolve, reject) => {
516
+ this.pending = { resolve, reject, validate };
517
+ this.draw();
518
+ });
519
+ }
520
+ finally {
521
+ this.pending = undefined;
522
+ this.dialog = undefined;
523
+ if (this.started)
524
+ this.draw();
525
+ }
526
+ }
527
+ select(title, choices, description = []) {
528
+ return this.prompt({ kind: 'select', title, choices, description, selected: 0 });
529
+ }
530
+ ask(title, value = '', description = [], validate) {
531
+ return this.prompt({ kind: 'input', title, value, cursor: [...SEGMENTS.segment(value)].length, description }, validate);
532
+ }
533
+ waitForAction() { return this.prompt(); }
534
+ activity() {
535
+ return this.select('最近活动', [
536
+ ...this.logs.filter(line => line.trim()).map((line, index) => ({ value: String(index), label: line })),
537
+ { value: 'back', label: '返回总览' },
538
+ ], ['↑↓ 浏览活动,Esc 返回;完整任务与审计记录可在网页中查看。']);
539
+ }
540
+ showProgress(title, description) {
541
+ this.pressed = undefined;
542
+ this.pointer = undefined;
543
+ this.dialog = { kind: 'progress', title, description, hint: !this.progressCancelable ? '正在应用设置,请稍候 · Ctrl+C 完成后退出'
544
+ : this.progressOpen ? 'o 打开登录页面 · Esc 取消 · Ctrl+C 退出' : 'Esc 取消 · Ctrl+C 退出' };
545
+ if (this.started)
546
+ this.draw();
547
+ }
548
+ async progress(title, description, run, onOpen, cancelable = true) {
549
+ if (this.exitRequested)
550
+ throw new TuiExitError('Exit requested');
551
+ if (this.pending || this.progressCancel)
552
+ throw new Error('Another interaction is already open');
553
+ const controller = new AbortController();
554
+ this.progressCancel = error => controller.abort(error);
555
+ this.progressOpen = onOpen;
556
+ this.progressCancelable = cancelable;
557
+ this.showProgress(title, description);
558
+ try {
559
+ const result = await run(controller.signal);
560
+ controller.signal.throwIfAborted();
561
+ return result;
562
+ }
563
+ catch (error) {
564
+ if (controller.signal.aborted)
565
+ throw controller.signal.reason;
566
+ throw error;
567
+ }
568
+ finally {
569
+ this.progressCancel = undefined;
570
+ this.progressOpen = undefined;
571
+ this.progressCancelable = true;
572
+ this.dialog = undefined;
573
+ if (this.started)
574
+ this.draw();
575
+ }
576
+ }
577
+ requestExit() {
578
+ this.exitRequested = true;
579
+ const error = new TuiExitError('Exit requested');
580
+ this.progressCancel?.(error);
581
+ this.pending?.reject(error);
582
+ }
583
+ handleKey(text, key) {
584
+ if (key.ctrl && key.name === 'c') {
585
+ this.requestExit();
586
+ return;
587
+ }
588
+ if (!key.ctrl && !key.meta && key.name === 'm' && this.dialog?.kind !== 'input') {
589
+ this.toggleMouse();
590
+ return;
591
+ }
592
+ if (this.progressCancel) {
593
+ if (key.name === 'escape' && this.progressCancelable)
594
+ this.progressCancel(new TuiCancelError('操作已取消'));
595
+ if (key.name === 'o' && this.progressOpen)
596
+ void this.progressOpen().catch(error => {
597
+ if (this.dialog) {
598
+ this.dialog.error = error instanceof Error ? error.message : '无法打开浏览器';
599
+ this.draw();
600
+ }
601
+ });
229
602
  return;
230
603
  }
231
- this.clearLine();
232
- this.stream.write(text);
604
+ const pending = this.pending;
605
+ if (!pending)
606
+ return;
607
+ const dialog = this.dialog;
608
+ if (!dialog) {
609
+ const action = key.name === 'return' ? (this.state === 'unpaired' ? 'login' : 'settings')
610
+ : { s: 'settings', a: 'activity', o: 'web', p: 'toggle', q: 'quit', c: 'config', l: 'login', '?': 'help' }[text || key.name || ''];
611
+ if (action)
612
+ pending.resolve(action);
613
+ return;
614
+ }
615
+ if (key.name === 'escape') {
616
+ pending.resolve(undefined);
617
+ return;
618
+ }
619
+ if (dialog.kind === 'select') {
620
+ const count = dialog.choices?.length ?? 0;
621
+ if (key.name === 'up')
622
+ dialog.selected = ((dialog.selected ?? 0) + count - 1) % Math.max(1, count);
623
+ if (key.name === 'down' || key.name === 'tab')
624
+ dialog.selected = ((dialog.selected ?? 0) + 1) % Math.max(1, count);
625
+ if (key.name === 'return') {
626
+ pending.resolve(dialog.choices?.[dialog.selected ?? 0]?.value);
627
+ return;
628
+ }
629
+ }
630
+ else if (dialog.kind === 'input') {
631
+ const segments = [...SEGMENTS.segment(dialog.value ?? '')].map(({ segment }) => segment);
632
+ let cursor = Math.min(dialog.cursor ?? segments.length, segments.length);
633
+ if (key.name === 'return') {
634
+ const value = (dialog.value ?? '').trim();
635
+ dialog.error = pending.validate?.(value);
636
+ if (!dialog.error) {
637
+ pending.resolve(value);
638
+ return;
639
+ }
640
+ }
641
+ else if (key.ctrl && key.name === 'u') {
642
+ segments.length = 0;
643
+ cursor = 0;
644
+ }
645
+ else if (key.name === 'left')
646
+ cursor = Math.max(0, cursor - 1);
647
+ else if (key.name === 'right')
648
+ cursor = Math.min(segments.length, cursor + 1);
649
+ else if (key.name === 'home' || key.ctrl && key.name === 'a')
650
+ cursor = 0;
651
+ else if (key.name === 'end' || key.ctrl && key.name === 'e')
652
+ cursor = segments.length;
653
+ else if (key.name === 'backspace' && cursor > 0)
654
+ segments.splice(--cursor, 1);
655
+ else if (key.name === 'delete')
656
+ segments.splice(cursor, 1);
657
+ else if (!key.ctrl && !key.meta && text && !/[\p{Cc}]/u.test(text)) {
658
+ this.insertText(text);
659
+ return;
660
+ }
661
+ dialog.value = segments.join('');
662
+ dialog.cursor = cursor;
663
+ }
664
+ this.draw();
665
+ }
666
+ insertText(text) {
667
+ const dialog = this.dialog;
668
+ if (!this.pending || dialog?.kind !== 'input')
669
+ return;
670
+ const clean = safeText(text.replace(/[\r\n\t]+/g, ' '));
671
+ const segments = [...SEGMENTS.segment(dialog.value ?? '')].map(({ segment }) => segment);
672
+ const cursor = Math.min(dialog.cursor ?? segments.length, segments.length);
673
+ const before = segments.slice(0, cursor).join('') + clean;
674
+ const combined = before + segments.slice(cursor).join('');
675
+ const next = [...SEGMENTS.segment(combined)].map(({ segment }) => segment).slice(0, 4096);
676
+ dialog.value = next.join('');
677
+ // Re-segment the prefix as well, so combining marks and emoji joiners
678
+ // stay editable as one grapheme even when delivered in separate chunks.
679
+ dialog.cursor = Math.min([...SEGMENTS.segment(before)].length, next.length);
680
+ dialog.error = undefined;
681
+ this.draw();
682
+ }
683
+ handleMouse(event) {
684
+ if (!this.mouseEnabled)
685
+ return;
686
+ const columns = this.options.columns ?? this.stream.columns ?? 80;
687
+ const rows = this.options.rows ?? this.stream.rows ?? 24;
688
+ const previousTarget = this.pointer && this.hitRegions.find(hit => hit.y === this.pointer.y &&
689
+ this.pointer.x >= hit.x && this.pointer.x < hit.x + hit.width);
690
+ if (event.modified || event.x > columns || event.y > rows) {
691
+ this.pointer = undefined;
692
+ this.pressed = undefined;
693
+ if (previousTarget)
694
+ this.draw();
695
+ return;
696
+ }
697
+ this.pointer = { x: event.x, y: event.y };
698
+ const target = this.hitRegions.find(hit => event.y === hit.y && event.x >= hit.x && event.x < hit.x + hit.width);
699
+ if (event.type === 'motion') {
700
+ // Redraw on entering/leaving a control, not for every pixel of movement.
701
+ if (target !== previousTarget)
702
+ this.draw();
703
+ return;
704
+ }
705
+ const dialog = this.dialog;
706
+ if (event.button === 'wheel-up' || event.button === 'wheel-down') {
707
+ // SGR terminals send wheel presses without a corresponding release.
708
+ if (event.type !== 'press' || dialog?.kind !== 'select')
709
+ return;
710
+ this.pressed = undefined;
711
+ const last = Math.max(0, (dialog.choices?.length ?? 0) - 1);
712
+ dialog.selected = Math.max(0, Math.min(last, (dialog.selected ?? 0) + (event.button === 'wheel-down' ? 1 : -1)));
713
+ this.draw();
714
+ return;
715
+ }
716
+ if (event.button !== 'left')
717
+ return;
718
+ if (event.type === 'press') {
719
+ this.pressed = target ? { action: target.action, choice: target.choice, dialog } : undefined;
720
+ if (dialog?.kind === 'select' && target?.choice !== undefined) {
721
+ dialog.selected = target.choice;
722
+ }
723
+ this.draw();
724
+ return;
725
+ }
726
+ const pressed = this.pressed;
727
+ this.pressed = undefined;
728
+ if (pressed)
729
+ this.draw();
730
+ if (!target || !pressed || pressed.dialog !== dialog || pressed.action !== target.action || pressed.choice !== target.choice)
731
+ return;
732
+ if (target.action === 'input' && dialog?.kind === 'input') {
733
+ const segments = [...SEGMENTS.segment(dialog.value ?? '')].map(({ segment }) => segment);
734
+ let cursor = target.inputStart ?? 0, cell = target.x;
735
+ for (; cursor < segments.length; cursor++) {
736
+ if (cursor === target.inputCursor) {
737
+ if (event.x <= cell)
738
+ break;
739
+ cell++; // The visible cursor marker itself occupies a cell.
740
+ }
741
+ const next = cell + displayWidth(segments[cursor]);
742
+ if (event.x < next)
743
+ break;
744
+ cell = next;
745
+ }
746
+ dialog.cursor = cursor;
747
+ this.draw();
748
+ }
749
+ else if (target.action === 'mouse')
750
+ this.toggleMouse();
751
+ else if (target.action === 'quit')
752
+ this.requestExit();
753
+ else if (target.action === 'open')
754
+ this.handleKey('o', { name: 'o' });
755
+ else if (target.action === 'back')
756
+ this.handleKey('', { name: 'escape' });
757
+ else if (target.action === 'confirm')
758
+ this.handleKey('', { name: 'return' });
759
+ else if (target.action === 'clear')
760
+ this.handleKey('', { name: 'u', ctrl: true });
761
+ else if (target.action === 'choice' && dialog?.kind === 'select')
762
+ this.pending?.resolve(dialog.choices?.[target.choice]?.value);
763
+ else if (!dialog)
764
+ this.pending?.resolve(target.action);
765
+ }
766
+ toggleMouse() {
767
+ if (!this.keyHandler)
768
+ return;
769
+ this.mouseEnabled = !this.mouseEnabled;
770
+ this.pressed = undefined;
771
+ this.pointer = undefined;
772
+ this.stream.write(this.mouseEnabled ? `${ESC}?1000h${ESC}?1003h${ESC}?1006h` : `${ESC}?1003l${ESC}?1006l${ESC}?1000l`);
233
773
  this.draw();
234
774
  }
235
775
  stop() {
@@ -238,30 +778,47 @@ export class RunnerTui {
238
778
  if (this.timer)
239
779
  clearInterval(this.timer);
240
780
  this.timer = undefined;
241
- this.clearLine();
242
781
  this.state = 'stopped';
243
- const columns = this.options.columns ?? this.stream.columns ?? 80;
244
- this.stream.write(this.indent + truncate(renderStatus('stopped', undefined, this.color, this.frame), Math.max(0, columns - this.indent.length - 1)) + '\n');
245
- this.stream.write(`${ESC}?25h`);
782
+ this.draw();
783
+ this.stream.write(`${RESET}${ESC}?2004l${ESC}?1003l${ESC}?1006l${ESC}?1000l${ESC}?1049l${ESC}?25h`);
246
784
  if (this.exitHandler) {
247
785
  process.off('exit', this.exitHandler);
248
786
  this.exitHandler = undefined;
249
787
  }
788
+ if (this.resizeHandler)
789
+ this.stream.off?.('resize', this.resizeHandler);
790
+ this.resizeHandler = undefined;
791
+ if (this.keyHandler) {
792
+ this.terminalInput?.close();
793
+ this.terminalInput = undefined;
794
+ this.keyboard?.off('keypress', this.keyHandler);
795
+ this.keyboard?.destroy();
796
+ this.keyboard = undefined;
797
+ if (this.dataHandler)
798
+ this.inputStream.off('data', this.dataHandler);
799
+ this.inputStream.setRawMode(this.wasRaw);
800
+ if (!this.wasFlowing)
801
+ this.inputStream.pause();
802
+ this.keyHandler = undefined;
803
+ this.dataHandler = undefined;
804
+ }
805
+ this.pressed = undefined;
806
+ this.pointer = undefined;
807
+ this.hitRegions = [];
808
+ this.mouseEnabled = false;
809
+ this.pending?.reject(new TuiExitError('Terminal closed'));
250
810
  this.started = false;
251
811
  }
252
812
  draw() {
253
- const columns = Math.max(1, this.options.columns ?? this.stream.columns ?? 80);
813
+ const columns = Math.max(1, Math.floor(this.options.columns ?? this.stream.columns ?? 80));
814
+ const rows = Math.max(1, Math.floor(this.options.rows ?? this.stream.rows ?? 24));
254
815
  const detail = this.retryAt === undefined ? this.detail : `${Math.max(0, Math.ceil((this.retryAt - Date.now()) / 1000))}s`;
255
- const status = renderStatus(this.state, detail ? safeText(detail) : undefined, this.color, this.frame);
256
- const indent = this.indent;
257
- this.stream.write('\r' + `${ESC}2K` + indent + truncate(status, Math.max(0, columns - indent.length - 1)));
258
- this.statusDrawn = true;
259
- }
260
- clearLine() {
261
- if (!this.statusDrawn)
262
- return;
263
- this.stream.write('\r' + `${ESC}2K`);
264
- this.statusDrawn = false;
816
+ const lines = renderRunnerScreen(this.info, this.state, detail, this.logs, {
817
+ ...this.options, columns, rows, color: this.color, dialog: this.dialog, hitRegions: this.hitRegions, mouse: this.mouseEnabled,
818
+ pointer: this.pointer, pressed: this.pressed,
819
+ }, this.frame);
820
+ // Avoid newlines and the last cell: neither redraw nor resize may scroll.
821
+ this.stream.write(lines.map((line, row) => `${ESC}${row + 1};1H${ESC}2K${line}`).join('') + `${ESC}H`);
265
822
  }
266
823
  }
267
824
  //# sourceMappingURL=tui.js.map