heartcode 0.1.30 → 0.1.32

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,51 @@
2
2
 
3
3
  What changed in each version of HeartCode, newest first.
4
4
 
5
+ ## 0.1.32 (2026-11-01)
6
+
7
+ - Dialogs: pickers (`/select_model`, `/resume`, `/rewind`, `/export`…), permission questions, typed
8
+ questions (`/rename`, "what should it do instead?") and what commands show (`/help`, `/context`,
9
+ `/cost`, `/diff`, `/mcp`, `/doctor`, `/model_info`) open in a box over the conversation: 70% of
10
+ the width, as tall as what's in it (70% at most), everything behind dimmed. A short list is
11
+ cards (name, description under it); a permission shows what it's about (this task's last lines)
12
+ above the choices; long text scrolls. Esc closes any of them; a question the model asks closes
13
+ an open dialog so it can be answered.
14
+ - Commands that run in the background: `run_command` with `background: true` (a dev server, a
15
+ watcher) answers after a few seconds and keeps it running; the `background` tool reads its new
16
+ output, lists them, stops one; the model hears when one exits. `⚙ 1 running` in the status bar;
17
+ `Alt+B` (or `/background`) shows their logs live in a dialog, a tab each (←/→, a click), ↑/↓ and
18
+ PgUp/PgDn scroll, K twice stops one and closes its tab. Everything still running is stopped when
19
+ HeartCode exits. Alt+B only acts in an empty box (Option+← sends the same keys: the word jump).
20
+ - `/context`: what fills the context window, part by part (system prompt, tools, your messages,
21
+ notes, replies, tool results whole and as pointers), the room left, and the biggest pieces.
22
+ - The wrap-up after a task (notes, research pages kept or dropped, throwaway files removed) runs
23
+ after the answer is back, beside what you do next, on a connection of its own; it keeps a file a
24
+ new message may use. `heart -p` prints the result first and exits once it's done; `/exit` waits
25
+ for it.
26
+ - Web search: your own SearXNG (settings page → General → Web search: its address in its own row,
27
+ with Test), and the engines in the order you set (↑/↓, each switchable). They're asked in that
28
+ order: the next only when one hasn't found enough, failed or took over 3 s; the rest aren't asked
29
+ once there's enough. A SearXNG's JSON API is used when it's on there.
30
+ - `/select_model` has an "auto" row (back to your whole list, forgetting this folder's choice), and
31
+ a folder that picked its own models says so at start.
32
+ - `/` commands in alphabetical order (the `/` menu and `/help`).
33
+ - Settings page: one light/dark button at the top right instead of the switch in the sidebar; on a
34
+ phone, the top bar no longer grows taller than its tabs. Typing and pasting in the SearXNG and
35
+ skill-URL boxes work (an Enter handler cancelled every other key).
36
+
37
+ ## 0.1.31 (2026-11-01)
38
+
39
+ - Commands typed while HeartCode works run at once instead of waiting in the queue, when they leave
40
+ the conversation alone: `/help`, `/cost`, `/model_info`, `/diff`, `/copy`, `/mcp`, `/doctor`,
41
+ `/toggle_thinking`, `/btw`, `/rename`, `/export`, `/tab`, `/close_tab`, `/exit`, `/settings`,
42
+ `/login_mcp`, `/install_skill`, `/import`, `/voice`, `/select_model`. The ones that change it
43
+ (`/compact`, `/clear_chat`, `/resume`, `/rewind`, `/tree`, `/fork`, `/init`, skills, `/tidy_memory`,
44
+ `/test_model`, `/reset`) still wait until it's done.
45
+ - `/select_model` while it works: the task goes on with its models, yours from the next message.
46
+ `/exit` while it works asks first (that stops the task).
47
+ - One question on screen at a time: a command's picker and the task's question (a permission)
48
+ take turns instead of drawing over each other.
49
+
5
50
  ## 0.1.30 (2026-11-01)
6
51
 
7
52
  - Settings page: the sidebar is 7 items in 4 groups split by lines (Models · General, Notifications ·
package/README.md CHANGED
@@ -31,7 +31,8 @@ tried did what I needed:
31
31
  current official docs first, not blogs or memory.
32
32
  - **Learns, per project, and keeps it.** Every web page it reads is kept whole in
33
33
  `.heartcode/research/`. When a task ends it saves what's worth knowing as notes
34
- (`.heartcode/memory/`), drops the junk and removes throwaway files. A mistake it fixes becomes a
34
+ (`.heartcode/memory/`), drops the junk and removes throwaway files, in the background, while
35
+ you go on. A mistake it fixes becomes a
35
36
  lesson it won't repeat. The next task starts from what's known instead of searching again.
36
37
  - **Checks its work before calling it done**: a plan first, a run after every change, and another
37
38
  model reviewing the result against what you asked. Going round in circles hands the work to
@@ -55,6 +56,11 @@ tried did what I needed:
55
56
  see what went wrong.
56
57
  - **Takes skills, MCP servers and hooks** in Claude Code's formats; `/import` brings yours over.
57
58
  - **Tabs** (`Alt+T`), each with its own conversation, and git worktrees for work kept apart.
59
+ - **Servers and watchers in the background**: the model starts one and goes on working, reads its
60
+ output when it needs to, and stops it. `Alt+B` (or `/background`) shows their logs live above the input,
61
+ a tab each (←/→ or a click switches), while you work; nothing outlives HeartCode.
62
+ - **`/context`**: what fills the context window, part by part (system prompt, tools, messages, tool
63
+ results) and the biggest single pieces.
58
64
 
59
65
  ## How I set it up and use it
60
66
 
@@ -99,7 +105,7 @@ The sidebar, in four groups:
99
105
  - **Models**: *Your list* (the models HeartCode uses, in order) and *Providers* (where they
100
106
  come from).
101
107
  - **General**: *Settings* (what it may do without asking, terminal colors, features, thinking
102
- effort, voice input, and which outside tools are ready) and *Status bar* (drag and drop what the
108
+ effort, voice input, web search: your own SearXNG and the engines' order, and which outside tools are ready) and *Status bar* (drag and drop what the
103
109
  bottom lines show, with a live preview). **Notifications**: Telegram.
104
110
  - **Skills**, **MCP servers** and **System prompt**: what HeartCode can do and how it's told.
105
111
  - **Advanced**: *Logs* (requests and runs) and *Files* (the rest of the settings, as files).
@@ -155,7 +161,11 @@ Type `Hi` and press Enter. Wait for the reply: your model works.
155
161
 
156
162
  Use HeartCode like any other coding agent: ask it to read, change, run and fix things in your
157
163
  project. `/` shows every command, `Shift+Tab` changes what it may do without asking, `Esc` stops
158
- it, and `heart --help` lists everything else.
164
+ it, and `heart --help` lists everything else. While it works, commands that leave the conversation
165
+ alone (`/help`, `/cost`, `/diff`, `/select_model`, `/settings`, `/tab`, `/exit`…) run at once; the
166
+ ones that change it (`/compact`, `/rewind`, `/resume`…) wait until it's done. Pickers, questions and what
167
+ commands show (`/help`, `/context`, `/diff`…) open in a dialog over the conversation; `Esc`
168
+ closes it.
159
169
 
160
170
  ## License
161
171
 
package/SKILL.md CHANGED
@@ -204,7 +204,13 @@ Unless you pass `--no-memory`, a run keeps what it learns in the project it work
204
204
  git) and `.heartcode/memory/` (notes). Notes and pages that match a task come with it next time,
205
205
  so later runs research less. After a task that read the web, ran commands or made files, a
206
206
  wrap-up request saves notes, keeps or deletes the pages it read, and removes throwaway files and
207
- empty folders the task made (a test script, a debug log).
207
+ empty folders the task made (a test script, a debug log). It runs after the answer: the
208
+ `result` (or the printed answer) comes first, and `heart -p` exits once the wrap-up is done (a few
209
+ seconds more).
210
+
211
+ A command that keeps running (a dev server, a watcher) is started with `run_command` and
212
+ `background: true`; the `background` tool reads its new output, lists such commands and stops one.
213
+ Whatever is still running is stopped when HeartCode exits.
208
214
 
209
215
  Before a task that changed files ends, another of the user's models (the same one when only one is
210
216
  used) reviews the work against the request in a request of its own; a NO sends it back to fix.
package/bin/heartcode.js CHANGED
@@ -5,7 +5,8 @@ import { Client } from '../src/client.js'
5
5
  import { loadConfig, saveConfig, readJson, writeJson, providerName, CONFIG_FILE, HOME, AUTO_MODEL, isAuto, parseModel, takeIn, whatOf, VERSION } from '../src/config.js'
6
6
  import { probe, loadProfile, strategy, describe, profilePath, profileFrom } from '../src/probe.js'
7
7
  import { learnFromUsage, LIMIT_MS } from '../src/context.js'
8
- import { Session, transcript } from '../src/agent.js'
8
+ import { Session, transcript, contextReport } from '../src/agent.js'
9
+ import { listJobs, getJob, stopJob, removeJob, runningJobs, tailLines, ago as ranFor } from '../src/background.js'
9
10
  import { treeItems, codePlan, move, leaving, leftText, leftFiles } from '../src/tree.js'
10
11
  import { UI, c, PERMISSIONS, duration, copyText, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width } from '../src/ui.js'
11
12
  import { listFiles, runCommand, clip } from '../src/tools.js'
@@ -117,6 +118,8 @@ const SECTIONS = [
117
118
  ['/init', 'look at the project and write AGENTS.md: its commands, conventions and layout'],
118
119
  ['/btw', 'ask something on the side, also while it works; the answer stays out of the conversation', true],
119
120
  ['/cost', 'tokens used and what they cost, this session'],
121
+ ['/context', "what's in the context now: system prompt, tools, messages, tool results, and the biggest pieces"],
122
+ ['/background', 'commands running in the background (servers, watchers): their logs live, a tab each (Alt+B) · /background stop [id] · /background files', true],
120
123
  ['/model_info', 'what the model can do and how HeartCode uses it'],
121
124
  ['/test_model', 'test the model for real (otherwise what it can do comes from models.dev, or your settings)'],
122
125
  ['/tidy_memory', 'merge, update and link the memory notes now'],
@@ -135,7 +138,12 @@ const SECTIONS = [
135
138
  ['/exit', 'quit HeartCode (Alt+W closes just this tab)'],
136
139
  ]],
137
140
  ]
138
- const COMMANDS = SECTIONS.flatMap(([, list]) => list)
141
+ const byName = (a, b) => a[0].localeCompare(b[0])
142
+ for (const [, list] of SECTIONS) list.sort(byName) // alphabetical, in /help and in the "/" menu
143
+ const COMMANDS = SECTIONS.flatMap(([, list]) => list).sort(byName)
144
+ // Typed while a task works, these run at once, beside it: they leave the conversation alone. The
145
+ // others (/compact, /rewind, /resume, /init…) wait in the queue until it's done.
146
+ const RIGHT_AWAY = new Set(['help', 'cost', 'context', 'background', 'model_info', 'diff', 'copy', 'mcp', 'doctor', 'toggle_thinking', 'btw', 'rename', 'export', 'tab', 'close_tab', 'exit', 'quit', 'settings', 'login_mcp', 'install_skill', 'import', 'voice', 'select_model'])
139
147
  const helpText = (sections) => sections.map(([title, list]) => ` ${c.bold(title)}\n` + list.map(([n, d]) => ` ${c.cyan(n.padEnd(18))} ${d}`).join('\n')).join('\n\n')
140
148
  const SLASH = helpText(SECTIONS)
141
149
 
@@ -148,11 +156,12 @@ function keysHelp(keys = {}) {
148
156
  const tabs = /(^|,)alt\+[1-9]/.test(Object.keys(keys).join(','))
149
157
  const rows = [
150
158
  ['Space', 'start voice input (when the input box is empty)'],
151
- ['Enter', 'send · while it works, queue the message'],
159
+ ['Enter', 'send · while it works, queue the message (commands like /help, /cost, /select_model run at once)'],
152
160
  ['Option/Shift/Ctrl+Enter', 'new line in the box'],
153
161
  ['Esc', 'stop the task (press twice to confirm)'],
154
162
  ['Esc Esc', 'rewind to an earlier message (at the prompt)'],
155
163
  ['Shift+Tab', 'change what runs without asking (permissions)'],
164
+ [forAct('background_log'), "the background commands' logs in a dialog, a tab each (←/→ switch, ↑/↓ scroll, K twice stops one, Esc closes)"],
156
165
  [forAct('new_tab'), 'new tab'],
157
166
  [forAct('close_tab'), 'close this tab'],
158
167
  [forAct('next_tab'), 'next tab'],
@@ -195,7 +204,7 @@ const mask = (k) => (k ? (k.length > 12 ? `${k.slice(0, 4)}…${k.slice(-4)}` :
195
204
  // overrides it — see App.status for the item names and format.
196
205
  const DEFAULT_STATUS = [
197
206
  { left: ['provider', 'model'], right: ['mode', 'thinking', 'images'] },
198
- { left: ['ctx', 'tps', 'autocompact'], right: ['permissions', 'worktree', 'cost'] },
207
+ { left: ['ctx', 'tps', 'autocompact'], right: ['background', 'permissions', 'worktree', 'cost'] },
199
208
  ]
200
209
 
201
210
  class App {
@@ -220,7 +229,7 @@ class App {
220
229
  if (this.cfg.session) return
221
230
  const saved = readJson(path.join(this.root, '.heartcode', 'models.json'), null)
222
231
  const valid = (saved?.session ?? []).filter((t) => t?.provider && t?.model && this.cfg.providers[t.provider])
223
- if (valid.length) this.cfg.session = valid
232
+ if (valid.length) [this.cfg.session, this.folderModels] = [valid, true]
224
233
  }
225
234
 
226
235
  saveProjectModels() {
@@ -573,7 +582,7 @@ class App {
573
582
  // Built-in commands (/name), then the skills you can type, namespaced as /skill:name so they're
574
583
  // easy to tell apart from HeartCode's own commands (and can't clash with them).
575
584
  commands() {
576
- const mine = [...this.skills.values()].filter((k) => k.use !== 'model').map((k) => [`/skill:${k.name}`, k.description, true])
585
+ const mine = [...this.skills.values()].filter((k) => k.use !== 'model').map((k) => [`/skill:${k.name}`, k.description, true]).sort(byName)
577
586
  return [...COMMANDS, ...mine]
578
587
  }
579
588
 
@@ -679,6 +688,7 @@ class App {
679
688
  cost: null,
680
689
  autocompact: cfg.autoCompact === false ? c.faint('auto-compact off') : null,
681
690
  worktree: this.worktree ? c.info(`⎇ ${this.worktree.branch}`) : null,
691
+ background: runningJobs(this.root).length ? c.info(`⚙ ${runningJobs(this.root).length} running`) + c.faint(' Alt+B') : null,
682
692
  permissions: { all: c.green('⏵⏵ all allowed'), commands: c.yellow('ask before commands'), ask: c.yellow('ask before changes'), plan: c.info('⏸ plan mode') }[ui.permission],
683
693
  }
684
694
  if (strat) {
@@ -693,7 +703,9 @@ class App {
693
703
  }
694
704
  const sep = c.ghost(' │ ')
695
705
  const vis = (str) => width(str.replace(/\x1b\[[0-9;]*m/g, ''))
696
- const layout = Array.isArray(cfg.statusBar) && cfg.statusBar.length ? cfg.statusBar : DEFAULT_STATUS
706
+ let layout = Array.isArray(cfg.statusBar) && cfg.statusBar.length ? cfg.statusBar : DEFAULT_STATUS
707
+ // commands running in the background are shown also on a bar laid out before there was this item
708
+ if (parts.background && !JSON.stringify(layout).includes('"background"')) layout = [...layout.slice(0, -1), ...layout.slice(-1).map((row) => (Array.isArray(row) ? { left: row, right: ['background'] } : { ...row, right: ['background', ...(row.right ?? [])] }))]
697
709
  const line = (row) => {
698
710
  const names = (g) => (g ?? []).map((t) => parts[t]).filter(Boolean).join(sep)
699
711
  const left = names(Array.isArray(row) ? row : row?.left)
@@ -860,31 +872,133 @@ class App {
860
872
  return cfg.session.filter((t) => cfg.providers[t.provider] && (all || !cfg.providers[t.provider].off) && t.model && !seen.has(`${t.provider}/${t.model}`) && seen.add(`${t.provider}/${t.model}`))
861
873
  }
862
874
 
875
+ // Alt+B, /background: the background commands' logs in a dialog, one at a time with a tab each.
876
+ // ←/→ (or a click on a tab): another one; ↑/↓, PgUp/PgDn, the wheel: back in its log (End: the
877
+ // newest again); K twice: stop it and close its tab; Esc or Alt+B: closed.
878
+ toggleJobs(on = !this.jobsShown) {
879
+ const { ui } = this
880
+ if (!on) return ui.setDialog(null)
881
+ this.jobsShown = true
882
+ const ERROR = /\b(error|errors|failed|fail|exception|traceback|panic|fatal)\b/i
883
+ const jobs = () => listJobs(this.root)
884
+ const current = () => jobs().find((j) => j.id === this.jobTab) ?? jobs().findLast((j) => !j.exited) ?? jobs().at(-1)
885
+ let spots = [] // where each tab is on its row: { from, to, id }
886
+ let back = 0 // lines scrolled back from the newest (0: following it)
887
+ let page = 10
888
+ let armed = 0 // K pressed once, when
889
+ let said = '' // a line for the footer (K's question)
890
+ const go = (d) => {
891
+ const all = jobs()
892
+ if (!all.length) return
893
+ this.jobTab = all[(all.indexOf(current()) + d + all.length) % all.length].id
894
+ back = 0
895
+ }
896
+ const kill = () => {
897
+ const job = current()
898
+ if (!job) return
899
+ if (Date.now() - armed > 2500) return (armed = Date.now()), (said = `Press K again to ${job.exited ? 'close' : 'stop and close'} #${job.id}`)
900
+ armed = 0
901
+ said = ''
902
+ const all = jobs()
903
+ const next = all[all.indexOf(job) + 1] ?? all[all.indexOf(job) - 1]
904
+ removeJob(job)
905
+ ui.print(c.dim(`${job.exited ? 'closed' : 'stopped'} #${job.id} ${clip(job.command, 80)}`))
906
+ if (!next) return this.toggleJobs(false)
907
+ this.jobTab = next.id
908
+ back = 0
909
+ }
910
+ ui.setDialog({
911
+ title: 'Background commands',
912
+ toggle: 'background_log', // Alt+B closes it too
913
+ close: () => (this.jobsShown = false),
914
+ key: (key) => {
915
+ if (key.name !== 'k') (armed = 0), (said = '')
916
+ if (key.name === 'left' || key.name === 'right') return go(key.name === 'left' ? -1 : 1)
917
+ if (key.name === 'up' || key.name === 'down') return (back = Math.max(0, back + (key.name === 'up' ? (key.wheel ? 3 : 1) : key.wheel ? -3 : -1)))
918
+ if (key.name === 'pageup' || key.name === 'pagedown') return (back = Math.max(0, back + (key.name === 'pageup' ? page : -page)))
919
+ if (key.name === 'end') return (back = 0)
920
+ if (key.name === 'home') return (back = 1e6)
921
+ if (key.name === 'k' && !key.ctrl && !key.meta) return kill()
922
+ },
923
+ click: (col, row) => {
924
+ const hit = row === 0 && spots.find((t) => col >= t.from && col < t.to)
925
+ if (hit) (this.jobTab = hit.id), (back = 0)
926
+ },
927
+ draw: (w, h) => {
928
+ const all = jobs()
929
+ if (!all.length) return ['', ` ${c.faint('Nothing runs in the background. The model starts servers and watchers there.')}`, '', ` ${c.faint('Esc close')}`]
930
+ const job = current()
931
+ this.jobTab = job.id
932
+ // the tabs, scrolled so the one shown is on screen
933
+ const label = (j) => ` ${j.exited ? '○' : '●'} #${j.id} ${clip(j.command.replace(/\s+/g, ' '), 18)} `
934
+ let first = 0
935
+ while (first < all.indexOf(job) && all.slice(first, all.indexOf(job) + 1).reduce((n, j) => n + width(label(j)) + 1, 0) > w - 2) first++
936
+ spots = []
937
+ let x = 1
938
+ let bar = ' '
939
+ for (const j of all.slice(first)) {
940
+ const lw = width(label(j))
941
+ if (x + lw > w - 2) break
942
+ spots.push({ from: x, to: x + lw, id: j.id })
943
+ bar += (j === job ? `\x1b[7m${c.brand(c.bold(label(j)))}\x1b[27m` : j.exited ? c.faint(label(j)) : c.muted(label(j))) + ' '
944
+ x += lw + 1
945
+ }
946
+ const hidden = all.length - spots.length
947
+ page = Math.max(1, h - 6)
948
+ const n = h - 5 // tabs, a rule, the command, (the log), a rule, the keys
949
+ const lines = tailLines(job, n + back + 2000) // enough to scroll back through
950
+ back = Math.min(back, Math.max(0, lines.length - n))
951
+ const shown = lines.slice(Math.max(0, lines.length - n - back), lines.length - back)
952
+ const state = job.exited ? c.yellow(`exited with ${job.code}`) : c.green('running')
953
+ const where = back ? c.yellow(` · ${back} line${back > 1 ? 's' : ''} back (End: the newest)`) : ''
954
+ return [
955
+ bar + (hidden ? c.faint(` +${hidden} more`) : ''),
956
+ c.ghost('─'.repeat(w)),
957
+ ` ${c.bold(clip(job.command, w - 40))} ${c.faint('·')} ${state} ${c.faint(`· ${ranFor(job)}`)}${where}`,
958
+ ...Array.from({ length: n }, (_, i) => (shown.length ? (shown[i] === undefined ? '' : ` ${ERROR.test(shown[i]) ? c.red(shown[i]) : c.muted(shown[i])}`) : i ? '' : ` ${c.faint('(no output yet)')}`)),
959
+ c.ghost('─'.repeat(w)),
960
+ ` ${said ? c.yellow(said) : c.faint(`${all.length > 1 ? '←/→ another one · ' : ''}↑/↓ PgUp/PgDn scroll · K ${job.exited ? 'close' : 'stop'} it · Esc close`)}`,
961
+ ]
962
+ },
963
+ })
964
+ }
965
+
863
966
  // Use a chosen set of models for this session: one pins it (no rotation), several rotate among
864
967
  // just those. Remembered for this folder (.heartcode/models.json); the saved ranking is untouched.
865
- async setSession(list) {
968
+ // later: chosen while a task works; it goes on with its models, yours from the next message.
969
+ async setSession(list, later = false) {
866
970
  const { cfg } = this
867
- cfg.session = list // the global #1 (cfg.provider/model) stays, so your whole list and the picker are unchanged
868
- this.saveProjectModels()
869
- this.s = null
870
- this.ui.print(list.length === 1 ? `${c.green('using')} ${c.cyan(list[0].model)} ${c.dim('· pinned for this folder')}` : `${c.green(`using ${list.length} models for this folder`)}: ${c.cyan(list.map((t) => t.model).join(', '))}`)
971
+ const apply = () => {
972
+ cfg.session = list // the global #1 (cfg.provider/model) stays, so your whole list and the picker are unchanged
973
+ this.saveProjectModels()
974
+ this.s = null
975
+ }
976
+ const msg = list.length === 1 ? `${c.green('using')} ${c.cyan(list[0].model)} ${c.dim('· pinned for this folder')}` : `${c.green(`using ${list.length} models for this folder`)}: ${c.cyan(list.map((t) => t.model).join(', '))}`
977
+ if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from your next message')}`)
978
+ apply()
979
+ this.ui.print(msg)
871
980
  await this.session()
872
981
  }
873
982
 
874
983
  // Back to auto: your whole list again (#1, then the next when one fails), following the saved
875
984
  // ranking. The folder's remembered choice is cleared.
876
- async auto() {
985
+ async auto(later = false) {
877
986
  const { cfg } = this
878
- delete cfg.session
879
- this.saveProjectModels()
880
- this.s = null
881
- this.ui.print(`${c.green('using')} ${c.dim('auto')} ${c.cyan(`(${this.myModels().length} models)`)}`)
987
+ const apply = () => {
988
+ delete cfg.session
989
+ this.saveProjectModels()
990
+ this.s = null
991
+ }
992
+ const msg = `${c.green('using')} ${c.dim('auto')} ${c.cyan(`(${this.myModels().length} models)`)}`
993
+ if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from your next message')}`)
994
+ apply()
995
+ this.ui.print(msg)
882
996
  await this.session()
883
997
  }
884
998
 
885
999
  // The picker: tick the models for this session — one pins it, several rotate among them, all of
886
1000
  // them (or none) is the same as auto (your whole list). "auto" is the first entry.
887
- async chooseModel(filter = '') {
1001
+ async chooseModel(filter = '', later = false) {
888
1002
  const { ui, cfg } = this
889
1003
  const mine = this.myModels()
890
1004
  if (!mine.length) {
@@ -894,18 +1008,21 @@ class App {
894
1008
  const key = (t) => `${t.provider}/${t.model}`
895
1009
  const chosen = new Set((cfg.session ?? mine).map(key)) // pre-ticked: this session's set, or all (auto)
896
1010
  const items = mine.map((t) => ({ label: t.model, t, checked: chosen.has(key(t)), desc: this.modelDesc(t, mine.indexOf(t)) }))
897
- const picked = await ui.pick('Models for this session — tick several to rotate, one to pin (all = auto)', items, { filter, multi: true })
1011
+ // first, standing alone: back to auto (Enter on it, whatever is ticked)
1012
+ const auto = { label: 'auto', only: true, auto: true, desc: `your whole list, in its order (${mine.length} models)${cfg.session ? ' · forgets what this folder picked' : ' · in use'}` }
1013
+ const picked = await ui.pick('Models for this session — tick several to rotate, one to pin, or auto', [auto, ...items], { filter, multi: true })
898
1014
  if (!picked) return
1015
+ if (picked.some((it) => it.auto)) return cfg.session ? this.auto(later) : ui.print(c.dim('already on auto'))
899
1016
  const list = picked.map((it) => it.t)
900
- return list.length >= mine.length ? this.auto() : this.setSession(list)
1017
+ return list.length >= mine.length ? this.auto(later) : this.setSession(list, later)
901
1018
  }
902
1019
 
903
1020
  // "/select_model a, b, c": use those models this session (one pins, several rotate). One model:
904
1021
  // "model", "provider model" or "provider/model". "/select_model auto": your whole list. No
905
1022
  // argument: the picker.
906
- async pickModel(args) {
907
- if (!args.length) return this.chooseModel()
908
- if (args.every((a) => isAuto(a))) return this.cfg.session ? this.auto() : this.ui.print(c.dim('already on auto'))
1023
+ async pickModel(args, later = false) {
1024
+ if (!args.length) return this.chooseModel('', later)
1025
+ if (args.every((a) => isAuto(a))) return this.cfg.session ? this.auto(later) : this.ui.print(c.dim('already on auto'))
909
1026
  const raw = args.join(' ')
910
1027
  const specs = raw.includes(',') ? raw.split(',').map((x) => x.trim()).filter(Boolean) : [raw]
911
1028
  const resolve = (spec) => {
@@ -922,9 +1039,9 @@ class App {
922
1039
  for (const spec of specs) (resolve(spec) ? found : missing).push(resolve(spec) ?? spec)
923
1040
  if (missing.length || !found.length) {
924
1041
  if (missing.length) this.ui.print(c.dim(`not in your models: ${missing.join(', ')} · add on /settings`))
925
- return this.chooseModel(specs.length === 1 ? specs[0] : '')
1042
+ return this.chooseModel(specs.length === 1 ? specs[0] : '', later)
926
1043
  }
927
- return this.setSession(found)
1044
+ return this.setSession(found, later)
928
1045
  }
929
1046
 
930
1047
  listProviders() {
@@ -1245,22 +1362,30 @@ async function signInMcp(app, name, signal) {
1245
1362
  return `signed in to ${name} · ${tools.length} tools`
1246
1363
  }
1247
1364
 
1248
- async function slash(app, line) {
1365
+ // working: typed while a task works and run beside it (RIGHT_AWAY): no spinner of its own, nothing
1366
+ // that would end the task's.
1367
+ async function slash(app, line, working = false) {
1249
1368
  const [cmd, ...args] = line.slice(1).trim().split(/\s+/)
1250
1369
  const { ui, cfg } = app
1370
+ const spin = (label) => !working && ui.spinner(label)
1371
+ const unspin = () => !working && ui.stopSpin()
1251
1372
  switch (cmd) {
1252
1373
  case 'close_tab':
1253
- return void (await app.closeTab())
1374
+ return void (await app.closeTab(working))
1254
1375
  case 'exit':
1255
1376
  case 'quit': {
1256
1377
  const n = app.tabs?.list.length ?? 1
1257
- if (n > 1) {
1258
- const go = await ui.pick(`Quit HeartCode? ${n} tabs are open`, [
1378
+ if (n > 1 || working) {
1379
+ const go = await ui.pick(`Quit HeartCode?${working ? ' It is still working: that stops.' : ''}${n > 1 ? ` ${n} tabs are open` : ''}`, [
1259
1380
  { label: 'Yes, quit', desc: 'they come back next time you start HeartCode here', yes: true },
1260
1381
  { label: 'No', desc: 'Alt+W closes just this tab' },
1261
1382
  ])
1262
1383
  if (!go?.yes) return
1263
1384
  }
1385
+ if (!working && app.s?.wrapping) {
1386
+ ui.spinner('keeping what the last task learned · Ctrl+C to quit now')
1387
+ await app.s.wrapping
1388
+ }
1264
1389
  return 'exit'
1265
1390
  }
1266
1391
  case 'reset': {
@@ -1285,11 +1410,12 @@ async function slash(app, line) {
1285
1410
  openBrowser(url)
1286
1411
  ui.print(`${c.info('↗')} ${c.bold('settings')} ${c.muted('opened in your browser:')}\n ${c.faint(url)}`)
1287
1412
  // a dialog until it's turned off: nothing else meanwhile, in any tab (Esc turns it off too).
1288
- // Not busy meanwhile: what's changed on the page applies at once, here too.
1289
- ui.idle()
1413
+ // Not busy meanwhile: what's changed on the page applies at once, here too (opened while a task
1414
+ // works: once it's done).
1415
+ if (!working) ui.idle()
1290
1416
  if (app.tabs) app.tabs.locked = true
1291
1417
  try {
1292
- await ui.pick(`${c.info('↗')} ${c.bold('The settings page is on')}`, [{ label: 'Turn off', desc: 'stops the page and gives HeartCode back' }], { fixed: true })
1418
+ await ui.pick('The settings page is on', [{ label: 'Turn off', desc: 'stops the page and gives HeartCode back' }], { fixed: true, body: `It's open in your browser:\n${url}\n\nWhat you change there applies right away.` })
1293
1419
  } finally {
1294
1420
  if (app.tabs) app.tabs.locked = false
1295
1421
  close()
@@ -1309,9 +1435,9 @@ async function slash(app, line) {
1309
1435
  return ui.print(`${c.cyan('/tab')} ${c.faint('a new tab ·')} ${c.cyan('/tab worktree')} ${c.muted('[name]')} ${c.faint('a new tab in its own git worktree ·')} ${c.cyan('/tab')} ${c.muted('<1–' + tabs.list.length + '>')} ${c.faint('go to that tab')}`)
1310
1436
  }
1311
1437
  case 'help':
1312
- return ui.print(app.help())
1438
+ return ui.showText('Commands and keys', app.help())
1313
1439
  case 'select_model':
1314
- return app.pickModel(args)
1440
+ return app.pickModel(args, working)
1315
1441
  case 'rename': {
1316
1442
  const name = args.join(' ').trim() || (await ui.ask(` ${c.bold('Name for this session')}: `, { initial: app.chat.name ?? '' }))?.trim()
1317
1443
  if (!name) return ui.print(c.dim('cancelled'))
@@ -1347,16 +1473,18 @@ async function slash(app, line) {
1347
1473
  const files = [...first.keys()].filter((f) => !want || f.includes(want)).sort()
1348
1474
  if (!files.length) return ui.print(want ? `No changes to ${want} in this session.` : 'No changes in this session yet.')
1349
1475
  let shown = 0
1476
+ const out = []
1350
1477
  for (const rel of files) {
1351
1478
  const abs = path.join(app.root, rel)
1352
1479
  const now = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null
1353
1480
  const was = first.get(rel)
1354
1481
  if (was === now) continue
1355
1482
  shown++
1356
- if (was === null || now === null) ui.print(`${c.bold(rel)} ${was === null ? c.green('(new)') : c.red('(deleted)')}`)
1357
- if (now !== null) ui.print(renderDiff(diffLines(was ?? '', now), rel, undefined, 3, 400))
1483
+ if (was === null || now === null) out.push(`${c.bold(rel)} ${was === null ? c.green('(new)') : c.red('(deleted)')}`)
1484
+ if (now !== null) out.push(renderDiff(diffLines(was ?? '', now), rel, undefined, 3, 400))
1358
1485
  }
1359
- return ui.print(c.dim(shown ? `${shown} file${shown > 1 ? 's' : ''} changed in this session${files.length > shown ? ` (${files.length - shown} back as they were)` : ''}` : 'every file HeartCode changed is back as it was'))
1486
+ out.push(c.dim(shown ? `${shown} file${shown > 1 ? 's' : ''} changed in this session${files.length > shown ? ` (${files.length - shown} back as they were)` : ''}` : 'every file HeartCode changed is back as it was'))
1487
+ return ui.showText(want ? `Changes to ${want}` : 'Changes in this session', out.join('\n'))
1360
1488
  }
1361
1489
  case 'init': {
1362
1490
  const has = (f) => fs.existsSync(path.join(app.root, f))
@@ -1370,15 +1498,54 @@ async function slash(app, line) {
1370
1498
  const how = copyText(answer)
1371
1499
  return ui.print(c.dim(`copied the last answer (${answer.split('\n').length} lines)${how === 'osc' ? ' through the terminal' : ''}`))
1372
1500
  }
1501
+ case 'background': {
1502
+ const jobs = listJobs(app.root)
1503
+ const label = (j) => `#${j.id} ${clip(j.command, 70)}`
1504
+ if (args[0] === 'off' || args[0] === 'hide') return app.toggleJobs(false)
1505
+ if (args[0] === 'stop') {
1506
+ const j = args[1] ? getJob(args[1]) : null
1507
+ const running = jobs.filter((x) => !x.exited)
1508
+ if (!j && !running.length) return ui.print(c.dim('Nothing is running in the background.'))
1509
+ const pick = j ? { j } : await ui.pick('Stop which one?', running.map((x) => ({ label: label(x), desc: `running · ${ranFor(x)}`, j: x })))
1510
+ if (!pick?.j) return
1511
+ return ui.print(stopJob(pick.j) ? `${c.ok('✓')} stopped ${label(pick.j)}` : c.dim(`#${pick.j.id} had already exited`))
1512
+ }
1513
+ if (args[0] === 'files') return jobs.length ? ui.showText('Background logs', jobs.map((j) => `${label(j)}\n ${c.faint(j.file)}`).join('\n')) : ui.print(c.dim('No background commands yet.'))
1514
+ if (getJob(args[0])) app.jobTab = getJob(args[0]).id // /background 2: its tab
1515
+ return app.toggleJobs(true) // their logs, live, a tab each
1516
+ }
1517
+ case 'context': {
1518
+ const s = app.s
1519
+ if (!s?.messages?.length) return ui.print('Nothing in the context yet: it fills with your first message.')
1520
+ const r = contextReport(s)
1521
+ const share = (n) => (r.window ? `${Math.round((n / r.window) * 100)}%` : '')
1522
+ const bar = (n) => c.brand('█'.repeat(r.window ? Math.round((n / r.window) * 40) : 0) || (n ? '▏' : ''))
1523
+ const row = (name, n, note = '') => ` ${name.padEnd(20)} ${kTokens(n).padStart(6)} ${c.faint(share(n).padStart(4))} ${bar(n)}${note ? ` ${c.faint(note)}` : ''}`
1524
+ const free = Math.max(0, r.compactAt - r.total)
1525
+ ui.showText(
1526
+ 'Context',
1527
+ [
1528
+ `${c.muted(`~${kTokens(r.total)} of ${kTokens(r.window)} (${share(r.total)}) · ${s.client.model}`)}${r.counted ? c.faint(` · the last request, as the server counted it: ${kTokens(r.counted)}`) : ''}`,
1529
+ ...r.parts.filter((p) => p.tokens).map((p) => row(p.name, p.tokens, p.note)),
1530
+ ` ${'room left'.padEnd(20)} ${kTokens(free).padStart(6)} ${c.faint(share(free).padStart(4))} ${c.faint(`before it summarizes, at 85% (${kTokens(r.compactAt)}) — or moves to a model with more room`)}`,
1531
+ '',
1532
+ c.bold('Biggest pieces'),
1533
+ ...r.biggest.map((b) => ` ${kTokens(b.tokens).padStart(6)} ${b.what} ${c.faint(b.ago ? `· ${b.ago} message${b.ago > 1 ? 's' : ''} ago` : '· the newest')}`),
1534
+ c.faint(' /compact summarizes it (add what to keep); older tool results become pointers to their files on their own'),
1535
+ ].join('\n'),
1536
+ )
1537
+ return
1538
+ }
1373
1539
  case 'cost': {
1374
1540
  const u = app.chat.usage
1375
1541
  if (!u?.requests) return ui.print('Nothing used yet in this session.')
1376
1542
  const price = app.s?.client.price?.()
1377
- ui.print(`${c.bold('tokens')} ${kTokens(u.input)} in${u.cached ? ` (${kTokens(u.cached)} from the cache)` : ''} · ${kTokens(u.output)} out · ${u.requests} request${u.requests > 1 ? 's' : ''}`)
1378
- return ui.print(
1379
- u.priced
1380
- ? `${c.bold('cost')} ${money(u.cost)}${price ? c.faint(` (${app.inUse()?.model}: $${price.input ?? 0} in / $${price.output ?? 0} out per million tokens, from models.dev)`) : ''}`
1381
- : c.faint(`cost: not known for ${app.inUse()?.model ?? 'this model'} (models.dev doesn't list it; local and subscription models have none)`),
1543
+ return ui.showText(
1544
+ 'Cost',
1545
+ `${c.bold('tokens')} ${kTokens(u.input)} in${u.cached ? ` (${kTokens(u.cached)} from the cache)` : ''} · ${kTokens(u.output)} out · ${u.requests} request${u.requests > 1 ? 's' : ''}\n` +
1546
+ (u.priced
1547
+ ? `${c.bold('cost')} ${money(u.cost)}${price ? c.faint(` (${app.inUse()?.model}: $${price.input ?? 0} in / $${price.output ?? 0} out per million tokens, from models.dev)`) : ''}`
1548
+ : c.faint(`cost: not known for ${app.inUse()?.model ?? 'this model'} (models.dev doesn't list it; local and subscription models have none)`)),
1382
1549
  )
1383
1550
  }
1384
1551
  case 'clear_chat': // a new session; the old one stays in /resume
@@ -1403,7 +1570,7 @@ async function slash(app, line) {
1403
1570
  const head = ` ${cp.ok ? c.green('✓') : c.red('✗')} ${c.bold(cp.name)}${cp.ok ? c.dim(' · ready') : c.yellow(' · needs setup')}`
1404
1571
  return cp.ok ? head : `${head}\n ${c.faint(`install ${cp.need}`)}`
1405
1572
  })
1406
- return ui.print(`${c.bold('External tools HeartCode features use')}\n${rows.join('\n')}`)
1573
+ return ui.showText('External tools HeartCode features use', rows.join('\n'))
1407
1574
  }
1408
1575
  case 'mcp': {
1409
1576
  const all = loadServers(app.root, { includeDisabled: true }) // enabled and off, so off ones are visible
@@ -1420,20 +1587,20 @@ async function slash(app, line) {
1420
1587
  })
1421
1588
  const needs = names.some((n) => running.has(n) && mcpAuth(all[n]) === 'out')
1422
1589
  const off = names.some((n) => !running.has(n))
1423
- return ui.print(`${c.bold('MCP servers')}\n${rows.join('\n')}${needs ? `\n ${c.dim('sign in to a remote one with /login_mcp <name>')}` : ''}${off ? `\n ${c.dim('turn one on in /settings → MCP servers')}` : ''}`)
1590
+ return ui.showText('MCP servers', `${rows.join('\n')}${needs ? `\n ${c.dim('sign in to a remote one with /login_mcp <name>')}` : ''}${off ? `\n ${c.dim('turn one on in /settings → MCP servers')}` : ''}`)
1424
1591
  }
1425
1592
  case 'login_mcp': {
1426
1593
  const remote = app.mcp.names.filter((n) => app.mcp.get(n).url)
1427
1594
  const name = args[0] ?? (await ui.pick('Sign in to which server?', remote.map((n) => ({ label: n, desc: app.mcp.get(n).url, hint: mcpAuth(app.mcp.get(n).cfg) === 'in' ? 'signed in' : 'not signed in' }))))?.label
1428
1595
  if (!name) return remote.length ? undefined : ui.print('No remote MCP servers (ones with a "url") to sign in to.')
1429
1596
  if (!app.mcp.get(name)?.url) return ui.print(`No remote MCP server "${name}".`)
1430
- ui.spinner(`connecting to ${name}`)
1597
+ spin(`connecting to ${name}`)
1431
1598
  try {
1432
1599
  const msg = await signInMcp(app, name, app.signal)
1433
- ui.stopSpin()
1600
+ unspin()
1434
1601
  return ui.print(`${c.green('✓')} ${msg}`)
1435
1602
  } catch (e) {
1436
- ui.stopSpin()
1603
+ unspin()
1437
1604
  return ui.print(`${c.red('✗')} ${e.message}`)
1438
1605
  }
1439
1606
  }
@@ -1450,7 +1617,7 @@ async function slash(app, line) {
1450
1617
  }
1451
1618
  }
1452
1619
  app.reload('skill')
1453
- app.reload('mcp')
1620
+ app.reload('mcp', working) // working: the old servers stop once the task is done
1454
1621
  log('import', chosen.map((it) => `${it.group}: ${it.label}`))
1455
1622
  return
1456
1623
  }
@@ -1458,20 +1625,21 @@ async function slash(app, line) {
1458
1625
  const url = args.find((a) => !a.startsWith('--'))
1459
1626
  if (!url) return ui.print('Usage: /install_skill <github repo or a SKILL.md url> [--project]')
1460
1627
  const scope = args.includes('--project') ? 'project' : 'global'
1461
- ui.spinner(`installing from ${url}`)
1628
+ spin(`installing from ${url}`)
1462
1629
  try {
1463
1630
  const msg = await installSkill(app.root, url, scope, { signal: app.signal })
1464
- ui.stopSpin()
1631
+ unspin()
1465
1632
  app.reload('skill')
1466
1633
  return ui.print(`${c.green('✓')} ${msg}${scope === 'project' ? ' (this folder)' : ''} ${c.dim('· run with /skill:<name>, /help lists them')}`)
1467
1634
  } catch (e) {
1468
- ui.stopSpin()
1635
+ unspin()
1469
1636
  return ui.print(`${c.red('✗')} could not install: ${e.message}`)
1470
1637
  }
1471
1638
  }
1472
1639
  case 'btw':
1473
- return app.btw(line.trim().replace(/^\/btw\b/, '').trim())
1640
+ return app.btw(line.trim().replace(/^\/btw\b/, '').trim(), working)
1474
1641
  case 'voice': {
1642
+ if (working) return ui.dictateIn() // into the box, as Space does while it works
1475
1643
  const text = await ui.dictate()
1476
1644
  if (text) app.nextInput = text // in the box, to read over and send
1477
1645
  return
@@ -1502,7 +1670,7 @@ async function slash(app, line) {
1502
1670
  return app.save()
1503
1671
  }
1504
1672
  case 'model_info':
1505
- return ui.print(`${c.cyan(s.client.model)}\n${describe(s.profile, s.strat)}`)
1673
+ return ui.showText(s.client.model, describe(s.profile, s.strat))
1506
1674
  case 'test_model': {
1507
1675
  const tested = await getProfile(app.client(s.client.provider, s.client.model), ui, true, app.signal) // tested on a fresh connection (requests not fitted to what it was thought to do), and saved
1508
1676
  s.reset()
@@ -1544,7 +1712,15 @@ async function repl(app, f = {}) {
1544
1712
  ui.onDoubleEscape = () => '/rewind'
1545
1713
  let ctl = null
1546
1714
  ui.onEscape = () => ctl?.abort()
1547
- ui.onBtw = (q) => app.btw(q, true) // /btw typed while it works
1715
+ // a command typed while it works: run now, beside the task, if it leaves the conversation alone
1716
+ ui.onPanel = () => app.toggleJobs() // Alt+B: the background commands' logs, side by side, live
1717
+ ui.onNow = (line) => {
1718
+ if (!RIGHT_AWAY.has(/^\/([\w-]+)/.exec(line)?.[1]) || !app.isCommand(line)) return false
1719
+ slash(app, line, true)
1720
+ .then((r) => r === 'exit' && (ctl?.abort(), app.save(), quit()))
1721
+ .catch((e) => (log('error', e.stack), ui.print(c.red(`error: ${e.message}`))))
1722
+ return true
1723
+ }
1548
1724
  ui.onWaiting = (question) => notify(cfg, 'waiting', `⏳ Waiting for you · ${path.basename(app.root)}\n${clip(question.replace(/\x1b\[[0-9;]*m/g, '').replace(/\s*›\s*$/, '').replace(/^\?\s*/, '').trim(), 1000)}`) // a question or a permission while it works (Telegram)
1549
1725
  ui.isCommand = (l) => app.isCommand(l)
1550
1726
  loadPrices().then(() => ui.render?.()) // models.dev: what each model can do, for the model lists
@@ -1620,6 +1796,8 @@ async function repl(app, f = {}) {
1620
1796
  if (f['resume-id']) await app.resume(loadChat(f['resume-id']))
1621
1797
  else if (f.resume) await app.resume()
1622
1798
  if (f.model) useModel(app, f.model) // a continued tab's own model
1799
+ // models this folder picked earlier (/select_model): said, with the way back to your whole list
1800
+ if (app.folderModels && cfg.session?.length) ui.print(`${c.muted('this folder uses')} ${c.cyan(cfg.session.map((t) => t.model).join(', '))} ${c.faint(`(picked earlier) · ${c.cyan('/select_model auto')} for your whole list again`)}`)
1623
1801
  app.tabs?.onChange?.() // the conversation it opened with
1624
1802
  for (;;) {
1625
1803
  const line = await ui.ask(` ${c.magenta('♥')} `, { suggest: true, initial: app.nextInput, history: true })