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