shellpuppet 0.1.0 → 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.
Files changed (101) hide show
  1. package/README.md +210 -33
  2. package/dist/cli/desktopShortcut.d.ts +22 -0
  3. package/dist/cli/desktopShortcut.js +157 -0
  4. package/dist/cli/desktopShortcut.js.map +1 -0
  5. package/dist/cli/index.js +268 -59
  6. package/dist/cli/index.js.map +1 -1
  7. package/dist/client/http.d.ts +74 -3
  8. package/dist/client/http.js +560 -37
  9. package/dist/client/http.js.map +1 -1
  10. package/dist/core/dialogs.d.ts +20 -12
  11. package/dist/core/dialogs.js +31 -19
  12. package/dist/core/dialogs.js.map +1 -1
  13. package/dist/core/manager.d.ts +35 -5
  14. package/dist/core/manager.js +121 -8
  15. package/dist/core/manager.js.map +1 -1
  16. package/dist/core/nativePty.d.ts +9 -5
  17. package/dist/core/nativePty.js +11 -6
  18. package/dist/core/nativePty.js.map +1 -1
  19. package/dist/core/promptDetector.d.ts +37 -3
  20. package/dist/core/promptDetector.js +303 -12
  21. package/dist/core/promptDetector.js.map +1 -1
  22. package/dist/core/reasoning.d.ts +19 -6
  23. package/dist/core/reasoning.js +223 -30
  24. package/dist/core/reasoning.js.map +1 -1
  25. package/dist/core/regexBudget.d.ts +20 -0
  26. package/dist/core/regexBudget.js +25 -1
  27. package/dist/core/regexBudget.js.map +1 -1
  28. package/dist/core/renderer.d.ts +16 -1
  29. package/dist/core/renderer.js +97 -6
  30. package/dist/core/renderer.js.map +1 -1
  31. package/dist/core/selection.d.ts +6 -0
  32. package/dist/core/selection.js +48 -0
  33. package/dist/core/selection.js.map +1 -0
  34. package/dist/core/session.d.ts +267 -13
  35. package/dist/core/session.js +585 -101
  36. package/dist/core/session.js.map +1 -1
  37. package/dist/core/types.d.ts +53 -18
  38. package/dist/core/types.js +30 -6
  39. package/dist/core/types.js.map +1 -1
  40. package/dist/core/waiter.d.ts +12 -4
  41. package/dist/core/waiter.js +63 -70
  42. package/dist/core/waiter.js.map +1 -1
  43. package/dist/core/windowsConsoleHost.d.ts +147 -0
  44. package/dist/core/windowsConsoleHost.js +588 -0
  45. package/dist/core/windowsConsoleHost.js.map +1 -0
  46. package/dist/core/windowsPtyStart.d.ts +100 -29
  47. package/dist/core/windowsPtyStart.js +143 -36
  48. package/dist/core/windowsPtyStart.js.map +1 -1
  49. package/dist/daemon/auth.d.ts +72 -2
  50. package/dist/daemon/auth.js +128 -3
  51. package/dist/daemon/auth.js.map +1 -1
  52. package/dist/daemon/config.d.ts +44 -1
  53. package/dist/daemon/config.js +276 -9
  54. package/dist/daemon/config.js.map +1 -1
  55. package/dist/daemon/folderPicker.d.ts +27 -0
  56. package/dist/daemon/folderPicker.js +115 -0
  57. package/dist/daemon/folderPicker.js.map +1 -0
  58. package/dist/daemon/index.js +20 -19
  59. package/dist/daemon/index.js.map +1 -1
  60. package/dist/daemon/launchProfiles.d.ts +155 -0
  61. package/dist/daemon/launchProfiles.js +554 -0
  62. package/dist/daemon/launchProfiles.js.map +1 -0
  63. package/dist/daemon/liveness.d.ts +1 -1
  64. package/dist/daemon/liveness.js +2 -2
  65. package/dist/daemon/liveness.js.map +1 -1
  66. package/dist/daemon/paths.d.ts +4 -0
  67. package/dist/daemon/paths.js.map +1 -1
  68. package/dist/daemon/restartHold.d.ts +16 -0
  69. package/dist/daemon/restartHold.js +126 -0
  70. package/dist/daemon/restartHold.js.map +1 -0
  71. package/dist/daemon/screenshot.d.ts +58 -1
  72. package/dist/daemon/screenshot.js +172 -26
  73. package/dist/daemon/screenshot.js.map +1 -1
  74. package/dist/daemon/server.d.ts +220 -10
  75. package/dist/daemon/server.js +1975 -205
  76. package/dist/daemon/server.js.map +1 -1
  77. package/dist/daemon/sessionFeed.d.ts +48 -0
  78. package/dist/daemon/sessionFeed.js +101 -0
  79. package/dist/daemon/sessionFeed.js.map +1 -0
  80. package/dist/daemon/viewerLauncher.d.ts +100 -9
  81. package/dist/daemon/viewerLauncher.js +349 -67
  82. package/dist/daemon/viewerLauncher.js.map +1 -1
  83. package/dist/mcp/config.d.ts +7 -14
  84. package/dist/mcp/config.js +10 -21
  85. package/dist/mcp/config.js.map +1 -1
  86. package/dist/mcp/index.js +20 -11
  87. package/dist/mcp/index.js.map +1 -1
  88. package/dist/mcp/tools.d.ts +14 -7
  89. package/dist/mcp/tools.js +161 -60
  90. package/dist/mcp/tools.js.map +1 -1
  91. package/dist/viewer/dashboard-folders.js +20 -0
  92. package/dist/viewer/dashboard-layout.js +52 -0
  93. package/dist/viewer/dashboard.css +67 -0
  94. package/dist/viewer/dashboard.html +44 -0
  95. package/dist/viewer/dashboard.js +1523 -0
  96. package/dist/viewer/icon.ico +0 -0
  97. package/dist/viewer/index.html +12 -7
  98. package/dist/viewer/pane.js +736 -0
  99. package/dist/viewer/viewer.css +18 -7
  100. package/dist/viewer/viewer.js +47 -624
  101. package/package.json +13 -13
@@ -0,0 +1,1523 @@
1
+ /** The dashboard's feed, arrangement, launch controls and human controls. */
2
+ /* global ShellPuppetPane, ShellPuppetDashboardLayout, ShellPuppetDashboardFolders */
3
+ (() => {
4
+ 'use strict';
5
+
6
+ const proof = document.querySelector('meta[name="sp-csrf"]')?.content || '';
7
+ const root = document.getElementById('panes');
8
+ const empty = document.getElementById('empty');
9
+ const error = document.getElementById('error');
10
+ const connection = document.getElementById('connection');
11
+ const attentionCount = document.getElementById('attention-count');
12
+ const shareCount = document.getElementById('share-count');
13
+ const profileSelect = document.getElementById('profile');
14
+ const folderField = document.getElementById('folder-field');
15
+ const folderSelect = document.getElementById('folder');
16
+ const folderFilter = document.getElementById('folder-filter');
17
+ const recentFolders = document.getElementById('recent-folders');
18
+ const boundedFolder = document.getElementById('bounded-folder');
19
+ const anyFolder = document.getElementById('any-folder');
20
+ const folderPath = document.getElementById('folder-path');
21
+ const folderPathOptions = document.getElementById('folder-path-options');
22
+ const browseFolder = document.getElementById('browse-folder');
23
+ const launcher = document.getElementById('launcher');
24
+ const watchOnly = document.getElementById('watch-only');
25
+ const profileProblems = document.getElementById('profile-problems');
26
+ const main = document.createElement('div');
27
+ const strip = document.createElement('div');
28
+ main.id = 'main-pane';
29
+ strip.id = 'strip';
30
+ const panes = new Map();
31
+ const PREF = 'shellpuppet.dashboard';
32
+ const TRACK_PREF = 'shellpuppet.dashboard.tracks';
33
+ const LAUNCH_PREF = 'shellpuppet.dashboard.launches';
34
+ const RECENT_PREF = 'shellpuppet.dashboard.recentFolders';
35
+ const NAME = /^[a-z][a-z0-9-]{0,31}$/;
36
+ let saved = {};
37
+ try { saved = JSON.parse(window.localStorage.getItem(PREF) || '{}') || {}; } catch { /* Preferences are optional. */ }
38
+ let order = Array.isArray(saved.order) ? saved.order.filter((id) => typeof id === 'string') : [];
39
+ let pins = Array.isArray(saved.pins) ? saved.pins.filter((id) => typeof id === 'string') : [];
40
+ let mode = ['auto', 'grid', 'focus'].includes(saved.mode) ? saved.mode : 'auto';
41
+ let autoFit = saved.autoFit !== false;
42
+ const configuredFont = Number(document.querySelector('meta[name="sp-dashboard-font-size"]')?.content);
43
+ let fontSize = Number.isInteger(saved.fontSize) && saved.fontSize >= 8 && saved.fontSize <= 32
44
+ ? saved.fontSize : saved.fontSize === null ? null
45
+ : Number.isInteger(configuredFont) && configuredFont >= 8 && configuredFont <= 32 ? configuredFont : null;
46
+ let autoFitTimer = null;
47
+ let assignmentSettleUntil = 0;
48
+ let assignmentSettleStartedAt = 0;
49
+ if (!window.name) window.name = `shellpuppet-dashboard-${Date.now()}-${Math.random()}`;
50
+ let tracks = { count: 0, focusStrip: null, columns: null, rows: null };
51
+ try {
52
+ const record = JSON.parse(window.sessionStorage.getItem(TRACK_PREF) || 'null');
53
+ if (record?.owner === window.name && Number.isInteger(record.count)) tracks = record;
54
+ } catch { /* Track sizes are optional. */ }
55
+ let activeDivider = null;
56
+ let endActiveDivider = null;
57
+ const focusOpenFits = new Set();
58
+ const incomingFits = new Set();
59
+ let prefix = typeof saved.prefix === 'string' && /^[a-z]$/.test(saved.prefix) ? saved.prefix : 'a';
60
+ let choosingPrefix = false;
61
+ let selected = null;
62
+ let focusId = null;
63
+ let enlarged = null;
64
+ let navigation = false;
65
+ let feed = null;
66
+ let retry = null;
67
+ let profiles = [];
68
+ /** Sessions this page started: profile name and, where used, folder name. */
69
+ let launches = loadLaunches();
70
+ let recent = {};
71
+ try { recent = JSON.parse(window.localStorage.getItem(RECENT_PREF) || '{}') || {}; } catch { recent = {}; }
72
+ /** Panes another window holds, hidden from this grid until that window closes. */
73
+ const popped = new Set();
74
+ /** This document is the pop-out window for one session, or null. */
75
+ const popSelf = popTarget();
76
+ const dismissed = new Set();
77
+ const pendingOpen = new Map();
78
+ const popWatches = new Map();
79
+ const windowToken = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
80
+ window.__dashboardDocumentToken = windowToken;
81
+ const newInstance = () => `i-${[...window.crypto.getRandomValues(new Uint8Array(16))]
82
+ .map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
83
+ let windowInstance = newInstance();
84
+ let registered = false;
85
+ const loadAt = window.performance.timeOrigin + window.performance.now();
86
+ let openedAt = loadAt;
87
+ const screenParams = new URLSearchParams(location.hash.slice(1));
88
+ const windowId = screenParams.get('screen') || windowToken;
89
+ const windowRank = screenParams.has('screen') ? Number(screenParams.get('rank')) || 1000 : 0;
90
+ const screenKey = screenParams.get('key');
91
+ let currentScreenKey = screenKey;
92
+ const windows = new Map();
93
+ const windowPair = (id, instance) => JSON.stringify([id, instance]);
94
+ const ownPair = () => windowPair(windowId, windowInstance);
95
+ const goneWindows = new Map();
96
+ const validWindowId = (id) => typeof id === 'string' && id.length <= 100 &&
97
+ /^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(id);
98
+ const lastSeen = new Map();
99
+ const childWatches = new Map();
100
+ let rosterTimer = null;
101
+ let windowLeft = false;
102
+ let assigned = screenParams.has('screen') ? new Set() : null;
103
+ let screens = [];
104
+ let watchedScreens = null;
105
+ let screenState = 'unavailable';
106
+ let nextFallback = 0;
107
+ let arranging = false;
108
+ let syncingVisibility = false;
109
+ let pendingArrange = false;
110
+ let pendingVisibility = false;
111
+ let followUpFrame = false;
112
+ const diagnostics = window.__dashboardDiagnostics;
113
+ function traceArrange(trigger) {
114
+ if (!diagnostics) return;
115
+ diagnostics.arrangeTriggers.push({ at: Math.round(window.performance.now()), trigger });
116
+ if (diagnostics.arrangeTriggers.length > 20) diagnostics.arrangeTriggers.shift();
117
+ }
118
+ let lastLayout = null;
119
+ let lastStructure = null;
120
+ let lastVisibilityGeometry = null;
121
+ if (popSelf === null) windows.set(ownPair(), { id: windowId, instance: windowInstance, rank: windowRank, openedAt, loadAt, key: screenKey,
122
+ width: window.innerWidth - 12, height: window.innerHeight - 54 });
123
+ let channel = null;
124
+ try { channel = new BroadcastChannel('shellpuppet.dashboard'); } catch { /* This window still tracks a pop-out it opened. */ }
125
+
126
+ function popTarget() {
127
+ const hash = location.hash.startsWith('#') ? location.hash.slice(1) : location.hash;
128
+ const match = /^pop=(.+)$/.exec(hash);
129
+ if (match === null) return null;
130
+ try { return decodeURIComponent(match[1] ?? ''); } catch { return null; }
131
+ }
132
+
133
+ function loadLaunches() {
134
+ let raw;
135
+ try { raw = JSON.parse(window.localStorage.getItem(LAUNCH_PREF) || '{}') || {}; } catch { return {}; }
136
+ if (typeof raw !== 'object' || raw === null) return {};
137
+ const out = {};
138
+ for (const [id, value] of Object.entries(raw)) {
139
+ if (typeof value !== 'object' || value === null || typeof value.profile !== 'string' || !NAME.test(value.profile)) continue;
140
+ const entry = { profile: value.profile };
141
+ if (typeof value.folder === 'string' && value.folder.length > 0 && !/[\\/:]/.test(value.folder) && !Array.from(value.folder).some((char) => char.charCodeAt(0) < 32) && value.folder !== '..') entry.folder = value.folder;
142
+ if (Number.isInteger(value.rootIndex) && value.rootIndex >= 0) entry.rootIndex = value.rootIndex;
143
+ if (typeof value.folderPath === 'string' && value.folderPath !== '') entry.folderPath = value.folderPath;
144
+ out[id] = entry;
145
+ }
146
+ return out;
147
+ }
148
+
149
+ const persist = () => {
150
+ try { window.localStorage.setItem(PREF, JSON.stringify({ mode, order, pins, prefix, autoFit, fontSize })); } catch { /* Layout still works. */ }
151
+ };
152
+ function saveTracks() {
153
+ try { window.sessionStorage.setItem(TRACK_PREF, JSON.stringify({ ...tracks, owner: window.name })); }
154
+ catch { /* The current document still keeps its sizes. */ }
155
+ }
156
+ function resetTracks() {
157
+ endActiveDivider?.();
158
+ tracks = { count: shown().length, focusStrip: null, columns: null, rows: null };
159
+ try { window.sessionStorage.removeItem(TRACK_PREF); } catch { /* The current document still resets. */ }
160
+ applyTracks();
161
+ }
162
+ function applyTracks() {
163
+ root.style.removeProperty('--strip-width');
164
+ root.style.removeProperty('--grid-columns');
165
+ root.style.removeProperty('--grid-rows');
166
+ if (Number.isFinite(tracks.focusStrip)) root.style.setProperty('--strip-width', `${tracks.focusStrip}px`);
167
+ if (Array.isArray(tracks.columns)) root.style.setProperty('--grid-columns', tracks.columns.map((x) => `${x}fr`).join(' '));
168
+ if (Array.isArray(tracks.rows)) root.style.setProperty('--grid-rows', tracks.rows.map((x) => `${x}fr`).join(' '));
169
+ }
170
+ function clampTracks(width, height, columns, rows) {
171
+ const { MIN_PANE_WIDTH: minWidth, MIN_PANE_HEIGHT: minHeight, MIN_STRIP_WIDTH: minStrip } = ShellPuppetDashboardLayout;
172
+ const focusSpace = width - 6;
173
+ if (typeof tracks.focusStrip === 'number' && Number.isFinite(tracks.focusStrip)) {
174
+ tracks.focusStrip = focusSpace >= minWidth + minStrip
175
+ ? Math.max(minStrip, Math.min(focusSpace - minWidth, tracks.focusStrip)) : null;
176
+ }
177
+ for (const [name, count, space, minimum] of [
178
+ ['columns', columns, width - 6 * (columns - 1), minWidth],
179
+ ['rows', rows, height - 6 * (rows - 1), minHeight],
180
+ ]) {
181
+ const values = tracks[name];
182
+ if (!Array.isArray(values)) continue;
183
+ if (values.length !== count || values.some((value) => typeof value !== 'number' || !Number.isFinite(value) || value <= 0) ||
184
+ space < count * minimum) { tracks[name] = null; continue; }
185
+ let remaining = space;
186
+ let weight = values.reduce((sum, value) => sum + value, 0);
187
+ const sizes = Array(count).fill(0);
188
+ const free = new Set(values.map((_, index) => index));
189
+ while (free.size > 0) {
190
+ const small = [...free].filter((index) => remaining * values[index] / weight < minimum);
191
+ if (small.length === 0) {
192
+ for (const index of free) sizes[index] = remaining * values[index] / weight;
193
+ break;
194
+ }
195
+ for (const index of small) {
196
+ sizes[index] = minimum;
197
+ remaining -= minimum;
198
+ weight -= values[index];
199
+ free.delete(index);
200
+ }
201
+ }
202
+ tracks[name] = sizes.map((size) => size / space);
203
+ }
204
+ }
205
+ const persistLaunches = () => {
206
+ try { window.localStorage.setItem(LAUNCH_PREF, JSON.stringify(launches)); } catch { /* Restart still works in this document. */ }
207
+ };
208
+ const showPrefix = () => {
209
+ document.getElementById('shortcut').textContent = `Shortcut: Ctrl+Shift+${prefix.toUpperCase()}`;
210
+ document.getElementById('shortcut-help').textContent = `Ctrl+Shift+${prefix.toUpperCase()}`;
211
+ };
212
+ const sorted = () => order.map((id) => panes.get(id)).filter(Boolean);
213
+ /** Panes this window holds after the roster's assignment. */
214
+ const shown = () => sorted().filter((item) => {
215
+ if (popSelf !== null) return item.id === popSelf;
216
+ return !popped.has(item.id) && (orderedWindows().length === 1 || assigned?.has(item.id));
217
+ });
218
+ function renderShareCount() {
219
+ if (popSelf !== null) { shareCount.hidden = true; return; }
220
+ const total = sorted().filter((item) => !popped.has(item.id)).length;
221
+ const here = shown().length;
222
+ const count = orderedWindows().length;
223
+ shareCount.textContent = `${here} of ${total} here, ${count} ${count === 1 ? 'window' : 'windows'}`;
224
+ }
225
+ const closeError = () => { error.hidden = true; document.getElementById('error-message').textContent = ''; };
226
+ const showError = (message) => { document.getElementById('error-message').textContent = message; error.hidden = false; };
227
+ function closeVisibleError() {
228
+ if (!error.hidden) { closeError(); return true; }
229
+ const focusedCard = document.activeElement?.closest('.pane');
230
+ const focused = focusedCard ? panes.get(focusedCard.dataset.session) : null;
231
+ const item = [focused, panes.get(selected), ...shown()].find((pane) => pane && visible(pane) && !pane.banner.hidden);
232
+ if (!item) return false;
233
+ item.banner.hidden = true;
234
+ return true;
235
+ }
236
+ function renderPreferences() {
237
+ document.getElementById('auto-fit').setAttribute('aria-pressed', String(autoFit));
238
+ document.getElementById('auto-fit').classList.toggle('active', autoFit);
239
+ document.getElementById('text-auto').textContent = fontSize === null ? 'Auto text' : `${fontSize} px`;
240
+ document.getElementById('text-auto').classList.toggle('active', fontSize === null);
241
+ }
242
+ function scheduleAutoFit() {
243
+ clearTimeout(autoFitTimer);
244
+ if (activeDivider) return;
245
+ if (!autoFit) { focusOpenFits.clear(); return; }
246
+ autoFitTimer = setTimeout(() => {
247
+ autoFitTimer = null;
248
+ if (window.performance.now() < assignmentSettleUntil) { scheduleAutoFit(); return; }
249
+ assignmentSettleStartedAt = 0;
250
+ for (const item of shown()) {
251
+ if (!visible(item)) continue;
252
+ item.client?.autoFitGrid(80, 24, focusOpenFits.has(item.id) || incomingFits.has(item.id));
253
+ }
254
+ }, assignmentSettleUntil > window.performance.now()
255
+ ? Math.max(0, assignmentSettleUntil - window.performance.now()) : 250);
256
+ }
257
+ function settleAssignmentFits() {
258
+ // A feed change and its window assignment can arrive in separate tasks.
259
+ // Wait for the last change before taking a pane's grid.
260
+ const now = window.performance.now();
261
+ if (assignmentSettleStartedAt === 0) assignmentSettleStartedAt = now;
262
+ assignmentSettleUntil = Math.min(now + 900, assignmentSettleStartedAt + 3000);
263
+ scheduleAutoFit();
264
+ }
265
+ function broadcastPreferences() {
266
+ channel?.postMessage({ type: 'preferences', autoFit, fontSize, token: windowToken });
267
+ }
268
+ function setFontSize(value, broadcast = true) {
269
+ assignmentSettleUntil = 0;
270
+ assignmentSettleStartedAt = 0;
271
+ fontSize = value;
272
+ for (const item of panes.values()) item.client?.setFontOverride(value);
273
+ renderPreferences(); persist(); scheduleAutoFit();
274
+ if (broadcast) broadcastPreferences();
275
+ }
276
+ const makeButton = (label, action) => {
277
+ const button = document.createElement('button');
278
+ button.type = 'button';
279
+ button.textContent = label;
280
+ button.setAttribute('aria-label', label);
281
+ button.addEventListener('click', (event) => { event.stopPropagation(); action(); });
282
+ return button;
283
+ };
284
+
285
+ const screenIdentity = (screen) => [screen.availLeft, screen.availTop,
286
+ screen.availWidth, screen.availHeight].join(',');
287
+ const orderedWindows = () => [...windows.values()].filter((entry) => entry.ready !== false)
288
+ .sort((a, b) => a.rank - b.rank || (a.loadAt ?? a.openedAt) - (b.loadAt ?? b.openedAt) || a.id.localeCompare(b.id) ||
289
+ a.instance.localeCompare(b.instance));
290
+ const ownWindow = () => ({ id: windowId, instance: windowInstance, document: windowToken,
291
+ rank: windowRank, openedAt, loadAt, key: currentScreenKey,
292
+ width: Math.max(1, root.clientWidth - 12), height: Math.max(1, root.clientHeight - 12) });
293
+ function advertise() {
294
+ if (popSelf !== null || channel === null) return;
295
+ windows.set(ownPair(), ownWindow());
296
+ lastSeen.set(ownPair(), Date.now());
297
+ channel.postMessage({ type: 'window-roster', window: ownWindow(), token: windowToken });
298
+ }
299
+ function applyAssignment(ids) {
300
+ const next = new Set(ids);
301
+ if (assigned !== null && next.size === assigned.size && [...next].every((id) => assigned.has(id))) return;
302
+ settleAssignmentFits();
303
+ const previous = assigned === null ? new Set() : assigned;
304
+ assigned = next;
305
+ for (const id of next) if (!previous.has(id)) incomingFits.add(id);
306
+ for (const id of previous) if (!next.has(id)) incomingFits.delete(id);
307
+ arrange('assignment');
308
+ }
309
+ function publishAssignment() {
310
+ if (popSelf !== null) return;
311
+ windows.set(ownPair(), ownWindow());
312
+ const roster = orderedWindows();
313
+ if (windowPair(roster[0]?.id, roster[0]?.instance) !== ownPair()) return;
314
+ const ids = sorted().map((item) => item.id).filter((id) => !popped.has(id));
315
+ if (roster.length === 1) { assigned = null; renderShareCount(); return; }
316
+ if (channel === null) return;
317
+ const byWindow = ShellPuppetDashboardLayout.assign(ids, roster.map((entry) => ({
318
+ ...entry, id: windowPair(entry.id, entry.instance),
319
+ })));
320
+ channel.postMessage({ type: 'window-assignment', owner: ownPair(), byWindow, token: windowToken });
321
+ applyAssignment(byWindow[ownPair()] || []);
322
+ }
323
+ function removeWindow(id, instance) {
324
+ const pair = windowPair(id, instance);
325
+ if (!windows.delete(pair)) return;
326
+ lastSeen.delete(pair);
327
+ settleAssignmentFits();
328
+ renderScreens();
329
+ arrange('window removed');
330
+ renderShareCount();
331
+ }
332
+ function markWindowGone(id, instance) {
333
+ if (validWindowId(instance)) {
334
+ const now = Date.now();
335
+ for (const [pair, closedAt] of goneWindows) if (now - closedAt > 600_000) goneWindows.delete(pair);
336
+ const pair = windowPair(id, instance);
337
+ goneWindows.delete(pair);
338
+ goneWindows.set(pair, now);
339
+ while (goneWindows.size > 64) goneWindows.delete(goneWindows.keys().next().value);
340
+ }
341
+ removeWindow(id, instance);
342
+ }
343
+ function openDashboard(hash, name, features) {
344
+ const child = window.open(`${location.origin}/dashboard${hash}`, name, features);
345
+ if (child === null) showError('The browser blocked the window. Press the button again.');
346
+ return child;
347
+ }
348
+ function openScreen(screen, screenRank) {
349
+ const id = `${windowToken}-${++nextFallback}`;
350
+ const key = screen === null ? null : screenIdentity(screen);
351
+ const rank = screen === null ? Date.now() * 1000 + nextFallback % 1000 : screenRank;
352
+ const hash = new URLSearchParams({ screen: id, rank: String(rank),
353
+ ...(key === null ? {} : { key, left: String(screen.availLeft), top: String(screen.availTop),
354
+ width: String(screen.availWidth), height: String(screen.availHeight) }) });
355
+ const features = screen === null ? 'popup' :
356
+ `popup,left=${screen.availLeft},top=${screen.availTop},width=${screen.availWidth},height=${screen.availHeight}`;
357
+ const child = openDashboard(`#${hash}`, `shellpuppet-screen-${id}`, features);
358
+ if (child === null) return;
359
+ windows.set(windowPair(id, null), { id, rank, openedAt: Date.now(), key, ready: false });
360
+ lastSeen.set(windowPair(id, null), Date.now());
361
+ renderScreens();
362
+ publishAssignment();
363
+ const watch = { id, child, instance: null, pair: windowPair(id, null), closedAt: null, timer: null };
364
+ watch.timer = setInterval(() => {
365
+ if (!child.closed) return;
366
+ if (watch.closedAt === null) { watch.closedAt = Date.now(); return; }
367
+ if (Date.now() - watch.closedAt < 1500) return;
368
+ // A duplicate shares the screen id, but only this child's instance has closed.
369
+ markWindowGone(watch.id, watch.instance);
370
+ clearInterval(watch.timer);
371
+ childWatches.delete(watch.pair);
372
+ }, 250);
373
+ childWatches.set(watch.pair, watch);
374
+ }
375
+ function renderScreens() {
376
+ const control = document.getElementById('screens');
377
+ control.textContent = '';
378
+ if (popSelf !== null) return;
379
+ if (screenState === 'prompt') {
380
+ control.append(makeButton('Allow screens', async () => {
381
+ control.querySelector('button').disabled = true;
382
+ try {
383
+ const details = await window.getScreenDetails();
384
+ screenState = 'granted';
385
+ watchScreens(details);
386
+ } catch { screenState = 'denied'; renderScreens(); }
387
+ }));
388
+ } else if (screenState === 'granted') {
389
+ screens.forEach(({ screen, rank }) => {
390
+ if ([...windows.values()].some((entry) => entry.key === screenIdentity(screen))) return;
391
+ control.append(makeButton(`Open on screen ${rank}`, () => openScreen(screen, rank)));
392
+ });
393
+ } else control.append(makeButton('Open another window', () => openScreen(null, 0)));
394
+ }
395
+ function setScreens(details) {
396
+ const current = details.currentScreen || details.screens.find((screen) => screen.isPrimary) || details.screens[0];
397
+ currentScreenKey = current ? screenIdentity(current) : screenKey;
398
+ screens = details.screens.map((screen, index) => ({ screen, rank: index + 1 }))
399
+ .filter((entry) => screenIdentity(entry.screen) !== screenIdentity(current));
400
+ advertise();
401
+ renderScreens();
402
+ }
403
+ function refreshScreens() {
404
+ if (watchedScreens !== null) setScreens(watchedScreens);
405
+ }
406
+ function watchScreens(details) {
407
+ if (watchedScreens !== details) {
408
+ watchedScreens?.removeEventListener?.('currentscreenchange', refreshScreens);
409
+ watchedScreens?.removeEventListener?.('screenschange', refreshScreens);
410
+ watchedScreens = details;
411
+ details.addEventListener?.('currentscreenchange', refreshScreens);
412
+ details.addEventListener?.('screenschange', refreshScreens);
413
+ }
414
+ setScreens(details);
415
+ }
416
+ async function discoverScreens() {
417
+ if (popSelf !== null || !navigator.permissions?.query) {
418
+ renderScreens(); return;
419
+ }
420
+ try {
421
+ const permission = await navigator.permissions.query({ name: 'window-management' });
422
+ if (!window.getScreenDetails) { renderScreens(); return; }
423
+ screenState = permission.state;
424
+ if (screenState === 'granted') watchScreens(await window.getScreenDetails());
425
+ else renderScreens();
426
+ } catch { screenState = 'unavailable'; renderScreens(); }
427
+ }
428
+
429
+ function rememberLaunch(id, profile, folder, rootIndex, chosenPath, recentPath) {
430
+ if (typeof id !== 'string' || !NAME.test(profile)) return;
431
+ const entry = { profile };
432
+ if (typeof folder === 'string' && folder !== '') entry.folder = folder;
433
+ if (Number.isInteger(rootIndex) && rootIndex >= 0) entry.rootIndex = rootIndex;
434
+ if (typeof chosenPath === 'string' && chosenPath !== '') entry.folderPath = chosenPath;
435
+ launches[id] = entry;
436
+ persistLaunches();
437
+ if (entry.folder || entry.folderPath) {
438
+ const key = recentPath || entry.folderPath || (entry.rootIndex === undefined ? entry.folder : `root:${entry.rootIndex}:${entry.folder}`);
439
+ recent = ShellPuppetDashboardFolders.remember(recent, profile, key);
440
+ try { window.localStorage.setItem(RECENT_PREF, JSON.stringify(recent)); } catch { /* Recent folders remain available here. */ }
441
+ renderFolders();
442
+ }
443
+ }
444
+
445
+ function launchBody(entry) {
446
+ if (!entry || typeof entry.profile !== 'string') return null;
447
+ const body = { profile: entry.profile };
448
+ if (typeof entry.folder === 'string' && entry.folder !== '') body.folder = entry.folder;
449
+ if (Number.isInteger(entry.rootIndex) && entry.rootIndex >= 0) body.rootIndex = entry.rootIndex;
450
+ if (typeof entry.folderPath === 'string' && entry.folderPath !== '') body.folderPath = entry.folderPath;
451
+ return body;
452
+ }
453
+
454
+ function createCard(summary) {
455
+ const card = document.createElement('section');
456
+ card.className = 'pane';
457
+ card.dataset.session = summary.id;
458
+ card.tabIndex = 0;
459
+ const head = document.createElement('div');
460
+ head.className = 'pane-head';
461
+ head.title = 'Double-click the title bar to Enlarge or Restore; outside the terminal, Escape closes an error first, then restores';
462
+ const label = document.createElement('span');
463
+ label.className = 'pane-label';
464
+ const purpose = document.createElement('span');
465
+ purpose.className = 'pane-purpose hint';
466
+ const badge = document.createElement('span');
467
+ badge.className = 'badge';
468
+ const state = document.createElement('span');
469
+ state.className = 'pane-state hint';
470
+ const space = document.createElement('span');
471
+ space.className = 'spacer';
472
+ const size = document.createElement('span');
473
+ size.className = 'pane-size';
474
+ const overflowNote = document.createElement('div');
475
+ overflowNote.className = 'pane-overflow-note';
476
+ overflowNote.textContent = 'Shift+wheel or drag the scrollbars to see the rest. Enlarge or Fit to show it whole.';
477
+ overflowNote.hidden = true;
478
+ const item = { id: summary.id, summary, card, label, purpose, badge, state, size, overflowNote, client: null, previousGrid: null };
479
+ item.fit = makeButton('Fit', () => { select(item.id); item.client?.fitGrid(); });
480
+ item.enlarge = makeButton('Enlarge', () => {
481
+ select(item.id);
482
+ if (enlarged === item.id) {
483
+ enlarged = null;
484
+ arrange('restore');
485
+ if (!autoFit && item.previousGrid) item.client?.takeGrid(item.previousGrid.cols, item.previousGrid.rows);
486
+ item.previousGrid = null;
487
+ } else {
488
+ item.previousGrid = item.client?.getGrid() || null;
489
+ enlarged = item.id;
490
+ arrange('enlarge');
491
+ if (!autoFit) window.requestAnimationFrame(() => item.client?.fitGrid());
492
+ }
493
+ });
494
+ item.pin = makeButton('Pin', () => {
495
+ pins = pins.includes(item.id) ? pins.filter((id) => id !== item.id) : [...pins, item.id];
496
+ persist(); arrange('pin');
497
+ });
498
+ item.left = makeButton('Move left', () => move(item.id, -1));
499
+ item.right = makeButton('Move right', () => move(item.id, 1));
500
+ item.menuButton = makeButton('Menu', () => { item.menu.hidden = !item.menu.hidden; });
501
+ const menu = document.createElement('div');
502
+ menu.className = 'pane-menu';
503
+ menu.hidden = true;
504
+ item.kill = makeButton('Kill', () => { void killSession(item.id); });
505
+ item.kill.dataset.action = 'kill';
506
+ item.copy = makeButton('Copy session id', () => { void copySessionId(item.id); });
507
+ item.copy.dataset.action = 'copy';
508
+ item.pop = makeButton('Pop out', () => popOut(item.id));
509
+ item.pop.dataset.action = 'pop';
510
+ item.restart = makeButton('Restart', () => { void restartSession(item.id); });
511
+ item.restart.dataset.action = 'restart';
512
+ item.dismiss = makeButton('Dismiss', () => dismiss(item.id));
513
+ item.dismiss.dataset.action = 'dismiss';
514
+ menu.append(item.kill, item.copy, item.pop, item.restart, item.dismiss);
515
+ item.menu = menu;
516
+ head.append(label, purpose, badge, state, space, size, item.fit, item.enlarge,
517
+ item.pin, item.left, item.right, item.menuButton);
518
+ head.addEventListener('dblclick', (event) => {
519
+ if (!event.target.closest('button')) item.enlarge.click();
520
+ });
521
+ const wrap = document.createElement('div');
522
+ wrap.className = 'pane-wrap';
523
+ const term = document.createElement('div');
524
+ term.className = 'pane-term';
525
+ const notices = document.createElement('div');
526
+ notices.className = 'pane-notices';
527
+ const banner = document.createElement('div');
528
+ banner.className = 'pane-banner';
529
+ banner.hidden = true;
530
+ const bannerMessage = document.createElement('span');
531
+ bannerMessage.className = 'pane-banner-message';
532
+ banner.append(bannerMessage, makeButton('Close pane error', () => {
533
+ const hadFocus = banner.contains(document.activeElement);
534
+ banner.hidden = true;
535
+ // A hidden button cannot hold visible focus: give it to the pane.
536
+ if (hadFocus) card.focus();
537
+ }));
538
+ const prompt = document.createElement('div');
539
+ prompt.className = 'pane-prompt';
540
+ prompt.hidden = true;
541
+ notices.append(banner, prompt);
542
+ wrap.append(term, notices);
543
+ card.append(head, menu, overflowNote, wrap);
544
+ Object.assign(item, { term, banner, prompt });
545
+ card.addEventListener('click', () => select(item.id, true));
546
+ card.addEventListener('focus', () => select(item.id));
547
+ updateCard(item);
548
+ return item;
549
+ }
550
+
551
+ function updateCard(item) {
552
+ const summary = item.summary;
553
+ item.label.textContent = summary.label || summary.id;
554
+ item.purpose.textContent = summary.purpose || '';
555
+ item.badge.textContent = attention(item) ? '● Waiting' : '';
556
+ item.card.classList.toggle('attention', attention(item));
557
+ item.card.classList.toggle('selected', selected === item.id);
558
+ item.card.classList.toggle('ended', summary.exited === true);
559
+ item.state.textContent = summary.exited !== true ? ''
560
+ : summary.exitCode === null || summary.exitCode === undefined
561
+ ? 'Ended: its output failed'
562
+ : `Ended (code ${String(summary.exitCode)})`;
563
+ item.pin.textContent = pins.includes(item.id) ? 'Unpin' : 'Pin';
564
+ item.enlarge.textContent = enlarged === item.id ? 'Restore' : 'Enlarge';
565
+ item.pin.setAttribute('aria-label', item.pin.textContent);
566
+ item.enlarge.setAttribute('aria-label', item.enlarge.textContent);
567
+ item.restart.hidden = launchBody(launches[item.id]) === null;
568
+ item.dismiss.hidden = summary.exited !== true;
569
+ item.pop.hidden = popSelf === item.id;
570
+ item.card.setAttribute('aria-label', `${item.label.textContent} ${item.purpose.textContent}`);
571
+ }
572
+ function attention(item) {
573
+ const prompt = item.summary.waitingOnPrompt;
574
+ return Boolean(prompt && prompt.waitingMs >= 20_000);
575
+ }
576
+ function updateAttention() {
577
+ for (const item of panes.values()) updateCard(item);
578
+ const count = sorted().filter(attention).length;
579
+ attentionCount.textContent = count ? `${count} waiting` : '';
580
+ const focus = panes.get(selected);
581
+ document.title = `${count ? `${count} waiting · ` : ''}${focus?.label.textContent || 'Dashboard'} · ShellPuppet`;
582
+ }
583
+ function select(id, focusTerminal = false) {
584
+ if (!panes.has(id)) return;
585
+ selected = id;
586
+ updateAttention();
587
+ if (focusTerminal) panes.get(id).client?.getTerminal().focus();
588
+ }
589
+ function move(id, delta) {
590
+ const index = order.indexOf(id);
591
+ const target = index + delta;
592
+ if (target < 0 || target >= order.length) return;
593
+ [order[index], order[target]] = [order[target], order[index]];
594
+ persist(); arrange('move');
595
+ }
596
+ function activate(item) {
597
+ const width = item.term.clientWidth;
598
+ const height = item.term.clientHeight;
599
+ if (item.client) {
600
+ if (item.clientWidth !== width || item.clientHeight !== height) {
601
+ item.clientWidth = width;
602
+ item.clientHeight = height;
603
+ item.client.relayout(false);
604
+ }
605
+ return;
606
+ }
607
+ item.clientWidth = width;
608
+ item.clientHeight = height;
609
+ item.client = ShellPuppetPane.create({
610
+ container: item.term, sessionId: item.id, dashboardProof: proof,
611
+ initialFontOverride: fontSize,
612
+ elements: { banner: item.banner, promptAlert: item.prompt, size: item.size, overflowNote: item.overflowNote },
613
+ onAttentionChange: () => updateAttention(),
614
+ onGeometryReady: () => scheduleAutoFit(),
615
+ onOutsideGeometry: () => scheduleAutoFit(),
616
+ onGridTaken: () => { focusOpenFits.delete(item.id); incomingFits.delete(item.id); },
617
+ });
618
+ }
619
+ function deactivate(item) {
620
+ if (!item.client) return;
621
+ const client = item.client;
622
+ item.client = null;
623
+ client.destroy();
624
+ item.term.textContent = '';
625
+ }
626
+ function visible(item) {
627
+ if (popSelf !== null) return item.id === popSelf && item.card.isConnected;
628
+ if (popped.has(item.id)) return false;
629
+ if (enlarged && item.id !== enlarged) return false;
630
+ const box = item.card.getBoundingClientRect();
631
+ if (box.width < 1 || box.height < 1) return false;
632
+ const container = item.card.parentElement === strip ? strip.getBoundingClientRect() : root.getBoundingClientRect();
633
+ return box.bottom > container.top && box.top < container.bottom && box.right > container.left && box.left < container.right;
634
+ }
635
+ function queueFollowUp() {
636
+ if (followUpFrame) return;
637
+ followUpFrame = true;
638
+ if (diagnostics) diagnostics.pendingFrames++;
639
+ window.requestAnimationFrame(() => {
640
+ followUpFrame = false;
641
+ if (diagnostics) diagnostics.pendingFrames--;
642
+ if (pendingArrange) {
643
+ pendingArrange = false;
644
+ arrange('follow-up');
645
+ }
646
+ if (pendingVisibility) {
647
+ pendingVisibility = false;
648
+ syncVisibility();
649
+ }
650
+ });
651
+ }
652
+ function syncVisibility() {
653
+ if (syncingVisibility) {
654
+ pendingVisibility = true;
655
+ queueFollowUp();
656
+ return;
657
+ }
658
+ const stripBox = strip.getBoundingClientRect();
659
+ const geometry = JSON.stringify([lastLayout, strip.scrollTop, strip.clientWidth, strip.clientHeight,
660
+ strip.scrollHeight, stripBox.top, stripBox.bottom]);
661
+ if (geometry === lastVisibilityGeometry) return;
662
+ syncingVisibility = true;
663
+ if (diagnostics) diagnostics.visibilityPasses++;
664
+ if (window.__dashboardTrace) {
665
+ window.__dashboardTrace.visibility++;
666
+ window.__dashboardTrace.visibilityDepth++;
667
+ window.__dashboardTrace.maxVisibilityDepth = Math.max(window.__dashboardTrace.maxVisibilityDepth, window.__dashboardTrace.visibilityDepth);
668
+ }
669
+ try {
670
+ for (const item of panes.values()) {
671
+ if (visible(item)) activate(item);
672
+ else deactivate(item);
673
+ }
674
+ lastVisibilityGeometry = geometry;
675
+ } finally {
676
+ syncingVisibility = false;
677
+ if (window.__dashboardTrace) window.__dashboardTrace.visibilityDepth--;
678
+ }
679
+ }
680
+ function trackSizes(axis) {
681
+ if (axis === 'focus') return [main.getBoundingClientRect().width, strip.getBoundingClientRect().width];
682
+ const items = shown();
683
+ const columns = Math.ceil(Math.sqrt(items.length));
684
+ const count = axis === 'column' ? columns : Math.ceil(items.length / columns);
685
+ return Array.from({ length: count }, (_, index) => {
686
+ const card = items[axis === 'column' ? index : index * columns]?.card;
687
+ return card?.getBoundingClientRect()[axis === 'column' ? 'width' : 'height'] || 0;
688
+ });
689
+ }
690
+ function setTrackSizes(axis, sizes) {
691
+ if (axis === 'focus') tracks.focusStrip = sizes[1];
692
+ else {
693
+ const total = sizes.reduce((sum, size) => sum + size, 0);
694
+ tracks[axis === 'column' ? 'columns' : 'rows'] = sizes.map((size) => size / total);
695
+ }
696
+ applyTracks();
697
+ positionDividers();
698
+ }
699
+ function positionDividers() {
700
+ const frame = root.getBoundingClientRect();
701
+ const items = shown();
702
+ const columns = Math.ceil(Math.sqrt(items.length));
703
+ for (const divider of root.querySelectorAll('.pane-divider')) {
704
+ const axis = divider.dataset.axis;
705
+ const index = Number(divider.dataset.index);
706
+ const target = axis === 'focus' ? main : items[axis === 'column' ? index : (index + 1) * columns - 1]?.card;
707
+ if (!target) continue;
708
+ const boundary = target.getBoundingClientRect()[axis === 'row' ? 'bottom' : 'right'];
709
+ const sizes = trackSizes(axis);
710
+ const minimum = axis === 'row' ? ShellPuppetDashboardLayout.MIN_PANE_HEIGHT : ShellPuppetDashboardLayout.MIN_PANE_WIDTH;
711
+ const secondMinimum = axis === 'focus' ? ShellPuppetDashboardLayout.MIN_STRIP_WIDTH : minimum;
712
+ const total = sizes[index] + sizes[index + 1];
713
+ const movable = total >= minimum + secondMinimum;
714
+ const value = Math.round(sizes[index]);
715
+ divider.setAttribute('aria-valuenow', String(value));
716
+ divider.setAttribute('aria-valuemin', String(movable ? minimum : value));
717
+ divider.setAttribute('aria-valuemax', String(movable ? Math.round(total - secondMinimum) : value));
718
+ divider.setAttribute('aria-valuetext', axis === 'focus' ? `Focus pane ${value} pixels wide` :
719
+ `${axis === 'column' ? 'Column' : 'Row'} ${index + 1} ${value} pixels ${axis === 'column' ? 'wide' : 'high'}`);
720
+ if (axis === 'row') {
721
+ divider.style.left = '6px'; divider.style.right = '6px';
722
+ divider.style.top = `${boundary - frame.top - 3}px`;
723
+ } else {
724
+ divider.style.top = '6px'; divider.style.bottom = '6px';
725
+ divider.style.left = `${boundary - frame.left - 3}px`;
726
+ }
727
+ }
728
+ }
729
+ function paneSizes() {
730
+ return new Map(shown().map((item) => [item.id, item.card.getBoundingClientRect()]));
731
+ }
732
+ function finishDivider(divider, before) {
733
+ activeDivider = null;
734
+ endActiveDivider = null;
735
+ divider.classList.remove('dragging');
736
+ saveTracks();
737
+ positionDividers();
738
+ lastVisibilityGeometry = null;
739
+ syncVisibility();
740
+ for (const item of shown()) {
741
+ const old = before.get(item.id);
742
+ if (!old || !item.client || !visible(item)) continue;
743
+ const now = item.card.getBoundingClientRect();
744
+ if (autoFit && (now.width > old.width + 1 || now.height > old.height + 1)) item.client.fitAfterDrag(true);
745
+ }
746
+ }
747
+ function beginDivider(divider, pointerId, start) {
748
+ endActiveDivider?.();
749
+ const axis = divider.dataset.axis;
750
+ const index = Number(divider.dataset.index);
751
+ const sizes = trackSizes(axis);
752
+ const before = paneSizes();
753
+ const minimum = axis === 'row' ? ShellPuppetDashboardLayout.MIN_PANE_HEIGHT : ShellPuppetDashboardLayout.MIN_PANE_WIDTH;
754
+ const secondMinimum = axis === 'focus' ? ShellPuppetDashboardLayout.MIN_STRIP_WIDTH : minimum;
755
+ clearTimeout(autoFitTimer);
756
+ activeDivider = divider;
757
+ divider.classList.add('dragging');
758
+ const move = (coordinate) => {
759
+ const total = sizes[index] + sizes[index + 1];
760
+ if (total < minimum + secondMinimum) return;
761
+ const first = Math.max(minimum, Math.min(total - secondMinimum, sizes[index] + coordinate - start));
762
+ if (Math.abs(first - sizes[index]) < 0.5) return;
763
+ const next = sizes.slice();
764
+ next[index] = first; next[index + 1] = total - first;
765
+ setTrackSizes(axis, next);
766
+ };
767
+ let ended = false;
768
+ const release = () => {
769
+ if (ended) return;
770
+ ended = true;
771
+ divider.removeEventListener('pointermove', onMove);
772
+ divider.removeEventListener('pointerup', onEnd);
773
+ divider.removeEventListener('pointercancel', onCancel);
774
+ divider.removeEventListener('lostpointercapture', onLost);
775
+ document.removeEventListener('pointermove', onDocumentMove, true);
776
+ document.removeEventListener('pointerup', onEnd);
777
+ document.removeEventListener('pointercancel', onCancel);
778
+ if (pointerId !== null && divider.hasPointerCapture(pointerId)) divider.releasePointerCapture(pointerId);
779
+ finishDivider(divider, before);
780
+ };
781
+ const onDocumentMove = (event) => {
782
+ if (event.pointerId === pointerId && !divider.hasPointerCapture(pointerId)) release();
783
+ };
784
+ const onMove = (event) => {
785
+ if (event.pointerId !== pointerId) return;
786
+ if (!divider.hasPointerCapture(pointerId)) { release(); return; }
787
+ move(axis === 'row' ? event.clientY : event.clientX);
788
+ };
789
+ const onEnd = (event) => { if (event.pointerId === pointerId) { move(axis === 'row' ? event.clientY : event.clientX); release(); } };
790
+ const onCancel = (event) => { if (event.pointerId === pointerId) release(); };
791
+ const onLost = (event) => { if (event.pointerId === pointerId) release(); };
792
+ endActiveDivider = release;
793
+ if (pointerId !== null) {
794
+ divider.setPointerCapture(pointerId);
795
+ divider.addEventListener('pointermove', onMove);
796
+ divider.addEventListener('pointerup', onEnd);
797
+ divider.addEventListener('pointercancel', onCancel);
798
+ divider.addEventListener('lostpointercapture', onLost);
799
+ document.addEventListener('pointermove', onDocumentMove, true);
800
+ document.addEventListener('pointerup', onEnd);
801
+ document.addEventListener('pointercancel', onCancel);
802
+ }
803
+ return { move, release };
804
+ }
805
+ function addDivider(axis, index) {
806
+ const divider = document.createElement('div');
807
+ divider.className = 'pane-divider';
808
+ divider.dataset.axis = axis;
809
+ divider.dataset.index = String(index);
810
+ divider.setAttribute('role', 'separator');
811
+ divider.setAttribute('aria-orientation', axis === 'row' ? 'horizontal' : 'vertical');
812
+ divider.setAttribute('aria-label', axis === 'focus' ? 'Resize focused pane and strip' :
813
+ `Resize ${axis === 'column' ? 'columns' : 'rows'} ${index + 1} and ${index + 2}`);
814
+ divider.tabIndex = 0;
815
+ divider.addEventListener('pointerdown', (event) => {
816
+ if (event.button !== 0) return;
817
+ event.preventDefault();
818
+ divider.focus();
819
+ beginDivider(divider, event.pointerId, axis === 'row' ? event.clientY : event.clientX);
820
+ });
821
+ divider.addEventListener('keydown', (event) => {
822
+ const steps = axis === 'row' ? { ArrowUp: -24, ArrowDown: 24 } : { ArrowLeft: -24, ArrowRight: 24 };
823
+ if (event.key !== 'Home' && !Object.hasOwn(steps, event.key)) return;
824
+ event.preventDefault(); event.stopPropagation();
825
+ if (event.key === 'Home') {
826
+ endActiveDivider?.();
827
+ const before = paneSizes();
828
+ if (axis === 'focus') tracks.focusStrip = null;
829
+ else tracks[axis === 'column' ? 'columns' : 'rows'] = null;
830
+ applyTracks(); finishDivider(divider, before);
831
+ } else {
832
+ const coordinate = divider.getBoundingClientRect()[axis === 'row' ? 'y' : 'x'];
833
+ const action = beginDivider(divider, null, coordinate);
834
+ action.move(coordinate + steps[event.key] * (event.shiftKey ? 4 : 1));
835
+ action.release();
836
+ }
837
+ });
838
+ root.append(divider);
839
+ return divider;
840
+ }
841
+ function renderDividers(layout, columns, rows, items, primary) {
842
+ const wanted = new Map();
843
+ const ids = items.map((item) => item.id);
844
+ if (layout === 'focus' && ids.length > 1) {
845
+ wanted.set('focus:0', JSON.stringify([[primary], ids.filter((id) => id !== primary)]));
846
+ }
847
+ if (layout === 'grid' && mode === 'grid' && ids.length > 1) {
848
+ for (let index = 0; index < columns - 1; index++) {
849
+ wanted.set(`column:${index}`, JSON.stringify([
850
+ ids.filter((_, position) => position % columns === index),
851
+ ids.filter((_, position) => position % columns === index + 1),
852
+ ]));
853
+ }
854
+ for (let index = 0; index < rows - 1; index++) {
855
+ wanted.set(`row:${index}`, JSON.stringify([
856
+ ids.slice(index * columns, (index + 1) * columns),
857
+ ids.slice((index + 1) * columns, (index + 2) * columns),
858
+ ]));
859
+ }
860
+ }
861
+ const existing = new Map([...root.querySelectorAll('.pane-divider')].map((divider) =>
862
+ [`${divider.dataset.axis}:${divider.dataset.index}`, divider]));
863
+ for (const [key, divider] of existing) {
864
+ if (wanted.get(key) === divider.dataset.panes) continue;
865
+ if (divider === activeDivider) endActiveDivider?.();
866
+ divider.remove();
867
+ }
868
+ for (const [key, sides] of wanted) {
869
+ if (existing.get(key)?.dataset.panes === sides) continue;
870
+ const [axis, index] = key.split(':');
871
+ addDivider(axis, Number(index)).dataset.panes = sides;
872
+ }
873
+ positionDividers();
874
+ }
875
+ function arrange(trigger = 'unspecified') {
876
+ if (trigger === 'enlarge' || trigger === 'restore' || trigger === 'window resize') {
877
+ assignmentSettleUntil = 0;
878
+ assignmentSettleStartedAt = 0;
879
+ }
880
+ traceArrange(trigger);
881
+ if (arranging || syncingVisibility) {
882
+ pendingArrange = true;
883
+ queueFollowUp();
884
+ return;
885
+ }
886
+ arranging = true;
887
+ if (diagnostics) diagnostics.arrangements++;
888
+ if (window.__dashboardTrace) {
889
+ window.__dashboardTrace.arrangements++;
890
+ window.__dashboardTrace.arrangeDepth++;
891
+ window.__dashboardTrace.maxArrangeDepth = Math.max(window.__dashboardTrace.maxArrangeDepth, window.__dashboardTrace.arrangeDepth);
892
+ }
893
+ try {
894
+ const items = shown();
895
+ if (tracks.count !== items.length) resetTracks();
896
+ renderShareCount();
897
+ const width = root.clientWidth - 12;
898
+ const height = root.clientHeight - 12;
899
+ const columns = Math.ceil(Math.sqrt(items.length));
900
+ const rows = Math.ceil(items.length / Math.max(1, columns));
901
+ if (items.length > 0) clampTracks(width, height, columns, rows);
902
+ applyTracks();
903
+ const autoGrid = items.length <= 1 || (width / columns >= 652 && height / rows >= 446);
904
+ const layout = popSelf !== null || enlarged ? 'enlarged' : mode === 'auto' ? (autoGrid ? 'grid' : 'focus') : mode;
905
+ const primary = layout === 'focus' ? pins.find((id) => items.some((item) => item.id === id)) ||
906
+ (mode === 'focus' && items.some((item) => item.id === focusId) ? focusId : items[0]?.id) : null;
907
+ const layoutKey = JSON.stringify([items.map((item) => item.id), width, height, layout, mode,
908
+ columns, rows, primary, enlarged, pins]);
909
+ if (layoutKey !== lastLayout) {
910
+ const structureKey = JSON.stringify([items.map((item) => item.id), layout, primary, enlarged]);
911
+ empty.hidden = items.length > 0;
912
+ root.className = layout === 'focus' && items.length === 1 ? 'focus focus-only' : layout;
913
+ root.dataset.layout = layout;
914
+ root.style.setProperty('--columns', String(Math.max(1, columns)));
915
+ root.style.setProperty('--rows', String(Math.max(1, rows)));
916
+ for (const name of ['auto', 'grid', 'focus']) document.getElementById(name).classList.toggle('active', mode === name);
917
+ if (structureKey !== lastStructure) {
918
+ for (const child of [...root.children]) if (!child.classList.contains('pane-divider')) child.remove();
919
+ if (layout === 'grid') {
920
+ for (const item of items) root.append(item.card);
921
+ } else if (layout === 'focus') {
922
+ main.textContent = '';
923
+ strip.textContent = '';
924
+ for (const item of items) (item.id === primary ? main : strip).append(item.card);
925
+ root.append(main, strip);
926
+ } else {
927
+ const item = panes.get(popSelf || enlarged);
928
+ if (item) root.append(item.card);
929
+ }
930
+ lastStructure = structureKey;
931
+ }
932
+ renderDividers(layout, columns, rows, items, primary);
933
+ for (const item of items) {
934
+ const box = item.card.getBoundingClientRect();
935
+ const measuredWidth = box.width;
936
+ const measuredHeight = box.height;
937
+ item.card.classList.toggle('below-floor', measuredWidth < 652 || measuredHeight < 446);
938
+ updateCard(item);
939
+ }
940
+ lastLayout = layoutKey;
941
+ syncVisibility();
942
+ scheduleAutoFit();
943
+ }
944
+ publishAssignment();
945
+ } finally {
946
+ arranging = false;
947
+ if (window.__dashboardTrace) window.__dashboardTrace.arrangeDepth--;
948
+ }
949
+ }
950
+
951
+ function dropLaunch(id) {
952
+ if (launches[id] === undefined) return;
953
+ delete launches[id];
954
+ persistLaunches();
955
+ }
956
+
957
+ function reconcile(sessions, full = false) {
958
+ const incoming = new Map(sessions.filter((s) => s && typeof s.id === 'string').map((s) => [s.id, s]));
959
+ if ([...panes.keys()].some((id) => !incoming.has(id) || dismissed.has(id)) ||
960
+ [...incoming.keys()].some((id) => !panes.has(id) && !dismissed.has(id))) settleAssignmentFits();
961
+ // A snapshot is the whole list. An added or removed frame is not, so it
962
+ // must not forget a dismissal or a launch for a session it did not mention.
963
+ if (full) {
964
+ for (const id of [...dismissed]) { if (!incoming.has(id)) dismissed.delete(id); }
965
+ for (const id of [...popped]) { if (!incoming.has(id)) releasePop(id); }
966
+ for (const id of Object.keys(launches)) { if (!incoming.has(id)) dropLaunch(id); }
967
+ }
968
+ for (const [id, item] of panes) {
969
+ if (incoming.has(id) && !dismissed.has(id)) continue;
970
+ deactivate(item); item.card.remove(); panes.delete(id);
971
+ }
972
+ order = order.filter((id) => incoming.has(id) && !dismissed.has(id));
973
+ pins = pins.filter((id) => incoming.has(id) && !dismissed.has(id));
974
+ for (const [id, summary] of incoming) {
975
+ if (dismissed.has(id)) continue;
976
+ if (!panes.has(id)) {
977
+ panes.set(id, createCard(summary));
978
+ // A session the saved order already names keeps that place.
979
+ if (!order.includes(id)) order.push(id);
980
+ } else panes.get(id).summary = summary;
981
+ }
982
+ if (!panes.has(selected)) selected = order.find((id) => panes.has(id)) || null;
983
+ if (!panes.has(focusId)) focusId = null;
984
+ if (!panes.has(enlarged)) enlarged = null;
985
+ persist(); arrange('feed reconcile'); updateAttention();
986
+ for (const id of [...pendingOpen.keys()]) enactOpen(id);
987
+ }
988
+ function receive(frame) {
989
+ if (!frame || typeof frame.type !== 'string') return;
990
+ if (frame.type === 'window-gone' && validWindowId(frame.id) && validWindowId(frame.instance)) {
991
+ if (popSelf !== null) return;
992
+ markWindowGone(frame.id, frame.instance);
993
+ return;
994
+ }
995
+ if (frame.type === 'snapshot' && Array.isArray(frame.sessions)) reconcile(frame.sessions, true);
996
+ else if (frame.type === 'session-added' && frame.session?.id) {
997
+ if (!panes.has(frame.session.id) && !dismissed.has(frame.session.id)) {
998
+ reconcile([...sorted().map((p) => p.summary), frame.session]);
999
+ }
1000
+ } else if (frame.type === 'session-updated' && frame.session?.id) {
1001
+ const item = panes.get(frame.session.id);
1002
+ if (item) { item.summary = frame.session; updateAttention(); }
1003
+ } else if (frame.type === 'session-removed' && typeof frame.session === 'string') {
1004
+ dismissed.delete(frame.session);
1005
+ dropLaunch(frame.session);
1006
+ releasePop(frame.session);
1007
+ reconcile(sorted().filter((p) => p.id !== frame.session).map((p) => p.summary));
1008
+ }
1009
+ }
1010
+ function connect() {
1011
+ feed = new WebSocket(`ws://${location.host}/dashboard/events`, [`sp-csrf.${proof}`]);
1012
+ feed.onopen = () => {
1013
+ connection.textContent = 'Connected'; error.hidden = true;
1014
+ if (popSelf === null) {
1015
+ if (registered) {
1016
+ channel?.postMessage({ type: 'window-leave', id: windowId, instance: windowInstance, token: windowToken });
1017
+ windows.delete(ownPair());
1018
+ lastSeen.delete(ownPair());
1019
+ windowInstance = newInstance();
1020
+ openedAt = Math.max(openedAt + 1, window.performance.timeOrigin + window.performance.now());
1021
+ }
1022
+ registered = true;
1023
+ feed.send(JSON.stringify({ type: 'window-register', id: windowId, instance: windowInstance }));
1024
+ advertise();
1025
+ publishAssignment();
1026
+ }
1027
+ };
1028
+ feed.onmessage = (event) => {
1029
+ try { receive(JSON.parse(event.data)); } catch { showError('The session feed sent an unreadable update.'); }
1030
+ };
1031
+ feed.onclose = () => { connection.textContent = 'Reconnecting'; retry = setTimeout(connect, 2000); };
1032
+ feed.onerror = () => showError('Could not connect to the dashboard session feed.');
1033
+ }
1034
+
1035
+ async function killSession(id) {
1036
+ let response;
1037
+ try {
1038
+ response = await fetch(`/sessions/${encodeURIComponent(id)}`, {
1039
+ method: 'DELETE',
1040
+ headers: { 'x-shellpuppet-csrf': proof },
1041
+ });
1042
+ } catch {
1043
+ showError('The session could not be ended.');
1044
+ return;
1045
+ }
1046
+ if (response.ok) return;
1047
+ let message = 'The session could not be ended.';
1048
+ try {
1049
+ const payload = await response.json();
1050
+ if (typeof payload.error === 'string') message = payload.error;
1051
+ } catch { /* The status line is enough. */ }
1052
+ showError(message);
1053
+ }
1054
+
1055
+ async function copySessionId(id) {
1056
+ // The id alone. No viewer grant, no request and no event.
1057
+ try {
1058
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
1059
+ await navigator.clipboard.writeText(id);
1060
+ return;
1061
+ }
1062
+ } catch { /* The selection copy below is the fallback. */ }
1063
+ const area = document.createElement('textarea');
1064
+ area.value = id;
1065
+ area.setAttribute('readonly', '');
1066
+ document.body.append(area);
1067
+ area.select();
1068
+ document.execCommand('copy');
1069
+ area.remove();
1070
+ }
1071
+
1072
+ function releasePop(id) {
1073
+ const watch = popWatches.get(id);
1074
+ if (watch !== undefined) { clearInterval(watch); popWatches.delete(id); }
1075
+ if (!popped.delete(id)) return;
1076
+ arrange('pop release');
1077
+ }
1078
+
1079
+ function popOut(id) {
1080
+ if (popSelf === id || popped.has(id)) return;
1081
+ // One window, and never a second open in the same click. The URL carries
1082
+ // the session id only: no grant and no cookie value.
1083
+ const child = openDashboard(`#pop=${encodeURIComponent(id)}`, `shellpuppet-pop-${id}`,
1084
+ 'popup,width=960,height=720');
1085
+ if (child === null) return;
1086
+ popped.add(id);
1087
+ arrange('pop out');
1088
+ const watch = setInterval(() => {
1089
+ if (!child.closed) return;
1090
+ releasePop(id);
1091
+ }, 500);
1092
+ popWatches.set(id, watch);
1093
+ }
1094
+
1095
+ function fitWhenReady(id, left = 30) {
1096
+ const client = panes.get(id)?.client;
1097
+ if (client?.fitGrid(80, 24)) return;
1098
+ if (left <= 0) return;
1099
+ window.requestAnimationFrame(() => fitWhenReady(id, left - 1));
1100
+ }
1101
+
1102
+ function enactOpen(id) {
1103
+ const open = pendingOpen.get(id);
1104
+ if (open === undefined) return;
1105
+ if (open === 'window') {
1106
+ pendingOpen.delete(id);
1107
+ popOut(id);
1108
+ return;
1109
+ }
1110
+ if (open === 'focus') {
1111
+ if (!panes.has(id)) return;
1112
+ pendingOpen.delete(id);
1113
+ mode = 'focus';
1114
+ focusId = id;
1115
+ selected = id;
1116
+ enlarged = null;
1117
+ persist();
1118
+ arrange('focus open');
1119
+ if (autoFit) { focusOpenFits.add(id); scheduleAutoFit(); }
1120
+ else fitWhenReady(id);
1121
+ }
1122
+ }
1123
+
1124
+ function applyOpen(id, open) {
1125
+ if (open !== 'focus' && open !== 'window') return;
1126
+ pendingOpen.set(id, open);
1127
+ enactOpen(id);
1128
+ }
1129
+
1130
+ async function postLaunch(body) {
1131
+ let response;
1132
+ try {
1133
+ response = await fetch('/dashboard/launch', {
1134
+ method: 'POST',
1135
+ headers: { 'content-type': 'application/json', 'x-shellpuppet-csrf': proof },
1136
+ body: JSON.stringify(body),
1137
+ });
1138
+ } catch {
1139
+ showError('The profile did not start.');
1140
+ return;
1141
+ }
1142
+ let payload;
1143
+ try { payload = await response.json(); } catch { payload = {}; }
1144
+ if (!response.ok) {
1145
+ showError(typeof payload.error === 'string' ? payload.error : 'The profile did not start.');
1146
+ return;
1147
+ }
1148
+ if (typeof payload.id !== 'string') return;
1149
+ const profile = profiles.find((item) => item?.name === body.profile);
1150
+ const root = profile?.anyFolder && body.rootIndex !== undefined
1151
+ ? profile.rootFolders?.find((item) => item.rootIndex === body.rootIndex && item.name === body.folder) : null;
1152
+ rememberLaunch(payload.id, body.profile, body.folder, body.rootIndex, body.folderPath, root?.path);
1153
+ const item = panes.get(payload.id);
1154
+ if (item) updateCard(item);
1155
+ applyOpen(payload.id, payload.open);
1156
+ }
1157
+
1158
+ function selectedProfile() {
1159
+ return profiles.find((profile) => profile && profile.name === profileSelect.value) || null;
1160
+ }
1161
+
1162
+ function renderFolders() {
1163
+ const profile = selectedProfile();
1164
+ const free = !!profile?.anyFolder;
1165
+ boundedFolder.hidden = free;
1166
+ anyFolder.hidden = !free;
1167
+ folderField.hidden = !(profile && profile.folderRequired);
1168
+ if (free) {
1169
+ const options = ShellPuppetDashboardFolders.anyOptions(recent, profile.name, profile.rootFolders);
1170
+ folderPathOptions.textContent = '';
1171
+ for (const value of options) {
1172
+ const option = document.createElement('option');
1173
+ option.value = value;
1174
+ folderPathOptions.append(option);
1175
+ }
1176
+ return;
1177
+ }
1178
+ const named = Array.isArray(profile?.folders) ? profile.folders : [];
1179
+ const rooted = Array.isArray(profile?.rootFolders) ? profile.rootFolders : [];
1180
+ const folders = [
1181
+ ...named.filter((folder) => folder && typeof folder.name === 'string').map((folder) => ({ name: folder.name, value: folder.name })),
1182
+ ...rooted.filter((folder) => folder && typeof folder.name === 'string' && Number.isInteger(folder.rootIndex)).map((folder) => ({ name: folder.name, value: `root:${folder.rootIndex}:${folder.name}`, rootIndex: folder.rootIndex })),
1183
+ ];
1184
+ const remembered = Array.isArray(recent[profile?.name]) ? recent[profile.name] : [];
1185
+ const ordered = ShellPuppetDashboardFolders.order(folders, recent, profile?.name);
1186
+ const query = folderFilter.value.trim().toLocaleLowerCase();
1187
+ const previous = folderSelect.value;
1188
+ folderSelect.textContent = '';
1189
+ recentFolders.textContent = '';
1190
+ folderField.hidden = !(profile && profile.folderRequired && folders.length > 0);
1191
+ for (const folder of ordered) {
1192
+ if (query && !folder.name.toLocaleLowerCase().includes(query)) continue;
1193
+ const option = document.createElement('option');
1194
+ option.value = folder.value;
1195
+ option.textContent = folder.rootIndex === undefined ? folder.name : `${folder.name} (root ${folder.rootIndex + 1})`;
1196
+ option.dataset.name = folder.name;
1197
+ if (folder.rootIndex !== undefined) option.dataset.rootIndex = String(folder.rootIndex);
1198
+ folderSelect.append(option);
1199
+ }
1200
+ if (Array.from(folderSelect.options).some((option) => option.value === previous)) folderSelect.value = previous;
1201
+ for (const folder of ordered.filter((choice) => remembered.includes(choice.value))) {
1202
+ const button = document.createElement('button');
1203
+ button.type = 'button';
1204
+ button.textContent = folder.rootIndex === undefined ? folder.name : `${folder.name} (root ${folder.rootIndex + 1})`;
1205
+ button.title = `Start in ${button.textContent}`;
1206
+ button.addEventListener('click', () => { folderFilter.value = ''; renderFolders(); folderSelect.value = folder.value; startSelected(); });
1207
+ recentFolders.append(button);
1208
+ }
1209
+ }
1210
+
1211
+ function renderProfiles() {
1212
+ profileSelect.textContent = '';
1213
+ for (const profile of profiles) {
1214
+ if (!profile || typeof profile.name !== 'string') continue;
1215
+ const option = document.createElement('option');
1216
+ option.value = profile.name;
1217
+ option.textContent = typeof profile.label === 'string' && profile.label !== '' ? profile.label : profile.name;
1218
+ profileSelect.append(option);
1219
+ }
1220
+ const loaded = profileSelect.options.length > 0;
1221
+ launcher.hidden = !loaded;
1222
+ watchOnly.hidden = loaded;
1223
+ renderFolders();
1224
+ }
1225
+
1226
+ async function loadProfiles() {
1227
+ let response;
1228
+ try {
1229
+ response = await fetch('/dashboard/profiles', { headers: { 'x-shellpuppet-csrf': proof } });
1230
+ } catch {
1231
+ showError('The profile list could not be loaded.');
1232
+ return;
1233
+ }
1234
+ if (!response.ok) {
1235
+ showError('The profile list could not be loaded.');
1236
+ return;
1237
+ }
1238
+ let body;
1239
+ try { body = await response.json(); } catch { body = {}; }
1240
+ profiles = Array.isArray(body.profiles) ? body.profiles : [];
1241
+ const problems = Array.isArray(body.problems) ? body.problems.filter((line) => typeof line === 'string') : [];
1242
+ profileProblems.textContent = problems.join(' ');
1243
+ profileProblems.hidden = problems.length === 0;
1244
+ renderProfiles();
1245
+ }
1246
+
1247
+ function startSelected() {
1248
+ const profile = selectedProfile();
1249
+ if (profile === null) return;
1250
+ const body = { profile: profile.name };
1251
+ if (profile.folderRequired) {
1252
+ if (profile.anyFolder) {
1253
+ if (folderPath.value === '') { showError('Choose a folder.'); return; }
1254
+ const rootChoice = profile.rootFolders?.find((item) => item.path === folderPath.value);
1255
+ if (rootChoice) { body.folder = rootChoice.name; body.rootIndex = rootChoice.rootIndex; }
1256
+ else body.folderPath = folderPath.value;
1257
+ void postLaunch(body);
1258
+ return;
1259
+ }
1260
+ if (folderSelect.value === '') { showError('Choose a folder.'); return; }
1261
+ const option = folderSelect.selectedOptions[0];
1262
+ if (!option) { showError('Choose a folder.'); return; }
1263
+ body.folder = option.dataset.name;
1264
+ if (option.dataset.rootIndex !== undefined) body.rootIndex = Number(option.dataset.rootIndex);
1265
+ }
1266
+ void postLaunch(body);
1267
+ }
1268
+
1269
+ async function browseForFolder() {
1270
+ const profile = selectedProfile();
1271
+ if (!profile?.anyFolder) return;
1272
+ browseFolder.disabled = true;
1273
+ try {
1274
+ const response = await fetch('/dashboard/folder-picker', {
1275
+ method: 'POST',
1276
+ headers: { 'content-type': 'application/json', 'x-shellpuppet-csrf': proof },
1277
+ body: JSON.stringify({ profile: profile.name }),
1278
+ });
1279
+ if (response.status === 204) return;
1280
+ const payload = await response.json();
1281
+ if (!response.ok) { showError(payload.error || 'The folder picker failed.'); return; }
1282
+ if (typeof payload.path === 'string') folderPath.value = payload.path;
1283
+ } catch { showError('The folder picker failed.'); }
1284
+ finally { browseFolder.disabled = false; }
1285
+ }
1286
+
1287
+ function restartSession(id) {
1288
+ const body = launchBody(launches[id]);
1289
+ if (body === null) return;
1290
+ void postLaunch(body);
1291
+ }
1292
+
1293
+ function dismiss(id) {
1294
+ dismissed.add(id);
1295
+ dropLaunch(id);
1296
+ const item = panes.get(id);
1297
+ if (item) { deactivate(item); item.card.remove(); panes.delete(id); }
1298
+ order = order.filter((entry) => entry !== id);
1299
+ pins = pins.filter((entry) => entry !== id);
1300
+ if (selected === id) selected = order.find((entry) => panes.has(entry)) || null;
1301
+ if (focusId === id) focusId = null;
1302
+ if (enlarged === id) enlarged = null;
1303
+ releasePop(id);
1304
+ persist();
1305
+ arrange('dismiss');
1306
+ updateAttention();
1307
+ }
1308
+
1309
+ function onWindowMessage(event) {
1310
+ const data = event.data;
1311
+ if (typeof data !== 'object' || data === null || data.token === windowToken) return;
1312
+ if (data.type === 'preferences' && typeof data.autoFit === 'boolean' &&
1313
+ (data.fontSize === null || (Number.isInteger(data.fontSize) && data.fontSize >= 8 && data.fontSize <= 32))) {
1314
+ autoFit = data.autoFit;
1315
+ setFontSize(data.fontSize, false);
1316
+ return;
1317
+ }
1318
+ if (data.type === 'window-roster' && popSelf === null && data.window &&
1319
+ validWindowId(data.window.id) && validWindowId(data.window.instance) &&
1320
+ validWindowId(data.window.document) &&
1321
+ Number.isFinite(data.window.rank) &&
1322
+ Number.isFinite(data.window.openedAt) &&
1323
+ (data.window.loadAt === undefined || Number.isFinite(data.window.loadAt)) &&
1324
+ Number.isFinite(data.window.width) && Number.isFinite(data.window.height)) {
1325
+ const now = Date.now();
1326
+ for (const [pair, closedAt] of goneWindows) if (now - closedAt > 600_000) goneWindows.delete(pair);
1327
+ if (goneWindows.has(JSON.stringify([data.window.id, data.window.instance]))) return;
1328
+ const pair = windowPair(data.window.id, data.window.instance);
1329
+ for (const [existingPair, entry] of windows) {
1330
+ if (existingPair !== pair && entry.id === data.window.id &&
1331
+ entry.document === data.window.document && entry.openedAt > data.window.openedAt) return;
1332
+ }
1333
+ for (const [existingPair, entry] of windows) {
1334
+ if (existingPair === pair || entry.id !== data.window.id || entry.document !== data.window.document) continue;
1335
+ if (entry.openedAt < data.window.openedAt) {
1336
+ windows.delete(existingPair);
1337
+ lastSeen.delete(existingPair);
1338
+ }
1339
+ }
1340
+ for (const watch of childWatches.values()) {
1341
+ if (watch.id !== data.window.id || watch.child.closed || watch.pair === pair) continue;
1342
+ try {
1343
+ if (watch.child.__dashboardDocumentToken !== data.window.document) continue;
1344
+ } catch { continue; }
1345
+ childWatches.delete(watch.pair);
1346
+ watch.pair = pair;
1347
+ watch.instance = data.window.instance;
1348
+ childWatches.set(pair, watch);
1349
+ }
1350
+ const fresh = !windows.has(pair);
1351
+ const previous = windows.get(pair);
1352
+ windows.delete(windowPair(data.window.id, null));
1353
+ lastSeen.delete(windowPair(data.window.id, null));
1354
+ windows.set(pair, data.window);
1355
+ lastSeen.set(pair, Date.now());
1356
+ if (fresh) advertise();
1357
+ if (fresh || previous.key !== data.window.key) renderScreens();
1358
+ publishAssignment();
1359
+ renderShareCount();
1360
+ return;
1361
+ }
1362
+ if (data.type === 'window-leave' && validWindowId(data.id) && validWindowId(data.instance)) {
1363
+ markWindowGone(data.id, data.instance);
1364
+ return;
1365
+ }
1366
+ if (data.type === 'window-assignment' && popSelf === null && windows.size > 1 &&
1367
+ data.owner === windowPair(orderedWindows()[0]?.id, orderedWindows()[0]?.instance) &&
1368
+ Array.isArray(data.byWindow?.[ownPair()])) {
1369
+ applyAssignment(data.byWindow[ownPair()]);
1370
+ return;
1371
+ }
1372
+ if (typeof data.id !== 'string') return;
1373
+ if (data.type === 'pop-claim') {
1374
+ if (data.id === popSelf) return;
1375
+ popped.add(data.id);
1376
+ arrange('pop claim');
1377
+ } else if (data.type === 'pop-release') {
1378
+ if (data.id === popSelf) return;
1379
+ releasePop(data.id);
1380
+ }
1381
+ }
1382
+
1383
+ for (const name of ['auto', 'grid', 'focus']) {
1384
+ document.getElementById(name).addEventListener('click', () => {
1385
+ assignmentSettleUntil = 0;
1386
+ assignmentSettleStartedAt = 0;
1387
+ if (name === 'focus') focusId = selected;
1388
+ if (name === 'auto' || name === 'grid') resetTracks();
1389
+ mode = name; enlarged = null; persist(); arrange('mode');
1390
+ if (name === 'focus' && !autoFit) {
1391
+ const items = shown();
1392
+ const primary = pins.find((id) => items.some((item) => item.id === id)) || focusId;
1393
+ window.requestAnimationFrame(() => panes.get(primary)?.client?.fitGrid());
1394
+ }
1395
+ });
1396
+ }
1397
+ strip.addEventListener('scroll', syncVisibility);
1398
+ document.getElementById('auto-fit').addEventListener('click', () => {
1399
+ assignmentSettleUntil = 0;
1400
+ assignmentSettleStartedAt = 0;
1401
+ autoFit = !autoFit;
1402
+ renderPreferences(); persist(); scheduleAutoFit(); broadcastPreferences();
1403
+ });
1404
+ document.getElementById('text-smaller').addEventListener('click', () => setFontSize(Math.max(8, (fontSize ?? 13) - 1)));
1405
+ document.getElementById('text-auto').addEventListener('click', () => setFontSize(null));
1406
+ document.getElementById('text-larger').addEventListener('click', () => setFontSize(Math.min(32, (fontSize ?? 13) + 1)));
1407
+ document.getElementById('error-close').addEventListener('click', closeError);
1408
+ document.getElementById('shortcut').addEventListener('click', () => {
1409
+ choosingPrefix = true;
1410
+ document.getElementById('shortcut').textContent = 'Press Ctrl+Shift and a letter';
1411
+ });
1412
+ attentionCount.addEventListener('click', () => {
1413
+ const waiting = shown().find((item) => attention(item) && item.id !== selected) || shown().find(attention);
1414
+ if (waiting) select(waiting.id);
1415
+ });
1416
+ profileSelect.addEventListener('change', renderFolders);
1417
+ folderFilter.addEventListener('input', renderFolders);
1418
+ folderFilter.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); startSelected(); } });
1419
+ folderPath.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); startSelected(); } });
1420
+ browseFolder.addEventListener('click', () => { void browseForFolder(); });
1421
+ document.getElementById('start').addEventListener('click', startSelected);
1422
+ document.getElementById('fullscreen').addEventListener('click', () => {
1423
+ const next = document.fullscreenElement
1424
+ ? document.exitFullscreen()
1425
+ : document.documentElement.requestFullscreen();
1426
+ void Promise.resolve(next).catch(() => showError('The browser did not make this window full screen.'));
1427
+ });
1428
+ if (channel !== null) channel.onmessage = onWindowMessage;
1429
+ window.addEventListener('resize', () => { advertise(); arrange('window resize'); });
1430
+ window.addEventListener('beforeunload', () => {
1431
+ endActiveDivider?.();
1432
+ leaveWindow();
1433
+ clearTimeout(retry);
1434
+ clearTimeout(autoFitTimer);
1435
+ feed?.close();
1436
+ for (const item of panes.values()) deactivate(item);
1437
+ for (const watch of popWatches.values()) clearInterval(watch);
1438
+ for (const watch of childWatches.values()) clearInterval(watch.timer);
1439
+ clearInterval(rosterTimer);
1440
+ });
1441
+ window.addEventListener('pagehide', () => {
1442
+ endActiveDivider?.();
1443
+ leaveWindow();
1444
+ if (popSelf === null || channel === null) return;
1445
+ channel.postMessage({ type: 'pop-release', id: popSelf, token: windowToken });
1446
+ });
1447
+ function leaveWindow() {
1448
+ if (popSelf !== null || windowLeft) return;
1449
+ windowLeft = true;
1450
+ channel?.postMessage({ type: 'window-leave', id: windowId, instance: windowInstance, token: windowToken });
1451
+ }
1452
+ document.addEventListener('keydown', (event) => {
1453
+ if (choosingPrefix) {
1454
+ event.preventDefault(); event.stopPropagation();
1455
+ choosingPrefix = false;
1456
+ if (event.ctrlKey && event.shiftKey && /^[a-z]$/i.test(event.key)) {
1457
+ prefix = event.key.toLowerCase();
1458
+ persist();
1459
+ closeError();
1460
+ } else if (event.key === 'Escape') {
1461
+ closeVisibleError();
1462
+ } else {
1463
+ showError('Choose Ctrl+Shift and a letter.');
1464
+ }
1465
+ showPrefix();
1466
+ return;
1467
+ }
1468
+ if (event.ctrlKey && event.shiftKey && event.key.toLowerCase() === prefix) {
1469
+ event.preventDefault(); event.stopPropagation(); navigation = true; return;
1470
+ }
1471
+ const terminalFocused = document.activeElement?.closest('.pane-term') !== null;
1472
+ if (event.key === 'Escape' && !terminalFocused && closeVisibleError()) {
1473
+ event.preventDefault(); event.stopPropagation(); return;
1474
+ }
1475
+ if (event.key === 'Escape' && enlarged && (navigation || !terminalFocused)) {
1476
+ event.preventDefault(); event.stopPropagation(); navigation = false;
1477
+ panes.get(enlarged)?.enlarge.click();
1478
+ return;
1479
+ }
1480
+ // Terminal mode: the focused pane's terminal receives the key, including Ctrl+\.
1481
+ if (!navigation) return;
1482
+ // A Ctrl+Shift chord for another letter is not this prefix, so the page
1483
+ // leaves it. Every other key while navigation is active is consumed.
1484
+ if (event.ctrlKey && event.shiftKey && /^[a-z]$/i.test(event.key) && event.key.toLowerCase() !== prefix) return;
1485
+ event.preventDefault(); event.stopPropagation();
1486
+ const key = event.key.toLowerCase();
1487
+ const list = shown();
1488
+ const index = list.findIndex((p) => p.id === selected);
1489
+ if (key === 'enter' || key === 'escape') { navigation = false; if (key === 'enter') select(selected, true); }
1490
+ else if (list.length === 0) return;
1491
+ else if (key === 'arrowright' || key === 'arrowdown') select(list[(index + 1) % list.length]?.id);
1492
+ else if (key === 'arrowleft' || key === 'arrowup') select(list[(index - 1 + list.length) % list.length]?.id);
1493
+ else if (/^[1-9]$/.test(key)) select(list[Number(key) - 1]?.id);
1494
+ else if (key === 'j') select(list.find((p) => attention(p) && p.id !== selected)?.id || list.find(attention)?.id);
1495
+ else if (key === 'p') panes.get(selected)?.pin.click();
1496
+ else if (key === 'f') panes.get(selected)?.fit.click();
1497
+ else if (key === 'm') panes.get(selected)?.enlarge.click();
1498
+ else if (key === '?') document.getElementById('help').hidden = !document.getElementById('help').hidden;
1499
+ }, true);
1500
+ showPrefix();
1501
+ renderPreferences();
1502
+ if (popSelf === null) {
1503
+ advertise();
1504
+ rosterTimer = setInterval(() => {
1505
+ advertise();
1506
+ for (const [pair, seen] of lastSeen) {
1507
+ if (pair !== ownPair() && Date.now() - seen > 180_000) {
1508
+ const entry = windows.get(pair);
1509
+ if (entry) removeWindow(entry.id, entry.instance);
1510
+ }
1511
+ }
1512
+ }, 1000);
1513
+ renderScreens();
1514
+ void discoverScreens();
1515
+ renderShareCount();
1516
+ }
1517
+ if (popSelf !== null) {
1518
+ document.getElementById('fullscreen').hidden = false;
1519
+ if (channel !== null) channel.postMessage({ type: 'pop-claim', id: popSelf, token: windowToken });
1520
+ }
1521
+ if (proof) { void loadProfiles(); connect(); }
1522
+ else showError('Start ShellPuppet from its shortcut or with shellpuppet desktop');
1523
+ })();