shellpuppet 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +63 -16
  2. package/dist/agents/agy/index.d.ts +2 -0
  3. package/dist/agents/agy/index.js +11 -0
  4. package/dist/agents/agy/index.js.map +1 -0
  5. package/dist/agents/agy/nudge.d.ts +2 -0
  6. package/dist/agents/agy/nudge.js +29 -0
  7. package/dist/agents/agy/nudge.js.map +1 -0
  8. package/dist/agents/agy/reading.d.ts +2 -0
  9. package/dist/agents/agy/reading.js +28 -0
  10. package/dist/agents/agy/reading.js.map +1 -0
  11. package/dist/agents/barNudge.d.ts +9 -0
  12. package/dist/agents/barNudge.js +21 -0
  13. package/dist/agents/barNudge.js.map +1 -0
  14. package/dist/agents/claude/index.d.ts +2 -0
  15. package/dist/agents/claude/index.js +31 -0
  16. package/dist/agents/claude/index.js.map +1 -0
  17. package/dist/agents/claude/nudge.d.ts +2 -0
  18. package/dist/agents/claude/nudge.js +38 -0
  19. package/dist/agents/claude/nudge.js.map +1 -0
  20. package/dist/agents/claude/prompts.d.ts +9 -0
  21. package/dist/agents/claude/prompts.js +16 -0
  22. package/dist/agents/claude/prompts.js.map +1 -0
  23. package/dist/agents/claude/reading.d.ts +2 -0
  24. package/dist/agents/claude/reading.js +25 -0
  25. package/dist/agents/claude/reading.js.map +1 -0
  26. package/dist/agents/codex/index.d.ts +2 -0
  27. package/dist/agents/codex/index.js +28 -0
  28. package/dist/agents/codex/index.js.map +1 -0
  29. package/dist/agents/codex/nudge.d.ts +2 -0
  30. package/dist/agents/codex/nudge.js +35 -0
  31. package/dist/agents/codex/nudge.js.map +1 -0
  32. package/dist/agents/codex/prompts.d.ts +9 -0
  33. package/dist/agents/codex/prompts.js +14 -0
  34. package/dist/agents/codex/prompts.js.map +1 -0
  35. package/dist/agents/codex/reading.d.ts +2 -0
  36. package/dist/agents/codex/reading.js +22 -0
  37. package/dist/agents/codex/reading.js.map +1 -0
  38. package/dist/agents/generic/index.d.ts +3 -0
  39. package/dist/agents/generic/index.js +9 -0
  40. package/dist/agents/generic/index.js.map +1 -0
  41. package/dist/agents/generic/prompts.d.ts +2 -0
  42. package/dist/agents/generic/prompts.js +10 -0
  43. package/dist/agents/generic/prompts.js.map +1 -0
  44. package/dist/agents/grok/actionBox.d.ts +13 -0
  45. package/dist/agents/grok/actionBox.js +127 -0
  46. package/dist/agents/grok/actionBox.js.map +1 -0
  47. package/dist/agents/grok/index.d.ts +2 -0
  48. package/dist/agents/grok/index.js +20 -0
  49. package/dist/agents/grok/index.js.map +1 -0
  50. package/dist/agents/grok/nudge.d.ts +2 -0
  51. package/dist/agents/grok/nudge.js +76 -0
  52. package/dist/agents/grok/nudge.js.map +1 -0
  53. package/dist/agents/grok/prompts.d.ts +4 -0
  54. package/dist/agents/grok/prompts.js +89 -0
  55. package/dist/agents/grok/prompts.js.map +1 -0
  56. package/dist/agents/grok/reading.d.ts +2 -0
  57. package/dist/agents/grok/reading.js +49 -0
  58. package/dist/agents/grok/reading.js.map +1 -0
  59. package/dist/agents/grok/readingRules.d.ts +2 -0
  60. package/dist/agents/grok/readingRules.js +44 -0
  61. package/dist/agents/grok/readingRules.js.map +1 -0
  62. package/dist/agents/index.d.ts +28 -0
  63. package/dist/agents/index.js +46 -0
  64. package/dist/agents/index.js.map +1 -0
  65. package/dist/agents/input.d.ts +2 -0
  66. package/dist/agents/input.js +9 -0
  67. package/dist/agents/input.js.map +1 -0
  68. package/dist/agents/mimo/index.d.ts +2 -0
  69. package/dist/agents/mimo/index.js +13 -0
  70. package/dist/agents/mimo/index.js.map +1 -0
  71. package/dist/agents/mimo/nudge.d.ts +3 -0
  72. package/dist/agents/mimo/nudge.js +59 -0
  73. package/dist/agents/mimo/nudge.js.map +1 -0
  74. package/dist/agents/mimo/prompts.d.ts +2 -0
  75. package/dist/agents/mimo/prompts.js +40 -0
  76. package/dist/agents/mimo/prompts.js.map +1 -0
  77. package/dist/agents/mimo/reading.d.ts +2 -0
  78. package/dist/agents/mimo/reading.js +31 -0
  79. package/dist/agents/mimo/reading.js.map +1 -0
  80. package/dist/agents/mimo/readingRules.d.ts +2 -0
  81. package/dist/agents/mimo/readingRules.js +79 -0
  82. package/dist/agents/mimo/readingRules.js.map +1 -0
  83. package/dist/agents/mimo/stalls.d.ts +2 -0
  84. package/dist/agents/mimo/stalls.js +81 -0
  85. package/dist/agents/mimo/stalls.js.map +1 -0
  86. package/dist/agents/muse/index.d.ts +2 -0
  87. package/dist/agents/muse/index.js +20 -0
  88. package/dist/agents/muse/index.js.map +1 -0
  89. package/dist/agents/muse/input.d.ts +3 -0
  90. package/dist/agents/muse/input.js +7 -0
  91. package/dist/agents/muse/input.js.map +1 -0
  92. package/dist/agents/muse/nudge.d.ts +2 -0
  93. package/dist/agents/muse/nudge.js +33 -0
  94. package/dist/agents/muse/nudge.js.map +1 -0
  95. package/dist/agents/muse/prompts.d.ts +14 -0
  96. package/dist/agents/muse/prompts.js +132 -0
  97. package/dist/agents/muse/prompts.js.map +1 -0
  98. package/dist/agents/muse/reading.d.ts +2 -0
  99. package/dist/agents/muse/reading.js +33 -0
  100. package/dist/agents/muse/reading.js.map +1 -0
  101. package/dist/agents/muse/readingRules.d.ts +2 -0
  102. package/dist/agents/muse/readingRules.js +49 -0
  103. package/dist/agents/muse/readingRules.js.map +1 -0
  104. package/dist/agents/nudgeReading.d.ts +74 -0
  105. package/dist/agents/nudgeReading.js +262 -0
  106. package/dist/agents/nudgeReading.js.map +1 -0
  107. package/dist/agents/opencode/index.d.ts +2 -0
  108. package/dist/agents/opencode/index.js +21 -0
  109. package/dist/agents/opencode/index.js.map +1 -0
  110. package/dist/agents/opencode/nudge.d.ts +6 -0
  111. package/dist/agents/opencode/nudge.js +187 -0
  112. package/dist/agents/opencode/nudge.js.map +1 -0
  113. package/dist/agents/opencode/prompts.d.ts +6 -0
  114. package/dist/agents/opencode/prompts.js +198 -0
  115. package/dist/agents/opencode/prompts.js.map +1 -0
  116. package/dist/agents/opencode/reading.d.ts +2 -0
  117. package/dist/agents/opencode/reading.js +29 -0
  118. package/dist/agents/opencode/reading.js.map +1 -0
  119. package/dist/agents/opencode/stalls.d.ts +3 -0
  120. package/dist/agents/opencode/stalls.js +14 -0
  121. package/dist/agents/opencode/stalls.js.map +1 -0
  122. package/dist/agents/qoder/index.d.ts +2 -0
  123. package/dist/agents/qoder/index.js +12 -0
  124. package/dist/agents/qoder/index.js.map +1 -0
  125. package/dist/agents/qoder/nudge.d.ts +2 -0
  126. package/dist/agents/qoder/nudge.js +16 -0
  127. package/dist/agents/qoder/nudge.js.map +1 -0
  128. package/dist/agents/qoder/prompts.d.ts +2 -0
  129. package/dist/agents/qoder/prompts.js +6 -0
  130. package/dist/agents/qoder/prompts.js.map +1 -0
  131. package/dist/agents/qoder/reading.d.ts +2 -0
  132. package/dist/agents/qoder/reading.js +41 -0
  133. package/dist/agents/qoder/reading.js.map +1 -0
  134. package/dist/agents/types.d.ts +187 -0
  135. package/dist/agents/types.js +2 -0
  136. package/dist/agents/types.js.map +1 -0
  137. package/dist/cli/index.js +185 -19
  138. package/dist/cli/index.js.map +1 -1
  139. package/dist/client/http.d.ts +5 -1
  140. package/dist/client/http.js +39 -9
  141. package/dist/client/http.js.map +1 -1
  142. package/dist/core/dialogs.d.ts +2 -4
  143. package/dist/core/dialogs.js +6 -12
  144. package/dist/core/dialogs.js.map +1 -1
  145. package/dist/core/mailbox.d.ts +222 -0
  146. package/dist/core/mailbox.js +545 -0
  147. package/dist/core/mailbox.js.map +1 -0
  148. package/dist/core/manager.d.ts +3 -0
  149. package/dist/core/manager.js +37 -2
  150. package/dist/core/manager.js.map +1 -1
  151. package/dist/core/messageText.d.ts +2 -0
  152. package/dist/core/messageText.js +6 -0
  153. package/dist/core/messageText.js.map +1 -0
  154. package/dist/core/nudge.d.ts +37 -0
  155. package/dist/core/nudge.js +57 -0
  156. package/dist/core/nudge.js.map +1 -0
  157. package/dist/core/promptDetector.d.ts +14 -12
  158. package/dist/core/promptDetector.js +113 -363
  159. package/dist/core/promptDetector.js.map +1 -1
  160. package/dist/core/promptText.d.ts +1 -0
  161. package/dist/core/promptText.js +4 -0
  162. package/dist/core/promptText.js.map +1 -0
  163. package/dist/core/readiness.d.ts +14 -0
  164. package/dist/core/readiness.js +95 -0
  165. package/dist/core/readiness.js.map +1 -0
  166. package/dist/core/reasoning.d.ts +68 -7
  167. package/dist/core/reasoning.js +572 -325
  168. package/dist/core/reasoning.js.map +1 -1
  169. package/dist/core/renderer.d.ts +63 -3
  170. package/dist/core/renderer.js +368 -42
  171. package/dist/core/renderer.js.map +1 -1
  172. package/dist/core/selection.d.ts +1 -1
  173. package/dist/core/selection.js +3 -3
  174. package/dist/core/selection.js.map +1 -1
  175. package/dist/core/session.d.ts +165 -13
  176. package/dist/core/session.js +998 -84
  177. package/dist/core/session.js.map +1 -1
  178. package/dist/core/types.d.ts +60 -4
  179. package/dist/core/types.js +41 -0
  180. package/dist/core/types.js.map +1 -1
  181. package/dist/core/waiter.d.ts +9 -2
  182. package/dist/core/waiter.js +35 -10
  183. package/dist/core/waiter.js.map +1 -1
  184. package/dist/daemon/audit.d.ts +1 -1
  185. package/dist/daemon/audit.js +2 -1
  186. package/dist/daemon/audit.js.map +1 -1
  187. package/dist/daemon/config.d.ts +42 -0
  188. package/dist/daemon/config.js +159 -4
  189. package/dist/daemon/config.js.map +1 -1
  190. package/dist/daemon/folderPicker.js +21 -2
  191. package/dist/daemon/folderPicker.js.map +1 -1
  192. package/dist/daemon/homeOwner.d.ts +15 -0
  193. package/dist/daemon/homeOwner.js +106 -0
  194. package/dist/daemon/homeOwner.js.map +1 -0
  195. package/dist/daemon/index.js +10 -6
  196. package/dist/daemon/index.js.map +1 -1
  197. package/dist/daemon/launchProfiles.d.ts +5 -0
  198. package/dist/daemon/launchProfiles.js +42 -40
  199. package/dist/daemon/launchProfiles.js.map +1 -1
  200. package/dist/daemon/nudgeScheduler.d.ts +21 -0
  201. package/dist/daemon/nudgeScheduler.js +61 -0
  202. package/dist/daemon/nudgeScheduler.js.map +1 -0
  203. package/dist/daemon/paths.d.ts +20 -16
  204. package/dist/daemon/paths.js +137 -49
  205. package/dist/daemon/paths.js.map +1 -1
  206. package/dist/daemon/restartSource.d.ts +7 -0
  207. package/dist/daemon/restartSource.js +89 -0
  208. package/dist/daemon/restartSource.js.map +1 -0
  209. package/dist/daemon/screenshot.d.ts +4 -1
  210. package/dist/daemon/screenshot.js +45 -7
  211. package/dist/daemon/screenshot.js.map +1 -1
  212. package/dist/daemon/server.d.ts +70 -13
  213. package/dist/daemon/server.js +1596 -294
  214. package/dist/daemon/server.js.map +1 -1
  215. package/dist/daemon/sessionFeed.js +4 -1
  216. package/dist/daemon/sessionFeed.js.map +1 -1
  217. package/dist/mcp/config.js +2 -1
  218. package/dist/mcp/config.js.map +1 -1
  219. package/dist/mcp/index.js +12 -2
  220. package/dist/mcp/index.js.map +1 -1
  221. package/dist/mcp/tools.d.ts +21 -1
  222. package/dist/mcp/tools.js +213 -28
  223. package/dist/mcp/tools.js.map +1 -1
  224. package/dist/viewer/dashboard-folders.js +7 -1
  225. package/dist/viewer/dashboard-layout.js +6 -52
  226. package/dist/viewer/dashboard.css +20 -4
  227. package/dist/viewer/dashboard.html +12 -3
  228. package/dist/viewer/dashboard.js +549 -382
  229. package/dist/viewer/pane.js +744 -136
  230. package/dist/viewer/viewer.css +1 -1
  231. package/dist/viewer/viewer.js +3 -1
  232. package/package.json +1 -1
@@ -9,8 +9,18 @@
9
9
  const error = document.getElementById('error');
10
10
  const connection = document.getElementById('connection');
11
11
  const attentionCount = document.getElementById('attention-count');
12
+ const messagesToggle = document.getElementById('messages-toggle');
13
+ const messagesView = document.getElementById('messages-view');
14
+ const messagesFilter = document.getElementById('messages-filter');
15
+ const messagesList = document.getElementById('messages-list');
16
+ const messagesDetail = document.getElementById('messages-detail');
17
+ const messagesOff = document.getElementById('messages-off');
18
+ const messagesEmpty = document.getElementById('messages-empty');
12
19
  const shareCount = document.getElementById('share-count');
13
20
  const profileSelect = document.getElementById('profile');
21
+ const resumeField = document.getElementById('resume-field');
22
+ const resumeId = document.getElementById('resume-id');
23
+ const sessionName = document.getElementById('session-name');
14
24
  const folderField = document.getElementById('folder-field');
15
25
  const folderSelect = document.getElementById('folder');
16
26
  const folderFilter = document.getElementById('folder-filter');
@@ -28,11 +38,156 @@
28
38
  main.id = 'main-pane';
29
39
  strip.id = 'strip';
30
40
  const panes = new Map();
41
+ let messageEntries = [];
42
+ let unreadCounts = {};
43
+ let messageGroups = [];
44
+ let messagingEnabled = false;
45
+ let messageSelection = null;
46
+ let messageFetching = false;
47
+ let messageDirty = false;
48
+ let messageTimer = null;
49
+ let lastMessageFetch = 0;
50
+ let messageRetryDelay = 0;
51
+ let messageFilter = '';
52
+ // eslint-disable-next-line no-control-regex
53
+ const visibleMessageText = (value) => value.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2060\u2066-\u2069\ufeff]/g,
54
+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`);
55
+
56
+ function unreadCount(id) {
57
+ return unreadCounts[id] ?? 0;
58
+ }
59
+ function renderMessages() {
60
+ const participantLabel = (participant) => `${participant.name}${participant.kind === 'claim' || participant.id.startsWith('claim_') ? ' (outside claim)' : ''}`;
61
+ const options = [{ value: '', label: 'All' }];
62
+ const participants = new Map();
63
+ for (const entry of messageEntries) {
64
+ participants.set(entry.from.id, participantLabel(entry.from));
65
+ participants.set(entry.to.id, participantLabel(entry.to));
66
+ }
67
+ for (const [id, name] of [...participants].sort((a, b) => a[1].localeCompare(b[1])))
68
+ options.push({ value: `session:${id}`, label: `${name} (${id})` });
69
+ for (const group of messageGroups) options.push({ value: `group:${group.group}`, label: `Group: ${group.group}` });
70
+ // A badge can open the view before the history arrives; keep its filter
71
+ // rather than dropping it because no row has named that session yet.
72
+ if (messageFilter && !options.some((option) => option.value === messageFilter)) {
73
+ const id = messageFilter.startsWith('session:') ? messageFilter.slice(8) : messageFilter;
74
+ const pane = panes.get(id);
75
+ options.push({ value: messageFilter, label: pane ? `${pane.label.textContent} (${id})` : id });
76
+ }
77
+ messagesFilter.replaceChildren();
78
+ for (const option of options) {
79
+ const node = document.createElement('option');
80
+ node.value = option.value;
81
+ node.textContent = option.label;
82
+ messagesFilter.append(node);
83
+ }
84
+ messagesFilter.value = messageFilter;
85
+ if (messagesFilter.value !== messageFilter) messageFilter = '';
86
+ const filtered = messageEntries.filter((entry) => {
87
+ if (!messageFilter) return true;
88
+ if (messageFilter.startsWith('session:')) {
89
+ const id = messageFilter.slice(8);
90
+ return entry.from.id === id || entry.to.id === id;
91
+ }
92
+ const group = messageGroups.find((item) => item.group === messageFilter.slice(6));
93
+ return group?.members.includes(entry.from.name) || group?.members.includes(entry.to.name) ||
94
+ group?.roles?.includes(entry.from.role) || group?.roles?.includes(panes.get(entry.to.id)?.summary.role);
95
+ }).sort((a, b) => b.time - a.time || b.id.localeCompare(a.id));
96
+ messagesOff.hidden = messagingEnabled;
97
+ messagesEmpty.hidden = !messagingEnabled || filtered.length > 0;
98
+ document.getElementById('messages-content').hidden = !messagingEnabled || filtered.length === 0;
99
+ const focusedId = document.activeElement?.dataset?.messageId;
100
+ messagesList.replaceChildren();
101
+ for (const entry of filtered) {
102
+ const row = document.createElement('button');
103
+ row.type = 'button';
104
+ row.className = 'message-row';
105
+ row.dataset.messageId = entry.id;
106
+ row.setAttribute('aria-current', String(entry.id === messageSelection));
107
+ row.textContent = `${participantLabel(entry.from)} → ${participantLabel(entry.to)} · ${new Date(entry.time).toLocaleString()} · ${entry.id} · ${entry.state}`;
108
+ row.addEventListener('click', () => { messageSelection = entry.id; renderMessages(); });
109
+ const listItem = document.createElement('li');
110
+ listItem.append(row);
111
+ messagesList.append(listItem);
112
+ }
113
+ const selectedEntry = filtered.find((entry) => entry.id === messageSelection);
114
+ messagesDetail.textContent = selectedEntry
115
+ ? visibleMessageText(selectedEntry.text ?? '') : 'Select a message to read it.';
116
+ if (focusedId) messagesList.querySelectorAll('button').forEach((row) => {
117
+ if (row.dataset.messageId === focusedId) row.focus();
118
+ });
119
+ }
120
+ function updateMessageBadge(item) {
121
+ const count = unreadCount(item.id);
122
+ item.messageCount.hidden = count === 0;
123
+ item.messageCount.textContent = count ? `${count} ${count === 1 ? 'message' : 'messages'}` : '';
124
+ item.messageCount.setAttribute('aria-label', `${count} unread messages for ${item.label.textContent}`);
125
+ }
126
+ async function loadMessages() {
127
+ messageTimer = null;
128
+ if (messageFetching || !messageDirty) return;
129
+ messageDirty = false;
130
+ messageFetching = true;
131
+ lastMessageFetch = Date.now();
132
+ const full = !messagesView.hidden;
133
+ try {
134
+ const response = await fetch(`/dashboard/messages${full ? '' : '?summary=1'}`, {
135
+ headers: { 'x-shellpuppet-csrf': proof },
136
+ });
137
+ if (!response.ok) throw new Error('The message history could not be read.');
138
+ const result = await response.json();
139
+ messagingEnabled = result.enabled === true;
140
+ unreadCounts = result.counts;
141
+ for (const item of panes.values()) updateMessageBadge(item);
142
+ if (full && !messagesView.hidden) {
143
+ messageEntries = result.messages;
144
+ messageGroups = result.groups;
145
+ renderMessages();
146
+ }
147
+ if (full !== !messagesView.hidden) messageDirty = true;
148
+ messageRetryDelay = 0;
149
+ } catch {
150
+ showError('The message history could not be read.');
151
+ // Keep the update pending: the socket may stay open with no further
152
+ // event, so retry rather than leave the badge stale.
153
+ messageDirty = true;
154
+ messageRetryDelay = Math.min(messageRetryDelay * 2 || 1000, 30_000);
155
+ }
156
+ finally { messageFetching = false; if (messageDirty) scheduleMessageRefresh(); }
157
+ }
158
+ function scheduleMessageRefresh() {
159
+ messageDirty = true;
160
+ if (messageFetching || messageTimer !== null) return;
161
+ messageTimer = setTimeout(() => { void loadMessages(); },
162
+ Math.max(messageRetryDelay, 250 - (Date.now() - lastMessageFetch)));
163
+ }
164
+ function openMessages(filter = '') {
165
+ messageFilter = filter;
166
+ messagesView.hidden = false;
167
+ root.hidden = true;
168
+ empty.hidden = true;
169
+ messagesToggle.setAttribute('aria-expanded', 'true');
170
+ messagesToggle.classList.add('active');
171
+ renderMessages();
172
+ messagesFilter.focus();
173
+ scheduleMessageRefresh();
174
+ }
175
+ function closeMessages() {
176
+ messagesView.hidden = true;
177
+ root.hidden = false;
178
+ empty.hidden = shown().length > 0;
179
+ messagesToggle.setAttribute('aria-expanded', 'false');
180
+ messagesToggle.classList.remove('active');
181
+ messagesToggle.focus();
182
+ messageEntries = [];
183
+ scheduleMessageRefresh();
184
+ }
31
185
  const PREF = 'shellpuppet.dashboard';
32
186
  const TRACK_PREF = 'shellpuppet.dashboard.tracks';
33
187
  const LAUNCH_PREF = 'shellpuppet.dashboard.launches';
34
188
  const RECENT_PREF = 'shellpuppet.dashboard.recentFolders';
35
189
  const NAME = /^[a-z][a-z0-9-]{0,31}$/;
190
+ const SESSION_NAME = /^[A-Za-z0-9._-]{1,40}$/;
36
191
  let saved = {};
37
192
  try { saved = JSON.parse(window.localStorage.getItem(PREF) || '{}') || {}; } catch { /* Preferences are optional. */ }
38
193
  let order = Array.isArray(saved.order) ? saved.order.filter((id) => typeof id === 'string') : [];
@@ -44,6 +199,7 @@
44
199
  ? saved.fontSize : saved.fontSize === null ? null
45
200
  : Number.isInteger(configuredFont) && configuredFont >= 8 && configuredFont <= 32 ? configuredFont : null;
46
201
  let autoFitTimer = null;
202
+ let fontFitFrame = null;
47
203
  let assignmentSettleUntil = 0;
48
204
  let assignmentSettleStartedAt = 0;
49
205
  if (!window.name) window.name = `shellpuppet-dashboard-${Date.now()}-${Math.random()}`;
@@ -66,43 +222,30 @@
66
222
  let retry = null;
67
223
  let profiles = [];
68
224
  /** Sessions this page started: profile name and, where used, folder name. */
69
- let launches = loadLaunches();
225
+ const launches = loadLaunches();
70
226
  let recent = {};
71
227
  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
228
  const dismissed = new Set();
77
229
  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;
230
+ // The launch reply can follow both a move away and a move back on this feed.
231
+ const movedSessions = new Set();
232
+ const windowToken = `w-${[...window.crypto.getRandomValues(new Uint8Array(12))]
233
+ .map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
81
234
  const newInstance = () => `i-${[...window.crypto.getRandomValues(new Uint8Array(16))]
82
235
  .map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
83
236
  let windowInstance = newInstance();
84
237
  let registered = false;
85
- const loadAt = window.performance.timeOrigin + window.performance.now();
86
- let openedAt = loadAt;
238
+ let lastFocusedAt = document.hasFocus() ? window.performance.timeOrigin + window.performance.now() : 0;
87
239
  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();
240
+ const hashWindowId = screenParams.get('screen');
241
+ const windowId = hashWindowId && /^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(hashWindowId) &&
242
+ hashWindowId.length <= 100 ? hashWindowId : windowToken;
93
243
  const windowPair = (id, instance) => JSON.stringify([id, instance]);
94
244
  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';
245
+ let assigned = new Set();
246
+ let receivedWindowState = false;
247
+ let daemonWindows = [];
248
+ const pendingWindowMoves = new Map();
106
249
  let nextFallback = 0;
107
250
  let arranging = false;
108
251
  let syncingVisibility = false;
@@ -116,36 +259,50 @@
116
259
  if (diagnostics.arrangeTriggers.length > 20) diagnostics.arrangeTriggers.shift();
117
260
  }
118
261
  let lastLayout = null;
262
+ let lastArrangedWidth = null;
263
+ let lastArrangedHeight = null;
119
264
  let lastStructure = null;
120
265
  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
266
  let channel = null;
124
- try { channel = new BroadcastChannel('shellpuppet.dashboard'); } catch { /* This window still tracks a pop-out it opened. */ }
267
+ try { channel = new BroadcastChannel('shellpuppet.dashboard'); } catch { /* Preferences remain local to this window. */ }
125
268
 
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; }
269
+ function storedLaunch(value) {
270
+ if (typeof value !== 'object' || value === null || typeof value.profile !== 'string' || !NAME.test(value.profile)) return null;
271
+ const entry = { profile: value.profile };
272
+ if (typeof value.name === 'string' && SESSION_NAME.test(value.name)) entry.name = value.name;
273
+ 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;
274
+ if (Number.isInteger(value.rootIndex) && value.rootIndex >= 0) entry.rootIndex = value.rootIndex;
275
+ if (typeof value.folderPath === 'string' && value.folderPath !== '') entry.folderPath = value.folderPath;
276
+ return entry;
131
277
  }
132
278
 
133
279
  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
280
  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
- }
281
+ // Existing profiles may still have the single catalogue written by older versions.
282
+ try {
283
+ const legacy = JSON.parse(window.localStorage.getItem(LAUNCH_PREF) || '{}');
284
+ for (const [id, value] of Object.entries(legacy)) {
285
+ const entry = storedLaunch(value);
286
+ if (entry) out[id] = entry;
287
+ }
288
+ } catch { /* The legacy catalogue is optional. */ }
289
+ try {
290
+ for (const key of Object.keys(window.localStorage)) {
291
+ if (!key.startsWith(LAUNCH_PREF + '.')) continue;
292
+ const id = key.slice(LAUNCH_PREF.length + 1);
293
+ const entry = readLaunch(key);
294
+ if (entry) out[id] = entry;
295
+ else delete out[id];
296
+ }
297
+ } catch { /* Storage is optional. */ }
146
298
  return out;
147
299
  }
148
300
 
301
+ function readLaunch(key) {
302
+ try { return storedLaunch(JSON.parse(window.localStorage.getItem(key))); }
303
+ catch { return null; }
304
+ }
305
+
149
306
  const persist = () => {
150
307
  try { window.localStorage.setItem(PREF, JSON.stringify({ mode, order, pins, prefix, autoFit, fontSize })); } catch { /* Layout still works. */ }
151
308
  };
@@ -202,24 +359,26 @@
202
359
  tracks[name] = sizes.map((size) => size / space);
203
360
  }
204
361
  }
205
- const persistLaunches = () => {
206
- try { window.localStorage.setItem(LAUNCH_PREF, JSON.stringify(launches)); } catch { /* Restart still works in this document. */ }
207
- };
362
+ window.addEventListener('storage', (event) => {
363
+ if (!event.key?.startsWith(LAUNCH_PREF + '.')) return;
364
+ const id = event.key.slice(LAUNCH_PREF.length + 1);
365
+ const entry = readLaunch(event.key);
366
+ if (entry) launches[id] = entry;
367
+ else delete launches[id];
368
+ const item = panes.get(id);
369
+ if (item) updateCard(item);
370
+ });
208
371
  const showPrefix = () => {
209
372
  document.getElementById('shortcut').textContent = `Shortcut: Ctrl+Shift+${prefix.toUpperCase()}`;
210
373
  document.getElementById('shortcut-help').textContent = `Ctrl+Shift+${prefix.toUpperCase()}`;
211
374
  };
212
375
  const sorted = () => order.map((id) => panes.get(id)).filter(Boolean);
213
376
  /** 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
- });
377
+ const shown = () => sorted().filter((item) => assigned.has(item.id));
218
378
  function renderShareCount() {
219
- if (popSelf !== null) { shareCount.hidden = true; return; }
220
- const total = sorted().filter((item) => !popped.has(item.id)).length;
379
+ const total = sorted().length;
221
380
  const here = shown().length;
222
- const count = orderedWindows().length;
381
+ const count = daemonWindows.length;
223
382
  shareCount.textContent = `${here} of ${total} here, ${count} ${count === 1 ? 'window' : 'windows'}`;
224
383
  }
225
384
  const closeError = () => { error.hidden = true; document.getElementById('error-message').textContent = ''; };
@@ -240,6 +399,7 @@
240
399
  document.getElementById('text-auto').classList.toggle('active', fontSize === null);
241
400
  }
242
401
  function scheduleAutoFit() {
402
+ scheduleFontFit();
243
403
  clearTimeout(autoFitTimer);
244
404
  if (activeDivider) return;
245
405
  if (!autoFit) { focusOpenFits.clear(); return; }
@@ -247,19 +407,48 @@
247
407
  autoFitTimer = null;
248
408
  if (window.performance.now() < assignmentSettleUntil) { scheduleAutoFit(); return; }
249
409
  assignmentSettleStartedAt = 0;
410
+ assignmentSettleUntil = 0;
250
411
  for (const item of shown()) {
251
- if (!visible(item)) continue;
412
+ if (!visible(item) || item.client?.isTemporaryGeometry()) continue;
252
413
  item.client?.autoFitGrid(80, 24, focusOpenFits.has(item.id) || incomingFits.has(item.id));
253
414
  }
254
- }, assignmentSettleUntil > window.performance.now()
255
- ? Math.max(0, assignmentSettleUntil - window.performance.now()) : 250);
415
+ }, assignmentSettleUntil ? Math.max(0, assignmentSettleUntil - window.performance.now()) : 250);
416
+ }
417
+ function fitFonts() {
418
+ const visiblePanes = shown().filter((item) => item.client && visible(item));
419
+ const below = new Set();
420
+ let shared = Infinity;
421
+ for (const item of visiblePanes) {
422
+ // The note can wrap the header. Test without it, then measure the
423
+ // remaining terminal space with the note in place.
424
+ item.card.classList.remove('below-floor');
425
+ const isBelow = item.client.belowDashboardFloor();
426
+ item.card.classList.toggle('below-floor', isBelow);
427
+ if (isBelow) {
428
+ below.add(item);
429
+ const font = item.client.floorFontSize();
430
+ if (font !== null) shared = Math.min(shared, font);
431
+ }
432
+ }
433
+ for (const item of visiblePanes) {
434
+ item.client.setDashboardFontLimit(below.has(item) && Number.isFinite(shared) ? shared : null);
435
+ }
436
+ }
437
+ function scheduleFontFit() {
438
+ if (fontFitFrame !== null) return;
439
+ fontFitFrame = window.requestAnimationFrame(() => {
440
+ fontFitFrame = null;
441
+ fitFonts();
442
+ });
256
443
  }
257
444
  function settleAssignmentFits() {
258
445
  // A feed change and its window assignment can arrive in separate tasks.
259
446
  // Wait for the last change before taking a pane's grid.
260
447
  const now = window.performance.now();
448
+ const settleMs = daemonWindows.length > 1 ? 900 : 250;
261
449
  if (assignmentSettleStartedAt === 0) assignmentSettleStartedAt = now;
262
- assignmentSettleUntil = Math.min(now + 900, assignmentSettleStartedAt + 3000);
450
+ // Leave one layout settling interval for measuring and sending the take.
451
+ assignmentSettleUntil = Math.min(now + settleMs, assignmentSettleStartedAt + 3000 - 250);
263
452
  scheduleAutoFit();
264
453
  }
265
454
  function broadcastPreferences() {
@@ -282,158 +471,44 @@
282
471
  return button;
283
472
  };
284
473
 
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) {
474
+ function applyAssignment(ids, byWindow) {
300
475
  const next = new Set(ids);
301
- if (assigned !== null && next.size === assigned.size && [...next].every((id) => assigned.has(id))) return;
476
+ if (next.size === assigned.size && [...next].every((id) => assigned.has(id))) return;
302
477
  settleAssignmentFits();
303
- const previous = assigned === null ? new Set() : assigned;
478
+ const previous = assigned;
304
479
  assigned = next;
305
480
  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);
481
+ for (const id of previous) if (!next.has(id)) {
482
+ incomingFits.delete(id);
483
+ const item = panes.get(id);
484
+ const successor = Object.entries(byWindow).some(([window, sessions]) =>
485
+ window !== ownPair() && Array.isArray(sessions) && sessions.includes(id));
486
+ if (item) deactivate(item, successor);
340
487
  }
341
- removeWindow(id, instance);
488
+ updateAttention();
342
489
  }
343
490
  function openDashboard(hash, name, features) {
344
491
  const child = window.open(`${location.origin}/dashboard${hash}`, name, features);
345
492
  if (child === null) showError('The browser blocked the window. Press the button again.');
346
493
  return child;
347
494
  }
348
- function openScreen(screen, screenRank) {
495
+ function openScreen() {
349
496
  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(); }
497
+ const hash = new URLSearchParams({ screen: id });
498
+ const child = openDashboard(`#${hash}`, `shellpuppet-window-${id}`, 'popup');
499
+ if (child === null) return null;
500
+ return id;
427
501
  }
428
502
 
429
- function rememberLaunch(id, profile, folder, rootIndex, chosenPath, recentPath) {
503
+ function rememberLaunch(id, profile, name, folder, rootIndex, chosenPath, recentPath) {
430
504
  if (typeof id !== 'string' || !NAME.test(profile)) return;
431
505
  const entry = { profile };
506
+ if (typeof name === 'string' && SESSION_NAME.test(name)) entry.name = name;
432
507
  if (typeof folder === 'string' && folder !== '') entry.folder = folder;
433
508
  if (Number.isInteger(rootIndex) && rootIndex >= 0) entry.rootIndex = rootIndex;
434
509
  if (typeof chosenPath === 'string' && chosenPath !== '') entry.folderPath = chosenPath;
435
510
  launches[id] = entry;
436
- persistLaunches();
511
+ try { window.localStorage.setItem(LAUNCH_PREF + '.' + id, JSON.stringify(entry)); } catch { /* Restart remains available here. */ }
437
512
  if (entry.folder || entry.folderPath) {
438
513
  const key = recentPath || entry.folderPath || (entry.rootIndex === undefined ? entry.folder : `root:${entry.rootIndex}:${entry.folder}`);
439
514
  recent = ShellPuppetDashboardFolders.remember(recent, profile, key);
@@ -445,6 +520,7 @@
445
520
  function launchBody(entry) {
446
521
  if (!entry || typeof entry.profile !== 'string') return null;
447
522
  const body = { profile: entry.profile };
523
+ if (typeof entry.name === 'string' && SESSION_NAME.test(entry.name)) body.name = entry.name;
448
524
  if (typeof entry.folder === 'string' && entry.folder !== '') body.folder = entry.folder;
449
525
  if (Number.isInteger(entry.rootIndex) && entry.rootIndex >= 0) body.rootIndex = entry.rootIndex;
450
526
  if (typeof entry.folderPath === 'string' && entry.folderPath !== '') body.folderPath = entry.folderPath;
@@ -463,8 +539,14 @@
463
539
  label.className = 'pane-label';
464
540
  const purpose = document.createElement('span');
465
541
  purpose.className = 'pane-purpose hint';
542
+ const role = document.createElement('span');
543
+ role.className = 'pane-role hint';
466
544
  const badge = document.createElement('span');
467
545
  badge.className = 'badge';
546
+ const messageCount = makeButton('', () => openMessages(`session:${item.id}`));
547
+ messageCount.className = 'pane-message-count';
548
+ messageCount.hidden = true;
549
+ messageCount.addEventListener('click', (event) => event.stopPropagation());
468
550
  const state = document.createElement('span');
469
551
  state.className = 'pane-state hint';
470
552
  const space = document.createElement('span');
@@ -475,19 +557,56 @@
475
557
  overflowNote.className = 'pane-overflow-note';
476
558
  overflowNote.textContent = 'Shift+wheel or drag the scrollbars to see the rest. Enlarge or Fit to show it whole.';
477
559
  overflowNote.hidden = true;
478
- const item = { id: summary.id, summary, card, label, purpose, badge, state, size, overflowNote, client: null, previousGrid: null };
560
+ const item = { id: summary.id, summary, card, label, purpose, role, badge, messageCount, state, size, overflowNote, client: null, previousGrid: null };
561
+ const renameForm = document.createElement('form');
562
+ renameForm.className = 'pane-rename';
563
+ renameForm.hidden = true;
564
+ const renameInput = document.createElement('input');
565
+ renameInput.type = 'text';
566
+ renameInput.maxLength = 40;
567
+ renameInput.setAttribute('aria-label', 'New session name');
568
+ const renameSave = document.createElement('button');
569
+ renameSave.type = 'submit';
570
+ renameSave.textContent = 'Save';
571
+ const renameCancel = makeButton('Cancel rename', () => { renameForm.hidden = true; });
572
+ renameForm.append(renameInput, renameSave, renameCancel);
573
+ renameForm.addEventListener('click', (event) => event.stopPropagation());
574
+ renameForm.addEventListener('submit', async (event) => {
575
+ event.preventDefault();
576
+ try {
577
+ const response = await fetch(`/dashboard/sessions/${encodeURIComponent(item.id)}/rename`, {
578
+ method: 'POST',
579
+ headers: { 'content-type': 'application/json', 'x-shellpuppet-csrf': proof },
580
+ body: JSON.stringify({ name: renameInput.value }),
581
+ });
582
+ const result = await response.json();
583
+ if (!response.ok) { showError(result.error || 'The session could not be renamed.'); return; }
584
+ renameForm.hidden = true;
585
+ } catch { showError('The session could not be renamed.'); }
586
+ });
587
+ item.rename = makeButton('Rename', () => {
588
+ renameInput.value = item.summary.name || item.summary.label || item.id;
589
+ renameForm.hidden = false;
590
+ renameInput.focus();
591
+ renameInput.select();
592
+ });
479
593
  item.fit = makeButton('Fit', () => { select(item.id); item.client?.fitGrid(); });
480
594
  item.enlarge = makeButton('Enlarge', () => {
481
595
  select(item.id);
482
596
  if (enlarged === item.id) {
483
597
  enlarged = null;
484
598
  arrange('restore');
485
- if (!autoFit && item.previousGrid) item.client?.takeGrid(item.previousGrid.cols, item.previousGrid.rows);
599
+ if (!autoFit && item.previousGrid) {
600
+ if (item.client?.belowDashboardFloor()) item.client.fitGrid();
601
+ else item.client?.takeGrid(item.previousGrid.cols, item.previousGrid.rows);
602
+ }
486
603
  item.previousGrid = null;
604
+ if (autoFit) window.requestAnimationFrame(() => item.client?.autoFitGrid(80, 24, true));
487
605
  } else {
488
606
  item.previousGrid = item.client?.getGrid() || null;
489
607
  enlarged = item.id;
490
608
  arrange('enlarge');
609
+ if (autoFit) window.requestAnimationFrame(() => item.client?.autoFitGrid(80, 24, true));
491
610
  if (!autoFit) window.requestAnimationFrame(() => item.client?.fitGrid());
492
611
  }
493
612
  });
@@ -511,13 +630,19 @@
511
630
  item.restart.dataset.action = 'restart';
512
631
  item.dismiss = makeButton('Dismiss', () => dismiss(item.id));
513
632
  item.dismiss.dataset.action = 'dismiss';
514
- menu.append(item.kill, item.copy, item.pop, item.restart, item.dismiss);
633
+ menu.append(item.rename, item.kill, item.copy, item.pop, item.restart, item.dismiss);
515
634
  item.menu = menu;
516
- head.append(label, purpose, badge, state, space, size, item.fit, item.enlarge,
635
+ head.append(label, renameForm, purpose, role, badge, messageCount, state, space, size, item.fit, item.enlarge,
517
636
  item.pin, item.left, item.right, item.menuButton);
518
637
  head.addEventListener('dblclick', (event) => {
519
638
  if (!event.target.closest('button')) item.enlarge.click();
520
639
  });
640
+ head.draggable = true;
641
+ head.addEventListener('dragstart', (event) => {
642
+ if (event.target.closest('button')) { event.preventDefault(); return; }
643
+ event.dataTransfer.setData('application/x-shellpuppet-pane', JSON.stringify({ id: item.id, source: ownPair() }));
644
+ event.dataTransfer.effectAllowed = 'move';
645
+ });
521
646
  const wrap = document.createElement('div');
522
647
  wrap.className = 'pane-wrap';
523
648
  const term = document.createElement('div');
@@ -551,8 +676,14 @@
551
676
  function updateCard(item) {
552
677
  const summary = item.summary;
553
678
  item.label.textContent = summary.label || summary.id;
554
- item.purpose.textContent = summary.purpose || '';
555
- item.badge.textContent = attention(item) ? '● Waiting' : '';
679
+ item.purpose.textContent = [summary.purpose, summary.parent && summary.startedBy && `Started by ${summary.startedBy}`].filter(Boolean).join(' · ');
680
+ // Only a chair is marked in the header: a label on every pane would wrap a narrow header onto a second row.
681
+ item.role.textContent = summary.role === 'chair' ? 'Chair' : '';
682
+ item.role.hidden = summary.role !== 'chair';
683
+ item.card.dataset.role = summary.role === 'chair' ? 'chair' : 'delegate';
684
+ item.badge.textContent = summary.stalled ? '● Stalled' : attention(item) ? '● Waiting' : '';
685
+ item.badge.title = summary.stalled
686
+ ? `${summary.stalled.reason} since ${summary.stalled.since}: ${summary.stalled.description}` : '';
556
687
  item.card.classList.toggle('attention', attention(item));
557
688
  item.card.classList.toggle('selected', selected === item.id);
558
689
  item.card.classList.toggle('ended', summary.exited === true);
@@ -566,32 +697,49 @@
566
697
  item.enlarge.setAttribute('aria-label', item.enlarge.textContent);
567
698
  item.restart.hidden = launchBody(launches[item.id]) === null;
568
699
  item.dismiss.hidden = summary.exited !== true;
569
- item.pop.hidden = popSelf === item.id;
570
700
  item.card.setAttribute('aria-label', `${item.label.textContent} ${item.purpose.textContent}`);
701
+ updateMessageBadge(item);
571
702
  }
572
703
  function attention(item) {
573
704
  const prompt = item.summary.waitingOnPrompt;
574
- return Boolean(prompt && prompt.waitingMs >= 20_000);
705
+ return Boolean(item.summary.stalled || (prompt && prompt.waitingMs >= 20_000));
706
+ }
707
+ function reconcileSelection() {
708
+ if (!assigned.has(selected) || !panes.has(selected)) selected = shown()[0]?.id ?? null;
709
+ if (!assigned.has(focusId) || !panes.has(focusId)) focusId = null;
710
+ if (!assigned.has(enlarged) || !panes.has(enlarged)) enlarged = null;
575
711
  }
576
712
  function updateAttention() {
713
+ reconcileSelection();
577
714
  for (const item of panes.values()) updateCard(item);
578
- const count = sorted().filter(attention).length;
579
- attentionCount.textContent = count ? `${count} waiting` : '';
715
+ const local = shown();
716
+ const count = local.filter(attention).length;
717
+ const state = local.some(item => item.summary.stalled) ? 'need attention' : 'waiting';
718
+ attentionCount.textContent = count ? `${count} ${state}` : '';
580
719
  const focus = panes.get(selected);
581
- document.title = `${count ? `${count} waiting · ` : ''}${focus?.label.textContent || 'Dashboard'} · ShellPuppet`;
720
+ document.title = `${count ? `${count} ${state} · ` : ''}${focus?.label.textContent || 'Dashboard'} · ShellPuppet`;
582
721
  }
583
722
  function select(id, focusTerminal = false) {
584
- if (!panes.has(id)) return;
723
+ if (!assigned.has(id) || !panes.has(id)) return;
585
724
  selected = id;
586
725
  updateAttention();
587
726
  if (focusTerminal) panes.get(id).client?.getTerminal().focus();
588
727
  }
589
728
  function move(id, delta) {
590
- const index = order.indexOf(id);
729
+ const local = shown().map((item) => item.id);
730
+ const index = local.indexOf(id);
591
731
  const target = index + delta;
592
- if (target < 0 || target >= order.length) return;
593
- [order[index], order[target]] = [order[target], order[index]];
732
+ if (index < 0 || target < 0 || target >= local.length) return;
733
+ const from = order.indexOf(id);
734
+ const to = order.indexOf(local[target]);
735
+ [order[from], order[to]] = [order[to], order[from]];
594
736
  persist(); arrange('move');
737
+ const current = shown();
738
+ const position = current.findIndex((item) => item.id === id);
739
+ if (position >= 0 && feed?.readyState === WebSocket.OPEN) feed.send(JSON.stringify({
740
+ type: 'window-move', session: id, source: ownPair(), target: ownPair(),
741
+ before: current[position + 1]?.id,
742
+ }));
595
743
  }
596
744
  function activate(item) {
597
745
  const width = item.term.clientWidth;
@@ -612,20 +760,25 @@
612
760
  elements: { banner: item.banner, promptAlert: item.prompt, size: item.size, overflowNote: item.overflowNote },
613
761
  onAttentionChange: () => updateAttention(),
614
762
  onGeometryReady: () => scheduleAutoFit(),
615
- onOutsideGeometry: () => scheduleAutoFit(),
763
+ onGeometryChange: () => scheduleFontFit(),
764
+ onMetricsChange: () => scheduleAutoFit(),
765
+ onOutsideGeometry: () => {
766
+ focusOpenFits.delete(item.id);
767
+ incomingFits.delete(item.id);
768
+ scheduleFontFit();
769
+ },
616
770
  onGridTaken: () => { focusOpenFits.delete(item.id); incomingFits.delete(item.id); },
617
771
  });
618
772
  }
619
- function deactivate(item) {
773
+ function deactivate(item, reassigned = false) {
620
774
  if (!item.client) return;
621
775
  const client = item.client;
622
776
  item.client = null;
623
- client.destroy();
777
+ client.destroy(reassigned);
624
778
  item.term.textContent = '';
625
779
  }
626
780
  function visible(item) {
627
- if (popSelf !== null) return item.id === popSelf && item.card.isConnected;
628
- if (popped.has(item.id)) return false;
781
+ if (!assigned.has(item.id)) return false;
629
782
  if (enlarged && item.id !== enlarged) return false;
630
783
  const box = item.card.getBoundingClientRect();
631
784
  if (box.width < 1 || box.height < 1) return false;
@@ -672,6 +825,7 @@
672
825
  else deactivate(item);
673
826
  }
674
827
  lastVisibilityGeometry = geometry;
828
+ scheduleFontFit();
675
829
  } finally {
676
830
  syncingVisibility = false;
677
831
  if (window.__dashboardTrace) window.__dashboardTrace.visibilityDepth--;
@@ -729,7 +883,7 @@
729
883
  function paneSizes() {
730
884
  return new Map(shown().map((item) => [item.id, item.card.getBoundingClientRect()]));
731
885
  }
732
- function finishDivider(divider, before) {
886
+ function finishDivider(divider, before, resetDirection = false) {
733
887
  activeDivider = null;
734
888
  endActiveDivider = null;
735
889
  divider.classList.remove('dragging');
@@ -737,11 +891,14 @@
737
891
  positionDividers();
738
892
  lastVisibilityGeometry = null;
739
893
  syncVisibility();
894
+ const affected = new Set(JSON.parse(divider.dataset.panes).flat());
740
895
  for (const item of shown()) {
896
+ if (!resetDirection && !affected.has(item.id)) continue;
741
897
  const old = before.get(item.id);
742
898
  if (!old || !item.client || !visible(item)) continue;
743
899
  const now = item.card.getBoundingClientRect();
744
- if (autoFit && (now.width > old.width + 1 || now.height > old.height + 1)) item.client.fitAfterDrag(true);
900
+ if (autoFit && (item.client.belowDashboardFloor() ||
901
+ now.width > old.width + 1 || now.height > old.height + 1)) item.client.fitAfterDrag(true);
745
902
  }
746
903
  }
747
904
  function beginDivider(divider, pointerId, start) {
@@ -827,7 +984,7 @@
827
984
  const before = paneSizes();
828
985
  if (axis === 'focus') tracks.focusStrip = null;
829
986
  else tracks[axis === 'column' ? 'columns' : 'rows'] = null;
830
- applyTracks(); finishDivider(divider, before);
987
+ applyTracks(); finishDivider(divider, before, true);
831
988
  } else {
832
989
  const coordinate = divider.getBoundingClientRect()[axis === 'row' ? 'y' : 'x'];
833
990
  const action = beginDivider(divider, null, coordinate);
@@ -873,6 +1030,8 @@
873
1030
  positionDividers();
874
1031
  }
875
1032
  function arrange(trigger = 'unspecified') {
1033
+ if (!receivedWindowState) return;
1034
+ reconcileSelection();
876
1035
  if (trigger === 'enlarge' || trigger === 'restore' || trigger === 'window resize') {
877
1036
  assignmentSettleUntil = 0;
878
1037
  assignmentSettleStartedAt = 0;
@@ -896,19 +1055,21 @@
896
1055
  renderShareCount();
897
1056
  const width = root.clientWidth - 12;
898
1057
  const height = root.clientHeight - 12;
1058
+ lastArrangedWidth = width;
1059
+ lastArrangedHeight = height;
899
1060
  const columns = Math.ceil(Math.sqrt(items.length));
900
1061
  const rows = Math.ceil(items.length / Math.max(1, columns));
901
1062
  if (items.length > 0) clampTracks(width, height, columns, rows);
902
1063
  applyTracks();
903
1064
  const autoGrid = items.length <= 1 || (width / columns >= 652 && height / rows >= 446);
904
- const layout = popSelf !== null || enlarged ? 'enlarged' : mode === 'auto' ? (autoGrid ? 'grid' : 'focus') : mode;
1065
+ const layout = enlarged ? 'enlarged' : mode === 'auto' ? (autoGrid ? 'grid' : 'focus') : mode;
905
1066
  const primary = layout === 'focus' ? pins.find((id) => items.some((item) => item.id === id)) ||
906
1067
  (mode === 'focus' && items.some((item) => item.id === focusId) ? focusId : items[0]?.id) : null;
907
1068
  const layoutKey = JSON.stringify([items.map((item) => item.id), width, height, layout, mode,
908
1069
  columns, rows, primary, enlarged, pins]);
909
1070
  if (layoutKey !== lastLayout) {
910
1071
  const structureKey = JSON.stringify([items.map((item) => item.id), layout, primary, enlarged]);
911
- empty.hidden = items.length > 0;
1072
+ empty.hidden = !messagesView.hidden || items.length > 0;
912
1073
  root.className = layout === 'focus' && items.length === 1 ? 'focus focus-only' : layout;
913
1074
  root.dataset.layout = layout;
914
1075
  root.style.setProperty('--columns', String(Math.max(1, columns)));
@@ -924,24 +1085,19 @@
924
1085
  for (const item of items) (item.id === primary ? main : strip).append(item.card);
925
1086
  root.append(main, strip);
926
1087
  } else {
927
- const item = panes.get(popSelf || enlarged);
1088
+ const item = items.find((pane) => pane.id === enlarged);
928
1089
  if (item) root.append(item.card);
929
1090
  }
930
1091
  lastStructure = structureKey;
931
1092
  }
932
1093
  renderDividers(layout, columns, rows, items, primary);
933
1094
  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
1095
  updateCard(item);
939
1096
  }
940
1097
  lastLayout = layoutKey;
941
1098
  syncVisibility();
942
1099
  scheduleAutoFit();
943
1100
  }
944
- publishAssignment();
945
1101
  } finally {
946
1102
  arranging = false;
947
1103
  if (window.__dashboardTrace) window.__dashboardTrace.arrangeDepth--;
@@ -951,18 +1107,23 @@
951
1107
  function dropLaunch(id) {
952
1108
  if (launches[id] === undefined) return;
953
1109
  delete launches[id];
954
- persistLaunches();
1110
+ try {
1111
+ const legacy = JSON.parse(window.localStorage.getItem(LAUNCH_PREF) || '{}');
1112
+ if (legacy?.[id]) window.localStorage.setItem(LAUNCH_PREF + '.' + id, 'null');
1113
+ else window.localStorage.removeItem(LAUNCH_PREF + '.' + id);
1114
+ } catch { /* Storage is optional. */ }
955
1115
  }
956
1116
 
957
1117
  function reconcile(sessions, full = false) {
958
1118
  const incoming = new Map(sessions.filter((s) => s && typeof s.id === 'string').map((s) => [s.id, s]));
959
1119
  if ([...panes.keys()].some((id) => !incoming.has(id) || dismissed.has(id)) ||
960
- [...incoming.keys()].some((id) => !panes.has(id) && !dismissed.has(id))) settleAssignmentFits();
1120
+ [...incoming.keys()].some((id) => !panes.has(id) && !dismissed.has(id))) {
1121
+ settleAssignmentFits();
1122
+ }
961
1123
  // A snapshot is the whole list. An added or removed frame is not, so it
962
1124
  // must not forget a dismissal or a launch for a session it did not mention.
963
1125
  if (full) {
964
1126
  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
1127
  for (const id of Object.keys(launches)) { if (!incoming.has(id)) dropLaunch(id); }
967
1128
  }
968
1129
  for (const [id, item] of panes) {
@@ -979,19 +1140,56 @@
979
1140
  if (!order.includes(id)) order.push(id);
980
1141
  } else panes.get(id).summary = summary;
981
1142
  }
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
1143
  persist(); arrange('feed reconcile'); updateAttention();
986
1144
  for (const id of [...pendingOpen.keys()]) enactOpen(id);
987
1145
  }
988
1146
  function receive(frame) {
989
1147
  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);
1148
+ if (frame.type === 'window-state' && Array.isArray(frame.windows) && frame.windows.includes(ownPair()) &&
1149
+ typeof frame.designated === 'string' && frame.assignments && typeof frame.assignments === 'object') {
1150
+ daemonWindows = frame.windows;
1151
+ const designated = frame.designated === ownPair();
1152
+ const toggle = document.getElementById('designated-window');
1153
+ toggle.setAttribute('aria-pressed', String(designated));
1154
+ toggle.classList.toggle('active', designated);
1155
+ toggle.disabled = false;
1156
+ document.getElementById('start').disabled = launcher.hidden;
1157
+ const ids = Array.isArray(frame.assignments[ownPair()]) ? frame.assignments[ownPair()] : [];
1158
+ receivedWindowState = true;
1159
+ if (typeof frame.move?.session === 'string') {
1160
+ const id = frame.move.session;
1161
+ movedSessions.add(id);
1162
+ pendingOpen.delete(id);
1163
+ focusOpenFits.delete(id);
1164
+ for (const [target, session] of pendingWindowMoves) {
1165
+ if (session === id) pendingWindowMoves.delete(target);
1166
+ }
1167
+ }
1168
+ if (frame.move?.target === ownPair() && typeof frame.move.session === 'string') {
1169
+ order = order.filter((id) => id !== frame.move.session);
1170
+ const before = typeof frame.move.before === 'string' ? order.indexOf(frame.move.before) : -1;
1171
+ order.splice(before < 0 ? order.length : before, 0, frame.move.session);
1172
+ persist();
1173
+ }
1174
+ applyAssignment(ids, frame.assignments);
1175
+ arrange('window state');
1176
+ for (const id of [...pendingOpen.keys()]) enactOpen(id);
1177
+ for (const [id, session] of pendingWindowMoves) {
1178
+ const target = frame.windows.find((pair) => {
1179
+ try { return JSON.parse(pair)[0] === id; } catch { return false; }
1180
+ });
1181
+ if (!target) continue;
1182
+ feed?.send(JSON.stringify({ type: 'window-move', session, source: ownPair(), target }));
1183
+ pendingWindowMoves.delete(id);
1184
+ }
1185
+ renderShareCount();
993
1186
  return;
994
1187
  }
1188
+ if (frame.type === 'message' || frame.type === 'message-state') {
1189
+ scheduleMessageRefresh();
1190
+ return;
1191
+ }
1192
+ if (frame.type === 'window-gone') return;
995
1193
  if (frame.type === 'snapshot' && Array.isArray(frame.sessions)) reconcile(frame.sessions, true);
996
1194
  else if (frame.type === 'session-added' && frame.session?.id) {
997
1195
  if (!panes.has(frame.session.id) && !dismissed.has(frame.session.id)) {
@@ -999,11 +1197,16 @@
999
1197
  }
1000
1198
  } else if (frame.type === 'session-updated' && frame.session?.id) {
1001
1199
  const item = panes.get(frame.session.id);
1002
- if (item) { item.summary = frame.session; updateAttention(); }
1200
+ if (item) {
1201
+ item.summary = frame.session;
1202
+ updateAttention();
1203
+ if (!messagesView.hidden && (frame.changed?.includes('label') || frame.changed?.includes('name'))) renderMessages();
1204
+ }
1003
1205
  } else if (frame.type === 'session-removed' && typeof frame.session === 'string') {
1206
+ movedSessions.delete(frame.session);
1207
+ pendingOpen.delete(frame.session);
1004
1208
  dismissed.delete(frame.session);
1005
1209
  dropLaunch(frame.session);
1006
- releasePop(frame.session);
1007
1210
  reconcile(sorted().filter((p) => p.id !== frame.session).map((p) => p.summary));
1008
1211
  }
1009
1212
  }
@@ -1011,24 +1214,38 @@
1011
1214
  feed = new WebSocket(`ws://${location.host}/dashboard/events`, [`sp-csrf.${proof}`]);
1012
1215
  feed.onopen = () => {
1013
1216
  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();
1217
+ scheduleMessageRefresh();
1218
+ if (registered) {
1219
+ windowInstance = newInstance();
1026
1220
  }
1221
+ registered = true;
1222
+ feed.send(JSON.stringify({ type: 'window-register', id: windowId, instance: windowInstance,
1223
+ focusedAt: lastFocusedAt }));
1027
1224
  };
1028
1225
  feed.onmessage = (event) => {
1029
1226
  try { receive(JSON.parse(event.data)); } catch { showError('The session feed sent an unreadable update.'); }
1030
1227
  };
1031
- feed.onclose = () => { connection.textContent = 'Reconnecting'; retry = setTimeout(connect, 2000); };
1228
+ feed.onclose = () => {
1229
+ connection.textContent = 'Reconnecting';
1230
+ receivedWindowState = false;
1231
+ daemonWindows = [];
1232
+ pendingWindowMoves.clear();
1233
+ pendingOpen.clear();
1234
+ movedSessions.clear();
1235
+ focusOpenFits.clear();
1236
+ endActiveDivider?.();
1237
+ applyAssignment([], {});
1238
+ root.replaceChildren();
1239
+ lastLayout = lastStructure = lastVisibilityGeometry = null;
1240
+ empty.hidden = !messagesView.hidden;
1241
+ shareCount.textContent = '';
1242
+ const toggle = document.getElementById('designated-window');
1243
+ toggle.classList.remove('active');
1244
+ toggle.setAttribute('aria-pressed', 'false');
1245
+ toggle.disabled = true;
1246
+ document.getElementById('start').disabled = true;
1247
+ retry = setTimeout(connect, 2000);
1248
+ };
1032
1249
  feed.onerror = () => showError('Could not connect to the dashboard session feed.');
1033
1250
  }
1034
1251
 
@@ -1069,46 +1286,31 @@
1069
1286
  area.remove();
1070
1287
  }
1071
1288
 
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
1289
  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);
1290
+ if (!assigned.has(id)) return;
1291
+ const newId = openScreen();
1292
+ if (newId !== null) pendingWindowMoves.set(newId, id);
1093
1293
  }
1094
1294
 
1095
- function fitWhenReady(id, left = 30) {
1295
+ function fitWhenReady(id, registration, left = 30) {
1296
+ if (registration !== ownPair() || !assigned.has(id) || movedSessions.has(id)) return;
1096
1297
  const client = panes.get(id)?.client;
1097
1298
  if (client?.fitGrid(80, 24)) return;
1098
1299
  if (left <= 0) return;
1099
- window.requestAnimationFrame(() => fitWhenReady(id, left - 1));
1300
+ window.requestAnimationFrame(() => fitWhenReady(id, registration, left - 1));
1100
1301
  }
1101
1302
 
1102
1303
  function enactOpen(id) {
1103
1304
  const open = pendingOpen.get(id);
1104
1305
  if (open === undefined) return;
1105
1306
  if (open === 'window') {
1307
+ if (!assigned.has(id)) return;
1106
1308
  pendingOpen.delete(id);
1107
1309
  popOut(id);
1108
1310
  return;
1109
1311
  }
1110
1312
  if (open === 'focus') {
1111
- if (!panes.has(id)) return;
1313
+ if (!assigned.has(id) || !panes.has(id)) return;
1112
1314
  pendingOpen.delete(id);
1113
1315
  mode = 'focus';
1114
1316
  focusId = id;
@@ -1117,7 +1319,7 @@
1117
1319
  persist();
1118
1320
  arrange('focus open');
1119
1321
  if (autoFit) { focusOpenFits.add(id); scheduleAutoFit(); }
1120
- else fitWhenReady(id);
1322
+ else fitWhenReady(id, ownPair());
1121
1323
  }
1122
1324
  }
1123
1325
 
@@ -1128,12 +1330,17 @@
1128
1330
  }
1129
1331
 
1130
1332
  async function postLaunch(body) {
1333
+ const launchingWindow = ownPair();
1334
+ if (feed?.readyState !== WebSocket.OPEN || !daemonWindows.includes(launchingWindow)) {
1335
+ showError('The dashboard window is reconnecting. Try again when it is connected.');
1336
+ return;
1337
+ }
1131
1338
  let response;
1132
1339
  try {
1133
1340
  response = await fetch('/dashboard/launch', {
1134
1341
  method: 'POST',
1135
1342
  headers: { 'content-type': 'application/json', 'x-shellpuppet-csrf': proof },
1136
- body: JSON.stringify(body),
1343
+ body: JSON.stringify({ ...body, window: launchingWindow }),
1137
1344
  });
1138
1345
  } catch {
1139
1346
  showError('The profile did not start.');
@@ -1149,10 +1356,12 @@
1149
1356
  const profile = profiles.find((item) => item?.name === body.profile);
1150
1357
  const root = profile?.anyFolder && body.rootIndex !== undefined
1151
1358
  ? 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);
1359
+ rememberLaunch(payload.id, body.profile, body.name, body.folder, body.rootIndex, body.folderPath, root?.path);
1153
1360
  const item = panes.get(payload.id);
1154
1361
  if (item) updateCard(item);
1155
- applyOpen(payload.id, payload.open);
1362
+ if (feed?.readyState === WebSocket.OPEN && ownPair() === launchingWindow && !movedSessions.has(payload.id)) {
1363
+ applyOpen(payload.id, payload.open);
1364
+ }
1156
1365
  }
1157
1366
 
1158
1367
  function selectedProfile() {
@@ -1161,6 +1370,7 @@
1161
1370
 
1162
1371
  function renderFolders() {
1163
1372
  const profile = selectedProfile();
1373
+ resumeField.hidden = !profile?.canResume;
1164
1374
  const free = !!profile?.anyFolder;
1165
1375
  boundedFolder.hidden = free;
1166
1376
  anyFolder.hidden = !free;
@@ -1214,13 +1424,15 @@
1214
1424
  if (!profile || typeof profile.name !== 'string') continue;
1215
1425
  const option = document.createElement('option');
1216
1426
  option.value = profile.name;
1217
- option.textContent = typeof profile.label === 'string' && profile.label !== '' ? profile.label : profile.name;
1427
+ option.textContent = ShellPuppetDashboardFolders.optionText(profile);
1218
1428
  profileSelect.append(option);
1219
1429
  }
1220
1430
  const loaded = profileSelect.options.length > 0;
1221
1431
  launcher.hidden = !loaded;
1432
+ document.getElementById('start').disabled = !loaded || !daemonWindows.includes(ownPair());
1222
1433
  watchOnly.hidden = loaded;
1223
1434
  renderFolders();
1435
+ sessionName.value = selectedProfile()?.name || '';
1224
1436
  }
1225
1437
 
1226
1438
  async function loadProfiles() {
@@ -1248,6 +1460,8 @@
1248
1460
  const profile = selectedProfile();
1249
1461
  if (profile === null) return;
1250
1462
  const body = { profile: profile.name };
1463
+ if (sessionName.value !== profile.name) body.name = sessionName.value;
1464
+ if (profile.canResume && resumeId.value) body.resumeId = resumeId.value;
1251
1465
  if (profile.folderRequired) {
1252
1466
  if (profile.anyFolder) {
1253
1467
  if (folderPath.value === '') { showError('Choose a folder.'); return; }
@@ -1297,10 +1511,8 @@
1297
1511
  if (item) { deactivate(item); item.card.remove(); panes.delete(id); }
1298
1512
  order = order.filter((entry) => entry !== id);
1299
1513
  pins = pins.filter((entry) => entry !== id);
1300
- if (selected === id) selected = order.find((entry) => panes.has(entry)) || null;
1301
1514
  if (focusId === id) focusId = null;
1302
1515
  if (enlarged === id) enlarged = null;
1303
- releasePop(id);
1304
1516
  persist();
1305
1517
  arrange('dismiss');
1306
1518
  updateAttention();
@@ -1313,70 +1525,6 @@
1313
1525
  (data.fontSize === null || (Number.isInteger(data.fontSize) && data.fontSize >= 8 && data.fontSize <= 32))) {
1314
1526
  autoFit = data.autoFit;
1315
1527
  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
1528
  }
1381
1529
  }
1382
1530
 
@@ -1387,6 +1535,12 @@
1387
1535
  if (name === 'focus') focusId = selected;
1388
1536
  if (name === 'auto' || name === 'grid') resetTracks();
1389
1537
  mode = name; enlarged = null; persist(); arrange('mode');
1538
+ if (name === 'focus' && autoFit) {
1539
+ const primary = pins.find((id) => shown().some((item) => item.id === id)) || focusId;
1540
+ if (panes.get(primary)?.client?.isTemporaryGeometry()) {
1541
+ window.requestAnimationFrame(() => panes.get(primary)?.client?.autoFitGrid(80, 24, true));
1542
+ }
1543
+ }
1390
1544
  if (name === 'focus' && !autoFit) {
1391
1545
  const items = shown();
1392
1546
  const primary = pins.find((id) => items.some((item) => item.id === id)) || focusId;
@@ -1395,16 +1549,62 @@
1395
1549
  });
1396
1550
  }
1397
1551
  strip.addEventListener('scroll', syncVisibility);
1552
+ function acceptsPaneMove(transfer) {
1553
+ return transfer?.types.includes('application/x-shellpuppet-pane') &&
1554
+ ['move', 'copyMove', 'linkMove', 'all', 'uninitialized'].includes(transfer.effectAllowed);
1555
+ }
1556
+ document.addEventListener('dragover', (event) => {
1557
+ if (!acceptsPaneMove(event.dataTransfer)) return;
1558
+ event.preventDefault();
1559
+ event.dataTransfer.dropEffect = 'move';
1560
+ });
1561
+ document.addEventListener('drop', (event) => {
1562
+ if (!acceptsPaneMove(event.dataTransfer)) return;
1563
+ event.preventDefault();
1564
+ let drag;
1565
+ try { drag = JSON.parse(event.dataTransfer.getData('application/x-shellpuppet-pane')); }
1566
+ catch { return; }
1567
+ if (typeof drag?.id !== 'string' || typeof drag?.source !== 'string') return;
1568
+ const pane = event.target.closest?.('.pane');
1569
+ let before = pane?.dataset.session;
1570
+ if (pane && before) {
1571
+ const box = pane.getBoundingClientRect();
1572
+ const after = root.dataset.layout === 'focus'
1573
+ ? event.clientY > box.top + box.height / 2
1574
+ : event.clientX > box.left + box.width / 2;
1575
+ if (after) before = shown()[shown().findIndex((item) => item.id === before) + 1]?.id;
1576
+ }
1577
+ if (feed?.readyState === WebSocket.OPEN) feed.send(JSON.stringify({
1578
+ type: 'window-move', session: drag.id, source: drag.source, target: ownPair(), before,
1579
+ }));
1580
+ });
1398
1581
  document.getElementById('auto-fit').addEventListener('click', () => {
1399
1582
  assignmentSettleUntil = 0;
1400
1583
  assignmentSettleStartedAt = 0;
1401
1584
  autoFit = !autoFit;
1402
1585
  renderPreferences(); persist(); scheduleAutoFit(); broadcastPreferences();
1403
1586
  });
1587
+ document.getElementById('designated-window').addEventListener('click', () => {
1588
+ if (feed?.readyState === WebSocket.OPEN) feed.send(JSON.stringify({ type: 'window-designate' }));
1589
+ });
1590
+ document.getElementById('new-window').addEventListener('click', () => { openScreen(); });
1591
+ window.addEventListener('focus', (event) => {
1592
+ if (!event.isTrusted) return;
1593
+ lastFocusedAt = window.performance.timeOrigin + event.timeStamp;
1594
+ if (feed?.readyState === WebSocket.OPEN) feed.send(JSON.stringify({ type: 'window-focus', focusedAt: lastFocusedAt }));
1595
+ });
1404
1596
  document.getElementById('text-smaller').addEventListener('click', () => setFontSize(Math.max(8, (fontSize ?? 13) - 1)));
1405
1597
  document.getElementById('text-auto').addEventListener('click', () => setFontSize(null));
1406
1598
  document.getElementById('text-larger').addEventListener('click', () => setFontSize(Math.min(32, (fontSize ?? 13) + 1)));
1407
1599
  document.getElementById('error-close').addEventListener('click', closeError);
1600
+ messagesToggle.addEventListener('click', () => {
1601
+ if (messagesView.hidden) openMessages(); else closeMessages();
1602
+ });
1603
+ messagesFilter.addEventListener('change', () => {
1604
+ messageFilter = messagesFilter.value;
1605
+ messageSelection = null;
1606
+ renderMessages();
1607
+ });
1408
1608
  document.getElementById('shortcut').addEventListener('click', () => {
1409
1609
  choosingPrefix = true;
1410
1610
  document.getElementById('shortcut').textContent = 'Press Ctrl+Shift and a letter';
@@ -1413,42 +1613,27 @@
1413
1613
  const waiting = shown().find((item) => attention(item) && item.id !== selected) || shown().find(attention);
1414
1614
  if (waiting) select(waiting.id);
1415
1615
  });
1416
- profileSelect.addEventListener('change', renderFolders);
1616
+ profileSelect.addEventListener('change', () => { resumeId.value = ''; sessionName.value = selectedProfile()?.name || ''; renderFolders(); });
1417
1617
  folderFilter.addEventListener('input', renderFolders);
1418
1618
  folderFilter.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); startSelected(); } });
1419
1619
  folderPath.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); startSelected(); } });
1420
1620
  browseFolder.addEventListener('click', () => { void browseForFolder(); });
1421
1621
  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
1622
  if (channel !== null) channel.onmessage = onWindowMessage;
1429
- window.addEventListener('resize', () => { advertise(); arrange('window resize'); });
1623
+ window.addEventListener('resize', () => {
1624
+ if (root.clientWidth - 12 !== lastArrangedWidth || root.clientHeight - 12 !== lastArrangedHeight)
1625
+ arrange('window resize');
1626
+ });
1430
1627
  window.addEventListener('beforeunload', () => {
1431
1628
  endActiveDivider?.();
1432
- leaveWindow();
1433
1629
  clearTimeout(retry);
1630
+ clearTimeout(messageTimer);
1434
1631
  clearTimeout(autoFitTimer);
1632
+ window.cancelAnimationFrame(fontFitFrame);
1435
1633
  feed?.close();
1436
1634
  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
1635
  });
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
- }
1636
+ window.addEventListener('pagehide', () => { endActiveDivider?.(); });
1452
1637
  document.addEventListener('keydown', (event) => {
1453
1638
  if (choosingPrefix) {
1454
1639
  event.preventDefault(); event.stopPropagation();
@@ -1499,25 +1684,7 @@
1499
1684
  }, true);
1500
1685
  showPrefix();
1501
1686
  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
- }
1687
+ renderShareCount();
1521
1688
  if (proof) { void loadProfiles(); connect(); }
1522
1689
  else showError('Start ShellPuppet from its shortcut or with shellpuppet desktop');
1523
1690
  })();