@yanzc/claude-pro 0.9.0 → 0.9.2

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 -320
  2. package/package.json +1 -2
  3. package/src/agent.js +240 -62
  4. package/src/agents.js +3 -2
  5. package/src/api.js +83 -41
  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 +177 -71
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +153 -153
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +2 -1
  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 +6 -62
  27. package/src/ratelimit.js +3 -5
  28. package/src/remote.js +26 -10
  29. package/src/restart.js +3 -0
  30. package/src/runtime.js +33 -10
  31. package/src/selfcheck.js +3 -3
  32. package/src/session.js +93 -3
  33. package/src/supervisor.js +10 -1
  34. package/src/tools/bash.js +19 -18
  35. package/src/tools/browser.js +365 -0
  36. package/src/tools/code.js +430 -0
  37. package/src/tools/effort.js +3 -4
  38. package/src/tools/files.js +92 -19
  39. package/src/tools/index.js +6 -0
  40. package/src/tools/notebook.js +11 -4
  41. package/src/tools/processes.js +274 -0
  42. package/src/tools/search.js +104 -21
  43. package/src/tools/web.js +316 -46
  44. package/src/trace.js +0 -4
  45. package/src/ui/ansi.js +92 -13
  46. package/src/ui/dialogs.js +16 -54
  47. package/src/ui/editor.js +231 -34
  48. package/src/ui/markdown.js +1 -2
  49. package/src/ui/render.js +1 -2
  50. package/src/ui/repl.js +246 -119
  51. package/src/ui/screen.js +139 -31
  52. package/src/updater.js +135 -165
  53. package/src/utils/clipboard.js +5 -3
  54. package/src/utils/paths.js +15 -17
  55. package/src/utils/shell.js +75 -21
  56. package/.env.example +0 -29
  57. package/src/verify.js +0 -57
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,15 +18,17 @@ 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
23
  import { buildCommands, modelChoices, effortChoices } from '../commands.js';
24
- import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
24
+ import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, reloadTiming, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
25
25
  import { resolvePath, displayPath } from '../utils/paths.js';
26
26
  import { listDirectory, recentDirectories } from '../utils/dirs.js';
27
27
  import { ripgrepPath } from '../utils/shell.js';
28
28
  import { describePause, formatClock, humanDuration, resumeText, shouldAnnounce } from '../ratelimit.js';
29
29
  import { shutdownBackgroundShells, listBackgroundShells } from '../tools/bash.js';
30
+ import { shutdownInterpreters } from '../tools/code.js';
31
+ import { browserSession } from '../browser/session.js';
30
32
  import { estimateTokens } from '../agent.js';
31
33
  import { readClipboardImage, imageFromFile, writeClipboard, readClipboardText } from '../utils/clipboard.js';
32
34
  import { fitImagesIn, imageSize } from '../utils/images.js';
@@ -68,6 +70,9 @@ const imageBlock = (img) => ({ type: 'image', source: { type: 'base64', media_ty
68
70
  // The images the remote page sends with a message ({media_type, data: base64}), checked as the API would: at most
69
71
  // REMOTE_MAX_IMAGES, each a PNG, JPEG, GIF or WebP of at most 5 MB. Throws what to tell the page.
70
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;
71
76
  const REMOTE_MAX_IMAGES = 6;
72
77
  const REMOTE_MAX_IMAGE_BYTES = 5 * 1024 * 1024;
73
78
  export function remoteImages(images) {
@@ -91,32 +96,84 @@ const SPINNER = ['·', '✢', '✳', '✶', '✻', '✽', '✽', '✻', '✶', '
91
96
  const VERBS = ['Thinking', 'Pondering', 'Crafting', 'Brewing', 'Computing', 'Conjuring', 'Cooking', 'Musing', 'Noodling', 'Percolating', 'Ruminating', 'Synthesizing', 'Working', 'Tinkering', 'Mulling', 'Deliberating', 'Churning', 'Forging', 'Hatching', 'Simmering'];
92
97
  const HISTORY_FILE = path.join(CONFIG_DIR, 'history.jsonl');
93
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.
94
106
  function loadHistory(cwd) {
95
- try {
96
- return fs.readFileSync(HISTORY_FILE, 'utf8').split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } })
97
- .filter((e) => e && e.project === cwd).map((e) => e.display).slice(-500);
98
- } 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 */ }
99
130
  }
100
131
 
101
- 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
+ }
102
139
  try {
103
140
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
104
- fs.appendFileSync(HISTORY_FILE, JSON.stringify({ display: text, project: cwd, timestamp: Date.now() }) + '\n');
141
+ fs.appendFileSync(HISTORY_FILE, JSON.stringify(entry) + '\n');
105
142
  } catch { /* ignore */ }
106
143
  }
107
144
 
145
+ // The files of the working directory, for the completion after an `@`. Listed when an `@` is first typed, not at
146
+ // the start, and never more than MAX_FILES of them: the listing is stopped there. (It ran at every start and
147
+ // restart and went through the whole directory before keeping the first 50,000: in a home directory of 1.3
148
+ // million files that was 10 seconds of ripgrep on every core and 45 MB, for every session open there, each time
149
+ // the program's source changed.) `onLoaded` is called when a listing is in, so that the completion is drawn again.
150
+ const MAX_FILES = 50_000;
108
151
  class FileIndex {
109
- constructor(cwd, getConfig = () => null) { this.cwd = cwd; this.getConfig = getConfig; this.files = []; this.at = 0; this.loading = false; }
152
+ constructor(cwd, getConfig = () => null, onLoaded = () => {}) {
153
+ Object.assign(this, { cwd, getConfig, onLoaded, files: [], at: 0, took: 0, loading: false });
154
+ }
110
155
  refresh() {
111
- if (this.loading || Date.now() - this.at < 30_000) return;
156
+ // listed again after 30 seconds, or later where the listing itself takes long
157
+ if (this.loading || Date.now() - this.at < Math.max(30_000, this.took * 30)) return;
112
158
  this.loading = true;
113
- const done = (list) => { this.files = list.slice(0, 50_000); this.at = Date.now(); this.loading = false; };
159
+ const started = Date.now();
160
+ const done = (list) => {
161
+ Object.assign(this, { files: list.slice(0, MAX_FILES), at: Date.now(), took: Date.now() - started, loading: false });
162
+ this.onLoaded();
163
+ };
114
164
  const rg = ripgrepPath(this.getConfig());
115
165
  if (rg) {
116
166
  const child = spawn(rg, ['--files', '--hidden', '--glob', '!.git'], { cwd: this.cwd, windowsHide: true });
117
167
  let out = '';
168
+ let lines = 0;
118
169
  child.stdout.setEncoding('utf8'); // a Chinese file name can be split between two chunks
119
- child.stdout.on('data', (d) => { if (out.length < 10_000_000) out += d; });
170
+ child.stdout.on('data', (d) => {
171
+ if (lines >= MAX_FILES) return;
172
+ out += d;
173
+ for (let i = d.indexOf('\n'); i !== -1; i = d.indexOf('\n', i + 1)) lines++;
174
+ if (lines >= MAX_FILES) child.kill();
175
+ });
176
+ // (stopped in the middle of a name: the list is cut to MAX_FILES whole ones in done)
120
177
  child.on('close', () => done(out.split(/\r?\n/).filter(Boolean).map((f) => f.replace(/\\/g, '/'))));
121
178
  child.on('error', () => done([]));
122
179
  } else {
@@ -125,7 +182,7 @@ class FileIndex {
125
182
  try {
126
183
  for await (const f of fs.promises.glob('**/*', { cwd: this.cwd, exclude: (p) => /(^|[\\/])(node_modules|\.git)$/.test(p) })) {
127
184
  list.push(f.replace(/\\/g, '/'));
128
- if (list.length > 50_000) break;
185
+ if (list.length > MAX_FILES) break;
129
186
  }
130
187
  } catch { /* ignore */ }
131
188
  done(list);
@@ -211,6 +268,8 @@ export class App {
211
268
  this.restarts = []; // when this session was restarted lately (carried over by each restart)
212
269
  this.restartRequest = null; // {reason, then, continueTurn}: restart as soon as nothing is running
213
270
  this.sourceChanged = null; // the program's own source changed since it was last checked
271
+ this.sourceChangedInTurn = false; // ...while a turn of this session ran: its own work, most likely
272
+ this.sourceQuietAt = 0; // a change made elsewhere is loaded once the source has been left alone until then
214
273
  this.reloading = false;
215
274
  this.skipAutoReload = false;
216
275
  this.peers = null; // this session as seen by the other sessions on the machine (see peers.js)
@@ -230,8 +289,9 @@ export class App {
230
289
  this.remotePeersLoading = null;
231
290
  this.remotePeersTimer = null;
232
291
  this.cost = 0; // what this conversation's requests have cost so far (USD at list prices): the footer and /cost
233
- this.fileIndex = new FileIndex(cwd, () => this.runtime?.config);
292
+ this.fileIndex = new FileIndex(cwd, () => this.runtime?.config, () => { this.editor?.refreshSuggestions(); this.screen?.schedule(); });
234
293
  this.store = new SessionStore(cwd);
294
+ 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');
235
295
  // What the terminal prints goes to the remote page too, except what it is told about as events.
236
296
  this.screen.onLog = (items) => {
237
297
  const lines = () => items.flatMap((i) => (Array.isArray(i) ? i : [i])).flatMap((l) => String(l).split(/\r?\n/));
@@ -240,7 +300,7 @@ export class App {
240
300
  };
241
301
  this.editor = new Editor({
242
302
  history: loadHistory(cwd),
243
- onSubmit: (value, raw, images) => { try { this.onSubmit(value, raw, images); } catch (e) { this.logError(e); } },
303
+ onSubmit: (value, raw, images, display, parts) => { try { this.onSubmit(value, raw, images, display, parts); } catch (e) { this.logError(e); } },
244
304
  onDoubleEscape: () => this.openRewind(),
245
305
  imageFromPath: (p) => {
246
306
  const r = imageFromFile(resolvePath(p, this.cwd));
@@ -284,6 +344,10 @@ export class App {
284
344
  this.screen.schedule();
285
345
  };
286
346
  this.commands = buildCommands(this);
347
+ // The window of the model in use may come from the gateway's model list (see Config.resolveModel): asked for now,
348
+ // so that the footer shows it before the first request.
349
+ // not in the self-check a restart runs first: that would ask the gateway once more for every restart
350
+ if (!this.driven && !this.selfCheck) loadGatewayModels(this.runtime.config).then(() => this.screen.schedule());
287
351
  // What the session showed before a restart: scrolled back to in fullscreen, repainted after a resize otherwise.
288
352
  if (Array.isArray(this.flags.restart?.screenHistory)) this.screen.history = this.flags.restart.screenHistory.filter((l) => typeof l === 'string');
289
353
  if (this.fullscreenWanted()) this.screen.setFull(true);
@@ -320,10 +384,9 @@ export class App {
320
384
  if (restart) this.continueAfterRestart(restart);
321
385
  else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
322
386
  // Nothing configured yet: the gateway is the default, and its browser login starts first.
323
- else if (this.config.usesGateway && !gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY)) {
387
+ else if (!gatewayLogin(this.config.gatewayUrl)) {
324
388
  Promise.resolve(this.commands.get('login').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
325
389
  }
326
- this.fileIndex.refresh();
327
390
  this.startSourceWatch();
328
391
  if (!this.driven) {
329
392
  // Updates are deliberately manual: /update checks npm and installs the selected release.
@@ -411,8 +474,10 @@ export class App {
411
474
  this.exiting = true;
412
475
  this.controller?.abort();
413
476
  clearInterval(this.spinnerTimer);
477
+ clearTimeout(this.reloadTimer);
414
478
  this.sourceWatch?.close();
415
479
  shutdownBackgroundShells();
480
+ shutdownInterpreters();
416
481
  this.runtime?.tasks.killAll();
417
482
  this.runtime?.mcp.close();
418
483
  this.peers?.close();
@@ -602,7 +667,7 @@ export class App {
602
667
  const env = this.config.env;
603
668
  if (!onlineEnabled(env)) return false;
604
669
  if (this.driven && !/^(1|true|yes|on)$/i.test(env.CLAUDE_PRO_ONLINE || '')) return false;
605
- return Boolean(gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY));
670
+ return Boolean(gatewayLogin(this.config.gatewayUrl));
606
671
  }
607
672
 
608
673
  // Online at the gateway from the start when this computer is logged in, and after a restart with the same
@@ -617,7 +682,7 @@ export class App {
617
682
  }
618
683
 
619
684
  // Connect this session to the gateway (see remote.js): the web page and the sessions on the account's other
620
- // computers reach it from then on. Needs the gateway login from /login or CLAUDE_PRO_GATEWAY_API_KEY; throws
685
+ // computers reach it from then on. Needs the gateway login from /login; throws
621
686
  // {code: 'NO_GATEWAY_LOGIN'} without it. A gateway that cannot be reached now is tried again in the background;
622
687
  // one that refuses the key throws, and that key is not tried again (see syncRemote).
623
688
  startRemote({ id } = {}) {
@@ -631,7 +696,7 @@ export class App {
631
696
  syncRemote() {
632
697
  if (this.exiting) return Promise.resolve(null);
633
698
  if (this.remoteStarting) return this.remoteStarting.catch(() => null);
634
- const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
699
+ const login = gatewayLogin(this.config.gatewayUrl);
635
700
  const r = this.remote;
636
701
  // logged out, or another account: not this account's session any more
637
702
  if (r && (!login || login.apiKey !== r.apiKey || normalizeGatewayUrl(login.url || this.config.gatewayUrl) !== normalizeGatewayUrl(r.base))) this.stopRemote();
@@ -644,7 +709,7 @@ export class App {
644
709
  }
645
710
 
646
711
  async connectRemote({ id }) {
647
- const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
712
+ const login = gatewayLogin(this.config.gatewayUrl);
648
713
  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' });
649
714
  // What the page may do here, besides watching (see remote.js): nothing with CLAUDE_PRO_REMOTE_COMMANDS=0.
650
715
  const commands = remoteCommandsEnabled(this.config.env) ? {
@@ -718,7 +783,7 @@ export class App {
718
783
  return { text };
719
784
  }
720
785
  if (this.remoteStarting) return { text: 'connecting…' };
721
- const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
786
+ const login = gatewayLogin(this.config.gatewayUrl);
722
787
  if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`) };
723
788
  if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)') };
724
789
  if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)') };
@@ -769,10 +834,13 @@ export class App {
769
834
  contextUsed() {
770
835
  const a = this.agent;
771
836
  if (a.lastContextTokens) return a.contextEstimate;
772
- const key = `${a.messages.length}|${this.runtime.tools.length}`;
837
+ // not built yet: the prompt is counted once git has answered in the background (building it here blocked on git)
838
+ const ready = this.runtime.systemPromptReady?.() ?? true;
839
+ const key = `${a.messages.length}|${this.runtime.tools.length}|${ready}`;
773
840
  if (this.contextGuess?.key !== key) {
841
+ if (!ready) this.runtime.prepareSnapshot().then(() => this.screen.schedule());
774
842
  let used = 0;
775
- try { used = estimateTokens(this.runtime.systemPrompt()) + estimateTokens(a.toolSchemas()) + estimateTokens(a.messages); } catch { /* 0 */ }
843
+ try { used = (ready ? estimateTokens(this.runtime.systemPrompt()) : 0) + estimateTokens(a.toolSchemas()) + estimateTokens(a.messages); } catch { /* 0 */ }
776
844
  this.contextGuess = { key, used };
777
845
  }
778
846
  return this.contextGuess.used;
@@ -791,8 +859,6 @@ export class App {
791
859
  if (!d) return null;
792
860
  d.remoteId ??= ++this.remoteDialogs;
793
861
  const base = { id: d.remoteId, title: d.title || '', question: d.question || '', body: d.body || [], markdown: d.markdown || null };
794
- // a question answered with typed text (TextDialog): a text box on the page, answered with {id, text}
795
- if (d.input) return { ...base, input: { placeholder: d.input.placeholder || '', value: d.value || '', multiline: Boolean(d.input.multiline) } };
796
862
  if (!Array.isArray(d.options)) return base;
797
863
  return { ...base, multi: Boolean(d.multi), options: d.options.map((o) => ({ label: String(o.label ?? ''), description: o.description || '', other: o.value === '__other__' })) };
798
864
  }
@@ -800,17 +866,11 @@ export class App {
800
866
  // ---------------------------------------------------------------- the page's commands (see remote.js)
801
867
 
802
868
  // The answer to the dialog the status showed the page (remoteDialog): {id, index}, {id, indices}, {id, text,
803
- // indices?} (its "other" option), {id, text} (a text box) or {id, cancel: true}.
869
+ // indices?} (its "other" option) or {id, cancel: true}.
804
870
  answerDialog({ id, index, indices, text, cancel } = {}) {
805
871
  const d = this.dialogs[0];
806
872
  if (!d || d.remoteId !== id) throw new Error('That question is no longer open.');
807
873
  if (cancel) { d.resolve(d.cancelValue); return {}; }
808
- if (d.input) {
809
- if (typeof text !== 'string') throw new Error('Type an answer first.');
810
- d.resolve(text);
811
- this.screen.schedule();
812
- return {};
813
- }
814
874
  if (!Array.isArray(d.options)) throw new Error('This dialog cannot be answered from the page.');
815
875
  const valueAt = (i) => {
816
876
  const o = d.options[i];
@@ -838,8 +898,12 @@ export class App {
838
898
  let value = String(text ?? '').replace(/\r\n/g, '\n');
839
899
  if (!value.trim() && pictures.length) value = pictures.map((_, i) => `[Image #${i + 1}]`).join(' ');
840
900
  if (!value.trim()) throw new Error('The message is empty.');
901
+ // The user's rule: the page does not end or restart the session, nor update claude-pro; only the terminal does
902
+ // (the automatic update goes on as before: it is not a command of the page). The gateway refuses these too, with
903
+ // the same pattern and message; this holds when it does not (another gateway, or one that misses them).
904
+ if (TERMINAL_ONLY.test(value)) throw new Error('结束、重启会话和更新 claude-pro 只能在终端里操作');
841
905
  if (this.exiting) throw new Error('The session is ending.');
842
- if (this.isTurnRunning() && value.trim().startsWith('/')) throw new Error('Commands wait until the current task is done (or stopped).');
906
+ if (this.isTurnRunning() && value.trim().startsWith('/') && !this.modelSwitchAtPause(value.trim())) throw new Error('Commands wait until the current task is done (or stopped).');
843
907
  if (this.dialogs.length && !this.isTurnRunning()) throw new Error('A question is open: answer it first.');
844
908
  const queued = this.isTurnRunning();
845
909
  this.onSubmit(value, value, pictures);
@@ -983,12 +1047,19 @@ export class App {
983
1047
  if (request.cwd) {
984
1048
  try { moved = moveSession(this.store.file, this.store.id, request.cwd); } catch (e) { this.notice(`Could not change the directory: ${e.message}`, 'warn'); return; }
985
1049
  }
1050
+ // a write of the conversation failed at some point: the file lacks part of it, and the next process goes on from it
1051
+ if (this.store.lost) { this.store.lost = false; this.store.reset(this.agent.messages); }
986
1052
  const state = {
987
1053
  at: now,
988
1054
  reason: request.reason || '',
989
1055
  continueWith: request.continueTurn ? restartNote(request) : '',
990
1056
  cwd: request.cwd || this.cwd,
991
1057
  changedDirectory: Boolean(request.cwd),
1058
+ // where the agent's shell is (a `cd` in Bash moves it): the next process goes on there, not at the project's root
1059
+ agentCwd: request.cwd ? null : this.agent.cwd,
1060
+ // the browser instance in use (one picked with /tabs may be any of several): the next process connects to it
1061
+ // again, where the tab ids in the conversation are still its tabs'
1062
+ browser: browserSession.preferred || null,
992
1063
  sessionId: this.store.id,
993
1064
  sessionFile: moved?.file || this.store.file,
994
1065
  modelOverride: cfg.modelOverride,
@@ -998,7 +1069,9 @@ export class App {
998
1069
  draft: this.editor.text,
999
1070
  screenHistory: this.screen.history.slice(-3000),
1000
1071
  draftCursor: this.editor.cursor,
1001
- queue: this.queue.map((q) => ({ text: q.text, images: q.images || [] })),
1072
+ draftParts: this.editor.draftParts(),
1073
+ // `peer`: a task of another session, which gets the answer of the turn that handles it
1074
+ queue: this.queue.map((q) => ({ text: q.text, images: q.images || [], display: q.display ?? null, peer: q.peer || null })),
1002
1075
  checkpoints: this.runtime.checkpoints.snapshot(),
1003
1076
  // a /cd is the user's: it does not count towards the restarts that look like a loop
1004
1077
  restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), ...(request.cwd ? [] : [now])],
@@ -1043,8 +1116,12 @@ export class App {
1043
1116
  this.loadSession(state.sessionFile, state.sessionId, { quiet: true });
1044
1117
  if (Array.isArray(state.todos)) this.agent.todos = state.todos;
1045
1118
  if (state.checkpoints) this.runtime.checkpoints.adopt(state.checkpoints);
1119
+ if (typeof state.agentCwd === 'string' && state.agentCwd !== this.cwd) {
1120
+ try { if (fs.statSync(state.agentCwd).isDirectory()) this.agent.cwd = state.agentCwd; } catch { /* gone: the project's root */ }
1121
+ }
1046
1122
  }
1047
- if (typeof state.draft === 'string' && state.draft) this.editor.set(state.draft, state.draftCursor);
1123
+ if (state.browser && typeof state.browser === 'object' && typeof state.browser.dir === 'string') browserSession.preferred = state.browser;
1124
+ if (typeof state.draft === 'string' && state.draft) this.editor.restoreDraft(state.draft, state.draftCursor, state.draftParts);
1048
1125
  // Fullscreen starts on an empty screen: without what the process before showed (an older version, or one
1049
1126
  // that ran classic), the conversation is drawn again from the session.
1050
1127
  if (this.screen.full && resumable && !Array.isArray(state.screenHistory)) this.printTranscript(this.agent.messages.slice(-80));
@@ -1063,15 +1140,28 @@ export class App {
1063
1140
  const queued = (Array.isArray(state.queue) ? state.queue : []).filter((q) => q && typeof q.text === 'string' && q.text.trim());
1064
1141
  if (!state.continueWith && !queued.length) return;
1065
1142
  const typed = queued.map((q) => q.text).join('\n\n');
1066
- this.startTurn([state.continueWith, typed].filter(Boolean).join('\n\n'), { echo: queued.length > 0, display: typed, topic: typed, images: queued.flatMap((q) => q.images || []) });
1143
+ const shown = queued.map((q) => (typeof q.display === 'string' ? q.display : q.text)).join('\n\n');
1144
+ this.startTurn([state.continueWith, typed].filter(Boolean).join('\n\n'), {
1145
+ echo: queued.length > 0,
1146
+ display: shown,
1147
+ topic: shown,
1148
+ images: queued.flatMap((q) => (Array.isArray(q.images) ? q.images : [])),
1149
+ peers: queued.map((q) => q.peer).filter((p) => p && typeof p === 'object' && p.from),
1150
+ });
1067
1151
  }
1068
1152
 
1069
- // Follow the program's own source: once a turn is over (or at once when idle) a change to it is loaded by
1070
- // a restart, if the new code starts.
1153
+ // Follow the program's own source: a change to it is loaded by a restart, if the new code starts. A change made
1154
+ // while a turn of this session runs is its own work, and is loaded when the turn is over. One that arrives while
1155
+ // the session is idle was made elsewhere (another session working on the program, an editor), one step of a
1156
+ // change that is not finished: it is loaded once the source has been left alone for a few minutes. (Loaded at
1157
+ // once, every edit of one session made each of the other open sessions check and restart, into a half-made
1158
+ // change: 8 of them, a dozen times in a day's work.)
1071
1159
  startSourceWatch() {
1072
- if (!canRestart() || /^(0|false|no|off)$/i.test(this.config.env.CLAUDE_PRO_AUTO_RESTART || '')) return;
1160
+ if (!canRestart()) return;
1073
1161
  this.sourceWatch = watchSource(INSTALL_DIR, (file) => {
1074
1162
  this.sourceChanged = file || true;
1163
+ if (this.isTurnRunning()) this.sourceChangedInTurn = true;
1164
+ else this.sourceQuietAt = Date.now() + reloadTiming.quietMs + Math.random() * reloadTiming.spreadMs; // (not all sessions at the same moment)
1075
1165
  // another window (or npm) installed a new version: say so, and load it once this session is idle. In a
1076
1166
  // source checkout a newer version in package.json is a release being made, not an install.
1077
1167
  const disk = installedVersion();
@@ -1088,8 +1178,18 @@ export class App {
1088
1178
  if (!this.sourceChanged || this.updating || this.reloading || this.isTurnRunning() || this.exiting || this.restartRequest || this.dialogs.length || this.queue.length) return;
1089
1179
  if (this.skipAutoReload) { this.skipAutoReload = false; return; } // the user just interrupted: not now
1090
1180
  if (this.restartBlockers().length) return; // looked at again whenever the program is next idle
1181
+ clearTimeout(this.reloadTimer);
1182
+ const wait = this.updateRestart || this.sourceChangedInTurn ? 0 : this.sourceQuietAt - Date.now(); // (an installed version is complete)
1183
+ if (wait > 0) {
1184
+ this.reloadTimer = setTimeout(() => this.maybeAutoReload(), wait + 50);
1185
+ this.reloadTimer.unref?.();
1186
+ this.screen.schedule();
1187
+ return;
1188
+ }
1091
1189
  const changed = this.sourceChanged;
1190
+ const inTurn = this.sourceChangedInTurn;
1092
1191
  this.sourceChanged = null;
1192
+ this.sourceChangedInTurn = false;
1093
1193
  this.reloading = true;
1094
1194
  this.flash(this.updateRestart ? `Updated to ${this.updateRestart}: checking it starts, then restarting…` : 'Source changed: checking the new code…');
1095
1195
  let check;
@@ -1099,19 +1199,19 @@ export class App {
1099
1199
  this.notice(`The program's source changed but the new code does not start, so it was not restarted:\n${check.output.split('\n').slice(0, 12).join('\n')}\nFix it; the restart follows by itself (or run /restart).`, 'warn');
1100
1200
  return;
1101
1201
  }
1102
- if (this.isTurnRunning() || this.dialogs.length) { this.sourceChanged = changed; return; } // something started meanwhile: later
1103
- this.requestRestart({ reason: this.updateRestart ? `updated to ${APP_NAME} ${this.updateRestart}` : 'source changed', force: true });
1202
+ if (this.isTurnRunning() || this.dialogs.length) { this.sourceChanged = changed; this.sourceChangedInTurn = inTurn; return; } // something started meanwhile: later
1203
+ const r = this.requestRestart({ reason: this.updateRestart ? `updated to ${APP_NAME} ${this.updateRestart}` : 'source changed', force: true });
1204
+ // refused (too many restarts in a row): say so, or later changes would go unloaded without a word
1205
+ 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');
1104
1206
  }
1105
1207
 
1106
- // A newer version on npm (see updater.js): it is installed once no session of this machine is working, and then
1107
- // loaded by a restart (this session's; the others restart when they see the files change). `force`: the /update
1108
- // command, which also says when there is nothing to do. `quiet`: the periodic check, which says nothing when an
1109
- // install fails (it is tried again in a minute).
1110
- async autoUpdate({ force = false, quiet = false } = {}) {
1111
- if (this.updating) { if (force) this.notice(`${APP_NAME} ${this.updating} is being installed.`); return; }
1208
+ // /update: a newer version on npm (see updater.js) is installed once no session of this machine is working, and
1209
+ // then loaded by a restart (this session's; the others restart when they see the files change).
1210
+ async updateFromNpm() {
1211
+ if (this.updating) { this.notice(`${APP_NAME} ${this.updating} is being installed.`); return; }
1112
1212
  let r;
1113
1213
  try {
1114
- r = await checkForUpdate({ force, env: { ...process.env, ...this.config.env } });
1214
+ r = await checkForUpdate();
1115
1215
  } catch (e) {
1116
1216
  r = { status: 'failed', error: e.message };
1117
1217
  }
@@ -1119,18 +1219,17 @@ export class App {
1119
1219
  if (r.status === 'available') {
1120
1220
  if (this.pendingUpdate !== r.version) {
1121
1221
  this.pendingUpdate = r.version;
1122
- this.updateQuiet = quiet;
1123
1222
  this.screen.schedule();
1124
1223
  }
1125
- if (force && this.working()) this.notice(`${APP_NAME} ${r.version} is out: it is installed as soon as this session's work is done.`);
1126
- await this.maybeInstallUpdate({ force });
1224
+ if (this.working()) this.notice(`${APP_NAME} ${r.version} is out: it is installed as soon as this session's work is done.`);
1225
+ await this.maybeInstallUpdate({ force: true });
1127
1226
  } else if (r.status === 'installed') {
1128
- 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'}.`);
1227
+ this.notice(`${APP_NAME} ${r.version} is installed already; this session restarts to load it ${this.working() ? 'once its work is done' : 'now'}.`);
1129
1228
  this.updateRestart = r.version;
1130
1229
  if (canRestart()) { this.sourceChanged ||= true; if (!this.isTurnRunning()) this.maybeAutoReload(); }
1131
1230
  } else if (r.status === 'failed') {
1132
- if (force || (r.version && !quiet)) this.notice(`Could not update ${APP_NAME}${r.version ? ` to ${r.version}` : ''}: ${r.error}`, 'warn');
1133
- } else if (force) {
1231
+ this.notice(`Could not update ${APP_NAME}${r.version ? ` to ${r.version}` : ''}: ${r.error}`, 'warn');
1232
+ } else {
1134
1233
  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.`);
1135
1234
  }
1136
1235
  }
@@ -1184,7 +1283,7 @@ export class App {
1184
1283
  }
1185
1284
  return;
1186
1285
  }
1187
- if (force || !this.updateQuiet) this.notice(`Could not update ${APP_NAME} to ${version}: ${r.error}`, 'warn');
1286
+ this.notice(`Could not update ${APP_NAME} to ${version}: ${r.error}`, 'warn');
1188
1287
  }
1189
1288
 
1190
1289
  printWelcome() {
@@ -1205,7 +1304,7 @@ export class App {
1205
1304
  c.claude('╰' + '─'.repeat(w - 2) + '╯'),
1206
1305
  ];
1207
1306
  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).'));
1208
- 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.`));
1307
+ if (!gatewayLogin(cfg.gatewayUrl)) lines.push('', c.yellow(` ⚠ Not logged in to the gateway ${cfg.gatewayUrl}. Run /login.`));
1209
1308
  const mcp = this.runtime.mcp.status();
1210
1309
  if (mcp.length) {
1211
1310
  const ok = mcp.filter((m) => m.status === 'connected').length;
@@ -1217,15 +1316,15 @@ export class App {
1217
1316
 
1218
1317
  // ---------------------------------------------------------------- input
1219
1318
 
1220
- // Fullscreen (see screen.js) unless CLAUDE_PRO_TUI=default, as Claude Code's /tui: the input box fixed at the
1221
- // bottom of the window, the conversation scrolled inside the program. Not in the tests that drive the App.
1319
+ // Fullscreen unless settings.tui selects the classic renderer; a driven test defaults to classic.
1222
1320
  fullscreenWanted() {
1223
- const mode = String(this.config.env.CLAUDE_PRO_TUI || (this.driven ? 'default' : 'fullscreen')).toLowerCase();
1321
+ const mode = this.driven && this.config.settings.tui == null ? 'default' : this.config.setting('tui');
1224
1322
  return mode === 'fullscreen' && this.stdout.isTTY !== false;
1225
1323
  }
1226
1324
 
1227
1325
  // Fullscreen: the wheel scrolls the conversation (3 rows a notch); a drag,
1228
1326
  // a double or a triple click selects text. Selection is copied only with Ctrl+C.
1327
+ // In the input box a click moves the cursor and a drag selects its text (see Editor.mouse).
1229
1328
  onMouse(m) {
1230
1329
  if (!this.screen.full || this.exiting) return;
1231
1330
  if (m.button & 64) {
@@ -1235,7 +1334,30 @@ export class App {
1235
1334
  return;
1236
1335
  }
1237
1336
  // Right-click is intentionally inert. Clipboard operations use Ctrl+C and Ctrl+V only.
1238
- this.screen.mouse(m);
1337
+ const had = this.screen.selection;
1338
+ const hadInput = this.editor.selection;
1339
+ const r = this.screen.mouse(m);
1340
+ if (r?.input) this.editor.mouse(r.input);
1341
+ else if ((m.button & 3) === 0 && !(m.button & 32) && !m.release) this.editor.clearSelection(); // a press elsewhere
1342
+ if ((this.screen.selection && this.screen.selection !== had) || (this.editor.selection && this.editor.selection !== hadInput)) {
1343
+ this.flashMessage = null; // the footer says what a selection takes
1344
+ this.screen.schedule();
1345
+ }
1346
+ }
1347
+
1348
+ // Quote what is selected in the conversation in the message being written, as ChatGPT's "Ask ChatGPT" does:
1349
+ // ctrl+q (alt+q where the terminal keeps ctrl+q), as the footer says while there is a selection. The box shows
1350
+ // "[Quote #1 +12 lines]"; the model gets the text and the line of the conversation it is under (see
1351
+ // Editor.insertQuote), so that it knows which part, and which file or command, the question is about.
1352
+ quoteSelection() {
1353
+ if (!this.screen.full) { this.flash('Quoting works in fullscreen (/tui fullscreen): select text with the mouse, then ctrl+q', 'warn'); return; }
1354
+ const quote = this.screen.selectionQuote();
1355
+ if (!quote?.text.trim()) { this.flash('Select part of the conversation first (drag over it, or double/triple-click), then ctrl+q', 'warn'); return; }
1356
+ if (this.dialogs.length) { this.flash('Answer the open question first, then quote', 'warn'); return; }
1357
+ if (this.finder) this.closeFind();
1358
+ this.screen.clearSelection();
1359
+ const label = this.editor.insertQuote(quote.text, quote.source);
1360
+ this.flash(`${label}${quote.source ? ` from ${quote.source}` : ''}: type your question below it`);
1239
1361
  }
1240
1362
 
1241
1363
  copyText(text) {
@@ -1342,10 +1464,19 @@ export class App {
1342
1464
  // then does what it does.
1343
1465
  if (this.screen.selection) {
1344
1466
  if (key.ctrl && key.name === 'c') { this.copyText(this.screen.selectedText()); this.screen.clearSelection(); return; }
1467
+ if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; }
1345
1468
  this.screen.clearSelection();
1346
1469
  if (key.name === 'escape') return;
1347
1470
  }
1348
1471
  }
1472
+ // A selection in the input box (see Editor.mouse), the same way: ctrl+c copies it (and neither interrupts nor
1473
+ // clears the message), esc only clears it, any other key clears it and then does what it does.
1474
+ if (this.editor.selection) {
1475
+ const shown = !this.dialogs.length && !this.finder; // else the box is not on screen, and the key is not for it
1476
+ if (shown && key.ctrl && key.name === 'c') { this.copyText(this.editor.selectedText()); this.editor.clearSelection(); return; }
1477
+ this.editor.clearSelection();
1478
+ if (shown && key.name === 'escape') return;
1479
+ }
1349
1480
  if (key.name === 'paste-start' || key.sequence === '\x1b[200~') {
1350
1481
  this.bracketedPaste = { raw: '' };
1351
1482
  return;
@@ -1353,6 +1484,7 @@ export class App {
1353
1484
  if (key.ctrl && key.name === 'c' && this.finder && !this.dialogs.length) { this.closeFind(); return; } // not the hidden input's text
1354
1485
  if (key.ctrl && key.name === 'c') { this.onCtrlC(); return; }
1355
1486
  if ((key.ctrl || key.meta) && key.name === 'v') { this.pasteClipboard(); return; } // alt+v: the clipboard's image
1487
+ if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; } // nothing selected: says how
1356
1488
  const dialog = this.dialogs[0];
1357
1489
  if (dialog) {
1358
1490
  dialog.handleKey(str, key);
@@ -1361,15 +1493,11 @@ export class App {
1361
1493
  }
1362
1494
  if (key.ctrl && key.name === 'f') { this.openFind(); return; }
1363
1495
  if (this.finder) { this.findKey(str, key); this.screen.schedule(); return; }
1364
- if (key.ctrl && key.name === 'o') {
1365
- this.verbose = !this.verbose;
1366
- this.notice(this.verbose ? 'Verbose mode on: showing thinking and full tool output' : 'Verbose mode off', 'info');
1367
- return;
1368
- }
1369
1496
  if (key.ctrl && key.name === 't') { this.showTodos = !this.showTodos; this.screen.schedule(); return; }
1370
1497
  if (key.ctrl && key.name === 'l') { if (this.screen.full) this.screen.repaint(); else this.screen.clearScreen(); return; }
1371
1498
  if (key.ctrl && key.name === 'd' && !this.editor.text) { this.keyboardExit(); return; }
1372
- if (key.name === 'escape' && this.isTurnRunning()) { this.interrupt(); return; }
1499
+ // esc closes an open completion list first (the editor does that), and only then stops the turn
1500
+ if (key.name === 'escape' && this.isTurnRunning() && !this.editor.suggestions) { this.interrupt(); return; }
1373
1501
  this.exitArmed = 0;
1374
1502
  this.editor.handleKey(str, key);
1375
1503
  this.screen.schedule();
@@ -1446,7 +1574,7 @@ export class App {
1446
1574
  });
1447
1575
  const items = [...peers, ...fileItems];
1448
1576
  if (!items.length) {
1449
- if (!q && m.index === 0 && !m[1] && !quiet) this.flash(this.remote ? 'No file or session is available here or online at the gateway' : 'No file or other session is available on this computer (/login to the gateway reaches your other computers)');
1577
+ if (!q && m.index === 0 && !m[1] && !quiet && !this.fileIndex.loading) this.flash(this.remote ? 'No file or session is available here or online at the gateway' : 'No file or other session is available on this computer (/login to the gateway reaches your other computers)');
1450
1578
  return null;
1451
1579
  }
1452
1580
  return { items, from: cursor - q.length - (quoted ? 2 : 1), to: cursor };
@@ -1478,19 +1606,20 @@ export class App {
1478
1606
  ];
1479
1607
  }
1480
1608
 
1481
- onSubmit(value, raw, images = []) {
1609
+ // `display`: how the message shows in the transcript when that is not `value` (a quote shows its first lines).
1610
+ onSubmit(value, raw, images = [], display = undefined, parts = null) {
1482
1611
  const text = value.trim();
1483
1612
  if (!text) { this.screen.schedule(); return; }
1484
1613
  if (this.screen.scrolledUp) this.screen.scrollBy('bottom'); // what was sent, and what comes of it, is in view
1485
- appendHistory(this.cwd, raw);
1614
+ appendHistory(this.cwd, raw, parts);
1486
1615
  if (this.sendTypedToPeer(text)) return;
1487
- if (this.isTurnRunning()) {
1616
+ if (this.isTurnRunning() && !this.modelSwitchAtPause(text)) {
1488
1617
  if (text.startsWith('/')) { this.notice('Wait for the current task to finish (or press Esc) before running commands.', 'warn'); return; }
1489
- this.queue.push({ text: value, images });
1618
+ this.queue.push({ text: value, images, ...(display ? { display } : {}) });
1490
1619
  this.screen.schedule();
1491
1620
  return;
1492
1621
  }
1493
- if (images.length) { this.startTurn(value, { images }); return; }
1622
+ if (images.length) { this.startTurn(value, { images, display }); return; }
1494
1623
  if (text === '?') { this.screen.log(this.shortcutsHelp()); return; }
1495
1624
  if (raw.startsWith('!')) { this.runBashMode(value.slice(1).trim()); return; }
1496
1625
  if (raw.startsWith('#')) { this.addMemory(value.slice(1).trim()); return; }
@@ -1503,11 +1632,18 @@ export class App {
1503
1632
  Promise.resolve(cmd.run(args, rest)).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
1504
1633
  return;
1505
1634
  }
1506
- if (!/^\/[\w:-]+$/.test(text.split(/\s/)[0])) { this.startTurn(value); return; } // e.g. a path like /usr/bin
1635
+ if (!/^\/[\w:-]+$/.test(text.split(/\s/)[0])) { this.startTurn(value, { display }); return; } // e.g. a path like /usr/bin
1507
1636
  this.notice(`Unknown command: /${name}. Type /help for the list of commands.`, 'warn');
1508
1637
  return;
1509
1638
  }
1510
- this.startTurn(value);
1639
+ this.startTurn(value, { display });
1640
+ }
1641
+
1642
+ // /model while the turn's request is paused for a rate limit: the one command that runs in a turn. The request
1643
+ // then goes on with the model chosen instead of waiting hours for the limit of the other (the user had to stop
1644
+ // the turn, change the model and say "go on" for that).
1645
+ modelSwitchAtPause(text) {
1646
+ return /^\/model(?:\s|$)/i.test(text) && this.agent.pausedForLimit;
1511
1647
  }
1512
1648
 
1513
1649
  // `@name message`: the message goes to that session, as a task for it. A session on another computer of the
@@ -1543,12 +1679,13 @@ export class App {
1543
1679
  shortcutsHelp() {
1544
1680
  const rows = [
1545
1681
  ['! for bash mode', 'double tap esc to clear input'],
1546
- ['/ for commands', 'ctrl + o to toggle verbose output'],
1682
+ ['/ for commands', '/verbose for detailed tool output'],
1547
1683
  ['@ for files and sessions', 'ctrl + f to find in the conversation'],
1548
1684
  ['PgUp/PgDn, wheel to scroll', 'ctrl + home/end to the top/bottom'],
1549
1685
  ['# to memorize', 'ctrl + t to toggle todos'],
1550
1686
  ['\\⏎ or alt+⏎ for newline', 'ctrl + l to redraw, ctrl + d to exit'],
1551
- ['ctrl + c to copy selection', 'ctrl + v to paste text or an image'],
1687
+ ['ctrl + c to copy selection', 'ctrl + q to quote it in your message'],
1688
+ ['ctrl + v to paste text or an image', ''],
1552
1689
  ];
1553
1690
  return rows.map(([a, b]) => c.dim(' ' + padEnd(a, 30) + b));
1554
1691
  }
@@ -1567,7 +1704,7 @@ export class App {
1567
1704
  if (this.finder && !seed.trim()) { this.finder.selected = Boolean(this.finder.text); this.screen.schedule(); return; } // open: select what is typed
1568
1705
  const text = (seed.split('\n').find((l) => l.trim()) || '').trim() || this.lastFind || '';
1569
1706
  if (!this.finder) this.screen.openFind();
1570
- this.finder = { text, cursor: text.length, selected: Boolean(text), pasting: null };
1707
+ this.finder = { text, cursor: text.length, selected: Boolean(text) };
1571
1708
  this.screen.setFind(text);
1572
1709
  this.screen.schedule();
1573
1710
  }
@@ -1593,13 +1730,7 @@ export class App {
1593
1730
  if (f.selected) edit(t, t.length);
1594
1731
  else edit(f.text.slice(0, f.cursor) + t + f.text.slice(f.cursor), f.cursor + t.length);
1595
1732
  };
1596
- if (name === 'paste-start') { f.pasting = ''; return; }
1597
- if (f.pasting !== null) {
1598
- if (name === 'paste-end') { const t = f.pasting.split(/\r?\n/).find((l) => l.trim()) || ''; f.pasting = null; insert(t.trim()); }
1599
- else if (name === 'return' || name === 'enter') f.pasting += '\n';
1600
- else if (str) f.pasting += str;
1601
- return;
1602
- }
1733
+ // a bracketed paste never gets here: App.onKey takes it whole (see insertFindText)
1603
1734
  if (name === 'escape') { this.closeFind(); return; }
1604
1735
  const back = (name === 'return' && (key.meta || key.shift)) || name === 'enter' || key.sequence === '\x1b[13;2u' || (name === 'f3' && key.shift);
1605
1736
  if (back || name === 'down' || (key.ctrl && name === 'n')) { f.selected = false; this.screen.findStep(-1); return; }
@@ -1969,7 +2100,8 @@ export class App {
1969
2100
  for (const b of blocks) {
1970
2101
  const bash = m.role === 'user' && b.type === 'text' ? bashModeLines(b.text) : null;
1971
2102
  if (bash) this.screen.log(bash, '');
1972
- else if (m.role === 'user' && b.type === 'text' && !b.text.startsWith('<system-reminder>')) this.screen.log(renderUserMessage(b.text.slice(0, 2000), this.width));
2103
+ 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));
2104
+ 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)) }), '');
1973
2105
  if (m.role === 'assistant' && b.type === 'text') this.screen.log(renderMarkdown(b.text, { width: this.width - 1, firstPrefix: `${DOT} `, indent: ' ' }), '');
1974
2106
  if (m.role === 'assistant' && b.type === 'tool_use') {
1975
2107
  const tool = toolMap.get(b.name) || { name: b.name };
@@ -2035,7 +2167,7 @@ export class App {
2035
2167
  this.remote?.emit({ t: 'start', kind: 'text' });
2036
2168
  } else if (ev.block.type === 'thinking') {
2037
2169
  this.remote?.emit({ t: 'start', kind: 'thinking' });
2038
- 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 };
2170
+ this.thinking = new MarkdownStream({ width: w, firstPrefix: c.dim('✻ '), indent: ' ', style: (s) => c.dim(c.italic(s)) });
2039
2171
  } else if (ev.block.type === 'tool_use') {
2040
2172
  this.flushThinking();
2041
2173
  this.pendingToolBlocks.set(ev.index, { name: ev.block.name, partial: '' });
@@ -2052,12 +2184,9 @@ export class App {
2052
2184
  case 'thinking':
2053
2185
  this.turnTokens += estimateTokens(ev.text);
2054
2186
  if (this.thinking) {
2055
- this.thinking.text += ev.text;
2056
2187
  this.remote?.emit({ t: 'delta', kind: 'thinking', text: ev.text });
2057
- if (this.thinking.md) {
2058
- const lines = this.thinking.md.write(ev.text);
2059
- if (lines.length) this.logLocal({ soon: true }, lines);
2060
- }
2188
+ const lines = this.thinking.write(ev.text);
2189
+ if (lines.length) this.logLocal({ soon: true }, lines);
2061
2190
  }
2062
2191
  break;
2063
2192
  case 'tool_input': {
@@ -2108,7 +2237,7 @@ export class App {
2108
2237
  // Say it once; later waits of the same pause only move the countdown (unless the reset moved a lot).
2109
2238
  const prev = this.rateWait;
2110
2239
  this.rateWait = { resumeAt: ev.resumeAt, label: ev.label, polling: ev.polling, overloaded: Boolean(ev.overloaded) };
2111
- if (shouldAnnounce(prev, ev)) this.notice(`${describePause(ev)} Esc cancels.`, 'warn');
2240
+ if (shouldAnnounce(prev, ev)) this.notice(`${describePause(ev)} Esc cancels${!ev.overloaded && this.agent.pauseControl ? '; /model goes on with another model at once' : ''}.`, 'warn');
2112
2241
  this.screen.schedule();
2113
2242
  }
2114
2243
 
@@ -2117,14 +2246,9 @@ export class App {
2117
2246
  if (!t) return;
2118
2247
  this.thinking = null;
2119
2248
  this.remote?.emit({ t: 'stop' });
2120
- if (t.md) {
2121
- const lines = t.md.end();
2122
- if (lines.length) this.logLocal(lines);
2123
- this.logLocal('');
2124
- } else if (t.text.trim()) {
2125
- const secs = Math.max(1, Math.round((Date.now() - t.start) / 1000));
2126
- this.logLocal(c.dim(c.italic(`✻ Thought for ${secs}s (ctrl+o to show thinking)`)), '');
2127
- }
2249
+ const lines = t.end();
2250
+ if (lines.length) this.logLocal(lines);
2251
+ if (t.emittedAny) this.logLocal('');
2128
2252
  }
2129
2253
 
2130
2254
  flushStreaming() {
@@ -2252,7 +2376,6 @@ export class App {
2252
2376
  if (!this.isMain(agent)) return;
2253
2377
  this.flushStreaming();
2254
2378
  this.status = auto ? 'Auto-compacting conversation' : 'Compacting conversation';
2255
- this.compactTokens = 0;
2256
2379
  this.screen.schedule();
2257
2380
  }
2258
2381
 
@@ -2262,11 +2385,10 @@ export class App {
2262
2385
  else if (ev.type === 'rate_limit_wait' || ev.type === 'rate_limit_resume') this.rateLimitEvent(ev);
2263
2386
  }
2264
2387
 
2265
- compactEnd(summary, agent, err, { part } = {}) {
2388
+ compactEnd(_summary, agent, err, { part } = {}) {
2266
2389
  if (!this.isMain(agent)) return;
2267
2390
  this.status = null;
2268
2391
  if (err) return;
2269
- this.lastSummary = summary;
2270
2392
  this.store.setCacheUntil(agent.cache.clockUntil, agent.cacheState());
2271
2393
  const what = part === 'before' ? 'The earlier part of the conversation was summarized' : part === 'after' ? 'The conversation from that message on was summarized' : 'Conversation compacted';
2272
2394
  this.screen.log(c.dim(`✻ ${what} (the summary is in context; /context to see usage)`), '');
@@ -2347,12 +2469,7 @@ export class App {
2347
2469
  const partial = this.md.partial();
2348
2470
  lines.push(...partial.slice(-Math.floor(this.screen.height / 2)));
2349
2471
  }
2350
- if (this.thinking?.md) lines.push(...this.thinking.md.partial().slice(-3));
2351
- else if (this.thinking && this.thinking.text) {
2352
- const text = this.thinking.text.trimEnd();
2353
- const last = text.slice(text.lastIndexOf('\n') + 1); // not split(): this runs every frame on all of it
2354
- lines.push(c.dim(c.italic(truncate(`✻ ${last}`, w))));
2355
- }
2472
+ if (this.thinking) lines.push(...this.thinking.partial().slice(-Math.floor(this.screen.height / 2)));
2356
2473
  for (const [, p] of this.pendingToolBlocks) {
2357
2474
  // The start of the input is enough for a one-line preview (a streaming Bash heredoc can be very long).
2358
2475
  const m = /"(?:file_path|command|pattern|url|description|query)"\s*:\s*"((?:\\.|[^"\\])*)/.exec(p.partial.slice(0, 4000));
@@ -2383,15 +2500,19 @@ export class App {
2383
2500
  }
2384
2501
  if (lines.length) lines.push('');
2385
2502
  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"');
2386
- const r = this.finder ? this.renderFind(width) : this.editor.render(width, { placeholder, title: this.boxTitle() });
2503
+ const after = this.finder ? [c.dim(truncate(' ⏎ or ↑ older · shift+⏎ or ↓ newer · PgUp/PgDn scroll · esc to close', w))]
2504
+ : this.editor.suggestions ? this.editor.renderSuggestions(w)
2505
+ : this.editor.text === '?' ? this.shortcutsHelp()
2506
+ : [this.footer(w)];
2507
+ // the box's text gets the screen less what is above and below it, its borders, and two rows of the conversation
2508
+ const maxRows = Math.max(3, this.screen.height - 1 - lines.length - after.length - 2 - 2);
2509
+ const r = this.finder ? this.renderFind(width) : this.editor.render(width, { placeholder, title: this.boxTitle(), maxRows });
2387
2510
  const top = lines.length;
2388
2511
  lines.push(...r.lines);
2389
2512
  if (r.cursor) cursor = { row: top + r.cursor.row, col: r.cursor.col };
2390
- if (this.finder) lines.push(c.dim(truncate(' ⏎ or ↑ older · shift+⏎ or ↓ newer · PgUp/PgDn scroll · esc to close', w)));
2391
- else if (this.editor.suggestions) lines.push(...this.editor.renderSuggestions(w));
2392
- else if (this.editor.text === '?') lines.push(...this.shortcutsHelp());
2393
- else lines.push(this.footer(w));
2394
- return { lines, cursor };
2513
+ const input = r.text ? { ...r.text, row: top + r.text.row } : null; // where the mouse reaches the input box's text
2514
+ lines.push(...after);
2515
+ return { lines, cursor, input };
2395
2516
  }
2396
2517
 
2397
2518
  // In the input box's top border: the directory the agent is in now (a `cd` moves it), and this
@@ -2418,6 +2539,8 @@ export class App {
2418
2539
  const flash = this.flashMessage && Date.now() < this.flashMessage.until ? this.flashMessage : null;
2419
2540
  if (this.exitArmed && Date.now() - this.exitArmed < 1500) left = c.dim(' Press Ctrl-C again to exit');
2420
2541
  else if (flash) left = (flash.kind === 'warn' ? c.yellow : c.dim)(' ' + truncate(flash.text, w - 4));
2542
+ else if (this.screen.full && this.screen.selection) left = c.dim(' ctrl+c to copy · ctrl+q to quote it in your message');
2543
+ else if (this.editor.selection) left = c.dim(' ctrl+c to copy · esc to clear');
2421
2544
  else if (this.restartRequest) left = c.dim(' ↻ restarting when this turn ends');
2422
2545
  else if (this.editor.mode === 'bash') left = c.magenta(' ! for bash mode');
2423
2546
  else if (this.editor.mode === 'memory') left = c.blue(' # to memorize');
@@ -2428,14 +2551,15 @@ export class App {
2428
2551
  if (!flash) {
2429
2552
  if (this.updating) left += c.dim(' · ') + c.blue(`⇣ updating ${APP_NAME} to ${this.updating}…`);
2430
2553
  else if (this.updateRestart && this.sourceChanged && !this.restartRequest) left += c.dim(' · ') + c.blue(`↻ ${this.updateRestart} installed: restarts ${this.working() ? 'when the work is done' : 'now'}`);
2554
+ else if (this.sourceChanged && !this.sourceChangedInTurn && !this.restartRequest && !this.reloading && !this.working() && this.sourceQuietAt > Date.now()) left += c.dim(' · ') + c.dim('↻ source changed: restarts once it is left alone (/restart: now)');
2431
2555
  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'}`);
2432
2556
  }
2433
2557
  const cfg = this.config;
2434
- const threshold = cfg.autoCompactThreshold(cfg.model);
2558
+ const threshold = cfg.compactWindow();
2435
2559
  const used = this.agent.contextEstimate;
2436
2560
  let notice = '';
2437
2561
  const pctLeft = Math.max(0, Math.round((1 - used / threshold) * 100));
2438
- if (pctLeft <= 30 && cfg.autoCompactEnabled) notice = c.yellow(`Context left until auto-compact: ${pctLeft}%`);
2562
+ if (pctLeft <= 30) notice = c.yellow(`Context left until auto-compact: ${pctLeft}%`);
2439
2563
  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`);
2440
2564
  else if (this.verbose) notice = c.dim('verbose');
2441
2565
  // The model and effort in use always have a place at the right: with the notice after it when both fit,
@@ -2473,5 +2597,8 @@ export async function runRepl({ flags, cwd, initialPrompt }) {
2473
2597
  process.stderr.write(`\nUnexpected error: ${e?.stack || e}\n`);
2474
2598
  process.exit(1);
2475
2599
  });
2600
+ // A promise without a handler that rejects is a bug to show, not a reason to end the session: Node ends the process
2601
+ // on one by default (through the handler above, with exit code 1, which the supervisor does not restart).
2602
+ process.on('unhandledRejection', (e) => { try { app.logError(e); } catch { /* the screen is gone */ } });
2476
2603
  return await app.start(initialPrompt);
2477
2604
  }