heartcode 0.1.54 → 0.1.57

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)
@@ -136,11 +140,13 @@ export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
136
140
  const MOUSE_ON = '\x1b[?1000h\x1b[?1002h\x1b[?1006h'
137
141
  const MOUSE_OFF = '\x1b[?1006l\x1b[?1002l\x1b[?1000l'
138
142
 
143
+ export const overSsh = Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.SSH_CLIENT)
144
+
139
145
  // The system clipboard (pbcopy, clip, wl-copy, xclip, xsel); else the terminal's (OSC 52). Over SSH,
140
- // the terminal's only: the system's would be the remote machine's, not the one you're at.
146
+ // the terminal's only: the system's would be the remote machine's, not the one you're at. OSC 52 has
147
+ // no answer and some terminals drop it (macOS Terminal), so 'osc' doesn't mean it got there.
141
148
  export function copyText(text) {
142
- const remote = Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.SSH_CLIENT)
143
- const tools = remote ? [] : process.platform === 'darwin' ? [['pbcopy']] : process.platform === 'win32' ? [['clip']] : [['wl-copy'], ['xclip', '-selection', 'clipboard'], ['xsel', '-b', '-i']]
149
+ const tools = overSsh ? [] : process.platform === 'darwin' ? [['pbcopy']] : process.platform === 'win32' ? [['clip']] : [['wl-copy'], ['xclip', '-selection', 'clipboard'], ['xsel', '-b', '-i']]
144
150
  for (const [cmd, ...args] of tools) if (spawnSync(cmd, args, { input: text, stdio: ['pipe', 'ignore', 'ignore'] }).status === 0) return 'system'
145
151
  process.stdout.write(`\x1b]52;c;${Buffer.from(text).toString('base64')}\x07`)
146
152
  return 'osc'
@@ -306,6 +312,8 @@ function sgrState(state = {}, text) {
306
312
  }
307
313
  const sgrPrefix = (st = {}) => [st.fg, st.bg, st.bold, st.italic].filter(Boolean).map((x) => `\x1b[${x}m`).join('')
308
314
 
315
+ const plainOf = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
316
+
309
317
  // Cuts a colored line to `cols` cells.
310
318
  function fit(line, cols) {
311
319
  return wrapAnsi(line, cols)[0]
@@ -356,13 +364,14 @@ export function wrapAnsi(line, cols) {
356
364
  return rows
357
365
  }
358
366
 
359
- // wrapAnsi at spaces: a word moves to the next row whole (one longer than a row is still cut)
360
- export function wrapWords(line, cols) {
367
+ // wrapAnsi at spaces: a word moves to the next row whole (one longer than a row is still cut);
368
+ // hang: the rows after the first indented by that many cells
369
+ export function wrapWords(line, cols, hang = 0) {
361
370
  const width = (x) => x.replace(/\x1b\[[0-9;]*m/g, '').length
362
371
  const rows = []
363
372
  let row = ''
364
373
  for (const word of line.split(/(?<= )/)) {
365
- if (width(row.trim()) && width(row + word.trimEnd()) > cols) {
374
+ if (width(row.trim()) && width(row + word.trimEnd()) > (rows.length ? cols - hang : cols)) {
366
375
  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
367
376
  rows.push(row.trimEnd() + (style ? '\x1b[0m' : ''))
368
377
  row = style
@@ -370,7 +379,33 @@ export function wrapWords(line, cols) {
370
379
  row += word
371
380
  }
372
381
  rows.push(row)
373
- return rows.flatMap((r) => wrapAnsi(r, cols))
382
+ const pad = ' '.repeat(hang)
383
+ return rows.flatMap((r, i) => {
384
+ const [head, ...more] = wrapAnsi(r, i ? cols - hang : cols)
385
+ return [i ? pad + head : head, ...(more.length ? wrapAnsi(more.join(''), cols - hang).map((x) => pad + x) : [])]
386
+ })
387
+ }
388
+
389
+ // wrapWords with a hanging indent: wrapped rows go under the text, not back to column 0 (after a
390
+ // marker like "! ", "● ", "⎿ ", or a two-column line's description column)
391
+ export function wrapHang(line, cols) {
392
+ const plain = line.replace(/\x1b\[[0-9;]*m/g, '')
393
+ if (width(plain) <= cols) return [line]
394
+ const m = /^\s*(?:[^\w\s]{1,2}|\d{1,3}[.)]) (?=\S)/.exec(plain) ?? /^\s*\S.*?\S {2,}(?=\S)/.exec(plain) ?? /^\s*/.exec(plain)
395
+ const hang = width(m[0])
396
+ return wrapWords(line, cols, hang < cols * 0.6 ? hang : 0)
397
+ }
398
+
399
+ // "a · b · c" on as many rows as it needs, broken between its parts (never inside one)
400
+ export function wrapParts(line, cols, sep = ' · ') {
401
+ const vis = (x) => width(x.replace(/\x1b\[[0-9;]*m/g, ''))
402
+ 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), [])
403
+ }
404
+
405
+ // 4000 → "4s", 75000 → "1m 15s", 2h 3m: a clock that fits on a busy line
406
+ const short = (ms) => {
407
+ const s = Math.max(0, Math.floor(ms / 1000))
408
+ 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`
374
409
  }
375
410
 
376
411
  // Streams text as an indented, word-wrapped block: "<marker>first line\n next line".
@@ -401,7 +436,7 @@ export class Block {
401
436
  out += '\n'.repeat(Math.min(this.newlines, 2)) + this.indent
402
437
  this.col = this.indent.length
403
438
  this.newlines = 0
404
- } else if (this.col >= this.width || (ch === ' ' && this.col >= this.width - 12)) {
439
+ } else if (!this.nowrap && (this.col >= this.width || (ch === ' ' && this.col >= this.width - 12))) {
405
440
  out += '\n' + this.indent + this.hang
406
441
  this.col = this.indent.length + this.hang.length
407
442
  if (ch === ' ') continue
@@ -417,9 +452,10 @@ export class Block {
417
452
  }
418
453
  }
419
454
 
420
- // The model's Markdown, drawn as it streams in: headings, lists, quotes, code blocks, rules,
421
- // **bold**, *italic* and `code`. Into a Block (which wraps); held back only while a line's start
422
- // or a "*" could still be a marker. Tables and links stay as written.
455
+ // The model's Markdown, drawn as it streams in: headings, lists, quotes, code blocks (with a gutter),
456
+ // tables (in columns: held back until the table ends), rules, **bold**, *italic* and `code`. Into a
457
+ // Block (which wraps); held back only while a line's start or a "*" could still be a marker. Links
458
+ // stay as written.
423
459
  export class Markdown {
424
460
  constructor(block, base = (x) => x) {
425
461
  Object.assign(this, { block, base, buf: '', sol: true, fence: false, bold: false, ital: false, code: false, line: null, prev: ' ' })
@@ -455,7 +491,11 @@ export class Markdown {
455
491
  this.fence = !this.fence
456
492
  return nl < 0 ? s.length : nl + 1 // the fence line itself isn't shown
457
493
  }
458
- if (this.fence) return 0
494
+ if (this.fence) {
495
+ b.hang = ' '
496
+ this.#out('│ ', c.ghost) // code, set apart from the prose
497
+ return 0
498
+ }
459
499
  if (whole && /^\s*([-*_])(\s*\1){2,}\s*$/.test(head)) {
460
500
  this.#out('─'.repeat(Math.min(40, b.width - b.indent.length)), c.ghost)
461
501
  return head.length
@@ -478,21 +518,72 @@ export class Markdown {
478
518
  if ((m = /^\s*>\s?/.exec(head))) {
479
519
  b.hang = ' '
480
520
  this.line = (x) => c.faint(c.italic(x))
481
- this.#out('│ ', c.ghost)
521
+ this.#out('▎ ', c.accent) // a quote: not the code gutter's │
482
522
  return m[0].length
483
523
  }
484
524
  return 0
485
525
  }
526
+ // A table ("| a | b |" rows, "|---|" under the head): once it has ended (false: not yet), drawn
527
+ // in columns fitted to the width, the head bold, a rule under it. Returns how much of s it took.
528
+ #table(s, final) {
529
+ const lines = []
530
+ let at = 0
531
+ for (;;) {
532
+ const nl = s.indexOf('\n', at)
533
+ if (nl < 0) {
534
+ const rest = s.slice(at)
535
+ if (/^[ \t]*[^ \t|]/.test(rest)) break // the next line isn't a row: the table is over
536
+ if (!final) return false // a row still coming, or the table may go on
537
+ if (rest.trim()) lines.push(rest), (at = s.length)
538
+ break
539
+ }
540
+ const line = s.slice(at, nl)
541
+ if (!/^[ \t]*\|/.test(line)) break
542
+ lines.push(line)
543
+ at = nl + 1
544
+ }
545
+ const sep = (l) => /^[ \t]*\|?[ \t]*:?-{2,}:?[ \t]*(\|[ \t]*:?-{2,}:?[ \t]*)*\|?[ \t]*$/.test(l)
546
+ const b = this.block
547
+ if (!lines.some(sep)) {
548
+ for (const l of lines) this.#out(l + '\n', this.base) // not a table after all: as written
549
+ return at
550
+ }
551
+ const strip = (t) => t.replace(/\*\*|__|`/g, '').trim()
552
+ const rows = lines.filter((l) => !sep(l)).map((l) => l.trim().replace(/^\||\|$/g, '').split('|').map(strip))
553
+ const n = Math.max(...rows.map((r) => r.length))
554
+ const wide = [...Array(n)].map((_, k) => Math.max(1, ...rows.map((r) => width(r[k] ?? ''))))
555
+ const room = b.width - b.indent.length - 3 * (n - 1)
556
+ 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
557
+ const cell = (t, w) => (width(t) > w ? `${sliceCols(t, 0, w - 1)}…` : t + ' '.repeat(w - width(t)))
558
+ b.nowrap = true
559
+ rows.forEach((r, i) => {
560
+ wide.forEach((w, k) => {
561
+ if (k) this.#out(' │ ', c.ghost)
562
+ const t = k === n - 1 ? cell(r[k] ?? '', w).trimEnd() : cell(r[k] ?? '', w)
563
+ this.#out(t || ' ', i ? this.base : (x) => c.bold(c.bright(x)))
564
+ })
565
+ this.#out('\n')
566
+ if (!i) this.#out(wide.map((w) => '─'.repeat(w)).join('─┼─') + '\n', c.ghost)
567
+ })
568
+ b.nowrap = false
569
+ return at
570
+ }
486
571
  #run(final) {
487
572
  let s = this.buf
488
573
  let text = ''
489
574
  const flush = () => (this.#out(text), (text = ''))
490
575
  let i = 0
491
576
  while (i < s.length) {
577
+ if (this.sol && !this.fence && /^[ \t]*\|/.test(s.slice(i, i + 40))) {
578
+ const n = this.#table(s.slice(i), final)
579
+ if (n === false) break
580
+ i += n
581
+ continue
582
+ }
492
583
  if (this.sol) {
493
584
  const n = this.#lineStart(s.slice(i), final)
494
585
  if (n === false) break
495
- this.sol = false
586
+ this.sol = n > 0 && s[i + n - 1] === '\n' // a fence line, taken whole: the next line starts next
496
587
  i += n
497
588
  continue
498
589
  }
@@ -688,6 +779,8 @@ export class UI {
688
779
  this.asking = false
689
780
  this.frame = 0
690
781
  this.dialog = null // a box over the screen (the background commands' logs)
782
+ this.waitingFor = null // () → the model a request waits on (the app's), for "waiting for <model>"
783
+ this.helpers = new Map() // helpers at work (agent.js): label → what it's doing now, shown under the spinner
691
784
  }
692
785
 
693
786
  // A dialog: a box in the middle, 70% of the screen each way, the conversation going on around it;
@@ -704,8 +797,9 @@ export class UI {
704
797
  this.render()
705
798
  }
706
799
  // Text to read (a command's answer: /help, /context, /diff…) in a dialog: ↑/↓, PgUp/PgDn, Home/End
707
- // and the wheel scroll it, Esc closes it. Without the full screen: printed.
708
- showText(title, text) {
800
+ // and the wheel scroll it, Esc closes it (and toggle: a key's action, as the key that opened it).
801
+ // Without the full screen: printed.
802
+ showText(title, text, toggle) {
709
803
  if (!this.full) return this.print(text)
710
804
  const all = String(text).split('\n')
711
805
  let top = 0
@@ -713,26 +807,27 @@ export class UI {
713
807
  let total = 0
714
808
  this.setDialog({
715
809
  title,
810
+ toggle,
716
811
  key: (key) => {
717
812
  const by = { up: key.wheel ? -3 : -1, down: key.wheel ? 3 : 1, pageup: -page, pagedown: page, home: -1e9, end: 1e9 }[key.name]
718
813
  if (by) top = Math.max(0, Math.min(top + by, total - page))
719
814
  },
720
815
  draw: (w, h) => {
721
- const rows = all.flatMap((l) => wrapWords(l, w))
816
+ const rows = all.flatMap((l) => wrapHang(l, w)) // a two-column line's description wraps under itself
722
817
  total = rows.length
723
- page = h - 2
818
+ const foot = (p) => wrapParts(`${total > p ? `${top + 1}–${Math.min(total, top + p)} of ${total} lines · ↑/↓ PgUp/PgDn scroll · ` : ''}Esc close`, w)
819
+ page = h - 1 - foot(h - 2).length
724
820
  top = Math.max(0, Math.min(top, total - page))
725
- const shown = rows.slice(top, top + page)
726
- const where = total > page ? `${top + 1}–${Math.min(total, top + page)} of ${total} lines · ↑/↓ PgUp/PgDn scroll · ` : ''
727
- return [...shown, '', c.faint(`${where}Esc close`)]
821
+ return [...rows.slice(top, top + page), '', ...foot(page).map((r) => c.faint(r))]
728
822
  },
729
823
  })
730
824
  }
731
825
 
732
- // where it is: { x, y, w, h } (screen cells, from 0; the inside, without the border)
826
+ // where it is: { x, y, w, h } (screen cells, from 0; the inside, without the border); 70% of the
827
+ // screen, 90% of a small one (a narrow one: long names on fewer rows)
733
828
  #dialogBox(cols, rows) {
734
- const w = Math.max(30, Math.floor(cols * 0.7))
735
- const h = Math.max(8, Math.floor(rows * 0.7))
829
+ const w = Math.max(30, Math.floor(cols * (cols < 100 ? 0.9 : 0.7)))
830
+ const h = Math.max(8, Math.floor(rows * (rows < 40 ? 0.9 : 0.7)))
736
831
  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 }
737
832
  }
738
833
  // d: { title, lines(w, h) → lines (at most h), fill?: always 70% tall too (a log), cursor?(w) →
@@ -751,14 +846,14 @@ export class UI {
751
846
  const x = Math.floor((cols - W - 2) / 2) + 1
752
847
  const y = Math.floor((rows - h - 2 * PY - 2) / 2) + 1
753
848
  this.dialogAt = { x, y, W, H: h + 2 * PY, cx: x + 1 + PX, cy: y + 1 + PY } // for the mouse (screen cells, from 1)
754
- const paint = (t) => (background ? `${background}${t.replace(/\x1b\[(0|49)?m/g, (m) => m + background)}\x1b[0m` : `${t}\x1b[0m`)
849
+ const paint = (t) => (background ? `${background}${foreground}${paintBg(t)}\x1b[0m` : `${t}\x1b[0m`)
755
850
  const pad = (t, n) => {
756
851
  const cut = fit(t, n)
757
852
  return cut + ' '.repeat(Math.max(0, n - width(cut.replace(/\x1b\[[0-9;]*m/g, ''))))
758
853
  }
759
854
  const title = name ? ` ${width(name) > W - 6 ? `${fit(name, W - 7)}…` : name} ` : '' // too long: cut (a question shows all of it inside)
760
855
  const row = (i, t) => `\x1b[${y + i};${x}H${paint(t)}`
761
- let out = row(0, c.brand('╭─') + c.bold(title) + c.brand('─'.repeat(Math.max(0, W - width(title) - 1)) + '╮'))
856
+ let out = row(0, c.brand('╭─') + c.bright(c.bold(title)) + c.brand('─'.repeat(Math.max(0, W - width(title) - 1)) + '╮'))
762
857
  const blank = c.brand('│') + ' '.repeat(W) + c.brand('│')
763
858
  for (let i = 0; i < PY; i++) out += row(1 + i, blank)
764
859
  for (let i = 0; i < h; i++) out += row(1 + PY + i, c.brand('│') + ' '.repeat(PX) + pad(lines[i] ?? '', w) + ' '.repeat(PX) + c.brand('│'))
@@ -771,11 +866,17 @@ export class UI {
771
866
  return [out, cur ? `\x1b[${y + 1 + PY + cur.row};${x + 1 + PX + Math.min(cur.col, w - 1)}H\x1b[?25h` : '\x1b[?25l']
772
867
  }
773
868
 
869
+ // A pick shown as cards: one to choose from a few, in no groups (no filter to type into)
870
+ #cards(pick) {
871
+ return Boolean(pick && !pick.multi && pick.items.length <= 6 && !pick.items.some((x) => x.group))
872
+ }
873
+
774
874
  // The question being asked, as a dialog: its title; what's typed (the filter, or the answer) with the
775
875
  // cursor; a picker's choices. A short list (a few, one to choose) is shown as cards: the name, its
776
876
  // description under it. A permission (confirm) shows what just happened (the change or command it
777
877
  // asks about) above the choices. A picker's body (pick's option): a few lines saying what's going on.
778
- #question() {
878
+ // Too little room: the keys and the countdown stay; the text, the choices, what it's about give way.
879
+ #question(cols, rows) {
779
880
  const rl = this.rl
780
881
  const m = this.menu
781
882
  const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
@@ -789,55 +890,125 @@ export class UI {
789
890
  const padTo = (t, n) => t + ' '.repeat(Math.max(0, n - width(plain(t))))
790
891
  const pick = m.pick
791
892
  const choices = pick ? m.items.filter((x) => !x.header) : []
792
- const cards = pick && !pick.multi && pick.items.length <= 6 && !m.items.some((x) => x.header)
893
+ const cards = this.#cards(pick)
894
+ const own = pick?.items.some((x) => x.own) // typing goes into "Something else", not a filter
895
+ const typingOwn = m.items[m.sel]?.item?.own && m.items[m.sel].item.text // ←/→ move in what's typed; Tab goes on
793
896
  const body = pick?.body ? String(pick.body).split('\n') : []
794
- const hint = (pick ? (pick.fixed ? '↑↓ move · Enter choose · Esc close' : pick.multi ? '↑↓ move · Space tick · Alt+A all · Alt+N none · Enter take · Esc cancel · type to filter' : `↑↓ move · Enter choose · Esc cancel${cards ? '' : ' · type to filter'}`) : 'Enter send · Esc cancel') + this.autoHint()
897
+ const hint = (pick?.nav ? (typingOwn ? 'Tab questions · ' : '←→ questions · ') : '') + (pick ? (pick.ctrlC ? 'Enter, Esc or Ctrl+C turn it off' : 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')
898
+ const timer = this.autoLine() // on its own line, so it's seen (and not cut off with the keys)
899
+ const long = width(title) > this.#dialogBox(cols, rows).w - 6 // too long for the border: inside instead, said once
900
+ // at most n rows; the rest said to be there
901
+ const clip = (lines, n) => (lines.length <= n ? lines : [...lines.slice(0, Math.max(0, n - 1)), c.faint(`↓ ${lines.length - n + 1} more lines`)])
902
+ // text on at most n rows of w, the last ending in "…" when there's more
903
+ const rowsOf = (t, w, n) => {
904
+ const r = wrapWords(t, w)
905
+ return r.length <= n ? r : [...r.slice(0, n - 1), `${fit(r[n - 1], w - 1)}…`]
906
+ }
795
907
  let at = 0
796
- const long = (w) => width(title) > w // too long for the border: all of it inside too
797
908
  return {
798
- title: title.length > 200 ? title.slice(0, 200) : title,
799
- cursor: (w) => (pick?.fixed || (cards && pick) ? null : { row: at, col: field(w).col }),
909
+ title: long || title.length > 200 ? '' : title,
910
+ cursor: (w) => (pick?.fixed || (cards && pick) || own ? null : { row: at, col: field(w).col }),
800
911
  lines: (w, h) => {
801
- const head = long(w) ? [...wrapAnsi(c.bold(title), w).map((l) => l), ''] : []
802
- const text = body.flatMap((l) => wrapAnsi(/^https?:\/\/\S+$/.test(l.trim()) ? c.info(l) : c.muted(l), w)) // an address in its link color
803
- const intro = [...head, ...text, ...(text.length ? [''] : [])]
912
+ const rule = c.ghost('─'.repeat(w))
913
+ const head = long ? [...wrapWords(c.bright(c.bold(title.slice(0, 1000))), w), ''] : []
914
+ const text = body.flatMap((l) => wrapHang(/^https?:\/\/\S+$/.test(l.trim()) ? c.info(l) : c.muted(l), w)) // an address in its link color
915
+ const intro = [...(pick?.tabs ? [...wrapAnsi(c.text(pick.tabs), w), ''] : []), ...head, ...text, ...(text.length ? [''] : [])]
916
+ const keys = wrapParts(hint, w).map((r) => c.faint(r))
804
917
  if (!pick) {
805
- const recent = this.askAbout ? this.#recent(w, Math.min(8, h - intro.length - 5)) : []
806
- const top = [...recent, ...(recent.length ? [c.ghost('─'.repeat(w)), ''] : []), ...intro]
918
+ const shown = clip(intro, h - 2 - keys.length)
919
+ const recent = this.askAbout ? this.#recent(w, Math.min(8, h - shown.length - 4 - keys.length), title) : []
920
+ const top = [...recent, ...(recent.length ? [rule, ''] : []), ...shown]
807
921
  at = top.length
808
- return [...top, field(w).text, '', c.faint(hint)]
922
+ return [...top, field(w).text, '', ...keys]
809
923
  }
924
+ const filter = pick.fixed || cards || own ? [] : [field(w).text, rule]
925
+ const tail = ['', ...(timer ? wrapParts(timer, w).map((r) => c.warn(r)) : []), ...keys]
926
+ // the cards: each its rows (a long name on two, a description on up to three), a gap between
927
+ const blocks = !cards
928
+ ? []
929
+ : choices.map((x, i) => {
930
+ const on = m.items[m.sel] === x
931
+ 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)))
932
+ const desc = x.item.desc ? rowsOf(String(x.item.desc), w - 2, 3).map((r) => ` ${on ? c.muted(r) : c.faint(r)}`) : []
933
+ const rows = [...name, ...desc].map((r) => (on ? c.select(padTo(r, w)) : r))
934
+ return i < choices.length - 1 && choices.some((y) => y.item.desc) ? [...rows, ''] : rows
935
+ })
936
+ const want = cards ? blocks.flat().length : Math.max(1, m.items.length)
937
+ const least = Math.min(want, cards ? Math.max(...blocks.map((b) => b.length)) + 2 : 3) // the choices give way first, down to this
938
+ const top0 = clip(intro, Math.max(3, h - tail.length - filter.length - least))
939
+ const room = Math.max(1, h - tail.length - filter.length - top0.length)
810
940
  let list
811
- if (cards) {
812
- list = choices.length
813
- ? choices.flatMap((x, i) => {
814
- const on = m.items[m.sel] === x
815
- const name = on ? `${c.brand('❯')} ${c.bright(c.bold(x.item.label))}` : ` ${c.text(x.item.label)}`
816
- const desc = x.item.desc ? (on ? ` ${c.muted(x.item.desc)}` : ` ${c.faint(x.item.desc)}`) : null
817
- const rows = [name, ...(desc ? [desc] : [])].map((r) => (on ? c.select(padTo(r, w)) : r))
818
- return i < choices.length - 1 && choices.some((y) => y.item.desc) ? [...rows, ''] : rows // a gap between cards that have two lines
819
- })
820
- : [c.faint(`nothing matches "${rl.line}"`)]
941
+ if (!choices.length) list = [c.faint(`nothing matches "${rl.line}"`)]
942
+ else if (!cards) list = this.#menuLines(w, Math.max(1, Math.min(room - (m.items.length > room ? 1 : 0), m.items.length))).slice(1)
943
+ else if (blocks.flat().length <= room) list = blocks.flat()
944
+ else {
945
+ // not all of them fit: the chosen one and those around it, with how many more above and below
946
+ let [a, b] = [Math.max(0, choices.findIndex((x) => m.items[m.sel] === x)), 0]
947
+ b = a + 1
948
+ const size = (a, b) => blocks.slice(a, b).flat().length + (a > 0) + (b < blocks.length)
949
+ for (;;) {
950
+ if (b < blocks.length && size(a, b + 1) <= room) b++
951
+ else if (a > 0 && size(a - 1, b) <= room) a--
952
+ else break
953
+ }
954
+ const up = a ? [c.faint(`↑ ${a} more`)] : []
955
+ const down = b < blocks.length ? [c.faint(`↓ ${blocks.length - b} more`)] : []
956
+ list = [...up, ...blocks.slice(a, b).flat().slice(0, Math.max(1, room - up.length - down.length)), ...down]
821
957
  }
822
- const filter = pick.fixed || cards ? [] : [field(w).text, c.ghost('─'.repeat(w))]
823
- const room = h - intro.length - filter.length - 2
824
- 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}"`)]
825
- const recent = this.askAbout ? this.#recent(w, Math.min(8, room - list.length - 1)) : []
826
- const top = [...recent, ...(recent.length ? [c.ghost('─'.repeat(w)), ''] : []), ...intro]
958
+ const recent = this.askAbout ? this.#recent(w, Math.min(8, h - tail.length - filter.length - top0.length - list.length - 2), title) : []
959
+ const top = [...recent, ...(recent.length ? [rule, ''] : []), ...top0]
827
960
  at = top.length
828
- return [...top, ...filter, ...list, '', c.faint(hint)]
961
+ return [...top, ...filter, ...list, ...tail]
829
962
  },
830
963
  }
831
964
  }
832
965
 
833
- // The last `n` rows of this task's output at width w (what a question in the middle of the work is about).
834
- #recent(w, n) {
966
+ // The plan (todo list) while it works, kept in sight under the spinner: how much is done, what's
967
+ // being done, what's left. Long ones: the finished folded into a count, the open ones up to 8.
968
+ #todoLines(cols) {
969
+ const todos = this.todos?.() ?? []
970
+ const open = todos.filter((t) => t.status !== 'completed')
971
+ if (!open.length) return []
972
+ const done = todos.length - open.length
973
+ const mark = { pending: c.muted('☐'), in_progress: c.info('◐'), completed: c.faint('☑') }
974
+ 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)
975
+ const shown = todos.length <= 8 ? todos : open.slice(0, 7)
976
+ return [
977
+ fit(` ${c.muted('Plan')} ${c.faint(`· ${done} of ${todos.length} done`)}`, cols),
978
+ ...(todos.length > 8 && done ? [fit(` ${c.faint(`☑ ${done} done`)}`, cols)] : []),
979
+ ...shown.map(line),
980
+ ...(open.length > shown.filter((t) => t.status !== 'completed').length ? [fit(` ${c.faint(`… ${open.length - 7} more`)}`, cols)] : []),
981
+ ]
982
+ }
983
+
984
+ // The last lines of this task's output, at most n rows of w (what a question in the middle of the work
985
+ // is about): whole lines, from the start of a block (not mid-sentence), without what the question
986
+ // itself says (about: its text, e.g. the command it asks to run).
987
+ #recent(w, n, about = '') {
835
988
  if (n <= 0) return []
836
- const out = []
989
+ const flat = (t) => t.replace(/\x1b\[[0-9;]*m/g, '').replace(/\s+/g, ' ').trim().toLowerCase()
990
+ const said = flat(about)
837
991
  const from = Math.max(0, (this.inputMark ?? 0) + 1) // this task's: from after your message
838
- for (let i = this.log.length - 1; i >= from && out.length < n; i--) out.unshift(...wrapAnsi(this.log[i], w))
839
- while (out.length && !out[0].trim()) out.shift()
840
- return out.slice(-n)
992
+ const got = [] // [{ i, rows }]
993
+ let used = 0
994
+ let cut = false
995
+ for (let i = this.log.length - 1; i >= from; i--) {
996
+ const t = flat(this.log[i]).replace(/^[^\w\s]{1,2} /, '')
997
+ if (t.length >= 8 && said.includes(t)) continue // already in the question
998
+ const rows = wrapHang(this.log[i], w)
999
+ if (used + rows.length > n) {
1000
+ cut = true
1001
+ break
1002
+ }
1003
+ got.unshift({ i, rows })
1004
+ used += rows.length
1005
+ }
1006
+ // cut short: from the first line that starts a block (after a blank line, or not indented)
1007
+ const start = cut ? got.findIndex((g) => !flat(this.log[g.i - 1] ?? '') || /^\S/.test(plainOf(this.log[g.i]))) : 0
1008
+ const out = got.slice(Math.max(0, start)).flatMap((g) => g.rows)
1009
+ while (out.length && !plainOf(out[0]).trim()) out.shift()
1010
+ while (out.length && !plainOf(out.at(-1)).trim()) out.pop()
1011
+ return out
841
1012
  }
842
1013
 
843
1014
  // One model reply: thinking (dim, its own block) kept apart from the answer.
@@ -862,10 +1033,11 @@ export class UI {
862
1033
  return {
863
1034
  think: (t) => {
864
1035
  if (!t || text) return
1036
+ this.tokenAt = Date.now() // it answers: no longer "waiting for" it
865
1037
  thought += t
866
1038
  if (!this.showThinking && !think) {
867
1039
  this.thinkTail = thought.slice(-4000) // its last two lines, live (render)
868
- return this.spinner(`thinking · ${secs()}`)
1040
+ return this.spinner('thinking') // the time: in the line under it (and "thought for" after)
869
1041
  }
870
1042
  if (!think) {
871
1043
  this.thinkTail = ''
@@ -880,7 +1052,9 @@ export class UI {
880
1052
  },
881
1053
  text: (t) => {
882
1054
  if (!t) return
1055
+ this.tokenAt = Date.now()
883
1056
  if (!text) {
1057
+ if (this.label === 'thinking') this.label = 'answering'
884
1058
  think?.end()
885
1059
  this.gap()
886
1060
  summary()
@@ -936,7 +1110,7 @@ export class UI {
936
1110
  // mouse: HeartCode takes the mouse (the wheel scrolls the conversation, dragging copies); off,
937
1111
  // the terminal keeps it, so text is selected and copied the terminal's own way (over SSH too).
938
1112
  fullscreen({ mouse = false } = {}) {
939
- if (this.full || !(this.input.isTTY && this.out.isTTY)) return
1113
+ if (this.full || !(this.input.isTTY && this.out.isTTY) || process.env.TERM === 'dumb') return
940
1114
  this.full = true
941
1115
  this.mouseOn = mouse ? MOUSE_ON : ''
942
1116
  // alternate screen · kitty keyboard protocol (Shift/Cmd+Enter are told apart) · bracketed paste
@@ -1040,7 +1214,7 @@ export class UI {
1040
1214
  this.render()
1041
1215
  }
1042
1216
  #copied(text) {
1043
- this.notice(`copied ${text.length} character${text.length === 1 ? '' : 's'}${copyText(text) === 'osc' ? ' (through the terminal)' : ''}`)
1217
+ this.notice(`copied ${text.length} character${text.length === 1 ? '' : 's'}${copyText(text) === 'osc' ? ' (if your terminal allows it)' : ''}`)
1044
1218
  }
1045
1219
  // A double click: the word under it (no spaces; quotes and brackets around it left out), copied.
1046
1220
  #copyWord(x, y) {
@@ -1156,7 +1330,7 @@ export class UI {
1156
1330
  const out = []
1157
1331
  this.log.forEach((line, i) => {
1158
1332
  const w = this.wrapped[i]
1159
- if (!w || w.src !== line) this.wrapped[i] = { src: line, rows: wrapAnsi(line, cols) }
1333
+ if (!w || w.src !== line) this.wrapped[i] = { src: line, rows: wrapHang(line, cols) } // at spaces, wrapped rows under the text
1160
1334
  out.push(...this.wrapped[i].rows)
1161
1335
  })
1162
1336
  return out
@@ -1184,23 +1358,33 @@ export class UI {
1184
1358
  const below = [hiddenBelow ? note(hiddenBelow, '↓') : rule, ...(statusText ? statusText.split('\n').map((l) => fit(' ' + l, cols)) : [])]
1185
1359
  const bottom = []
1186
1360
  if (this.timer && !this.asking) {
1187
- // the spinner on its own line; the timer (and Esc) on the next, so neither line is crammed
1361
+ // the spinner on its own line, one status: the model not answering yet (since this request went),
1362
+ // else what's being done; the time in all (and Esc) on the next, on more lines when it doesn't fit
1188
1363
  const request = this.requestSince?.()
1189
- const timer = this.busySince ? `responding ${duration(this.worked())}${request ? ` · waiting for model ${duration(Date.now() - request)}` : ''} · Esc to stop${this.thinkTail ? ' · Alt+O shows all thinking' : ''}` : ''
1364
+ const label = this.#label()
1365
+ const waiting = request && !(this.tokenAt >= request) && this.beforeRetry === undefined
1366
+ const status = waiting ? `${/^(working|thinking|answering)$/.test(plainOf(label)) ? '' : `${label} · `}waiting for ${this.waitingFor?.() || 'the model'} ${short(Date.now() - request)}` : label
1367
+ 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(' · ') : ''
1190
1368
  if (this.thinkTail) {
1191
1369
  // the thinking's last two lines (long ones wrapped), dim, changing as it comes
1192
1370
  const w = Math.max(20, cols - 6)
1193
1371
  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)
1194
1372
  for (const l of lines.slice(-2)) bottom.push(fit(` ${c.think(c.italic(l))}`, cols))
1195
1373
  }
1196
- bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(this.#label())}`, cols))
1197
- if (timer) bottom.push(fit(` ${c.faint(timer)}`, cols))
1374
+ bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(status)}`, cols))
1375
+ if (timer) bottom.push(...wrapParts(timer, cols - 2).map((r) => fit(` ${c.faint(r)}`, cols)))
1376
+ // helpers at work (agent.js keeps them in this.helpers: label → what it's doing), then the plan
1377
+ const helpers = [...this.helpers]
1378
+ 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))
1379
+ if (helpers.length > 6) bottom.push(c.faint(` … ${helpers.length - 5} more`))
1380
+ bottom.push(...this.#todoLines(cols))
1198
1381
  }
1199
1382
  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`))
1200
1383
  if (this.ahead.length) {
1201
1384
  const key = (k, d) => `${c.muted(k)} ${c.faint(d)}`
1202
1385
  const sep = c.ghost(' · ')
1203
- 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))
1386
+ 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)}`
1387
+ bottom.push(...wrapParts(queued, cols - 2, sep).map((r) => fit(` ${r}`, cols))) // on more lines, not cut
1204
1388
  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))
1205
1389
  if (this.ahead.length > 5) bottom.push(c.faint(` … ${this.ahead.length - 5} more`))
1206
1390
  }
@@ -1223,7 +1407,7 @@ export class UI {
1223
1407
  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)
1224
1408
  }
1225
1409
  // a theme with a background: every row painted with it (a style ending its own background goes back to it)
1226
- 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`
1410
+ let row = background ? (line) => `${background}${foreground}${paintBg(line)}\x1b[K\x1b[0m` : (line) => `${line}\x1b[0m\x1b[K`
1227
1411
  let s = '\x1b[?25l'
1228
1412
  // a dialog open: everything behind it dimmed
1229
1413
  if (this.dialog || asked) {
@@ -1260,7 +1444,7 @@ export class UI {
1260
1444
  let cursor
1261
1445
  if (this.dialog || asked) {
1262
1446
  this.regions = new Map()
1263
- 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())
1447
+ 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))
1264
1448
  s += box
1265
1449
  cursor = cur // a question: its cursor in the box; else hidden
1266
1450
  } else {
@@ -1313,6 +1497,7 @@ export class UI {
1313
1497
  return this.dialog.key?.(key, s), this.render()
1314
1498
  }
1315
1499
  if (this.recording) return this.recording.key(key, bound) // voice: Space, Enter, Esc; the rest waits
1500
+ if (this.menu.pick?.ctrlC && key.ctrl && key.name === 'c') return this.cancelAsk()
1316
1501
  // a fixed dialog (pick(…, { fixed })): only its keys, nothing typed and no shortcuts
1317
1502
  if (this.menu.pick?.fixed && !['up', 'down', 'return', 'escape'].includes(key.name) && !(key.ctrl && key.name === 'c')) return
1318
1503
  // In a multi-select: Alt+A ticks all, Alt+N unticks all (before Alt+A sends and Alt+N switches tabs)
@@ -1328,7 +1513,8 @@ export class UI {
1328
1513
  // and not in a menu or a mid-task yes/no question, where Space types a space as usual)
1329
1514
  if (key.name === 'space' && !this.rl.line && !this.menu.pick && !(this.asking && !this.histOn) && this.voiceReady()) return this.#action('voice', write)
1330
1515
  if (!this.asking && !(key.ctrl && key.name === 'c')) return this.#typeAhead(s, key, write)
1331
- if (key.name === 'tab' && key.shift) return this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === this.permission) + 1) % PERMISSIONS.length][0])
1516
+ // Shift+Tab: the mode at the prompt only; never while a question is open (between questions: the one before)
1517
+ if (key.name === 'tab' && key.shift && !this.menu.pick?.nav) return this.histOn ? this.cyclePermission() : undefined
1332
1518
  // A new line instead of sending: Shift/Ctrl/Alt/Cmd+Enter (arrive as "\n" or ESC+Enter),
1333
1519
  // Ctrl+J, "\" right before Enter, and line breaks inside a paste.
1334
1520
  if (key.name === 'paste-start' || key.name === 'paste-end') {
@@ -1361,6 +1547,7 @@ export class UI {
1361
1547
  const twice = key.sequence === '\x1b\x1b' || Date.now() - (this.lastEscape ?? 0) < 800 // a lone Esc also comes with meta set
1362
1548
  this.lastEscape = twice ? 0 : Date.now()
1363
1549
  if (twice) {
1550
+ this.remember(rl.line) // wiped, not lost: ↑ brings it back
1364
1551
  this.clearInput()
1365
1552
  return this.refreshMenu()
1366
1553
  }
@@ -1378,6 +1565,25 @@ export class UI {
1378
1565
  return
1379
1566
  }
1380
1567
  if (m.pick) {
1568
+ // an answer of their own (ask_user's "Something else"): what's typed goes into it, right there
1569
+ const own = m.pick.items.find((x) => x.own)
1570
+ const onOwn = own && it?.item === own
1571
+ const typing = own && !key.ctrl && !key.meta && ((key.name === 'backspace' && onOwn) || (/^[^\x00-\x1f\x7f]+$/.test(s ?? '') && !(key.name === 'space' && m.pick.multi && !onOwn)))
1572
+ if (typing) {
1573
+ own.hint ??= own.text ? 'type your own answer' : own.desc // what it says before anything's typed
1574
+ own.text = key.name === 'backspace' ? (own.text ?? '').slice(0, -1) : (own.text ?? '') + s
1575
+ own.desc = own.text ? `› ${own.text}▏` : own.hint
1576
+ if (m.pick.multi) own.checked = Boolean(own.text)
1577
+ m.sel = m.items.findIndex((x) => x.item === own)
1578
+ return this.refreshMenu()
1579
+ }
1580
+ if (onOwn && own.text && (key.name === 'left' || key.name === 'right')) return // typing: not to another question (Tab still goes)
1581
+ if (onOwn && key.name === 'return' && !own.text?.trim() && !m.pick.multi) return // nothing typed yet: type it here
1582
+ // between questions (ask_user with several): what's ticked stays ticked
1583
+ if (m.pick.nav && !rl.line && (key.name === 'left' || key.name === 'right' || key.name === 'tab')) {
1584
+ m.pick.chosen = { nav: key.name === 'left' || (key.name === 'tab' && key.shift) ? -1 : 1 }
1585
+ return write('\r', { name: 'return' })
1586
+ }
1381
1587
  if (key.name === 'up' || key.name === 'down') return this.#move(key.name === 'up' ? -1 : 1)
1382
1588
  if (key.name === 'tab') return
1383
1589
  if (m.pick.multi && key.name === 'space' && it && !it.item.only) {
@@ -1392,6 +1598,7 @@ export class UI {
1392
1598
  return write('\r', { name: 'return' })
1393
1599
  }
1394
1600
  if (key.name === 'return') return // nothing matches the filter
1601
+ if (!own && this.#cards(m.pick)) return // cards have no filter: typing into one nobody sees would hide them all
1395
1602
  write(s, key)
1396
1603
  return this.refreshMenu()
1397
1604
  }
@@ -1451,7 +1658,7 @@ export class UI {
1451
1658
  if (m.on) return (m.off = rl.line), this.#suggestWhileWorking() // first Esc just closes the suggestions
1452
1659
  return this.escStop()
1453
1660
  }
1454
- if (key.name === 'tab' && key.shift) return this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === this.permission) + 1) % PERMISSIONS.length][0])
1661
+ if (key.name === 'tab' && key.shift) return this.cyclePermission()
1455
1662
  if (key.name === 'pageup' || key.name === 'pagedown') return this.scrollBy(key.name === 'pageup' ? this.page() : -this.page())
1456
1663
  if (it && (key.name === 'up' || key.name === 'down')) {
1457
1664
  m.sel = (m.sel + (key.name === 'up' ? m.items.length - 1 : 1)) % m.items.length
@@ -1513,7 +1720,7 @@ export class UI {
1513
1720
  case 'stop':
1514
1721
  return this.asking ? undefined : this.onEscape?.()
1515
1722
  case 'cycle_permissions':
1516
- return this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === this.permission) + 1) % PERMISSIONS.length][0])
1723
+ return this.asking && !this.histOn ? undefined : this.cyclePermission() // not while a question is open
1517
1724
  case 'newline':
1518
1725
  rl.line = rl.line.slice(0, rl.cursor) + '\n' + rl.line.slice(rl.cursor)
1519
1726
  rl.cursor++
@@ -1734,7 +1941,9 @@ export class UI {
1734
1941
  const w = Math.min(Math.max(0, ...shown.filter((x) => !x.header).map((x) => x.value.length)), 48)
1735
1942
  const lines = shown.map((x, i) => {
1736
1943
  if (x.header) return c.accent(c.bold(x.value.slice(0, width)))
1737
- const plain = `${x.value.padEnd(w)} ${x.desc ?? ''}`.slice(0, width - 2 - pad.length)
1944
+ const full = `${x.value.padEnd(w)} ${x.desc ?? ''}`.trimEnd()
1945
+ const room = width - 2 - pad.length
1946
+ const plain = full.length > room ? `${full.slice(0, room - 1)}…` : full // cut: said so
1738
1947
  const name = plain.slice(0, w)
1739
1948
  if (first + i !== m.sel) return `${pad} ${c.text(name)}${c.faint(plain.slice(w))}`
1740
1949
  const row = `${c.brand('❯')} ${c.bright(c.bold(name))}${c.muted(plain.slice(w))}`
@@ -1824,13 +2033,14 @@ export class UI {
1824
2033
 
1825
2034
  // history: this prompt's messages go into ↑/↓ history (only the main prompt, never answers like keys).
1826
2035
  // One question on screen at a time: a command run beside a task (onNow) and the task can both ask.
2036
+ // A question also waits for voice being recorded to end (its words go where they were going).
1827
2037
  async #free() {
1828
- while (this.full && this.asking) await new Promise((r) => this.freed.push(r))
2038
+ while ((this.full && this.asking) || this.recording) await new Promise((r) => (this.recording ? setTimeout(r, 200) : this.freed.push(r)))
1829
2039
  }
1830
2040
 
1831
2041
  ask(prompt, { initial = '', suggest = false, history = false } = {}) {
1832
2042
  if (this.dialog && !history) this.setDialog(null) // a question (a permission, a picker) needs you: the dialog makes way
1833
- if (this.full && this.asking) return this.#free().then(() => this.ask(prompt, { initial, suggest, history }))
2043
+ if (this.full && (this.asking || (this.recording && !history))) return this.#free().then(() => this.ask(prompt, { initial, suggest, history }))
1834
2044
  if (history && this.kept) [initial, this.kept] = [initial || this.kept, ''] // typed before a submit()
1835
2045
  this.stopSpin()
1836
2046
  const rl = this.#rl()
@@ -1849,6 +2059,8 @@ export class UI {
1849
2059
  }
1850
2060
  // a question in the middle of work: what's being typed for later waits until it's answered
1851
2061
  const draft = !history && rl.line ? [rl.line, (rl.line = ''), (rl.cursor = 0)][0] : ''
2062
+ // piped input: its lines are messages, not answers; nobody's there to answer
2063
+ if (!history && !rl.terminal) return this.write(prompt + c.dim('(no answer: the input is not a terminal)') + '\n'), Promise.resolve(null)
1852
2064
  if (this.queue.length) {
1853
2065
  const l = this.queue.shift()
1854
2066
  log('input', `${prompt.trim()} ${/api key/i.test(prompt) && l ? `${l.slice(0, 4)}…(${l.length} chars)` : l}`) // never log keys
@@ -1889,11 +2101,12 @@ export class UI {
1889
2101
  const pick = this.menu.pick
1890
2102
  const echo = prompt.replace(/^ /, '') // the input's margin isn't part of the conversation
1891
2103
  this.inputMark = this.log.length - 1 // where this message starts, for /rewind
1892
- const picked = Array.isArray(pick?.chosen) ? pick.chosen.map((x) => x.label).join(', ') : pick?.chosen?.label
2104
+ const said = (x) => (x.own && x.text?.trim() ? x.text.trim() : x.label) // their own answer: what they typed
2105
+ const picked = Array.isArray(pick?.chosen) ? pick.chosen.map(said).join(', ') : pick?.chosen && said(pick.chosen)
1893
2106
  if (pick?.quiet) this.render()
1894
- else if (pick) this.write(echo + (picked ?? c.dim(pick.closedAs ?? 'cancelled')) + (pick.auto?.fired ? c.dim(` · no answer in ${pick.auto.secs}s: the recommended one`) : '') + '\n')
2107
+ 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')
1895
2108
  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)
1896
- else if (l !== null) this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n')
2109
+ else if (l?.trim()) this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n')
1897
2110
  else this.render()
1898
2111
  }
1899
2112
  if (draft) [rl.line, rl.cursor] = [draft, draft.length]
@@ -1914,18 +2127,22 @@ export class UI {
1914
2127
  // multi: tick several with Space; returns the ticked items (an array), or null.
1915
2128
  // quiet: the question and answer aren't left in the conversation (a question before it starts).
1916
2129
  // fixed: a dialog: no typing to filter, no other keys meanwhile.
2130
+ // ctrlC: Ctrl+C closes it too, like Esc (not the first half of quitting).
1917
2131
  // auto: { item, secs }: nobody answers for secs seconds (each key starts the wait again) → item is chosen.
1918
- async pick(title, items, { filter = '', multi = false, quiet = false, fixed = false, body = '', auto = null } = {}) {
2132
+ // tabs: a row of tabs above it (several questions); nav: ←/→ (Tab, Shift+Tab) close it with { nav: -1 | 1 }.
2133
+ async pick(title, items, { filter = '', multi = false, quiet = false, fixed = false, body = '', auto = null, tabs = '', nav = false, ctrlC = false } = {}) {
1919
2134
  if (!this.full) {
1920
2135
  items.forEach((it, i) => this.print(` ${i + 1}. ${it.group ? `${it.group} · ` : ''}${it.label}${it.desc ? ' ' + c.dim(it.desc) : ''}`))
1921
2136
  const a = await this.ask(`${title} ${c.dim(multi ? '(numbers, like 1,3)' : '(number)')}: `)
2137
+ 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)
2138
+ if (this.autoPicked) return multi ? [auto.item] : auto.item
1922
2139
  if (!multi) return items[Number(a) - 1] ?? null
1923
2140
  const chosen = String(a ?? '').split(/[\s,]+/).map((n) => items[Number(n) - 1]).filter(Boolean)
1924
2141
  return chosen.length ? chosen : null
1925
2142
  }
1926
2143
  await this.#free()
1927
2144
  if (multi) for (const it of items) if (!it.only) it.checked ??= false
1928
- this.menu.pick = { items, chosen: null, multi, quiet, fixed, body, auto: auto && { ...auto } }
2145
+ this.menu.pick = { items, chosen: null, multi, quiet, fixed, body, tabs, nav, ctrlC, auto: auto && { ...auto } }
1929
2146
  this.autoPicked = false // chosen for the user (nobody answered in time), for the caller to say so
1930
2147
  if (auto) {
1931
2148
  this.#armAuto()
@@ -1949,8 +2166,11 @@ export class UI {
1949
2166
  a.timer = setTimeout(() => {
1950
2167
  const pick = this.menu.pick
1951
2168
  if (pick?.auto !== a) return
1952
- a.fired = this.autoPicked = true
1953
- pick.chosen = pick.multi ? [a.item] : a.item
2169
+ if (this.out.hidden) return this.#armAuto() // a tab in the background: you haven't seen it yet
2170
+ const ticked = pick.items.filter((x) => x.checked)
2171
+ const typed = pick.items.find((x) => x.own && x.text?.trim()) // their own answer, typed but not sent
2172
+ a.fired = this.autoPicked = (pick.multi ? ticked.length : typed) ? 'theirs' : true
2173
+ pick.chosen = pick.multi ? (ticked.length ? ticked : [a.item]) : (typed ?? a.item)
1954
2174
  this.rl.line = ''
1955
2175
  this.rl.cursor = 0
1956
2176
  this.ttyWrite('\r', { name: 'return' })
@@ -1958,19 +2178,41 @@ export class UI {
1958
2178
  this.render()
1959
2179
  }
1960
2180
 
2181
+ // A tab comes on screen: its question's wait starts now.
2182
+ resumeAuto() {
2183
+ if (this.menu.pick?.auto) this.#armAuto()
2184
+ }
2185
+
1961
2186
  autoHint() {
1962
2187
  const a = this.menu.pick?.auto
1963
2188
  return a ? ` · recommended in ${Math.max(0, Math.ceil((a.until - Date.now()) / 1000))}s` : ''
1964
2189
  }
1965
2190
 
2191
+ // A pick that chooses by itself (auto): how long until it does, and what it will do then.
2192
+ autoLine() {
2193
+ const pick = this.menu.pick
2194
+ const a = pick?.auto
2195
+ if (!a) return ''
2196
+ const theirs = pick.items.some((x) => x.checked || (x.own && x.text?.trim())) // ticked or typed: that's what goes
2197
+ 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`
2198
+ }
2199
+
1966
2200
  setPermission(mode) {
1967
2201
  log('permissions', mode)
1968
2202
  if (mode === 'plan' && this.permission !== 'plan') this.beforePlan = this.permission // what plan mode asks like, and goes back to
2203
+ this.leftPlan = null
1969
2204
  this.permission = mode
1970
2205
  this.onPermission?.(mode)
1971
2206
  this.render()
1972
2207
  }
1973
2208
 
2209
+ // Shift+Tab: the next mode; plan goes back to the mode before it, and the next press goes on after plan.
2210
+ cyclePermission() {
2211
+ if (this.permission === 'plan' && this.beforePlan && this.beforePlan !== 'plan') return this.setPermission(this.beforePlan), (this.leftPlan = this.beforePlan)
2212
+ const at = this.leftPlan === this.permission ? 'plan' : this.permission
2213
+ this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === at) + 1) % PERMISSIONS.length][0])
2214
+ }
2215
+
1974
2216
  // kind: 'edit', 'command' or 'read'. true = yes, false = no, string = "no, and here is why"
1975
2217
  // kind 'read' (web search and fetch): asked like a command, but never in plan mode, which is for
1976
2218
  // looking around. Otherwise plan mode asks as the mode before it did (only reading tools get here).
@@ -1987,6 +2229,7 @@ export class UI {
1987
2229
  }
1988
2230
  }
1989
2231
  const a = await this.ask(`${c.yellow('?')} ${question} ${c.dim('[Y/n or type feedback]')} `)
2232
+ 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.`
1990
2233
  if (a === null) return false
1991
2234
  const t = a.trim()
1992
2235
  if (/^(y|yes)?$/i.test(t)) return true
@@ -1998,12 +2241,13 @@ export class UI {
1998
2241
  { label: 'Yes', value: true },
1999
2242
  { label: "Yes, and don't ask again", value: 'all' },
2000
2243
  { label: 'No', value: false },
2001
- { label: 'No, and tell the model what to do instead', value: 'why' },
2244
+ { 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"
2002
2245
  ]
2003
- const a = (await this.pick(`${c.yellow('?')} ${question}`, opts))?.value ?? false
2004
- if (a === 'all') this.setPermission('all')
2246
+ const got = await this.pick(`${c.yellow('?')} ${question}`, opts)
2247
+ const a = got?.value ?? false
2248
+ if (a === 'all') this.permission === 'plan' ? (this.beforePlan = 'all') : this.setPermission('all') // plan mode stays: it goes on to 'all' afterwards
2005
2249
  if (a !== 'why') return Boolean(a)
2006
- return (await this.ask(`${c.bold('What should it do instead?')} `))?.trim() || false
2250
+ return got.text?.trim() || false
2007
2251
  }
2008
2252
 
2009
2253
  write(s) {
@@ -2041,7 +2285,7 @@ export class UI {
2041
2285
  Object.assign(this, { tail: m.tail, sgr: m.sgr })
2042
2286
  const lines = text ? text.split('\n') : []
2043
2287
  if (lines.length === 1 || (lines.length && this.dialog)) this.notice(lines[0], 4000, '›')
2044
- else if (lines.length) this.showText(title, text)
2288
+ else if (lines.length) this.showText(title === '/toggle_thinking' ? 'Thinking' : title, text, title) // its key (Alt+O) closes it again
2045
2289
  else this.render()
2046
2290
  }
2047
2291
  // A blank line before a new block, unless there already is one.
@@ -2066,6 +2310,7 @@ export class UI {
2066
2310
 
2067
2311
  spinner(label) {
2068
2312
  this.label = label
2313
+ if (this.requestSince?.()) this.tokenAt = Date.now() // changed during a request: something came (a tool call being written)
2069
2314
  if (!this.out.isTTY || this.timer) return
2070
2315
  let i = 0
2071
2316
  const tick = () => {
@@ -2091,10 +2336,12 @@ export class UI {
2091
2336
  }
2092
2337
  this.beforeRetry ??= typeof this.label === 'function' ? 'thinking' : this.label || 'thinking'
2093
2338
  const until = Date.now() + ms
2094
- const why = shortError(err)
2339
+ // why first, short: "cannot reach http://127.0.0.1:47329/v1/chat/completions (ECONNREFUSED)" → "can't reach 127.0.0.1:47329"
2340
+ let why = shortError(err).replace(/^cannot reach (\S+)(?: \([^)]*\))?/, (m, u) => `can't reach ${URL.canParse(u) ? new URL(u).host : u}`)
2341
+ if (why.length > 50) why = `${why.slice(0, 49)}…`
2095
2342
  const left = () => Math.max(0, Math.ceil((until - Date.now()) / 1000)) * 1000
2096
- if (next) return this.spinner(() => `${c.yellow('⚠')} ${why} · trying ${next.provider} · ${next.model}${left() ? ` in ${duration(left())} (all failed once)` : ''} (attempt ${attempt})`)
2097
- this.spinner(() => `${c.yellow('⚠')} retrying in ${duration(left())} (attempt ${attempt}) · ${why}`)
2343
+ if (next) return this.spinner(() => `${c.yellow('⚠')} ${why} · trying ${next.provider} · ${next.model}${left() ? ` in ${short(left())} (all failed once)` : ''} (try ${attempt})`)
2344
+ this.spinner(() => `${c.yellow('⚠')} ${why} · retrying in ${short(left())} (try ${attempt})`)
2098
2345
  }
2099
2346
 
2100
2347
  stopSpin() {