heartcode 0.1.95 → 0.1.102

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/CHANGELOG.md CHANGED
@@ -2,6 +2,62 @@
2
2
 
3
3
  What changed in each version of HeartCode, newest first.
4
4
 
5
+ ## 0.1.102 (2026-11-27)
6
+
7
+ - **Import & export your settings** (`/settings` → Advanced → Import & export): tick what goes in the
8
+ file — providers and CLIs, the model list and helpers (with abilities set by hand), MCP servers,
9
+ skills, prompt changes — and whether API keys go too (off by default; without them, MCP servers'
10
+ env and headers stay out as well). Importing shows what the file has, with the same tickboxes, and
11
+ merges: it adds and updates what has the same name, and removes nothing of yours.
12
+ - **A CLI that isn't installed on this computer comes in switched off** (tagged "not installed" on
13
+ Providers). Switching it on asks to install it first, then switches it on once it's in; Turn all on
14
+ and Turn on N providers leave those off and say so.
15
+
16
+ ## 0.1.101 (2026-11-24)
17
+
18
+ - **Room above the status line**: three empty rows between the conversation and "thinking · 27s"
19
+ while it works (one on a short terminal), so the two don't run together.
20
+
21
+ ## 0.1.100 (2026-11-24)
22
+
23
+ - The 0.1.99 note named the wrong key for the whole plan: it's Alt+L.
24
+
25
+ ## 0.1.99 (2026-11-24)
26
+
27
+ - **One quiet row under the conversation while it works**: what's happening in a few words
28
+ ("thinking", "running a command", "searching the web"), the plan's progress and helpers as a
29
+ count ("plan 2/5 · 2 helpers"), the time, and Esc. The command, its output, the helpers' doings
30
+ and the plan's steps are no longer listed there: what's being done is in the conversation above
31
+ (each step as it runs). The whole plan: Alt+L (`show_plan`) as before.
32
+ - **The ♥ by the input beats while HeartCode works on your message** (lub-dub, then a rest).
33
+
34
+ ## 0.1.98 (2026-11-24)
35
+
36
+ - **No more stray lines under the spinner.** A multi-line command (a script run with `node -e "…"`,
37
+ a heredoc) put its line breaks into the spinner ("running … › its last output line") and into its
38
+ step ("✓ Run …"); the terminal wrote them on rows the screen didn't track, which stayed there
39
+ ("s = s… › ok · 8m 53s") or scrambled the lines around them. Both are one line now, and nothing
40
+ drawn under the conversation can carry a line break or a tab.
41
+
42
+ ## 0.1.97 (2026-11-24)
43
+
44
+ - **`/update` shows the whole changelog**, newest first, with the versions since yours marked
45
+ `· new`; PgUp/PgDn or the mouse wheel scroll it (↑↓ still choose Update now / Not now). It said
46
+ "no changelog found": it was read from GitHub's main branch, which can be behind npm; now it's
47
+ the changelog of the version on offer, from its npm package.
48
+ - Any question with a long text above its choices scrolls the same way.
49
+
50
+ ## 0.1.96 (2026-11-24)
51
+
52
+ - **A test no longer passes a model that only seemed to answer.** Asked to reply "OK":
53
+ - **Answered with an error** (`✗ error reply`): its answer is an error as text ("doesn't have enough
54
+ credits", "Upgrade your plan", `Model "…" is not available`): the request went through, the
55
+ model doesn't work.
56
+ - **Didn't answer** (`✗ off-topic`): something else altogether (an image or audio link, a safety
57
+ verdict, a persona's greeting): likely not a chat model.
58
+ Both count as not working (helpers, Doesn't work) and are in the Result filter. Results already
59
+ saved are judged the same way, without testing again.
60
+
5
61
  ## 0.1.95 (2026-11-23)
6
62
 
7
63
  - **The Providers page, rewritten**: one state (the filters, the folds, the ticked models) and one way
package/README.md CHANGED
@@ -224,6 +224,13 @@ Ask it to read, change, run and fix things in your project, like any coding agen
224
224
 
225
225
  <img width="972" height="611" alt="Image" src="https://github.com/user-attachments/assets/dcf9488a-7cee-4a24-8e3e-c86876d379c9" />
226
226
 
227
+ ## Taking your setup to another computer
228
+
229
+ `/settings` → Advanced → **Import & export**: export your providers, model list, MCP servers, skills and
230
+ prompt changes to a file (API keys only if you tick them), and import it on the other computer. It
231
+ merges into what's there. CLIs that computer doesn't have come in switched off; switching one on
232
+ installs it first.
233
+
227
234
  ## More on the settings page
228
235
 
229
236
  What's in the sidebar:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heartcode",
3
- "version": "0.1.95",
3
+ "version": "0.1.102",
4
4
  "description": "A coding CLI for any local or OpenAI-compatible model, including small models without tool calling.",
5
5
  "keywords": [
6
6
  "ai",
package/src/settings.html CHANGED
@@ -272,6 +272,9 @@
272
272
  .preset.skel { pointer-events: none; }
273
273
  .preset.skel .shim:first-child { width: 70%; height: 13px; margin-top: 0; }
274
274
  @keyframes shim { from { background-position: 200% 0; } to { background-position: -200% 0; } }
275
+ .move-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(340px, 1fr)); gap: 16px; align-items: start; }
276
+ .move-grid h2 { margin: 0 0 4px; font-size: 16px; }
277
+ .move-grid .opt input[type=checkbox]:disabled + i { opacity: .4; }
275
278
  .cli-bar { display: flex; align-items: center; gap: 12px; margin: 4px 0 10px; font-size: 13px; }
276
279
  #cli-form { width: min(980px, calc(100vw - 32px)); }
277
280
  .preset.cli .box { position: absolute; top: 10px; right: 10px; width: 16px; height: 16px; border-radius: 4px; border: 1.5px solid var(--line-strong); display: grid; place-items: center; color: transparent; }
@@ -895,7 +898,7 @@
895
898
  <a href="#mcp" data-page="mcp"><span class="ic">⧉</span> MCP servers <span class="count" id="n-mcp"></span></a>
896
899
  <a href="#prompts" data-page="prompts"><span class="ic">✎</span> System prompt</a>
897
900
  <div class="nav-group" role="separator"></div>
898
- <a href="#logging" data-page="logging" data-tabs="logging files"><span class="ic">▤</span> Advanced <span class="count" id="n-failed"></span></a>
901
+ <a href="#logging" data-page="logging" data-tabs="logging files move"><span class="ic">▤</span> Advanced <span class="count" id="n-failed"></span></a>
899
902
  </nav>
900
903
  <div class="using" id="using"></div>
901
904
  </aside>
@@ -1118,6 +1121,27 @@
1118
1121
  </section>
1119
1122
 
1120
1123
  <!-- Advanced files -->
1124
+ <section class="page" id="page-move">
1125
+ <div class="head"><div><h1>Import &amp; export</h1><p class="lead">Take your setup to another computer, or bring one in. Importing adds to what's here and updates what has the same name: nothing of yours is removed.</p></div></div>
1126
+ <div class="move-grid">
1127
+ <div class="card">
1128
+ <h2>Export</h2>
1129
+ <p class="muted">What goes in the file:</p>
1130
+ <div id="x-parts"></div>
1131
+ <label class="opt"><div class="t"><b>Include API keys</b><span>Off: providers come without their keys, and MCP servers without their env and headers (they often hold tokens too). On: the file works at once on the other computer, but anyone with it has your keys.</span></div><span class="sw"><input type="checkbox" id="x-keys"><i></i></span></label>
1132
+ <div class="actions"><button class="primary" id="x-go" type="button">Export to a file</button></div>
1133
+ </div>
1134
+ <div class="card">
1135
+ <h2>Import</h2>
1136
+ <p class="muted">A file exported from HeartCode (here or on another computer).</p>
1137
+ <input type="file" id="i-file" accept=".json,application/json" hidden>
1138
+ <div class="row" style="align-items:center;gap:10px"><button id="i-pick" type="button">Choose a file…</button><span class="muted mono" id="i-name"></span></div>
1139
+ <div id="i-parts"></div>
1140
+ <div class="hint" id="i-note"></div>
1141
+ <div class="actions"><button class="primary" id="i-go" type="button" disabled>Import</button></div>
1142
+ </div>
1143
+ </div>
1144
+ </section>
1121
1145
  <section class="page" id="page-files">
1122
1146
  <div class="head"><div><h1>Settings files</h1><p class="lead">The rest of HeartCode's settings, as the files they're kept in (<span class="mono" id="f-home"></span>). A JSON file that doesn't parse isn't saved; save one empty to delete it.</p></div></div>
1123
1147
  <div class="md">
@@ -1543,7 +1567,7 @@ addEventListener('scroll', drawVirtual, { capture: true, passive: true }) // the
1543
1567
  addEventListener('resize', drawVirtual)
1544
1568
 
1545
1569
  // pages: one at a time, from the address (#providers…)
1546
- const PAGES = ['providers', 'models', 'general', 'statusbar', 'notify', 'logging', 'prompts', 'mcp', 'skills', 'files']
1570
+ const PAGES = ['providers', 'models', 'general', 'statusbar', 'notify', 'logging', 'prompts', 'mcp', 'skills', 'files', 'move']
1547
1571
  const page = () => (PAGES.includes(location.hash.slice(1)) ? location.hash.slice(1) : 'providers')
1548
1572
  function showPage() {
1549
1573
  for (const p of PAGES) $('page-' + p).classList.toggle('on', p === page())
@@ -1560,7 +1584,7 @@ function showPage() {
1560
1584
  addEventListener('hashchange', showPage)
1561
1585
  // A sidebar item with several pages (data-tabs): a tab bar on top of each of them. Each page keeps
1562
1586
  // its own address (#providers, #statusbar, #files…), so links to one still open it.
1563
- const TAB_NAMES = { models: 'List', providers: 'Providers', general: 'Settings', statusbar: 'Status bar', logging: 'Logs', files: 'Files' }
1587
+ const TAB_NAMES = { models: 'List', providers: 'Providers', general: 'Settings', statusbar: 'Status bar', logging: 'Logs', files: 'Files', move: 'Import & export' }
1564
1588
  const TAB_COUNTS = { providers: 'n-providers' } // a count shown on the tab, not the sidebar item
1565
1589
  for (const a of document.querySelectorAll('nav a[data-tabs]')) {
1566
1590
  const tabs = a.dataset.tabs.split(' ')
@@ -1644,6 +1668,74 @@ async function saveItem(kind, id, path, body, done) {
1644
1668
  return r
1645
1669
  }
1646
1670
 
1671
+ // --- Import & export (Advanced): the parts, ticked; keys only when asked; an import merged in ---
1672
+ const MOVE_PARTS = [
1673
+ ['providers', 'Providers and CLIs', 'their addresses, which are on, models added by name (keys only with "Include API keys")'],
1674
+ ['models', 'Model list and helpers', 'your models in order, what to do when one fails, the helpers and their jobs, abilities set by hand'],
1675
+ ['mcp', 'MCP servers', 'the servers you added'],
1676
+ ['skills', 'Skills', 'your own skills and their files'],
1677
+ ['prompts', 'Prompt changes', 'your changes to HeartCode\'s prompts (System prompt)'],
1678
+ ]
1679
+ const movePick = { x: new Set(['providers', 'models']), i: new Set() }
1680
+ let importing = null // { name, data }
1681
+ const partRows = (side, counts) => MOVE_PARTS.map(([k, label, desc]) => h('label', { className: 'opt' },
1682
+ h('div', { className: 't' }, h('b', { textContent: `${label}${counts[k] != null ? ` (${counts[k]})` : ''}` }), h('span', { textContent: desc })),
1683
+ h('span', { className: 'sw' }, h('input', { type: 'checkbox', checked: movePick[side].has(k), disabled: !counts[k], onchange: (e) => (e.target.checked ? movePick[side].add(k) : movePick[side].delete(k), drawMove()) }), h('i'))))
1684
+ function drawMove() {
1685
+ if (!S) return
1686
+ const mine = { providers: S.providers.length, models: S.order.length, mcp: S.mcp.filter((x) => x.from === 'yours').length, skills: S.skills.filter((x) => x.mine).length, prompts: S.prompts.filter((x) => x.changed).length }
1687
+ for (const k of movePick.x) if (!mine[k]) movePick.x.delete(k)
1688
+ put($('x-parts'), partRows('x', mine))
1689
+ $('x-go').disabled = !movePick.x.size
1690
+ const d = importing?.data
1691
+ const theirs = d ? { providers: Object.keys(d.providers ?? {}).length, models: d.models?.list?.length, mcp: Object.keys(d.mcp ?? {}).length, skills: Object.keys(d.skills ?? {}).length, prompts: Object.values(d.prompts ?? {}).reduce((n, x) => n + Object.keys(x).length, 0) } : {}
1692
+ put($('i-parts'), d ? partRows('i', theirs) : [])
1693
+ $('i-go').disabled = !movePick.i.size
1694
+ const clis = Object.entries(d?.providers ?? {}).filter(([, p]) => /^cli:\/\//i.test(p.baseUrl ?? '')).map(([n, p]) => ({ n, id: /^cli:\/\/([^/]+)/i.exec(p.baseUrl)[1] }))
1695
+ const missing = CLIS ? clis.filter((x) => !CLIS.find((k) => k.id === x.id)?.installed).map((x) => x.n) : []
1696
+ $('i-note').textContent = !d ? '' : [d.keys ? 'This file has API keys in it.' : 'No API keys in this file: add them under Providers (Edit) after importing.', missing.length && movePick.i.has('providers') ? `Not installed here, so they come in switched off: ${missing.join(', ')}. Switching one on asks to install it.` : ''].filter(Boolean).join(' ')
1697
+ }
1698
+ $('x-go').onclick = async () => {
1699
+ const r = await api('/api/export', { parts: [...movePick.x], keys: $('x-keys').checked }).catch((e) => (toast(e.message, true), null))
1700
+ if (!r) return
1701
+ const a = h('a', { href: URL.createObjectURL(new Blob([JSON.stringify(r, null, 2)], { type: 'application/json' })), download: `heartcode-settings-${new Date().toISOString().slice(0, 10)}.json` })
1702
+ document.body.append(a)
1703
+ a.click()
1704
+ a.remove()
1705
+ toast(`exported ${[...movePick.x].length} part${movePick.x.size === 1 ? '' : 's'}${$('x-keys').checked ? ', with your API keys: keep the file private' : ''}`)
1706
+ }
1707
+ $('i-pick').onclick = () => $('i-file').click()
1708
+ $('i-file').onchange = async (e) => {
1709
+ const f = e.target.files[0]
1710
+ e.target.value = ''
1711
+ if (!f) return
1712
+ let data
1713
+ try {
1714
+ data = JSON.parse(await f.text())
1715
+ if (data?.heartcode !== 'settings') throw new Error()
1716
+ } catch {
1717
+ importing = null
1718
+ drawMove()
1719
+ return toast(`${f.name} isn't a HeartCode settings file`, true)
1720
+ }
1721
+ importing = { name: f.name, data }
1722
+ movePick.i = new Set(MOVE_PARTS.map(([k]) => k).filter((k) => data[k] && Object.keys(data[k]).length))
1723
+ $('i-name').textContent = `${f.name}${data.from ? ` · from HeartCode ${data.from}` : ''}`
1724
+ if (!CLIS) loadClis() // which of its CLIs are installed here
1725
+ drawMove()
1726
+ }
1727
+ $('i-go').onclick = async () => {
1728
+ if (!importing) return
1729
+ const r = await act('/api/import', { data: importing.data, parts: [...movePick.i] })
1730
+ if (!r) return
1731
+ const t = r.report
1732
+ const said = [t.providers != null && `${t.providers} provider${t.providers === 1 ? '' : 's'}`, t.models != null && `${t.models} model${t.models === 1 ? '' : 's'} added to the list`, t.mcp != null && `${t.mcp} MCP server${t.mcp === 1 ? '' : 's'}`, t.skills != null && `${t.skills} skill${t.skills === 1 ? '' : 's'}`, t.prompts != null && `${t.prompts} prompt change${t.prompts === 1 ? '' : 's'}`].filter(Boolean)
1733
+ toast(`imported: ${said.join(', ')}${t.cliOff.length ? ` · ${t.cliOff.length} CLI${t.cliOff.length === 1 ? '' : 's'} not installed here, left off` : ''}${t.skipped ? ` · ${t.skipped} model${t.skipped === 1 ? '' : 's'} skipped (no provider)` : ''}`, false, 8000)
1734
+ importing = null
1735
+ $('i-name').textContent = ''
1736
+ drawMove()
1737
+ }
1738
+
1647
1739
  // --- Providers & models ---
1648
1740
  const PRESETS = [
1649
1741
  ['openrouter', 'OpenRouter', 'https://openrouter.ai/api/v1', 'hundreds of models'],
@@ -1671,6 +1763,7 @@ $('p-url').oninput = () => (drawPresets(), drawCliNote())
1671
1763
  // adds each as a provider at cli://<its name>; one that isn't installed installs from here (its log shown
1672
1764
  // as it goes, ticked once it's in), then is signed in to in a terminal
1673
1765
  let CLIS = null
1766
+ let clisAsked = false
1674
1767
  let cliPoll = null
1675
1768
  const CLI_PICKS = new Set()
1676
1769
  let cliTouched = false // ticks changed by hand: installed ones aren't ticked again by themselves
@@ -1682,6 +1775,8 @@ function loadClis() {
1682
1775
  for (const k of list) if (k.installed && !cliAdded(k.id) && (!cliTouched || was.get(k.id) === false)) CLI_PICKS.add(k.id) // ticked: what's here, and one just installed
1683
1776
  drawClis()
1684
1777
  if ($('p-form').open) drawCliNote()
1778
+ drawMove() // an import's CLIs: installed here or not
1779
+ redraw() // Providers: which CLIs aren't installed
1685
1780
  clearTimeout(cliPoll)
1686
1781
  if (list.some((k) => k.installing || k.pending) && $('cli-form').open) cliPoll = setTimeout(loadClis, list.some((k) => k.installing) ? 1500 : 700) // an install's log; versions still being asked
1687
1782
  }, (e) => toast(e.message, true))
@@ -1877,7 +1972,35 @@ const redraw = () => S && !redrawing && (redrawing = requestAnimationFrame(() =>
1877
1972
  // the providers ticked: those with a model ticked (a provider's own box ticks all of its models shown)
1878
1973
  const selProviders = () => [...new Set([...TICKED].map((k) => splitKey(k).provider))].filter((n) => S?.providers.some((p) => p.name === n))
1879
1974
  const offOf = (names) => S.providers.filter((p) => names.includes(p.name))
1880
- const switchProviders = (names, on) => act('/api/provider/on', { names, on }, `${names.length === 1 ? names[0] : `${names.length} providers`} ${on ? 'on' : 'off'}${on ? '' : ': HeartCode skips their models'}`)
1975
+ // a coding CLI provider's CLI ('claude'…), and whether it's installed here (unknown until loadClis: yes)
1976
+ const cliIdOf = (p) => /^cli:\/\/([^/]+)/i.exec(p?.baseUrl ?? '')?.[1]
1977
+ const notInstalled = (p) => Boolean(cliIdOf(p) && CLIS && !CLIS.find((k) => k.id === cliIdOf(p))?.installed)
1978
+ // on, except the CLIs not installed here: those are said, and left off
1979
+ const saidLeft = (r) => r?.notInstalled?.length && toast(`${r.notInstalled.join(', ')} ${r.notInstalled.length === 1 ? "isn't" : "aren't"} installed on this computer: left off (switch one on to install it)`, true, 7000)
1980
+ const switchProviders = async (names, on) => saidLeft(await act('/api/provider/on', { names, on }, `${names.length === 1 ? names[0] : `${names.length} providers`} ${on ? 'on' : 'off'}${on ? '' : ': HeartCode skips their models'}`))
1981
+ // A CLI that isn't installed here (imported from another computer), switched on: installed first, asked;
1982
+ // on once it's in
1983
+ async function installThenOn(p) {
1984
+ const k = CLIS.find((x) => x.id === cliIdOf(p))
1985
+ if (!k?.install) {
1986
+ toast(`${k?.title ?? p.name} isn't installed, and nothing here can install it${k?.needs ? ` (needs ${k.needs})` : ''}: opening its page`, true, 7000)
1987
+ return k?.page && window.open(k.page, '_blank', 'noopener')
1988
+ }
1989
+ if (!confirm(`${k.title} isn't installed on this computer. Install it now, then switch ${p.name} on?\n\nThis runs: ${k.install}`)) return
1990
+ await api('/api/cli/install', { id: k.id }).catch((e) => toast(e.message, true))
1991
+ job(`install-${k.id}`, { where: ['catalog'], what: `Installing ${k.title}`, detail: 'then it switches on' })
1992
+ for (;;) {
1993
+ await new Promise((r) => setTimeout(r, 2000))
1994
+ const list = await api('/api/clis').catch(() => null)
1995
+ const now = list?.find((x) => x.id === k.id)
1996
+ if (!now || now.installing) continue
1997
+ CLIS = list
1998
+ job(`install-${k.id}`)
1999
+ if (!now.installed) return toast(`${k.title} didn't install: ${now.error || 'see + Add CLIs'}`, true, 9000)
2000
+ toast(`${k.title} installed. Sign in once with "${k.login}" in a terminal if it asks.`, false, 7000)
2001
+ return switchProviders([p.name], true)
2002
+ }
2003
+ }
1881
2004
  // the top button: the ticked providers when some are, else all; off while any of them is on
1882
2005
  function onAllLabel() {
1883
2006
  const sel = selProviders()
@@ -1890,7 +2013,7 @@ $('on-all').onclick = () => {
1890
2013
  const sel = selProviders()
1891
2014
  if (sel.length) return switchProviders(sel, !offOf(sel).some((p) => !p.off))
1892
2015
  const on = !S?.providers.some((p) => !p.off)
1893
- act('/api/provider/on', { on }, on ? 'every provider is on' : 'every provider is off: HeartCode skips their models until you turn one on')
2016
+ act('/api/provider/on', { on }, on ? 'every provider is on' : 'every provider is off: HeartCode skips their models until you turn one on').then(saidLeft)
1894
2017
  }
1895
2018
  // the folds, on the sections there (nothing built again); a search shows them all open
1896
2019
  function applyFolds() {
@@ -1960,13 +2083,15 @@ const MEANS = {
1960
2083
  502: '502: the provider (or a proxy before it) couldn\'t reach the model',
1961
2084
  503: '503: the model or provider is unavailable now',
1962
2085
  504: '504: the provider timed out',
2086
+ 'answered with an error': 'the request went through, but its answer is an error: not enough credits, upgrade your plan, a model that isn\'t available… (as text, not as an error code)',
2087
+ "didn't answer": 'the request went through, but it didn\'t answer the question (asked to reply "OK"): an image or audio link, a safety verdict, something else altogether. Likely not a chat model',
1963
2088
  empty: 'it answered, but with no text at all',
1964
2089
  'no answer': 'no answer within the test timeout (Tests wait, above the list)',
1965
2090
  failed: 'it failed without a status code (a lost connection, an unreadable reply…)',
1966
2091
  }
1967
2092
  // What a test came to, in a word: works, its status code (402, 429…), empty, no answer or failed;
1968
2093
  // null while it runs or before it's tested
1969
- const outcome = (r) => (!r || r.going ? null : r.ok ? 'works' : r.status ? String(r.status) : r.kind === 'empty' || (!r.kind && /nothing/.test(r.error)) ? 'empty' : r.kind === 'timeout' || (!r.kind && /within/.test(r.error)) ? 'no answer' : 'failed') // kind: said by the server (older results: their words)
2094
+ const outcome = (r) => (!r || r.going ? null : r.ok ? 'works' : r.kind === 'said-error' ? 'answered with an error' : r.kind === 'off-task' ? "didn't answer" : r.status ? String(r.status) : r.kind === 'empty' || (!r.kind && /nothing/.test(r.error)) ? 'empty' : r.kind === 'timeout' || (!r.kind && /within/.test(r.error)) ? 'no answer' : 'failed') // kind: said by the server (older results: their words)
1970
2095
  // The Works? cell: the last result (cut short, all of it on hover) and Test.
1971
2096
  function triedCell(t) {
1972
2097
  const r = TRIES[keyOf(t)]
@@ -1975,7 +2100,7 @@ function triedCell(t) {
1975
2100
  : r.going ? ['going', 'testing…', 'sending it a short message']
1976
2101
  : r.ok && r.toolsOk === false ? ['ok', `✓ ${(r.ms / 1000).toFixed(1)}s · ✗ tools`, `it answers ("${r.reply}"), but it couldn't do a small job with a tool, so it's a poor choice for work: ${r.toolsWhy}${secs}`]
1977
2102
  : r.ok ? ['ok', `✓ ${(r.ms / 1000).toFixed(1)}s`, `works: it answered "${r.reply}"${r.toolsOk ? ', and did a small job with a tool' : ''}${secs}`]
1978
- : ['bad', `✗ ${outcome(r)}`, `doesn't work: ${r.error}${secs}`] // the reason on hover
2103
+ : ['bad', `✗ ${{ 'answered with an error': 'error reply', "didn't answer": 'off-topic' }[outcome(r)] ?? outcome(r)}`, `doesn't work: ${r.error}${secs}`] // short in the cell, the reason on hover
1979
2104
  return h('div', { className: 'try ' + cls }, h('span', { className: 'msg', textContent: text, title: about }))
1980
2105
  }
1981
2106
  function showTried(t) {
@@ -2221,9 +2346,10 @@ function drawProviders(s) {
2221
2346
  else loadModels(p.name, MODELS[p.name]?.off)
2222
2347
  }
2223
2348
  for (const k of [...TICKED]) if (!s.providers.some((p) => p.name === splitKey(k).provider)) TICKED.delete(k) // a provider deleted: its ticks go
2349
+ if (!CLIS && !clisAsked && s.providers.some(cliIdOf)) (clisAsked = true), loadClis() // which CLIs are installed here (tagged, asked to install)
2224
2350
  const view = catView(s)
2225
2351
  // built again only when what's shown changed; the rest is marked on the rows there
2226
- const stamp = JSON.stringify([view.map((x) => [x.p.name, x.p.off, x.p.baseUrl, x.p.key, x.p.added, x.m.loading ?? false, x.m.error ?? '', x.m.off ?? false, x.m.list?.length ?? 0, x.ids.join('\n')]), catKind, onOnly, freeOnly])
2352
+ const stamp = JSON.stringify([view.map((x) => [x.p.name, x.p.off, x.p.baseUrl, x.p.key, x.p.added, x.m.loading ?? false, x.m.error ?? '', x.m.off ?? false, x.m.list?.length ?? 0, x.ids.join('\n'), notInstalled(x.p)]), catKind, onOnly, freeOnly])
2227
2353
  if (stamp !== catStamp) buildCatalog(view, s)
2228
2354
  catStamp = stamp
2229
2355
  markCatalog(s)
@@ -2471,6 +2597,7 @@ function buildCatalog(view, s) {
2471
2597
  h('div', { className: 'who' },
2472
2598
  h('span', { className: 'name' }, provIcon(p.name), p.name),
2473
2599
  p.off ? h('span', { className: 'tag', textContent: 'off' }) : null,
2600
+ notInstalled(p) ? h('span', { className: 'tag err', textContent: 'not installed', title: `${p.name}'s CLI isn't installed on this computer: switch it on to install it` }) : null,
2474
2601
  m.off ? h('span', { className: 'tag', textContent: 'list off', title: "its list isn't loaded: add a model by its name, in the box on the right" }) : m.loading ? h('span', { className: 'tag', textContent: 'loading…' }) : m.error ? h('span', { className: 'tag err', textContent: "can't list its models", title: m.error }) : h('span', { className: 'tag', textContent: `${m.list.length} model${m.list.length === 1 ? '' : 's'}` }),
2475
2602
  h('span', { className: 'tag inlist', hidden: true }),
2476
2603
  h('span', { className: 'meta mono', textContent: p.baseUrl, title: `${p.baseUrl} · key ${p.key || 'none'}` })),
@@ -2582,7 +2709,11 @@ function drawPicks(view = catView()) {
2582
2709
  } else if (e.target.matches('.pick-all')) {
2583
2710
  for (const r of sec.querySelectorAll('.mwrap')) e.target.checked ? TICKED.add(`${name}/${r.dataset.model}`) : TICKED.delete(`${name}/${r.dataset.model}`)
2584
2711
  drawPicks()
2585
- } else if (e.target.matches('.p-on')) act('/api/provider/on', { name, on: e.target.checked }, e.target.checked ? `${name} is on` : `${name} is off: HeartCode skips its models`)
2712
+ } else if (e.target.matches('.p-on')) {
2713
+ const p = provOf(sec)
2714
+ if (e.target.checked && notInstalled(p)) return (e.target.checked = false), installThenOn(p) // installed first
2715
+ act('/api/provider/on', { name, on: e.target.checked }, e.target.checked ? `${name} is on` : `${name} is off: HeartCode skips its models`).then((r) => !r && redraw()) // refused: the switch as it was
2716
+ }
2586
2717
  })
2587
2718
  list.addEventListener('click', async (e) => {
2588
2719
  const { sec, w } = where(e.target)
@@ -3998,6 +4129,7 @@ function render(s) {
3998
4129
  for (const [key, r] of Object.entries(TRIES)) if (!r.going && placeOf(...key.split(/\/(.*)/s)) === undefined) delete TRIES[key] // off your list: its result too
3999
4130
  drawProviders(s)
4000
4131
  applyFolds()
4132
+ drawMove()
4001
4133
  drawMine(s)
4002
4134
  drawUsing(s)
4003
4135
  drawGeneral(s)
package/src/settings.js CHANGED
@@ -14,6 +14,7 @@ import { DEFAULT_SERVERS, mcpAuth, serverName } from './mcp.js'
14
14
  import { sections, BUILTIN_PROMPTS, prompt, reloadPrompts } from './prompts.js'
15
15
  import { Client } from './client.js'
16
16
  import { clisInfo, installCli, cliOf, cliUrl, CLIS } from './clis.js'
17
+ import { onPath } from './spawn.js'
17
18
  import { clip, TOOL_DEFS } from './tools.js'
18
19
  import { loadProfile, strategy, profilePath, profileFrom } from './probe.js'
19
20
  import { loadPrices, priceOf, limitsOf } from './usage.js'
@@ -264,7 +265,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
264
265
  // doesn't stop them. Each result is kept in ~/.heart/model-tests.json ("provider/model" → { ok, ms,
265
266
  // reply | error, status, at }) and sent to the page as it comes.
266
267
  const TESTS_FILE = path.join(HOME, 'model-tests.json')
267
- const tests = readJson(TESTS_FILE, {})
268
+ const tests = Object.fromEntries(Object.entries(readJson(TESTS_FILE, {})).map(([k, r]) => [k, judged(r)])) // older results judged the same way
268
269
  let saving = null
269
270
  const gone = new Set() // tests forgotten here since the last write
270
271
  // merged with the file as it is now: another HeartCode's results written meanwhile stay
@@ -309,7 +310,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
309
310
  const reply = (r.content || '').trim()
310
311
  if (!reply && !r.toolCalls.length) return { ok: false, kind: 'empty', ms: Date.now() - t0, error: `it answered with nothing${r.usage?.completion_tokens ? ` (${r.usage.completion_tokens} tokens it said it wrote)` : ''}` }
311
312
  const ms = Date.now() - t0
312
- return { ok: true, ms, reply: reply.slice(0, 80), ...(testedOf({ provider, model })?.mode === 'tools' && !c.cli && (await toolTest(c, stop))) }
313
+ const verdict = judged({ ok: true, ms, reply: reply.slice(0, 200) })
314
+ if (!verdict.ok) return verdict // an error said as its answer, or no answer to the question: no tool test
315
+ return { ...verdict, ...(testedOf({ provider, model })?.mode === 'tools' && !c.cli && (await toolTest(c, stop))) }
313
316
  } catch (e) {
314
317
  if (stop?.aborted) return { stopped: true }
315
318
  return { ok: false, ms: Date.now() - t0, status: e.status ?? null, ...(e.name === 'TimeoutError' && { kind: 'timeout' }), error: e.name === 'TimeoutError' ? noAnswer() : whyFailed(e), ...(e.retryAfter > 0 && { retryAfter: Number(e.retryAfter) }) }
@@ -581,6 +584,17 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
581
584
  autoPick()
582
585
  return state()
583
586
  },
587
+ // Settings to take to another machine (Advanced → Import & export): the parts asked for, keys only
588
+ // when asked; and a file like it taken in, merged (nothing of yours is removed)
589
+ 'POST /api/export': ({ parts = [], keys = false } = {}) => exportSettings(cfg, parts, keys),
590
+ 'POST /api/import': ({ data, parts = [] } = {}) => {
591
+ const report = importSettings(cfg, data, parts)
592
+ save('model')
593
+ reloadPrompts()
594
+ forgetTests()
595
+ autoPick()
596
+ return { ...state(), report }
597
+ },
584
598
  // the coding CLIs (clis.js): which are installed, how to install the rest, an install going on
585
599
  'GET /api/clis': () => clisInfo(),
586
600
  // several CLIs added at once (Add CLIs): each a provider named after it; one added already is skipped
@@ -634,13 +648,16 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
634
648
  'POST /api/provider/on': ({ name, names, on }) => {
635
649
  const list = names ?? (name !== undefined ? [name] : Object.keys(cfg.providers))
636
650
  for (const n of list) if (!cfg.providers[n]) throw new Error(`no provider "${n}"`)
637
- for (const p of list.map((n) => cfg.providers[n])) {
651
+ // a coding CLI not installed here (one imported from another machine) stays off until it is
652
+ const missing = on ? list.filter((n) => { const id = cliOf(cfg.providers[n].baseUrl); return id && !onPath(CLIS[id].bin) }) : []
653
+ if (missing.length && list.length === 1) throw Object.assign(new Error(`${CLIS[cliOf(cfg.providers[missing[0]].baseUrl)].title} isn't installed on this computer: install it first (+ Add CLIs)`), { notInstalled: missing[0] })
654
+ for (const p of list.filter((n) => !missing.includes(n)).map((n) => cfg.providers[n])) {
638
655
  if (on) delete p.off
639
656
  else p.off = true
640
657
  }
641
658
  save('model') // the running sessions' model lists follow at once
642
659
  autoPick()
643
- return state()
660
+ return { ...state(), ...(missing.length && { notInstalled: missing }) }
644
661
  },
645
662
  // A model added by its name (one the provider doesn't list, or its list is off): remembered under
646
663
  // the provider, not put in the list (clicked there, it is). models: several at once.
@@ -1238,7 +1255,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1238
1255
  let raw = ''
1239
1256
  for await (const ch of req) {
1240
1257
  raw += ch
1241
- if (raw.length > 1_000_000) return send(413, { error: 'too big' })
1258
+ if (raw.length > (url.pathname === '/api/import' ? 50_000_000 : 1_000_000)) return send(413, { error: 'too big' }) // an import may carry skills
1242
1259
  }
1243
1260
  if (req.method === 'POST' && !/^application\/json/.test(req.headers['content-type'] ?? '')) return send(415, { error: 'JSON only' })
1244
1261
  send(200, await route(raw ? JSON.parse(raw) : {}))
@@ -1283,6 +1300,164 @@ function warm() {
1283
1300
  step(0)
1284
1301
  }
1285
1302
 
1303
+ // --- Import & export: settings taken to another machine ---
1304
+ // A file: { heartcode: 'settings', version: 1, from (HeartCode's version), at, parts…, keys (whether
1305
+ // keys are in it) }. Parts: providers (CLIs too), models (the list in order, when one fails, the
1306
+ // helpers, models' abilities set by hand), mcp (servers), skills (your own, their files), prompts
1307
+ // (your changes to HeartCode's prompts). Without keys: no provider key, no MCP server's env or headers.
1308
+ export const EXPORT_PARTS = ['providers', 'models', 'mcp', 'skills', 'prompts']
1309
+ const listOf = (cfg) => [...(cfg.providers[cfg.provider] && cfg.model ? [{ provider: cfg.provider, model: cfg.model }] : []), ...rotationOf(cfg).then]
1310
+ const profileClient = (cfg, t) => cfg.providers[t.provider] && new Client({ baseUrl: cfg.providers[t.provider].baseUrl, model: t.model })
1311
+ // a folder's text files, by their path in it (a skill's); nothing big or binary
1312
+ function filesOf(dir, base = dir, out = {}) {
1313
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
1314
+ const f = path.join(dir, e.name)
1315
+ if (e.isDirectory()) filesOf(f, base, out)
1316
+ else if (e.isFile() && fs.statSync(f).size < 2_000_000) {
1317
+ const text = fs.readFileSync(f, 'utf8')
1318
+ if (!text.includes('\u0000')) out[path.relative(base, f).split(path.sep).join('/')] = text
1319
+ }
1320
+ }
1321
+ return out
1322
+ }
1323
+ export function exportSettings(cfg, parts, keys) {
1324
+ const want = new Set(parts.filter((p) => EXPORT_PARTS.includes(p)))
1325
+ if (!want.size) throw new Error('pick at least one part to export')
1326
+ const out = { heartcode: 'settings', version: 1, from: VERSION, at: new Date().toISOString(), keys: Boolean(keys) }
1327
+ if (want.has('providers')) out.providers = Object.fromEntries(Object.entries(cfg.providers).filter(([n]) => n !== cfg.adhoc).map(([n, p]) => [n, { baseUrl: p.baseUrl, ...(keys && p.apiKey && { apiKey: p.apiKey }), ...(p.off && { off: true }), ...(p.list === false && { list: false }), ...(p.models?.length && { models: p.models }) }]))
1328
+ if (want.has('models')) {
1329
+ const list = listOf(cfg)
1330
+ const { then, ...rotation } = rotationOf(cfg)
1331
+ const profiles = {}
1332
+ for (const t of list) {
1333
+ const c = profileClient(cfg, t)
1334
+ const p = c && loadProfile(c)
1335
+ if (p?.source === 'you' && p.set && Object.keys(p.set).length) profiles[`${t.provider}/${t.model}`] = p.set // set by hand (not a CLI's own)
1336
+ }
1337
+ out.models = { list, rotation, ...(cfg.helpers && { helpers: cfg.helpers }), ...(cfg.helpersAuto && { helpersAuto: true }), ...(Object.keys(profiles).length && { profiles }) }
1338
+ }
1339
+ if (want.has('mcp')) {
1340
+ const servers = readJson(path.join(HOME, 'mcp.json'), {})?.mcpServers ?? {}
1341
+ out.mcp = Object.fromEntries(Object.entries(servers).map(([n, sv]) => { const { env, headers, ...rest } = sv; return [n, keys ? sv : rest] }))
1342
+ }
1343
+ if (want.has('skills')) {
1344
+ const dir = skillsDir()
1345
+ out.skills = {}
1346
+ for (const e of fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }) : []) {
1347
+ if (e.isDirectory()) out.skills[e.name] = filesOf(path.join(dir, e.name))
1348
+ else if (e.name.endsWith('.md')) out.skills[e.name.slice(0, -3)] = { 'SKILL.md': fs.readFileSync(path.join(dir, e.name), 'utf8'), single: true }
1349
+ }
1350
+ }
1351
+ if (want.has('prompts')) {
1352
+ out.prompts = {}
1353
+ for (const file of PROMPT_FILES) if (fs.existsSync(ownPrompts(file))) out.prompts[file] = Object.fromEntries(sections(fs.readFileSync(ownPrompts(file), 'utf8')))
1354
+ }
1355
+ return out
1356
+ }
1357
+ // Merged in: what the file has is added, or updates the one of the same name; nothing of yours goes.
1358
+ // A coding CLI not installed here comes in switched off (switching it on asks to install it first).
1359
+ // { providers, models, skipped, cliOff: [names], mcp, skills, prompts }: what was taken in.
1360
+ export function importSettings(cfg, data, parts) {
1361
+ if (data?.heartcode !== 'settings') throw new Error("that isn't a HeartCode settings file")
1362
+ const want = new Set(parts.filter((p) => EXPORT_PARTS.includes(p) && data[p]))
1363
+ if (!want.size) throw new Error('pick at least one part that the file has')
1364
+ const report = { cliOff: [] }
1365
+ if (want.has('providers')) {
1366
+ report.providers = 0
1367
+ for (const [raw, p] of Object.entries(data.providers ?? {})) {
1368
+ const name = safeName(raw)
1369
+ if (!name || typeof p?.baseUrl !== 'string') continue
1370
+ const id = cliOf(p.baseUrl)
1371
+ if (/^cli:/i.test(p.baseUrl) && !id) continue // a CLI this HeartCode doesn't know
1372
+ const had = cfg.providers[name] ?? {}
1373
+ const next = { ...had, baseUrl: p.baseUrl.replace(/\/+$/, ''), ...(p.apiKey && { apiKey: String(p.apiKey) }) }
1374
+ const models = [...new Set([...(had.models ?? []), ...(Array.isArray(p.models) ? p.models.map(String) : [])])]
1375
+ if (models.length) next.models = models
1376
+ if (p.list === false) next.list = false
1377
+ if (p.off) next.off = true
1378
+ if (id && !onPath(CLIS[id].bin)) (next.off = true), report.cliOff.push(name)
1379
+ cfg.providers[name] = next
1380
+ forgetList(name)
1381
+ report.providers++
1382
+ }
1383
+ }
1384
+ if (want.has('models')) {
1385
+ const m = data.models
1386
+ const mine = listOf(cfg)
1387
+ const had = new Set(mine.map((t) => `${t.provider}/${t.model}`))
1388
+ const add = (Array.isArray(m.list) ? m.list : []).map((t) => ({ provider: safeName(t?.provider), model: String(t?.model ?? '').trim() })).filter((t) => t.model && cfg.providers[t.provider] && !had.has(`${t.provider}/${t.model}`) && had.add(`${t.provider}/${t.model}`))
1389
+ report.skipped = (Array.isArray(m.list) ? m.list : []).filter((t) => !cfg.providers[safeName(t?.provider)]).length // their provider isn't here (not in the file, or not imported)
1390
+ const all = [...mine, ...add]
1391
+ if (all.length) {
1392
+ const opts = mine.length ? rotationOf(cfg) : { ...rotationOf(cfg), ...Object.fromEntries(Object.entries(m.rotation ?? {}).filter(([k, v]) => (k === 'retries' ? Number.isInteger(v) && v >= 1 && v <= 20 : ROTATION[k]?.includes(v)))) } // yours kept when you had a list
1393
+ Object.assign(cfg, { provider: all[0].provider, model: all[0].model, rotation: { on: opts.on, retries: opts.retries, next: opts.next, then: all.slice(1) } })
1394
+ }
1395
+ report.models = add.length
1396
+ if (m.helpers && typeof m.helpers === 'object') cfg.helpers = helpersOf({ ...m.helpers, ...cfg.helpers })
1397
+ if (m.helpersAuto && !cfg.helpers) cfg.helpersAuto = true
1398
+ for (const [k, set] of Object.entries(m.profiles ?? {})) {
1399
+ const t = { provider: k.slice(0, k.indexOf('/')), model: k.slice(k.indexOf('/') + 1) }
1400
+ const c = profileClient(cfg, t)
1401
+ if (!c || !set || typeof set !== 'object') continue
1402
+ const p = loadProfile(c) ?? profileFrom(c, limitsOf(t.provider, c.baseUrl, t.model))
1403
+ if (p.source !== 'you' && p.source !== 'cli') writeJson(profilePath(c), { ...p, set, source: 'you' }), (report.set = (report.set ?? 0) + 1) // yours set by hand stay; a CLI's are its own
1404
+ }
1405
+ }
1406
+ if (want.has('mcp')) {
1407
+ const file = path.join(HOME, 'mcp.json')
1408
+ const now = readJson(file, {}) ?? {}
1409
+ const servers = { ...now.mcpServers }
1410
+ report.mcp = 0
1411
+ for (const [n, sv] of Object.entries(data.mcp ?? {})) if (sv && typeof sv === 'object' && (sv.command || sv.url)) (servers[n] = { ...servers[n], ...sv }), report.mcp++
1412
+ writeJson(file, { ...now, mcpServers: servers })
1413
+ }
1414
+ if (want.has('skills')) {
1415
+ report.skills = 0
1416
+ for (const [raw, files] of Object.entries(data.skills ?? {})) {
1417
+ const name = safeName(raw)
1418
+ if (!name || !files || typeof files !== 'object') continue
1419
+ let wrote = 0
1420
+ if (files.single) {
1421
+ fs.mkdirSync(skillsDir(), { recursive: true })
1422
+ fs.writeFileSync(path.join(skillsDir(), `${name}.md`), String(files['SKILL.md'] ?? ''))
1423
+ wrote++
1424
+ } else {
1425
+ const dir = path.join(skillsDir(), name)
1426
+ for (const [rel, text] of Object.entries(files)) {
1427
+ const to = path.resolve(dir, rel)
1428
+ if (!to.startsWith(dir + path.sep) || typeof text !== 'string') continue // nothing outside its folder
1429
+ fs.mkdirSync(path.dirname(to), { recursive: true })
1430
+ fs.writeFileSync(to, text)
1431
+ wrote++
1432
+ }
1433
+ }
1434
+ if (wrote) report.skills++
1435
+ }
1436
+ }
1437
+ if (want.has('prompts')) {
1438
+ report.prompts = 0
1439
+ for (const [file, secs] of Object.entries(data.prompts ?? {})) {
1440
+ if (!PROMPT_FILES.includes(file) || !secs || typeof secs !== 'object') continue
1441
+ for (const [name, text] of Object.entries(secs)) if (typeof text === 'string') setPrompt(file, name, text), report.prompts++
1442
+ }
1443
+ }
1444
+ return report
1445
+ }
1446
+
1447
+ // A test's answer, judged: asked to reply with just "OK", a model that answered with an error as its
1448
+ // text (a provider's "not enough credits", a CLI's "Model … is not available") or with something else
1449
+ // altogether (an image link, a safety verdict, a persona's greeting) doesn't work for HeartCode,
1450
+ // though the request went through. OK with more around it (thinking written into the answer) works.
1451
+ const SAID_ERROR = /\b(error|exception|execution failed|not available|unavailable|not supported|insufficient|not enough credits|enough credits|top ?up|upgrade your plan|recharg\w*|quota|rate.?limit\w*|unauthori[sz]ed|forbidden|invalid (api )?key|access denied|not allowed|exceeded|billing|payment required)\b/i
1452
+ export function judged(r) {
1453
+ if (!r?.ok || typeof r.reply !== 'string') return r
1454
+ const text = r.reply.trim()
1455
+ if (/^\W*ok(ay)?\W*$/i.test(text)) return r
1456
+ if (SAID_ERROR.test(text)) return { ...r, ok: false, kind: 'said-error', error: `it answered with an error: "${clip(text.replace(/\s+/g, ' '), 160)}"` }
1457
+ if (!/\bok(ay)?\b/i.test(text)) return { ...r, ok: false, kind: 'off-task', error: `it didn't answer the question (asked to reply "OK"): "${clip(text.replace(/\s+/g, ' '), 160)}"` }
1458
+ return r
1459
+ }
1460
+
1286
1461
  // This machine's IPv4 addresses on its networks (Wi-Fi, Ethernet, a VPN), not the loopback one
1287
1462
  const addresses = () => Object.values(os.networkInterfaces()).flat().filter((n) => n && n.family === 'IPv4' && !n.internal).map((n) => n.address)
1288
1463
 
package/src/tools.js CHANGED
@@ -573,13 +573,7 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
573
573
  const secs = Number(wait) > 0 ? Number(wait) : background ? 3 : 30
574
574
  const before = snapshot(s)
575
575
  const job = startJob(s.root, cmd)
576
- // its latest output line beside it, read a few times a second (the label is re-read every frame)
577
- let last = ''
578
- let readAt = 0
579
- s.ui.spinner(() => {
580
- if (Date.now() - readAt > 250) [readAt, last] = [Date.now(), tailLines(job, 3).filter((l) => l.trim()).at(-1)?.trim() ?? '']
581
- return `running ${clip(cmd, 50)}${last ? ` › ${clip(last, 60)}` : ''}`
582
- })
576
+ s.ui.spinner('running a command') // the command itself is the step above, in the conversation
583
577
  await waitFor(job, secs * 1000, signal)
584
578
  s.ui.stopSpin()
585
579
  if (!job.exited) {
@@ -623,7 +617,7 @@ async function backgroundTool(s, a, signal) {
623
617
  return was ? `Stopped #${job.id} (${job.command}).` : `#${job.id} had already exited with ${job.code}.`
624
618
  }
625
619
  if (Number(a.wait) > 0) {
626
- s.ui.spinner(`waiting on #${job.id} ${clip(job.command, 60)}`)
620
+ s.ui.spinner('waiting for a background command')
627
621
  await waitFor(job, Number(a.wait) * 1000, signal)
628
622
  s.ui.stopSpin()
629
623
  }
@@ -1200,7 +1194,7 @@ async function webTool(s, name, args, signal) {
1200
1194
  log('research', `"${what}": ${saved.length} saved page(s) offered first`)
1201
1195
  return prompt('agent/research-saved', { query: what, pages: saved.map((r) => `- ${r.title} — ${r.url} (read ${r.fetched}${r.used_for ? `; used for: ${r.used_for}` : ''}) → ${r.file}`).join('\n') })
1202
1196
  }
1203
- s.ui.spinner(`searching: ${clip(what, 60)}`)
1197
+ s.ui.spinner('searching the web')
1204
1198
  const out = await webSearch(what, { signal })
1205
1199
  if (s.root && !s.noResearch && !/^(error:|no results)/.test(out)) {
1206
1200
  const { file } = saveSearch(s.root, what, out)
@@ -1208,7 +1202,7 @@ async function webTool(s, name, args, signal) {
1208
1202
  }
1209
1203
  return out
1210
1204
  }
1211
- s.ui.spinner(`fetching ${clip(what, 60)}`)
1205
+ s.ui.spinner('reading a web page')
1212
1206
  const allowed = hostsIn(s.task) // a local or private host you named: may be fetched
1213
1207
  if (!s.root || s.noResearch) return await webFetch(what, { start: args.start, signal, allowed }) // nothing kept (--no-memory)
1214
1208
  const page = await fetchPage(what, { signal, allowed })
@@ -1411,7 +1405,7 @@ async function callMcp(s, server, tool, a, signal) {
1411
1405
  s.mcpRead.add(`${server.name}\n${tool}`)
1412
1406
  }
1413
1407
  const done = await s.mcpGate?.() // a helper may be using the MCP servers (a browser): its turn first
1414
- s.ui.spinner(`${server.name} · ${tool}`)
1408
+ s.ui.spinner(`using ${server.name}`)
1415
1409
  const started = Date.now()
1416
1410
  let r
1417
1411
  try {
package/src/ui.js CHANGED
@@ -202,6 +202,7 @@ function sliceCols(text, from, to) {
202
202
  return out
203
203
  }
204
204
  const FRAMES = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
205
+ const BEAT = [1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0] // the ♥ while it works, a frame (80 ms) each: lub, dub, rest
205
206
 
206
207
  // 75000 → "1 minute 15 seconds"; the two biggest units: "5 hours 33 minutes", "2 days 3 hours"
207
208
  export function duration(ms) {
@@ -830,6 +831,12 @@ export class UI {
830
831
  if (was && was !== dialog) was.close?.()
831
832
  this.render()
832
833
  }
834
+ // a question's long text moved by n lines (drawn in #question, which keeps it in range)
835
+ #scrollText(n) {
836
+ const p = this.menu.pick
837
+ p.textTop = Math.max(0, Math.min((p.textTop ?? 0) + n, p.textMax))
838
+ this.render()
839
+ }
833
840
  // Text to read (a command's answer: /help, /context, /diff…) in a dialog: ↑/↓, PgUp/PgDn, Home/End
834
841
  // and the wheel scroll it, Esc closes it (and toggle: a key's action, as the key that opened it).
835
842
  // Without the full screen: printed.
@@ -938,6 +945,18 @@ export class UI {
938
945
  const r = wrapWords(t, w)
939
946
  return r.length <= n ? r : [...r.slice(0, n - 1), `${fit(r[n - 1], w - 1)}…`]
940
947
  }
948
+ // a picker's text longer than its room (the whole changelog on /update): a window of it, which
949
+ // PgUp/PgDn and the wheel move (↑↓ still choose), and where it is under it
950
+ const scrolled = (lines, n) => {
951
+ if (!pick) return clip(lines, n)
952
+ const room = Math.max(1, n - 1)
953
+ pick.textMax = Math.max(0, lines.length - room)
954
+ if (!pick.textMax) return lines
955
+ pick.textTop = Math.max(0, Math.min(pick.textTop ?? 0, pick.textMax))
956
+ pick.textPage = Math.max(1, room - 1)
957
+ const t = pick.textTop
958
+ return [...lines.slice(t, t + room), c.faint(`${t + 1}–${Math.min(lines.length, t + room)} of ${lines.length} lines · PgUp/PgDn or the wheel scroll`)]
959
+ }
941
960
  let at = 0
942
961
  return {
943
962
  title: long || title.length > 200 ? '' : title,
@@ -969,7 +988,7 @@ export class UI {
969
988
  })
970
989
  const want = cards ? blocks.flat().length : Math.max(1, m.items.length)
971
990
  const least = Math.min(want, cards ? Math.max(...blocks.map((b) => b.length)) + 2 : 3) // the choices give way first, down to this
972
- const top0 = clip(intro, Math.max(3, h - tail.length - filter.length - least))
991
+ const top0 = scrolled(intro, Math.max(3, h - tail.length - filter.length - least))
973
992
  const room = Math.max(1, h - tail.length - filter.length - top0.length)
974
993
  let list
975
994
  if (!choices.length) list = [c.faint(`nothing matches "${rl.line}"`)]
@@ -997,21 +1016,6 @@ export class UI {
997
1016
  }
998
1017
  }
999
1018
 
1000
- // The plan (todo list) while it works, kept in sight under the spinner: how much is done, and three
1001
- // of its steps (what's being done, then what's next); the rest on a key (show_plan).
1002
- #todoLines(cols) {
1003
- const todos = this.todos?.() ?? []
1004
- const open = todos.filter((t) => t.status !== 'completed')
1005
- if (!open.length) return []
1006
- const done = todos.length - open.length
1007
- const mark = { pending: c.muted('☐'), in_progress: c.info('◐'), completed: c.faint('☑'), stuck: c.warn('⚠') }
1008
- 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
1009
- // one line: how far it is, the step being done now (the whole plan: show_plan)
1010
- const now = todos.find((t) => t.status === 'in_progress') ?? open[0]
1011
- const k = this.keyFor('show_plan')
1012
- return [fit(` ${c.muted(`Plan ${done}/${todos.length}`)} ${mark[now.status]} ${c.info(now.content)}${by(now)}${k ? c.faint(` · ${k} all of it`) : ''}`, cols)]
1013
- }
1014
-
1015
1019
  // The whole plan in a box (show_plan, /todos): every step and its state; the key closes it again.
1016
1020
  showPlan() {
1017
1021
  const todos = this.todos?.() ?? []
@@ -1188,6 +1192,7 @@ export class UI {
1188
1192
  if (b & 64) {
1189
1193
  if ((b & 0xc3) !== 64 && (b & 0xc3) !== 65) return
1190
1194
  if (this.dialog) return this.dialog.key?.({ name: b & 1 ? 'down' : 'up', wheel: true }), this.render()
1195
+ if (this.asking && this.menu.pick?.textMax) return this.#scrollText(b & 1 ? 3 : -3) // a question's long text
1191
1196
  return this.#wheel(b & 1 ? -1 : 1) // 64 up, 65 down
1192
1197
  }
1193
1198
  if ((b & 3) !== 0 && !up) return // the left button only (a release says 3 in some terminals)
@@ -1382,7 +1387,9 @@ export class UI {
1382
1387
  const asked = this.asking && !this.histOn && rl
1383
1388
  // The input box: the rows around the cursor, at most INPUT_ROWS; the rules count the rest.
1384
1389
  const typing = !this.asking && rl && this.mainPrompt // working: what's typed meanwhile shows in the box
1385
- 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 } }
1390
+ // while it works on your message, the input's ♥ beats (lub-dub, then a rest), a beat a second
1391
+ const prompt = typing && this.busySince && this.timer && !BEAT[this.frame % BEAT.length] ? this.mainPrompt.replace('♥', '♡') : this.mainPrompt
1392
+ const input = asked ? layoutInput(this.mainPrompt ?? ' ', '', 0, cols) : this.asking || typing ? layoutInput(this.asking ? rl._prompt : prompt, rl.line, rl.cursor, cols) : { rows: [''], cur: { row: 0, col: 0 } }
1386
1393
  const first = Math.max(0, Math.min(input.cur.row - INPUT_ROWS + 1, input.rows.length - INPUT_ROWS))
1387
1394
  const box = input.rows.slice(first, first + INPUT_ROWS)
1388
1395
  const inputRows = box.length
@@ -1398,15 +1405,17 @@ export class UI {
1398
1405
  const request = this.requestSince?.()
1399
1406
  const label = this.#label()
1400
1407
  const waiting = request && !(this.tokenAt >= request) && this.beforeRetry === undefined && Date.now() - request > 2000
1401
- const status = waiting ? `${/^(working|thinking|answering)$/.test(plainOf(label)) ? '' : `${label} · `}waiting for ${this.waitingFor?.() || 'the model'}` : label
1408
+ const status = String(waiting ? `${/^(working|thinking|answering)$/.test(plainOf(label)) ? '' : `${label} · `}waiting for ${this.waitingFor?.() || 'the model'}` : label).replace(/\s*[\r\n\t]+\s*/g, ' ') // never a line break or tab to the terminal: it would write on a row the screen doesn't know about, left there
1402
1409
  const timer = this.busySince ? `${short(this.worked())} · Esc twice to stop` : ''
1403
- // one row; a long status (a retry, a command's last line) wraps instead of being cut
1404
- wrapParts(`${status}${timer ? ` · ${timer}` : ''}`, cols - 2).forEach((r, i) => bottom.push(fit(`${i ? ' ' : c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(r)}`, cols)))
1405
- // helpers at work (agent.js keeps them in this.helpers: label → what it's doing), then the plan
1406
- const helpers = [...this.helpers]
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))
1408
- if (helpers.length > 6) bottom.push(c.faint(` … ${helpers.length - 5} more`))
1409
- bottom.push(...this.#todoLines(cols))
1410
+ // One row, always: what's happening in a few words, how far the plan is, helpers at work, the
1411
+ // time. What's being done shows in the conversation above (its steps); nothing more here.
1412
+ const todos = this.todos?.() ?? []
1413
+ const done = todos.filter((t) => t.status === 'completed').length
1414
+ const extra = [todos.length && done < todos.length ? `plan ${done}/${todos.length}` : '', this.helpers.size ? `${this.helpers.size} helper${this.helpers.size === 1 ? '' : 's'}` : ''].filter(Boolean)
1415
+ const what = plainOf(status).split(' › ')[0]
1416
+ const tail = [...extra, timer].filter(Boolean).join(' · ')
1417
+ const room = Math.max(10, cols - 3 - width(tail) - (tail ? 3 : 0))
1418
+ bottom.push(...Array(rows >= 24 ? 3 : 1).fill(''), fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(width(what) > room ? `${fit(what, room - 1)}…` : what)}${tail ? c.faint(` · ${tail}`) : ''}`, cols)) // apart from the conversation above it: three empty rows (one on a short screen)
1410
1419
  }
1411
1420
  if (this.scroll) bottom.push(c.dim(` ↓ ${Number.isFinite(this.scroll) ? this.scroll : 'more'} lines below · held here for reading${this.keyFor('scroll_bottom') ? ` · ${this.keyFor('scroll_bottom')} to the bottom` : ''}`))
1412
1421
  if (this.ahead.length) {
@@ -1429,6 +1438,7 @@ export class UI {
1429
1438
  if (this.noticeText) bottom.push(fit(this.noticeMark ? `${c.warn(this.noticeMark)} ${c.muted(this.noticeText)}` : ` ${c.muted(this.noticeText)}`, cols))
1430
1439
  if (menu.on && !asked) bottom.push(...this.#menuLines(cols))
1431
1440
  bottom.push(first ? note(first, '↑') : rule)
1441
+ for (let i = 0; i < bottom.length; i++) bottom[i] = bottom[i].replace(/[\r\n\t]/g, ' ') // a row is one row: a break in a label (a helper's, a command's) would be written on a row the screen doesn't track
1432
1442
  const head = [...(this.tabBar?.(cols) ?? []), ...(this.header?.(cols) ?? [])].map((l) => fit(l, cols))
1433
1443
  const inputTop = rows - below.length - inputRows + 1 // first row of the input
1434
1444
  const avail = Math.max(0, inputTop - 1 - bottom.length - head.length)
@@ -1581,6 +1591,7 @@ export class UI {
1581
1591
  return this.render()
1582
1592
  }
1583
1593
  }
1594
+ if ((key.name === 'pageup' || key.name === 'pagedown') && this.menu.pick?.textMax) return this.#scrollText(key.name === 'pageup' ? -this.menu.pick.textPage : this.menu.pick.textPage)
1584
1595
  if (key.name === 'pageup' || key.name === 'pagedown') return this.scrollBy(key.name === 'pageup' ? this.page() : -this.page())
1585
1596
  const m = this.menu
1586
1597
  const it = m.on && m.items[m.sel]
@@ -2389,6 +2400,7 @@ export class UI {
2389
2400
  // are indented under it, kept apart from the others')
2390
2401
  // note: says what happened (learned, reviewed, removed), no result to wait for; ok false: a bad one
2391
2402
  step(name, detail = '', who = '', { sub = '', note = false, ok = true } = {}) {
2403
+ detail = String(detail ?? '').replace(/\s*[\r\n\t]+\s*/g, ' ') // one line (a multi-line command): a step is a row, and a break in it scrambles the rows around it
2392
2404
  const key = sub
2393
2405
  if (note) {
2394
2406
  if (this.afterBlock) this.gap()
@@ -2426,6 +2438,7 @@ export class UI {
2426
2438
  // got, summed over a group (90 lines, 12 matches); files: the files a search found them in.
2427
2439
  // Called again for the same step: its words are added (an edit: "formatted with prettier").
2428
2440
  result(text = '', { ok = true, refused = false, none = false, n, unit, files, sub = '' } = {}) {
2441
+ text = String(text ?? '').replace(/\s*[\r\n\t]+\s*/g, ' ') // one line, as the step's
2429
2442
  const st = this.steps?.get(sub)
2430
2443
  const item = st?.items.at(-1)
2431
2444
  if (!this.full || !st || st.log !== this.log) {
package/src/update.js CHANGED
@@ -43,15 +43,19 @@ export function installKind() {
43
43
  export const UPDATE_COMMANDS = { npm: 'npm install -g heartcode@latest', pnpm: 'pnpm add -g heartcode@latest', yarn: 'yarn global add heartcode@latest', bun: 'bun add -g heartcode@latest' }
44
44
  export const packageDir = PKG
45
45
 
46
- // The changelog's sections from the newest down to (not including) the one running, or ''.
46
+ // The whole changelog of the version on offer, newest first (scrolled in the dialog): from its npm
47
+ // package (the version you'd get; GitHub's main branch can be behind npm), else GitHub. '' if none.
48
+ // The versions since the one running are marked new.
47
49
  export async function whatsNew(current, latest) {
48
- try {
49
- const r = await fetch('https://raw.githubusercontent.com/p32929/HeartCode/main/CHANGELOG.md', { signal: AbortSignal.timeout(8000) })
50
- const text = await r.text()
51
- const start = text.indexOf(`## ${latest}`)
52
- const end = text.indexOf(`## ${current}`)
53
- return start >= 0 ? text.slice(start, end > start ? end : undefined).trim().replace(/\n {2,}(?=\S)/g, ' ') : '' // a list item's wrapped lines joined: the box wraps it to its width
54
- } catch {
55
- return ''
50
+ for (const url of [`https://cdn.jsdelivr.net/npm/heartcode@${latest}/CHANGELOG.md`, `https://unpkg.com/heartcode@${latest}/CHANGELOG.md`, 'https://raw.githubusercontent.com/p32929/HeartCode/main/CHANGELOG.md']) {
51
+ try {
52
+ const r = await fetch(url, { signal: AbortSignal.timeout(8000) })
53
+ const text = r.ok ? await r.text() : ''
54
+ const start = text.indexOf('\n## ')
55
+ if (start < 0) continue
56
+ const body = text.slice(start + 1).trim().replace(/\n {2,}(?![-*] )(?=\S)/g, ' ') // a list item's wrapped lines joined (the box wraps it to its width); a sub-item stays its own
57
+ return body.replace(/^## (\d+\.\d+\.\d+)(.*)$/gm, (line, v, rest) => (newer(v, current) ? `## ${v}${rest} · new` : line))
58
+ } catch {}
56
59
  }
60
+ return ''
57
61
  }