@yanzc/claude-pro 0.8.0 → 0.9.1

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.
Files changed (57) hide show
  1. package/README.md +342 -318
  2. package/package.json +1 -2
  3. package/src/agent.js +80 -14
  4. package/src/agents.js +3 -2
  5. package/src/api.js +39 -34
  6. package/src/browser/broker.js +367 -0
  7. package/src/browser/cdp.js +114 -0
  8. package/src/browser/render.js +242 -0
  9. package/src/browser/session.js +948 -0
  10. package/src/browser/snapshot.js +212 -0
  11. package/src/cache.js +1 -1
  12. package/src/checkpoints.js +1 -0
  13. package/src/commands.js +169 -67
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +145 -144
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +3 -2
  18. package/src/gateway.js +208 -164
  19. package/src/hooks.js +2 -2
  20. package/src/keepalive.js +1 -1
  21. package/src/main.js +52 -40
  22. package/src/mcp.js +2 -2
  23. package/src/peers.js +1 -10
  24. package/src/print.js +9 -3
  25. package/src/prompt-profiles.js +0 -6
  26. package/src/prompts.js +7 -63
  27. package/src/ratelimit.js +2 -4
  28. package/src/remote.js +76 -14
  29. package/src/runtime.js +33 -10
  30. package/src/selfcheck.js +3 -3
  31. package/src/session.js +93 -3
  32. package/src/supervisor.js +10 -1
  33. package/src/tools/bash.js +18 -17
  34. package/src/tools/browser.js +365 -0
  35. package/src/tools/code.js +430 -0
  36. package/src/tools/effort.js +3 -4
  37. package/src/tools/files.js +368 -45
  38. package/src/tools/index.js +9 -1
  39. package/src/tools/notebook.js +11 -4
  40. package/src/tools/processes.js +274 -0
  41. package/src/tools/search.js +33 -8
  42. package/src/tools/web.js +316 -46
  43. package/src/trace.js +0 -4
  44. package/src/ui/ansi.js +92 -13
  45. package/src/ui/dialogs.js +16 -54
  46. package/src/ui/editor.js +231 -34
  47. package/src/ui/markdown.js +1 -2
  48. package/src/ui/render.js +1 -2
  49. package/src/ui/repl.js +335 -101
  50. package/src/ui/screen.js +139 -31
  51. package/src/updater.js +135 -165
  52. package/src/utils/clipboard.js +5 -3
  53. package/src/utils/dirs.js +136 -0
  54. package/src/utils/encoding.js +23 -2
  55. package/src/utils/paths.js +15 -17
  56. package/src/utils/shell.js +66 -11
  57. package/.env.example +0 -29
package/src/ui/repl.js CHANGED
@@ -8,7 +8,7 @@ import readline from 'node:readline';
8
8
  import { spawn } from 'node:child_process';
9
9
  import { c, ESC, stringWidth, stripAnsi, truncate, padEnd, wordWrap } from './ansi.js';
10
10
  import { Screen, queryCursorRow, mouseFilter } from './screen.js';
11
- import { Editor, topBorder } from './editor.js';
11
+ import { Editor, topBorder, shownQuotes } from './editor.js';
12
12
  import { SelectDialog } from './dialogs.js';
13
13
  import { MarkdownStream, renderMarkdown } from './markdown.js';
14
14
  import {
@@ -18,20 +18,23 @@ import { createRuntime } from '../runtime.js';
18
18
  import { SessionStore, firstUserText, moveSession } from '../session.js';
19
19
  import { defaultEffort, effortSupported, effortToSend, quickQuery } from '../api.js';
20
20
  import { CONFIG_DIR, VERSION, APP_NAME, INSTALL_DIR } from '../config.js';
21
- import { gatewayLogin, normalizeGatewayUrl, formatUsd } from '../gateway.js';
21
+ import { gatewayLogin, loadGatewayModels, normalizeGatewayUrl, formatUsd } from '../gateway.js';
22
22
  import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
23
- import { buildCommands } from '../commands.js';
23
+ import { buildCommands, modelChoices, effortChoices } from '../commands.js';
24
24
  import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
25
25
  import { resolvePath, displayPath } from '../utils/paths.js';
26
+ import { listDirectory, recentDirectories } from '../utils/dirs.js';
26
27
  import { ripgrepPath } from '../utils/shell.js';
27
28
  import { describePause, formatClock, humanDuration, resumeText, shouldAnnounce } from '../ratelimit.js';
28
29
  import { shutdownBackgroundShells, listBackgroundShells } from '../tools/bash.js';
30
+ import { shutdownInterpreters } from '../tools/code.js';
31
+ import { browserSession } from '../browser/session.js';
29
32
  import { estimateTokens } from '../agent.js';
30
33
  import { readClipboardImage, imageFromFile, writeClipboard, readClipboardText } from '../utils/clipboard.js';
31
34
  import { fitImagesIn, imageSize } from '../utils/images.js';
32
35
  import { checkForUpdate, installUpdate, installedVersion, installedByNpm, isNewer } from '../updater.js';
33
36
  import { PeerNode, peersEnabled, findPeer, resolvePeer, machineName, cleanName, peerMessagePrompt } from '../peers.js';
34
- import { RemoteControl, transcriptItems, onlineEnabled, REMOTE_WIDTH } from '../remote.js';
37
+ import { RemoteControl, transcriptItems, onlineEnabled, remoteCommandsEnabled, REMOTE_WIDTH } from '../remote.js';
35
38
 
36
39
  // A model id as people say it: claude-sonnet-5-5 -> sonnet-5-5, claude-haiku-4-5-20251001 -> haiku-4-5.
37
40
  export const modelTag = (model) => String(model?.id ?? '').replace(/^claude-/, '').replace(/-\d{8}$/, '');
@@ -67,6 +70,9 @@ const imageBlock = (img) => ({ type: 'image', source: { type: 'base64', media_ty
67
70
  // The images the remote page sends with a message ({media_type, data: base64}), checked as the API would: at most
68
71
  // REMOTE_MAX_IMAGES, each a PNG, JPEG, GIF or WebP of at most 5 MB. Throws what to tell the page.
69
72
  const REMOTE_IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
73
+ // What the page may not send (see App.remoteSend): ending or restarting the session, or updating claude-pro (which
74
+ // restarts it), with or without arguments. The gateway uses the same pattern.
75
+ const TERMINAL_ONLY = /^\s*\/(exit|quit|restart|reload|update)(?:\s|$)/i;
70
76
  const REMOTE_MAX_IMAGES = 6;
71
77
  const REMOTE_MAX_IMAGE_BYTES = 5 * 1024 * 1024;
72
78
  export function remoteImages(images) {
@@ -90,17 +96,49 @@ const SPINNER = ['·', '✢', '✳', '✶', '✻', '✽', '✽', '✻', '✶', '
90
96
  const VERBS = ['Thinking', 'Pondering', 'Crafting', 'Brewing', 'Computing', 'Conjuring', 'Cooking', 'Musing', 'Noodling', 'Percolating', 'Ruminating', 'Synthesizing', 'Working', 'Tinkering', 'Mulling', 'Deliberating', 'Churning', 'Forging', 'Hatching', 'Simmering'];
91
97
  const HISTORY_FILE = path.join(CONFIG_DIR, 'history.jsonl');
92
98
 
99
+ const HISTORY_KEEP = 500; // entries a project's history loads (and keeps, see loadHistory)
100
+ const HISTORY_PRUNE_CHARS = 5_000_000;
101
+ const HISTORY_PASTE_CHARS = 100_000; // pasted text kept with an entry in the file, at most (images are not kept)
102
+
103
+ // The input history of the project, oldest first: the text, or {text, parts} with the pasted text and quotes its
104
+ // placeholders stand for (see Editor.submit). A file past HISTORY_PRUNE_CHARS is written again with the last
105
+ // HISTORY_KEEP entries of each project: it grew for good (every message of every project), read whole at each start.
93
106
  function loadHistory(cwd) {
94
- try {
95
- return fs.readFileSync(HISTORY_FILE, 'utf8').split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } })
96
- .filter((e) => e && e.project === cwd).map((e) => e.display).slice(-500);
97
- } catch { return []; }
107
+ let text;
108
+ try { text = fs.readFileSync(HISTORY_FILE, 'utf8'); } catch { return []; }
109
+ const entries = text.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter((e) => e && typeof e.display === 'string');
110
+ if (text.length > HISTORY_PRUNE_CHARS) pruneHistory(entries);
111
+ return entries.filter((e) => e.project === cwd).slice(-HISTORY_KEEP).map((e) => (Array.isArray(e.pastes) && e.pastes.length
112
+ ? { text: e.display, parts: { pastes: e.pastes, quotes: Array.isArray(e.quotes) ? e.quotes : [] } }
113
+ : e.display));
114
+ }
115
+
116
+ function pruneHistory(entries) {
117
+ const count = new Map();
118
+ const keep = [];
119
+ for (let i = entries.length - 1; i >= 0; i--) {
120
+ const n = count.get(entries[i].project) || 0;
121
+ if (n >= HISTORY_KEEP) continue;
122
+ count.set(entries[i].project, n + 1);
123
+ keep.push(entries[i]);
124
+ }
125
+ try { // whole or not at all; an entry another window adds meanwhile may be lost, which costs an up-arrow
126
+ const tmp = `${HISTORY_FILE}.${process.pid}.tmp`;
127
+ fs.writeFileSync(tmp, keep.reverse().map((e) => JSON.stringify(e)).join('\n') + '\n');
128
+ fs.renameSync(tmp, HISTORY_FILE);
129
+ } catch { /* pruned another time */ }
98
130
  }
99
131
 
100
- function appendHistory(cwd, text) {
132
+ function appendHistory(cwd, text, parts = null) {
133
+ const entry = { display: text, project: cwd, timestamp: Date.now() };
134
+ const pastes = (parts?.pastes || []).filter(([label]) => text.includes(label));
135
+ if (pastes.length && pastes.reduce((n, [, content]) => n + String(content).length, 0) <= HISTORY_PASTE_CHARS) {
136
+ entry.pastes = pastes;
137
+ if (parts.quotes?.length) entry.quotes = parts.quotes;
138
+ }
101
139
  try {
102
140
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
103
- fs.appendFileSync(HISTORY_FILE, JSON.stringify({ display: text, project: cwd, timestamp: Date.now() }) + '\n');
141
+ fs.appendFileSync(HISTORY_FILE, JSON.stringify(entry) + '\n');
104
142
  } catch { /* ignore */ }
105
143
  }
106
144
 
@@ -231,6 +269,7 @@ export class App {
231
269
  this.cost = 0; // what this conversation's requests have cost so far (USD at list prices): the footer and /cost
232
270
  this.fileIndex = new FileIndex(cwd, () => this.runtime?.config);
233
271
  this.store = new SessionStore(cwd);
272
+ SessionStore.onError = (e, store) => this.notice(`Could not save the conversation to ${store.file} (${e.code || e.message}): it is written again whole before a restart, but /resume may miss what was not saved.`, 'warn');
234
273
  // What the terminal prints goes to the remote page too, except what it is told about as events.
235
274
  this.screen.onLog = (items) => {
236
275
  const lines = () => items.flatMap((i) => (Array.isArray(i) ? i : [i])).flatMap((l) => String(l).split(/\r?\n/));
@@ -239,7 +278,7 @@ export class App {
239
278
  };
240
279
  this.editor = new Editor({
241
280
  history: loadHistory(cwd),
242
- onSubmit: (value, raw, images) => { try { this.onSubmit(value, raw, images); } catch (e) { this.logError(e); } },
281
+ onSubmit: (value, raw, images, display, parts) => { try { this.onSubmit(value, raw, images, display, parts); } catch (e) { this.logError(e); } },
243
282
  onDoubleEscape: () => this.openRewind(),
244
283
  imageFromPath: (p) => {
245
284
  const r = imageFromFile(resolvePath(p, this.cwd));
@@ -283,6 +322,10 @@ export class App {
283
322
  this.screen.schedule();
284
323
  };
285
324
  this.commands = buildCommands(this);
325
+ // The window of the model in use may come from the gateway's model list (see Config.resolveModel): asked for now,
326
+ // so that the footer shows it before the first request.
327
+ // not in the self-check a restart runs first: that would ask the gateway once more for every restart
328
+ if (!this.driven && !this.selfCheck) loadGatewayModels(this.runtime.config).then(() => this.screen.schedule());
286
329
  // What the session showed before a restart: scrolled back to in fullscreen, repainted after a resize otherwise.
287
330
  if (Array.isArray(this.flags.restart?.screenHistory)) this.screen.history = this.flags.restart.screenHistory.filter((l) => typeof l === 'string');
288
331
  if (this.fullscreenWanted()) this.screen.setFull(true);
@@ -319,7 +362,7 @@ export class App {
319
362
  if (restart) this.continueAfterRestart(restart);
320
363
  else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
321
364
  // Nothing configured yet: the gateway is the default, and its browser login starts first.
322
- else if (this.config.usesGateway && !gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY)) {
365
+ else if (!gatewayLogin(this.config.gatewayUrl)) {
323
366
  Promise.resolve(this.commands.get('login').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
324
367
  }
325
368
  this.fileIndex.refresh();
@@ -412,6 +455,7 @@ export class App {
412
455
  clearInterval(this.spinnerTimer);
413
456
  this.sourceWatch?.close();
414
457
  shutdownBackgroundShells();
458
+ shutdownInterpreters();
415
459
  this.runtime?.tasks.killAll();
416
460
  this.runtime?.mcp.close();
417
461
  this.peers?.close();
@@ -601,7 +645,7 @@ export class App {
601
645
  const env = this.config.env;
602
646
  if (!onlineEnabled(env)) return false;
603
647
  if (this.driven && !/^(1|true|yes|on)$/i.test(env.CLAUDE_PRO_ONLINE || '')) return false;
604
- return Boolean(gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY));
648
+ return Boolean(gatewayLogin(this.config.gatewayUrl));
605
649
  }
606
650
 
607
651
  // Online at the gateway from the start when this computer is logged in, and after a restart with the same
@@ -616,7 +660,7 @@ export class App {
616
660
  }
617
661
 
618
662
  // Connect this session to the gateway (see remote.js): the web page and the sessions on the account's other
619
- // computers reach it from then on. Needs the gateway login from /login or CLAUDE_PRO_GATEWAY_API_KEY; throws
663
+ // computers reach it from then on. Needs the gateway login from /login; throws
620
664
  // {code: 'NO_GATEWAY_LOGIN'} without it. A gateway that cannot be reached now is tried again in the background;
621
665
  // one that refuses the key throws, and that key is not tried again (see syncRemote).
622
666
  startRemote({ id } = {}) {
@@ -630,7 +674,7 @@ export class App {
630
674
  syncRemote() {
631
675
  if (this.exiting) return Promise.resolve(null);
632
676
  if (this.remoteStarting) return this.remoteStarting.catch(() => null);
633
- const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
677
+ const login = gatewayLogin(this.config.gatewayUrl);
634
678
  const r = this.remote;
635
679
  // logged out, or another account: not this account's session any more
636
680
  if (r && (!login || login.apiKey !== r.apiKey || normalizeGatewayUrl(login.url || this.config.gatewayUrl) !== normalizeGatewayUrl(r.base))) this.stopRemote();
@@ -643,8 +687,18 @@ export class App {
643
687
  }
644
688
 
645
689
  async connectRemote({ id }) {
646
- const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
690
+ const login = gatewayLogin(this.config.gatewayUrl);
647
691
  if (!login) throw Object.assign(new Error(`this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login logs in)`), { code: 'NO_GATEWAY_LOGIN' });
692
+ // What the page may do here, besides watching (see remote.js): nothing with CLAUDE_PRO_REMOTE_COMMANDS=0.
693
+ const commands = remoteCommandsEnabled(this.config.env) ? {
694
+ send: (body) => this.remoteSend(body.text, body.images),
695
+ interrupt: () => this.remoteInterrupt(),
696
+ answer: (body) => this.answerDialog(body),
697
+ options: () => this.remoteOptions(),
698
+ suggest: (body) => this.remoteSuggest(body),
699
+ list: (body) => this.remoteList(body),
700
+ output: (body) => this.remoteOutput(body),
701
+ } : {};
648
702
  const remote = new RemoteControl({
649
703
  gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
650
704
  id,
@@ -659,6 +713,7 @@ export class App {
659
713
  ...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
660
714
  ],
661
715
  status: () => this.remoteStatus(),
716
+ ...commands,
662
717
  peerMessage: (msg) => this.onPeerMessage(msg),
663
718
  changed: () => {
664
719
  this.screen.schedule();
@@ -701,11 +756,12 @@ export class App {
701
756
  if (r) {
702
757
  const who = r.account ? ` as ${r.account}` : '';
703
758
  const pages = r.viewers ? c.dim(` · ${r.viewers} page${r.viewers === 1 ? '' : 's'} open now`) : '';
704
- const text = r.online ? `${c.green('online')}${who}${pages}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
759
+ const readOnly = r.commands.length ? '' : c.dim(' · read-only on the page (CLAUDE_PRO_REMOTE_COMMANDS=0)');
760
+ const text = r.online ? `${c.green('online')}${who}${pages}${readOnly}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
705
761
  return { text };
706
762
  }
707
763
  if (this.remoteStarting) return { text: 'connecting…' };
708
- const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
764
+ const login = gatewayLogin(this.config.gatewayUrl);
709
765
  if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`) };
710
766
  if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)') };
711
767
  if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)') };
@@ -756,10 +812,13 @@ export class App {
756
812
  contextUsed() {
757
813
  const a = this.agent;
758
814
  if (a.lastContextTokens) return a.contextEstimate;
759
- const key = `${a.messages.length}|${this.runtime.tools.length}`;
815
+ // not built yet: the prompt is counted once git has answered in the background (building it here blocked on git)
816
+ const ready = this.runtime.systemPromptReady?.() ?? true;
817
+ const key = `${a.messages.length}|${this.runtime.tools.length}|${ready}`;
760
818
  if (this.contextGuess?.key !== key) {
819
+ if (!ready) this.runtime.prepareSnapshot().then(() => this.screen.schedule());
761
820
  let used = 0;
762
- try { used = estimateTokens(this.runtime.systemPrompt()) + estimateTokens(a.toolSchemas()) + estimateTokens(a.messages); } catch { /* 0 */ }
821
+ try { used = (ready ? estimateTokens(this.runtime.systemPrompt()) : 0) + estimateTokens(a.toolSchemas()) + estimateTokens(a.messages); } catch { /* 0 */ }
763
822
  this.contextGuess = { key, used };
764
823
  }
765
824
  return this.contextGuess.used;
@@ -778,12 +837,147 @@ export class App {
778
837
  if (!d) return null;
779
838
  d.remoteId ??= ++this.remoteDialogs;
780
839
  const base = { id: d.remoteId, title: d.title || '', question: d.question || '', body: d.body || [], markdown: d.markdown || null };
781
- // a question answered with typed text (TextDialog): a text box on the page, answered with {id, text}
782
- if (d.input) return { ...base, input: { placeholder: d.input.placeholder || '', value: d.value || '', multiline: Boolean(d.input.multiline) } };
783
840
  if (!Array.isArray(d.options)) return base;
784
841
  return { ...base, multi: Boolean(d.multi), options: d.options.map((o) => ({ label: String(o.label ?? ''), description: o.description || '', other: o.value === '__other__' })) };
785
842
  }
786
843
 
844
+ // ---------------------------------------------------------------- the page's commands (see remote.js)
845
+
846
+ // The answer to the dialog the status showed the page (remoteDialog): {id, index}, {id, indices}, {id, text,
847
+ // indices?} (its "other" option) or {id, cancel: true}.
848
+ answerDialog({ id, index, indices, text, cancel } = {}) {
849
+ const d = this.dialogs[0];
850
+ if (!d || d.remoteId !== id) throw new Error('That question is no longer open.');
851
+ if (cancel) { d.resolve(d.cancelValue); return {}; }
852
+ if (!Array.isArray(d.options)) throw new Error('This dialog cannot be answered from the page.');
853
+ const valueAt = (i) => {
854
+ const o = d.options[i];
855
+ if (!Number.isInteger(i) || !o || o.value === '__other__') throw new Error('No such option.');
856
+ return o.value;
857
+ };
858
+ if (typeof text === 'string') {
859
+ if (!text.trim()) throw new Error('Type an answer first.');
860
+ d.resolve(d.multi ? [...(indices || []).map(valueAt), text.trim()] : text.trim());
861
+ } else if (d.multi) {
862
+ if (!indices?.length) throw new Error('Choose at least one option.');
863
+ d.resolve(indices.map(valueAt));
864
+ } else {
865
+ d.resolve(valueAt(index));
866
+ }
867
+ this.screen.schedule();
868
+ return {};
869
+ }
870
+
871
+ // A message from the page: as if typed in the input box and sent (a turn, queued while one runs; /commands, !,
872
+ // #, @session), its images as if pasted there. Images alone go as their placeholders, which is what the input box
873
+ // sends for them.
874
+ remoteSend(text, images) {
875
+ const pictures = remoteImages(images);
876
+ let value = String(text ?? '').replace(/\r\n/g, '\n');
877
+ if (!value.trim() && pictures.length) value = pictures.map((_, i) => `[Image #${i + 1}]`).join(' ');
878
+ if (!value.trim()) throw new Error('The message is empty.');
879
+ // The user's rule: the page does not end or restart the session, nor update claude-pro; only the terminal does
880
+ // (the automatic update goes on as before: it is not a command of the page). The gateway refuses these too, with
881
+ // the same pattern and message; this holds when it does not (another gateway, or one that misses them).
882
+ if (TERMINAL_ONLY.test(value)) throw new Error('结束、重启会话和更新 claude-pro 只能在终端里操作');
883
+ if (this.exiting) throw new Error('The session is ending.');
884
+ if (this.isTurnRunning() && value.trim().startsWith('/')) throw new Error('Commands wait until the current task is done (or stopped).');
885
+ if (this.dialogs.length && !this.isTurnRunning()) throw new Error('A question is open: answer it first.');
886
+ const queued = this.isTurnRunning();
887
+ this.onSubmit(value, value, pictures);
888
+ this.screen.schedule();
889
+ return { queued };
890
+ }
891
+
892
+ // Esc: the turn stops, and the questions waiting for an answer are cancelled.
893
+ remoteInterrupt() {
894
+ for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
895
+ this.interrupt();
896
+ this.screen.schedule();
897
+ return {};
898
+ }
899
+
900
+ // For the page's model and effort menus: what /model and /effort offer (in plain text; the page sends /model
901
+ // <value> or /effort <value>), what is chosen (`current`), and the model and effort in use, as the status says.
902
+ async remoteOptions() {
903
+ const cfg = this.config;
904
+ const [models, efforts] = await Promise.all([modelChoices(cfg), effortChoices(cfg)]);
905
+ const chosen = cfg.modelOverride || 'default';
906
+ const current = models.find((o) => o.value === chosen) || models.find((o) => o.value !== 'default' && cfg.resolveModel(o.value).id === cfg.model.id);
907
+ const effortChosen = cfg.effortOverride || 'default';
908
+ const { effort } = modelInfo(cfg);
909
+ return {
910
+ model: cfg.model.id,
911
+ models: models.map((o) => ({ ...o, ...(o === current ? { current: true } : {}) })),
912
+ effort: effort || defaultEffort(cfg.model.id, cfg),
913
+ efforts: efforts.options.map((o) => ({ ...o, ...(o.value === effortChosen ? { current: true } : {}) })),
914
+ };
915
+ }
916
+
917
+ // For the page's input box: what the input box here would suggest (/commands, @files and @sessions), in plain
918
+ // text, without anything happening here. Sessions on the other computers are asked for first when the list is old.
919
+ async remoteSuggest(body = {}) {
920
+ const text = String(body.text ?? '');
921
+ const cursor = Number.isInteger(body.cursor) ? Math.max(0, Math.min(text.length, body.cursor)) : text.length;
922
+ if (/(^|\s)@[^\s@"]*$/u.test(text.slice(0, cursor)) && this.remote?.online && Date.now() - this.remotePeersAt > 10_000) {
923
+ await Promise.race([this.refreshRemotePeers(), new Promise((r) => setTimeout(r, 3000))]);
924
+ }
925
+ const found = this.suggest(text, cursor, { quiet: true });
926
+ if (!found?.items?.length) return { items: [] };
927
+ const plain = (s) => (s == null ? '' : stripAnsi(String(s)));
928
+ return {
929
+ items: found.items.slice(0, 50).map((it) => ({ value: it.value, label: plain(it.label ?? it.value), description: plain(it.description), submitOnEnter: Boolean(it.submitOnEnter), noSpace: Boolean(it.noSpace) })),
930
+ from: found.from,
931
+ to: found.to,
932
+ };
933
+ }
934
+
935
+ // For the page's directory browser (/cd): the directories in `path` ("": this session's working directory), with
936
+ // the drives, the home directory and where sessions ran lately.
937
+ remoteList(body = {}) {
938
+ const wanted = typeof body.path === 'string' && body.path.trim() ? body.path : (this.agent.cwd || this.cwd);
939
+ return listDirectory(wanted, {
940
+ recent: () => {
941
+ if (!this.recentDirs || Date.now() - this.recentDirs.at > 30_000) this.recentDirs = { at: Date.now(), list: recentDirectories({ projects: path.join(CONFIG_DIR, 'projects') }) };
942
+ return this.recentDirs.list;
943
+ },
944
+ });
945
+ }
946
+
947
+ // For the page's "the whole output": the full result of the tool call `id` ({text, truncated, running?}, at most
948
+ // 1 MB of UTF-8): the file it was saved to when it was too long for the conversation or cleared from it later,
949
+ // and what it printed so far while it runs.
950
+ remoteOutput({ id } = {}) {
951
+ if (typeof id !== 'string' || !id) throw new Error('Which tool call?');
952
+ const MAX = 1024 * 1024;
953
+ const cut = (text, running = false) => {
954
+ const buf = Buffer.from(text, 'utf8');
955
+ const truncated = buf.length > MAX;
956
+ // (a character cut at the end decodes as U+FFFD, which is then dropped)
957
+ const shown = truncated ? buf.subarray(0, MAX).toString('utf8').replace(/\ufffd$/, '') : text;
958
+ return { text: shown, truncated, ...(running ? { running } : {}) };
959
+ };
960
+ let result = null;
961
+ for (const m of this.agent.messages) {
962
+ if (m.role !== 'user' || !Array.isArray(m.content)) continue;
963
+ for (const b of m.content) if (b.type === 'tool_result' && b.tool_use_id === id) result = b;
964
+ }
965
+ if (!result) {
966
+ const live = this.active.find((e) => e.tu?.id === id);
967
+ if (live) return cut(live.progressAll?.() ?? String(live.progress || ''), true);
968
+ throw new Error('There is no such tool call in this conversation.');
969
+ }
970
+ let text = typeof result.content === 'string' ? result.content
971
+ : (Array.isArray(result.content) ? result.content : []).map((b) => (b.type === 'text' ? b.text : b.type === 'image' ? '[image]' : '')).join('\n');
972
+ // saved whole in the project's tool-results (a large result, a Bash output, a result cleared after a pause)
973
+ const saved = /(?:saved to:?|saved at)\s+(\S+?\.txt)\b/.exec(text)?.[1];
974
+ const results = path.join(CONFIG_DIR, 'projects');
975
+ if (saved && path.resolve(saved).startsWith(results + path.sep) && path.resolve(saved).includes(`${path.sep}tool-results${path.sep}`)) {
976
+ try { text = fs.readFileSync(saved, 'utf8'); } catch { /* the reference is what there is */ }
977
+ }
978
+ return cut(text);
979
+ }
980
+
787
981
  // ---------------------------------------------------------------- restarting (see restart.js)
788
982
 
789
983
  // What a restart would kill: agents and shells that are still running in the background.
@@ -831,12 +1025,19 @@ export class App {
831
1025
  if (request.cwd) {
832
1026
  try { moved = moveSession(this.store.file, this.store.id, request.cwd); } catch (e) { this.notice(`Could not change the directory: ${e.message}`, 'warn'); return; }
833
1027
  }
1028
+ // a write of the conversation failed at some point: the file lacks part of it, and the next process goes on from it
1029
+ if (this.store.lost) { this.store.lost = false; this.store.reset(this.agent.messages); }
834
1030
  const state = {
835
1031
  at: now,
836
1032
  reason: request.reason || '',
837
1033
  continueWith: request.continueTurn ? restartNote(request) : '',
838
1034
  cwd: request.cwd || this.cwd,
839
1035
  changedDirectory: Boolean(request.cwd),
1036
+ // where the agent's shell is (a `cd` in Bash moves it): the next process goes on there, not at the project's root
1037
+ agentCwd: request.cwd ? null : this.agent.cwd,
1038
+ // the browser instance in use (one picked with /tabs may be any of several): the next process connects to it
1039
+ // again, where the tab ids in the conversation are still its tabs'
1040
+ browser: browserSession.preferred || null,
840
1041
  sessionId: this.store.id,
841
1042
  sessionFile: moved?.file || this.store.file,
842
1043
  modelOverride: cfg.modelOverride,
@@ -846,7 +1047,9 @@ export class App {
846
1047
  draft: this.editor.text,
847
1048
  screenHistory: this.screen.history.slice(-3000),
848
1049
  draftCursor: this.editor.cursor,
849
- queue: this.queue.map((q) => ({ text: q.text, images: q.images || [] })),
1050
+ draftParts: this.editor.draftParts(),
1051
+ // `peer`: a task of another session, which gets the answer of the turn that handles it
1052
+ queue: this.queue.map((q) => ({ text: q.text, images: q.images || [], display: q.display ?? null, peer: q.peer || null })),
850
1053
  checkpoints: this.runtime.checkpoints.snapshot(),
851
1054
  // a /cd is the user's: it does not count towards the restarts that look like a loop
852
1055
  restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), ...(request.cwd ? [] : [now])],
@@ -891,8 +1094,12 @@ export class App {
891
1094
  this.loadSession(state.sessionFile, state.sessionId, { quiet: true });
892
1095
  if (Array.isArray(state.todos)) this.agent.todos = state.todos;
893
1096
  if (state.checkpoints) this.runtime.checkpoints.adopt(state.checkpoints);
1097
+ if (typeof state.agentCwd === 'string' && state.agentCwd !== this.cwd) {
1098
+ try { if (fs.statSync(state.agentCwd).isDirectory()) this.agent.cwd = state.agentCwd; } catch { /* gone: the project's root */ }
1099
+ }
894
1100
  }
895
- if (typeof state.draft === 'string' && state.draft) this.editor.set(state.draft, state.draftCursor);
1101
+ if (state.browser && typeof state.browser === 'object' && typeof state.browser.dir === 'string') browserSession.preferred = state.browser;
1102
+ if (typeof state.draft === 'string' && state.draft) this.editor.restoreDraft(state.draft, state.draftCursor, state.draftParts);
896
1103
  // Fullscreen starts on an empty screen: without what the process before showed (an older version, or one
897
1104
  // that ran classic), the conversation is drawn again from the session.
898
1105
  if (this.screen.full && resumable && !Array.isArray(state.screenHistory)) this.printTranscript(this.agent.messages.slice(-80));
@@ -911,13 +1118,20 @@ export class App {
911
1118
  const queued = (Array.isArray(state.queue) ? state.queue : []).filter((q) => q && typeof q.text === 'string' && q.text.trim());
912
1119
  if (!state.continueWith && !queued.length) return;
913
1120
  const typed = queued.map((q) => q.text).join('\n\n');
914
- this.startTurn([state.continueWith, typed].filter(Boolean).join('\n\n'), { echo: queued.length > 0, display: typed, topic: typed, images: queued.flatMap((q) => q.images || []) });
1121
+ const shown = queued.map((q) => (typeof q.display === 'string' ? q.display : q.text)).join('\n\n');
1122
+ this.startTurn([state.continueWith, typed].filter(Boolean).join('\n\n'), {
1123
+ echo: queued.length > 0,
1124
+ display: shown,
1125
+ topic: shown,
1126
+ images: queued.flatMap((q) => (Array.isArray(q.images) ? q.images : [])),
1127
+ peers: queued.map((q) => q.peer).filter((p) => p && typeof p === 'object' && p.from),
1128
+ });
915
1129
  }
916
1130
 
917
1131
  // Follow the program's own source: once a turn is over (or at once when idle) a change to it is loaded by
918
1132
  // a restart, if the new code starts.
919
1133
  startSourceWatch() {
920
- if (!canRestart() || /^(0|false|no|off)$/i.test(this.config.env.CLAUDE_PRO_AUTO_RESTART || '')) return;
1134
+ if (!canRestart()) return;
921
1135
  this.sourceWatch = watchSource(INSTALL_DIR, (file) => {
922
1136
  this.sourceChanged = file || true;
923
1137
  // another window (or npm) installed a new version: say so, and load it once this session is idle. In a
@@ -948,18 +1162,18 @@ export class App {
948
1162
  return;
949
1163
  }
950
1164
  if (this.isTurnRunning() || this.dialogs.length) { this.sourceChanged = changed; return; } // something started meanwhile: later
951
- this.requestRestart({ reason: this.updateRestart ? `updated to ${APP_NAME} ${this.updateRestart}` : 'source changed', force: true });
1165
+ const r = this.requestRestart({ reason: this.updateRestart ? `updated to ${APP_NAME} ${this.updateRestart}` : 'source changed', force: true });
1166
+ // refused (too many restarts in a row): say so, or later changes would go unloaded without a word
1167
+ if (!r.ok) this.notice(`The program's source changed, but it was not restarted to load it: ${r.message.replace(/ That looks like a loop:.*$/, '')} A change after that window loads it, or /restart once it has passed.`, 'warn');
952
1168
  }
953
1169
 
954
- // A newer version on npm (see updater.js): it is installed once no session of this machine is working, and then
955
- // loaded by a restart (this session's; the others restart when they see the files change). `force`: the /update
956
- // command, which also says when there is nothing to do. `quiet`: the periodic check, which says nothing when an
957
- // install fails (it is tried again in a minute).
958
- async autoUpdate({ force = false, quiet = false } = {}) {
959
- if (this.updating) { if (force) this.notice(`${APP_NAME} ${this.updating} is being installed.`); return; }
1170
+ // /update: a newer version on npm (see updater.js) is installed once no session of this machine is working, and
1171
+ // then loaded by a restart (this session's; the others restart when they see the files change).
1172
+ async updateFromNpm() {
1173
+ if (this.updating) { this.notice(`${APP_NAME} ${this.updating} is being installed.`); return; }
960
1174
  let r;
961
1175
  try {
962
- r = await checkForUpdate({ force, env: { ...process.env, ...this.config.env } });
1176
+ r = await checkForUpdate();
963
1177
  } catch (e) {
964
1178
  r = { status: 'failed', error: e.message };
965
1179
  }
@@ -967,18 +1181,17 @@ export class App {
967
1181
  if (r.status === 'available') {
968
1182
  if (this.pendingUpdate !== r.version) {
969
1183
  this.pendingUpdate = r.version;
970
- this.updateQuiet = quiet;
971
1184
  this.screen.schedule();
972
1185
  }
973
- if (force && this.working()) this.notice(`${APP_NAME} ${r.version} is out: it is installed as soon as this session's work is done.`);
974
- await this.maybeInstallUpdate({ force });
1186
+ if (this.working()) this.notice(`${APP_NAME} ${r.version} is out: it is installed as soon as this session's work is done.`);
1187
+ await this.maybeInstallUpdate({ force: true });
975
1188
  } else if (r.status === 'installed') {
976
- if (force || this.updateRestart !== r.version) this.notice(`${APP_NAME} ${r.version} is installed already; this session restarts to load it ${this.working() ? 'once its work is done' : 'now'}.`);
1189
+ this.notice(`${APP_NAME} ${r.version} is installed already; this session restarts to load it ${this.working() ? 'once its work is done' : 'now'}.`);
977
1190
  this.updateRestart = r.version;
978
1191
  if (canRestart()) { this.sourceChanged ||= true; if (!this.isTurnRunning()) this.maybeAutoReload(); }
979
1192
  } else if (r.status === 'failed') {
980
- if (force || (r.version && !quiet)) this.notice(`Could not update ${APP_NAME}${r.version ? ` to ${r.version}` : ''}: ${r.error}`, 'warn');
981
- } else if (force) {
1193
+ this.notice(`Could not update ${APP_NAME}${r.version ? ` to ${r.version}` : ''}: ${r.error}`, 'warn');
1194
+ } else {
982
1195
  this.notice(r.status === 'dev' ? `This copy runs from a source checkout (${INSTALL_DIR}): update it with git.` : `${APP_NAME} ${VERSION} is the latest version.`);
983
1196
  }
984
1197
  }
@@ -1032,7 +1245,7 @@ export class App {
1032
1245
  }
1033
1246
  return;
1034
1247
  }
1035
- if (force || !this.updateQuiet) this.notice(`Could not update ${APP_NAME} to ${version}: ${r.error}`, 'warn');
1248
+ this.notice(`Could not update ${APP_NAME} to ${version}: ${r.error}`, 'warn');
1036
1249
  }
1037
1250
 
1038
1251
  printWelcome() {
@@ -1053,7 +1266,7 @@ export class App {
1053
1266
  c.claude('╰' + '─'.repeat(w - 2) + '╯'),
1054
1267
  ];
1055
1268
  lines.push('', c.dim(' Full access: every tool runs immediately, nothing is ever asked. File edits are checkpointed;'), c.dim(' /rewind puts files and/or the conversation back (shell-command changes are not tracked).'));
1056
- if (!gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY)) lines.push('', c.yellow(` ⚠ Not logged in to the gateway ${cfg.gatewayUrl}. Run /login.`));
1269
+ if (!gatewayLogin(cfg.gatewayUrl)) lines.push('', c.yellow(` ⚠ Not logged in to the gateway ${cfg.gatewayUrl}. Run /login.`));
1057
1270
  const mcp = this.runtime.mcp.status();
1058
1271
  if (mcp.length) {
1059
1272
  const ok = mcp.filter((m) => m.status === 'connected').length;
@@ -1065,15 +1278,15 @@ export class App {
1065
1278
 
1066
1279
  // ---------------------------------------------------------------- input
1067
1280
 
1068
- // Fullscreen (see screen.js) unless CLAUDE_PRO_TUI=default, as Claude Code's /tui: the input box fixed at the
1069
- // bottom of the window, the conversation scrolled inside the program. Not in the tests that drive the App.
1281
+ // Fullscreen unless settings.tui selects the classic renderer; a driven test defaults to classic.
1070
1282
  fullscreenWanted() {
1071
- const mode = String(this.config.env.CLAUDE_PRO_TUI || (this.driven ? 'default' : 'fullscreen')).toLowerCase();
1283
+ const mode = this.driven && this.config.settings.tui == null ? 'default' : this.config.setting('tui');
1072
1284
  return mode === 'fullscreen' && this.stdout.isTTY !== false;
1073
1285
  }
1074
1286
 
1075
1287
  // Fullscreen: the wheel scrolls the conversation (3 rows a notch); a drag,
1076
1288
  // a double or a triple click selects text. Selection is copied only with Ctrl+C.
1289
+ // In the input box a click moves the cursor and a drag selects its text (see Editor.mouse).
1077
1290
  onMouse(m) {
1078
1291
  if (!this.screen.full || this.exiting) return;
1079
1292
  if (m.button & 64) {
@@ -1083,7 +1296,30 @@ export class App {
1083
1296
  return;
1084
1297
  }
1085
1298
  // Right-click is intentionally inert. Clipboard operations use Ctrl+C and Ctrl+V only.
1086
- this.screen.mouse(m);
1299
+ const had = this.screen.selection;
1300
+ const hadInput = this.editor.selection;
1301
+ const r = this.screen.mouse(m);
1302
+ if (r?.input) this.editor.mouse(r.input);
1303
+ else if ((m.button & 3) === 0 && !(m.button & 32) && !m.release) this.editor.clearSelection(); // a press elsewhere
1304
+ if ((this.screen.selection && this.screen.selection !== had) || (this.editor.selection && this.editor.selection !== hadInput)) {
1305
+ this.flashMessage = null; // the footer says what a selection takes
1306
+ this.screen.schedule();
1307
+ }
1308
+ }
1309
+
1310
+ // Quote what is selected in the conversation in the message being written, as ChatGPT's "Ask ChatGPT" does:
1311
+ // ctrl+q (alt+q where the terminal keeps ctrl+q), as the footer says while there is a selection. The box shows
1312
+ // "[Quote #1 +12 lines]"; the model gets the text and the line of the conversation it is under (see
1313
+ // Editor.insertQuote), so that it knows which part, and which file or command, the question is about.
1314
+ quoteSelection() {
1315
+ if (!this.screen.full) { this.flash('Quoting works in fullscreen (/tui fullscreen): select text with the mouse, then ctrl+q', 'warn'); return; }
1316
+ const quote = this.screen.selectionQuote();
1317
+ if (!quote?.text.trim()) { this.flash('Select part of the conversation first (drag over it, or double/triple-click), then ctrl+q', 'warn'); return; }
1318
+ if (this.dialogs.length) { this.flash('Answer the open question first, then quote', 'warn'); return; }
1319
+ if (this.finder) this.closeFind();
1320
+ this.screen.clearSelection();
1321
+ const label = this.editor.insertQuote(quote.text, quote.source);
1322
+ this.flash(`${label}${quote.source ? ` from ${quote.source}` : ''}: type your question below it`);
1087
1323
  }
1088
1324
 
1089
1325
  copyText(text) {
@@ -1190,10 +1426,19 @@ export class App {
1190
1426
  // then does what it does.
1191
1427
  if (this.screen.selection) {
1192
1428
  if (key.ctrl && key.name === 'c') { this.copyText(this.screen.selectedText()); this.screen.clearSelection(); return; }
1429
+ if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; }
1193
1430
  this.screen.clearSelection();
1194
1431
  if (key.name === 'escape') return;
1195
1432
  }
1196
1433
  }
1434
+ // A selection in the input box (see Editor.mouse), the same way: ctrl+c copies it (and neither interrupts nor
1435
+ // clears the message), esc only clears it, any other key clears it and then does what it does.
1436
+ if (this.editor.selection) {
1437
+ const shown = !this.dialogs.length && !this.finder; // else the box is not on screen, and the key is not for it
1438
+ if (shown && key.ctrl && key.name === 'c') { this.copyText(this.editor.selectedText()); this.editor.clearSelection(); return; }
1439
+ this.editor.clearSelection();
1440
+ if (shown && key.name === 'escape') return;
1441
+ }
1197
1442
  if (key.name === 'paste-start' || key.sequence === '\x1b[200~') {
1198
1443
  this.bracketedPaste = { raw: '' };
1199
1444
  return;
@@ -1201,6 +1446,7 @@ export class App {
1201
1446
  if (key.ctrl && key.name === 'c' && this.finder && !this.dialogs.length) { this.closeFind(); return; } // not the hidden input's text
1202
1447
  if (key.ctrl && key.name === 'c') { this.onCtrlC(); return; }
1203
1448
  if ((key.ctrl || key.meta) && key.name === 'v') { this.pasteClipboard(); return; } // alt+v: the clipboard's image
1449
+ if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; } // nothing selected: says how
1204
1450
  const dialog = this.dialogs[0];
1205
1451
  if (dialog) {
1206
1452
  dialog.handleKey(str, key);
@@ -1209,15 +1455,11 @@ export class App {
1209
1455
  }
1210
1456
  if (key.ctrl && key.name === 'f') { this.openFind(); return; }
1211
1457
  if (this.finder) { this.findKey(str, key); this.screen.schedule(); return; }
1212
- if (key.ctrl && key.name === 'o') {
1213
- this.verbose = !this.verbose;
1214
- this.notice(this.verbose ? 'Verbose mode on: showing thinking and full tool output' : 'Verbose mode off', 'info');
1215
- return;
1216
- }
1217
1458
  if (key.ctrl && key.name === 't') { this.showTodos = !this.showTodos; this.screen.schedule(); return; }
1218
1459
  if (key.ctrl && key.name === 'l') { if (this.screen.full) this.screen.repaint(); else this.screen.clearScreen(); return; }
1219
1460
  if (key.ctrl && key.name === 'd' && !this.editor.text) { this.keyboardExit(); return; }
1220
- if (key.name === 'escape' && this.isTurnRunning()) { this.interrupt(); return; }
1461
+ // esc closes an open completion list first (the editor does that), and only then stops the turn
1462
+ if (key.name === 'escape' && this.isTurnRunning() && !this.editor.suggestions) { this.interrupt(); return; }
1221
1463
  this.exitArmed = 0;
1222
1464
  this.editor.handleKey(str, key);
1223
1465
  this.screen.schedule();
@@ -1326,19 +1568,20 @@ export class App {
1326
1568
  ];
1327
1569
  }
1328
1570
 
1329
- onSubmit(value, raw, images = []) {
1571
+ // `display`: how the message shows in the transcript when that is not `value` (a quote shows its first lines).
1572
+ onSubmit(value, raw, images = [], display = undefined, parts = null) {
1330
1573
  const text = value.trim();
1331
1574
  if (!text) { this.screen.schedule(); return; }
1332
1575
  if (this.screen.scrolledUp) this.screen.scrollBy('bottom'); // what was sent, and what comes of it, is in view
1333
- appendHistory(this.cwd, raw);
1576
+ appendHistory(this.cwd, raw, parts);
1334
1577
  if (this.sendTypedToPeer(text)) return;
1335
1578
  if (this.isTurnRunning()) {
1336
1579
  if (text.startsWith('/')) { this.notice('Wait for the current task to finish (or press Esc) before running commands.', 'warn'); return; }
1337
- this.queue.push({ text: value, images });
1580
+ this.queue.push({ text: value, images, ...(display ? { display } : {}) });
1338
1581
  this.screen.schedule();
1339
1582
  return;
1340
1583
  }
1341
- if (images.length) { this.startTurn(value, { images }); return; }
1584
+ if (images.length) { this.startTurn(value, { images, display }); return; }
1342
1585
  if (text === '?') { this.screen.log(this.shortcutsHelp()); return; }
1343
1586
  if (raw.startsWith('!')) { this.runBashMode(value.slice(1).trim()); return; }
1344
1587
  if (raw.startsWith('#')) { this.addMemory(value.slice(1).trim()); return; }
@@ -1351,11 +1594,11 @@ export class App {
1351
1594
  Promise.resolve(cmd.run(args, rest)).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
1352
1595
  return;
1353
1596
  }
1354
- if (!/^\/[\w:-]+$/.test(text.split(/\s/)[0])) { this.startTurn(value); return; } // e.g. a path like /usr/bin
1597
+ if (!/^\/[\w:-]+$/.test(text.split(/\s/)[0])) { this.startTurn(value, { display }); return; } // e.g. a path like /usr/bin
1355
1598
  this.notice(`Unknown command: /${name}. Type /help for the list of commands.`, 'warn');
1356
1599
  return;
1357
1600
  }
1358
- this.startTurn(value);
1601
+ this.startTurn(value, { display });
1359
1602
  }
1360
1603
 
1361
1604
  // `@name message`: the message goes to that session, as a task for it. A session on another computer of the
@@ -1391,12 +1634,13 @@ export class App {
1391
1634
  shortcutsHelp() {
1392
1635
  const rows = [
1393
1636
  ['! for bash mode', 'double tap esc to clear input'],
1394
- ['/ for commands', 'ctrl + o to toggle verbose output'],
1637
+ ['/ for commands', '/verbose for detailed tool output'],
1395
1638
  ['@ for files and sessions', 'ctrl + f to find in the conversation'],
1396
1639
  ['PgUp/PgDn, wheel to scroll', 'ctrl + home/end to the top/bottom'],
1397
1640
  ['# to memorize', 'ctrl + t to toggle todos'],
1398
1641
  ['\\⏎ or alt+⏎ for newline', 'ctrl + l to redraw, ctrl + d to exit'],
1399
- ['ctrl + c to copy selection', 'ctrl + v to paste text or an image'],
1642
+ ['ctrl + c to copy selection', 'ctrl + q to quote it in your message'],
1643
+ ['ctrl + v to paste text or an image', ''],
1400
1644
  ];
1401
1645
  return rows.map(([a, b]) => c.dim(' ' + padEnd(a, 30) + b));
1402
1646
  }
@@ -1415,7 +1659,7 @@ export class App {
1415
1659
  if (this.finder && !seed.trim()) { this.finder.selected = Boolean(this.finder.text); this.screen.schedule(); return; } // open: select what is typed
1416
1660
  const text = (seed.split('\n').find((l) => l.trim()) || '').trim() || this.lastFind || '';
1417
1661
  if (!this.finder) this.screen.openFind();
1418
- this.finder = { text, cursor: text.length, selected: Boolean(text), pasting: null };
1662
+ this.finder = { text, cursor: text.length, selected: Boolean(text) };
1419
1663
  this.screen.setFind(text);
1420
1664
  this.screen.schedule();
1421
1665
  }
@@ -1441,13 +1685,7 @@ export class App {
1441
1685
  if (f.selected) edit(t, t.length);
1442
1686
  else edit(f.text.slice(0, f.cursor) + t + f.text.slice(f.cursor), f.cursor + t.length);
1443
1687
  };
1444
- if (name === 'paste-start') { f.pasting = ''; return; }
1445
- if (f.pasting !== null) {
1446
- if (name === 'paste-end') { const t = f.pasting.split(/\r?\n/).find((l) => l.trim()) || ''; f.pasting = null; insert(t.trim()); }
1447
- else if (name === 'return' || name === 'enter') f.pasting += '\n';
1448
- else if (str) f.pasting += str;
1449
- return;
1450
- }
1688
+ // a bracketed paste never gets here: App.onKey takes it whole (see insertFindText)
1451
1689
  if (name === 'escape') { this.closeFind(); return; }
1452
1690
  const back = (name === 'return' && (key.meta || key.shift)) || name === 'enter' || key.sequence === '\x1b[13;2u' || (name === 'f3' && key.shift);
1453
1691
  if (back || name === 'down' || (key.ctrl && name === 'n')) { f.selected = false; this.screen.findStep(-1); return; }
@@ -1817,7 +2055,8 @@ export class App {
1817
2055
  for (const b of blocks) {
1818
2056
  const bash = m.role === 'user' && b.type === 'text' ? bashModeLines(b.text) : null;
1819
2057
  if (bash) this.screen.log(bash, '');
1820
- else if (m.role === 'user' && b.type === 'text' && !b.text.startsWith('<system-reminder>')) this.screen.log(renderUserMessage(b.text.slice(0, 2000), this.width));
2058
+ else if (m.role === 'user' && b.type === 'text' && !b.text.startsWith('<system-reminder>')) this.screen.log(renderUserMessage(shownQuotes(b.text).slice(0, 2000), this.width));
2059
+ if (m.role === 'assistant' && b.type === 'thinking' && b.thinking) this.screen.log(renderMarkdown(b.thinking, { width: this.width - 1, firstPrefix: c.dim('✻ '), indent: ' ', style: (s) => c.dim(c.italic(s)) }), '');
1821
2060
  if (m.role === 'assistant' && b.type === 'text') this.screen.log(renderMarkdown(b.text, { width: this.width - 1, firstPrefix: `${DOT} `, indent: ' ' }), '');
1822
2061
  if (m.role === 'assistant' && b.type === 'tool_use') {
1823
2062
  const tool = toolMap.get(b.name) || { name: b.name };
@@ -1883,7 +2122,7 @@ export class App {
1883
2122
  this.remote?.emit({ t: 'start', kind: 'text' });
1884
2123
  } else if (ev.block.type === 'thinking') {
1885
2124
  this.remote?.emit({ t: 'start', kind: 'thinking' });
1886
- this.thinking = { start: Date.now(), text: '', md: this.verbose ? new MarkdownStream({ width: w, firstPrefix: c.dim('✻ '), indent: ' ', style: (s) => c.dim(c.italic(s)) }) : null };
2125
+ this.thinking = new MarkdownStream({ width: w, firstPrefix: c.dim('✻ '), indent: ' ', style: (s) => c.dim(c.italic(s)) });
1887
2126
  } else if (ev.block.type === 'tool_use') {
1888
2127
  this.flushThinking();
1889
2128
  this.pendingToolBlocks.set(ev.index, { name: ev.block.name, partial: '' });
@@ -1900,12 +2139,9 @@ export class App {
1900
2139
  case 'thinking':
1901
2140
  this.turnTokens += estimateTokens(ev.text);
1902
2141
  if (this.thinking) {
1903
- this.thinking.text += ev.text;
1904
2142
  this.remote?.emit({ t: 'delta', kind: 'thinking', text: ev.text });
1905
- if (this.thinking.md) {
1906
- const lines = this.thinking.md.write(ev.text);
1907
- if (lines.length) this.logLocal({ soon: true }, lines);
1908
- }
2143
+ const lines = this.thinking.write(ev.text);
2144
+ if (lines.length) this.logLocal({ soon: true }, lines);
1909
2145
  }
1910
2146
  break;
1911
2147
  case 'tool_input': {
@@ -1965,14 +2201,9 @@ export class App {
1965
2201
  if (!t) return;
1966
2202
  this.thinking = null;
1967
2203
  this.remote?.emit({ t: 'stop' });
1968
- if (t.md) {
1969
- const lines = t.md.end();
1970
- if (lines.length) this.logLocal(lines);
1971
- this.logLocal('');
1972
- } else if (t.text.trim()) {
1973
- const secs = Math.max(1, Math.round((Date.now() - t.start) / 1000));
1974
- this.logLocal(c.dim(c.italic(`✻ Thought for ${secs}s (ctrl+o to show thinking)`)), '');
1975
- }
2204
+ const lines = t.end();
2205
+ if (lines.length) this.logLocal(lines);
2206
+ if (t.emittedAny) this.logLocal('');
1976
2207
  }
1977
2208
 
1978
2209
  flushStreaming() {
@@ -1998,7 +2229,8 @@ export class App {
1998
2229
  this.screen.schedule();
1999
2230
  return {
2000
2231
  progress: (p, meta) => {
2001
- if (typeof p === 'string') { entry.progress = p; entry.progressLines = meta?.lines; this.remote?.toolProgress(tu.id, entry); }
2232
+ // `all`: the whole output so far (the progress is its end), for the page's "the whole output"
2233
+ if (typeof p === 'string') { entry.progress = p; entry.progressLines = meta?.lines; entry.progressAll = meta?.all; this.remote?.toolProgress(tu.id, entry); }
2002
2234
  else if (p?.type === 'subtool') { entry.sub.push(p.header); entry.subCount++; this.remote?.emit({ t: 'sub', id: tu.id, head: p.header }); }
2003
2235
  this.screen.schedule();
2004
2236
  },
@@ -2099,7 +2331,6 @@ export class App {
2099
2331
  if (!this.isMain(agent)) return;
2100
2332
  this.flushStreaming();
2101
2333
  this.status = auto ? 'Auto-compacting conversation' : 'Compacting conversation';
2102
- this.compactTokens = 0;
2103
2334
  this.screen.schedule();
2104
2335
  }
2105
2336
 
@@ -2109,11 +2340,10 @@ export class App {
2109
2340
  else if (ev.type === 'rate_limit_wait' || ev.type === 'rate_limit_resume') this.rateLimitEvent(ev);
2110
2341
  }
2111
2342
 
2112
- compactEnd(summary, agent, err, { part } = {}) {
2343
+ compactEnd(_summary, agent, err, { part } = {}) {
2113
2344
  if (!this.isMain(agent)) return;
2114
2345
  this.status = null;
2115
2346
  if (err) return;
2116
- this.lastSummary = summary;
2117
2347
  this.store.setCacheUntil(agent.cache.clockUntil, agent.cacheState());
2118
2348
  const what = part === 'before' ? 'The earlier part of the conversation was summarized' : part === 'after' ? 'The conversation from that message on was summarized' : 'Conversation compacted';
2119
2349
  this.screen.log(c.dim(`✻ ${what} (the summary is in context; /context to see usage)`), '');
@@ -2194,12 +2424,7 @@ export class App {
2194
2424
  const partial = this.md.partial();
2195
2425
  lines.push(...partial.slice(-Math.floor(this.screen.height / 2)));
2196
2426
  }
2197
- if (this.thinking?.md) lines.push(...this.thinking.md.partial().slice(-3));
2198
- else if (this.thinking && this.thinking.text) {
2199
- const text = this.thinking.text.trimEnd();
2200
- const last = text.slice(text.lastIndexOf('\n') + 1); // not split(): this runs every frame on all of it
2201
- lines.push(c.dim(c.italic(truncate(`✻ ${last}`, w))));
2202
- }
2427
+ if (this.thinking) lines.push(...this.thinking.partial().slice(-Math.floor(this.screen.height / 2)));
2203
2428
  for (const [, p] of this.pendingToolBlocks) {
2204
2429
  // The start of the input is enough for a one-line preview (a streaming Bash heredoc can be very long).
2205
2430
  const m = /"(?:file_path|command|pattern|url|description|query)"\s*:\s*"((?:\\.|[^"\\])*)/.exec(p.partial.slice(0, 4000));
@@ -2230,15 +2455,19 @@ export class App {
2230
2455
  }
2231
2456
  if (lines.length) lines.push('');
2232
2457
  const placeholder = this.isTurnRunning() ? 'Type a message to queue it for the agent…' : (this.agent.messages.length ? '' : 'Try "explain this codebase" or "fix the failing test"');
2233
- const r = this.finder ? this.renderFind(width) : this.editor.render(width, { placeholder, title: this.boxTitle() });
2458
+ const after = this.finder ? [c.dim(truncate(' ⏎ or ↑ older · shift+⏎ or ↓ newer · PgUp/PgDn scroll · esc to close', w))]
2459
+ : this.editor.suggestions ? this.editor.renderSuggestions(w)
2460
+ : this.editor.text === '?' ? this.shortcutsHelp()
2461
+ : [this.footer(w)];
2462
+ // the box's text gets the screen less what is above and below it, its borders, and two rows of the conversation
2463
+ const maxRows = Math.max(3, this.screen.height - 1 - lines.length - after.length - 2 - 2);
2464
+ const r = this.finder ? this.renderFind(width) : this.editor.render(width, { placeholder, title: this.boxTitle(), maxRows });
2234
2465
  const top = lines.length;
2235
2466
  lines.push(...r.lines);
2236
2467
  if (r.cursor) cursor = { row: top + r.cursor.row, col: r.cursor.col };
2237
- if (this.finder) lines.push(c.dim(truncate(' ⏎ or ↑ older · shift+⏎ or ↓ newer · PgUp/PgDn scroll · esc to close', w)));
2238
- else if (this.editor.suggestions) lines.push(...this.editor.renderSuggestions(w));
2239
- else if (this.editor.text === '?') lines.push(...this.shortcutsHelp());
2240
- else lines.push(this.footer(w));
2241
- return { lines, cursor };
2468
+ const input = r.text ? { ...r.text, row: top + r.text.row } : null; // where the mouse reaches the input box's text
2469
+ lines.push(...after);
2470
+ return { lines, cursor, input };
2242
2471
  }
2243
2472
 
2244
2473
  // In the input box's top border: the directory the agent is in now (a `cd` moves it), and this
@@ -2265,6 +2494,8 @@ export class App {
2265
2494
  const flash = this.flashMessage && Date.now() < this.flashMessage.until ? this.flashMessage : null;
2266
2495
  if (this.exitArmed && Date.now() - this.exitArmed < 1500) left = c.dim(' Press Ctrl-C again to exit');
2267
2496
  else if (flash) left = (flash.kind === 'warn' ? c.yellow : c.dim)(' ' + truncate(flash.text, w - 4));
2497
+ else if (this.screen.full && this.screen.selection) left = c.dim(' ctrl+c to copy · ctrl+q to quote it in your message');
2498
+ else if (this.editor.selection) left = c.dim(' ctrl+c to copy · esc to clear');
2268
2499
  else if (this.restartRequest) left = c.dim(' ↻ restarting when this turn ends');
2269
2500
  else if (this.editor.mode === 'bash') left = c.magenta(' ! for bash mode');
2270
2501
  else if (this.editor.mode === 'memory') left = c.blue(' # to memorize');
@@ -2278,11 +2509,11 @@ export class App {
2278
2509
  else if (this.pendingUpdate) left += c.dim(' · ') + c.dim(`update ${this.pendingUpdate} ready · ${this.updateWaitingFor ? `installs when @${this.updateWaitingFor.split(',')[0]} is idle` : 'installs when idle'}`);
2279
2510
  }
2280
2511
  const cfg = this.config;
2281
- const threshold = cfg.autoCompactThreshold(cfg.model);
2512
+ const threshold = cfg.compactWindow();
2282
2513
  const used = this.agent.contextEstimate;
2283
2514
  let notice = '';
2284
2515
  const pctLeft = Math.max(0, Math.round((1 - used / threshold) * 100));
2285
- if (pctLeft <= 30 && cfg.autoCompactEnabled) notice = c.yellow(`Context left until auto-compact: ${pctLeft}%`);
2516
+ if (pctLeft <= 30) notice = c.yellow(`Context left until auto-compact: ${pctLeft}%`);
2286
2517
  else if (this.runtime.tasks.running().length) notice = c.dim(`${this.runtime.tasks.running().length} background agent${this.runtime.tasks.running().length === 1 ? '' : 's'} running · /tasks`);
2287
2518
  else if (this.verbose) notice = c.dim('verbose');
2288
2519
  // The model and effort in use always have a place at the right: with the notice after it when both fit,
@@ -2320,5 +2551,8 @@ export async function runRepl({ flags, cwd, initialPrompt }) {
2320
2551
  process.stderr.write(`\nUnexpected error: ${e?.stack || e}\n`);
2321
2552
  process.exit(1);
2322
2553
  });
2554
+ // A promise without a handler that rejects is a bug to show, not a reason to end the session: Node ends the process
2555
+ // on one by default (through the handler above, with exit code 1, which the supervisor does not restart).
2556
+ process.on('unhandledRejection', (e) => { try { app.logError(e); } catch { /* the screen is gone */ } });
2323
2557
  return await app.start(initialPrompt);
2324
2558
  }