townmouse 0.0.0-stage → 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 (108) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/DESIGN.md +153 -0
  3. package/LICENSE +661 -0
  4. package/README.md +600 -2
  5. package/SECURITY.md +60 -0
  6. package/TOWNMOUSE.md +91 -0
  7. package/assets/brand/mascot/README.md +23 -0
  8. package/assets/brand/mascot/townmouse-aristocrat.png +0 -0
  9. package/assets/brand/mascot/townmouse-icon.svg +1 -0
  10. package/assets/brand/mascot/townmouse-monocled.png +0 -0
  11. package/bin/townmouse +68 -0
  12. package/docs/PACKAGING.md +371 -0
  13. package/docs/browser-workspace.md +237 -0
  14. package/docs/panes.md +442 -0
  15. package/native/TownmouseApp.swift +108 -0
  16. package/npm-shrinkwrap.json +1282 -0
  17. package/package.json +93 -4
  18. package/public/apple-touch-icon.png +0 -0
  19. package/public/brand/floydslabs-credit.png +0 -0
  20. package/public/brand/floydslabs-credit.webp +0 -0
  21. package/public/brand/townmouse-aristocrat.webp +0 -0
  22. package/public/brand/townmouse-monocled.webp +0 -0
  23. package/public/browser-picture.mjs +159 -0
  24. package/public/clipboard-text.mjs +5 -0
  25. package/public/favicon-16x16.png +0 -0
  26. package/public/favicon-32x32.png +0 -0
  27. package/public/favicon.ico +0 -0
  28. package/public/favicon.svg +1 -0
  29. package/public/features/app-version.mjs +35 -0
  30. package/public/features/autosave.mjs +80 -0
  31. package/public/features/clipboard.mjs +69 -0
  32. package/public/features/command-palette.mjs +181 -0
  33. package/public/features/desktop-palette.mjs +19 -0
  34. package/public/features/export.mjs +37 -0
  35. package/public/features/file-drop.mjs +77 -0
  36. package/public/features/floating-palette.mjs +113 -0
  37. package/public/features/fontsize.mjs +72 -0
  38. package/public/features/haptic-keys.mjs +42 -0
  39. package/public/features/history-undo.mjs +102 -0
  40. package/public/features/keepalive.mjs +36 -0
  41. package/public/features/keybar-config.mjs +70 -0
  42. package/public/features/keyboard-shortcuts.mjs +74 -0
  43. package/public/features/links.mjs +139 -0
  44. package/public/features/multi-window-sync.mjs +76 -0
  45. package/public/features/osc-bridge.mjs +64 -0
  46. package/public/features/phone-landscape-focus.mjs +157 -0
  47. package/public/features/recent-commands.mjs +100 -0
  48. package/public/features/search.mjs +134 -0
  49. package/public/features/session-lock.mjs +96 -0
  50. package/public/features/session-manager.mjs +251 -0
  51. package/public/features/settings-sync.mjs +77 -0
  52. package/public/features/shortcut-help.mjs +85 -0
  53. package/public/features/smart-completions.mjs +101 -0
  54. package/public/features/smart-suggest.mjs +124 -0
  55. package/public/features/snippets.mjs +85 -0
  56. package/public/features/split-view.mjs +102 -0
  57. package/public/features/status-metrics.mjs +137 -0
  58. package/public/features/stylus-support.mjs +124 -0
  59. package/public/features/swipe-history.mjs +141 -0
  60. package/public/features/swipe-sessions.mjs +85 -0
  61. package/public/features/tab-reorder.mjs +70 -0
  62. package/public/features/theme-system.mjs +51 -0
  63. package/public/features/toast-status.mjs +118 -0
  64. package/public/features/two-finger-menu.mjs +87 -0
  65. package/public/features/voice-input.mjs +244 -0
  66. package/public/features/wake-fullscreen.mjs +67 -0
  67. package/public/features/window-title.mjs +47 -0
  68. package/public/features/zoom.mjs +80 -0
  69. package/public/icon-128.png +0 -0
  70. package/public/icon-180.png +0 -0
  71. package/public/icon-192.png +0 -0
  72. package/public/icon-48.png +0 -0
  73. package/public/icon-512-maskable.png +0 -0
  74. package/public/icon-512.png +0 -0
  75. package/public/icon.svg +1 -0
  76. package/public/index.html +2304 -0
  77. package/public/input-chunks.mjs +22 -0
  78. package/public/input-guard.mjs +218 -0
  79. package/public/manifest.json +56 -0
  80. package/public/panes.css +1433 -0
  81. package/public/panes.html +211 -0
  82. package/public/panes.mjs +3183 -0
  83. package/public/service-worker.js +67 -0
  84. package/public/workspace.css +1621 -0
  85. package/public/workspace.mjs +1715 -0
  86. package/scripts/install-service.sh +303 -0
  87. package/scripts/node-runtime.sh +138 -0
  88. package/scripts/panes +568 -0
  89. package/scripts/prepare-native.sh +35 -0
  90. package/scripts/retire-legacy-service.sh +76 -0
  91. package/scripts/run-hooks +69 -0
  92. package/scripts/townmouse.sh +152 -0
  93. package/scripts/uninstall-service.sh +65 -0
  94. package/src/agent-guide.js +329 -0
  95. package/src/attachments.js +128 -0
  96. package/src/browser-dom.js +548 -0
  97. package/src/browser-workspace.js +1733 -0
  98. package/src/chrome-resolve.js +80 -0
  99. package/src/owner-page.js +43 -0
  100. package/src/pty-permissions.js +99 -0
  101. package/src/regex-worker.js +13 -0
  102. package/src/replay-text.js +189 -0
  103. package/src/request-boundary.js +58 -0
  104. package/src/safe-regex.js +87 -0
  105. package/src/server.js +1582 -0
  106. package/src/shell-resolve.js +42 -0
  107. package/src/static-deps.js +61 -0
  108. package/src/workspace-panes.js +1431 -0
@@ -0,0 +1,3183 @@
1
+ import { Terminal } from '/node_modules/@xterm/xterm/lib/xterm.mjs';
2
+ import { FitAddon } from '/node_modules/@xterm/addon-fit/lib/addon-fit.mjs';
3
+ import { WebLinksAddon } from '/node_modules/@xterm/addon-web-links/lib/addon-web-links.mjs';
4
+ import { chunkInput } from '/input-chunks.mjs';
5
+ import { decodeClipboardText } from '/clipboard-text.mjs';
6
+ import { currentVersion, loadAppVersion } from '/features/app-version.mjs';
7
+ import { createViewedWatch, createPictureLoop } from '/browser-picture.mjs';
8
+
9
+ const API_ROOT = '/api/panes';
10
+ const STATE_POLL_MS = 1200;
11
+ const READ_POLL_MS = 180;
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;
18
+ const MAX_HISTORY = 120000;
19
+ const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
20
+
21
+ const byId = (id) => document.getElementById(id);
22
+ const els = {
23
+ app: byId('panes-app'),
24
+ grid: byId('pane-grid'),
25
+ tabStrip: byId('tabstrip'),
26
+ workspace: byId('workspace'),
27
+ emptyState: byId('empty-state'),
28
+ emptyTitle: byId('empty-title'),
29
+ emptyCopy: byId('empty-copy'),
30
+ emptyActions: byId('empty-actions'),
31
+ emptyAddTerminal: byId('empty-add-terminal'),
32
+ emptyAddBrowser: byId('empty-add-browser'),
33
+ emptyNewTab: byId('empty-new-tab'),
34
+ backButton: byId('back-button'),
35
+ hostPill: byId('host-pill'),
36
+ hostName: byId('host-name'),
37
+ tabsButton: byId('tabs-button'),
38
+ tabCount: byId('tab-count'),
39
+ keyboardButton: byId('keyboard-button'),
40
+ menuButton: byId('menu-button'),
41
+ tabsDialog: byId('tabs-dialog'),
42
+ tabsList: byId('tabs-list'),
43
+ tabsEmpty: byId('tabs-empty'),
44
+ tabsLimits: byId('tabs-limits'),
45
+ tabsNewTab: byId('tabs-new-tab'),
46
+ tabsAddTerminal: byId('tabs-add-terminal'),
47
+ tabsAddBrowser: byId('tabs-add-browser'),
48
+ menuDialog: byId('menu-dialog'),
49
+ menuAddTerminal: byId('menu-add-terminal'),
50
+ menuAddBrowser: byId('menu-add-browser'),
51
+ menuNewTab: byId('menu-new-tab'),
52
+ menuAttach: byId('menu-attach'),
53
+ menuReader: byId('menu-reader'),
54
+ menuShortcuts: byId('menu-shortcuts'),
55
+ menuFontUp: byId('menu-font-up'),
56
+ menuFontDown: byId('menu-font-down'),
57
+ shortcutsDialog: byId('shortcuts-dialog'),
58
+ attachInput: byId('attach-input'),
59
+ readerView: byId('reader-view'),
60
+ readerText: byId('reader-text'),
61
+ readerRefresh: byId('reader-refresh'),
62
+ readerClose: byId('reader-close'),
63
+ closeConfirm: byId('close-confirm'),
64
+ closeConfirmTitle: byId('close-confirm-title'),
65
+ closeConfirmCopy: byId('close-confirm-copy'),
66
+ closeCancel: byId('close-cancel'),
67
+ closeApprove: byId('close-approve'),
68
+ keybar: byId('pane-keybar'),
69
+ contextMenu: byId('pane-context-menu'),
70
+ browserContextMenu: byId('browser-context-menu'),
71
+ browserControl: byId('browser-control'),
72
+ browserControlLabel: byId('browser-control-label'),
73
+ browserControlSelect: byId('browser-control-select'),
74
+ browserControlValue: byId('browser-control-value'),
75
+ browserControlCancel: byId('browser-control-cancel'),
76
+ browserControlApply: byId('browser-control-apply'),
77
+ pageDialog: byId('page-dialog'),
78
+ pageDialogMessage: byId('page-dialog-message'),
79
+ pageDialogField: byId('page-dialog-field'),
80
+ pageDialogInput: byId('page-dialog-input'),
81
+ pageDialogDismiss: byId('page-dialog-dismiss'),
82
+ pageDialogAccept: byId('page-dialog-accept'),
83
+ notice: byId('notice'),
84
+ srStatus: byId('sr-status')
85
+ };
86
+
87
+ const TERMINAL_THEME = {
88
+ background: '#0a0d12',
89
+ foreground: '#e8eef6',
90
+ cursor: '#8ab4ff',
91
+ cursorAccent: '#0a0d12',
92
+ selectionBackground: 'rgba(138, 180, 255, 0.24)',
93
+ black: '#11161d',
94
+ red: '#ff8f8f',
95
+ green: '#7fe3c0',
96
+ yellow: '#e9d6a1',
97
+ blue: '#8ab4ff',
98
+ magenta: '#d9b1cf',
99
+ cyan: '#8fe6d4',
100
+ white: '#e8eef6',
101
+ brightBlack: '#5f6f88',
102
+ brightRed: '#ffb3b3',
103
+ brightGreen: '#a5f2d8',
104
+ brightYellow: '#f3e5bd',
105
+ brightBlue: '#a9c8ff',
106
+ brightMagenta: '#e8cae1',
107
+ brightCyan: '#b6f4e6',
108
+ brightWhite: '#f4f8ff'
109
+ };
110
+
111
+ const CLOSE_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>';
112
+ const BACK_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M15 18l-6-6 6-6"/></svg>';
113
+ const RELOAD_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="M20 12a8 8 0 1 1-2.3-5.7M20 4v5h-5"/></svg>';
114
+ const MAXIMIZE_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 4H4v5M15 4h5v5M4 15v5h5M20 15v5h-5"/></svg>';
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>';
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>';
117
+
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 = '';
122
+ let currentState = null;
123
+ let lastSignature = '';
124
+ let currentTabId = null;
125
+ let refreshInFlight = null;
126
+ let noticeTimer = 0;
127
+ let noticeText = '';
128
+ let noticeAt = 0;
129
+ let tabsDialogSignature = '';
130
+ let booting = false;
131
+ let pendingClose = null;
132
+ let pageDialogRecordId = null;
133
+ let pageDialogId = null;
134
+ let pageDialogType = '';
135
+ let contextRecordId = null;
136
+ let browserContextRecordId = null;
137
+ let browserControlRecordId = null;
138
+ let browserControlPoint = null;
139
+ let browserControlKind = '';
140
+
141
+ const cursors = new Map();
142
+ const histories = new Map();
143
+ const records = new Map();
144
+ // Input queues are keyed by pane id, not by the view record. A tab switch can
145
+ // dispose and recreate a record while a paste is still being delivered; both
146
+ // views must feed the same ordered queue.
147
+ const inputPumps = new Map();
148
+
149
+ const PANE_FONT_KEY = 'townmouse.paneFontSize';
150
+
151
+ function paneFontOverride() {
152
+ const value = Number(window.localStorage.getItem(PANE_FONT_KEY));
153
+ return value >= 8 && value <= 24 ? value : 0;
154
+ }
155
+
156
+ function adjustPaneFont(delta) {
157
+ const record = activeTerminalRecord();
158
+ const current = paneFontOverride() || (record?.term?.options.fontSize) || 11;
159
+ const next = Math.max(8, Math.min(24, current + delta));
160
+ try { window.localStorage.setItem(PANE_FONT_KEY, String(next)); } catch (_) { /* storage disabled */ }
161
+ for (const candidate of records.values()) {
162
+ if (candidate.kind !== 'terminal' || !candidate.term) continue;
163
+ candidate.term.options.fontSize = next;
164
+ safeFit(candidate);
165
+ }
166
+ showNotice(`Terminal text ${next}px`, 'info', 1800);
167
+ }
168
+
169
+ function inputPumpFor(paneId) {
170
+ let pump = inputPumps.get(paneId);
171
+ if (!pump) {
172
+ pump = { paneId, pendingInput: '', inputTimer: 0, inputBusy: false, inputStopped: false };
173
+ inputPumps.set(paneId, pump);
174
+ }
175
+ return pump;
176
+ }
177
+
178
+ function shellQuote(value) {
179
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
180
+ }
181
+
182
+ async function uploadAttachment(file) {
183
+ const response = await fetch('/api/attachments', {
184
+ method: 'POST',
185
+ headers: {
186
+ 'Content-Type': file.type || 'application/octet-stream',
187
+ 'X-Filename': encodeURIComponent(file.name || 'attachment')
188
+ },
189
+ body: file
190
+ });
191
+ let payload = null;
192
+ try { payload = await response.json(); } catch (_) { payload = null; }
193
+ if (!response.ok) throw new Error((payload && payload.error) || `Upload failed (${response.status}).`);
194
+ return payload;
195
+ }
196
+
197
+ async function attachFiles(record, files) {
198
+ if (!record || !files || !files.length) return;
199
+ for (const file of files) {
200
+ try {
201
+ const attachment = await uploadAttachment(file);
202
+ if (record.kind === 'terminal' && record.term) {
203
+ record.term.paste(`${shellQuote(attachment.path)} `);
204
+ showAttachmentNotice(attachment, file);
205
+ } else if (record.kind === 'browser') {
206
+ // Navigate the local browser straight at loopback; a forwarded host is
207
+ // for human-facing links, not the pane's own Chromium.
208
+ await api(`/panes/${record.id}/url`, { method: 'POST', body: { url: attachment.localUrl || attachment.url } });
209
+ record.lastViewport = '';
210
+ requestSnapshot(record, 120);
211
+ showNotice(`Opened ${file.name} in the browser pane`, 'info', 2600);
212
+ }
213
+ } catch (error) {
214
+ showNotice(error.message || `Could not attach ${file.name}.`, 'error');
215
+ }
216
+ }
217
+ }
218
+
219
+ function reorderActivePane(direction) {
220
+ const tab = activeTab();
221
+ if (!tab || tab.panes.length < 2) return;
222
+ const from = tab.panes.findIndex((pane) => pane.id === effectiveActivePaneId(tab));
223
+ const to = Math.max(0, Math.min(tab.panes.length - 1, from + direction));
224
+ if (from < 0 || to === from) return;
225
+ void (async () => {
226
+ try {
227
+ const next = await api(`/tabs/${tab.id}/reorder`, { method: 'POST', body: { paneId: tab.panes[from].id, index: to } });
228
+ if (next && next.tabs) applyState(next, { force: true });
229
+ else await refresh();
230
+ logStatus('Pane reordered.');
231
+ } catch (error) {
232
+ showNotice(error.message || 'Could not reorder the pane.', 'error');
233
+ }
234
+ })();
235
+ }
236
+
237
+ function wirePaneReorder(root, paneId) {
238
+ const header = root.querySelector('.pane-header');
239
+ if (!header) return;
240
+ header.addEventListener('pointerdown', (event) => {
241
+ if (event.target.closest('button, input')) return;
242
+ const startX = event.clientX;
243
+ const startY = event.clientY;
244
+ let dragging = false;
245
+ let target = null;
246
+ const clearTarget = () => {
247
+ if (target) target.classList.remove('drop-target');
248
+ target = null;
249
+ };
250
+ const move = (moveEvent) => {
251
+ if (!dragging && Math.hypot(moveEvent.clientX - startX, moveEvent.clientY - startY) > 8) {
252
+ dragging = true;
253
+ root.classList.add('reordering');
254
+ }
255
+ if (!dragging) return;
256
+ const under = document.elementFromPoint(moveEvent.clientX, moveEvent.clientY)?.closest?.('.pane');
257
+ if (under === target) return;
258
+ clearTarget();
259
+ if (under && under !== root) {
260
+ target = under;
261
+ target.classList.add('drop-target');
262
+ }
263
+ };
264
+ const end = (upEvent) => {
265
+ document.removeEventListener('pointermove', move);
266
+ document.removeEventListener('pointerup', end);
267
+ document.removeEventListener('pointercancel', end);
268
+ root.classList.remove('reordering');
269
+ const drop = target;
270
+ clearTarget();
271
+ if (!dragging || !drop || !currentState) return;
272
+ const tab = activeTab();
273
+ if (!tab) return;
274
+ const from = tab.panes.findIndex((pane) => pane.id === paneId);
275
+ const dropId = drop.dataset.paneId;
276
+ const over = tab.panes.findIndex((pane) => pane.id === dropId);
277
+ if (from < 0 || over < 0 || from === over) return;
278
+ const rect = drop.getBoundingClientRect();
279
+ const after = upEvent.clientX > rect.left + rect.width / 2;
280
+ const index = Math.max(0, Math.min(tab.panes.length - 1, over + (after ? 1 : 0) - (from < over ? 1 : 0)));
281
+ void (async () => {
282
+ try {
283
+ const next = await api(`/tabs/${tab.id}/reorder`, { method: 'POST', body: { paneId, index } });
284
+ if (next && next.tabs) applyState(next, { force: true });
285
+ else await refresh();
286
+ } catch (error) {
287
+ showNotice(error.message || 'Could not reorder the pane.', 'error');
288
+ }
289
+ })();
290
+ };
291
+ document.addEventListener('pointermove', move);
292
+ document.addEventListener('pointerup', end);
293
+ document.addEventListener('pointercancel', end);
294
+ });
295
+ }
296
+
297
+ function wireDrop(root, paneId) {
298
+ const recordFor = () => records.get(paneId);
299
+ const hasFiles = (event) => Array.from(event.dataTransfer?.types || []).includes('Files');
300
+ root.addEventListener('dragover', (event) => {
301
+ if (!hasFiles(event)) return;
302
+ event.preventDefault();
303
+ event.stopPropagation();
304
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
305
+ root.classList.add('drop-target');
306
+ });
307
+ root.addEventListener('dragleave', (event) => {
308
+ if (!root.contains(event.relatedTarget)) root.classList.remove('drop-target');
309
+ });
310
+ root.addEventListener('drop', (event) => {
311
+ if (!event.dataTransfer?.files?.length) return;
312
+ event.preventDefault();
313
+ event.stopPropagation();
314
+ root.classList.remove('drop-target');
315
+ void attachFiles(recordFor(), Array.from(event.dataTransfer.files));
316
+ });
317
+ root.addEventListener('paste', (event) => {
318
+ const files = Array.from(event.clipboardData?.items || [])
319
+ .filter((item) => item.kind === 'file')
320
+ .map((item) => item.getAsFile())
321
+ .filter(Boolean);
322
+ if (!files.length) return;
323
+ event.preventDefault();
324
+ event.stopImmediatePropagation();
325
+ void attachFiles(recordFor(), files);
326
+ }, true);
327
+ }
328
+
329
+ function logStatus(message) {
330
+ els.srStatus.textContent = message;
331
+ }
332
+
333
+ function showNotice(message, kind = 'error', duration = 4200, copyUrl = '') {
334
+ if (!message) return;
335
+ const now = Date.now();
336
+ if (kind === 'error' && message === noticeText && now - noticeAt < 1200) return;
337
+ noticeText = message;
338
+ noticeAt = now;
339
+ els.notice.textContent = message;
340
+ els.notice.dataset.kind = kind;
341
+ if (copyUrl) {
342
+ els.notice.dataset.copyUrl = copyUrl;
343
+ els.notice.title = 'Tap to copy the attachment URL';
344
+ } else {
345
+ delete els.notice.dataset.copyUrl;
346
+ els.notice.removeAttribute('title');
347
+ }
348
+ els.notice.hidden = false;
349
+ clearTimeout(noticeTimer);
350
+ if (duration > 0) {
351
+ noticeTimer = window.setTimeout(() => { els.notice.hidden = true; }, duration);
352
+ }
353
+ }
354
+
355
+ function showAttachmentNotice(attachment, file) {
356
+ // The URL is part of the message, not a filename that disappears. Tapping
357
+ // the notice copies it; agents can get the same URL from `panes attach`.
358
+ showNotice(`Attached ${file.name} · ${attachment.url}`, 'info', 8000, attachment.url);
359
+ }
360
+
361
+ function syncMenuState() {
362
+ const anyOpen = [els.contextMenu, els.browserContextMenu]
363
+ .some((menu) => menu && !menu.hidden);
364
+ els.app?.classList.toggle('menu-open', anyOpen);
365
+ }
366
+
367
+ function syncDialogState() {
368
+ const anyOpen = [els.browserControl, els.pageDialog]
369
+ .some((dialog) => dialog && !dialog.hidden);
370
+ els.app?.classList.toggle('dialog-open', anyOpen);
371
+ }
372
+
373
+ function hideContextMenu() {
374
+ contextRecordId = null;
375
+ browserContextRecordId = null;
376
+ if (els.contextMenu) els.contextMenu.hidden = true;
377
+ if (els.browserContextMenu) els.browserContextMenu.hidden = true;
378
+ syncMenuState();
379
+ }
380
+
381
+ function showBrowserContextMenu(record, _clientX, _clientY) {
382
+ if (!els.browserContextMenu || !record || record.kind !== 'browser') return;
383
+ // A blocking page prompt owns the bottom strip; the rail would be hidden
384
+ // behind it and the action would look broken.
385
+ if (els.app?.classList.contains('dialog-open')) return;
386
+ hideContextMenu();
387
+ closeSheets();
388
+ browserContextRecordId = record.id;
389
+ record.suppressClickUntil = Date.now() + 700;
390
+ els.browserContextMenu.hidden = false;
391
+ syncMenuState();
392
+ els.browserContextMenu.querySelector('[role="menuitem"]')?.focus();
393
+ }
394
+
395
+ function wireBrowserContext(record) {
396
+ record.image.addEventListener('contextmenu', (event) => {
397
+ event.preventDefault();
398
+ void setActivePane(record.id);
399
+ showBrowserContextMenu(record, event.clientX, event.clientY);
400
+ });
401
+ let timer = 0;
402
+ let startX = 0;
403
+ let startY = 0;
404
+ record.view.addEventListener('pointerdown', (event) => {
405
+ if (event.pointerType === 'mouse') return;
406
+ startX = event.clientX;
407
+ startY = event.clientY;
408
+ clearTimeout(timer);
409
+ timer = window.setTimeout(() => showBrowserContextMenu(record, startX, startY), 550);
410
+ });
411
+ record.view.addEventListener('pointermove', (event) => {
412
+ if (Math.hypot(event.clientX - startX, event.clientY - startY) > 10) clearTimeout(timer);
413
+ });
414
+ for (const type of ['pointerup', 'pointercancel', 'pointerleave']) {
415
+ record.view.addEventListener(type, () => clearTimeout(timer));
416
+ }
417
+ }
418
+
419
+ function showContextMenu(record, _clientX, _clientY) {
420
+ if (!els.contextMenu || !record || record.kind !== 'terminal') return;
421
+ if (els.app?.classList.contains('dialog-open')) return;
422
+ hideContextMenu();
423
+ closeSheets();
424
+ contextRecordId = record.id;
425
+ els.contextMenu.hidden = false;
426
+ syncMenuState();
427
+ els.contextMenu.querySelector('[role="menuitem"]')?.focus();
428
+ }
429
+
430
+ function wirePaneContext(root, record) {
431
+ root.addEventListener('contextmenu', (event) => {
432
+ if (event.target.closest('input, button')) return;
433
+ event.preventDefault();
434
+ void setActivePane(record.id);
435
+ showContextMenu(record, event.clientX, event.clientY);
436
+ });
437
+ const body = root.querySelector('.pane-body');
438
+ if (!body) return;
439
+ let timer = 0;
440
+ let startX = 0;
441
+ let startY = 0;
442
+ body.addEventListener('pointerdown', (event) => {
443
+ if (event.pointerType === 'mouse') return;
444
+ startX = event.clientX;
445
+ startY = event.clientY;
446
+ clearTimeout(timer);
447
+ timer = window.setTimeout(() => showContextMenu(record, startX, startY), 550);
448
+ });
449
+ body.addEventListener('pointermove', (event) => {
450
+ if (Math.hypot(event.clientX - startX, event.clientY - startY) > 10) clearTimeout(timer);
451
+ });
452
+ for (const type of ['pointerup', 'pointercancel', 'pointerleave']) {
453
+ body.addEventListener(type, () => clearTimeout(timer));
454
+ }
455
+ }
456
+
457
+ function hideBrowserControl() {
458
+ browserControlRecordId = null;
459
+ browserControlPoint = null;
460
+ browserControlKind = '';
461
+ if (els.browserControl) els.browserControl.hidden = true;
462
+ syncDialogState();
463
+ }
464
+
465
+ function showBrowserControl(record, control, point) {
466
+ if (!els.browserControl || !record || !control) return;
467
+ // Only dismiss soft docks when the control is first revealed; later updates
468
+ // of an already-visible control must not close a sheet the user opened.
469
+ if (els.browserControl.hidden) {
470
+ closeSheets();
471
+ hideContextMenu();
472
+ }
473
+ browserControlRecordId = record.id;
474
+ browserControlPoint = point;
475
+ browserControlKind = control.kind;
476
+ els.browserControl.hidden = false;
477
+ syncDialogState();
478
+ if (control.kind === 'select') {
479
+ els.browserControlLabel.textContent = 'Choose an option';
480
+ els.browserControlSelect.hidden = false;
481
+ els.browserControlValue.hidden = true;
482
+ els.browserControlSelect.replaceChildren(...(control.options || []).map((option) => {
483
+ const el = document.createElement('option');
484
+ el.value = option.value;
485
+ el.textContent = option.label;
486
+ if (option.value === control.value) el.selected = true;
487
+ return el;
488
+ }));
489
+ } else {
490
+ els.browserControlLabel.textContent = `Choose a ${control.kind} value`;
491
+ els.browserControlSelect.hidden = true;
492
+ els.browserControlValue.hidden = false;
493
+ els.browserControlValue.type = control.kind;
494
+ els.browserControlValue.value = control.value || '';
495
+ }
496
+ (control.kind === 'select' ? els.browserControlSelect : els.browserControlValue).focus();
497
+ }
498
+
499
+ async function applyBrowserControl() {
500
+ const record = records.get(browserControlRecordId);
501
+ if (!record || !browserControlPoint) { hideBrowserControl(); return; }
502
+ const value = browserControlKind === 'select'
503
+ ? els.browserControlSelect.value
504
+ : els.browserControlValue.value;
505
+ const action = browserControlKind === 'select' ? 'selectAt' : 'setValueAt';
506
+ const point = browserControlPoint;
507
+ hideBrowserControl();
508
+ await browserAction(record, action, { ...point, value });
509
+ }
510
+
511
+ function hidePageDialog() {
512
+ pageDialogRecordId = null;
513
+ pageDialogId = null;
514
+ pageDialogType = '';
515
+ if (els.pageDialog) els.pageDialog.hidden = true;
516
+ syncDialogState();
517
+ }
518
+
519
+ function showPageDialog(record, dialog) {
520
+ if (!els.pageDialog || !record || !dialog || !dialog.id) return;
521
+ if (pageDialogId !== dialog.id) {
522
+ // A blocking page dialog outranks the soft docks. Close them on arrival;
523
+ // the next snapshot reuses this id, so a sheet the user reopens later is
524
+ // not closed again. The browser control shares the bottom strip, so it
525
+ // must not be left underneath the prompt.
526
+ closeSheets();
527
+ hideContextMenu();
528
+ hideBrowserControl();
529
+ pageDialogRecordId = record.id;
530
+ pageDialogId = dialog.id;
531
+ pageDialogType = dialog.type || 'alert';
532
+ els.pageDialogMessage.textContent = `Page ${pageDialogType}: ${dialog.message || ''}`;
533
+ els.pageDialogField.hidden = pageDialogType !== 'prompt';
534
+ els.pageDialogInput.value = dialog.defaultValue || '';
535
+ els.pageDialogAccept.textContent = pageDialogType === 'alert' ? 'OK' : 'Accept';
536
+ }
537
+ els.pageDialog.hidden = false;
538
+ syncDialogState();
539
+ }
540
+
541
+ async function answerPageDialog(action) {
542
+ const record = records.get(pageDialogRecordId);
543
+ if (!record) { hidePageDialog(); return; }
544
+ const body = { action };
545
+ if (action === 'accept' && pageDialogType === 'prompt') body.text = els.pageDialogInput.value;
546
+ try {
547
+ await api(`/panes/${record.id}/browser/dialog`, { method: 'POST', body });
548
+ hidePageDialog();
549
+ requestSnapshot(record, 120);
550
+ logStatus(action === 'accept' ? 'Page dialog accepted.' : 'Page dialog dismissed.');
551
+ } catch (error) {
552
+ showNotice(error.message || 'Could not answer the page dialog.', 'error');
553
+ }
554
+ }
555
+
556
+ async function sendAsOwner(path, method, body, signal) {
557
+ const headers = { 'X-Townmouse-Owner': ownerKey };
558
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
559
+ const response = await fetch(API_ROOT + path, {
560
+ method,
561
+ headers,
562
+ cache: 'no-store',
563
+ body: body === undefined ? undefined : JSON.stringify(body),
564
+ ...(signal ? { signal } : {})
565
+ });
566
+ let payload = null;
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
+ }
578
+ if (!response.ok) {
579
+ throw new Error((payload && payload.error) || `Request failed (${response.status}).`);
580
+ }
581
+ return payload;
582
+ }
583
+
584
+ function activeTab(state = currentState) {
585
+ if (!state || !Array.isArray(state.tabs)) return null;
586
+ return state.tabs.find((tab) => tab.id === state.activeTabId) || state.tabs[0] || null;
587
+ }
588
+
589
+ function effectiveActivePaneId(tab = activeTab()) {
590
+ if (!tab || !tab.panes.length) return null;
591
+ const candidate = currentState && currentState.activePaneId;
592
+ return tab.panes.some((pane) => pane.id === candidate) ? candidate : tab.panes[0].id;
593
+ }
594
+
595
+ function paneTitle(pane, index) {
596
+ const title = String(pane.title || '').trim();
597
+ if (title) return title;
598
+ if (pane.kind === 'browser') {
599
+ if (pane.url && pane.url !== 'about:blank') return pane.url;
600
+ return 'Browser';
601
+ }
602
+ return `Terminal ${index + 1}`;
603
+ }
604
+
605
+ // ─── Terminal key bar ──────────────────────────────────────────────────────
606
+ // Phones have no Esc/Tab/Ctrl/arrow keys. Emit the same xterm sequences as the
607
+ // main terminal directly through the pane input queue, independent of focus.
608
+
609
+ const PANE_SEQ = {
610
+ esc: '\x1b', tab: '\t',
611
+ up: '\x1b[A', down: '\x1b[B', right: '\x1b[C', left: '\x1b[D',
612
+ home: '\x1b[H', end: '\x1b[F', pgup: '\x1b[5~', pgdn: '\x1b[6~'
613
+ };
614
+ const paneMods = { ctrl: false, alt: false };
615
+
616
+ function activeTerminalRecord() {
617
+ const record = records.get(effectiveActivePaneId());
618
+ return record && record.kind === 'terminal' && !record.disposed ? record : null;
619
+ }
620
+
621
+ async function refreshReaderView() {
622
+ const paneId = effectiveActivePaneId();
623
+ const record = records.get(paneId);
624
+ if (!els.readerText) return;
625
+ if (!record) {
626
+ els.readerText.textContent = 'No active pane.';
627
+ return;
628
+ }
629
+ if (record.kind === 'browser') {
630
+ els.readerText.textContent = 'Reading page text…';
631
+ try {
632
+ const page = await api(`/panes/${paneId}/browser/content`);
633
+ els.readerText.textContent = String(page.text || '').trim() || 'This page has no readable text.';
634
+ } catch (error) {
635
+ els.readerText.textContent = error.message || 'Could not read the page.';
636
+ }
637
+ els.readerText.scrollTop = 0;
638
+ return;
639
+ }
640
+ if (!record.term) {
641
+ els.readerText.textContent = 'No active terminal.';
642
+ return;
643
+ }
644
+ const buffer = record.term.buffer.active;
645
+ const lines = [];
646
+ for (let i = 0; i < buffer.length; i++) {
647
+ const line = buffer.getLine(i);
648
+ lines.push(line ? line.translateToString(true) : '');
649
+ }
650
+ while (lines.length && !lines[0].trim()) lines.shift();
651
+ while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
652
+ els.readerText.textContent = lines.join('\n') || 'No terminal text yet.';
653
+ els.readerText.scrollTop = 0;
654
+ }
655
+
656
+ function openReaderView() {
657
+ if (!els.readerView) return;
658
+ closeSheets();
659
+ els.readerView.hidden = false;
660
+ void refreshReaderView();
661
+ els.readerClose.focus();
662
+ }
663
+
664
+ function closeReaderView() {
665
+ if (!els.readerView) return;
666
+ els.readerView.hidden = true;
667
+ // The reader had the keyboard; it goes back to the active pane.
668
+ settleKeyboard(document.activeElement, activeTab());
669
+ }
670
+
671
+ function syncPaneMods() {
672
+ if (!els.keybar) return;
673
+ els.keybar.querySelectorAll('.pane-key.toggle[data-mod]').forEach((button) => {
674
+ const active = Boolean(paneMods[button.dataset.mod]);
675
+ button.classList.toggle('active', active);
676
+ button.setAttribute('aria-pressed', active ? 'true' : 'false');
677
+ });
678
+ }
679
+
680
+ function clearPaneMods() {
681
+ paneMods.ctrl = false;
682
+ paneMods.alt = false;
683
+ syncPaneMods();
684
+ }
685
+
686
+ function emitPaneSequence(sequence) {
687
+ const record = activeTerminalRecord();
688
+ if (!record) return;
689
+ sendTerminalInput(record, sequence);
690
+ clearPaneMods();
691
+ if (record.term) record.term.focus();
692
+ }
693
+
694
+ function emitPaneLiteral(character) {
695
+ const record = activeTerminalRecord();
696
+ if (!record) return;
697
+ let output = character;
698
+ if (paneMods.ctrl && output.length === 1) output = String.fromCharCode(output.charCodeAt(0) & 0x1f);
699
+ if (paneMods.alt && output.length === 1) output = '\x1b' + output;
700
+ sendTerminalInput(record, output);
701
+ clearPaneMods();
702
+ if (record.term) record.term.focus();
703
+ }
704
+
705
+ function makePaneKey(label, options = {}) {
706
+ const button = document.createElement('button');
707
+ button.type = 'button';
708
+ button.className = 'pane-key';
709
+ button.textContent = label;
710
+ if (options.title) button.title = options.title;
711
+ if (options.key) button.dataset.key = options.key;
712
+ if (options.toggle) {
713
+ button.classList.add('toggle');
714
+ button.dataset.mod = options.toggle;
715
+ button.setAttribute('aria-pressed', 'false');
716
+ button.addEventListener('click', () => {
717
+ paneMods[options.toggle] = !paneMods[options.toggle];
718
+ Object.keys(paneMods).forEach((name) => {
719
+ if (name !== options.toggle) paneMods[name] = false;
720
+ });
721
+ syncPaneMods();
722
+ });
723
+ } else if (options.sequence) {
724
+ button.addEventListener('click', () => emitPaneSequence(options.sequence));
725
+ } else if (options.literal) {
726
+ button.addEventListener('click', () => emitPaneLiteral(options.literal));
727
+ }
728
+ return button;
729
+ }
730
+
731
+ let keybarKind = '';
732
+
733
+ function makeBrowserKey(label, key, title) {
734
+ const button = makePaneKey(label, { title });
735
+ button.addEventListener('click', () => {
736
+ const record = records.get(effectiveActivePaneId());
737
+ if (record && record.kind === 'browser') void browserAction(record, 'key', { key });
738
+ });
739
+ return button;
740
+ }
741
+
742
+ function buildPaneKeybar(kind = 'terminal') {
743
+ if (!els.keybar || keybarKind === kind) return;
744
+ keybarKind = kind;
745
+ const keys = kind === 'browser'
746
+ ? [
747
+ makeBrowserKey('ENTER', 'Enter', 'Enter'),
748
+ makeBrowserKey('TAB', 'Tab', 'Tab'),
749
+ makeBrowserKey('ESC', 'Escape', 'Escape'),
750
+ makeBrowserKey('←', 'ArrowLeft', 'Left'),
751
+ makeBrowserKey('↑', 'ArrowUp', 'Up'),
752
+ makeBrowserKey('↓', 'ArrowDown', 'Down'),
753
+ makeBrowserKey('→', 'ArrowRight', 'Right'),
754
+ makeBrowserKey('⌫', 'Backspace', 'Backspace')
755
+ ]
756
+ : [
757
+ makePaneKey('ESC', { sequence: PANE_SEQ.esc, title: 'Escape' }),
758
+ makePaneKey('TAB', { sequence: PANE_SEQ.tab, title: 'Tab' }),
759
+ makePaneKey('CTRL', { toggle: 'ctrl', title: 'Ctrl (sticky)' }),
760
+ makePaneKey('ALT', { toggle: 'alt', title: 'Alt (sticky)' }),
761
+ makePaneKey('C', { literal: 'c', key: 'c', title: 'C; with CTRL active sends Ctrl+C' }),
762
+ makePaneKey('←', { sequence: PANE_SEQ.left, title: 'Left' }),
763
+ makePaneKey('↑', { sequence: PANE_SEQ.up, title: 'Up' }),
764
+ makePaneKey('↓', { sequence: PANE_SEQ.down, title: 'Down' }),
765
+ makePaneKey('→', { sequence: PANE_SEQ.right, title: 'Right' }),
766
+ makePaneKey('HOME', { sequence: PANE_SEQ.home, title: 'Home' }),
767
+ makePaneKey('END', { sequence: PANE_SEQ.end, title: 'End' }),
768
+ makePaneKey('PGUP', { sequence: PANE_SEQ.pgup, title: 'Page Up' }),
769
+ makePaneKey('PGDN', { sequence: PANE_SEQ.pgdn, title: 'Page Down' })
770
+ ];
771
+ els.keybar.replaceChildren(...keys);
772
+ }
773
+
774
+ function updateKeybar() {
775
+ if (!els.keybar) return;
776
+ const record = activeTerminalRecord();
777
+ const active = records.get(effectiveActivePaneId());
778
+ if (active && active.kind === 'browser') {
779
+ buildPaneKeybar('browser');
780
+ els.keybar.hidden = false;
781
+ } else if (record) {
782
+ buildPaneKeybar('terminal');
783
+ els.keybar.hidden = false;
784
+ } else {
785
+ els.keybar.hidden = true;
786
+ }
787
+ if (els.menuReader) els.menuReader.disabled = !active;
788
+ if (els.menuFontUp) els.menuFontUp.disabled = !record;
789
+ if (els.menuFontDown) els.menuFontDown.disabled = !record;
790
+ }
791
+
792
+ function paneCountLabel(count) {
793
+ return `${count} ${count === 1 ? 'pane' : 'panes'}`;
794
+ }
795
+
796
+ async function refresh() {
797
+ if (!ownerKey) return currentState;
798
+ if (refreshInFlight) {
799
+ try { await refreshInFlight; } catch (_) { /* previous refresh already reported */ }
800
+ }
801
+ const work = (async () => {
802
+ try {
803
+ const next = await api('/state');
804
+ applyState(next);
805
+ return next;
806
+ } catch (error) {
807
+ showNotice(error.message || 'Workspace refresh failed.', 'error');
808
+ return currentState;
809
+ }
810
+ })();
811
+ refreshInFlight = work;
812
+ try {
813
+ return await work;
814
+ } finally {
815
+ if (refreshInFlight === work) refreshInFlight = null;
816
+ }
817
+ }
818
+
819
+ function applyState(next, { force = false } = {}) {
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;
827
+ const previousTabId = currentState && currentState.activeTabId;
828
+ currentState = next;
829
+ updateChrome();
830
+ const tab = activeTab();
831
+ const signature = tab
832
+ ? `${tab.id}|${tab.panes.map((pane) => `${pane.id}:${pane.kind}`).join(',')}`
833
+ : 'none';
834
+ if (force || signature !== lastSignature) {
835
+ lastSignature = signature;
836
+ rebuild(tab);
837
+ } else {
838
+ updatePaneChrome(tab);
839
+ }
840
+ // rebuild() returns before updatePaneChrome() when the active tab is empty.
841
+ discardStaleOverlays();
842
+ prunePaneMemory();
843
+ if (els.tabsDialog.open) renderTabsDialog();
844
+ updateDocumentTitle(tab);
845
+ if (previousTabId && tab && previousTabId !== tab.id) logStatus(`Switched to ${tab.title}.`);
846
+ }
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
+
855
+ function updateChrome() {
856
+ const tabs = (currentState && currentState.tabs) || [];
857
+ els.tabCount.textContent = String(tabs.length);
858
+ els.tabsButton.setAttribute('aria-label', tabs.length === 1 ? 'Workspace tabs, 1 tab' : `Workspace tabs, ${tabs.length} tabs`);
859
+ updateHostContext();
860
+ const limits = currentState && currentState.limits;
861
+ if (limits) {
862
+ els.tabsLimits.textContent = `Up to ${limits.maxTabs} tabs, ${limits.maxPanesPerTab} panes per tab.`;
863
+ }
864
+ updateAddLimits();
865
+ renderTabStrip();
866
+ }
867
+
868
+ function renderTabStrip() {
869
+ if (!els.tabStrip) return;
870
+ const tabs = (currentState && currentState.tabs) || [];
871
+ els.tabStrip.hidden = tabs.length < 2;
872
+ if (tabs.length < 2) { els.tabStrip.replaceChildren(); return; }
873
+ const list = document.createElement('div');
874
+ list.className = 'tabstrip-tabs';
875
+ list.setAttribute('role', 'tablist');
876
+ list.setAttribute('aria-label', 'Workspace tabs');
877
+ for (const tab of tabs) {
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);
882
+ const item = document.createElement('div');
883
+ item.className = 'tabstrip-item' + (active ? ' is-active' : '') + (waiting ? ' has-ask' : '');
884
+ item.dataset.createdBy = tab.createdBy || 'human';
885
+ const button = document.createElement('button');
886
+ button.type = 'button';
887
+ button.className = 'tabstrip-tab' + (active ? ' is-active' : '') + (tab.createdBy === 'agent' ? ' agent-tab' : '');
888
+ button.textContent = tab.title;
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;
893
+ button.setAttribute('role', 'tab');
894
+ button.setAttribute('aria-selected', active ? 'true' : 'false');
895
+ button.setAttribute('aria-controls', 'pane-grid');
896
+ button.tabIndex = active ? 0 : -1;
897
+ button.addEventListener('click', () => { void activateTab(tab.id); });
898
+ const close = document.createElement('button');
899
+ close.type = 'button';
900
+ close.className = 'tabstrip-close';
901
+ close.textContent = '×';
902
+ close.setAttribute('aria-label', `Close tab ${tab.title}`);
903
+ close.addEventListener('click', (event) => {
904
+ event.stopPropagation();
905
+ requestClose('tab', tab.id, tab.title);
906
+ });
907
+ item.append(button, close);
908
+ list.append(item);
909
+ }
910
+ list.addEventListener('keydown', (event) => {
911
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
912
+ const buttons = [...list.querySelectorAll('[role="tab"]')];
913
+ const index = buttons.indexOf(document.activeElement);
914
+ if (index < 0) return;
915
+ event.preventDefault();
916
+ const next = event.key === 'Home' ? 0
917
+ : event.key === 'End' ? buttons.length - 1
918
+ : (index + (event.key === 'ArrowRight' ? 1 : -1) + buttons.length) % buttons.length;
919
+ buttons[next].focus();
920
+ const tab = tabs[next];
921
+ if (tab) void activateTab(tab.id);
922
+ });
923
+ const add = document.createElement('button');
924
+ add.type = 'button';
925
+ add.className = 'tabstrip-add';
926
+ add.textContent = '+ Tab';
927
+ add.setAttribute('aria-label', 'New workspace tab');
928
+ add.addEventListener('click', () => { void newTab(); });
929
+ els.tabStrip.replaceChildren(list, add);
930
+ }
931
+
932
+ const LAYOUT_PREFIX = 'townmouse.pane-layout.';
933
+
934
+ function readPaneLayout(tabId) {
935
+ try {
936
+ const saved = JSON.parse(window.localStorage.getItem(LAYOUT_PREFIX + tabId) || '{}');
937
+ return {
938
+ x: Math.max(0.2, Math.min(0.8, Number(saved.x) || 0.5)),
939
+ y: Math.max(0.2, Math.min(0.8, Number(saved.y) || 0.5))
940
+ };
941
+ } catch (_) {
942
+ return { x: 0.5, y: 0.5 };
943
+ }
944
+ }
945
+
946
+ function savePaneLayout(tabId, layout) {
947
+ try {
948
+ window.localStorage.setItem(LAYOUT_PREFIX + tabId, JSON.stringify(layout));
949
+ } catch (_) { /* storage may be disabled */ }
950
+ }
951
+
952
+ function applyPaneLayout(tab) {
953
+ if (!els.grid || !currentState) return;
954
+ const panes = tab ? tab.panes : [];
955
+ els.grid.querySelectorAll('.pane-splitter').forEach((splitter) => splitter.remove());
956
+ els.grid.style.gridTemplateColumns = '';
957
+ els.grid.style.gridTemplateRows = '';
958
+ els.grid.style.gap = '';
959
+ for (const record of records.values()) record.root.style.gridArea = '';
960
+ if (!tab || panes.length < 2 || window.matchMedia('(max-width: 600px)').matches) return;
961
+
962
+ const count = panes.length;
963
+ const layout = readPaneLayout(tab.id);
964
+ const setTemplates = () => {
965
+ els.grid.style.gridTemplateColumns = `calc((100% - 6px) * ${layout.x}) 6px minmax(0, 1fr)`;
966
+ els.grid.style.gridTemplateRows = count === 2
967
+ ? 'minmax(0, 1fr)'
968
+ : `calc((100% - 6px) * ${layout.y}) 6px minmax(0, 1fr)`;
969
+ els.grid.style.gap = '0';
970
+ els.grid.querySelectorAll('.pane-splitter').forEach((splitter) => {
971
+ splitter.setAttribute('aria-valuenow', String(Math.round((splitter.classList.contains('vertical') ? layout.x : layout.y) * 100)));
972
+ });
973
+ };
974
+ const areas = count === 2
975
+ ? ['1 / 1 / 2 / 2', '1 / 3 / 2 / 4']
976
+ : count === 3
977
+ ? ['1 / 1 / 2 / 4', '3 / 1 / 4 / 2', '3 / 3 / 4 / 4']
978
+ : ['1 / 1 / 2 / 2', '1 / 3 / 2 / 4', '3 / 1 / 4 / 2', '3 / 3 / 4 / 4'];
979
+ panes.forEach((pane, index) => {
980
+ const record = records.get(pane.id);
981
+ if (record && areas[index]) record.root.style.gridArea = areas[index];
982
+ });
983
+
984
+ function makeSplitter(orientation, area) {
985
+ const splitter = document.createElement('div');
986
+ splitter.className = `pane-splitter ${orientation}`;
987
+ splitter.style.gridArea = area;
988
+ splitter.tabIndex = 0;
989
+ splitter.setAttribute('role', 'separator');
990
+ splitter.setAttribute('aria-orientation', orientation === 'vertical' ? 'vertical' : 'horizontal');
991
+ splitter.setAttribute('aria-label', orientation === 'vertical' ? 'Resize pane columns' : 'Resize pane rows');
992
+ splitter.setAttribute('aria-valuemin', '20');
993
+ splitter.setAttribute('aria-valuemax', '80');
994
+ splitter.setAttribute('aria-valuenow', String(Math.round((orientation === 'vertical' ? layout.x : layout.y) * 100)));
995
+ const value = () => orientation === 'vertical' ? layout.x : layout.y;
996
+ const apply = (clientX, clientY) => {
997
+ const rect = els.grid.getBoundingClientRect();
998
+ const ratio = orientation === 'vertical'
999
+ ? (clientX - rect.left) / rect.width
1000
+ : (clientY - rect.top) / rect.height;
1001
+ const clamped = Math.max(0.2, Math.min(0.8, ratio));
1002
+ if (orientation === 'vertical') layout.x = clamped;
1003
+ else layout.y = clamped;
1004
+ setTemplates();
1005
+ savePaneLayout(tab.id, layout);
1006
+ };
1007
+ splitter.addEventListener('pointerdown', (event) => {
1008
+ event.preventDefault();
1009
+ splitter.setPointerCapture?.(event.pointerId);
1010
+ splitter.classList.add('dragging');
1011
+ const move = (moveEvent) => apply(moveEvent.clientX, moveEvent.clientY);
1012
+ const end = () => {
1013
+ splitter.classList.remove('dragging');
1014
+ splitter.removeEventListener('pointermove', move);
1015
+ };
1016
+ splitter.addEventListener('pointermove', move);
1017
+ splitter.addEventListener('pointerup', end, { once: true });
1018
+ splitter.addEventListener('pointercancel', end, { once: true });
1019
+ });
1020
+ splitter.addEventListener('dblclick', () => {
1021
+ layout.x = 0.5;
1022
+ layout.y = 0.5;
1023
+ setTemplates();
1024
+ savePaneLayout(tab.id, layout);
1025
+ });
1026
+ splitter.addEventListener('keydown', (event) => {
1027
+ const step = event.shiftKey ? 0.1 : 0.02;
1028
+ let next = value();
1029
+ if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') next -= step;
1030
+ else if (event.key === 'ArrowRight' || event.key === 'ArrowDown') next += step;
1031
+ else if (event.key === 'Home') next = 0.2;
1032
+ else if (event.key === 'End') next = 0.8;
1033
+ else return;
1034
+ event.preventDefault();
1035
+ next = Math.max(0.2, Math.min(0.8, next));
1036
+ if (orientation === 'vertical') layout.x = next;
1037
+ else layout.y = next;
1038
+ setTemplates();
1039
+ savePaneLayout(tab.id, layout);
1040
+ });
1041
+ return splitter;
1042
+ }
1043
+
1044
+ const splitters = [];
1045
+ if (count === 2) {
1046
+ splitters.push(makeSplitter('vertical', '1 / 2 / 2 / 3'));
1047
+ } else if (count === 3) {
1048
+ splitters.push(makeSplitter('horizontal', '2 / 1 / 3 / 4'));
1049
+ splitters.push(makeSplitter('vertical', '3 / 2 / 4 / 3'));
1050
+ } else {
1051
+ splitters.push(makeSplitter('vertical', '1 / 2 / 2 / 3'));
1052
+ splitters.push(makeSplitter('horizontal', '2 / 1 / 3 / 4'));
1053
+ splitters.push(makeSplitter('vertical', '3 / 2 / 4 / 3'));
1054
+ }
1055
+ els.grid.append(...splitters);
1056
+ setTemplates();
1057
+ }
1058
+
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;
1064
+ const nextTabId = tab ? tab.id : null;
1065
+ const panes = tab ? tab.panes : [];
1066
+
1067
+ if (nextTabId !== currentTabId) {
1068
+ // A tab switch is the one time terminals are discarded outright; their
1069
+ // cursors and local scrollback survive in the maps below.
1070
+ els.grid.classList.remove('is-maximized');
1071
+ teardownPanes();
1072
+ els.grid.replaceChildren();
1073
+ currentTabId = nextTabId;
1074
+ } else {
1075
+ for (const [id, record] of [...records]) {
1076
+ const pane = panes.find((candidate) => candidate.id === id);
1077
+ if (!pane || pane.kind !== record.kind) {
1078
+ if (record.root.classList.contains('is-maximized')) {
1079
+ els.grid.classList.remove('is-maximized');
1080
+ }
1081
+ disposeRecord(record);
1082
+ records.delete(id);
1083
+ record.root.remove();
1084
+ }
1085
+ }
1086
+ }
1087
+
1088
+ const count = panes.length;
1089
+ els.grid.dataset.count = String(count);
1090
+ if (!tab || count === 0) {
1091
+ els.grid.hidden = true;
1092
+ els.emptyState.hidden = false;
1093
+ updateEmptyState(tab);
1094
+ settleKeyboard(keyboard, tab);
1095
+ return;
1096
+ }
1097
+ els.grid.hidden = false;
1098
+ els.emptyState.hidden = true;
1099
+ panes.forEach((pane, index) => {
1100
+ const existing = records.get(pane.id);
1101
+ const node = existing
1102
+ ? existing.root
1103
+ : (pane.kind === 'browser' ? createBrowserPane(pane) : createTerminalPane(pane));
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
+ });
1109
+ updatePaneChrome(tab);
1110
+ applyPaneLayout(tab);
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();
1228
+ }
1229
+
1230
+ // Maximize/restore is available both from Alt+M and from a visible control in
1231
+ // the pane header, so the feature is discoverable without knowing the shortcut.
1232
+ function togglePaneMaximized(paneId) {
1233
+ const id = paneId || effectiveActivePaneId();
1234
+ const record = records.get(id);
1235
+ if (!record) return;
1236
+ const maximize = !(els.grid.classList.contains('is-maximized') && record.root.classList.contains('is-maximized'));
1237
+ els.grid.classList.toggle('is-maximized', maximize);
1238
+ for (const [candidateId, candidate] of records) {
1239
+ candidate.root.classList.toggle('is-maximized', maximize && candidateId === id);
1240
+ }
1241
+ syncMaximizeButtons();
1242
+ logStatus(maximize ? 'Pane maximized.' : 'Pane restored.');
1243
+ }
1244
+
1245
+ function syncMaximizeButtons() {
1246
+ const gridMaximized = els.grid.classList.contains('is-maximized');
1247
+ for (const record of records.values()) {
1248
+ const button = record.maximizeButton;
1249
+ if (!button) continue;
1250
+ const active = gridMaximized && record.root.classList.contains('is-maximized');
1251
+ button.innerHTML = active ? RESTORE_ICON : MAXIMIZE_ICON;
1252
+ button.setAttribute('aria-label', active ? 'Restore pane' : 'Maximize pane');
1253
+ button.setAttribute('aria-pressed', active ? 'true' : 'false');
1254
+ button.title = active ? 'Restore split view (Alt+M)' : 'Maximize pane (Alt+M)';
1255
+ }
1256
+ }
1257
+
1258
+ function updateEmptyState(tab) {
1259
+ if (!tab) {
1260
+ els.emptyTitle.textContent = 'No workspace tabs';
1261
+ els.emptyCopy.textContent = 'Create a tab to open terminals and browsers.';
1262
+ } else if (!tab.panes.length) {
1263
+ els.emptyTitle.textContent = 'This tab is empty';
1264
+ els.emptyCopy.textContent = `${tab.title} has no panes yet. Add a terminal or a browser.`;
1265
+ }
1266
+ els.emptyActions.hidden = false;
1267
+ }
1268
+
1269
+ // Compact age for agent-reported status, so an old report does not read as a
1270
+ // fresh one. Program status and agent status are shown as separate facts.
1271
+ function formatAge(ms) {
1272
+ const seconds = Math.max(0, Math.round(ms / 1000));
1273
+ if (seconds < 45) return 'just now';
1274
+ const minutes = Math.round(seconds / 60);
1275
+ if (minutes < 60) return `${minutes}m`;
1276
+ const hours = Math.round(minutes / 60);
1277
+ if (hours < 24) return `${hours}h`;
1278
+ return `${Math.round(hours / 24)}d`;
1279
+ }
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
+
1452
+ function updatePaneChrome(tab) {
1453
+ if (!tab) { updateBackButton(); updateKeybar(); updateHostContext(); return; }
1454
+ const activeId = effectiveActivePaneId(tab);
1455
+ tab.panes.forEach((pane, index) => {
1456
+ const record = records.get(pane.id);
1457
+ if (!record) return;
1458
+ record.root.classList.toggle('is-active', pane.id === activeId);
1459
+ const title = paneTitle(pane, index);
1460
+ if (record.titleEl.textContent !== title) record.titleEl.textContent = title;
1461
+ record.titleEl.title = title;
1462
+ record.closeButton.setAttribute('aria-label', `Close ${pane.kind} pane ${title}`);
1463
+ syncPaneAccess(record, pane);
1464
+ if (record.kind === 'terminal') {
1465
+ const status = pane.status === 'exited' ? 'exited' : 'running';
1466
+ if (record.root.dataset.status !== status) record.root.dataset.status = status;
1467
+ const agentState = pane.agentState || '';
1468
+ record.root.dataset.agentState = agentState;
1469
+ record.root.dataset.programStatus = status;
1470
+ const ageMs = Number(pane.agentStateAgeMs);
1471
+ const agentText = agentState
1472
+ ? `${agentState}${Number.isFinite(ageMs) ? ` · ${formatAge(ageMs)}` : ''}`
1473
+ : '';
1474
+ const kindText = status === 'exited'
1475
+ ? (agentText ? `Terminal · exited · ${agentText}` : 'Terminal · exited')
1476
+ : agentText ? `Terminal · ${agentText}` : 'Terminal';
1477
+ if (record.kindEl.textContent !== kindText) record.kindEl.textContent = kindText;
1478
+ const command = pane.command;
1479
+ const commandText = command
1480
+ ? ` Last command: ${command.status}${Number.isFinite(command.exitCode) ? ` (exit ${command.exitCode})` : ''}.`
1481
+ : '';
1482
+ record.kindEl.title = (agentState
1483
+ ? `Program: ${status}. Agent last reported "${agentState}" ${Number.isFinite(ageMs) ? formatAge(ageMs) : 'recently'} ago.`
1484
+ : `Program: ${status}. The agent has not reported a status.`) + commandText;
1485
+ } else {
1486
+ if (record.kindEl.textContent !== 'Browser') record.kindEl.textContent = 'Browser';
1487
+ if (pane.url && !record.addressDirty && document.activeElement !== record.addressInput && record.addressInput.value !== addressBoxText(pane.url)) {
1488
+ record.addressInput.value = addressBoxText(pane.url);
1489
+ }
1490
+ record.currentUrl = pane.url || record.currentUrl;
1491
+ }
1492
+ });
1493
+ discardStaleOverlays();
1494
+ updateKeybar();
1495
+ updateBackButton();
1496
+ }
1497
+
1498
+ // Overlay ids can outlive their pane when a tab is switched or a pane closes.
1499
+ // Reconcile them with the rebuilt records so a stale menu/control/dialog does
1500
+ // not keep the reserved strip (and its .dialog-open/.menu-open class) latched.
1501
+ function discardStaleOverlays() {
1502
+ if (browserControlRecordId && !records.has(browserControlRecordId)) hideBrowserControl();
1503
+ if (contextRecordId && !records.has(contextRecordId)) hideContextMenu();
1504
+ if (browserContextRecordId && !records.has(browserContextRecordId)) hideContextMenu();
1505
+ if (pageDialogRecordId && !records.has(pageDialogRecordId)) hidePageDialog();
1506
+ }
1507
+
1508
+ function updateActiveClasses() {
1509
+ const tab = activeTab();
1510
+ const activeId = effectiveActivePaneId(tab);
1511
+ for (const [id, record] of records) {
1512
+ record.root.classList.toggle('is-active', id === activeId);
1513
+ }
1514
+ const active = records.get(activeId);
1515
+ if (active && active.kind === 'browser') {
1516
+ requestAnimationFrame(() => {
1517
+ if (!active.disposed) active.resizeBrowser?.();
1518
+ });
1519
+ }
1520
+ updateKeybar();
1521
+ updateHostContext();
1522
+ updateBackButton();
1523
+ }
1524
+
1525
+ function updateHostContext() {
1526
+ if (!els.hostName) return;
1527
+ const tab = activeTab();
1528
+ const host = currentState?.host || 'localhost';
1529
+ const narrow = window.matchMedia('(max-width: 699px)').matches;
1530
+ els.hostName.textContent = narrow && tab ? tab.title : host;
1531
+ if (els.hostPill) els.hostPill.title = narrow ? `Active tab: ${tab ? tab.title : 'none'} · ${host}` : host;
1532
+ }
1533
+
1534
+ function updateBackButton() {
1535
+ const record = records.get(effectiveActivePaneId());
1536
+ const enabled = Boolean(record && record.kind === 'browser' && record.canGoBack);
1537
+ els.backButton.disabled = !enabled;
1538
+ els.backButton.setAttribute('aria-label', enabled ? `Back in ${record.titleEl.textContent || 'browser'}` : 'Back');
1539
+ }
1540
+
1541
+ function prunePaneMemory() {
1542
+ if (!currentState) return;
1543
+ const live = new Set();
1544
+ for (const tab of currentState.tabs) for (const pane of tab.panes) live.add(pane.id);
1545
+ for (const id of cursors.keys()) {
1546
+ if (!live.has(id)) { cursors.delete(id); histories.delete(id); }
1547
+ }
1548
+ }
1549
+
1550
+ async function setActivePane(paneId) {
1551
+ if (!paneId || !currentState) return;
1552
+ if (currentState.activePaneId === paneId) { updateActiveClasses(); return; }
1553
+ currentState = { ...currentState, activePaneId: paneId };
1554
+ updateActiveClasses();
1555
+ try {
1556
+ const next = await api('/active', { method: 'POST', body: { paneId } });
1557
+ applyState(next);
1558
+ } catch (error) {
1559
+ showNotice(error.message || 'Could not select the pane.', 'error');
1560
+ }
1561
+ }
1562
+
1563
+ function onPanePointerDown(event) {
1564
+ if (event.target.closest('button')) return;
1565
+ const paneId = event.currentTarget.dataset.paneId;
1566
+ if (paneId) void setActivePane(paneId);
1567
+ }
1568
+
1569
+ function teardownPanes() {
1570
+ // Switching tabs disposes the terminal view but not the server-side shell.
1571
+ // Let already-queued input (an editor paste, a command plus Enter) finish
1572
+ // instead of silently truncating it when the user changes views.
1573
+ for (const record of records.values()) disposeRecord(record, { keepInput: true });
1574
+ records.clear();
1575
+ }
1576
+
1577
+ function disposeRecord(record, { keepInput = false } = {}) {
1578
+ if (!record || record.disposed) return;
1579
+ record.disposed = true;
1580
+ if (record.readTimer) { clearTimeout(record.readTimer); record.readTimer = 0; }
1581
+ if (record.streamController) {
1582
+ try { record.streamController.abort(); } catch (_) { /* already ended */ }
1583
+ record.streamController = null;
1584
+ }
1585
+ const pump = record.kind === 'terminal' ? inputPumpFor(record.id) : null;
1586
+ if (keepInput && pump) {
1587
+ // No timer and no request in flight means nothing would deliver what is
1588
+ // already queued; restart the flush before dropping the view.
1589
+ if (pump.pendingInput && !pump.inputBusy && !pump.inputTimer) {
1590
+ pump.inputTimer = window.setTimeout(() => {
1591
+ pump.inputTimer = 0;
1592
+ void flushTerminalInput(pump);
1593
+ }, 12);
1594
+ }
1595
+ } else if (pump) {
1596
+ pump.inputStopped = true;
1597
+ pump.pendingInput = '';
1598
+ if (pump.inputTimer) { clearTimeout(pump.inputTimer); pump.inputTimer = 0; }
1599
+ inputPumps.delete(record.id);
1600
+ }
1601
+ if (record.viewWatch) { record.viewWatch.stop(); record.viewWatch = null; }
1602
+ if (record.pictures) { record.pictures.stop(); record.pictures = null; }
1603
+ if (record.wheelTimer) { clearTimeout(record.wheelTimer); record.wheelTimer = 0; }
1604
+ if (record.fitFrame) { cancelAnimationFrame(record.fitFrame); record.fitFrame = 0; }
1605
+ if (record.resizeObserver) {
1606
+ try { record.resizeObserver.disconnect(); } catch (_) { /* already detached */ }
1607
+ record.resizeObserver = null;
1608
+ }
1609
+ if (record.resizeTimer) { clearTimeout(record.resizeTimer); record.resizeTimer = 0; }
1610
+ if (record.term) {
1611
+ try { record.term.dispose(); } catch (_) { /* already disposed */ }
1612
+ record.term = null;
1613
+ }
1614
+ }
1615
+
1616
+ function createTerminalPane(pane) {
1617
+ const root = document.createElement('section');
1618
+ root.className = 'pane pane-terminal';
1619
+ root.dataset.paneId = pane.id;
1620
+ root.dataset.kind = 'terminal';
1621
+ root.dataset.createdBy = pane.createdBy || 'human';
1622
+ root.dataset.status = pane.status === 'exited' ? 'exited' : 'running';
1623
+ root.innerHTML =
1624
+ '<header class="pane-header">' +
1625
+ '<span class="pane-title"></span>' +
1626
+ '<span class="pane-kind">Terminal</span>' +
1627
+ `<button type="button" class="pane-maximize" aria-label="Maximize pane" title="Maximize (Alt+M)">${MAXIMIZE_ICON}</button>` +
1628
+ `<button type="button" class="pane-close" aria-label="Close terminal pane">${CLOSE_ICON}</button>` +
1629
+ '</header>' +
1630
+ '<div class="pane-body"><div class="terminal-host"></div></div>';
1631
+
1632
+ const record = {
1633
+ id: pane.id,
1634
+ kind: 'terminal',
1635
+ root,
1636
+ titleEl: root.querySelector('.pane-title'),
1637
+ kindEl: root.querySelector('.pane-kind'),
1638
+ closeButton: root.querySelector('.pane-close'),
1639
+ host: root.querySelector('.terminal-host'),
1640
+ term: null,
1641
+ fit: null,
1642
+ resizeObserver: null,
1643
+ fitFrame: 0,
1644
+ readTimer: 0,
1645
+ pendingInput: '',
1646
+ inputTimer: 0,
1647
+ inputBusy: false,
1648
+ inputStopped: false,
1649
+ streamController: null,
1650
+ offset: cursors.get(pane.id) || 0,
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,
1659
+ exited: false,
1660
+ pendingStart: pane.status === 'starting',
1661
+ starting: false,
1662
+ disposed: false
1663
+ };
1664
+ record.titleEl.textContent = pane.title || 'Terminal';
1665
+ record.closeButton.setAttribute('aria-label', `Close terminal pane ${pane.title || 'Terminal'}`);
1666
+ record.maximizeButton = root.querySelector('.pane-maximize');
1667
+ record.maximizeButton.addEventListener('click', () => { togglePaneMaximized(pane.id); });
1668
+ root.addEventListener('pointerdown', onPanePointerDown);
1669
+ root.addEventListener('focusin', () => { void setActivePane(pane.id); });
1670
+ record.closeButton.addEventListener('click', () => { requestClose('pane', pane.id, record.titleEl.textContent); });
1671
+ records.set(pane.id, record);
1672
+ attachPaneAccess(root, record, pane);
1673
+ wireDrop(root, pane.id);
1674
+ wirePaneReorder(root, pane.id);
1675
+ wirePaneContext(root, record);
1676
+ requestAnimationFrame(() => {
1677
+ if (!record.disposed && root.isConnected) mountTerminal(record);
1678
+ });
1679
+ return root;
1680
+ }
1681
+
1682
+ function mountTerminal(record) {
1683
+ if (record.term || record.disposed || !record.host.isConnected) return;
1684
+ const term = new Terminal({
1685
+ cursorBlink: !reducedMotion.matches,
1686
+ cursorStyle: 'bar',
1687
+ cursorWidth: 2,
1688
+ fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',
1689
+ fontSize: 13,
1690
+ lineHeight: 1.15,
1691
+ letterSpacing: 0,
1692
+ scrollback: 5000,
1693
+ convertEol: false,
1694
+ allowTransparency: false,
1695
+ theme: TERMINAL_THEME
1696
+ });
1697
+ const fit = new FitAddon();
1698
+ term.loadAddon(fit);
1699
+ term.loadAddon(new WebLinksAddon());
1700
+ try {
1701
+ term.open(record.host);
1702
+ // OSC 52 clipboard writes: agents and shell tools can copy without a
1703
+ // synthetic keystroke. Reads are deliberately not supported.
1704
+ term.parser.registerOscHandler(52, (data) => {
1705
+ const payload = String(data).split(';')[1] || '';
1706
+ if (payload && payload !== '?') {
1707
+ try {
1708
+ const text = decodeClipboardText(payload);
1709
+ if (text) navigator.clipboard?.writeText(text).catch(() => {});
1710
+ } catch (_) { /* malformed clipboard payload */ }
1711
+ }
1712
+ return true;
1713
+ });
1714
+ } catch (error) {
1715
+ showNotice('The terminal could not be opened.', 'error');
1716
+ try { term.dispose(); } catch (_) { /* nothing to release */ }
1717
+ return;
1718
+ }
1719
+ record.term = term;
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.
1730
+ // Terminal copy: Cmd/Ctrl+C with a selection copies; with no selection it
1731
+ // still reaches the PTY as SIGINT, matching terminal expectations.
1732
+ term.attachCustomKeyEventHandler((event) => {
1733
+ const platform = navigator.userAgentData?.platform || navigator.platform || '';
1734
+ const copyChord = /mac|iphone|ipad/i.test(platform)
1735
+ ? event.metaKey && !event.ctrlKey
1736
+ : event.ctrlKey && event.shiftKey;
1737
+ // Bare Ctrl+C must always interrupt the foreground process, even when
1738
+ // text is selected. Swallowing it for copy is a terminal cardinal sin.
1739
+ if (!copyChord || event.key.toLowerCase() !== 'c' || !term.hasSelection()) return true;
1740
+ try { navigator.clipboard?.writeText(term.getSelection()); } catch (_) { /* clipboard denied */ }
1741
+ return false;
1742
+ });
1743
+ term.onData((data) => {
1744
+ if (!record.disposed && data) sendTerminalInput(record, data);
1745
+ });
1746
+ term.onResize(({ cols, rows }) => {
1747
+ if (!record.disposed && !record.opensWide) sendTerminalResize(record, cols, rows);
1748
+ });
1749
+ handKeyboardToTerminal(record);
1750
+ const history = histories.get(record.id);
1751
+ requestAnimationFrame(() => {
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
+ }
1763
+ // Fit before replaying or spawning: the first prompt and the local history
1764
+ // must be laid out at the pane's real width, not xterm's default grid.
1765
+ safeFit(record);
1766
+ if (history) term.write(history);
1767
+ if (record.pendingStart) {
1768
+ void startPendingTerminal(record);
1769
+ } else {
1770
+ void startTerminalStream(record);
1771
+ sendTerminalResize(record, record.term.cols, record.term.rows);
1772
+ }
1773
+ });
1774
+ const applyFontSize = () => {
1775
+ if (record.disposed || !record.term) return;
1776
+ const width = record.host.getBoundingClientRect().width;
1777
+ const override = paneFontOverride();
1778
+ const size = override || (width >= 560 ? 13 : width >= 430 ? 12 : width >= 320 ? 11 : 10);
1779
+ if (record.term.options.fontSize !== size) {
1780
+ record.term.options.fontSize = size;
1781
+ safeFit(record);
1782
+ }
1783
+ };
1784
+ applyFontSize();
1785
+ record.resizeObserver = new ResizeObserver(() => {
1786
+ if (record.disposed) return;
1787
+ if (record.fitFrame) cancelAnimationFrame(record.fitFrame);
1788
+ record.fitFrame = requestAnimationFrame(() => {
1789
+ record.fitFrame = 0;
1790
+ applyFontSize();
1791
+ safeFit(record);
1792
+ });
1793
+ });
1794
+ record.resizeObserver.observe(record.host);
1795
+ }
1796
+
1797
+ async function startPendingTerminal(record) {
1798
+ if (!record || record.disposed || record.starting || !record.term) return;
1799
+ record.starting = true;
1800
+ try {
1801
+ await api(`/panes/${record.id}/start`, {
1802
+ method: 'POST',
1803
+ body: { cols: record.term.cols, rows: record.term.rows }
1804
+ });
1805
+ if (record.disposed) return;
1806
+ record.pendingStart = false;
1807
+ void startTerminalStream(record);
1808
+ } catch (error) {
1809
+ if (!record.disposed) {
1810
+ showNotice(error.message || 'The terminal could not start.', 'error');
1811
+ void startTerminalStream(record);
1812
+ }
1813
+ } finally {
1814
+ record.starting = false;
1815
+ }
1816
+ }
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
+
1877
+ function safeFit(record) {
1878
+ if (record.disposed || !record.fit || !record.term || record.opensWide) return;
1879
+ const rect = record.host.getBoundingClientRect();
1880
+ if (rect.width < 24 || rect.height < 24) return;
1881
+ try { record.fit.fit(); } catch (_) { /* layout not ready yet */ }
1882
+ }
1883
+
1884
+ function sendTerminalResize(record, cols, rows) {
1885
+ const next = `${cols}x${rows}`;
1886
+ if (record.lastResize === next) return;
1887
+ record.lastResize = next;
1888
+ api(`/panes/${record.id}/resize`, { method: 'POST', body: { cols, rows } }).catch(() => {
1889
+ record.lastResize = '';
1890
+ });
1891
+ }
1892
+
1893
+ function sendTerminalInput(record, data) {
1894
+ const pump = inputPumpFor(record.id);
1895
+ if (pump.inputStopped || !data) return;
1896
+ // Coalesce fast typing and pastes into one ordered request instead of one
1897
+ // HTTP round-trip per keystroke. This is the difference between smooth and
1898
+ // jittery input when the agent or a build is also producing output.
1899
+ pump.pendingInput += data;
1900
+ if (pump.inputTimer || pump.inputBusy) return;
1901
+ pump.inputTimer = window.setTimeout(() => {
1902
+ pump.inputTimer = 0;
1903
+ void flushTerminalInput(pump);
1904
+ }, 12);
1905
+ }
1906
+
1907
+ async function flushTerminalInput(pump) {
1908
+ if (pump.inputStopped || pump.inputBusy || !pump.pendingInput) return;
1909
+ const payload = pump.pendingInput;
1910
+ pump.pendingInput = '';
1911
+ pump.inputBusy = true;
1912
+ try {
1913
+ // Keep each request below the global JSON body limit so large pastes work.
1914
+ for (const chunk of chunkInput(payload)) {
1915
+ if (pump.inputStopped) break;
1916
+ await api(`/panes/${pump.paneId}/input`, { method: 'POST', body: { data: chunk } });
1917
+ }
1918
+ } catch (error) {
1919
+ if (!pump.inputStopped) logStatus('Terminal input could not be sent.');
1920
+ } finally {
1921
+ pump.inputBusy = false;
1922
+ if (!pump.inputStopped && pump.pendingInput) {
1923
+ pump.inputTimer = window.setTimeout(() => {
1924
+ pump.inputTimer = 0;
1925
+ void flushTerminalInput(pump);
1926
+ }, 12);
1927
+ }
1928
+ }
1929
+ }
1930
+
1931
+ async function startTerminalStream(record) {
1932
+ if (record.disposed || !record.term) return;
1933
+ if (record.streamController) {
1934
+ try { record.streamController.abort(); } catch (_) { /* already ended */ }
1935
+ }
1936
+ const controller = new AbortController();
1937
+ record.streamController = controller;
1938
+ try {
1939
+ const response = await fetch(`/api/panes/panes/${record.id}/stream?since=${record.offset || 0}`, {
1940
+ headers: { 'X-Townmouse-Owner': ownerKey },
1941
+ signal: controller.signal,
1942
+ cache: 'no-store'
1943
+ });
1944
+ if (!response.ok || !response.body) throw new Error(`Output stream failed (${response.status}).`);
1945
+ const reader = response.body.getReader();
1946
+ const decoder = new TextDecoder();
1947
+ let buffer = '';
1948
+ while (!record.disposed) {
1949
+ const { value, done } = await reader.read();
1950
+ if (done) break;
1951
+ buffer += decoder.decode(value, { stream: true });
1952
+ let boundary;
1953
+ while ((boundary = buffer.indexOf('\n\n')) >= 0) {
1954
+ const event = buffer.slice(0, boundary);
1955
+ buffer = buffer.slice(boundary + 2);
1956
+ const line = event.split('\n').find((entry) => entry.startsWith('data: '));
1957
+ if (!line) continue;
1958
+ let payload = null;
1959
+ try { payload = JSON.parse(line.slice(6)); } catch (_) { continue; }
1960
+ if (!record.term || record.disposed) continue;
1961
+ if (payload.data) {
1962
+ writeTerminalOutput(record, payload.data, Number(payload.offset));
1963
+ rememberOutput(record.id, payload.data);
1964
+ }
1965
+ if (Number.isFinite(Number(payload.offset))) {
1966
+ record.offset = Number(payload.offset);
1967
+ cursors.set(record.id, record.offset);
1968
+ }
1969
+ if (payload.exited && !record.exited) markTerminalExited(record);
1970
+ }
1971
+ }
1972
+ } catch (error) {
1973
+ if (record.disposed || controller.signal.aborted) return;
1974
+ }
1975
+ // A dropped stream is not a dead terminal: fall back to polling.
1976
+ if (!record.disposed) startTerminalRead(record);
1977
+ }
1978
+
1979
+ function startTerminalRead(record) {
1980
+ if (record.readTimer) { clearTimeout(record.readTimer); record.readTimer = 0; }
1981
+ const poll = async () => {
1982
+ if (record.disposed) return;
1983
+ try {
1984
+ const payload = await api(`/panes/${record.id}/read?since=${record.offset || 0}`);
1985
+ if (record.disposed || !record.term) return;
1986
+ if (payload && payload.data) {
1987
+ writeTerminalOutput(record, payload.data, Number(payload.offset));
1988
+ rememberOutput(record.id, payload.data);
1989
+ }
1990
+ const nextOffset = Number(payload && payload.offset);
1991
+ if (Number.isFinite(nextOffset)) {
1992
+ record.offset = nextOffset;
1993
+ cursors.set(record.id, nextOffset);
1994
+ }
1995
+ if (payload && payload.exited && !record.exited) markTerminalExited(record);
1996
+ } catch (error) {
1997
+ // A missed read is retried; the workspace poll reports connection loss.
1998
+ } finally {
1999
+ if (!record.disposed && !record.exited) {
2000
+ record.readTimer = window.setTimeout(poll, READ_POLL_MS);
2001
+ }
2002
+ }
2003
+ };
2004
+ poll();
2005
+ }
2006
+
2007
+ function markTerminalExited(record) {
2008
+ if (record.exited) return;
2009
+ record.exited = true;
2010
+ record.root.dataset.status = 'exited';
2011
+ record.kindEl.textContent = 'Terminal · exited';
2012
+ const marker = '\r\n\x1b[38;5;244m[process exited]\x1b[0m\r\n';
2013
+ if (record.term) record.term.write(marker);
2014
+ rememberOutput(record.id, '\r\n[process exited]\r\n');
2015
+ logStatus(`${record.titleEl.textContent} exited.`);
2016
+ }
2017
+
2018
+ function rememberOutput(paneId, data) {
2019
+ const value = (histories.get(paneId) || '') + data;
2020
+ histories.set(paneId, value.length > MAX_HISTORY ? value.slice(-MAX_HISTORY) : value);
2021
+ }
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
+
2030
+ function createBrowserPane(pane) {
2031
+ const root = document.createElement('section');
2032
+ root.className = 'pane pane-browser';
2033
+ root.dataset.paneId = pane.id;
2034
+ root.dataset.kind = 'browser';
2035
+ root.dataset.createdBy = pane.createdBy || 'human';
2036
+ root.innerHTML =
2037
+ '<header class="pane-header">' +
2038
+ '<span class="pane-title"></span>' +
2039
+ '<span class="pane-kind">Browser</span>' +
2040
+ `<button type="button" class="pane-maximize" aria-label="Maximize pane" title="Maximize (Alt+M)">${MAXIMIZE_ICON}</button>` +
2041
+ `<button type="button" class="pane-close" aria-label="Close browser pane">${CLOSE_ICON}</button>` +
2042
+ '</header>' +
2043
+ '<div class="pane-body">' +
2044
+ '<div class="browser-toolbar">' +
2045
+ `<button type="button" class="browser-icon-button browser-back" aria-label="Back">${BACK_ICON}</button>` +
2046
+ '<button type="button" class="browser-icon-button browser-forward" aria-label="Forward"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg></button>' +
2047
+ `<button type="button" class="browser-icon-button browser-reload" aria-label="Reload">${RELOAD_ICON}</button>` +
2048
+ `<button type="button" class="browser-icon-button browser-size" aria-label="Lock browser size" aria-pressed="false" title="Fixed size: keep the page from resizing with your viewer">${LOCK_ICON}</button>` +
2049
+ '<form class="address-form" novalidate>' +
2050
+ '<input class="address-input" type="text" inputmode="url" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="Enter an address" aria-label="Address">' +
2051
+ '<button type="submit" class="address-go">Go</button>' +
2052
+ '</form>' +
2053
+ '</div>' +
2054
+ '<div class="browser-view">' +
2055
+ '<img class="browser-image" alt="" draggable="false" tabindex="0">' +
2056
+ '<button type="button" class="pane-reopen" hidden>Reopen browser</button>' +
2057
+ '</div>' +
2058
+ '<form class="browser-type-row" novalidate>' +
2059
+ '<input class="browser-type-input" type="text" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="Type into the page" aria-label="Type into the page">' +
2060
+ '<button type="submit" class="address-go">Send</button>' +
2061
+ '</form>' +
2062
+ '</div>';
2063
+
2064
+ const record = {
2065
+ id: pane.id,
2066
+ kind: 'browser',
2067
+ root,
2068
+ titleEl: root.querySelector('.pane-title'),
2069
+ kindEl: root.querySelector('.pane-kind'),
2070
+ closeButton: root.querySelector('.pane-close'),
2071
+ addressForm: root.querySelector('.address-form'),
2072
+ addressInput: root.querySelector('.address-input'),
2073
+ typeForm: root.querySelector('.browser-type-row'),
2074
+ typeInput: root.querySelector('.browser-type-input'),
2075
+ view: root.querySelector('.browser-view'),
2076
+ image: root.querySelector('.browser-image'),
2077
+ reopenButton: root.querySelector('.pane-reopen'),
2078
+ backButton: root.querySelector('.browser-back'),
2079
+ forwardButton: root.querySelector('.browser-forward'),
2080
+ reloadButton: root.querySelector('.browser-reload'),
2081
+ sizeButton: root.querySelector('.browser-size'),
2082
+ sizing: pane.sizing === 'fixed' ? 'fixed' : 'fit',
2083
+ width: 1280,
2084
+ height: 800,
2085
+ currentUrl: pane.url || '',
2086
+ addressDirty: false,
2087
+ // Whether a person can see this pane right now, and its picture stream.
2088
+ viewed: false,
2089
+ pictures: null,
2090
+ viewWatch: null,
2091
+ wheelDelta: 0,
2092
+ wheelDeltaX: 0,
2093
+ wheelTimer: 0,
2094
+ lastDialogAt: '',
2095
+ resizeObserver: null,
2096
+ resizeTimer: 0,
2097
+ lastViewport: '',
2098
+ canGoBack: false,
2099
+ canGoForward: false,
2100
+ disposed: false
2101
+ };
2102
+ record.titleEl.textContent = pane.title || 'Browser';
2103
+ record.closeButton.setAttribute('aria-label', `Close browser pane ${pane.title || 'Browser'}`);
2104
+ record.maximizeButton = root.querySelector('.pane-maximize');
2105
+ record.maximizeButton.addEventListener('click', () => { togglePaneMaximized(pane.id); });
2106
+ record.addressInput.value = addressBoxText(pane.url);
2107
+ record.backButton.disabled = true;
2108
+ record.forwardButton.disabled = true;
2109
+
2110
+ root.addEventListener('pointerdown', onPanePointerDown);
2111
+ root.addEventListener('focusin', () => { void setActivePane(pane.id); });
2112
+ record.closeButton.addEventListener('click', () => { requestClose('pane', pane.id, record.titleEl.textContent); });
2113
+ record.backButton.addEventListener('click', () => { void browserAction(record, 'back'); });
2114
+ record.forwardButton.addEventListener('click', () => { void browserAction(record, 'forward'); });
2115
+ record.reloadButton.addEventListener('click', () => { void browserAction(record, 'reload'); });
2116
+ record.sizeButton.addEventListener('click', () => { void toggleBrowserSizing(record); });
2117
+ record.addressForm.addEventListener('submit', (event) => {
2118
+ event.preventDefault();
2119
+ void navigateBrowser(record);
2120
+ });
2121
+ record.addressInput.addEventListener('input', () => { record.addressDirty = true; });
2122
+ record.addressInput.addEventListener('blur', () => {
2123
+ window.setTimeout(() => {
2124
+ if (record.disposed || !record.addressDirty || document.activeElement === record.addressInput) return;
2125
+ record.addressDirty = false;
2126
+ record.addressInput.value = addressBoxText(record.currentUrl);
2127
+ }, 250);
2128
+ });
2129
+ record.typeForm.addEventListener('submit', (event) => {
2130
+ event.preventDefault();
2131
+ submitBrowserType(record);
2132
+ });
2133
+ record.image.addEventListener('click', (event) => {
2134
+ record.image.focus({ preventScroll: true });
2135
+ void onBrowserImageClick(record, event);
2136
+ });
2137
+ record.reopenButton.addEventListener('click', async () => {
2138
+ try {
2139
+ await api(`/panes/${record.id}/browser/reopen`, { method: 'POST' });
2140
+ record.lastViewport = '';
2141
+ record.reopenButton.hidden = true;
2142
+ record.root.classList.remove('is-offline');
2143
+ requestSnapshot(record, 120);
2144
+ } catch (error) {
2145
+ showNotice(error.message || 'Could not reopen the browser.', 'error');
2146
+ }
2147
+ });
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.
2151
+ if (event.metaKey || event.ctrlKey || event.altKey) return;
2152
+ if (event.key.length === 1) {
2153
+ event.preventDefault();
2154
+ void browserAction(record, 'type', { text: event.key });
2155
+ return;
2156
+ }
2157
+ const named = ['Enter', 'Backspace', 'Escape', 'Tab', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown'];
2158
+ if (!named.includes(event.key)) return;
2159
+ event.preventDefault();
2160
+ void browserAction(record, 'key', { key: event.key });
2161
+ });
2162
+ record.view.addEventListener('wheel', (event) => onBrowserWheel(record, event), { passive: false });
2163
+ let touchY = 0;
2164
+ let touchX = 0;
2165
+ let touchActive = false;
2166
+ record.view.addEventListener('touchstart', (event) => {
2167
+ if (event.touches.length !== 1) return;
2168
+ touchActive = true;
2169
+ touchY = event.touches[0].clientY;
2170
+ touchX = event.touches[0].clientX;
2171
+ }, { passive: true });
2172
+ record.view.addEventListener('touchmove', (event) => {
2173
+ if (!touchActive || event.touches.length !== 1) return;
2174
+ event.preventDefault();
2175
+ const nextY = event.touches[0].clientY;
2176
+ const nextX = event.touches[0].clientX;
2177
+ const deltaY = touchY - nextY;
2178
+ const deltaX = touchX - nextX;
2179
+ touchY = nextY;
2180
+ touchX = nextX;
2181
+ if (deltaY || deltaX) queueBrowserScroll(record, deltaY, deltaX);
2182
+ }, { passive: false });
2183
+ record.view.addEventListener('touchend', () => { touchActive = false; }, { passive: true });
2184
+
2185
+ records.set(pane.id, record);
2186
+ attachPaneAccess(root, record, pane);
2187
+ wireDrop(root, pane.id);
2188
+ wirePaneReorder(root, pane.id);
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
+ });
2214
+ const resizeBrowser = () => {
2215
+ if (record.disposed || !record.root.isConnected) return;
2216
+ // Fixed-size mode: the human's viewer never rearranges the page. The image
2217
+ // is scaled with object-fit instead.
2218
+ if (record.sizing === 'fixed') return;
2219
+ const rect = record.view.getBoundingClientRect();
2220
+ const width = Math.round(rect.width);
2221
+ const height = Math.round(rect.height);
2222
+ if (width < 50 || height < 50) return;
2223
+ const key = `${width}x${height}`;
2224
+ if (record.lastViewport === key) return;
2225
+ record.lastViewport = key;
2226
+ api(`/panes/${record.id}/resize`, { method: 'POST', body: { width, height } })
2227
+ .then((size) => {
2228
+ if (record.disposed) return;
2229
+ if (size && Number.isFinite(size.width)) record.width = size.width;
2230
+ if (size && Number.isFinite(size.height)) record.height = size.height;
2231
+ requestSnapshot(record, 120);
2232
+ })
2233
+ .catch(() => { record.lastViewport = ''; });
2234
+ };
2235
+ record.resizeObserver = new ResizeObserver(() => {
2236
+ if (record.disposed) return;
2237
+ if (record.resizeTimer) clearTimeout(record.resizeTimer);
2238
+ record.resizeTimer = window.setTimeout(() => {
2239
+ record.resizeTimer = 0;
2240
+ resizeBrowser();
2241
+ }, 180);
2242
+ });
2243
+ record.resizeBrowser = resizeBrowser;
2244
+ record.resizeObserver.observe(record.view);
2245
+ requestAnimationFrame(() => {
2246
+ if (!record.disposed && root.isConnected) {
2247
+ resizeBrowser();
2248
+ requestSnapshot(record, 0);
2249
+ }
2250
+ });
2251
+ return root;
2252
+ }
2253
+
2254
+ function updateBrowserSizingChrome(record) {
2255
+ if (!record.sizeButton) return;
2256
+ const fixed = record.sizing === 'fixed';
2257
+ record.sizeButton.setAttribute('aria-pressed', fixed ? 'true' : 'false');
2258
+ record.sizeButton.setAttribute('aria-label', fixed ? 'Unlock browser size' : 'Lock browser size');
2259
+ record.sizeButton.title = fixed
2260
+ ? `Fixed at ${record.width}×${record.height} — your viewer scales the picture, not the page. Click to fit the pane again.`
2261
+ : 'Fixed size: keep the page from resizing when you open menus, resize the viewer, or switch tabs.';
2262
+ }
2263
+
2264
+ async function toggleBrowserSizing(record) {
2265
+ if (record.disposed) return;
2266
+ const next = record.sizing === 'fixed' ? 'fit' : 'fixed';
2267
+ try {
2268
+ const size = await api(`/panes/${record.id}/browser/sizing`, {
2269
+ method: 'POST',
2270
+ body: { mode: next, width: record.width, height: record.height }
2271
+ });
2272
+ if (record.disposed) return;
2273
+ record.sizing = size && size.sizing === 'fixed' ? 'fixed' : 'fit';
2274
+ if (size && Number.isFinite(size.width)) record.width = size.width;
2275
+ if (size && Number.isFinite(size.height)) record.height = size.height;
2276
+ updateBrowserSizingChrome(record);
2277
+ if (record.sizing === 'fit') {
2278
+ record.lastViewport = '';
2279
+ record.resizeBrowser?.();
2280
+ }
2281
+ requestSnapshot(record, 100);
2282
+ showNotice(
2283
+ record.sizing === 'fixed'
2284
+ ? `Browser size locked at ${record.width}×${record.height}.`
2285
+ : 'Browser fits the pane again.',
2286
+ 'info'
2287
+ );
2288
+ } catch (error) {
2289
+ if (!record.disposed) showNotice(error.message || 'Could not change browser sizing.', 'error');
2290
+ }
2291
+ }
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.
2296
+ function requestSnapshot(record, delay = 0) {
2297
+ if (record.disposed || !record.pictures) return;
2298
+ record.pictures.ask(delay);
2299
+ }
2300
+
2301
+ // `fresh`: the answer carries a picture the pane has not shown yet.
2302
+ function applySnapshot(record, snapshot, fresh = Boolean(snapshot && snapshot.image)) {
2303
+ if (!snapshot) return;
2304
+ const width = Number(snapshot.width);
2305
+ const height = Number(snapshot.height);
2306
+ if (Number.isFinite(width) && width > 0) record.width = width;
2307
+ if (Number.isFinite(height) && height > 0) record.height = height;
2308
+ if (snapshot.url) {
2309
+ record.currentUrl = snapshot.url;
2310
+ if (!record.addressDirty && document.activeElement !== record.addressInput && record.addressInput.value !== addressBoxText(snapshot.url)) {
2311
+ record.addressInput.value = addressBoxText(snapshot.url);
2312
+ }
2313
+ }
2314
+ if (snapshot.title) {
2315
+ record.titleEl.textContent = snapshot.title;
2316
+ record.titleEl.title = snapshot.title;
2317
+ record.closeButton.setAttribute('aria-label', `Close browser pane ${snapshot.title}`);
2318
+ }
2319
+ if (fresh && snapshot.image) {
2320
+ record.image.src = `data:image/jpeg;base64,${snapshot.image}`;
2321
+ record.image.alt = snapshot.title ? `Snapshot of ${snapshot.title}` : 'Browser page snapshot';
2322
+ }
2323
+ if (snapshot.sizing) record.sizing = snapshot.sizing === 'fixed' ? 'fixed' : 'fit';
2324
+ updateBrowserSizingChrome(record);
2325
+ if (typeof snapshot.canGoBack === 'boolean') {
2326
+ record.canGoBack = snapshot.canGoBack;
2327
+ record.backButton.disabled = !snapshot.canGoBack;
2328
+ }
2329
+ if (typeof snapshot.canGoForward === 'boolean') {
2330
+ record.canGoForward = snapshot.canGoForward;
2331
+ record.forwardButton.disabled = !snapshot.canGoForward;
2332
+ }
2333
+ if (snapshot.dialog && snapshot.dialog.id) {
2334
+ showPageDialog(record, snapshot.dialog);
2335
+ } else if (pageDialogRecordId === record.id) {
2336
+ hidePageDialog();
2337
+ }
2338
+ record.root.classList.remove('is-offline');
2339
+ record.reopenButton.hidden = true;
2340
+ }
2341
+
2342
+ async function onBrowserImageClick(record, event) {
2343
+ if (event.button !== undefined && event.button !== 0) return;
2344
+ if (record.suppressClickUntil && Date.now() < record.suppressClickUntil) return;
2345
+ const rect = record.image.getBoundingClientRect();
2346
+ if (rect.width <= 0 || rect.height <= 0) return;
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;
2351
+ if (!width || !height) return;
2352
+ const scale = Math.min(rect.width / width, rect.height / height);
2353
+ if (!Number.isFinite(scale) || scale <= 0) return;
2354
+ const contentWidth = width * scale;
2355
+ const contentHeight = height * scale;
2356
+ const left = rect.left + (rect.width - contentWidth) / 2;
2357
+ const top = rect.top + (rect.height - contentHeight) / 2;
2358
+ const localX = event.clientX - left;
2359
+ const localY = event.clientY - top;
2360
+ if (localX < 0 || localY < 0 || localX > contentWidth || localY > contentHeight) return;
2361
+ const x = Math.max(0, Math.min(width, Math.round(localX / scale)));
2362
+ const y = Math.max(0, Math.min(height, Math.round(localY / scale)));
2363
+ const updated = await browserAction(record, 'click', { x, y });
2364
+ if (updated && updated.control) showBrowserControl(record, updated.control, { x, y });
2365
+ else if (browserControlRecordId === record.id) hideBrowserControl();
2366
+ }
2367
+
2368
+ function queueBrowserScroll(record, deltaY, deltaX = 0) {
2369
+ const dy = Math.max(-1500, Math.min(1500, Number(deltaY) || 0));
2370
+ const dx = Math.max(-1500, Math.min(1500, Number(deltaX) || 0));
2371
+ if (!dy && !dx) return;
2372
+ record.wheelDelta += dy;
2373
+ record.wheelDeltaX = (record.wheelDeltaX || 0) + dx;
2374
+ if (record.wheelTimer) return;
2375
+ record.wheelTimer = window.setTimeout(() => {
2376
+ record.wheelTimer = 0;
2377
+ const totalY = Math.max(-1500, Math.min(1500, record.wheelDelta));
2378
+ const totalX = Math.max(-1500, Math.min(1500, record.wheelDeltaX || 0));
2379
+ record.wheelDelta = 0;
2380
+ record.wheelDeltaX = 0;
2381
+ if ((totalY || totalX) && !record.disposed) {
2382
+ void browserAction(record, 'scroll', { deltaY: totalY, deltaX: totalX, pointer: true });
2383
+ }
2384
+ }, 70);
2385
+ }
2386
+
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.
2391
+ event.preventDefault();
2392
+ queueBrowserScroll(record, event.deltaY, event.deltaX);
2393
+ }
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
+
2403
+ async function browserAction(record, action, extra = {}) {
2404
+ if (record.disposed) return;
2405
+ try {
2406
+ const updated = await api(`/panes/${record.id}/browser/action`, {
2407
+ method: 'POST',
2408
+ body: { action, ...extra }
2409
+ });
2410
+ if (record.disposed) return;
2411
+ if (updated) {
2412
+ if (updated.url) {
2413
+ record.currentUrl = updated.url;
2414
+ if (!record.addressDirty && document.activeElement !== record.addressInput) record.addressInput.value = addressBoxText(updated.url);
2415
+ }
2416
+ if (updated.title) {
2417
+ record.titleEl.textContent = updated.title;
2418
+ record.titleEl.title = updated.title;
2419
+ }
2420
+ }
2421
+ requestSnapshot(record, 220);
2422
+ return updated;
2423
+ } catch (error) {
2424
+ if (!record.disposed) showNotice(error.message || 'Browser action failed.', 'error');
2425
+ }
2426
+ }
2427
+
2428
+ function normalizeAddress(value) {
2429
+ const raw = String(value || '').trim();
2430
+ if (!raw) return '';
2431
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) return raw;
2432
+ if (/^(about|data|view-source):/i.test(raw)) return raw;
2433
+ if (/^(localhost|127\.0\.0\.1|\[::1\])(?::|\/|$)/i.test(raw)) return `http://${raw}`;
2434
+ return `https://${raw.replace(/^\/+/, '')}`;
2435
+ }
2436
+
2437
+ async function navigateBrowser(record) {
2438
+ const url = normalizeAddress(record.addressInput.value);
2439
+ if (!url) return;
2440
+ record.addressDirty = false;
2441
+ record.addressInput.value = url;
2442
+ try {
2443
+ const updated = await api(`/panes/${record.id}/url`, { method: 'POST', body: { url } });
2444
+ if (record.disposed) return;
2445
+ if (updated) {
2446
+ record.currentUrl = updated.url || url;
2447
+ if (updated.title) {
2448
+ record.titleEl.textContent = updated.title;
2449
+ record.titleEl.title = updated.title;
2450
+ }
2451
+ }
2452
+ record.addressInput.blur();
2453
+ requestSnapshot(record, 180);
2454
+ } catch (error) {
2455
+ if (!record.disposed) showNotice(error.message || 'Could not open that address.', 'error');
2456
+ }
2457
+ }
2458
+
2459
+ function submitBrowserType(record) {
2460
+ const text = record.typeInput.value;
2461
+ if (!text) return;
2462
+ record.typeInput.value = '';
2463
+ void browserAction(record, 'type', { text });
2464
+ }
2465
+
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 = '';
2472
+ closeSheets();
2473
+ try {
2474
+ let tabId = currentState && currentState.activeTabId;
2475
+ if (!tabId || !currentState.tabs.some((tab) => tab.id === tabId)) {
2476
+ const created = await api('/tabs', { method: 'POST', body: {} });
2477
+ tabId = created.id;
2478
+ }
2479
+ const body = kind === 'terminal' ? { kind, start: false } : { kind };
2480
+ const pane = await api(`/tabs/${tabId}/panes`, { method: 'POST', body });
2481
+ await refresh();
2482
+ if (pane && pane.id) {
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;
2492
+ }
2493
+ logStatus(kind === 'browser' ? 'Browser pane added.' : 'Terminal pane added.');
2494
+ } catch (error) {
2495
+ showNotice(error.message || 'Could not add the pane.', 'error');
2496
+ await refresh();
2497
+ } finally {
2498
+ keyboardSpokenFor = '';
2499
+ keysForNewPane = '';
2500
+ }
2501
+ }
2502
+
2503
+ async function newTab() {
2504
+ closeSheets();
2505
+ try {
2506
+ await api('/tabs', { method: 'POST', body: {} });
2507
+ await refresh();
2508
+ logStatus('New workspace tab created.');
2509
+ } catch (error) {
2510
+ showNotice(error.message || 'Could not create a tab.', 'error');
2511
+ }
2512
+ }
2513
+
2514
+ function requestClose(kind, id, title) {
2515
+ pendingClose = { kind, id, title };
2516
+ els.closeConfirmTitle.textContent = `Close ${title}?`;
2517
+ if (kind === 'tab') {
2518
+ const tab = currentState && currentState.tabs.find((candidate) => candidate.id === id);
2519
+ const count = tab ? tab.panes.length : 0;
2520
+ els.closeConfirmCopy.textContent = count
2521
+ ? `Closing this tab ends ${count === 1 ? 'its pane' : `all ${count} panes`} and any running jobs. This cannot be undone.`
2522
+ : 'Closing this tab cannot be undone.';
2523
+ } else {
2524
+ els.closeConfirmCopy.textContent = 'Closing this pane ends its shell and any running job. This cannot be undone.';
2525
+ }
2526
+ els.closeApprove.textContent = kind === 'tab' ? 'Close tab' : 'Close pane';
2527
+ closeSheets();
2528
+ hideContextMenu();
2529
+ els.closeConfirm.show();
2530
+ syncPanelState();
2531
+ els.closeCancel.focus();
2532
+ }
2533
+
2534
+ async function closeTab(tabId, title) {
2535
+ try {
2536
+ const payload = await api(`/tabs/${tabId}`, { method: 'DELETE' });
2537
+ if (payload && payload.state) applyState(payload.state);
2538
+ else await refresh();
2539
+ tabsDialogSignature = '';
2540
+ if (els.tabsDialog.open) renderTabsDialog();
2541
+ logStatus(`Closed tab ${title}.`);
2542
+ } catch (error) {
2543
+ showNotice(error.message || 'Could not close the tab.', 'error');
2544
+ }
2545
+ }
2546
+
2547
+ async function closePane(paneId, title) {
2548
+ try {
2549
+ const payload = await api(`/panes/${paneId}`, { method: 'DELETE' });
2550
+ if (payload && payload.state) applyState(payload.state);
2551
+ else await refresh();
2552
+ logStatus(`Closed ${title}.`);
2553
+ } catch (error) {
2554
+ showNotice(error.message || 'Could not close the pane.', 'error');
2555
+ }
2556
+ }
2557
+
2558
+ async function activateTab(tabId) {
2559
+ try {
2560
+ const tab = currentState && currentState.tabs.find((candidate) => candidate.id === tabId);
2561
+ const body = { tabId };
2562
+ if (tab && tab.panes[0]) body.paneId = tab.panes[0].id;
2563
+ const next = await api('/active', { method: 'POST', body });
2564
+ closeSheets();
2565
+ applyState(next);
2566
+ logStatus(`Switched to ${tab ? tab.title : 'tab'}.`);
2567
+ } catch (error) {
2568
+ showNotice(error.message || 'Could not switch tabs.', 'error');
2569
+ }
2570
+ }
2571
+
2572
+ function tabsDialogSignatureValue() {
2573
+ if (!currentState) return '';
2574
+ const tabs = currentState.tabs.map((tab) => {
2575
+ const active = tab.id === currentState.activeTabId ? '1' : '0';
2576
+ return `${tab.id}:${tab.title}:${tab.panes.length}:${active}`;
2577
+ });
2578
+ return `${tabs.join('|')}|${currentState.activePaneId || ''}|${JSON.stringify(currentState.limits || null)}`;
2579
+ }
2580
+
2581
+ function renderTabsDialog() {
2582
+ if (!currentState) return;
2583
+ const signature = tabsDialogSignatureValue();
2584
+ if (signature === tabsDialogSignature && els.tabsList.childElementCount) return;
2585
+ tabsDialogSignature = signature;
2586
+ const tabs = currentState.tabs;
2587
+ els.tabsList.replaceChildren();
2588
+ els.tabsEmpty.hidden = tabs.length > 0;
2589
+ const activeId = currentState.activeTabId;
2590
+ const fragment = document.createDocumentFragment();
2591
+ for (const tab of tabs) {
2592
+ const row = document.createElement('li');
2593
+ row.className = `tab-row${tab.id === activeId ? ' is-active' : ''}`;
2594
+
2595
+ const select = document.createElement('button');
2596
+ select.type = 'button';
2597
+ select.className = 'tab-select';
2598
+ select.dataset.tabId = tab.id;
2599
+ select.setAttribute('aria-label', `Switch to ${tab.title}, ${paneCountLabel(tab.panes.length)}`);
2600
+ if (tab.id === activeId) select.setAttribute('aria-current', 'true');
2601
+ const name = document.createElement('span');
2602
+ name.className = 'tab-name';
2603
+ name.textContent = tab.title;
2604
+ select.append(name);
2605
+ if (tab.id === activeId) {
2606
+ const current = document.createElement('span');
2607
+ current.className = 'tab-current';
2608
+ current.textContent = 'Current';
2609
+ select.append(current);
2610
+ }
2611
+ const meta = document.createElement('span');
2612
+ meta.className = 'tab-meta';
2613
+ meta.textContent = paneCountLabel(tab.panes.length);
2614
+ select.append(meta);
2615
+ select.addEventListener('click', () => { void activateTab(tab.id); });
2616
+
2617
+ const close = document.createElement('button');
2618
+ close.type = 'button';
2619
+ close.className = 'tab-close';
2620
+ close.innerHTML = CLOSE_ICON;
2621
+ close.setAttribute('aria-label', `Close tab ${tab.title}`);
2622
+ close.addEventListener('click', () => { requestClose('tab', tab.id, tab.title); });
2623
+
2624
+ row.append(select, close);
2625
+ fragment.append(row);
2626
+ }
2627
+ els.tabsList.append(fragment);
2628
+ updateAddLimits();
2629
+ }
2630
+
2631
+ function updateAddLimits() {
2632
+ if (!currentState) return;
2633
+ const tab = activeTab();
2634
+ const limits = currentState.limits || {};
2635
+ const maxPanes = limits.maxPanesPerTab || 4;
2636
+ const maxTabs = limits.maxTabs || 24;
2637
+ const atPaneLimit = Boolean(tab && tab.panes.length >= maxPanes);
2638
+ const atTabLimit = currentState.tabs.length >= maxTabs;
2639
+ els.tabsAddTerminal.disabled = atPaneLimit;
2640
+ els.tabsAddBrowser.disabled = atPaneLimit;
2641
+ els.menuAddTerminal.disabled = atPaneLimit;
2642
+ els.menuAddBrowser.disabled = atPaneLimit;
2643
+ els.emptyAddTerminal.disabled = atPaneLimit;
2644
+ els.emptyAddBrowser.disabled = atPaneLimit;
2645
+ els.tabsNewTab.disabled = atTabLimit;
2646
+ els.menuNewTab.disabled = atTabLimit;
2647
+ els.emptyNewTab.disabled = atTabLimit;
2648
+ }
2649
+
2650
+ function syncPanelState() {
2651
+ const anyOpen = [els.tabsDialog, els.menuDialog, els.shortcutsDialog, els.closeConfirm]
2652
+ .some((dialog) => dialog && dialog.open);
2653
+ els.app?.classList.toggle('panel-open', anyOpen);
2654
+ }
2655
+
2656
+ function openSheets(dialog) {
2657
+ if (dialog.open) return;
2658
+ closeSheets();
2659
+ hideContextMenu();
2660
+ dialog.show();
2661
+ syncPanelState();
2662
+ dialog.querySelector('button, input, select')?.focus();
2663
+ }
2664
+
2665
+ function closeSheets() {
2666
+ for (const dialog of [els.tabsDialog, els.menuDialog, els.shortcutsDialog, els.closeConfirm]) {
2667
+ if (dialog?.open) dialog.close();
2668
+ }
2669
+ syncPanelState();
2670
+ }
2671
+
2672
+ function openTabsDialog() {
2673
+ tabsDialogSignature = '';
2674
+ if (!currentState) {
2675
+ void refresh();
2676
+ return;
2677
+ }
2678
+ renderTabsDialog();
2679
+ openSheets(els.tabsDialog);
2680
+ }
2681
+
2682
+ function openMenuDialog() {
2683
+ updateAddLimits();
2684
+ openSheets(els.menuDialog);
2685
+ }
2686
+
2687
+ function focusPaneById(paneId, mode = 'type') {
2688
+ const record = records.get(paneId);
2689
+ if (!record) return false;
2690
+ if (record.kind === 'terminal') {
2691
+ if (record.term) {
2692
+ record.term.focus();
2693
+ return true;
2694
+ }
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 };
2698
+ return true;
2699
+ }
2700
+ if (record.kind === 'browser') {
2701
+ const input = mode === 'address' ? record.addressInput : record.typeInput;
2702
+ input.focus();
2703
+ return true;
2704
+ }
2705
+ return false;
2706
+ }
2707
+
2708
+ function focusActive() {
2709
+ const tab = activeTab();
2710
+ if (!tab || !tab.panes.length) {
2711
+ if (!els.emptyState.hidden) els.emptyAddTerminal.focus();
2712
+ else showNotice('Add a terminal or browser to type.', 'info', 2600);
2713
+ return;
2714
+ }
2715
+ const paneId = effectiveActivePaneId(tab);
2716
+ const record = records.get(paneId);
2717
+ if (!record) {
2718
+ // The pane is still being built; ask again once it is there.
2719
+ requestAnimationFrame(() => { if (!overlayOpen()) focusPaneById(paneId); });
2720
+ return;
2721
+ }
2722
+ void setActivePane(paneId);
2723
+ focusPaneById(paneId, record.kind === 'browser' ? 'type' : 'terminal');
2724
+ }
2725
+
2726
+ function triggerBack() {
2727
+ const record = records.get(effectiveActivePaneId());
2728
+ if (record && record.kind === 'browser') void browserAction(record, 'back');
2729
+ }
2730
+
2731
+ function bindEvents() {
2732
+ document.addEventListener('keydown', (event) => {
2733
+ if (!event.altKey || event.ctrlKey || event.metaKey) return;
2734
+ if (document.querySelector('dialog[open]')) return;
2735
+ const target = event.target;
2736
+ if (target && target.closest && target.closest('input:not(.xterm-helper-textarea), textarea:not(.xterm-helper-textarea), [contenteditable="true"]')) return;
2737
+ const tabs = (currentState && currentState.tabs) || [];
2738
+ if (event.key.toLowerCase() === 't') {
2739
+ event.preventDefault();
2740
+ void newTab();
2741
+ return;
2742
+ }
2743
+ if (event.key.toLowerCase() === 'w') {
2744
+ const tab = activeTab();
2745
+ const paneId = effectiveActivePaneId(tab);
2746
+ const record = records.get(paneId);
2747
+ if (record) {
2748
+ event.preventDefault();
2749
+ requestClose('pane', paneId, record.titleEl.textContent || 'pane');
2750
+ }
2751
+ return;
2752
+ }
2753
+ if (event.key === '[' || event.key === ']') {
2754
+ if (!tabs.length) return;
2755
+ const index = Math.max(0, tabs.findIndex((tab) => tab.id === currentState.activeTabId));
2756
+ const next = tabs[(index + (event.key === ']' ? 1 : -1) + tabs.length) % tabs.length];
2757
+ if (next) { event.preventDefault(); void activateTab(next.id); }
2758
+ return;
2759
+ }
2760
+ if (event.key.toLowerCase() === 'm') {
2761
+ const paneId = effectiveActivePaneId();
2762
+ if (!records.get(paneId)) return;
2763
+ event.preventDefault();
2764
+ togglePaneMaximized(paneId);
2765
+ return;
2766
+ }
2767
+ if (/^[1-9]$/.test(event.key) && tabs.length) {
2768
+ const index = event.key === '9' ? tabs.length - 1 : Number(event.key) - 1;
2769
+ if (tabs[index]) { event.preventDefault(); void activateTab(tabs[index].id); }
2770
+ return;
2771
+ }
2772
+ if (event.key === 'ArrowLeft' || event.key === 'ArrowRight' || event.key === 'ArrowUp' || event.key === 'ArrowDown') {
2773
+ const tab = activeTab();
2774
+ if (!tab || !tab.panes.length) return;
2775
+ const step = event.key === 'ArrowLeft' || event.key === 'ArrowUp' ? -1 : 1;
2776
+ if (event.shiftKey) {
2777
+ event.preventDefault();
2778
+ reorderActivePane(step);
2779
+ return;
2780
+ }
2781
+ const at = tab.panes.findIndex((pane) => pane.id === effectiveActivePaneId(tab));
2782
+ const next = tab.panes[(at + step + tab.panes.length) % tab.panes.length];
2783
+ if (next) {
2784
+ event.preventDefault();
2785
+ void setActivePane(next.id);
2786
+ focusPaneById(next.id, next.kind === 'browser' ? 'type' : 'terminal');
2787
+ }
2788
+ }
2789
+ });
2790
+ window.addEventListener('dragover', (event) => {
2791
+ if (Array.from(event.dataTransfer?.types || []).includes('Files')) event.preventDefault();
2792
+ });
2793
+ window.addEventListener('drop', (event) => {
2794
+ if (!event.dataTransfer?.files?.length) return;
2795
+ if (event.target.closest?.('.pane')) return;
2796
+ event.preventDefault();
2797
+ const record = records.get(effectiveActivePaneId());
2798
+ void attachFiles(record, Array.from(event.dataTransfer.files));
2799
+ });
2800
+ els.emptyAddTerminal.addEventListener('click', () => { void addPane('terminal'); });
2801
+ els.emptyAddBrowser.addEventListener('click', () => { void addPane('browser'); });
2802
+ els.emptyNewTab.addEventListener('click', () => { void newTab(); });
2803
+
2804
+ els.contextMenu.addEventListener('click', async (event) => {
2805
+ const action = event.target.closest('[data-context]')?.dataset.context;
2806
+ const record = records.get(contextRecordId);
2807
+ hideContextMenu();
2808
+ if (!action || !record || !record.term) return;
2809
+ try {
2810
+ if (action === 'copy') {
2811
+ if (!record.term.hasSelection()) { showNotice('Select terminal text first.', 'info', 2200); return; }
2812
+ await navigator.clipboard.writeText(record.term.getSelection());
2813
+ showNotice('Selection copied.', 'info', 2200);
2814
+ } else if (action === 'paste') {
2815
+ const text = await navigator.clipboard.readText();
2816
+ if (text) sendTerminalInput(record, text);
2817
+ } else if (action === 'select-all') {
2818
+ record.term.selectAll();
2819
+ } else if (action === 'clear') {
2820
+ record.term.clear();
2821
+ } else if (action === 'reader') {
2822
+ openReaderView();
2823
+ }
2824
+ } catch (error) {
2825
+ showNotice(error.message || 'Clipboard is unavailable in this browser.', 'error');
2826
+ }
2827
+ });
2828
+ els.browserContextMenu.addEventListener('click', async (event) => {
2829
+ const action = event.target.closest('[data-browser-context]')?.dataset.browserContext;
2830
+ const record = records.get(browserContextRecordId);
2831
+ hideContextMenu();
2832
+ if (!action || !record) return;
2833
+ if (action === 'copy-url') {
2834
+ try {
2835
+ await navigator.clipboard.writeText(record.currentUrl || '');
2836
+ showNotice('Page URL copied.', 'info', 2200);
2837
+ } catch (_) {
2838
+ showNotice('Copy blocked by the browser.', 'error');
2839
+ }
2840
+ return;
2841
+ }
2842
+ if (action === 'open') {
2843
+ if (record.currentUrl) window.open(record.currentUrl, '_blank');
2844
+ return;
2845
+ }
2846
+ if (['back', 'forward', 'reload'].includes(action)) void browserAction(record, action);
2847
+ });
2848
+ document.addEventListener('pointerdown', (event) => {
2849
+ if (!els.contextMenu.hidden && !els.contextMenu.contains(event.target)) hideContextMenu();
2850
+ if (!els.browserContextMenu.hidden && !els.browserContextMenu.contains(event.target)) hideContextMenu();
2851
+ }, true);
2852
+ document.addEventListener('keydown', (event) => {
2853
+ if (event.key === 'Escape' && !els.contextMenu.hidden) { event.preventDefault(); hideContextMenu(); }
2854
+ }, true);
2855
+ els.browserControlCancel.addEventListener('click', hideBrowserControl);
2856
+ els.browserControlApply.addEventListener('click', () => { void applyBrowserControl(); });
2857
+ els.browserControlValue.addEventListener('keydown', (event) => {
2858
+ if (event.key === 'Enter') { event.preventDefault(); void applyBrowserControl(); }
2859
+ });
2860
+ els.pageDialogDismiss.addEventListener('click', () => { void answerPageDialog('dismiss'); });
2861
+ els.pageDialogAccept.addEventListener('click', () => { void answerPageDialog('accept'); });
2862
+ els.pageDialogInput.addEventListener('keydown', (event) => {
2863
+ if (event.key === 'Enter') { event.preventDefault(); void answerPageDialog('accept'); }
2864
+ });
2865
+ els.closeCancel.addEventListener('click', () => {
2866
+ pendingClose = null;
2867
+ els.closeConfirm.close();
2868
+ });
2869
+ els.closeConfirm.addEventListener('cancel', () => { pendingClose = null; });
2870
+ els.closeApprove.addEventListener('click', () => {
2871
+ const target = pendingClose;
2872
+ pendingClose = null;
2873
+ els.closeConfirm.close();
2874
+ if (!target) return;
2875
+ if (target.kind === 'tab') void closeTab(target.id, target.title);
2876
+ else void closePane(target.id, target.title);
2877
+ });
2878
+ els.notice.addEventListener('click', async () => {
2879
+ const url = els.notice.dataset.copyUrl;
2880
+ if (!url) return;
2881
+ try {
2882
+ await navigator.clipboard.writeText(url);
2883
+ showNotice('Attachment URL copied', 'info', 2200);
2884
+ } catch (_) {
2885
+ showNotice('Copy blocked by the browser; select the URL instead.', 'error', 3200);
2886
+ }
2887
+ });
2888
+ els.backButton.addEventListener('click', triggerBack);
2889
+ els.tabsButton.addEventListener('click', openTabsDialog);
2890
+ els.keyboardButton.addEventListener('click', focusActive);
2891
+ els.menuButton.addEventListener('click', openMenuDialog);
2892
+
2893
+ els.tabsNewTab.addEventListener('click', () => { void newTab(); });
2894
+ els.tabsAddTerminal.addEventListener('click', () => { void addPane('terminal'); });
2895
+ els.tabsAddBrowser.addEventListener('click', () => { void addPane('browser'); });
2896
+ els.menuNewTab.addEventListener('click', () => { void newTab(); });
2897
+ els.menuAddTerminal.addEventListener('click', () => { void addPane('terminal'); });
2898
+ els.menuAddBrowser.addEventListener('click', () => { void addPane('browser'); });
2899
+ els.menuAttach.addEventListener('click', () => { closeSheets(); els.attachInput.click(); });
2900
+ els.menuReader.addEventListener('click', openReaderView);
2901
+ els.menuFontUp.addEventListener('click', () => adjustPaneFont(1));
2902
+ els.menuFontDown.addEventListener('click', () => adjustPaneFont(-1));
2903
+ els.menuShortcuts.addEventListener('click', () => {
2904
+ openSheets(els.shortcutsDialog);
2905
+ });
2906
+ els.readerRefresh.addEventListener('click', refreshReaderView);
2907
+ els.readerClose.addEventListener('click', closeReaderView);
2908
+ els.readerView.addEventListener('keydown', (event) => {
2909
+ if (event.key === 'Escape') { event.preventDefault(); closeReaderView(); }
2910
+ });
2911
+ els.attachInput.addEventListener('change', () => {
2912
+ const files = Array.from(els.attachInput.files || []);
2913
+ els.attachInput.value = '';
2914
+ void attachFiles(records.get(effectiveActivePaneId()), files);
2915
+ });
2916
+
2917
+ document.querySelectorAll('[data-close]').forEach((button) => {
2918
+ button.addEventListener('click', (event) => {
2919
+ const dialog = button.closest('dialog');
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();
2925
+ });
2926
+ });
2927
+
2928
+ for (const dialog of [els.tabsDialog, els.menuDialog, els.shortcutsDialog, els.closeConfirm]) {
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
+ });
2935
+ }
2936
+ // closeSheets() can dismiss the confirmation programmatically (for example
2937
+ // when a page dialog arrives); clear the pending target on every close.
2938
+ // The close event is queued, so requestClose may have already reopened the
2939
+ // dialog with a new target by the time it fires.
2940
+ els.closeConfirm?.addEventListener('close', () => {
2941
+ if (!els.closeConfirm.open) pendingClose = null;
2942
+ });
2943
+ // Capture-phase: the docks are non-modal, so focus can sit in an xterm that
2944
+ // consumes Escape before a bubble listener would ever see it.
2945
+ document.addEventListener('keydown', (event) => {
2946
+ if (event.key !== 'Escape') return;
2947
+ // Check the sheet list directly: this runs on every Escape in a TUI, and a
2948
+ // document-wide dialog query would also match non-sheet overlays.
2949
+ const anySheet = [els.tabsDialog, els.menuDialog, els.shortcutsDialog, els.closeConfirm]
2950
+ .some((dialog) => dialog && dialog.open);
2951
+ if (!anySheet) return;
2952
+ // A pane owns its keys. Escape goes to vim/less/the page; the dock has a
2953
+ // visible close control because it is not modal.
2954
+ if (event.target instanceof Element && event.target.closest('.pane')) return;
2955
+ event.preventDefault();
2956
+ event.stopPropagation();
2957
+ keyboardReturns = true;
2958
+ closeSheets();
2959
+ }, true);
2960
+
2961
+ for (const dialog of [els.tabsDialog, els.menuDialog]) {
2962
+ dialog.addEventListener('click', (event) => {
2963
+ if (event.target !== dialog) return;
2964
+ keyboardReturns = true;
2965
+ dialog.close();
2966
+ });
2967
+ }
2968
+
2969
+ const onMotionPreference = () => {
2970
+ for (const record of records.values()) {
2971
+ if (record.term) record.term.options.cursorBlink = !reducedMotion.matches;
2972
+ }
2973
+ };
2974
+ if (typeof reducedMotion.addEventListener === 'function') {
2975
+ reducedMotion.addEventListener('change', onMotionPreference);
2976
+ }
2977
+ }
2978
+
2979
+ let statePollTimer = 0;
2980
+
2981
+ function startStatePolling() {
2982
+ if (statePollTimer) clearInterval(statePollTimer);
2983
+ statePollTimer = window.setInterval(() => {
2984
+ if (!document.hidden) void refresh();
2985
+ }, STATE_POLL_MS);
2986
+ document.addEventListener('visibilitychange', () => {
2987
+ if (!document.hidden) void refresh();
2988
+ });
2989
+ }
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
+
3059
+ async function bootstrap() {
3060
+ if (booting) return;
3061
+ booting = true;
3062
+ els.emptyTitle.textContent = 'Connecting to the workspace';
3063
+ els.emptyCopy.textContent = 'Reading tabs and panes.';
3064
+ els.emptyActions.hidden = true;
3065
+ const payload = await fetchBootstrap();
3066
+ if (!payload) {
3067
+ ownerKey = '';
3068
+ booting = false;
3069
+ els.emptyTitle.textContent = 'Workspace unavailable';
3070
+ els.emptyCopy.textContent = 'Waiting for the local server. Retrying.';
3071
+ els.emptyActions.hidden = true;
3072
+ showNotice(lastBootstrapError || 'Could not reach the workspace. Retrying.', 'error', 0);
3073
+ window.setTimeout(() => { void bootstrap(); }, 1800);
3074
+ return;
3075
+ }
3076
+ adoptBootstrap(payload);
3077
+ clearTimeout(noticeTimer);
3078
+ els.notice.hidden = true;
3079
+ logStatus('Workspace ready.');
3080
+ booting = false;
3081
+ startStatePolling();
3082
+ }
3083
+
3084
+ window.__panes = {
3085
+ refresh: () => refresh(),
3086
+ state: () => currentState,
3087
+ dimensions: (paneId) => {
3088
+ const record = records.get(paneId || effectiveActivePaneId());
3089
+ return record && record.term ? { cols: record.term.cols, rows: record.term.rows } : null;
3090
+ },
3091
+ selectAll: (paneId) => {
3092
+ const record = records.get(paneId || effectiveActivePaneId());
3093
+ if (record && record.term) record.term.selectAll();
3094
+ },
3095
+ selection: (paneId) => {
3096
+ const record = records.get(paneId || effectiveActivePaneId());
3097
+ return record && record.term ? record.term.getSelection() : '';
3098
+ },
3099
+ fontSize: (paneId) => {
3100
+ const record = records.get(paneId || effectiveActivePaneId());
3101
+ return record && record.term ? record.term.options.fontSize : null;
3102
+ },
3103
+ render: (next) => {
3104
+ if (next && Array.isArray(next.tabs)) {
3105
+ applyState(next, { force: true });
3106
+ } else if (currentState) {
3107
+ applyState(currentState, { force: true });
3108
+ }
3109
+ return currentState;
3110
+ }
3111
+ };
3112
+
3113
+ Object.defineProperty(window.__panes, '__debug', {
3114
+ value: { histories, cursors, records },
3115
+ enumerable: false
3116
+ });
3117
+
3118
+ const syncKeyboardInset = () => {
3119
+ const viewport = window.visualViewport;
3120
+ const inset = viewport ? Math.max(0, window.innerHeight - viewport.height - viewport.offsetTop) : 0;
3121
+ document.documentElement.style.setProperty('--keyboard-inset', `${Math.round(inset)}px`);
3122
+ document.body.classList.toggle('keyboard-open', inset > 80);
3123
+ };
3124
+ window.visualViewport?.addEventListener('resize', syncKeyboardInset);
3125
+ window.visualViewport?.addEventListener('scroll', syncKeyboardInset);
3126
+ syncKeyboardInset();
3127
+
3128
+ let layoutResizeFrame = 0;
3129
+ window.addEventListener('resize', () => {
3130
+ if (layoutResizeFrame) cancelAnimationFrame(layoutResizeFrame);
3131
+ layoutResizeFrame = requestAnimationFrame(() => {
3132
+ layoutResizeFrame = 0;
3133
+ applyPaneLayout(activeTab());
3134
+ updateHostContext();
3135
+ });
3136
+ });
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
+
3178
+ buildPaneKeybar();
3179
+ bindEvents();
3180
+ void loadAppVersion().then((version) => { if (version) updateDocumentTitle(activeTab()); });
3181
+ void bootstrap();
3182
+
3183
+