heartcode 0.1.45 → 0.1.56

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/src/ui.js CHANGED
@@ -78,6 +78,9 @@ export const THEMES = {
78
78
  }
79
79
  export const c = { bold: sgr(1, 22), italic: sgr(3, 23) }
80
80
  export let background = '' // the theme's background, as an escape sequence ('' = the terminal's)
81
+ let foreground = '' // and its text color, with it: the terminal's own may not show on it (light on a dark terminal)
82
+ // A row painted in the theme's background (and text color, where a style ends its own)
83
+ const paintBg = (t) => t.replace(/\x1b\[(0|39|49)?m/g, (m, n) => m + (n === '39' ? foreground : n === '49' ? background : background + foreground))
81
84
  // Each palette color's opening sequence, to recolor what's already on screen (UI.recolor).
82
85
  export const themeCodes = () => Object.fromEntries(Object.keys(THEMES.dark).filter((k) => k !== 'background').map((k) => [k, c[k]('\0').split('\0')[0]]))
83
86
  export function setTheme(name = 'dark') {
@@ -93,6 +96,7 @@ export function setTheme(name = 'dark') {
93
96
  const [bgHex, bgBasic] = t.background ?? [null]
94
97
  delete t.background
95
98
  background = color && bgHex ? bg(bgHex, bgBasic)('\0').split('\0')[0] : ''
99
+ foreground = background && t.text[0] ? fg(t.text[0], t.text[1])('\0').split('\0')[0] : ''
96
100
  for (const [k, [hex, basic]] of Object.entries(t)) {
97
101
  if (!hex) c[k] = k === 'select' ? sgr(7, 27) : basic === 1 ? sgr(1, 22) : basic === 2 ? sgr(2, 22) : (s) => String(s)
98
102
  else c[k] = (k === 'select' ? bg : fg)(hex, basic)
@@ -103,23 +107,24 @@ export function setTheme(name = 'dark') {
103
107
  }
104
108
  setTheme()
105
109
 
106
- // keybindings.json: { "ctrl+o": "cycle_permissions", "ctrl+g": "/toggle_thinking", "shift+tab": "none" }.
110
+ // keybindings.json: { "alt+o": "cycle_permissions", "alt+g": "/toggle_thinking", "shift+tab": "none" }.
107
111
  // Actions: stop, send_first, send_all, queue_mode, cycle_permissions, newline, clear_input, scroll_up, scroll_down (a page),
108
112
  // scroll_line_up, scroll_line_down (3 lines), scroll_top, scroll_bottom, voice, new_tab,
109
113
  // close_tab, next_tab, prev_tab, tab_1…tab_9, none (turns a
110
114
  // built-in key off); anything else is sent as typed (a /command or a message). Ctrl+C stays Ctrl+C.
111
115
  const CONTROL_KEYS = { '\x1c': 'ctrl+\\', '\x1d': 'ctrl+]', '\x1e': 'ctrl+^', '\x1f': 'ctrl+_' } // no name from readline
112
116
  export const keyId = (key, s = '') => CONTROL_KEYS[key.sequence ?? s] ?? [key.ctrl && 'ctrl', key.meta && 'alt', key.shift && 'shift', key.name ?? s].filter(Boolean).join('+').toLowerCase()
113
- // The built-in keys use Alt/Option, not Ctrl, so they don't clash with the shell and readline (Ctrl+N/P
114
- // history, Ctrl+T transpose, Ctrl+Q flow-control, Ctrl+\ quit). On macOS Terminal.app, Alt keys need
115
- // "Use Option as Meta key" on (Settings → Profiles → Keyboard); Ctrl+PgUp/PgDn cycle tabs without it.
117
+ // The built-in keys use Alt/Option, never Ctrl (the user's rule; Ctrl keys also clash with the shell and
118
+ // readline: Ctrl+N/P history, Ctrl+T transpose, Ctrl+Q flow-control, Ctrl+\ quit). Only Ctrl+C (stop)
119
+ // and Ctrl+D (quit) stay, the terminal's own. On macOS Terminal.app, Alt keys need "Use Option as Meta
120
+ // key" on (Settings → Profiles → Keyboard).
116
121
  // While it works, Enter queues a message; Alt+S stops the answer and sends the first queued one,
117
122
  // Alt+A all of them (as one message); Alt+M switches what goes when an answer is done (all or the
118
123
  // next one). /voice records (Space in an empty box, or a key in keybindings.json); Alt+T, Alt+W,
119
- // Alt+N/P (or Ctrl+PgDn/PgUp), Alt+1…9: tabs; Shift+↑↓ and Alt+↑↓ scroll the conversation (as
120
- // PgUp/PgDn and the mouse wheel do), Alt+Shift+↑↓ (or Ctrl+Home/End) to its top and bottom.
124
+ // Alt+N/P, Alt+1…9: tabs; Shift+↑↓ and Alt+↑↓ scroll the conversation (as PgUp/PgDn and the mouse
125
+ // wheel do), Alt+Shift+↑↓ to its top and bottom; Alt+O: all of the model's thinking, or its last lines.
121
126
  // keybindings.json can move any of them.
122
- export const DEFAULT_KEYS = { 'alt+b': 'background_log', 'alt+s': 'send_first', 'alt+a': 'send_all', 'alt+m': 'queue_mode', 'shift+up': 'scroll_line_up', 'shift+down': 'scroll_line_down', 'alt+up': 'scroll_up', 'alt+down': 'scroll_down', 'alt+shift+up': 'scroll_top', 'alt+shift+down': 'scroll_bottom', 'ctrl+home': 'scroll_top', 'ctrl+end': 'scroll_bottom', 'alt+t': 'new_tab', 'alt+w': 'close_tab', 'alt+n': 'next_tab', 'alt+p': 'prev_tab', 'ctrl+pagedown': 'next_tab', 'ctrl+pageup': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
127
+ export const DEFAULT_KEYS = { 'alt+o': '/toggle_thinking', 'alt+b': 'background_log', 'alt+s': 'send_first', 'alt+a': 'send_all', 'alt+m': 'queue_mode', 'shift+up': 'scroll_line_up', 'shift+down': 'scroll_line_down', 'alt+up': 'scroll_up', 'alt+down': 'scroll_down', 'alt+shift+up': 'scroll_top', 'alt+shift+down': 'scroll_bottom', 'alt+t': 'new_tab', 'alt+w': 'close_tab', 'alt+n': 'next_tab', 'alt+p': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
123
128
  export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
124
129
  let raw = {}
125
130
  try {
@@ -135,9 +140,11 @@ export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
135
140
  const MOUSE_ON = '\x1b[?1000h\x1b[?1002h\x1b[?1006h'
136
141
  const MOUSE_OFF = '\x1b[?1006l\x1b[?1002l\x1b[?1000l'
137
142
 
138
- // The system clipboard (pbcopy, clip, wl-copy, xclip, xsel); else the terminal's (OSC 52, works over SSH too).
143
+ // The system clipboard (pbcopy, clip, wl-copy, xclip, xsel); else the terminal's (OSC 52). Over SSH,
144
+ // the terminal's only: the system's would be the remote machine's, not the one you're at.
139
145
  export function copyText(text) {
140
- const tools = process.platform === 'darwin' ? [['pbcopy']] : process.platform === 'win32' ? [['clip']] : [['wl-copy'], ['xclip', '-selection', 'clipboard'], ['xsel', '-b', '-i']]
146
+ const remote = Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.SSH_CLIENT)
147
+ const tools = remote ? [] : process.platform === 'darwin' ? [['pbcopy']] : process.platform === 'win32' ? [['clip']] : [['wl-copy'], ['xclip', '-selection', 'clipboard'], ['xsel', '-b', '-i']]
141
148
  for (const [cmd, ...args] of tools) if (spawnSync(cmd, args, { input: text, stdio: ['pipe', 'ignore', 'ignore'] }).status === 0) return 'system'
142
149
  process.stdout.write(`\x1b]52;c;${Buffer.from(text).toString('base64')}\x07`)
143
150
  return 'osc'
@@ -303,6 +310,8 @@ function sgrState(state = {}, text) {
303
310
  }
304
311
  const sgrPrefix = (st = {}) => [st.fg, st.bg, st.bold, st.italic].filter(Boolean).map((x) => `\x1b[${x}m`).join('')
305
312
 
313
+ const plainOf = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
314
+
306
315
  // Cuts a colored line to `cols` cells.
307
316
  function fit(line, cols) {
308
317
  return wrapAnsi(line, cols)[0]
@@ -353,13 +362,14 @@ export function wrapAnsi(line, cols) {
353
362
  return rows
354
363
  }
355
364
 
356
- // wrapAnsi at spaces: a word moves to the next row whole (one longer than a row is still cut)
357
- export function wrapWords(line, cols) {
365
+ // wrapAnsi at spaces: a word moves to the next row whole (one longer than a row is still cut);
366
+ // hang: the rows after the first indented by that many cells
367
+ export function wrapWords(line, cols, hang = 0) {
358
368
  const width = (x) => x.replace(/\x1b\[[0-9;]*m/g, '').length
359
369
  const rows = []
360
370
  let row = ''
361
371
  for (const word of line.split(/(?<= )/)) {
362
- if (width(row.trim()) && width(row + word.trimEnd()) > cols) {
372
+ if (width(row.trim()) && width(row + word.trimEnd()) > (rows.length ? cols - hang : cols)) {
363
373
  const style = (row.match(/\x1b\[[0-9;]*m/g) ?? []).reduce((st, e) => (e === '\x1b[0m' ? '' : st + e), '') // colors still on: carried to the next row
364
374
  rows.push(row.trimEnd() + (style ? '\x1b[0m' : ''))
365
375
  row = style
@@ -367,7 +377,33 @@ export function wrapWords(line, cols) {
367
377
  row += word
368
378
  }
369
379
  rows.push(row)
370
- return rows.flatMap((r) => wrapAnsi(r, cols))
380
+ const pad = ' '.repeat(hang)
381
+ return rows.flatMap((r, i) => {
382
+ const [head, ...more] = wrapAnsi(r, i ? cols - hang : cols)
383
+ return [i ? pad + head : head, ...(more.length ? wrapAnsi(more.join(''), cols - hang).map((x) => pad + x) : [])]
384
+ })
385
+ }
386
+
387
+ // wrapWords with a hanging indent: wrapped rows go under the text, not back to column 0 (after a
388
+ // marker like "! ", "● ", "⎿ ", or a two-column line's description column)
389
+ export function wrapHang(line, cols) {
390
+ const plain = line.replace(/\x1b\[[0-9;]*m/g, '')
391
+ if (width(plain) <= cols) return [line]
392
+ const m = /^\s*(?:[^\w\s]{1,2}|\d{1,3}[.)]) (?=\S)/.exec(plain) ?? /^\s*\S.*?\S {2,}(?=\S)/.exec(plain) ?? /^\s*/.exec(plain)
393
+ const hang = width(m[0])
394
+ return wrapWords(line, cols, hang < cols * 0.6 ? hang : 0)
395
+ }
396
+
397
+ // "a · b · c" on as many rows as it needs, broken between its parts (never inside one)
398
+ export function wrapParts(line, cols, sep = ' · ') {
399
+ const vis = (x) => width(x.replace(/\x1b\[[0-9;]*m/g, ''))
400
+ return line.split(sep).reduce((rows, k) => (rows.length && vis(rows.at(-1) + sep + k) <= cols ? (rows[rows.length - 1] += sep + k) : rows.push(k), rows), [])
401
+ }
402
+
403
+ // 4000 → "4s", 75000 → "1m 15s", 2h 3m: a clock that fits on a busy line
404
+ const short = (ms) => {
405
+ const s = Math.max(0, Math.floor(ms / 1000))
406
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${Math.floor(s / 3600)}h ${Math.floor(s / 60) % 60}m`
371
407
  }
372
408
 
373
409
  // Streams text as an indented, word-wrapped block: "<marker>first line\n next line".
@@ -398,7 +434,7 @@ export class Block {
398
434
  out += '\n'.repeat(Math.min(this.newlines, 2)) + this.indent
399
435
  this.col = this.indent.length
400
436
  this.newlines = 0
401
- } else if (this.col >= this.width || (ch === ' ' && this.col >= this.width - 12)) {
437
+ } else if (!this.nowrap && (this.col >= this.width || (ch === ' ' && this.col >= this.width - 12))) {
402
438
  out += '\n' + this.indent + this.hang
403
439
  this.col = this.indent.length + this.hang.length
404
440
  if (ch === ' ') continue
@@ -414,9 +450,10 @@ export class Block {
414
450
  }
415
451
  }
416
452
 
417
- // The model's Markdown, drawn as it streams in: headings, lists, quotes, code blocks, rules,
418
- // **bold**, *italic* and `code`. Into a Block (which wraps); held back only while a line's start
419
- // or a "*" could still be a marker. Tables and links stay as written.
453
+ // The model's Markdown, drawn as it streams in: headings, lists, quotes, code blocks (with a gutter),
454
+ // tables (in columns: held back until the table ends), rules, **bold**, *italic* and `code`. Into a
455
+ // Block (which wraps); held back only while a line's start or a "*" could still be a marker. Links
456
+ // stay as written.
420
457
  export class Markdown {
421
458
  constructor(block, base = (x) => x) {
422
459
  Object.assign(this, { block, base, buf: '', sol: true, fence: false, bold: false, ital: false, code: false, line: null, prev: ' ' })
@@ -452,7 +489,11 @@ export class Markdown {
452
489
  this.fence = !this.fence
453
490
  return nl < 0 ? s.length : nl + 1 // the fence line itself isn't shown
454
491
  }
455
- if (this.fence) return 0
492
+ if (this.fence) {
493
+ b.hang = ' '
494
+ this.#out('│ ', c.ghost) // code, set apart from the prose
495
+ return 0
496
+ }
456
497
  if (whole && /^\s*([-*_])(\s*\1){2,}\s*$/.test(head)) {
457
498
  this.#out('─'.repeat(Math.min(40, b.width - b.indent.length)), c.ghost)
458
499
  return head.length
@@ -475,21 +516,72 @@ export class Markdown {
475
516
  if ((m = /^\s*>\s?/.exec(head))) {
476
517
  b.hang = ' '
477
518
  this.line = (x) => c.faint(c.italic(x))
478
- this.#out('│ ', c.ghost)
519
+ this.#out('▎ ', c.accent) // a quote: not the code gutter's │
479
520
  return m[0].length
480
521
  }
481
522
  return 0
482
523
  }
524
+ // A table ("| a | b |" rows, "|---|" under the head): once it has ended (false: not yet), drawn
525
+ // in columns fitted to the width, the head bold, a rule under it. Returns how much of s it took.
526
+ #table(s, final) {
527
+ const lines = []
528
+ let at = 0
529
+ for (;;) {
530
+ const nl = s.indexOf('\n', at)
531
+ if (nl < 0) {
532
+ const rest = s.slice(at)
533
+ if (/^[ \t]*[^ \t|]/.test(rest)) break // the next line isn't a row: the table is over
534
+ if (!final) return false // a row still coming, or the table may go on
535
+ if (rest.trim()) lines.push(rest), (at = s.length)
536
+ break
537
+ }
538
+ const line = s.slice(at, nl)
539
+ if (!/^[ \t]*\|/.test(line)) break
540
+ lines.push(line)
541
+ at = nl + 1
542
+ }
543
+ const sep = (l) => /^[ \t]*\|?[ \t]*:?-{2,}:?[ \t]*(\|[ \t]*:?-{2,}:?[ \t]*)*\|?[ \t]*$/.test(l)
544
+ const b = this.block
545
+ if (!lines.some(sep)) {
546
+ for (const l of lines) this.#out(l + '\n', this.base) // not a table after all: as written
547
+ return at
548
+ }
549
+ const strip = (t) => t.replace(/\*\*|__|`/g, '').trim()
550
+ const rows = lines.filter((l) => !sep(l)).map((l) => l.trim().replace(/^\||\|$/g, '').split('|').map(strip))
551
+ const n = Math.max(...rows.map((r) => r.length))
552
+ const wide = [...Array(n)].map((_, k) => Math.max(1, ...rows.map((r) => width(r[k] ?? ''))))
553
+ const room = b.width - b.indent.length - 3 * (n - 1)
554
+ while (wide.reduce((x, y) => x + y, 0) > room && Math.max(...wide) > 3) wide[wide.indexOf(Math.max(...wide))]-- // too wide: the widest columns give way
555
+ const cell = (t, w) => (width(t) > w ? `${sliceCols(t, 0, w - 1)}…` : t + ' '.repeat(w - width(t)))
556
+ b.nowrap = true
557
+ rows.forEach((r, i) => {
558
+ wide.forEach((w, k) => {
559
+ if (k) this.#out(' │ ', c.ghost)
560
+ const t = k === n - 1 ? cell(r[k] ?? '', w).trimEnd() : cell(r[k] ?? '', w)
561
+ this.#out(t || ' ', i ? this.base : (x) => c.bold(c.bright(x)))
562
+ })
563
+ this.#out('\n')
564
+ if (!i) this.#out(wide.map((w) => '─'.repeat(w)).join('─┼─') + '\n', c.ghost)
565
+ })
566
+ b.nowrap = false
567
+ return at
568
+ }
483
569
  #run(final) {
484
570
  let s = this.buf
485
571
  let text = ''
486
572
  const flush = () => (this.#out(text), (text = ''))
487
573
  let i = 0
488
574
  while (i < s.length) {
575
+ if (this.sol && !this.fence && /^[ \t]*\|/.test(s.slice(i, i + 40))) {
576
+ const n = this.#table(s.slice(i), final)
577
+ if (n === false) break
578
+ i += n
579
+ continue
580
+ }
489
581
  if (this.sol) {
490
582
  const n = this.#lineStart(s.slice(i), final)
491
583
  if (n === false) break
492
- this.sol = false
584
+ this.sol = n > 0 && s[i + n - 1] === '\n' // a fence line, taken whole: the next line starts next
493
585
  i += n
494
586
  continue
495
587
  }
@@ -652,6 +744,7 @@ export const PERMISSIONS = [
652
744
  ['plan', 'plan first: look around without changing anything, then approve the plan'],
653
745
  ]
654
746
 
747
+ let drewLast = null // the UI (tab) that last drew the screen: only its own last frame can be diffed against
655
748
  export class UI {
656
749
  constructor({ yes = false, input = process.stdin, output = process.stdout } = {}) {
657
750
  this.permission = yes ? 'all' : 'ask' // see PERMISSIONS
@@ -670,7 +763,8 @@ export class UI {
670
763
  this.onInterrupt = null
671
764
  this.timer = null
672
765
  this.label = ''
673
- this.showThinking = true
766
+ this.showThinking = false // all of it as it comes (Alt+O); off: its last two lines, live, above the spinner
767
+ this.thinkTail = '' // the thinking coming in now, for those two lines
674
768
  this.tail = ''
675
769
  // suggest(line, cursor) → [{ value, desc, start, end, space, insertOnly }] for the menu under the prompt
676
770
  this.suggest = null
@@ -683,6 +777,8 @@ export class UI {
683
777
  this.asking = false
684
778
  this.frame = 0
685
779
  this.dialog = null // a box over the screen (the background commands' logs)
780
+ this.waitingFor = null // () → the model a request waits on (the app's), for "waiting for <model>"
781
+ this.helpers = new Map() // helpers at work (agent.js): label → what it's doing now, shown under the spinner
686
782
  }
687
783
 
688
784
  // A dialog: a box in the middle, 70% of the screen each way, the conversation going on around it;
@@ -699,8 +795,9 @@ export class UI {
699
795
  this.render()
700
796
  }
701
797
  // Text to read (a command's answer: /help, /context, /diff…) in a dialog: ↑/↓, PgUp/PgDn, Home/End
702
- // and the wheel scroll it, Esc closes it. Without the full screen: printed.
703
- showText(title, text) {
798
+ // and the wheel scroll it, Esc closes it (and toggle: a key's action, as the key that opened it).
799
+ // Without the full screen: printed.
800
+ showText(title, text, toggle) {
704
801
  if (!this.full) return this.print(text)
705
802
  const all = String(text).split('\n')
706
803
  let top = 0
@@ -708,26 +805,27 @@ export class UI {
708
805
  let total = 0
709
806
  this.setDialog({
710
807
  title,
808
+ toggle,
711
809
  key: (key) => {
712
810
  const by = { up: key.wheel ? -3 : -1, down: key.wheel ? 3 : 1, pageup: -page, pagedown: page, home: -1e9, end: 1e9 }[key.name]
713
811
  if (by) top = Math.max(0, Math.min(top + by, total - page))
714
812
  },
715
813
  draw: (w, h) => {
716
- const rows = all.flatMap((l) => wrapWords(l, w))
814
+ const rows = all.flatMap((l) => wrapHang(l, w)) // a two-column line's description wraps under itself
717
815
  total = rows.length
718
- page = h - 2
816
+ const foot = (p) => wrapParts(`${total > p ? `${top + 1}–${Math.min(total, top + p)} of ${total} lines · ↑/↓ PgUp/PgDn scroll · ` : ''}Esc close`, w)
817
+ page = h - 1 - foot(h - 2).length
719
818
  top = Math.max(0, Math.min(top, total - page))
720
- const shown = rows.slice(top, top + page)
721
- const where = total > page ? `${top + 1}–${Math.min(total, top + page)} of ${total} lines · ↑/↓ PgUp/PgDn scroll · ` : ''
722
- return [...shown, '', c.faint(`${where}Esc close`)]
819
+ return [...rows.slice(top, top + page), '', ...foot(page).map((r) => c.faint(r))]
723
820
  },
724
821
  })
725
822
  }
726
823
 
727
- // where it is: { x, y, w, h } (screen cells, from 0; the inside, without the border)
824
+ // where it is: { x, y, w, h } (screen cells, from 0; the inside, without the border); 70% of the
825
+ // screen, 90% of a small one (a narrow one: long names on fewer rows)
728
826
  #dialogBox(cols, rows) {
729
- const w = Math.max(30, Math.floor(cols * 0.7))
730
- const h = Math.max(8, Math.floor(rows * 0.7))
827
+ const w = Math.max(30, Math.floor(cols * (cols < 100 ? 0.9 : 0.7)))
828
+ const h = Math.max(8, Math.floor(rows * (rows < 40 ? 0.9 : 0.7)))
731
829
  return { x: Math.floor((cols - w) / 2) + 1, y: Math.floor((rows - h) / 2) + 1, w: Math.min(w, cols) - 2, h: Math.min(h, rows) - 2 }
732
830
  }
733
831
  // d: { title, lines(w, h) → lines (at most h), fill?: always 70% tall too (a log), cursor?(w) →
@@ -746,14 +844,14 @@ export class UI {
746
844
  const x = Math.floor((cols - W - 2) / 2) + 1
747
845
  const y = Math.floor((rows - h - 2 * PY - 2) / 2) + 1
748
846
  this.dialogAt = { x, y, W, H: h + 2 * PY, cx: x + 1 + PX, cy: y + 1 + PY } // for the mouse (screen cells, from 1)
749
- const paint = (t) => (background ? `${background}${t.replace(/\x1b\[(0|49)?m/g, (m) => m + background)}\x1b[0m` : `${t}\x1b[0m`)
847
+ const paint = (t) => (background ? `${background}${foreground}${paintBg(t)}\x1b[0m` : `${t}\x1b[0m`)
750
848
  const pad = (t, n) => {
751
849
  const cut = fit(t, n)
752
850
  return cut + ' '.repeat(Math.max(0, n - width(cut.replace(/\x1b\[[0-9;]*m/g, ''))))
753
851
  }
754
852
  const title = name ? ` ${width(name) > W - 6 ? `${fit(name, W - 7)}…` : name} ` : '' // too long: cut (a question shows all of it inside)
755
853
  const row = (i, t) => `\x1b[${y + i};${x}H${paint(t)}`
756
- let out = row(0, c.brand('╭─') + c.bold(title) + c.brand('─'.repeat(Math.max(0, W - width(title) - 1)) + '╮'))
854
+ let out = row(0, c.brand('╭─') + c.bright(c.bold(title)) + c.brand('─'.repeat(Math.max(0, W - width(title) - 1)) + '╮'))
757
855
  const blank = c.brand('│') + ' '.repeat(W) + c.brand('│')
758
856
  for (let i = 0; i < PY; i++) out += row(1 + i, blank)
759
857
  for (let i = 0; i < h; i++) out += row(1 + PY + i, c.brand('│') + ' '.repeat(PX) + pad(lines[i] ?? '', w) + ' '.repeat(PX) + c.brand('│'))
@@ -766,11 +864,17 @@ export class UI {
766
864
  return [out, cur ? `\x1b[${y + 1 + PY + cur.row};${x + 1 + PX + Math.min(cur.col, w - 1)}H\x1b[?25h` : '\x1b[?25l']
767
865
  }
768
866
 
867
+ // A pick shown as cards: one to choose from a few, in no groups (no filter to type into)
868
+ #cards(pick) {
869
+ return Boolean(pick && !pick.multi && pick.items.length <= 6 && !pick.items.some((x) => x.group))
870
+ }
871
+
769
872
  // The question being asked, as a dialog: its title; what's typed (the filter, or the answer) with the
770
873
  // cursor; a picker's choices. A short list (a few, one to choose) is shown as cards: the name, its
771
874
  // description under it. A permission (confirm) shows what just happened (the change or command it
772
875
  // asks about) above the choices. A picker's body (pick's option): a few lines saying what's going on.
773
- #question() {
876
+ // Too little room: the keys and the countdown stay; the text, the choices, what it's about give way.
877
+ #question(cols, rows) {
774
878
  const rl = this.rl
775
879
  const m = this.menu
776
880
  const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
@@ -784,55 +888,125 @@ export class UI {
784
888
  const padTo = (t, n) => t + ' '.repeat(Math.max(0, n - width(plain(t))))
785
889
  const pick = m.pick
786
890
  const choices = pick ? m.items.filter((x) => !x.header) : []
787
- const cards = pick && !pick.multi && pick.items.length <= 6 && !m.items.some((x) => x.header)
891
+ const cards = this.#cards(pick)
892
+ const own = pick?.items.some((x) => x.own) // typing goes into "Something else", not a filter
893
+ const typingOwn = m.items[m.sel]?.item?.own && m.items[m.sel].item.text // ←/→ move in what's typed; Tab goes on
788
894
  const body = pick?.body ? String(pick.body).split('\n') : []
789
- const hint = pick ? (pick.fixed ? '↑↓ move · Enter choose · Esc close' : pick.multi ? '↑↓ move · Space tick · Ctrl+A all · Ctrl+N none · Enter take · Esc cancel · type to filter' : `↑↓ move · Enter choose · Esc cancel${cards ? '' : ' · type to filter'}`) : 'Enter send · Esc cancel'
895
+ const hint = (pick?.nav ? (typingOwn ? 'Tab questions · ' : '←→ questions · ') : '') + (pick ? (pick.fixed ? '↑↓ move · Enter choose · Esc close' : pick.multi ? `↑↓ move · Space tick · Alt+A/N all/none · Enter take · Esc cancel · ${own ? 'type your own' : 'type to filter'}` : `↑↓ move · Enter choose · Esc cancel${own ? ' · type your own' : cards ? '' : ' · type to filter'}`) : 'Enter send · Esc cancel')
896
+ const timer = this.autoLine() // on its own line, so it's seen (and not cut off with the keys)
897
+ const long = width(title) > this.#dialogBox(cols, rows).w - 6 // too long for the border: inside instead, said once
898
+ // at most n rows; the rest said to be there
899
+ const clip = (lines, n) => (lines.length <= n ? lines : [...lines.slice(0, Math.max(0, n - 1)), c.faint(`↓ ${lines.length - n + 1} more lines`)])
900
+ // text on at most n rows of w, the last ending in "…" when there's more
901
+ const rowsOf = (t, w, n) => {
902
+ const r = wrapWords(t, w)
903
+ return r.length <= n ? r : [...r.slice(0, n - 1), `${fit(r[n - 1], w - 1)}…`]
904
+ }
790
905
  let at = 0
791
- const long = (w) => width(title) > w // too long for the border: all of it inside too
792
906
  return {
793
- title: title.length > 200 ? title.slice(0, 200) : title,
794
- cursor: (w) => (pick?.fixed || (cards && pick) ? null : { row: at, col: field(w).col }),
907
+ title: long || title.length > 200 ? '' : title,
908
+ cursor: (w) => (pick?.fixed || (cards && pick) || own ? null : { row: at, col: field(w).col }),
795
909
  lines: (w, h) => {
796
- const head = long(w) ? [...wrapAnsi(c.bold(title), w).map((l) => l), ''] : []
797
- const text = body.flatMap((l) => wrapAnsi(/^https?:\/\/\S+$/.test(l.trim()) ? c.info(l) : c.muted(l), w)) // an address in its link color
798
- const intro = [...head, ...text, ...(text.length ? [''] : [])]
910
+ const rule = c.ghost('─'.repeat(w))
911
+ const head = long ? [...wrapWords(c.bright(c.bold(title.slice(0, 1000))), w), ''] : []
912
+ const text = body.flatMap((l) => wrapHang(/^https?:\/\/\S+$/.test(l.trim()) ? c.info(l) : c.muted(l), w)) // an address in its link color
913
+ const intro = [...(pick?.tabs ? [...wrapAnsi(c.text(pick.tabs), w), ''] : []), ...head, ...text, ...(text.length ? [''] : [])]
914
+ const keys = wrapParts(hint, w).map((r) => c.faint(r))
799
915
  if (!pick) {
800
- const recent = this.askAbout ? this.#recent(w, Math.min(8, h - intro.length - 5)) : []
801
- const top = [...recent, ...(recent.length ? [c.ghost('─'.repeat(w)), ''] : []), ...intro]
916
+ const shown = clip(intro, h - 2 - keys.length)
917
+ const recent = this.askAbout ? this.#recent(w, Math.min(8, h - shown.length - 4 - keys.length), title) : []
918
+ const top = [...recent, ...(recent.length ? [rule, ''] : []), ...shown]
802
919
  at = top.length
803
- return [...top, field(w).text, '', c.faint(hint)]
920
+ return [...top, field(w).text, '', ...keys]
804
921
  }
922
+ const filter = pick.fixed || cards || own ? [] : [field(w).text, rule]
923
+ const tail = ['', ...(timer ? wrapParts(timer, w).map((r) => c.warn(r)) : []), ...keys]
924
+ // the cards: each its rows (a long name on two, a description on up to three), a gap between
925
+ const blocks = !cards
926
+ ? []
927
+ : choices.map((x, i) => {
928
+ const on = m.items[m.sel] === x
929
+ const name = rowsOf(x.item.label, w - 2, 2).map((r, k) => (k ? ' ' : on ? `${c.brand('❯')} ` : ' ') + (on ? c.bright(c.bold(r)) : c.text(r)))
930
+ const desc = x.item.desc ? rowsOf(String(x.item.desc), w - 2, 3).map((r) => ` ${on ? c.muted(r) : c.faint(r)}`) : []
931
+ const rows = [...name, ...desc].map((r) => (on ? c.select(padTo(r, w)) : r))
932
+ return i < choices.length - 1 && choices.some((y) => y.item.desc) ? [...rows, ''] : rows
933
+ })
934
+ const want = cards ? blocks.flat().length : Math.max(1, m.items.length)
935
+ const least = Math.min(want, cards ? Math.max(...blocks.map((b) => b.length)) + 2 : 3) // the choices give way first, down to this
936
+ const top0 = clip(intro, Math.max(3, h - tail.length - filter.length - least))
937
+ const room = Math.max(1, h - tail.length - filter.length - top0.length)
805
938
  let list
806
- if (cards) {
807
- list = choices.length
808
- ? choices.flatMap((x, i) => {
809
- const on = m.items[m.sel] === x
810
- const name = on ? `${c.brand('❯')} ${c.bright(c.bold(x.item.label))}` : ` ${c.text(x.item.label)}`
811
- const desc = x.item.desc ? (on ? ` ${c.muted(x.item.desc)}` : ` ${c.faint(x.item.desc)}`) : null
812
- const rows = [name, ...(desc ? [desc] : [])].map((r) => (on ? c.select(padTo(r, w)) : r))
813
- return i < choices.length - 1 && choices.some((y) => y.item.desc) ? [...rows, ''] : rows // a gap between cards that have two lines
814
- })
815
- : [c.faint(`nothing matches "${rl.line}"`)]
939
+ if (!choices.length) list = [c.faint(`nothing matches "${rl.line}"`)]
940
+ else if (!cards) list = this.#menuLines(w, Math.max(1, Math.min(room - (m.items.length > room ? 1 : 0), m.items.length))).slice(1)
941
+ else if (blocks.flat().length <= room) list = blocks.flat()
942
+ else {
943
+ // not all of them fit: the chosen one and those around it, with how many more above and below
944
+ let [a, b] = [Math.max(0, choices.findIndex((x) => m.items[m.sel] === x)), 0]
945
+ b = a + 1
946
+ const size = (a, b) => blocks.slice(a, b).flat().length + (a > 0) + (b < blocks.length)
947
+ for (;;) {
948
+ if (b < blocks.length && size(a, b + 1) <= room) b++
949
+ else if (a > 0 && size(a - 1, b) <= room) a--
950
+ else break
951
+ }
952
+ const up = a ? [c.faint(`↑ ${a} more`)] : []
953
+ const down = b < blocks.length ? [c.faint(`↓ ${blocks.length - b} more`)] : []
954
+ list = [...up, ...blocks.slice(a, b).flat().slice(0, Math.max(1, room - up.length - down.length)), ...down]
816
955
  }
817
- const filter = pick.fixed || cards ? [] : [field(w).text, c.ghost('─'.repeat(w))]
818
- const room = h - intro.length - filter.length - 2
819
- if (!cards) list = m.items.length ? this.#menuLines(w, Math.max(1, Math.min(room - (m.items.length > room ? 1 : 0), m.items.length))).slice(1) : [c.faint(`nothing matches "${rl.line}"`)]
820
- const recent = this.askAbout ? this.#recent(w, Math.min(8, room - list.length - 1)) : []
821
- const top = [...recent, ...(recent.length ? [c.ghost('─'.repeat(w)), ''] : []), ...intro]
956
+ const recent = this.askAbout ? this.#recent(w, Math.min(8, h - tail.length - filter.length - top0.length - list.length - 2), title) : []
957
+ const top = [...recent, ...(recent.length ? [rule, ''] : []), ...top0]
822
958
  at = top.length
823
- return [...top, ...filter, ...list, '', c.faint(hint)]
959
+ return [...top, ...filter, ...list, ...tail]
824
960
  },
825
961
  }
826
962
  }
827
963
 
828
- // The last `n` rows of this task's output at width w (what a question in the middle of the work is about).
829
- #recent(w, n) {
964
+ // The plan (todo list) while it works, kept in sight under the spinner: how much is done, what's
965
+ // being done, what's left. Long ones: the finished folded into a count, the open ones up to 8.
966
+ #todoLines(cols) {
967
+ const todos = this.todos?.() ?? []
968
+ const open = todos.filter((t) => t.status !== 'completed')
969
+ if (!open.length) return []
970
+ const done = todos.length - open.length
971
+ const mark = { pending: c.muted('☐'), in_progress: c.info('◐'), completed: c.faint('☑') }
972
+ const line = (t) => fit(` ${mark[t.status]} ${t.status === 'in_progress' ? c.info(c.bold(t.content)) : t.status === 'completed' ? c.faint(t.content) : c.muted(t.content)}`, cols)
973
+ const shown = todos.length <= 8 ? todos : open.slice(0, 7)
974
+ return [
975
+ fit(` ${c.muted('Plan')} ${c.faint(`· ${done} of ${todos.length} done`)}`, cols),
976
+ ...(todos.length > 8 && done ? [fit(` ${c.faint(`☑ ${done} done`)}`, cols)] : []),
977
+ ...shown.map(line),
978
+ ...(open.length > shown.filter((t) => t.status !== 'completed').length ? [fit(` ${c.faint(`… ${open.length - 7} more`)}`, cols)] : []),
979
+ ]
980
+ }
981
+
982
+ // The last lines of this task's output, at most n rows of w (what a question in the middle of the work
983
+ // is about): whole lines, from the start of a block (not mid-sentence), without what the question
984
+ // itself says (about: its text, e.g. the command it asks to run).
985
+ #recent(w, n, about = '') {
830
986
  if (n <= 0) return []
831
- const out = []
987
+ const flat = (t) => t.replace(/\x1b\[[0-9;]*m/g, '').replace(/\s+/g, ' ').trim().toLowerCase()
988
+ const said = flat(about)
832
989
  const from = Math.max(0, (this.inputMark ?? 0) + 1) // this task's: from after your message
833
- for (let i = this.log.length - 1; i >= from && out.length < n; i--) out.unshift(...wrapAnsi(this.log[i], w))
834
- while (out.length && !out[0].trim()) out.shift()
835
- return out.slice(-n)
990
+ const got = [] // [{ i, rows }]
991
+ let used = 0
992
+ let cut = false
993
+ for (let i = this.log.length - 1; i >= from; i--) {
994
+ const t = flat(this.log[i]).replace(/^[^\w\s]{1,2} /, '')
995
+ if (t.length >= 8 && said.includes(t)) continue // already in the question
996
+ const rows = wrapHang(this.log[i], w)
997
+ if (used + rows.length > n) {
998
+ cut = true
999
+ break
1000
+ }
1001
+ got.unshift({ i, rows })
1002
+ used += rows.length
1003
+ }
1004
+ // cut short: from the first line that starts a block (after a blank line, or not indented)
1005
+ const start = cut ? got.findIndex((g) => !flat(this.log[g.i - 1] ?? '') || /^\S/.test(plainOf(this.log[g.i]))) : 0
1006
+ const out = got.slice(Math.max(0, start)).flatMap((g) => g.rows)
1007
+ while (out.length && !plainOf(out[0]).trim()) out.shift()
1008
+ while (out.length && !plainOf(out.at(-1)).trim()) out.pop()
1009
+ return out
836
1010
  }
837
1011
 
838
1012
  // One model reply: thinking (dim, its own block) kept apart from the answer.
@@ -843,27 +1017,42 @@ export class UI {
843
1017
  const write = (x) => this.write(x)
844
1018
  let think = null
845
1019
  let text = null
846
- let thought = false
1020
+ let thought = '' // all of it so far: shown whole when Alt+O switches to all of it midway
847
1021
  const summary = () => {
848
- if (thought && !this.showThinking) this.print(c.faint(c.italic(`✻ ${who ? `${who} ` : ''}thought for ${secs()}`)))
1022
+ this.thinkTail = ''
1023
+ if (thought.trim() && !think) {
1024
+ // what it thought stays in the conversation: its last two lines (all of it: Alt+O)
1025
+ const last = thought.split('\n').map((l) => l.trim()).filter(Boolean).slice(-2)
1026
+ this.print(c.faint(c.italic(`✻ ${who ? `${who} ` : ''}thought for ${secs()} · Alt+O shows all of it`)))
1027
+ this.print(c.think(c.italic(last.map((l) => ` ${l}`).join('\n'))))
1028
+ this.lastThought = { who, text: thought } // Alt+O shows it, now that it's over (showLastThought)
1029
+ }
849
1030
  }
850
1031
  return {
851
1032
  think: (t) => {
852
1033
  if (!t || text) return
853
- thought = true
854
- if (!this.showThinking) return this.spinner(`thinking · ${secs()}`)
1034
+ this.tokenAt = Date.now() // it answers: no longer "waiting for" it
1035
+ thought += t
1036
+ if (!this.showThinking && !think) {
1037
+ this.thinkTail = thought.slice(-4000) // its last two lines, live (render)
1038
+ return this.spinner('thinking') // the time: in the line under it (and "thought for" after)
1039
+ }
855
1040
  if (!think) {
1041
+ this.thinkTail = ''
856
1042
  this.gap()
857
1043
  this.print(c.faint(c.italic(`✻ ${who ? `${who} is thinking` : 'Thinking'}…`)))
858
1044
  const style = (x) => c.think(c.italic(x))
859
1045
  think = new Block(write, { style })
860
1046
  if (color) think = new Markdown(think, style)
1047
+ return think.push(thought) // what came before the switch too
861
1048
  }
862
1049
  think.push(t)
863
1050
  },
864
1051
  text: (t) => {
865
1052
  if (!t) return
1053
+ this.tokenAt = Date.now()
866
1054
  if (!text) {
1055
+ if (this.label === 'thinking') this.label = 'answering'
867
1056
  think?.end()
868
1057
  this.gap()
869
1058
  summary()
@@ -881,6 +1070,16 @@ export class UI {
881
1070
  }
882
1071
  }
883
1072
 
1073
+ // The thinking that was shown as two lines, all of it (Alt+O after it's over): true when there was some
1074
+ showLastThought() {
1075
+ const t = this.lastThought
1076
+ if (!t?.text.trim()) return false
1077
+ this.lastThought = null
1078
+ this.print(c.faint(c.italic(`✻ ${t.who ? `${t.who}'s` : 'The'} thinking, all of it:`)))
1079
+ this.print(c.think(c.italic(t.text.trim().replace(/^/gm, ' '))))
1080
+ return true
1081
+ }
1082
+
884
1083
  #rl() {
885
1084
  if (this.rl) return this.rl
886
1085
  const terminal = Boolean(this.input.isTTY && this.out.isTTY)
@@ -909,12 +1108,13 @@ export class UI {
909
1108
  // mouse: HeartCode takes the mouse (the wheel scrolls the conversation, dragging copies); off,
910
1109
  // the terminal keeps it, so text is selected and copied the terminal's own way (over SSH too).
911
1110
  fullscreen({ mouse = false } = {}) {
912
- if (this.full || !(this.input.isTTY && this.out.isTTY)) return
1111
+ if (this.full || !(this.input.isTTY && this.out.isTTY) || process.env.TERM === 'dumb') return
913
1112
  this.full = true
914
1113
  this.mouseOn = mouse ? MOUSE_ON : ''
915
1114
  // alternate screen · kitty keyboard protocol (Shift/Cmd+Enter are told apart) · bracketed paste
916
1115
  // · mouse reports (SGR), when HeartCode takes the mouse
917
1116
  this.out.write('\x1b[?1049h\x1b[H\x1b[2J\x1b[>1u\x1b[?2004h' + this.mouseOn)
1117
+ this.frame0 = null
918
1118
  this.out.on('resize', () => this.render())
919
1119
  this.#rl()
920
1120
  process.on('exit', () => this.leaveFullscreen())
@@ -933,11 +1133,18 @@ export class UI {
933
1133
  this.rl?.resume()
934
1134
  if (wasFull) {
935
1135
  this.out.write('\x1b[?1049h\x1b[>1u\x1b[?2004h' + this.mouseOn)
1136
+ this.frame0 = null
936
1137
  this.render()
937
1138
  }
938
1139
  }
939
1140
  }
940
1141
 
1142
+ // Taking the mouse, or giving it back to the terminal, now (the settings page's switch)
1143
+ setMouse(on) {
1144
+ this.mouseOn = on ? MOUSE_ON : ''
1145
+ if (this.full) this.out.write(on ? MOUSE_ON : MOUSE_OFF)
1146
+ }
1147
+
941
1148
  // The mouse: the wheel scrolls the conversation; dragging selects in it, copied when let go
942
1149
  // (the terminal can't select itself while HeartCode takes the mouse). A click or a key clears it.
943
1150
  // The mouse: the wheel scrolls (a dialog's own text, else the conversation); dragging selects, copied
@@ -951,7 +1158,7 @@ export class UI {
951
1158
  if (b & 64) {
952
1159
  if ((b & 0xc3) !== 64 && (b & 0xc3) !== 65) return
953
1160
  if (this.dialog) return this.dialog.key?.({ name: b & 1 ? 'down' : 'up', wheel: true }), this.render()
954
- return this.scrollBy(b & 1 ? -3 : 3) // 64 up, 65 down
1161
+ return this.#wheel(b & 1 ? -1 : 1) // 64 up, 65 down
955
1162
  }
956
1163
  if ((b & 3) !== 0 && !up) return // the left button only (a release says 3 in some terminals)
957
1164
  const press = !(b & 32) && !up
@@ -1060,6 +1267,16 @@ export class UI {
1060
1267
  this.scroll = Math.max(0, this.scroll + n) // Infinity: the top (render keeps it in range)
1061
1268
  this.render()
1062
1269
  }
1270
+ // The wheel: a line per event when they come in a stream (a trackpad, a wheel spun fast), three for a
1271
+ // lone notch; the screen drawn once a frame however many come (each its own drawing was jerky)
1272
+ #wheel(dir) {
1273
+ if (!this.full || this.out.hidden) return
1274
+ const now = Date.now()
1275
+ const step = now - (this.wheelAt ?? 0) < 60 ? 1 : 3
1276
+ this.wheelAt = now
1277
+ this.scroll = Math.max(0, this.scroll + dir * step)
1278
+ this.wheelDraw ??= setTimeout(() => ((this.wheelDraw = null), this.render()), 16)
1279
+ }
1063
1280
  page() {
1064
1281
  return Math.max(1, (this.out.rows || 24) - 4)
1065
1282
  }
@@ -1111,7 +1328,7 @@ export class UI {
1111
1328
  const out = []
1112
1329
  this.log.forEach((line, i) => {
1113
1330
  const w = this.wrapped[i]
1114
- if (!w || w.src !== line) this.wrapped[i] = { src: line, rows: wrapAnsi(line, cols) }
1331
+ if (!w || w.src !== line) this.wrapped[i] = { src: line, rows: wrapHang(line, cols) } // at spaces, wrapped rows under the text
1115
1332
  out.push(...this.wrapped[i].rows)
1116
1333
  })
1117
1334
  return out
@@ -1139,17 +1356,33 @@ export class UI {
1139
1356
  const below = [hiddenBelow ? note(hiddenBelow, '↓') : rule, ...(statusText ? statusText.split('\n').map((l) => fit(' ' + l, cols)) : [])]
1140
1357
  const bottom = []
1141
1358
  if (this.timer && !this.asking) {
1142
- // the spinner on its own line; the timer (and Esc) on the next, so neither line is crammed
1359
+ // the spinner on its own line, one status: the model not answering yet (since this request went),
1360
+ // else what's being done; the time in all (and Esc) on the next, on more lines when it doesn't fit
1143
1361
  const request = this.requestSince?.()
1144
- const timer = this.busySince ? `responding ${duration(this.worked())}${request ? ` · waiting for model ${duration(Date.now() - request)}` : ''} · Esc to stop` : ''
1145
- bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(this.#label())}`, cols))
1146
- if (timer) bottom.push(fit(` ${c.faint(timer)}`, cols))
1362
+ const label = this.#label()
1363
+ const waiting = request && !(this.tokenAt >= request) && this.beforeRetry === undefined
1364
+ const status = waiting ? `${/^(working|thinking|answering)$/.test(plainOf(label)) ? '' : `${label} · `}waiting for ${this.waitingFor?.() || 'the model'} ${short(Date.now() - request)}` : label
1365
+ const timer = this.busySince ? [this.beforeRetry !== undefined && 'no answer yet', `${short(this.worked())} in all`, 'Esc to stop', this.thinkTail && 'Alt+O shows all thinking'].filter(Boolean).join(' · ') : ''
1366
+ if (this.thinkTail) {
1367
+ // the thinking's last two lines (long ones wrapped), dim, changing as it comes
1368
+ const w = Math.max(20, cols - 6)
1369
+ const lines = this.thinkTail.split('\n').map((l) => l.replace(/\s+/g, ' ').trim()).filter(Boolean).flatMap((l) => l.match(new RegExp(`.{1,${w}}(\\s|$)|.{${w}}`, 'g')) ?? [l]).map((l) => l.trim()).filter(Boolean)
1370
+ for (const l of lines.slice(-2)) bottom.push(fit(` ${c.think(c.italic(l))}`, cols))
1371
+ }
1372
+ bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(status)}`, cols))
1373
+ if (timer) bottom.push(...wrapParts(timer, cols - 2).map((r) => fit(` ${c.faint(r)}`, cols)))
1374
+ // helpers at work (agent.js keeps them in this.helpers: label → what it's doing), then the plan
1375
+ const helpers = [...this.helpers]
1376
+ for (const [name, what] of helpers.slice(0, helpers.length > 6 ? 5 : 6)) bottom.push(fit(` ${c.faint('◦')} ${c.muted(name)}${what ? c.faint(` · ${what}`) : ''}`, cols))
1377
+ if (helpers.length > 6) bottom.push(c.faint(` … ${helpers.length - 5} more`))
1378
+ bottom.push(...this.#todoLines(cols))
1147
1379
  }
1148
1380
  if (this.scroll) bottom.push(c.dim(` ↓ ${Number.isFinite(this.scroll) ? this.scroll : 'more'} lines below · held here while you read · Alt+Shift+↓ to the bottom`))
1149
1381
  if (this.ahead.length) {
1150
1382
  const key = (k, d) => `${c.muted(k)} ${c.faint(d)}`
1151
1383
  const sep = c.ghost(' · ')
1152
- bottom.push(fit(` ${c.bright(`queued ${this.ahead.length}`)}${sep}${c.faint(`when done: ${this.queueMode === 'one' ? 'one by one' : 'all together'}`)}${sep}${[key('Alt+S', 'send first now'), key('Alt+A', 'send all now'), key('Alt+M', 'change when done')].join(sep)}`, cols))
1384
+ const queued = `${c.bright(`queued ${this.ahead.length}`)}${sep}${c.faint(`when done: ${this.queueMode === 'one' ? 'one by one' : 'all together'}`)}${sep}${[key('Alt+S', 'send first now'), key('Alt+A', 'send all now'), key('Alt+M', 'change when done')].join(sep)}`
1385
+ bottom.push(...wrapParts(queued, cols - 2, sep).map((r) => fit(` ${r}`, cols))) // on more lines, not cut
1153
1386
  for (const [i, l] of this.ahead.slice(0, 5).entries()) bottom.push(fit(` ${c.accent(`${i + 1}.`)} ${c.muted(l.replace(/\s+/g, ' '))}`, cols))
1154
1387
  if (this.ahead.length > 5) bottom.push(c.faint(` … ${this.ahead.length - 5} more`))
1155
1388
  }
@@ -1172,20 +1405,32 @@ export class UI {
1172
1405
  for (let i = Math.max(0, s.row - top); i <= Math.min(view.length - 1, e.row - top); i++) view[i] = highlight(view[i], top + i === s.row ? s.col : 0, top + i === e.row ? e.col + 1 : Infinity)
1173
1406
  }
1174
1407
  // a theme with a background: every row painted with it (a style ending its own background goes back to it)
1175
- let row = background ? (line) => `${background}${line.replace(/\x1b\[(0|49)?m/g, (m) => m + background)}\x1b[K\x1b[0m` : (line) => `${line}\x1b[0m\x1b[K`
1408
+ let row = background ? (line) => `${background}${foreground}${paintBg(line)}\x1b[K\x1b[0m` : (line) => `${line}\x1b[0m\x1b[K`
1176
1409
  let s = '\x1b[?25l'
1177
1410
  // a dialog open: everything behind it dimmed
1178
1411
  if (this.dialog || asked) {
1179
1412
  const plainRow = row
1180
1413
  row = (line) => plainRow(`\x1b[2m${line.replace(/\x1b\[(0|22)?m/g, (m) => m + '\x1b[2m')}`)
1181
1414
  }
1415
+ // only the rows that changed since the last frame are written (scrolling rewrote the whole screen
1416
+ // every time); a dialog or a selection over it, or a resize: all of them
1417
+ const overlay = Boolean(this.dialog || asked || this.ssel || this.flash)
1418
+ const was = !overlay && !this.frameOverlay && this.frameSize === `${rows}x${cols}` && drewLast === this ? this.frame0 : null // another tab drew since: all of it
1419
+ const frame = []
1420
+ const put = (r, line, always = false) => {
1421
+ const text = row(line)
1422
+ frame[r] = text
1423
+ if (always || was?.[r] !== text) s += `\x1b[${r};1H${text}`
1424
+ }
1182
1425
  for (let r = 0; r < inputTop - 1; r++) {
1183
1426
  const i = r - head.length
1184
- const line = i < 0 ? head[r] : i < avail ? (view[i] ?? '') : bottom[i - avail]
1185
- s += `\x1b[${r + 1};1H${row(line)}`
1427
+ put(r + 1, i < 0 ? head[r] : i < avail ? (view[i] ?? '') : bottom[i - avail])
1186
1428
  }
1187
- box.forEach((line, i) => (s += `\x1b[${inputTop + i};1H${row(line)}`))
1188
- below.forEach((line, i) => (s += `\x1b[${inputTop + inputRows + i};1H${row(line)}`))
1429
+ // the input and what's under it, every time: readline clears from the cursor down on its own (Enter)
1430
+ box.forEach((line, i) => put(inputTop + i, line, true))
1431
+ below.forEach((line, i) => put(inputTop + inputRows + i, line, true))
1432
+ ;[this.frame0, this.frameOverlay, this.frameSize] = [frame, overlay, `${rows}x${cols}`]
1433
+ drewLast = this
1189
1434
  // what can be selected besides the conversation (screen rows from 1): the header's first line (the
1190
1435
  // project's folder), the input box, the status bar; with a dialog open, only what's in it
1191
1436
  const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
@@ -1197,7 +1442,7 @@ export class UI {
1197
1442
  let cursor
1198
1443
  if (this.dialog || asked) {
1199
1444
  this.regions = new Map()
1200
- const [box, cur] = this.#drawDialog(cols, rows, this.dialog ? { title: this.dialog.title, fill: this.dialog.fill, lines: (w, h) => this.dialog.draw(w, h) } : this.#question())
1445
+ const [box, cur] = this.#drawDialog(cols, rows, this.dialog ? { title: this.dialog.title, fill: this.dialog.fill, lines: (w, h) => this.dialog.draw(w, h) } : this.#question(cols, rows))
1201
1446
  s += box
1202
1447
  cursor = cur // a question: its cursor in the box; else hidden
1203
1448
  } else {
@@ -1241,6 +1486,7 @@ export class UI {
1241
1486
  this.ttyWrite = write
1242
1487
  rl._ttyWrite = (s, key = {}) => {
1243
1488
  if (!this.full) return write(s, key)
1489
+ if (this.menu.pick?.auto) this.#armAuto() // a key: you're there; the wait starts again (debounced)
1244
1490
  if (this.sel || this.ssel) (this.sel = this.ssel = null), this.render() // a key ends a selection
1245
1491
  const bound = !(key.ctrl && key.name === 'c') && this.keys[keyId(key, s)] // ~/.heart/keybindings.json
1246
1492
  // a dialog: its keys, all of them; Esc (or its own key) closes it; Ctrl+C still stops and quits
@@ -1251,8 +1497,8 @@ export class UI {
1251
1497
  if (this.recording) return this.recording.key(key, bound) // voice: Space, Enter, Esc; the rest waits
1252
1498
  // a fixed dialog (pick(…, { fixed })): only its keys, nothing typed and no shortcuts
1253
1499
  if (this.menu.pick?.fixed && !['up', 'down', 'return', 'escape'].includes(key.name) && !(key.ctrl && key.name === 'c')) return
1254
- // In a multi-select: Ctrl+A ticks all, Ctrl+N unticks all (before tab shortcuts claim Ctrl+N)
1255
- if (this.menu.pick?.multi && key.ctrl && (key.name === 'a' || key.name === 'n')) {
1500
+ // In a multi-select: Alt+A ticks all, Alt+N unticks all (before Alt+A sends and Alt+N switches tabs)
1501
+ if (this.menu.pick?.multi && key.meta && (key.name === 'a' || key.name === 'n')) {
1256
1502
  for (const x of this.menu.pick.items) if (!x.only) x.checked = key.name === 'a'
1257
1503
  return this.refreshMenu()
1258
1504
  }
@@ -1264,7 +1510,8 @@ export class UI {
1264
1510
  // and not in a menu or a mid-task yes/no question, where Space types a space as usual)
1265
1511
  if (key.name === 'space' && !this.rl.line && !this.menu.pick && !(this.asking && !this.histOn) && this.voiceReady()) return this.#action('voice', write)
1266
1512
  if (!this.asking && !(key.ctrl && key.name === 'c')) return this.#typeAhead(s, key, write)
1267
- if (key.name === 'tab' && key.shift) return this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === this.permission) + 1) % PERMISSIONS.length][0])
1513
+ // Shift+Tab: the mode at the prompt only; never while a question is open (between questions: the one before)
1514
+ if (key.name === 'tab' && key.shift && !this.menu.pick?.nav) return this.histOn ? this.cyclePermission() : undefined
1268
1515
  // A new line instead of sending: Shift/Ctrl/Alt/Cmd+Enter (arrive as "\n" or ESC+Enter),
1269
1516
  // Ctrl+J, "\" right before Enter, and line breaks inside a paste.
1270
1517
  if (key.name === 'paste-start' || key.name === 'paste-end') {
@@ -1297,6 +1544,7 @@ export class UI {
1297
1544
  const twice = key.sequence === '\x1b\x1b' || Date.now() - (this.lastEscape ?? 0) < 800 // a lone Esc also comes with meta set
1298
1545
  this.lastEscape = twice ? 0 : Date.now()
1299
1546
  if (twice) {
1547
+ this.remember(rl.line) // wiped, not lost: ↑ brings it back
1300
1548
  this.clearInput()
1301
1549
  return this.refreshMenu()
1302
1550
  }
@@ -1314,10 +1562,29 @@ export class UI {
1314
1562
  return
1315
1563
  }
1316
1564
  if (m.pick) {
1565
+ // an answer of their own (ask_user's "Something else"): what's typed goes into it, right there
1566
+ const own = m.pick.items.find((x) => x.own)
1567
+ const onOwn = own && it?.item === own
1568
+ const typing = own && !key.ctrl && !key.meta && ((key.name === 'backspace' && onOwn) || (/^[^\x00-\x1f\x7f]+$/.test(s ?? '') && !(key.name === 'space' && m.pick.multi && !onOwn)))
1569
+ if (typing) {
1570
+ own.hint ??= own.text ? 'type your own answer' : own.desc // what it says before anything's typed
1571
+ own.text = key.name === 'backspace' ? (own.text ?? '').slice(0, -1) : (own.text ?? '') + s
1572
+ own.desc = own.text ? `› ${own.text}▏` : own.hint
1573
+ if (m.pick.multi) own.checked = Boolean(own.text)
1574
+ m.sel = m.items.findIndex((x) => x.item === own)
1575
+ return this.refreshMenu()
1576
+ }
1577
+ if (onOwn && own.text && (key.name === 'left' || key.name === 'right')) return // typing: not to another question (Tab still goes)
1578
+ if (onOwn && key.name === 'return' && !own.text?.trim() && !m.pick.multi) return // nothing typed yet: type it here
1579
+ // between questions (ask_user with several): what's ticked stays ticked
1580
+ if (m.pick.nav && !rl.line && (key.name === 'left' || key.name === 'right' || key.name === 'tab')) {
1581
+ m.pick.chosen = { nav: key.name === 'left' || (key.name === 'tab' && key.shift) ? -1 : 1 }
1582
+ return write('\r', { name: 'return' })
1583
+ }
1317
1584
  if (key.name === 'up' || key.name === 'down') return this.#move(key.name === 'up' ? -1 : 1)
1318
1585
  if (key.name === 'tab') return
1319
1586
  if (m.pick.multi && key.name === 'space' && it && !it.item.only) {
1320
- it.item.checked = !it.item.checked // Space ticks; Enter takes the ticked ones; Ctrl+A/N all/none (handled earlier, before tab shortcuts)
1587
+ it.item.checked = !it.item.checked // Space ticks; Enter takes the ticked ones; Alt+A/N all/none (handled earlier, before tab shortcuts)
1321
1588
  return this.refreshMenu()
1322
1589
  }
1323
1590
  if (key.name === 'escape' || (key.name === 'return' && it)) {
@@ -1328,6 +1595,7 @@ export class UI {
1328
1595
  return write('\r', { name: 'return' })
1329
1596
  }
1330
1597
  if (key.name === 'return') return // nothing matches the filter
1598
+ if (!own && this.#cards(m.pick)) return // cards have no filter: typing into one nobody sees would hide them all
1331
1599
  write(s, key)
1332
1600
  return this.refreshMenu()
1333
1601
  }
@@ -1387,7 +1655,7 @@ export class UI {
1387
1655
  if (m.on) return (m.off = rl.line), this.#suggestWhileWorking() // first Esc just closes the suggestions
1388
1656
  return this.escStop()
1389
1657
  }
1390
- if (key.name === 'tab' && key.shift) return this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === this.permission) + 1) % PERMISSIONS.length][0])
1658
+ if (key.name === 'tab' && key.shift) return this.cyclePermission()
1391
1659
  if (key.name === 'pageup' || key.name === 'pagedown') return this.scrollBy(key.name === 'pageup' ? this.page() : -this.page())
1392
1660
  if (it && (key.name === 'up' || key.name === 'down')) {
1393
1661
  m.sel = (m.sel + (key.name === 'up' ? m.items.length - 1 : 1)) % m.items.length
@@ -1449,7 +1717,7 @@ export class UI {
1449
1717
  case 'stop':
1450
1718
  return this.asking ? undefined : this.onEscape?.()
1451
1719
  case 'cycle_permissions':
1452
- return this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === this.permission) + 1) % PERMISSIONS.length][0])
1720
+ return this.asking && !this.histOn ? undefined : this.cyclePermission() // not while a question is open
1453
1721
  case 'newline':
1454
1722
  rl.line = rl.line.slice(0, rl.cursor) + '\n' + rl.line.slice(rl.cursor)
1455
1723
  rl.cursor++
@@ -1670,7 +1938,9 @@ export class UI {
1670
1938
  const w = Math.min(Math.max(0, ...shown.filter((x) => !x.header).map((x) => x.value.length)), 48)
1671
1939
  const lines = shown.map((x, i) => {
1672
1940
  if (x.header) return c.accent(c.bold(x.value.slice(0, width)))
1673
- const plain = `${x.value.padEnd(w)} ${x.desc ?? ''}`.slice(0, width - 2 - pad.length)
1941
+ const full = `${x.value.padEnd(w)} ${x.desc ?? ''}`.trimEnd()
1942
+ const room = width - 2 - pad.length
1943
+ const plain = full.length > room ? `${full.slice(0, room - 1)}…` : full // cut: said so
1674
1944
  const name = plain.slice(0, w)
1675
1945
  if (first + i !== m.sel) return `${pad} ${c.text(name)}${c.faint(plain.slice(w))}`
1676
1946
  const row = `${c.brand('❯')} ${c.bright(c.bold(name))}${c.muted(plain.slice(w))}`
@@ -1678,8 +1948,8 @@ export class UI {
1678
1948
  })
1679
1949
  const more = m.items.length - first - shown.length
1680
1950
  if (more > 0) lines.push(c.faint(` … ${more} more`))
1681
- const how = m.pick?.multi ? '↑↓ move · Space tick · Ctrl+A all · Ctrl+N none · Enter take · Esc cancel · type to filter' : '↑↓ move · Enter choose · Esc cancel · type to filter'
1682
- if (m.pick) lines.unshift(c.faint(m.items.length ? how : `nothing matches "${this.rl.line}" · Esc cancel`))
1951
+ const how = m.pick?.multi ? '↑↓ move · Space tick · Alt+A all · Alt+N none · Enter take · Esc cancel · type to filter' : '↑↓ move · Enter choose · Esc cancel · type to filter'
1952
+ if (m.pick) lines.unshift(c.faint(m.items.length ? how + this.autoHint() : `nothing matches "${this.rl.line}" · Esc cancel`))
1683
1953
  return lines
1684
1954
  }
1685
1955
 
@@ -1760,13 +2030,14 @@ export class UI {
1760
2030
 
1761
2031
  // history: this prompt's messages go into ↑/↓ history (only the main prompt, never answers like keys).
1762
2032
  // One question on screen at a time: a command run beside a task (onNow) and the task can both ask.
2033
+ // A question also waits for voice being recorded to end (its words go where they were going).
1763
2034
  async #free() {
1764
- while (this.full && this.asking) await new Promise((r) => this.freed.push(r))
2035
+ while ((this.full && this.asking) || this.recording) await new Promise((r) => (this.recording ? setTimeout(r, 200) : this.freed.push(r)))
1765
2036
  }
1766
2037
 
1767
2038
  ask(prompt, { initial = '', suggest = false, history = false } = {}) {
1768
2039
  if (this.dialog && !history) this.setDialog(null) // a question (a permission, a picker) needs you: the dialog makes way
1769
- if (this.full && this.asking) return this.#free().then(() => this.ask(prompt, { initial, suggest, history }))
2040
+ if (this.full && (this.asking || (this.recording && !history))) return this.#free().then(() => this.ask(prompt, { initial, suggest, history }))
1770
2041
  if (history && this.kept) [initial, this.kept] = [initial || this.kept, ''] // typed before a submit()
1771
2042
  this.stopSpin()
1772
2043
  const rl = this.#rl()
@@ -1785,6 +2056,8 @@ export class UI {
1785
2056
  }
1786
2057
  // a question in the middle of work: what's being typed for later waits until it's answered
1787
2058
  const draft = !history && rl.line ? [rl.line, (rl.line = ''), (rl.cursor = 0)][0] : ''
2059
+ // piped input: its lines are messages, not answers; nobody's there to answer
2060
+ if (!history && !rl.terminal) return this.write(prompt + c.dim('(no answer: the input is not a terminal)') + '\n'), Promise.resolve(null)
1788
2061
  if (this.queue.length) {
1789
2062
  const l = this.queue.shift()
1790
2063
  log('input', `${prompt.trim()} ${/api key/i.test(prompt) && l ? `${l.slice(0, 4)}…(${l.length} chars)` : l}`) // never log keys
@@ -1825,11 +2098,12 @@ export class UI {
1825
2098
  const pick = this.menu.pick
1826
2099
  const echo = prompt.replace(/^ /, '') // the input's margin isn't part of the conversation
1827
2100
  this.inputMark = this.log.length - 1 // where this message starts, for /rewind
1828
- const picked = Array.isArray(pick?.chosen) ? pick.chosen.map((x) => x.label).join(', ') : pick?.chosen?.label
2101
+ const said = (x) => (x.own && x.text?.trim() ? x.text.trim() : x.label) // their own answer: what they typed
2102
+ const picked = Array.isArray(pick?.chosen) ? pick.chosen.map(said).join(', ') : pick?.chosen && said(pick.chosen)
1829
2103
  if (pick?.quiet) this.render()
1830
- else if (pick) this.write(echo + (picked ?? c.dim('cancelled')) + '\n')
2104
+ else if (pick) this.write(echo + (picked ?? c.dim(pick.closedAs ?? 'cancelled')) + (pick.auto?.fired ? c.dim(` · no answer in ${pick.auto.secs}s: ${pick.auto.fired === 'theirs' ? 'yours' : 'the recommended one'}`) : '') + '\n')
1831
2105
  else if (l !== null && history && this.isCommand(l.trim()) && !/^\s*\/skill:/.test(l)) this.notice(/^\S+/.exec(l.trim())[0], 3000, '›') // a command isn't part of the conversation: its name for a moment (not its arguments: maybe a key)
1832
- else if (l !== null) this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n')
2106
+ else if (l?.trim()) this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n')
1833
2107
  else this.render()
1834
2108
  }
1835
2109
  if (draft) [rl.line, rl.cursor] = [draft, draft.length]
@@ -1839,7 +2113,9 @@ export class UI {
1839
2113
  )
1840
2114
  }
1841
2115
 
1842
- cancelAsk() {
2116
+ // as: what the dialog it closes says it came to (the default: cancelled)
2117
+ cancelAsk(as) {
2118
+ if (as && this.menu.pick) this.menu.pick.closedAs = as
1843
2119
  for (const w of this.waiters.splice(0)) w(null)
1844
2120
  }
1845
2121
 
@@ -1848,33 +2124,91 @@ export class UI {
1848
2124
  // multi: tick several with Space; returns the ticked items (an array), or null.
1849
2125
  // quiet: the question and answer aren't left in the conversation (a question before it starts).
1850
2126
  // fixed: a dialog: no typing to filter, no other keys meanwhile.
1851
- async pick(title, items, { filter = '', multi = false, quiet = false, fixed = false, body = '' } = {}) {
2127
+ // auto: { item, secs }: nobody answers for secs seconds (each key starts the wait again) → item is chosen.
2128
+ // tabs: a row of tabs above it (several questions); nav: ←/→ (Tab, Shift+Tab) close it with { nav: -1 | 1 }.
2129
+ async pick(title, items, { filter = '', multi = false, quiet = false, fixed = false, body = '', auto = null, tabs = '', nav = false } = {}) {
1852
2130
  if (!this.full) {
1853
2131
  items.forEach((it, i) => this.print(` ${i + 1}. ${it.group ? `${it.group} · ` : ''}${it.label}${it.desc ? ' ' + c.dim(it.desc) : ''}`))
1854
2132
  const a = await this.ask(`${title} ${c.dim(multi ? '(numbers, like 1,3)' : '(number)')}: `)
2133
+ this.autoPicked = a === null && Boolean(auto) && !this.rl.terminal && 'nobody' // piped input: nobody's there to answer, so the recommended one (Esc stays no answer)
2134
+ if (this.autoPicked) return multi ? [auto.item] : auto.item
1855
2135
  if (!multi) return items[Number(a) - 1] ?? null
1856
2136
  const chosen = String(a ?? '').split(/[\s,]+/).map((n) => items[Number(n) - 1]).filter(Boolean)
1857
2137
  return chosen.length ? chosen : null
1858
2138
  }
1859
2139
  await this.#free()
1860
2140
  if (multi) for (const it of items) if (!it.only) it.checked ??= false
1861
- this.menu.pick = { items, chosen: null, multi, quiet, fixed, body }
2141
+ this.menu.pick = { items, chosen: null, multi, quiet, fixed, body, tabs, nav, auto: auto && { ...auto } }
2142
+ this.autoPicked = false // chosen for the user (nobody answered in time), for the caller to say so
2143
+ if (auto) {
2144
+ this.#armAuto()
2145
+ this.autoTick = setInterval(() => this.menu.pick?.auto && this.render(), 1000) // the countdown in the hint
2146
+ }
1862
2147
  try {
1863
2148
  await this.ask(`${c.bold(title)} ${c.dim('›')} `, { suggest: true, initial: filter })
1864
2149
  return this.menu.pick.chosen
1865
2150
  } finally {
2151
+ clearTimeout(this.menu.pick?.auto?.timer)
2152
+ clearInterval(this.autoTick)
1866
2153
  this.menu.pick = null
1867
2154
  }
1868
2155
  }
1869
2156
 
2157
+ // The wait of a pick with auto, from now: a key starts it again (debounced); at its end the item is chosen.
2158
+ #armAuto() {
2159
+ const a = this.menu.pick.auto
2160
+ clearTimeout(a.timer)
2161
+ a.until = Date.now() + a.secs * 1000
2162
+ a.timer = setTimeout(() => {
2163
+ const pick = this.menu.pick
2164
+ if (pick?.auto !== a) return
2165
+ if (this.out.hidden) return this.#armAuto() // a tab in the background: you haven't seen it yet
2166
+ const ticked = pick.items.filter((x) => x.checked)
2167
+ const typed = pick.items.find((x) => x.own && x.text?.trim()) // their own answer, typed but not sent
2168
+ a.fired = this.autoPicked = (pick.multi ? ticked.length : typed) ? 'theirs' : true
2169
+ pick.chosen = pick.multi ? (ticked.length ? ticked : [a.item]) : (typed ?? a.item)
2170
+ this.rl.line = ''
2171
+ this.rl.cursor = 0
2172
+ this.ttyWrite('\r', { name: 'return' })
2173
+ }, a.secs * 1000)
2174
+ this.render()
2175
+ }
2176
+
2177
+ // A tab comes on screen: its question's wait starts now.
2178
+ resumeAuto() {
2179
+ if (this.menu.pick?.auto) this.#armAuto()
2180
+ }
2181
+
2182
+ autoHint() {
2183
+ const a = this.menu.pick?.auto
2184
+ return a ? ` · recommended in ${Math.max(0, Math.ceil((a.until - Date.now()) / 1000))}s` : ''
2185
+ }
2186
+
2187
+ // A pick that chooses by itself (auto): how long until it does, and what it will do then.
2188
+ autoLine() {
2189
+ const pick = this.menu.pick
2190
+ const a = pick?.auto
2191
+ if (!a) return ''
2192
+ const theirs = pick.items.some((x) => x.checked || (x.own && x.text?.trim())) // ticked or typed: that's what goes
2193
+ return `◷ ${Math.max(0, Math.ceil((a.until - Date.now()) / 1000))}s · then ${theirs ? 'yours is sent' : (a.say ?? 'the recommended answer is chosen')} · a key restarts it`
2194
+ }
2195
+
1870
2196
  setPermission(mode) {
1871
2197
  log('permissions', mode)
1872
2198
  if (mode === 'plan' && this.permission !== 'plan') this.beforePlan = this.permission // what plan mode asks like, and goes back to
2199
+ this.leftPlan = null
1873
2200
  this.permission = mode
1874
2201
  this.onPermission?.(mode)
1875
2202
  this.render()
1876
2203
  }
1877
2204
 
2205
+ // Shift+Tab: the next mode; plan goes back to the mode before it, and the next press goes on after plan.
2206
+ cyclePermission() {
2207
+ if (this.permission === 'plan' && this.beforePlan && this.beforePlan !== 'plan') return this.setPermission(this.beforePlan), (this.leftPlan = this.beforePlan)
2208
+ const at = this.leftPlan === this.permission ? 'plan' : this.permission
2209
+ this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === at) + 1) % PERMISSIONS.length][0])
2210
+ }
2211
+
1878
2212
  // kind: 'edit', 'command' or 'read'. true = yes, false = no, string = "no, and here is why"
1879
2213
  // kind 'read' (web search and fetch): asked like a command, but never in plan mode, which is for
1880
2214
  // looking around. Otherwise plan mode asks as the mode before it did (only reading tools get here).
@@ -1891,6 +2225,7 @@ export class UI {
1891
2225
  }
1892
2226
  }
1893
2227
  const a = await this.ask(`${c.yellow('?')} ${question} ${c.dim('[Y/n or type feedback]')} `)
2228
+ if (a === null && !this.rl.terminal) return `Not allowed: HeartCode's input is not a terminal, so nobody can approve this. Don't retry it; say in your reply what you would have done.`
1894
2229
  if (a === null) return false
1895
2230
  const t = a.trim()
1896
2231
  if (/^(y|yes)?$/i.test(t)) return true
@@ -1902,12 +2237,13 @@ export class UI {
1902
2237
  { label: 'Yes', value: true },
1903
2238
  { label: "Yes, and don't ask again", value: 'all' },
1904
2239
  { label: 'No', value: false },
1905
- { label: 'No, and tell the model what to do instead', value: 'why' },
2240
+ { label: 'No, and tell the model what to do instead', desc: 'type it here', value: 'why', own: true }, // typed in its row, as ask_user's "Something else"
1906
2241
  ]
1907
- const a = (await this.pick(`${c.yellow('?')} ${question}`, opts))?.value ?? false
1908
- if (a === 'all') this.setPermission('all')
2242
+ const got = await this.pick(`${c.yellow('?')} ${question}`, opts)
2243
+ const a = got?.value ?? false
2244
+ if (a === 'all') this.permission === 'plan' ? (this.beforePlan = 'all') : this.setPermission('all') // plan mode stays: it goes on to 'all' afterwards
1909
2245
  if (a !== 'why') return Boolean(a)
1910
- return (await this.ask(`${c.bold('What should it do instead?')} `))?.trim() || false
2246
+ return got.text?.trim() || false
1911
2247
  }
1912
2248
 
1913
2249
  write(s) {
@@ -1945,7 +2281,7 @@ export class UI {
1945
2281
  Object.assign(this, { tail: m.tail, sgr: m.sgr })
1946
2282
  const lines = text ? text.split('\n') : []
1947
2283
  if (lines.length === 1 || (lines.length && this.dialog)) this.notice(lines[0], 4000, '›')
1948
- else if (lines.length) this.showText(title, text)
2284
+ else if (lines.length) this.showText(title === '/toggle_thinking' ? 'Thinking' : title, text, title) // its key (Alt+O) closes it again
1949
2285
  else this.render()
1950
2286
  }
1951
2287
  // A blank line before a new block, unless there already is one.
@@ -1970,6 +2306,7 @@ export class UI {
1970
2306
 
1971
2307
  spinner(label) {
1972
2308
  this.label = label
2309
+ if (this.requestSince?.()) this.tokenAt = Date.now() // changed during a request: something came (a tool call being written)
1973
2310
  if (!this.out.isTTY || this.timer) return
1974
2311
  let i = 0
1975
2312
  const tick = () => {
@@ -1995,10 +2332,12 @@ export class UI {
1995
2332
  }
1996
2333
  this.beforeRetry ??= typeof this.label === 'function' ? 'thinking' : this.label || 'thinking'
1997
2334
  const until = Date.now() + ms
1998
- const why = shortError(err)
2335
+ // why first, short: "cannot reach http://127.0.0.1:47329/v1/chat/completions (ECONNREFUSED)" → "can't reach 127.0.0.1:47329"
2336
+ let why = shortError(err).replace(/^cannot reach (\S+)(?: \([^)]*\))?/, (m, u) => `can't reach ${URL.canParse(u) ? new URL(u).host : u}`)
2337
+ if (why.length > 50) why = `${why.slice(0, 49)}…`
1999
2338
  const left = () => Math.max(0, Math.ceil((until - Date.now()) / 1000)) * 1000
2000
- if (next) return this.spinner(() => `${c.yellow('⚠')} ${why} · trying ${next.provider} · ${next.model}${left() ? ` in ${duration(left())} (all failed once)` : ''} (attempt ${attempt})`)
2001
- this.spinner(() => `${c.yellow('⚠')} retrying in ${duration(left())} (attempt ${attempt}) · ${why}`)
2339
+ if (next) return this.spinner(() => `${c.yellow('⚠')} ${why} · trying ${next.provider} · ${next.model}${left() ? ` in ${short(left())} (all failed once)` : ''} (try ${attempt})`)
2340
+ this.spinner(() => `${c.yellow('⚠')} ${why} · retrying in ${short(left())} (try ${attempt})`)
2002
2341
  }
2003
2342
 
2004
2343
  stopSpin() {