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
package/public/index.html CHANGED
@@ -388,7 +388,9 @@
388
388
  .settings-section { grid-column: 1 / -1; }
389
389
  .settings-keybar-row .t1keybar-cfg { grid-template-columns: repeat(5, 1fr); }
390
390
  }
391
- .t1session-tabs { flex-wrap: wrap; overflow: visible !important; margin-left: 0 !important; }
391
+ /* The session row keeps to one line and scrolls sideways when it is full. Its
392
+ styles live with the module that renders it (features/session-manager.mjs)
393
+ and in the workspace stylesheet. */
392
394
  body[data-style="floyd"] button { font-size: 12px; }
393
395
  body[data-style="floyd"] .terminal-status, body[data-style="floyd"] .terminal-footer { font-size: 11px; }
394
396
  .keybar .kb-key:active, .keybar .kb-key.toggle.active, .t1button.active,
@@ -414,7 +416,7 @@
414
416
  <div class="app-shell">
415
417
  <div class="banner" id="banner"></div>
416
418
  <header class="terminal-header">
417
- <div class="terminal-title">Townmouse</div>
419
+ <div class="terminal-title"><span>Townmouse<span class="terminal-title-session" id="titleSession"></span></span></div>
418
420
  <div class="terminal-actions">
419
421
  <button id="settingsBtn" type="button" title="Settings">Settings</button>
420
422
  <button id="reconnectBtn" type="button">Reconnect</button>
@@ -430,6 +432,14 @@
430
432
  <div class="t1toolbar" id="t1toolbar" role="toolbar" aria-label="Features"></div>
431
433
  <main class="terminal-container">
432
434
  <div id="terminal"></div>
435
+ <!-- Shown instead of the terminal when no shell is open: what happened, and
436
+ the one way forward. A shell is never started on the person's behalf. -->
437
+ <div class="session-empty" id="session-empty" hidden>
438
+ <h2 id="session-empty-title">No shell is open</h2>
439
+ <p id="session-empty-detail"></p>
440
+ <pre class="session-empty-output" id="session-empty-output" hidden></pre>
441
+ <button id="session-empty-start" type="button">Start a shell</button>
442
+ </div>
433
443
  </main>
434
444
 
435
445
  <!-- iPhone key bar: compact single row of essentials. -->
@@ -447,7 +457,10 @@
447
457
  <div id="settingsModal" role="dialog" aria-label="Settings">
448
458
  <div class="settings-panel">
449
459
  <div class="settings-dock-bar">
450
- <h2>Settings</h2>
460
+ <div class="settings-heading">
461
+ <h2>Settings</h2>
462
+ <p class="settings-version" data-app-version-label>Townmouse</p>
463
+ </div>
451
464
  <button id="settingsCloseTop" type="button">Done</button>
452
465
  </div>
453
466
  <div class="settings-row">
@@ -540,7 +553,19 @@
540
553
  const DEFAULT_STYLE = 'default';
541
554
  const LS_THEME = 'terminalone.theme';
542
555
  const LS_STYLE = 'terminalone.style';
556
+ // The shell this browser was last viewing. Each tab also keeps its own.
543
557
  const LS_SESSION = 'terminalone.sessionId';
558
+ const LS_EPOCH = 'terminalone.epoch';
559
+ const SS_VIEWING = 'terminalone.viewing';
560
+ const SS_EPOCH = 'terminalone.epoch';
561
+ const SS_SHELLLESS = 'terminalone.shellless';
562
+ const SS_ACTIVATION = 'terminalone.activation';
563
+ const SS_NOTICE = 'terminalone.notice';
564
+ // An agent's "show this session" request is followed only while this fresh.
565
+ const ACTIVATION_TTL_MS = 60 * 1000;
566
+ // A notice about a restart survives the reload the page does to refresh its
567
+ // owner session, but not for long.
568
+ const NOTICE_TTL_MS = 2 * 60 * 1000;
544
569
 
545
570
  // ── State ───────────────────────────────────────────────────────────────
546
571
  let ws = null;
@@ -554,6 +579,25 @@
554
579
  let sessionReady = false;
555
580
  let userInitiatedClose = false;
556
581
  let currentSessionId = null;
582
+ // Shell sessions (see "Shell sessions" below). The server's list is the only
583
+ // record of which shells exist; this window remembers the one it views.
584
+ let currentSession = null; // how the server last described that shell
585
+ let sessionList = [];
586
+ let sessionMax = 0;
587
+ let sessionKnown = false; // the server has described its current run
588
+ let knownEpoch = ssGet(SS_EPOCH) || lsGet(LS_EPOCH, null);
589
+ // connecting: asking for a shell. live: viewing one. ended: no shell, by
590
+ // nobody's accident, with one clear action.
591
+ let viewerState = 'connecting';
592
+ let viewerResumed = false; // the viewed shell came back from the server
593
+ let attachRequest = null; // what the opening socket should ask for
594
+ let lastAttach = null; // the last such request, kept for its answer
595
+ let pendingNotice = null; // said once the next shell is up
596
+ let noticeShown = false; // once per document load
597
+ let closingOwn = null; // the session this window is closing itself
598
+ let suppressAutoFocus = false; // one-shot: the next terminal must not take focus
599
+ let commandSeq = 0;
600
+ const pendingCommands = new Map();
557
601
  let currentTheme = DEFAULT_THEME;
558
602
  let currentStyle = DEFAULT_STYLE;
559
603
  let rain = null; // lazily created digital-rain controller
@@ -681,6 +725,17 @@
681
725
  function lsDel(key) {
682
726
  try { localStorage.removeItem(key); } catch (_) {}
683
727
  }
728
+ // Per-tab storage: a second tab keeps its own shell rather than inheriting
729
+ // the first tab's.
730
+ function ssGet(key) {
731
+ try { return sessionStorage.getItem(key); } catch (_) { return null; }
732
+ }
733
+ function ssSet(key, value) {
734
+ try { sessionStorage.setItem(key, value); } catch (_) {}
735
+ }
736
+ function ssDel(key) {
737
+ try { sessionStorage.removeItem(key); } catch (_) {}
738
+ }
684
739
 
685
740
  // ── Device detection (iPhone vs iPad vs desktop) ──────────────────────────
686
741
  // iPadOS 13+ requests desktop sites and reports platform 'MacIntel' with a
@@ -747,9 +802,30 @@
747
802
  }
748
803
 
749
804
  // ── UI feedback helpers ────────────────────────────────────────────────────
750
- function showBanner(msg, type = 'error') {
805
+ function showBanner(msg, type = 'error', options = {}) {
751
806
  const banner = $('#banner');
752
- banner.textContent = msg;
807
+ banner.textContent = '';
808
+ const text = document.createElement('span');
809
+ text.className = 'banner-text';
810
+ text.textContent = msg;
811
+ banner.append(text);
812
+ if (options.action) {
813
+ const action = document.createElement('button');
814
+ action.type = 'button';
815
+ action.className = 'banner-action';
816
+ action.textContent = options.action.label;
817
+ action.addEventListener('click', options.action.run);
818
+ banner.append(action);
819
+ }
820
+ if (options.dismissible) {
821
+ const dismiss = document.createElement('button');
822
+ dismiss.type = 'button';
823
+ dismiss.className = 'banner-dismiss';
824
+ dismiss.textContent = 'Dismiss';
825
+ // A notice the person has read must not come back on the next load.
826
+ dismiss.addEventListener('click', () => { ssDel(SS_NOTICE); hideBanner(); });
827
+ banner.append(dismiss);
828
+ }
753
829
  banner.className = `banner ${type}`;
754
830
  // hideBanner writes an inline display:none that would otherwise outrank
755
831
  // every .banner.error/.warn rule and keep later banners invisible.
@@ -1094,6 +1170,7 @@
1094
1170
  function initTerminal() {
1095
1171
  cleanupTerminalResources();
1096
1172
  sessionReady = false;
1173
+ showSessionEmpty(false);
1097
1174
  resumeReplay = null;
1098
1175
  replayEnded = false;
1099
1176
  replayPending = 0;
@@ -1134,10 +1211,25 @@
1134
1211
  } catch (_) { /* older xterm without OSC handlers */ }
1135
1212
  // If resume already selected the old replay dimensions, do not fit to the
1136
1213
  // new viewport here; replay-end owns that transition.
1137
- requestAnimationFrame(() => { if (!resumeReplay) fitAddon.fit(); });
1138
- // Web-font metrics can land after the first paint; refit once they settle.
1139
- if (document.fonts && document.fonts.ready) {
1140
- document.fonts.ready.then(() => scheduleFit()).catch(() => {});
1214
+ // The frame can land after this terminal was disposed (a quick switch, or
1215
+ // the last shell being closed), so check it is still here.
1216
+ requestAnimationFrame(() => { if (!resumeReplay && fitAddon) fitAddon.fit(); });
1217
+ // The grid is measured with whatever font is in place when the terminal is
1218
+ // opened, and measured again only when its font setting is set to a new
1219
+ // value. A web font that arrives after that leaves the grid with the
1220
+ // stand-in font's line spacing for good, and a later fit keeps it, because
1221
+ // a fit reuses the last measurement. So each time a font finishes loading,
1222
+ // set the font again with one more stand-in at the end of the stack (a new
1223
+ // value, never reached), which makes the terminal measure, and then fit.
1224
+ const refitForFont = () => {
1225
+ if (!term) return;
1226
+ term.options.fontFamily = `${STYLES[currentStyle]}, monospace`;
1227
+ scheduleFit();
1228
+ };
1229
+ if (document.fonts) {
1230
+ document.fonts.addEventListener('loadingdone', refitForFont);
1231
+ addTerminalResource(() => document.fonts.removeEventListener('loadingdone', refitForFont));
1232
+ document.fonts.ready.then(refitForFont).catch(() => {});
1141
1233
  }
1142
1234
 
1143
1235
 
@@ -1158,14 +1250,20 @@
1158
1250
  sendInputFn = (data) => guard.send(data);
1159
1251
  bindAttachmentDrop();
1160
1252
 
1161
- addTerminalResource(bindInputGuard(term, guard));
1253
+ // While a resumed shell's earlier output is being replayed, the terminal's
1254
+ // answers to questions in that output must not be typed into the shell.
1255
+ addTerminalResource(bindInputGuard(term, guard, { ignoreGenerated: () => resumeReplay !== null }));
1162
1256
 
1163
1257
  // Take focus on load where there is no touchscreen, so the very first
1164
1258
  // keypress reaches the terminal. A tablet would get its on-screen keyboard
1165
1259
  // opened uninvited, so those devices rely on the key-capture fallback above.
1166
1260
  // (Headless Chrome reports a coarse pointer, so maxTouchPoints is the
1167
1261
  // reliable signal here.)
1168
- if (!navigator.maxTouchPoints) {
1262
+ // A session an agent asked to show does not pull the keyboard out of
1263
+ // whatever the person was doing.
1264
+ const holdFocus = suppressAutoFocus;
1265
+ suppressAutoFocus = false;
1266
+ if (!navigator.maxTouchPoints && !holdFocus) {
1169
1267
  requestAnimationFrame(() => { try { term.focus(); } catch (_) {} });
1170
1268
  }
1171
1269
 
@@ -1205,7 +1303,16 @@
1205
1303
  case 'ready': {
1206
1304
  sessionReady = true;
1207
1305
  currentSessionId = msg.sessionId;
1208
- lsSet(LS_SESSION, msg.sessionId);
1306
+ // A different epoch means the app itself was restarted since this window
1307
+ // last heard from it. That is worth saying; one closed shell is not.
1308
+ const restarted = Boolean(knownEpoch && msg.epoch && knownEpoch !== msg.epoch);
1309
+ if (msg.epoch) rememberEpoch(msg.epoch);
1310
+ if (restarted) { sessionList = []; sessionKnown = false; }
1311
+ currentSession = { id: msg.sessionId, name: msg.name || 'Shell', cwd: msg.cwd || '', command: msg.command || '' };
1312
+ viewerState = 'live';
1313
+ viewerResumed = Boolean(msg.resumed);
1314
+ closingOwn = null;
1315
+ rememberSession(msg.sessionId);
1209
1316
  if (msg.resumed) {
1210
1317
  // Replay the buffered output at the dimensions it was produced with,
1211
1318
  // then fit to this viewport after replay-end. Otherwise old wraps and
@@ -1245,8 +1352,29 @@
1245
1352
  }
1246
1353
  setSessionInfo(`session ${msg.sessionId.slice(0, 8)}`, msg.sessionId);
1247
1354
  window.dispatchEvent(new CustomEvent('t1:session-ready', {
1248
- detail: { command: msg.command, cwd: msg.cwd, resumed: !!msg.resumed }
1355
+ detail: {
1356
+ command: msg.command, cwd: msg.cwd, resumed: !!msg.resumed,
1357
+ sessionId: msg.sessionId, name: currentSession.name, restarted
1358
+ }
1249
1359
  }));
1360
+ renderSessionChrome();
1361
+ showPendingNotice();
1362
+ break;
1363
+ }
1364
+ case 'sessions': {
1365
+ // The server's account of which shells exist, pushed whenever it changes.
1366
+ applySessionState(msg);
1367
+ break;
1368
+ }
1369
+ case 'session-ended': {
1370
+ onSessionEnded(msg.sessionId, msg.reason || 'closed', msg);
1371
+ break;
1372
+ }
1373
+ case 'result': {
1374
+ const pending = pendingCommands.get(msg.requestId);
1375
+ if (!pending) break;
1376
+ pendingCommands.delete(msg.requestId);
1377
+ pending.resolve(msg);
1250
1378
  break;
1251
1379
  }
1252
1380
  case 'output': {
@@ -1286,19 +1414,14 @@
1286
1414
  break;
1287
1415
  }
1288
1416
  case 'resume-failed': {
1289
- // Target session gone/expired — fall back to a fresh shell on this open ws.
1417
+ // The shell this window remembered is not on the server. What happens
1418
+ // next is decided from the server's real list and said out loud.
1290
1419
  resumeReplay = null;
1291
1420
  replayEnded = false;
1292
1421
  replayPending = 0;
1293
1422
  postReplayOutput = [];
1294
1423
  scheduleFit();
1295
- infoResumeFail(msg);
1296
- lsDel(LS_SESSION);
1297
- currentSessionId = null;
1298
- if (ws && ws.readyState === WebSocket.OPEN) {
1299
- const dims = fitAddon?.proposeDimensions() || { cols: 120, rows: 40 };
1300
- ws.send(JSON.stringify({ type: 'shell', cols: dims.cols, rows: dims.rows }));
1301
- }
1424
+ onResumeFailed(msg);
1302
1425
  break;
1303
1426
  }
1304
1427
  case 'voice-ready': {
@@ -1323,8 +1446,399 @@
1323
1446
  }
1324
1447
  }
1325
1448
 
1326
- function infoResumeFail(msg) {
1327
- term?.write(`\r\n\x1b[33m[resume unavailable — starting fresh shell]\x1b[0m\r\n`);
1449
+ // ── Shell sessions ─────────────────────────────────────────────────────────
1450
+ // The server keeps the list of shells. This window remembers the one it is
1451
+ // viewing and asks the server for it; the row, the title and the Sessions
1452
+ // list are drawn from what the server sends back. When the shell this window
1453
+ // is viewing is gone, the window says so and lands on a shell that exists,
1454
+ // or on one clear action. Nothing here starts a shell on the quiet.
1455
+
1456
+ function rememberEpoch(epoch) {
1457
+ knownEpoch = epoch;
1458
+ ssSet(SS_EPOCH, epoch);
1459
+ lsSet(LS_EPOCH, epoch);
1460
+ }
1461
+
1462
+ // The shell to ask for: this tab's own, else the browser's last, else none.
1463
+ function rememberedSession() {
1464
+ return ssGet(SS_VIEWING) || lsGet(LS_SESSION, null);
1465
+ }
1466
+
1467
+ function rememberSession(id) {
1468
+ if (id) {
1469
+ ssSet(SS_VIEWING, id);
1470
+ lsSet(LS_SESSION, id);
1471
+ ssDel(SS_SHELLLESS);
1472
+ } else {
1473
+ ssDel(SS_VIEWING);
1474
+ lsDel(LS_SESSION);
1475
+ }
1476
+ }
1477
+
1478
+ // What a newly opened socket should ask the server for.
1479
+ function planInitialAttach() {
1480
+ const id = rememberedSession();
1481
+ if (id) return { resume: id };
1482
+ // A window with no shell on purpose stays that way across a reload or a
1483
+ // reconnect. It never grows a shell by itself.
1484
+ if (viewerState === 'ended' || ssGet(SS_SHELLLESS) === '1') return { control: true };
1485
+ return { create: true };
1486
+ }
1487
+
1488
+ function sendOnSocket(payload) {
1489
+ if (ws && ws.readyState === WebSocket.OPEN) {
1490
+ ws.send(JSON.stringify(payload));
1491
+ return true;
1492
+ }
1493
+ return false;
1494
+ }
1495
+
1496
+ // A command the server answers by requestId, so its outcome can be shown
1497
+ // where it was asked instead of in the terminal.
1498
+ function sessionCommand(payload) {
1499
+ return new Promise((resolve, reject) => {
1500
+ if (!(ws && ws.readyState === WebSocket.OPEN)) {
1501
+ reject(new Error('Townmouse is not connected.'));
1502
+ return;
1503
+ }
1504
+ const requestId = `c${++commandSeq}`;
1505
+ pendingCommands.set(requestId, { resolve, reject });
1506
+ ws.send(JSON.stringify({ ...payload, requestId }));
1507
+ });
1508
+ }
1509
+
1510
+ function rejectPendingCommands(error) {
1511
+ for (const pending of pendingCommands.values()) pending.reject(error);
1512
+ pendingCommands.clear();
1513
+ }
1514
+
1515
+ // Stop using the current socket on purpose. The close that follows is this
1516
+ // window's own doing, so nothing may reconnect or start a shell from it.
1517
+ function abandonSocket() {
1518
+ if (reconnectTimer) {
1519
+ clearTimeout(reconnectTimer);
1520
+ reconnectTimer = null;
1521
+ }
1522
+ if (ws) {
1523
+ try { ws.onclose = null; ws.close(); } catch (_) {}
1524
+ }
1525
+ ws = null;
1526
+ rejectPendingCommands(new Error('The connection was closed.'));
1527
+ }
1528
+
1529
+ function disposeTerminal() {
1530
+ try { term?.dispose(); } catch (_) {}
1531
+ cleanupTerminalResources();
1532
+ term = null;
1533
+ fitAddon = null;
1534
+ sendInputFn = null;
1535
+ sessionReady = false;
1536
+ }
1537
+
1538
+ function focusTerminal() {
1539
+ try { term?.focus(); } catch (_) { /* no terminal */ }
1540
+ }
1541
+
1542
+ // The title names the shell this window is viewing, or nothing.
1543
+ function renderSessionChrome() {
1544
+ const label = document.getElementById('titleSession');
1545
+ if (label) label.textContent = viewerState === 'live' && currentSession ? ` / ${currentSession.name}` : '';
1546
+ }
1547
+
1548
+ function announceSessions() {
1549
+ window.dispatchEvent(new CustomEvent('t1:sessions-change', {
1550
+ detail: { sessions: sessionList.map((session) => ({ ...session })), max: sessionMax, state: viewerState }
1551
+ }));
1552
+ }
1553
+
1554
+ // Replaces the terminal while no shell is open. Pass nothing to bring the
1555
+ // terminal back.
1556
+ function showSessionEmpty(options) {
1557
+ const empty = document.getElementById('session-empty');
1558
+ const host = document.getElementById('terminal');
1559
+ if (!empty || !host) return;
1560
+ if (!options) {
1561
+ empty.hidden = true;
1562
+ host.hidden = false;
1563
+ return;
1564
+ }
1565
+ document.getElementById('session-empty-title').textContent = options.heading || 'No shell is open';
1566
+ document.getElementById('session-empty-detail').textContent = options.detail || '';
1567
+ const output = document.getElementById('session-empty-output');
1568
+ output.textContent = options.output || '';
1569
+ output.hidden = !options.output;
1570
+ host.hidden = true;
1571
+ empty.hidden = false;
1572
+ }
1573
+
1574
+ function showPendingNotice() {
1575
+ let text = pendingNotice;
1576
+ pendingNotice = null;
1577
+ let carried = false;
1578
+ if (!text && !noticeShown) {
1579
+ // A notice outlives the reload the page does to refresh its owner
1580
+ // session, once, until the person dismisses it or it gets old.
1581
+ try {
1582
+ const saved = JSON.parse(ssGet(SS_NOTICE) || 'null');
1583
+ if (saved && Date.now() - saved.at < NOTICE_TTL_MS) {
1584
+ text = saved.text;
1585
+ carried = true;
1586
+ }
1587
+ } catch (_) { /* no notice */ }
1588
+ }
1589
+ if (!text) return;
1590
+ if (carried) noticeShown = true;
1591
+ ssSet(SS_NOTICE, JSON.stringify({ text, at: Date.now() }));
1592
+ showBanner(text, 'info', { dismissible: true });
1593
+ }
1594
+
1595
+ // The server's account of which shells exist, in row order.
1596
+ function applySessionState(state) {
1597
+ if (!state || !Array.isArray(state.sessions)) return;
1598
+ if (state.epoch && state.epoch !== knownEpoch) {
1599
+ // A different run of the app: nothing it listed carried over.
1600
+ rememberEpoch(state.epoch);
1601
+ sessionList = [];
1602
+ sessionKnown = false;
1603
+ }
1604
+ const before = sessionList;
1605
+ const known = new Set(before.map((session) => session.id));
1606
+ sessionList = state.sessions;
1607
+ sessionMax = Number(state.max) || 0;
1608
+ const first = !sessionKnown;
1609
+ sessionKnown = true;
1610
+ if (viewerState === 'live' && currentSessionId) {
1611
+ const mine = sessionList.find((session) => session.id === currentSessionId);
1612
+ if (mine) {
1613
+ currentSession = mine;
1614
+ } else {
1615
+ // The server dropped the shell this window is viewing and its notice
1616
+ // did not arrive. It counts exactly like the notice.
1617
+ onSessionEnded(currentSessionId, 'closed', state);
1618
+ return;
1619
+ }
1620
+ }
1621
+ if (!first) {
1622
+ // An agent starting a shell while the person watches should not go unnoticed.
1623
+ for (const session of sessionList) {
1624
+ if (!known.has(session.id) && session.id !== currentSessionId && session.createdBy === 'agent') {
1625
+ T1.toast(`Agent started “${session.name}”`);
1626
+ }
1627
+ }
1628
+ }
1629
+ followActivation(state.activation);
1630
+ renderSessionChrome();
1631
+ announceSessions();
1632
+ }
1633
+
1634
+ function seenActivation() {
1635
+ const [epoch, seq] = String(ssGet(SS_ACTIVATION) || ':0').split(':');
1636
+ return epoch === knownEpoch ? Number(seq) || 0 : 0;
1637
+ }
1638
+
1639
+ // `activate` is the one agent action that moves the person's view. It is
1640
+ // followed once, while it is fresh; the person asked the agent for it.
1641
+ function followActivation(activation) {
1642
+ if (!activation || !Number.isFinite(activation.seq)) return;
1643
+ if (activation.seq <= seenActivation()) return;
1644
+ ssSet(SS_ACTIVATION, `${knownEpoch}:${activation.seq}`);
1645
+ if (Date.now() - activation.at > ACTIVATION_TTL_MS) return;
1646
+ if (viewerState === 'live' && activation.id === currentSessionId) return;
1647
+ const target = sessionList.find((session) => session.id === activation.id);
1648
+ if (!target) return;
1649
+ T1.toast(`Showing “${target.name}”, as the agent asked.`);
1650
+ const held = document.activeElement instanceof Element &&
1651
+ Boolean(document.activeElement.closest('dialog, input, textarea, select, [contenteditable="true"], .workspace-drawer'));
1652
+ attachSession(target.id, held);
1653
+ }
1654
+
1655
+ function attachSession(id, holdFocus = false) {
1656
+ suppressAutoFocus = holdFocus;
1657
+ abandonSocket();
1658
+ attachRequest = { resume: id };
1659
+ connect();
1660
+ }
1661
+
1662
+ function switchSession(id) {
1663
+ if (!id) return false;
1664
+ if (viewerState === 'live' && id === currentSessionId) {
1665
+ focusTerminal();
1666
+ return true;
1667
+ }
1668
+ // Only a shell the server lists can be switched to. Anything else is
1669
+ // refused; it is never turned into a new shell.
1670
+ if (!sessionList.some((session) => session.id === id)) {
1671
+ T1.toast('That session is no longer available.', 'warn');
1672
+ return false;
1673
+ }
1674
+ attachSession(id);
1675
+ return true;
1676
+ }
1677
+
1678
+ function newSession() {
1679
+ abandonSocket();
1680
+ attachRequest = { create: true };
1681
+ connect();
1682
+ }
1683
+
1684
+ // End a session the server lists. The shell stops on the server; a window
1685
+ // that was viewing it is moved on by the notice the server sends.
1686
+ async function closeSession(id) {
1687
+ const wasCurrent = viewerState === 'live' && id === currentSessionId;
1688
+ if (wasCurrent) closingOwn = id;
1689
+ try {
1690
+ const result = await sessionCommand({ type: 'close', sessionId: id });
1691
+ if (!result.ok && wasCurrent) closingOwn = null;
1692
+ return Boolean(result.ok);
1693
+ } catch (error) {
1694
+ if (wasCurrent) closingOwn = null;
1695
+ T1.toast(error.message || 'The session could not be closed.', 'error');
1696
+ return false;
1697
+ }
1698
+ }
1699
+
1700
+ async function renameSession(id, name) {
1701
+ try {
1702
+ const result = await sessionCommand({ type: 'rename', sessionId: id, name });
1703
+ if (result.ok) return { ok: true, name: result.name };
1704
+ return { ok: false, error: result.error || 'That name was not saved.' };
1705
+ } catch (error) {
1706
+ return { ok: false, error: error.message || 'That name was not saved.' };
1707
+ }
1708
+ }
1709
+
1710
+ // The shell to the right of the one that ended, else the one to the left,
1711
+ // else the one looked at most recently. Browser tabs move this way too.
1712
+ function neighbour(id, order, live) {
1713
+ const index = order.findIndex((session) => session.id === id);
1714
+ for (let step = 1; index >= 0 && step <= order.length; step += 1) {
1715
+ for (const candidate of [order[index + step], order[index - step]]) {
1716
+ if (!candidate) continue;
1717
+ const next = live.find((session) => session.id === candidate.id);
1718
+ if (next) return next;
1719
+ }
1720
+ }
1721
+ return live.slice().sort((a, b) => (b.lastViewedAt || 0) - (a.lastViewedAt || 0))[0];
1722
+ }
1723
+
1724
+ // The shell this window was viewing is gone: closed here, closed by an
1725
+ // agent or another window, or unable to keep running. The window lands on
1726
+ // a shell that exists, or on one clear action, and says which unless the
1727
+ // person closed it themselves.
1728
+ function onSessionEnded(id, reason = 'closed', state) {
1729
+ if (viewerState !== 'live' || id !== currentSessionId) return;
1730
+ const bySelf = closingOwn === id;
1731
+ closingOwn = null;
1732
+ const name = currentSession?.name || 'The shell';
1733
+ const order = sessionList;
1734
+ const live = (state && Array.isArray(state.sessions) ? state.sessions : sessionList)
1735
+ .filter((session) => session.id !== id);
1736
+ abandonSocket();
1737
+ sessionList = live;
1738
+ sessionKnown = true;
1739
+ currentSessionId = null;
1740
+ currentSession = null;
1741
+ if (live.length) {
1742
+ const target = neighbour(id, order, live);
1743
+ if (!bySelf) {
1744
+ pendingNotice = reason === 'error'
1745
+ ? `“${name}” stopped unexpectedly. This window is now in “${target.name}”.`
1746
+ : `“${name}” was closed. This window is now in “${target.name}”.`;
1747
+ }
1748
+ attachRequest = { resume: target.id, after: 'ended' };
1749
+ connect();
1750
+ return;
1751
+ }
1752
+ enterEndedState(reason, name, bySelf);
1753
+ }
1754
+
1755
+ // What the window shows while no shell is open: what happened (as far as it
1756
+ // is known) and the one way forward. Shown when the last shell is closed and
1757
+ // again on every load that finds no shell on purpose.
1758
+ function showNoShell(options = {}) {
1759
+ const { reason = 'closed', name = '', bySelf = false, output = '' } = options;
1760
+ updateStatus('No shell', 'neutral');
1761
+ setFooter('No shell is open');
1762
+ setSessionInfo('');
1763
+ hideBanner();
1764
+ showSessionEmpty({
1765
+ heading: reason === 'error'
1766
+ ? `“${name}” could not keep running`
1767
+ : (name ? (bySelf ? `You closed “${name}”` : `“${name}” was closed`) : 'No shell is open'),
1768
+ detail: reason === 'error'
1769
+ ? 'Its shell exited again and again, so it was not restarted. Check $SHELL and your shell profile, then start another shell.'
1770
+ : (name
1771
+ ? 'No shell is open. A shell you close is gone for good; start one when you need it.'
1772
+ : 'A shell you close is gone for good. Start one when you need it.'),
1773
+ output
1774
+ });
1775
+ renderSessionChrome();
1776
+ announceSessions();
1777
+ }
1778
+
1779
+ // No shell, and none started in the background: the person stays in charge.
1780
+ // The window keeps a shell-less connection so the row stays current and can
1781
+ // still be acted on.
1782
+ function enterEndedState(reason, name, bySelf) {
1783
+ let output = '';
1784
+ if (reason === 'error' && term) {
1785
+ // What the shell printed before it gave up is the diagnosis. Keep the
1786
+ // last of it readable.
1787
+ output = String(window.__terminalOne.text?.() || '')
1788
+ .split('\n')
1789
+ .map((line) => line.trimEnd())
1790
+ .filter((line) => line.trim())
1791
+ .slice(-6)
1792
+ .join('\n');
1793
+ }
1794
+ rememberSession(null);
1795
+ ssSet(SS_SHELLLESS, '1');
1796
+ viewerState = 'ended';
1797
+ viewerResumed = false;
1798
+ disposeTerminal();
1799
+ showNoShell({ reason, name, bySelf, output });
1800
+ abandonSocket();
1801
+ attachRequest = { control: true };
1802
+ connect();
1803
+ document.getElementById('session-empty-start')?.focus();
1804
+ }
1805
+
1806
+ // The shell this window remembered is not on the server: the app was
1807
+ // restarted, or that shell was closed while the window was away. Say which
1808
+ // is known, then land on a shell that exists, or start exactly one.
1809
+ function onResumeFailed(msg) {
1810
+ const failed = msg.sessionId || rememberedSession() || '';
1811
+ const restarted = Boolean(knownEpoch && msg.epoch && msg.epoch !== knownEpoch);
1812
+ const before = restarted ? [] : sessionList;
1813
+ if (msg.epoch) rememberEpoch(msg.epoch);
1814
+ rememberSession(null);
1815
+ const live = (Array.isArray(msg.sessions) ? msg.sessions : []).filter((session) => session.id !== failed);
1816
+ const failedName = (before.find((session) => session.id === failed) || currentSession || {}).name;
1817
+ // Was this window opening, or moving off a shell that was closed under it?
1818
+ const movingOff = Boolean(lastAttach && lastAttach.after === 'ended');
1819
+ if (restarted) {
1820
+ sessionList = [];
1821
+ sessionKnown = false;
1822
+ }
1823
+ applySessionState({ ...msg, sessions: live });
1824
+ const said = restarted
1825
+ ? 'Townmouse was restarted, so the shells from before have ended.'
1826
+ : `“${failedName || 'The shell this window was viewing'}” is no longer available.`;
1827
+ const dims = fitAddon?.proposeDimensions() || { cols: 120, rows: 40 };
1828
+ if (live.length) {
1829
+ const target = live.slice().sort((a, b) => (b.lastViewedAt || 0) - (a.lastViewedAt || 0))[0];
1830
+ pendingNotice = `${said} This window is now in “${target.name}”.`;
1831
+ sendOnSocket({ type: 'resume', sessionId: target.id, cols: dims.cols, rows: dims.rows });
1832
+ return;
1833
+ }
1834
+ if (movingOff) {
1835
+ // Every other shell is gone too. That is not a fresh start: the choice
1836
+ // of a new shell is left to the person.
1837
+ enterEndedState('closed', failedName, false);
1838
+ return;
1839
+ }
1840
+ pendingNotice = `${said} This is a new shell.`;
1841
+ sendOnSocket({ type: 'shell', cols: dims.cols, rows: dims.rows });
1328
1842
  }
1329
1843
 
1330
1844
  function connect() {
@@ -1336,45 +1850,73 @@
1336
1850
  }
1337
1851
 
1338
1852
  userInitiatedClose = false;
1339
-
1340
1853
  if (ws) {
1341
1854
  try { ws.close(); } catch (_) {}
1342
1855
  }
1343
1856
 
1344
- initTerminal();
1345
- updateStatus('Connecting…', 'connecting');
1346
- hideBanner();
1857
+ const request = attachRequest || planInitialAttach();
1858
+ attachRequest = null;
1859
+ lastAttach = request;
1860
+ if (request.control) {
1861
+ if (viewerState !== 'ended') {
1862
+ // Loaded with no shell on purpose: the person closed the last one. Show
1863
+ // that, rather than a blank space where the terminal was.
1864
+ viewerState = 'ended';
1865
+ showNoShell();
1866
+ }
1867
+ } else {
1868
+ initTerminal();
1869
+ viewerState = 'connecting';
1870
+ updateStatus('Connecting…', 'connecting');
1871
+ hideBanner();
1872
+ }
1347
1873
 
1348
1874
  const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
1349
- ws = new WebSocket(`${protocol}//${location.host}`);
1875
+ // The handlers hold this socket, not the shared `ws`: an event from a
1876
+ // socket that has been replaced must not act on the new one.
1877
+ const socket = new WebSocket(`${protocol}//${location.host}`);
1878
+ ws = socket;
1350
1879
 
1351
- ws.onopen = () => {
1880
+ socket.onopen = () => {
1352
1881
  reconnectAttempts = 0;
1353
1882
  const dims = fitAddon?.proposeDimensions() || { cols: 120, rows: 40 };
1354
- // If we have a saved session id, try to resume it; otherwise spawn fresh.
1355
- const savedId = lsGet(LS_SESSION, null);
1356
- if (savedId) {
1357
- ws.send(JSON.stringify({ type: 'resume', sessionId: savedId, cols: dims.cols, rows: dims.rows }));
1883
+ if (request.resume) {
1884
+ // Ask for a shell the server has. If it is gone the server answers with
1885
+ // its real list, and onResumeFailed decides what happens next.
1886
+ socket.send(JSON.stringify({ type: 'resume', sessionId: request.resume, cols: dims.cols, rows: dims.rows }));
1887
+ } else if (request.create) {
1888
+ // The one way a shell is started: it was asked for, here.
1889
+ socket.send(JSON.stringify({ type: 'shell', cols: dims.cols, rows: dims.rows }));
1358
1890
  } else {
1359
- ws.send(JSON.stringify({ type: 'shell', cols: dims.cols, rows: dims.rows }));
1891
+ // No shell on purpose. The socket only carries the list of sessions.
1892
+ updateStatus('No shell', 'neutral');
1893
+ socket.send(JSON.stringify({ type: 'sessions' }));
1360
1894
  }
1361
1895
  scheduleFit();
1362
1896
  };
1363
1897
 
1364
- ws.onmessage = (evt) => {
1898
+ socket.onmessage = (evt) => {
1365
1899
  try { handleServerMessage(JSON.parse(evt.data)); }
1366
1900
  catch (e) { showBanner('Malformed server message', 'error'); }
1367
1901
  };
1368
1902
 
1369
- ws.onerror = () => {
1903
+ socket.onerror = () => {
1370
1904
  showBanner('WebSocket connection failed', 'error');
1371
1905
  updateStatus('WS error', 'error');
1372
1906
  };
1373
1907
 
1374
- ws.onclose = () => {
1908
+ socket.onclose = () => {
1909
+ if (ws !== socket) return;
1910
+ rejectPendingCommands(new Error('The connection closed.'));
1911
+ // A shell this window closed itself ends here, whether or not the
1912
+ // server's notice reached this socket first.
1913
+ if (closingOwn && closingOwn === currentSessionId) {
1914
+ onSessionEnded(currentSessionId, 'closed', null);
1915
+ return;
1916
+ }
1375
1917
  if (userInitiatedClose) return;
1376
1918
  updateStatus('Disconnected', 'error');
1377
- // Leave the saved session id in place so the reconnect attempts a resume.
1919
+ // The remembered shell stays remembered, so the reconnect resumes it.
1378
1920
  const delay = Math.min(1_000 * Math.pow(2, reconnectAttempts), 60_000);
1379
1921
  reconnectAttempts++;
1380
1922
  reconnectTimer = setTimeout(() => {
@@ -1383,49 +1925,22 @@
1383
1925
  };
1384
1926
  }
1385
1927
 
1928
+ // Ends the shell this window is viewing. The caller has already asked; this
1929
+ // leaves the window with no shell of its own.
1386
1930
  function closeConnection() {
1387
- userInitiatedClose = true;
1931
+ const id = currentSessionId;
1932
+ if (!id || viewerState !== 'live') return;
1388
1933
  reconnectAttempts = 0;
1389
-
1390
- // Explicit close must never resume: clear the saved session id first.
1391
- lsDel(LS_SESSION);
1392
- currentSessionId = null;
1393
-
1394
1934
  if (reconnectTimer) {
1395
1935
  clearTimeout(reconnectTimer);
1396
1936
  reconnectTimer = null;
1397
1937
  }
1398
-
1399
- if (ws) {
1400
- try { ws.send(JSON.stringify({ type: 'close' })); } catch (_) {}
1401
- ws.close();
1402
- ws = null;
1403
- }
1404
-
1405
- try { term?.dispose(); } catch (_) {}
1406
- cleanupTerminalResources();
1407
- term = null;
1408
- fitAddon = null;
1409
- sendInputFn = null;
1410
-
1411
- updateStatus('Closed', 'neutral');
1412
- setFooter('Connection closed');
1413
- setSessionInfo('');
1414
- }
1415
-
1416
- function restartConnection(sessionId) {
1417
- userInitiatedClose = true;
1418
- reconnectAttempts = 0;
1419
- if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
1420
- if (ws) {
1421
- try { ws.onclose = null; ws.close(); } catch (_) {}
1422
- ws = null;
1938
+ closingOwn = id;
1939
+ if (sendOnSocket({ type: 'close' })) {
1940
+ try { ws.close(); } catch (_) {}
1941
+ } else {
1942
+ onSessionEnded(id, 'closed', null);
1423
1943
  }
1424
- currentSessionId = null;
1425
- if (sessionId) lsSet(LS_SESSION, sessionId);
1426
- else lsDel(LS_SESSION);
1427
- userInitiatedClose = false;
1428
- connect();
1429
1944
  }
1430
1945
 
1431
1946
  // ── Settings UI ─────────────────────────────────────────────────────────────
@@ -1545,6 +2060,7 @@
1545
2060
  connect();
1546
2061
  });
1547
2062
  $('#closeBtn').addEventListener('click', closeConnection);
2063
+ $('#session-empty-start').addEventListener('click', newSession);
1548
2064
 
1549
2065
  // Re-detect on orientation change (iPhone↔iPad-like layout shifts are rare,
1550
2066
  // but viewport reflow should refresh the key bars).
@@ -1628,6 +2144,17 @@
1628
2144
  get device() { return document.body.dataset.device || detectDevice(); },
1629
2145
  sendData: (data) => { if (sendInputFn) sendInputFn(data); },
1630
2146
  fit: () => scheduleFit(),
2147
+ // Shell sessions, for the row and the Sessions list.
2148
+ sessions: () => sessionList.map((session) => ({ ...session })),
2149
+ sessionView: () => ({
2150
+ state: viewerState,
2151
+ current: currentSession ? { ...currentSession } : null,
2152
+ max: sessionMax,
2153
+ known: sessionKnown,
2154
+ resumed: viewerResumed
2155
+ }),
2156
+ newSession,
2157
+ switchSession,
1631
2158
  toast: (msg, type = 'info') => __showToast(msg, type),
1632
2159
  onTermReady,
1633
2160
  storage: {
@@ -1666,7 +2193,7 @@
1666
2193
  'haptic-keys', 'keepalive', 'multi-window-sync', 'phone-landscape-focus',
1667
2194
  'session-lock', 'settings-sync', 'shortcut-help', 'smart-completions',
1668
2195
  'smart-suggest', 'split-view', 'stylus-support', 'swipe-history',
1669
- 'swipe-sessions', 'tab-reorder', 'two-finger-menu', 'window-title'
2196
+ 'swipe-sessions', 'two-finger-menu', 'app-version', 'window-title'
1670
2197
  ];
1671
2198
  (async () => {
1672
2199
  const loaded = [];
@@ -1718,8 +2245,20 @@
1718
2245
  setStyle: applyStyle,
1719
2246
  termTheme: () => term && term.options.theme,
1720
2247
  close: closeConnection,
1721
- newSession: () => restartConnection(null),
1722
- switchSession: (id) => restartConnection(id),
2248
+ // Shell sessions. The list is the server's; these act on it and never
2249
+ // start a shell that was not asked for.
2250
+ newSession,
2251
+ switchSession,
2252
+ closeSession,
2253
+ renameSession,
2254
+ sessions: () => sessionList.map((session) => ({ ...session })),
2255
+ sessionView: () => ({
2256
+ state: viewerState,
2257
+ current: currentSession ? { ...currentSession } : null,
2258
+ max: sessionMax,
2259
+ known: sessionKnown,
2260
+ resumed: viewerResumed
2261
+ }),
1723
2262
  // Test hooks for the key bar + resume.
1724
2263
  detectDevice,
1725
2264
  visibleKeyBar: () => {
@@ -1732,7 +2271,7 @@
1732
2271
  const bar = (document.body.dataset.device === 'iphone' ? $('#keybarIphone') : $('#keybarIpad'));
1733
2272
  return bar ? bar.querySelectorAll('.kb-key').length : 0;
1734
2273
  },
1735
- savedSession: () => lsGet(LS_SESSION, null),
2274
+ savedSession: () => rememberedSession(),
1736
2275
  // Attachment controls insert a shell-quoted path through the same guarded
1737
2276
  // input path as the keyboard and key bar.
1738
2277
  sendData: (data) => {