heartcode 0.1.32 → 0.1.35

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,41 @@
2
2
 
3
3
  What changed in each version of HeartCode, newest first.
4
4
 
5
+ ## 0.1.35 (2026-11-02)
6
+
7
+ - Settings page, Your list: every column sorts by the value it shows, ↑ smallest first and ↓
8
+ largest first, the first click the useful way (Model A→Z, Provider your ranking, Context and
9
+ Abilities most first, Tools/Thinking/Images with first, prices cheapest first, Works? fastest
10
+ first). Works? sorts by the test's time; failed and untested models (no time), unknown prices and
11
+ contexts are last either way (untested before failed). Clicks still stack sorts (each breaks the
12
+ ties of the ones before). A sort kept from before is converted.
13
+ - A sort redraws the table once (it was redrawn again half a second later, when the page's own
14
+ saved sort came back from the server as a change); the header spins until the new order is drawn,
15
+ and while tests run the sort line says the order moves as results come in.
16
+ - Stop (and every button in the table) works at the first click while tests run: the table was
17
+ redrawn at every result, replacing buttons between a click's press and release. Now it's redrawn
18
+ at most every 400 ms, never while the mouse button is down, Stop keeps its place and acts on press.
19
+
20
+ ## 0.1.34 (2026-11-02)
21
+
22
+ - Model tests on the settings page (Test all, Test selected, a row's Test and Hello) wait 10
23
+ seconds for an answer by default, not 90; the Timeout box next to Test all changes it (1 to 600
24
+ seconds, kept in the config as testTimeout).
25
+ - Sorting by Works? puts the fastest working model first (by its test's time), then the untested,
26
+ then the ones that don't work.
27
+
28
+ ## 0.1.33 (2026-11-01)
29
+
30
+ - Text you may need can be selected and copied, not only the conversation: drag to select (copied
31
+ when you let go), double-click to copy a word (an address, a path, a model's name). Inside a
32
+ dialog (the settings page's address, /help, /context, /diff, the background logs, a permission's
33
+ command, the choices), the header's folder (a double click copies the whole path, also when it's
34
+ shown cut), the input box and the status bar. Not the tab bar, the borders or the key hints. A
35
+ plain click in a dialog still does its job (a tab in the background logs). /help lists it, and
36
+ Shift+drag (Option+drag on macOS) for the terminal's own selection.
37
+ - Windows: the browser opens through Windows' URL handler (rundll32 url.dll,FileProtocolHandler)
38
+ instead of `cmd /c start`, for /settings and an MCP server's sign-in page.
39
+
5
40
  ## 0.1.32 (2026-11-01)
6
41
 
7
42
  - Dialogs: pickers (`/select_model`, `/resume`, `/rewind`, `/export`…), permission questions, typed
package/README.md CHANGED
@@ -124,11 +124,13 @@ On **Models → Providers**:
124
124
  On **Models → Your list**:
125
125
 
126
126
  1. **Sort them by context and abilities.** Click the *Abilities* column, then *Context*: the
127
- models that can do the most, with the biggest context window, come first. Click
128
- **Save order** to keep it.
127
+ models that can do the most come first, the biggest context window first among those (each
128
+ column clicked breaks the ties of the ones before; click one again to reverse it, a third time to
129
+ drop it). Click **Save order** to keep it.
129
130
  2. **Rearrange a bit more.** Drag a row to move it. #1 is the one HeartCode uses; the others are
130
131
  its fallbacks, tried in order.
131
132
  3. **Test them** (optional): **Test all** sends each a short message and shows which really answer.
133
+ Each test waits up to 10 seconds; the **Timeout** box next to it changes that.
132
134
 
133
135
  If a model says *not found* in models.dev, **Retry** looks it up again, or **Set up** tells
134
136
  HeartCode what it can do.
package/bin/heartcode.js CHANGED
@@ -173,6 +173,9 @@ function keysHelp(keys = {}) {
173
173
  [[forAct('scroll_up'), forAct('scroll_down')].filter(Boolean).join(' / '), 'scroll the conversation a page'],
174
174
  [[forAct('scroll_line_up'), forAct('scroll_line_down')].filter(Boolean).join(' / '), 'scroll a few lines'],
175
175
  ['Ctrl+C', 'stop · twice quits HeartCode'],
176
+ ['Drag', 'select and copy: the conversation, a dialog, the folder, the input, the status bar'],
177
+ ['Double-click', 'copy the word under it (an address, a path, a model)'],
178
+ [process.platform === 'darwin' ? 'Option+drag' : 'Shift+drag', "the terminal's own selection, past HeartCode's"],
176
179
  ].filter(([k]) => k)
177
180
  return rows
178
181
  }
@@ -244,7 +247,7 @@ class App {
244
247
  if (!this.ui.noUser)
245
248
  mcp.onSignIn = (name, url) => {
246
249
  this.ui.print(`${c.info('↗')} ${c.bold(name)} ${c.muted('needs you to sign in; opening your browser…')}\n ${c.faint(url)}`)
247
- const [cmd, ...args] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['cmd', '/c', 'start', '', url] : ['xdg-open', url]
250
+ const [cmd, ...args] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['rundll32', 'url.dll,FileProtocolHandler', url] : ['xdg-open', url]
248
251
  spawnSync(cmd, args, { stdio: 'ignore' })
249
252
  this.ui.spinner(`waiting for you to sign in to ${name} in the browser · Esc to stop`)
250
253
  }
@@ -1164,9 +1167,11 @@ function useModel(app, { provider, model }) {
1164
1167
  // The settings page (/settings): on while its dialog is (one at a time).
1165
1168
  let settingsPage = null
1166
1169
 
1170
+ // The browser, with a page. Windows: its URL handler (cmd's start mangles a URL whose arguments
1171
+ // it reads as its own, and wants a quoted empty title first).
1167
1172
  function openBrowser(url) {
1168
1173
  if (process.env.HEART_NO_BROWSER) return
1169
- const [cmd, ...args] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['cmd', '/c', 'start', '', url] : ['xdg-open', url]
1174
+ const [cmd, ...args] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['rundll32', 'url.dll,FileProtocolHandler', url] : ['xdg-open', url]
1170
1175
  spawnSync(cmd, args, { stdio: 'ignore' })
1171
1176
  }
1172
1177
 
@@ -1781,6 +1786,7 @@ async function repl(app, f = {}) {
1781
1786
  // Pinned to the top of the screen; /clear_chat and scrolling leave it alone.
1782
1787
  const home = process.env.HOME
1783
1788
  const where = home && app.root.startsWith(home) ? '~' + app.root.slice(home.length) : app.root
1789
+ ui.folder = app.root // what a double click on the header's folder copies
1784
1790
  ui.header = (cols = 100) => [
1785
1791
  `${c.brand('♥')} ${c.bright(c.bold('HeartCode'))} ${c.faint(VERSION)} ${c.muted(where.length > cols - 16 ? '…' + where.slice(-(cols - 17)) : where)}`,
1786
1792
  [['/', 'run a command'], ['@', 'attach a file'], ...(ui.voiceReady?.() ? [['Space', 'talk (voice)']] : []), [NEWLINE_KEY, 'add a new line'], ['Esc', 'stop'], ['Shift+Tab', 'change permissions']].map(([k, d]) => `${c.muted(k)} ${c.faint(d)}`).join(c.ghost(' · ')),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heartcode",
3
- "version": "0.1.32",
3
+ "version": "0.1.35",
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/config.js CHANGED
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url'
6
6
  export const HOME = process.env.HEART_HOME || path.join(os.homedir(), '.heart')
7
7
  export const CONFIG_FILE = path.join(HOME, 'config.json')
8
8
 
9
- const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search']
9
+ const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout']
10
10
  const LOCAL_NAMES = { 11434: 'ollama', 1234: 'lmstudio', 8080: 'llamacpp' }
11
11
 
12
12
  export function readJson(file, fallback) {
package/src/settings.html CHANGED
@@ -473,6 +473,12 @@
473
473
  .setting .t span { display: block; margin-top: 2px; color: var(--muted); font-size: 13px; line-height: 1.45; text-wrap: pretty; }
474
474
  .setting select, .setting input { flex: none; width: 240px; }
475
475
  .settings-col .card.wide { grid-column: 1 / -1; }
476
+ /* a sort being applied: its header spins, the table dims */
477
+ #mt.sorting { opacity: .55; transition: opacity .1s; pointer-events: none; }
478
+ button.sorting::after { content: ''; display: inline-block; width: 9px; height: 9px; margin-left: 6px; vertical-align: -1px; border: 1.5px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: spin .6s linear infinite; }
479
+ .sort-live { color: var(--warn); }
480
+ .test-wait { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--muted); white-space: nowrap; }
481
+ .test-wait input { width: 64px; height: 28px; padding: 2px 8px; font-size: 12.5px; text-align: right; }
476
482
  .ws-url { display: flex; gap: 8px; margin-top: 10px; }
477
483
  .ws-url input { flex: 1; min-width: 0; }
478
484
  .ws-addr { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 6px; }
@@ -998,6 +1004,7 @@ function job(id, state) {
998
1004
  }
999
1005
  // a panel's place for them: made empty, filled now and kept up to date by job()
1000
1006
  const jobSlot = (where) => fillSlot(h('div', { className: 'job-slot', 'data-where': where }))
1007
+ let tableJobs = null // the Your models table's (made once, put back in each time the table is drawn)
1001
1008
  function fillSlot(slot) {
1002
1009
  const mine = [...JOBS.values()].filter((j) => j.where.includes(slot.dataset.where))
1003
1010
  for (const el of [...slot.children]) if (!mine.some((j) => j.id === el.dataset.job)) el.remove()
@@ -1017,7 +1024,13 @@ function fillSlot(slot) {
1017
1024
  stop.hidden = !j.stop
1018
1025
  stop.textContent = j.stopping ? 'Stopping…' : 'Stop'
1019
1026
  stop.disabled = Boolean(j.stopping)
1020
- stop.onclick = () => (j.stop(), job(j.id, { stopping: true }))
1027
+ // at the press, not the release: a stop that's wanted now (and the keyboard's Enter/Space still click)
1028
+ const halt = (e) => {
1029
+ e.preventDefault()
1030
+ if (!JOBS.get(j.id)?.stopping) j.stop(), job(j.id, { stopping: true })
1031
+ }
1032
+ stop.onpointerdown = halt
1033
+ stop.onclick = halt
1021
1034
  el.querySelector('.bar').classList.toggle('unknown', !known)
1022
1035
  el.querySelector('.bar i').style.width = known ? `${Math.round((100 * (j.done ?? 0)) / j.total)}%` : ''
1023
1036
  }
@@ -1389,7 +1402,7 @@ const MEANS = {
1389
1402
  503: '503: the model or provider is unavailable now',
1390
1403
  504: '504: the provider timed out',
1391
1404
  empty: 'it answered, but with no text at all',
1392
- 'no answer': 'no answer within 90 seconds',
1405
+ 'no answer': 'no answer within the test timeout (next to Test all)',
1393
1406
  failed: 'it failed without a status code (a lost connection, an unreadable reply…)',
1394
1407
  }
1395
1408
  // What a test came to, in a word: works, its status code (402, 429…), empty, no answer or failed;
@@ -1412,7 +1425,27 @@ function showTried(t) {
1412
1425
  if (!TRIES[keyOf(t)]?.going) mineSoon() // a result: the counts by result (and a sort by it) change
1413
1426
  }
1414
1427
  let mineFrame = 0
1415
- const mineSoon = () => (mineFrame ||= requestAnimationFrame(() => ((mineFrame = 0), S && drawMine(S))))
1428
+ // While tests run, results come many a second: the table is drawn again at most every 400 ms (drawn
1429
+ // every frame, its buttons were replaced between a click's press and release, and the click was lost)
1430
+ // And never while the mouse button is down: a click's press and release then land on the same button.
1431
+ let mineLast = 0
1432
+ let pressed = false
1433
+ let drawAfterPress = false
1434
+ addEventListener('pointerdown', () => (pressed = true), true)
1435
+ for (const ev of ['pointerup', 'pointercancel']) addEventListener(ev, () => {
1436
+ pressed = false
1437
+ if (drawAfterPress) (drawAfterPress = false), setTimeout(mineSoon, 0) // after the click it finishes
1438
+ }, true)
1439
+ const mineSoon = () => {
1440
+ if (mineFrame) return
1441
+ const later = testingAll ? Math.max(0, mineLast + 400 - Date.now()) : 0
1442
+ mineFrame = setTimeout(() => requestAnimationFrame(() => {
1443
+ mineFrame = 0
1444
+ if (pressed) return (drawAfterPress = true) // drawn once it's let go
1445
+ mineLast = Date.now()
1446
+ S && drawMine(S)
1447
+ }), later)
1448
+ }
1416
1449
  // Tests run on the settings server (closing this page doesn't stop them; their results are kept
1417
1450
  // there for next time): this page asks for them and shows what the server says as it goes.
1418
1451
  async function tryModel(t) {
@@ -1924,18 +1957,23 @@ function buildCatalog(s) {
1924
1957
  // --- Your models page: the list as a table; sorted by several columns at once (each a tie-break
1925
1958
  // for the ones before it), the sort kept in this browser ---
1926
1959
  const can = (t) => ({ tools: t.tested ? t.tested.mode === 'tools' : t.known?.tools !== false, thinking: Boolean(t.tested ? t.tested.thinking : t.known?.thinking), images: Boolean(t.tested ? t.tested.vision : t.known?.images) })
1927
- // how: text (A to Z first), cheap (lowest first), else most first
1960
+ // Every column sorts by the value it shows: up (↑) smallest first, down (↓) largest first. first: the
1961
+ // direction of the first click (the useful one). get: the value; null when there's none (no price, no
1962
+ // context, no time because it failed or wasn't tested): last, either way; missing: their order then.
1963
+ // words: what each direction means, for the "Sorted by" line.
1928
1964
  const COLS = {
1929
- model: { label: 'Model', how: 'text', get: (t) => t.model },
1930
- provider: { label: 'Provider', how: 'rank', get: (t) => RANKED.get(t.provider) }, // by your ranking of the providers
1931
- context: { label: 'Context', get: (t) => t.tested?.context ?? t.known?.context ?? 0 },
1932
- abilities: { label: 'Abilities', get: (t) => Object.values(can(t)).filter(Boolean).length },
1933
- tools: { label: 'Tools', get: (t) => can(t).tools },
1934
- thinking: { label: 'Thinking', get: (t) => can(t).thinking },
1935
- images: { label: 'Images', get: (t) => can(t).images },
1936
- input: { label: 'In $/M', how: 'cheap', get: (t) => t.price?.input ?? null },
1937
- output: { label: 'Out $/M', how: 'cheap', get: (t) => t.price?.output ?? null },
1938
- works: { label: 'Works?', get: (t) => { const r = TRIES[keyOf(t)]; return !r || r.going ? 1 : r.ok ? 2 : 0 } }, // tested and working first; not tested; not working
1965
+ model: { label: 'Model', first: 'up', get: (t) => t.model, words: ['A→Z', 'Z→A'] },
1966
+ // a provider's priority: your ranking's first is the highest
1967
+ provider: { label: 'Provider', first: 'down', get: (t) => -(RANKED.get(t.provider) ?? 1e6), words: ['your ranking, reversed', 'your ranking'] },
1968
+ context: { label: 'Context', first: 'down', get: (t) => t.tested?.context ?? t.known?.context ?? null, words: ['smallest first', 'biggest first'] },
1969
+ abilities: { label: 'Abilities', first: 'down', get: (t) => Object.values(can(t)).filter(Boolean).length, words: ['fewest first', 'most first'] },
1970
+ tools: { label: 'Tools', first: 'down', get: (t) => can(t).tools, words: ['without first', 'with first'] },
1971
+ thinking: { label: 'Thinking', first: 'down', get: (t) => can(t).thinking, words: ['without first', 'with first'] },
1972
+ images: { label: 'Images', first: 'down', get: (t) => can(t).images, words: ['without first', 'with first'] },
1973
+ input: { label: 'In $/M', first: 'up', get: (t) => t.price?.input ?? null, words: ['cheapest first', 'priciest first'] },
1974
+ output: { label: 'Out $/M', first: 'up', get: (t) => t.price?.output ?? null, words: ['cheapest first', 'priciest first'] },
1975
+ // its test's time (seconds, as shown); failed or not tested: no time, at the end (not tested before failed)
1976
+ works: { label: 'Works?', first: 'up', get: (t) => { const r = TRIES[keyOf(t)]; return r?.ok && !r.going ? r.ms ?? 0 : null }, missing: (t) => { const r = TRIES[keyOf(t)]; return !r || r.going ? 0 : 1 }, words: ['fastest first', 'slowest first'] },
1939
1977
  }
1940
1978
  let SORT = []
1941
1979
  // your ranking of the providers, best first (kept: savePref); a provider not ranked yet comes after, A to Z
@@ -1966,20 +2004,28 @@ $('pr-save').onclick = () => {
1966
2004
  RANK = [...list, ...RANK.filter((n) => !list.includes(n))] // providers not in your list now keep their place for later
1967
2005
  savePref('rank', RANK)
1968
2006
  $('pr').close()
1969
- setSort(SORT.some((x) => x.key === 'provider') ? SORT : [{ key: 'provider', dir: 'up' }, ...SORT]) // sorted by it now
2007
+ setSort(SORT.some((x) => x.key === 'provider') ? SORT : [{ key: 'provider', dir: 'down' }, ...SORT]) // sorted by it now
1970
2008
  }
1971
- const firstDir = (key) => (COLS[key].how ? 'up' : 'down') // up: A to Z, low to high
2009
+ const firstDir = (key) => COLS[key].first // up: A to Z, low to high
1972
2010
  function setSort(next) {
1973
2011
  SORT = next
1974
- savePref('sort', SORT)
2012
+ savePref('sorts', SORT)
1975
2013
  drawMine(S)
1976
2014
  }
1977
- // a column's header: first click adds it (after those already sorted by), the second flips it, the third drops it
1978
- function clickSort(key) {
2015
+ // A column's header: the first click adds it (after the ones already sorted by, to break their ties),
2016
+ // the second flips it, the third drops it. Until the new order is drawn, the header spins and the table
2017
+ // dims (the next frame: the click shows at once).
2018
+ function clickSort(key, btn) {
1979
2019
  const at = SORT.find((x) => x.key === key)
1980
- if (!at) return setSort([...SORT, { key, dir: firstDir(key) }])
1981
- if (at.dir === firstDir(key)) return setSort(SORT.map((x) => (x === at ? { key, dir: at.dir === 'up' ? 'down' : 'up' } : x)))
1982
- setSort(SORT.filter((x) => x !== at))
2020
+ const next = !at ? [...SORT, { key, dir: firstDir(key) }]
2021
+ : at.dir === firstDir(key) ? SORT.map((x) => (x === at ? { key, dir: at.dir === 'up' ? 'down' : 'up' } : x))
2022
+ : SORT.filter((x) => x !== at)
2023
+ btn?.classList.add('sorting')
2024
+ $('mt')?.classList.add('sorting')
2025
+ requestAnimationFrame(() => setTimeout(() => {
2026
+ setSort(next)
2027
+ $('mt')?.classList.remove('sorting')
2028
+ }, 0))
1983
2029
  }
1984
2030
  let RANKED = new Map() // provider → its place in the ranking, for one sort
1985
2031
  function sorted(order) {
@@ -1987,15 +2033,16 @@ function sorted(order) {
1987
2033
  const cmp = (a, b, { key, dir }) => {
1988
2034
  let x = COLS[key].get(a)
1989
2035
  let y = COLS[key].get(b)
2036
+ if (x == null && y == null) return (COLS[key].missing?.(a) ?? 0) - (COLS[key].missing?.(b) ?? 0)
1990
2037
  if (x === y) return 0
1991
- if (x == null) return 1 // unknown (no price): last, either way
2038
+ if (x == null) return 1 // none (no price, no time): last, either way
1992
2039
  if (y == null) return -1
1993
2040
  const r = typeof x === 'string' ? byName(x, y) : Number(x) - Number(y)
1994
2041
  return dir === 'up' ? r : -r
1995
2042
  }
1996
2043
  return order.map((t, i) => ({ t, i })).sort((a, b) => SORT.reduce((r, s) => r || cmp(a.t, b.t, s), 0) || a.i - b.i).map((x) => x.t)
1997
2044
  }
1998
- const dirText = (key, dir) => (key === 'provider' ? (dir === 'up' ? 'your ranking' : 'your ranking, reversed') : key === 'works' ? (dir === 'down' ? 'working first' : 'not working first') : COLS[key].how === 'text' ? (dir === 'up' ? 'A→Z' : 'Z→A') : COLS[key].how === 'cheap' ? (dir === 'up' ? 'cheapest first' : 'priciest first') : dir === 'down' ? 'most first' : 'least first')
2045
+ const dirText = (key, dir) => COLS[key].words[dir === 'up' ? 0 : 1] + (key === 'works' ? ' (then not tested, then not working)' : '')
1999
2046
  // The models ticked on the Your models page ("provider/model"), to remove several at once; the last
2000
2047
  // one ticked, so a Shift+click ticks the ones between
2001
2048
  const PICKED = new Set()
@@ -2027,7 +2074,7 @@ function drawMine(s) {
2027
2074
  // the order you see, saved as yours; the sort then goes (your own order from here on: drag on)
2028
2075
  const keep = (list, moved) => {
2029
2076
  SORT = []
2030
- savePref('sort', SORT)
2077
+ savePref('sorts', SORT)
2031
2078
  return saveOrder(withOff(list), list[0] !== order[0] ? `${moved ? '' : 'order saved: '}HeartCode now uses ${list[0].provider} · ${list[0].model}` : 'order saved')
2032
2079
  }
2033
2080
  // a row dragged (in the order shown, sorted or not)
@@ -2040,7 +2087,7 @@ function drawMine(s) {
2040
2087
  }
2041
2088
  const head = (key, num) => {
2042
2089
  const at = SORT.findIndex((x) => x.key === key)
2043
- return h('button', { type: 'button', className: (at >= 0 ? 'on ' : '') + (num ? 'num' : ''), title: `sort by ${COLS[key].label.toLowerCase()}`, onclick: () => clickSort(key) },
2090
+ return h('button', { type: 'button', className: (at >= 0 ? 'on ' : '') + (num ? 'num' : ''), title: `sort by ${COLS[key].label.toLowerCase()} too (after the ones already sorted by) · click again: reversed · again: not by it`, onclick: (e) => clickSort(key, e.currentTarget) },
2044
2091
  COLS[key].label, at >= 0 ? ` ${SORT[at].dir === 'up' ? '↑' : '↓'}${SORT.length > 1 ? at + 1 : ''}` : '')
2045
2092
  }
2046
2093
  const table = order.length ? h('ol', { className: 'mtable' + (order.length < 2 ? '' : ' drag') }) : null
@@ -2059,7 +2106,8 @@ function drawMine(s) {
2059
2106
  h('div', { className: 'mt-top' },
2060
2107
  h('div', { className: 'sorts' }, SORT.length
2061
2108
  ? ['Sorted by ', SORT.map(({ key, dir }, k) => h('span', { className: 'chip' }, `${k + 1}. ${COLS[key].label}: ${dirText(key, dir)}`, h('button', { type: 'button', textContent: '✕', 'aria-label': `stop sorting by ${COLS[key].label}`, onclick: () => setSort(SORT.filter((x) => x.key !== key)) })))]
2062
- : order.length > 1 ? 'Your order: #1 first, the next when one fails.' : ''),
2109
+ : order.length > 1 ? 'Your order: #1 first, the next when one fails.' : '',
2110
+ testingAll && SORT.some((x) => x.key === 'works') ? h('span', { className: 'sort-live' }, ' · tests still running: the order moves as their results come in') : null),
2063
2111
  PICKED.size ? h('button', { className: 'small danger', textContent: `Remove ${PICKED.size} selected`, onclick: removePicked }) : null,
2064
2112
  PICKED.size ? h('button', { className: 'small', textContent: `Test ${PICKED.size} selected`, disabled: testingAll, onclick: () => tryAll(order.filter((t) => PICKED.has(keyOf(t)))) }) : null,
2065
2113
  PICKED.size ? h('button', { className: 'small', textContent: 'Clear selection', onclick: () => (PICKED.clear(), drawMine(S)) }) : null,
@@ -2068,7 +2116,14 @@ function drawMine(s) {
2068
2116
  SORT.length ? h('button', { className: 'small', textContent: 'Clear sort', onclick: () => setSort([]) }) : null,
2069
2117
  order.length > 1 ? h('button', { className: 'small primary', textContent: 'Save order', title: 'save the order shown as your model order (#1 first)', onclick: () => keep(view) }) : null,
2070
2118
  order.length ? h('button', { className: 'small', textContent: 'Refresh from models.dev', title: 'ask models.dev again what each model can do: context, tools, thinking, images, price', onclick: () => lookUp() }) : null,
2071
- order.length ? h('button', { className: 'small', textContent: 'Test all', disabled: testingAll, title: 'send each a short message to see which really answer: every provider at once, a few from each (one at a time per 100 models)', onclick: () => tryAll(order) }) : null),
2119
+ order.length ? h('button', { className: 'small', textContent: 'Test all', disabled: testingAll, title: 'send each a short message to see which really answer: every provider at once, a few from each (one at a time per 100 models)', onclick: () => tryAll(order) }) : null,
2120
+ // how long a test waits for an answer (every model test: Test all, a row's Test and Hello)
2121
+ order.length ? h('label', { className: 'test-wait', title: 'how long a model test waits for its answer before it counts as failed' }, 'Timeout',
2122
+ h('input', { type: 'number', min: 1, max: 600, step: 1, value: S.settings.testTimeout ?? 10, 'aria-label': 'Test timeout in seconds', onchange: (e) => {
2123
+ const v = Math.round(Number(e.target.value))
2124
+ if (!(v >= 1 && v <= 600)) return (e.target.value = S.settings.testTimeout ?? 10), toast('a whole number of seconds, 1 to 600', true)
2125
+ act('/api/setting', { name: 'testTimeout', value: v }, `tests wait ${v} second${v === 1 ? '' : 's'} for an answer`)
2126
+ } }), 's') : null),
2072
2127
  // when the one in use fails, and what a new message starts with
2073
2128
  order.length > 1 ? h('div', { className: 'mt-rules' },
2074
2129
  h('span', { className: 'rule' },
@@ -2083,7 +2138,7 @@ function drawMine(s) {
2083
2138
  h('span', { className: 'hint', textContent: s.rotation.on === 'retries' ? 'A rate limit or outage: that model is tried again that many times first; any other error moves on at once.' : "Any error moves on at once, to another provider's model first." })) : null,
2084
2139
  order.length
2085
2140
  ? h('div', { className: 'mt-scroll' }, h('div', { className: 'mt' },
2086
- jobSlot('table'),
2141
+ (tableJobs ??= jobSlot('table')), // the same one every time: its Stop button isn't replaced under the mouse
2087
2142
  byOutcome.length ? h('div', { className: 'mt-outcomes' }, h('span', { textContent: 'Test results', title: 'click one to select those models; ↻ tests them again' }), byOutcome) : null,
2088
2143
  h('div', { className: 'mt-h' }, h('span'),
2089
2144
  h('input', { type: 'checkbox', checked: all, indeterminate: PICKED.size > 0 && !all, title: all ? 'select none' : 'select all', 'aria-label': 'select all', onchange: () => (all ? PICKED.clear() : view.forEach((t) => PICKED.add(keyOf(t))), (lastPicked = null), drawMine(S)) }),
@@ -2754,7 +2809,8 @@ function render(s) {
2754
2809
  $('free-only').checked = freeOnly
2755
2810
  FOLDED.clear()
2756
2811
  for (const n of Array.isArray(p.folded) ? p.folded : []) FOLDED.add(n)
2757
- SORT = Array.isArray(p.sort) ? p.sort.filter((x) => COLS[x?.key]) : []
2812
+ const flip = (x) => (['provider', 'works'].includes(x.key) ? { ...x, dir: x.dir === 'up' ? 'down' : 'up' } : x) // an older page's sort: these two ran the other way
2813
+ SORT = Array.isArray(p.sorts) ? p.sorts.filter((x) => COLS[x?.key]) : Array.isArray(p.sort) ? p.sort.filter((x) => COLS[x?.key]).map(flip) : []
2758
2814
  RANK = Array.isArray(p.rank) ? p.rank.filter((x) => typeof x === 'string') : []
2759
2815
  }
2760
2816
  S = s
package/src/settings.js CHANGED
@@ -127,7 +127,7 @@ const LIST_V = 2 // how a saved list was read (2: airforce's cents, Cloudflare's
127
127
  // The page's own choices (sorts, folded providers, the provider ranking): kept here, not in the
128
128
  // browser, whose storage is per address (a new port each time)
129
129
  const PREFS = path.join(HOME, 'settings-page.json')
130
- const PREF_KEYS = ['catSort', 'freeOnly', 'folded', 'sort', 'rank']
130
+ const PREF_KEYS = ['catSort', 'freeOnly', 'folded', 'sort', 'sorts', 'rank']
131
131
  function forgetList(...names) {
132
132
  const all = readJson(LISTS, {})
133
133
  if (!names.some((n) => n in all)) return
@@ -236,6 +236,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
236
236
  for (const key of Object.keys(tests)) if (!mine.has(key)) (delete tests[key]), gone++
237
237
  if (gone) saveTests()
238
238
  }
239
+ // How long a model test waits for its answer (cfg.testTimeout, seconds; the settings page sets it).
240
+ const testWait = () => (Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10) * 1000
241
+ const noAnswer = () => `no answer within ${testWait() / 1000} seconds`
239
242
  // Never throws: { ok, ms, reply } or { ok: false, ms, status, error }; { stopped } when stop
240
243
  // (a run's Stop) cancels it.
241
244
  async function tryOne({ provider, model }, stop) {
@@ -244,14 +247,14 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
244
247
  c.purpose = 'test'
245
248
  const t0 = Date.now()
246
249
  try {
247
- const signal = stop ? AbortSignal.any([AbortSignal.timeout(90_000), stop]) : AbortSignal.timeout(90_000)
250
+ const signal = stop ? AbortSignal.any([AbortSignal.timeout(testWait()), stop]) : AbortSignal.timeout(testWait())
248
251
  const r = await c.chat({ messages: [{ role: 'user', content: 'Reply with just the word OK.' }], stream: true }, { signal })
249
252
  const reply = (r.content || '').trim()
250
253
  if (!reply && !r.toolCalls.length) return { ok: false, ms: Date.now() - t0, error: `it answered with nothing${r.usage?.completion_tokens ? ` (${r.usage.completion_tokens} tokens it said it wrote)` : ''}` }
251
254
  return { ok: true, ms: Date.now() - t0, reply: reply.slice(0, 80) }
252
255
  } catch (e) {
253
256
  if (stop?.aborted) return { stopped: true }
254
- return { ok: false, ms: Date.now() - t0, status: e.status ?? null, error: e.name === 'TimeoutError' ? 'no answer within 90 seconds' : whyFailed(e), ...(e.retryAfter > 0 && { retryAfter: Number(e.retryAfter) }) }
257
+ return { ok: false, ms: Date.now() - t0, status: e.status ?? null, error: e.name === 'TimeoutError' ? noAnswer() : whyFailed(e), ...(e.retryAfter > 0 && { retryAfter: Number(e.retryAfter) }) }
255
258
  }
256
259
  }
257
260
  // result: kept and sent to the page (given: a test already made, as a run decided to end it)
@@ -360,7 +363,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
360
363
  model: cfg.model ?? null,
361
364
  order: [...(cfg.providers[cfg.provider] && cfg.model ? [{ provider: cfg.provider, model: cfg.model }] : []), ...rotationOf(cfg).then].map((t) => ({ ...t, tested: testedOf(t), known: knownOf(t), price: priceFor(t) })),
362
365
  rotation: (({ then, ...opts }) => opts)(rotationOf(cfg)),
363
- settings: { permissions: cfg.permissions ?? 'all', effort: cfg.effort ?? 'default', theme: cfg.theme ?? 'dark', context: cfg.context ?? null, ...Object.fromEntries(Object.keys(TOGGLES).map((k) => [k, cfg[k] !== false])), ...Object.fromEntries(LOG_SWITCHES.map((k) => [k, cfg[k] === true])), logDetail: cfg.logDetail === 'summary' ? 'summary' : 'full', logDays: logDays(cfg) },
366
+ settings: { permissions: cfg.permissions ?? 'all', effort: cfg.effort ?? 'default', theme: cfg.theme ?? 'dark', context: cfg.context ?? null, ...Object.fromEntries(Object.keys(TOGGLES).map((k) => [k, cfg[k] !== false])), ...Object.fromEntries(LOG_SWITCHES.map((k) => [k, cfg[k] === true])), logDetail: cfg.logDetail === 'summary' ? 'summary' : 'full', logDays: logDays(cfg), testTimeout: Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10 },
364
367
  logs: { runs: tilde(path.join(LOGS, 'runs')), requests: tilde(REQUESTS) },
365
368
  voice: cfg.voice ? JSON.stringify(cfg.voice, null, 2) : '',
366
369
  statusBar: cfg.statusBar === undefined ? null : cfg.statusBar, // false (off), a list of lines, or null (default)
@@ -383,6 +386,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
383
386
  'POST /api/prefs': ({ key, value }) => {
384
387
  if (!PREF_KEYS.includes(key)) throw new Error(`no such choice: ${key}`)
385
388
  writeJson(PREFS, { ...readJson(PREFS, {}), [key]: value })
389
+ shown = JSON.stringify(state()) // the page's own choice: not sent back to it as a change (a second redraw)
386
390
  return {}
387
391
  },
388
392
  'POST /api/clear-logs': () => ({ gone: clearLogs(), size: logSize() }),
@@ -552,7 +556,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
552
556
  const sent = { method: 'POST', url, headers: { 'content-type': 'application/json', ...(c.apiKey && { authorization: `Bearer ${mask(c.apiKey)}` }) }, body }
553
557
  const t0 = Date.now()
554
558
  try {
555
- const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...(c.apiKey && { authorization: `Bearer ${c.apiKey}` }) }, body: JSON.stringify(body), signal: AbortSignal.timeout(90_000) })
559
+ const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...(c.apiKey && { authorization: `Bearer ${c.apiKey}` }) }, body: JSON.stringify(body), signal: AbortSignal.timeout(testWait()) })
556
560
  const text = await res.text()
557
561
  let json = null
558
562
  try {
@@ -561,7 +565,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
561
565
  const reply = json?.choices?.[0]?.message?.content ?? null
562
566
  return { sent, received: { status: res.status, ok: res.ok, ms: Date.now() - t0, type: res.headers.get('content-type'), body: json ?? text.slice(0, 20_000) }, reply }
563
567
  } catch (e) {
564
- return { sent, received: { error: e.name === 'TimeoutError' ? 'no answer within 90 seconds' : `couldn't send it: ${e.cause?.code || e.cause?.message || e.message}`, ms: Date.now() - t0 } }
568
+ return { sent, received: { error: e.name === 'TimeoutError' ? noAnswer() : `couldn't send it: ${e.cause?.code || e.cause?.message || e.message}`, ms: Date.now() - t0 } }
565
569
  }
566
570
  },
567
571
  'POST /api/tests': () => ({ results: tests, run: run && { ...runState(), pending: [...run.pending] } }),
@@ -640,7 +644,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
640
644
  if ((name in TOGGLES || LOG_SWITCHES.includes(name)) && typeof value !== 'boolean') throw new Error(`${name}: on or off`)
641
645
  if (name === 'logDays' && !(Number.isInteger(value) && value >= 1 && value <= 3650)) throw new Error('logDays: a whole number of days, 1 to 3650')
642
646
  if (name === 'logDetail' && !DETAILS.includes(value)) throw new Error(`logDetail: ${DETAILS.join(' or ')}`)
643
- if (!['permissions', 'effort', 'theme', 'context', 'logDetail', 'logDays', ...Object.keys(TOGGLES), ...LOG_SWITCHES].includes(name)) throw new Error(`no setting "${name}"`)
647
+ if (name === 'testTimeout' && !(Number.isInteger(value) && value >= 1 && value <= 600)) throw new Error('test timeout: a whole number of seconds, 1 to 600')
648
+ if (!['permissions', 'effort', 'theme', 'context', 'logDetail', 'logDays', 'testTimeout', ...Object.keys(TOGGLES), ...LOG_SWITCHES].includes(name)) throw new Error(`no setting "${name}"`)
644
649
  cfg[name] = name === 'effort' && value === 'default' ? undefined : name === 'context' ? (value === null ? undefined : Number(value)) : value
645
650
  save(`setting:${name}`)
646
651
  if (name === 'logRequests' || name === 'logDetail') useRequestLog(cfg) // from the next request (a running HeartCode takes it in too: applySettings)
package/src/ui.js CHANGED
@@ -739,10 +739,13 @@ export class UI {
739
739
  const blank = c.brand('│') + ' '.repeat(W) + c.brand('│')
740
740
  for (let i = 0; i < PY; i++) out += row(1 + i, blank)
741
741
  for (let i = 0; i < h; i++) out += row(1 + PY + i, c.brand('│') + ' '.repeat(PX) + pad(lines[i] ?? '', w) + ' '.repeat(PX) + c.brand('│'))
742
+ // what's in it can be selected (copied), all but its last line (the keys)
743
+ const last = lines.findLastIndex((l) => String(l ?? '').trim())
744
+ for (let i = 0; i < Math.min(h, last); i++) this.regions.set(y + 1 + PY + i, { x: x + 1 + PX, text: fit(lines[i] ?? '', w).replace(/\x1b\[[0-9;]*m/g, '').trimEnd() })
742
745
  for (let i = 0; i < PY; i++) out += row(1 + PY + h + i, blank)
743
746
  out += row(2 + 2 * PY + h - 1, c.brand('╰' + '─'.repeat(W) + '╯'))
744
747
  const cur = d.cursor?.(w)
745
- return out + (cur ? `\x1b[${y + 1 + PY + cur.row};${x + 1 + PX + Math.min(cur.col, w - 1)}H\x1b[?25h` : '\x1b[?25l')
748
+ return [out, cur ? `\x1b[${y + 1 + PY + cur.row};${x + 1 + PX + Math.min(cur.col, w - 1)}H\x1b[?25h` : '\x1b[?25l']
746
749
  }
747
750
 
748
751
  // The question being asked, as a dialog: its title; what's typed (the filter, or the answer) with the
@@ -916,25 +919,57 @@ export class UI {
916
919
 
917
920
  // The mouse: the wheel scrolls the conversation; dragging selects in it, copied when let go
918
921
  // (the terminal can't select itself while HeartCode takes the mouse). A click or a key clears it.
922
+ // The mouse: the wheel scrolls (a dialog's own text, else the conversation); dragging selects, copied
923
+ // when let go: in the conversation (it stays selected as it scrolls), in a dialog, the header's
924
+ // folder, the input box or the status bar; a double click copies the word under it (an address, a
925
+ // path, a model's name). The terminal can't select itself while HeartCode takes the mouse
926
+ // (Shift+drag, or Option+drag on macOS, still lets it). A click or a key clears a selection.
919
927
  #mouse(b, x, y, up) {
920
928
  if (!this.full) return
921
- if (b & 64) return (b & 0xc3) === 64 || (b & 0xc3) === 65 ? this.scrollBy(b & 1 ? -3 : 3) : undefined // 64 up, 65 down
929
+ const modal = Boolean(this.dialog || (this.asking && !this.histOn && this.rl))
930
+ if (b & 64) {
931
+ if ((b & 0xc3) !== 64 && (b & 0xc3) !== 65) return
932
+ if (this.dialog) return this.dialog.key?.({ name: b & 1 ? 'down' : 'up', wheel: true }), this.render()
933
+ return this.scrollBy(b & 1 ? -3 : 3) // 64 up, 65 down
934
+ }
922
935
  if ((b & 3) !== 0 && !up) return // the left button only (a release says 3 in some terminals)
923
- if (this.dialog) {
924
- // the wheel scrolls it; a click inside goes to it, outside closes it
936
+ const press = !(b & 32) && !up
937
+ if (press) {
938
+ const twice = this.lastClick && Date.now() - this.lastClick.t < 450 && this.lastClick.x === x && this.lastClick.y === y
939
+ this.lastClick = { t: Date.now(), x, y }
940
+ if (twice) return this.#copyWord(x, y)
941
+ this.sel = null
942
+ this.ssel = null
943
+ this.flash = null
925
944
  const d = this.dialogAt
926
- if (b & 64) return (b & 0xc3) === 64 || (b & 0xc3) === 65 ? (this.dialog.key?.({ name: b & 1 ? 'down' : 'up', wheel: true }), this.render()) : undefined
927
- if ((b & 32) || up || !d) return
928
- if (x < d.x || y < d.y || x > d.x + d.W + 1 || y > d.y + d.H + 1) return this.setDialog(null) // outside it
929
- return this.dialog.click?.(x - d.cx, y - d.cy), this.render()
945
+ if (modal && d && (x < d.x || y < d.y || x > d.x + d.W + 1 || y > d.y + d.H + 1)) return this.dialog ? this.setDialog(null) : this.render() // outside a dialog: closed (a question stays)
946
+ if (!modal && y <= 3 && this.onTabClick) return this.onTabClick(x - 1) // the tab bar's 3 rows
947
+ if (modal || this.regions?.has(y)) {
948
+ // a dialog, the header, the input, the status bar: a screen selection (a click without a drag: the dialog's own)
949
+ this.ssel = { a: { x, y }, b: { x, y }, moved: false, rows: this.regions, inDialog: modal }
950
+ return this.render()
951
+ }
930
952
  }
931
- if (!(b & 32) && !up && y <= 3 && this.onTabClick) return this.onTabClick(x - 1) // the tab bar's 3 rows
932
-
953
+ if (this.ssel) {
954
+ const sel = this.ssel
955
+ if (x !== sel.b.x || y !== sel.b.y) Object.assign(sel, { b: { x, y }, moved: true })
956
+ if (up) {
957
+ this.ssel = null
958
+ const text = sel.moved && this.#selectedRows(sel).map((r) => r.text.trimEnd()).join('\n').trim()
959
+ if (text) this.#copied(text)
960
+ else if (sel.inDialog && this.dialog && this.dialogAt) this.dialog.click?.(x - this.dialogAt.cx, y - this.dialogAt.cy)
961
+ else if (sel.inDialog) return this.render()
962
+ if (text) this.flash = sel // left lit a moment, so you see what was copied
963
+ if (text) setTimeout(() => this.flash === sel && ((this.flash = null), this.render()), 700).unref?.()
964
+ }
965
+ return this.render()
966
+ }
967
+ if (modal) return
933
968
  const v = this.viewAt
934
969
  if (!v) return
935
970
  const r = Math.min(Math.max(y - 1 - v.first, 0), v.avail - 1) // a drag past the edge stops at it
936
971
  const at = { row: v.top + Math.min(r, Math.max(0, v.count - 1)), col: x - 1 }
937
- if (!(b & 32) && !up) {
972
+ if (press) {
938
973
  // a press: starts a selection, inside the conversation only
939
974
  this.sel = y - 1 >= v.first && y - 1 < v.first + v.count ? { a: at, b: at, moved: false } : null
940
975
  return this.render()
@@ -944,10 +979,39 @@ export class UI {
944
979
  if (up) {
945
980
  const text = this.sel.moved && this.#selected()
946
981
  if (!text) this.sel = null
947
- else this.notice(`copied ${text.length} character${text.length === 1 ? '' : 's'}${copyText(text) === 'osc' ? ' (through the terminal)' : ''}`)
982
+ else this.#copied(text)
948
983
  }
949
984
  this.render()
950
985
  }
986
+ #copied(text) {
987
+ this.notice(`copied ${text.length} character${text.length === 1 ? '' : 's'}${copyText(text) === 'osc' ? ' (through the terminal)' : ''}`)
988
+ }
989
+ // A double click: the word under it (no spaces; quotes and brackets around it left out), copied.
990
+ #copyWord(x, y) {
991
+ this.sel = null
992
+ let row = this.regions?.get(y)
993
+ const v = this.viewAt
994
+ if (!row && v && !this.dialog && y - 1 >= v.first && y - 1 < v.first + v.count) row = { x: 1, text: (this.#rows(this.out.columns || 80)[v.top + y - 1 - v.first] ?? '').replace(/\x1b\[[0-9;]*m/g, '') }
995
+ if (!row) return
996
+ const cells = [] // [char, its column]
997
+ let col = row.x
998
+ for (const ch of row.text) cells.push([ch, col]), (col += width(ch))
999
+ const at = cells.findIndex(([, cx], i) => x >= cx && x < (cells[i + 1]?.[1] ?? cx + 1))
1000
+ if (at === -1 || /\s/.test(cells[at][0])) return
1001
+ let s = at
1002
+ let e = at
1003
+ while (s > 0 && !/\s/.test(cells[s - 1][0])) s--
1004
+ while (e < cells.length - 1 && !/\s/.test(cells[e + 1][0])) e++
1005
+ while (s < e && /["'`(\[{<]/.test(cells[s][0])) s++
1006
+ while (e > s && /["'`)\]}>,;:.!?]/.test(cells[e][0]) && !/^https?:\/\/\S+\/$/.test(cells.slice(s, e + 1).map((c) => c[0]).join(''))) e--
1007
+ let word = cells.slice(s, e + 1).map((c) => c[0]).join('')
1008
+ if (row.path && /[\\/~…]/.test(word)) word = row.path // the folder in the header: all of it, not what fits
1009
+ this.#copied(word)
1010
+ const sel = { a: { x: cells[s][1], y }, b: { x: cells[e][1], y }, rows: new Map([[y, row]]) }
1011
+ this.flash = sel
1012
+ setTimeout(() => this.flash === sel && ((this.flash = null), this.render()), 700).unref?.()
1013
+ this.render()
1014
+ }
951
1015
  #selRange() {
952
1016
  const { a, b } = this.sel
953
1017
  return a.row < b.row || (a.row === b.row && a.col <= b.col) ? [a, b] : [b, a]
@@ -1098,11 +1162,49 @@ export class UI {
1098
1162
  }
1099
1163
  box.forEach((line, i) => (s += `\x1b[${inputTop + i};1H${row(line)}`))
1100
1164
  below.forEach((line, i) => (s += `\x1b[${inputTop + inputRows + i};1H${row(line)}`))
1101
- if (this.dialog) s += this.#drawDialog(cols, rows, { title: this.dialog.title, fill: this.dialog.fill, lines: (w, h) => this.dialog.draw(w, h) }) // over everything, the cursor hidden
1102
- else if (asked) s += this.#drawDialog(cols, rows, this.#question()) // a question: its cursor in the box
1103
- else if (this.asking || typing) s += `\x1b[${inputTop + input.cur.row - first};${input.cur.col + 1}H\x1b[?25h`
1104
- else s += `\x1b[${inputTop};1H`
1105
- out.write(s)
1165
+ // what can be selected besides the conversation (screen rows from 1): the header's first line (the
1166
+ // project's folder), the input box, the status bar; with a dialog open, only what's in it
1167
+ const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
1168
+ const tabRows = this.tabBar?.(cols)?.length ?? 0
1169
+ this.regions = new Map()
1170
+ if (this.header && head[tabRows] !== undefined) this.regions.set(tabRows + 1, { x: 1, text: plain(head[tabRows]), path: this.folder }) // path: the whole folder (shown cut when long)
1171
+ box.forEach((line, i) => this.regions.set(inputTop + i, { x: 1, text: plain(line) }))
1172
+ below.slice(1).forEach((line, i) => this.regions.set(inputTop + inputRows + 1 + i, { x: 1, text: plain(line) }))
1173
+ let cursor
1174
+ if (this.dialog || asked) {
1175
+ this.regions = new Map()
1176
+ const [box, cur] = this.#drawDialog(cols, rows, this.dialog ? { title: this.dialog.title, fill: this.dialog.fill, lines: (w, h) => this.dialog.draw(w, h) } : this.#question())
1177
+ s += box
1178
+ cursor = cur // a question: its cursor in the box; else hidden
1179
+ } else {
1180
+ this.dialogAt = null
1181
+ cursor = this.asking || typing ? `\x1b[${inputTop + input.cur.row - first};${input.cur.col + 1}H\x1b[?25h` : `\x1b[${inputTop};1H`
1182
+ }
1183
+ out.write(s + this.#screenSelection() + cursor)
1184
+ }
1185
+
1186
+ // A selection outside the conversation (in a dialog, the header, the input, the status bar), or a
1187
+ // word just double-clicked: drawn reversed over what's there.
1188
+ #screenSelection() {
1189
+ const sel = this.ssel ?? this.flash
1190
+ if (!sel) return ''
1191
+ let out = ''
1192
+ for (const { y, x, text } of this.#selectedRows(sel)) out += `\x1b[${y};${x}H\x1b[7m${text}\x1b[27m`
1193
+ return out
1194
+ }
1195
+ // The rows a screen selection covers: [{ y, x, text }] (x: where the selected part starts).
1196
+ #selectedRows(sel) {
1197
+ const [a, b] = sel.a.y < sel.b.y || (sel.a.y === sel.b.y && sel.a.x <= sel.b.x) ? [sel.a, sel.b] : [sel.b, sel.a]
1198
+ const out = []
1199
+ for (let y = a.y; y <= b.y; y++) {
1200
+ const r = sel.rows?.get(y) ?? this.regions?.get(y)
1201
+ if (!r) continue
1202
+ const end = r.x + width(r.text) // just past its last cell
1203
+ const from = Math.max(r.x, y === a.y ? a.x : r.x)
1204
+ const to = Math.min(end, y === b.y ? b.x + 1 : end)
1205
+ if (to > from) out.push({ y, x: from, text: sliceCols(r.text, from - r.x, to - r.x) })
1206
+ }
1207
+ return out
1106
1208
  }
1107
1209
 
1108
1210
 
@@ -1115,7 +1217,7 @@ export class UI {
1115
1217
  this.ttyWrite = write
1116
1218
  rl._ttyWrite = (s, key = {}) => {
1117
1219
  if (!this.full) return write(s, key)
1118
- if (this.sel) (this.sel = null), this.render() // a key ends a selection
1220
+ if (this.sel || this.ssel) (this.sel = this.ssel = null), this.render() // a key ends a selection
1119
1221
  const bound = !(key.ctrl && key.name === 'c') && this.keys[keyId(key, s)] // ~/.heart/keybindings.json
1120
1222
  // a dialog: its keys, all of them; Esc (or its own key) closes it; Ctrl+C still stops and quits
1121
1223
  if (this.dialog && !(key.ctrl && key.name === 'c')) {