@yanzc/claude-pro 0.10.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/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, queryCursorRow, mouseFilter } from './screen.js';
11
- import { Editor, topBorder, shownQuotes } from './editor.js';
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, renderTodos, renderUserMessage, resultLines, formatTokens, formatDuration, toolLabel, bashModeLines,
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 { browserSession } from '../browser/session.js';
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 { RemoteControl, transcriptItems, onlineEnabled, remoteCommandsEnabled, REMOTE_WIDTH } from '../remote.js';
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
- constructor({ flags, cwd, stdin = process.stdin, stdout = process.stdout, noProcessExit = false, selfCheck = false }) {
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.noProcessExit = noProcessExit || selfCheck;
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,6 +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
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;
281
295
  this.remoteMuted = 0; // > 0 while printing something the page is told about in its own terms
282
296
  this.remoteDialogs = 0;
283
297
  this.remoteStarting = null;
@@ -291,14 +305,23 @@ export class App {
291
305
  this.remotePeersLoading = null;
292
306
  this.remotePeersTimer = null;
293
307
  this.cost = 0; // what this conversation's requests have cost so far (USD at list prices): the footer and /cost
294
- this.fileIndex = new FileIndex(cwd, () => this.runtime?.config, () => { this.editor?.refreshSuggestions(); this.screen?.schedule(); });
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');
295
318
  this.store = new SessionStore(cwd);
296
- SessionStore.onError = (e, store) => this.notice(`Could not save the conversation to ${store.file} (${e.code || e.message}): it is written again whole before a restart, but /resume may miss what was not saved.`, 'warn');
319
+ this.store.onError = this.storeError;
297
320
  // What the terminal prints goes to the remote page too, except what it is told about as events.
298
321
  this.screen.onLog = (items) => {
299
322
  const lines = () => items.flatMap((i) => (Array.isArray(i) ? i : [i])).flatMap((l) => String(l).split(/\r?\n/));
300
- if (!this.remote || this.remoteMuted) return;
301
- this.remote.output(lines());
323
+ if (this.remoteMuted || !this.liveFeed?.active) return;
324
+ this.liveFeed.output(lines());
302
325
  };
303
326
  this.editor = new Editor({
304
327
  history: loadHistory(cwd),
@@ -307,15 +330,20 @@ export class App {
307
330
  imageFromPath: (p) => {
308
331
  const r = imageFromFile(resolvePath(p, this.cwd));
309
332
  if (r.error && !/not found|Not a file/.test(r.error)) this.flash(r.error, 'warn');
310
- if (r.image) this.flashMessage = null;
311
333
  return r.image || null;
312
334
  },
313
- getSuggestions: (text, cursor) => this.suggest(text, cursor),
335
+ getSuggestions: (text, cursor, opts) => this.suggest(text, cursor, opts),
314
336
  onChange: () => this.screen.schedule(),
315
337
  });
316
338
  }
317
339
 
318
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); }
319
347
  get config() { return this.runtime.config; }
320
348
  get width() { return this.screen.width; }
321
349
  isTurnRunning() { return this.busy || this.turnStarting; }
@@ -323,20 +351,29 @@ export class App {
323
351
  // ---------------------------------------------------------------- lifecycle
324
352
 
325
353
  async start(initialPrompt) {
354
+ if (this.exiting) return this.exitCode;
326
355
  const stdin = this.stdin;
327
356
  stdin.setRawMode(true);
328
357
  // Where the cursor is, before anything is drawn: the input box is kept on the last rows of the window from
329
358
  // there (see screen.js).
330
359
  if (stdin.isTTY && this.stdout.isTTY) this.screen.pinFrom(await queryCursorRow(stdin, this.stdout));
360
+ if (this.exiting) return this.exitCode;
331
361
  stdin.setEncoding('utf8');
332
362
  this.stdout.write(ESC.bracketedPasteOn);
333
- const cleanup = () => this.restoreTerminal();
334
- process.on('exit', cleanup);
335
- process.on('SIGTERM', () => this.exit(143));
336
- process.on('SIGHUP', () => this.exit(129));
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
+ }
337
368
 
338
369
  await this.startPeer();
339
- this.runtime = await createRuntime({ cwd: this.cwd, flags: this.flags, io: this, sessionId: this.store.id });
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;
340
377
  // The conversation's id, sent to the gateway with each request (see streamMessage); it follows /clear and /resume.
341
378
  Object.defineProperty(this.runtime.config, 'sessionId', { get: () => this.store.id, configurable: true });
342
379
  // Every request's cost (the conversation's, its sub-agents', side queries'), kept with the session.
@@ -350,15 +387,11 @@ export class App {
350
387
  // so that the footer shows it before the first request.
351
388
  // not in the self-check a restart runs first: that would ask the gateway once more for every restart
352
389
  if (!this.driven && !this.selfCheck) loadGatewayModels(this.runtime.config).then(() => this.screen.schedule());
353
- // What the session showed before a restart: scrolled back to in fullscreen, repainted after a resize otherwise.
390
+ // What the session showed before a restart: repainted after a resize.
354
391
  if (Array.isArray(this.flags.restart?.screenHistory)) this.screen.history = this.flags.restart.screenHistory.filter((l) => typeof l === 'string');
355
- if (this.fullscreenWanted()) this.screen.setFull(true);
356
- // Keys typed while starting up stay buffered in stdin until we listen. Mouse reports (fullscreen: the wheel)
357
- // are taken out before the keys are read.
358
- const keys = mouseFilter(stdin, (m) => this.onMouse(m));
359
- this.keys = keys;
360
- readline.emitKeypressEvents(keys);
361
- 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) => {
362
395
  if (/^\x1b\[\d+;\d+R$/.test(key?.sequence || '')) return; // a late answer to the cursor position query, not a key
363
396
  try { this.onKey(str, key || {}); } catch (e) { this.logError(e); }
364
397
  });
@@ -374,14 +407,22 @@ export class App {
374
407
  if (restart) this.resumeAfterRestart(restart, resumable);
375
408
  else if (this.flags.resumeFile) this.loadSession(this.flags.resumeFile, this.flags.resumeId);
376
409
  else if (this.flags.resume) await this.commands.get('resume').run('');
410
+ if (this.exiting) return this.exitCode;
377
411
  if (!restart && this.flags.name?.trim()) this.renameSession(this.flags.name); // --name, as /rename does
378
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
+ }
379
419
 
380
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(); }
381
424
  this.spinnerTimer = setInterval(() => {
382
- const clock = this.cacheClock(); // the footer's clock counts down while nothing else is drawn
383
- if (this.isTurnRunning() || this.active.length || clock !== this.shownClock) this.screen.schedule();
384
- this.shownClock = clock;
425
+ if (this.isTurnRunning() || this.active.length) this.screen.schedule();
385
426
  }, 120);
386
427
  if (restart) this.continueAfterRestart(restart);
387
428
  else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
@@ -390,6 +431,11 @@ export class App {
390
431
  Promise.resolve(this.commands.get('connect').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
391
432
  }
392
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
+ }
393
439
  if (!this.driven) {
394
440
  // Updates are deliberately manual: /update checks npm and installs the selected release.
395
441
  // Do not query the registry or install/restart a running session in the background.
@@ -397,7 +443,7 @@ export class App {
397
443
  this.loginTimer = setInterval(() => this.syncRemote(), 10_000);
398
444
  this.loginTimer.unref?.();
399
445
  }
400
- return new Promise((resolve) => { this.resolveExit = resolve; });
446
+ return this.exiting ? this.exitCode : new Promise((resolve) => { this.resolveExit = resolve; });
401
447
  }
402
448
 
403
449
  // What the session is about now: the current model named the topic last, or else the first thing asked
@@ -471,34 +517,54 @@ export class App {
471
517
  } catch { /* ignore */ }
472
518
  }
473
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
+
474
534
  exit(code = 0, { restart = false } = {}) {
475
535
  if (this.exiting) return;
476
536
  this.exiting = true;
477
- this.controller?.abort();
478
- clearInterval(this.spinnerTimer);
479
- clearTimeout(this.reloadTimer);
480
- this.sourceWatch?.close();
481
- shutdownBackgroundShells();
482
- shutdownInterpreters();
483
- this.runtime?.tasks.killAll();
484
- this.runtime?.mcp.close();
485
- this.peers?.close();
486
- clearInterval(this.remotePeersTimer);
487
- clearInterval(this.loginTimer);
488
- const remoteClosed = this.remote?.close({ restarting: restart });
489
- const u = this.agent?.totalUsage();
537
+ this.exitCode = code;
538
+ let remoteClosed;
490
539
  const farewell = []; // left on the terminal once the program's screen is gone (see Screen.close)
491
- if (!restart && u && u.requests) {
492
- 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`));
493
- }
494
- if (!restart && this.agent?.messages.length) farewell.push(c.dim(`Resume this session with: ${APP_NAME} --resume ${this.store.id}`));
495
- this.restoreTerminal({ handOver: restart, farewell });
496
- this.stdin.pause();
497
- this.resolveExit?.(code);
498
- if (!this.noProcessExit) {
499
- // with remote control on, the gateway is told first (at most a second and a half; see RemoteControl.close)
500
- if (remoteClosed) remoteClosed.finally(() => process.exit(code));
501
- else setTimeout(() => process.exit(code), 50).unref();
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
+ }
502
568
  }
503
569
  }
504
570
 
@@ -509,13 +575,34 @@ export class App {
509
575
  async startPeer() {
510
576
  if (this.driven || !peersEnabled()) return;
511
577
  try {
512
- this.peers = await new PeerNode({
578
+ const peer = new PeerNode({
513
579
  cwd: this.cwd,
514
580
  name: this.flags.restart?.peerName,
515
581
  id: this.flags.restart?.peerId,
516
582
  onMessage: (msg) => this.onPeerMessage(msg),
517
- getStatus: () => ({ busy: this.working() }),
518
- }).start();
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;
519
606
  } catch (e) {
520
607
  this.peers = null;
521
608
  this.notice(`Other sessions cannot reach this one: ${e.message}`, 'warn');
@@ -564,20 +651,30 @@ export class App {
564
651
  }
565
652
 
566
653
  // The account's sessions on other computers that are online now, from the gateway (what was known stays when
567
- // it cannot be asked). Sessions of this computer are left out: they are reached directly.
654
+ // it cannot be asked), and those of its contacts (other people, /contacts). Sessions of this computer are left
655
+ // out: they are reached directly.
568
656
  refreshRemotePeers() {
569
657
  if (!this.remote?.registered) return Promise.resolve(this.remotePeers);
570
658
  this.remotePeersLoading ??= (async () => {
571
659
  try {
572
660
  const near = new Set([this.peers?.id, ...(this.peers?.peers() || []).map((p) => p.id)].filter(Boolean));
573
- const list = await this.remote.sessions();
574
- this.remotePeers = list
575
- .filter((p) => p.online && !p.ended && p.id !== this.remote?.id && !near.has(p.peerId))
576
- .map((p) => {
577
- const machine = p.machine || p.host || 'computer';
578
- const name = p.name || 'session';
579
- return { id: p.id, name, machine, cwd: p.cwd || '', remote: true, label: `${machine}/${name}`, busy: Boolean(p.busy), title: p.title || '' };
580
- });
661
+ const { own, contacts } = await this.remote.sessions();
662
+ this.remotePeers = [
663
+ ...own
664
+ .filter((p) => p.online && !p.ended && p.id !== this.remote?.id && !near.has(p.peerId))
665
+ .map((p) => {
666
+ const machine = p.machine || p.host || 'computer';
667
+ const name = p.name || 'session';
668
+ return { id: p.id, name, machine, cwd: p.cwd || '', remote: true, label: `${machine}/${name}`, busy: Boolean(p.busy), title: p.title || '' };
669
+ }),
670
+ ...contacts
671
+ .filter((p) => p.online && p.account)
672
+ .map((p) => {
673
+ const machine = p.machine || 'computer';
674
+ const name = p.name || 'session';
675
+ return { id: p.id, name, machine, cwd: '', remote: true, contact: true, account: p.account, label: `${p.account}:${machine}/${name}`, busy: Boolean(p.busy), title: '' };
676
+ }),
677
+ ];
581
678
  this.remotePeersAt = Date.now();
582
679
  } catch { /* the gateway cannot be asked now */ } finally {
583
680
  this.remotePeersLoading = null;
@@ -594,19 +691,64 @@ export class App {
594
691
  return {
595
692
  me: { name, cwd: this.agent?.cwd || this.cwd, label: `${machineName(this.config.env)}/${name}` },
596
693
  local: this.peers?.peers() || [],
597
- remote: this.remotePeers,
694
+ remote: this.remotePeers.filter((p) => !p.contact),
695
+ contacts: this.remotePeers.filter((p) => p.contact),
598
696
  online: Boolean(this.remote?.online),
599
697
  };
600
698
  }
601
699
 
700
+ // 通讯录 events from the gateway: another account asked this one to be a contact, or accepted its request.
701
+ onContactEvent(ev) {
702
+ const handle = String(ev.handle || '').replace(/[^\w-]/g, '');
703
+ if (!handle || this.exiting) return;
704
+ if (ev.event === 'request') {
705
+ this.screen.log(`${c.blue('✉')} ${c.bold(handle)} asks to be your contact: their claude-pro sessions and yours could then send each other tasks.`,
706
+ c.dim(` /contacts accept ${handle} · /contacts reject ${handle} · /contacts block ${handle} (or 通讯录 on the gateway's web page)`), '');
707
+ } else if (ev.event === 'accepted') {
708
+ this.screen.log(`${c.blue('✉')} ${c.bold(handle)} accepted you as a contact: their online sessions show in /peers as @${handle}:computer/name.`, '');
709
+ this.refreshRemotePeers();
710
+ }
711
+ }
712
+
713
+ // A task from a contact's session (another person) runs only once the user allows it here, unless the user set
714
+ // that contact's tasks to run by themselves (trust "auto", /contacts trust). Resolves with whether it runs.
715
+ async allowContactTask(msg) {
716
+ if (msg.from.trust === 'auto') return true;
717
+ const preview = msg.text.length > 1200 ? `${msg.text.slice(0, 1200)}…` : msg.text;
718
+ const choice = await this.showDialog(new SelectDialog({
719
+ title: `Task from the contact ${msg.from.account}`,
720
+ body: [c.dim(`From their session @${msg.from.name}, another person's agent, not you:`), ...preview.split('\n').flatMap((line) => wordWrap(line, Math.max(20, this.width - 8))).slice(0, 20)],
721
+ question: 'Let this session work on it? Its final answer is sent back to them.',
722
+ color: c.yellow,
723
+ options: [
724
+ { label: 'Run it', value: 'run', description: 'This task only' },
725
+ { label: 'Decline', value: 'decline', description: 'They are told that you declined it' },
726
+ { label: `Always run tasks from ${msg.from.account}`, value: 'always', description: 'Their later tasks run without asking (/contacts trust to change it)' },
727
+ ],
728
+ }));
729
+ if (choice === 'always') {
730
+ this.remote?.contacts('trust', { handle: msg.from.account, trust: 'auto' }).catch((e) => this.notice(`Could not save that at the gateway: ${e.message}`, 'warn'));
731
+ }
732
+ return choice === 'run' || choice === 'always';
733
+ }
734
+
602
735
  onPeerMessage(msg) {
603
736
  if (this.exiting) return;
737
+ if (msg.kind === 'task' && msg.from.account && !msg.confirmed && msg.from.trust !== 'auto') {
738
+ this.allowContactTask(msg).then((ok) => {
739
+ if (ok) { this.onPeerMessage({ ...msg, confirmed: true }); return; }
740
+ this.screen.log(c.dim(` ✉ Declined the task from @${msg.from.name}`), '');
741
+ this.replyToPeer(msg, `The user of ${this.peerLabel()} declined this task.`);
742
+ }, (e) => this.logError(e));
743
+ return;
744
+ }
604
745
  const from = c.bold(`@${msg.from.name}`);
605
746
  const width = this.width - 1;
606
747
  if (msg.kind === 'reply' && this.userSentToPeers.delete(`${msg.from.id}:${msg.inReplyTo}`)) {
607
748
  // the answer to something the user sent: shown, and noted for the model, without a turn of its own
608
749
  this.screen.log(`${c.blue('✉')} ${from} ${c.dim('answered:')}`, ...renderMarkdown(msg.text, { width: width - 2 }).map((l) => ' ' + l), '');
609
- this.agent.addReminder(`The user sent a message to another claude-pro session, ${msg.from.name} (${msg.from.cwd}), which answered:\n${msg.text}`);
750
+ const whose = msg.from.account ? `of the contact "${msg.from.account}" (another person)` : `(${msg.from.cwd})`;
751
+ this.agent.addReminder(`The user sent a message to another claude-pro session, ${msg.from.name} ${whose}, which answered:\n${msg.text}`);
610
752
  return;
611
753
  }
612
754
  const display = `✉ ${msg.kind === 'reply' ? 'answer from' : 'task from'} @${msg.from.name}: ${msg.text}`;
@@ -659,7 +801,28 @@ export class App {
659
801
  // A message of the user in the transcript (typed here, on the remote page, or sent by another session).
660
802
  echoUser(text, images = 0) {
661
803
  this.logLocal(renderUserMessage(text, this.width));
662
- this.remote?.emit({ t: 'user', text: images ? `${text}\n[${images} image${images === 1 ? '' : 's'}]` : String(text) });
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;
663
826
  }
664
827
 
665
828
  // Whether this session should be online at the gateway (see remote.js): whenever this computer is logged in to
@@ -713,16 +876,6 @@ export class App {
713
876
  async connectRemote({ id }) {
714
877
  const login = gatewayLogin(this.config.gatewayUrl);
715
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' });
716
- // What the page may do here, besides watching (see remote.js): nothing with CLAUDE_PRO_REMOTE_COMMANDS=0.
717
- const commands = remoteCommandsEnabled(this.config.env) ? {
718
- send: (body) => this.remoteSend(body.text, body.images),
719
- interrupt: () => this.remoteInterrupt(),
720
- answer: (body) => this.answerDialog(body),
721
- options: () => this.remoteOptions(),
722
- suggest: (body) => this.remoteSuggest(body),
723
- list: (body) => this.remoteList(body),
724
- output: (body) => this.remoteOutput(body),
725
- } : {};
726
879
  const remote = new RemoteControl({
727
880
  gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
728
881
  id,
@@ -730,15 +883,10 @@ export class App {
730
883
  info: () => ({
731
884
  name: this.peerLabel(), machine: machineName(this.config.env), peerId: this.peers?.id || null, title: this.sessionLabel() || '',
732
885
  cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'), model: modelInfo(this.config).model, version: VERSION,
733
- kind: 'terminal',
734
886
  }),
735
- seed: () => [
736
- ...transcriptItems(this.agent.messages, { tools: this.runtime.tools, ctx: this.agent.makeCtx(), cwd: this.cwd }),
737
- ...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
738
- ],
739
887
  status: () => this.remoteStatus(),
740
- ...commands,
741
- peerMessage: (msg) => this.onPeerMessage(msg),
888
+ peerMessage: (msg) => this.moving || this.exiting ? false : this.onPeerMessage(msg),
889
+ contactEvent: (ev) => this.onContactEvent(ev),
742
890
  changed: () => {
743
891
  this.screen.schedule();
744
892
  if (remote.online && Date.now() - this.remotePeersAt > 10_000) this.refreshRemotePeers();
@@ -774,14 +922,12 @@ export class App {
774
922
  this.screen.schedule();
775
923
  }
776
924
 
777
- // This session at the gateway, for /status: {text}. (Its page is in the web page's list, 远程控制: no link here.)
925
+ // This session at the gateway (its session relay: tasks across computers and from contacts), for /status: {text}.
778
926
  remoteState() {
779
927
  const r = this.remote;
780
928
  if (r) {
781
929
  const who = r.account ? ` as ${r.account}` : '';
782
- const pages = r.viewers ? c.dim(` · ${r.viewers} page${r.viewers === 1 ? '' : 's'} open now`) : '';
783
- const readOnly = r.commands.length ? '' : c.dim(' · read-only on the page (CLAUDE_PRO_REMOTE_COMMANDS=0)');
784
- 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}…`;
785
931
  return { text };
786
932
  }
787
933
  if (this.remoteStarting) return { text: 'connecting…' };
@@ -821,7 +967,7 @@ export class App {
821
967
  cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'),
822
968
  name: this.peerLabel(),
823
969
  tasks: this.runtime.tasks.running().length,
824
- restarting: Boolean(this.restartRequest),
970
+ restarting: Boolean(this.restartRequest || this.host?.restartWaits(this)),
825
971
  asking: this.dialogs.length > 0, // a question waits for an answer (the page reminds the user of it)
826
972
  conversationId: this.store.id,
827
973
  cost: Number(this.cost.toFixed(6)),
@@ -851,7 +997,7 @@ export class App {
851
997
  // What runs in the background: the agent's background agents and shells.
852
998
  backgroundWork() {
853
999
  const agents = this.runtime.tasks.list().map((t) => ({ id: t.id, kind: 'agent', description: t.description, status: t.status, startedAt: t.started }));
854
- 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 }));
855
1001
  return [...agents, ...shells];
856
1002
  }
857
1003
 
@@ -1014,8 +1160,11 @@ export class App {
1014
1160
 
1015
1161
  restartBlockers() {
1016
1162
  const found = [];
1017
- for (const t of this.runtime.tasks.running()) found.push(`background agent ${t.id} "${t.description}"`);
1018
- for (const s of listBackgroundShells()) if (s.status === 'running') found.push(`background shell ${s.id} (${String(s.command).slice(0, 40)})`);
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
+ }
1019
1168
  return found;
1020
1169
  }
1021
1170
 
@@ -1024,7 +1173,7 @@ export class App {
1024
1173
  // the new process and goes on by itself. Returns {ok, message}.
1025
1174
  // `cwd`: the session goes on in that directory (/cd).
1026
1175
  requestRestart({ reason = '', then = '', continueTurn = false, force = false, cwd = null } = {}) {
1027
- if (!canRestart()) return { ok: false, message: 'This session cannot restart itself.' };
1176
+ if (!this.canRestart()) return { ok: false, message: 'This session cannot restart itself.' };
1028
1177
  const now = Date.now();
1029
1178
  const recent = this.restarts.filter((t) => now - t < RESTART_WINDOW_MS);
1030
1179
  if (recent.length >= MAX_RESTARTS && !cwd) {
@@ -1038,31 +1187,64 @@ export class App {
1038
1187
  return { ok: true };
1039
1188
  }
1040
1189
 
1041
- // 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.
1042
1193
  restartNow() {
1043
1194
  const request = this.restartRequest || {};
1044
1195
  this.restartRequest = null;
1045
- const cfg = this.config;
1046
- const now = Date.now();
1196
+ if (this.host && !request.cwd) { this.host.restartFor(this, request); return; }
1047
1197
  // /cd: the conversation's file goes along to the new directory's project (see moveSession); the old one is
1048
1198
  // removed once the next process is sure to find the new one
1049
1199
  let moved = null;
1050
1200
  if (request.cwd) {
1051
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; }
1052
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();
1053
1237
  // a write of the conversation failed at some point: the file lacks part of it, and the next process goes on from it
1054
- if (this.store.lost) { this.store.lost = false; this.store.reset(this.agent.messages); }
1055
- const state = {
1238
+ this.flushUnsavedConversation();
1239
+ return {
1056
1240
  at: now,
1057
1241
  reason: request.reason || '',
1058
1242
  continueWith: request.continueTurn ? restartNote(request) : '',
1059
1243
  cwd: request.cwd || this.cwd,
1060
1244
  changedDirectory: Boolean(request.cwd),
1061
- // where the agent's shell is (a `cd` in Bash moves it): the next process goes on there, not at the project's root
1062
- agentCwd: request.cwd ? null : this.agent.cwd,
1063
1245
  // the browser instance in use (it may be any of several): the next process connects to it again, where the
1064
1246
  // tab ids in the conversation are still its tabs'
1065
- browser: browserSession.preferred || null,
1247
+ browser: browserSessionFor(this.owner).preferred || null,
1066
1248
  sessionId: this.store.id,
1067
1249
  sessionFile: moved?.file || this.store.file,
1068
1250
  modelOverride: cfg.modelOverride,
@@ -1076,22 +1258,39 @@ export class App {
1076
1258
  // `peer`: a task of another session, which gets the answer of the turn that handles it
1077
1259
  queue: this.queue.map((q) => ({ text: q.text, images: q.images || [], display: q.display ?? null, peer: q.peer || null })),
1078
1260
  checkpoints: this.runtime.checkpoints.snapshot(),
1079
- // a /cd is the user's: it does not count towards the restarts that look like a loop
1080
- 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] : [])],
1081
1262
  // a name given with /rename or --name stays; the one taken from the directory follows it
1082
1263
  peerName: request.cwd && !this.customTitle ? null : this.peers?.name || this.sessionName,
1083
1264
  peerId: this.peers?.id,
1084
1265
  remote: this.remote?.handoff() || null,
1266
+ restartNote: this.restartNote || null, // the last restart line, merged with the next one when nothing came between
1267
+ used: this.inUse(),
1085
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;
1086
1277
  try {
1087
- writeRestartState(state);
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)
1088
1288
  } catch (e) {
1089
- moved?.undo();
1090
- this.notice(`Could not restart: ${e.message}`, 'warn');
1091
- return;
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));
1092
1293
  }
1093
- moved?.commit();
1094
- this.exit(RESTART_EXIT_CODE, { restart: true });
1095
1294
  }
1096
1295
 
1097
1296
  // /cd: the session goes on in `dir` (an existing directory). It restarts there, so that everything that belongs to
@@ -1100,7 +1299,7 @@ export class App {
1100
1299
  // page's id and a name given with /rename stay. Returns {ok, message}.
1101
1300
  changeDirectory(dir) {
1102
1301
  if (this.isTurnRunning()) return { ok: false, message: 'Wait for the current task to finish (or press Esc) before changing the directory.' };
1103
- 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.' };
1104
1303
  return this.requestRestart({ reason: `working directory ${dir}`, cwd: dir });
1105
1304
  }
1106
1305
 
@@ -1115,19 +1314,14 @@ export class App {
1115
1314
  // The Effort tool's level holds for the request the restart continues, not for the user's next one.
1116
1315
  if (state.effortBoost) { cfg.effortBoost = state.effortBoost; cfg.effortBoostKeepNext = Boolean(state.continueWith); }
1117
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)
1118
1318
  if (resumable) {
1119
1319
  this.loadSession(state.sessionFile, state.sessionId, { quiet: true });
1120
1320
  if (Array.isArray(state.todos)) this.agent.todos = state.todos;
1121
1321
  if (state.checkpoints) this.runtime.checkpoints.adopt(state.checkpoints);
1122
- if (typeof state.agentCwd === 'string' && state.agentCwd !== this.cwd) {
1123
- try { if (fs.statSync(state.agentCwd).isDirectory()) this.agent.cwd = state.agentCwd; } catch { /* gone: the project's root */ }
1124
- }
1125
1322
  }
1126
- if (state.browser && typeof state.browser === 'object' && typeof state.browser.dir === 'string') browserSession.preferred = state.browser;
1323
+ if (state.browser && typeof state.browser === 'object' && typeof state.browser.dir === 'string') browserSessionFor(this.owner).preferred = state.browser;
1127
1324
  if (typeof state.draft === 'string' && state.draft) this.editor.restoreDraft(state.draft, state.draftCursor, state.draftParts);
1128
- // Fullscreen starts on an empty screen: without what the process before showed (an older version, or one
1129
- // that ran classic), the conversation is drawn again from the session.
1130
- if (this.screen.full && resumable && !Array.isArray(state.screenHistory)) this.printTranscript(this.agent.messages.slice(-80));
1131
1325
  if (state.changedDirectory) {
1132
1326
  // /cd: the line it answers with, here and on the remote page (which starts again from the conversation)
1133
1327
  const line = `Working directory: ${this.cwd}`;
@@ -1135,7 +1329,25 @@ export class App {
1135
1329
  this.seedOutput = [line];
1136
1330
  return;
1137
1331
  }
1138
- this.screen.log(c.dim(`${glyphs.restart} Restarted${state.reason ? `: ${state.reason}` : ''}${state.continueWith ? ' · continuing' : ''}`), '');
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 };
1139
1351
  }
1140
1352
 
1141
1353
  // The turn that goes on after a restart: the note for the model, and what the user had queued meanwhile.
@@ -1160,7 +1372,7 @@ export class App {
1160
1372
  // once, every edit of one session made each of the other open sessions check and restart, into a half-made
1161
1373
  // change: 8 of them, a dozen times in a day's work.)
1162
1374
  startSourceWatch() {
1163
- if (!canRestart()) return;
1375
+ if (!canRestart() || this.host) return; // (the web console follows the source for all its sessions: web/host.js)
1164
1376
  this.sourceWatch = watchSource(INSTALL_DIR, (file) => {
1165
1377
  this.sourceChanged = file || true;
1166
1378
  if (this.isTurnRunning()) this.sourceChangedInTurn = true;
@@ -1178,7 +1390,8 @@ export class App {
1178
1390
  }
1179
1391
 
1180
1392
  async maybeAutoReload() {
1181
- if (!this.sourceChanged || this.updating || this.reloading || this.isTurnRunning() || this.exiting || this.restartRequest || this.dialogs.length || this.queue.length) return;
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;
1182
1395
  if (this.skipAutoReload) { this.skipAutoReload = false; return; } // the user just interrupted: not now
1183
1396
  if (this.restartBlockers().length) return; // looked at again whenever the program is next idle
1184
1397
  clearTimeout(this.reloadTimer);
@@ -1229,7 +1442,7 @@ export class App {
1229
1442
  } else if (r.status === 'installed') {
1230
1443
  this.notice(`${APP_NAME} ${r.version} is installed already; this session restarts to load it ${this.working() ? 'once its work is done' : 'now'}.`);
1231
1444
  this.updateRestart = r.version;
1232
- if (canRestart()) { this.sourceChanged ||= true; if (!this.isTurnRunning()) this.maybeAutoReload(); }
1445
+ if (this.canRestart()) { this.sourceChanged ||= true; if (!this.isTurnRunning()) this.maybeAutoReload(); }
1233
1446
  } else if (r.status === 'failed') {
1234
1447
  this.notice(`Could not update ${APP_NAME}${r.version ? ` to ${r.version}` : ''}: ${r.error}`, 'warn');
1235
1448
  } else {
@@ -1277,7 +1490,7 @@ export class App {
1277
1490
  if (r.status === 'updated' || r.status === 'installed') {
1278
1491
  this.pendingUpdate = null;
1279
1492
  this.updateRestart = r.version;
1280
- if (canRestart()) {
1493
+ if (this.canRestart()) {
1281
1494
  this.notice(`${APP_NAME} was updated to ${r.version} (from ${VERSION}); restarting to load it. The conversation carries over.`);
1282
1495
  this.sourceChanged = true;
1283
1496
  this.maybeAutoReload();
@@ -1291,20 +1504,12 @@ export class App {
1291
1504
 
1292
1505
  printWelcome() {
1293
1506
  const cfg = this.config;
1294
- const w = Math.min(this.width - 1, 76);
1295
- const inner = w - 4;
1296
- const row = (s) => c.claude('│') + ' ' + padEnd(truncate(s, inner), inner) + ' ' + c.claude('│');
1297
1507
  const model = cfg.model;
1298
1508
  const lines = [
1299
- c.claude(glyphs.topLeft + '─'.repeat(w - 2) + glyphs.topRight),
1300
- row(`${c.claude('✻')} Welcome to ${c.bold(APP_NAME)}! ${c.dim(`v${VERSION} · a command line coding agent`)}`),
1301
- row(''),
1302
- row(c.dim(' /help for help, /status for your current setup')),
1303
- row(''),
1304
- row(c.dim(` cwd: ${this.cwd}`)),
1305
- row(c.dim(` model: ${model.label}${cfg.effort ? ` · effort ${cfg.effort}` : ''} · ${formatTokens(model.contextWindow)} context`)),
1306
- row(c.dim(` backend: ${cfg.endpointLabel}`)),
1307
- 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}`),
1308
1513
  ];
1309
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).'));
1310
1515
  // (the model in use cannot be reached: said, with what connects it)
@@ -1316,56 +1521,12 @@ export class App {
1316
1521
  const ok = mcp.filter((m) => m.status === 'connected').length;
1317
1522
  lines.push(c.dim(` MCP: ${ok}/${mcp.length} servers connected${ok < mcp.length ? ' · /mcp for details' : ''}`));
1318
1523
  }
1319
- lines.push('', c.dim(' Tips for getting started:'), c.dim(' 1. Ask questions, edit files, or run commands'), c.dim(' 2. Be as specific as you would with another engineer for the best results'), c.dim(` 3. Run /init to create a CLAUDE.md file with instructions for ${APP_NAME}`), '');
1524
+ lines.push('');
1320
1525
  this.logLocal(lines);
1321
1526
  }
1322
1527
 
1323
1528
  // ---------------------------------------------------------------- input
1324
1529
 
1325
- // Always fullscreen on a terminal (there is no other mode to choose). Output that is no terminal (isTTY false: a
1326
- // test's fake terminal that asks for it) is written as it comes, with the input box after it.
1327
- fullscreenWanted() {
1328
- return this.stdout.isTTY !== false;
1329
- }
1330
-
1331
- // Fullscreen: the wheel scrolls the conversation (3 rows a notch); a drag,
1332
- // a double or a triple click selects text. Selection is copied only with Ctrl+C.
1333
- // In the input box a click moves the cursor and a drag selects its text (see Editor.mouse).
1334
- onMouse(m) {
1335
- if (!this.screen.full || this.exiting) return;
1336
- if (m.button & 64) {
1337
- if (m.button & 128) return;
1338
- const speed = 3;
1339
- this.screen.scrollBy(m.button & 1 ? -speed : speed);
1340
- return;
1341
- }
1342
- // Right-click is intentionally inert. Clipboard operations use Ctrl+C and Ctrl+V only.
1343
- const had = this.screen.selection;
1344
- const hadInput = this.editor.selection;
1345
- const r = this.screen.mouse(m);
1346
- if (r?.input) this.editor.mouse(r.input);
1347
- else if ((m.button & 3) === 0 && !(m.button & 32) && !m.release) this.editor.clearSelection(); // a press elsewhere
1348
- if ((this.screen.selection && this.screen.selection !== had) || (this.editor.selection && this.editor.selection !== hadInput)) {
1349
- this.flashMessage = null; // the footer says what a selection takes
1350
- this.screen.schedule();
1351
- }
1352
- }
1353
-
1354
- // Quote what is selected in the conversation in the message being written, as ChatGPT's "Ask ChatGPT" does:
1355
- // ctrl+q (alt+q where the terminal keeps ctrl+q), as the footer says while there is a selection. The box shows
1356
- // "[Quote #1 +12 lines]"; the model gets the text and the line of the conversation it is under (see
1357
- // Editor.insertQuote), so that it knows which part, and which file or command, the question is about.
1358
- quoteSelection() {
1359
- if (!this.screen.full) { this.flash('Quoting needs the fullscreen view: select text with the mouse, then ctrl+q', 'warn'); return; }
1360
- const quote = this.screen.selectionQuote();
1361
- if (!quote?.text.trim()) { this.flash('Select part of the conversation first (drag over it, or double/triple-click), then ctrl+q', 'warn'); return; }
1362
- if (this.dialogs.length) { this.flash('Answer the open question first, then quote', 'warn'); return; }
1363
- if (this.finder) this.closeFind();
1364
- this.screen.clearSelection();
1365
- const label = this.editor.insertQuote(quote.text, quote.source);
1366
- this.flash(`${label}${quote.source ? ` from ${quote.source}` : ''}: type your question below it`);
1367
- }
1368
-
1369
1530
  copyText(text) {
1370
1531
  writeClipboard(text).then((ok) => {
1371
1532
  if (ok) this.flash(`Copied ${text.length.toLocaleString()} characters to the clipboard`);
@@ -1376,30 +1537,14 @@ export class App {
1376
1537
  clipboardEditor() {
1377
1538
  const dialog = this.dialogs[0];
1378
1539
  if (dialog) return dialog.editor || dialog.other || null;
1379
- return this.finder ? null : this.editor;
1540
+ return this.editor;
1380
1541
  }
1381
1542
 
1382
- insertFindText(text) {
1383
- const f = this.finder;
1384
- const clean = String(text ?? '').replace(/[\r\n\t]+/g, ' ');
1385
- if (!f || !clean) return;
1386
- if (f.selected) {
1387
- f.text = clean;
1388
- f.cursor = clean.length;
1389
- f.selected = false;
1390
- } else {
1391
- f.text = f.text.slice(0, f.cursor) + clean + f.text.slice(f.cursor);
1392
- f.cursor += clean.length;
1393
- }
1394
- this.screen.setFind(f.text);
1395
- }
1396
-
1397
- // Pasted text into the input box, the open dialog's text field or the find box.
1543
+ // Pasted text into the input box or the open dialog's text field.
1398
1544
  insertPastedText(text, target = this.clipboardEditor()) {
1399
1545
  const clean = String(text || '').replace(/\x1b\[20[01]~/g, '');
1400
1546
  if (!clean) return;
1401
1547
  if (target) target.insertPaste(clean);
1402
- else if (this.finder) this.insertFindText(clean);
1403
1548
  this.screen.schedule();
1404
1549
  }
1405
1550
 
@@ -1407,9 +1552,8 @@ export class App {
1407
1552
  // is only done when the terminal had nothing to paste (alt+v, ctrl+v as a key, an empty bracketed paste).
1408
1553
  pasteClipboard(target = this.clipboardEditor()) {
1409
1554
  if (this.readingClipboard || this.exiting) return;
1410
- if (!target && !this.finder) return; // selection dialogs have no text field to paste into
1555
+ if (!target) return; // selection dialogs have no text field to paste into
1411
1556
  this.readingClipboard = true;
1412
- this.flash('Reading clipboard…');
1413
1557
  const allowImage = Boolean(target?.insertImage);
1414
1558
  const image = allowImage
1415
1559
  ? readClipboardImage().catch((e) => ({ image: null, error: e.message }))
@@ -1435,7 +1579,7 @@ export class App {
1435
1579
  }
1436
1580
 
1437
1581
  onKey(str, key) {
1438
- if (this.exiting) return;
1582
+ if (this.exiting || this.moving) return;
1439
1583
  // Terminals paste (ctrl+v in Windows Terminal and VS Code) as bracketed paste: readline reports paste-start/end
1440
1584
  // and emits the text as ordinary keys between them. That text goes in at once. A paste with no text is what a
1441
1585
  // terminal sends for an image on the clipboard, which only the system clipboard has (alt+v reads it on demand).
@@ -1453,57 +1597,22 @@ export class App {
1453
1597
  }
1454
1598
  return;
1455
1599
  }
1456
- if (this.screen.full) {
1457
- const half = Math.max(1, Math.floor((this.screen.lastArea || this.screen.height) / 2));
1458
- if (key.name === 'pageup') { this.screen.scrollBy(half); return; }
1459
- if (key.name === 'pagedown') { this.screen.scrollBy(-half); return; }
1460
- if (key.ctrl && key.name === 'home') { this.screen.scrollBy('top'); return; }
1461
- if (key.ctrl && key.name === 'end') { this.screen.scrollBy('bottom'); return; }
1462
- // ctrl+f looks for what is selected, if anything
1463
- if (key.ctrl && key.name === 'f' && !this.dialogs.length) {
1464
- const seed = this.screen.selection ? this.screen.selectedText() : '';
1465
- this.screen.clearSelection();
1466
- this.openFind(seed);
1467
- return;
1468
- }
1469
- // A selection: ctrl+c copies it (and does not interrupt), esc only clears it, any other key clears it and
1470
- // then does what it does.
1471
- if (this.screen.selection) {
1472
- if (key.ctrl && key.name === 'c') { this.copyText(this.screen.selectedText()); this.screen.clearSelection(); return; }
1473
- if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; }
1474
- this.screen.clearSelection();
1475
- if (key.name === 'escape') return;
1476
- }
1477
- }
1478
- // A selection in the input box (see Editor.mouse), the same way: ctrl+c copies it (and neither interrupts nor
1479
- // clears the message), esc only clears it, any other key clears it and then does what it does.
1480
- if (this.editor.selection) {
1481
- const shown = !this.dialogs.length && !this.finder; // else the box is not on screen, and the key is not for it
1482
- if (shown && key.ctrl && key.name === 'c') { this.copyText(this.editor.selectedText()); this.editor.clearSelection(); return; }
1483
- this.editor.clearSelection();
1484
- if (shown && key.name === 'escape') return;
1485
- }
1486
1600
  if (key.name === 'paste-start' || key.sequence === '\x1b[200~') {
1487
1601
  this.bracketedPaste = { raw: '' };
1488
1602
  return;
1489
1603
  }
1490
- if (key.ctrl && key.name === 'c' && this.finder && !this.dialogs.length) { this.closeFind(); return; } // not the hidden input's text
1491
1604
  if (key.ctrl && key.name === 'c') { this.onCtrlC(); return; }
1492
1605
  if ((key.ctrl || key.meta) && key.name === 'v') { this.pasteClipboard(); return; } // alt+v: the clipboard's image
1493
- if ((key.ctrl || key.meta) && key.name === 'q') { this.quoteSelection(); return; } // nothing selected: says how
1494
1606
  const dialog = this.dialogs[0];
1495
1607
  if (dialog) {
1496
1608
  dialog.handleKey(str, key);
1497
1609
  this.screen.schedule();
1498
1610
  return;
1499
1611
  }
1500
- if (key.ctrl && key.name === 'f') { this.openFind(); return; }
1501
- if (this.finder) { this.findKey(str, key); this.screen.schedule(); return; }
1502
- if (key.ctrl && key.name === 't') { this.showTodos = !this.showTodos; this.screen.schedule(); return; }
1503
- 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; }
1504
1613
  if (key.ctrl && key.name === 'd' && !this.editor.text) { this.keyboardExit(); return; }
1505
1614
  // esc closes an open completion list first (the editor does that), and only then stops the turn
1506
- if (key.name === 'escape' && this.isTurnRunning() && !this.editor.suggestions) { this.interrupt(); return; }
1615
+ if (key.name === 'escape' && this.isTurnRunning() && !this.editor.completing) { this.interrupt(); return; }
1507
1616
  this.exitArmed = 0;
1508
1617
  this.editor.handleKey(str, key);
1509
1618
  this.screen.schedule();
@@ -1616,7 +1725,6 @@ export class App {
1616
1725
  onSubmit(value, raw, images = [], display = undefined, parts = null) {
1617
1726
  const text = value.trim();
1618
1727
  if (!text) { this.screen.schedule(); return; }
1619
- if (this.screen.scrolledUp) this.screen.scrollBy('bottom'); // what was sent, and what comes of it, is in view
1620
1728
  appendHistory(this.cwd, raw, parts);
1621
1729
  if (this.sendTypedToPeer(text)) return;
1622
1730
  if (this.isTurnRunning() && !this.modelSwitchAtPause(text)) {
@@ -1639,7 +1747,7 @@ export class App {
1639
1747
  return;
1640
1748
  }
1641
1749
  if (!/^\/[\w:-]+$/.test(text.split(/\s/)[0])) { this.startTurn(value, { display }); return; } // e.g. a path like /usr/bin
1642
- this.notice(`Unknown command: /${name}. Type /help for the list of commands.`, 'warn');
1750
+ this.notice(`Unknown command: /${name}. Type / and press Tab for the list of commands, or /help.`, 'warn');
1643
1751
  return;
1644
1752
  }
1645
1753
  this.startTurn(value, { display });
@@ -1685,102 +1793,15 @@ export class App {
1685
1793
  shortcutsHelp() {
1686
1794
  const rows = [
1687
1795
  ['! for bash mode', 'double tap esc to clear input'],
1688
- ['/ for commands', '/verbose for detailed tool output'],
1689
- ['@ for files and sessions', 'ctrl + f to find in the conversation'],
1690
- ['PgUp/PgDn, wheel to scroll', 'ctrl + home/end to the top/bottom'],
1691
- ['# to memorize', 'ctrl + t to toggle todos'],
1692
- ['\\⏎ or alt+⏎ for newline', 'ctrl + l to redraw, ctrl + d to exit'],
1693
- ['ctrl + c to copy selection', 'ctrl + q to quote it in your message'],
1694
- ['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'],
1695
1801
  ];
1696
1802
  return rows.map(([a, b]) => c.dim(' ' + padEnd(a, 30) + b));
1697
1803
  }
1698
1804
 
1699
- // ---------------------------------------------------------------- finding in the conversation (ctrl+f)
1700
- //
1701
- // As in VS Code: a box takes the input box's place, the conversation shows the matches as they are typed, the
1702
- // current one apart, and goes to it. In a conversation the newest matter most: the first one shown is the
1703
- // nearest above the bottom of the view, enter (or ↑) goes on to older ones, shift+enter (or ↓) back to newer
1704
- // ones, round from either end. Esc closes the box and leaves the view where it is. The text typed last comes
1705
- // back selected (typing replaces it), or what is selected with the mouse. Fullscreen only: in the classic
1706
- // renderer the conversation is in the terminal's own scrollback.
1707
-
1708
- openFind(seed = '') {
1709
- if (!this.screen.full) { this.flash('ctrl+f needs the fullscreen view; here use the terminal\'s own find', 'warn'); return; }
1710
- if (this.finder && !seed.trim()) { this.finder.selected = Boolean(this.finder.text); this.screen.schedule(); return; } // open: select what is typed
1711
- const text = (seed.split('\n').find((l) => l.trim()) || '').trim() || this.lastFind || '';
1712
- if (!this.finder) this.screen.openFind();
1713
- this.finder = { text, cursor: text.length, selected: Boolean(text) };
1714
- this.screen.setFind(text);
1715
- this.screen.schedule();
1716
- }
1717
-
1718
- closeFind() {
1719
- if (!this.finder) return;
1720
- this.lastFind = this.finder.text;
1721
- this.finder = null;
1722
- this.screen.closeFind();
1723
- this.screen.schedule();
1724
- }
1725
-
1726
- findKey(str, key) {
1727
- const f = this.finder;
1728
- const name = key.name;
1729
- const edit = (text, cursor) => {
1730
- Object.assign(f, { text, cursor, selected: false });
1731
- this.screen.setFind(text);
1732
- };
1733
- const insert = (s) => {
1734
- const t = s.replace(/[\r\n\t]+/g, ' ');
1735
- if (!t) return;
1736
- if (f.selected) edit(t, t.length);
1737
- else edit(f.text.slice(0, f.cursor) + t + f.text.slice(f.cursor), f.cursor + t.length);
1738
- };
1739
- // a bracketed paste never gets here: App.onKey takes it whole (see insertFindText)
1740
- if (name === 'escape') { this.closeFind(); return; }
1741
- const back = (name === 'return' && (key.meta || key.shift)) || name === 'enter' || key.sequence === '\x1b[13;2u' || (name === 'f3' && key.shift);
1742
- if (back || name === 'down' || (key.ctrl && name === 'n')) { f.selected = false; this.screen.findStep(-1); return; }
1743
- if (name === 'return' || name === 'f3' || name === 'up' || (key.ctrl && name === 'p')) { f.selected = false; this.screen.findStep(1); return; }
1744
- const chars = [...f.text.slice(0, f.cursor)];
1745
- if (name === 'backspace') {
1746
- if (f.selected) edit('', 0);
1747
- else if (chars.length) { const keep = chars.slice(0, -1).join(''); edit(keep + f.text.slice(f.cursor), keep.length); }
1748
- return;
1749
- }
1750
- if (name === 'delete') {
1751
- if (f.selected) edit('', 0);
1752
- 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); }
1753
- return;
1754
- }
1755
- if (key.ctrl && name === 'u') { edit('', 0); return; }
1756
- if (name === 'left') { f.selected = false; f.cursor = chars.slice(0, -1).join('').length; return; }
1757
- if (name === 'right') { f.selected = false; f.cursor = Math.min(f.text.length, f.cursor + ([...f.text.slice(f.cursor)][0]?.length || 0)); return; }
1758
- if (name === 'home' || (key.ctrl && name === 'a')) { f.selected = false; f.cursor = 0; return; }
1759
- if (name === 'end' || (key.ctrl && name === 'e')) { f.selected = false; f.cursor = f.text.length; return; }
1760
- if (str && !key.ctrl && !key.meta && !/[\x00-\x1f\x7f]/.test(str)) insert(str);
1761
- }
1762
-
1763
- // The find box, in the input box's place: what is typed (selected: in reverse video), and how many matches.
1764
- renderFind(width) {
1765
- const f = this.finder;
1766
- const boxW = Math.max(20, width - 1);
1767
- const textW = boxW - 6;
1768
- const s = this.screen.findStatus();
1769
- const count = !f.text ? '' : s?.total ? `${s.index + 1}/${s.total}` : c.red('No results');
1770
- const title = { left: 'Find in the conversation', right: count };
1771
- // the part of the text that fits, the cursor in it
1772
- let before = f.text.slice(0, f.cursor);
1773
- while (before && stringWidth(before) > textW - 1) before = [...before].slice(1).join('');
1774
- const shown = truncate(before + f.text.slice(f.cursor), textW, '');
1775
- const content = f.selected && shown ? c.inverse(shown) : shown;
1776
- const lines = [
1777
- topBorder(boxW, c.yellow, title),
1778
- c.yellow('│') + ' ' + c.yellow(glyphs.find) + ' ' + padEnd(content, textW) + ' ' + c.yellow('│'),
1779
- c.yellow(glyphs.bottomLeft + '─'.repeat(boxW - 2) + glyphs.bottomRight),
1780
- ];
1781
- return { lines, cursor: { row: 1, col: 4 + stringWidth(before) } };
1782
- }
1783
-
1784
1805
  // ---------------------------------------------------------------- turns
1785
1806
 
1786
1807
  // Where a mentioned path is (null when there is no such file): relative to the project root, which is
@@ -1888,7 +1909,8 @@ export class App {
1888
1909
 
1889
1910
  // What `@name` in a message the user wrote stands for, told to the model: which session, and how to reach it.
1890
1911
  async peerMentions(prompt) {
1891
- const refs = [...new Set([...String(prompt).matchAll(/(?:^|\s)@([^\s@"&,。;;::!!??、))]+)/gu)].map((m) => m[1]))];
1912
+ // (a colon inside is a contact's session, yzc:computer/name; one at the end is punctuation)
1913
+ const refs = [...new Set([...String(prompt).matchAll(/(?:^|\s)@([^\s@"&,。;;:!!??、))]+)/gu)].map((m) => m[1].replace(/:+$/, '')).filter(Boolean))];
1892
1914
  if (!refs.length) return [];
1893
1915
  const local = this.peers?.peers() || [];
1894
1916
  const notes = [];
@@ -1896,22 +1918,39 @@ export class App {
1896
1918
  let found = resolvePeer(local, this.remotePeers, ref, { ids: false });
1897
1919
  if (!found.peer && !found.ambiguous && this.remote) found = resolvePeer(local, await this.refreshRemotePeers(), ref, { ids: false });
1898
1920
  const p = found.peer;
1899
- 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}`);
1921
+ if (p?.contact) notes.push(`@${ref} is the claude-pro session "${p.label}" of the contact "${p.account}", another person (not the user)`);
1922
+ else 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}`);
1900
1923
  else if (found.ambiguous) notes.push(found.error);
1901
1924
  }
1902
1925
  if (!notes.length) return [];
1903
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>` }];
1904
1927
  }
1905
1928
 
1906
- // A short-lived message in the footer (not written to the transcript).
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.
1907
1948
  flash(text, kind = 'info') {
1908
- this.flashMessage = { text, kind, until: Date.now() + 4000 };
1909
- this.screen.schedule();
1910
- clearTimeout(this.flashTimer);
1911
- this.flashTimer = setTimeout(() => this.screen.schedule(), 4100);
1949
+ this.notice(text, kind);
1912
1950
  }
1913
1951
 
1914
1952
  async runAgent(content, { peers = [] } = {}) {
1953
+ this.used = true; // (see inUse)
1915
1954
  this.turnStarting = false;
1916
1955
  this.busy = true;
1917
1956
  this.turnPeers.push(...peers);
@@ -1920,6 +1959,7 @@ export class App {
1920
1959
  this.controller = new AbortController();
1921
1960
  this.turnStart = Date.now();
1922
1961
  this.turnTokens = 0;
1962
+ this.turnCostStart = this.cost;
1923
1963
  this.verb = VERBS[Math.floor(Math.random() * VERBS.length)];
1924
1964
  this.screen.schedule();
1925
1965
  try {
@@ -1941,6 +1981,9 @@ export class App {
1941
1981
  } finally {
1942
1982
  this.flushStreaming();
1943
1983
  this.flushActive(true);
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(), '');
1944
1987
  this.answerPeers(result, error);
1945
1988
  this.busy = false;
1946
1989
  this.controller = null;
@@ -2057,10 +2100,11 @@ export class App {
2057
2100
 
2058
2101
  // `quiet`: do not print the transcript (a restart: it is still on screen).
2059
2102
  loadSession(file, id, { quiet = false } = {}) {
2060
- const loaded = SessionStore.load(file);
2103
+ const loaded = this.runtime.useSession(id, () => SessionStore.load(file));
2061
2104
  this.previousSession = null; // the conversation before a /clear: resuming another one ends the offer
2062
2105
  this.seedOutput = [];
2063
2106
  this.store = new SessionStore(this.cwd, id);
2107
+ this.store.onError = this.storeError;
2064
2108
  this.runtime.trace?.setSessionId(id);
2065
2109
  this.topic = loaded.topic;
2066
2110
  this.customTitle = loaded.name;
@@ -2081,9 +2125,11 @@ export class App {
2081
2125
  this.store.systemPrompt = loaded.systemPrompt;
2082
2126
  this.runtime.resumeSystemPrompt(loaded.systemPrompt, loaded.promptCode);
2083
2127
  // Its cache still warm (a restart, a quick resume): it goes on being refreshed while idle (keepalive.js).
2084
- this.agent.restoreCacheState(loaded.cacheState);
2085
- if (!this.topic) this.refreshTopic(this.latestPrompt()); // a session from before topics were kept
2086
- this.remote?.resync();
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();
2087
2133
  if (quiet) return;
2088
2134
  const restoredCount = loaded.messages.length;
2089
2135
  const shown = loaded.messages.slice(-30);
@@ -2119,14 +2165,17 @@ export class App {
2119
2165
  }
2120
2166
 
2121
2167
  newSession() {
2122
- this.store = new SessionStore(this.cwd);
2168
+ const store = new SessionStore(this.cwd);
2169
+ this.runtime.useSession(store.id);
2170
+ this.store = store;
2171
+ this.store.onError = this.storeError;
2123
2172
  this.runtime.trace?.setSessionId(this.store.id);
2124
2173
  this.seedOutput = [];
2125
2174
  this.topic = null;
2126
2175
  this.customTitle = null;
2127
2176
  this.firstPrompt = null;
2128
2177
  this.cost = 0;
2129
- this.remote?.resync();
2178
+ this.liveFeed.resync();
2130
2179
  }
2131
2180
 
2132
2181
  // ---------------------------------------------------------------- dialogs
@@ -2170,9 +2219,9 @@ export class App {
2170
2219
  if (ev.block.type === 'text') {
2171
2220
  this.flushThinking();
2172
2221
  this.md = new MarkdownStream({ width: w, firstPrefix: `${DOT} `, indent: ' ' });
2173
- this.remote?.emit({ t: 'start', kind: 'text' });
2222
+ this.emitEvent({ t: 'start', kind: 'text' });
2174
2223
  } else if (ev.block.type === 'thinking') {
2175
- this.remote?.emit({ t: 'start', kind: 'thinking' });
2224
+ this.emitEvent({ t: 'start', kind: 'thinking' });
2176
2225
  this.thinking = new MarkdownStream({ width: w, firstPrefix: c.dim('✻ '), indent: ' ', style: (s) => c.dim(c.italic(s)) });
2177
2226
  } else if (ev.block.type === 'tool_use') {
2178
2227
  this.flushThinking();
@@ -2184,13 +2233,13 @@ export class App {
2184
2233
  if (this.md) {
2185
2234
  const lines = this.md.write(ev.text);
2186
2235
  if (lines.length) this.logLocal({ soon: true }, lines);
2187
- this.remote?.emit({ t: 'delta', kind: 'text', text: ev.text });
2236
+ this.emitEvent({ t: 'delta', kind: 'text', text: ev.text });
2188
2237
  }
2189
2238
  break;
2190
2239
  case 'thinking':
2191
2240
  this.turnTokens += estimateTokens(ev.text);
2192
2241
  if (this.thinking) {
2193
- this.remote?.emit({ t: 'delta', kind: 'thinking', text: ev.text });
2242
+ this.emitEvent({ t: 'delta', kind: 'thinking', text: ev.text });
2194
2243
  const lines = this.thinking.write(ev.text);
2195
2244
  if (lines.length) this.logLocal({ soon: true }, lines);
2196
2245
  }
@@ -2207,7 +2256,7 @@ export class App {
2207
2256
  if (lines.length) this.logLocal(lines);
2208
2257
  this.logLocal('');
2209
2258
  this.md = null;
2210
- this.remote?.emit({ t: 'stop' });
2259
+ this.emitEvent({ t: 'stop' });
2211
2260
  } else if (ev.block.type === 'thinking') {
2212
2261
  this.flushThinking();
2213
2262
  } else if (ev.block.type === 'tool_use') {
@@ -2222,7 +2271,7 @@ export class App {
2222
2271
  this.rateLimitEvent(ev);
2223
2272
  break;
2224
2273
  case 'reset':
2225
- if (this.md || this.thinking) this.remote?.emit({ t: 'stop' });
2274
+ if (this.md || this.thinking) this.emitEvent({ t: 'stop' });
2226
2275
  this.md = null;
2227
2276
  this.thinking = null;
2228
2277
  this.pendingToolBlocks.clear();
@@ -2251,7 +2300,7 @@ export class App {
2251
2300
  const t = this.thinking;
2252
2301
  if (!t) return;
2253
2302
  this.thinking = null;
2254
- this.remote?.emit({ t: 'stop' });
2303
+ this.emitEvent({ t: 'stop' });
2255
2304
  const lines = t.end();
2256
2305
  if (lines.length) this.logLocal(lines);
2257
2306
  if (t.emittedAny) this.logLocal('');
@@ -2263,7 +2312,7 @@ export class App {
2263
2312
  const lines = this.md.end();
2264
2313
  if (lines.length) this.logLocal(lines, '');
2265
2314
  this.md = null;
2266
- this.remote?.emit({ t: 'stop' });
2315
+ this.emitEvent({ t: 'stop' });
2267
2316
  }
2268
2317
  this.pendingToolBlocks.clear();
2269
2318
  }
@@ -2276,13 +2325,13 @@ export class App {
2276
2325
  if (!this.isMain(agent)) return {};
2277
2326
  const entry = { tu, tool, input, status: 'running', progress: '', sub: [], subCount: 0, ctx: agent.makeCtx(), started: Date.now() };
2278
2327
  this.active.push(entry);
2279
- this.remote?.emit({ t: 'tool', id: tu.id, head: toolHeader(tool, input, entry.ctx, { width: REMOTE_WIDTH, dot: false }) });
2328
+ this.emitEvent({ t: 'tool', id: tu.id, head: toolHeader(tool, input, entry.ctx, { width: REMOTE_WIDTH, dot: false }) });
2280
2329
  this.screen.schedule();
2281
2330
  return {
2282
2331
  progress: (p, meta) => {
2283
2332
  // `all`: the whole output so far (the progress is its end), for the page's "the whole output"
2284
- if (typeof p === 'string') { entry.progress = p; entry.progressLines = meta?.lines; entry.progressAll = meta?.all; this.remote?.toolProgress(tu.id, entry); }
2285
- else if (p?.type === 'subtool') { entry.sub.push(p.header); entry.subCount++; this.remote?.emit({ t: 'sub', id: tu.id, head: p.header }); }
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 }); }
2286
2335
  this.screen.schedule();
2287
2336
  },
2288
2337
  done: (result) => {
@@ -2298,20 +2347,60 @@ export class App {
2298
2347
  if (!this.isMain(agent)) return;
2299
2348
  const ctx = agent.makeCtx();
2300
2349
  const entry = { tu, tool, input: tu.input, status: 'rejected', rejected: true, rejectMessage: message, ctx };
2301
- if (this.remote) {
2302
- this.remote.emit({ t: 'tool', id: tu.id, head: toolHeader(tool, tu.input, ctx, { width: REMOTE_WIDTH, dot: false }) });
2350
+ if (this.liveFeed.active) {
2351
+ this.emitEvent({ t: 'tool', id: tu.id, head: toolHeader(tool, tu.input, ctx, { width: REMOTE_WIDTH, dot: false }) });
2303
2352
  this.remoteToolDone(entry);
2304
2353
  }
2305
2354
  this.logLocal(toolHeader(tool, tu.input, ctx, { status: 'rejected', width: this.width }), renderToolResult(entry, { width: this.width, cwd: this.cwd }), '');
2306
2355
  }
2307
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
+
2308
2397
  // A tool call finished (or was refused, or interrupted): its result on the remote page, once.
2309
2398
  remoteToolDone(entry) {
2310
- if (!this.remote || !entry.tu?.id || entry.remoteDone) return;
2399
+ if (!this.liveFeed.active || !entry.tu?.id || entry.remoteDone) return;
2311
2400
  entry.remoteDone = true;
2312
2401
  let lines = [];
2313
2402
  try { lines = renderToolResult(entry, { width: REMOTE_WIDTH, cwd: this.cwd }); } catch { /* shown without */ }
2314
- this.remote.emit({ t: 'done', id: entry.tu.id, status: entry.result?.isError || entry.rejected ? 'error' : 'done', lines });
2403
+ this.emitEvent({ t: 'done', id: entry.tu.id, status: entry.result?.isError || entry.rejected ? 'error' : 'done', lines });
2315
2404
  }
2316
2405
 
2317
2406
  // Move finished tool entries (in call order) from the live region to the transcript.
@@ -2488,8 +2577,6 @@ export class App {
2488
2577
  if (!this.dialogs.length) {
2489
2578
  if (lines.length) lines.push('');
2490
2579
  lines.push(this.spinnerLine());
2491
- const todos = this.agent.todos;
2492
- if (this.showTodos && todos.length) lines.push(...renderTodos(todos).map((l) => truncate(l, w)));
2493
2580
  }
2494
2581
  } else if (this.active.length) {
2495
2582
  for (const e of this.active) lines.push(...this.renderActiveEntry(e, w));
@@ -2507,93 +2594,27 @@ export class App {
2507
2594
  }
2508
2595
  if (lines.length) lines.push('');
2509
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"');
2510
- const after = this.finder ? [c.dim(truncate(' ⏎ or ↑ older · shift+⏎ or ↓ newer · PgUp/PgDn scroll · esc to close', w))]
2511
- : this.editor.suggestions ? this.editor.renderSuggestions(w)
2512
- : this.editor.text === '?' ? this.shortcutsHelp()
2513
- : [this.footer(w)];
2514
- // the box's text gets the screen less what is above and below it, its borders, and two rows of the conversation
2515
- const maxRows = Math.max(3, this.screen.height - 1 - lines.length - after.length - 2 - 2);
2516
- 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 });
2517
2602
  const top = lines.length;
2518
2603
  lines.push(...r.lines);
2519
2604
  if (r.cursor) cursor = { row: top + r.cursor.row, col: r.cursor.col };
2520
- const input = r.text ? { ...r.text, row: top + r.text.row } : null; // where the mouse reaches the input box's text
2521
2605
  lines.push(...after);
2522
- return { lines, cursor, input };
2523
- }
2524
-
2525
- // In the input box's top border: the directory the agent is in now (a `cd` moves it), and this
2526
- // session's name for the other sessions.
2527
- boxTitle() {
2528
- const dir = this.agent?.cwd || this.cwd;
2529
- const home = os.homedir();
2530
- const shown = dir.toLowerCase().startsWith(home.toLowerCase()) ? '~' + dir.slice(home.length) : dir;
2531
- const name = this.peers || this.remote ? `@${this.peerLabel()}` : '';
2532
- return { left: shown.replace(/\\/g, '/'), right: name && this.remote?.online ? `⇄ ${name}` : name };
2533
- }
2534
-
2535
- // The prompt cache clock, as in Claude Code's VS Code extension: the minutes the conversation's cache has left
2536
- // ("◷ 12m"), or the icon alone in red once it has run out or right after a compaction, until the next response:
2537
- // the next message then writes the whole conversation to the cache again. Nothing before a response reported
2538
- // cache use.
2539
- cacheClock() {
2540
- const clock = this.agent?.cache.clock();
2541
- return !clock ? '' : clock.cold ? c.red(glyphs.clock) : c.dim(`${glyphs.clock} ${clock.minutes}m`);
2542
- }
2543
-
2544
- footer(w) {
2545
- let left;
2546
- const flash = this.flashMessage && Date.now() < this.flashMessage.until ? this.flashMessage : null;
2547
- if (this.exitArmed && Date.now() - this.exitArmed < 1500) left = c.dim(' Press Ctrl-C again to exit');
2548
- else if (flash) left = (flash.kind === 'warn' ? c.yellow : c.dim)(' ' + truncate(flash.text, w - 4));
2549
- else if (this.screen.full && this.screen.selection) left = c.dim(' ctrl+c to copy · ctrl+q to quote it in your message');
2550
- else if (this.editor.selection) left = c.dim(' ctrl+c to copy · esc to clear');
2551
- else if (this.restartRequest) left = c.dim(` ${glyphs.restart} restarting when this turn ends`);
2552
- else if (this.editor.mode === 'bash') left = c.magenta(' ! for bash mode');
2553
- else if (this.editor.mode === 'memory') left = c.blue(' # to memorize');
2554
- else left = c.dim(' ? for shortcuts');
2555
- if (this.remote?.online && this.remote.viewers && !flash && !(this.exitArmed && Date.now() - this.exitArmed < 1500)) {
2556
- left += c.dim(' · ') + c.green(`⇄ ${this.remote.viewers} watching`);
2557
- }
2558
- if (!flash) {
2559
- if (this.updating) left += c.dim(' · ') + c.blue(`${glyphs.update} updating ${APP_NAME} to ${this.updating}…`);
2560
- 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'}`);
2561
- 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)`);
2562
- 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'}`);
2563
- }
2564
- const cfg = this.config;
2565
- const threshold = cfg.compactWindow();
2566
- const used = this.agent.contextEstimate;
2567
- let notice = '';
2568
- const pctLeft = Math.max(0, Math.round((1 - used / threshold) * 100));
2569
- if (pctLeft <= 30) notice = c.yellow(`Context left until auto-compact: ${pctLeft}%`);
2570
- 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`);
2571
- else if (this.verbose) notice = c.dim('verbose');
2572
- // The model and effort in use always have a place at the right: with the notice after it when both fit,
2573
- // and the notice alone when they do not (a context warning matters more than the model's name).
2574
- const { model, effort } = modelInfo(cfg);
2575
- // An effort that is not set is not sent: the API then uses the model's default, which is shown instead.
2576
- const level = effort || defaultEffort(cfg.model.id, cfg);
2577
- const info = c.dim(level ? `${model} · ${level}` : model);
2578
- const version = c.dim(`v${VERSION}`);
2579
- const compactTokens = (n) => formatTokens(n).replace(/\.0([kM])$/, '$1');
2580
- const context = c.dim(`ctx ${compactTokens(used)}/${compactTokens(cfg.model.contextWindow)}`);
2581
- // Before the context, version and model: the prompt cache clock, then what the conversation has cost so far;
2582
- // when room is short the cost goes first, then the clock.
2583
- const spent = this.cost > 0 ? c.dim(formatUsd(this.cost)) : '';
2584
- const clock = this.cacheClock();
2585
- const join = (...parts) => parts.filter(Boolean).join(c.dim(' · '));
2586
- const room = w - stringWidth(left) - 1;
2587
- const right = [
2588
- join(notice, clock, spent, context, version, info),
2589
- join(notice, clock, context, version, info),
2590
- join(notice, context, version, info),
2591
- join(notice, context, version),
2592
- join(notice, version),
2593
- version,
2594
- ].find((r) => r && stringWidth(r) < room) || '';
2595
- const gap = room - stringWidth(right);
2596
- 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 '';
2597
2618
  }
2598
2619
  }
2599
2620