heartcode 0.1.57 → 0.1.59

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
@@ -466,7 +466,7 @@ export function searchesOutside(cmd, root) {
466
466
  // Waited on for `wait` seconds (the model's choice): finished by then, its exit code and output;
467
467
  // still running, it carries on in the background, and the model checks on it when it likes.
468
468
  export async function runConfirmed(s, cmd, signal, background = false, wait) {
469
- s.ui.step(background ? 'run in background' : 'run', cmd)
469
+ s.ui.step(background ? 'run in background' : 'run', cmd, s.client?.model)
470
470
  if (s.ui.permission === 'plan' && !readOnlyCommand(cmd)) {
471
471
  s.ui.result('not run: plan mode')
472
472
  return prompt('agent/plan-refused', { command: true })
@@ -609,22 +609,23 @@ export function writeResult(rel, r) {
609
609
  const str = { type: 'string' }
610
610
  const int = { type: 'integer' }
611
611
  const obj = (properties, required = []) => ({ type: 'object', properties, required })
612
+ // (descriptions read each time: a project's own prompts and the settings page's edits apply at once)
612
613
  export const TOOL_DEFS = [
613
- { name: 'read_file', description: prompt('agent/tool-read_file'), parameters: obj({ path: str, start_line: int, end_line: int }, ['path']) },
614
- { name: 'search', description: prompt('agent/tool-search'), parameters: obj({ query: str, path: str }, ['query']) },
615
- { name: 'changes', description: prompt('agent/tool-changes'), parameters: obj({ path: str, all: { type: 'boolean' } }) },
616
- { name: 'list_files', description: prompt('agent/tool-list_files'), parameters: obj({ path: str, filter: str }) },
617
- { name: 'find_command', description: prompt('agent/tool-find_command'), parameters: obj({ names: { type: 'array', items: str } }, ['names']) },
618
- { name: 'lsp', description: prompt('agent/tool-lsp'), parameters: obj({ server: str, language: str, action: { type: 'string', enum: ['definition', 'references', 'hover', 'errors'] }, file: str, line: int, column: int, name: str }, ['server', 'language', 'action', 'file']) },
614
+ { name: 'read_file', get description() { return prompt('agent/tool-read_file') }, parameters: obj({ path: str, start_line: int, end_line: int }, ['path']) },
615
+ { name: 'search', get description() { return prompt('agent/tool-search') }, parameters: obj({ query: str, path: str }, ['query']) },
616
+ { name: 'changes', get description() { return prompt('agent/tool-changes') }, parameters: obj({ path: str, all: { type: 'boolean' } }) },
617
+ { name: 'list_files', get description() { return prompt('agent/tool-list_files') }, parameters: obj({ path: str, filter: str }) },
618
+ { name: 'find_command', get description() { return prompt('agent/tool-find_command') }, parameters: obj({ names: { type: 'array', items: str } }, ['names']) },
619
+ { name: 'lsp', get description() { return prompt('agent/tool-lsp') }, parameters: obj({ server: str, language: str, action: { type: 'string', enum: ['definition', 'references', 'hover', 'errors'] }, file: str, line: int, column: int, name: str }, ['server', 'language', 'action', 'file']) },
619
620
  // One edit per call: a list of edits per call measured 2–6 malformed calls per benchmark run vs 0.
620
- { 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']) },
621
- { name: 'write_file', description: prompt('agent/tool-write_file'), parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
622
- { name: 'run_command', description: prompt('agent/tool-run_command'), parameters: obj({ command: str, wait: int, background: { type: 'boolean' } }, ['command']) },
623
- { name: 'background', description: prompt('agent/tool-background'), parameters: obj({ action: { type: 'string', enum: ['output', 'list', 'stop'] }, id: int, wait: int }, ['action']) },
624
- { name: 'todo', description: prompt('agent/tool-todo'), parameters: obj({ todos: { type: 'array', items: obj({ content: str, status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] }, parallel: { type: 'boolean' }, model: str, files: { type: 'array', items: str } }, ['content', 'status']) } }, ['todos']) },
625
- { name: 'web_search', description: prompt('agent/tool-web_search'), parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
626
- { name: 'web_fetch', description: prompt('agent/tool-web_fetch'), parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
627
- { name: 'ask_user', description: prompt('agent/tool-ask_user'), parameters: obj({ question: str, header: str, options: { type: 'array', items: str }, multiple: { type: 'boolean' }, emphasis: { type: 'boolean' } }, ['question', 'options']) }, // one question a call (small models manage that); several calls in one reply are one dialog (agent.js)
621
+ { name: 'edit_file', get description() { return prompt('agent/tool-edit_file') }, parameters: obj({ path: str, search: str, replace: str, start_line: int, end_line: int }, ['path', 'replace']) },
622
+ { name: 'write_file', get description() { return prompt('agent/tool-write_file') }, parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
623
+ { name: 'run_command', get description() { return prompt('agent/tool-run_command') }, parameters: obj({ command: str, wait: int, background: { type: 'boolean' } }, ['command']) },
624
+ { name: 'background', get description() { return prompt('agent/tool-background') }, parameters: obj({ action: { type: 'string', enum: ['output', 'list', 'stop'] }, id: int, wait: int }, ['action']) },
625
+ { name: 'todo', get description() { return prompt('agent/tool-todo') }, parameters: obj({ todos: { type: 'array', items: obj({ content: str, status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] }, parallel: { type: 'boolean' }, model: str, files: { type: 'array', items: str } }, ['content', 'status']) } }, ['todos']) },
626
+ { name: 'web_search', get description() { return prompt('agent/tool-web_search') }, parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
627
+ { name: 'web_fetch', get description() { return prompt('agent/tool-web_fetch') }, parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
628
+ { name: 'ask_user', get description() { return prompt('agent/tool-ask_user') }, parameters: obj({ question: str, header: str, options: { type: 'array', items: str }, multiple: { type: 'boolean' }, emphasis: { type: 'boolean' } }, ['question', 'options']) }, // one question a call (small models manage that); several calls in one reply are one dialog (agent.js)
628
629
  ]
629
630
 
630
631
  // Plan mode (permission "plan"): looking around is fine, changing things isn't. Edits are refused,
@@ -697,9 +698,9 @@ export function extraTools(s) {
697
698
  }
698
699
  if (!s.isSub && s.subagent) {
699
700
  const team = s.team?.() ?? []
700
- const model = { type: 'string', description: 'Which of your models does the job ("provider model" from "Your other models"). Left out: yours, or with images you can\'t see, the first of yours that can.' }
701
+ const model = { type: 'string', description: team.some((t) => t.jobs) ? 'Which helper does the job ("provider model" from "Your helpers"). Left out: the first helper.' : 'Which of your models does the job ("provider model" from "Your other models"). Left out: yours, or with images you can\'t see, the first of yours that can.' }
701
702
  const images = { type: 'array', items: str, description: 'Image paths or URLs for the helper to look at. Needs a model that sees images.' }
702
- out.push({ name: 'agent', description: prompt('agent/tool-agent'), parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }) }, ['description', 'prompt']) })
703
+ out.push({ name: 'agent', get description() { return prompt('agent/tool-agent') }, parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }) }, ['description', 'prompt']) })
703
704
  }
704
705
  return [...out, ...(s.director && !s.appendSystem ? s.director.toolDefs(s) : [])] // manage (director.js); not when a program gives the instructions (--append-system-prompt)
705
706
  }
@@ -709,13 +710,22 @@ export function extraTools(s) {
709
710
  const MARK = { pending: '☐', in_progress: '◐', completed: '☑' }
710
711
  // In the conversation: the whole plan when it's new (or its steps changed), else only the steps whose
711
712
  // status changed, on one line; the whole of it stays in sight under the spinner (full screen).
713
+ // the plan for a program reading HeartCode (headless stream-json): its steps, and who's doing a part
714
+ export const sendTodos = (s) => !s.isSub && s.ui.event?.({ subtype: 'todos', todos: (s.chat.todos ?? []).map(({ content, status, by, byProvider }) => ({ content, status, ...(by && { by: byProvider ? `${byProvider}/${by}` : by }) })) })
712
715
  function showTodos(s, before, todos) {
713
716
  const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x) }
714
- const item = (t) => paint[t.status](`${MARK[t.status]} ${t.content}`)
715
- const same = s.ui.full && before?.length === todos.length && before.every((t, i) => t.content === todos[i].content)
716
- if (!same) return s.ui.print(todos.map((t) => ` ${item(t)}`).join('\n') || c.faint(' (todo list cleared)'))
717
- const moved = todos.filter((t, i) => t.status !== before[i].status)
718
- if (moved.length) s.ui.print(` ${moved.map(item).join(c.faint(' · '))}`)
717
+ const item = (t) => paint[t.status](`${MARK[t.status]} ${t.content}`) + (t.by ? c.faint(` · ${t.by}`) : '')
718
+ // full screen, the same plan changed (most of its steps still in it): only what changed, on one line
719
+ // (steps added, taken out, or whose status moved); the whole plan is pinned under the spinner
720
+ const was = new Map((before ?? []).map((t) => [t.content, t.status]))
721
+ const kept = todos.filter((t) => was.has(t.content)).length
722
+ if (!s.ui.full || !before?.length || kept < Math.max(1, todos.length / 2)) return s.ui.print(todos.map((t) => ` ${item(t)}`).join('\n') || c.faint(' (todo list cleared)'))
723
+ const now = new Set(todos.map((t) => t.content))
724
+ const changes = [
725
+ ...todos.filter((t) => was.get(t.content) !== t.status).map((t) => (was.has(t.content) ? item(t) : `${c.faint('+')} ${item(t)}`)),
726
+ ...(before ?? []).filter((t) => !now.has(t.content)).map((t) => c.faint(`− ${t.content}`)),
727
+ ]
728
+ if (changes.length) s.ui.print(` ${changes.join(c.faint(' · '))}`)
719
729
  }
720
730
  async function todoTool(s, args, signal, id) {
721
731
  let list = args.todos ?? args.items ?? args
@@ -731,8 +741,10 @@ async function todoTool(s, args, signal, id) {
731
741
  .map((t) => (typeof t === 'string' ? { content: t, status: 'pending' } : { content: String(t?.content ?? t?.task ?? t?.title ?? ''), status: String(t?.status ?? 'pending'), ...(t?.model && { model: String(t.model) }), ...((t?.parallel === true || t?.parallel === 'true') && { parallel: true }), ...([t?.files ?? []].flat().filter(Boolean).length && { files: [t.files].flat().map(String) }) }))
732
742
  .filter((t) => t.content.trim())
733
743
  .map((t) => ({ ...t, status: /done|complete/i.test(t.status) ? 'completed' : /progress|doing|active/i.test(t.status) ? 'in_progress' : 'pending' }))
744
+ for (const t of todos) Object.assign(t, ((x) => (x?.by && !t.by ? { by: x.by, byProvider: x.byProvider } : {}))(s.chat.todos?.find((x) => x.content === t.content))) // the model a part was given to: kept when the plan is written again
734
745
  showTodos(s, s.chat.todos, todos)
735
746
  s.chat.todos = todos
747
+ sendTodos(s)
736
748
  s.todoTouched = true
737
749
  const parts = await runParts(s, todos, signal, id)
738
750
  const done = todos.filter((t) => t.status === 'completed').length
@@ -755,7 +767,8 @@ async function runParts(s, todos, signal, id) {
755
767
  const parts = todos.filter((t) => t.status === 'pending' && (t.parallel || t.model))
756
768
  if (!parts.length || s.isSub || !s.subagent || s.ui.permission === 'plan') return ''
757
769
  // a model that isn't one of yours (a name made up, the product's own name): the part runs on this one
758
- const yours = [{ provider: s.client?.provider, model: s.client?.model }, ...(s.team?.() ?? [])]
770
+ const team = s.team?.() ?? []
771
+ const yours = [{ provider: s.client?.provider, model: s.client?.model }, ...(team.some((t) => t.jobs) ? team.filter((t) => t.jobs) : team)] // with helpers ticked: those (only they can be started)
759
772
  const known = (m) => yours.some((y) => `${y.provider} ${y.model}` === m || y.model === m || m.endsWith(` ${y.model}`))
760
773
  const unknown = [...new Set(parts.filter((t) => t.model && !known(t.model)).map((t) => t.model))]
761
774
  for (const t of parts) if (t.model && !known(t.model)) delete t.model
@@ -770,7 +783,7 @@ async function runParts(s, todos, signal, id) {
770
783
  const brief = prompt('agent/part', { task: s.task ?? '', plan, part: t.content, files: (t.files ?? []).join(', '), choices })
771
784
  let out
772
785
  try {
773
- out = await s.subagent({ prompt: brief, model: t.model, description: clip(t.content, 40), ownFiles: t.files }, signal, id)
786
+ out = await s.subagent({ prompt: brief, model: t.model, description: clip(t.content, 40), ownFiles: t.files, part: t }, signal, id) // part: its model is noted on it (by)
774
787
  } catch (e) {
775
788
  if (e.name === 'AbortError' || signal?.aborted) throw e
776
789
  out = `error: ${e.message}`
@@ -781,6 +794,7 @@ async function runParts(s, todos, signal, id) {
781
794
  )
782
795
  s.chat.todos = todos
783
796
  showTodos(s, shown, todos)
797
+ sendTodos(s)
784
798
  return prompt('agent/parts-done', { reports: reports.join('\n\n'), unknown: unknown.join(', '), models: yours.map((y) => `${y.provider} ${y.model}`).join(', ') })
785
799
  }
786
800
 
@@ -1403,7 +1417,7 @@ async function toolRun(name, args, s, signal, id) {
1403
1417
  const notMine = !pre.block && s.ownFiles && partPaths(name, args).find((f) => !s.ownFiles.includes(path.resolve(s.root, f)))
1404
1418
  const stop = pre.block ? prompt('agent/hook', { reason: pre.block, blocked: true }) : notMine ? prompt('agent/part-files', { file: notMine, files: s.ownFiles.map((f) => path.relative(s.root, f)).join(', ') }) : null
1405
1419
  if (stop && name === 'run_command') {
1406
- s.ui.step('run', String(args?.command ?? '')) // a command's lines are shown where it runs, which this one never reaches
1420
+ s.ui.step('run', String(args?.command ?? ''), s.client?.model) // a command's lines are shown where it runs, which this one never reaches
1407
1421
  s.ui.result(refusal(stop))
1408
1422
  }
1409
1423
  if (stop) return stop
@@ -1468,7 +1482,8 @@ async function tool(name, args, s, signal, id) {
1468
1482
  const v = folderView(root, String(args.path))
1469
1483
  return v.error ? `error: ${v.error}` : v.entries.join('\n') + (v.more ? `\n… ${v.more} more` : '') || '(empty folder)'
1470
1484
  }
1471
- const files = listFiles(root).filter((f) => !args.filter || f.includes(args.filter))
1485
+ const under = String(args.path ?? '').replace(/^\.?\/+|\/+$/g, '') // with a filter too: the files under that folder that match
1486
+ const files = listFiles(root).filter((f) => (!under || under === '.' || f === under || f.startsWith(`${under}/`)) && (!args.filter || f.includes(args.filter)))
1472
1487
  return files.slice(0, 500).join('\n') + (files.length > 500 ? `\n… ${files.length - 500} more` : '') || 'no files'
1473
1488
  }
1474
1489
  case 'search':
package/src/ui.js CHANGED
@@ -107,11 +107,14 @@ export function setTheme(name = 'dark') {
107
107
  }
108
108
  setTheme()
109
109
 
110
- // keybindings.json: { "alt+o": "cycle_permissions", "alt+g": "/toggle_thinking", "shift+tab": "none" }.
110
+ // keybindings.json: { "alt+g": "cycle_permissions", "alt+r": "/rewind", "shift+tab": "none" }.
111
111
  // Actions: stop, send_first, send_all, queue_mode, cycle_permissions, newline, clear_input, scroll_up, scroll_down (a page),
112
- // scroll_line_up, scroll_line_down (3 lines), scroll_top, scroll_bottom, voice, new_tab,
112
+ // scroll_line_up, scroll_line_down (3 lines), scroll_top, scroll_bottom, voice, toggle_thinking, background_log, new_tab,
113
113
  // close_tab, next_tab, prev_tab, tab_1…tab_9, none (turns a
114
114
  // built-in key off); anything else is sent as typed (a /command or a message). Ctrl+C stays Ctrl+C.
115
+ // A key as people read it ("alt+shift+down" → "Alt+Shift+↓")
116
+ const KEY_NAMES = { pageup: 'PgUp', pagedown: 'PgDn', up: '↑', down: '↓', left: '←', right: '→', ctrl: 'Ctrl', alt: 'Alt', shift: 'Shift' }
117
+ export const prettyKey = (k) => k.split('+').map((p) => KEY_NAMES[p] ?? (p.length === 1 ? p.toUpperCase() : p[0].toUpperCase() + p.slice(1))).join('+')
115
118
  const CONTROL_KEYS = { '\x1c': 'ctrl+\\', '\x1d': 'ctrl+]', '\x1e': 'ctrl+^', '\x1f': 'ctrl+_' } // no name from readline
116
119
  export const keyId = (key, s = '') => CONTROL_KEYS[key.sequence ?? s] ?? [key.ctrl && 'ctrl', key.meta && 'alt', key.shift && 'shift', key.name ?? s].filter(Boolean).join('+').toLowerCase()
117
120
  // The built-in keys use Alt/Option, never Ctrl (the user's rule; Ctrl keys also clash with the shell and
@@ -124,7 +127,7 @@ export const keyId = (key, s = '') => CONTROL_KEYS[key.sequence ?? s] ?? [key.ct
124
127
  // Alt+N/P, Alt+1…9: tabs; Shift+↑↓ and Alt+↑↓ scroll the conversation (as PgUp/PgDn and the mouse
125
128
  // wheel do), Alt+Shift+↑↓ to its top and bottom; Alt+O: all of the model's thinking, or its last lines.
126
129
  // keybindings.json can move any of them.
127
- export const DEFAULT_KEYS = { 'alt+o': '/toggle_thinking', 'alt+b': 'background_log', 'alt+s': 'send_first', 'alt+a': 'send_all', 'alt+m': 'queue_mode', 'shift+up': 'scroll_line_up', 'shift+down': 'scroll_line_down', 'alt+up': 'scroll_up', 'alt+down': 'scroll_down', 'alt+shift+up': 'scroll_top', 'alt+shift+down': 'scroll_bottom', 'alt+t': 'new_tab', 'alt+w': 'close_tab', 'alt+n': 'next_tab', 'alt+p': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
130
+ export const DEFAULT_KEYS = { 'alt+o': 'toggle_thinking', 'alt+b': 'background_log', 'alt+s': 'send_first', 'alt+a': 'send_all', 'alt+m': 'queue_mode', 'shift+up': 'scroll_line_up', 'shift+down': 'scroll_line_down', 'alt+up': 'scroll_up', 'alt+down': 'scroll_down', 'alt+shift+up': 'scroll_top', 'alt+shift+down': 'scroll_bottom', 'alt+t': 'new_tab', 'alt+w': 'close_tab', 'alt+n': 'next_tab', 'alt+p': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
128
131
  export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
129
132
  let raw = {}
130
133
  try {
@@ -747,6 +750,7 @@ export const PERMISSIONS = [
747
750
  ]
748
751
 
749
752
  let drewLast = null // the UI (tab) that last drew the screen: only its own last frame can be diffed against
753
+ let drewAt = null // the tab whose frame lastFrame is (another tab drawing in between: it's no longer on screen)
750
754
  export class UI {
751
755
  constructor({ yes = false, input = process.stdin, output = process.stdout } = {}) {
752
756
  this.permission = yes ? 'all' : 'ask' // see PERMISSIONS
@@ -780,7 +784,7 @@ export class UI {
780
784
  this.frame = 0
781
785
  this.dialog = null // a box over the screen (the background commands' logs)
782
786
  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
787
+ this.helpers = new Map() // helpers at work (agent.js): label → { model, what it's doing now }, shown under the spinner
784
788
  }
785
789
 
786
790
  // A dialog: a box in the middle, 70% of the screen each way, the conversation going on around it;
@@ -971,7 +975,8 @@ export class UI {
971
975
  if (!open.length) return []
972
976
  const done = todos.length - open.length
973
977
  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)
978
+ const by = (t) => (t.by ? c.faint(' · ') + (t.status === 'in_progress' ? c.info(t.by) : c.faint(t.by)) : '') // the model a part was given to
979
+ 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)}${by(t)}`, cols)
975
980
  const shown = todos.length <= 8 ? todos : open.slice(0, 7)
976
981
  return [
977
982
  fit(` ${c.muted('Plan')} ${c.faint(`· ${done} of ${todos.length} done`)}`, cols),
@@ -1015,6 +1020,7 @@ export class UI {
1015
1020
  // who: the model thinking, named over its thinking (helpers say their own: helperUI in agent.js)
1016
1021
  response(who) {
1017
1022
  const t0 = Date.now()
1023
+ this.lastThought = null // the key shows this reply's thinking from now on, not an older one's
1018
1024
  const secs = () => duration(Date.now() - t0)
1019
1025
  const write = (x) => this.write(x)
1020
1026
  let think = null
@@ -1025,7 +1031,7 @@ export class UI {
1025
1031
  if (thought.trim() && !think) {
1026
1032
  // what it thought stays in the conversation: its last two lines (all of it: Alt+O)
1027
1033
  const last = thought.split('\n').map((l) => l.trim()).filter(Boolean).slice(-2)
1028
- this.print(c.faint(c.italic(`✻ ${who ? `${who} ` : ''}thought for ${secs()} · Alt+O shows all of it`)))
1034
+ this.print(c.faint(c.italic(`✻ ${who ? `${who} ` : ''}thought for ${secs()}${this.keyFor('toggle_thinking') ? ` · ${this.keyFor('toggle_thinking')} shows all of it` : ''}`)))
1029
1035
  this.print(c.think(c.italic(last.map((l) => ` ${l}`).join('\n'))))
1030
1036
  this.lastThought = { who, text: thought } // Alt+O shows it, now that it's over (showLastThought)
1031
1037
  }
@@ -1041,6 +1047,8 @@ export class UI {
1041
1047
  }
1042
1048
  if (!think) {
1043
1049
  this.thinkTail = ''
1050
+ this.replying = true // its own text shows it's at work: no spinner line after it
1051
+ this.liveStep = null
1044
1052
  this.gap()
1045
1053
  this.print(c.faint(c.italic(`✻ ${who ? `${who} is thinking` : 'Thinking'}…`)))
1046
1054
  const style = (x) => c.think(c.italic(x))
@@ -1054,6 +1062,8 @@ export class UI {
1054
1062
  if (!t) return
1055
1063
  this.tokenAt = Date.now()
1056
1064
  if (!text) {
1065
+ this.replying = true
1066
+ this.liveStep = null
1057
1067
  if (this.label === 'thinking') this.label = 'answering'
1058
1068
  think?.end()
1059
1069
  this.gap()
@@ -1067,6 +1077,7 @@ export class UI {
1067
1077
  if (text) text.end()
1068
1078
  else if (think) think.end()
1069
1079
  else summary()
1080
+ this.replying = false
1070
1081
  this.afterBlock = Boolean(text || think)
1071
1082
  },
1072
1083
  }
@@ -1116,8 +1127,10 @@ export class UI {
1116
1127
  // alternate screen · kitty keyboard protocol (Shift/Cmd+Enter are told apart) · bracketed paste
1117
1128
  // · mouse reports (SGR), when HeartCode takes the mouse
1118
1129
  this.out.write('\x1b[?1049h\x1b[H\x1b[2J\x1b[>1u\x1b[?2004h' + this.mouseOn)
1119
- this.frame0 = null
1120
- this.out.on('resize', () => this.render())
1130
+ this.frame0 = this.lastFrame = null
1131
+ // a new size: the whole screen again, after readline's own handler (it clears from its cursor down,
1132
+ // which took the input box and the status bar with it)
1133
+ this.out.on('resize', () => setImmediate(() => ((this.frameSize = this.lastFrame = null), this.render())))
1121
1134
  this.#rl()
1122
1135
  process.on('exit', () => this.leaveFullscreen())
1123
1136
  }
@@ -1135,12 +1148,18 @@ export class UI {
1135
1148
  this.rl?.resume()
1136
1149
  if (wasFull) {
1137
1150
  this.out.write('\x1b[?1049h\x1b[>1u\x1b[?2004h' + this.mouseOn)
1138
- this.frame0 = null
1151
+ this.frame0 = this.lastFrame = null
1139
1152
  this.render()
1140
1153
  }
1141
1154
  }
1142
1155
  }
1143
1156
 
1157
+ // The key bound to an action now (keybindings.json can move or remove it), as people read it; null: none
1158
+ keyFor(action) {
1159
+ const k = Object.entries(this.keys ?? {}).find(([, v]) => v === action)?.[0]
1160
+ return k ? prettyKey(k) : null
1161
+ }
1162
+
1144
1163
  // Taking the mouse, or giving it back to the terminal, now (the settings page's switch)
1145
1164
  setMouse(on) {
1146
1165
  this.mouseOn = on ? MOUSE_ON : ''
@@ -1325,14 +1344,23 @@ export class UI {
1325
1344
  }
1326
1345
 
1327
1346
  // The conversation as screen rows (wrapped to the width; cached per line).
1347
+ // While it works, the conversation shows where too: the step running (its ● spins until its
1348
+ // result), else (waiting on the model between steps) a line of its own at the end, as the
1349
+ // spinner under the conversation says it.
1328
1350
  #rows(cols) {
1329
1351
  if (this.wrapCols !== cols) [this.wrapped, this.wrapCols] = [[], cols]
1352
+ const spin = this.timer && !this.asking ? c.brand(FRAMES[this.frame % FRAMES.length]) : null
1353
+ let last = this.log.length - 1
1354
+ while (last >= 0 && !this.log[last]) last--
1355
+ const live = spin && this.liveStep && this.log[last] === this.liveStep ? last : -1 // only while nothing came after it
1330
1356
  const out = []
1331
1357
  this.log.forEach((line, i) => {
1358
+ if (i === live) return out.push(...wrapHang(line.replace('●', spin), cols)) // not kept: it changes every frame
1332
1359
  const w = this.wrapped[i]
1333
1360
  if (!w || w.src !== line) this.wrapped[i] = { src: line, rows: wrapHang(line, cols) } // at spaces, wrapped rows under the text
1334
1361
  out.push(...this.wrapped[i].rows)
1335
1362
  })
1363
+ if (spin && live === -1 && !this.replying && this.statusText) out.push(...wrapHang(`${spin} ${c.muted(this.statusText)}`, cols))
1336
1364
  return out
1337
1365
  }
1338
1366
 
@@ -1364,26 +1392,27 @@ export class UI {
1364
1392
  const label = this.#label()
1365
1393
  const waiting = request && !(this.tokenAt >= request) && this.beforeRetry === undefined
1366
1394
  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(' · ') : ''
1395
+ const timer = this.busySince ? [this.beforeRetry !== undefined && 'no answer yet', `${short(this.worked())} in all`, 'Esc twice to stop', this.thinkTail && this.keyFor('toggle_thinking') && `${this.keyFor('toggle_thinking')} shows all thinking`].filter(Boolean).join(' · ') : ''
1368
1396
  if (this.thinkTail) {
1369
1397
  // the thinking's last two lines (long ones wrapped), dim, changing as it comes
1370
1398
  const w = Math.max(20, cols - 6)
1371
1399
  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)
1372
1400
  for (const l of lines.slice(-2)) bottom.push(fit(` ${c.think(c.italic(l))}`, cols))
1373
1401
  }
1402
+ this.statusText = status // the same, at the end of the conversation (#rows)
1374
1403
  bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(status)}`, cols))
1375
1404
  if (timer) bottom.push(...wrapParts(timer, cols - 2).map((r) => fit(` ${c.faint(r)}`, cols)))
1376
1405
  // helpers at work (agent.js keeps them in this.helpers: label → what it's doing), then the plan
1377
1406
  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))
1407
+ for (const [name, { model, what }] of helpers.slice(0, helpers.length > 6 ? 5 : 6)) bottom.push(fit(` ${c.faint('◦')} ${c.muted(name)}${model ? `${c.faint(' · ')}${c.info(model)}` : ''}${what ? c.faint(` · ${what}`) : ''}`, cols))
1379
1408
  if (helpers.length > 6) bottom.push(c.faint(` … ${helpers.length - 5} more`))
1380
1409
  bottom.push(...this.#todoLines(cols))
1381
1410
  }
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`))
1411
+ if (this.scroll) bottom.push(c.dim(` ↓ ${Number.isFinite(this.scroll) ? this.scroll : 'more'} lines below · held here while you read${this.keyFor('scroll_bottom') ? ` · ${this.keyFor('scroll_bottom')} to the bottom` : ''}`))
1383
1412
  if (this.ahead.length) {
1384
1413
  const key = (k, d) => `${c.muted(k)} ${c.faint(d)}`
1385
1414
  const sep = c.ghost(' · ')
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)}`
1415
+ const queued = `${c.bright(`queued ${this.ahead.length}`)}${sep}${c.faint(`when done: ${this.queueMode === 'one' ? 'one by one' : 'all together'}`)}${sep}${[['Esc', 'edit or cancel'], [this.keyFor('send_first'), 'send first now'], [this.keyFor('send_all'), 'send all now'], [this.keyFor('queue_mode'), 'change when done']].filter(([k]) => k).map(([k, d]) => key(k, d)).join(sep)}`
1387
1416
  bottom.push(...wrapParts(queued, cols - 2, sep).map((r) => fit(` ${r}`, cols))) // on more lines, not cut
1388
1417
  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))
1389
1418
  if (this.ahead.length > 5) bottom.push(c.faint(` … ${this.ahead.length - 5} more`))
@@ -1416,12 +1445,18 @@ export class UI {
1416
1445
  }
1417
1446
  // only the rows that changed since the last frame are written (scrolling rewrote the whole screen
1418
1447
  // every time); a dialog or a selection over it, or a resize: all of them
1419
- const overlay = Boolean(this.dialog || asked || this.ssel || this.flash)
1420
- const was = !overlay && !this.frameOverlay && this.frameSize === `${rows}x${cols}` && drewLast === this ? this.frame0 : null // another tab drew since: all of it
1448
+ // a dialog open in the last frame too: the same, as long as the box itself stays where it was (it's
1449
+ // drawn over the rows again each frame; all of them once it moved, grew or closed). Writing every
1450
+ // row each frame under it made it flicker, 12 times a second while the spinner turns.
1451
+ // (a selection drawn over the screen: all of them, every time, as its old cells must go)
1452
+ const overlay = this.ssel || this.flash ? 'selection' : this.dialog || asked ? 'dialog' : ''
1453
+ const was = overlay !== 'selection' && overlay === this.frameOverlay && this.frameSize === `${rows}x${cols}` && drewLast === this ? this.frame0 : null // another tab drew since: all of it
1421
1454
  const frame = []
1455
+ let every = s // all the rows, for when the box moved (decided once it's drawn)
1422
1456
  const put = (r, line, always = false) => {
1423
1457
  const text = row(line)
1424
1458
  frame[r] = text
1459
+ every += `\x1b[${r};1H${text}`
1425
1460
  if (always || was?.[r] !== text) s += `\x1b[${r};1H${text}`
1426
1461
  }
1427
1462
  for (let r = 0; r < inputTop - 1; r++) {
@@ -1445,13 +1480,19 @@ export class UI {
1445
1480
  if (this.dialog || asked) {
1446
1481
  this.regions = new Map()
1447
1482
  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))
1483
+ const rect = JSON.stringify(this.dialogAt)
1484
+ if (rect !== this.frameRect) s = every // it moved, grew or shrank: the rows it no longer covers again
1485
+ this.frameRect = rect
1448
1486
  s += box
1449
1487
  cursor = cur // a question: its cursor in the box; else hidden
1450
1488
  } else {
1451
- this.dialogAt = null
1489
+ this.dialogAt = this.frameRect = null
1452
1490
  cursor = this.asking || typing ? `\x1b[${inputTop + input.cur.row - first};${input.cur.col + 1}H\x1b[?25h` : `\x1b[${inputTop};1H`
1453
1491
  }
1454
- out.write(s + this.#screenSelection() + cursor)
1492
+ const frameText = `\x1b[?2026h${s}${this.#screenSelection()}${cursor}\x1b[?2026l` // shown at once where the terminal can (synchronized output), never half-drawn
1493
+ if (frameText === this.lastFrame && drewAt === this) return // the same as on screen (a spinner tick under a dialog): nothing written
1494
+ ;[this.lastFrame, drewAt] = [frameText, this]
1495
+ out.write(frameText)
1455
1496
  }
1456
1497
 
1457
1498
  // A selection outside the conversation (in a dialog, the header, the input, the status bar), or a
@@ -1493,7 +1534,7 @@ export class UI {
1493
1534
  const bound = !(key.ctrl && key.name === 'c') && this.keys[keyId(key, s)] // ~/.heart/keybindings.json
1494
1535
  // a dialog: its keys, all of them; Esc (or its own key) closes it; Ctrl+C still stops and quits
1495
1536
  if (this.dialog && !(key.ctrl && key.name === 'c')) {
1496
- if (key.name === 'escape' || (bound && bound === this.dialog.toggle)) return this.setDialog(null)
1537
+ if (key.name === 'escape' || (bound && bound.replace(/^\//, '') === String(this.dialog.toggle ?? '').replace(/^\//, ''))) return this.setDialog(null)
1497
1538
  return this.dialog.key?.(key, s), this.render()
1498
1539
  }
1499
1540
  if (this.recording) return this.recording.key(key, bound) // voice: Space, Enter, Esc; the rest waits
@@ -1650,15 +1691,40 @@ export class UI {
1650
1691
  }
1651
1692
 
1652
1693
  // input), sent when the answer is done, or at once with send_first / send_all. Esc stops the task.
1694
+ // Queued messages taken back into the box (Esc, ↑): before what's typed there, one a line.
1695
+ #unqueue(msgs) {
1696
+ const rl = this.rl
1697
+ rl.line = [...msgs, rl.line].filter((x) => x.trim()).join('\n')
1698
+ rl.cursor = rl.line.length
1699
+ this.escArm = 0
1700
+ this.render()
1701
+ }
1653
1702
  #typeAhead(s, key, write) {
1654
1703
  const rl = this.rl
1655
1704
  const m = this.menu
1656
1705
  const it = m.on && m.items[m.sel] // a suggestion is highlighted (commands/@files show while working too)
1706
+ // Esc, a layer at a time, and the work goes on: the queued messages come back into the box (to
1707
+ // change, or drop); then what's in the box is cleared; only then does Esc stop the work
1657
1708
  if (key.name === 'escape') {
1658
1709
  if (m.on) return (m.off = rl.line), this.#suggestWhileWorking() // first Esc just closes the suggestions
1710
+ if (this.ahead.length) {
1711
+ const n = this.ahead.length
1712
+ this.#unqueue(this.ahead.splice(0))
1713
+ return this.notice(`${n === 1 ? 'The queued message is' : `${n} queued messages are`} back in the box: change ${n === 1 ? 'it' : 'them'} and press Enter, or Esc to clear`, 4000)
1714
+ }
1715
+ if (rl.line.trim()) return this.clearInput(), (this.escArm = 0), this.notice('Cleared · Esc twice stops the answer', 2500)
1659
1716
  return this.escStop()
1660
1717
  }
1718
+ // ↑ in an empty box: the last queued message back into it, to change or drop
1719
+ if (key.name === 'up' && !rl.line && this.ahead.length && !it) return this.#unqueue([this.ahead.pop()])
1661
1720
  if (key.name === 'tab' && key.shift) return this.cyclePermission()
1721
+ // Shift+Enter, Option+Enter: a new line in the box, as at the prompt (readline would send the line)
1722
+ if (key.name === 'enter' || (key.name === 'return' && key.meta)) {
1723
+ rl.line = rl.line.slice(0, rl.cursor) + '\n' + rl.line.slice(rl.cursor)
1724
+ rl.cursor++
1725
+ m.items = []
1726
+ return this.render()
1727
+ }
1662
1728
  if (key.name === 'pageup' || key.name === 'pagedown') return this.scrollBy(key.name === 'pageup' ? this.page() : -this.page())
1663
1729
  if (it && (key.name === 'up' || key.name === 'down')) {
1664
1730
  m.sel = (m.sel + (key.name === 'up' ? m.items.length - 1 : 1)) % m.items.length
@@ -1707,6 +1773,19 @@ export class UI {
1707
1773
  switch (what) {
1708
1774
  case 'none':
1709
1775
  return
1776
+ // the model's thinking: all of it as it comes, or its last two lines; one just over, all of it in a
1777
+ // box now (the key closes it). A key, not a message: nothing is sent, queued or kept in ↑
1778
+ // after an answer: its whole thinking in a box (the key closes it again; how thinking shows
1779
+ // stays as it was); else how thinking shows switches: all of it as it comes, or its last two
1780
+ // lines (a thought shown in full already goes on in full until its reply ends)
1781
+ case 'toggle_thinking':
1782
+ case '/toggle_thinking': {
1783
+ const t = !this.busySince ? this.lastThought : null
1784
+ if (t?.text?.trim()) return this.showText(`${t.who ? `${t.who}'s thinking` : 'Thinking'}`, t.text.trim(), 'toggle_thinking')
1785
+ this.showThinking = !this.showThinking
1786
+ const k = this.keyFor('toggle_thinking') ?? 'the key'
1787
+ return this.notice(this.showThinking ? `Thinking: all of it, as it comes · ${k}: its last two lines` : `Thinking: its last two lines from the next reply on · ${k}: all of it`, 2500)
1788
+ }
1710
1789
  case 'new_tab':
1711
1790
  case 'close_tab':
1712
1791
  case 'next_tab':
@@ -2295,12 +2374,16 @@ export class UI {
2295
2374
  print(s = '') {
2296
2375
  this.write(s + '\n')
2297
2376
  }
2298
- step(name, detail = '') {
2377
+ // who: the model that made this call (named after it)
2378
+ step(name, detail = '', who = '') {
2299
2379
  if (this.afterBlock) this.gap()
2300
2380
  this.afterBlock = false
2301
- this.print(`${c.accent('●')} ${c.accent(c.bold(name))} ${c.info(detail)}`)
2381
+ const line = `${c.accent('●')} ${c.accent(c.bold(name))} ${c.info(detail)}${who ? c.faint(` · ${who}`) : ''}`
2382
+ this.print(line)
2383
+ this.liveStep = line // its ● spins until its result (#rows)
2302
2384
  }
2303
2385
  result(text) {
2386
+ this.liveStep = null
2304
2387
  this.print(` ${c.ghost('⎿')} ${c.faint(text)}`)
2305
2388
  }
2306
2389
  warn(text) {
@@ -2349,6 +2432,7 @@ export class UI {
2349
2432
  if (this.busySince) return void (this.label = 'working') // still busy: keep spinning, generically
2350
2433
  clearInterval(this.timer)
2351
2434
  this.timer = null
2435
+ this.liveStep = null
2352
2436
  if (this.full) this.render()
2353
2437
  else this.out.write('\r\x1b[K')
2354
2438
  }