@yanzc/claude-pro 0.7.8 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -58
- package/package.json +1 -1
- package/src/agent.js +127 -25
- package/src/cache.js +18 -0
- package/src/commands.js +24 -28
- package/src/config.js +8 -2
- package/src/filestate.js +1 -1
- package/src/keepalive.js +129 -0
- package/src/main.js +12 -39
- package/src/mcp.js +58 -13
- package/src/peers.js +6 -75
- package/src/prompts.js +3 -3
- package/src/remote.js +77 -33
- package/src/runtime.js +3 -0
- package/src/session.js +48 -15
- package/src/supervisor.js +4 -6
- package/src/tools/bash.js +30 -14
- package/src/tools/files.js +366 -62
- package/src/tools/index.js +3 -1
- package/src/tools/search.js +14 -10
- package/src/tools/web.js +14 -6
- package/src/ui/ansi.js +24 -9
- package/src/ui/repl.js +314 -305
- package/src/ui/screen.js +38 -11
- package/src/updater.js +7 -3
- package/src/utils/clipboard.js +16 -75
- package/src/utils/diff.js +21 -3
- package/src/utils/dirs.js +136 -0
- package/src/utils/encoding.js +187 -0
- package/src/utils/paths.js +46 -5
- package/src/utils/shell.js +90 -19
- package/src/attach.js +0 -146
- package/src/background.js +0 -514
- package/src/connect.js +0 -79
- package/src/history.js +0 -163
- package/src/host.js +0 -1474
- package/src/ui/vterm.js +0 -62
package/src/ui/repl.js
CHANGED
|
@@ -6,7 +6,7 @@ import path from 'node:path';
|
|
|
6
6
|
import os from 'node:os';
|
|
7
7
|
import readline from 'node:readline';
|
|
8
8
|
import { spawn } from 'node:child_process';
|
|
9
|
-
import { c, ESC, stringWidth, truncate, padEnd, wordWrap
|
|
9
|
+
import { c, ESC, stringWidth, stripAnsi, truncate, padEnd, wordWrap } from './ansi.js';
|
|
10
10
|
import { Screen, queryCursorRow, mouseFilter } from './screen.js';
|
|
11
11
|
import { Editor, topBorder } from './editor.js';
|
|
12
12
|
import { SelectDialog } from './dialogs.js';
|
|
@@ -23,17 +23,16 @@ import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
|
|
|
23
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';
|
|
29
30
|
import { estimateTokens } from '../agent.js';
|
|
30
|
-
import { readClipboardImage, imageFromFile,
|
|
31
|
+
import { readClipboardImage, imageFromFile, writeClipboard, readClipboardText } from '../utils/clipboard.js';
|
|
31
32
|
import { fitImagesIn, imageSize } from '../utils/images.js';
|
|
32
33
|
import { checkForUpdate, installUpdate, installedVersion, installedByNpm, isNewer } from '../updater.js';
|
|
33
34
|
import { PeerNode, peersEnabled, findPeer, resolvePeer, machineName, cleanName, peerMessagePrompt } from '../peers.js';
|
|
34
|
-
import { RemoteControl, transcriptItems, onlineEnabled, REMOTE_WIDTH } from '../remote.js';
|
|
35
|
-
import { ensureHost as startHostIfNeeded, ensureAutostart, hostEnabled, listDirectory, recentDirectories, computerId, markBackgroundEnded } from '../host.js';
|
|
36
|
-
import { VirtualTerminal } from './vterm.js';
|
|
35
|
+
import { RemoteControl, transcriptItems, onlineEnabled, remoteCommandsEnabled, REMOTE_WIDTH } from '../remote.js';
|
|
37
36
|
|
|
38
37
|
// A model id as people say it: claude-sonnet-5-5 -> sonnet-5-5, claude-haiku-4-5-20251001 -> haiku-4-5.
|
|
39
38
|
export const modelTag = (model) => String(model?.id ?? '').replace(/^claude-/, '').replace(/-\d{8}$/, '');
|
|
@@ -88,12 +87,6 @@ export function remoteImages(images) {
|
|
|
88
87
|
});
|
|
89
88
|
}
|
|
90
89
|
|
|
91
|
-
const FOCUS_EVENTS_ON = '\x1b[?1004h';
|
|
92
|
-
const FOCUS_EVENTS_OFF = '\x1b[?1004l';
|
|
93
|
-
// What a terminal that attaches to a background session is put in first (see attachClient): the fullscreen
|
|
94
|
-
// renderer's alternate screen and mouse reports (screen.js), cleared.
|
|
95
|
-
const ATTACH_MODES = '\x1b[?1049h\x1b[?1002h\x1b[?1006h\x1b[2J';
|
|
96
|
-
|
|
97
90
|
const SPINNER = ['·', '✢', '✳', '✶', '✻', '✽', '✽', '✻', '✶', '✳', '✢', '·'];
|
|
98
91
|
const VERBS = ['Thinking', 'Pondering', 'Crafting', 'Brewing', 'Computing', 'Conjuring', 'Cooking', 'Musing', 'Noodling', 'Percolating', 'Ruminating', 'Synthesizing', 'Working', 'Tinkering', 'Mulling', 'Deliberating', 'Churning', 'Forging', 'Hatching', 'Simmering'];
|
|
99
92
|
const HISTORY_FILE = path.join(CONFIG_DIR, 'history.jsonl');
|
|
@@ -122,6 +115,7 @@ class FileIndex {
|
|
|
122
115
|
if (rg) {
|
|
123
116
|
const child = spawn(rg, ['--files', '--hidden', '--glob', '!.git'], { cwd: this.cwd, windowsHide: true });
|
|
124
117
|
let out = '';
|
|
118
|
+
child.stdout.setEncoding('utf8'); // a Chinese file name can be split between two chunks
|
|
125
119
|
child.stdout.on('data', (d) => { if (out.length < 10_000_000) out += d; });
|
|
126
120
|
child.on('close', () => done(out.split(/\r?\n/).filter(Boolean).map((f) => f.replace(/\\/g, '/'))));
|
|
127
121
|
child.on('error', () => done([]));
|
|
@@ -138,9 +132,10 @@ class FileIndex {
|
|
|
138
132
|
})();
|
|
139
133
|
}
|
|
140
134
|
}
|
|
141
|
-
search(
|
|
142
|
-
|
|
143
|
-
|
|
135
|
+
// The files and their directories with what search() compares, made once per listing (it runs on every keypress
|
|
136
|
+
// after an @, and building it from up to 50,000 paths each time made typing lag in a big project).
|
|
137
|
+
entries() {
|
|
138
|
+
if (this.cache && this.cacheAt === this.at) return this.cache;
|
|
144
139
|
const dirs = new Set();
|
|
145
140
|
for (const f of this.files) {
|
|
146
141
|
const parts = f.split('/');
|
|
@@ -149,12 +144,20 @@ class FileIndex {
|
|
|
149
144
|
}
|
|
150
145
|
// Without ripgrep the listing comes from a glob that also returns directories (as plain names): they are already in `dirs`, with their slash.
|
|
151
146
|
const all = [...dirs, ...this.files.filter((f) => !dirs.has(f + '/'))];
|
|
152
|
-
|
|
153
|
-
for (const f of all) {
|
|
147
|
+
this.cache = all.map((f) => {
|
|
154
148
|
const lower = f.toLowerCase();
|
|
155
|
-
|
|
149
|
+
return { f, lower, base: lower.replace(/\/$/, '').split('/').pop(), depth: f.split('/').length };
|
|
150
|
+
});
|
|
151
|
+
this.cacheAt = this.at;
|
|
152
|
+
return this.cache;
|
|
153
|
+
}
|
|
154
|
+
search(q) {
|
|
155
|
+
this.refresh();
|
|
156
|
+
const query = q.toLowerCase();
|
|
157
|
+
const scored = [];
|
|
158
|
+
for (const { f, lower, base, depth } of this.entries()) {
|
|
156
159
|
let score = -1;
|
|
157
|
-
if (!query) score =
|
|
160
|
+
if (!query) score = depth;
|
|
158
161
|
else if (base.startsWith(query)) score = 0;
|
|
159
162
|
else if (lower.startsWith(query)) score = 1;
|
|
160
163
|
else if (base.includes(query)) score = 2;
|
|
@@ -170,14 +173,9 @@ export class App {
|
|
|
170
173
|
// `noProcessExit`: the tests, which drive the App themselves; it never ends the process, and it has no peers, no
|
|
171
174
|
// gateway connection, no update checks and the default renderer. `selfCheck` (see selfcheck.js): it never ends the
|
|
172
175
|
// process either, but otherwise starts as a session does, so that code only a real start runs is checked too.
|
|
173
|
-
|
|
174
|
-
// and from `claude-pro attach`; what it prints goes to its log (process.stdout, a file the computer service gave it).
|
|
175
|
-
constructor({ flags, cwd, stdin = process.stdin, stdout = process.stdout, noProcessExit = false, selfCheck = false, vterm = null }) {
|
|
176
|
+
constructor({ flags, cwd, stdin = process.stdin, stdout = process.stdout, noProcessExit = false, selfCheck = false }) {
|
|
176
177
|
this.flags = flags;
|
|
177
178
|
this.cwd = cwd;
|
|
178
|
-
this.vterm = vterm;
|
|
179
|
-
this.headless = Boolean(vterm);
|
|
180
|
-
if (vterm) { stdin = vterm.input; stdout = vterm.output; }
|
|
181
179
|
this.stdin = stdin;
|
|
182
180
|
this.stdout = stdout;
|
|
183
181
|
this.noProcessExit = noProcessExit || selfCheck;
|
|
@@ -190,6 +188,9 @@ export class App {
|
|
|
190
188
|
this.controller = null;
|
|
191
189
|
this.queue = [];
|
|
192
190
|
this.dialogs = [];
|
|
191
|
+
// Some terminals turn Ctrl+V into a bracketed-paste sequence. Keep its raw text as a fallback
|
|
192
|
+
// when the platform clipboard helper is unavailable, while still preferring clipboard images.
|
|
193
|
+
this.bracketedPaste = null;
|
|
193
194
|
this.active = []; // running tool entries, in call order
|
|
194
195
|
this.pendingToolBlocks = new Map(); // streaming tool_use blocks, by index
|
|
195
196
|
this.md = null;
|
|
@@ -234,11 +235,6 @@ export class App {
|
|
|
234
235
|
// What the terminal prints goes to the remote page too, except what it is told about as events.
|
|
235
236
|
this.screen.onLog = (items) => {
|
|
236
237
|
const lines = () => items.flatMap((i) => (Array.isArray(i) ? i : [i])).flatMap((l) => String(l).split(/\r?\n/));
|
|
237
|
-
// a background session's log: what it printed, as plain text
|
|
238
|
-
if (this.headless) {
|
|
239
|
-
const stamp = new Date().toISOString().slice(11, 19);
|
|
240
|
-
try { process.stdout.write(`${lines().map((l) => `${stamp} ${stripAnsi(l)}`.trimEnd()).join('\n')}\n`); } catch { /* no log */ }
|
|
241
|
-
}
|
|
242
238
|
if (!this.remote || this.remoteMuted) return;
|
|
243
239
|
this.remote.output(lines());
|
|
244
240
|
};
|
|
@@ -269,10 +265,9 @@ export class App {
|
|
|
269
265
|
stdin.setRawMode(true);
|
|
270
266
|
// Where the cursor is, before anything is drawn: the input box is kept on the last rows of the window from
|
|
271
267
|
// there (see screen.js).
|
|
272
|
-
if (stdin.isTTY && this.stdout.isTTY
|
|
268
|
+
if (stdin.isTTY && this.stdout.isTTY) this.screen.pinFrom(await queryCursorRow(stdin, this.stdout));
|
|
273
269
|
stdin.setEncoding('utf8');
|
|
274
270
|
this.stdout.write(ESC.bracketedPasteOn);
|
|
275
|
-
this.watchCopies();
|
|
276
271
|
const cleanup = () => this.restoreTerminal();
|
|
277
272
|
process.on('exit', cleanup);
|
|
278
273
|
process.on('SIGTERM', () => this.exit(143));
|
|
@@ -324,9 +319,8 @@ export class App {
|
|
|
324
319
|
}, 120);
|
|
325
320
|
if (restart) this.continueAfterRestart(restart);
|
|
326
321
|
else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
|
|
327
|
-
// Nothing configured yet: the gateway is the default, and its browser login starts first.
|
|
328
|
-
|
|
329
|
-
else if (this.config.usesGateway && !gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY) && !this.headless) {
|
|
322
|
+
// 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)) {
|
|
330
324
|
Promise.resolve(this.commands.get('login').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
|
|
331
325
|
}
|
|
332
326
|
this.fileIndex.refresh();
|
|
@@ -337,8 +331,6 @@ export class App {
|
|
|
337
331
|
// online or offline as this computer's gateway login changes (/login or /logout in another window)
|
|
338
332
|
this.loginTimer = setInterval(() => this.syncRemote(), 10_000);
|
|
339
333
|
this.loginTimer.unref?.();
|
|
340
|
-
// the computer service (a process of its own, see host.js), once the session is up
|
|
341
|
-
setTimeout(() => this.ensureHost(), 3000).unref?.();
|
|
342
334
|
}
|
|
343
335
|
return new Promise((resolve) => { this.resolveExit = resolve; });
|
|
344
336
|
}
|
|
@@ -404,13 +396,11 @@ export class App {
|
|
|
404
396
|
|
|
405
397
|
// `handOver`: another process takes the terminal over at once (a restart). It is left the way the program
|
|
406
398
|
// had it (raw mode, bracketed paste, the tab's title), so that keys typed in between are not echoed or lost.
|
|
407
|
-
restoreTerminal({ handOver = false } = {}) {
|
|
399
|
+
restoreTerminal({ handOver = false, farewell = [] } = {}) {
|
|
408
400
|
if (this.restored) return;
|
|
409
401
|
this.restored = true;
|
|
410
402
|
try {
|
|
411
|
-
this.screen.close({ keepTitle: handOver });
|
|
412
|
-
this.clipboardWatch?.close();
|
|
413
|
-
if (this.clipboardWatch) this.stdout.write(FOCUS_EVENTS_OFF);
|
|
403
|
+
this.screen.close({ keepTitle: handOver, after: farewell });
|
|
414
404
|
this.stdout.write(handOver ? ESC.showCursor : ESC.bracketedPasteOff + ESC.showCursor);
|
|
415
405
|
if (!handOver && this.stdin.isTTY) this.stdin.setRawMode(false);
|
|
416
406
|
} catch { /* ignore */ }
|
|
@@ -430,17 +420,13 @@ export class App {
|
|
|
430
420
|
clearInterval(this.loginTimer);
|
|
431
421
|
const remoteClosed = this.remote?.close({ restarting: restart });
|
|
432
422
|
const u = this.agent?.totalUsage();
|
|
423
|
+
const farewell = []; // left on the terminal once the program's screen is gone (see Screen.close)
|
|
433
424
|
if (!restart && u && u.requests) {
|
|
434
|
-
|
|
425
|
+
farewell.push(c.dim(`Total usage: ${formatTokens(u.input + u.cacheRead + u.cacheWrite)} input (${formatTokens(u.cacheRead)} cached), ${formatTokens(u.output)} output, ${u.requests + u.compactions} requests`));
|
|
435
426
|
}
|
|
436
|
-
if (!restart && this.agent?.messages.length)
|
|
437
|
-
this.restoreTerminal({ handOver: restart });
|
|
427
|
+
if (!restart && this.agent?.messages.length) farewell.push(c.dim(`Resume this session with: ${APP_NAME} --resume ${this.store.id}`));
|
|
428
|
+
this.restoreTerminal({ handOver: restart, farewell });
|
|
438
429
|
this.stdin.pause();
|
|
439
|
-
if (this.headless) {
|
|
440
|
-
// ended for good (/exit, the computer service's stop): the service does not open it again
|
|
441
|
-
if (code === 0 && !restart && this.remote?.id) markBackgroundEnded(this.remote.id);
|
|
442
|
-
setTimeout(() => this.vterm.closeAll(), 20).unref?.(); // the last screen first
|
|
443
|
-
}
|
|
444
430
|
this.resolveExit?.(code);
|
|
445
431
|
if (!this.noProcessExit) {
|
|
446
432
|
// with remote control on, the gateway is told first (at most a second and a half; see RemoteControl.close)
|
|
@@ -462,9 +448,6 @@ export class App {
|
|
|
462
448
|
id: this.flags.restart?.peerId,
|
|
463
449
|
onMessage: (msg) => this.onPeerMessage(msg),
|
|
464
450
|
getStatus: () => ({ busy: this.working() }),
|
|
465
|
-
info: () => ({ kind: this.headless ? 'background' : 'terminal', remoteId: this.remote?.id || this.flags.remoteId || this.flags.restart?.remote?.id || null, conversationId: this.store.id, attached: this.vterm ? this.vterm.clients.size : 0 }),
|
|
466
|
-
onControl: (body) => this.onControl(body),
|
|
467
|
-
onAttach: this.headless ? (socket, size) => this.attachClient(socket, size) : null,
|
|
468
451
|
}).start();
|
|
469
452
|
} catch (e) {
|
|
470
453
|
this.peers = null;
|
|
@@ -472,67 +455,10 @@ export class App {
|
|
|
472
455
|
}
|
|
473
456
|
}
|
|
474
457
|
|
|
475
|
-
// The computer service (see host.js) about a background session: {action: 'exit'} ends it as /exit does (a turn
|
|
476
|
-
// that runs, or a question that waits, is stopped first), 'restart' restarts it as /restart does, 'interrupt' is
|
|
477
|
-
// Esc.
|
|
478
|
-
onControl({ action } = {}) {
|
|
479
|
-
if (action === 'interrupt') return this.remoteInterrupt();
|
|
480
|
-
if (action === 'exit') {
|
|
481
|
-
for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
|
|
482
|
-
this.interrupt();
|
|
483
|
-
setTimeout(() => this.exit(0), 50); // once the answer is out
|
|
484
|
-
return {};
|
|
485
|
-
}
|
|
486
|
-
if (action === 'restart') {
|
|
487
|
-
for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
|
|
488
|
-
this.interrupt();
|
|
489
|
-
const res = this.requestRestart({ reason: 'restarted from the web page', force: true });
|
|
490
|
-
if (!res.ok) throw new Error(res.message);
|
|
491
|
-
return {};
|
|
492
|
-
}
|
|
493
|
-
throw new Error(`Unknown action: ${action}`);
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
// `claude-pro attach` (see attach.js) on this background session: the screen, drawn whole for it, and its keys.
|
|
497
|
-
// From the client: one JSON object a line, {keys: base64} or {resize: [columns, rows]}. A turn that runs goes on:
|
|
498
|
-
// the client gets the conversation as it is (scrolled back with the wheel, PgUp), the live part and what follows.
|
|
499
|
-
// The registry says how many are attached (the web page shows it, see background.js); one that goes away
|
|
500
|
-
// (detached, its window closed, its process killed) changes nothing else.
|
|
501
|
-
attachClient(socket, { cols, rows } = {}) {
|
|
502
|
-
const client = { write: (d) => { if (!socket.destroyed) socket.write(d); }, close: () => socket.end() };
|
|
503
|
-
socket.on('error', () => { /* its close follows */ });
|
|
504
|
-
// An HTTP server's sockets stay half open when the other side closes (allowHalfOpen): without this, a client that
|
|
505
|
-
// went away (its window closed, its process killed) would count as attached until a write failed, a minute later.
|
|
506
|
-
socket.on('end', () => socket.destroy());
|
|
507
|
-
socket.on('close', () => {
|
|
508
|
-
this.vterm.detach(client);
|
|
509
|
-
this.peers?.update();
|
|
510
|
-
});
|
|
511
|
-
this.vterm.attach(client, { cols, rows });
|
|
512
|
-
this.peers?.update();
|
|
513
|
-
client.write(`${ATTACH_MODES}${ESC.bracketedPasteOn}`);
|
|
514
|
-
this.screen.title = ''; // its window gets the title too (sent again with the next draw)
|
|
515
|
-
if (this.screen.full) this.screen.repaint();
|
|
516
|
-
let buf = '';
|
|
517
|
-
// (no setEncoding: an HTTP server's socket refuses it; the lines are ASCII anyway, JSON with base64)
|
|
518
|
-
socket.on('data', (d) => {
|
|
519
|
-
buf += d.toString('latin1');
|
|
520
|
-
for (let i = buf.indexOf('\n'); i >= 0; i = buf.indexOf('\n')) {
|
|
521
|
-
const line = buf.slice(0, i);
|
|
522
|
-
buf = buf.slice(i + 1);
|
|
523
|
-
let m;
|
|
524
|
-
try { m = JSON.parse(line); } catch { continue; }
|
|
525
|
-
if (Array.isArray(m?.resize)) this.vterm.resize(m.resize[0], m.resize[1]);
|
|
526
|
-
else if (typeof m?.keys === 'string') this.vterm.type(Buffer.from(m.keys, 'base64'));
|
|
527
|
-
}
|
|
528
|
-
});
|
|
529
|
-
socket.resume(); // the HTTP server leaves an upgraded socket paused
|
|
530
|
-
}
|
|
531
|
-
|
|
532
458
|
// This session's name for the others.
|
|
533
459
|
peerLabel() { return this.peers?.name || this.sessionName || cleanName(path.basename(this.cwd)) || 'claude-pro'; }
|
|
534
460
|
|
|
535
|
-
// /rename: the session's name, for the other sessions (
|
|
461
|
+
// /rename: the session's name, for the other sessions (@name, here and at the gateway) and as the conversation's
|
|
536
462
|
// title (the tab, /resume, the web page), instead of the topic. Returns the name it got: name-2... when another
|
|
537
463
|
// session on this computer has it.
|
|
538
464
|
renameSession(name) {
|
|
@@ -557,11 +483,11 @@ export class App {
|
|
|
557
483
|
if (!found.peer && !found.error && this.remote) found = resolvePeer(local, await this.refreshRemotePeers(), target);
|
|
558
484
|
if (!found.peer) {
|
|
559
485
|
const offline = this.remote ? '' : ' Sessions on your other computers can be reached once this one is online at the gateway (/login).';
|
|
560
|
-
throw new Error(found.error || `No running session called "${String(target).replace(/^[
|
|
486
|
+
throw new Error(found.error || `No running session called "${String(target).replace(/^[@&&]/, '')}". /peers lists them.${offline}`);
|
|
561
487
|
}
|
|
562
488
|
peer = found.peer;
|
|
563
489
|
}
|
|
564
|
-
if (peer.remote && !this.remote) throw new Error(
|
|
490
|
+
if (peer.remote && !this.remote) throw new Error(`@${peer.label} is on another computer, and this session is not online at the gateway (/status says why).`);
|
|
565
491
|
if (!peer.remote && !this.peers) throw new Error('Talking to other sessions on this computer is off (CLAUDE_PRO_PEERS=0).');
|
|
566
492
|
const r = peer.remote
|
|
567
493
|
? { ...(await this.remote.sendPeer(peer.id, { text })), peer }
|
|
@@ -608,7 +534,7 @@ export class App {
|
|
|
608
534
|
|
|
609
535
|
onPeerMessage(msg) {
|
|
610
536
|
if (this.exiting) return;
|
|
611
|
-
const from = c.bold(
|
|
537
|
+
const from = c.bold(`@${msg.from.name}`);
|
|
612
538
|
const width = this.width - 1;
|
|
613
539
|
if (msg.kind === 'reply' && this.userSentToPeers.delete(`${msg.from.id}:${msg.inReplyTo}`)) {
|
|
614
540
|
// the answer to something the user sent: shown, and noted for the model, without a turn of its own
|
|
@@ -616,7 +542,7 @@ export class App {
|
|
|
616
542
|
this.agent.addReminder(`The user sent a message to another claude-pro session, ${msg.from.name} (${msg.from.cwd}), which answered:\n${msg.text}`);
|
|
617
543
|
return;
|
|
618
544
|
}
|
|
619
|
-
const display = `✉ ${msg.kind === 'reply' ? 'answer from' : 'task from'}
|
|
545
|
+
const display = `✉ ${msg.kind === 'reply' ? 'answer from' : 'task from'} @${msg.from.name}: ${msg.text}`;
|
|
620
546
|
const item = { text: peerMessagePrompt(msg), images: [], display, peer: msg.kind === 'task' ? msg : null };
|
|
621
547
|
if (this.isTurnRunning()) { this.queue.push(item); this.screen.schedule(); return; }
|
|
622
548
|
this.startTurn(item.text, { display, peers: item.peer ? [item.peer] : [] });
|
|
@@ -624,10 +550,10 @@ export class App {
|
|
|
624
550
|
|
|
625
551
|
// Send `text` as the answer to `msg`, a message of another session: here, or through the gateway.
|
|
626
552
|
replyToPeer(msg, text) {
|
|
627
|
-
const done = () => this.screen.log(c.dim(` ⎿ Answer sent to
|
|
628
|
-
const failed = (e) => this.notice(`Could not send the answer to
|
|
553
|
+
const done = () => this.screen.log(c.dim(` ⎿ Answer sent to @${msg.from.name}`));
|
|
554
|
+
const failed = (e) => this.notice(`Could not send the answer to @${msg.from.name}: ${e.message}`, 'warn');
|
|
629
555
|
if (msg.from.remote) { // from another computer: back through the gateway
|
|
630
|
-
if (!this.remote) { this.notice(`This session is no longer online at the gateway: the answer to
|
|
556
|
+
if (!this.remote) { this.notice(`This session is no longer online at the gateway: the answer to @${msg.from.name} was not sent.`, 'warn'); return; }
|
|
631
557
|
this.remote.sendPeer(msg.from.id, { kind: 'reply', text, inReplyTo: msg.id }).then(done, failed);
|
|
632
558
|
return;
|
|
633
559
|
}
|
|
@@ -635,7 +561,7 @@ export class App {
|
|
|
635
561
|
// by id, or by name: a session that was restarted by older code comes back with a new id
|
|
636
562
|
const running = this.peers.peers();
|
|
637
563
|
const peer = findPeer(running, msg.from.id) || running.find((p) => p.name === msg.from.name && p.cwd === msg.from.cwd);
|
|
638
|
-
if (!peer) { this.notice(
|
|
564
|
+
if (!peer) { this.notice(`@${msg.from.name} is no longer running: its answer was not sent.`, 'warn'); return; }
|
|
639
565
|
this.peers.send(peer, { text, kind: 'reply', inReplyTo: msg.id }).then(done, failed);
|
|
640
566
|
}
|
|
641
567
|
|
|
@@ -656,9 +582,11 @@ export class App {
|
|
|
656
582
|
// ---------------------------------------------------------------- remote control (see remote.js)
|
|
657
583
|
|
|
658
584
|
// Print to the terminal only: the remote page is told about this as an event of its own.
|
|
585
|
+
// `{soon: true}` first: drawn with the next frame (streamed text, see Screen.logSoon).
|
|
659
586
|
logLocal(...items) {
|
|
587
|
+
const soon = items[0]?.soon === true && items.shift();
|
|
660
588
|
this.remoteMuted++;
|
|
661
|
-
try { this.screen.log(...items); } finally { this.remoteMuted--; }
|
|
589
|
+
try { if (soon) this.screen.logSoon(...items); else this.screen.log(...items); } finally { this.remoteMuted--; }
|
|
662
590
|
}
|
|
663
591
|
|
|
664
592
|
// A message of the user in the transcript (typed here, on the remote page, or sent by another session).
|
|
@@ -677,15 +605,13 @@ export class App {
|
|
|
677
605
|
return Boolean(gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY));
|
|
678
606
|
}
|
|
679
607
|
|
|
680
|
-
// Online at the gateway from the start
|
|
681
|
-
//
|
|
682
|
-
// page waits for); and after a restart as before (with the same id, so that open pages and messages on their way
|
|
683
|
-
// find it again).
|
|
608
|
+
// Online at the gateway from the start when this computer is logged in, and after a restart with the same
|
|
609
|
+
// session id so that an already-open page keeps following it.
|
|
684
610
|
autoStartRemote(restart) {
|
|
685
|
-
const id = restart?.remote?.id ||
|
|
611
|
+
const id = restart?.remote?.id || null;
|
|
686
612
|
if (!id && !this.onlineWanted()) return;
|
|
687
613
|
this.startRemote({ id }).catch((e) => {
|
|
688
|
-
if (e.code === 'NO_GATEWAY_LOGIN'
|
|
614
|
+
if (e.code === 'NO_GATEWAY_LOGIN') return;
|
|
689
615
|
this.notice(`This session could not go online at the gateway: ${e.message}`, 'warn');
|
|
690
616
|
});
|
|
691
617
|
}
|
|
@@ -710,30 +636,26 @@ export class App {
|
|
|
710
636
|
// logged out, or another account: not this account's session any more
|
|
711
637
|
if (r && (!login || login.apiKey !== r.apiKey || normalizeGatewayUrl(login.url || this.config.gatewayUrl) !== normalizeGatewayUrl(r.base))) this.stopRemote();
|
|
712
638
|
if (this.remote) return Promise.resolve(this.remote);
|
|
713
|
-
if (!login || login.apiKey === this.remoteRefused || !
|
|
639
|
+
if (!login || login.apiKey === this.remoteRefused || !this.onlineWanted()) return Promise.resolve(null);
|
|
714
640
|
return this.startRemote().catch((e) => {
|
|
715
641
|
this.notice(`This session could not go online at the gateway: ${e.message}`, 'warn');
|
|
716
642
|
return null;
|
|
717
643
|
});
|
|
718
644
|
}
|
|
719
645
|
|
|
720
|
-
// The computer service (see host.js): started in the background when none runs, so that the gateway's web page can
|
|
721
|
-
// open sessions on this computer even when no session is open, and set up to start at logon (once; after /login,
|
|
722
|
-
// `login`, again unless `claude-pro host uninstall` said no). Not in the tests nor in the self-check.
|
|
723
|
-
ensureHost({ login = false } = {}) {
|
|
724
|
-
const env = this.config.env;
|
|
725
|
-
if (this.driven || this.selfCheck || process.env.NODE_TEST_CONTEXT || this.exiting) return;
|
|
726
|
-
if (!onlineEnabled(env) || !hostEnabled(env) || !gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY)) return;
|
|
727
|
-
try { startHostIfNeeded(); } catch { /* the next session tries again */ }
|
|
728
|
-
try {
|
|
729
|
-
const auto = ensureAutostart({ force: login, env });
|
|
730
|
-
if (auto?.file && login) this.notice(`The computer service starts at logon from now on (${auto.file}; claude-pro host uninstall stops that).`);
|
|
731
|
-
} catch { /* not this time */ }
|
|
732
|
-
}
|
|
733
|
-
|
|
734
646
|
async connectRemote({ id }) {
|
|
735
647
|
const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
736
648
|
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
|
+
// What the page may do here, besides watching (see remote.js): nothing with CLAUDE_PRO_REMOTE_COMMANDS=0.
|
|
650
|
+
const commands = remoteCommandsEnabled(this.config.env) ? {
|
|
651
|
+
send: (body) => this.remoteSend(body.text, body.images),
|
|
652
|
+
interrupt: () => this.remoteInterrupt(),
|
|
653
|
+
answer: (body) => this.answerDialog(body),
|
|
654
|
+
options: () => this.remoteOptions(),
|
|
655
|
+
suggest: (body) => this.remoteSuggest(body),
|
|
656
|
+
list: (body) => this.remoteList(body),
|
|
657
|
+
output: (body) => this.remoteOutput(body),
|
|
658
|
+
} : {};
|
|
737
659
|
const remote = new RemoteControl({
|
|
738
660
|
gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
|
|
739
661
|
id,
|
|
@@ -741,25 +663,25 @@ export class App {
|
|
|
741
663
|
info: () => ({
|
|
742
664
|
name: this.peerLabel(), machine: machineName(this.config.env), peerId: this.peers?.id || null, title: this.sessionLabel() || '',
|
|
743
665
|
cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'), model: modelInfo(this.config).model, version: VERSION,
|
|
744
|
-
|
|
666
|
+
kind: 'terminal',
|
|
745
667
|
}),
|
|
746
668
|
seed: () => [
|
|
747
669
|
...transcriptItems(this.agent.messages, { tools: this.runtime.tools, ctx: this.agent.makeCtx(), cwd: this.cwd }),
|
|
748
670
|
...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
|
|
749
671
|
],
|
|
750
672
|
status: () => this.remoteStatus(),
|
|
751
|
-
|
|
752
|
-
interrupt: () => this.remoteInterrupt(),
|
|
753
|
-
answer: (body) => this.answerDialog(body),
|
|
754
|
-
options: () => this.remoteOptions(),
|
|
755
|
-
suggest: (body) => this.remoteSuggest(body),
|
|
756
|
-
list: (body) => this.remoteList(body),
|
|
757
|
-
output: (body) => this.remoteOutput(body),
|
|
673
|
+
...commands,
|
|
758
674
|
peerMessage: (msg) => this.onPeerMessage(msg),
|
|
759
675
|
changed: () => {
|
|
760
676
|
this.screen.schedule();
|
|
761
677
|
if (remote.online && Date.now() - this.remotePeersAt > 10_000) this.refreshRemotePeers();
|
|
762
678
|
},
|
|
679
|
+
// The key was refused after the start (revoked on the web page, say): offline until the login changes.
|
|
680
|
+
refused: () => {
|
|
681
|
+
this.remoteRefused = login.apiKey;
|
|
682
|
+
if (this.remote === remote) { this.remote = null; this.remotePeers = []; }
|
|
683
|
+
this.notice('The gateway refused this computer\'s key: this session is offline there now (/logout, then /login).', 'warn');
|
|
684
|
+
},
|
|
763
685
|
},
|
|
764
686
|
});
|
|
765
687
|
remote.account = login.account?.email || login.account?.name || null;
|
|
@@ -772,7 +694,6 @@ export class App {
|
|
|
772
694
|
if (this.exiting) { remote.close(); return remote; }
|
|
773
695
|
this.remote = remote;
|
|
774
696
|
this.remoteRefused = null;
|
|
775
|
-
this.peers?.update(); // its id at the gateway, in the registry
|
|
776
697
|
this.remotePeersTimer ??= setInterval(() => { if (this.remote?.online) this.refreshRemotePeers(); }, 60_000);
|
|
777
698
|
this.remotePeersTimer.unref?.();
|
|
778
699
|
this.screen.schedule();
|
|
@@ -792,7 +713,8 @@ export class App {
|
|
|
792
713
|
if (r) {
|
|
793
714
|
const who = r.account ? ` as ${r.account}` : '';
|
|
794
715
|
const pages = r.viewers ? c.dim(` · ${r.viewers} page${r.viewers === 1 ? '' : 's'} open now`) : '';
|
|
795
|
-
const
|
|
716
|
+
const readOnly = r.commands.length ? '' : c.dim(' · read-only on the page (CLAUDE_PRO_REMOTE_COMMANDS=0)');
|
|
717
|
+
const text = r.online ? `${c.green('online')}${who}${pages}${readOnly}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
|
|
796
718
|
return { text };
|
|
797
719
|
}
|
|
798
720
|
if (this.remoteStarting) return { text: 'connecting…' };
|
|
@@ -838,7 +760,7 @@ export class App {
|
|
|
838
760
|
cost: Number(this.cost.toFixed(6)),
|
|
839
761
|
context: { used: this.contextUsed(), window: cfg.model.contextWindow },
|
|
840
762
|
background: this.backgroundWork(),
|
|
841
|
-
kind:
|
|
763
|
+
kind: 'terminal',
|
|
842
764
|
};
|
|
843
765
|
}
|
|
844
766
|
|
|
@@ -875,6 +797,10 @@ export class App {
|
|
|
875
797
|
return { ...base, multi: Boolean(d.multi), options: d.options.map((o) => ({ label: String(o.label ?? ''), description: o.description || '', other: o.value === '__other__' })) };
|
|
876
798
|
}
|
|
877
799
|
|
|
800
|
+
// ---------------------------------------------------------------- the page's commands (see remote.js)
|
|
801
|
+
|
|
802
|
+
// 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}.
|
|
878
804
|
answerDialog({ id, index, indices, text, cancel } = {}) {
|
|
879
805
|
const d = this.dialogs[0];
|
|
880
806
|
if (!d || d.remoteId !== id) throw new Error('That question is no longer open.');
|
|
@@ -904,8 +830,9 @@ export class App {
|
|
|
904
830
|
return {};
|
|
905
831
|
}
|
|
906
832
|
|
|
907
|
-
// A message from the page: as if typed in the input box
|
|
908
|
-
// as their placeholders, which is what the input box
|
|
833
|
+
// A message from the page: as if typed in the input box and sent (a turn, queued while one runs; /commands, !,
|
|
834
|
+
// #, @session), its images as if pasted there. Images alone go as their placeholders, which is what the input box
|
|
835
|
+
// sends for them.
|
|
909
836
|
remoteSend(text, images) {
|
|
910
837
|
const pictures = remoteImages(images);
|
|
911
838
|
let value = String(text ?? '').replace(/\r\n/g, '\n');
|
|
@@ -920,21 +847,37 @@ export class App {
|
|
|
920
847
|
return { queued };
|
|
921
848
|
}
|
|
922
849
|
|
|
923
|
-
//
|
|
924
|
-
|
|
850
|
+
// Esc: the turn stops, and the questions waiting for an answer are cancelled.
|
|
851
|
+
remoteInterrupt() {
|
|
852
|
+
for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
|
|
853
|
+
this.interrupt();
|
|
854
|
+
this.screen.schedule();
|
|
855
|
+
return {};
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// For the page's model and effort menus: what /model and /effort offer (in plain text; the page sends /model
|
|
859
|
+
// <value> or /effort <value>), what is chosen (`current`), and the model and effort in use, as the status says.
|
|
925
860
|
async remoteOptions() {
|
|
926
861
|
const cfg = this.config;
|
|
927
862
|
const [models, efforts] = await Promise.all([modelChoices(cfg), effortChoices(cfg)]);
|
|
863
|
+
const chosen = cfg.modelOverride || 'default';
|
|
864
|
+
const current = models.find((o) => o.value === chosen) || models.find((o) => o.value !== 'default' && cfg.resolveModel(o.value).id === cfg.model.id);
|
|
865
|
+
const effortChosen = cfg.effortOverride || 'default';
|
|
928
866
|
const { effort } = modelInfo(cfg);
|
|
929
|
-
return {
|
|
867
|
+
return {
|
|
868
|
+
model: cfg.model.id,
|
|
869
|
+
models: models.map((o) => ({ ...o, ...(o === current ? { current: true } : {}) })),
|
|
870
|
+
effort: effort || defaultEffort(cfg.model.id, cfg),
|
|
871
|
+
efforts: efforts.options.map((o) => ({ ...o, ...(o.value === effortChosen ? { current: true } : {}) })),
|
|
872
|
+
};
|
|
930
873
|
}
|
|
931
874
|
|
|
932
|
-
// For the page's input box: what the input box here would suggest (/commands, @files
|
|
933
|
-
// without anything happening here. Sessions on the other computers are asked for first when the list is old.
|
|
875
|
+
// For the page's input box: what the input box here would suggest (/commands, @files and @sessions), in plain
|
|
876
|
+
// text, without anything happening here. Sessions on the other computers are asked for first when the list is old.
|
|
934
877
|
async remoteSuggest(body = {}) {
|
|
935
878
|
const text = String(body.text ?? '');
|
|
936
879
|
const cursor = Number.isInteger(body.cursor) ? Math.max(0, Math.min(text.length, body.cursor)) : text.length;
|
|
937
|
-
if (/(^|\s)[
|
|
880
|
+
if (/(^|\s)@[^\s@"]*$/u.test(text.slice(0, cursor)) && this.remote?.online && Date.now() - this.remotePeersAt > 10_000) {
|
|
938
881
|
await Promise.race([this.refreshRemotePeers(), new Promise((r) => setTimeout(r, 3000))]);
|
|
939
882
|
}
|
|
940
883
|
const found = this.suggest(text, cursor, { quiet: true });
|
|
@@ -947,25 +890,31 @@ export class App {
|
|
|
947
890
|
};
|
|
948
891
|
}
|
|
949
892
|
|
|
950
|
-
// For the page's directory browser (/cd): the
|
|
951
|
-
//
|
|
893
|
+
// For the page's directory browser (/cd): the directories in `path` ("": this session's working directory), with
|
|
894
|
+
// the drives, the home directory and where sessions ran lately.
|
|
952
895
|
remoteList(body = {}) {
|
|
953
|
-
const wanted = typeof body.path === 'string' && body.path.trim() ? body.path : this.cwd;
|
|
896
|
+
const wanted = typeof body.path === 'string' && body.path.trim() ? body.path : (this.agent.cwd || this.cwd);
|
|
954
897
|
return listDirectory(wanted, {
|
|
955
898
|
recent: () => {
|
|
956
|
-
if (!this.recentDirs || Date.now() - this.recentDirs.at > 30_000) this.recentDirs = { at: Date.now(), list: recentDirectories() };
|
|
899
|
+
if (!this.recentDirs || Date.now() - this.recentDirs.at > 30_000) this.recentDirs = { at: Date.now(), list: recentDirectories({ projects: path.join(CONFIG_DIR, 'projects') }) };
|
|
957
900
|
return this.recentDirs.list;
|
|
958
901
|
},
|
|
959
902
|
});
|
|
960
903
|
}
|
|
961
904
|
|
|
962
|
-
// For the page's "the whole output": the full result of the tool call `id` ({text, truncated}, at most
|
|
963
|
-
// file it was saved to when it was too long for the conversation
|
|
964
|
-
// far while it runs.
|
|
905
|
+
// For the page's "the whole output": the full result of the tool call `id` ({text, truncated, running?}, at most
|
|
906
|
+
// 1 MB of UTF-8): the file it was saved to when it was too long for the conversation or cleared from it later,
|
|
907
|
+
// and what it printed so far while it runs.
|
|
965
908
|
remoteOutput({ id } = {}) {
|
|
966
909
|
if (typeof id !== 'string' || !id) throw new Error('Which tool call?');
|
|
967
910
|
const MAX = 1024 * 1024;
|
|
968
|
-
const cut = (text, running = false) =>
|
|
911
|
+
const cut = (text, running = false) => {
|
|
912
|
+
const buf = Buffer.from(text, 'utf8');
|
|
913
|
+
const truncated = buf.length > MAX;
|
|
914
|
+
// (a character cut at the end decodes as U+FFFD, which is then dropped)
|
|
915
|
+
const shown = truncated ? buf.subarray(0, MAX).toString('utf8').replace(/\ufffd$/, '') : text;
|
|
916
|
+
return { text: shown, truncated, ...(running ? { running } : {}) };
|
|
917
|
+
};
|
|
969
918
|
let result = null;
|
|
970
919
|
for (const m of this.agent.messages) {
|
|
971
920
|
if (m.role !== 'user' || !Array.isArray(m.content)) continue;
|
|
@@ -973,12 +922,12 @@ export class App {
|
|
|
973
922
|
}
|
|
974
923
|
if (!result) {
|
|
975
924
|
const live = this.active.find((e) => e.tu?.id === id);
|
|
976
|
-
if (live) return cut(String(live.progress || ''), true);
|
|
925
|
+
if (live) return cut(live.progressAll?.() ?? String(live.progress || ''), true);
|
|
977
926
|
throw new Error('There is no such tool call in this conversation.');
|
|
978
927
|
}
|
|
979
928
|
let text = typeof result.content === 'string' ? result.content
|
|
980
929
|
: (Array.isArray(result.content) ? result.content : []).map((b) => (b.type === 'text' ? b.text : b.type === 'image' ? '[image]' : '')).join('\n');
|
|
981
|
-
// saved whole in the
|
|
930
|
+
// saved whole in the project's tool-results (a large result, a Bash output, a result cleared after a pause)
|
|
982
931
|
const saved = /(?:saved to:?|saved at)\s+(\S+?\.txt)\b/.exec(text)?.[1];
|
|
983
932
|
const results = path.join(CONFIG_DIR, 'projects');
|
|
984
933
|
if (saved && path.resolve(saved).startsWith(results + path.sep) && path.resolve(saved).includes(`${path.sep}tool-results${path.sep}`)) {
|
|
@@ -987,13 +936,6 @@ export class App {
|
|
|
987
936
|
return cut(text);
|
|
988
937
|
}
|
|
989
938
|
|
|
990
|
-
remoteInterrupt() {
|
|
991
|
-
for (const d of this.dialogs.splice(0)) d.resolve(d.cancelValue);
|
|
992
|
-
this.interrupt();
|
|
993
|
-
this.screen.schedule();
|
|
994
|
-
return {};
|
|
995
|
-
}
|
|
996
|
-
|
|
997
939
|
// ---------------------------------------------------------------- restarting (see restart.js)
|
|
998
940
|
|
|
999
941
|
// What a restart would kill: agents and shells that are still running in the background.
|
|
@@ -1208,7 +1150,7 @@ export class App {
|
|
|
1208
1150
|
if (this.updateWaitingFor !== busy.join(',')) {
|
|
1209
1151
|
this.updateWaitingFor = busy.join(',');
|
|
1210
1152
|
this.screen.schedule();
|
|
1211
|
-
if (force) this.notice(`${APP_NAME} ${version} is installed once
|
|
1153
|
+
if (force) this.notice(`${APP_NAME} ${version} is installed once @${busy.join(', @')} ${busy.length === 1 ? 'is' : 'are'} done working.`);
|
|
1212
1154
|
}
|
|
1213
1155
|
clearTimeout(this.updateRetry);
|
|
1214
1156
|
this.updateRetry = setTimeout(() => this.maybeInstallUpdate(), 30_000);
|
|
@@ -1275,30 +1217,15 @@ export class App {
|
|
|
1275
1217
|
|
|
1276
1218
|
// ---------------------------------------------------------------- input
|
|
1277
1219
|
|
|
1278
|
-
// Say "copied" when the user copies text selected in this terminal, as Claude Code does. The terminal does the
|
|
1279
|
-
// selecting and copying and tells nobody, so the clipboard is watched; focus events (which the terminal sends
|
|
1280
|
-
// once asked to) keep copies made in other windows from being announced. Off with CLAUDE_PRO_COPY_NOTICE=0,
|
|
1281
|
-
// and when not writing to the real terminal (the tests).
|
|
1282
|
-
watchCopies() {
|
|
1283
|
-
if (this.stdout !== process.stdout || !this.stdout.isTTY || /^(0|false|no)$/i.test(process.env.CLAUDE_PRO_COPY_NOTICE || '')) return;
|
|
1284
|
-
this.focused = true;
|
|
1285
|
-
this.clipboardWatch = watchClipboard((chars) => {
|
|
1286
|
-
if (!this.focused || this.exiting) return;
|
|
1287
|
-
this.flash(chars ? `Copied ${chars.toLocaleString()} characters to the clipboard` : 'Copied to the clipboard');
|
|
1288
|
-
});
|
|
1289
|
-
this.stdout.write(FOCUS_EVENTS_ON);
|
|
1290
|
-
}
|
|
1291
|
-
|
|
1292
1220
|
// Fullscreen (see screen.js) unless CLAUDE_PRO_TUI=default, as Claude Code's /tui: the input box fixed at the
|
|
1293
1221
|
// bottom of the window, the conversation scrolled inside the program. Not in the tests that drive the App.
|
|
1294
1222
|
fullscreenWanted() {
|
|
1295
|
-
if (this.headless) return true; // `claude-pro attach` gets the whole screen, drawn again when it comes
|
|
1296
1223
|
const mode = String(this.config.env.CLAUDE_PRO_TUI || (this.driven ? 'default' : 'fullscreen')).toLowerCase();
|
|
1297
1224
|
return mode === 'fullscreen' && this.stdout.isTTY !== false;
|
|
1298
1225
|
}
|
|
1299
1226
|
|
|
1300
1227
|
// Fullscreen: the wheel scrolls the conversation (3 rows a notch); a drag,
|
|
1301
|
-
// a double or a triple click selects
|
|
1228
|
+
// a double or a triple click selects text. Selection is copied only with Ctrl+C.
|
|
1302
1229
|
onMouse(m) {
|
|
1303
1230
|
if (!this.screen.full || this.exiting) return;
|
|
1304
1231
|
if (m.button & 64) {
|
|
@@ -1307,37 +1234,97 @@ export class App {
|
|
|
1307
1234
|
this.screen.scrollBy(m.button & 1 ? -speed : speed);
|
|
1308
1235
|
return;
|
|
1309
1236
|
}
|
|
1310
|
-
//
|
|
1311
|
-
|
|
1312
|
-
// handled the same way (long text folded, an image path attached, into a dialog's answer box).
|
|
1313
|
-
if ((m.button & 3) === 2 && !(m.button & 32) && !m.release) {
|
|
1314
|
-
if (this.screen.selection) {
|
|
1315
|
-
this.copyText(this.screen.selectedText());
|
|
1316
|
-
this.screen.clearSelection();
|
|
1317
|
-
return;
|
|
1318
|
-
}
|
|
1319
|
-
readClipboardText().then((text) => {
|
|
1320
|
-
if (!text || this.exiting) return;
|
|
1321
|
-
const clean = text.replace(/\x1b\[20[01]~/g, '').replace(/\r\n|\n/g, '\r');
|
|
1322
|
-
this.keys.write(`\x1b[200~${clean}\x1b[201~`);
|
|
1323
|
-
});
|
|
1324
|
-
return;
|
|
1325
|
-
}
|
|
1326
|
-
const r = this.screen.mouse(m);
|
|
1327
|
-
if (r?.copy) this.copyText(r.copy);
|
|
1237
|
+
// Right-click is intentionally inert. Clipboard operations use Ctrl+C and Ctrl+V only.
|
|
1238
|
+
this.screen.mouse(m);
|
|
1328
1239
|
}
|
|
1329
1240
|
|
|
1330
1241
|
copyText(text) {
|
|
1331
1242
|
writeClipboard(text).then((ok) => {
|
|
1332
1243
|
if (ok) this.flash(`Copied ${text.length.toLocaleString()} characters to the clipboard`);
|
|
1333
|
-
else this.flash('Could not copy: no clipboard tool found
|
|
1244
|
+
else this.flash('Could not copy: no clipboard tool found', 'warn');
|
|
1245
|
+
});
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
clipboardEditor() {
|
|
1249
|
+
const dialog = this.dialogs[0];
|
|
1250
|
+
if (dialog) return dialog.editor || dialog.other || null;
|
|
1251
|
+
return this.finder ? null : this.editor;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
insertFindText(text) {
|
|
1255
|
+
const f = this.finder;
|
|
1256
|
+
const clean = String(text ?? '').replace(/[\r\n\t]+/g, ' ');
|
|
1257
|
+
if (!f || !clean) return;
|
|
1258
|
+
if (f.selected) {
|
|
1259
|
+
f.text = clean;
|
|
1260
|
+
f.cursor = clean.length;
|
|
1261
|
+
f.selected = false;
|
|
1262
|
+
} else {
|
|
1263
|
+
f.text = f.text.slice(0, f.cursor) + clean + f.text.slice(f.cursor);
|
|
1264
|
+
f.cursor += clean.length;
|
|
1265
|
+
}
|
|
1266
|
+
this.screen.setFind(f.text);
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
// Pasted text into the input box, the open dialog's text field or the find box.
|
|
1270
|
+
insertPastedText(text, target = this.clipboardEditor()) {
|
|
1271
|
+
const clean = String(text || '').replace(/\x1b\[20[01]~/g, '');
|
|
1272
|
+
if (!clean) return;
|
|
1273
|
+
if (target) target.insertPaste(clean);
|
|
1274
|
+
else if (this.finder) this.insertFindText(clean);
|
|
1275
|
+
this.screen.schedule();
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
// Read the system clipboard: an image first, else its text. Each read starts PowerShell (about a second), so it
|
|
1279
|
+
// is only done when the terminal had nothing to paste (alt+v, ctrl+v as a key, an empty bracketed paste).
|
|
1280
|
+
pasteClipboard(target = this.clipboardEditor()) {
|
|
1281
|
+
if (this.readingClipboard || this.exiting) return;
|
|
1282
|
+
if (!target && !this.finder) return; // selection dialogs have no text field to paste into
|
|
1283
|
+
this.readingClipboard = true;
|
|
1284
|
+
this.flash('Reading clipboard…');
|
|
1285
|
+
const allowImage = Boolean(target?.insertImage);
|
|
1286
|
+
const image = allowImage
|
|
1287
|
+
? readClipboardImage().catch((e) => ({ image: null, error: e.message }))
|
|
1288
|
+
: Promise.resolve({ image: null });
|
|
1289
|
+
image.then((r) => {
|
|
1290
|
+
if (r.image && target) {
|
|
1291
|
+
const label = target.insertImage(r.image);
|
|
1292
|
+
const size = r.image.width ? `${r.image.width}×${r.image.height}, ` : '';
|
|
1293
|
+
this.flash(`${label} attached (${size}${formatTokens(r.image.bytes).replace(/k$/, 'KB')})`);
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
return readClipboardText().then((text) => {
|
|
1297
|
+
if (this.exiting) return;
|
|
1298
|
+
if (text) this.insertPastedText(text, target);
|
|
1299
|
+
else if (r.error) this.flash(`Could not read the clipboard: ${r.error}`, 'warn');
|
|
1300
|
+
});
|
|
1301
|
+
}).catch((e) => {
|
|
1302
|
+
if (!this.exiting) this.flash(`Could not read the clipboard: ${e.message}`, 'warn');
|
|
1303
|
+
}).finally(() => {
|
|
1304
|
+
this.readingClipboard = false;
|
|
1305
|
+
this.screen.schedule();
|
|
1334
1306
|
});
|
|
1335
1307
|
}
|
|
1336
1308
|
|
|
1337
1309
|
onKey(str, key) {
|
|
1338
1310
|
if (this.exiting) return;
|
|
1339
|
-
|
|
1340
|
-
|
|
1311
|
+
// Terminals paste (ctrl+v in Windows Terminal and VS Code) as bracketed paste: readline reports paste-start/end
|
|
1312
|
+
// and emits the text as ordinary keys between them. That text goes in at once. A paste with no text is what a
|
|
1313
|
+
// terminal sends for an image on the clipboard, which only the system clipboard has (alt+v reads it on demand).
|
|
1314
|
+
if (this.bracketedPaste) {
|
|
1315
|
+
if (key.name === 'paste-end' || key.sequence === '\x1b[201~') {
|
|
1316
|
+
const raw = this.bracketedPaste.raw;
|
|
1317
|
+
this.bracketedPaste = null;
|
|
1318
|
+
if (raw) this.insertPastedText(raw);
|
|
1319
|
+
else this.pasteClipboard();
|
|
1320
|
+
} else if (key.name === 'return' || key.name === 'enter') {
|
|
1321
|
+
// Keep CRLF intact; Editor.insertPaste normalizes line endings once.
|
|
1322
|
+
this.bracketedPaste.raw += str || '\n';
|
|
1323
|
+
} else if (str) {
|
|
1324
|
+
this.bracketedPaste.raw += str;
|
|
1325
|
+
}
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1341
1328
|
if (this.screen.full) {
|
|
1342
1329
|
const half = Math.max(1, Math.floor((this.screen.lastArea || this.screen.height) / 2));
|
|
1343
1330
|
if (key.name === 'pageup') { this.screen.scrollBy(half); return; }
|
|
@@ -1359,8 +1346,13 @@ export class App {
|
|
|
1359
1346
|
if (key.name === 'escape') return;
|
|
1360
1347
|
}
|
|
1361
1348
|
}
|
|
1349
|
+
if (key.name === 'paste-start' || key.sequence === '\x1b[200~') {
|
|
1350
|
+
this.bracketedPaste = { raw: '' };
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1362
1353
|
if (key.ctrl && key.name === 'c' && this.finder && !this.dialogs.length) { this.closeFind(); return; } // not the hidden input's text
|
|
1363
1354
|
if (key.ctrl && key.name === 'c') { this.onCtrlC(); return; }
|
|
1355
|
+
if ((key.ctrl || key.meta) && key.name === 'v') { this.pasteClipboard(); return; } // alt+v: the clipboard's image
|
|
1364
1356
|
const dialog = this.dialogs[0];
|
|
1365
1357
|
if (dialog) {
|
|
1366
1358
|
dialog.handleKey(str, key);
|
|
@@ -1369,8 +1361,6 @@ export class App {
|
|
|
1369
1361
|
}
|
|
1370
1362
|
if (key.ctrl && key.name === 'f') { this.openFind(); return; }
|
|
1371
1363
|
if (this.finder) { this.findKey(str, key); this.screen.schedule(); return; }
|
|
1372
|
-
// alt+v like Claude Code on Windows (ctrl+v is the terminal's own text paste there).
|
|
1373
|
-
if ((key.meta || key.ctrl) && key.name === 'v') { this.pasteImage(); return; }
|
|
1374
1364
|
if (key.ctrl && key.name === 'o') {
|
|
1375
1365
|
this.verbose = !this.verbose;
|
|
1376
1366
|
this.notice(this.verbose ? 'Verbose mode on: showing thinking and full tool output' : 'Verbose mode off', 'info');
|
|
@@ -1385,12 +1375,9 @@ export class App {
|
|
|
1385
1375
|
this.screen.schedule();
|
|
1386
1376
|
}
|
|
1387
1377
|
|
|
1388
|
-
// ctrl+c twice, ctrl+d: the end of the session
|
|
1389
|
-
// `claude-pro attach` and leaving it is detaching (/exit ends the session there).
|
|
1378
|
+
// ctrl+c twice, ctrl+d: the end of the session.
|
|
1390
1379
|
keyboardExit() {
|
|
1391
|
-
|
|
1392
|
-
this.exitArmed = 0;
|
|
1393
|
-
this.flash('This session runs in the background: ctrl+] detaches from it, /exit ends it');
|
|
1380
|
+
this.exit(0);
|
|
1394
1381
|
}
|
|
1395
1382
|
|
|
1396
1383
|
onCtrlC() {
|
|
@@ -1414,7 +1401,7 @@ export class App {
|
|
|
1414
1401
|
this.screen.schedule();
|
|
1415
1402
|
}
|
|
1416
1403
|
|
|
1417
|
-
// `quiet`:
|
|
1404
|
+
// `quiet`: do not print the transcript (a restart: it is still on screen).
|
|
1418
1405
|
suggest(text, cursor, { quiet = false } = {}) {
|
|
1419
1406
|
if (text.startsWith('/') && !/\s/.test(text) && cursor === text.length) {
|
|
1420
1407
|
const q = text.slice(1).toLowerCase();
|
|
@@ -1430,41 +1417,50 @@ export class App {
|
|
|
1430
1417
|
if (items.length === 1 && items[0].value === text && !items[0].submitOnEnter) return null;
|
|
1431
1418
|
return { items, from: 0, to: text.length };
|
|
1432
1419
|
}
|
|
1433
|
-
//
|
|
1420
|
+
// One `@` namespace serves both files and sessions. A quoted token is a file path; session names are
|
|
1421
|
+
// never quoted because cleanName() removes spaces from them.
|
|
1434
1422
|
const before = text.slice(0, cursor);
|
|
1435
1423
|
const m = /(^|\s)@(?:"([^"@]*)|([^\s@"]*))$/.exec(before);
|
|
1436
|
-
if (m)
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
//
|
|
1447
|
-
//
|
|
1448
|
-
const
|
|
1449
|
-
|
|
1450
|
-
|
|
1424
|
+
if (!m) return null;
|
|
1425
|
+
const quoted = m[2] !== undefined;
|
|
1426
|
+
const q = quoted ? m[2] : m[3];
|
|
1427
|
+
const fileQuery = q.replace(/^\.\/+/, '');
|
|
1428
|
+
const filePrefix = q.startsWith('./') ? './' : '';
|
|
1429
|
+
const files = this.fileIndex.search(fileQuery);
|
|
1430
|
+
const peerResult = quoted ? null : this.peerSuggestions(q, cursor, m.index === 0 && !m[1], { quiet: true });
|
|
1431
|
+
const peers = peerResult?.items || [];
|
|
1432
|
+
const peerRefs = new Set(peers.map((item) => item.value.slice(1)));
|
|
1433
|
+
// A name with spaces has to be quoted for the mention to be read back as one file. A directory
|
|
1434
|
+
// leaves the quote open, so that completion goes on inside it. When a file and session have the
|
|
1435
|
+
// same name, the file completion uses ./ so the session-priority submit rule cannot misroute it.
|
|
1436
|
+
const fileItems = files.map((f) => {
|
|
1437
|
+
const conflict = !quoted && !filePrefix && peerRefs.has(f);
|
|
1438
|
+
const ref = conflict ? `./${f}` : `${filePrefix}${f}`;
|
|
1439
|
+
const value = quoted || /\s/.test(f) ? (f.endsWith('/') ? `@"${ref}` : `@"${ref}"`) : '@' + ref;
|
|
1440
|
+
return {
|
|
1441
|
+
value,
|
|
1442
|
+
label: conflict ? `@./${f}` : f,
|
|
1443
|
+
description: f.endsWith('/') ? 'directory' : 'file',
|
|
1444
|
+
noSpace: f.endsWith('/'),
|
|
1445
|
+
};
|
|
1446
|
+
});
|
|
1447
|
+
const items = [...peers, ...fileItems];
|
|
1448
|
+
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)');
|
|
1450
|
+
return null;
|
|
1451
|
+
}
|
|
1452
|
+
return { items, from: cursor - q.length - (quoted ? 2 : 1), to: cursor };
|
|
1451
1453
|
}
|
|
1452
1454
|
|
|
1453
1455
|
peerSuggestions(q, cursor, atStart = true, { quiet = false } = {}) {
|
|
1454
|
-
if (
|
|
1456
|
+
if (this.remote?.online && Date.now() - this.remotePeersAt > 10_000) {
|
|
1455
1457
|
this.refreshRemotePeers().then(() => {
|
|
1456
|
-
if (!/[
|
|
1458
|
+
if (!/(^|\s)@(?:"[^"@]*|[^\s@"]*)$/u.test(this.editor.text.slice(0, this.editor.cursor))) return;
|
|
1457
1459
|
this.editor.refreshSuggestions();
|
|
1458
1460
|
this.screen.schedule();
|
|
1459
1461
|
});
|
|
1460
1462
|
}
|
|
1461
|
-
const
|
|
1462
|
-
const items = [
|
|
1463
|
-
...(this.peers?.peers() || []).filter((p) => p.name.toLowerCase().startsWith(lq))
|
|
1464
|
-
.map((p) => ({ value: '&' + p.name, label: `&${p.name}`, description: `this computer · ${displayPath(p.cwd, this.cwd)}` })),
|
|
1465
|
-
...this.remotePeers.filter((p) => [p.label, p.name, p.machine].some((v) => v.toLowerCase().startsWith(lq)))
|
|
1466
|
-
.map((p) => ({ value: '&' + p.label, label: `&${p.label}`, description: `${p.machine} · ${p.cwd}${p.busy ? ' · busy' : ''}` })),
|
|
1467
|
-
];
|
|
1463
|
+
const items = this.peerSuggestionItems(q);
|
|
1468
1464
|
if (!items.length) {
|
|
1469
1465
|
if (!q && atStart && !quiet) this.flash(this.remote ? 'No other session is running here or online at the gateway' : 'No other session is running on this computer (/login to the gateway reaches your other computers)');
|
|
1470
1466
|
return null;
|
|
@@ -1472,6 +1468,16 @@ export class App {
|
|
|
1472
1468
|
return { items, from: cursor - q.length - 1, to: cursor };
|
|
1473
1469
|
}
|
|
1474
1470
|
|
|
1471
|
+
peerSuggestionItems(q) {
|
|
1472
|
+
const lq = q.toLowerCase();
|
|
1473
|
+
return [
|
|
1474
|
+
...(this.peers?.peers() || []).filter((p) => p.name.toLowerCase().startsWith(lq))
|
|
1475
|
+
.map((p) => ({ value: '@' + p.name, label: `@${p.name}`, description: `session · this computer · ${displayPath(p.cwd, this.cwd)}` })),
|
|
1476
|
+
...this.remotePeers.filter((p) => [p.label, p.name, p.machine].some((v) => v.toLowerCase().startsWith(lq)))
|
|
1477
|
+
.map((p) => ({ value: '@' + p.label, label: `@${p.label}`, description: `session · ${p.machine} · ${p.cwd}${p.busy ? ' · busy' : ''}` })),
|
|
1478
|
+
];
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1475
1481
|
onSubmit(value, raw, images = []) {
|
|
1476
1482
|
const text = value.trim();
|
|
1477
1483
|
if (!text) { this.screen.schedule(); return; }
|
|
@@ -1504,20 +1510,30 @@ export class App {
|
|
|
1504
1510
|
this.startTurn(value);
|
|
1505
1511
|
}
|
|
1506
1512
|
|
|
1507
|
-
//
|
|
1508
|
-
// gateway account:
|
|
1513
|
+
// `@name message`: the message goes to that session, as a task for it. A session on another computer of the
|
|
1514
|
+
// gateway account: `@machine/name message`, or `@machine message` when that computer runs one session. A known
|
|
1515
|
+
// file wins only when no session matches; use `@./name` to force a file when the names collide.
|
|
1509
1516
|
sendTypedToPeer(text) {
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
const
|
|
1513
|
-
if (!m
|
|
1514
|
-
|
|
1517
|
+
// Quoted @ tokens are file syntax; session names are clean and never contain spaces.
|
|
1518
|
+
if (/^@"[^"]*"(?:\s+[\s\S]*)?$/u.test(text)) return false;
|
|
1519
|
+
const m = /^@(\S+)(?:\s+([\s\S]*))?$/u.exec(text);
|
|
1520
|
+
if (!m) return false;
|
|
1521
|
+
const task = m[2]?.trim();
|
|
1515
1522
|
const found = resolvePeer(this.peers?.peers() || [], this.remotePeers, m[1], { ids: false });
|
|
1523
|
+
const file = this.mentionedFile(m[1]);
|
|
1524
|
+
const pathLike = /^(?:\.\.?[\\/]|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(m[1]);
|
|
1525
|
+
// A plain @file (including a file followed by ordinary prose) remains a normal prompt. A matching
|
|
1526
|
+
// session has priority at the beginning of a line, and an unknown name with a task is allowed to
|
|
1527
|
+
// fall through to sendToPeer(), which refreshes the remote list before reporting an error.
|
|
1528
|
+
if (!found.peer && !found.ambiguous && (file || pathLike)) return false;
|
|
1529
|
+
if (!found.peer && !found.ambiguous && !task) return false;
|
|
1530
|
+
if (!task) { this.notice('Type the task after the name: @name task (/peers lists the sessions).', 'warn'); return true; }
|
|
1531
|
+
this.echoUser(text);
|
|
1516
1532
|
if (found.ambiguous) { this.notice(found.error, 'warn'); return true; }
|
|
1517
1533
|
this.sendToPeer(found.peer || m[1], task).then(
|
|
1518
1534
|
({ peer }) => {
|
|
1519
1535
|
const where = peer.remote ? `on ${peer.machine}: ${peer.cwd}` : displayPath(peer.cwd, this.cwd);
|
|
1520
|
-
this.screen.log(c.dim(` ⎿ Sent to
|
|
1536
|
+
this.screen.log(c.dim(` ⎿ Sent to @${peer.label || peer.name} (${where}); its answer will be shown here`), '');
|
|
1521
1537
|
},
|
|
1522
1538
|
(e) => this.notice(e.message, 'warn'),
|
|
1523
1539
|
);
|
|
@@ -1528,11 +1544,11 @@ export class App {
|
|
|
1528
1544
|
const rows = [
|
|
1529
1545
|
['! for bash mode', 'double tap esc to clear input'],
|
|
1530
1546
|
['/ for commands', 'ctrl + o to toggle verbose output'],
|
|
1531
|
-
['@ for
|
|
1547
|
+
['@ for files and sessions', 'ctrl + f to find in the conversation'],
|
|
1532
1548
|
['PgUp/PgDn, wheel to scroll', 'ctrl + home/end to the top/bottom'],
|
|
1533
1549
|
['# to memorize', 'ctrl + t to toggle todos'],
|
|
1534
1550
|
['\\⏎ or alt+⏎ for newline', 'ctrl + l to redraw, ctrl + d to exit'],
|
|
1535
|
-
['
|
|
1551
|
+
['ctrl + c to copy selection', 'ctrl + v to paste text or an image'],
|
|
1536
1552
|
];
|
|
1537
1553
|
return rows.map(([a, b]) => c.dim(' ' + padEnd(a, 30) + b));
|
|
1538
1554
|
}
|
|
@@ -1659,8 +1675,13 @@ export class App {
|
|
|
1659
1675
|
const seen = new Set();
|
|
1660
1676
|
const read = this.runtime.tools.find((t) => t.name === 'Read');
|
|
1661
1677
|
const skipped = (file, why) => this.screen.log(c.dim(` ⎿ Skipped ${displayPath(file, this.cwd)}: ${why}`));
|
|
1678
|
+
const localPeers = this.peers?.peers() || [];
|
|
1662
1679
|
for (const m of text.matchAll(/(?:^|\s)@("[^"]+"|[^\s"]+)/g)) {
|
|
1663
|
-
const
|
|
1680
|
+
const token = m[1];
|
|
1681
|
+
const peerRef = token.startsWith('"') ? null : token.replace(/[,.;:!?)]+$/, '');
|
|
1682
|
+
const peer = peerRef ? resolvePeer(localPeers, this.remotePeers, peerRef, { ids: false }) : null;
|
|
1683
|
+
if (peer?.peer || peer?.ambiguous) continue; // a peer wins over a same-named file; use @./name for the file
|
|
1684
|
+
const file = this.mentionedFile(token);
|
|
1664
1685
|
if (!file || seen.has(file)) continue; // @someone, @..., a file that is not there: not a mention
|
|
1665
1686
|
seen.add(file);
|
|
1666
1687
|
let st;
|
|
@@ -1728,9 +1749,9 @@ export class App {
|
|
|
1728
1749
|
await this.runAgent(content, { peers });
|
|
1729
1750
|
}
|
|
1730
1751
|
|
|
1731
|
-
// What
|
|
1752
|
+
// What `@name` in a message the user wrote stands for, told to the model: which session, and how to reach it.
|
|
1732
1753
|
async peerMentions(prompt) {
|
|
1733
|
-
const refs = [...new Set([...String(prompt).matchAll(/(?:^|\s)
|
|
1754
|
+
const refs = [...new Set([...String(prompt).matchAll(/(?:^|\s)@([^\s@"&,。;;::!!??、))]+)/gu)].map((m) => m[1]))];
|
|
1734
1755
|
if (!refs.length) return [];
|
|
1735
1756
|
const local = this.peers?.peers() || [];
|
|
1736
1757
|
const notes = [];
|
|
@@ -1738,35 +1759,13 @@ export class App {
|
|
|
1738
1759
|
let found = resolvePeer(local, this.remotePeers, ref, { ids: false });
|
|
1739
1760
|
if (!found.peer && !found.ambiguous && this.remote) found = resolvePeer(local, await this.refreshRemotePeers(), ref, { ids: false });
|
|
1740
1761
|
const p = found.peer;
|
|
1741
|
-
if (p) notes.push(
|
|
1762
|
+
if (p) notes.push(`@${ref} is the claude-pro session "${p.label || p.name}" ${p.remote ? `on the user's computer "${p.machine}"` : 'on this computer'}, working in ${p.cwd}`);
|
|
1742
1763
|
else if (found.ambiguous) notes.push(found.error);
|
|
1743
1764
|
}
|
|
1744
1765
|
if (!notes.length) return [];
|
|
1745
1766
|
return [{ type: 'text', text: `<system-reminder>The user refers to other sessions: ${notes.join('; ')}. MessagePeer (to: the name in quotes) sends a session a task.</system-reminder>` }];
|
|
1746
1767
|
}
|
|
1747
1768
|
|
|
1748
|
-
// alt+v (ctrl+v where the terminal passes it through): attach an image from the clipboard.
|
|
1749
|
-
async pasteImage() {
|
|
1750
|
-
if (this.readingClipboard) return;
|
|
1751
|
-
this.readingClipboard = true;
|
|
1752
|
-
this.flash('Reading image from clipboard…');
|
|
1753
|
-
try {
|
|
1754
|
-
const r = await readClipboardImage();
|
|
1755
|
-
if (r.image) {
|
|
1756
|
-
const label = this.editor.insertImage(r.image);
|
|
1757
|
-
const size = r.image.width ? `${r.image.width}×${r.image.height}, ` : '';
|
|
1758
|
-
this.flash(`${label} attached (${size}${formatTokens(r.image.bytes).replace(/k$/, 'KB')})`);
|
|
1759
|
-
} else {
|
|
1760
|
-
this.flash(r.error || 'No image found in clipboard. Copy an image (e.g. Win+Shift+S) and press alt+v again.', 'warn');
|
|
1761
|
-
}
|
|
1762
|
-
} catch (e) {
|
|
1763
|
-
this.flash(`Could not read the clipboard: ${e.message}`, 'warn');
|
|
1764
|
-
} finally {
|
|
1765
|
-
this.readingClipboard = false;
|
|
1766
|
-
this.screen.schedule();
|
|
1767
|
-
}
|
|
1768
|
-
}
|
|
1769
|
-
|
|
1770
1769
|
// A short-lived message in the footer (not written to the transcript).
|
|
1771
1770
|
flash(text, kind = 'info') {
|
|
1772
1771
|
this.flashMessage = { text, kind, until: Date.now() + 4000 };
|
|
@@ -1861,10 +1860,10 @@ export class App {
|
|
|
1861
1860
|
this.active.push(entry);
|
|
1862
1861
|
let result;
|
|
1863
1862
|
try {
|
|
1864
|
-
ctx.onProgress = (p) => { entry.progress = p; };
|
|
1863
|
+
ctx.onProgress = (p, meta) => { entry.progress = p; entry.progressLines = meta?.lines; };
|
|
1865
1864
|
result = await tool.call({ command }, ctx);
|
|
1866
|
-
} catch {
|
|
1867
|
-
const partial = (entry.progress
|
|
1865
|
+
} catch (err) {
|
|
1866
|
+
const partial = stripAnsi(err?.partialOutput ?? entry.progress ?? '').replace(/\r\n/g, '\n').trimEnd(); // all of it, not just the end the progress shows
|
|
1868
1867
|
result = { isError: true, content: `${partial ? partial + '\n' : ''}Interrupted by user`, interrupted: true };
|
|
1869
1868
|
}
|
|
1870
1869
|
this.active = this.active.filter((e) => e !== entry);
|
|
@@ -1926,7 +1925,6 @@ export class App {
|
|
|
1926
1925
|
this.seedOutput = [];
|
|
1927
1926
|
this.store = new SessionStore(this.cwd, id);
|
|
1928
1927
|
this.runtime.trace?.setSessionId(id);
|
|
1929
|
-
this.peers?.update(); // the conversation, in the registry
|
|
1930
1928
|
this.topic = loaded.topic;
|
|
1931
1929
|
this.customTitle = loaded.name;
|
|
1932
1930
|
// a conversation that was given a name brings it back: the other sessions reach this one by it again
|
|
@@ -1945,12 +1943,22 @@ export class App {
|
|
|
1945
1943
|
// Continue behind the system prompt the conversation had (and its cache), not a freshly built one.
|
|
1946
1944
|
this.store.systemPrompt = loaded.systemPrompt;
|
|
1947
1945
|
this.runtime.resumeSystemPrompt(loaded.systemPrompt, loaded.promptCode);
|
|
1946
|
+
// Its cache still warm (a restart, a quick resume): it goes on being refreshed while idle (keepalive.js).
|
|
1947
|
+
this.agent.restoreCacheState(loaded.cacheState);
|
|
1948
1948
|
if (!this.topic) this.refreshTopic(this.latestPrompt()); // a session from before topics were kept
|
|
1949
1949
|
this.remote?.resync();
|
|
1950
1950
|
if (quiet) return;
|
|
1951
|
-
|
|
1951
|
+
const restoredCount = loaded.messages.length;
|
|
1952
|
+
const shown = loaded.messages.slice(-30);
|
|
1953
|
+
const hasSummary = loaded.messages.some((message) => {
|
|
1954
|
+
const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : (message.content || []);
|
|
1955
|
+
return message.role === 'user' && blocks.some((block) => block?.type === 'text' && String(block.text || '').startsWith('This session is being continued'));
|
|
1956
|
+
});
|
|
1957
|
+
const contextNote = hasSummary ? 'including the saved compaction summary' : 'including the saved conversation history';
|
|
1958
|
+
const omitted = restoredCount - shown.length;
|
|
1959
|
+
this.logLocal(c.dim(`Resumed session ${id}: restored ${restoredCount} messages to model context, ${contextNote}; showing the ${shown.length} most recent${omitted ? ` (${omitted} older messages not printed)` : ''}.`), '');
|
|
1952
1960
|
this.remoteMuted++;
|
|
1953
|
-
try { this.printTranscript(
|
|
1961
|
+
try { this.printTranscript(shown); } finally { this.remoteMuted--; }
|
|
1954
1962
|
}
|
|
1955
1963
|
|
|
1956
1964
|
printTranscript(messages) {
|
|
@@ -1975,7 +1983,6 @@ export class App {
|
|
|
1975
1983
|
newSession() {
|
|
1976
1984
|
this.store = new SessionStore(this.cwd);
|
|
1977
1985
|
this.runtime.trace?.setSessionId(this.store.id);
|
|
1978
|
-
this.peers?.update();
|
|
1979
1986
|
this.seedOutput = [];
|
|
1980
1987
|
this.topic = null;
|
|
1981
1988
|
this.customTitle = null;
|
|
@@ -2038,7 +2045,7 @@ export class App {
|
|
|
2038
2045
|
this.turnTokens += estimateTokens(ev.text);
|
|
2039
2046
|
if (this.md) {
|
|
2040
2047
|
const lines = this.md.write(ev.text);
|
|
2041
|
-
if (lines.length) this.logLocal(lines);
|
|
2048
|
+
if (lines.length) this.logLocal({ soon: true }, lines);
|
|
2042
2049
|
this.remote?.emit({ t: 'delta', kind: 'text', text: ev.text });
|
|
2043
2050
|
}
|
|
2044
2051
|
break;
|
|
@@ -2049,7 +2056,7 @@ export class App {
|
|
|
2049
2056
|
this.remote?.emit({ t: 'delta', kind: 'thinking', text: ev.text });
|
|
2050
2057
|
if (this.thinking.md) {
|
|
2051
2058
|
const lines = this.thinking.md.write(ev.text);
|
|
2052
|
-
if (lines.length) this.logLocal(lines);
|
|
2059
|
+
if (lines.length) this.logLocal({ soon: true }, lines);
|
|
2053
2060
|
}
|
|
2054
2061
|
}
|
|
2055
2062
|
break;
|
|
@@ -2142,8 +2149,9 @@ export class App {
|
|
|
2142
2149
|
this.remote?.emit({ t: 'tool', id: tu.id, head: toolHeader(tool, input, entry.ctx, { width: REMOTE_WIDTH, dot: false }) });
|
|
2143
2150
|
this.screen.schedule();
|
|
2144
2151
|
return {
|
|
2145
|
-
progress: (p) => {
|
|
2146
|
-
|
|
2152
|
+
progress: (p, meta) => {
|
|
2153
|
+
// `all`: the whole output so far (the progress is its end), for the page's "the whole output"
|
|
2154
|
+
if (typeof p === 'string') { entry.progress = p; entry.progressLines = meta?.lines; entry.progressAll = meta?.all; this.remote?.toolProgress(tu.id, entry); }
|
|
2147
2155
|
else if (p?.type === 'subtool') { entry.sub.push(p.header); entry.subCount++; this.remote?.emit({ t: 'sub', id: tu.id, head: p.header }); }
|
|
2148
2156
|
this.screen.schedule();
|
|
2149
2157
|
},
|
|
@@ -2236,7 +2244,7 @@ export class App {
|
|
|
2236
2244
|
systemPrompt(text, agent) { if (this.isMain(agent)) this.store.setSystemPrompt(text); }
|
|
2237
2245
|
messagesReplaced(msgs, agent) { if (this.isMain(agent)) this.store.reset(msgs); }
|
|
2238
2246
|
usage(_u, agent) {
|
|
2239
|
-
if (this.isMain(agent)) this.store.setCacheUntil(agent.cache.clockUntil); //
|
|
2247
|
+
if (this.isMain(agent)) this.store.setCacheUntil(agent.cache.clockUntil, agent.cacheState()); // for a resumed or restarted conversation
|
|
2240
2248
|
this.screen.schedule();
|
|
2241
2249
|
}
|
|
2242
2250
|
|
|
@@ -2259,7 +2267,7 @@ export class App {
|
|
|
2259
2267
|
this.status = null;
|
|
2260
2268
|
if (err) return;
|
|
2261
2269
|
this.lastSummary = summary;
|
|
2262
|
-
this.store.setCacheUntil(agent.cache.clockUntil);
|
|
2270
|
+
this.store.setCacheUntil(agent.cache.clockUntil, agent.cacheState());
|
|
2263
2271
|
const what = part === 'before' ? 'The earlier part of the conversation was summarized' : part === 'after' ? 'The conversation from that message on was summarized' : 'Conversation compacted';
|
|
2264
2272
|
this.screen.log(c.dim(`✻ ${what} (the summary is in context; /context to see usage)`), '');
|
|
2265
2273
|
}
|
|
@@ -2316,9 +2324,11 @@ export class App {
|
|
|
2316
2324
|
if (!sub.length) sub.push(c.dim('Initializing…'));
|
|
2317
2325
|
lines.push(...resultLines(sub));
|
|
2318
2326
|
} else if (e.progress) {
|
|
2327
|
+
// `progress` is the end of the output (see Bash); `progressLines` how many lines all of it has.
|
|
2319
2328
|
const out = e.progress.replace(/\r\n/g, '\n').trimEnd().split('\n');
|
|
2329
|
+
const total = Math.max(out.length, e.progressLines || 0);
|
|
2320
2330
|
const tail = out.slice(-5).map((l) => c.dim(truncate(l.replace(/\r/g, ''), w - 8)));
|
|
2321
|
-
if (
|
|
2331
|
+
if (total > 5) tail.unshift(c.dim(`… +${total - 5} lines`));
|
|
2322
2332
|
lines.push(...resultLines(tail));
|
|
2323
2333
|
} else {
|
|
2324
2334
|
const secs = Math.floor((Date.now() - e.started) / 1000);
|
|
@@ -2339,11 +2349,13 @@ export class App {
|
|
|
2339
2349
|
}
|
|
2340
2350
|
if (this.thinking?.md) lines.push(...this.thinking.md.partial().slice(-3));
|
|
2341
2351
|
else if (this.thinking && this.thinking.text) {
|
|
2342
|
-
const
|
|
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
|
|
2343
2354
|
lines.push(c.dim(c.italic(truncate(`✻ ${last}`, w))));
|
|
2344
2355
|
}
|
|
2345
2356
|
for (const [, p] of this.pendingToolBlocks) {
|
|
2346
|
-
|
|
2357
|
+
// The start of the input is enough for a one-line preview (a streaming Bash heredoc can be very long).
|
|
2358
|
+
const m = /"(?:file_path|command|pattern|url|description|query)"\s*:\s*"((?:\\.|[^"\\])*)/.exec(p.partial.slice(0, 4000));
|
|
2347
2359
|
const tool = this.runtime.tools.find((t) => t.name === p.name) || { name: p.name };
|
|
2348
2360
|
const arg = m ? m[1].replace(/\\n/g, ' ').replace(/\\(.)/g, '$1') : '';
|
|
2349
2361
|
lines.push(`${c.gray(DOT)} ${c.bold(toolLabel(tool, {}))}${arg ? `(${truncate(arg, w - 20)})` : ''} ${c.dim(p.partial.length > 200 ? `(${formatTokens(Math.round(p.partial.length / 4))} tokens…)` : '…')}`);
|
|
@@ -2367,7 +2379,7 @@ export class App {
|
|
|
2367
2379
|
return { lines, cursor };
|
|
2368
2380
|
}
|
|
2369
2381
|
if (this.queue.length) {
|
|
2370
|
-
for (const q of this.queue) lines.push(c.dim(' ⎿ queued: ') + c.gray(truncate((q.display ?? q.text).replace(/\s+/g, ' '), w - 14)));
|
|
2382
|
+
for (const q of this.queue) lines.push(c.dim(' ⎿ queued: ') + c.gray(truncate(String(q.display ?? q.text).slice(0, w * 4).replace(/\s+/g, ' '), w - 14)));
|
|
2371
2383
|
}
|
|
2372
2384
|
if (lines.length) lines.push('');
|
|
2373
2385
|
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"');
|
|
@@ -2388,7 +2400,7 @@ export class App {
|
|
|
2388
2400
|
const dir = this.agent?.cwd || this.cwd;
|
|
2389
2401
|
const home = os.homedir();
|
|
2390
2402
|
const shown = dir.toLowerCase().startsWith(home.toLowerCase()) ? '~' + dir.slice(home.length) : dir;
|
|
2391
|
-
const name = this.peers || this.remote ?
|
|
2403
|
+
const name = this.peers || this.remote ? `@${this.peerLabel()}` : '';
|
|
2392
2404
|
return { left: shown.replace(/\\/g, '/'), right: name && this.remote?.online ? `⇄ ${name}` : name };
|
|
2393
2405
|
}
|
|
2394
2406
|
|
|
@@ -2416,7 +2428,7 @@ export class App {
|
|
|
2416
2428
|
if (!flash) {
|
|
2417
2429
|
if (this.updating) left += c.dim(' · ') + c.blue(`⇣ updating ${APP_NAME} to ${this.updating}…`);
|
|
2418
2430
|
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'}`);
|
|
2419
|
-
else if (this.pendingUpdate) left += c.dim(' · ') + c.dim(`update ${this.pendingUpdate} ready · ${this.updateWaitingFor ? `installs when
|
|
2431
|
+
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'}`);
|
|
2420
2432
|
}
|
|
2421
2433
|
const cfg = this.config;
|
|
2422
2434
|
const threshold = cfg.autoCompactThreshold(cfg.model);
|
|
@@ -2455,10 +2467,7 @@ export class App {
|
|
|
2455
2467
|
}
|
|
2456
2468
|
|
|
2457
2469
|
export async function runRepl({ flags, cwd, initialPrompt }) {
|
|
2458
|
-
|
|
2459
|
-
const vterm = flags.headless ? new VirtualTerminal() : null;
|
|
2460
|
-
if (vterm) process.stdout.write(`${new Date().toISOString()} claude-pro ${VERSION} background session in ${cwd} (pid ${process.pid})\n`);
|
|
2461
|
-
const app = new App({ flags, cwd, vterm });
|
|
2470
|
+
const app = new App({ flags, cwd });
|
|
2462
2471
|
process.on('uncaughtException', (e) => {
|
|
2463
2472
|
app.restoreTerminal();
|
|
2464
2473
|
process.stderr.write(`\nUnexpected error: ${e?.stack || e}\n`);
|