heartcode 0.1.30 → 0.1.33

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/tools.js CHANGED
@@ -17,6 +17,7 @@ import { runHooks } from './hooks.js'
17
17
  import { parsePatch, applyChunks } from './patch.js'
18
18
  import { formatFile } from './format.js'
19
19
  import { diagnose, lspTool, findCommand } from './lsp.js'
20
+ import { startJob, newOutput, listJobs, getJob, stopJob, jobLine } from './background.js'
20
21
 
21
22
  const IGNORE = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'coverage', '.venv', 'venv', '__pycache__', 'target', '.cache', '.DS_Store'])
22
23
 
@@ -271,7 +272,7 @@ export function runCommand(root, cmd, { signal, timeout = 120_000, stdin, env, s
271
272
  clearTimeout(timer)
272
273
  signal?.removeEventListener('abort', stop)
273
274
  if (kill(0) && code !== 'interrupted' && code !== 'timeout') {
274
- note += '\n(Processes this command left running in the background were stopped: run_command cannot keep a server running.)'
275
+ note += '\n(Processes this command left running in the background were stopped. To keep a server or watcher running, run it with background: true.)'
275
276
  }
276
277
  kill('SIGTERM')
277
278
  setTimeout(() => kill('SIGKILL'), 2000).unref()
@@ -396,8 +397,8 @@ export function searchesOutside(cmd, root) {
396
397
  })
397
398
  }
398
399
 
399
- export async function runConfirmed(s, cmd, signal) {
400
- s.ui.step('run', cmd)
400
+ export async function runConfirmed(s, cmd, signal, background = false) {
401
+ s.ui.step(background ? 'run in background' : 'run', cmd)
401
402
  if (s.ui.permission === 'plan' && !readOnlyCommand(cmd)) {
402
403
  s.ui.result('not run: plan mode')
403
404
  return prompt('agent/plan-refused-command')
@@ -409,6 +410,11 @@ export async function runConfirmed(s, cmd, signal) {
409
410
  }
410
411
  const ok = s.ui.permission === 'plan' ? true : await s.ui.confirm(`Run ${c.bold(cmd)}?`, 'command') // plan mode: only read-only ones get here
411
412
  if (ok !== true) return `The user declined to run this command.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
413
+ if (background) {
414
+ const { job, output } = await startJob(s.root, cmd)
415
+ s.ui.result(job.exited ? `exited with ${job.code}` : `running in the background as #${job.id}`)
416
+ return prompt('agent/background-started', { id: job.id, running: !job.exited, code: job.code, output: output.trim() || '(nothing yet)', file: job.file })
417
+ }
412
418
  const before = snapshot(s)
413
419
  s.ui.spinner(`running ${cmd}`)
414
420
  const t0 = Date.now()
@@ -421,6 +427,22 @@ export async function runConfirmed(s, cmd, signal) {
421
427
  return `exit code ${code}\n${tail(output, 4000) || '(no output)'}${changed ? `\nFiles this command changed: ${changed}` : ''}${why}`
422
428
  }
423
429
 
430
+ // The background tool: what a command started with background: true printed since the last look,
431
+ // the list of them, or stop one.
432
+ function backgroundTool(s, a) {
433
+ const mine = listJobs(s.root)
434
+ if (a.action === 'list') return mine.length ? mine.map(jobLine).join('\n') : 'No background commands.'
435
+ const job = getJob(a.id ?? mine.at(-1)?.id)
436
+ if (!job || job.root !== s.root) return `error: no background command #${a.id}. ${mine.length ? `They are: ${mine.map((j) => `#${j.id} ${j.command}`).join(', ')}` : 'None are running.'}`
437
+ if (a.action === 'stop') {
438
+ const was = stopJob(job)
439
+ s.ui.result(was ? `stopped #${job.id}` : `#${job.id} had already exited`)
440
+ return was ? `Stopped #${job.id} (${job.command}).` : `#${job.id} had already exited with ${job.code}.`
441
+ }
442
+ const out = newOutput(job)
443
+ return `${jobLine(job)}\n${out.trim() ? `New output since the last look:\n${out}` : '(no new output since the last look)'}`
444
+ }
445
+
424
446
  // Files a shell command changes are tracked like HeartCode's own edits: shown as diffs, kept for
425
447
  // /rewind, and told to the model. Text files up to 256 KB, read only when they changed since the
426
448
  // last look (the contents are cached per session).
@@ -497,7 +519,8 @@ export const TOOL_DEFS = [
497
519
  // One edit per call: a list of edits per call measured 2–6 malformed calls per benchmark run vs 0.
498
520
  { name: 'edit_file', description: prompt('agent/tool-edit_file'), parameters: obj({ path: str, search: str, replace: str, start_line: int, end_line: int }, ['path', 'replace']) },
499
521
  { name: 'write_file', description: prompt('agent/tool-write_file'), parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
500
- { name: 'run_command', description: prompt('agent/tool-run_command'), parameters: obj({ command: str }, ['command']) },
522
+ { name: 'run_command', description: prompt('agent/tool-run_command'), parameters: obj({ command: str, background: { type: 'boolean' } }, ['command']) },
523
+ { name: 'background', description: prompt('agent/tool-background'), parameters: obj({ action: { type: 'string', enum: ['output', 'list', 'stop'] }, id: int }, ['action']) },
501
524
  { name: 'todo', description: prompt('agent/tool-todo'), parameters: obj({ todos: { type: 'array', items: obj({ content: str, status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] } }, ['content', 'status']) } }, ['todos']) },
502
525
  { name: 'web_search', description: prompt('agent/tool-web_search'), parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
503
526
  { name: 'web_fetch', description: prompt('agent/tool-web_fetch'), parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
@@ -1159,7 +1182,9 @@ async function tool(name, args, s, signal, id) {
1159
1182
  }
1160
1183
  case 'run_command':
1161
1184
  if (/^\s*apply_patch\b[\s\S]*\*\*\* Begin Patch/.test(String(args.command ?? ''))) return await applyPatch(s, args.command) // apply_patch <<'EOF' … as Codex runs it
1162
- return (await runConfirmed(s, String(args.command ?? ''), signal)) + outsideNote(root, String(args.command ?? ''))
1185
+ return (await runConfirmed(s, String(args.command ?? ''), signal, args.background === true || args.background === 'true')) + outsideNote(root, String(args.command ?? ''))
1186
+ case 'background':
1187
+ return backgroundTool(s, args)
1163
1188
  case 'apply_patch':
1164
1189
  return await applyPatch(s, args.input ?? args.patch ?? args.command ?? '')
1165
1190
  case 'mcp':
package/src/ui.js CHANGED
@@ -118,7 +118,7 @@ export const keyId = (key, s = '') => CONTROL_KEYS[key.sequence ?? s] ?? [key.ct
118
118
  // next one). /voice records (Space in an empty box, or a key in keybindings.json); Alt+T, Alt+W,
119
119
  // Alt+N/P (or Ctrl+PgDn/PgUp), Alt+1…9: tabs; Shift+↑↓ and Alt+↑↓ scroll the conversation (as
120
120
  // PgUp/PgDn and the mouse wheel do). keybindings.json can move any of them.
121
- export const DEFAULT_KEYS = { '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+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}`])) }
121
+ 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+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}`])) }
122
122
  export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
123
123
  let raw = {}
124
124
  try {
@@ -646,6 +646,7 @@ export class UI {
646
646
  this.isCommand = (l) => l.startsWith('/') // the app's: only real commands (a path like /Users/… is a message)
647
647
  this.keys = { ...DEFAULT_KEYS, ...loadKeys() }
648
648
  this.waiters = []
649
+ this.freed = [] // asks waiting for the one on screen (a command's picker beside a task's question)
649
650
  this.closed = false
650
651
  this.rl = null
651
652
  this.onInterrupt = null
@@ -663,6 +664,157 @@ export class UI {
663
664
  this.scroll = 0
664
665
  this.asking = false
665
666
  this.frame = 0
667
+ this.dialog = null // a box over the screen (the background commands' logs)
668
+ }
669
+
670
+ // A dialog: a box in the middle, 70% of the screen each way, the conversation going on around it;
671
+ // drawn again twice a second while it's open. { title, draw(w, h) → lines, key?(key), click?(col, row),
672
+ // close?(), toggle?: the key action that closes it too }. While it's open every key is its own (Ctrl+C
673
+ // aside); Esc, or a click outside it, closes it.
674
+ setDialog(dialog) {
675
+ const was = this.dialog
676
+ this.dialog = dialog
677
+ clearInterval(this.dialogTimer)
678
+ this.dialogTimer = dialog ? setInterval(() => this.render(), 500) : null
679
+ this.dialogTimer?.unref()
680
+ if (was && was !== dialog) was.close?.()
681
+ this.render()
682
+ }
683
+ // Text to read (a command's answer: /help, /context, /diff…) in a dialog: ↑/↓, PgUp/PgDn, Home/End
684
+ // and the wheel scroll it, Esc closes it. Without the full screen: printed.
685
+ showText(title, text) {
686
+ if (!this.full) return this.print(text)
687
+ const all = String(text).split('\n')
688
+ let top = 0
689
+ let page = 10
690
+ let total = 0
691
+ this.setDialog({
692
+ title,
693
+ key: (key) => {
694
+ const by = { up: key.wheel ? -3 : -1, down: key.wheel ? 3 : 1, pageup: -page, pagedown: page, home: -1e9, end: 1e9 }[key.name]
695
+ if (by) top = Math.max(0, Math.min(top + by, total - page))
696
+ },
697
+ draw: (w, h) => {
698
+ const rows = all.flatMap((l) => wrapAnsi(l, w))
699
+ total = rows.length
700
+ page = h - 2
701
+ top = Math.max(0, Math.min(top, total - page))
702
+ const shown = rows.slice(top, top + page)
703
+ const where = total > page ? `${top + 1}–${Math.min(total, top + page)} of ${total} lines · ↑/↓ PgUp/PgDn scroll · ` : ''
704
+ return [...shown, '', c.faint(`${where}Esc close`)]
705
+ },
706
+ })
707
+ }
708
+
709
+ // where it is: { x, y, w, h } (screen cells, from 0; the inside, without the border)
710
+ #dialogBox(cols, rows) {
711
+ const w = Math.max(30, Math.floor(cols * 0.7))
712
+ const h = Math.max(8, Math.floor(rows * 0.7))
713
+ 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 }
714
+ }
715
+ // d: { title, lines(w, h) → lines (at most h), fill?: always 70% tall too (a log), cursor?(w) →
716
+ // { row, col } in the lines (else hidden) }. The box is 70% of the screen wide, as tall as what's in
717
+ // it (70% at most), in the middle, with a margin inside.
718
+ #drawDialog(cols, rows, d) {
719
+ const PX = 2 // the margin inside: columns each side
720
+ const PY = 1 // and rows above and below
721
+ const max = this.#dialogBox(cols, rows)
722
+ const name = String(d.title ?? '')
723
+ const iwMax = max.w - 2 * PX
724
+ const w = iwMax
725
+ const lines = d.lines(w, max.h - 2 * PY).slice(0, max.h - 2 * PY)
726
+ const h = d.fill ? max.h - 2 * PY : lines.length
727
+ const W = w + 2 * PX
728
+ const x = Math.floor((cols - W - 2) / 2) + 1
729
+ const y = Math.floor((rows - h - 2 * PY - 2) / 2) + 1
730
+ this.dialogAt = { x, y, W, H: h + 2 * PY, cx: x + 1 + PX, cy: y + 1 + PY } // for the mouse (screen cells, from 1)
731
+ const paint = (t) => (background ? `${background}${t.replace(/\x1b\[(0|49)?m/g, (m) => m + background)}\x1b[0m` : `${t}\x1b[0m`)
732
+ const pad = (t, n) => {
733
+ const cut = fit(t, n)
734
+ return cut + ' '.repeat(Math.max(0, n - width(cut.replace(/\x1b\[[0-9;]*m/g, ''))))
735
+ }
736
+ const title = name ? ` ${width(name) > W - 6 ? `${fit(name, W - 7)}…` : name} ` : '' // too long: cut (a question shows all of it inside)
737
+ const row = (i, t) => `\x1b[${y + i};${x}H${paint(t)}`
738
+ let out = row(0, c.brand('╭─') + c.bold(title) + c.brand('─'.repeat(Math.max(0, W - width(title) - 1)) + '╮'))
739
+ const blank = c.brand('│') + ' '.repeat(W) + c.brand('│')
740
+ for (let i = 0; i < PY; i++) out += row(1 + i, blank)
741
+ for (let i = 0; i < h; i++) out += row(1 + PY + i, c.brand('│') + ' '.repeat(PX) + pad(lines[i] ?? '', w) + ' '.repeat(PX) + c.brand('│'))
742
+ // what's in it can be selected (copied), all but its last line (the keys)
743
+ const last = lines.findLastIndex((l) => String(l ?? '').trim())
744
+ for (let i = 0; i < Math.min(h, last); i++) this.regions.set(y + 1 + PY + i, { x: x + 1 + PX, text: fit(lines[i] ?? '', w).replace(/\x1b\[[0-9;]*m/g, '').trimEnd() })
745
+ for (let i = 0; i < PY; i++) out += row(1 + PY + h + i, blank)
746
+ out += row(2 + 2 * PY + h - 1, c.brand('╰' + '─'.repeat(W) + '╯'))
747
+ const cur = d.cursor?.(w)
748
+ return [out, cur ? `\x1b[${y + 1 + PY + cur.row};${x + 1 + PX + Math.min(cur.col, w - 1)}H\x1b[?25h` : '\x1b[?25l']
749
+ }
750
+
751
+ // The question being asked, as a dialog: its title; what's typed (the filter, or the answer) with the
752
+ // cursor; a picker's choices. A short list (a few, one to choose) is shown as cards: the name, its
753
+ // description under it. A permission (confirm) shows what just happened (the change or command it
754
+ // asks about) above the choices. A picker's body (pick's option): a few lines saying what's going on.
755
+ #question() {
756
+ const rl = this.rl
757
+ const m = this.menu
758
+ const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
759
+ const title = plain(rl._prompt).replace(/\s*›?\s*$/, '').replace(/:\s*$/, '').trim()
760
+ const field = (w) => {
761
+ const pre = '› '
762
+ const room = w - pre.length - 1
763
+ const from = Math.max(0, rl.cursor - room)
764
+ return { text: c.brand(pre) + c.bright(rl.line.slice(from, from + room)), col: pre.length + rl.cursor - from }
765
+ }
766
+ const padTo = (t, n) => t + ' '.repeat(Math.max(0, n - width(plain(t))))
767
+ const pick = m.pick
768
+ const choices = pick ? m.items.filter((x) => !x.header) : []
769
+ const cards = pick && !pick.multi && pick.items.length <= 6 && !m.items.some((x) => x.header)
770
+ const body = pick?.body ? String(pick.body).split('\n') : []
771
+ 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'
772
+ let at = 0
773
+ const long = (w) => width(title) > w // too long for the border: all of it inside too
774
+ return {
775
+ title: title.length > 200 ? title.slice(0, 200) : title,
776
+ cursor: (w) => (pick?.fixed || (cards && pick) ? null : { row: at, col: field(w).col }),
777
+ lines: (w, h) => {
778
+ const head = long(w) ? [...wrapAnsi(c.bold(title), w).map((l) => l), ''] : []
779
+ const text = body.flatMap((l) => wrapAnsi(/^https?:\/\/\S+$/.test(l.trim()) ? c.info(l) : c.muted(l), w)) // an address in its link color
780
+ const intro = [...head, ...text, ...(text.length ? [''] : [])]
781
+ if (!pick) {
782
+ const recent = this.askAbout ? this.#recent(w, Math.min(8, h - intro.length - 5)) : []
783
+ const top = [...recent, ...(recent.length ? [c.ghost('─'.repeat(w)), ''] : []), ...intro]
784
+ at = top.length
785
+ return [...top, field(w).text, '', c.faint(hint)]
786
+ }
787
+ let list
788
+ if (cards) {
789
+ list = choices.length
790
+ ? choices.flatMap((x, i) => {
791
+ const on = m.items[m.sel] === x
792
+ const name = on ? `${c.brand('❯')} ${c.bright(c.bold(x.item.label))}` : ` ${c.text(x.item.label)}`
793
+ const desc = x.item.desc ? (on ? ` ${c.muted(x.item.desc)}` : ` ${c.faint(x.item.desc)}`) : null
794
+ const rows = [name, ...(desc ? [desc] : [])].map((r) => (on ? c.select(padTo(r, w)) : r))
795
+ return i < choices.length - 1 && choices.some((y) => y.item.desc) ? [...rows, ''] : rows // a gap between cards that have two lines
796
+ })
797
+ : [c.faint(`nothing matches "${rl.line}"`)]
798
+ }
799
+ const filter = pick.fixed || cards ? [] : [field(w).text, c.ghost('─'.repeat(w))]
800
+ const room = h - intro.length - filter.length - 2
801
+ 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}"`)]
802
+ const recent = this.askAbout ? this.#recent(w, Math.min(8, room - list.length - 1)) : []
803
+ const top = [...recent, ...(recent.length ? [c.ghost('─'.repeat(w)), ''] : []), ...intro]
804
+ at = top.length
805
+ return [...top, ...filter, ...list, '', c.faint(hint)]
806
+ },
807
+ }
808
+ }
809
+
810
+ // The last `n` rows of this task's output at width w (what a question in the middle of the work is about).
811
+ #recent(w, n) {
812
+ if (n <= 0) return []
813
+ const out = []
814
+ const from = Math.max(0, (this.inputMark ?? 0) + 1) // this task's: from after your message
815
+ for (let i = this.log.length - 1; i >= from && out.length < n; i--) out.unshift(...wrapAnsi(this.log[i], w))
816
+ while (out.length && !out[0].trim()) out.shift()
817
+ return out.slice(-n)
666
818
  }
667
819
 
668
820
  // One model reply: thinking (dim, its own block) kept apart from the answer.
@@ -767,16 +919,57 @@ export class UI {
767
919
 
768
920
  // The mouse: the wheel scrolls the conversation; dragging selects in it, copied when let go
769
921
  // (the terminal can't select itself while HeartCode takes the mouse). A click or a key clears it.
922
+ // The mouse: the wheel scrolls (a dialog's own text, else the conversation); dragging selects, copied
923
+ // when let go: in the conversation (it stays selected as it scrolls), in a dialog, the header's
924
+ // folder, the input box or the status bar; a double click copies the word under it (an address, a
925
+ // path, a model's name). The terminal can't select itself while HeartCode takes the mouse
926
+ // (Shift+drag, or Option+drag on macOS, still lets it). A click or a key clears a selection.
770
927
  #mouse(b, x, y, up) {
771
928
  if (!this.full) return
772
- if (b & 64) return (b & 0xc3) === 64 || (b & 0xc3) === 65 ? this.scrollBy(b & 1 ? -3 : 3) : undefined // 64 up, 65 down
929
+ const modal = Boolean(this.dialog || (this.asking && !this.histOn && this.rl))
930
+ if (b & 64) {
931
+ if ((b & 0xc3) !== 64 && (b & 0xc3) !== 65) return
932
+ if (this.dialog) return this.dialog.key?.({ name: b & 1 ? 'down' : 'up', wheel: true }), this.render()
933
+ return this.scrollBy(b & 1 ? -3 : 3) // 64 up, 65 down
934
+ }
773
935
  if ((b & 3) !== 0 && !up) return // the left button only (a release says 3 in some terminals)
774
- if (!(b & 32) && !up && y <= 3 && this.onTabClick) return this.onTabClick(x - 1) // the tab bar's 3 rows
936
+ const press = !(b & 32) && !up
937
+ if (press) {
938
+ const twice = this.lastClick && Date.now() - this.lastClick.t < 450 && this.lastClick.x === x && this.lastClick.y === y
939
+ this.lastClick = { t: Date.now(), x, y }
940
+ if (twice) return this.#copyWord(x, y)
941
+ this.sel = null
942
+ this.ssel = null
943
+ this.flash = null
944
+ const d = this.dialogAt
945
+ if (modal && d && (x < d.x || y < d.y || x > d.x + d.W + 1 || y > d.y + d.H + 1)) return this.dialog ? this.setDialog(null) : this.render() // outside a dialog: closed (a question stays)
946
+ if (!modal && y <= 3 && this.onTabClick) return this.onTabClick(x - 1) // the tab bar's 3 rows
947
+ if (modal || this.regions?.has(y)) {
948
+ // a dialog, the header, the input, the status bar: a screen selection (a click without a drag: the dialog's own)
949
+ this.ssel = { a: { x, y }, b: { x, y }, moved: false, rows: this.regions, inDialog: modal }
950
+ return this.render()
951
+ }
952
+ }
953
+ if (this.ssel) {
954
+ const sel = this.ssel
955
+ if (x !== sel.b.x || y !== sel.b.y) Object.assign(sel, { b: { x, y }, moved: true })
956
+ if (up) {
957
+ this.ssel = null
958
+ const text = sel.moved && this.#selectedRows(sel).map((r) => r.text.trimEnd()).join('\n').trim()
959
+ if (text) this.#copied(text)
960
+ else if (sel.inDialog && this.dialog && this.dialogAt) this.dialog.click?.(x - this.dialogAt.cx, y - this.dialogAt.cy)
961
+ else if (sel.inDialog) return this.render()
962
+ if (text) this.flash = sel // left lit a moment, so you see what was copied
963
+ if (text) setTimeout(() => this.flash === sel && ((this.flash = null), this.render()), 700).unref?.()
964
+ }
965
+ return this.render()
966
+ }
967
+ if (modal) return
775
968
  const v = this.viewAt
776
969
  if (!v) return
777
970
  const r = Math.min(Math.max(y - 1 - v.first, 0), v.avail - 1) // a drag past the edge stops at it
778
971
  const at = { row: v.top + Math.min(r, Math.max(0, v.count - 1)), col: x - 1 }
779
- if (!(b & 32) && !up) {
972
+ if (press) {
780
973
  // a press: starts a selection, inside the conversation only
781
974
  this.sel = y - 1 >= v.first && y - 1 < v.first + v.count ? { a: at, b: at, moved: false } : null
782
975
  return this.render()
@@ -786,10 +979,39 @@ export class UI {
786
979
  if (up) {
787
980
  const text = this.sel.moved && this.#selected()
788
981
  if (!text) this.sel = null
789
- else this.notice(`copied ${text.length} character${text.length === 1 ? '' : 's'}${copyText(text) === 'osc' ? ' (through the terminal)' : ''}`)
982
+ else this.#copied(text)
790
983
  }
791
984
  this.render()
792
985
  }
986
+ #copied(text) {
987
+ this.notice(`copied ${text.length} character${text.length === 1 ? '' : 's'}${copyText(text) === 'osc' ? ' (through the terminal)' : ''}`)
988
+ }
989
+ // A double click: the word under it (no spaces; quotes and brackets around it left out), copied.
990
+ #copyWord(x, y) {
991
+ this.sel = null
992
+ let row = this.regions?.get(y)
993
+ const v = this.viewAt
994
+ if (!row && v && !this.dialog && y - 1 >= v.first && y - 1 < v.first + v.count) row = { x: 1, text: (this.#rows(this.out.columns || 80)[v.top + y - 1 - v.first] ?? '').replace(/\x1b\[[0-9;]*m/g, '') }
995
+ if (!row) return
996
+ const cells = [] // [char, its column]
997
+ let col = row.x
998
+ for (const ch of row.text) cells.push([ch, col]), (col += width(ch))
999
+ const at = cells.findIndex(([, cx], i) => x >= cx && x < (cells[i + 1]?.[1] ?? cx + 1))
1000
+ if (at === -1 || /\s/.test(cells[at][0])) return
1001
+ let s = at
1002
+ let e = at
1003
+ while (s > 0 && !/\s/.test(cells[s - 1][0])) s--
1004
+ while (e < cells.length - 1 && !/\s/.test(cells[e + 1][0])) e++
1005
+ while (s < e && /["'`(\[{<]/.test(cells[s][0])) s++
1006
+ while (e > s && /["'`)\]}>,;:.!?]/.test(cells[e][0]) && !/^https?:\/\/\S+\/$/.test(cells.slice(s, e + 1).map((c) => c[0]).join(''))) e--
1007
+ let word = cells.slice(s, e + 1).map((c) => c[0]).join('')
1008
+ if (row.path && /[\\/~…]/.test(word)) word = row.path // the folder in the header: all of it, not what fits
1009
+ this.#copied(word)
1010
+ const sel = { a: { x: cells[s][1], y }, b: { x: cells[e][1], y }, rows: new Map([[y, row]]) }
1011
+ this.flash = sel
1012
+ setTimeout(() => this.flash === sel && ((this.flash = null), this.render()), 700).unref?.()
1013
+ this.render()
1014
+ }
793
1015
  #selRange() {
794
1016
  const { a, b } = this.sel
795
1017
  return a.row < b.row || (a.row === b.row && a.col <= b.col) ? [a, b] : [b, a]
@@ -880,9 +1102,12 @@ export class UI {
880
1102
  const { out, rl, menu } = this
881
1103
  const rows = out.rows || 24
882
1104
  const cols = out.columns || 80
1105
+ // A question (a picker, a permission, something to type) is a dialog over the screen; the input
1106
+ // box behind it stays as it was.
1107
+ const asked = this.asking && !this.histOn && rl
883
1108
  // The input box: the rows around the cursor, at most INPUT_ROWS; the rules count the rest.
884
1109
  const typing = !this.asking && rl && this.mainPrompt // working: what's typed meanwhile shows in the box
885
- const input = this.asking || typing ? layoutInput(this.asking ? rl._prompt : this.mainPrompt, rl.line, rl.cursor, cols) : { rows: [''], cur: { row: 0, col: 0 } }
1110
+ const input = asked ? layoutInput(this.mainPrompt ?? ' ', '', 0, cols) : this.asking || typing ? layoutInput(this.asking ? rl._prompt : this.mainPrompt, rl.line, rl.cursor, cols) : { rows: [''], cur: { row: 0, col: 0 } }
886
1111
  const first = Math.max(0, Math.min(input.cur.row - INPUT_ROWS + 1, input.rows.length - INPUT_ROWS))
887
1112
  const box = input.rows.slice(first, first + INPUT_ROWS)
888
1113
  const inputRows = box.length
@@ -908,7 +1133,7 @@ export class UI {
908
1133
  if (this.ahead.length > 5) bottom.push(c.faint(` … ${this.ahead.length - 5} more`))
909
1134
  }
910
1135
  if (this.noticeText) bottom.push(fit(`${c.warn('!')} ${c.muted(this.noticeText)}`, cols))
911
- if (menu.on) bottom.push(...this.#menuLines(cols))
1136
+ if (menu.on && !asked) bottom.push(...this.#menuLines(cols))
912
1137
  bottom.push(first ? note(first, '↑') : rule)
913
1138
  const head = [...(this.tabBar?.(cols) ?? []), ...(this.header?.(cols) ?? [])].map((l) => fit(l, cols))
914
1139
  const inputTop = rows - below.length - inputRows + 1 // first row of the input
@@ -923,8 +1148,13 @@ export class UI {
923
1148
  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)
924
1149
  }
925
1150
  // a theme with a background: every row painted with it (a style ending its own background goes back to it)
926
- const row = background ? (line) => `${background}${line.replace(/\x1b\[(0|49)?m/g, (m) => m + background)}\x1b[K\x1b[0m` : (line) => `${line}\x1b[0m\x1b[K`
1151
+ 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`
927
1152
  let s = '\x1b[?25l'
1153
+ // a dialog open: everything behind it dimmed
1154
+ if (this.dialog || asked) {
1155
+ const plainRow = row
1156
+ row = (line) => plainRow(`\x1b[2m${line.replace(/\x1b\[(0|22)?m/g, (m) => m + '\x1b[2m')}`)
1157
+ }
928
1158
  for (let r = 0; r < inputTop - 1; r++) {
929
1159
  const i = r - head.length
930
1160
  const line = i < 0 ? head[r] : i < avail ? (view[i] ?? '') : bottom[i - avail]
@@ -932,9 +1162,49 @@ export class UI {
932
1162
  }
933
1163
  box.forEach((line, i) => (s += `\x1b[${inputTop + i};1H${row(line)}`))
934
1164
  below.forEach((line, i) => (s += `\x1b[${inputTop + inputRows + i};1H${row(line)}`))
935
- if (this.asking || typing) s += `\x1b[${inputTop + input.cur.row - first};${input.cur.col + 1}H\x1b[?25h`
936
- else s += `\x1b[${inputTop};1H`
937
- out.write(s)
1165
+ // what can be selected besides the conversation (screen rows from 1): the header's first line (the
1166
+ // project's folder), the input box, the status bar; with a dialog open, only what's in it
1167
+ const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
1168
+ const tabRows = this.tabBar?.(cols)?.length ?? 0
1169
+ this.regions = new Map()
1170
+ if (this.header && head[tabRows] !== undefined) this.regions.set(tabRows + 1, { x: 1, text: plain(head[tabRows]), path: this.folder }) // path: the whole folder (shown cut when long)
1171
+ box.forEach((line, i) => this.regions.set(inputTop + i, { x: 1, text: plain(line) }))
1172
+ below.slice(1).forEach((line, i) => this.regions.set(inputTop + inputRows + 1 + i, { x: 1, text: plain(line) }))
1173
+ let cursor
1174
+ if (this.dialog || asked) {
1175
+ this.regions = new Map()
1176
+ 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())
1177
+ s += box
1178
+ cursor = cur // a question: its cursor in the box; else hidden
1179
+ } else {
1180
+ this.dialogAt = null
1181
+ cursor = this.asking || typing ? `\x1b[${inputTop + input.cur.row - first};${input.cur.col + 1}H\x1b[?25h` : `\x1b[${inputTop};1H`
1182
+ }
1183
+ out.write(s + this.#screenSelection() + cursor)
1184
+ }
1185
+
1186
+ // A selection outside the conversation (in a dialog, the header, the input, the status bar), or a
1187
+ // word just double-clicked: drawn reversed over what's there.
1188
+ #screenSelection() {
1189
+ const sel = this.ssel ?? this.flash
1190
+ if (!sel) return ''
1191
+ let out = ''
1192
+ for (const { y, x, text } of this.#selectedRows(sel)) out += `\x1b[${y};${x}H\x1b[7m${text}\x1b[27m`
1193
+ return out
1194
+ }
1195
+ // The rows a screen selection covers: [{ y, x, text }] (x: where the selected part starts).
1196
+ #selectedRows(sel) {
1197
+ const [a, b] = sel.a.y < sel.b.y || (sel.a.y === sel.b.y && sel.a.x <= sel.b.x) ? [sel.a, sel.b] : [sel.b, sel.a]
1198
+ const out = []
1199
+ for (let y = a.y; y <= b.y; y++) {
1200
+ const r = sel.rows?.get(y) ?? this.regions?.get(y)
1201
+ if (!r) continue
1202
+ const end = r.x + width(r.text) // just past its last cell
1203
+ const from = Math.max(r.x, y === a.y ? a.x : r.x)
1204
+ const to = Math.min(end, y === b.y ? b.x + 1 : end)
1205
+ if (to > from) out.push({ y, x: from, text: sliceCols(r.text, from - r.x, to - r.x) })
1206
+ }
1207
+ return out
938
1208
  }
939
1209
 
940
1210
 
@@ -947,16 +1217,24 @@ export class UI {
947
1217
  this.ttyWrite = write
948
1218
  rl._ttyWrite = (s, key = {}) => {
949
1219
  if (!this.full) return write(s, key)
950
- if (this.sel) (this.sel = null), this.render() // a key ends a selection
1220
+ if (this.sel || this.ssel) (this.sel = this.ssel = null), this.render() // a key ends a selection
951
1221
  const bound = !(key.ctrl && key.name === 'c') && this.keys[keyId(key, s)] // ~/.heart/keybindings.json
1222
+ // a dialog: its keys, all of them; Esc (or its own key) closes it; Ctrl+C still stops and quits
1223
+ if (this.dialog && !(key.ctrl && key.name === 'c')) {
1224
+ if (key.name === 'escape' || (bound && bound === this.dialog.toggle)) return this.setDialog(null)
1225
+ return this.dialog.key?.(key, s), this.render()
1226
+ }
952
1227
  if (this.recording) return this.recording.key(key, bound) // voice: Space, Enter, Esc; the rest waits
953
1228
  // a fixed dialog (pick(…, { fixed })): only its keys, nothing typed and no shortcuts
954
1229
  if (this.menu.pick?.fixed && !['up', 'down', 'return', 'escape'].includes(key.name) && !(key.ctrl && key.name === 'c')) return
955
1230
  // In a multi-select: Ctrl+A ticks all, Ctrl+N unticks all (before tab shortcuts claim Ctrl+N)
956
1231
  if (this.menu.pick?.multi && key.ctrl && (key.name === 'a' || key.name === 'n')) {
957
- for (const x of this.menu.pick.items) x.checked = key.name === 'a'
1232
+ for (const x of this.menu.pick.items) if (!x.only) x.checked = key.name === 'a'
958
1233
  return this.refreshMenu()
959
1234
  }
1235
+ // Option+← sends what Alt+B does in many terminals (Esc b): with text in the box, it's the word jump
1236
+ if (bound === 'background_log' && this.rl.line) return write(s, key)
1237
+
960
1238
  if (bound) return this.#action(bound, write)
961
1239
  // Space in an empty box starts voice straight away — no /voice needed (only when it's set up,
962
1240
  // and not in a menu or a mid-task yes/no question, where Space types a space as usual)
@@ -1014,13 +1292,13 @@ export class UI {
1014
1292
  if (m.pick) {
1015
1293
  if (key.name === 'up' || key.name === 'down') return this.#move(key.name === 'up' ? -1 : 1)
1016
1294
  if (key.name === 'tab') return
1017
- if (m.pick.multi && key.name === 'space' && it) {
1295
+ if (m.pick.multi && key.name === 'space' && it && !it.item.only) {
1018
1296
  it.item.checked = !it.item.checked // Space ticks; Enter takes the ticked ones; Ctrl+A/N all/none (handled earlier, before tab shortcuts)
1019
1297
  return this.refreshMenu()
1020
1298
  }
1021
1299
  if (key.name === 'escape' || (key.name === 'return' && it)) {
1022
1300
  const ticked = m.pick.items.filter((x) => x.checked)
1023
- m.pick.chosen = key.name !== 'return' ? null : m.pick.multi ? (ticked.length ? ticked : [it.item]) : it.item
1301
+ m.pick.chosen = key.name !== 'return' ? null : m.pick.multi ? (ticked.length && !it.item.only ? ticked : [it.item]) : it.item // only: an entry that stands alone (Enter on it takes just it)
1024
1302
  rl.line = ''
1025
1303
  rl.cursor = 0
1026
1304
  return write('\r', { name: 'return' })
@@ -1103,8 +1381,7 @@ export class UI {
1103
1381
  rl.cursor = 0
1104
1382
  m.items = []
1105
1383
  m.off = null
1106
- if (/^\/btw\b/.test(line) && this.onBtw) this.onBtw(line.replace(/^\/btw\b/, '').trim()) // answered now, beside the task
1107
- else if (line) this.ahead.push(line) // a /command runs when the task is done (the queue)
1384
+ if (line && !this.onNow?.(line)) this.ahead.push(line) // a command that leaves the conversation alone runs now, beside the task (onNow); the rest when it's done (the queue)
1108
1385
  return this.render()
1109
1386
  }
1110
1387
  if (['up', 'down', 'tab'].includes(key.name) || key.name === 'paste-start' || key.name === 'paste-end') {
@@ -1140,15 +1417,11 @@ export class UI {
1140
1417
  case 'next_tab':
1141
1418
  case 'prev_tab':
1142
1419
  return this.onTab?.(what)
1143
- case 'voice': // the words go where the cursor is, in the box (also while it works)
1420
+ case 'voice':
1144
1421
  if (m.pick || (this.asking && !this.histOn)) return
1145
- return this.dictate().then((text) => {
1146
- if (!text) return
1147
- const pad = rl.line && !/\s$/.test(rl.line.slice(0, rl.cursor)) ? ' ' : ''
1148
- rl.line = rl.line.slice(0, rl.cursor) + pad + text + rl.line.slice(rl.cursor)
1149
- rl.cursor += pad.length + text.length
1150
- this.render()
1151
- })
1422
+ return this.dictateIn()
1423
+ case 'background_log':
1424
+ return this.onPanel?.()
1152
1425
  case 'stop':
1153
1426
  return this.asking ? undefined : this.onEscape?.()
1154
1427
  case 'cycle_permissions':
@@ -1191,6 +1464,17 @@ export class UI {
1191
1464
  write('\r', { name: 'return' })
1192
1465
  }
1193
1466
 
1467
+ // The words go where the cursor is, in the box (also while it works).
1468
+ async dictateIn() {
1469
+ const text = await this.dictate()
1470
+ if (!text) return
1471
+ const rl = this.rl
1472
+ const pad = rl.line && !/\s$/.test(rl.line.slice(0, rl.cursor)) ? ' ' : ''
1473
+ rl.line = rl.line.slice(0, rl.cursor) + pad + text + rl.line.slice(rl.cursor)
1474
+ rl.cursor += pad.length + text.length
1475
+ this.render()
1476
+ }
1477
+
1194
1478
  // Voice mode (/voice, or a key bound to voice): Space to talk, Space again to pause (and again to go on), Enter
1195
1479
  // (or the voice key) to finish, Esc to cancel. While you speak, what's been heard so far shows in
1196
1480
  // the input box (where the cursor was), redone about every second with the quickest model; a
@@ -1334,10 +1618,10 @@ export class UI {
1334
1618
  this.render()
1335
1619
  }
1336
1620
 
1337
- #menuLines(cols) {
1621
+ #menuLines(cols, rows) {
1338
1622
  const m = this.menu
1339
1623
  const width = cols - 1
1340
- const max = m.pick ? Math.max(5, (this.out.rows || 24) - 8) : MENU_ROWS
1624
+ const max = rows ?? (m.pick ? Math.max(5, (this.out.rows || 24) - 8) : MENU_ROWS)
1341
1625
  const first = Math.max(0, Math.min(m.sel - max + 1, m.items.length - max))
1342
1626
  const shown = m.items.slice(first, first + max)
1343
1627
  const pad = m.items.some((x) => x.header) ? ' ' : ''
@@ -1431,7 +1715,14 @@ export class UI {
1431
1715
  }
1432
1716
 
1433
1717
  // history: this prompt's messages go into ↑/↓ history (only the main prompt, never answers like keys).
1718
+ // One question on screen at a time: a command run beside a task (onNow) and the task can both ask.
1719
+ async #free() {
1720
+ while (this.full && this.asking) await new Promise((r) => this.freed.push(r))
1721
+ }
1722
+
1434
1723
  ask(prompt, { initial = '', suggest = false, history = false } = {}) {
1724
+ if (this.dialog && !history) this.setDialog(null) // a question (a permission, a picker) needs you: the dialog makes way
1725
+ if (this.full && this.asking) return this.#free().then(() => this.ask(prompt, { initial, suggest, history }))
1435
1726
  if (history && this.kept) [initial, this.kept] = [initial || this.kept, ''] // typed before a submit()
1436
1727
  this.stopSpin()
1437
1728
  const rl = this.#rl()
@@ -1498,6 +1789,7 @@ export class UI {
1498
1789
  }
1499
1790
  if (draft) [rl.line, rl.cursor] = [draft, draft.length]
1500
1791
  resolve(l)
1792
+ this.freed.shift()?.()
1501
1793
  }),
1502
1794
  )
1503
1795
  }
@@ -1511,7 +1803,7 @@ export class UI {
1511
1803
  // multi: tick several with Space; returns the ticked items (an array), or null.
1512
1804
  // quiet: the question and answer aren't left in the conversation (a question before it starts).
1513
1805
  // fixed: a dialog: no typing to filter, no other keys meanwhile.
1514
- async pick(title, items, { filter = '', multi = false, quiet = false, fixed = false } = {}) {
1806
+ async pick(title, items, { filter = '', multi = false, quiet = false, fixed = false, body = '' } = {}) {
1515
1807
  if (!this.full) {
1516
1808
  items.forEach((it, i) => this.print(` ${i + 1}. ${it.group ? `${it.group} · ` : ''}${it.label}${it.desc ? ' ' + c.dim(it.desc) : ''}`))
1517
1809
  const a = await this.ask(`${title} ${c.dim(multi ? '(numbers, like 1,3)' : '(number)')}: `)
@@ -1519,8 +1811,9 @@ export class UI {
1519
1811
  const chosen = String(a ?? '').split(/[\s,]+/).map((n) => items[Number(n) - 1]).filter(Boolean)
1520
1812
  return chosen.length ? chosen : null
1521
1813
  }
1522
- if (multi) for (const it of items) it.checked ??= false
1523
- this.menu.pick = { items, chosen: null, multi, quiet, fixed }
1814
+ await this.#free()
1815
+ if (multi) for (const it of items) if (!it.only) it.checked ??= false
1816
+ this.menu.pick = { items, chosen: null, multi, quiet, fixed, body }
1524
1817
  try {
1525
1818
  await this.ask(`${c.bold(title)} ${c.dim('›')} `, { suggest: true, initial: filter })
1526
1819
  return this.menu.pick.chosen
@@ -1545,16 +1838,12 @@ export class UI {
1545
1838
  const mode = this.permission === 'plan' ? (this.beforePlan ?? 'ask') : this.permission
1546
1839
  if (mode === 'all' || (mode === 'commands' && kind === 'edit')) return true
1547
1840
  if (this.full) {
1548
- const opts = [
1549
- { label: 'Yes', value: true },
1550
- { label: "Yes, and don't ask again", value: 'all' },
1551
- { label: 'No', value: false },
1552
- { label: 'No, and tell the model what to do instead', value: 'why' },
1553
- ]
1554
- const a = (await this.pick(`${c.yellow('?')} ${question}`, opts))?.value ?? false
1555
- if (a === 'all') this.setPermission('all')
1556
- if (a !== 'why') return Boolean(a)
1557
- return (await this.ask(`${c.bold('What should it do instead?')} `))?.trim() || false
1841
+ this.askAbout = true // the dialog shows what it's about (the diff, the command) above the choices
1842
+ try {
1843
+ return await this.#confirmFull(question)
1844
+ } finally {
1845
+ this.askAbout = false
1846
+ }
1558
1847
  }
1559
1848
  const a = await this.ask(`${c.yellow('?')} ${question} ${c.dim('[Y/n or type feedback]')} `)
1560
1849
  if (a === null) return false
@@ -1563,6 +1852,18 @@ export class UI {
1563
1852
  if (/^(n|no)$/i.test(t)) return false
1564
1853
  return t
1565
1854
  }
1855
+ async #confirmFull(question) {
1856
+ const opts = [
1857
+ { label: 'Yes', value: true },
1858
+ { label: "Yes, and don't ask again", value: 'all' },
1859
+ { label: 'No', value: false },
1860
+ { label: 'No, and tell the model what to do instead', value: 'why' },
1861
+ ]
1862
+ const a = (await this.pick(`${c.yellow('?')} ${question}`, opts))?.value ?? false
1863
+ if (a === 'all') this.setPermission('all')
1864
+ if (a !== 'why') return Boolean(a)
1865
+ return (await this.ask(`${c.bold('What should it do instead?')} `))?.trim() || false
1866
+ }
1566
1867
 
1567
1868
  write(s) {
1568
1869
  if (!this.full) this.stopSpin() // inline, the spinner shares the line; full screen it has its own row
@@ -1666,6 +1967,7 @@ export class UI {
1666
1967
 
1667
1968
  close() {
1668
1969
  this.busySince = null // closing ends any work in progress: the spinner stops too
1970
+ clearInterval(this.dialogTimer)
1669
1971
  this.stopSpin()
1670
1972
  this.rl?.close()
1671
1973
  this.leaveFullscreen()