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/panes.mjs CHANGED
@@ -3,11 +3,18 @@ import { FitAddon } from '/node_modules/@xterm/addon-fit/lib/addon-fit.mjs';
3
3
  import { WebLinksAddon } from '/node_modules/@xterm/addon-web-links/lib/addon-web-links.mjs';
4
4
  import { chunkInput } from '/input-chunks.mjs';
5
5
  import { decodeClipboardText } from '/clipboard-text.mjs';
6
+ import { currentVersion, loadAppVersion } from '/features/app-version.mjs';
7
+ import { createViewedWatch, createPictureLoop } from '/browser-picture.mjs';
6
8
 
7
9
  const API_ROOT = '/api/panes';
8
10
  const STATE_POLL_MS = 1200;
9
11
  const READ_POLL_MS = 180;
10
- const SNAPSHOT_POLL_MS = 1000;
12
+ // A browser pane a person can see keeps one request waiting on the server for
13
+ // its next picture, for this long at a time. A pane nobody can see asks only
14
+ // for its title, address and page prompt, this often; no picture is taken.
15
+ const SNAPSHOT_WAIT_MS = 500;
16
+ const SNAPSHOT_RETRY_MS = 60;
17
+ const SNAPSHOT_IDLE_MS = 3000;
11
18
  const MAX_HISTORY = 120000;
12
19
  const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
13
20
 
@@ -108,7 +115,10 @@ const MAXIMIZE_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" s
108
115
  const RESTORE_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 4v5H4M15 4v5h5M4 15h5v5M20 15h-5v5M9 9h6v6H9z"/></svg>';
109
116
  const LOCK_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>';
110
117
 
111
- let token = '';
118
+ // The page's own key, handed over once by the bootstrap route. It is the
119
+ // owner's: the server takes it for the person's page, and takes the workspace
120
+ // token for an agent, so this page never needs the token an agent holds.
121
+ let ownerKey = '';
112
122
  let currentState = null;
113
123
  let lastSignature = '';
114
124
  let currentTabId = null;
@@ -543,17 +553,28 @@ async function answerPageDialog(action) {
543
553
  }
544
554
  }
545
555
 
546
- async function api(path, { method = 'GET', body } = {}) {
547
- const headers = { 'X-Townmouse-Token': token };
556
+ async function sendAsOwner(path, method, body, signal) {
557
+ const headers = { 'X-Townmouse-Owner': ownerKey };
548
558
  if (body !== undefined) headers['Content-Type'] = 'application/json';
549
559
  const response = await fetch(API_ROOT + path, {
550
560
  method,
551
561
  headers,
552
562
  cache: 'no-store',
553
- body: body === undefined ? undefined : JSON.stringify(body)
563
+ body: body === undefined ? undefined : JSON.stringify(body),
564
+ ...(signal ? { signal } : {})
554
565
  });
555
566
  let payload = null;
556
567
  try { payload = await response.json(); } catch (_) { payload = null; }
568
+ return { response, payload };
569
+ }
570
+
571
+ async function api(path, { method = 'GET', body, signal } = {}) {
572
+ let { response, payload } = await sendAsOwner(path, method, body, signal);
573
+ // The server did not know the page's key: it restarted and minted a new
574
+ // one. Renew it once and ask again rather than drawing an agent's view.
575
+ if (response.status === 403 && payload && payload.code === 'UNKNOWN_KEY') {
576
+ if (await renewOwnerKey()) ({ response, payload } = await sendAsOwner(path, method, body, signal));
577
+ }
557
578
  if (!response.ok) {
558
579
  throw new Error((payload && payload.error) || `Request failed (${response.status}).`);
559
580
  }
@@ -643,8 +664,8 @@ function openReaderView() {
643
664
  function closeReaderView() {
644
665
  if (!els.readerView) return;
645
666
  els.readerView.hidden = true;
646
- const record = activeTerminalRecord();
647
- if (record && record.term) record.term.focus();
667
+ // The reader had the keyboard; it goes back to the active pane.
668
+ settleKeyboard(document.activeElement, activeTab());
648
669
  }
649
670
 
650
671
  function syncPaneMods() {
@@ -773,7 +794,7 @@ function paneCountLabel(count) {
773
794
  }
774
795
 
775
796
  async function refresh() {
776
- if (!token) return currentState;
797
+ if (!ownerKey) return currentState;
777
798
  if (refreshInFlight) {
778
799
  try { await refreshInFlight; } catch (_) { /* previous refresh already reported */ }
779
800
  }
@@ -797,6 +818,12 @@ async function refresh() {
797
818
 
798
819
  function applyState(next, { force = false } = {}) {
799
820
  if (!next || !Array.isArray(next.tabs)) return;
821
+ // A poll that left before a change can arrive after it. An older answer
822
+ // never replaces a newer one, so a grant just given does not flash back to
823
+ // Private, and a title does not flicker to what it was.
824
+ const older = currentState && next.epoch === currentState.epoch &&
825
+ Number(next.seq) < Number(currentState.seq);
826
+ if (!force && older) return;
800
827
  const previousTabId = currentState && currentState.activeTabId;
801
828
  currentState = next;
802
829
  updateChrome();
@@ -807,9 +834,6 @@ function applyState(next, { force = false } = {}) {
807
834
  if (force || signature !== lastSignature) {
808
835
  lastSignature = signature;
809
836
  rebuild(tab);
810
- if (!navigator.maxTouchPoints && tab) {
811
- requestAnimationFrame(() => focusPaneById(effectiveActivePaneId(tab), 'terminal'));
812
- }
813
837
  } else {
814
838
  updatePaneChrome(tab);
815
839
  }
@@ -817,11 +841,17 @@ function applyState(next, { force = false } = {}) {
817
841
  discardStaleOverlays();
818
842
  prunePaneMemory();
819
843
  if (els.tabsDialog.open) renderTabsDialog();
820
- if (tab) document.title = `${tab.title} — Panes`;
821
- else document.title = 'Panes — Townmouse';
844
+ updateDocumentTitle(tab);
822
845
  if (previousTabId && tab && previousTabId !== tab.id) logStatus(`Switched to ${tab.title}.`);
823
846
  }
824
847
 
848
+ function updateDocumentTitle(tab) {
849
+ // The version rides in the title, so the window itself says what is running.
850
+ const version = currentVersion();
851
+ if (tab) document.title = `${tab.title} — Panes${version ? ` · Townmouse ${version}` : ''}`;
852
+ else document.title = `Panes — Townmouse${version ? ` ${version}` : ''}`;
853
+ }
854
+
825
855
  function updateChrome() {
826
856
  const tabs = (currentState && currentState.tabs) || [];
827
857
  els.tabCount.textContent = String(tabs.length);
@@ -846,14 +876,20 @@ function renderTabStrip() {
846
876
  list.setAttribute('aria-label', 'Workspace tabs');
847
877
  for (const tab of tabs) {
848
878
  const active = tab.id === currentState.activeTabId;
879
+ // An ask waiting in a tab the person is not looking at is marked here, so
880
+ // it is not left waiting unseen.
881
+ const waiting = tab.panes.some((pane) => pane.accessRequest);
849
882
  const item = document.createElement('div');
850
- item.className = 'tabstrip-item' + (active ? ' is-active' : '');
883
+ item.className = 'tabstrip-item' + (active ? ' is-active' : '') + (waiting ? ' has-ask' : '');
851
884
  item.dataset.createdBy = tab.createdBy || 'human';
852
885
  const button = document.createElement('button');
853
886
  button.type = 'button';
854
887
  button.className = 'tabstrip-tab' + (active ? ' is-active' : '') + (tab.createdBy === 'agent' ? ' agent-tab' : '');
855
888
  button.textContent = tab.title;
856
- if (tab.createdBy === 'agent') button.title = `${tab.title} — created by an agent`;
889
+ const hint = waiting
890
+ ? `${tab.title} — an agent is waiting for your answer`
891
+ : (tab.createdBy === 'agent' ? `${tab.title} — created by an agent` : '');
892
+ if (hint) button.title = hint;
857
893
  button.setAttribute('role', 'tab');
858
894
  button.setAttribute('aria-selected', active ? 'true' : 'false');
859
895
  button.setAttribute('aria-controls', 'pane-grid');
@@ -1021,9 +1057,12 @@ function applyPaneLayout(tab) {
1021
1057
  }
1022
1058
 
1023
1059
  function rebuild(tab) {
1060
+ // A rebuild can move nodes (a pane is added ahead of others, a tab is left),
1061
+ // and moving the node someone is typing in takes the keyboard away. Where the
1062
+ // keyboard was is kept, and given back below.
1063
+ const keyboard = document.activeElement;
1024
1064
  const nextTabId = tab ? tab.id : null;
1025
1065
  const panes = tab ? tab.panes : [];
1026
- const nextIds = new Set(panes.map((pane) => pane.id));
1027
1066
 
1028
1067
  if (nextTabId !== currentTabId) {
1029
1068
  // A tab switch is the one time terminals are discarded outright; their
@@ -1052,21 +1091,140 @@ function rebuild(tab) {
1052
1091
  els.grid.hidden = true;
1053
1092
  els.emptyState.hidden = false;
1054
1093
  updateEmptyState(tab);
1094
+ settleKeyboard(keyboard, tab);
1055
1095
  return;
1056
1096
  }
1057
1097
  els.grid.hidden = false;
1058
1098
  els.emptyState.hidden = true;
1059
- for (const pane of panes) {
1099
+ panes.forEach((pane, index) => {
1060
1100
  const existing = records.get(pane.id);
1061
1101
  const node = existing
1062
1102
  ? existing.root
1063
1103
  : (pane.kind === 'browser' ? createBrowserPane(pane) : createTerminalPane(pane));
1064
- // Appending an existing node only reorders it; its xterm DOM lives on.
1065
- els.grid.append(node);
1066
- }
1104
+ // A pane that is already in its place is left where it is: its xterm DOM
1105
+ // lives on, and so does whatever has the keyboard inside it. A new pane, or
1106
+ // one that changed position, is put at its place.
1107
+ if (els.grid.children[index] !== node) els.grid.insertBefore(node, els.grid.children[index] || null);
1108
+ });
1067
1109
  updatePaneChrome(tab);
1068
1110
  applyPaneLayout(tab);
1069
1111
  syncMaximizeButtons();
1112
+ settleKeyboard(keyboard, tab);
1113
+ }
1114
+
1115
+ // ─── The keyboard ──────────────────────────────────────────────────────────
1116
+ // The rules, in one place.
1117
+ //
1118
+ // 1. The keyboard goes where the person puts it, or where one of their actions
1119
+ // says: "Add browser pane" to the new pane's address box, the Keyboard button
1120
+ // to the active pane, Alt+Arrow to the next pane. Until such an action has
1121
+ // placed it, nothing else moves it.
1122
+ // 2. A rebuild of the panes never moves it. If what had it is still in the
1123
+ // document, it gets it back; if it has nowhere to live (its pane closed, its
1124
+ // tab was left), the active pane's typing target takes it.
1125
+ // 3. A sheet, the reader or a page prompt has the keyboard while it is open:
1126
+ // nothing takes it from them, and a sheet hands it back to the pane the
1127
+ // person was in when they close it.
1128
+ // 4. Nothing moves the keyboard on a touch screen on its own: focusing a box
1129
+ // there raises the soft keyboard.
1130
+ //
1131
+ // Before this, the rebuild focused the active pane from a later frame, so it
1132
+ // could take the keyboard from the address box a person had just been given,
1133
+ // and from an open sheet.
1134
+
1135
+ // The last place inside the panes that had the keyboard.
1136
+ let lastPaneFocus = null;
1137
+ // The one terminal that is to take the keyboard once it is mounted; a newer
1138
+ // request replaces an older one, and only if the keyboard has not moved since.
1139
+ let keyboardWaitsFor = null;
1140
+ // An action has said where the keyboard goes next and is getting there (adding
1141
+ // a pane takes the server a moment). Until it has, nothing else moves it, so
1142
+ // nothing typed in the meantime can run in a terminal. The value says which
1143
+ // kind of pane is coming.
1144
+ let keyboardSpokenFor = '';
1145
+ // Keys typed while a browser pane is being added, kept for its address box: a
1146
+ // fast typist must not lose the start of the address.
1147
+ let keysForNewPane = '';
1148
+ // A person is closing a sheet on purpose (Escape, or a pointer on its close
1149
+ // control). A sheet can also be closed by a stray Space or Enter, which presses
1150
+ // the control that has the keyboard; then the keyboard stays where the browser
1151
+ // puts it and the rest of what is typed reaches no terminal.
1152
+ let keyboardReturns = false;
1153
+
1154
+ function overlayOpen() {
1155
+ return [els.tabsDialog, els.menuDialog, els.shortcutsDialog, els.closeConfirm].some((dialog) => dialog && dialog.open)
1156
+ || !els.readerView.hidden
1157
+ || !els.pageDialog.hidden
1158
+ || !els.browserControl.hidden
1159
+ || !els.contextMenu.hidden
1160
+ || !els.browserContextMenu.hidden;
1161
+ }
1162
+
1163
+ // Where the keyboard may stay when the panes are rebuilt.
1164
+ function keepsKeyboard(element) {
1165
+ return Boolean(element && element.closest('.pane, dialog, .reader-view, .page-dialog, .context-menu'));
1166
+ }
1167
+
1168
+ function settleKeyboard(previously, tab) {
1169
+ if (navigator.maxTouchPoints || overlayOpen() || keyboardSpokenFor) return;
1170
+ if (previously && previously.isConnected && keepsKeyboard(previously)) {
1171
+ if (document.activeElement === previously) return;
1172
+ previously.focus({ preventScroll: true });
1173
+ if (document.activeElement === previously) return;
1174
+ }
1175
+ const record = records.get(effectiveActivePaneId(tab));
1176
+ if (record) {
1177
+ focusPaneById(record.id, record.kind === 'browser' ? 'type' : 'terminal');
1178
+ } else if (!els.emptyState.hidden) {
1179
+ // The tab is empty: the way on is the first thing the empty state offers.
1180
+ els.emptyAddTerminal.focus({ preventScroll: true });
1181
+ }
1182
+ }
1183
+
1184
+ // A sheet that a person closed had the keyboard; give it back to where the
1185
+ // person was in the panes.
1186
+ function returnKeyboardToPanes() {
1187
+ if (!keyboardReturns) return;
1188
+ keyboardReturns = false;
1189
+ if (navigator.maxTouchPoints || overlayOpen() || keyboardSpokenFor) return;
1190
+ const focused = document.activeElement;
1191
+ if (focused && focused !== document.body && focused.closest('.pane')) return;
1192
+ if (lastPaneFocus && lastPaneFocus.isConnected) lastPaneFocus.focus({ preventScroll: true });
1193
+ }
1194
+
1195
+ document.addEventListener('focusin', (event) => {
1196
+ const element = event.target;
1197
+ if (element instanceof Element && element.closest('.pane')) lastPaneFocus = element;
1198
+ }, true);
1199
+
1200
+ function takesText(element) {
1201
+ return element instanceof HTMLElement
1202
+ && (element.isContentEditable || element.tagName === 'INPUT' || element.tagName === 'TEXTAREA');
1203
+ }
1204
+
1205
+ // Typed in the moment between choosing "Add browser pane" and its box having
1206
+ // the keyboard: kept for the box. Keys typed into anything that can take text
1207
+ // are not ours to keep, and a composed key cannot be kept.
1208
+ document.addEventListener('keydown', (event) => {
1209
+ if (keyboardSpokenFor !== 'browser' || event.defaultPrevented) return;
1210
+ if (event.metaKey || event.ctrlKey || event.altKey || event.isComposing) return;
1211
+ if (takesText(event.target)) return;
1212
+ if (event.key.length === 1) keysForNewPane += event.key;
1213
+ else if (event.key === 'Backspace') keysForNewPane = keysForNewPane.slice(0, -1);
1214
+ else if (event.key === 'Enter') keysForNewPane += '\n';
1215
+ else return;
1216
+ event.preventDefault();
1217
+ }, { capture: true });
1218
+
1219
+ // The new browser pane's address box has the keyboard: it gets what was typed
1220
+ // while it was being made, and Enter sends it if Enter was typed too.
1221
+ function giveNewPaneItsKeys(record) {
1222
+ const typed = keysForNewPane;
1223
+ keysForNewPane = '';
1224
+ if (!typed || !record || record.disposed || record.kind !== 'browser') return;
1225
+ record.addressInput.value = typed.replace(/\n$/, '');
1226
+ record.addressInput.dispatchEvent(new Event('input', { bubbles: true }));
1227
+ if (typed.endsWith('\n')) record.addressForm.requestSubmit();
1070
1228
  }
1071
1229
 
1072
1230
  // Maximize/restore is available both from Alt+M and from a visible control in
@@ -1120,6 +1278,177 @@ function formatAge(ms) {
1120
1278
  return `${Math.round(hours / 24)}d`;
1121
1279
  }
1122
1280
 
1281
+ // ─── Agent access ──────────────────────────────────────────────────────────
1282
+ //
1283
+ // The answer to the only question that matters about a pane: what can an
1284
+ // agent do in it? Each of the owner's panes says so in its header, and the
1285
+ // same control changes it: Private, View only, Allow control, which are the
1286
+ // terminal surface's three levels in its own words. An agent's pane carries
1287
+ // its "agent" badge instead and needs no control. When an agent asks for
1288
+ // access, the ask docks under the header of the pane it is about and pushes
1289
+ // that pane's content down; nothing is drawn over a live pane.
1290
+
1291
+ const ACCESS_LEVELS = ['private', 'view', 'control'];
1292
+ const ACCESS_LABEL = { private: 'Private', view: 'View only', control: 'Allow control' };
1293
+
1294
+ function accessLevelOf(pane) {
1295
+ const level = pane && pane.agentAccess && pane.agentAccess.level;
1296
+ return ACCESS_LABEL[level] ? level : 'private';
1297
+ }
1298
+
1299
+ function attachPaneAccess(root, record, pane) {
1300
+ root.dataset.agentAccess = accessLevelOf(pane);
1301
+ if (pane.createdBy === 'agent') return;
1302
+ const header = root.querySelector('.pane-header');
1303
+ if (!header) return;
1304
+ const label = document.createElement('label');
1305
+ label.className = 'pane-access';
1306
+ const caption = document.createElement('span');
1307
+ caption.className = 'pane-access-label';
1308
+ caption.setAttribute('aria-hidden', 'true');
1309
+ caption.textContent = 'Agent access';
1310
+ const select = document.createElement('select');
1311
+ select.className = 'pane-access-select';
1312
+ select.setAttribute('aria-label', 'Agent access');
1313
+ select.title = 'What an agent may do in this pane';
1314
+ for (const level of ACCESS_LEVELS) {
1315
+ const option = document.createElement('option');
1316
+ option.value = level;
1317
+ option.textContent = ACCESS_LABEL[level];
1318
+ select.append(option);
1319
+ }
1320
+ select.value = accessLevelOf(pane);
1321
+ select.addEventListener('change', () => { void setPaneAccess(record, select.value); });
1322
+ label.append(caption, select);
1323
+ header.insertBefore(label, root.querySelector('.pane-maximize'));
1324
+
1325
+ const ask = document.createElement('div');
1326
+ ask.className = 'pane-ask';
1327
+ ask.setAttribute('role', 'region');
1328
+ ask.setAttribute('aria-label', 'Agent access request');
1329
+ ask.hidden = true;
1330
+ root.insertBefore(ask, root.querySelector('.pane-body'));
1331
+ record.accessSelect = select;
1332
+ record.askEl = ask;
1333
+ }
1334
+
1335
+ // The header says one level in both of its ways at once: the word in the
1336
+ // control and the tone around it never disagree.
1337
+ function showPaneAccess(record, level) {
1338
+ if (record.root.dataset.agentAccess !== level) record.root.dataset.agentAccess = level;
1339
+ if (record.accessSelect && record.accessSelect.value !== level) record.accessSelect.value = level;
1340
+ }
1341
+
1342
+ function syncPaneAccess(record, pane) {
1343
+ // While the person is choosing in the control, or a change of theirs is on
1344
+ // its way, the header keeps saying what it said: a poll arriving then must
1345
+ // neither pull the control back nor recolour it under them.
1346
+ const held = record.accessBusy || document.activeElement === record.accessSelect;
1347
+ if (!held) showPaneAccess(record, accessLevelOf(pane));
1348
+ renderPaneAsk(record, pane);
1349
+ }
1350
+
1351
+ // A change the page itself made has landed: the header shows what the server
1352
+ // says now. Focus does not hold it back here, because an answer given on the
1353
+ // ask strip moves the focus onto the control as the strip goes.
1354
+ function settlePaneAccess(record) {
1355
+ record.accessBusy = false;
1356
+ let pane = null;
1357
+ for (const tab of (currentState && currentState.tabs) || []) {
1358
+ pane = (tab.panes || []).find((candidate) => candidate.id === record.id);
1359
+ if (pane) break;
1360
+ }
1361
+ showPaneAccess(record, pane ? accessLevelOf(pane) : record.root.dataset.agentAccess);
1362
+ }
1363
+
1364
+ async function setPaneAccess(record, level) {
1365
+ record.accessBusy = true;
1366
+ try {
1367
+ applyState(await api(`/panes/${record.id}/permission`, { method: 'POST', body: { permission: level } }));
1368
+ const said = level === 'private' ? 'Sharing revoked. Agents can no longer reach this pane.'
1369
+ : `Agents can now ${level === 'view' ? 'look at' : 'control'} this pane.`;
1370
+ showNotice(said, 'info', 3200);
1371
+ logStatus(said);
1372
+ } catch (error) {
1373
+ showNotice(error.message || 'Could not change what an agent may do.', 'error');
1374
+ } finally {
1375
+ settlePaneAccess(record);
1376
+ }
1377
+ }
1378
+
1379
+ // An ask is redrawn only when it is a different ask, so a poll arriving while
1380
+ // the person is reading it does not rebuild the buttons under their finger.
1381
+ function renderPaneAsk(record, pane) {
1382
+ const ask = record.askEl;
1383
+ if (!ask) return;
1384
+ const request = pane.accessRequest || null;
1385
+ const signature = request ? `${request.at}:${request.level}` : '';
1386
+ if (signature === record.askRendered) return;
1387
+ const heldFocus = ask.contains(document.activeElement);
1388
+ record.askRendered = signature;
1389
+ ask.replaceChildren();
1390
+ if (!request) {
1391
+ ask.hidden = true;
1392
+ if (heldFocus && record.accessSelect) record.accessSelect.focus();
1393
+ return;
1394
+ }
1395
+ const text = document.createElement('p');
1396
+ text.className = 'pane-ask-text';
1397
+ const lead = document.createElement('strong');
1398
+ lead.textContent = `An agent asks for ${request.label}.`;
1399
+ text.append(lead, request.message ? ` ${request.message}` : '');
1400
+ const actions = document.createElement('div');
1401
+ actions.className = 'pane-ask-actions';
1402
+ const answer = (label, value, primary) => {
1403
+ const button = document.createElement('button');
1404
+ button.type = 'button';
1405
+ button.className = 'btn' + (primary ? ' btn-primary' : value === 'decline' ? ' btn-quiet' : '');
1406
+ button.textContent = label;
1407
+ button.addEventListener('click', () => {
1408
+ // A second press while the answer is on its way does nothing. The
1409
+ // buttons are not disabled for it: a disabled button drops the
1410
+ // keyboard focus, and the focus is about to move to the control.
1411
+ if (record.askBusy) return;
1412
+ record.askBusy = true;
1413
+ void answerPaneAsk(record, value);
1414
+ });
1415
+ return button;
1416
+ };
1417
+ // Least to most, the order of the levels themselves; the answer to the ask
1418
+ // is the primary control on the right, where this surface puts it.
1419
+ actions.append(answer('Not now', 'decline'));
1420
+ if (request.level === 'control') actions.append(answer(ACCESS_LABEL.view, 'view'));
1421
+ actions.append(answer(ACCESS_LABEL[request.level], request.level, true));
1422
+ ask.append(text, actions);
1423
+ ask.hidden = false;
1424
+ logStatus(`An agent asks for ${request.label} on ${record.titleEl.textContent}.`);
1425
+ }
1426
+
1427
+ async function answerPaneAsk(record, value) {
1428
+ try {
1429
+ if (value === 'decline') {
1430
+ await api(`/panes/${record.id}/request-access`, { method: 'DELETE' });
1431
+ await refresh();
1432
+ const said = 'Told the agent not now. What an agent may do is unchanged.';
1433
+ showNotice(said, 'info', 3200);
1434
+ logStatus(said);
1435
+ return;
1436
+ }
1437
+ record.accessBusy = true;
1438
+ applyState(await api(`/panes/${record.id}/permission`, { method: 'POST', body: { permission: value } }));
1439
+ const said = `Agents can now ${value === 'view' ? 'look at' : 'control'} this pane.`;
1440
+ showNotice(said, 'info', 3200);
1441
+ logStatus(said);
1442
+ } catch (error) {
1443
+ showNotice(error.message || 'Could not answer the agent.', 'error');
1444
+ record.askRendered = '';
1445
+ await refresh();
1446
+ } finally {
1447
+ record.askBusy = false;
1448
+ settlePaneAccess(record);
1449
+ }
1450
+ }
1451
+
1123
1452
  function updatePaneChrome(tab) {
1124
1453
  if (!tab) { updateBackButton(); updateKeybar(); updateHostContext(); return; }
1125
1454
  const activeId = effectiveActivePaneId(tab);
@@ -1131,6 +1460,7 @@ function updatePaneChrome(tab) {
1131
1460
  if (record.titleEl.textContent !== title) record.titleEl.textContent = title;
1132
1461
  record.titleEl.title = title;
1133
1462
  record.closeButton.setAttribute('aria-label', `Close ${pane.kind} pane ${title}`);
1463
+ syncPaneAccess(record, pane);
1134
1464
  if (record.kind === 'terminal') {
1135
1465
  const status = pane.status === 'exited' ? 'exited' : 'running';
1136
1466
  if (record.root.dataset.status !== status) record.root.dataset.status = status;
@@ -1154,8 +1484,8 @@ function updatePaneChrome(tab) {
1154
1484
  : `Program: ${status}. The agent has not reported a status.`) + commandText;
1155
1485
  } else {
1156
1486
  if (record.kindEl.textContent !== 'Browser') record.kindEl.textContent = 'Browser';
1157
- if (pane.url && !record.addressDirty && document.activeElement !== record.addressInput && record.addressInput.value !== pane.url) {
1158
- record.addressInput.value = pane.url;
1487
+ if (pane.url && !record.addressDirty && document.activeElement !== record.addressInput && record.addressInput.value !== addressBoxText(pane.url)) {
1488
+ record.addressInput.value = addressBoxText(pane.url);
1159
1489
  }
1160
1490
  record.currentUrl = pane.url || record.currentUrl;
1161
1491
  }
@@ -1268,7 +1598,8 @@ function disposeRecord(record, { keepInput = false } = {}) {
1268
1598
  if (pump.inputTimer) { clearTimeout(pump.inputTimer); pump.inputTimer = 0; }
1269
1599
  inputPumps.delete(record.id);
1270
1600
  }
1271
- if (record.snapshotTimer) { clearTimeout(record.snapshotTimer); record.snapshotTimer = 0; }
1601
+ if (record.viewWatch) { record.viewWatch.stop(); record.viewWatch = null; }
1602
+ if (record.pictures) { record.pictures.stop(); record.pictures = null; }
1272
1603
  if (record.wheelTimer) { clearTimeout(record.wheelTimer); record.wheelTimer = 0; }
1273
1604
  if (record.fitFrame) { cancelAnimationFrame(record.fitFrame); record.fitFrame = 0; }
1274
1605
  if (record.resizeObserver) {
@@ -1318,6 +1649,13 @@ function createTerminalPane(pane) {
1318
1649
  streamController: null,
1319
1650
  offset: cursors.get(pane.id) || 0,
1320
1651
  lastResize: '',
1652
+ // The widest the shell has been; what it printed was laid out for it.
1653
+ maxCols: Number(pane.maxCols) || 0,
1654
+ // Set while the terminal shows the shell's own width (see "A terminal that
1655
+ // opened at the shell's width").
1656
+ opensWide: false,
1657
+ parsedOffset: cursors.get(pane.id) || 0,
1658
+ fitAfterOffset: null,
1321
1659
  exited: false,
1322
1660
  pendingStart: pane.status === 'starting',
1323
1661
  starting: false,
@@ -1331,6 +1669,7 @@ function createTerminalPane(pane) {
1331
1669
  root.addEventListener('focusin', () => { void setActivePane(pane.id); });
1332
1670
  record.closeButton.addEventListener('click', () => { requestClose('pane', pane.id, record.titleEl.textContent); });
1333
1671
  records.set(pane.id, record);
1672
+ attachPaneAccess(root, record, pane);
1334
1673
  wireDrop(root, pane.id);
1335
1674
  wirePaneReorder(root, pane.id);
1336
1675
  wirePaneContext(root, record);
@@ -1379,6 +1718,15 @@ function mountTerminal(record) {
1379
1718
  }
1380
1719
  record.term = term;
1381
1720
  record.fit = fit;
1721
+ // A shell the server started on its own begins at 100 columns, and a phone
1722
+ // shows about 60: what such a shell has printed was laid out for a width
1723
+ // wider than the pane. A line as wide as the shell wraps in a narrower grid,
1724
+ // and what follows it lands a row off. That is the mark zsh prints in front
1725
+ // of a prompt, left behind as a block at the top of the pane. So the terminal
1726
+ // opens at the shell's width and is fitted to the pane only once the shell
1727
+ // has been given the pane's size and all that was printed before is in (see
1728
+ // "A terminal that opened at the shell's width"). onResize reports sizes to
1729
+ // the shell; the wide size is never one of them.
1382
1730
  // Terminal copy: Cmd/Ctrl+C with a selection copies; with no selection it
1383
1731
  // still reaches the PTY as SIGINT, matching terminal expectations.
1384
1732
  term.attachCustomKeyEventHandler((event) => {
@@ -1396,11 +1744,22 @@ function mountTerminal(record) {
1396
1744
  if (!record.disposed && data) sendTerminalInput(record, data);
1397
1745
  });
1398
1746
  term.onResize(({ cols, rows }) => {
1399
- if (!record.disposed) sendTerminalResize(record, cols, rows);
1747
+ if (!record.disposed && !record.opensWide) sendTerminalResize(record, cols, rows);
1400
1748
  });
1749
+ handKeyboardToTerminal(record);
1401
1750
  const history = histories.get(record.id);
1402
1751
  requestAnimationFrame(() => {
1403
1752
  if (record.disposed || !record.term) return;
1753
+ // The pane's room, with the font size set (applyFontSize below has run).
1754
+ const room = record.fit.proposeDimensions();
1755
+ record.opensWide = !record.pendingStart && Boolean(room) && record.maxCols > room.cols;
1756
+ if (record.opensWide) {
1757
+ term.resize(record.maxCols, room.rows);
1758
+ if (history) writeTerminalOutput(record, history, record.offset);
1759
+ void startTerminalStream(record);
1760
+ fitToPaneWhenCaughtUp(record, room);
1761
+ return;
1762
+ }
1404
1763
  // Fit before replaying or spawning: the first prompt and the local history
1405
1764
  // must be laid out at the pane's real width, not xterm's default grid.
1406
1765
  safeFit(record);
@@ -1456,8 +1815,67 @@ async function startPendingTerminal(record) {
1456
1815
  }
1457
1816
  }
1458
1817
 
1818
+ // ─── The keyboard and a terminal that is still being mounted ───────────────
1819
+
1820
+ // A terminal that was asked for the keyboard before it was mounted takes it
1821
+ // now, unless the keyboard has moved elsewhere since or a sheet has it.
1822
+ function handKeyboardToTerminal(record) {
1823
+ const waiting = keyboardWaitsFor;
1824
+ if (!waiting || waiting.paneId !== record.id || !record.term) return;
1825
+ keyboardWaitsFor = null;
1826
+ if (!overlayOpen() && document.activeElement === waiting.was) record.term.focus();
1827
+ }
1828
+
1829
+ // ─── A terminal that opened at the shell's width ───────────────────────────
1830
+ // The pane's size is sent at once. The server answers with the point in the
1831
+ // output from which on the shell writes for that size. Until everything up to
1832
+ // that point has not only arrived but been parsed, the terminal stays at the
1833
+ // shell's width; then it is fitted to the pane, and the terminal reflows, as it
1834
+ // does when a window narrows.
1835
+
1836
+ function fitToPaneWhenCaughtUp(record, room) {
1837
+ // The fit will report this same size; it need not be sent twice.
1838
+ record.lastResize = `${room.cols}x${room.rows}`;
1839
+ api(`/panes/${record.id}/resize`, { method: 'POST', body: { cols: room.cols, rows: room.rows } })
1840
+ .then((size) => {
1841
+ if (record.disposed) return;
1842
+ record.fitAfterOffset = Number.isFinite(Number(size && size.offset)) ? Number(size.offset) : record.parsedOffset;
1843
+ fitWhenCaughtUp(record);
1844
+ })
1845
+ .catch(() => {
1846
+ // The shell was not told. The pane must not stay wider than its room: fit
1847
+ // now, and the fit sends the size again.
1848
+ record.lastResize = '';
1849
+ if (record.disposed) return;
1850
+ record.fitAfterOffset = record.parsedOffset;
1851
+ fitWhenCaughtUp(record);
1852
+ });
1853
+ }
1854
+
1855
+ // Output for a terminal that opened wide is parsed at that width. Each piece
1856
+ // says when it is parsed, and the piece that reaches the point the server named
1857
+ // fits the terminal to the pane.
1858
+ function writeTerminalOutput(record, data, offset) {
1859
+ offset = Number.isFinite(offset) ? offset : record.parsedOffset;
1860
+ if (!record.opensWide) {
1861
+ record.term.write(data);
1862
+ return;
1863
+ }
1864
+ record.term.write(data, () => {
1865
+ record.parsedOffset = offset;
1866
+ fitWhenCaughtUp(record);
1867
+ });
1868
+ }
1869
+
1870
+ function fitWhenCaughtUp(record) {
1871
+ if (record.disposed || !record.term || !record.opensWide) return;
1872
+ if (record.fitAfterOffset === null || record.parsedOffset < record.fitAfterOffset) return;
1873
+ record.opensWide = false;
1874
+ safeFit(record);
1875
+ }
1876
+
1459
1877
  function safeFit(record) {
1460
- if (record.disposed || !record.fit || !record.term) return;
1878
+ if (record.disposed || !record.fit || !record.term || record.opensWide) return;
1461
1879
  const rect = record.host.getBoundingClientRect();
1462
1880
  if (rect.width < 24 || rect.height < 24) return;
1463
1881
  try { record.fit.fit(); } catch (_) { /* layout not ready yet */ }
@@ -1519,7 +1937,7 @@ async function startTerminalStream(record) {
1519
1937
  record.streamController = controller;
1520
1938
  try {
1521
1939
  const response = await fetch(`/api/panes/panes/${record.id}/stream?since=${record.offset || 0}`, {
1522
- headers: { 'X-Townmouse-Token': token },
1940
+ headers: { 'X-Townmouse-Owner': ownerKey },
1523
1941
  signal: controller.signal,
1524
1942
  cache: 'no-store'
1525
1943
  });
@@ -1541,7 +1959,7 @@ async function startTerminalStream(record) {
1541
1959
  try { payload = JSON.parse(line.slice(6)); } catch (_) { continue; }
1542
1960
  if (!record.term || record.disposed) continue;
1543
1961
  if (payload.data) {
1544
- record.term.write(payload.data);
1962
+ writeTerminalOutput(record, payload.data, Number(payload.offset));
1545
1963
  rememberOutput(record.id, payload.data);
1546
1964
  }
1547
1965
  if (Number.isFinite(Number(payload.offset))) {
@@ -1566,7 +1984,7 @@ function startTerminalRead(record) {
1566
1984
  const payload = await api(`/panes/${record.id}/read?since=${record.offset || 0}`);
1567
1985
  if (record.disposed || !record.term) return;
1568
1986
  if (payload && payload.data) {
1569
- record.term.write(payload.data);
1987
+ writeTerminalOutput(record, payload.data, Number(payload.offset));
1570
1988
  rememberOutput(record.id, payload.data);
1571
1989
  }
1572
1990
  const nextOffset = Number(payload && payload.offset);
@@ -1602,6 +2020,13 @@ function rememberOutput(paneId, data) {
1602
2020
  histories.set(paneId, value.length > MAX_HISTORY ? value.slice(-MAX_HISTORY) : value);
1603
2021
  }
1604
2022
 
2023
+ // What the address box shows for a page. A pane that shows no page yet shows
2024
+ // an empty box, never "about:blank": text typed into that made an address that
2025
+ // could not open ("abouexample.comt:blank", "Invalid URL").
2026
+ function addressBoxText(url) {
2027
+ return url && url !== 'about:blank' ? url : '';
2028
+ }
2029
+
1605
2030
  function createBrowserPane(pane) {
1606
2031
  const root = document.createElement('section');
1607
2032
  root.className = 'pane pane-browser';
@@ -1659,10 +2084,10 @@ function createBrowserPane(pane) {
1659
2084
  height: 800,
1660
2085
  currentUrl: pane.url || '',
1661
2086
  addressDirty: false,
1662
- lastImage: '',
1663
- snapshotBusy: false,
1664
- snapshotWanted: false,
1665
- snapshotTimer: 0,
2087
+ // Whether a person can see this pane right now, and its picture stream.
2088
+ viewed: false,
2089
+ pictures: null,
2090
+ viewWatch: null,
1666
2091
  wheelDelta: 0,
1667
2092
  wheelDeltaX: 0,
1668
2093
  wheelTimer: 0,
@@ -1678,7 +2103,7 @@ function createBrowserPane(pane) {
1678
2103
  record.closeButton.setAttribute('aria-label', `Close browser pane ${pane.title || 'Browser'}`);
1679
2104
  record.maximizeButton = root.querySelector('.pane-maximize');
1680
2105
  record.maximizeButton.addEventListener('click', () => { togglePaneMaximized(pane.id); });
1681
- record.addressInput.value = pane.url && pane.url !== 'about:blank' ? pane.url : '';
2106
+ record.addressInput.value = addressBoxText(pane.url);
1682
2107
  record.backButton.disabled = true;
1683
2108
  record.forwardButton.disabled = true;
1684
2109
 
@@ -1698,7 +2123,7 @@ function createBrowserPane(pane) {
1698
2123
  window.setTimeout(() => {
1699
2124
  if (record.disposed || !record.addressDirty || document.activeElement === record.addressInput) return;
1700
2125
  record.addressDirty = false;
1701
- record.addressInput.value = record.currentUrl || '';
2126
+ record.addressInput.value = addressBoxText(record.currentUrl);
1702
2127
  }, 250);
1703
2128
  });
1704
2129
  record.typeForm.addEventListener('submit', (event) => {
@@ -1721,6 +2146,8 @@ function createBrowserPane(pane) {
1721
2146
  }
1722
2147
  });
1723
2148
  record.image.addEventListener('keydown', (event) => {
2149
+ // A key with Cmd, Ctrl or Alt is not typed into the page. The browser's zoom
2150
+ // chords are cancelled for the whole surface, wherever the keyboard is.
1724
2151
  if (event.metaKey || event.ctrlKey || event.altKey) return;
1725
2152
  if (event.key.length === 1) {
1726
2153
  event.preventDefault();
@@ -1756,9 +2183,34 @@ function createBrowserPane(pane) {
1756
2183
  record.view.addEventListener('touchend', () => { touchActive = false; }, { passive: true });
1757
2184
 
1758
2185
  records.set(pane.id, record);
2186
+ attachPaneAccess(root, record, pane);
1759
2187
  wireDrop(root, pane.id);
1760
2188
  wirePaneReorder(root, pane.id);
1761
2189
  wireBrowserContext(record);
2190
+ // The pane's picture: fast while a person can see the pane, nothing (only
2191
+ // its title, address and page prompt) while they cannot.
2192
+ record.pictures = createPictureLoop({
2193
+ waitMs: SNAPSHOT_WAIT_MS,
2194
+ retryMs: SNAPSHOT_RETRY_MS,
2195
+ idleMs: SNAPSHOT_IDLE_MS,
2196
+ viewed: () => record.viewed,
2197
+ request: ({ watching, since, waitMs, signal }) => api(
2198
+ `/panes/${record.id}/browser/snapshot${watching ? `?watch=1&since=${since}&wait=${waitMs}` : '?watch=0'}`,
2199
+ { signal }
2200
+ ),
2201
+ apply: (snapshot, fresh) => applySnapshot(record, snapshot, fresh),
2202
+ failure: () => {
2203
+ if (record.disposed) return;
2204
+ record.root.classList.add('is-offline');
2205
+ record.reopenButton.hidden = false;
2206
+ }
2207
+ });
2208
+ record.viewWatch = createViewedWatch(record.view, (viewed) => {
2209
+ record.viewed = viewed;
2210
+ if (record.disposed) return;
2211
+ if (viewed) requestSnapshot(record, 0);
2212
+ else record.pictures.unseen();
2213
+ });
1762
2214
  const resizeBrowser = () => {
1763
2215
  if (record.disposed || !record.root.isConnected) return;
1764
2216
  // Fixed-size mode: the human's viewer never rearranges the page. The image
@@ -1838,43 +2290,16 @@ async function toggleBrowserSizing(record) {
1838
2290
  }
1839
2291
  }
1840
2292
 
2293
+ // Ask for the pane's picture soon. While the pane can be seen the request goes
2294
+ // out at once (it waits on the server for the picture, so the old pause for a
2295
+ // repaint is not needed); while it cannot, after `delay` ms, without a picture.
1841
2296
  function requestSnapshot(record, delay = 0) {
1842
- if (record.disposed) return;
1843
- if (record.snapshotBusy) {
1844
- record.snapshotWanted = true;
1845
- return;
1846
- }
1847
- if (record.snapshotTimer) clearTimeout(record.snapshotTimer);
1848
- record.snapshotTimer = window.setTimeout(() => {
1849
- record.snapshotTimer = 0;
1850
- void pollSnapshot(record);
1851
- }, Math.max(0, delay));
1852
- }
1853
-
1854
- async function pollSnapshot(record) {
1855
- if (record.disposed || !record.root.isConnected) return;
1856
- if (record.snapshotBusy) {
1857
- record.snapshotWanted = true;
1858
- return;
1859
- }
1860
- record.snapshotBusy = true;
1861
- record.snapshotWanted = false;
1862
- try {
1863
- const snapshot = await api(`/panes/${record.id}/browser/snapshot`);
1864
- if (record.disposed) return;
1865
- applySnapshot(record, snapshot);
1866
- } catch (error) {
1867
- if (!record.disposed) {
1868
- record.root.classList.add('is-offline');
1869
- record.reopenButton.hidden = false;
1870
- }
1871
- } finally {
1872
- record.snapshotBusy = false;
1873
- if (!record.disposed) requestSnapshot(record, record.snapshotWanted ? 120 : SNAPSHOT_POLL_MS);
1874
- }
2297
+ if (record.disposed || !record.pictures) return;
2298
+ record.pictures.ask(delay);
1875
2299
  }
1876
2300
 
1877
- function applySnapshot(record, snapshot) {
2301
+ // `fresh`: the answer carries a picture the pane has not shown yet.
2302
+ function applySnapshot(record, snapshot, fresh = Boolean(snapshot && snapshot.image)) {
1878
2303
  if (!snapshot) return;
1879
2304
  const width = Number(snapshot.width);
1880
2305
  const height = Number(snapshot.height);
@@ -1882,8 +2307,8 @@ function applySnapshot(record, snapshot) {
1882
2307
  if (Number.isFinite(height) && height > 0) record.height = height;
1883
2308
  if (snapshot.url) {
1884
2309
  record.currentUrl = snapshot.url;
1885
- if (!record.addressDirty && document.activeElement !== record.addressInput && record.addressInput.value !== snapshot.url) {
1886
- record.addressInput.value = snapshot.url;
2310
+ if (!record.addressDirty && document.activeElement !== record.addressInput && record.addressInput.value !== addressBoxText(snapshot.url)) {
2311
+ record.addressInput.value = addressBoxText(snapshot.url);
1887
2312
  }
1888
2313
  }
1889
2314
  if (snapshot.title) {
@@ -1891,8 +2316,7 @@ function applySnapshot(record, snapshot) {
1891
2316
  record.titleEl.title = snapshot.title;
1892
2317
  record.closeButton.setAttribute('aria-label', `Close browser pane ${snapshot.title}`);
1893
2318
  }
1894
- if (snapshot.image && snapshot.image !== record.lastImage) {
1895
- record.lastImage = snapshot.image;
2319
+ if (fresh && snapshot.image) {
1896
2320
  record.image.src = `data:image/jpeg;base64,${snapshot.image}`;
1897
2321
  record.image.alt = snapshot.title ? `Snapshot of ${snapshot.title}` : 'Browser page snapshot';
1898
2322
  }
@@ -1920,8 +2344,10 @@ async function onBrowserImageClick(record, event) {
1920
2344
  if (record.suppressClickUntil && Date.now() < record.suppressClickUntil) return;
1921
2345
  const rect = record.image.getBoundingClientRect();
1922
2346
  if (rect.width <= 0 || rect.height <= 0) return;
1923
- const width = record.width || record.image.naturalWidth;
1924
- const height = record.height || record.image.naturalHeight;
2347
+ // The picture on screen is what the person clicked: map against its own
2348
+ // size, not against the size the page may have changed to a moment later.
2349
+ const width = record.image.naturalWidth || record.width;
2350
+ const height = record.image.naturalHeight || record.height;
1925
2351
  if (!width || !height) return;
1926
2352
  const scale = Math.min(rect.width / width, rect.height / height);
1927
2353
  if (!Number.isFinite(scale) || scale <= 0) return;
@@ -1959,10 +2385,21 @@ function queueBrowserScroll(record, deltaY, deltaX = 0) {
1959
2385
  }
1960
2386
 
1961
2387
  function onBrowserWheel(record, event) {
2388
+ // A wheel over the picture is for the page inside, never for the workspace:
2389
+ // the picture does not scroll itself, and neither does the surface behind it.
2390
+ // A pinch never comes this far; the document-wide guard stops it first.
1962
2391
  event.preventDefault();
1963
2392
  queueBrowserScroll(record, event.deltaY, event.deltaX);
1964
2393
  }
1965
2394
 
2395
+ // Cmd or Ctrl with these keys is the browser's own zoom: the equals and plus
2396
+ // keys, the minus and underscore keys, zero, and the keypad's plus and minus.
2397
+ const ZOOM_KEYS = new Set(['+', '=', '-', '_', '0', 'Add', 'Subtract']);
2398
+
2399
+ function isZoomKey(event) {
2400
+ return (event.metaKey || event.ctrlKey) && ZOOM_KEYS.has(event.key);
2401
+ }
2402
+
1966
2403
  async function browserAction(record, action, extra = {}) {
1967
2404
  if (record.disposed) return;
1968
2405
  try {
@@ -1974,7 +2411,7 @@ async function browserAction(record, action, extra = {}) {
1974
2411
  if (updated) {
1975
2412
  if (updated.url) {
1976
2413
  record.currentUrl = updated.url;
1977
- if (!record.addressDirty && document.activeElement !== record.addressInput) record.addressInput.value = updated.url;
2414
+ if (!record.addressDirty && document.activeElement !== record.addressInput) record.addressInput.value = addressBoxText(updated.url);
1978
2415
  }
1979
2416
  if (updated.title) {
1980
2417
  record.titleEl.textContent = updated.title;
@@ -2027,6 +2464,11 @@ function submitBrowserType(record) {
2027
2464
  }
2028
2465
 
2029
2466
  async function addPane(kind) {
2467
+ // The new pane's box is where the keyboard goes. Until it is there, the
2468
+ // keyboard stays out of every pane: what is typed meanwhile goes nowhere near
2469
+ // a shell, and for a browser pane it is kept for the address box.
2470
+ keyboardSpokenFor = kind;
2471
+ keysForNewPane = '';
2030
2472
  closeSheets();
2031
2473
  try {
2032
2474
  let tabId = currentState && currentState.activeTabId;
@@ -2038,15 +2480,23 @@ async function addPane(kind) {
2038
2480
  const pane = await api(`/tabs/${tabId}/panes`, { method: 'POST', body });
2039
2481
  await refresh();
2040
2482
  if (pane && pane.id) {
2041
- window.setTimeout(() => {
2042
- if (kind === 'browser') focusPaneById(pane.id, 'address');
2043
- else focusPaneById(pane.id, 'terminal');
2044
- }, 80);
2483
+ // The new pane takes over, and the keyboard goes to it at once: to the
2484
+ // address box of a browser pane, so an address can be typed straight away.
2485
+ // The box takes the keyboard only while its pane is active, and the pane is
2486
+ // made active before the server is told. So no reply and no frame comes
2487
+ // between the two steps: the keyboard cannot be taken from the box.
2488
+ const activated = setActivePane(pane.id);
2489
+ focusPaneById(pane.id, kind === 'browser' ? 'address' : 'terminal');
2490
+ giveNewPaneItsKeys(records.get(pane.id));
2491
+ await activated;
2045
2492
  }
2046
2493
  logStatus(kind === 'browser' ? 'Browser pane added.' : 'Terminal pane added.');
2047
2494
  } catch (error) {
2048
2495
  showNotice(error.message || 'Could not add the pane.', 'error');
2049
2496
  await refresh();
2497
+ } finally {
2498
+ keyboardSpokenFor = '';
2499
+ keysForNewPane = '';
2050
2500
  }
2051
2501
  }
2052
2502
 
@@ -2242,9 +2692,9 @@ function focusPaneById(paneId, mode = 'type') {
2242
2692
  record.term.focus();
2243
2693
  return true;
2244
2694
  }
2245
- requestAnimationFrame(() => {
2246
- if (!record.disposed && record.term) record.term.focus();
2247
- });
2695
+ // The terminal is being mounted and takes the keyboard when it is there
2696
+ // (see handKeyboardToTerminal). The newest request is the one that counts.
2697
+ keyboardWaitsFor = { paneId, was: document.activeElement };
2248
2698
  return true;
2249
2699
  }
2250
2700
  if (record.kind === 'browser') {
@@ -2265,7 +2715,8 @@ function focusActive() {
2265
2715
  const paneId = effectiveActivePaneId(tab);
2266
2716
  const record = records.get(paneId);
2267
2717
  if (!record) {
2268
- requestAnimationFrame(() => { focusPaneById(paneId); });
2718
+ // The pane is still being built; ask again once it is there.
2719
+ requestAnimationFrame(() => { if (!overlayOpen()) focusPaneById(paneId); });
2269
2720
  return;
2270
2721
  }
2271
2722
  void setActivePane(paneId);
@@ -2464,14 +2915,23 @@ function bindEvents() {
2464
2915
  });
2465
2916
 
2466
2917
  document.querySelectorAll('[data-close]').forEach((button) => {
2467
- button.addEventListener('click', () => {
2918
+ button.addEventListener('click', (event) => {
2468
2919
  const dialog = button.closest('dialog');
2469
- if (dialog) dialog.close();
2920
+ if (!dialog) return;
2921
+ // A pointer closed the sheet; Enter or Space on this control did not.
2922
+ // (A click from a keyboard carries no pointer type and no click count.)
2923
+ keyboardReturns = Boolean(event.pointerType) || event.detail > 0;
2924
+ dialog.close();
2470
2925
  });
2471
2926
  });
2472
2927
 
2473
2928
  for (const dialog of [els.tabsDialog, els.menuDialog, els.shortcutsDialog, els.closeConfirm]) {
2474
- dialog?.addEventListener('close', syncPanelState);
2929
+ dialog?.addEventListener('close', () => {
2930
+ syncPanelState();
2931
+ // The browser puts the keyboard back on the control that opened the sheet;
2932
+ // a person who was typing in a pane goes on typing there.
2933
+ returnKeyboardToPanes();
2934
+ });
2475
2935
  }
2476
2936
  // closeSheets() can dismiss the confirmation programmatically (for example
2477
2937
  // when a page dialog arrives); clear the pending target on every close.
@@ -2494,12 +2954,15 @@ function bindEvents() {
2494
2954
  if (event.target instanceof Element && event.target.closest('.pane')) return;
2495
2955
  event.preventDefault();
2496
2956
  event.stopPropagation();
2957
+ keyboardReturns = true;
2497
2958
  closeSheets();
2498
2959
  }, true);
2499
2960
 
2500
2961
  for (const dialog of [els.tabsDialog, els.menuDialog]) {
2501
2962
  dialog.addEventListener('click', (event) => {
2502
- if (event.target === dialog) dialog.close();
2963
+ if (event.target !== dialog) return;
2964
+ keyboardReturns = true;
2965
+ dialog.close();
2503
2966
  });
2504
2967
  }
2505
2968
 
@@ -2525,41 +2988,95 @@ function startStatePolling() {
2525
2988
  });
2526
2989
  }
2527
2990
 
2991
+ // The bootstrap route answers only a page that arrived by a real navigation
2992
+ // (it carries the owner cookie) and asks as a page asks, and hands the page
2993
+ // its key for this server run along with the workspace.
2994
+ let lastBootstrapError = '';
2995
+ // When the server keeps the owner's key from this page, its reason is written
2996
+ // for an agent that has wandered here. A person is told what to do instead.
2997
+ const OWNER_PAGE_CODES = new Set(['OWNER_PAGE_REQUIRED', 'NOT_FROM_OWNER_PAGE', 'AGENT_TOKEN']);
2998
+ const OWNER_PAGE_MESSAGE = 'This page could not show the server that it was opened by you, so it was not given the owner\'s key. Reload the page. If this keeps happening, the browser is too old to identify its own requests: use Chrome 76 or later, Safari 16.4 or later, or Firefox 90 or later.';
2999
+ async function fetchBootstrap() {
3000
+ try {
3001
+ const response = await fetch(`${API_ROOT}/bootstrap`, { cache: 'no-store' });
3002
+ const payload = await response.json().catch(() => null);
3003
+ if (!response.ok) {
3004
+ lastBootstrapError = (payload && OWNER_PAGE_CODES.has(payload.code))
3005
+ ? OWNER_PAGE_MESSAGE
3006
+ : (payload && payload.error) || `Workspace bootstrap failed (${response.status}).`;
3007
+ return null;
3008
+ }
3009
+ return payload && payload.ownerKey && payload.state ? payload : null;
3010
+ } catch (error) {
3011
+ lastBootstrapError = error.message || 'Could not reach the workspace.';
3012
+ return null;
3013
+ }
3014
+ }
3015
+
3016
+ function adoptBootstrap(payload) {
3017
+ ownerKey = payload.ownerKey;
3018
+ let previousEpoch = '';
3019
+ try { previousEpoch = window.sessionStorage.getItem('townmouse.workspaceEpoch') || ''; } catch (_) { /* storage disabled */ }
3020
+ const epoch = payload.state.epoch;
3021
+ applyState(payload.state, { force: true });
3022
+ if (previousEpoch && epoch && previousEpoch !== epoch) {
3023
+ showNotice('Workspace restarted. Layout restored; terminal scrollback and running jobs are gone.', 'info', 9000);
3024
+ }
3025
+ if (epoch) {
3026
+ try { window.sessionStorage.setItem('townmouse.workspaceEpoch', epoch); } catch (_) { /* storage disabled */ }
3027
+ }
3028
+ }
3029
+
3030
+ // The page key and the owner cookie are minted per server run. After a
3031
+ // restart the page holds stale ones. Renew them from the cookie without
3032
+ // troubling the person and, if the cookie has gone too, reload the page
3033
+ // once, which is what mints a fresh one. A second reload within moments
3034
+ // cannot help, so then the person is told instead.
3035
+ const RELOAD_GUARD_KEY = 'townmouse.panesReloadAt';
3036
+ let renewal = null;
3037
+ function renewOwnerKey() {
3038
+ if (!renewal) {
3039
+ renewal = (async () => {
3040
+ const payload = await fetchBootstrap();
3041
+ if (payload) { adoptBootstrap(payload); return true; }
3042
+ let last = 0;
3043
+ try { last = Number(window.sessionStorage.getItem(RELOAD_GUARD_KEY) || 0); } catch (_) { /* storage disabled */ }
3044
+ if (!(Date.now() - last < 15000)) {
3045
+ try { window.sessionStorage.setItem(RELOAD_GUARD_KEY, String(Date.now())); } catch (_) { /* storage disabled */ }
3046
+ window.location.reload();
3047
+ // If a beforeunload handler keeps this document alive, the renewal
3048
+ // must not stay latched forever.
3049
+ await new Promise((resolve) => window.setTimeout(resolve, 5000));
3050
+ return false;
3051
+ }
3052
+ showNotice('Owner session expired. Reload the page to keep working in your panes.', 'error', 0);
3053
+ return false;
3054
+ })().finally(() => { renewal = null; });
3055
+ }
3056
+ return renewal;
3057
+ }
3058
+
2528
3059
  async function bootstrap() {
2529
3060
  if (booting) return;
2530
3061
  booting = true;
2531
3062
  els.emptyTitle.textContent = 'Connecting to the workspace';
2532
3063
  els.emptyCopy.textContent = 'Reading tabs and panes.';
2533
3064
  els.emptyActions.hidden = true;
2534
- try {
2535
- const response = await fetch(`${API_ROOT}/bootstrap`, { cache: 'no-store' });
2536
- let payload = null;
2537
- try { payload = await response.json(); } catch (_) { payload = null; }
2538
- if (!response.ok) throw new Error((payload && payload.error) || `Workspace bootstrap failed (${response.status}).`);
2539
- if (!payload || !payload.token) throw new Error('Workspace bootstrap did not return a token.');
2540
- token = payload.token;
2541
- const previousEpoch = window.sessionStorage.getItem('townmouse.workspaceEpoch');
2542
- const epoch = payload.state && payload.state.epoch;
2543
- applyState(payload.state, { force: true });
2544
- clearTimeout(noticeTimer);
2545
- els.notice.hidden = true;
2546
- if (previousEpoch && epoch && previousEpoch !== epoch) {
2547
- showNotice('Workspace restarted. Layout restored; terminal scrollback and running jobs are gone.', 'info', 9000);
2548
- }
2549
- if (epoch) {
2550
- try { window.sessionStorage.setItem('townmouse.workspaceEpoch', epoch); } catch (_) { /* storage disabled */ }
2551
- }
2552
- logStatus('Workspace ready.');
2553
- } catch (error) {
2554
- token = '';
3065
+ const payload = await fetchBootstrap();
3066
+ if (!payload) {
3067
+ ownerKey = '';
2555
3068
  booting = false;
2556
3069
  els.emptyTitle.textContent = 'Workspace unavailable';
2557
3070
  els.emptyCopy.textContent = 'Waiting for the local server. Retrying.';
2558
3071
  els.emptyActions.hidden = true;
2559
- showNotice(error.message || 'Could not reach the workspace. Retrying.', 'error', 0);
3072
+ showNotice(lastBootstrapError || 'Could not reach the workspace. Retrying.', 'error', 0);
2560
3073
  window.setTimeout(() => { void bootstrap(); }, 1800);
2561
3074
  return;
2562
3075
  }
3076
+ adoptBootstrap(payload);
3077
+ clearTimeout(noticeTimer);
3078
+ els.notice.hidden = true;
3079
+ logStatus('Workspace ready.');
2563
3080
  booting = false;
2564
3081
  startStatePolling();
2565
3082
  }
@@ -2618,8 +3135,49 @@ window.addEventListener('resize', () => {
2618
3135
  });
2619
3136
  });
2620
3137
 
3138
+ // The workspace is an application, not a document: a pinch must not zoom it,
3139
+ // wherever the pointer is. Chrome reports a trackpad pinch as a wheel event with
3140
+ // Control held, Safari as a gesture event. Listening here, first and for the
3141
+ // whole document, covers a terminal, a browser pane's picture, the sheets and
3142
+ // the bars alike: none of them is ever asked to tell a pinch from a scroll, and
3143
+ // a terminal never sees one as a scroll. A wheel without Control is a scroll
3144
+ // and is left to what is under the pointer.
3145
+ for (const type of ['wheel', 'gesturestart', 'gesturechange']) {
3146
+ document.addEventListener(type, (event) => {
3147
+ if (type !== 'wheel' || event.ctrlKey) {
3148
+ event.preventDefault();
3149
+ event.stopPropagation();
3150
+ }
3151
+ }, { capture: true, passive: false });
3152
+ }
3153
+
3154
+ // The keyboard must not zoom it either. Cmd or Ctrl with +, − or 0 is the
3155
+ // browser's own zoom; here it throws the whole layout off. It is cancelled
3156
+ // wherever the keyboard is: on a terminal, a picture, in an address box, in a
3157
+ // sheet. Before, only the picture itself was guarded, so the same keys zoomed
3158
+ // the workspace from the address box that "Add browser pane" had just focused.
3159
+ document.addEventListener('keydown', (event) => {
3160
+ if (isZoomKey(event)) event.preventDefault();
3161
+ }, { capture: true });
3162
+
3163
+ // Text is typed where the keyboard is, nowhere else. A tool can ask the browser
3164
+ // to insert text without key events; the browser then aims it at whatever it
3165
+ // edited last, which on this surface can be a terminal that handed the keyboard
3166
+ // to an open sheet. Such an event is cancelled unless its target can take text.
3167
+ // A keyboard never produces it on anything else, so typing is not touched. Text
3168
+ // aimed that way while a browser pane is being added is kept for its address
3169
+ // box, like keys typed in that moment.
3170
+ document.addEventListener('beforeinput', (event) => {
3171
+ if (takesText(event.target)) return;
3172
+ if (keyboardSpokenFor === 'browser' && event.inputType === 'insertText' && typeof event.data === 'string') {
3173
+ keysForNewPane += event.data;
3174
+ }
3175
+ event.preventDefault();
3176
+ }, { capture: true });
3177
+
2621
3178
  buildPaneKeybar();
2622
3179
  bindEvents();
3180
+ void loadAppVersion().then((version) => { if (version) updateDocumentTitle(activeTab()); });
2623
3181
  void bootstrap();
2624
3182
 
2625
3183