shellpuppet 0.2.0 → 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 (238) hide show
  1. package/README.md +83 -18
  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 +255 -33
  138. package/dist/cli/index.js.map +1 -1
  139. package/dist/client/http.d.ts +17 -3
  140. package/dist/client/http.js +232 -35
  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 +166 -14
  176. package/dist/core/session.js +1000 -86
  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/liveness.d.ts +1 -1
  201. package/dist/daemon/liveness.js +2 -2
  202. package/dist/daemon/liveness.js.map +1 -1
  203. package/dist/daemon/nudgeScheduler.d.ts +21 -0
  204. package/dist/daemon/nudgeScheduler.js +61 -0
  205. package/dist/daemon/nudgeScheduler.js.map +1 -0
  206. package/dist/daemon/paths.d.ts +22 -16
  207. package/dist/daemon/paths.js +137 -49
  208. package/dist/daemon/paths.js.map +1 -1
  209. package/dist/daemon/restartHold.d.ts +16 -0
  210. package/dist/daemon/restartHold.js +126 -0
  211. package/dist/daemon/restartHold.js.map +1 -0
  212. package/dist/daemon/restartSource.d.ts +7 -0
  213. package/dist/daemon/restartSource.js +89 -0
  214. package/dist/daemon/restartSource.js.map +1 -0
  215. package/dist/daemon/screenshot.d.ts +4 -1
  216. package/dist/daemon/screenshot.js +45 -7
  217. package/dist/daemon/screenshot.js.map +1 -1
  218. package/dist/daemon/server.d.ts +71 -13
  219. package/dist/daemon/server.js +1601 -296
  220. package/dist/daemon/server.js.map +1 -1
  221. package/dist/daemon/sessionFeed.js +4 -1
  222. package/dist/daemon/sessionFeed.js.map +1 -1
  223. package/dist/mcp/config.js +2 -1
  224. package/dist/mcp/config.js.map +1 -1
  225. package/dist/mcp/index.js +12 -2
  226. package/dist/mcp/index.js.map +1 -1
  227. package/dist/mcp/tools.d.ts +21 -1
  228. package/dist/mcp/tools.js +213 -28
  229. package/dist/mcp/tools.js.map +1 -1
  230. package/dist/viewer/dashboard-folders.js +7 -1
  231. package/dist/viewer/dashboard-layout.js +6 -52
  232. package/dist/viewer/dashboard.css +20 -4
  233. package/dist/viewer/dashboard.html +12 -3
  234. package/dist/viewer/dashboard.js +550 -378
  235. package/dist/viewer/pane.js +744 -136
  236. package/dist/viewer/viewer.css +1 -1
  237. package/dist/viewer/viewer.js +3 -1
  238. package/package.json +1 -1
@@ -8,7 +8,8 @@
8
8
  * Wire protocol: BINARY WebSocket frames carry terminal bytes (snapshots, the
9
9
  * live stream and the exit notice); TEXT frames are JSON control messages:
10
10
  * `identity`, `geometry`, `input-source`, `input-refused`, `exited`,
11
- * `prompt-stall` and `prompt-clear`. What this pane sends is text: a JSON
11
+ * `prompt-stall`, `prompt-clear`, `session-stalled` and `session-stall-clear`.
12
+ * What this pane sends is text: a JSON
12
13
  * resize message, or bytes for the program, which are either keystrokes or
13
14
  * the terminal's own answers to the program's queries. The daemon tells those
14
15
  * two apart.
@@ -17,7 +18,7 @@
17
18
  * - `term.onData` is registered exactly ONCE, never inside the connect path.
18
19
  * Registering per-connect would stack a listener per reconnect and send
19
20
  * every keystroke N times.
20
- * - The fit addon measures what grid this window would like, and the pane asks
21
+ * - The pane measures what grid this window would like, and asks
21
22
  * the daemon for it rather than assuming it (§5). The daemon decides who is
22
23
  * driving the grid and answers with a geometry frame; only that frame
23
24
  * resizes anything here.
@@ -28,7 +29,7 @@
28
29
  * replayed here would start mid-frame.
29
30
  */
30
31
 
31
- /* global Terminal, FitAddon */
32
+ /* global Terminal */
32
33
 
33
34
  window.ShellPuppetPane = (() => {
34
35
  'use strict';
@@ -36,6 +37,28 @@ window.ShellPuppetPane = (() => {
36
37
  const MIN_FONT_PX = 6;
37
38
  const MAX_FONT_PX = 40;
38
39
  const DEFAULT_FONT_PX = 13;
40
+ const NOTICE_HISTORY_MS = 10000;
41
+ const NOTICE_DECISION_MS = 1200;
42
+ const NOTICE_COVER_MARGIN_MS = 20;
43
+ const NOTICE_DELIVERY_GUARD_MS = 5;
44
+ const NOTICE_QUIET_MS = 1000;
45
+ const scaledEvents = new WeakSet();
46
+ let scaledSelection = null;
47
+ const cellMetrics = new Map();
48
+ const fontListeners = new Set();
49
+ let fontGeneration = 0;
50
+ document.fonts?.addEventListener('loadingdone', () => {
51
+ cellMetrics.clear();
52
+ fontGeneration++;
53
+ for (const refresh of fontListeners) refresh();
54
+ });
55
+
56
+ function remember(cache, key, value) {
57
+ // Bound caches across font choices, window sizes and device scales.
58
+ if (cache.size >= 256) cache.delete(cache.keys().next().value);
59
+ cache.set(key, value);
60
+ return value;
61
+ }
39
62
 
40
63
  function clampFont(px) {
41
64
  return Math.min(MAX_FONT_PX, Math.max(MIN_FONT_PX, px));
@@ -48,12 +71,15 @@ window.ShellPuppetPane = (() => {
48
71
  * @param {HTMLElement} config.container - The element to host the terminal.
49
72
  * @param {string} config.sessionId - The session to connect to.
50
73
  * @param {boolean} [config.captureMode=false] - Headless screenshot mode.
74
+ * @param {boolean} [config.passive=false] - Opt the stream out of taking an unowned grid on connect.
51
75
  * @param {boolean} [config.redactedCapture=false] - Redact sensitive rows.
52
76
  * @param {Object} config.elements - References to badge elements.
53
77
  * @param {number|null} [config.initialFontOverride=null] - Initial font size.
54
78
  * @param {function} [config.onTitleChange] - Called when the window title should change.
55
79
  * @param {function} [config.onFontOverrideChange] - Called when the font override changes.
56
- * @param {function} [config.onGeometryReady] - Called after the first geometry frame.
80
+ * @param {function} [config.onGeometryReady] - Called after the first geometry frame and after temporary geometry ends.
81
+ * @param {function} [config.onGeometryChange] - Called after each geometry frame.
82
+ * @param {function} [config.onMetricsChange] - Called after font or device-scale metrics change.
57
83
  * @param {function} [config.onOutsideGeometry] - Called when another client changes an unheld grid.
58
84
  * @param {string} [config.dashboardProof] - Document proof for a dashboard stream.
59
85
  * @param {function} [config.onAttentionChange] - Reports prompt attention.
@@ -64,12 +90,15 @@ window.ShellPuppetPane = (() => {
64
90
  container,
65
91
  sessionId,
66
92
  captureMode = false,
93
+ passive = false,
67
94
  redactedCapture = false,
68
95
  elements = {},
69
96
  initialFontOverride = null,
70
97
  onTitleChange = () => {},
71
98
  onFontOverrideChange = () => {},
72
99
  onGeometryReady = () => {},
100
+ onGeometryChange = () => {},
101
+ onMetricsChange = () => {},
73
102
  onOutsideGeometry = () => {},
74
103
  onGridTaken = () => {},
75
104
  dashboardProof = null,
@@ -85,6 +114,7 @@ window.ShellPuppetPane = (() => {
85
114
  let sessionEnded = false;
86
115
  let inputFailed = false;
87
116
  let promptWaiting = false;
117
+ let providerStall = null;
88
118
  let gridCols = 0;
89
119
  let gridRows = 0;
90
120
  let gridMax = { cols: Infinity, rows: Infinity };
@@ -95,9 +125,15 @@ window.ShellPuppetPane = (() => {
95
125
  let destroyed = false;
96
126
  let reconnectTimer = null;
97
127
  let pendingTakeGrid = false;
98
- let outsideResizePending = false;
99
- let lastOutsideFitAt = 0;
128
+ let pendingTakeSize = null;
129
+ let pendingTakeSocket = null;
100
130
  let followingExternal = false;
131
+ let transferOffered = false;
132
+ let temporaryGeometry = false;
133
+ let dashboardFontLimit = null;
134
+ let fontScale = 1;
135
+ const fittingFonts = new Map();
136
+ let viewportSyncPending = false;
101
137
 
102
138
  const showBanner = (message) => {
103
139
  if (!elements.banner) return;
@@ -108,7 +144,7 @@ window.ShellPuppetPane = (() => {
108
144
  };
109
145
 
110
146
  const refreshTitle = () => {
111
- const prefix = sessionEnded ? '[ENDED] ' : promptWaiting ? '[ANSWER ME] ' : '';
147
+ const prefix = sessionEnded ? '[ENDED] ' : promptWaiting ? '[ANSWER ME] ' : providerStall ? '[STALLED] ' : '';
112
148
  onTitleChange(prefix + identityTitle);
113
149
  };
114
150
  refreshTitle();
@@ -116,6 +152,7 @@ window.ShellPuppetPane = (() => {
116
152
  const showEnded = (exitCode) => {
117
153
  if (sessionEnded) return;
118
154
  sessionEnded = true;
155
+ disposeNoticeTracking();
119
156
  if (elements.readonly) elements.readonly.disabled = true;
120
157
  const withCode = typeof exitCode === 'number';
121
158
  if (elements.readonly) {
@@ -183,6 +220,10 @@ window.ShellPuppetPane = (() => {
183
220
  }
184
221
  elements.promptAlert.append(list);
185
222
  }
223
+ if (elements.promptAlert.hidden || noticeKind !== 'prompt') {
224
+ noticeNewEpisode = noticeKind !== 'prompt' || noticeHiddenLong();
225
+ }
226
+ noticeKind = 'prompt';
186
227
  elements.promptAlert.hidden = false;
187
228
  positionNotices();
188
229
  promptWaiting = true;
@@ -191,7 +232,10 @@ window.ShellPuppetPane = (() => {
191
232
  };
192
233
 
193
234
  const clearPromptAlert = () => {
235
+ promptWaiting = false;
236
+ if (providerStall) { showStallAlert(providerStall); return; }
194
237
  if (!elements.promptAlert) return;
238
+ if (!elements.promptAlert.hidden) noticeHiddenAt = window.performance.now();
195
239
  elements.promptAlert.hidden = true;
196
240
  elements.promptAlert.textContent = '';
197
241
  promptWaiting = false;
@@ -199,6 +243,31 @@ window.ShellPuppetPane = (() => {
199
243
  refreshTitle();
200
244
  };
201
245
 
246
+ const showStallAlert = (stalled) => {
247
+ providerStall = stalled;
248
+ if (!elements.promptAlert || promptWaiting) return;
249
+ elements.promptAlert.textContent = `Stalled: ${stalled.reason} since ${stalled.since}. ${stalled.description}`;
250
+ if (elements.promptAlert.hidden || noticeKind !== 'stall') {
251
+ noticeNewEpisode = noticeKind !== 'stall' || noticeHiddenLong();
252
+ }
253
+ noticeKind = 'stall';
254
+ elements.promptAlert.hidden = false;
255
+ positionNotices();
256
+ onAttentionChange(true);
257
+ refreshTitle();
258
+ };
259
+
260
+ const clearStallAlert = () => {
261
+ providerStall = null;
262
+ if (!promptWaiting && elements.promptAlert) {
263
+ if (!elements.promptAlert.hidden) noticeHiddenAt = window.performance.now();
264
+ elements.promptAlert.hidden = true;
265
+ elements.promptAlert.textContent = '';
266
+ }
267
+ onAttentionChange(promptWaiting);
268
+ refreshTitle();
269
+ };
270
+
202
271
  const term = new Terminal({
203
272
  cursorBlink: true,
204
273
  fontSize: fontOverride ?? DEFAULT_FONT_PX,
@@ -207,9 +276,74 @@ window.ShellPuppetPane = (() => {
207
276
  fontFamily: 'ui-monospace, "Cascadia Code", Consolas, monospace',
208
277
  theme: { background: '#0b0e14', foreground: '#c5cdd9', cursor: '#6cb6ff' },
209
278
  });
210
- const fit = new FitAddon.FitAddon();
211
- term.loadAddon(fit);
212
279
  term.open(container);
280
+ let pendingWrites = 0;
281
+ let terminalReleased = false;
282
+ const releaseTerminal = () => {
283
+ if (terminalReleased) return;
284
+ terminalReleased = true;
285
+ term.dispose();
286
+ };
287
+ // Closing a pane detaches it immediately. Its finite parser queue keeps
288
+ // the terminal alive until the last callback, including geometry markers.
289
+ const writeTerminal = (data, applied) => {
290
+ if (destroyed) return;
291
+ pendingWrites++;
292
+ term.write(data, () => {
293
+ pendingWrites--;
294
+ if (!destroyed) applied?.();
295
+ if (destroyed && pendingWrites === 0) window.queueMicrotask(releaseTerminal);
296
+ });
297
+ };
298
+ const resizeTerminal = (cols, rows, force = false) => {
299
+ if (destroyed) return;
300
+ const apply = () => {
301
+ if (force || term.cols !== cols || term.rows !== rows) term.resize(cols, rows);
302
+ };
303
+ if (pendingWrites === 0) apply();
304
+ else writeTerminal('', apply);
305
+ };
306
+ let metricsFrame = null;
307
+ const refreshFontMetrics = () => {
308
+ if (destroyed || metricsFrame !== null) return;
309
+ // Let xterm finish updating its renderer before measuring a new fit.
310
+ metricsFrame = window.requestAnimationFrame(() => {
311
+ metricsFrame = null;
312
+ if (destroyed) return;
313
+ term._core._charSizeService.measure();
314
+ relayout(false);
315
+ onMetricsChange();
316
+ });
317
+ };
318
+ fontListeners.add(refreshFontMetrics);
319
+ const resolutionListener = term._core._coreBrowserService.onDprChange(refreshFontMetrics);
320
+ // xterm measures mouse positions in unscaled cells. Keep selection and
321
+ // terminal mouse reports aligned when a tiny held screen needs scaling.
322
+ const scaleMouseEvent = (event) => {
323
+ if (fontScale === 1 || scaledEvents.has(event)) return;
324
+ const inside = container.contains(event.target);
325
+ if (event.type === 'mousedown' || event.type === 'pointerdown') scaledSelection = inside ? container : null;
326
+ if (event.type === 'mousemove' && event.buttons === 0 && scaledSelection === container) scaledSelection = null;
327
+ if (scaledSelection ? scaledSelection !== container : !inside) return;
328
+ const screen = term.element?.querySelector('.xterm-screen');
329
+ if (!screen) return;
330
+ const rect = screen.getBoundingClientRect();
331
+ const clientX = rect.left + (event.clientX - rect.left) / fontScale;
332
+ const clientY = rect.top + (event.clientY - rect.top) / fontScale;
333
+ // Keep the original event, target and pointer id so native capture works.
334
+ // xterm's scrollbar uses page coordinates for its drag deltas. Native
335
+ // offsetX/Y are already local to the transformed target; leave them alone.
336
+ Object.defineProperties(event, {
337
+ clientX: { value: clientX }, clientY: { value: clientY },
338
+ pageX: { value: clientX + window.scrollX }, pageY: { value: clientY + window.scrollY },
339
+ movementX: { value: event.movementX / fontScale }, movementY: { value: event.movementY / fontScale },
340
+ });
341
+ scaledEvents.add(event);
342
+ if (['mouseup', 'pointerup', 'pointercancel'].includes(event.type)) scaledSelection = null;
343
+ };
344
+ const scaledMouseEvents = ['mousedown', 'mousemove', 'mouseup', 'wheel', 'contextmenu',
345
+ 'pointerdown', 'pointermove', 'pointerup', 'pointercancel'];
346
+ for (const type of scaledMouseEvents) document.addEventListener(type, scaleMouseEvent, true);
213
347
  const outerScroll = container.parentElement;
214
348
  const helper = term.element?.querySelector('.xterm-helper-textarea');
215
349
  if (dashboardProof !== null && outerScroll && helper) {
@@ -254,6 +388,7 @@ window.ShellPuppetPane = (() => {
254
388
  const isMac = /Mac|iPhone|iPad/i.test(platform);
255
389
  // Let the browser deliver paste to xterm's textarea on Windows and Linux.
256
390
  term.attachCustomKeyEventHandler((event) => {
391
+ if (destroyed) return false;
257
392
  if (isMac || event.type !== 'keydown' || !event.ctrlKey || event.shiftKey || event.altKey || event.metaKey) return true;
258
393
  if (event.key.toLowerCase() === 'v') return false;
259
394
  if (event.key.toLowerCase() === 'c' && term.hasSelection()) {
@@ -264,17 +399,282 @@ window.ShellPuppetPane = (() => {
264
399
  }
265
400
  const selection = term.getSelection();
266
401
  void navigator.clipboard.writeText(selection).then(() => {
267
- if (term.getSelection() === selection) term.clearSelection();
402
+ if (!destroyed && term.getSelection() === selection) term.clearSelection();
268
403
  }).catch(() => showBanner('Could not copy selected text to the clipboard.'));
269
404
  return false;
270
405
  }
271
406
  return true;
272
407
  });
273
408
 
274
- // The terminal can be centred within #wrap when its grid is held. Anchor
275
- // notices to the rendered screen, not to the outer fit box, and keep the
276
- // cursor's half free even as a TUI moves its cursor without a grid change.
277
- function positionNotices() {
409
+ let noticeBottom = null;
410
+ let noticeLastMove = null;
411
+ let noticeLastRepaint = -Infinity;
412
+ let noticeLegMoved = false;
413
+ let noticeStayPreviousRepaint;
414
+ let noticeStayEdge = null;
415
+ let noticeStaySince = null;
416
+ let noticeStayMoved = false;
417
+ let noticeAnchor = null;
418
+ let noticeCycle = null;
419
+ let noticeCycleVisits = [];
420
+ let noticeCycleMoves = 0;
421
+ const noticeVisits = [];
422
+ let noticeGeometry = null;
423
+ let noticeSeen = false;
424
+ let noticeNewEpisode = false;
425
+ let noticeHiddenAt = null;
426
+ // The kind of the last alert shown: a different kind is a new notice.
427
+ let noticeKind = null;
428
+ // An alert shown after the notice was hidden for the whole retained history
429
+ // is a new notice: none of its cadence evidence remains. A shorter gap, such
430
+ // as the daemon re-announcing a prompt whose choices a repaint changed,
431
+ // keeps the cadence.
432
+ const noticeHiddenLong = () => noticeHiddenAt === null ||
433
+ window.performance.now() - noticeHiddenAt >= NOTICE_HISTORY_MS;
434
+ let noticeFrame = null;
435
+ let noticeTimer = null;
436
+ let noticeEvidenceTimer = null;
437
+ let noticeDisposed = false;
438
+
439
+ function clearNoticeTimer() {
440
+ clearTimeout(noticeTimer);
441
+ noticeTimer = null;
442
+ clearTimeout(noticeEvidenceTimer);
443
+ noticeEvidenceTimer = null;
444
+ }
445
+
446
+ function trimNoticeVisits(now) {
447
+ const cutoff = now - NOTICE_HISTORY_MS;
448
+ while (noticeVisits.length > 1 && noticeVisits[1].since <= cutoff) noticeVisits.shift();
449
+ if (noticeVisits.length && noticeVisits[0].since < cutoff) {
450
+ noticeVisits[0].since = cutoff;
451
+ noticeVisits[0].clipped = true;
452
+ }
453
+ }
454
+
455
+ function noticeCoversRow(row, bottom) {
456
+ if (!noticeGeometry) return false;
457
+ const distance = bottom ? term.rows - row - 1 : row;
458
+ return distance * noticeGeometry.cell < noticeGeometry.height - 0.01;
459
+ }
460
+
461
+ function noticeWeights(visits, now) {
462
+ let top = 0, bottom = 0;
463
+ for (let i = 0; i < visits.length; i++) {
464
+ const visit = visits[i];
465
+ const duration = Math.max(0, (visits[i + 1]?.since ?? now) - visit.since);
466
+ if (noticeCoversRow(visit.row, false)) top += duration;
467
+ if (noticeCoversRow(visit.row, true)) bottom += duration;
468
+ }
469
+ return { top, bottom };
470
+ }
471
+
472
+ function noticeClearEdge({ top, bottom }) {
473
+ // Cursor events are observed after this pane's listener has run. Keep
474
+ // a small clear lead beyond the ratio boundary for delivered evidence.
475
+ if (top + NOTICE_DELIVERY_GUARD_MS <= bottom * 2 / 3 &&
476
+ bottom - top >= NOTICE_COVER_MARGIN_MS) return false;
477
+ if (bottom + NOTICE_DELIVERY_GUARD_MS <= top * 2 / 3 &&
478
+ top - bottom >= NOTICE_COVER_MARGIN_MS) return true;
479
+ return null;
480
+ }
481
+
482
+ function finishNoticeRest() {
483
+ // A completed rectangle stay reclassifies an earlier move in any of
484
+ // its rows. Rest follows do not spend the repaint budget.
485
+ if (noticeStayPreviousRepaint !== undefined) {
486
+ noticeLastRepaint = noticeStayPreviousRepaint;
487
+ noticeStayPreviousRepaint = undefined;
488
+ }
489
+ }
490
+
491
+ function rememberNoticeCycle(row, now) {
492
+ if (row !== noticeAnchor || !noticeGeometry) return;
493
+ // Keep the current anchor-return word outside the ten-second weight
494
+ // window. A full delivered cycle can be longer than that window.
495
+ let visits = noticeCycleVisits.map(visit => ({ ...visit }));
496
+ if (!visits.length) return;
497
+ const half = visits.length / 2;
498
+ const repeated = Number.isInteger(half) && visits.slice(0, half).every((visit, i) =>
499
+ visit.row === visits[i + half].row);
500
+ if (repeated) visits = visits.slice(half);
501
+ const duration = now - visits[0].since;
502
+ const weights = noticeWeights(visits, now);
503
+ let longestLeg = 0;
504
+ for (let i = 0; i < visits.length; i++) {
505
+ longestLeg = Math.max(longestLeg, (visits[i + 1]?.since ?? now) - visits[i].since);
506
+ }
507
+ noticeCycleMoves = 0;
508
+ if (repeated) noticeCycleVisits = noticeCycleVisits.slice(half);
509
+ if (weights.top <= 0 || weights.bottom <= 0) return;
510
+ // A repeated row word renews its evidence even when delivery makes
511
+ // this occurrence slightly shorter than the previous one.
512
+ const sameWord = noticeCycle && visits.length === noticeCycle.visits.length &&
513
+ visits.every((visit, i) => visit.row === noticeCycle.visits[i].row);
514
+ if (!noticeCycle || sameWord || now - noticeCycle.end >= noticeCycle.validFor || duration >= noticeCycle.duration) {
515
+ noticeCycle = { visits, end: now, duration,
516
+ validFor: Math.max(NOTICE_HISTORY_MS, duration + longestLeg) };
517
+ }
518
+ }
519
+
520
+ function placeNotices(now, immediate = false) {
521
+ if (!noticeGeometry || noticeGeometry.height <= 0) return;
522
+ const { notices, top, bottom } = noticeGeometry;
523
+ const row = term.buffer.active.cursorY;
524
+ noticeBottom ??= row < term.rows / 2;
525
+ trimNoticeVisits(now);
526
+ const quiet = noticeStayEdge !== null && now - noticeStaySince >= NOTICE_QUIET_MS;
527
+ if (quiet) finishNoticeRest();
528
+ if (!noticeLegMoved && (noticeStayEdge === null || !noticeStayMoved)) {
529
+ let destination = noticeBottom;
530
+ const initial = !noticeVisits.length || (immediate && noticeVisits.length === 1);
531
+ if (initial || quiet) {
532
+ if (noticeCoversRow(row, noticeBottom)) destination = !noticeBottom;
533
+ } else if (now - noticeVisits[0].since >= NOTICE_DECISION_MS &&
534
+ now - noticeLastRepaint >= NOTICE_HISTORY_MS && noticeCycleMoves === 0) {
535
+ const whole = noticeClearEdge(noticeWeights(noticeVisits, now));
536
+ // A short complete cycle represents a repeated cadence. Apply the
537
+ // absolute margin over the decision horizon, so a 24/9 ms cycle
538
+ // cannot veto a clear lead accumulated across many repetitions.
539
+ const cycle = noticeCycle && now - noticeCycle.end < noticeCycle.validFor ? (() => {
540
+ const weights = noticeWeights(noticeCycle.visits, noticeCycle.end);
541
+ const scale = Math.max(1, NOTICE_DECISION_MS / Math.max(1, noticeCycle.duration));
542
+ return noticeClearEdge({ top: weights.top * scale, bottom: weights.bottom * scale });
543
+ })() : undefined;
544
+ // Whole-history hysteresis and the absolute budget apply even at
545
+ // startup. A retained cycle can veto a move, never authorise
546
+ // one against the whole history.
547
+ if (whole !== null && (cycle === undefined || cycle === whole)) {
548
+ destination = whole;
549
+ }
550
+ }
551
+ if (destination !== noticeBottom && !noticeCoversRow(row, destination)) {
552
+ noticeBottom = destination;
553
+ noticeLegMoved = true;
554
+ if (noticeStayEdge !== null) noticeStayMoved = true;
555
+ if (!initial && !quiet) {
556
+ if (noticeStayEdge !== null && noticeStayPreviousRepaint === undefined) {
557
+ noticeStayPreviousRepaint = noticeLastRepaint;
558
+ }
559
+ noticeLastRepaint = now;
560
+ noticeCycleMoves++;
561
+ }
562
+ }
563
+ }
564
+ notices.style.top = noticeBottom ? 'auto' : `${String(top)}px`;
565
+ notices.style.bottom = noticeBottom ? `${String(bottom)}px` : 'auto';
566
+ }
567
+
568
+ // Cursor events record occupancy without measuring the DOM. A frame
569
+ // coalesces placement decisions and uses the last measured geometry.
570
+ function sampleNoticeCursor() {
571
+ noticeFrame = null;
572
+ if (destroyed || sessionEnded) return;
573
+ const now = window.performance.now();
574
+ placeNotices(now);
575
+ // A frame can be delivered before an overdue timer after a long pause.
576
+ // Keep a callback armed while a covered stay is waiting for its deadline.
577
+ if (noticeStayEdge === (noticeBottom ? 'bottom' : 'top') &&
578
+ now - noticeStaySince < NOTICE_QUIET_MS) {
579
+ noticeFrame = window.requestAnimationFrame(sampleNoticeCursor);
580
+ }
581
+ }
582
+
583
+ function settleNoticeCursor() {
584
+ noticeTimer = null;
585
+ if (destroyed || sessionEnded) return;
586
+ // Timer deadlines can round down relative to performance.now(). Do not
587
+ // consume the only quiet check a fraction before its deadline.
588
+ const remaining = NOTICE_QUIET_MS - (window.performance.now() - noticeStaySince);
589
+ if (remaining > 100) {
590
+ noticeTimer = setTimeout(settleNoticeCursor, remaining - 100);
591
+ return;
592
+ }
593
+ if (noticeFrame === null) noticeFrame = window.requestAnimationFrame(sampleNoticeCursor);
594
+ if (remaining > 0) {
595
+ // The armed frame can start just before the deadline and finish just
596
+ // after it. Check at the deadline too, before that frame is delivered.
597
+ noticeTimer = setTimeout(settleNoticeCursor, remaining);
598
+ } else {
599
+ placeNotices(window.performance.now());
600
+ }
601
+ }
602
+
603
+ function checkNoticeEvidence() {
604
+ noticeEvidenceTimer = null;
605
+ if (destroyed || sessionEnded || (noticeStayEdge !== null &&
606
+ window.performance.now() - noticeStaySince >= NOTICE_QUIET_MS)) return;
607
+ // An active leg accumulates covered time even without cursor events.
608
+ // Bound decision latency without adding DOM measurements or a timer
609
+ // that continues after rest, disposal or the session ending.
610
+ if (noticeFrame === null) noticeFrame = window.requestAnimationFrame(sampleNoticeCursor);
611
+ noticeEvidenceTimer = setTimeout(checkNoticeEvidence, 50);
612
+ }
613
+
614
+ function scheduleNoticeCursor() {
615
+ if (destroyed || sessionEnded) return;
616
+ const row = term.buffer.active.cursorY;
617
+ // Horizontal typing and animation cannot distinguish a repaint from
618
+ // rest. Only a new row starts another leg or restarts the quiet timer.
619
+ const now = window.performance.now();
620
+ if (noticeVisits[noticeVisits.length - 1]?.row === row) return;
621
+ const edge = noticeCoversRow(row, false) ? 'top' : noticeCoversRow(row, true) ? 'bottom' : null;
622
+ if (noticeStayEdge !== null && edge !== noticeStayEdge && now - noticeStaySince >= NOTICE_QUIET_MS) {
623
+ // A genuine rest ends the preceding repaint. Its idle time must not
624
+ // outweigh the evidence delivered by the next staged redraw.
625
+ // Retain a zero-duration boundary so a later layout is not mistaken
626
+ // for the first placement of a newly shown notice.
627
+ noticeVisits.splice(0, noticeVisits.length - 1);
628
+ if (noticeVisits.length) noticeVisits[0].since = now;
629
+ finishNoticeRest();
630
+ noticeCycle = null;
631
+ noticeCycleVisits = [];
632
+ noticeCycleMoves = 0;
633
+ noticeAnchor = edge === null ? null : row;
634
+ }
635
+ if (edge !== noticeStayEdge) {
636
+ noticeStayEdge = edge;
637
+ noticeStaySince = edge === null ? null : now;
638
+ noticeStayMoved = false;
639
+ noticeStayPreviousRepaint = undefined;
640
+ }
641
+ trimNoticeVisits(now);
642
+ // An uncovered preparation row can recur within a longer repaint.
643
+ // Anchor a complete cycle at the first row inside either rectangle.
644
+ if (noticeAnchor === null && edge !== null) {
645
+ noticeAnchor = row;
646
+ noticeCycleVisits = [];
647
+ noticeCycleMoves = 0;
648
+ }
649
+ rememberNoticeCycle(row, now);
650
+ noticeLegMoved = false;
651
+ noticeVisits.push({ row, since: now });
652
+ if (noticeAnchor !== null) noticeCycleVisits.push({ row, since: now });
653
+ trimNoticeVisits(now);
654
+ noticeLastMove = now;
655
+ clearNoticeTimer();
656
+ // The final move must win even when no more cursor events arrive.
657
+ if (noticeStayEdge !== null) noticeTimer = setTimeout(settleNoticeCursor,
658
+ Math.max(0, NOTICE_QUIET_MS - (now - noticeStaySince) - 100));
659
+ noticeEvidenceTimer = setTimeout(checkNoticeEvidence, 50);
660
+ if (noticeFrame === null) noticeFrame = window.requestAnimationFrame(sampleNoticeCursor);
661
+ }
662
+
663
+ function disposeNoticeTracking() {
664
+ if (noticeDisposed) return;
665
+ noticeDisposed = true;
666
+ noticeCursorListener.dispose();
667
+ noticeResizeObserver.disconnect();
668
+ if (noticeFrame !== null) window.cancelAnimationFrame(noticeFrame);
669
+ noticeFrame = null;
670
+ clearNoticeTimer();
671
+ noticeVisits.length = 0;
672
+ }
673
+
674
+ // Alerts and layout changes measure once and place from existing evidence.
675
+ // A held grid can be centred, so anchor to its screen, not the outer box.
676
+ function positionNotices(initialPlacement = false) {
677
+ if (destroyed) return;
278
678
  const notices = elements.promptAlert?.parentElement || elements.banner?.parentElement;
279
679
  const wrap = container.parentElement;
280
680
  const screen = term.element?.querySelector('.xterm-screen');
@@ -282,15 +682,51 @@ window.ShellPuppetPane = (() => {
282
682
  const screenRect = screen.getBoundingClientRect();
283
683
  const wrapRect = wrap.getBoundingClientRect();
284
684
  notices.style.maxHeight = `${String(screenRect.height / 3)}px`;
285
- if (term.buffer.active.cursorY < term.rows / 2) {
286
- notices.style.top = 'auto';
287
- notices.style.bottom = `${String(wrapRect.bottom - screenRect.bottom)}px`;
288
- } else {
289
- notices.style.bottom = 'auto';
290
- notices.style.top = `${String(screenRect.top - wrapRect.top)}px`;
685
+ const noticeHeight = notices.getBoundingClientRect().height;
686
+ const firstVisibleNotice = (!noticeSeen || noticeNewEpisode) && noticeHeight > 0;
687
+ if (noticeHeight > 0) { noticeSeen = true; noticeNewEpisode = false; }
688
+ noticeGeometry = { notices, top: screenRect.top - wrapRect.top,
689
+ bottom: wrapRect.bottom - screenRect.bottom, cell: screenRect.height / term.rows,
690
+ height: noticeHeight };
691
+ const now = window.performance.now();
692
+ const row = term.buffer.active.cursorY;
693
+ if (firstVisibleNotice && !sessionEnded) {
694
+ // Cursor time before a notice exists cannot decide its repaint edge.
695
+ noticeVisits.length = 0;
696
+ noticeVisits.push({ row, since: now });
697
+ noticeLastRepaint = -Infinity;
698
+ noticeLegMoved = false;
699
+ noticeStayPreviousRepaint = undefined;
700
+ noticeStayEdge = null;
701
+ noticeStaySince = null;
702
+ noticeStayMoved = false;
703
+ noticeAnchor = null;
704
+ noticeCycle = null;
705
+ noticeCycleVisits = [];
706
+ noticeCycleMoves = 0;
707
+ }
708
+ const edge = noticeCoversRow(row, false) ? 'top' : noticeCoversRow(row, true) ? 'bottom' : null;
709
+ if (edge !== noticeStayEdge) {
710
+ noticeStayEdge = edge;
711
+ noticeStaySince = edge === null ? null : now;
712
+ noticeStayMoved = false;
713
+ noticeStayPreviousRepaint = undefined;
714
+ clearNoticeTimer();
715
+ if (edge !== null && !noticeDisposed) {
716
+ noticeTimer = setTimeout(settleNoticeCursor, NOTICE_QUIET_MS - 100);
717
+ if (noticeFrame === null) noticeFrame = window.requestAnimationFrame(sampleNoticeCursor);
718
+ }
291
719
  }
720
+ // A repeated prompt control or resize must use the existing cadence.
721
+ // Only first visibility (including an alert after a hidden period longer
722
+ // than the retained history) and a completed snapshot can place immediately.
723
+ placeNotices(now, firstVisibleNotice || initialPlacement === true);
292
724
  }
293
- term.onCursorMove(positionNotices);
725
+ const noticeCursorListener = term.onCursorMove(scheduleNoticeCursor);
726
+ // Content can change height without a cursor move (including font loads).
727
+ const noticeResizeObserver = new window.ResizeObserver(positionNotices);
728
+ const noticeContainer = elements.promptAlert?.parentElement || elements.banner?.parentElement;
729
+ if (noticeContainer) noticeResizeObserver.observe(noticeContainer);
294
730
  positionNotices();
295
731
 
296
732
  if (redactedCapture) {
@@ -338,13 +774,10 @@ window.ShellPuppetPane = (() => {
338
774
  }
339
775
 
340
776
  function relayout(deliberate) {
777
+ if (destroyed) return;
341
778
  if (!geometryDecided) return;
342
- if (dashboardProof !== null) {
343
- applyFontPreference(gridCols, gridRows);
344
- positionNotices();
345
- return;
346
- }
347
- if (controlMode === 'held' || captureMode || (controlMode === 'adopt' && !deliberate)) {
779
+ if (dashboardProof !== null || passive || readOnlyEnforced || controlMode === 'held' ||
780
+ captureMode || (controlMode === 'adopt' && !deliberate)) {
348
781
  applyFontPreference(gridCols, gridRows);
349
782
  } else {
350
783
  requestFit();
@@ -356,7 +789,7 @@ window.ShellPuppetPane = (() => {
356
789
  const font = drivingFontPx();
357
790
  if (term.options.fontSize !== font) {
358
791
  term.options.fontSize = font;
359
- term.resize(term.cols, term.rows);
792
+ resizeTerminal(term.cols, term.rows, true);
360
793
  }
361
794
  updateZoomButtons();
362
795
  const proposed = propose();
@@ -370,38 +803,44 @@ window.ShellPuppetPane = (() => {
370
803
  }
371
804
 
372
805
  function propose() {
373
- let proposed;
374
- try {
375
- proposed = fit.proposeDimensions();
376
- } catch {
377
- return null;
378
- }
379
- if (!proposed || !proposed.cols || !proposed.rows) return null;
380
- return { cols: proposed.cols, rows: proposed.rows };
806
+ return proposeAtFont(term.options.fontSize);
381
807
  }
382
808
 
383
809
  function fixedFontPx() {
384
810
  return fontOverride === null ? DEFAULT_FONT_PX : fontOverride;
385
811
  }
386
812
 
813
+ function proposeAtFont(font) {
814
+ const style = window.getComputedStyle(container);
815
+ const terminalStyle = window.getComputedStyle(term.element);
816
+ const width = parseInt(style.width) - parseInt(terminalStyle.paddingLeft) - parseInt(terminalStyle.paddingRight) -
817
+ (term.options.scrollback === 0 ? 0 : term.options.overviewRuler?.width || 14);
818
+ const height = parseInt(style.height) - parseInt(terminalStyle.paddingTop) - parseInt(terminalStyle.paddingBottom);
819
+ if (!(width > 0 && height > 0)) return null;
820
+ // Use the unrounded cell in both clients. The DOM renderer rounds the
821
+ // whole canvas, so its CSS cell width changes with the current grid and
822
+ // can make a viewer request another resize on the geometry reply.
823
+ const cell = renderedCell(font);
824
+ if (!cell) return null;
825
+ let cols = Math.floor(width / cell.width);
826
+ let rows = Math.floor(height / cell.height);
827
+ // Include every whole cell whose rounded canvas fits, as gridFitsAtFont
828
+ // does, without depending on the current grid's rounded average cell.
829
+ while (Math.round((cols + 1) * cell.width) <= width) cols++;
830
+ while (Math.round((rows + 1) * cell.height) <= height) rows++;
831
+ return { cols: Math.max(2, cols), rows: Math.max(1, rows) };
832
+ }
833
+
387
834
  function proposeDashboardGrid() {
388
- const drawn = term.options.fontSize;
389
- let proposed;
390
- try {
391
- term.options.fontSize = fixedFontPx();
392
- proposed = propose();
393
- if (proposed === null) return null;
394
- if (proposed.cols > gridMax.cols || proposed.rows > gridMax.rows) {
395
- for (let font = fixedFontPx() + 1; font <= MAX_FONT_PX; font++) {
396
- term.options.fontSize = font;
397
- const larger = propose();
398
- if (larger === null ||
399
- (larger.cols < gridMax.cols && larger.rows < gridMax.rows)) break;
400
- proposed = larger;
401
- }
835
+ let proposed = proposeAtFont(fixedFontPx());
836
+ if (proposed === null) return null;
837
+ if (proposed.cols > gridMax.cols || proposed.rows > gridMax.rows) {
838
+ for (let font = fixedFontPx() + 1; font <= MAX_FONT_PX; font++) {
839
+ const larger = proposeAtFont(font);
840
+ if (larger === null ||
841
+ (larger.cols < gridMax.cols && larger.rows < gridMax.rows)) break;
842
+ proposed = larger;
402
843
  }
403
- } finally {
404
- term.options.fontSize = drawn;
405
844
  }
406
845
  return proposed;
407
846
  }
@@ -423,36 +862,105 @@ window.ShellPuppetPane = (() => {
423
862
  return font;
424
863
  }
425
864
 
426
- function fitGridByFont(cols, rows, grow = true) {
865
+ function availableSpace() {
427
866
  const wrap = container.parentElement;
428
- if (!wrap) return;
429
-
867
+ if (!wrap) return null;
430
868
  const styles = window.getComputedStyle(wrap);
431
- const availableWidth = wrap.clientWidth
432
- - parseFloat(styles.paddingLeft) - parseFloat(styles.paddingRight);
433
- const availableHeight = wrap.clientHeight
434
- - parseFloat(styles.paddingTop) - parseFloat(styles.paddingBottom);
435
- if (availableWidth <= 0 || availableHeight <= 0) return;
869
+ const width = wrap.clientWidth - parseFloat(styles.paddingLeft) - parseFloat(styles.paddingRight);
870
+ const height = wrap.clientHeight - parseFloat(styles.paddingTop) - parseFloat(styles.paddingBottom);
871
+ return width > 0 && height > 0 ? { width, height } : null;
872
+ }
436
873
 
437
- for (let pass = 0; pass < 4; pass++) {
438
- const screen = term.element && term.element.querySelector('.xterm-screen');
439
- if (!screen) return;
440
- const renderedWidth = screen.offsetWidth;
441
- const renderedHeight = screen.offsetHeight;
442
- if (renderedWidth <= 0 || renderedHeight <= 0) return;
874
+ function fontSettings() {
875
+ const options = term.options;
876
+ return JSON.stringify([fontGeneration, window.devicePixelRatio, options.fontFamily,
877
+ options.fontWeight, options.fontWeightBold, options.letterSpacing, options.lineHeight]);
878
+ }
443
879
 
444
- const scale = Math.min(
445
- availableWidth / renderedWidth,
446
- availableHeight / renderedHeight,
447
- );
448
- if (Math.abs(scale - 1) < 0.01 || (scale > 1 && !grow)) return;
880
+ function renderedCell(font) {
881
+ const key = `${fontSettings()}:${font}`;
882
+ if (cellMetrics.has(key)) return cellMetrics.get(key);
883
+ const drawn = term.options.fontSize;
884
+ try {
885
+ // A fit can run after loadingdone but before the font refresh frame.
886
+ // Setting the current size again does not make xterm measure it.
887
+ if (font === drawn) term._core._charSizeService.measure();
888
+ else term.options.fontSize = font;
889
+ // xterm's DOM renderer rounds the complete canvas to CSS pixels. Cache
890
+ // the unrounded cell so a different grid cannot inherit that rounding.
891
+ const cell = term._core._renderService.dimensions.device.cell;
892
+ const dpr = window.devicePixelRatio;
893
+ if (!(cell.width > 0 && cell.height > 0)) return null;
894
+ return remember(cellMetrics, key, { width: cell.width / dpr, height: cell.height / dpr });
895
+ } finally {
896
+ term.options.fontSize = drawn;
897
+ }
898
+ }
449
899
 
450
- const current = term.options.fontSize || DEFAULT_FONT_PX;
451
- const next = Math.min(MAX_FONT_PX, Math.max(MIN_FONT_PX, Math.floor(current * scale)));
452
- if (next === current) return;
900
+ function gridFitsAtFont(cols, rows, font, space) {
901
+ const cell = renderedCell(font);
902
+ return cell !== null && Math.round(cell.width * cols) <= space.width &&
903
+ Math.round(cell.height * rows) <= space.height;
904
+ }
453
905
 
454
- term.options.fontSize = next;
455
- term.resize(cols, rows);
906
+ function largestFittingFont(cols, rows, maximum = MAX_FONT_PX, minimum = MIN_FONT_PX) {
907
+ const space = availableSpace();
908
+ if (!space || cols <= 0 || rows <= 0) return null;
909
+ const key = JSON.stringify([fontSettings(), space.width, space.height, cols, rows, maximum, minimum]);
910
+ if (fittingFonts.has(key)) return fittingFonts.get(key);
911
+ let low = minimum;
912
+ let high = maximum;
913
+ let best = 0;
914
+ while (low <= high) {
915
+ const font = Math.floor((low + high) / 2);
916
+ if (gridFitsAtFont(cols, rows, font, space)) {
917
+ best = font;
918
+ low = font + 1;
919
+ } else high = font - 1;
920
+ }
921
+ if (best === 0 && minimum === 1) {
922
+ // Even one pixel per row can exceed a very small held pane.
923
+ // Scale that minimum uniformly so its whole screen remains visible.
924
+ const cell = renderedCell(1);
925
+ if (cell) {
926
+ best = Math.min(maximum, space.width / Math.round(cell.width * cols),
927
+ space.height / Math.round(cell.height * rows));
928
+ }
929
+ }
930
+ return remember(fittingFonts, key, best || minimum);
931
+ }
932
+
933
+ function belowDashboardFloor(cols = 80, rows = 24) {
934
+ const space = availableSpace();
935
+ if (!space) return false;
936
+ return !gridFitsAtFont(cols, rows, fixedFontPx(), space);
937
+ }
938
+
939
+ function fitGridByFont(cols, rows, maximum = MAX_FONT_PX) {
940
+ const minimum = dashboardProof !== null || passive || readOnlyEnforced ? 1 : MIN_FONT_PX;
941
+ const font = largestFittingFont(cols, rows, maximum, minimum);
942
+ if (font !== null) drawFont(font);
943
+ }
944
+
945
+ function drawFont(font) {
946
+ term.options.fontSize = Math.max(1, font);
947
+ fontScale = Math.min(1, font);
948
+ if (fontScale === 1 && scaledSelection === container) scaledSelection = null;
949
+ term.element.style.transform = fontScale < 1 ? `scale(${fontScale})` : '';
950
+ container.dataset.fontSize = String(font);
951
+ // Font measurement can leave xterm's history viewport at a candidate's
952
+ // dimensions. Sync once after the final display size, then restore the
953
+ // history row with the new cell height. Both callbacks run after render.
954
+ if (!viewportSyncPending) {
955
+ viewportSyncPending = true;
956
+ term._core._viewport.queueSync();
957
+ term._core._renderService.addRefreshCallback(() => {
958
+ viewportSyncPending = false;
959
+ // Terminal.scrollToLine is a no-op when the buffer is already on
960
+ // this row, even if the viewport still has the old pixel offset.
961
+ // Read the row now so output received before paint is kept too.
962
+ if (!destroyed) term._core._viewport.scrollToLine(term.buffer.active.viewportY, true);
963
+ });
456
964
  }
457
965
  }
458
966
 
@@ -471,31 +979,41 @@ window.ShellPuppetPane = (() => {
471
979
  }
472
980
 
473
981
  function applyFontPreference(cols, rows) {
474
- if (fontOverride === null) {
982
+ if (dashboardProof !== null && dashboardFontLimit !== null) {
983
+ const font = largestFittingFont(cols, rows, dashboardFontLimit, 1);
984
+ if (font !== null) drawFont(font);
985
+ } else if (fontOverride === null) {
475
986
  fitGridByFont(cols, rows);
987
+ } else if (passive || readOnlyEnforced) {
988
+ fitGridByFont(cols, rows, fontOverride);
989
+ } else if (dashboardProof !== null) {
990
+ const capped = cols >= gridMax.cols || rows >= gridMax.rows;
991
+ // Retained owned grids must still fit when Auto fit is off. The saved
992
+ // size is the ceiling unless an owned grid has reached its size cap.
993
+ fitGridByFont(cols, rows, capped && controlMode === 'yours' ? MAX_FONT_PX : fontOverride);
476
994
  } else {
477
- if (term.options.fontSize !== fontOverride) {
478
- term.options.fontSize = fontOverride;
479
- term.resize(cols, rows);
480
- }
481
- if (dashboardProof !== null) {
482
- const capped = cols >= gridMax.cols || rows >= gridMax.rows;
483
- if (controlMode !== 'yours' || capped) fitGridByFont(cols, rows, capped && controlMode === 'yours');
484
- }
995
+ drawFont(fontOverride);
485
996
  }
486
997
  updateZoomButtons();
487
- container.dataset.fontSize = String(term.options.fontSize);
488
998
  updateOverflowState();
489
999
  }
490
1000
 
491
1001
  function applyGeometry(cols, rows, max) {
492
1002
  if (!Number.isInteger(cols) || !Number.isInteger(rows)) return;
1003
+ const resized = term.cols !== cols || term.rows !== rows;
493
1004
  gridCols = cols;
494
1005
  gridRows = rows;
495
1006
  if (max && Number.isInteger(max.cols) && Number.isInteger(max.rows)) {
496
1007
  gridMax = { cols: max.cols, rows: max.rows };
497
1008
  }
498
- if (term.cols !== cols || term.rows !== rows) term.resize(cols, rows);
1009
+ // Compare at the parser boundary: another geometry frame may be queued.
1010
+ resizeTerminal(cols, rows);
1011
+ if (resized) {
1012
+ // A resize during a header excursion must not discard the prompt's
1013
+ // occupancy. Clamp rows lost from a smaller grid; subsequent cursor
1014
+ // events and the quiet fallback account for the arriving snapshot.
1015
+ for (const visit of noticeVisits) visit.row = Math.min(visit.row, rows - 1);
1016
+ }
499
1017
  if (controlMode === 'yours' && !captureMode && dashboardProof === null) {
500
1018
  updateZoomButtons();
501
1019
  } else {
@@ -507,6 +1025,7 @@ window.ShellPuppetPane = (() => {
507
1025
  (controlMode === 'held' ? ' (fixed)' : controlMode === 'adopt' ? ' (following)' : '');
508
1026
  }
509
1027
  positionNotices();
1028
+ onGeometryChange();
510
1029
  }
511
1030
 
512
1031
  function updateZoomButtons() {
@@ -518,20 +1037,10 @@ window.ShellPuppetPane = (() => {
518
1037
  }
519
1038
 
520
1039
  function setFontOverride(value) {
1040
+ if (destroyed) return;
521
1041
  fontOverride = value;
522
1042
  onFontOverrideChange(value);
523
- if (dashboardProof !== null) {
524
- applyFontPreference(gridCols, gridRows);
525
- positionNotices();
526
- return;
527
- }
528
- if (controlMode === 'held' || captureMode) {
529
- applyFontPreference(gridCols, gridRows);
530
- positionNotices();
531
- return;
532
- }
533
- requestFit();
534
- positionNotices();
1043
+ relayout(true);
535
1044
  }
536
1045
 
537
1046
  function nudgeFont(delta) {
@@ -549,34 +1058,75 @@ window.ShellPuppetPane = (() => {
549
1058
 
550
1059
  function connect() {
551
1060
  if (destroyed) return;
552
- ws = new WebSocket(`ws://${location.host}/sessions/${encodeURIComponent(sessionId)}/stream`,
1061
+ ws = new WebSocket(`ws://${location.host}/sessions/${encodeURIComponent(sessionId)}/stream${passive ? '?drive=0' : ''}`,
553
1062
  dashboardProof === null ? undefined : [`sp-csrf.${dashboardProof}`]);
1063
+ const socket = ws;
554
1064
  ws.binaryType = 'arraybuffer';
555
1065
 
556
1066
  ws.onopen = () => {
1067
+ if (destroyed) return;
1068
+ // A reconnect may have missed a clear. The daemon replays the current
1069
+ // prompt and stall with a fresh snapshot, so drop both and place what
1070
+ // it replays as a new notice from that snapshot.
1071
+ const reconnected = everConnected;
1072
+ if (reconnected) {
1073
+ promptWaiting = false;
1074
+ firstFrameSeen = false;
1075
+ }
1076
+ clearStallAlert();
1077
+ if (reconnected) noticeHiddenAt = null;
557
1078
  everConnected = true;
558
1079
  if (elements.dot) elements.dot.classList.remove('off');
559
1080
  if (elements.banner) elements.banner.hidden = true;
560
1081
  retriesLeft = 8;
561
1082
  geometryDecided = false;
1083
+ if (pendingTakeSocket !== socket) {
1084
+ pendingTakeGrid = false;
1085
+ pendingTakeSize = null;
1086
+ pendingTakeSocket = null;
1087
+ }
562
1088
  };
563
1089
 
564
1090
  ws.onmessage = (event) => {
565
1091
  if (destroyed) return;
566
1092
  if (event.data instanceof ArrayBuffer) {
567
1093
  if (redactedCapture && window.__shellpuppetPainted === true) return;
568
- if (captureMode && !firstFrameSeen) {
1094
+ if (!firstFrameSeen) {
569
1095
  firstFrameSeen = true;
570
- term.write(new Uint8Array(event.data), () => {
1096
+ writeTerminal(new Uint8Array(event.data), () => {
1097
+ if (destroyed) return;
1098
+ // Snapshot parsing is asynchronous and may follow an ended
1099
+ // identity or an alert. Its intermediate rows are not repaint
1100
+ // history. Place once at its final cursor, even after tracking
1101
+ // has been disposed; ordinary stream chunks need no layout.
1102
+ noticeVisits.length = 0;
1103
+ noticeLegMoved = false;
1104
+ noticeStayPreviousRepaint = undefined;
1105
+ noticeLastRepaint = -Infinity;
1106
+ noticeCycle = null;
1107
+ noticeAnchor = null;
1108
+ noticeCycleVisits = [];
1109
+ noticeCycleMoves = 0;
1110
+ noticeStayEdge = null;
1111
+ noticeStaySince = null;
1112
+ noticeStayMoved = false;
1113
+ if (!noticeDisposed) {
1114
+ noticeLastMove = window.performance.now();
1115
+ noticeVisits.push({ row: term.buffer.active.cursorY, since: noticeLastMove });
1116
+ }
1117
+ positionNotices(true);
1118
+ if (!captureMode) return;
571
1119
  window.requestAnimationFrame(() => {
1120
+ if (destroyed) return;
572
1121
  window.requestAnimationFrame(() => {
1122
+ if (destroyed) return;
573
1123
  window.__shellpuppetPainted = true;
574
1124
  });
575
1125
  });
576
1126
  });
577
1127
  return;
578
1128
  }
579
- term.write(new Uint8Array(event.data));
1129
+ writeTerminal(new Uint8Array(event.data));
580
1130
  return;
581
1131
  }
582
1132
  try {
@@ -587,31 +1137,53 @@ window.ShellPuppetPane = (() => {
587
1137
  const firstGeometry = !geometryDecided;
588
1138
  geometryDecided = true;
589
1139
  controlMode = captureMode ? 'adopt' : control.control || 'adopt';
1140
+ const wasOffered = transferOffered;
1141
+ transferOffered = controlMode === 'adopt' && control.dashboardTransferable === true;
1142
+ const wasTemporary = temporaryGeometry;
1143
+ temporaryGeometry = control.temporary === true;
1144
+ if (pendingTakeSocket !== null && pendingTakeSocket !== socket) {
1145
+ pendingTakeGrid = false;
1146
+ pendingTakeSize = null;
1147
+ pendingTakeSocket = null;
1148
+ }
1149
+ if (controlMode === 'held') {
1150
+ pendingTakeGrid = false;
1151
+ pendingTakeSize = null;
1152
+ pendingTakeSocket = null;
1153
+ }
590
1154
  if (dashboardProof !== null && firstGeometry && controlMode === 'yours') {
1155
+ followingExternal = false;
591
1156
  pendingTakeGrid = false;
1157
+ pendingTakeSize = null;
1158
+ pendingTakeSocket = null;
592
1159
  onGridTaken();
593
1160
  }
594
- if (dashboardProof !== null && !firstGeometry) {
1161
+ if (dashboardProof !== null && (!firstGeometry || control.owned === true)) {
595
1162
  if (controlMode === 'yours' && pendingTakeGrid) {
1163
+ followingExternal = false;
596
1164
  pendingTakeGrid = false;
1165
+ pendingTakeSize = null;
1166
+ pendingTakeSocket = null;
597
1167
  onGridTaken();
598
- } else if (controlMode === 'adopt' && !followingExternal) {
1168
+ } else if (controlMode === 'adopt' && !followingExternal && !transferOffered) {
599
1169
  pendingTakeGrid = false;
600
- if (Date.now() - lastOutsideFitAt < 10_000) {
601
- followingExternal = true;
602
- outsideResizePending = false;
603
- } else {
604
- outsideResizePending = true;
605
- onOutsideGeometry();
606
- }
1170
+ pendingTakeSize = null;
1171
+ pendingTakeSocket = null;
1172
+ followingExternal = true;
1173
+ onOutsideGeometry();
1174
+ } else if (transferOffered) {
1175
+ followingExternal = false;
607
1176
  }
608
1177
  }
609
1178
  applyGeometry(control.cols, control.rows, control.max);
610
- if (firstGeometry) onGeometryReady();
611
- if (controlMode === 'yours' && !captureMode && dashboardProof === null) requestFit();
1179
+ if (firstGeometry || (transferOffered && !wasOffered) || (wasTemporary && !temporaryGeometry)) onGeometryReady();
1180
+ if (controlMode === 'yours' && !temporaryGeometry && !captureMode && dashboardProof === null) requestFit();
612
1181
  } else if (control && control.type === 'identity') {
613
1182
  showIdentity(control);
614
1183
  } else if (control && control.type === 'exited') {
1184
+ pendingTakeGrid = false;
1185
+ pendingTakeSize = null;
1186
+ pendingTakeSocket = null;
615
1187
  showEnded(control.exitCode);
616
1188
  } else if (control && control.type === 'input-refused') {
617
1189
  if (control.reason === 'exited') showEnded(control.exitCode);
@@ -620,6 +1192,10 @@ window.ShellPuppetPane = (() => {
620
1192
  showPromptAlert(control.question, control.waitingMs, control.options);
621
1193
  } else if (control && control.type === 'prompt-clear') {
622
1194
  clearPromptAlert();
1195
+ } else if (control && control.type === 'session-stalled') {
1196
+ showStallAlert(control.stalled);
1197
+ } else if (control && control.type === 'session-stall-clear') {
1198
+ clearStallAlert();
623
1199
  }
624
1200
  } catch {
625
1201
  // Unknown text frame: ignore rather than corrupt the terminal.
@@ -627,6 +1203,11 @@ window.ShellPuppetPane = (() => {
627
1203
  };
628
1204
 
629
1205
  ws.onclose = () => {
1206
+ if (pendingTakeSocket === socket) {
1207
+ pendingTakeGrid = false;
1208
+ pendingTakeSize = null;
1209
+ pendingTakeSocket = null;
1210
+ }
630
1211
  if (destroyed) return;
631
1212
  if (elements.dot) elements.dot.classList.add('off');
632
1213
  if (retriesLeft-- > 0) {
@@ -648,18 +1229,30 @@ window.ShellPuppetPane = (() => {
648
1229
  connect();
649
1230
 
650
1231
  return {
651
- destroy() {
1232
+ destroy(reassigned = false) {
1233
+ if (destroyed) return;
652
1234
  destroyed = true;
1235
+ fontListeners.delete(refreshFontMetrics);
1236
+ resolutionListener.dispose();
1237
+ if (metricsFrame !== null) window.cancelAnimationFrame(metricsFrame);
1238
+ disposeNoticeTracking();
1239
+ if (scaledSelection === container) scaledSelection = null;
1240
+ for (const type of scaledMouseEvents) document.removeEventListener(type, scaleMouseEvent, true);
653
1241
  outerScroll?.removeEventListener('wheel', scrollOversizedPane, true);
654
1242
  clearTimeout(reconnectTimer);
655
- if (ws) ws.close();
1243
+ if (ws) {
1244
+ if (reassigned && dashboardProof !== null && ws.readyState === 1)
1245
+ ws.send(JSON.stringify({ type: 'release-grid' }));
1246
+ ws.close();
1247
+ }
656
1248
  if (redactedCapture) delete window.__shellpuppetCoverRows;
657
- term.dispose();
1249
+ if (pendingWrites === 0) releaseTerminal();
658
1250
  },
659
1251
  setFontOverride(value) {
660
1252
  setFontOverride(value);
661
1253
  },
662
1254
  nudgeFont(delta) {
1255
+ if (destroyed) return;
663
1256
  nudgeFont(delta);
664
1257
  },
665
1258
  getFontOverride() {
@@ -685,49 +1278,64 @@ window.ShellPuppetPane = (() => {
685
1278
  getGrid() {
686
1279
  return { cols: gridCols, rows: gridRows };
687
1280
  },
1281
+ belowDashboardFloor() {
1282
+ if (destroyed) return false;
1283
+ return belowDashboardFloor();
1284
+ },
1285
+ floorFontSize() {
1286
+ if (destroyed) return null;
1287
+ return largestFittingFont(80, 24, MAX_FONT_PX, 1);
1288
+ },
1289
+ setDashboardFontLimit(font) {
1290
+ if (destroyed) return;
1291
+ dashboardFontLimit = font;
1292
+ if (geometryDecided) applyFontPreference(gridCols, gridRows);
1293
+ positionNotices();
1294
+ },
688
1295
  autoFitGrid(floorCols = 80, floorRows = 24, force = false) {
689
- if (dashboardProof === null || controlMode === 'held' || (followingExternal && !force) || !geometryDecided ||
1296
+ if (destroyed) return false;
1297
+ if (dashboardProof === null || controlMode === 'held' || (temporaryGeometry && !force) ||
1298
+ (followingExternal && !force) || !geometryDecided ||
690
1299
  !ws || ws.readyState !== 1 || sessionEnded) return false;
691
1300
  if (force) {
692
1301
  followingExternal = false;
693
- outsideResizePending = false;
694
- lastOutsideFitAt = 0;
695
1302
  }
696
1303
  let proposed = proposeDashboardGrid();
697
1304
  if (proposed === null) {
698
1305
  if (container.clientWidth <= 0 || container.clientHeight <= 0) return false;
699
1306
  proposed = { cols: floorCols, rows: floorRows };
700
1307
  }
701
- const cols = Math.min(gridMax.cols, Math.max(floorCols, proposed.cols));
702
- const rows = Math.min(gridMax.rows, Math.max(floorRows, proposed.rows));
703
- if (cols === gridCols && rows === gridRows && !force) return false;
704
- if (outsideResizePending) lastOutsideFitAt = Date.now();
705
- outsideResizePending = false;
706
- return this.takeGrid(cols, rows);
1308
+ const belowFloor = belowDashboardFloor(floorCols, floorRows);
1309
+ const cols = Math.min(gridMax.cols, belowFloor ? floorCols : Math.max(floorCols, proposed.cols));
1310
+ const rows = Math.min(gridMax.rows, belowFloor ? floorRows : Math.max(floorRows, proposed.rows));
1311
+ if (cols === gridCols && rows === gridRows && !force && !transferOffered) return false;
1312
+ if (pendingTakeSocket === ws && pendingTakeSize?.cols === cols && pendingTakeSize?.rows === rows) return false;
1313
+ return this.takeGrid(cols, rows, transferOffered);
707
1314
  },
708
- takeGrid(cols, rows) {
1315
+ isTemporaryGeometry() { return temporaryGeometry; },
1316
+ takeGrid(cols, rows, acceptOffer = false) {
1317
+ if (destroyed) return false;
709
1318
  if (dashboardProof === null || !ws || ws.readyState !== 1 || !geometryDecided) return false;
710
1319
  const wanted = { cols: Math.max(2, Math.min(400, cols)), rows: Math.max(2, Math.min(150, rows)) };
711
1320
  pendingTakeGrid = true;
712
- ws.send(JSON.stringify({ type: 'resize', ...wanted, take: true }));
1321
+ pendingTakeSize = wanted;
1322
+ pendingTakeSocket = ws;
1323
+ ws.send(JSON.stringify({ type: 'resize', ...wanted, take: true, ...(acceptOffer ? { acceptOffer } : {}) }));
713
1324
  return true;
714
1325
  },
715
- fitGrid(floorCols = 0, floorRows = 0) {
1326
+ fitGrid(floorCols = 80, floorRows = 24) {
1327
+ if (destroyed) return false;
716
1328
  if (dashboardProof === null) return false;
717
1329
  followingExternal = false;
718
- outsideResizePending = false;
719
- lastOutsideFitAt = 0;
720
- if (term.options.fontSize !== fixedFontPx()) {
721
- term.options.fontSize = fixedFontPx();
722
- term.resize(term.cols, term.rows);
723
- }
724
1330
  const proposed = proposeDashboardGrid();
1331
+ if (belowDashboardFloor(floorCols, floorRows)) return this.takeGrid(floorCols, floorRows);
725
1332
  return proposed !== null && this.takeGrid(
726
1333
  Math.max(floorCols, proposed.cols), Math.max(floorRows, proposed.rows));
727
1334
  },
728
1335
  fitAfterDrag(useAutoFit) {
729
1336
  if (controlMode === 'held' || captureMode || !geometryDecided) return false;
730
- return useAutoFit ? this.autoFitGrid(80, 24) : this.fitGrid(80, 24);
1337
+ // A deliberate drag still takes its grid when the floor is unchanged.
1338
+ return useAutoFit ? this.autoFitGrid(80, 24, true) : this.fitGrid(80, 24);
731
1339
  },
732
1340
  };
733
1341
  }