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,1715 @@
1
+ import { createViewedWatch, createPictureLoop } from '/browser-picture.mjs';
2
+
3
+ const icons = {
4
+ terminal: 'M4 5l6 7-6 7M13 19h7',
5
+ browser: 'M3 7h18M7 4v3M3 4h18v16H3z',
6
+ agent: 'M8 4h8v4h4v12H4V8h4zM8 12h1m6 0h1M9 16h6',
7
+ tools: 'M4 7h16M4 17h16M8 4v6M16 14v6',
8
+ plus: 'M12 5v14M5 12h14',
9
+ cursor: 'M5 3l14 9-6 .8 3.5 6.2-2.6 1.6-3.5-6.3L5 20z',
10
+ share: 'M12 3v12M8 7l4-4 4 4M5 14v6h14v-6',
11
+ hide: 'M3 12s3.6-6 9-6 9 6 9 6-3.6 6-9 6-9-6-9-6zM12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z',
12
+ chevron: 'M6 9l6 6 6-6',
13
+ expand: 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5',
14
+ collapse: 'M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5',
15
+ settings: 'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM4 12h2m12 0h2M12 4v2m0 12v2M6.3 6.3l1.4 1.4m8.6 8.6 1.4 1.4M17.7 6.3l-1.4 1.4M7.7 16.3l-1.4 1.4',
16
+ refresh: 'M20 12a8 8 0 1 1-2.3-5.7M20 4v5h-5',
17
+ close: 'M6 6l12 12M18 6L6 18',
18
+ clock: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18M12 7v5l3 2',
19
+ search: 'M10 4a6 6 0 1 0 0 12 6 6 0 0 0 0-12zM15 15l5 5',
20
+ mic: 'M12 4a3 3 0 0 0-3 3v4a3 3 0 0 0 6 0V7a3 3 0 0 0-3-3zM5 11a7 7 0 0 0 14 0M12 18v3M8 21h8',
21
+ download: 'M12 4v10M8 10l4 4 4-4M4 19h16',
22
+ clipboard: 'M8 5h8v14H8zM9 5V3h6v2',
23
+ copy: 'M8 8h10v12H8zM6 16H4V4h10v2',
24
+ select: 'M4 4h6M4 10h4M4 16h6M14 4h6M16 10h4M14 16h6',
25
+ snippets: 'M5 4h14v16H5zM8 8h8M8 12h8M8 16h5',
26
+ wake: 'M12 2v3M12 19v3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M2 12h3M19 12h3M4.9 19.1 7 17M17 7l2.1-2.1M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8z',
27
+ fullscreen: 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5',
28
+ lock: 'M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3',
29
+ sync: 'M4 12a8 8 0 0 1 14-5M20 12a8 8 0 0 1-14 5M18 3v4h-4M6 21v-4h4',
30
+ dot: 'M12 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4z',
31
+ session: 'M4 5h16v14H4zM8 5v14M12 9h4M12 13h4',
32
+ edit: 'M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z',
33
+ split: 'M4 4h16v16H4zM12 4v16M8 8h1m-1 4h1m-1 4h1'
34
+ };
35
+ const icon = (name) => '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="' + icons[name] + '"/></svg>';
36
+ const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[character]));
37
+
38
+ const TOOL_META = {
39
+ Recent: { icon: 'clock', desc: 'Reopen a recent command' },
40
+ Search: { icon: 'search', desc: 'Search scrollback' },
41
+ Voice: { icon: 'mic', desc: 'Dictate into the terminal' },
42
+ Export: { icon: 'download', desc: 'Save terminal output' },
43
+ Paste: { icon: 'clipboard', desc: 'Paste from the clipboard' },
44
+ Copy: { icon: 'copy', desc: 'Copy the selection' },
45
+ 'Select all': { icon: 'select', desc: 'Select the scrollback' },
46
+ Snippets: { icon: 'snippets', desc: 'Insert a saved command' },
47
+ Wake: { icon: 'wake', desc: 'Keep the screen awake' },
48
+ Fullscreen: { icon: 'fullscreen', desc: 'Use the whole screen' },
49
+ Lock: { icon: 'lock', desc: 'Lock this session' },
50
+ Sync: { icon: 'sync', desc: 'Export settings with a sync token' },
51
+ Split: { icon: 'split', desc: 'Split the terminal into panes' }
52
+ };
53
+ const ACTION_META = {
54
+ settingsBtn: { icon: 'settings', desc: 'Terminal style, theme, and voice' },
55
+ reconnectBtn: { icon: 'refresh', desc: 'Reconnect the shell' },
56
+ closeBtn: { icon: 'close', desc: 'End this terminal session', danger: true }
57
+ };
58
+
59
+ export async function init(T1) {
60
+ const body = document.body;
61
+ const shell = document.querySelector('.app-shell');
62
+ const header = document.querySelector('.terminal-header');
63
+ body.classList.add('workspace');
64
+
65
+ const sidebar = document.createElement('nav');
66
+ sidebar.className = 'workspace-nav';
67
+ sidebar.setAttribute('aria-label', 'Townmouse workspaces');
68
+ sidebar.innerHTML =
69
+ '<div class="workspace-brand"><div class="brand-art"><img class="brand-mascot" src="/brand/townmouse-monocled.webp" alt=""></div><span>Townmouse<small>Agent workspace</small></span></div>' +
70
+ '<button id="workspace-terminal" type="button">' + icon('terminal') + '<span>Terminal</span></button>' +
71
+ '<button id="workspace-browser" type="button">' + icon('browser') + '<span>Browser</span></button>' +
72
+ '<div class="workspace-label">Tabs</div>' +
73
+ '<div id="browser-tabs" role="tablist" aria-label="Browser tabs"></div>' +
74
+ '<button id="new-browser" type="button">' + icon('plus') + '<span>New tab</span></button>' +
75
+ '<div class="workspace-label">Agent</div>' +
76
+ '<button id="agent-browser" type="button">' + icon('agent') + '<span>Agent</span></button>' +
77
+ '<button id="workspace-panes" type="button">' + icon('split') + '<span>Panes</span></button>' +
78
+ '<button id="workspace-attach" type="button">' + icon('plus') + '<span>Attach</span></button>' +
79
+ '<div class="nav-bottom"><button id="workspace-tools" type="button">' + icon('tools') + '<span>Tools</span></button><a class="workspace-credit" href="https://floydslabs.com" target="_blank" rel="noreferrer"><img src="/brand/floydslabs-credit.webp" alt=""><span>Built at Floyd’s Labs</span></a><p class="nav-status" id="workspace-server">Local server</p></div>';
80
+ body.append(sidebar);
81
+ sidebar.querySelectorAll('button').forEach((button) => button.setAttribute('aria-label', button.textContent.trim()));
82
+ sidebar.querySelector('#agent-browser')?.setAttribute('aria-label', 'Agent browser');
83
+ sidebar.querySelector('#workspace-browser')?.setAttribute('aria-label', 'Browser workspace');
84
+ sidebar.querySelector('#workspace-panes')?.setAttribute('aria-label', 'Pane workspace');
85
+ sidebar.querySelector('#workspace-attach')?.setAttribute('aria-label', 'Attach a file to the terminal');
86
+ sidebar.querySelector('#workspace-tools')?.setAttribute('aria-label', 'Tools and settings');
87
+
88
+ // Desktop can trade the labeled menu for a 72px rail, giving the live
89
+ // surfaces the reclaimed width. The choice survives reloads.
90
+ const navToggle = document.createElement('button');
91
+ navToggle.type = 'button';
92
+ navToggle.id = 'workspace-nav-toggle';
93
+ navToggle.className = 'workspace-nav-toggle';
94
+ navToggle.innerHTML = icon('chevron') + '<span>Collapse</span>';
95
+ sidebar.prepend(navToggle);
96
+ const LS_NAV = 'townmouse.navCollapsed';
97
+ const LS_BROWSER_CHROME = 'townmouse.browserChrome';
98
+ const setNavCollapsed = (collapsed) => {
99
+ body.classList.toggle('nav-collapsed', collapsed);
100
+ navToggle.setAttribute('aria-expanded', String(!collapsed));
101
+ navToggle.setAttribute('aria-label', collapsed ? 'Expand navigation' : 'Collapse navigation');
102
+ navToggle.querySelector('span').textContent = collapsed ? 'Expand' : 'Collapse';
103
+ try { localStorage.setItem(LS_NAV, collapsed ? '1' : '0'); } catch (_) { /* storage may be blocked */ }
104
+ };
105
+ let navCollapsed = false;
106
+ try { navCollapsed = localStorage.getItem(LS_NAV) === '1'; } catch (_) { /* default expanded */ }
107
+ setNavCollapsed(navCollapsed);
108
+ navToggle.addEventListener('click', () => setNavCollapsed(!body.classList.contains('nav-collapsed')));
109
+
110
+ const browser = document.createElement('section');
111
+ browser.className = 'browser-surface';
112
+ browser.hidden = true;
113
+ browser.setAttribute('aria-label', 'Townmouse browser workspace');
114
+ browser.innerHTML =
115
+ '<div class="browser-tabstrip">' +
116
+ '<div class="browser-tablist" id="browser-tablist" role="tablist" aria-label="Browser tabs"></div>' +
117
+ '<button type="button" id="new-browser-inline" class="browser-icon-button" aria-label="New browser tab" title="New tab">' + icon('plus') + '</button>' +
118
+ '<button type="button" id="browser-share-toggle" class="browser-strip-button" aria-label="Sharing and tab controls" aria-controls="browser-permissions" aria-expanded="false">' + icon('share') + '<span>Share</span></button>' +
119
+ '<button type="button" id="browser-expand" class="browser-icon-button" aria-label="Expand browser view" aria-expanded="false" title="Expand browser view">' + icon('expand') + '</button>' +
120
+ '<button type="button" id="hide-browser-compact" class="browser-strip-button" aria-label="Hide browser view" title="Hide view">' + icon('hide') + '<span>Hide</span></button>' +
121
+ '</div>' +
122
+ '<button type="button" id="browser-chrome-restore" class="browser-chrome-restore" hidden aria-label="Show browser controls">' +
123
+ icon('chevron') + '<span class="browser-chrome-restore-title" id="browser-chrome-restore-title">New tab</span>' +
124
+ '<span class="browser-chrome-restore-hint">Show controls</span>' +
125
+ '</button>' +
126
+ '<header class="browser-heading"><div><span class="browser-eyebrow">Browser workspace</span><h2 id="browser-title">New tab</h2></div><button type="button" id="hide-browser" aria-label="Hide browser view">Hide view</button></header>' +
127
+ '<form id="browser-address">' +
128
+ '<button type="button" id="browser-back" aria-label="Go back" title="Back">‹</button>' +
129
+ '<button type="button" id="browser-forward" aria-label="Go forward" title="Forward">›</button>' +
130
+ '<button type="button" id="browser-reload" aria-label="Reload page" title="Reload">↻</button>' +
131
+ '<input id="browser-url" aria-label="Web or local address" placeholder="Search or enter address" autocomplete="off">' +
132
+ '<button type="button" id="browser-share-bottom" class="browser-strip-button" aria-label="Sharing and tab controls" aria-controls="browser-permissions" aria-expanded="false">' + icon('share') + '<span>Share</span></button>' +
133
+ '<button type="button" id="browser-chrome-toggle" class="browser-strip-button" aria-label="Collapse browser controls" aria-expanded="true" title="Collapse browser controls">' + icon('chevron') + '<span>Collapse</span></button>' +
134
+ '<button type="submit">Go</button>' +
135
+ '</form>' +
136
+ '<div class="browser-permissions" id="browser-permissions">' +
137
+ '<label for="browser-share">Agent access</label>' +
138
+ '<select id="browser-share" aria-label="Agent access"><option value="private">Private</option><option value="view">View only</option><option value="control">Allow control</option></select>' +
139
+ '<button type="button" id="copy-agent">Copy connection</button>' +
140
+ '<button type="button" id="browser-read">Read page</button>' +
141
+ '<button type="button" id="close-browser" aria-label="Close current browser tab">Close tab</button>' +
142
+ '</div>' +
143
+ '<div id="browser-message" role="status">' +
144
+ '<span class="browser-badge" id="browser-kind">Human</span>' +
145
+ '<span class="browser-badge" id="browser-permission">Private</span>' +
146
+ '<strong id="browser-title-compact">New tab</strong>' +
147
+ '<span id="browser-message-text"></span>' +
148
+ '</div>' +
149
+ '<div class="browser-canvas">' +
150
+ '<img id="browser-frame" alt="Live browser page. Click to interact; use the text field below for typing." tabindex="0" hidden>' +
151
+ '<div id="browser-empty"><h3>A place for the web</h3><p>Open documentation, preview a local app,<br>or work alongside your terminal agent.</p></div>' +
152
+ '</div>' +
153
+ '<form id="browser-type"><input aria-label="Text to send to browser" placeholder="Type into the focused page field"><button type="submit">Send</button><button type="button" id="browser-tab" aria-label="Send Tab key">Tab</button><button type="button" id="browser-enter" aria-label="Send Enter key">Enter</button></form>';
154
+ const splitHandle = document.createElement('div');
155
+ splitHandle.className = 'split-handle';
156
+ splitHandle.id = 'split-handle';
157
+ splitHandle.setAttribute('role', 'separator');
158
+ splitHandle.setAttribute('aria-orientation', 'horizontal');
159
+ splitHandle.setAttribute('aria-label', 'Resize terminal and browser');
160
+ splitHandle.setAttribute('aria-valuemin', '30');
161
+ splitHandle.setAttribute('aria-valuemax', '80');
162
+ splitHandle.setAttribute('aria-valuenow', '60');
163
+ splitHandle.tabIndex = 0;
164
+ shell.append(splitHandle);
165
+ shell.append(browser);
166
+
167
+ const drawer = document.createElement('dialog');
168
+ drawer.className = 'workspace-drawer';
169
+ drawer.id = 'workspace-drawer';
170
+ drawer.setAttribute('aria-label', 'Tools and settings');
171
+ drawer.innerHTML =
172
+ '<header><div><small>Townmouse controls</small><h2>Tools &amp; settings</h2></div><button id="drawer-close" type="button">Done</button></header>' +
173
+ '<input id="tool-filter" placeholder="Find a tool" aria-label="Find a tool" autocomplete="off">' +
174
+ '<div class="drawer-groups" id="drawer-groups">' +
175
+ '<section class="drawer-group drawer-group-workspace" data-group="workspace"><h3>Workspace</h3><div class="drawer-list" id="drawer-workspace"></div></section>' +
176
+ '<section class="drawer-group" data-group="session"><h3>Session</h3><div class="drawer-list" id="drawer-session"></div></section>' +
177
+ '<section class="drawer-group" data-group="appearance"><h3>Appearance</h3><div class="drawer-list" id="drawer-appearance"></div></section>' +
178
+ '<section class="drawer-group" data-group="tools"><h3>Terminal tools</h3><div class="drawer-list" id="drawer-tools"></div></section>' +
179
+ '</div>' +
180
+ '<p class="drawer-empty" id="tool-empty" hidden>No matching tools.</p>' +
181
+ '<a class="drawer-credit" href="https://floydslabs.com" target="_blank" rel="noreferrer"><img src="/brand/floydslabs-credit.webp" alt=""><span><small>Built by</small>Floyd’s Labs</span></a>';
182
+ body.append(drawer);
183
+
184
+ const sessionMenu = document.createElement('dialog');
185
+ sessionMenu.className = 'workspace-drawer session-menu';
186
+ sessionMenu.id = 'session-menu';
187
+ sessionMenu.setAttribute('aria-label', 'Terminal sessions');
188
+ sessionMenu.innerHTML =
189
+ '<header><div><small>Terminal sessions</small><h2>Sessions</h2></div><button id="session-menu-close" type="button">Done</button></header>' +
190
+ '<p class="session-menu-count" id="session-menu-count" role="status"></p>' +
191
+ '<div id="session-menu-list" class="drawer-list" role="list" aria-label="Shells"></div>' +
192
+ '<button id="session-menu-new" type="button" class="drawer-row">' + icon('plus') + '<span class="drawer-row-copy" data-desc="Start another shell"><span class="drawer-row-name">New session</span></span></button>';
193
+ body.append(sessionMenu);
194
+
195
+ // One confirmation for every close, from a chip, from the Sessions list or
196
+ // from Tools. It names the shell and says what happens next.
197
+ const closeConfirm = document.createElement('dialog');
198
+ closeConfirm.className = 'workspace-drawer workspace-confirm';
199
+ closeConfirm.id = 'close-confirm';
200
+ closeConfirm.setAttribute('aria-labelledby', 'close-confirm-title');
201
+ closeConfirm.innerHTML =
202
+ '<header><div><small>Session</small><h2 id="close-confirm-title">Close terminal?</h2></div></header>' +
203
+ '<p id="close-confirm-text"></p>' +
204
+ '<div class="confirm-actions"><button id="close-confirm-cancel" type="button">Cancel</button><button id="close-confirm-close" type="button" class="danger">Close terminal</button></div>';
205
+ body.append(closeConfirm);
206
+
207
+ const $ = (id) => document.getElementById(id);
208
+ // One dock, one panel. Opening a panel closes the others so two surfaces
209
+ // never stack in the same reserved strip.
210
+ let dockTrigger = null;
211
+ const closeOtherDocks = (keep) => {
212
+ document.querySelectorAll('dialog.workspace-drawer[open]').forEach((dialog) => {
213
+ if (dialog !== keep) dialog.close();
214
+ });
215
+ // Settings is a div, not a dialog, so the selector above cannot see it.
216
+ // Close it here or Tools/Sessions can stack on top of it in the same dock.
217
+ const settings = document.getElementById('settingsModal');
218
+ if (settings && settings !== keep && settings.classList.contains('open')) {
219
+ settings.classList.remove('open');
220
+ }
221
+ };
222
+ const settingsModal = document.getElementById('settingsModal');
223
+ const terminalActions = document.querySelector('.terminal-actions');
224
+ const toolbar = $('t1toolbar');
225
+
226
+ function makeRow(button, meta) {
227
+ const label = button.textContent.trim();
228
+ button.classList.add('drawer-row');
229
+ if (meta.danger) button.classList.add('drawer-row-danger');
230
+ button.dataset.search = (label + ' ' + (meta.desc || '')).toLowerCase();
231
+ button.setAttribute('aria-label', label + (meta.desc ? '. ' + meta.desc : ''));
232
+ button.innerHTML = icon(meta.icon || 'dot') +
233
+ '<span class="drawer-row-copy" data-desc="' + escapeHtml(meta.desc || '') + '"><span class="drawer-row-name">' + escapeHtml(label) + '</span></span>';
234
+ }
235
+
236
+ if (terminalActions) {
237
+ const settings = terminalActions.querySelector('#settingsBtn');
238
+ const reconnectButton = terminalActions.querySelector('#reconnectBtn');
239
+ const close = terminalActions.querySelector('#closeBtn');
240
+ if (settings) { makeRow(settings, ACTION_META.settingsBtn); $('drawer-appearance').append(settings); }
241
+ if (reconnectButton) { makeRow(reconnectButton, ACTION_META.reconnectBtn); $('drawer-session').append(reconnectButton); }
242
+ if (close) {
243
+ close.textContent = 'Close terminal';
244
+ makeRow(close, ACTION_META.closeBtn);
245
+ $('drawer-session').append(close);
246
+ }
247
+ terminalActions.remove();
248
+ }
249
+
250
+ const newSessionRow = document.createElement('button');
251
+ newSessionRow.type = 'button';
252
+ newSessionRow.id = 'drawer-new-session';
253
+ newSessionRow.className = 'drawer-row';
254
+ newSessionRow.dataset.search = 'new session start another shell';
255
+ newSessionRow.setAttribute('aria-label', 'New session. Start another shell.');
256
+ newSessionRow.innerHTML = icon('plus') + '<span class="drawer-row-copy"><span class="drawer-row-name">New session</span><span class="drawer-row-desc">Start another shell</span></span>';
257
+ newSessionRow.addEventListener('click', () => {
258
+ // The same guarded action the header's + uses: at the session limit it
259
+ // opens the Sessions list instead of starting one.
260
+ window.__terminalOne?.requestNewSession?.();
261
+ });
262
+ $('drawer-session').prepend(newSessionRow);
263
+
264
+ if (toolbar) {
265
+ const fontGroup = toolbar.querySelector('.t1font-group');
266
+ if (fontGroup) {
267
+ const fontRow = document.createElement('div');
268
+ fontRow.className = 'drawer-row drawer-font-row';
269
+ fontRow.dataset.search = 'text size terminal font size';
270
+ fontRow.innerHTML = '<span class="drawer-row-copy"><span class="drawer-row-name">Text size</span><span class="drawer-row-desc">Terminal font size</span></span>';
271
+ fontRow.append(fontGroup);
272
+ $('drawer-appearance').append(fontRow);
273
+ }
274
+ $('drawer-tools').append(toolbar);
275
+ for (const button of [...toolbar.querySelectorAll(':scope > button')]) {
276
+ const label = button.textContent.trim();
277
+ makeRow(button, TOOL_META[label] || { icon: 'dot' });
278
+ }
279
+ toolbar.classList.add('drawer-list');
280
+ const syncPressed = () => {
281
+ toolbar.querySelectorAll('.drawer-row').forEach((row) => {
282
+ if (row.classList.contains('active')) row.setAttribute('aria-pressed', 'true');
283
+ else row.removeAttribute('aria-pressed');
284
+ });
285
+ };
286
+ syncPressed();
287
+ new MutationObserver(syncPressed).observe(toolbar, { subtree: true, attributes: true, attributeFilter: ['class'] });
288
+ }
289
+
290
+ const readerRow = document.createElement('button');
291
+ readerRow.type = 'button';
292
+ readerRow.id = 'drawer-reader';
293
+ readerRow.textContent = 'Reader view';
294
+ makeRow(readerRow, { icon: 'dot', desc: 'Word-wrapped transcript for long agent output' });
295
+ readerRow.addEventListener('click', () => {
296
+ drawer.close();
297
+ openReaderView();
298
+ });
299
+ $('drawer-tools').append(readerRow);
300
+
301
+ // Phone navigation is four surfaces. Panes and Attach are actions, so they
302
+ // live here as labeled rows instead of competing for a sixth bottom-nav slot.
303
+ for (const [label, desc, iconName, target] of [
304
+ ['Panes', 'Open the four-pane workspace', 'split', 'workspace-panes'],
305
+ ['Attach a file', 'Upload into the terminal', 'plus', 'workspace-attach']
306
+ ]) {
307
+ const row = document.createElement('button');
308
+ row.type = 'button';
309
+ row.className = 'drawer-row drawer-phone-only';
310
+ row.dataset.search = (label + ' ' + desc).toLowerCase();
311
+ row.setAttribute('aria-label', label + '. ' + desc);
312
+ row.innerHTML = icon(iconName) +
313
+ '<span class="drawer-row-copy"><span class="drawer-row-name">' + label + '</span><span class="drawer-row-desc">' + desc + '</span></span>';
314
+ row.addEventListener('click', () => {
315
+ row.closest('dialog')?.close();
316
+ $(target)?.click();
317
+ });
318
+ $('drawer-workspace').append(row);
319
+ }
320
+
321
+ const isNarrow = () => window.matchMedia('(max-width: 699px)').matches;
322
+ const isTouch = () => window.matchMedia('(pointer: coarse)').matches;
323
+ const setMessage = (message) => { const el = $('browser-message-text'); if (el) el.textContent = message; };
324
+ const setAddressPlaceholder = () => {
325
+ $('browser-url').placeholder = isNarrow()
326
+ ? 'Search or address'
327
+ : 'Search or enter address';
328
+ };
329
+ setAddressPlaceholder();
330
+ window.addEventListener('resize', setAddressPlaceholder);
331
+
332
+ function filterDrawer(query) {
333
+ const value = query.trim().toLowerCase();
334
+ let matches = 0;
335
+ drawer.querySelectorAll('[data-search]').forEach((row) => {
336
+ const show = !value || row.dataset.search.includes(value);
337
+ row.hidden = !show;
338
+ if (show) matches += 1;
339
+ });
340
+ drawer.querySelectorAll('.drawer-group').forEach((group) => {
341
+ const rows = [...group.querySelectorAll('[data-search]')];
342
+ group.hidden = rows.length > 0 && rows.every((row) => row.hidden);
343
+ });
344
+ $('tool-empty').hidden = matches > 0 || !value;
345
+ }
346
+
347
+ // ── Sessions: the pill, the list and the confirmation ─────────────────────
348
+ // All three read one thing, the server's list, which the page script keeps
349
+ // and announces as `t1:session-ready` and `t1:sessions-change`. None of them
350
+ // keeps a list of its own. An earlier version did (session names in
351
+ // localStorage), which is how chips for ended shells came to stay.
352
+ const statusWrap = header.querySelector('.statuswrap');
353
+ const sessionApi = () => window.__terminalOne || {};
354
+ const sessionsNow = () => sessionApi().sessions?.() || [];
355
+ const sessionViewNow = () => sessionApi().sessionView?.() || { state: 'connecting', current: null, max: 0, known: false };
356
+
357
+ const sessionPill = document.createElement('button');
358
+ sessionPill.type = 'button';
359
+ sessionPill.className = 'workspace-session-pill';
360
+ sessionPill.id = 'workspace-session-pill';
361
+ sessionPill.setAttribute('aria-haspopup', 'dialog');
362
+ sessionPill.setAttribute('aria-controls', 'session-menu');
363
+ sessionPill.setAttribute('aria-expanded', 'false');
364
+ sessionPill.setAttribute('aria-label', 'Sessions');
365
+ // The label is its own element so a long one is cut with an ellipsis while
366
+ // the chevron that says "this opens a list" stays in view. The folder is a
367
+ // separate span: it is the first thing the header gives up.
368
+ const sessionPillLabel = document.createElement('span');
369
+ sessionPillLabel.className = 'workspace-session-pill-label';
370
+ const sessionPillName = document.createElement('span');
371
+ sessionPillName.className = 'workspace-session-pill-name';
372
+ const sessionPillFolder = document.createElement('span');
373
+ sessionPillFolder.className = 'workspace-session-pill-folder';
374
+ sessionPillLabel.append(sessionPillName, sessionPillFolder);
375
+ sessionPill.append(sessionPillLabel);
376
+ header.insertBefore(sessionPill, statusWrap);
377
+
378
+ const reconnect = document.createElement('button');
379
+ reconnect.type = 'button';
380
+ reconnect.id = 'workspace-reconnect';
381
+ reconnect.className = 'workspace-reconnect';
382
+ reconnect.textContent = 'Reconnect';
383
+ reconnect.hidden = true;
384
+ header.insertBefore(reconnect, statusWrap);
385
+
386
+ const baseName = (value) => String(value || '').split('/').filter(Boolean).pop() || '';
387
+ function ago(from) {
388
+ const ms = from ? Date.now() - from : 0;
389
+ if (!from || ms < 60_000) return 'just now';
390
+ if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ago`;
391
+ if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)}h ago`;
392
+ return `${Math.floor(ms / 86_400_000)}d ago`;
393
+ }
394
+
395
+ // The pill names the shell this window is in and opens the list.
396
+ function renderSessionPill() {
397
+ const view = sessionViewNow();
398
+ const current = view.state === 'live' ? view.current : null;
399
+ const name = current?.name || '';
400
+ const folder = current?.cwd ? baseName(current.cwd) : '';
401
+ sessionPillName.textContent = name || (view.state === 'ended' ? 'Sessions' : 'Shell');
402
+ sessionPillFolder.textContent = name && folder ? ` · ${folder}` : '';
403
+ sessionPill.title = name
404
+ ? `Sessions. Current shell: ${name}${current?.cwd ? ` (${current.cwd})` : ''}`
405
+ : 'Sessions';
406
+ sessionPill.setAttribute('aria-label', name ? `Sessions. Current shell: ${name}` : 'Sessions');
407
+ }
408
+
409
+ function iconButton(name, label, part, run) {
410
+ const button = document.createElement('button');
411
+ button.type = 'button';
412
+ button.className = `session-row-action session-row-${part}`;
413
+ button.dataset.part = part;
414
+ button.setAttribute('aria-label', label);
415
+ button.title = label;
416
+ button.innerHTML = icon(name);
417
+ button.addEventListener('click', run);
418
+ return button;
419
+ }
420
+
421
+ function renderSessionMenu() {
422
+ const list = $('session-menu-list');
423
+ const view = sessionViewNow();
424
+ const sessions = sessionsNow();
425
+ const currentId = view.current?.id || '';
426
+ // A row being renamed keeps its input; its rename redraws the list.
427
+ if (list.querySelector('.session-row.renaming')) return;
428
+ const focusedRow = document.activeElement?.closest?.('.session-row');
429
+ const focusKey = focusedRow
430
+ ? { id: focusedRow.dataset.sessionId, part: document.activeElement.dataset.part || 'main' }
431
+ : null;
432
+ list.innerHTML = '';
433
+ for (const session of sessions) {
434
+ const current = session.id === currentId;
435
+ // The folder by name; the whole path is in the tooltip. A row is narrow.
436
+ const facts = [
437
+ session.createdBy === 'agent' ? 'started by agent' : '',
438
+ session.cwd ? baseName(session.cwd) : '',
439
+ `started ${ago(session.createdAt)}`
440
+ ].filter(Boolean).join(' · ');
441
+ const row = document.createElement('div');
442
+ row.className = 'session-row' + (current ? ' active' : '');
443
+ row.dataset.sessionId = session.id;
444
+ row.setAttribute('role', 'listitem');
445
+ const main = document.createElement('button');
446
+ main.type = 'button';
447
+ main.className = 'drawer-row session-row-main' + (current ? ' active' : '');
448
+ main.dataset.part = 'main';
449
+ if (current) main.setAttribute('aria-current', 'true');
450
+ main.setAttribute('aria-label', `${session.name}. ${current ? 'Current session' : 'Switch to this session'}`);
451
+ if (session.cwd) main.title = session.cwd;
452
+ main.innerHTML = icon('session') + '<span class="drawer-row-copy"><span class="drawer-row-name session-row-name"></span></span>';
453
+ main.querySelector('.session-row-name').textContent = session.name;
454
+ main.querySelector('.drawer-row-copy').dataset.desc = current
455
+ ? (facts ? `Current session · ${facts}` : 'Current session')
456
+ : facts || 'Switch to this session';
457
+ main.addEventListener('click', () => {
458
+ sessionMenu.close();
459
+ sessionApi().switchSession?.(session.id);
460
+ });
461
+ row.append(
462
+ main,
463
+ iconButton('edit', `Rename ${session.name}`, 'rename', () => startRename(row, session)),
464
+ // The list is left open here so the confirmation knows to come back
465
+ // to it afterwards.
466
+ iconButton('close', `Close ${session.name}`, 'close', () => requestClose(session.id))
467
+ );
468
+ list.append(row);
469
+ }
470
+ if (!sessions.length) {
471
+ const empty = document.createElement('p');
472
+ empty.className = 'session-menu-empty';
473
+ empty.textContent = view.state === 'ended'
474
+ ? 'No shell is open. Start one below.'
475
+ : 'No shell is open besides this one.';
476
+ list.append(empty);
477
+ }
478
+ // The limit is stated where the person would hit it.
479
+ const max = view.max || 0;
480
+ const atLimit = Boolean(max && sessions.length >= max);
481
+ $('session-menu-count').textContent = max
482
+ ? (atLimit ? `All ${max} sessions are in use` : `${sessions.length} of ${max} sessions in use`)
483
+ : '';
484
+ $('session-menu-new').disabled = atLimit;
485
+ $('session-menu-new').querySelector('.drawer-row-copy').dataset.desc = atLimit
486
+ ? 'Close a session above to start another'
487
+ : 'Start another shell';
488
+ if (focusKey) {
489
+ const row = list.querySelector(`.session-row[data-session-id="${focusKey.id}"]`);
490
+ const target = row?.querySelector(`[data-part="${focusKey.part}"]`) || list.querySelector('.session-row [data-part="main"]');
491
+ target?.focus({ preventScroll: true });
492
+ }
493
+ }
494
+
495
+ // A name is edited in the row itself: Enter saves, Escape or leaving keeps
496
+ // the old one. The name is kept by the server, so every window sees it.
497
+ function startRename(row, session) {
498
+ if (row.classList.contains('renaming')) return;
499
+ const main = row.querySelector('.session-row-main');
500
+ const name = main.querySelector('.drawer-row-name');
501
+ const copy = main.querySelector('.drawer-row-copy');
502
+ const before = name.textContent;
503
+ const described = copy.dataset.desc;
504
+ const restore = (refocus = false) => {
505
+ row.classList.remove('renaming');
506
+ name.textContent = before;
507
+ copy.dataset.desc = described;
508
+ // After Escape the keyboard goes back to the row's control. After a
509
+ // click elsewhere it stays where the person put it.
510
+ if (refocus && row.isConnected) row.querySelector('.session-row-rename')?.focus({ preventScroll: true });
511
+ };
512
+ row.classList.add('renaming');
513
+ copy.dataset.desc = 'Enter saves · Escape keeps the old name';
514
+ name.textContent = '';
515
+ const input = document.createElement('input');
516
+ input.type = 'text';
517
+ input.className = 'session-row-input';
518
+ input.value = before;
519
+ input.maxLength = 40;
520
+ input.autocomplete = 'off';
521
+ input.spellcheck = false;
522
+ input.setAttribute('aria-label', `New name for ${before}`);
523
+ name.append(input);
524
+ input.focus();
525
+ input.select();
526
+ let settled = false;
527
+ const finish = async (save, refocus = false) => {
528
+ if (settled) return;
529
+ settled = true;
530
+ const wanted = input.value;
531
+ if (!save || wanted.trim() === before) {
532
+ restore(refocus);
533
+ return;
534
+ }
535
+ // The row is let go before the answer so the list the server then
536
+ // broadcasts can redraw it with the new name.
537
+ row.classList.remove('renaming');
538
+ const result = await sessionApi().renameSession?.(session.id, wanted);
539
+ if (!result || !result.ok) {
540
+ T1.toast((result && result.error) || 'That name was not saved.', 'warn');
541
+ restore(true);
542
+ }
543
+ };
544
+ input.addEventListener('keydown', (event) => {
545
+ if (event.key === 'Enter') { event.preventDefault(); void finish(true); }
546
+ else if (event.key === 'Escape') { event.preventDefault(); void finish(false, true); }
547
+ });
548
+ input.addEventListener('blur', () => { void finish(false); });
549
+ }
550
+
551
+ function openSessionMenu() {
552
+ dockTrigger = sessionPill;
553
+ renderSessionMenu();
554
+ // Shown before any other dock is closed. Closing first leaves one layout
555
+ // with no dock, the header widens for it, and the row of chips loses its
556
+ // scroll place (the current chip scrolls out of view) with no resize left
557
+ // for an observer to see.
558
+ if (!sessionMenu.open) sessionMenu.show();
559
+ closeOtherDocks(sessionMenu);
560
+ sessionPill.setAttribute('aria-expanded', 'true');
561
+ const list = $('session-menu-list');
562
+ const start = list.querySelector('.session-row.active [data-part="main"]') ||
563
+ list.querySelector('.session-row [data-part="main"]') ||
564
+ (!$('session-menu-new').disabled ? $('session-menu-new') : $('session-menu-close'));
565
+ start?.focus({ preventScroll: true });
566
+ }
567
+
568
+ // Every close asks first, in the app's own confirmation: it is the one
569
+ // action here that cannot be taken back. It names the shell and says what
570
+ // happens to this window afterwards.
571
+ let closeTarget = null;
572
+ let backToSessions = false;
573
+ function requestClose(id) {
574
+ const target = id || sessionViewNow().current?.id;
575
+ const session = sessionsNow().find((candidate) => candidate.id === target);
576
+ if (!session) return;
577
+ const view = sessionViewNow();
578
+ const current = view.state === 'live' && view.current?.id === session.id;
579
+ const others = sessionsNow().filter((candidate) => candidate.id !== session.id);
580
+ closeTarget = session.id;
581
+ $('close-confirm-title').textContent = `Close “${session.name}”?`;
582
+ $('close-confirm-text').textContent = 'This ends its shell. Anything still running in it stops. ' +
583
+ (!current ? 'You stay in the shell you are viewing.'
584
+ : others.length ? 'This window then moves to another shell.'
585
+ : 'It is the only session, so no shell will be open afterwards.');
586
+ backToSessions = sessionMenu.open;
587
+ dockTrigger = document.activeElement;
588
+ // Shown before the Sessions list is closed, so the dock's space never
589
+ // lapses in between (see openSessionMenu).
590
+ if (!closeConfirm.open) closeConfirm.show();
591
+ closeOtherDocks(closeConfirm);
592
+ $('close-confirm-cancel').focus();
593
+ }
594
+
595
+ function requestNewSession() {
596
+ const view = sessionViewNow();
597
+ const count = sessionsNow().length;
598
+ if (view.known && view.max && count >= view.max) {
599
+ // At the limit, plainly: say so, and open the list where every shell
600
+ // can be closed.
601
+ T1.toast(`All ${view.max} sessions are in use. Close one to start another.`, 'warn');
602
+ openSessionMenu();
603
+ return;
604
+ }
605
+ sessionApi().newSession?.();
606
+ }
607
+
608
+ sessionPill.addEventListener('click', openSessionMenu);
609
+ sessionMenu.addEventListener('close', () => sessionPill.setAttribute('aria-expanded', 'false'));
610
+ $('session-menu-close').onclick = () => sessionMenu.close();
611
+ $('session-menu-new').onclick = () => {
612
+ sessionMenu.close();
613
+ requestNewSession();
614
+ };
615
+ sessionMenu.addEventListener('click', (event) => { if (event.target === sessionMenu) sessionMenu.close(); });
616
+
617
+ $('close-confirm-cancel').onclick = () => closeConfirm.close();
618
+ $('close-confirm-close').onclick = () => {
619
+ const id = closeTarget;
620
+ closeConfirm.close();
621
+ if (id) void sessionApi().closeSession?.(id);
622
+ };
623
+ closeConfirm.addEventListener('click', (event) => { if (event.target === closeConfirm) closeConfirm.close(); });
624
+ closeConfirm.addEventListener('close', () => {
625
+ // Back to the list whether the shell was closed or kept: closing several
626
+ // should not mean reopening the list for each.
627
+ if (!backToSessions) return;
628
+ backToSessions = false;
629
+ openSessionMenu();
630
+ });
631
+
632
+ // The row (features/session-manager.mjs) asks for these two by name.
633
+ Object.assign(window.__terminalOne, { requestNewSession, requestClose });
634
+
635
+ // The title gives way last. When it is short by less than a couple of pixels
636
+ // (the rounding of flex layout) its text is clipped rather than given an
637
+ // ellipsis; an ellipsis means the title really had to shrink.
638
+ const titleText = header.querySelector('.terminal-title > span');
639
+ const settleTitle = () => {
640
+ if (!titleText) return;
641
+ titleText.classList.toggle('title-clip', titleText.scrollWidth - titleText.clientWidth < 2);
642
+ };
643
+ const settleTitleSoon = () => requestAnimationFrame(settleTitle);
644
+
645
+ const renderSessions = () => {
646
+ renderSessionPill();
647
+ if (sessionMenu.open) renderSessionMenu();
648
+ settleTitleSoon();
649
+ };
650
+ for (const name of ['t1:session-ready', 't1:sessions-change']) window.addEventListener(name, renderSessions);
651
+ window.addEventListener('resize', settleTitleSoon);
652
+ // A dock opening or closing changes the header's width without a resize event.
653
+ if (typeof ResizeObserver === 'function') new ResizeObserver(settleTitleSoon).observe(header);
654
+ renderSessions();
655
+
656
+ const statusEl = $('status');
657
+ if (statusEl) {
658
+ // With no shell on purpose the connection itself is fine; there is
659
+ // nothing to reconnect.
660
+ const updateReconnect = () => {
661
+ reconnect.hidden = statusEl.classList.contains('connected') || statusEl.textContent.includes('No shell');
662
+ };
663
+ new MutationObserver(updateReconnect).observe(statusEl, { attributes: true, attributeFilter: ['class'], childList: true, subtree: true });
664
+ updateReconnect();
665
+ }
666
+ reconnect.addEventListener('click', () => $('reconnectBtn')?.click());
667
+
668
+ // Settings focus restoration after the inherited close handler runs.
669
+ if (settingsModal) {
670
+ new MutationObserver(() => {
671
+ if (settingsModal.classList.contains('open')) return;
672
+ setTimeout(() => {
673
+ // Closing Settings to open another dock must not steal that dock's focus.
674
+ if (document.querySelector('dialog.workspace-drawer[open]')) return;
675
+ $('workspace-tools')?.focus();
676
+ }, 0);
677
+ }).observe(settingsModal, { attributes: true, attributeFilter: ['class'] });
678
+ }
679
+
680
+ // ── Split handle and browser expand ────────────────────────────────────────
681
+ const desktopSplitQuery = window.matchMedia('(min-width: 1100px)');
682
+ function splitOrientation() {
683
+ return desktopSplitQuery.matches ? 'vertical' : 'horizontal';
684
+ }
685
+ function splitVariable() {
686
+ return splitOrientation() === 'vertical' ? '--terminal-split' : '--browser-split';
687
+ }
688
+ function currentSplit() {
689
+ const fallback = splitOrientation() === 'vertical' ? 47 : 60;
690
+ const value = parseFloat(getComputedStyle(shell).getPropertyValue(splitVariable()));
691
+ return Number.isFinite(value) ? value : fallback;
692
+ }
693
+ function splitBounds() {
694
+ if (splitOrientation() === 'vertical') {
695
+ const width = shell.getBoundingClientRect().width || 0;
696
+ if (width > 0) {
697
+ const min = Math.max(25, (320 / width) * 100);
698
+ const max = Math.min(75, ((width - 12 - 420) / width) * 100);
699
+ if (max > min) return { min, max };
700
+ }
701
+ }
702
+ return { min: 25, max: 75 };
703
+ }
704
+ function setSplit(value) {
705
+ const bounds = splitBounds();
706
+ const next = Math.max(bounds.min, Math.min(bounds.max, value));
707
+ shell.style.setProperty(splitVariable(), next + '%');
708
+ splitHandle.setAttribute('aria-valuemin', String(Math.round(bounds.min)));
709
+ splitHandle.setAttribute('aria-valuemax', String(Math.round(bounds.max)));
710
+ splitHandle.setAttribute('aria-valuenow', String(Math.round(next)));
711
+ splitHandle.setAttribute('aria-valuetext',
712
+ (splitOrientation() === 'vertical' ? 'Terminal ' : 'Browser ') + Math.round(next) + ' percent');
713
+ }
714
+ function syncSplitOrientation() {
715
+ const orientation = splitOrientation();
716
+ splitHandle.dataset.orientation = orientation;
717
+ splitHandle.setAttribute('aria-orientation', orientation);
718
+ setSplit(currentSplit());
719
+ }
720
+ window.addEventListener('resize', () => {
721
+ if (!browser.hidden) setSplit(currentSplit());
722
+ });
723
+ shell.style.setProperty('--terminal-split', '47%');
724
+ shell.style.setProperty('--browser-split', '60%');
725
+ syncSplitOrientation();
726
+ desktopSplitQuery.addEventListener?.('change', syncSplitOrientation);
727
+ let splitDrag = null;
728
+ splitHandle.addEventListener('pointerdown', (event) => {
729
+ if (event.button !== undefined && event.button !== 0) return;
730
+ const rect = shell.getBoundingClientRect();
731
+ splitDrag = {
732
+ x: event.clientX,
733
+ y: event.clientY,
734
+ split: currentSplit(),
735
+ orientation: splitOrientation(),
736
+ width: rect.width || 1,
737
+ height: rect.height || 1
738
+ };
739
+ splitHandle.setPointerCapture?.(event.pointerId);
740
+ splitHandle.classList.add('split-drag');
741
+ document.body.classList.add('split-dragging');
742
+ event.preventDefault();
743
+ });
744
+ splitHandle.addEventListener('pointermove', (event) => {
745
+ if (!splitDrag) return;
746
+ if (splitDrag.orientation === 'vertical') {
747
+ setSplit(splitDrag.split + ((event.clientX - splitDrag.x) / splitDrag.width) * 100);
748
+ } else {
749
+ setSplit(splitDrag.split - ((event.clientY - splitDrag.y) / splitDrag.height) * 100);
750
+ }
751
+ });
752
+ const endSplit = () => {
753
+ splitDrag = null;
754
+ splitHandle.classList.remove('split-drag');
755
+ document.body.classList.remove('split-dragging');
756
+ };
757
+ splitHandle.addEventListener('pointerup', endSplit);
758
+ splitHandle.addEventListener('pointercancel', endSplit);
759
+ splitHandle.addEventListener('lostpointercapture', endSplit);
760
+ splitHandle.addEventListener('keydown', (event) => {
761
+ const orientation = splitOrientation();
762
+ let delta = 0;
763
+ if (orientation === 'vertical') {
764
+ if (event.key === 'ArrowLeft') delta = -3;
765
+ if (event.key === 'ArrowRight') delta = 3;
766
+ } else {
767
+ if (event.key === 'ArrowUp') delta = -3;
768
+ if (event.key === 'ArrowDown') delta = 3;
769
+ }
770
+ if (event.key === 'Home') delta = 25 - currentSplit();
771
+ if (event.key === 'End') delta = 75 - currentSplit();
772
+ if (!delta) return;
773
+ event.preventDefault();
774
+ setSplit(currentSplit() + delta);
775
+ });
776
+
777
+ $('browser-expand').addEventListener('click', () => {
778
+ const open = body.classList.toggle('browser-max');
779
+ const button = $('browser-expand');
780
+ button.setAttribute('aria-expanded', String(open));
781
+ button.setAttribute('aria-label', open ? 'Collapse browser view' : 'Expand browser view');
782
+ button.title = open ? 'Collapse browser view' : 'Expand browser view';
783
+ button.innerHTML = icon(open ? 'collapse' : 'expand');
784
+ });
785
+
786
+ // ── Browser state and tabs ─────────────────────────────────────────────────
787
+ let key;
788
+ let tabs = [];
789
+ let current = null;
790
+ const permissionLabel = (permission) => permission === 'view' ? 'View only' : permission === 'control' ? 'Control' : 'Private';
791
+
792
+ // The workspace key and the owner capability are minted per server process.
793
+ // A server restart (or a long-lived tab) leaves the page holding a stale key;
794
+ // recover the key from the owner cookie, and reload once if the cookie itself
795
+ // was rotated. Without this, every browser action repeats "Only the owner…".
796
+ let authRecovering = false;
797
+ let authBlocked = false;
798
+ async function fetchWorkspaceKey() {
799
+ try {
800
+ const res = await fetch('/api/browser/bootstrap', {
801
+ headers: { 'Content-Type': 'application/json' }
802
+ });
803
+ if (!res.ok) return null;
804
+ const value = await res.json();
805
+ return value && typeof value.key === 'string' ? value.key : null;
806
+ } catch (_) { return null; }
807
+ }
808
+ const RELOAD_GUARD_KEY = 'townmouse.ownerReloadAt';
809
+ function readReloadGuard() {
810
+ const now = Date.now();
811
+ const valid = (value) => Number.isFinite(value) && value > 0 && value <= now;
812
+ try {
813
+ const stored = Number(sessionStorage.getItem(RELOAD_GUARD_KEY) || 0);
814
+ if (valid(stored)) return stored;
815
+ } catch (_) { /* storage blocked */ }
816
+ // window.name survives a reload when Safari blocks cookies and storage.
817
+ // Reject foreign/future values (a future timestamp would make the guard
818
+ // arithmetic think a reload just happened forever).
819
+ const match = /(?:^|;)townmouseReloadAt=(\d+)(?:;|$)/.exec(window.name || '');
820
+ const fallback = match ? Number(match[1]) : 0;
821
+ return valid(fallback) ? fallback : 0;
822
+ }
823
+ function writeReloadGuard(at) {
824
+ try { sessionStorage.setItem(RELOAD_GUARD_KEY, String(at)); return; } catch (_) { /* storage blocked */ }
825
+ window.name = `townmouseReloadAt=${at}`;
826
+ }
827
+ function queueResumeRequest(request) {
828
+ if (!request || request.method === 'GET' || typeof request.path !== 'string') return;
829
+ try {
830
+ const raw = sessionStorage.getItem('townmouse.resume');
831
+ const prior = raw ? JSON.parse(raw) : null;
832
+ const queue = Array.isArray(prior) ? prior : prior ? [prior] : [];
833
+ queue.push(request);
834
+ sessionStorage.setItem('townmouse.resume', JSON.stringify(queue));
835
+ } catch (_) { /* storage blocked; the reload still recovers the session */ }
836
+ }
837
+ function recoverOwnerSession(request) {
838
+ if (authRecovering) {
839
+ // A GET poll may already own the recovery/reload slot; do not drop a
840
+ // user mutation that failed at the same moment.
841
+ queueResumeRequest(request);
842
+ return;
843
+ }
844
+ authRecovering = true;
845
+ setMessage('Refreshing the owner session…');
846
+ const last = readReloadGuard();
847
+ if (Date.now() - last < 15000) {
848
+ // A reload this soon after the last one did not fix the session. Stop
849
+ // retrying (and stop polling) until the user reloads manually.
850
+ authRecovering = false;
851
+ authBlocked = true;
852
+ setMessage('Owner session expired. Reload the page to reconnect.');
853
+ return;
854
+ }
855
+ // Replay user actions that the stale key refused, so a click is not
856
+ // silently lost. Background polls are not worth replaying; a fresh load
857
+ // fetches state anyway.
858
+ queueResumeRequest(request);
859
+ writeReloadGuard(Date.now());
860
+ location.reload();
861
+ // If a beforeunload handler or a slow navigation keeps this document
862
+ // alive, do not leave recovery latched forever.
863
+ setTimeout(() => { authRecovering = false; }, 5000);
864
+ }
865
+ async function api(path = '', method = 'GET', data, retry = true, signal) {
866
+ // Once the guarded recovery has given up, every poll would otherwise repeat
867
+ // the rejected request (plus a bootstrap fetch) until a manual reload.
868
+ if (authBlocked) throw new Error('Owner session expired. Reload the page to reconnect.');
869
+ const res = await fetch('/api/browser' + path, {
870
+ method,
871
+ headers: { 'Content-Type': 'application/json', 'X-Workspace-Key': key || '' },
872
+ ...(data ? { body: JSON.stringify(data) } : {}),
873
+ ...(signal ? { signal } : {})
874
+ });
875
+ const value = await res.json().catch(() => ({}));
876
+ if (res.ok) return value;
877
+ const message = value.error || `Request failed (${res.status}).`;
878
+ const ownerAuthFailure = res.status === 403 &&
879
+ /^(Workspace access required|Only the owner can|Owner page required|Browser access token required)/.test(message);
880
+ if (ownerAuthFailure && retry) {
881
+ if (path === '/bootstrap') {
882
+ // The page navigation already had its one chance to mint the owner
883
+ // cookie. If bootstrap still denies, a reload cannot fix it (blocked
884
+ // cookies or an offline/service-worker shell) and would loop forever.
885
+ authBlocked = true;
886
+ setMessage('Owner session unavailable. Reload with cookies enabled for this site.');
887
+ throw new Error(message);
888
+ }
889
+ const fresh = await fetchWorkspaceKey();
890
+ if (fresh) {
891
+ key = fresh;
892
+ return api(path, method, data, false);
893
+ }
894
+ recoverOwnerSession({ path, method, data });
895
+ }
896
+ throw new Error(message);
897
+ }
898
+ function safe(fn) {
899
+ return async (event) => {
900
+ try { await fn(event); }
901
+ catch (error) {
902
+ // The 403 that triggered recovery must not overwrite the "refreshing"
903
+ // message with the owner restriction recovery exists to hide.
904
+ if (authBlocked || authRecovering) return;
905
+ setMessage(error.message);
906
+ T1.toast?.(error.message);
907
+ }
908
+ };
909
+ }
910
+
911
+ function updateBrowserState() {
912
+ if (!current) return;
913
+ $('browser-kind').textContent = current.kind === 'agent' ? 'Agent' : 'Human';
914
+ $('browser-permission').textContent = current.kind === 'agent' ? 'Control' : permissionLabel(current.permission);
915
+ $('browser-kind').classList.toggle('agent', current.kind === 'agent');
916
+ }
917
+
918
+ function closeTab(tab) {
919
+ return safe(async () => {
920
+ if (!tab) return;
921
+ const id = tab.id;
922
+ const wasCurrent = current?.id === id;
923
+ await api('/' + id, 'DELETE');
924
+ tabs = tabs.filter((candidate) => candidate.id !== id);
925
+ if (!wasCurrent) { renderTabs(); return; }
926
+ current = null;
927
+ const next = tabs.filter((candidate) => candidate.kind === 'human').at(-1) || tabs.find((candidate) => candidate.kind === 'agent');
928
+ if (next) await show(next); else hide();
929
+ })();
930
+ }
931
+
932
+ function renderTabContainer(container, list) {
933
+ if (!container) return;
934
+ for (const old of container.querySelectorAll('.browser-tab')) {
935
+ if (!list.some((tab) => tab.id === old.dataset.id)) old.remove();
936
+ }
937
+ const blankCount = list.filter((tab) => tab.kind === 'human' && tab.title === 'about:blank').length;
938
+ for (const [index, tab] of list.entries()) {
939
+ let row = [...container.querySelectorAll('.browser-tab')].find((button) => button.dataset.id === tab.id);
940
+ if (!row) {
941
+ row = document.createElement('div');
942
+ row.dataset.id = tab.id;
943
+ row.className = 'browser-tab';
944
+ row.setAttribute('role', 'tab');
945
+ row.innerHTML = icon(tab.kind === 'agent' ? 'agent' : 'browser') +
946
+ '<span class="browser-tab-label"></span>' +
947
+ '<span class="browser-tab-badge"></span>' +
948
+ '<button type="button" class="browser-tab-close" aria-label="Close tab">×</button>';
949
+ row.addEventListener('click', safe(() => show(tab)));
950
+ row.addEventListener('keydown', (event) => {
951
+ if (event.target !== row) return;
952
+ if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); safe(() => show(tab))(event); }
953
+ if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
954
+ event.preventDefault();
955
+ const buttons = [...container.querySelectorAll('.browser-tab')];
956
+ const at = buttons.indexOf(row);
957
+ const next = buttons[(at + (event.key === 'ArrowRight' ? 1 : -1) + buttons.length) % buttons.length];
958
+ next?.focus();
959
+ }
960
+ });
961
+ const close = row.querySelector('.browser-tab-close');
962
+ close.addEventListener('click', (event) => { event.stopPropagation(); closeTab(tab); });
963
+ close.addEventListener('keydown', (event) => {
964
+ if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); event.stopPropagation(); closeTab(tab); }
965
+ });
966
+ container.append(row);
967
+ }
968
+ const blankIndex = list.slice(0, index + 1).filter((candidate) => candidate.kind === 'human' && candidate.title === 'about:blank').length;
969
+ const label = tab.kind === 'agent'
970
+ ? 'Agent browser'
971
+ : (tab.title === 'about:blank'
972
+ ? (blankCount > 1 ? 'New tab ' + blankIndex : 'New tab')
973
+ : tab.title);
974
+ row.querySelector('.browser-tab-label').textContent = label;
975
+ const badge = row.querySelector('.browser-tab-badge');
976
+ badge.textContent = tab.kind === 'agent' ? 'Agent' : 'Human';
977
+ badge.classList.toggle('agent', tab.kind === 'agent');
978
+ row.title = label + (tab.kind === 'agent' ? ', agent browser' : ', human browser tab');
979
+ row.setAttribute('aria-label', label + (tab.kind === 'agent' ? ', agent browser' : ', human browser tab'));
980
+ const selected = tab.id === current?.id;
981
+ row.classList.toggle('selected', selected);
982
+ row.setAttribute('aria-selected', String(selected));
983
+ row.tabIndex = selected ? 0 : -1;
984
+ if (selected) {
985
+ requestAnimationFrame(() => {
986
+ if (container.scrollWidth > container.clientWidth) {
987
+ row.scrollIntoView({ block: 'nearest', inline: 'nearest' });
988
+ }
989
+ });
990
+ }
991
+ }
992
+ }
993
+
994
+ function selectNav(element, selected) {
995
+ element.classList.toggle('selected', selected);
996
+ if (selected) element.setAttribute('aria-current', 'page');
997
+ else element.removeAttribute('aria-current');
998
+ }
999
+
1000
+ function renderTabs() {
1001
+ renderTabContainer($('browser-tabs'), tabs);
1002
+ renderTabContainer($('browser-tablist'), tabs);
1003
+ // A collapsed desktop rail hides the sidebar tab list. Only then does the
1004
+ // browser strip earn its vertical height; one tab needs no switcher.
1005
+ body.classList.toggle('multi-tab', tabs.length > 1);
1006
+ selectNav($('workspace-terminal'), browser.hidden);
1007
+ selectNav($('workspace-browser'), !browser.hidden && current?.kind === 'human');
1008
+ selectNav($('agent-browser'), !browser.hidden && current?.kind === 'agent');
1009
+ updateBrowserState();
1010
+ }
1011
+
1012
+ function hide() {
1013
+ browser.hidden = true;
1014
+ pictures.unseen();
1015
+ body.classList.remove('browser-open', 'browser-max');
1016
+ $('browser-expand').setAttribute('aria-expanded', 'false');
1017
+ $('browser-expand').innerHTML = icon('expand');
1018
+ browser.classList.remove('share-open');
1019
+ setShareExpanded(false);
1020
+ renderTabs();
1021
+ wakeChrome();
1022
+ window.dispatchEvent(new Event('resize'));
1023
+ }
1024
+
1025
+ async function show(tab) {
1026
+ if (document.activeElement && document.activeElement.closest('.terminal-container')) document.activeElement.blur();
1027
+ current = tab;
1028
+ browser.hidden = false;
1029
+ body.classList.add('browser-open');
1030
+ setSplit(currentSplit());
1031
+ browser.classList.remove('share-open');
1032
+ setShareExpanded(false);
1033
+ $('browser-share').value = tab.permission || 'private';
1034
+ $('browser-url').value = tab.url === 'about:blank' ? '' : tab.url;
1035
+ updateBrowserState();
1036
+ renderTabs();
1037
+ wakeChrome();
1038
+ await resizeViewer();
1039
+ await refresh();
1040
+ window.dispatchEvent(new Event('resize'));
1041
+ }
1042
+
1043
+ function setShareExpanded(open) {
1044
+ browser.classList.toggle('share-open', open);
1045
+ for (const id of ['browser-share-toggle', 'browser-share-bottom']) {
1046
+ const button = $(id);
1047
+ if (button) button.setAttribute('aria-expanded', String(open));
1048
+ }
1049
+ }
1050
+ function toggleShare() { setShareExpanded(!browser.classList.contains('share-open')); }
1051
+
1052
+ // Browser chrome is collapsible so the page can use the whole surface. The
1053
+ // collapsed state is remembered; the restore strip names the current page so
1054
+ // a collapsed surface never becomes a mystery.
1055
+ let chromeCollapsed = false;
1056
+ try { chromeCollapsed = localStorage.getItem(LS_BROWSER_CHROME) === 'collapsed'; } catch (_) { /* storage may be blocked */ }
1057
+ function setChromeCollapsed(collapsed, persist = true) {
1058
+ chromeCollapsed = collapsed;
1059
+ browser.classList.toggle('chrome-collapsed', collapsed);
1060
+ const toggle = $('browser-chrome-toggle');
1061
+ const restore = $('browser-chrome-restore');
1062
+ if (toggle) {
1063
+ toggle.setAttribute('aria-expanded', String(!collapsed));
1064
+ toggle.setAttribute('aria-label', collapsed ? 'Show browser controls' : 'Collapse browser controls');
1065
+ toggle.title = collapsed ? 'Show browser controls' : 'Collapse browser controls';
1066
+ }
1067
+ if (restore) restore.hidden = !collapsed;
1068
+ if (collapsed) { browser.classList.remove('share-open'); setShareExpanded(false); }
1069
+ if (persist) {
1070
+ try { localStorage.setItem(LS_BROWSER_CHROME, collapsed ? 'collapsed' : 'expanded'); } catch (_) { /* storage may be blocked */ }
1071
+ }
1072
+ // The canvas changes size without a window resize, so tell the server.
1073
+ window.setTimeout(() => { resizeViewer().catch(() => {}); }, 0);
1074
+ }
1075
+ function updateChromeRestoreTitle(title) {
1076
+ const label = $('browser-chrome-restore-title');
1077
+ if (label) label.textContent = title || 'New tab';
1078
+ }
1079
+
1080
+ async function resizeViewer() {
1081
+ if (!current || browser.hidden) return;
1082
+ const box = browser.querySelector('.browser-canvas');
1083
+ const width = box.clientWidth;
1084
+ const height = box.clientHeight;
1085
+ if (current.viewWidth === width && current.viewHeight === height) return;
1086
+ current.viewWidth = width;
1087
+ current.viewHeight = height;
1088
+ await api('/' + current.id + '/viewport', 'POST', { width, height });
1089
+ }
1090
+ // A docked panel changes the browser column without firing window.resize;
1091
+ // observe the canvas so the server viewport (and screenshot) follows the
1092
+ // visible surface instead of staying at its pre-dock size.
1093
+ const viewerResizeObserver = typeof ResizeObserver === 'function'
1094
+ ? new ResizeObserver(() => {
1095
+ clearTimeout(window.__browserResize);
1096
+ window.__browserResize = setTimeout(() => resizeViewer().catch(() => {}), 250);
1097
+ })
1098
+ : null;
1099
+ if (viewerResizeObserver) {
1100
+ const viewerBox = browser.querySelector('.browser-canvas');
1101
+ if (viewerBox) viewerResizeObserver.observe(viewerBox);
1102
+ }
1103
+ window.addEventListener('resize', () => {
1104
+ clearTimeout(window.__browserResize);
1105
+ window.__browserResize = setTimeout(() => resizeViewer().catch(() => {}), 250);
1106
+ });
1107
+
1108
+ // ── The picture of the page ────────────────────────────────────────────────
1109
+ // One request at a time. While the Browser view can be seen, the request
1110
+ // waits on the server for the next picture (up to SNAPSHOT_WAIT_MS): a change
1111
+ // shows as it happens, and a still page costs one small request per wait and
1112
+ // sends no picture. While the view cannot be seen (the view hidden, another
1113
+ // tab in front, the window minimized, scrolled out of the window), nothing is
1114
+ // asked for until it can be seen again.
1115
+ const SNAPSHOT_WAIT_MS = 500;
1116
+ const SNAPSHOT_RETRY_MS = 60;
1117
+ // After something was done to the page, how long to wait for its picture
1118
+ // before answering; the stream keeps watching after that.
1119
+ const SNAPSHOT_ACTION_WAIT_MS = 150;
1120
+ let pictureOf = null;
1121
+ const pictures = createPictureLoop({
1122
+ waitMs: SNAPSHOT_WAIT_MS,
1123
+ retryMs: SNAPSHOT_RETRY_MS,
1124
+ viewed: () => Boolean(current) && !browser.hidden && viewWatch.viewed(),
1125
+ ready: () => Boolean(current),
1126
+ request: ({ watching, since, waitMs, signal }) => {
1127
+ pictureOf = current.id;
1128
+ return api('/' + current.id + '/snapshot' + (watching ? `?watch=1&since=${since}&wait=${waitMs}` : '?watch=0'), 'GET', undefined, true, signal);
1129
+ },
1130
+ apply: (snapshot, fresh) => {
1131
+ const id = pictureOf;
1132
+ if (current?.id !== id) return;
1133
+ Object.assign(current, snapshot);
1134
+ delete current.image;
1135
+ // Only a new picture is put on screen. While a page prompt is waiting the
1136
+ // last picture stays, instead of a broken one.
1137
+ if (fresh && snapshot.image) $('browser-frame').src = 'data:image/jpeg;base64,' + snapshot.image;
1138
+ const blank = snapshot.url === 'about:blank';
1139
+ $('browser-frame').hidden = blank;
1140
+ $('browser-empty').hidden = !blank;
1141
+ const title = current.kind === 'agent' ? 'Agent browser' : (snapshot.title || 'New tab');
1142
+ $('browser-title').textContent = title;
1143
+ $('browser-title-compact').textContent = title;
1144
+ updateChromeRestoreTitle(title);
1145
+ if (document.activeElement !== $('browser-url')) $('browser-url').value = blank ? '' : snapshot.url;
1146
+ updateBrowserState();
1147
+ renderTabs();
1148
+ },
1149
+ failure: (error) => {
1150
+ const id = pictureOf;
1151
+ if (/no longer exists|404/i.test(error.message || '')) {
1152
+ tabs = tabs.filter((candidate) => candidate.id !== id);
1153
+ if (current && current.id === id) {
1154
+ current = null;
1155
+ hide();
1156
+ } else {
1157
+ renderTabs();
1158
+ }
1159
+ setMessage('Browser tab closed; it was removed from the sidebar.');
1160
+ } else {
1161
+ setMessage(error.message || 'Browser snapshot failed.');
1162
+ }
1163
+ }
1164
+ });
1165
+ const viewWatch = createViewedWatch(browser.querySelector('.browser-canvas'), (viewed) => {
1166
+ if (viewed) pictures.ask(0);
1167
+ else pictures.unseen();
1168
+ });
1169
+
1170
+ // One request now, for a picture of what was just done or just shown.
1171
+ async function refresh() {
1172
+ if (!current || browser.hidden || authBlocked || authRecovering) return;
1173
+ await pictures.refresh(SNAPSHOT_ACTION_WAIT_MS);
1174
+ }
1175
+
1176
+ async function action(name, data = {}) {
1177
+ if (!current) return;
1178
+ await api('/' + current.id + '/action', 'POST', { action: name, ...data });
1179
+ await refresh();
1180
+ }
1181
+
1182
+ const createBrowser = async () => {
1183
+ setMessage('Starting a private browser…');
1184
+ const tab = await api('', 'POST', { kind: 'human' });
1185
+ tabs.push(tab);
1186
+ await show(tab);
1187
+ setMessage('');
1188
+ };
1189
+ const openBrowser = async () => {
1190
+ const human = tabs.filter((tab) => tab.kind === 'human');
1191
+ if (current?.kind === 'human') { await show(current); return; }
1192
+ if (human.length) { await show(human[human.length - 1]); return; }
1193
+ await createBrowser();
1194
+ };
1195
+ const openAgent = async () => {
1196
+ let tab = tabs.find((candidate) => candidate.kind === 'agent');
1197
+ if (!tab) {
1198
+ tab = await api('', 'POST', { kind: 'agent' });
1199
+ tabs.push(tab);
1200
+ }
1201
+ await show(tab);
1202
+ setMessage(isNarrow()
1203
+ ? 'Agent browser keeps running when hidden. Copy its connection to your agent.'
1204
+ : 'The agent browser keeps running when this view is hidden. Copy its connection to your terminal agent.');
1205
+ };
1206
+
1207
+ $('new-browser').onclick = safe(createBrowser);
1208
+ $('new-browser-inline').onclick = safe(createBrowser);
1209
+ $('workspace-browser').onclick = safe(openBrowser);
1210
+ $('agent-browser').onclick = safe(openAgent);
1211
+ $('workspace-panes').onclick = () => {
1212
+ // Keep the main terminal's WebSocket alive; navigating this window away
1213
+ // would leave its shell in the five-minute resume grace and then kill it.
1214
+ const opened = window.open('/panes.html', 'townmouse-panes');
1215
+ if (opened) opened.opener = null;
1216
+ else location.assign('/panes.html');
1217
+ };
1218
+
1219
+ let readerView = null;
1220
+ let readerText = null;
1221
+
1222
+ function refreshReaderView() {
1223
+ if (!readerText) return;
1224
+ const raw = window.__terminalOne?.text?.() || '';
1225
+ const lines = String(raw).replace(/\s+$/, '').split('\n');
1226
+ while (lines.length && !lines[0].trim()) lines.shift();
1227
+ readerText.textContent = lines.join('\n') || 'No terminal text yet.';
1228
+ readerText.scrollTop = 0;
1229
+ }
1230
+
1231
+ function closeReaderView() {
1232
+ if (!readerView) return;
1233
+ readerView.hidden = true;
1234
+ try { document.querySelector('.xterm-helper-textarea')?.focus(); } catch (_) { /* no terminal */ }
1235
+ }
1236
+
1237
+ function openReaderView() {
1238
+ if (!readerView) {
1239
+ readerView = document.createElement('section');
1240
+ readerView.id = 'reader-view';
1241
+ readerView.className = 'reader-view';
1242
+ readerView.hidden = true;
1243
+ readerView.setAttribute('role', 'dialog');
1244
+ readerView.setAttribute('aria-modal', 'true');
1245
+ readerView.setAttribute('aria-labelledby', 'reader-title');
1246
+ readerView.innerHTML =
1247
+ '<header class="reader-header">' +
1248
+ '<div><small>Word-wrapped transcript</small><h2 id="reader-title">Reader</h2></div>' +
1249
+ '<div class="reader-actions">' +
1250
+ '<button type="button" id="reader-refresh">Refresh</button>' +
1251
+ '<button type="button" id="reader-close" aria-label="Close reader">Close</button>' +
1252
+ '</div>' +
1253
+ '</header>' +
1254
+ '<pre class="reader-text" id="reader-text" tabindex="0"></pre>';
1255
+ readerView.querySelector('#reader-refresh').addEventListener('click', refreshReaderView);
1256
+ readerView.querySelector('#reader-close').addEventListener('click', closeReaderView);
1257
+ readerView.addEventListener('keydown', (event) => {
1258
+ if (event.key === 'Escape') { event.preventDefault(); closeReaderView(); }
1259
+ });
1260
+ body.append(readerView);
1261
+ readerText = readerView.querySelector('#reader-text');
1262
+ }
1263
+ readerView.hidden = false;
1264
+ refreshReaderView();
1265
+ readerView.querySelector('#reader-close').focus();
1266
+ }
1267
+
1268
+ let attachmentCardTimer = 0;
1269
+ function copyAttachmentText(value, success) {
1270
+ const fallback = () => {
1271
+ const area = document.createElement('textarea');
1272
+ area.value = value;
1273
+ area.setAttribute('readonly', '');
1274
+ area.style.position = 'fixed';
1275
+ area.style.opacity = '0';
1276
+ body.append(area);
1277
+ area.select();
1278
+ try { document.execCommand('copy'); } catch (_) { /* nothing else to try */ }
1279
+ area.remove();
1280
+ };
1281
+ if (navigator.clipboard?.writeText) {
1282
+ navigator.clipboard.writeText(value).then(() => T1.toast?.(success), () => { fallback(); T1.toast?.(success); });
1283
+ } else {
1284
+ fallback();
1285
+ T1.toast?.(success);
1286
+ }
1287
+ }
1288
+
1289
+ function showAttachmentCard(attachment, file) {
1290
+ let card = document.getElementById('attachment-card');
1291
+ if (!card) {
1292
+ card = document.createElement('aside');
1293
+ card.id = 'attachment-card';
1294
+ card.className = 'attachment-card';
1295
+ card.setAttribute('role', 'status');
1296
+ card.setAttribute('aria-live', 'polite');
1297
+ card.hidden = true;
1298
+ card.innerHTML =
1299
+ '<div class="attachment-card-head">' +
1300
+ '<span class="attachment-card-name"></span>' +
1301
+ '<button type="button" class="attachment-card-close" aria-label="Dismiss attachment">×</button>' +
1302
+ '</div>' +
1303
+ '<div class="attachment-card-row"><span>Path</span><code data-field="path"></code></div>' +
1304
+ '<div class="attachment-card-row"><span>URL</span><code data-field="url"></code></div>' +
1305
+ '<div class="attachment-card-actions">' +
1306
+ '<button type="button" data-attachment-action="copy-path">Copy path</button>' +
1307
+ '<button type="button" data-attachment-action="copy-url">Copy URL</button>' +
1308
+ '<button type="button" data-attachment-action="open-url">Open URL</button>' +
1309
+ '</div>';
1310
+ card.addEventListener('click', (event) => {
1311
+ const action = event.target.closest('[data-attachment-action]')?.dataset.attachmentAction;
1312
+ if (event.target.closest('.attachment-card-close')) {
1313
+ card.hidden = true;
1314
+ return;
1315
+ }
1316
+ if (action === 'copy-path') copyAttachmentText(card.dataset.path || '', 'Attachment path copied');
1317
+ if (action === 'copy-url') copyAttachmentText(card.dataset.url || '', 'Attachment URL copied');
1318
+ if (action === 'open-url' && card.dataset.url) window.open(card.dataset.url, '_blank', 'noopener');
1319
+ });
1320
+ // In-flow inside the shell: the card reserves height and pushes the
1321
+ // terminal instead of covering the top of the live surface.
1322
+ const shell = document.querySelector('.app-shell');
1323
+ const terminalContainer = shell?.querySelector('.terminal-container');
1324
+ if (shell && terminalContainer) shell.insertBefore(card, terminalContainer);
1325
+ else body.append(card);
1326
+ }
1327
+ card.dataset.path = attachment.path || '';
1328
+ card.dataset.url = attachment.url || '';
1329
+ card.querySelector('.attachment-card-name').textContent = `Attached ${file.name || 'file'}`;
1330
+ card.querySelector('[data-field="path"]').textContent = attachment.path || '';
1331
+ card.querySelector('[data-field="url"]').textContent = attachment.url || '';
1332
+ card.hidden = false;
1333
+ clearTimeout(attachmentCardTimer);
1334
+ attachmentCardTimer = window.setTimeout(() => { card.hidden = true; }, 15000);
1335
+ }
1336
+
1337
+ const attachInput = document.createElement('input');
1338
+ attachInput.type = 'file';
1339
+ attachInput.multiple = true;
1340
+ attachInput.accept = 'image/*,.pdf,.txt,.json,.md,.zip';
1341
+ attachInput.hidden = true;
1342
+ body.append(attachInput);
1343
+ $('workspace-attach').onclick = () => attachInput.click();
1344
+ attachInput.onchange = async () => {
1345
+ const files = Array.from(attachInput.files || []);
1346
+ attachInput.value = '';
1347
+ for (const file of files) {
1348
+ try {
1349
+ const response = await fetch('/api/attachments', {
1350
+ method: 'POST',
1351
+ headers: { 'Content-Type': file.type || 'application/octet-stream', 'X-Filename': encodeURIComponent(file.name || 'attachment') },
1352
+ body: file
1353
+ });
1354
+ const attachment = await response.json();
1355
+ if (!response.ok) throw new Error(attachment.error || `Upload failed (${response.status}).`);
1356
+ const quoted = `'${String(attachment.path).replace(/'/g, `'\\''`)}'`;
1357
+ T1.sendData?.(quoted + ' ');
1358
+ showAttachmentCard(attachment, file);
1359
+ } catch (error) {
1360
+ T1.toast?.(error.message || `Could not attach ${file.name}.`);
1361
+ }
1362
+ }
1363
+ };
1364
+ $('workspace-terminal').onclick = hide;
1365
+ $('hide-browser').onclick = hide;
1366
+ $('hide-browser-compact').onclick = hide;
1367
+ $('browser-share-toggle').onclick = toggleShare;
1368
+ $('browser-share-bottom').onclick = toggleShare;
1369
+ $('browser-chrome-toggle').onclick = () => setChromeCollapsed(true);
1370
+ $('browser-chrome-restore').onclick = () => setChromeCollapsed(false);
1371
+ setChromeCollapsed(chromeCollapsed, false);
1372
+
1373
+ $('workspace-tools').setAttribute('aria-controls', 'workspace-drawer');
1374
+ $('workspace-tools').setAttribute('aria-expanded', 'false');
1375
+ drawer.addEventListener('close', () => $('workspace-tools').setAttribute('aria-expanded', 'false'));
1376
+ $('workspace-tools').onclick = () => {
1377
+ dockTrigger = $('workspace-tools');
1378
+ filterDrawer('');
1379
+ $('tool-filter').value = '';
1380
+ closeOtherDocks(drawer);
1381
+ if (!drawer.open) drawer.show();
1382
+ $('workspace-tools').setAttribute('aria-expanded', 'true');
1383
+ if (!isTouch()) $('tool-filter').focus();
1384
+ };
1385
+ $('drawer-close').onclick = () => drawer.close();
1386
+ drawer.addEventListener('click', (event) => {
1387
+ if (event.target === drawer) { drawer.close(); return; }
1388
+ const row = event.target.closest('.drawer-row');
1389
+ if (!row || row.classList.contains('drawer-font-row') || row.id === 'closeBtn') return;
1390
+ drawer.close();
1391
+ });
1392
+ drawer.addEventListener('click', (event) => {
1393
+ const close = event.target.closest('#closeBtn');
1394
+ if (!close) return;
1395
+ // "Close terminal" closes the shell this window is viewing. It goes
1396
+ // through the same confirmation as a chip's close control, and nowhere
1397
+ // else: a shell never ends without the person answering for it.
1398
+ event.preventDefault();
1399
+ event.stopPropagation();
1400
+ requestClose();
1401
+ }, true);
1402
+ $('tool-filter').oninput = (event) => filterDrawer(event.target.value);
1403
+
1404
+ // Docked panels close with Escape, like any other surface-level affordance,
1405
+ // but the terminal underneath stays live and focused throughout.
1406
+ // Capture-phase: the docks are non-modal, so the terminal keeps focus and
1407
+ // xterm would otherwise consume Escape before this handler sees it.
1408
+ document.addEventListener('keydown', (event) => {
1409
+ if (event.key !== 'Escape') return;
1410
+ const openPanel = [...document.querySelectorAll('dialog.workspace-drawer[open]')].pop();
1411
+ if (!openPanel) return;
1412
+ // The terminal and browser keep their keys. If focus is in a live surface,
1413
+ // Escape belongs to that surface; the dock is closed with its own control.
1414
+ // The rename field in the Sessions list works the same way: its Escape
1415
+ // cancels the rename, and the next Escape closes the list.
1416
+ if (event.target instanceof Element &&
1417
+ event.target.closest('.terminal-container, .browser-canvas, .session-row-input')) return;
1418
+ event.preventDefault();
1419
+ event.stopPropagation();
1420
+ const trigger = dockTrigger;
1421
+ dockTrigger = null;
1422
+ openPanel.close();
1423
+ if (trigger && trigger.isConnected && trigger.offsetParent !== null) trigger.focus();
1424
+ else $('workspace-tools')?.focus();
1425
+ }, true);
1426
+
1427
+ $('browser-address').onsubmit = safe(async (event) => {
1428
+ event.preventDefault();
1429
+ let url = $('browser-url').value.trim();
1430
+ if (!url) return;
1431
+ if (!/^[a-z]+:/i.test(url)) {
1432
+ url = /\s/.test(url) || !/[.:]/.test(url)
1433
+ ? 'https://www.google.com/search?q=' + encodeURIComponent(url)
1434
+ : 'http://' + url;
1435
+ }
1436
+ setMessage('Loading page…');
1437
+ await action('navigate', { url });
1438
+ setMessage('Live browser on the terminal host.');
1439
+ });
1440
+ for (const name of ['back', 'forward', 'reload']) $('browser-' + name).onclick = safe(() => action(name));
1441
+
1442
+ $('browser-share').onchange = safe(async (event) => {
1443
+ Object.assign(current, await api('/' + current.id + '/permission', 'POST', { permission: event.target.value }));
1444
+ updateBrowserState();
1445
+ setMessage(current.permission === 'private'
1446
+ ? 'Sharing revoked. Previous connection tokens no longer work.'
1447
+ : 'Access changed. Copy a new connection for your agent.');
1448
+ });
1449
+ $('browser-read').onclick = safe(async () => {
1450
+ if (!current) return;
1451
+ const data = await api('/' + current.id + '/content');
1452
+ const dialog = document.createElement('dialog');
1453
+ dialog.className = 'workspace-drawer';
1454
+ dialog.setAttribute('aria-label', 'Browser page text');
1455
+ const heading = document.createElement('h2');
1456
+ heading.textContent = data.title;
1457
+ const content = document.createElement('div');
1458
+ content.className = 'browser-reading';
1459
+ content.textContent = data.text;
1460
+ const close = document.createElement('button');
1461
+ close.textContent = 'Done';
1462
+ close.onclick = () => { dialog.close(); dialog.remove(); };
1463
+ // Escape and closeOtherDocks close the dialog without running close.onclick;
1464
+ // remove it on close so one-off docks do not accumulate in the DOM.
1465
+ dialog.addEventListener('close', () => dialog.remove());
1466
+ dialog.append(heading, close, content);
1467
+ body.append(dialog);
1468
+ dockTrigger = document.activeElement;
1469
+ closeOtherDocks(dialog);
1470
+ dialog.show();
1471
+ close.focus();
1472
+ });
1473
+ $('copy-agent').onclick = safe(async () => {
1474
+ const access = await api('/' + current.id + '/access');
1475
+ const connection = JSON.stringify({ ...access, endpoint: location.origin + access.endpoint });
1476
+ try {
1477
+ await navigator.clipboard.writeText(connection);
1478
+ setMessage('Connection copied. Paste it into your terminal agent.');
1479
+ } catch (_) {
1480
+ const dialog = document.createElement('dialog');
1481
+ dialog.className = 'workspace-drawer';
1482
+ dialog.setAttribute('aria-label', 'Agent connection');
1483
+ const label = document.createElement('p');
1484
+ label.textContent = 'Copy this connection into your terminal agent. Keep it private.';
1485
+ const field = document.createElement('textarea');
1486
+ field.value = connection;
1487
+ field.readOnly = true;
1488
+ field.setAttribute('aria-label', 'Agent connection');
1489
+ const done = document.createElement('button');
1490
+ done.textContent = 'Done';
1491
+ done.onclick = () => { dialog.close(); dialog.remove(); };
1492
+ dialog.addEventListener('close', () => dialog.remove());
1493
+ dialog.append(label, field, done);
1494
+ body.append(dialog);
1495
+ dockTrigger = document.activeElement;
1496
+ closeOtherDocks(dialog);
1497
+ dialog.show();
1498
+ field.select();
1499
+ }
1500
+ });
1501
+ $('close-browser').onclick = safe(() => closeTab(current));
1502
+
1503
+ $('browser-frame').onclick = safe(async (event) => {
1504
+ const rect = event.target.getBoundingClientRect();
1505
+ await action('click', {
1506
+ x: (event.clientX - rect.left) * (current.width || 1280) / rect.width,
1507
+ y: (event.clientY - rect.top) * (current.height || 800) / rect.height
1508
+ });
1509
+ });
1510
+ $('browser-frame').onkeydown = safe(async (event) => {
1511
+ if (event.key === 'Tab') return;
1512
+ event.preventDefault();
1513
+ await action('key', { key: event.key === ' ' ? 'Space' : event.key });
1514
+ });
1515
+ $('browser-frame').addEventListener('wheel', safe(async (event) => {
1516
+ event.preventDefault();
1517
+ await action('scroll', { deltaY: event.deltaY, pointer: true });
1518
+ }), { passive: false });
1519
+ $('browser-type').onsubmit = safe(async (event) => {
1520
+ event.preventDefault();
1521
+ const input = event.target.querySelector('input');
1522
+ await action('type', { text: input.value });
1523
+ input.value = '';
1524
+ });
1525
+ $('browser-tab').onclick = safe(() => action('key', { key: 'Tab' }));
1526
+ $('browser-enter').onclick = safe(() => action('key', { key: 'Enter' }));
1527
+
1528
+ let touchStart = null;
1529
+ $('browser-frame').addEventListener('touchstart', (event) => { touchStart = event.touches[0].clientY; }, { passive: true });
1530
+ $('browser-frame').addEventListener('touchend', safe(async (event) => {
1531
+ if (touchStart !== null) {
1532
+ const delta = touchStart - event.changedTouches[0].clientY;
1533
+ touchStart = null;
1534
+ if (Math.abs(delta) > 20) await action('scroll', { deltaY: delta, pointer: true });
1535
+ }
1536
+ }));
1537
+
1538
+ // ── Terminal helper inputs, cursor, reduced motion, keybar ─────────────────
1539
+ const helperTextarea = document.querySelector('.xterm-helper-textarea');
1540
+ if (helperTextarea) helperTextarea.setAttribute('autocomplete', 'off');
1541
+
1542
+ const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
1543
+ const applyTerminalMotion = () => {
1544
+ if (!T1.term) return;
1545
+ try {
1546
+ const term = T1.term;
1547
+ term.options.cursorBlink = !reduceMotion.matches;
1548
+ if (term.options.theme) {
1549
+ // Assign a new object so xterm repaints the cursor with the workspace token.
1550
+ term.options.theme = { ...term.options.theme, cursor: '#d6ad68', cursorAccent: '#14171b' };
1551
+ }
1552
+ } catch (_) { /* the terminal may be disposing during a reconnect */ }
1553
+ };
1554
+ applyTerminalMotion();
1555
+ reduceMotion.addEventListener?.('change', applyTerminalMotion);
1556
+ T1.onTermReady?.(() => { applyTerminalMotion(); setTimeout(applyTerminalMotion, 80); });
1557
+ document.getElementById('themeSelect')?.addEventListener('change', () => setTimeout(applyTerminalMotion, 0));
1558
+
1559
+ const phoneKeybar = $('keybarIphone');
1560
+ if (phoneKeybar && !phoneKeybar.querySelector('.kb-keys-toggle')) {
1561
+ const group = phoneKeybar.querySelector('.kb-group');
1562
+ if (group) {
1563
+ const toggle = document.createElement('button');
1564
+ toggle.type = 'button';
1565
+ toggle.className = 'kb-key kb-keys-toggle';
1566
+ toggle.title = 'More control keys';
1567
+ toggle.setAttribute('aria-label', 'More control keys');
1568
+ toggle.setAttribute('aria-expanded', 'false');
1569
+ toggle.innerHTML = icon('chevron');
1570
+ toggle.addEventListener('click', () => {
1571
+ const open = phoneKeybar.classList.toggle('keys-expanded');
1572
+ toggle.setAttribute('aria-expanded', String(open));
1573
+ });
1574
+ group.append(toggle);
1575
+ }
1576
+ }
1577
+
1578
+ const syncKeyboardInset = () => {
1579
+ const viewport = window.visualViewport;
1580
+ const inset = viewport ? Math.max(0, window.innerHeight - viewport.height - viewport.offsetTop) : 0;
1581
+ document.documentElement.style.setProperty('--keyboard-inset', `${Math.round(inset)}px`);
1582
+ body.classList.toggle('keyboard-open', inset > 80);
1583
+ };
1584
+ window.visualViewport?.addEventListener('resize', syncKeyboardInset);
1585
+ window.visualViewport?.addEventListener('scroll', syncKeyboardInset);
1586
+ syncKeyboardInset();
1587
+
1588
+ $('workspace-server').textContent = location.host ? 'Local server · ' + location.host : 'Local server';
1589
+
1590
+ // The voice feature appends its group after the key bar is built. Move it into
1591
+ // the tablet's second grid row so it keeps a stable slot.
1592
+ const ipadBar = $('keybarIpad');
1593
+ if (ipadBar) {
1594
+ const rows = [...ipadBar.querySelectorAll(':scope > .kb-grid-row')];
1595
+ if (rows.length) {
1596
+ for (const group of [...ipadBar.querySelectorAll(':scope > .kb-group')]) {
1597
+ group.dataset.kb = group.dataset.kb || 'voice';
1598
+ rows[rows.length - 1].append(group);
1599
+ }
1600
+ }
1601
+ }
1602
+
1603
+ try {
1604
+ key = (await api('/bootstrap')).key;
1605
+ let pending = null;
1606
+ try {
1607
+ pending = JSON.parse(sessionStorage.getItem('townmouse.resume') || 'null');
1608
+ sessionStorage.removeItem('townmouse.resume');
1609
+ } catch (_) { /* storage blocked */ }
1610
+ const replay = Array.isArray(pending) ? pending : pending ? [pending] : [];
1611
+ let replayedTab = null;
1612
+ for (const request of replay) {
1613
+ if (!request || typeof request.path !== 'string' || request.path === '/bootstrap') continue;
1614
+ try {
1615
+ const result = await api(request.path, request.method || 'GET', request.data);
1616
+ if (request.method === 'POST' && request.path === '' && result?.id) replayedTab = result;
1617
+ } catch (_) { /* replay is best-effort */ }
1618
+ }
1619
+ tabs = await api();
1620
+ renderTabs();
1621
+ // Re-apply the visible half of a replayed "New tab" click: the mutation
1622
+ // alone created the tab server-side but left the browser surface hidden.
1623
+ if (replayedTab) await show(tabs.find((tab) => tab.id === replayedTab.id) || replayedTab);
1624
+ } catch (error) {
1625
+ if (!authRecovering && !authBlocked) setMessage(error.message);
1626
+ }
1627
+ // The browser view's picture is asked for by `show()` and `refresh()` and
1628
+ // then keeps streaming only while the view can be seen; nothing polls it on
1629
+ // a timer any more.
1630
+ // Reconcile the sidebar with the server so a crashed Chromium or a closed
1631
+ // context cannot leave a permanently stale tab.
1632
+ setInterval(async () => {
1633
+ try {
1634
+ tabs = await api();
1635
+ renderTabs();
1636
+ } catch (_) { /* the snapshot loop reports the outage */ }
1637
+ }, 5000);
1638
+ // The workspace chrome changes the header/keybar heights after the terminal's
1639
+ // first fit. Refit once the new layout has settled.
1640
+ requestAnimationFrame(() => { T1.fit?.(); window.dispatchEvent(new Event('resize')); });
1641
+ setTimeout(() => { T1.fit?.(); }, 200);
1642
+
1643
+ // ── Phone chrome auto-collapse ─────────────────────────────────────────────
1644
+ // The terminal and browser are the product. On a phone, all chrome except the
1645
+ // bottom navigation collapses after seven seconds without a touch; the next
1646
+ // touch brings it back. The first touch on the content only wakes the chrome.
1647
+ const phoneChromeQuery = window.matchMedia('(max-width: 699px)');
1648
+ const CHROME_IDLE_MS = 7000;
1649
+ let chromeIdleTimer = null;
1650
+
1651
+ function chromeIdleBlocked() {
1652
+ if (document.hidden) return true;
1653
+ if (document.querySelector('dialog[open]')) return true;
1654
+ const active = document.activeElement;
1655
+ return !!(active && active.matches('input, textarea, select, [contenteditable="true"]') &&
1656
+ !active.closest('.terminal-container'));
1657
+ }
1658
+ function clearChromeIdleTimer() {
1659
+ if (chromeIdleTimer) { clearTimeout(chromeIdleTimer); chromeIdleTimer = null; }
1660
+ }
1661
+ function refitAfterChromeChange() {
1662
+ requestAnimationFrame(() => { T1.fit?.(); window.dispatchEvent(new Event('resize')); });
1663
+ }
1664
+ function collapseChrome() {
1665
+ if (!phoneChromeQuery.matches || chromeIdleBlocked()) return;
1666
+ body.classList.add('chrome-idle');
1667
+ clearChromeIdleTimer();
1668
+ refitAfterChromeChange();
1669
+ }
1670
+ function wakeChrome() {
1671
+ if (body.classList.contains('chrome-idle')) {
1672
+ body.classList.remove('chrome-idle');
1673
+ refitAfterChromeChange();
1674
+ }
1675
+ scheduleChromeIdle();
1676
+ }
1677
+ function scheduleChromeIdle() {
1678
+ clearChromeIdleTimer();
1679
+ if (!phoneChromeQuery.matches) { body.classList.remove('chrome-idle'); return; }
1680
+ if (chromeIdleBlocked()) {
1681
+ if (!document.hidden) chromeIdleTimer = setTimeout(scheduleChromeIdle, 1000);
1682
+ return;
1683
+ }
1684
+ chromeIdleTimer = setTimeout(() => {
1685
+ chromeIdleTimer = null;
1686
+ if (chromeIdleBlocked()) scheduleChromeIdle();
1687
+ else collapseChrome();
1688
+ }, CHROME_IDLE_MS);
1689
+ }
1690
+
1691
+ document.addEventListener('pointerdown', () => {
1692
+ // Waking the chrome must not eat the gesture: the same tap still reaches
1693
+ // the terminal or browser underneath. A second tap is not required.
1694
+ wakeChrome();
1695
+ }, { capture: true });
1696
+ document.addEventListener('keydown', () => wakeChrome(), { capture: true });
1697
+ document.addEventListener('input', () => wakeChrome(), { capture: true });
1698
+ document.addEventListener('focusin', () => { clearChromeIdleTimer(); scheduleChromeIdle(); });
1699
+ document.addEventListener('focusout', () => setTimeout(scheduleChromeIdle, 0));
1700
+ document.addEventListener('visibilitychange', () => {
1701
+ if (document.hidden) clearChromeIdleTimer();
1702
+ else scheduleChromeIdle();
1703
+ });
1704
+ phoneChromeQuery.addEventListener?.('change', () => {
1705
+ if (!phoneChromeQuery.matches) {
1706
+ body.classList.remove('chrome-idle');
1707
+ clearChromeIdleTimer();
1708
+ } else {
1709
+ scheduleChromeIdle();
1710
+ }
1711
+ });
1712
+ scheduleChromeIdle();
1713
+
1714
+ window.__workspace = { ready: true };
1715
+ }