townmouse 0.2.1 → 0.4.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +72 -2
  2. package/DESIGN.md +26 -42
  3. package/README.md +286 -54
  4. package/SECURITY.md +3 -0
  5. package/TOWNMOUSE.md +1 -1
  6. package/bin/townmouse +2 -2
  7. package/docs/PACKAGING.md +104 -8
  8. package/docs/browser-workspace.md +62 -9
  9. package/docs/panes.md +199 -9
  10. package/native/TownmouseApp.swift +5 -5
  11. package/npm-shrinkwrap.json +1282 -0
  12. package/package.json +11 -7
  13. package/public/browser-picture.mjs +159 -0
  14. package/public/features/app-version.mjs +35 -0
  15. package/public/features/autosave.mjs +5 -1
  16. package/public/features/multi-window-sync.mjs +3 -1
  17. package/public/features/osc-bridge.mjs +8 -3
  18. package/public/features/session-manager.mjs +202 -100
  19. package/public/features/status-metrics.mjs +23 -0
  20. package/public/features/tab-reorder.mjs +8 -0
  21. package/public/features/window-title.mjs +10 -3
  22. package/public/index.html +617 -78
  23. package/public/input-guard.mjs +10 -2
  24. package/public/panes.css +189 -13
  25. package/public/panes.html +4 -1
  26. package/public/panes.mjs +667 -109
  27. package/public/workspace.css +198 -24
  28. package/public/workspace.mjs +346 -106
  29. package/scripts/install-service.sh +97 -63
  30. package/scripts/panes +134 -5
  31. package/scripts/retire-legacy-service.sh +76 -0
  32. package/scripts/{t1.sh → townmouse.sh} +60 -21
  33. package/scripts/uninstall-service.sh +31 -15
  34. package/src/agent-guide.js +72 -3
  35. package/src/attachments.js +2 -2
  36. package/src/browser-dom.js +5 -2
  37. package/src/browser-workspace.js +549 -62
  38. package/src/owner-page.js +43 -0
  39. package/src/request-boundary.js +1 -1
  40. package/src/server.js +588 -128
  41. package/src/workspace-panes.js +423 -91
@@ -1,3 +1,5 @@
1
+ import { createViewedWatch, createPictureLoop } from '/browser-picture.mjs';
2
+
1
3
  const icons = {
2
4
  terminal: 'M4 5l6 7-6 7M13 19h7',
3
5
  browser: 'M3 7h18M7 4v3M3 4h18v16H3z',
@@ -27,6 +29,7 @@ const icons = {
27
29
  sync: 'M4 12a8 8 0 0 1 14-5M20 12a8 8 0 0 1-14 5M18 3v4h-4M6 21v-4h4',
28
30
  dot: 'M12 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4z',
29
31
  session: 'M4 5h16v14H4zM8 5v14M12 9h4M12 13h4',
32
+ edit: 'M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z',
30
33
  split: 'M4 4h16v16H4zM12 4v16M8 8h1m-1 4h1m-1 4h1'
31
34
  };
32
35
  const icon = (name) => '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="' + icons[name] + '"/></svg>';
@@ -184,17 +187,20 @@ export async function init(T1) {
184
187
  sessionMenu.setAttribute('aria-label', 'Terminal sessions');
185
188
  sessionMenu.innerHTML =
186
189
  '<header><div><small>Terminal sessions</small><h2>Sessions</h2></div><button id="session-menu-close" type="button">Done</button></header>' +
187
- '<div id="session-menu-list" class="drawer-list"></div>' +
188
- '<button id="session-menu-new" type="button" class="drawer-row">' + icon('plus') + '<span class="drawer-row-copy"><span class="drawer-row-name">New session</span><span class="drawer-row-desc">Start another shell</span></span></button>';
190
+ '<p class="session-menu-count" id="session-menu-count" role="status"></p>' +
191
+ '<div id="session-menu-list" class="drawer-list" role="list" aria-label="Shells"></div>' +
192
+ '<button id="session-menu-new" type="button" class="drawer-row">' + icon('plus') + '<span class="drawer-row-copy" data-desc="Start another shell"><span class="drawer-row-name">New session</span></span></button>';
189
193
  body.append(sessionMenu);
190
194
 
195
+ // One confirmation for every close, from a chip, from the Sessions list or
196
+ // from Tools. It names the shell and says what happens next.
191
197
  const closeConfirm = document.createElement('dialog');
192
198
  closeConfirm.className = 'workspace-drawer workspace-confirm';
193
199
  closeConfirm.id = 'close-confirm';
194
- closeConfirm.setAttribute('aria-label', 'Close terminal?');
200
+ closeConfirm.setAttribute('aria-labelledby', 'close-confirm-title');
195
201
  closeConfirm.innerHTML =
196
- '<header><div><small>Session</small><h2>Close terminal?</h2></div></header>' +
197
- '<p>This ends the shell and clears the saved session on this page.</p>' +
202
+ '<header><div><small>Session</small><h2 id="close-confirm-title">Close terminal?</h2></div></header>' +
203
+ '<p id="close-confirm-text"></p>' +
198
204
  '<div class="confirm-actions"><button id="close-confirm-cancel" type="button">Cancel</button><button id="close-confirm-close" type="button" class="danger">Close terminal</button></div>';
199
205
  body.append(closeConfirm);
200
206
 
@@ -249,8 +255,9 @@ export async function init(T1) {
249
255
  newSessionRow.setAttribute('aria-label', 'New session. Start another shell.');
250
256
  newSessionRow.innerHTML = icon('plus') + '<span class="drawer-row-copy"><span class="drawer-row-name">New session</span><span class="drawer-row-desc">Start another shell</span></span>';
251
257
  newSessionRow.addEventListener('click', () => {
252
- const plus = document.querySelector('.t1session-new');
253
- if (plus) plus.click();
258
+ // The same guarded action the header's + uses: at the session limit it
259
+ // opens the Sessions list instead of starting one.
260
+ window.__terminalOne?.requestNewSession?.();
254
261
  });
255
262
  $('drawer-session').prepend(newSessionRow);
256
263
 
@@ -337,15 +344,35 @@ export async function init(T1) {
337
344
  $('tool-empty').hidden = matches > 0 || !value;
338
345
  }
339
346
 
340
- // ── Session identity and visible reconnect ─────────────────────────────────
347
+ // ── Sessions: the pill, the list and the confirmation ─────────────────────
348
+ // All three read one thing, the server's list, which the page script keeps
349
+ // and announces as `t1:session-ready` and `t1:sessions-change`. None of them
350
+ // keeps a list of its own. An earlier version did (session names in
351
+ // localStorage), which is how chips for ended shells came to stay.
341
352
  const statusWrap = header.querySelector('.statuswrap');
353
+ const sessionApi = () => window.__terminalOne || {};
354
+ const sessionsNow = () => sessionApi().sessions?.() || [];
355
+ const sessionViewNow = () => sessionApi().sessionView?.() || { state: 'connecting', current: null, max: 0, known: false };
356
+
342
357
  const sessionPill = document.createElement('button');
343
358
  sessionPill.type = 'button';
344
359
  sessionPill.className = 'workspace-session-pill';
345
360
  sessionPill.id = 'workspace-session-pill';
346
361
  sessionPill.setAttribute('aria-haspopup', 'dialog');
362
+ sessionPill.setAttribute('aria-controls', 'session-menu');
363
+ sessionPill.setAttribute('aria-expanded', 'false');
347
364
  sessionPill.setAttribute('aria-label', 'Sessions');
348
- sessionPill.hidden = true;
365
+ // The label is its own element so a long one is cut with an ellipsis while
366
+ // the chevron that says "this opens a list" stays in view. The folder is a
367
+ // separate span: it is the first thing the header gives up.
368
+ const sessionPillLabel = document.createElement('span');
369
+ sessionPillLabel.className = 'workspace-session-pill-label';
370
+ const sessionPillName = document.createElement('span');
371
+ sessionPillName.className = 'workspace-session-pill-name';
372
+ const sessionPillFolder = document.createElement('span');
373
+ sessionPillFolder.className = 'workspace-session-pill-folder';
374
+ sessionPillLabel.append(sessionPillName, sessionPillFolder);
375
+ sessionPill.append(sessionPillLabel);
349
376
  header.insertBefore(sessionPill, statusWrap);
350
377
 
351
378
  const reconnect = document.createElement('button');
@@ -356,100 +383,283 @@ export async function init(T1) {
356
383
  reconnect.hidden = true;
357
384
  header.insertBefore(reconnect, statusWrap);
358
385
 
359
- function updateSessionPill() {
360
- const footer = $('footerMeta')?.textContent || '';
361
- const session = $('sessionInfo')?.textContent || '';
362
- const cwdMatch = footer.match(/·\s*(.+?)(?:\s*·|$)/);
363
- const cwd = cwdMatch ? cwdMatch[1].trim() : '';
364
- const base = cwd.split('/').filter(Boolean).pop();
365
- const idMatch = session.match(/session\s+([a-f0-9-]+)/i);
366
- const fullId = $('sessionInfo')?.dataset.sessionId || '';
367
- const sessionId = fullId || (idMatch ? idMatch[1] : '');
368
- sessionPill.textContent = base ? 'Shell · ' + base : 'Shell';
369
- sessionPill.title = sessionId ? 'Session ' + sessionId : 'Shell session';
370
- sessionPill.setAttribute('aria-label', 'Sessions. ' + (base ? 'Shell · ' + base : 'Shell'));
371
- sessionPill.hidden = false;
372
- if (sessionId) {
373
- const names = window.__terminalOne?.sessionNames?.() || {};
374
- if (!names[sessionId]) window.__terminalOne?.renameSession?.(sessionId, sessionId.slice(0, 8));
375
- }
386
+ const baseName = (value) => String(value || '').split('/').filter(Boolean).pop() || '';
387
+ function ago(from) {
388
+ const ms = from ? Date.now() - from : 0;
389
+ if (!from || ms < 60_000) return 'just now';
390
+ if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ago`;
391
+ if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)}h ago`;
392
+ return `${Math.floor(ms / 86_400_000)}d ago`;
393
+ }
394
+
395
+ // The pill names the shell this window is in and opens the list.
396
+ function renderSessionPill() {
397
+ const view = sessionViewNow();
398
+ const current = view.state === 'live' ? view.current : null;
399
+ const name = current?.name || '';
400
+ const folder = current?.cwd ? baseName(current.cwd) : '';
401
+ sessionPillName.textContent = name || (view.state === 'ended' ? 'Sessions' : 'Shell');
402
+ sessionPillFolder.textContent = name && folder ? ` · ${folder}` : '';
403
+ sessionPill.title = name
404
+ ? `Sessions. Current shell: ${name}${current?.cwd ? ` (${current.cwd})` : ''}`
405
+ : 'Sessions';
406
+ sessionPill.setAttribute('aria-label', name ? `Sessions. Current shell: ${name}` : 'Sessions');
407
+ }
408
+
409
+ function iconButton(name, label, part, run) {
410
+ const button = document.createElement('button');
411
+ button.type = 'button';
412
+ button.className = `session-row-action session-row-${part}`;
413
+ button.dataset.part = part;
414
+ button.setAttribute('aria-label', label);
415
+ button.title = label;
416
+ button.innerHTML = icon(name);
417
+ button.addEventListener('click', run);
418
+ return button;
376
419
  }
377
420
 
378
- async function renderSessionMenu() {
421
+ function renderSessionMenu() {
379
422
  const list = $('session-menu-list');
423
+ const view = sessionViewNow();
424
+ const sessions = sessionsNow();
425
+ const currentId = view.current?.id || '';
426
+ // A row being renamed keeps its input; its rename redraws the list.
427
+ if (list.querySelector('.session-row.renaming')) return;
428
+ const focusedRow = document.activeElement?.closest?.('.session-row');
429
+ const focusKey = focusedRow
430
+ ? { id: focusedRow.dataset.sessionId, part: document.activeElement.dataset.part || 'main' }
431
+ : null;
380
432
  list.innerHTML = '';
381
- const current = $('sessionInfo')?.dataset.sessionId || (($('sessionInfo')?.textContent || '').match(/session\s+([a-f0-9-]+)/i) || [])[1] || '';
382
- const names = window.__terminalOne?.sessionNames?.() || {};
383
- const sessions = new Map();
384
- try {
385
- const response = await fetch('/admin/sessions', { cache: 'no-store' });
386
- if (response.ok) {
387
- const body = await response.json();
388
- for (const session of body.sessions || []) sessions.set(session.id, session);
389
- }
390
- } catch (_) { /* the current session still renders below */ }
391
- if (current) sessions.set(current, sessions.get(current) || { id: current });
392
- let added = 0;
393
- for (const [id, info] of sessions) {
394
- const name = names[id] || id.slice(0, 8);
395
- const active = id === current;
396
- const row = document.createElement('button');
397
- row.type = 'button';
398
- row.className = 'drawer-row' + (active ? ' active' : '');
399
- const detail = active ? 'Current session' : (info.resumable === false ? 'Attached shell' : 'Switch to this session');
400
- row.innerHTML = icon('session') + '<span class="drawer-row-copy"><span class="drawer-row-name">' + escapeHtml(name) + '</span><span class="drawer-row-desc">' + detail + '</span></span>';
401
- row.onclick = () => {
433
+ for (const session of sessions) {
434
+ const current = session.id === currentId;
435
+ // The folder by name; the whole path is in the tooltip. A row is narrow.
436
+ const facts = [
437
+ session.createdBy === 'agent' ? 'started by agent' : '',
438
+ session.cwd ? baseName(session.cwd) : '',
439
+ `started ${ago(session.createdAt)}`
440
+ ].filter(Boolean).join(' · ');
441
+ const row = document.createElement('div');
442
+ row.className = 'session-row' + (current ? ' active' : '');
443
+ row.dataset.sessionId = session.id;
444
+ row.setAttribute('role', 'listitem');
445
+ const main = document.createElement('button');
446
+ main.type = 'button';
447
+ main.className = 'drawer-row session-row-main' + (current ? ' active' : '');
448
+ main.dataset.part = 'main';
449
+ if (current) main.setAttribute('aria-current', 'true');
450
+ main.setAttribute('aria-label', `${session.name}. ${current ? 'Current session' : 'Switch to this session'}`);
451
+ if (session.cwd) main.title = session.cwd;
452
+ main.innerHTML = icon('session') + '<span class="drawer-row-copy"><span class="drawer-row-name session-row-name"></span></span>';
453
+ main.querySelector('.session-row-name').textContent = session.name;
454
+ main.querySelector('.drawer-row-copy').dataset.desc = current
455
+ ? (facts ? `Current session · ${facts}` : 'Current session')
456
+ : facts || 'Switch to this session';
457
+ main.addEventListener('click', () => {
402
458
  sessionMenu.close();
403
- if (!active) window.__terminalOne?.switchSession?.(id);
404
- };
459
+ sessionApi().switchSession?.(session.id);
460
+ });
461
+ row.append(
462
+ main,
463
+ iconButton('edit', `Rename ${session.name}`, 'rename', () => startRename(row, session)),
464
+ // The list is left open here so the confirmation knows to come back
465
+ // to it afterwards.
466
+ iconButton('close', `Close ${session.name}`, 'close', () => requestClose(session.id))
467
+ );
405
468
  list.append(row);
406
- added += 1;
407
469
  }
408
- if (!added) {
409
- const row = document.createElement('div');
410
- row.className = 'drawer-row';
411
- row.innerHTML = icon('session') + '<span class="drawer-row-copy"><span class="drawer-row-name">Current shell</span><span class="drawer-row-desc">One session</span></span>';
412
- list.append(row);
470
+ if (!sessions.length) {
471
+ const empty = document.createElement('p');
472
+ empty.className = 'session-menu-empty';
473
+ empty.textContent = view.state === 'ended'
474
+ ? 'No shell is open. Start one below.'
475
+ : 'No shell is open besides this one.';
476
+ list.append(empty);
477
+ }
478
+ // The limit is stated where the person would hit it.
479
+ const max = view.max || 0;
480
+ const atLimit = Boolean(max && sessions.length >= max);
481
+ $('session-menu-count').textContent = max
482
+ ? (atLimit ? `All ${max} sessions are in use` : `${sessions.length} of ${max} sessions in use`)
483
+ : '';
484
+ $('session-menu-new').disabled = atLimit;
485
+ $('session-menu-new').querySelector('.drawer-row-copy').dataset.desc = atLimit
486
+ ? 'Close a session above to start another'
487
+ : 'Start another shell';
488
+ if (focusKey) {
489
+ const row = list.querySelector(`.session-row[data-session-id="${focusKey.id}"]`);
490
+ const target = row?.querySelector(`[data-part="${focusKey.part}"]`) || list.querySelector('.session-row [data-part="main"]');
491
+ target?.focus({ preventScroll: true });
413
492
  }
414
493
  }
415
494
 
416
- sessionPill.addEventListener('click', () => {
417
- dockTrigger = sessionPill;
418
- void renderSessionMenu().finally(() => {
419
- closeOtherDocks(sessionMenu);
420
- if (!sessionMenu.open) sessionMenu.show();
421
- sessionMenu.querySelector('.drawer-row')?.focus();
495
+ // A name is edited in the row itself: Enter saves, Escape or leaving keeps
496
+ // the old one. The name is kept by the server, so every window sees it.
497
+ function startRename(row, session) {
498
+ if (row.classList.contains('renaming')) return;
499
+ const main = row.querySelector('.session-row-main');
500
+ const name = main.querySelector('.drawer-row-name');
501
+ const copy = main.querySelector('.drawer-row-copy');
502
+ const before = name.textContent;
503
+ const described = copy.dataset.desc;
504
+ const restore = (refocus = false) => {
505
+ row.classList.remove('renaming');
506
+ name.textContent = before;
507
+ copy.dataset.desc = described;
508
+ // After Escape the keyboard goes back to the row's control. After a
509
+ // click elsewhere it stays where the person put it.
510
+ if (refocus && row.isConnected) row.querySelector('.session-row-rename')?.focus({ preventScroll: true });
511
+ };
512
+ row.classList.add('renaming');
513
+ copy.dataset.desc = 'Enter saves · Escape keeps the old name';
514
+ name.textContent = '';
515
+ const input = document.createElement('input');
516
+ input.type = 'text';
517
+ input.className = 'session-row-input';
518
+ input.value = before;
519
+ input.maxLength = 40;
520
+ input.autocomplete = 'off';
521
+ input.spellcheck = false;
522
+ input.setAttribute('aria-label', `New name for ${before}`);
523
+ name.append(input);
524
+ input.focus();
525
+ input.select();
526
+ let settled = false;
527
+ const finish = async (save, refocus = false) => {
528
+ if (settled) return;
529
+ settled = true;
530
+ const wanted = input.value;
531
+ if (!save || wanted.trim() === before) {
532
+ restore(refocus);
533
+ return;
534
+ }
535
+ // The row is let go before the answer so the list the server then
536
+ // broadcasts can redraw it with the new name.
537
+ row.classList.remove('renaming');
538
+ const result = await sessionApi().renameSession?.(session.id, wanted);
539
+ if (!result || !result.ok) {
540
+ T1.toast((result && result.error) || 'That name was not saved.', 'warn');
541
+ restore(true);
542
+ }
543
+ };
544
+ input.addEventListener('keydown', (event) => {
545
+ if (event.key === 'Enter') { event.preventDefault(); void finish(true); }
546
+ else if (event.key === 'Escape') { event.preventDefault(); void finish(false, true); }
422
547
  });
423
- });
548
+ input.addEventListener('blur', () => { void finish(false); });
549
+ }
550
+
551
+ function openSessionMenu() {
552
+ dockTrigger = sessionPill;
553
+ renderSessionMenu();
554
+ // Shown before any other dock is closed. Closing first leaves one layout
555
+ // with no dock, the header widens for it, and the row of chips loses its
556
+ // scroll place (the current chip scrolls out of view) with no resize left
557
+ // for an observer to see.
558
+ if (!sessionMenu.open) sessionMenu.show();
559
+ closeOtherDocks(sessionMenu);
560
+ sessionPill.setAttribute('aria-expanded', 'true');
561
+ const list = $('session-menu-list');
562
+ const start = list.querySelector('.session-row.active [data-part="main"]') ||
563
+ list.querySelector('.session-row [data-part="main"]') ||
564
+ (!$('session-menu-new').disabled ? $('session-menu-new') : $('session-menu-close'));
565
+ start?.focus({ preventScroll: true });
566
+ }
567
+
568
+ // Every close asks first, in the app's own confirmation: it is the one
569
+ // action here that cannot be taken back. It names the shell and says what
570
+ // happens to this window afterwards.
571
+ let closeTarget = null;
572
+ let backToSessions = false;
573
+ function requestClose(id) {
574
+ const target = id || sessionViewNow().current?.id;
575
+ const session = sessionsNow().find((candidate) => candidate.id === target);
576
+ if (!session) return;
577
+ const view = sessionViewNow();
578
+ const current = view.state === 'live' && view.current?.id === session.id;
579
+ const others = sessionsNow().filter((candidate) => candidate.id !== session.id);
580
+ closeTarget = session.id;
581
+ $('close-confirm-title').textContent = `Close “${session.name}”?`;
582
+ $('close-confirm-text').textContent = 'This ends its shell. Anything still running in it stops. ' +
583
+ (!current ? 'You stay in the shell you are viewing.'
584
+ : others.length ? 'This window then moves to another shell.'
585
+ : 'It is the only session, so no shell will be open afterwards.');
586
+ backToSessions = sessionMenu.open;
587
+ dockTrigger = document.activeElement;
588
+ // Shown before the Sessions list is closed, so the dock's space never
589
+ // lapses in between (see openSessionMenu).
590
+ if (!closeConfirm.open) closeConfirm.show();
591
+ closeOtherDocks(closeConfirm);
592
+ $('close-confirm-cancel').focus();
593
+ }
594
+
595
+ function requestNewSession() {
596
+ const view = sessionViewNow();
597
+ const count = sessionsNow().length;
598
+ if (view.known && view.max && count >= view.max) {
599
+ // At the limit, plainly: say so, and open the list where every shell
600
+ // can be closed.
601
+ T1.toast(`All ${view.max} sessions are in use. Close one to start another.`, 'warn');
602
+ openSessionMenu();
603
+ return;
604
+ }
605
+ sessionApi().newSession?.();
606
+ }
607
+
608
+ sessionPill.addEventListener('click', openSessionMenu);
609
+ sessionMenu.addEventListener('close', () => sessionPill.setAttribute('aria-expanded', 'false'));
424
610
  $('session-menu-close').onclick = () => sessionMenu.close();
425
611
  $('session-menu-new').onclick = () => {
426
612
  sessionMenu.close();
427
- window.__terminalOne?.newSession?.();
613
+ requestNewSession();
428
614
  };
429
- window.__terminalOne?.setSessionSwitchCallback?.((id) => {
430
- if (id === '__new__') window.__terminalOne.newSession?.();
431
- else window.__terminalOne.switchSession?.(id);
432
- });
433
615
  sessionMenu.addEventListener('click', (event) => { if (event.target === sessionMenu) sessionMenu.close(); });
434
616
 
435
617
  $('close-confirm-cancel').onclick = () => closeConfirm.close();
436
618
  $('close-confirm-close').onclick = () => {
437
- const close = $('closeBtn');
438
- close.dataset.confirmed = '1';
619
+ const id = closeTarget;
439
620
  closeConfirm.close();
440
- drawer.close();
441
- close.click();
621
+ if (id) void sessionApi().closeSession?.(id);
442
622
  };
443
623
  closeConfirm.addEventListener('click', (event) => { if (event.target === closeConfirm) closeConfirm.close(); });
444
- for (const id of ['footerMeta', 'sessionInfo']) {
445
- const el = $(id);
446
- if (el) new MutationObserver(updateSessionPill).observe(el, { childList: true, subtree: true, characterData: true });
447
- }
448
- updateSessionPill();
624
+ closeConfirm.addEventListener('close', () => {
625
+ // Back to the list whether the shell was closed or kept: closing several
626
+ // should not mean reopening the list for each.
627
+ if (!backToSessions) return;
628
+ backToSessions = false;
629
+ openSessionMenu();
630
+ });
631
+
632
+ // The row (features/session-manager.mjs) asks for these two by name.
633
+ Object.assign(window.__terminalOne, { requestNewSession, requestClose });
634
+
635
+ // The title gives way last. When it is short by less than a couple of pixels
636
+ // (the rounding of flex layout) its text is clipped rather than given an
637
+ // ellipsis; an ellipsis means the title really had to shrink.
638
+ const titleText = header.querySelector('.terminal-title > span');
639
+ const settleTitle = () => {
640
+ if (!titleText) return;
641
+ titleText.classList.toggle('title-clip', titleText.scrollWidth - titleText.clientWidth < 2);
642
+ };
643
+ const settleTitleSoon = () => requestAnimationFrame(settleTitle);
644
+
645
+ const renderSessions = () => {
646
+ renderSessionPill();
647
+ if (sessionMenu.open) renderSessionMenu();
648
+ settleTitleSoon();
649
+ };
650
+ for (const name of ['t1:session-ready', 't1:sessions-change']) window.addEventListener(name, renderSessions);
651
+ window.addEventListener('resize', settleTitleSoon);
652
+ // A dock opening or closing changes the header's width without a resize event.
653
+ if (typeof ResizeObserver === 'function') new ResizeObserver(settleTitleSoon).observe(header);
654
+ renderSessions();
449
655
 
450
656
  const statusEl = $('status');
451
657
  if (statusEl) {
452
- const updateReconnect = () => { reconnect.hidden = statusEl.classList.contains('connected'); };
658
+ // With no shell on purpose the connection itself is fine; there is
659
+ // nothing to reconnect.
660
+ const updateReconnect = () => {
661
+ reconnect.hidden = statusEl.classList.contains('connected') || statusEl.textContent.includes('No shell');
662
+ };
453
663
  new MutationObserver(updateReconnect).observe(statusEl, { attributes: true, attributeFilter: ['class'], childList: true, subtree: true });
454
664
  updateReconnect();
455
665
  }
@@ -577,7 +787,6 @@ export async function init(T1) {
577
787
  let key;
578
788
  let tabs = [];
579
789
  let current = null;
580
- let busy = false;
581
790
  const permissionLabel = (permission) => permission === 'view' ? 'View only' : permission === 'control' ? 'Control' : 'Private';
582
791
 
583
792
  // The workspace key and the owner capability are minted per server process.
@@ -653,14 +862,15 @@ export async function init(T1) {
653
862
  // alive, do not leave recovery latched forever.
654
863
  setTimeout(() => { authRecovering = false; }, 5000);
655
864
  }
656
- async function api(path = '', method = 'GET', data, retry = true) {
865
+ async function api(path = '', method = 'GET', data, retry = true, signal) {
657
866
  // Once the guarded recovery has given up, every poll would otherwise repeat
658
867
  // the rejected request (plus a bootstrap fetch) until a manual reload.
659
868
  if (authBlocked) throw new Error('Owner session expired. Reload the page to reconnect.');
660
869
  const res = await fetch('/api/browser' + path, {
661
870
  method,
662
871
  headers: { 'Content-Type': 'application/json', 'X-Workspace-Key': key || '' },
663
- ...(data ? { body: JSON.stringify(data) } : {})
872
+ ...(data ? { body: JSON.stringify(data) } : {}),
873
+ ...(signal ? { signal } : {})
664
874
  });
665
875
  const value = await res.json().catch(() => ({}));
666
876
  if (res.ok) return value;
@@ -801,6 +1011,7 @@ export async function init(T1) {
801
1011
 
802
1012
  function hide() {
803
1013
  browser.hidden = true;
1014
+ pictures.unseen();
804
1015
  body.classList.remove('browser-open', 'browser-max');
805
1016
  $('browser-expand').setAttribute('aria-expanded', 'false');
806
1017
  $('browser-expand').innerHTML = icon('expand');
@@ -894,27 +1105,49 @@ export async function init(T1) {
894
1105
  window.__browserResize = setTimeout(() => resizeViewer().catch(() => {}), 250);
895
1106
  });
896
1107
 
897
- async function refresh() {
898
- if (!current || browser.hidden || busy) return;
899
- busy = true;
900
- const id = current.id;
901
- try {
902
- const snap = await api('/' + id + '/snapshot');
1108
+ // ── The picture of the page ────────────────────────────────────────────────
1109
+ // One request at a time. While the Browser view can be seen, the request
1110
+ // waits on the server for the next picture (up to SNAPSHOT_WAIT_MS): a change
1111
+ // shows as it happens, and a still page costs one small request per wait and
1112
+ // sends no picture. While the view cannot be seen (the view hidden, another
1113
+ // tab in front, the window minimized, scrolled out of the window), nothing is
1114
+ // asked for until it can be seen again.
1115
+ const SNAPSHOT_WAIT_MS = 500;
1116
+ const SNAPSHOT_RETRY_MS = 60;
1117
+ // After something was done to the page, how long to wait for its picture
1118
+ // before answering; the stream keeps watching after that.
1119
+ const SNAPSHOT_ACTION_WAIT_MS = 150;
1120
+ let pictureOf = null;
1121
+ const pictures = createPictureLoop({
1122
+ waitMs: SNAPSHOT_WAIT_MS,
1123
+ retryMs: SNAPSHOT_RETRY_MS,
1124
+ viewed: () => Boolean(current) && !browser.hidden && viewWatch.viewed(),
1125
+ ready: () => Boolean(current),
1126
+ request: ({ watching, since, waitMs, signal }) => {
1127
+ pictureOf = current.id;
1128
+ return api('/' + current.id + '/snapshot' + (watching ? `?watch=1&since=${since}&wait=${waitMs}` : '?watch=0'), 'GET', undefined, true, signal);
1129
+ },
1130
+ apply: (snapshot, fresh) => {
1131
+ const id = pictureOf;
903
1132
  if (current?.id !== id) return;
904
- Object.assign(current, snap);
1133
+ Object.assign(current, snapshot);
905
1134
  delete current.image;
906
- $('browser-frame').src = 'data:image/jpeg;base64,' + snap.image;
907
- const blank = snap.url === 'about:blank';
1135
+ // Only a new picture is put on screen. While a page prompt is waiting the
1136
+ // last picture stays, instead of a broken one.
1137
+ if (fresh && snapshot.image) $('browser-frame').src = 'data:image/jpeg;base64,' + snapshot.image;
1138
+ const blank = snapshot.url === 'about:blank';
908
1139
  $('browser-frame').hidden = blank;
909
1140
  $('browser-empty').hidden = !blank;
910
- const title = current.kind === 'agent' ? 'Agent browser' : (snap.title || 'New tab');
1141
+ const title = current.kind === 'agent' ? 'Agent browser' : (snapshot.title || 'New tab');
911
1142
  $('browser-title').textContent = title;
912
1143
  $('browser-title-compact').textContent = title;
913
1144
  updateChromeRestoreTitle(title);
914
- if (document.activeElement !== $('browser-url')) $('browser-url').value = blank ? '' : snap.url;
1145
+ if (document.activeElement !== $('browser-url')) $('browser-url').value = blank ? '' : snapshot.url;
915
1146
  updateBrowserState();
916
1147
  renderTabs();
917
- } catch (error) {
1148
+ },
1149
+ failure: (error) => {
1150
+ const id = pictureOf;
918
1151
  if (/no longer exists|404/i.test(error.message || '')) {
919
1152
  tabs = tabs.filter((candidate) => candidate.id !== id);
920
1153
  if (current && current.id === id) {
@@ -927,9 +1160,17 @@ export async function init(T1) {
927
1160
  } else {
928
1161
  setMessage(error.message || 'Browser snapshot failed.');
929
1162
  }
930
- } finally {
931
- busy = false;
932
1163
  }
1164
+ });
1165
+ const viewWatch = createViewedWatch(browser.querySelector('.browser-canvas'), (viewed) => {
1166
+ if (viewed) pictures.ask(0);
1167
+ else pictures.unseen();
1168
+ });
1169
+
1170
+ // One request now, for a picture of what was just done or just shown.
1171
+ async function refresh() {
1172
+ if (!current || browser.hidden || authBlocked || authRecovering) return;
1173
+ await pictures.refresh(SNAPSHOT_ACTION_WAIT_MS);
933
1174
  }
934
1175
 
935
1176
  async function action(name, data = {}) {
@@ -1151,13 +1392,12 @@ export async function init(T1) {
1151
1392
  drawer.addEventListener('click', (event) => {
1152
1393
  const close = event.target.closest('#closeBtn');
1153
1394
  if (!close) return;
1154
- if (close.dataset.confirmed === '1') { delete close.dataset.confirmed; return; }
1395
+ // "Close terminal" closes the shell this window is viewing. It goes
1396
+ // through the same confirmation as a chip's close control, and nowhere
1397
+ // else: a shell never ends without the person answering for it.
1155
1398
  event.preventDefault();
1156
1399
  event.stopPropagation();
1157
- drawer.close();
1158
- closeOtherDocks(closeConfirm);
1159
- if (!closeConfirm.open) closeConfirm.show();
1160
- $('close-confirm-cancel').focus();
1400
+ requestClose();
1161
1401
  }, true);
1162
1402
  $('tool-filter').oninput = (event) => filterDrawer(event.target.value);
1163
1403
 
@@ -1171,8 +1411,10 @@ export async function init(T1) {
1171
1411
  if (!openPanel) return;
1172
1412
  // The terminal and browser keep their keys. If focus is in a live surface,
1173
1413
  // Escape belongs to that surface; the dock is closed with its own control.
1414
+ // The rename field in the Sessions list works the same way: its Escape
1415
+ // cancels the rename, and the next Escape closes the list.
1174
1416
  if (event.target instanceof Element &&
1175
- event.target.closest('.terminal-container, .browser-canvas')) return;
1417
+ event.target.closest('.terminal-container, .browser-canvas, .session-row-input')) return;
1176
1418
  event.preventDefault();
1177
1419
  event.stopPropagation();
1178
1420
  const trigger = dockTrigger;
@@ -1296,8 +1538,6 @@ export async function init(T1) {
1296
1538
  // ── Terminal helper inputs, cursor, reduced motion, keybar ─────────────────
1297
1539
  const helperTextarea = document.querySelector('.xterm-helper-textarea');
1298
1540
  if (helperTextarea) helperTextarea.setAttribute('autocomplete', 'off');
1299
- const newSession = document.querySelector('.t1session-new');
1300
- if (newSession) newSession.setAttribute('aria-label', 'New terminal session');
1301
1541
 
1302
1542
  const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
1303
1543
  const applyTerminalMotion = () => {
@@ -1384,9 +1624,9 @@ export async function init(T1) {
1384
1624
  } catch (error) {
1385
1625
  if (!authRecovering && !authBlocked) setMessage(error.message);
1386
1626
  }
1387
- setInterval(() => refresh().catch((error) => {
1388
- if (!authRecovering && !authBlocked) setMessage(error.message);
1389
- }), 1000);
1627
+ // The browser view's picture is asked for by `show()` and `refresh()` and
1628
+ // then keeps streaming only while the view can be seen; nothing polls it on
1629
+ // a timer any more.
1390
1630
  // Reconcile the sidebar with the server so a crashed Chromium or a closed
1391
1631
  // context cannot leave a permanently stale tab.
1392
1632
  setInterval(async () => {