@yanzc/claude-pro 0.11.0 → 0.12.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 +55 -36
- package/package.json +1 -1
- package/src/agent.js +4 -3
- package/src/browser/session.js +21 -1
- package/src/commands.js +103 -18
- package/src/config.js +1 -2
- package/src/live.js +148 -0
- package/src/main.js +5 -3
- package/src/peers.js +41 -4
- package/src/remote.js +73 -267
- package/src/runtime.js +36 -11
- package/src/selfcheck.js +3 -3
- package/src/session.js +116 -7
- package/src/supervisor.js +1 -1
- package/src/tools/bash.js +21 -12
- package/src/tools/browser.js +14 -8
- package/src/tools/code.js +18 -11
- package/src/tools/restart.js +1 -1
- package/src/ui/dialogs.js +23 -30
- package/src/ui/editor.js +65 -169
- package/src/ui/repl.js +399 -456
- package/src/ui/screen.js +47 -674
- package/src/updater.js +5 -4
- package/src/web/api.js +787 -0
- package/src/web/app.css +412 -0
- package/src/web/app.js +1850 -0
- package/src/web/data.js +424 -0
- package/src/web/host.js +334 -0
- package/src/web/login.html +66 -0
- package/src/web/page.html +41 -0
- package/src/web/remote-access.js +232 -0
- package/src/web/server.js +459 -0
package/src/ui/repl.js
CHANGED
|
@@ -3,16 +3,15 @@
|
|
|
3
3
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import os from 'node:os';
|
|
7
6
|
import readline from 'node:readline';
|
|
8
7
|
import { spawn } from 'node:child_process';
|
|
9
8
|
import { c, ESC, glyphs, stringWidth, stripAnsi, truncate, padEnd, wordWrap } from './ansi.js';
|
|
10
|
-
import { Screen,
|
|
11
|
-
import { Editor,
|
|
9
|
+
import { Screen, HeadlessScreen, queryCursorRow } from './screen.js';
|
|
10
|
+
import { Editor, shownQuotes } from './editor.js';
|
|
12
11
|
import { SelectDialog } from './dialogs.js';
|
|
13
12
|
import { MarkdownStream, renderMarkdown } from './markdown.js';
|
|
14
13
|
import {
|
|
15
|
-
DOT, toolHeader, renderToolResult,
|
|
14
|
+
DOT, toolHeader, renderToolResult, renderUserMessage, resultLines, formatTokens, formatDuration, toolLabel, bashModeLines,
|
|
16
15
|
} from './render.js';
|
|
17
16
|
import { createRuntime } from '../runtime.js';
|
|
18
17
|
import { SessionStore, firstUserText, moveSession } from '../session.js';
|
|
@@ -29,13 +28,14 @@ import { ripgrepPath } from '../utils/shell.js';
|
|
|
29
28
|
import { describePause, formatClock, humanDuration, resumeText, shouldAnnounce } from '../ratelimit.js';
|
|
30
29
|
import { shutdownBackgroundShells, listBackgroundShells } from '../tools/bash.js';
|
|
31
30
|
import { shutdownInterpreters } from '../tools/code.js';
|
|
32
|
-
import {
|
|
31
|
+
import { browserSessionFor, closeBrowserSession } from '../browser/session.js';
|
|
33
32
|
import { estimateTokens } from '../agent.js';
|
|
34
33
|
import { readClipboardImage, imageFromFile, writeClipboard, readClipboardText } from '../utils/clipboard.js';
|
|
35
34
|
import { fitImagesIn, imageSize } from '../utils/images.js';
|
|
36
35
|
import { checkForUpdate, installUpdate, installedVersion, installedByNpm, isNewer } from '../updater.js';
|
|
37
36
|
import { PeerNode, peersEnabled, findPeer, resolvePeer, machineName, cleanName, peerMessagePrompt } from '../peers.js';
|
|
38
|
-
import {
|
|
37
|
+
import { LiveFeed } from '../live.js';
|
|
38
|
+
import { RemoteControl, transcriptItems, onlineEnabled, REMOTE_WIDTH } from '../remote.js';
|
|
39
39
|
|
|
40
40
|
// A model id as people say it: claude-sonnet-5-5 -> sonnet-5-5, claude-haiku-4-5-20251001 -> haiku-4-5.
|
|
41
41
|
// (every model with its provider in front: 7bit/opus-5-5, deepseek/deepseek-v4-pro)
|
|
@@ -232,14 +232,17 @@ export class App {
|
|
|
232
232
|
// `noProcessExit`: the tests, which drive the App themselves; it never ends the process, and it has no peers, no
|
|
233
233
|
// gateway connection, no update checks and the default renderer. `selfCheck` (see selfcheck.js): it never ends the
|
|
234
234
|
// process either, but otherwise starts as a session does, so that code only a real start runs is checked too.
|
|
235
|
-
|
|
235
|
+
// `host`: a 后台会话, one of the sessions the web console runs in its own process (see web/host.js): no terminal
|
|
236
|
+
// (what it prints goes to the console's live view only), the process is the host's, and so are restarts.
|
|
237
|
+
constructor({ flags, cwd, stdin = process.stdin, stdout = process.stdout, noProcessExit = false, selfCheck = false, host = null }) {
|
|
236
238
|
this.flags = flags;
|
|
237
239
|
this.cwd = cwd;
|
|
238
240
|
this.stdin = stdin;
|
|
239
241
|
this.stdout = stdout;
|
|
240
|
-
this.
|
|
242
|
+
this.host = host;
|
|
243
|
+
this.noProcessExit = noProcessExit || selfCheck || Boolean(host);
|
|
241
244
|
this.driven = noProcessExit;
|
|
242
|
-
this.screen = new Screen(stdout);
|
|
245
|
+
this.screen = host ? new HeadlessScreen(stdout) : new Screen(stdout);
|
|
243
246
|
this.busy = false;
|
|
244
247
|
// Attachment expansion is asynchronous. Claim the turn before the first await so two
|
|
245
248
|
// rapid submits cannot start two Agent.run() calls against the same message array.
|
|
@@ -255,7 +258,6 @@ export class App {
|
|
|
255
258
|
this.md = null;
|
|
256
259
|
this.thinking = null;
|
|
257
260
|
this.verbose = !!flags.verbose;
|
|
258
|
-
this.showTodos = true;
|
|
259
261
|
this.turnStart = 0;
|
|
260
262
|
this.turnTokens = 0;
|
|
261
263
|
this.verb = 'Thinking';
|
|
@@ -278,7 +280,18 @@ export class App {
|
|
|
278
280
|
this.turnPeers = []; // tasks from other sessions that the running turn answers: [{msg}]
|
|
279
281
|
this.userSentToPeers = new Set(); // ids of messages the user sent to other sessions with @name
|
|
280
282
|
this.remote = null; // the browser page that watches and steers this session (see remote.js), when it is on
|
|
281
|
-
|
|
283
|
+
// the local web console's live view of this session (claude-pro web, see live.js and web/server.js)
|
|
284
|
+
this.liveFeed = new LiveFeed({
|
|
285
|
+
seed: () => [
|
|
286
|
+
...transcriptItems(this.agent?.messages || [], { tools: this.runtime?.tools || [], ctx: this.agent?.makeCtx(), cwd: this.cwd, images: true }),
|
|
287
|
+
...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
|
|
288
|
+
],
|
|
289
|
+
status: () => this.liveStatus(),
|
|
290
|
+
});
|
|
291
|
+
// run by the web console (a 后台会话): only the console shows it, and ends it. `legacyHidden`: one an older version
|
|
292
|
+
// of the console started in a hidden window, a process of its own: it moves into the console's (maybeMoveIntoConsole)
|
|
293
|
+
this.legacyHidden = !host && /^(1|true|yes)$/i.test(process.env.CLAUDE_PRO_BACKGROUND || '');
|
|
294
|
+
this.hidden = Boolean(host) || this.legacyHidden;
|
|
282
295
|
this.remoteMuted = 0; // > 0 while printing something the page is told about in its own terms
|
|
283
296
|
this.remoteDialogs = 0;
|
|
284
297
|
this.remoteStarting = null;
|
|
@@ -292,14 +305,23 @@ export class App {
|
|
|
292
305
|
this.remotePeersLoading = null;
|
|
293
306
|
this.remotePeersTimer = null;
|
|
294
307
|
this.cost = 0; // what this conversation's requests have cost so far (USD at list prices): the footer and /cost
|
|
295
|
-
this.fileIndex = new FileIndex(cwd, () => this.runtime?.config, () => {
|
|
308
|
+
this.fileIndex = new FileIndex(cwd, () => this.runtime?.config, () => {
|
|
309
|
+
const e = this.editor;
|
|
310
|
+
if (!e) return;
|
|
311
|
+
// a Tab pressed while the list was being made had nothing to complete: it does now
|
|
312
|
+
const miss = e.lastMiss;
|
|
313
|
+
if (miss && miss.text === e.text && miss.cursor === e.cursor && Date.now() - miss.at < 5000) e.complete();
|
|
314
|
+
else e.refreshSuggestions();
|
|
315
|
+
this.screen?.schedule();
|
|
316
|
+
});
|
|
317
|
+
this.storeError = (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');
|
|
296
318
|
this.store = new SessionStore(cwd);
|
|
297
|
-
|
|
319
|
+
this.store.onError = this.storeError;
|
|
298
320
|
// What the terminal prints goes to the remote page too, except what it is told about as events.
|
|
299
321
|
this.screen.onLog = (items) => {
|
|
300
322
|
const lines = () => items.flatMap((i) => (Array.isArray(i) ? i : [i])).flatMap((l) => String(l).split(/\r?\n/));
|
|
301
|
-
if (
|
|
302
|
-
this.
|
|
323
|
+
if (this.remoteMuted || !this.liveFeed?.active) return;
|
|
324
|
+
this.liveFeed.output(lines());
|
|
303
325
|
};
|
|
304
326
|
this.editor = new Editor({
|
|
305
327
|
history: loadHistory(cwd),
|
|
@@ -308,15 +330,20 @@ export class App {
|
|
|
308
330
|
imageFromPath: (p) => {
|
|
309
331
|
const r = imageFromFile(resolvePath(p, this.cwd));
|
|
310
332
|
if (r.error && !/not found|Not a file/.test(r.error)) this.flash(r.error, 'warn');
|
|
311
|
-
if (r.image) this.flashMessage = null;
|
|
312
333
|
return r.image || null;
|
|
313
334
|
},
|
|
314
|
-
getSuggestions: (text, cursor) => this.suggest(text, cursor),
|
|
335
|
+
getSuggestions: (text, cursor, opts) => this.suggest(text, cursor, opts),
|
|
315
336
|
onChange: () => this.screen.schedule(),
|
|
316
337
|
});
|
|
317
338
|
}
|
|
318
339
|
|
|
319
340
|
get agent() { return this.runtime.agent; }
|
|
341
|
+
// Whether this session can restart (to load new code, or for /cd): under the supervisor, or in the web console.
|
|
342
|
+
canRestart() { return Boolean(this.host) || canRestart(); }
|
|
343
|
+
get owner() { return this.runtime?.config?.owner; }
|
|
344
|
+
// Whether the conversation is being worked on, not only looked at: a session the web console took up because its
|
|
345
|
+
// conversation was opened is not, until it runs a turn (`used`, carried over by a restart).
|
|
346
|
+
inUse() { return !this.host || Boolean(this.used); }
|
|
320
347
|
get config() { return this.runtime.config; }
|
|
321
348
|
get width() { return this.screen.width; }
|
|
322
349
|
isTurnRunning() { return this.busy || this.turnStarting; }
|
|
@@ -324,20 +351,29 @@ export class App {
|
|
|
324
351
|
// ---------------------------------------------------------------- lifecycle
|
|
325
352
|
|
|
326
353
|
async start(initialPrompt) {
|
|
354
|
+
if (this.exiting) return this.exitCode;
|
|
327
355
|
const stdin = this.stdin;
|
|
328
356
|
stdin.setRawMode(true);
|
|
329
357
|
// Where the cursor is, before anything is drawn: the input box is kept on the last rows of the window from
|
|
330
358
|
// there (see screen.js).
|
|
331
359
|
if (stdin.isTTY && this.stdout.isTTY) this.screen.pinFrom(await queryCursorRow(stdin, this.stdout));
|
|
360
|
+
if (this.exiting) return this.exitCode;
|
|
332
361
|
stdin.setEncoding('utf8');
|
|
333
362
|
this.stdout.write(ESC.bracketedPasteOn);
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
363
|
+
if (!this.host) { // (the host's process is not this session's)
|
|
364
|
+
process.on('exit', () => this.restoreTerminal());
|
|
365
|
+
process.on('SIGTERM', () => this.exit(143));
|
|
366
|
+
process.on('SIGHUP', () => this.exit(129));
|
|
367
|
+
}
|
|
338
368
|
|
|
339
369
|
await this.startPeer();
|
|
340
|
-
|
|
370
|
+
if (this.exiting) return this.exitCode;
|
|
371
|
+
const runtime = await createRuntime({ cwd: this.cwd, flags: this.flags, io: this, sessionId: this.store.id });
|
|
372
|
+
if (this.exiting) {
|
|
373
|
+
this.closeRuntime(runtime); // exit could not clean up the runtime while it was still being built
|
|
374
|
+
return this.exitCode;
|
|
375
|
+
}
|
|
376
|
+
this.runtime = runtime;
|
|
341
377
|
// The conversation's id, sent to the gateway with each request (see streamMessage); it follows /clear and /resume.
|
|
342
378
|
Object.defineProperty(this.runtime.config, 'sessionId', { get: () => this.store.id, configurable: true });
|
|
343
379
|
// Every request's cost (the conversation's, its sub-agents', side queries'), kept with the session.
|
|
@@ -351,15 +387,11 @@ export class App {
|
|
|
351
387
|
// so that the footer shows it before the first request.
|
|
352
388
|
// not in the self-check a restart runs first: that would ask the gateway once more for every restart
|
|
353
389
|
if (!this.driven && !this.selfCheck) loadGatewayModels(this.runtime.config).then(() => this.screen.schedule());
|
|
354
|
-
// What the session showed before a restart:
|
|
390
|
+
// What the session showed before a restart: repainted after a resize.
|
|
355
391
|
if (Array.isArray(this.flags.restart?.screenHistory)) this.screen.history = this.flags.restart.screenHistory.filter((l) => typeof l === 'string');
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
const keys = mouseFilter(stdin, (m) => this.onMouse(m));
|
|
360
|
-
this.keys = keys;
|
|
361
|
-
readline.emitKeypressEvents(keys);
|
|
362
|
-
keys.on('keypress', (str, key) => {
|
|
392
|
+
// Keys typed while starting up stay buffered in stdin until we listen.
|
|
393
|
+
readline.emitKeypressEvents(stdin);
|
|
394
|
+
stdin.on('keypress', (str, key) => {
|
|
363
395
|
if (/^\x1b\[\d+;\d+R$/.test(key?.sequence || '')) return; // a late answer to the cursor position query, not a key
|
|
364
396
|
try { this.onKey(str, key || {}); } catch (e) { this.logError(e); }
|
|
365
397
|
});
|
|
@@ -375,14 +407,22 @@ export class App {
|
|
|
375
407
|
if (restart) this.resumeAfterRestart(restart, resumable);
|
|
376
408
|
else if (this.flags.resumeFile) this.loadSession(this.flags.resumeFile, this.flags.resumeId);
|
|
377
409
|
else if (this.flags.resume) await this.commands.get('resume').run('');
|
|
410
|
+
if (this.exiting) return this.exitCode;
|
|
378
411
|
if (!restart && this.flags.name?.trim()) this.renameSession(this.flags.name); // --name, as /rename does
|
|
379
412
|
this.autoStartRemote(restart);
|
|
413
|
+
// 远程访问 on: the console's server (and its tunnel) is brought up again by any session that starts
|
|
414
|
+
if (!this.driven && !this.selfCheck && !this.host) { // (in the console's process it is up already)
|
|
415
|
+
import('../web/remote-access.js')
|
|
416
|
+
.then((ra) => (ra.readRemote().enabled ? import('../web/server.js').then((w) => w.ensureWebServer()) : null))
|
|
417
|
+
.catch(() => { /* /web remote says what is wrong */ });
|
|
418
|
+
}
|
|
380
419
|
|
|
381
420
|
this.screen.setLive((w) => this.renderLive(w));
|
|
421
|
+
// the restart line took the place of the same one of the process before (see resumeAfterRestart): the screen is
|
|
422
|
+
// written again from the history, which no longer has the old one
|
|
423
|
+
if (this.collapsedRestart) { this.collapsedRestart = false; this.screen.repaint(); }
|
|
382
424
|
this.spinnerTimer = setInterval(() => {
|
|
383
|
-
|
|
384
|
-
if (this.isTurnRunning() || this.active.length || clock !== this.shownClock) this.screen.schedule();
|
|
385
|
-
this.shownClock = clock;
|
|
425
|
+
if (this.isTurnRunning() || this.active.length) this.screen.schedule();
|
|
386
426
|
}, 120);
|
|
387
427
|
if (restart) this.continueAfterRestart(restart);
|
|
388
428
|
else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
|
|
@@ -391,6 +431,11 @@ export class App {
|
|
|
391
431
|
Promise.resolve(this.commands.get('connect').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
|
|
392
432
|
}
|
|
393
433
|
this.startSourceWatch();
|
|
434
|
+
if (this.legacyHidden && !this.selfCheck) {
|
|
435
|
+
this.moveTimer = setInterval(() => this.maybeMoveIntoConsole(), 60_000);
|
|
436
|
+
this.moveTimer.unref?.();
|
|
437
|
+
setTimeout(() => this.maybeMoveIntoConsole(), 5000).unref?.();
|
|
438
|
+
}
|
|
394
439
|
if (!this.driven) {
|
|
395
440
|
// Updates are deliberately manual: /update checks npm and installs the selected release.
|
|
396
441
|
// Do not query the registry or install/restart a running session in the background.
|
|
@@ -398,7 +443,7 @@ export class App {
|
|
|
398
443
|
this.loginTimer = setInterval(() => this.syncRemote(), 10_000);
|
|
399
444
|
this.loginTimer.unref?.();
|
|
400
445
|
}
|
|
401
|
-
return new Promise((resolve) => { this.resolveExit = resolve; });
|
|
446
|
+
return this.exiting ? this.exitCode : new Promise((resolve) => { this.resolveExit = resolve; });
|
|
402
447
|
}
|
|
403
448
|
|
|
404
449
|
// What the session is about now: the current model named the topic last, or else the first thing asked
|
|
@@ -472,34 +517,54 @@ export class App {
|
|
|
472
517
|
} catch { /* ignore */ }
|
|
473
518
|
}
|
|
474
519
|
|
|
520
|
+
closeRuntime(runtime) {
|
|
521
|
+
// In the console process, no owner means there is nothing to clean up, not every session.
|
|
522
|
+
const owner = this.host ? runtime?.config?.owner : undefined;
|
|
523
|
+
if (!this.host || owner) {
|
|
524
|
+
shutdownBackgroundShells(owner);
|
|
525
|
+
shutdownInterpreters(owner);
|
|
526
|
+
}
|
|
527
|
+
if (this.host && owner) closeBrowserSession(owner);
|
|
528
|
+
runtime?.agent?.keepAlive?.stop();
|
|
529
|
+
runtime?.tasks?.killAll();
|
|
530
|
+
runtime?.mcp?.close();
|
|
531
|
+
runtime?.releaseSession?.();
|
|
532
|
+
}
|
|
533
|
+
|
|
475
534
|
exit(code = 0, { restart = false } = {}) {
|
|
476
535
|
if (this.exiting) return;
|
|
477
536
|
this.exiting = true;
|
|
478
|
-
this.
|
|
479
|
-
|
|
480
|
-
clearTimeout(this.reloadTimer);
|
|
481
|
-
this.sourceWatch?.close();
|
|
482
|
-
shutdownBackgroundShells();
|
|
483
|
-
shutdownInterpreters();
|
|
484
|
-
this.runtime?.tasks.killAll();
|
|
485
|
-
this.runtime?.mcp.close();
|
|
486
|
-
this.peers?.close();
|
|
487
|
-
clearInterval(this.remotePeersTimer);
|
|
488
|
-
clearInterval(this.loginTimer);
|
|
489
|
-
const remoteClosed = this.remote?.close({ restarting: restart });
|
|
490
|
-
const u = this.agent?.totalUsage();
|
|
537
|
+
this.exitCode = code;
|
|
538
|
+
let remoteClosed;
|
|
491
539
|
const farewell = []; // left on the terminal once the program's screen is gone (see Screen.close)
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
540
|
+
try {
|
|
541
|
+
this.controller?.abort();
|
|
542
|
+
clearInterval(this.spinnerTimer);
|
|
543
|
+
clearTimeout(this.reloadTimer);
|
|
544
|
+
this.sourceWatch?.close();
|
|
545
|
+
clearTimeout(this.updateRetry);
|
|
546
|
+
clearInterval(this.moveTimer);
|
|
547
|
+
this.closeRuntime(this.runtime);
|
|
548
|
+
this.peers?.close();
|
|
549
|
+
this.liveFeed?.close();
|
|
550
|
+
clearInterval(this.remotePeersTimer);
|
|
551
|
+
clearInterval(this.loginTimer);
|
|
552
|
+
remoteClosed = this.remote?.close({ restarting: restart });
|
|
553
|
+
const agent = this.runtime?.agent;
|
|
554
|
+
const u = agent?.totalUsage();
|
|
555
|
+
if (!restart && u?.requests) {
|
|
556
|
+
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`));
|
|
557
|
+
}
|
|
558
|
+
if (!restart && agent?.messages.length) farewell.push(c.dim(`Resume this session with: ${APP_NAME} --resume ${this.store.id}`));
|
|
559
|
+
} finally {
|
|
560
|
+
this.resolveExit?.(code);
|
|
561
|
+
this.restoreTerminal({ handOver: restart, farewell });
|
|
562
|
+
this.stdin.pause();
|
|
563
|
+
if (!this.noProcessExit) {
|
|
564
|
+
// with remote control on, the gateway is told first (at most a second and a half; see RemoteControl.close)
|
|
565
|
+
if (remoteClosed) remoteClosed.finally(() => process.exit(code));
|
|
566
|
+
else setTimeout(() => process.exit(code), 50).unref();
|
|
567
|
+
}
|
|
503
568
|
}
|
|
504
569
|
}
|
|
505
570
|
|
|
@@ -510,13 +575,34 @@ export class App {
|
|
|
510
575
|
async startPeer() {
|
|
511
576
|
if (this.driven || !peersEnabled()) return;
|
|
512
577
|
try {
|
|
513
|
-
|
|
578
|
+
const peer = new PeerNode({
|
|
514
579
|
cwd: this.cwd,
|
|
515
580
|
name: this.flags.restart?.peerName,
|
|
516
581
|
id: this.flags.restart?.peerId,
|
|
517
582
|
onMessage: (msg) => this.onPeerMessage(msg),
|
|
518
|
-
getStatus: () =>
|
|
519
|
-
|
|
583
|
+
getStatus: () => this.liveStatus(),
|
|
584
|
+
live: { feed: this.liveFeed, command: (type, body) => this.pageCommand(type, body), image: (n) => this.liveImage(n) },
|
|
585
|
+
});
|
|
586
|
+
if (this.legacyHidden) {
|
|
587
|
+
const handle = peer.handle.bind(peer);
|
|
588
|
+
peer.handle = (req, res) => {
|
|
589
|
+
if (req.method === 'POST' && req.url === '/message' && req.headers.authorization === `Bearer ${peer.token}`) {
|
|
590
|
+
// PeerNode acknowledges before calling onMessage. Refuse at the endpoint, and do not move while an
|
|
591
|
+
// already accepted request is still uploading its message.
|
|
592
|
+
if (this.moving || this.exiting) {
|
|
593
|
+
res.writeHead(503, { 'content-type': 'application/json' });
|
|
594
|
+
res.end(JSON.stringify({ error: 'Session is moving or ending; try again.' }));
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
this.peerMessages = (this.peerMessages || 0) + 1;
|
|
598
|
+
res.once('close', () => { this.peerMessages--; });
|
|
599
|
+
}
|
|
600
|
+
handle(req, res);
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
await peer.start();
|
|
604
|
+
if (this.exiting) peer.close();
|
|
605
|
+
else this.peers = peer;
|
|
520
606
|
} catch (e) {
|
|
521
607
|
this.peers = null;
|
|
522
608
|
this.notice(`Other sessions cannot reach this one: ${e.message}`, 'warn');
|
|
@@ -715,7 +801,28 @@ export class App {
|
|
|
715
801
|
// A message of the user in the transcript (typed here, on the remote page, or sent by another session).
|
|
716
802
|
echoUser(text, images = 0) {
|
|
717
803
|
this.logLocal(renderUserMessage(text, this.width));
|
|
718
|
-
|
|
804
|
+
// the web console shows the images themselves: they become the next ones of the conversation (see liveImage)
|
|
805
|
+
this.liveFeed.emit({ t: 'user', text: String(text) });
|
|
806
|
+
if (images && this.liveFeed.active) {
|
|
807
|
+
const before = this.conversationImages().length;
|
|
808
|
+
for (let i = 0; i < images; i++) this.liveFeed.emit({ t: 'image', n: before + i });
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// The images of the user's messages, in order (what transcriptItems numbers {k: 'image', n}).
|
|
813
|
+
conversationImages() {
|
|
814
|
+
const out = [];
|
|
815
|
+
for (const m of this.agent?.messages || []) {
|
|
816
|
+
if (m.role !== 'user' || !Array.isArray(m.content)) continue;
|
|
817
|
+
for (const b of m.content) if (b.type === 'image') out.push(b);
|
|
818
|
+
}
|
|
819
|
+
return out;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// The n-th image of the conversation, for the web console: {mediaType, data (Buffer)} or null.
|
|
823
|
+
liveImage(n) {
|
|
824
|
+
const b = this.conversationImages()[n];
|
|
825
|
+
return b?.source?.type === 'base64' ? { mediaType: b.source.media_type, data: Buffer.from(b.source.data, 'base64') } : null;
|
|
719
826
|
}
|
|
720
827
|
|
|
721
828
|
// Whether this session should be online at the gateway (see remote.js): whenever this computer is logged in to
|
|
@@ -731,8 +838,6 @@ export class App {
|
|
|
731
838
|
// Online at the gateway from the start when this computer is logged in, and after a restart with the same
|
|
732
839
|
// session id so that an already-open page keeps following it.
|
|
733
840
|
autoStartRemote(restart) {
|
|
734
|
-
// Remote control (the web page shows and steers the session) only after /rc or --rc, and through restarts.
|
|
735
|
-
this.remoteControl = Boolean(restart ? restart.remoteControl : this.flags.remoteControl);
|
|
736
841
|
const id = restart?.remote?.id || null;
|
|
737
842
|
if (!id && !this.onlineWanted()) return;
|
|
738
843
|
this.startRemote({ id }).catch((e) => {
|
|
@@ -771,33 +876,16 @@ export class App {
|
|
|
771
876
|
async connectRemote({ id }) {
|
|
772
877
|
const login = gatewayLogin(this.config.gatewayUrl);
|
|
773
878
|
if (!login) throw Object.assign(new Error(`this computer is not logged in to the gateway ${this.config.gatewayUrl} (/connect 7bit.fun connects it)`), { code: 'NO_GATEWAY_LOGIN' });
|
|
774
|
-
// What the page may do here, besides watching (see remote.js): nothing with CLAUDE_PRO_REMOTE_COMMANDS=0.
|
|
775
|
-
const commands = remoteCommandsEnabled(this.config.env) ? {
|
|
776
|
-
send: (body) => this.remoteSend(body.text, body.images),
|
|
777
|
-
interrupt: () => this.remoteInterrupt(),
|
|
778
|
-
answer: (body) => this.answerDialog(body),
|
|
779
|
-
options: () => this.remoteOptions(),
|
|
780
|
-
suggest: (body) => this.remoteSuggest(body),
|
|
781
|
-
list: (body) => this.remoteList(body),
|
|
782
|
-
output: (body) => this.remoteOutput(body),
|
|
783
|
-
} : {};
|
|
784
879
|
const remote = new RemoteControl({
|
|
785
880
|
gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
|
|
786
881
|
id,
|
|
787
|
-
rc: this.remoteControl,
|
|
788
882
|
handlers: {
|
|
789
883
|
info: () => ({
|
|
790
884
|
name: this.peerLabel(), machine: machineName(this.config.env), peerId: this.peers?.id || null, title: this.sessionLabel() || '',
|
|
791
885
|
cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'), model: modelInfo(this.config).model, version: VERSION,
|
|
792
|
-
kind: 'terminal',
|
|
793
886
|
}),
|
|
794
|
-
seed: () => [
|
|
795
|
-
...transcriptItems(this.agent.messages, { tools: this.runtime.tools, ctx: this.agent.makeCtx(), cwd: this.cwd }),
|
|
796
|
-
...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
|
|
797
|
-
],
|
|
798
887
|
status: () => this.remoteStatus(),
|
|
799
|
-
|
|
800
|
-
peerMessage: (msg) => this.onPeerMessage(msg),
|
|
888
|
+
peerMessage: (msg) => this.moving || this.exiting ? false : this.onPeerMessage(msg),
|
|
801
889
|
contactEvent: (ev) => this.onContactEvent(ev),
|
|
802
890
|
changed: () => {
|
|
803
891
|
this.screen.schedule();
|
|
@@ -827,21 +915,6 @@ export class App {
|
|
|
827
915
|
return remote;
|
|
828
916
|
}
|
|
829
917
|
|
|
830
|
-
// /rc: the web page (远程控制) shows this session's conversation and may steer it, or (off) only messages between
|
|
831
|
-
// sessions go through the gateway. Resolves with what to tell the user.
|
|
832
|
-
async setRemoteControl(on) {
|
|
833
|
-
this.remoteControl = Boolean(on);
|
|
834
|
-
this.screen.schedule();
|
|
835
|
-
if (!on) {
|
|
836
|
-
if (this.remote) await this.remote.setRc(false);
|
|
837
|
-
return 'Remote control is off: the web page no longer shows this session (messages between sessions still go through the gateway).';
|
|
838
|
-
}
|
|
839
|
-
const remote = this.remote || await this.syncRemote();
|
|
840
|
-
if (!remote) return `Remote control is on, but this session is not online at the gateway: ${stripAnsi(this.remoteState().text)}`;
|
|
841
|
-
await remote.setRc(true);
|
|
842
|
-
return 'Remote control is on: 远程控制 on the gateway\'s web page shows this session and can send it messages and commands. /rc off turns it off.';
|
|
843
|
-
}
|
|
844
|
-
|
|
845
918
|
stopRemote() {
|
|
846
919
|
this.remote?.close();
|
|
847
920
|
this.remote = null;
|
|
@@ -849,14 +922,12 @@ export class App {
|
|
|
849
922
|
this.screen.schedule();
|
|
850
923
|
}
|
|
851
924
|
|
|
852
|
-
// This session at the gateway
|
|
925
|
+
// This session at the gateway (its session relay: tasks across computers and from contacts), for /status: {text}.
|
|
853
926
|
remoteState() {
|
|
854
927
|
const r = this.remote;
|
|
855
928
|
if (r) {
|
|
856
929
|
const who = r.account ? ` as ${r.account}` : '';
|
|
857
|
-
const
|
|
858
|
-
const readOnly = !r.rc ? c.dim(' · remote control off (/rc turns it on)') : r.commands.length ? c.dim(' · remote control on') : c.dim(' · remote control on, read-only on the page (CLAUDE_PRO_REMOTE_COMMANDS=0)');
|
|
859
|
-
const text = r.online ? `${c.green('online')}${who}${pages}${readOnly}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
|
|
930
|
+
const text = r.online ? `${c.green('online')}${who}${c.dim(' · your other computers and your contacts can send it tasks')}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
|
|
860
931
|
return { text };
|
|
861
932
|
}
|
|
862
933
|
if (this.remoteStarting) return { text: 'connecting…' };
|
|
@@ -896,7 +967,7 @@ export class App {
|
|
|
896
967
|
cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'),
|
|
897
968
|
name: this.peerLabel(),
|
|
898
969
|
tasks: this.runtime.tasks.running().length,
|
|
899
|
-
restarting: Boolean(this.restartRequest),
|
|
970
|
+
restarting: Boolean(this.restartRequest || this.host?.restartWaits(this)),
|
|
900
971
|
asking: this.dialogs.length > 0, // a question waits for an answer (the page reminds the user of it)
|
|
901
972
|
conversationId: this.store.id,
|
|
902
973
|
cost: Number(this.cost.toFixed(6)),
|
|
@@ -926,7 +997,7 @@ export class App {
|
|
|
926
997
|
// What runs in the background: the agent's background agents and shells.
|
|
927
998
|
backgroundWork() {
|
|
928
999
|
const agents = this.runtime.tasks.list().map((t) => ({ id: t.id, kind: 'agent', description: t.description, status: t.status, startedAt: t.started }));
|
|
929
|
-
const shells = listBackgroundShells().map((s) => ({ id: s.id, kind: 'shell', description: s.description || s.command, status: s.status, startedAt: s.startedAt || null }));
|
|
1000
|
+
const shells = listBackgroundShells(this.owner).map((s) => ({ id: s.id, kind: 'shell', description: s.description || s.command, status: s.status, startedAt: s.startedAt || null }));
|
|
930
1001
|
return [...agents, ...shells];
|
|
931
1002
|
}
|
|
932
1003
|
|
|
@@ -1089,8 +1160,11 @@ export class App {
|
|
|
1089
1160
|
|
|
1090
1161
|
restartBlockers() {
|
|
1091
1162
|
const found = [];
|
|
1092
|
-
for (const t of this.runtime
|
|
1093
|
-
|
|
1163
|
+
for (const t of this.runtime?.tasks?.running() || []) found.push(`background agent ${t.id} "${t.description}"`);
|
|
1164
|
+
const owner = this.owner;
|
|
1165
|
+
if (owner || !this.host) {
|
|
1166
|
+
for (const s of listBackgroundShells(owner)) if (s.status === 'running') found.push(`background shell ${s.id} (${String(s.command).slice(0, 40)})`);
|
|
1167
|
+
}
|
|
1094
1168
|
return found;
|
|
1095
1169
|
}
|
|
1096
1170
|
|
|
@@ -1099,7 +1173,7 @@ export class App {
|
|
|
1099
1173
|
// the new process and goes on by itself. Returns {ok, message}.
|
|
1100
1174
|
// `cwd`: the session goes on in that directory (/cd).
|
|
1101
1175
|
requestRestart({ reason = '', then = '', continueTurn = false, force = false, cwd = null } = {}) {
|
|
1102
|
-
if (!canRestart()) return { ok: false, message: 'This session cannot restart itself.' };
|
|
1176
|
+
if (!this.canRestart()) return { ok: false, message: 'This session cannot restart itself.' };
|
|
1103
1177
|
const now = Date.now();
|
|
1104
1178
|
const recent = this.restarts.filter((t) => now - t < RESTART_WINDOW_MS);
|
|
1105
1179
|
if (recent.length >= MAX_RESTARTS && !cwd) {
|
|
@@ -1113,21 +1187,56 @@ export class App {
|
|
|
1113
1187
|
return { ok: true };
|
|
1114
1188
|
}
|
|
1115
1189
|
|
|
1116
|
-
// Leave the state of the session for the next process and go; the supervisor starts it again.
|
|
1190
|
+
// Leave the state of the session for the next process and go; the supervisor starts it again. In the web console
|
|
1191
|
+
// (`host`) a restart that loads new code restarts the console's process with all its sessions, once all of them
|
|
1192
|
+
// are idle (see web/host.js); a /cd needs no new code, and this session alone starts again, at once.
|
|
1117
1193
|
restartNow() {
|
|
1118
1194
|
const request = this.restartRequest || {};
|
|
1119
1195
|
this.restartRequest = null;
|
|
1120
|
-
|
|
1121
|
-
const now = Date.now();
|
|
1196
|
+
if (this.host && !request.cwd) { this.host.restartFor(this, request); return; }
|
|
1122
1197
|
// /cd: the conversation's file goes along to the new directory's project (see moveSession); the old one is
|
|
1123
1198
|
// removed once the next process is sure to find the new one
|
|
1124
1199
|
let moved = null;
|
|
1125
1200
|
if (request.cwd) {
|
|
1126
1201
|
try { moved = moveSession(this.store.file, this.store.id, request.cwd); } catch (e) { this.notice(`Could not change the directory: ${e.message}`, 'warn'); return; }
|
|
1127
1202
|
}
|
|
1203
|
+
const state = this.restartState(request, { moved });
|
|
1204
|
+
if (this.host) {
|
|
1205
|
+
moved?.commit();
|
|
1206
|
+
this.host.relaunch(this, state);
|
|
1207
|
+
return;
|
|
1208
|
+
}
|
|
1209
|
+
try {
|
|
1210
|
+
writeRestartState(state);
|
|
1211
|
+
} catch (e) {
|
|
1212
|
+
moved?.undo();
|
|
1213
|
+
this.notice(`Could not restart: ${e.message}`, 'warn');
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
moved?.commit();
|
|
1217
|
+
this.exit(RESTART_EXIT_CODE, { restart: true });
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
// Recover a missing conversation write before releasing the only in-memory copy.
|
|
1221
|
+
flushUnsavedConversation() {
|
|
1222
|
+
const store = this.store;
|
|
1223
|
+
if (!store?.lost) return true;
|
|
1224
|
+
const messages = this.runtime?.agent?.messages;
|
|
1225
|
+
if (!messages) return false;
|
|
1226
|
+
store.lost = false;
|
|
1227
|
+
store.reset(messages); // append sets lost again if this write fails too
|
|
1228
|
+
return !store.lost;
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
// What the next process (in the web console: the next App) needs to take the session up where it is now.
|
|
1232
|
+
// `counts`: towards the restarts that look like a loop; not a /cd (the user's), nor a restart of the web console that
|
|
1233
|
+
// another of its sessions or a change of the source caused.
|
|
1234
|
+
restartState(request = {}, { moved = null, counts = !request.cwd } = {}) {
|
|
1235
|
+
const cfg = this.config;
|
|
1236
|
+
const now = Date.now();
|
|
1128
1237
|
// a write of the conversation failed at some point: the file lacks part of it, and the next process goes on from it
|
|
1129
|
-
|
|
1130
|
-
|
|
1238
|
+
this.flushUnsavedConversation();
|
|
1239
|
+
return {
|
|
1131
1240
|
at: now,
|
|
1132
1241
|
reason: request.reason || '',
|
|
1133
1242
|
continueWith: request.continueTurn ? restartNote(request) : '',
|
|
@@ -1135,7 +1244,7 @@ export class App {
|
|
|
1135
1244
|
changedDirectory: Boolean(request.cwd),
|
|
1136
1245
|
// the browser instance in use (it may be any of several): the next process connects to it again, where the
|
|
1137
1246
|
// tab ids in the conversation are still its tabs'
|
|
1138
|
-
browser:
|
|
1247
|
+
browser: browserSessionFor(this.owner).preferred || null,
|
|
1139
1248
|
sessionId: this.store.id,
|
|
1140
1249
|
sessionFile: moved?.file || this.store.file,
|
|
1141
1250
|
modelOverride: cfg.modelOverride,
|
|
@@ -1149,23 +1258,39 @@ export class App {
|
|
|
1149
1258
|
// `peer`: a task of another session, which gets the answer of the turn that handles it
|
|
1150
1259
|
queue: this.queue.map((q) => ({ text: q.text, images: q.images || [], display: q.display ?? null, peer: q.peer || null })),
|
|
1151
1260
|
checkpoints: this.runtime.checkpoints.snapshot(),
|
|
1152
|
-
|
|
1153
|
-
restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), ...(request.cwd ? [] : [now])],
|
|
1261
|
+
restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), ...(counts ? [now] : [])],
|
|
1154
1262
|
// a name given with /rename or --name stays; the one taken from the directory follows it
|
|
1155
1263
|
peerName: request.cwd && !this.customTitle ? null : this.peers?.name || this.sessionName,
|
|
1156
1264
|
peerId: this.peers?.id,
|
|
1157
1265
|
remote: this.remote?.handoff() || null,
|
|
1158
|
-
|
|
1266
|
+
restartNote: this.restartNote || null, // the last restart line, merged with the next one when nothing came between
|
|
1267
|
+
used: this.inUse(),
|
|
1159
1268
|
};
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
// A session of an older version that the console started in a hidden window, a process (and a supervisor) of its
|
|
1272
|
+
// own: once it is idle the console takes it up in its own process (see web/host.js), with the same id and the state
|
|
1273
|
+
// a restart carries over, and this process ends (exit code 0: the supervisor does not start it again).
|
|
1274
|
+
async maybeMoveIntoConsole() {
|
|
1275
|
+
if (!this.legacyHidden || this.moving || this.exiting || !this.runtime || this.peerMessages || this.working() || this.restartRequest || this.reloading || this.updating) return;
|
|
1276
|
+
this.moving = true;
|
|
1160
1277
|
try {
|
|
1161
|
-
|
|
1278
|
+
const { adoptIntoConsole } = await import('../web/server.js');
|
|
1279
|
+
if (this.exiting || this.working() || this.restartRequest || this.reloading || this.updating) return;
|
|
1280
|
+
if (!this.flushUnsavedConversation()) return;
|
|
1281
|
+
const state = this.restartState({ reason: 'moved into the web console' }, { counts: false });
|
|
1282
|
+
const r = await adoptIntoConsole(state);
|
|
1283
|
+
if (!r?.ok) { this.moveRefused = r?.error || 'refused'; return; }
|
|
1284
|
+
// the console's session has this one's id now, and its peer file: closed here without removing it
|
|
1285
|
+
try { this.peers?.server?.close(); } catch { /* gone */ }
|
|
1286
|
+
this.peers = null;
|
|
1287
|
+
this.exit(0, { restart: true }); // (the gateway's remote page, if any, goes on with the console's session)
|
|
1162
1288
|
} catch (e) {
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1289
|
+
this.moveRefused = e.message; // tried again in a minute
|
|
1290
|
+
} finally {
|
|
1291
|
+
this.moving = false;
|
|
1292
|
+
if (!this.exiting && this.sourceChanged) this.maybeAutoReload().catch((e) => this.logError(e));
|
|
1166
1293
|
}
|
|
1167
|
-
moved?.commit();
|
|
1168
|
-
this.exit(RESTART_EXIT_CODE, { restart: true });
|
|
1169
1294
|
}
|
|
1170
1295
|
|
|
1171
1296
|
// /cd: the session goes on in `dir` (an existing directory). It restarts there, so that everything that belongs to
|
|
@@ -1174,7 +1299,7 @@ export class App {
|
|
|
1174
1299
|
// page's id and a name given with /rename stay. Returns {ok, message}.
|
|
1175
1300
|
changeDirectory(dir) {
|
|
1176
1301
|
if (this.isTurnRunning()) return { ok: false, message: 'Wait for the current task to finish (or press Esc) before changing the directory.' };
|
|
1177
|
-
if (!canRestart()) return { ok: false, message: 'This session cannot change its directory: that restarts it, and it was not started by the claude-pro launcher. Start claude-pro in that directory instead.' };
|
|
1302
|
+
if (!this.canRestart()) return { ok: false, message: 'This session cannot change its directory: that restarts it, and it was not started by the claude-pro launcher. Start claude-pro in that directory instead.' };
|
|
1178
1303
|
return this.requestRestart({ reason: `working directory ${dir}`, cwd: dir });
|
|
1179
1304
|
}
|
|
1180
1305
|
|
|
@@ -1189,16 +1314,14 @@ export class App {
|
|
|
1189
1314
|
// The Effort tool's level holds for the request the restart continues, not for the user's next one.
|
|
1190
1315
|
if (state.effortBoost) { cfg.effortBoost = state.effortBoost; cfg.effortBoostKeepNext = Boolean(state.continueWith); }
|
|
1191
1316
|
this.restarts = (Array.isArray(state.restarts) ? state.restarts : []).filter((t) => Number.isFinite(t));
|
|
1317
|
+
this.used = state.used !== false; // (a state from before it was kept: a session in use)
|
|
1192
1318
|
if (resumable) {
|
|
1193
1319
|
this.loadSession(state.sessionFile, state.sessionId, { quiet: true });
|
|
1194
1320
|
if (Array.isArray(state.todos)) this.agent.todos = state.todos;
|
|
1195
1321
|
if (state.checkpoints) this.runtime.checkpoints.adopt(state.checkpoints);
|
|
1196
1322
|
}
|
|
1197
|
-
if (state.browser && typeof state.browser === 'object' && typeof state.browser.dir === 'string')
|
|
1323
|
+
if (state.browser && typeof state.browser === 'object' && typeof state.browser.dir === 'string') browserSessionFor(this.owner).preferred = state.browser;
|
|
1198
1324
|
if (typeof state.draft === 'string' && state.draft) this.editor.restoreDraft(state.draft, state.draftCursor, state.draftParts);
|
|
1199
|
-
// Fullscreen starts on an empty screen: without what the process before showed (an older version, or one
|
|
1200
|
-
// that ran classic), the conversation is drawn again from the session.
|
|
1201
|
-
if (this.screen.full && resumable && !Array.isArray(state.screenHistory)) this.printTranscript(this.agent.messages.slice(-80));
|
|
1202
1325
|
if (state.changedDirectory) {
|
|
1203
1326
|
// /cd: the line it answers with, here and on the remote page (which starts again from the conversation)
|
|
1204
1327
|
const line = `Working directory: ${this.cwd}`;
|
|
@@ -1206,7 +1329,25 @@ export class App {
|
|
|
1206
1329
|
this.seedOutput = [line];
|
|
1207
1330
|
return;
|
|
1208
1331
|
}
|
|
1209
|
-
|
|
1332
|
+
const text = `${glyphs.restart} Restarted${state.reason ? `: ${state.reason}` : ''}${state.continueWith ? ' · continuing' : ''}`;
|
|
1333
|
+
// The same restart line as last time with nothing shown since (idle while the source keeps changing): one line
|
|
1334
|
+
// with a count instead of a screenful of them.
|
|
1335
|
+
let count = 1;
|
|
1336
|
+
const prev = state.restartNote;
|
|
1337
|
+
const hist = this.screen.history;
|
|
1338
|
+
if (prev && prev.text === text && !state.continueWith) {
|
|
1339
|
+
let i = hist.length;
|
|
1340
|
+
while (i > 0 && hist[i - 1] === '') i--;
|
|
1341
|
+
if (i > 0 && hist[i - 1] === prev.line) {
|
|
1342
|
+
hist.splice(i - 1);
|
|
1343
|
+
count = (prev.count || 1) + 1;
|
|
1344
|
+
this.collapsedRestart = true;
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
const line = c.dim(count > 1 ? `${text} (×${count})` : text);
|
|
1348
|
+
if (this.collapsedRestart) this.screen.queueLog([line, '']); // drawn by the repaint in start()
|
|
1349
|
+
else this.screen.log(line, '');
|
|
1350
|
+
this.restartNote = { text, count, line };
|
|
1210
1351
|
}
|
|
1211
1352
|
|
|
1212
1353
|
// The turn that goes on after a restart: the note for the model, and what the user had queued meanwhile.
|
|
@@ -1231,7 +1372,7 @@ export class App {
|
|
|
1231
1372
|
// once, every edit of one session made each of the other open sessions check and restart, into a half-made
|
|
1232
1373
|
// change: 8 of them, a dozen times in a day's work.)
|
|
1233
1374
|
startSourceWatch() {
|
|
1234
|
-
if (!canRestart()) return;
|
|
1375
|
+
if (!canRestart() || this.host) return; // (the web console follows the source for all its sessions: web/host.js)
|
|
1235
1376
|
this.sourceWatch = watchSource(INSTALL_DIR, (file) => {
|
|
1236
1377
|
this.sourceChanged = file || true;
|
|
1237
1378
|
if (this.isTurnRunning()) this.sourceChangedInTurn = true;
|
|
@@ -1249,7 +1390,8 @@ export class App {
|
|
|
1249
1390
|
}
|
|
1250
1391
|
|
|
1251
1392
|
async maybeAutoReload() {
|
|
1252
|
-
if (
|
|
1393
|
+
if (this.host) { this.host.check(); return; } // all the console's sessions restart together, once all are idle
|
|
1394
|
+
if (!this.sourceChanged || this.updating || this.reloading || this.isTurnRunning() || this.exiting || this.moving || this.restartRequest || this.dialogs.length || this.queue.length) return;
|
|
1253
1395
|
if (this.skipAutoReload) { this.skipAutoReload = false; return; } // the user just interrupted: not now
|
|
1254
1396
|
if (this.restartBlockers().length) return; // looked at again whenever the program is next idle
|
|
1255
1397
|
clearTimeout(this.reloadTimer);
|
|
@@ -1300,7 +1442,7 @@ export class App {
|
|
|
1300
1442
|
} else if (r.status === 'installed') {
|
|
1301
1443
|
this.notice(`${APP_NAME} ${r.version} is installed already; this session restarts to load it ${this.working() ? 'once its work is done' : 'now'}.`);
|
|
1302
1444
|
this.updateRestart = r.version;
|
|
1303
|
-
if (canRestart()) { this.sourceChanged ||= true; if (!this.isTurnRunning()) this.maybeAutoReload(); }
|
|
1445
|
+
if (this.canRestart()) { this.sourceChanged ||= true; if (!this.isTurnRunning()) this.maybeAutoReload(); }
|
|
1304
1446
|
} else if (r.status === 'failed') {
|
|
1305
1447
|
this.notice(`Could not update ${APP_NAME}${r.version ? ` to ${r.version}` : ''}: ${r.error}`, 'warn');
|
|
1306
1448
|
} else {
|
|
@@ -1348,7 +1490,7 @@ export class App {
|
|
|
1348
1490
|
if (r.status === 'updated' || r.status === 'installed') {
|
|
1349
1491
|
this.pendingUpdate = null;
|
|
1350
1492
|
this.updateRestart = r.version;
|
|
1351
|
-
if (canRestart()) {
|
|
1493
|
+
if (this.canRestart()) {
|
|
1352
1494
|
this.notice(`${APP_NAME} was updated to ${r.version} (from ${VERSION}); restarting to load it. The conversation carries over.`);
|
|
1353
1495
|
this.sourceChanged = true;
|
|
1354
1496
|
this.maybeAutoReload();
|
|
@@ -1362,20 +1504,12 @@ export class App {
|
|
|
1362
1504
|
|
|
1363
1505
|
printWelcome() {
|
|
1364
1506
|
const cfg = this.config;
|
|
1365
|
-
const w = Math.min(this.width - 1, 76);
|
|
1366
|
-
const inner = w - 4;
|
|
1367
|
-
const row = (s) => c.claude('│') + ' ' + padEnd(truncate(s, inner), inner) + ' ' + c.claude('│');
|
|
1368
1507
|
const model = cfg.model;
|
|
1369
1508
|
const lines = [
|
|
1370
|
-
c.claude(
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
row(''),
|
|
1375
|
-
row(c.dim(` cwd: ${this.cwd}`)),
|
|
1376
|
-
row(c.dim(` model: ${model.label}${cfg.effort ? ` · effort ${cfg.effort}` : ''} · ${formatTokens(model.contextWindow)} context`)),
|
|
1377
|
-
row(c.dim(` backend: ${cfg.endpointLabel}`)),
|
|
1378
|
-
c.claude(glyphs.bottomLeft + '─'.repeat(w - 2) + glyphs.bottomRight),
|
|
1509
|
+
`${c.claude('✻')} Welcome to ${c.bold(APP_NAME)}! ${c.dim(`v${VERSION} · /help · ? for shortcuts · ${APP_NAME} web: the web console`)}`,
|
|
1510
|
+
c.dim(` cwd: ${this.cwd}`),
|
|
1511
|
+
c.dim(` model: ${model.label}${cfg.effort ? ` · effort ${cfg.effort}` : ''} · ${formatTokens(model.contextWindow)} context`),
|
|
1512
|
+
c.dim(` backend: ${cfg.endpointLabel}`),
|
|
1379
1513
|
];
|
|
1380
1514
|
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).'));
|
|
1381
1515
|
// (the model in use cannot be reached: said, with what connects it)
|
|
@@ -1387,56 +1521,12 @@ export class App {
|
|
|
1387
1521
|
const ok = mcp.filter((m) => m.status === 'connected').length;
|
|
1388
1522
|
lines.push(c.dim(` MCP: ${ok}/${mcp.length} servers connected${ok < mcp.length ? ' · /mcp for details' : ''}`));
|
|
1389
1523
|
}
|
|
1390
|
-
lines.push(''
|
|
1524
|
+
lines.push('');
|
|
1391
1525
|
this.logLocal(lines);
|
|
1392
1526
|
}
|
|
1393
1527
|
|
|
1394
1528
|
// ---------------------------------------------------------------- input
|
|
1395
1529
|
|
|
1396
|
-
// Always fullscreen on a terminal (there is no other mode to choose). Output that is no terminal (isTTY false: a
|
|
1397
|
-
// test's fake terminal that asks for it) is written as it comes, with the input box after it.
|
|
1398
|
-
fullscreenWanted() {
|
|
1399
|
-
return this.stdout.isTTY !== false;
|
|
1400
|
-
}
|
|
1401
|
-
|
|
1402
|
-
// Fullscreen: the wheel scrolls the conversation (3 rows a notch); a drag,
|
|
1403
|
-
// a double or a triple click selects text. Selection is copied only with Ctrl+C.
|
|
1404
|
-
// In the input box a click moves the cursor and a drag selects its text (see Editor.mouse).
|
|
1405
|
-
onMouse(m) {
|
|
1406
|
-
if (!this.screen.full || this.exiting) return;
|
|
1407
|
-
if (m.button & 64) {
|
|
1408
|
-
if (m.button & 128) return;
|
|
1409
|
-
const speed = 3;
|
|
1410
|
-
this.screen.scrollBy(m.button & 1 ? -speed : speed);
|
|
1411
|
-
return;
|
|
1412
|
-
}
|
|
1413
|
-
// Right-click is intentionally inert. Clipboard operations use Ctrl+C and Ctrl+V only.
|
|
1414
|
-
const had = this.screen.selection;
|
|
1415
|
-
const hadInput = this.editor.selection;
|
|
1416
|
-
const r = this.screen.mouse(m);
|
|
1417
|
-
if (r?.input) this.editor.mouse(r.input);
|
|
1418
|
-
else if ((m.button & 3) === 0 && !(m.button & 32) && !m.release) this.editor.clearSelection(); // a press elsewhere
|
|
1419
|
-
if ((this.screen.selection && this.screen.selection !== had) || (this.editor.selection && this.editor.selection !== hadInput)) {
|
|
1420
|
-
this.flashMessage = null; // the footer says what a selection takes
|
|
1421
|
-
this.screen.schedule();
|
|
1422
|
-
}
|
|
1423
|
-
}
|
|
1424
|
-
|
|
1425
|
-
// Quote what is selected in the conversation in the message being written, as ChatGPT's "Ask ChatGPT" does:
|
|
1426
|
-
// ctrl+q (alt+q where the terminal keeps ctrl+q), as the footer says while there is a selection. The box shows
|
|
1427
|
-
// "[Quote #1 +12 lines]"; the model gets the text and the line of the conversation it is under (see
|
|
1428
|
-
// Editor.insertQuote), so that it knows which part, and which file or command, the question is about.
|
|
1429
|
-
quoteSelection() {
|
|
1430
|
-
if (!this.screen.full) { this.flash('Quoting needs the fullscreen view: select text with the mouse, then ctrl+q', 'warn'); return; }
|
|
1431
|
-
const quote = this.screen.selectionQuote();
|
|
1432
|
-
if (!quote?.text.trim()) { this.flash('Select part of the conversation first (drag over it, or double/triple-click), then ctrl+q', 'warn'); return; }
|
|
1433
|
-
if (this.dialogs.length) { this.flash('Answer the open question first, then quote', 'warn'); return; }
|
|
1434
|
-
if (this.finder) this.closeFind();
|
|
1435
|
-
this.screen.clearSelection();
|
|
1436
|
-
const label = this.editor.insertQuote(quote.text, quote.source);
|
|
1437
|
-
this.flash(`${label}${quote.source ? ` from ${quote.source}` : ''}: type your question below it`);
|
|
1438
|
-
}
|
|
1439
|
-
|
|
1440
1530
|
copyText(text) {
|
|
1441
1531
|
writeClipboard(text).then((ok) => {
|
|
1442
1532
|
if (ok) this.flash(`Copied ${text.length.toLocaleString()} characters to the clipboard`);
|
|
@@ -1447,30 +1537,14 @@ export class App {
|
|
|
1447
1537
|
clipboardEditor() {
|
|
1448
1538
|
const dialog = this.dialogs[0];
|
|
1449
1539
|
if (dialog) return dialog.editor || dialog.other || null;
|
|
1450
|
-
return this.
|
|
1451
|
-
}
|
|
1452
|
-
|
|
1453
|
-
insertFindText(text) {
|
|
1454
|
-
const f = this.finder;
|
|
1455
|
-
const clean = String(text ?? '').replace(/[\r\n\t]+/g, ' ');
|
|
1456
|
-
if (!f || !clean) return;
|
|
1457
|
-
if (f.selected) {
|
|
1458
|
-
f.text = clean;
|
|
1459
|
-
f.cursor = clean.length;
|
|
1460
|
-
f.selected = false;
|
|
1461
|
-
} else {
|
|
1462
|
-
f.text = f.text.slice(0, f.cursor) + clean + f.text.slice(f.cursor);
|
|
1463
|
-
f.cursor += clean.length;
|
|
1464
|
-
}
|
|
1465
|
-
this.screen.setFind(f.text);
|
|
1540
|
+
return this.editor;
|
|
1466
1541
|
}
|
|
1467
1542
|
|
|
1468
|
-
// Pasted text into the input box
|
|
1543
|
+
// Pasted text into the input box or the open dialog's text field.
|
|
1469
1544
|
insertPastedText(text, target = this.clipboardEditor()) {
|
|
1470
1545
|
const clean = String(text || '').replace(/\x1b\[20[01]~/g, '');
|
|
1471
1546
|
if (!clean) return;
|
|
1472
1547
|
if (target) target.insertPaste(clean);
|
|
1473
|
-
else if (this.finder) this.insertFindText(clean);
|
|
1474
1548
|
this.screen.schedule();
|
|
1475
1549
|
}
|
|
1476
1550
|
|
|
@@ -1478,9 +1552,8 @@ export class App {
|
|
|
1478
1552
|
// is only done when the terminal had nothing to paste (alt+v, ctrl+v as a key, an empty bracketed paste).
|
|
1479
1553
|
pasteClipboard(target = this.clipboardEditor()) {
|
|
1480
1554
|
if (this.readingClipboard || this.exiting) return;
|
|
1481
|
-
if (!target
|
|
1555
|
+
if (!target) return; // selection dialogs have no text field to paste into
|
|
1482
1556
|
this.readingClipboard = true;
|
|
1483
|
-
this.flash('Reading clipboard…');
|
|
1484
1557
|
const allowImage = Boolean(target?.insertImage);
|
|
1485
1558
|
const image = allowImage
|
|
1486
1559
|
? readClipboardImage().catch((e) => ({ image: null, error: e.message }))
|
|
@@ -1506,7 +1579,7 @@ export class App {
|
|
|
1506
1579
|
}
|
|
1507
1580
|
|
|
1508
1581
|
onKey(str, key) {
|
|
1509
|
-
if (this.exiting) return;
|
|
1582
|
+
if (this.exiting || this.moving) return;
|
|
1510
1583
|
// Terminals paste (ctrl+v in Windows Terminal and VS Code) as bracketed paste: readline reports paste-start/end
|
|
1511
1584
|
// and emits the text as ordinary keys between them. That text goes in at once. A paste with no text is what a
|
|
1512
1585
|
// terminal sends for an image on the clipboard, which only the system clipboard has (alt+v reads it on demand).
|
|
@@ -1524,57 +1597,22 @@ export class App {
|
|
|
1524
1597
|
}
|
|
1525
1598
|
return;
|
|
1526
1599
|
}
|
|
1527
|
-
if (this.screen.full) {
|
|
1528
|
-
const half = Math.max(1, Math.floor((this.screen.lastArea || this.screen.height) / 2));
|
|
1529
|
-
if (key.name === 'pageup') { this.screen.scrollBy(half); return; }
|
|
1530
|
-
if (key.name === 'pagedown') { this.screen.scrollBy(-half); return; }
|
|
1531
|
-
if (key.ctrl && key.name === 'home') { this.screen.scrollBy('top'); return; }
|
|
1532
|
-
if (key.ctrl && key.name === 'end') { this.screen.scrollBy('bottom'); return; }
|
|
1533
|
-
// ctrl+f looks for what is selected, if anything
|
|
1534
|
-
if (key.ctrl && key.name === 'f' && !this.dialogs.length) {
|
|
1535
|
-
const seed = this.screen.selection ? this.screen.selectedText() : '';
|
|
1536
|
-
this.screen.clearSelection();
|
|
1537
|
-
this.openFind(seed);
|
|
1538
|
-
return;
|
|
1539
|
-
}
|
|
1540
|
-
// A selection: ctrl+c copies it (and does not interrupt), esc only clears it, any other key clears it and
|
|
1541
|
-
// then does what it does.
|
|
1542
|
-
if (this.screen.selection) {
|
|
1543
|
-
if (key.ctrl && key.name === 'c') { this.copyText(this.screen.selectedText()); this.screen.clearSelection(); return; }
|
|
1544
|
-
if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; }
|
|
1545
|
-
this.screen.clearSelection();
|
|
1546
|
-
if (key.name === 'escape') return;
|
|
1547
|
-
}
|
|
1548
|
-
}
|
|
1549
|
-
// A selection in the input box (see Editor.mouse), the same way: ctrl+c copies it (and neither interrupts nor
|
|
1550
|
-
// clears the message), esc only clears it, any other key clears it and then does what it does.
|
|
1551
|
-
if (this.editor.selection) {
|
|
1552
|
-
const shown = !this.dialogs.length && !this.finder; // else the box is not on screen, and the key is not for it
|
|
1553
|
-
if (shown && key.ctrl && key.name === 'c') { this.copyText(this.editor.selectedText()); this.editor.clearSelection(); return; }
|
|
1554
|
-
this.editor.clearSelection();
|
|
1555
|
-
if (shown && key.name === 'escape') return;
|
|
1556
|
-
}
|
|
1557
1600
|
if (key.name === 'paste-start' || key.sequence === '\x1b[200~') {
|
|
1558
1601
|
this.bracketedPaste = { raw: '' };
|
|
1559
1602
|
return;
|
|
1560
1603
|
}
|
|
1561
|
-
if (key.ctrl && key.name === 'c' && this.finder && !this.dialogs.length) { this.closeFind(); return; } // not the hidden input's text
|
|
1562
1604
|
if (key.ctrl && key.name === 'c') { this.onCtrlC(); return; }
|
|
1563
1605
|
if ((key.ctrl || key.meta) && key.name === 'v') { this.pasteClipboard(); return; } // alt+v: the clipboard's image
|
|
1564
|
-
if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; } // nothing selected: says how
|
|
1565
1606
|
const dialog = this.dialogs[0];
|
|
1566
1607
|
if (dialog) {
|
|
1567
1608
|
dialog.handleKey(str, key);
|
|
1568
1609
|
this.screen.schedule();
|
|
1569
1610
|
return;
|
|
1570
1611
|
}
|
|
1571
|
-
if (key.ctrl && key.name === '
|
|
1572
|
-
if (this.finder) { this.findKey(str, key); this.screen.schedule(); return; }
|
|
1573
|
-
if (key.ctrl && key.name === 't') { this.showTodos = !this.showTodos; this.screen.schedule(); return; }
|
|
1574
|
-
if (key.ctrl && key.name === 'l') { if (this.screen.full) this.screen.repaint(); else this.screen.clearScreen(); return; }
|
|
1612
|
+
if (key.ctrl && key.name === 'l') { this.screen.clearScreen(); return; }
|
|
1575
1613
|
if (key.ctrl && key.name === 'd' && !this.editor.text) { this.keyboardExit(); return; }
|
|
1576
1614
|
// esc closes an open completion list first (the editor does that), and only then stops the turn
|
|
1577
|
-
if (key.name === 'escape' && this.isTurnRunning() && !this.editor.
|
|
1615
|
+
if (key.name === 'escape' && this.isTurnRunning() && !this.editor.completing) { this.interrupt(); return; }
|
|
1578
1616
|
this.exitArmed = 0;
|
|
1579
1617
|
this.editor.handleKey(str, key);
|
|
1580
1618
|
this.screen.schedule();
|
|
@@ -1687,7 +1725,6 @@ export class App {
|
|
|
1687
1725
|
onSubmit(value, raw, images = [], display = undefined, parts = null) {
|
|
1688
1726
|
const text = value.trim();
|
|
1689
1727
|
if (!text) { this.screen.schedule(); return; }
|
|
1690
|
-
if (this.screen.scrolledUp) this.screen.scrollBy('bottom'); // what was sent, and what comes of it, is in view
|
|
1691
1728
|
appendHistory(this.cwd, raw, parts);
|
|
1692
1729
|
if (this.sendTypedToPeer(text)) return;
|
|
1693
1730
|
if (this.isTurnRunning() && !this.modelSwitchAtPause(text)) {
|
|
@@ -1710,7 +1747,7 @@ export class App {
|
|
|
1710
1747
|
return;
|
|
1711
1748
|
}
|
|
1712
1749
|
if (!/^\/[\w:-]+$/.test(text.split(/\s/)[0])) { this.startTurn(value, { display }); return; } // e.g. a path like /usr/bin
|
|
1713
|
-
this.notice(`Unknown command: /${name}. Type /
|
|
1750
|
+
this.notice(`Unknown command: /${name}. Type / and press Tab for the list of commands, or /help.`, 'warn');
|
|
1714
1751
|
return;
|
|
1715
1752
|
}
|
|
1716
1753
|
this.startTurn(value, { display });
|
|
@@ -1756,102 +1793,15 @@ export class App {
|
|
|
1756
1793
|
shortcutsHelp() {
|
|
1757
1794
|
const rows = [
|
|
1758
1795
|
['! for bash mode', 'double tap esc to clear input'],
|
|
1759
|
-
['/ for commands', '
|
|
1760
|
-
['@ for files and sessions', '
|
|
1761
|
-
['
|
|
1762
|
-
['
|
|
1763
|
-
['
|
|
1764
|
-
['ctrl + c to copy selection', 'ctrl + q to quote it in your message'],
|
|
1765
|
-
['ctrl + v to paste text or an image', ''],
|
|
1796
|
+
['/ for commands', 'tab to complete / and @'],
|
|
1797
|
+
['@ for files and sessions', '/verbose for detailed tool output'],
|
|
1798
|
+
['# to memorize', 'esc to interrupt'],
|
|
1799
|
+
['\\⏎ or alt+⏎ for newline', 'ctrl + l to clear, ctrl + d to exit'],
|
|
1800
|
+
['ctrl + v to paste text or an image', 'claude-pro web: the web console'],
|
|
1766
1801
|
];
|
|
1767
1802
|
return rows.map(([a, b]) => c.dim(' ' + padEnd(a, 30) + b));
|
|
1768
1803
|
}
|
|
1769
1804
|
|
|
1770
|
-
// ---------------------------------------------------------------- finding in the conversation (ctrl+f)
|
|
1771
|
-
//
|
|
1772
|
-
// As in VS Code: a box takes the input box's place, the conversation shows the matches as they are typed, the
|
|
1773
|
-
// current one apart, and goes to it. In a conversation the newest matter most: the first one shown is the
|
|
1774
|
-
// nearest above the bottom of the view, enter (or ↑) goes on to older ones, shift+enter (or ↓) back to newer
|
|
1775
|
-
// ones, round from either end. Esc closes the box and leaves the view where it is. The text typed last comes
|
|
1776
|
-
// back selected (typing replaces it), or what is selected with the mouse. Fullscreen only: in the classic
|
|
1777
|
-
// renderer the conversation is in the terminal's own scrollback.
|
|
1778
|
-
|
|
1779
|
-
openFind(seed = '') {
|
|
1780
|
-
if (!this.screen.full) { this.flash('ctrl+f needs the fullscreen view; here use the terminal\'s own find', 'warn'); return; }
|
|
1781
|
-
if (this.finder && !seed.trim()) { this.finder.selected = Boolean(this.finder.text); this.screen.schedule(); return; } // open: select what is typed
|
|
1782
|
-
const text = (seed.split('\n').find((l) => l.trim()) || '').trim() || this.lastFind || '';
|
|
1783
|
-
if (!this.finder) this.screen.openFind();
|
|
1784
|
-
this.finder = { text, cursor: text.length, selected: Boolean(text) };
|
|
1785
|
-
this.screen.setFind(text);
|
|
1786
|
-
this.screen.schedule();
|
|
1787
|
-
}
|
|
1788
|
-
|
|
1789
|
-
closeFind() {
|
|
1790
|
-
if (!this.finder) return;
|
|
1791
|
-
this.lastFind = this.finder.text;
|
|
1792
|
-
this.finder = null;
|
|
1793
|
-
this.screen.closeFind();
|
|
1794
|
-
this.screen.schedule();
|
|
1795
|
-
}
|
|
1796
|
-
|
|
1797
|
-
findKey(str, key) {
|
|
1798
|
-
const f = this.finder;
|
|
1799
|
-
const name = key.name;
|
|
1800
|
-
const edit = (text, cursor) => {
|
|
1801
|
-
Object.assign(f, { text, cursor, selected: false });
|
|
1802
|
-
this.screen.setFind(text);
|
|
1803
|
-
};
|
|
1804
|
-
const insert = (s) => {
|
|
1805
|
-
const t = s.replace(/[\r\n\t]+/g, ' ');
|
|
1806
|
-
if (!t) return;
|
|
1807
|
-
if (f.selected) edit(t, t.length);
|
|
1808
|
-
else edit(f.text.slice(0, f.cursor) + t + f.text.slice(f.cursor), f.cursor + t.length);
|
|
1809
|
-
};
|
|
1810
|
-
// a bracketed paste never gets here: App.onKey takes it whole (see insertFindText)
|
|
1811
|
-
if (name === 'escape') { this.closeFind(); return; }
|
|
1812
|
-
const back = (name === 'return' && (key.meta || key.shift)) || name === 'enter' || key.sequence === '\x1b[13;2u' || (name === 'f3' && key.shift);
|
|
1813
|
-
if (back || name === 'down' || (key.ctrl && name === 'n')) { f.selected = false; this.screen.findStep(-1); return; }
|
|
1814
|
-
if (name === 'return' || name === 'f3' || name === 'up' || (key.ctrl && name === 'p')) { f.selected = false; this.screen.findStep(1); return; }
|
|
1815
|
-
const chars = [...f.text.slice(0, f.cursor)];
|
|
1816
|
-
if (name === 'backspace') {
|
|
1817
|
-
if (f.selected) edit('', 0);
|
|
1818
|
-
else if (chars.length) { const keep = chars.slice(0, -1).join(''); edit(keep + f.text.slice(f.cursor), keep.length); }
|
|
1819
|
-
return;
|
|
1820
|
-
}
|
|
1821
|
-
if (name === 'delete') {
|
|
1822
|
-
if (f.selected) edit('', 0);
|
|
1823
|
-
else if (f.cursor < f.text.length) { const next = [...f.text.slice(f.cursor)].slice(1).join(''); edit(f.text.slice(0, f.cursor) + next, f.cursor); }
|
|
1824
|
-
return;
|
|
1825
|
-
}
|
|
1826
|
-
if (key.ctrl && name === 'u') { edit('', 0); return; }
|
|
1827
|
-
if (name === 'left') { f.selected = false; f.cursor = chars.slice(0, -1).join('').length; return; }
|
|
1828
|
-
if (name === 'right') { f.selected = false; f.cursor = Math.min(f.text.length, f.cursor + ([...f.text.slice(f.cursor)][0]?.length || 0)); return; }
|
|
1829
|
-
if (name === 'home' || (key.ctrl && name === 'a')) { f.selected = false; f.cursor = 0; return; }
|
|
1830
|
-
if (name === 'end' || (key.ctrl && name === 'e')) { f.selected = false; f.cursor = f.text.length; return; }
|
|
1831
|
-
if (str && !key.ctrl && !key.meta && !/[\x00-\x1f\x7f]/.test(str)) insert(str);
|
|
1832
|
-
}
|
|
1833
|
-
|
|
1834
|
-
// The find box, in the input box's place: what is typed (selected: in reverse video), and how many matches.
|
|
1835
|
-
renderFind(width) {
|
|
1836
|
-
const f = this.finder;
|
|
1837
|
-
const boxW = Math.max(20, width - 1);
|
|
1838
|
-
const textW = boxW - 6;
|
|
1839
|
-
const s = this.screen.findStatus();
|
|
1840
|
-
const count = !f.text ? '' : s?.total ? `${s.index + 1}/${s.total}` : c.red('No results');
|
|
1841
|
-
const title = { left: 'Find in the conversation', right: count };
|
|
1842
|
-
// the part of the text that fits, the cursor in it
|
|
1843
|
-
let before = f.text.slice(0, f.cursor);
|
|
1844
|
-
while (before && stringWidth(before) > textW - 1) before = [...before].slice(1).join('');
|
|
1845
|
-
const shown = truncate(before + f.text.slice(f.cursor), textW, '');
|
|
1846
|
-
const content = f.selected && shown ? c.inverse(shown) : shown;
|
|
1847
|
-
const lines = [
|
|
1848
|
-
topBorder(boxW, c.yellow, title),
|
|
1849
|
-
c.yellow('│') + ' ' + c.yellow(glyphs.find) + ' ' + padEnd(content, textW) + ' ' + c.yellow('│'),
|
|
1850
|
-
c.yellow(glyphs.bottomLeft + '─'.repeat(boxW - 2) + glyphs.bottomRight),
|
|
1851
|
-
];
|
|
1852
|
-
return { lines, cursor: { row: 1, col: 4 + stringWidth(before) } };
|
|
1853
|
-
}
|
|
1854
|
-
|
|
1855
1805
|
// ---------------------------------------------------------------- turns
|
|
1856
1806
|
|
|
1857
1807
|
// Where a mentioned path is (null when there is no such file): relative to the project root, which is
|
|
@@ -1976,15 +1926,31 @@ export class App {
|
|
|
1976
1926
|
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>` }];
|
|
1977
1927
|
}
|
|
1978
1928
|
|
|
1979
|
-
//
|
|
1929
|
+
// The status line under each answer: "✻ Done at 14:05 · worked 1m 3s · $0.12 (total $3.40) · ctx 45k/1M · opus-5-5 max".
|
|
1930
|
+
doneLine() {
|
|
1931
|
+
const at = new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false });
|
|
1932
|
+
const parts = [`✻ Done at ${at}`, `worked ${formatDuration(Date.now() - this.turnStart)}`];
|
|
1933
|
+
const spent = this.cost - (this.turnCostStart || 0);
|
|
1934
|
+
if (spent > 0) parts.push(this.cost > spent + 0.005 ? `${formatUsd(spent)} (total ${formatUsd(this.cost)})` : formatUsd(spent));
|
|
1935
|
+
try {
|
|
1936
|
+
const cfg = this.config;
|
|
1937
|
+
const k = (n) => formatTokens(n).replace(/\.0([kM])$/, '$1');
|
|
1938
|
+
parts.push(`ctx ${k(this.agent.contextEstimate)}/${k(cfg.model.contextWindow)}`);
|
|
1939
|
+
const { model, effort } = modelInfo(cfg);
|
|
1940
|
+
const level = effort || defaultEffort(cfg.model.id, cfg);
|
|
1941
|
+
parts.push(level ? `${model} ${level}` : model);
|
|
1942
|
+
} catch { /* no model information: the time and the cost are enough */ }
|
|
1943
|
+
return c.dim(parts.join(' · '));
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
// A short message about something the user just did (a paste, a copy, a completion with nothing to offer): a
|
|
1947
|
+
// line of its own, as there is no footer to show it in.
|
|
1980
1948
|
flash(text, kind = 'info') {
|
|
1981
|
-
this.
|
|
1982
|
-
this.screen.schedule();
|
|
1983
|
-
clearTimeout(this.flashTimer);
|
|
1984
|
-
this.flashTimer = setTimeout(() => this.screen.schedule(), 4100);
|
|
1949
|
+
this.notice(text, kind);
|
|
1985
1950
|
}
|
|
1986
1951
|
|
|
1987
1952
|
async runAgent(content, { peers = [] } = {}) {
|
|
1953
|
+
this.used = true; // (see inUse)
|
|
1988
1954
|
this.turnStarting = false;
|
|
1989
1955
|
this.busy = true;
|
|
1990
1956
|
this.turnPeers.push(...peers);
|
|
@@ -1993,6 +1959,7 @@ export class App {
|
|
|
1993
1959
|
this.controller = new AbortController();
|
|
1994
1960
|
this.turnStart = Date.now();
|
|
1995
1961
|
this.turnTokens = 0;
|
|
1962
|
+
this.turnCostStart = this.cost;
|
|
1996
1963
|
this.verb = VERBS[Math.floor(Math.random() * VERBS.length)];
|
|
1997
1964
|
this.screen.schedule();
|
|
1998
1965
|
try {
|
|
@@ -2014,11 +1981,9 @@ export class App {
|
|
|
2014
1981
|
} finally {
|
|
2015
1982
|
this.flushStreaming();
|
|
2016
1983
|
this.flushActive(true);
|
|
2017
|
-
// When the answer came and how long the turn took, under the answer (the user asked for the time, 2026-11-21)
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
this.screen.log(c.dim(`✻ Done at ${at} · worked ${formatDuration(Date.now() - this.turnStart)}`), '');
|
|
2021
|
-
}
|
|
1984
|
+
// When the answer came and how long the turn took, under the answer (the user asked for the time, 2026-11-21),
|
|
1985
|
+
// with what there is no footer for: the cost, the context in use, the model.
|
|
1986
|
+
if (result && !result.interrupted && !error) this.screen.log(this.doneLine(), '');
|
|
2022
1987
|
this.answerPeers(result, error);
|
|
2023
1988
|
this.busy = false;
|
|
2024
1989
|
this.controller = null;
|
|
@@ -2135,10 +2100,11 @@ export class App {
|
|
|
2135
2100
|
|
|
2136
2101
|
// `quiet`: do not print the transcript (a restart: it is still on screen).
|
|
2137
2102
|
loadSession(file, id, { quiet = false } = {}) {
|
|
2138
|
-
const loaded = SessionStore.load(file);
|
|
2103
|
+
const loaded = this.runtime.useSession(id, () => SessionStore.load(file));
|
|
2139
2104
|
this.previousSession = null; // the conversation before a /clear: resuming another one ends the offer
|
|
2140
2105
|
this.seedOutput = [];
|
|
2141
2106
|
this.store = new SessionStore(this.cwd, id);
|
|
2107
|
+
this.store.onError = this.storeError;
|
|
2142
2108
|
this.runtime.trace?.setSessionId(id);
|
|
2143
2109
|
this.topic = loaded.topic;
|
|
2144
2110
|
this.customTitle = loaded.name;
|
|
@@ -2159,9 +2125,11 @@ export class App {
|
|
|
2159
2125
|
this.store.systemPrompt = loaded.systemPrompt;
|
|
2160
2126
|
this.runtime.resumeSystemPrompt(loaded.systemPrompt, loaded.promptCode);
|
|
2161
2127
|
// Its cache still warm (a restart, a quick resume): it goes on being refreshed while idle (keepalive.js).
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
this.
|
|
2128
|
+
// (in the web console a conversation is taken up as soon as it is opened: one only looked at costs nothing, no
|
|
2129
|
+
// cache refreshes and no title request, until it is used)
|
|
2130
|
+
this.agent.restoreCacheState(loaded.cacheState, { keepWarm: this.inUse() });
|
|
2131
|
+
if (!this.topic && this.inUse()) this.refreshTopic(this.latestPrompt()); // a session from before topics were kept
|
|
2132
|
+
this.liveFeed.resync();
|
|
2165
2133
|
if (quiet) return;
|
|
2166
2134
|
const restoredCount = loaded.messages.length;
|
|
2167
2135
|
const shown = loaded.messages.slice(-30);
|
|
@@ -2197,14 +2165,17 @@ export class App {
|
|
|
2197
2165
|
}
|
|
2198
2166
|
|
|
2199
2167
|
newSession() {
|
|
2200
|
-
|
|
2168
|
+
const store = new SessionStore(this.cwd);
|
|
2169
|
+
this.runtime.useSession(store.id);
|
|
2170
|
+
this.store = store;
|
|
2171
|
+
this.store.onError = this.storeError;
|
|
2201
2172
|
this.runtime.trace?.setSessionId(this.store.id);
|
|
2202
2173
|
this.seedOutput = [];
|
|
2203
2174
|
this.topic = null;
|
|
2204
2175
|
this.customTitle = null;
|
|
2205
2176
|
this.firstPrompt = null;
|
|
2206
2177
|
this.cost = 0;
|
|
2207
|
-
this.
|
|
2178
|
+
this.liveFeed.resync();
|
|
2208
2179
|
}
|
|
2209
2180
|
|
|
2210
2181
|
// ---------------------------------------------------------------- dialogs
|
|
@@ -2248,9 +2219,9 @@ export class App {
|
|
|
2248
2219
|
if (ev.block.type === 'text') {
|
|
2249
2220
|
this.flushThinking();
|
|
2250
2221
|
this.md = new MarkdownStream({ width: w, firstPrefix: `${DOT} `, indent: ' ' });
|
|
2251
|
-
this.
|
|
2222
|
+
this.emitEvent({ t: 'start', kind: 'text' });
|
|
2252
2223
|
} else if (ev.block.type === 'thinking') {
|
|
2253
|
-
this.
|
|
2224
|
+
this.emitEvent({ t: 'start', kind: 'thinking' });
|
|
2254
2225
|
this.thinking = new MarkdownStream({ width: w, firstPrefix: c.dim('✻ '), indent: ' ', style: (s) => c.dim(c.italic(s)) });
|
|
2255
2226
|
} else if (ev.block.type === 'tool_use') {
|
|
2256
2227
|
this.flushThinking();
|
|
@@ -2262,13 +2233,13 @@ export class App {
|
|
|
2262
2233
|
if (this.md) {
|
|
2263
2234
|
const lines = this.md.write(ev.text);
|
|
2264
2235
|
if (lines.length) this.logLocal({ soon: true }, lines);
|
|
2265
|
-
this.
|
|
2236
|
+
this.emitEvent({ t: 'delta', kind: 'text', text: ev.text });
|
|
2266
2237
|
}
|
|
2267
2238
|
break;
|
|
2268
2239
|
case 'thinking':
|
|
2269
2240
|
this.turnTokens += estimateTokens(ev.text);
|
|
2270
2241
|
if (this.thinking) {
|
|
2271
|
-
this.
|
|
2242
|
+
this.emitEvent({ t: 'delta', kind: 'thinking', text: ev.text });
|
|
2272
2243
|
const lines = this.thinking.write(ev.text);
|
|
2273
2244
|
if (lines.length) this.logLocal({ soon: true }, lines);
|
|
2274
2245
|
}
|
|
@@ -2285,7 +2256,7 @@ export class App {
|
|
|
2285
2256
|
if (lines.length) this.logLocal(lines);
|
|
2286
2257
|
this.logLocal('');
|
|
2287
2258
|
this.md = null;
|
|
2288
|
-
this.
|
|
2259
|
+
this.emitEvent({ t: 'stop' });
|
|
2289
2260
|
} else if (ev.block.type === 'thinking') {
|
|
2290
2261
|
this.flushThinking();
|
|
2291
2262
|
} else if (ev.block.type === 'tool_use') {
|
|
@@ -2300,7 +2271,7 @@ export class App {
|
|
|
2300
2271
|
this.rateLimitEvent(ev);
|
|
2301
2272
|
break;
|
|
2302
2273
|
case 'reset':
|
|
2303
|
-
if (this.md || this.thinking) this.
|
|
2274
|
+
if (this.md || this.thinking) this.emitEvent({ t: 'stop' });
|
|
2304
2275
|
this.md = null;
|
|
2305
2276
|
this.thinking = null;
|
|
2306
2277
|
this.pendingToolBlocks.clear();
|
|
@@ -2329,7 +2300,7 @@ export class App {
|
|
|
2329
2300
|
const t = this.thinking;
|
|
2330
2301
|
if (!t) return;
|
|
2331
2302
|
this.thinking = null;
|
|
2332
|
-
this.
|
|
2303
|
+
this.emitEvent({ t: 'stop' });
|
|
2333
2304
|
const lines = t.end();
|
|
2334
2305
|
if (lines.length) this.logLocal(lines);
|
|
2335
2306
|
if (t.emittedAny) this.logLocal('');
|
|
@@ -2341,7 +2312,7 @@ export class App {
|
|
|
2341
2312
|
const lines = this.md.end();
|
|
2342
2313
|
if (lines.length) this.logLocal(lines, '');
|
|
2343
2314
|
this.md = null;
|
|
2344
|
-
this.
|
|
2315
|
+
this.emitEvent({ t: 'stop' });
|
|
2345
2316
|
}
|
|
2346
2317
|
this.pendingToolBlocks.clear();
|
|
2347
2318
|
}
|
|
@@ -2354,13 +2325,13 @@ export class App {
|
|
|
2354
2325
|
if (!this.isMain(agent)) return {};
|
|
2355
2326
|
const entry = { tu, tool, input, status: 'running', progress: '', sub: [], subCount: 0, ctx: agent.makeCtx(), started: Date.now() };
|
|
2356
2327
|
this.active.push(entry);
|
|
2357
|
-
this.
|
|
2328
|
+
this.emitEvent({ t: 'tool', id: tu.id, head: toolHeader(tool, input, entry.ctx, { width: REMOTE_WIDTH, dot: false }) });
|
|
2358
2329
|
this.screen.schedule();
|
|
2359
2330
|
return {
|
|
2360
2331
|
progress: (p, meta) => {
|
|
2361
2332
|
// `all`: the whole output so far (the progress is its end), for the page's "the whole output"
|
|
2362
|
-
if (typeof p === 'string') { entry.progress = p; entry.progressLines = meta?.lines; entry.progressAll = meta?.all; this.
|
|
2363
|
-
else if (p?.type === 'subtool') { entry.sub.push(p.header); entry.subCount++; this.
|
|
2333
|
+
if (typeof p === 'string') { entry.progress = p; entry.progressLines = meta?.lines; entry.progressAll = meta?.all; this.liveFeed.toolProgress(tu.id, entry); }
|
|
2334
|
+
else if (p?.type === 'subtool') { entry.sub.push(p.header); entry.subCount++; this.emitEvent({ t: 'sub', id: tu.id, head: p.header }); }
|
|
2364
2335
|
this.screen.schedule();
|
|
2365
2336
|
},
|
|
2366
2337
|
done: (result) => {
|
|
@@ -2376,20 +2347,60 @@ export class App {
|
|
|
2376
2347
|
if (!this.isMain(agent)) return;
|
|
2377
2348
|
const ctx = agent.makeCtx();
|
|
2378
2349
|
const entry = { tu, tool, input: tu.input, status: 'rejected', rejected: true, rejectMessage: message, ctx };
|
|
2379
|
-
if (this.
|
|
2380
|
-
this.
|
|
2350
|
+
if (this.liveFeed.active) {
|
|
2351
|
+
this.emitEvent({ t: 'tool', id: tu.id, head: toolHeader(tool, tu.input, ctx, { width: REMOTE_WIDTH, dot: false }) });
|
|
2381
2352
|
this.remoteToolDone(entry);
|
|
2382
2353
|
}
|
|
2383
2354
|
this.logLocal(toolHeader(tool, tu.input, ctx, { status: 'rejected', width: this.width }), renderToolResult(entry, { width: this.width, cwd: this.cwd }), '');
|
|
2384
2355
|
}
|
|
2385
2356
|
|
|
2357
|
+
// An event of the transcript, for the gateway's page and the local web console's live view (each takes its own copy).
|
|
2358
|
+
emitEvent(ev) {
|
|
2359
|
+
this.liveFeed.emit({ ...ev });
|
|
2360
|
+
}
|
|
2361
|
+
|
|
2362
|
+
// What the local web console shows of this session: its list and the status under the live view.
|
|
2363
|
+
liveStatus() {
|
|
2364
|
+
let status = {};
|
|
2365
|
+
try { status = this.remoteStatus(); } catch { /* the basics below */ }
|
|
2366
|
+
return { ...status, busy: this.working(), turn: this.isTurnRunning(), sessionId: this.store?.id, pid: process.pid, hidden: this.hidden };
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
// A command of the local web console's live view: the same ones the gateway's page sends (see remote.js).
|
|
2370
|
+
pageCommand(type, body = {}) {
|
|
2371
|
+
const handlers = {
|
|
2372
|
+
send: (b) => this.remoteSend(b.text, b.images),
|
|
2373
|
+
interrupt: () => this.remoteInterrupt(),
|
|
2374
|
+
dialog: (b) => this.answerDialog(b),
|
|
2375
|
+
options: () => this.remoteOptions(),
|
|
2376
|
+
suggest: (b) => this.remoteSuggest(b),
|
|
2377
|
+
list: (b) => this.remoteList(b),
|
|
2378
|
+
output: (b) => this.remoteOutput(b),
|
|
2379
|
+
end: (b) => this.pageEnd(b),
|
|
2380
|
+
};
|
|
2381
|
+
if (!Object.hasOwn(handlers, type)) throw new Error(`Unknown command: ${type}`);
|
|
2382
|
+
if (['send', 'interrupt', 'dialog', 'end'].includes(type)) {
|
|
2383
|
+
if (this.exiting) throw new Error('The session is ending.');
|
|
2384
|
+
if (this.moving) throw new Error('The session is moving into the web console; try again.');
|
|
2385
|
+
}
|
|
2386
|
+
return handlers[type](body);
|
|
2387
|
+
}
|
|
2388
|
+
|
|
2389
|
+
// The web console only ends sessions it owns. The host process survives and the current HTTP request can reply.
|
|
2390
|
+
pageEnd({ force = false } = {}) {
|
|
2391
|
+
if (!this.host) throw new Error('请在对应的终端结束这个会话');
|
|
2392
|
+
if (!force && this.working()) throw new Error('会话正在工作:先停止当前任务,或选择强制结束');
|
|
2393
|
+
this.exit(0);
|
|
2394
|
+
return { ending: true };
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2386
2397
|
// A tool call finished (or was refused, or interrupted): its result on the remote page, once.
|
|
2387
2398
|
remoteToolDone(entry) {
|
|
2388
|
-
if (!this.
|
|
2399
|
+
if (!this.liveFeed.active || !entry.tu?.id || entry.remoteDone) return;
|
|
2389
2400
|
entry.remoteDone = true;
|
|
2390
2401
|
let lines = [];
|
|
2391
2402
|
try { lines = renderToolResult(entry, { width: REMOTE_WIDTH, cwd: this.cwd }); } catch { /* shown without */ }
|
|
2392
|
-
this.
|
|
2403
|
+
this.emitEvent({ t: 'done', id: entry.tu.id, status: entry.result?.isError || entry.rejected ? 'error' : 'done', lines });
|
|
2393
2404
|
}
|
|
2394
2405
|
|
|
2395
2406
|
// Move finished tool entries (in call order) from the live region to the transcript.
|
|
@@ -2566,8 +2577,6 @@ export class App {
|
|
|
2566
2577
|
if (!this.dialogs.length) {
|
|
2567
2578
|
if (lines.length) lines.push('');
|
|
2568
2579
|
lines.push(this.spinnerLine());
|
|
2569
|
-
const todos = this.agent.todos;
|
|
2570
|
-
if (this.showTodos && todos.length) lines.push(...renderTodos(todos).map((l) => truncate(l, w)));
|
|
2571
2580
|
}
|
|
2572
2581
|
} else if (this.active.length) {
|
|
2573
2582
|
for (const e of this.active) lines.push(...this.renderActiveEntry(e, w));
|
|
@@ -2585,93 +2594,27 @@ export class App {
|
|
|
2585
2594
|
}
|
|
2586
2595
|
if (lines.length) lines.push('');
|
|
2587
2596
|
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"');
|
|
2588
|
-
const
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
const maxRows = Math.max(3, this.screen.height - 1 - lines.length - after.length - 2 - 2);
|
|
2594
|
-
const r = this.finder ? this.renderFind(width) : this.editor.render(width, { placeholder, title: this.boxTitle(), maxRows });
|
|
2597
|
+
const hint = this.hint();
|
|
2598
|
+
const after = this.editor.suggestions ? this.editor.renderSuggestions(w) : hint ? [hint] : [];
|
|
2599
|
+
// the input's text gets the screen less what is above and below it, and two rows of the conversation
|
|
2600
|
+
const maxRows = Math.max(3, this.screen.height - 1 - lines.length - after.length - 1 - 2);
|
|
2601
|
+
const r = this.editor.render(width, { placeholder, maxRows });
|
|
2595
2602
|
const top = lines.length;
|
|
2596
2603
|
lines.push(...r.lines);
|
|
2597
2604
|
if (r.cursor) cursor = { row: top + r.cursor.row, col: r.cursor.col };
|
|
2598
|
-
const input = r.text ? { ...r.text, row: top + r.text.row } : null; // where the mouse reaches the input box's text
|
|
2599
2605
|
lines.push(...after);
|
|
2600
|
-
return { lines, cursor
|
|
2601
|
-
}
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
//
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
// The prompt cache clock, as in Claude Code's VS Code extension: the minutes the conversation's cache has left
|
|
2614
|
-
// ("◷ 12m"), or the icon alone in red once it has run out or right after a compaction, until the next response:
|
|
2615
|
-
// the next message then writes the whole conversation to the cache again. Nothing before a response reported
|
|
2616
|
-
// cache use.
|
|
2617
|
-
cacheClock() {
|
|
2618
|
-
const clock = this.agent?.cache.clock();
|
|
2619
|
-
return !clock ? '' : clock.cold ? c.red(glyphs.clock) : c.dim(`${glyphs.clock} ${clock.minutes}m`);
|
|
2620
|
-
}
|
|
2621
|
-
|
|
2622
|
-
footer(w) {
|
|
2623
|
-
let left;
|
|
2624
|
-
const flash = this.flashMessage && Date.now() < this.flashMessage.until ? this.flashMessage : null;
|
|
2625
|
-
if (this.exitArmed && Date.now() - this.exitArmed < 1500) left = c.dim(' Press Ctrl-C again to exit');
|
|
2626
|
-
else if (flash) left = (flash.kind === 'warn' ? c.yellow : c.dim)(' ' + truncate(flash.text, w - 4));
|
|
2627
|
-
else if (this.screen.full && this.screen.selection) left = c.dim(' ctrl+c to copy · ctrl+q to quote it in your message');
|
|
2628
|
-
else if (this.editor.selection) left = c.dim(' ctrl+c to copy · esc to clear');
|
|
2629
|
-
else if (this.restartRequest) left = c.dim(` ${glyphs.restart} restarting when this turn ends`);
|
|
2630
|
-
else if (this.editor.mode === 'bash') left = c.magenta(' ! for bash mode');
|
|
2631
|
-
else if (this.editor.mode === 'memory') left = c.blue(' # to memorize');
|
|
2632
|
-
else left = c.dim(' ? for shortcuts');
|
|
2633
|
-
if (this.remote?.online && this.remote.viewers && !flash && !(this.exitArmed && Date.now() - this.exitArmed < 1500)) {
|
|
2634
|
-
left += c.dim(' · ') + c.green(`⇄ ${this.remote.viewers} watching`);
|
|
2635
|
-
}
|
|
2636
|
-
if (!flash) {
|
|
2637
|
-
if (this.updating) left += c.dim(' · ') + c.blue(`${glyphs.update} updating ${APP_NAME} to ${this.updating}…`);
|
|
2638
|
-
else if (this.updateRestart && this.sourceChanged && !this.restartRequest) left += c.dim(' · ') + c.blue(`${glyphs.restart} ${this.updateRestart} installed: restarts ${this.working() ? 'when the work is done' : 'now'}`);
|
|
2639
|
-
else if (this.sourceChanged && !this.sourceChangedInTurn && !this.restartRequest && !this.reloading && !this.working() && this.sourceQuietAt > Date.now()) left += c.dim(' · ') + c.dim(`${glyphs.restart} source changed: restarts once it is left alone (/restart: now)`);
|
|
2640
|
-
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'}`);
|
|
2641
|
-
}
|
|
2642
|
-
const cfg = this.config;
|
|
2643
|
-
const threshold = cfg.compactWindow();
|
|
2644
|
-
const used = this.agent.contextEstimate;
|
|
2645
|
-
let notice = '';
|
|
2646
|
-
const pctLeft = Math.max(0, Math.round((1 - used / threshold) * 100));
|
|
2647
|
-
if (pctLeft <= 30) notice = c.yellow(`Context left until auto-compact: ${pctLeft}%`);
|
|
2648
|
-
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`);
|
|
2649
|
-
else if (this.verbose) notice = c.dim('verbose');
|
|
2650
|
-
// The model and effort in use always have a place at the right: with the notice after it when both fit,
|
|
2651
|
-
// and the notice alone when they do not (a context warning matters more than the model's name).
|
|
2652
|
-
const { model, effort } = modelInfo(cfg);
|
|
2653
|
-
// An effort that is not set is not sent: the API then uses the model's default, which is shown instead.
|
|
2654
|
-
const level = effort || defaultEffort(cfg.model.id, cfg);
|
|
2655
|
-
const info = c.dim(level ? `${model} · ${level}` : model);
|
|
2656
|
-
const version = c.dim(`v${VERSION}`);
|
|
2657
|
-
const compactTokens = (n) => formatTokens(n).replace(/\.0([kM])$/, '$1');
|
|
2658
|
-
const context = c.dim(`ctx ${compactTokens(used)}/${compactTokens(cfg.model.contextWindow)}`);
|
|
2659
|
-
// Before the context, version and model: the prompt cache clock, then what the conversation has cost so far;
|
|
2660
|
-
// when room is short the cost goes first, then the clock.
|
|
2661
|
-
const spent = this.cost > 0 ? c.dim(formatUsd(this.cost)) : '';
|
|
2662
|
-
const clock = this.cacheClock();
|
|
2663
|
-
const join = (...parts) => parts.filter(Boolean).join(c.dim(' · '));
|
|
2664
|
-
const room = w - stringWidth(left) - 1;
|
|
2665
|
-
const right = [
|
|
2666
|
-
join(notice, clock, spent, context, version, info),
|
|
2667
|
-
join(notice, clock, context, version, info),
|
|
2668
|
-
join(notice, context, version, info),
|
|
2669
|
-
join(notice, context, version),
|
|
2670
|
-
join(notice, version),
|
|
2671
|
-
version,
|
|
2672
|
-
].find((r) => r && stringWidth(r) < room) || '';
|
|
2673
|
-
const gap = room - stringWidth(right);
|
|
2674
|
-
return right ? left + ' '.repeat(gap) + right : left;
|
|
2606
|
+
return { lines, cursor };
|
|
2607
|
+
}
|
|
2608
|
+
|
|
2609
|
+
|
|
2610
|
+
// A line under the input, only while there is something to say that cannot wait for the end of the turn.
|
|
2611
|
+
hint() {
|
|
2612
|
+
if (this.exitArmed && Date.now() - this.exitArmed < 1500) return c.dim(' Press Ctrl-C again to exit');
|
|
2613
|
+
if (this.restartRequest) return c.dim(` ${glyphs.restart} restarting when this turn ends`);
|
|
2614
|
+
if (this.updating) return c.blue(` ${glyphs.update} updating ${APP_NAME} to ${this.updating}…`);
|
|
2615
|
+
if (this.updateRestart && this.sourceChanged) return c.blue(` ${glyphs.restart} ${this.updateRestart} installed: restarts ${this.working() ? 'when the work is done' : 'now'}`);
|
|
2616
|
+
if (this.sourceChanged && !this.sourceChangedInTurn && !this.reloading && !this.working() && this.sourceQuietAt > Date.now()) return c.dim(` ${glyphs.restart} source changed: restarts once it is left alone (/restart: now)`);
|
|
2617
|
+
return '';
|
|
2675
2618
|
}
|
|
2676
2619
|
}
|
|
2677
2620
|
|