dsh-conversation-float 0.1.2 → 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.
package/client.js CHANGED
@@ -10,12 +10,12 @@
10
10
  * the panel (same document, same React root, so events and reconciliation keep
11
11
  * working) and moved back to its seat when the panel closes.
12
12
  *
13
- * While the float is on screen it can be dragged onto three drop bands:
13
+ * While the window is on screen it can be dragged onto three drop bands:
14
14
  *
15
- * left the float is stowed — still mounted, hidden — and the left sidebar
16
- * grows a row that brings it back; the centre column stays empty,
17
- * exactly as it is while the float is on screen
18
- * center the float closes and the Conversation returns to its column
15
+ * left the window minimises — still mounted, hidden — and its taskbar row
16
+ * in the left sidebar brings it back; the centre column stays empty,
17
+ * exactly as it is while the window is on screen
18
+ * center the window closes and the Conversation returns to its column
19
19
  * right the tab is handed to the right sidebar, where DSH docks it
20
20
  *
21
21
  * The bands are measured once per drag. Holding the press for {@link DWELL_MS}
@@ -29,10 +29,25 @@ window.__ModuleLoader__.load({
29
29
  'use strict'
30
30
 
31
31
  const React = require('react')
32
+ const ReactDOM = require('react-dom')
32
33
  const h = React.createElement
33
34
 
34
35
  const NS = 'dsh-conversation-float'
35
36
 
37
+ /**
38
+ * The dock kit's own menu row. It ships in the browser module table, the same
39
+ * place React comes from, so a client bundle may require it without declaring
40
+ * anything extra; the plain button is only for a host that lacks it.
41
+ */
42
+ const primitives = (() => {
43
+ try {
44
+ return require('@deepseek-ai/dsh-client-ui-primitives') ?? null
45
+ } catch {
46
+ return null
47
+ }
48
+ })()
49
+ const MenuItemButton = primitives?.MenuItemButton ?? null
50
+
36
51
  /**
37
52
  * Copy for every locale DSH ships. The word for the Conversation is read
38
53
  * from this table only, so the panel title, the sidebar row and the entry
@@ -43,72 +58,124 @@ window.__ModuleLoader__.load({
43
58
  "conversation": "会话",
44
59
  "floatTitle": "会话浮窗",
45
60
  "showDsh": "显示 DSH 界面",
61
+ "hideDsh": "隐藏 DSH 界面",
62
+ "moveLeft": "会话收至此处",
63
+
64
+ "moveRight": "会话移至此处",
46
65
  "stow": "放进左栏",
47
66
  "center": "回到中间",
48
67
  "dock": "停到右栏",
68
+ "toMain": "将主对话",
69
+ "switchTo": "切换到当前会话",
70
+ "minimize": "收起浮窗",
71
+ "close": "关闭浮窗",
49
72
  "description": "把会话视图做成 DSH 自带的浮窗:拖到左边收进左栏抽屉、拖到中间回到中栏、拖到右边停进右侧栏。"
50
73
  },
51
74
  "en": {
52
75
  "conversation": "Conversation",
53
76
  "floatTitle": "Conversation float",
54
77
  "showDsh": "Show DSH",
78
+ "hideDsh": "Hide DSH",
79
+ "moveLeft": "Stow the conversation here",
80
+
81
+ "moveRight": "Move the conversation here",
55
82
  "stow": "Stow in the left sidebar",
56
83
  "center": "Return to the middle",
57
84
  "dock": "Dock in the right sidebar",
85
+ "toMain": "Main conversation: ",
86
+ "switchTo": "Switch to this conversation",
87
+ "minimize": "Minimize",
88
+ "close": "Close",
58
89
  "description": "Turns the Conversation view into DSH own floating panel: drag it left to stow it in the sidebar drawer, centre to return it to the middle column, right to dock it in the right sidebar."
59
90
  },
60
91
  "de": {
61
92
  "conversation": "Konversation",
62
93
  "floatTitle": "Konversations-Float",
63
94
  "showDsh": "DSH anzeigen",
95
+ "hideDsh": "DSH ausblenden",
96
+ "moveLeft": "Konversation hierher legen",
97
+
98
+ "moveRight": "Konversation hierher verschieben",
64
99
  "stow": "In der linken Seitenleiste ablegen",
65
100
  "center": "Zurück in die Mitte",
66
101
  "dock": "In der rechten Seitenleiste andocken",
102
+ "toMain": "Hauptkonversation: ",
103
+ "switchTo": "Zu dieser Konversation wechseln",
67
104
  "description": "Macht die Konversationsansicht zu DSH eigenem schwebenden Panel: nach links ziehen legt sie in der linken Seitenleiste ab, Mitte bringt sie zurück, rechts dockt sie rechts an."
68
105
  },
69
106
  "es": {
70
107
  "conversation": "Conversación",
71
108
  "floatTitle": "Ventana flotante de conversación",
72
109
  "showDsh": "Mostrar DSH",
110
+ "hideDsh": "Ocultar DSH",
111
+ "moveLeft": "Guardar la conversación aquí",
112
+
113
+ "moveRight": "Mover la conversación aquí",
73
114
  "stow": "Guardar en la barra izquierda",
74
115
  "center": "Volver al centro",
75
116
  "dock": "Acoplar en la barra derecha",
117
+ "toMain": "Conversación principal: ",
118
+ "switchTo": "Cambiar a esta conversación",
76
119
  "description": "Convierte la vista de conversación en el panel flotante propio de DSH: a la izquierda se guarda en la barra lateral, al centro vuelve a la columna central, a la derecha se acopla a la barra derecha."
77
120
  },
78
121
  "fr": {
79
122
  "conversation": "Conversation",
80
123
  "floatTitle": "Fenêtre flottante de conversation",
81
124
  "showDsh": "Afficher DSH",
125
+ "hideDsh": "Masquer DSH",
126
+ "moveLeft": "Ranger la conversation ici",
127
+
128
+ "moveRight": "Déplacer la conversation ici",
82
129
  "stow": "Placer dans la barre latérale gauche",
83
130
  "center": "Revenir au centre",
84
131
  "dock": "Ancrer dans la barre latérale droite",
132
+ "toMain": "Conversation principale : ",
133
+ "switchTo": "Passer à cette conversation",
85
134
  "description": "Transforme la vue de conversation en panneau flottant propre à DSH : à gauche il se range dans la barre latérale, au centre il revient dans la colonne, à droite il s ancre à droite."
86
135
  },
87
136
  "ja": {
88
137
  "conversation": "会話",
89
138
  "floatTitle": "会話フロート",
90
139
  "showDsh": "DSH を表示",
140
+ "hideDsh": "DSH を隠す",
141
+ "moveLeft": "会話をここにしまう",
142
+
143
+ "moveRight": "会話をここへ移動",
91
144
  "stow": "左サイドバーにしまう",
92
145
  "center": "中央に戻す",
93
146
  "dock": "右サイドバーにドッキング",
147
+ "toMain": "メインの会話を",
148
+ "switchTo": "この会話に切り替え",
94
149
  "description": "会話ビューを DSH 自身のフロートパネルにします。左へドラッグで左サイドバーに収納、中央で中央列に戻り、右で右サイドバーにドッキングします。"
95
150
  },
96
151
  "pt": {
97
152
  "conversation": "Conversa",
98
153
  "floatTitle": "Janela flutuante da conversa",
99
154
  "showDsh": "Mostrar DSH",
155
+ "hideDsh": "Ocultar DSH",
156
+ "moveLeft": "Guardar a conversa aqui",
157
+
158
+ "moveRight": "Mover a conversa para aqui",
100
159
  "stow": "Guardar na barra lateral esquerda",
101
160
  "center": "Voltar ao centro",
102
161
  "dock": "Ancorar na barra lateral direita",
162
+ "toMain": "Conversa principal: ",
163
+ "switchTo": "Mudar para esta conversa",
103
164
  "description": "Transforma a vista de conversa no painel flutuante do próprio DSH: à esquerda guarda na barra lateral, no centro volta à coluna central, à direita ancora na barra direita."
104
165
  },
105
166
  "ru": {
106
167
  "conversation": "Беседа",
107
168
  "floatTitle": "Плавающее окно беседы",
108
169
  "showDsh": "Показать DSH",
170
+ "hideDsh": "Скрыть DSH",
171
+ "moveLeft": "Убрать беседу сюда",
172
+
173
+ "moveRight": "Переместить беседу сюда",
109
174
  "stow": "Убрать в левую панель",
110
175
  "center": "Вернуть в центр",
111
176
  "dock": "Закрепить в правой панели",
177
+ "toMain": "Основная беседа: ",
178
+ "switchTo": "Перейти к этой беседе",
112
179
  "description": "Превращает вид беседы в собственное плавающее окно DSH: влево — убрать в левую панель, в центр — вернуть в средний столбец, вправо — закрепить в правой панели."
113
180
  }
114
181
  }
@@ -127,75 +194,326 @@ window.__ModuleLoader__.load({
127
194
  return table[key] ?? COPY.en[key] ?? key
128
195
  }
129
196
  const ANCHOR_ATTR = 'data-dsh-conversation-float-anchor'
197
+ /** Set on a taskbar row's button, with the Session its window shows. */
198
+ const ROW_MARK_ATTR = 'data-dsh-conversation-float-row'
130
199
  const CHAT_ID = 'conversation-float-panel'
131
200
  const CHAT_KIND = 'conversation-float-panel'
132
201
  /** A resource address our own tab type claims; the panel is opened by it. */
133
202
  const CHAT_ADDRESS = 'dsh-resource://conversation-float'
134
- /** The left sidebar row, and the main-panel key it addresses. */
135
- const DOCK_ROW_ID = 'conversation-float'
136
- /** How long a band must be held before it draws and before it can land. */
203
+ /**
204
+ * How long a band must be held before it draws and before it can land.
205
+ *
206
+ * This is the only wall clock the plugin keeps, and it is a HAND constant,
207
+ * not a guess at a commit. On a touch screen every drag crosses a band —
208
+ * the window is most of the width — so "drag" has to mean "move the window"
209
+ * and "hold, then drag" means "move the Conversation". Shortening it makes
210
+ * the guard against a stray brush weaker, and no device measurement here
211
+ * shows the shorter hold surviving that; 1200ms stands until one does.
212
+ */
137
213
  const DWELL_MS = 1200
214
+ /** Marks the window whose hold has armed the bands. */
215
+ const ARMED_ATTR = 'data-dsh-conversation-float-armed'
216
+
138
217
  /** The dock kit's own marker for a floating panel. */
139
218
  const FLOAT_ATTR = 'data-dockkit-float'
140
- /** Set on the float panel while it is stowed in the left drawer. */
141
- const STOW_ATTR = 'data-dsh-conversation-float-stowed'
219
+ /** Marks our own tab body, so the reconcile pass never reads another plugin's. */
220
+ const BODY_ATTR = 'data-dsh-conversation-float-body'
142
221
  /** Marks the float that hosts our tab, so our rules hit no other panel. */
143
222
  const OWN_FLOAT_ATTR = 'data-dsh-conversation-float-float'
144
223
  /** Set on every frame column that the float is temporarily hiding. */
145
224
  const CHROME_ATTR = 'data-dsh-conversation-float-chromeless'
225
+ /** Set on the one frame column this plugin has moved somewhere. */
226
+ const COLUMN_ATTR = 'data-dsh-conversation-float-column'
227
+ /**
228
+ * Set on a body that renders a Session's own Conversation content instead of
229
+ * hosting the live column. Such a body shows the transcript only: the one
230
+ * composer belongs to the Session on screen.
231
+ */
232
+ const FACTORY_ATTR = 'data-dsh-conversation-float-factory'
233
+ /** A live-Session factory view that keeps its header and composer. */
234
+ const FACTORY_LIVE_ATTR = 'data-dsh-conversation-float-factory-live'
146
235
 
147
236
  let sidebarRight = null
148
237
  let layout = null
149
238
  let movedColumn = null
150
239
  let movedFrom = null
151
- /** Whether the left sidebar currently holds a re-opener for the float. */
152
- let dockedLeft = false
153
240
  /** Whether the rest of DSH is currently hidden behind the float. */
154
241
  let chromeless = false
155
242
 
243
+
156
244
  /** Re-render subscribers: the entry button says one thing per state. */
157
245
  const stateListeners = new Set()
158
246
 
159
247
  function notifyState() {
160
248
  for (const fn of stateListeners) fn()
161
249
  }
250
+ /**
251
+ * The layout tick: every mounted float body re-decides which host it is for.
252
+ *
253
+ * This runs when something that could change the answer happens — the
254
+ * Session on screen changes, or the Session list does — instead of every
255
+ * body polling on its own clock. Independent timers were what let two floats
256
+ * race for the one column.
257
+ */
258
+ const layoutListeners = new Set()
259
+ /** Set while a pass runs: the plugin's own DOM writes must not ask for one. */
260
+ let inLayout = false
261
+ /** Whether the main slot carried a page during the last pass. */
262
+ let lastPageOpen = false
263
+ /**
264
+ * What one layout pass has already worked out.
265
+ *
266
+ * While a page owns the main slot the Conversation column is gone, so every
267
+ * lookup of it degrades to a whole-document scan plus forced layout reads —
268
+ * and every mounted body asked three times in the same pass. One pass has
269
+ * one answer; anything that moves the column drops it.
270
+ */
271
+ let passMemo = null
272
+ /** Whether this pass moved the Conversation between hosts. */
273
+ let columnMovedInPass = false
274
+ function beginPass() {
275
+ passMemo = { column: null, columnKnown: false, live: null, liveKnown: false, page: false, pageKnown: false }
276
+ columnMovedInPass = false
277
+ }
278
+ function endPass() {
279
+ passMemo = null
280
+ }
281
+ /**
282
+ * Note that this pass moved the Conversation between hosts.
283
+ *
284
+ * A move keeps the node and the Session it shows, so the memo survives it:
285
+ * only forgetColumn() drops a column, and that is where the memo is cleared.
286
+ */
287
+ function noteColumnMoved() {
288
+ columnMovedInPass = true
289
+ }
290
+ function notifyLayout() {
291
+ if (inLayout) return
292
+ // Retried on every pass rather than on a timer: until the workspace
293
+ // service is up there is nothing to subscribe to, and a pass is exactly
294
+ // what happens when anything else changes.
295
+ followSelection()
296
+ const pageOpen = mainPanelOpen()
297
+ const pageChanged = pageOpen !== lastPageOpen
298
+ lastPageOpen = pageOpen
299
+ // A page owns the main slot: the Conversation is not on screen, the column
300
+ // is home and every body already shows its own transcript. Nothing a pass
301
+ // could decide is different until the page closes — and that transition is
302
+ // what the flag above catches.
303
+ if (pageOpen && !pageChanged) return
304
+ inLayout = true
305
+ beginPass()
306
+ try {
307
+ // Repair the host first: every body below decides from "the Session on
308
+ // screen", and a column parked in a page the window has left answers
309
+ // that question with the old Conversation.
310
+ try {
311
+ reconcileLiveColumn()
312
+ } catch (error) {
313
+ report('[conversation-float] column reconcile failed:', error)
314
+ }
315
+ for (const listener of [...layoutListeners]) {
316
+ try {
317
+ listener()
318
+ } catch (error) {
319
+ report('[conversation-float] layout pass failed:', error)
320
+ }
321
+ }
322
+ // The pass may have moved the Conversation between hosts, and a copy that
323
+ // left in the same breath can take the composer's editor with it. A pass
324
+ // that moved nothing cannot have broken it, so the subtree query that
325
+ // looks for the composer stays out of the common case.
326
+ if (columnMovedInPass) {
327
+ try {
328
+ healComposer()
329
+ } catch (error) {
330
+ report('[conversation-float] composer heal failed:', error)
331
+ }
332
+ }
333
+ refreshSwitchChips()
334
+ } finally {
335
+ inLayout = false
336
+ endPass()
337
+ }
338
+ }
162
339
  /** Set when the hide was requested before the float finished mounting. */
163
340
  let pendingChromeless = false
164
341
  /** The last sane band geometry, kept for when the columns are hidden. */
165
342
  let lastBand = null
166
343
  /** Sidebar state captured when the float opened; restored when it closes. */
167
344
  let savedChrome = null
168
- /** Set when the user changed a sidebar while the float was open. */
169
- let chromeTouched = false
170
- /** How long after a press or a key a column change still counts as the user's. */
171
- const GESTURE_WINDOW = 900
172
- /** How long the float's own force-open needs to settle before sampling. */
173
- const FORCE_SETTLE_MS = 1200
174
- /** The last time the user pressed a key or a mouse button, in ms. */
175
- let gestureAt = 0
176
- /** While the plugin moves the columns itself, changes are not the user's. */
177
- let holdOffUntil = 0
345
+ /**
346
+ * A retry of the sidebar arrangement, cancelable by the user's own hand.
347
+ *
348
+ * This replaced a time window that claimed to suppress "changes the plugin
349
+ * caused": nothing ever read that window, so the promise in the comment was
350
+ * never kept. A hand on the sidebars now ends the retry directly.
351
+ */
352
+ let chromeApplyStop = null
178
353
  /** Set while docking to the right sidebar: the column is not going home. */
179
354
  let dockingRight = false
355
+ /** Set when a minimise is waiting for the float that carries the column. */
356
+ let pendingMinimise = false
357
+ /** The Session list projection, when the Client exposes it. */
358
+ let sessions = null
180
359
  /** Set while the float is being reopened from the drawer. */
181
360
  let suspendRestore = false
182
- /** Disposer of the `sidebar.panellist` row, while it is registered. */
183
- let dockRow = null
184
361
  /** The drop preview overlay, created on demand. */
185
362
  let preview = null
186
363
 
364
+ /* ------------------------------------------------------------- timing */
365
+
366
+ /*
367
+ * Two kinds of waiting live here, and they are not the same thing.
368
+ *
369
+ * A duration that measures a HAND — the hold that arms the drop bands
370
+ * ({@link DWELL_MS}) — cannot be replaced by anything: the decision is the
371
+ * user's, and only the clock knows when it was made.
372
+ *
373
+ * A duration that guesses when another system commits is the fragile kind:
374
+ * it expires early on a busy frame and late on an idle one. Those waits are
375
+ * written as the condition they want and re-read once per frame
376
+ * ({@link untilFrame}), so they end the frame the commit arrives.
377
+ *
378
+ * There are no settle durations left either. A step that has to follow a
379
+ * close defers with queueMicrotask, which is "after this commit" without a
380
+ * duration: later than the unmount, earlier than any input. The touch hold
381
+ * below is the only wall clock in the plugin.
382
+ */
383
+
384
+ /** Frame-driven waits owned by the plugin instance; they die with it. */
385
+ const pendingWaits = new Set()
386
+
387
+ function cancelWaits() {
388
+ for (const stop of [...pendingWaits]) stop()
389
+ pendingWaits.clear()
390
+ }
391
+
392
+ /**
393
+ * Re-read `check` every frame until it returns true, then call `then`.
394
+ *
395
+ * `deadlineMs` is a backstop for a condition that can never come true (the
396
+ * Session was closed mid-flight), never the way a normal wait ends.
397
+ *
398
+ * @param check read once per frame; true ends the wait
399
+ * @param then run on the frame the condition holds
400
+ * @param deadlineMs when to give up, and `onExpire` what to do instead
401
+ */
402
+ function untilFrame(check, then, deadlineMs = 2000, onExpire = null) {
403
+ const started = performance.now()
404
+ let raf = 0
405
+ let done = false
406
+ const stop = () => {
407
+ if (done) return
408
+ done = true
409
+ pendingWaits.delete(stop)
410
+ if (raf !== 0) window.cancelAnimationFrame(raf)
411
+ }
412
+ const step = () => {
413
+ raf = 0
414
+ if (done) return
415
+ let ok = false
416
+ try { ok = check() === true } catch { ok = false }
417
+ if (ok) {
418
+ stop()
419
+ try { then?.() } catch (error) { report('[conversation-float] a deferred step failed:', error) }
420
+ return
421
+ }
422
+ if (performance.now() - started > deadlineMs) {
423
+ stop()
424
+ try { onExpire?.() } catch (error) { report('[conversation-float] a deferred fallback failed:', error) }
425
+ return
426
+ }
427
+ raf = window.requestAnimationFrame(step)
428
+ }
429
+ pendingWaits.add(stop)
430
+ raf = window.requestAnimationFrame(step)
431
+ return stop
432
+ }
433
+
434
+ /**
435
+ * The plugin's single diagnostic sink.
436
+ *
437
+ * Every failure in this file used to end at console.warn, which is fine to
438
+ * write and impossible to read back: a band that silently did nothing left
439
+ * no trace a user could hand over. Keeping the last one lets diag() report
440
+ * what actually went wrong.
441
+ */
442
+ /** Whether a page asked for the mutating probe surface. */
443
+ function floatDebugEnabled() {
444
+ try {
445
+ if (window.__dshFloatDebug === true) return true
446
+ return /[?&]dshFloatDebug=1\b/.test(window.location.search)
447
+ } catch {
448
+ return false
449
+ }
450
+ }
451
+
452
+ function report(...args) {
453
+ try {
454
+ window.__dshFloatLastError = {
455
+ at: Date.now(),
456
+ text: args.map((value) => (value && value.stack) || String(value)).join(' '),
457
+ }
458
+ } catch { /* no window yet */ }
459
+ console.warn(...args)
460
+ }
461
+
187
462
  /* ------------------------------------------------------- the live column */
188
463
 
464
+ /**
465
+ * The frame column that carries the Conversation. An ANCESTOR is moved, never
466
+ * the Conversation node itself: React keeps child lists inside the nodes it
467
+ * owns, so pulling one of those children out of its parent breaks the next
468
+ * reconciliation — a Session switch then renders nothing at all. Moving the
469
+ * column keeps every list inside the moved subtree intact.
470
+ */
189
471
  function findColumn() {
190
- if (movedColumn !== null && movedColumn.isConnected) return movedColumn
472
+ if (passMemo !== null && passMemo.columnKnown) return passMemo.column
473
+ const column = movedColumn !== null && movedColumn.isConnected ? movedColumn : scanColumn()
474
+ if (passMemo !== null) {
475
+ passMemo.column = column
476
+ passMemo.columnKnown = true
477
+ }
478
+ return column
479
+ }
480
+
481
+ /**
482
+ * The frame's own Conversation column, read without trusting the record of
483
+ * which node this plugin moved.
484
+ *
485
+ * A Session switch can take the column we were holding out of the document
486
+ * (DSH unmounts the Session and draws the next one), and the record then
487
+ * names a node nobody can see. Every repair below has to be able to ask
488
+ * "what does the frame say right now", and this is how it asks.
489
+ */
490
+ function scanColumn() {
491
+ // The window renders a Conversation of its own. That one is never the
492
+ // middle column this helper is looking for, so it is skipped by name.
493
+ const insideOurs = (el) => el !== null && el.closest(`[${WINDOW_ATTR}]`) !== null
191
494
  const candidates = [
192
- document.querySelector('[data-conversation-session]'),
495
+ [...document.querySelectorAll('[data-conversation-session]')].find((el) => !insideOurs(el)) ?? null,
193
496
  document.querySelector(`[${ANCHOR_ATTR}]`),
194
497
  document.querySelector('[data-conversation-header-corner]'),
195
498
  document.querySelector('[data-conversation-tabs]'),
196
499
  ]
197
500
  for (const anchor of candidates) {
198
- if (anchor === null) continue
501
+ if (anchor === null || insideOurs(anchor)) continue
502
+ // While the Conversation is hosted by one of our bodies, the column is
503
+ // that body's own child — walking up instead would climb out of the
504
+ // right sidebar and name the whole right column as "the column", and
505
+ // moving that into the float feeds it its own ancestor.
506
+ const body = anchor.closest(`[${BODY_ATTR}]`)
507
+ if (body !== null) {
508
+ // Only a column WE moved into this body counts. A body rendering a
509
+ // Conversation of its own (a docked page) has the anchor as a view;
510
+ // reading that view as the frame's column made the panel believe it
511
+ // was hosting the live column while it was rendering a copy.
512
+ for (const child of Array.from(body.children)) {
513
+ if (child.hasAttribute(COLUMN_ATTR) && child.contains(anchor)) return child
514
+ }
515
+ return null
516
+ }
199
517
  let node = anchor
200
518
  while (node.parentElement !== null) {
201
519
  const parent = node.parentElement
@@ -220,11 +538,39 @@ window.__ModuleLoader__.load({
220
538
  }
221
539
  }
222
540
 
223
- /** Upper-left corner of that seat: centred, snapped, clear of the frame. */
541
+ /** The room the sidebars leave in the middle: their two inner edges. */
542
+ function middleRoom() {
543
+ const width = window.innerWidth
544
+ const overlay = document.querySelector('[data-shell-overlay]')
545
+ const frame = overlay === null ? null : overlay.parentElement
546
+ let left = 0
547
+ let right = width
548
+ if (frame !== null) {
549
+ const sidebar = frame.firstElementChild
550
+ if (sidebar !== null) {
551
+ const box = sidebar.getBoundingClientRect()
552
+ if (box.width > 80) left = Math.round(box.right)
553
+ }
554
+ const rightColumn = frame.querySelector('[data-rightbar-col]')
555
+ if (rightColumn !== null) {
556
+ const box = rightColumn.getBoundingClientRect()
557
+ if (box.width > 80) right = Math.round(box.left)
558
+ }
559
+ }
560
+ return { left, right: Math.max(left, right) }
561
+ }
562
+
563
+ /**
564
+ * Upper-left corner of that seat: centred in the room the sidebars leave,
565
+ * snapped, clear of the frame. With the window showing nothing but the
566
+ * float those columns measure zero and the seat falls back to the window.
567
+ */
224
568
  function floatSeat(size) {
225
569
  const snap = (value) => Math.max(0, Math.round(value / GRID) * GRID)
570
+ const room = middleRoom()
571
+ const free = room.right - room.left
226
572
  return {
227
- x: snap((window.innerWidth - size.width) / 2),
573
+ x: free > size.width ? snap(room.left + (free - size.width) / 2) : snap(room.left),
228
574
  y: Math.max(48, snap((window.innerHeight - size.height) / 2)),
229
575
  }
230
576
  }
@@ -265,64 +611,55 @@ window.__ModuleLoader__.load({
265
611
  try {
266
612
  seat.actions.resizeFloat(seat.sessionId, paneId, rect)
267
613
  } catch (error) {
268
- console.warn('[conversation-float] could not size the floating panel:', error)
614
+ report('[conversation-float] could not size the floating panel:', error)
269
615
  }
270
616
  }
271
- /** The session's dock-kit action face, or null when it is not reachable. */
272
- function sessionSeat() {
273
- try {
274
- const direct = sidebarRight?.require?.()
275
- if (direct !== undefined && direct !== null) return direct
276
- } catch {
277
- /* fall through to the per-session face */
278
- }
279
- try {
280
- const sessionId = sidebarRight?.mounted?.getSnapshot?.()
281
- const actions = sessionId === undefined ? undefined : sidebarRight?.actionsFor?.(sessionId)
282
- if (actions !== undefined && actions !== null) return { sessionId, actions }
283
- } catch {
284
- return null
285
- }
286
- return null
287
- }
288
-
289
- /** Float our tab for real, with the size we want. */
290
- function floatExistingTab() {
291
- if (floatPanel() !== null) {
292
- sizeFloat()
293
- return true
294
- }
295
- const tabId = floatTabId()
296
- if (tabId === null) return false
297
- const seat = sessionSeat()
298
- if (seat === null || typeof seat.actions?.floatTab !== 'function') return false
299
- const size = floatSize()
300
- const corner = floatSeat(size)
301
- try {
302
- seat.actions.floatTab(seat.sessionId, tabId, { ...corner, width: size.width, height: size.height })
303
- return true
304
- } catch (error) {
305
- console.warn('[conversation-float] could not float the docked tab:', error)
306
- return false
307
- }
308
- }
309
- function attachColumn(container) {
617
+ function attachColumn(container, keepHome = false) {
310
618
  const column = findColumn()
311
619
  if (column === null || container === null) return null
312
- movedFrom = { parent: column.parentNode, next: column.nextSibling }
620
+ // Never feed a node its own descendant: that append throws and leaves the
621
+ // bookkeeping pointing at a node that was never moved.
622
+ if (column.contains(container)) return null
623
+ // A retained body that takes the column over from another body keeps the
624
+ // seat recorded first: the middle column, never the tab it came from.
625
+ if (!keepHome || movedFrom === null) {
626
+ const parent = column.parentNode
627
+ // Any host counts, not just a window: a docked page is retained the same
628
+ // way and can be closed at any moment. The seat worth remembering is the
629
+ // frame's, never the host it is leaving.
630
+ const fromHost = parent !== null && typeof parent.closest === 'function'
631
+ && (parent.closest(`[${WINDOW_ATTR}]`) !== null || parent.closest(`[${BODY_ATTR}]`) !== null)
632
+ if (fromHost) {
633
+ const seat = homeSeat(null)
634
+ movedFrom = seat === null ? null : { parent: seat.parent, next: seat.before }
635
+ } else {
636
+ movedFrom = { parent, next: column.nextSibling }
637
+ }
638
+ }
313
639
  movedColumn = column
640
+ column.setAttribute(COLUMN_ATTR, '')
314
641
  column.style.width = "100%"
315
642
  column.style.height = "100%"
316
643
  column.style.minWidth = "0"
317
644
  column.style.minHeight = "0"
318
645
  column.style.overflow = "hidden"
319
646
  container.appendChild(column)
647
+ noteColumnMoved()
320
648
  const ownPanel = floatPanel()
321
649
  if (ownPanel !== null) ownPanel.setAttribute(OWN_FLOAT_ATTR, '')
322
650
  // The dock kit gives a new float its own seat; ask it — through the same
323
651
  // intent its own resize drag uses — for the configured one.
324
652
  sizeFloat()
325
653
 
654
+ // A host has taken the column, so a docking that was waiting for its tab
655
+ // has arrived: the restore guard must not outlive it.
656
+ dockingRight = false
657
+
658
+ // The left-hand action asked for the conversation while no float existed.
659
+ // The body is mounted in a layout effect — before paint — so minimising
660
+ // here means the window is never painted on its way out.
661
+ if (pendingMinimise && flushPendingMinimise()) return column
662
+
326
663
  // The float body is mounted now, so a hide that was waiting for it can be
327
664
  // applied against a real float element.
328
665
  if (pendingChromeless) setChromeless(true)
@@ -330,6 +667,25 @@ window.__ModuleLoader__.load({
330
667
  }
331
668
 
332
669
 
670
+ /**
671
+ * Where the column belongs in the frame: the seat recorded when it was
672
+ * taken, or — when a re-render replaced that seat's neighbours — the spot
673
+ * the middle column keeps, right before the right column.
674
+ */
675
+ function homeSeat(home) {
676
+ if (home !== null && home.parent !== null && home.parent.isConnected) {
677
+ const next = home.next
678
+ if (next === null || next.parentNode === home.parent) return { parent: home.parent, before: next }
679
+ }
680
+ const overlay = document.querySelector('[data-shell-overlay]')
681
+ const frame = overlay === null ? null : overlay.parentElement
682
+ if (frame === null) return null
683
+ const before = frame.querySelector(':scope > [data-rightbar-col]') ??
684
+ frame.querySelector(':scope > [data-shell-bottom]') ??
685
+ frame.querySelector(':scope > [data-shell-overlay]')
686
+ return { parent: frame, before }
687
+ }
688
+
333
689
  /** The frame's middle column, used when the recorded home was re-rendered. */
334
690
  function currentCenter() {
335
691
  const overlay = document.querySelector('[data-shell-overlay]')
@@ -346,11 +702,265 @@ window.__ModuleLoader__.load({
346
702
  return null
347
703
  }
348
704
 
349
- function detachColumn() {
705
+ /**
706
+ * Whether DSH is showing a page (plugins, automation, settings) in the main
707
+ * panel instead of the Conversation. The panel host lives inside the column
708
+ * we move, so a page rendered while the column sits in a float — and DSH
709
+ * suppresses the whole float while a page is open — would be invisible.
710
+ */
711
+ function mainPanelOpen() {
712
+ if (passMemo !== null && passMemo.pageKnown) return passMemo.page
713
+ const slot = document.querySelector('[data-slot="main"]')
714
+ let open = false
715
+ if (slot !== null) {
716
+ for (const child of slot.children) {
717
+ if (child.getAttribute('data-slot') === 'main.conversation') continue
718
+ open = true
719
+ break
720
+ }
721
+ }
722
+ if (passMemo !== null) {
723
+ passMemo.page = open
724
+ passMemo.pageKnown = true
725
+ }
726
+ return open
727
+ }
728
+
729
+ /* --------------------------------------------------------- internals */
730
+ /*
731
+ * DSH internals adapter: the only places this plugin reads something DSH
732
+ * does not publish. Keeping them named in one block means an upgrade has
733
+ * one place to look instead of five:
734
+ *
735
+ * 1. the Lexical editor, reached through the React fiber of its box
736
+ * (composerEditor)
737
+ * 2. editor.setRootElement, the only way to give that editor its box back
738
+ * (healComposer)
739
+ * 3. conversation.input.shell(id).persistDraft, the Session's single draft
740
+ * slot (guardDraftWriter)
741
+ *
742
+ * compatReport() probes all three; diag() reports it. A build that lost one
743
+ * of them should say so on the first diagnostic rather than on the first
744
+ * keystroke that goes nowhere.
745
+ */
746
+
747
+ /* ------------------------------------------------------ the live composer */
748
+
749
+ /**
750
+ * The Lexical editor behind a composer box, read off the box itself.
751
+ *
752
+ * The composer does not own its editable surface: `ComposerContentEditable`
753
+ * hands the same editor a DOM node (`editor.setRootElement(el)`) on mount
754
+ * and `null` on unmount, and one editor can only ever have one root. The
755
+ * box therefore reports the editor that renders into it, which is the only
756
+ * handle this plugin needs.
757
+ */
758
+ function composerEditor(box) {
759
+ const key = Object.keys(box).find((name) => name.startsWith('__reactFiber$'))
760
+ if (key === undefined) return null
761
+ let fiber = box[key]
762
+ for (let depth = 0; fiber && depth < 24; depth += 1, fiber = fiber.return) {
763
+ const props = fiber.memoizedProps
764
+ if (props && props.editor && typeof props.editor.setRootElement === 'function') return props.editor
765
+ }
766
+ return null
767
+ }
768
+
769
+ /**
770
+ * Give the composer on screen its editor back.
771
+ *
772
+ * A Session's input is one shell with one editor. Our window renders a
773
+ * transcript of a Session that is not the live one, and that copy mounts a
774
+ * composer of its own on the SAME editor; when the copy goes away it calls
775
+ * `setRootElement(null)`, and the composer the user is now looking at is a
776
+ * dead box: it keeps whatever text was left in it, typing never reaches the
777
+ * shell, and the draft the send button reads is the one the shell had before
778
+ * the switch. Nothing in DSH re-attaches it, because the surviving composer
779
+ * never remounted — its DOM was moved, not rendered. Re-attaching the editor
780
+ * is what heals it, and the shell's own document (the persisted draft) comes
781
+ * back with it.
782
+ *
783
+ * @returns whether the editor had to be re-attached
784
+ */
785
+ function healComposer() {
786
+ // The composer that needs healing belongs to the Conversation ON SCREEN,
787
+ // and that is not always the column this plugin moved: while the live
788
+ // Session sits in the middle column, a window's copy can take the editor
789
+ // and the plugin holds nothing at all. Reading only `movedColumn` healed
790
+ // the case that cannot happen and skipped the one that does.
791
+ const column = (movedColumn !== null && movedColumn.isConnected) ? movedColumn : findColumn()
792
+ if (column === null || !column.isConnected) return false
793
+ const sessionId = columnSession(column) ?? selectedSession()
794
+ if (sessionId === null) return false
795
+ let changed = false
796
+ const seat = column.querySelector('[data-composer-seat]')
797
+ const box = seat === null
798
+ ? null
799
+ : [...seat.querySelectorAll('[contenteditable]')].find((el) => el.getAttribute('contenteditable') !== 'false') ?? null
800
+ if (box !== null) {
801
+ const editor = composerEditor(box)
802
+ if (editor !== null) {
803
+ let root = box
804
+ try {
805
+ root = editor.getRootElement()
806
+ } catch {
807
+ root = box
808
+ }
809
+ if (root !== box) {
810
+ try {
811
+ editor.setRootElement(box)
812
+ changed = true
813
+ } catch (error) {
814
+ report('[conversation-float] could not re-attach the composer:', error)
815
+ }
816
+ }
817
+ }
818
+ }
819
+ try {
820
+ if (guardDraftWriter(sessionId)) changed = true
821
+ } catch (error) {
822
+ report('[conversation-float] could not restore the draft writer:', error)
823
+ }
824
+ return changed
825
+ }
826
+
827
+ /** sessionId -> { shell, write }: the draft writer bound while this Session was live. */
828
+ const liveDraftWriters = new Map()
829
+
830
+ /** Which of the three published-nowhere hooks are present right now. */
831
+ function compatReport() {
832
+ const column = findColumn()
833
+ const seat = (column ?? document).querySelector('[data-composer-seat]')
834
+ const box = seat === null
835
+ ? null
836
+ : [...seat.querySelectorAll('[contenteditable]')].find((el) => el.getAttribute('contenteditable') !== 'false') ?? null
837
+ const editor = box === null ? null : composerEditor(box)
838
+ let shellOk = false
839
+ try {
840
+ const conversation = typeof ctxRef?.get === 'function' ? ctxRef.get('conversation') : null
841
+ const id = columnSession(column ?? document.body) ?? selectedSession()
842
+ const shell = id === null || conversation === null || conversation === undefined ? null : conversation.input?.shell?.(id)
843
+ shellOk = shell !== null && shell !== undefined && typeof shell.bindDraftPersistence === 'function'
844
+ } catch {
845
+ shellOk = false
846
+ }
847
+ return {
848
+ fiberEditor: editor !== null,
849
+ setRootElement: editor !== null && typeof editor.setRootElement === 'function',
850
+ draftShell: shellOk,
851
+ }
852
+ }
853
+
854
+ /** The Session's input shell — the one object holding its editor and draft slot. */
855
+ function draftShellOf(sessionId) {
856
+ try {
857
+ const conversation = typeof ctxRef?.get === 'function' ? ctxRef.get('conversation') : null
858
+ const shell = conversation === null || conversation === undefined
859
+ ? null
860
+ : conversation.input?.shell?.(sessionId)
861
+ return shell !== null && shell !== undefined && typeof shell.bindDraftPersistence === 'function' ? shell : null
862
+ } catch (error) {
863
+ return null
864
+ }
865
+ }
866
+
867
+ /**
868
+ * Put the Session's draft writer back after a copy cleared it.
869
+ *
870
+ * The writer is a single field on the input shell (`persistDraft`), and a
871
+ * cleared field is how the draft stops reaching storage while the composer
872
+ * still looks alive. The writer DSH bound while this Session was the one on
873
+ * screen is the right one: it writes the draft into the Conversation store
874
+ * the reload path and the send button read. It is only ever put back into an
875
+ * EMPTY slot — a writer DSH has bound since is never replaced, so a
876
+ * remounted composer keeps its own.
877
+ *
878
+ * @returns whether the slot had to be filled
879
+ */
880
+ function guardDraftWriter(sessionId) {
881
+ const shell = draftShellOf(sessionId)
882
+ if (shell === null) return false
883
+ const current = shell.persistDraft
884
+ const known = liveDraftWriters.get(sessionId)
885
+ if (current !== undefined && current !== null) {
886
+ if (known === undefined || known.shell !== shell) {
887
+ liveDraftWriters.set(sessionId, { shell, write: current })
888
+ capSessionMap(liveDraftWriters)
889
+ }
890
+ return false
891
+ }
892
+ if (known === undefined || known.shell !== shell) return false
893
+ try {
894
+ shell.persistDraft = known.write
895
+ } catch (error) {
896
+ return false
897
+ }
898
+ return true
899
+ }
900
+
901
+ /**
902
+ * Re-attach the composer now, and again once the layout has settled.
903
+ *
904
+ * The copy that steals the editor goes away a commit after the pass that
905
+ * notices the Session is live again, so one attempt can land before the
906
+ * thief has finished leaving.
907
+ */
908
+ function healComposerSoon() {
909
+ const heal = () => {
910
+ try { healComposer() } catch (error) { report('[conversation-float] composer heal failed:', error) }
911
+ }
912
+ heal()
913
+ // The copy that steals the editor goes away a commit after the pass that
914
+ // notices the Session is live again, so one attempt can land before the
915
+ // thief has finished leaving. Waiting on the editor ends the wait on the
916
+ // frame it is back; the three fixed delays it used to have expired before
917
+ // or after that commit depending on how busy the frame was.
918
+ const box = liveComposerBox()
919
+ if (box === null) return
920
+ untilFrame(() => {
921
+ heal()
922
+ return editorAttachedTo(box)
923
+ }, null, 1200)
924
+ }
925
+
926
+ /** The contenteditable of the Conversation on screen, wherever it lives. */
927
+ function liveComposerBox() {
928
+ const column = (movedColumn !== null && movedColumn.isConnected) ? movedColumn : findColumn()
929
+ const root = column ?? document
930
+ const seat = root.querySelector('[data-composer-seat]')
931
+ if (seat === null) return null
932
+ return [...seat.querySelectorAll('[contenteditable]')]
933
+ .find((el) => el.getAttribute('contenteditable') !== 'false') ?? null
934
+ }
935
+
936
+ /** Whether the editor that renders into `box` is attached to it right now. */
937
+ function editorAttachedTo(box) {
938
+ if (box === null) return false
939
+ const editor = composerEditor(box)
940
+ if (editor === null) return false
941
+ try { return editor.getRootElement() === box } catch { return false }
942
+ }
943
+
944
+ /** Where the column went on its way home (probe only, read by the tests). */
945
+ function markDetach(where) {
946
+ try {
947
+ const box = window.__dshFloatDetach ?? (window.__dshFloatDetach = { seat: 0, center: 0, fallback: 0, nowhere: 0, disconnected: 0, calls: 0 })
948
+ box.calls += 1
949
+ box[where] = (box[where] ?? 0) + 1
950
+ } catch { /* no window yet */ }
951
+ }
952
+
953
+ function detachColumn(keepChrome = false) {
350
954
  const column = movedColumn
351
955
  const home = movedFrom
956
+ if (column !== null) column.removeAttribute(COLUMN_ATTR)
352
957
  movedColumn = null
353
958
  movedFrom = null
959
+ notifyState()
960
+ // Closing is the plugin's doing, even when a click on the panel's own
961
+ // close button started it. Nothing has to be suppressed for that: the
962
+ // restore below compares against a snapshot taken before the float
963
+ // opened, so a re-rail cannot be mistaken for the user's arrangement.
354
964
  for (const el of document.querySelectorAll(`[${OWN_FLOAT_ATTR}]`)) el.removeAttribute(OWN_FLOAT_ATTR)
355
965
  // The float is leaving the screen: the rest of DSH has to come back.
356
966
  if (chromeless) setChromeless(false)
@@ -359,143 +969,435 @@ window.__ModuleLoader__.load({
359
969
  // out of the left drawer, a remounted float body) also detaches it for
360
970
  // a frame; restoring there would collapse the sidebars under a float
361
971
  // that is still on screen.
362
- if (!dockingRight && !suspendRestore) scheduleRestoreChrome()
972
+ if (!keepChrome && !dockingRight && !suspendRestore) scheduleRestoreChrome()
363
973
  dockingRight = false
364
974
  if (column === null) return
975
+ noteColumnMoved()
365
976
  column.style.width = ''
366
977
  column.style.height = ''
367
978
  column.style.minWidth = ''
368
979
  column.style.minHeight = ''
369
980
  column.style.overflow = ''
370
- if (home !== null && home.parent !== null && home.parent.isConnected) {
371
- home.parent.insertBefore(column, home.next)
981
+ // DSH took the Conversation down while it was ours (a main panel opened,
982
+ // the Session changed): a node React has removed must not be put back, or
983
+ // a stale copy of the conversation would sit in the middle column.
984
+ if (!column.isConnected) {
985
+ markDetach('disconnected')
986
+ // ...unless nothing else shows this Conversation any more: then the node
987
+ // left the document with the window that hosted it, and putting it back
988
+ // in the frame beats a blank screen that never comes back.
989
+ //
990
+ // The test used to be a plain `[data-conversation-session]` query, which
991
+ // every float's own transcript copy answers as well — so with one other
992
+ // window open the rescue never fired and the screen stayed blank for
993
+ // good. Only a column the frame could actually use may count as a
994
+ // survivor.
995
+ if (scanColumn() === null) {
996
+ const seat = homeSeat(home)
997
+ if (seat !== null) {
998
+ markDetach('rescued')
999
+ seat.parent.insertBefore(column, seat.before)
1000
+ }
1001
+ }
1002
+ return
1003
+ }
1004
+ const seat = homeSeat(home)
1005
+ if (seat !== null) {
1006
+ markDetach('seat')
1007
+ seat.parent.insertBefore(column, seat.before)
372
1008
  return
373
1009
  }
374
1010
  // The recorded seat is gone (the panel took it down with it): put the
375
1011
  // column back in the middle column so the session is never lost.
376
1012
  const center = currentCenter()
377
- if (center !== null) center.appendChild(column)
1013
+ if (center !== null) {
1014
+ markDetach('center')
1015
+ center.appendChild(column)
1016
+ return
1017
+ }
1018
+ // Last resort: keep it in the frame instead of letting it leave the
1019
+ // document with the window that hosted it.
1020
+ const frame = document.querySelector('[data-shell-overlay]')?.parentElement ?? null
1021
+ if (frame !== null) {
1022
+ markDetach('fallback')
1023
+ frame.insertBefore(column, frame.querySelector(':scope > [data-rightbar-col]'))
1024
+ return
1025
+ }
1026
+ markDetach('nowhere')
378
1027
  }
379
1028
 
380
- /**
381
- * A closed floating panel can take our body down without running its
382
- * cleanup first, so the column is watched directly: as soon as its container
383
- * leaves the document it goes home.
384
- */
385
- function watchColumn() {
386
- /** The float element the last repair ran against. */
387
- let seenFloat = null
388
- /** The float whose fixed size was last applied. */
389
- let sizedFloat = null
390
- /** Attempts made to settle that float size. */
391
- let sizeTries = 0
392
- let seenParent = null
393
- let seenHost = null
394
- let frame = 0
395
- const check = () => {
396
- frame = 0
397
- if (movedColumn !== null && !movedColumn.isConnected) detachColumn()
398
- const panel = floatPanel()
399
- // Never stay hidden without a float: that is a blank window.
400
- if (chromeless && panel === null) setChromeless(false)
401
- // The repairs below walk the whole frame, so they run only when the
402
- // float moves house (a new panel, a new parent column, or a new body)
403
- // and never on every mutation a drag produces.
404
- const parent = panel === null ? null : panel.parentElement
405
- const host = panel === null ? null : panel.querySelector(".dsw-host")
406
- if (panel !== null) {
407
- if (panel !== sizedFloat) {
408
- sizedFloat = panel
409
- sizeTries = 0
410
- }
411
- const want = floatSize()
412
- const box = panel.getBoundingClientRect()
413
- const off = Math.abs(box.width - want.width) > 24 || Math.abs(box.height - want.height) > 24
414
- if (off && sizeTries < 4) {
415
- sizeTries += 1
416
- sizeFloat()
417
- }
418
- }
419
- if (panel !== seenFloat || parent !== seenParent || host !== seenHost) {
420
- seenFloat = panel
421
- seenParent = parent
422
- seenHost = host
423
- if (panel !== null) {
424
- healFloatBody()
425
- if (chromeless) refreshChromeless()
426
- }
427
- }
428
- noteChromeChange()
1029
+ /** Every mounted body of our own tab: one per right-sidebar Session. */
1030
+ function dockedHosts() {
1031
+ const hosts = []
1032
+ for (const host of document.querySelectorAll(`[data-sidebar-right-tab] [${BODY_ATTR}]`)) {
1033
+ // The floating panel's body is not a docked one.
1034
+ if (host.closest(`[${FLOAT_ATTR}]`) === null) hosts.push(host)
429
1035
  }
1036
+ return hosts
1037
+ }
430
1038
 
1039
+ /** Whether a host is on screen: a retained body of a hidden tab is not. */
1040
+ function hostOnScreen(host) {
1041
+ if (!host.isConnected) return false
1042
+ const box = host.getBoundingClientRect()
1043
+ return box.width > 0 && box.height > 0
1044
+ }
431
1045
 
432
- const schedule = () => {
433
- if (frame !== 0) return
434
- frame = window.requestAnimationFrame(check)
435
- }
436
- const observer = new MutationObserver(schedule)
437
- observer.observe(document.body, { childList: true, subtree: true })
1046
+ /** The Session the column is showing right now. */
1047
+ function columnSession(column) {
1048
+ const mark = column.querySelector('[data-conversation-session]')
1049
+ return mark === null ? null : mark.getAttribute('data-conversation-session')
1050
+ }
438
1051
 
439
- return () => {
440
- observer.disconnect()
441
- if (frame !== 0) window.cancelAnimationFrame(frame)
442
- }
1052
+ /** The Session a docked body belongs to. */
1053
+ function hostSession(host) {
1054
+ const owner = host.closest('[data-sidebar-right-session]')
1055
+ return owner === null ? null : owner.getAttribute('data-sidebar-right-session')
1056
+ }
1057
+
1058
+ /** The Session a floating panel belongs to, or null when it carries none. */
1059
+ function floatOwnerSession(panel) {
1060
+ const owner = panel.closest('[data-sidebar-right-session]')
1061
+ return owner === null ? null : owner.getAttribute('data-sidebar-right-session')
443
1062
  }
444
1063
 
445
1064
  /**
446
- * A float that lost its body — clicking the drawer row re-lays the main
447
- * column, the panel remounts, and the Conversation is momentarily out of the
448
- * document — is put back together here. An empty float is worse than a flash.
1065
+ * Whether a panel can be seen. The right sidebar keeps one panel per Session
1066
+ * and hides the others, so a float of a Session the window has left measures
1067
+ * zero: it is still mounted, and it must never be treated as the live host.
449
1068
  */
450
- function healFloatBody() {
451
- const panel = floatPanel()
452
- if (panel === null) return
453
- const host = panel.querySelector('.dsw-host')
454
- if (host === null) return
455
- if (movedColumn !== null && host.contains(movedColumn)) return
456
- const column = findColumn()
457
- if (column === null || host.contains(column)) return
458
- attachColumn(host)
1069
+ function panelVisible(panel) {
1070
+ if (!panel.isConnected) return false
1071
+ if (panel.closest('[hidden], [aria-hidden="true"]') !== null) return false
1072
+ const box = panel.getBoundingClientRect()
1073
+ return box.width > 0 && box.height > 0
459
1074
  }
460
- /** Re-apply the hide list: the float may have moved to another branch. */
461
- function refreshChromeless() {
462
- for (const el of document.querySelectorAll(`[${CHROME_ATTR}]`)) el.removeAttribute(CHROME_ATTR)
463
- for (const el of chromeTargets()) el.setAttribute(CHROME_ATTR, '')
1075
+
1076
+ /** Whether a float may host the conversation currently showing `session`. */
1077
+ function floatHostsSession(panel, session) {
1078
+ const owner = floatOwnerSession(panel)
1079
+ return owner === null || session === null || owner === session
464
1080
  }
465
- /* ---------------------------------------------------------- the chrome */
466
1081
 
1082
+ /** When the recorded column was first seen outside the document, in ms. */
1083
+ let columnOrphanedAt = 0
1084
+ /** The last Session the live Conversation was seen showing. */
1085
+ let lastSession = null
467
1086
  /**
468
- * Hide everything the float does not need. Clicking the entry opens the
469
- * float and leaves the window showing nothing but the float; the same
470
- * button then brings the rest of DSH back (and hides it again).
1087
+ * The Session the live Conversation is showing right now. It falls back to
1088
+ * the last one seen: opening a main panel takes the Conversation down for a
1089
+ * commit, and the drawer row press has to know which Conversation it means.
471
1090
  */
472
- function chromeTargets() {
473
- const overlay = document.querySelector('[data-shell-overlay]')
474
- const frame = overlay === null ? null : overlay.parentElement
475
- if (frame === null) return []
476
- const floatEl = floatPanel()
477
- const hidden = []
478
- /** Keep the branch that holds the float; hide every sibling beside it. */
479
- const walk = (el) => {
480
- if (floatEl !== null && (el === floatEl || el.contains(floatEl))) {
481
- if (el === floatEl) return
482
- for (const kid of Array.from(el.children)) walk(kid)
483
- return
484
- }
485
- hidden.push(el)
1091
+ function liveSession() {
1092
+ // Read through findColumn(), never `movedColumn ?? ...`: a recorded node
1093
+ // that has left the document still answers columnSession() with the
1094
+ // Session it used to show, and that freezes every decision on a
1095
+ // Conversation the user already left.
1096
+ if (passMemo !== null && passMemo.liveKnown) return passMemo.live
1097
+ const column = findColumn()
1098
+ let answer = null
1099
+ const shown = column === null ? null : columnSession(column)
1100
+ if (shown !== null) {
1101
+ answer = shown
1102
+ } else {
1103
+ // A docked page can be the Conversation's only home; its Session is the
1104
+ // one on screen and the entry must still find it.
1105
+ const docked = dockedBodySession()
1106
+ answer = docked !== null ? docked : lastSession
486
1107
  }
487
- for (const el of Array.from(frame.children)) {
488
- if (el === overlay) continue
489
- walk(el)
1108
+ if (answer !== null) lastSession = answer
1109
+ if (passMemo !== null) {
1110
+ passMemo.live = answer
1111
+ passMemo.liveKnown = true
490
1112
  }
491
- return hidden
1113
+ return answer
1114
+ }
1115
+
1116
+ /** Set while a deferred layout pass is already queued. */
1117
+ let kickScheduled = false
1118
+ /**
1119
+ * Queue one layout pass once the browser has committed the current frame.
1120
+ *
1121
+ * Two frames, not one: DSH writes the current Session, then React commits the
1122
+ * column for it. A pass that runs between the two sees the old nodes.
1123
+ */
1124
+ function kickLayout(frames = 2) {
1125
+ if (kickScheduled) return
1126
+ kickScheduled = true
1127
+ const run = () => {
1128
+ kickScheduled = false
1129
+ notifyLayout()
1130
+ }
1131
+ // A page taking or leaving the slot swaps whole subtrees and has no Session
1132
+ // commit to wait behind: one frame is enough there. A Session switch writes
1133
+ // its store before React commits the column, so that one keeps the second.
1134
+ if (frames >= 2) window.requestAnimationFrame(() => window.requestAnimationFrame(run))
1135
+ else window.requestAnimationFrame(run)
1136
+ }
1137
+
1138
+ /**
1139
+ * Subscribe to the one store that says which Session is on screen.
1140
+ *
1141
+ * The service may not be up when this plugin mounts, so the subscription is
1142
+ * taken as soon as it can be: once here, and again on every layout pass until it
1143
+ * takes. A Session switch then reaches every float in the same task it
1144
+ * happens in, instead of waiting for a tick.
1145
+ */
1146
+ let followingSelection = false
1147
+ function followSelection() {
1148
+ if (followingSelection) return
1149
+ let selection = null
1150
+ try {
1151
+ const workspace = typeof ctxRef?.get === 'function' ? ctxRef.get('uiWorkspace') : null
1152
+ selection = workspace === null || workspace === undefined ? null : workspace.selection ?? null
1153
+ } catch (error) {
1154
+ return
1155
+ }
1156
+ if (selection === null || typeof selection.subscribe !== 'function') return
1157
+ followingSelection = true
1158
+ try {
1159
+ // The store is written before React commits the new Session's DOM, so the
1160
+ // pass waits for the frame to be painted: deciding against the previous
1161
+ // Session's nodes is exactly how a column ends up parked.
1162
+ selection.subscribe(() => kickLayout())
1163
+ } catch (error) {
1164
+ followingSelection = false
1165
+ report('[conversation-float] could not follow the current Session:', error)
1166
+ }
1167
+ }
1168
+
1169
+ /**
1170
+ * The Session DSH itself says is on screen.
1171
+ *
1172
+ * The workspace navigation service keeps exactly one answer, in one store
1173
+ * (`uiWorkspace.selection`, persisted as `dsh.sessions.current`), and writes
1174
+ * it on every Session switch. It is the only source that does not depend on
1175
+ * a column node this plugin may be holding somewhere off screen.
1176
+ */
1177
+ function selectedSession() {
1178
+ try {
1179
+ const workspace = typeof ctxRef?.get === 'function' ? ctxRef.get('uiWorkspace') : null
1180
+ const snapshot = workspace === null || workspace === undefined ? null : workspace.selection?.getSnapshot?.()
1181
+ const id = snapshot?.sessionId
1182
+ return typeof id === 'string' && id !== '' ? id : null
1183
+ } catch (error) {
1184
+ return null
1185
+ }
1186
+ }
1187
+
1188
+ /**
1189
+ * The container that should carry this Session's Conversation, if one exists:
1190
+ * its window's body, or the right-sidebar page DSH is showing for it. Null
1191
+ * means there is nowhere but the middle column.
1192
+ */
1193
+ function hostForSession(sessionId) {
1194
+ if (sessionId === null) return null
1195
+ const win = windows.get(sessionId)
1196
+ if (win !== undefined) return win.body
1197
+ for (const host of dockedHosts()) {
1198
+ if (host.closest(`[${FLOAT_ATTR}]`) !== null) continue
1199
+ if (!hostOnScreen(host)) continue
1200
+ const owner = hostSession(host)
1201
+ if (owner === null || owner === sessionId) return host
1202
+ }
1203
+ return null
1204
+ }
1205
+
1206
+ /**
1207
+ * Hand the column to whoever should carry this Session, in ONE move.
1208
+ *
1209
+ * Parking it at home first and letting the next body pick it up later is what
1210
+ * the eye sees as "it jumps to the middle on every switch": the two moves land
1211
+ * in different passes. A host that already exists takes it directly; only a
1212
+ * Session with no host at all sends the column home.
1213
+ *
1214
+ * @returns whether the column was moved
1215
+ */
1216
+ function handOffColumn(sessionId) {
1217
+ const host = hostForSession(sessionId)
1218
+ if (host !== null) {
1219
+ if (movedColumn !== null && host.contains(movedColumn)) return false
1220
+ try {
1221
+ attachColumn(host, movedColumn !== null)
1222
+ } catch (error) {
1223
+ report('[conversation-float] could not hand the conversation over:', error)
1224
+ }
1225
+ return true
1226
+ }
1227
+ detachColumn(true)
1228
+ return true
1229
+ }
1230
+
1231
+ /**
1232
+ * Hand the Conversation back when the host it was moved into stops being it.
1233
+ *
1234
+ * The right sidebar keeps one page per Session and hides the rest, so a
1235
+ * Conversation docked there stays inside a page the window has left. Reading
1236
+ * that page's Session as "the one on screen" used to freeze the plugin on
1237
+ * the old Conversation: the float of the new one never took the column, so
1238
+ * the page tabs and the composer stayed behind in the sidebar, the middle
1239
+ * column stayed empty, and closing anything afterwards left a blank page.
1240
+ *
1241
+ * Three states have to be told apart, because the answer is not the same:
1242
+ *
1243
+ * our own window, or a dock-kit float the column lives there on purpose
1244
+ * the frame's middle column it is already home
1245
+ * a docked page of another Session taken back (see below)
1246
+ *
1247
+ * "Taken back" is either a release — when DSH has already drawn a column of
1248
+ * its own, ours is a leftover and putting it beside the live one would show
1249
+ * the same Conversation twice — or a detach, when ours is still the only
1250
+ * Conversation surface there is.
1251
+ *
1252
+ * @returns whether anything was repaired
1253
+ */
1254
+ function reconcileLiveColumn() {
1255
+ const column = movedColumn
1256
+ if (column === null) {
1257
+ columnOrphanedAt = 0
1258
+ return false
1259
+ }
1260
+ if (!column.isConnected) {
1261
+ // DSH took the node down with the Session it belonged to. If it has
1262
+ // drawn a column of its own, ours is a leftover and has to be dropped —
1263
+ // putting it back would show the old Conversation beside the new one.
1264
+ if (scanColumn() !== null) {
1265
+ columnOrphanedAt = 0
1266
+ forgetColumn(column, false)
1267
+ return true
1268
+ }
1269
+ // Nothing shows the Conversation at all. The frame may be one commit
1270
+ // away from drawing it, so give it a moment before rescuing ours: a
1271
+ // rescue that races the frame's own column leaves two of them.
1272
+ if (columnOrphanedAt === 0) {
1273
+ columnOrphanedAt = Date.now()
1274
+ return false
1275
+ }
1276
+ if (Date.now() - columnOrphanedAt < 700) return false
1277
+ columnOrphanedAt = 0
1278
+ detachColumn(true)
1279
+ return true
1280
+ }
1281
+ columnOrphanedAt = 0
1282
+ if (column.closest(`[${WINDOW_ATTR}]`) !== null) return false
1283
+ if (column.closest(`[${FLOAT_ATTR}]`) !== null) return false
1284
+ const page = column.closest('[data-sidebar-right-session]')
1285
+ if (page === null) return false
1286
+ const owner = page.getAttribute('data-sidebar-right-session')
1287
+ const live = selectedSession() ?? dockedBodySession()
1288
+ if (live === null || owner === null || owner === live) return false
1289
+ // A tab can belong to a subagent chat, which is addressed rather than
1290
+ // named: such an address is not a Session, so a mismatch with it means
1291
+ // nothing and must not take the column away.
1292
+ if (!knownSession(owner) || !knownSession(live)) return false
1293
+ const fresh = scanColumn()
1294
+ if (fresh !== null && fresh !== column) {
1295
+ forgetColumn(column, true)
1296
+ return true
1297
+ }
1298
+ // Straight to whatever should carry the Session we switched to — never
1299
+ // through the middle column, which is the visible "jump".
1300
+ handOffColumn(live)
1301
+ return true
1302
+ }
1303
+
1304
+ /** Whether an id names a Session the list knows (or the list is unreadable). */
1305
+ function knownSession(id) {
1306
+ try {
1307
+ const byId = sessions?.list?.getSnapshot?.()?.byId
1308
+ if (byId === undefined || byId === null) return true
1309
+ return Object.prototype.hasOwnProperty.call(byId, id)
1310
+ } catch (error) {
1311
+ return true
1312
+ }
1313
+ }
1314
+
1315
+ /**
1316
+ * Let go of a column without putting it back.
1317
+ *
1318
+ * @param column the node the bookkeeping names, which may already be gone
1319
+ * @param discardDom also take it out of the tab body it sits in. Only for a
1320
+ * leftover: DSH has drawn a column of its own, so this one
1321
+ * is a copy nothing renders into any more, and keeping it
1322
+ * would show two Conversations the next time that page is
1323
+ * opened.
1324
+ */
1325
+ function forgetColumn(column, discardDom) {
1326
+ if (movedColumn === column) {
1327
+ movedColumn = null
1328
+ movedFrom = null
1329
+ }
1330
+ if (column === null) return
1331
+ column.removeAttribute(COLUMN_ATTR)
1332
+ column.style.width = ''
1333
+ column.style.height = ''
1334
+ column.style.minWidth = ''
1335
+ column.style.minHeight = ''
1336
+ column.style.overflow = ''
1337
+ if (discardDom && column.isConnected && column.closest(`[${BODY_ATTR}]`) !== null) column.remove()
1338
+ noteColumnMoved()
1339
+ // The column is gone: no pass may keep answering with it.
1340
+ if (passMemo !== null) {
1341
+ passMemo.columnKnown = false
1342
+ passMemo.liveKnown = false
1343
+ }
1344
+ notifyState()
1345
+ }
1346
+
1347
+ /** The Session of the right-sidebar page that is on screen, if any. */
1348
+ function dockedBodySession() {
1349
+ for (const host of document.querySelectorAll(`[${BODY_ATTR}]`)) {
1350
+ if (host.closest(`[${FLOAT_ATTR}]`) !== null) continue
1351
+ if (!hostOnScreen(host)) continue
1352
+ const owner = hostSession(host)
1353
+ if (owner !== null) return owner
1354
+ }
1355
+ return null
1356
+ }
1357
+
1358
+ /* ---------------------------------------------------------- the chrome */
1359
+
1360
+ /**
1361
+ * Hide everything the float does not need. Clicking the entry opens the
1362
+ * float and leaves the window showing nothing but the float; the same
1363
+ * button then brings the rest of DSH back (and hides it again).
1364
+ */
1365
+ function chromeTargets() {
1366
+ const overlay = document.querySelector('[data-shell-overlay]')
1367
+ const frame = overlay === null ? null : overlay.parentElement
1368
+ if (frame === null) return []
1369
+ const floatEl = floatPanel()
1370
+ const hidden = []
1371
+ /** Keep the branch that holds the float; hide every sibling beside it. */
1372
+ const walk = (el) => {
1373
+ if (floatEl !== null && (el === floatEl || el.contains(floatEl))) {
1374
+ if (el === floatEl) return
1375
+ for (const kid of Array.from(el.children)) walk(kid)
1376
+ return
1377
+ }
1378
+ hidden.push(el)
1379
+ }
1380
+ for (const el of Array.from(frame.children)) {
1381
+ if (el === overlay) continue
1382
+ walk(el)
1383
+ }
1384
+ return hidden
1385
+ }
1386
+
1387
+ /** What the entry's tooltip promises for the next press. */
1388
+ function entryTitle() {
1389
+ const sessionId = liveSession()
1390
+ const win = sessionId === null ? undefined : windows.get(sessionId)
1391
+ if (win === undefined || win.el.hidden) return t('floatTitle')
1392
+ return chromeless ? t('showDsh') : t('hideDsh')
492
1393
  }
493
1394
 
494
1395
  function setChromeless(next) {
495
1396
  if (next) {
496
1397
  // The float mounts asynchronously: hiding before it exists would hide
497
- // every column, including the one that is about to host it.
498
- if (floatPanel() === null) {
1398
+ // every column, including the one that is about to host it. Our own
1399
+ // window is not a dock-kit float, so both count as "something to keep".
1400
+ if (floatPanel() === null && windows.size === 0) {
499
1401
  pendingChromeless = true
500
1402
  return
501
1403
  }
@@ -511,7 +1413,7 @@ window.__ModuleLoader__.load({
511
1413
  }
512
1414
  try {
513
1415
  const button = document.querySelector(`[${ANCHOR_ATTR}]`)
514
- if (button !== null) button.title = next ? t('showDsh') : t('floatTitle')
1416
+ if (button !== null) button.title = entryTitle()
515
1417
  } catch {
516
1418
  /* the button may not be mounted */
517
1419
  }
@@ -522,24 +1424,28 @@ window.__ModuleLoader__.load({
522
1424
  * sidebar, so the window used to come back as "only the right column": a
523
1425
  * reveal opens the drawer again, the same way opening the float does.
524
1426
  */
525
- function revealChrome() {
1427
+ function revealChrome(forceDrawer = false) {
526
1428
  setChromeless(false)
527
- // The columns opened here are the plugin's doing, not the user's: a
528
- // short settle, not a long one, or the user's own first click after the
529
- // reveal would be ignored as if it were the plugin's.
530
- holdOff(400)
531
- // The design: while the window is only the float, both sidebars are open —
532
- // the drawer holds a stowed float, the right column is where "收回到侧边栏"
533
- // docks. The reveal opens both, whatever DSH railed away while hidden.
534
- try {
535
- if (leftCollapsed()) layout?.toggleSidebar?.()
536
- } catch (error) {
537
- console.warn('[conversation-float] could not expand the left sidebar:', error)
1429
+ // The columns are opened by the plugin, and a hand on them ends any retry
1430
+ // this pass started (see the pointerdown tracker in apply()), so the
1431
+ // user's own first click is never swallowed by a settle window.
1432
+ // Back to the arrangement the window had: whatever the user last left the
1433
+ // sidebars in, or the pair the float found. Never a blanket "both open" —
1434
+ // that would undo a sidebar the user closed on purpose.
1435
+ const base = restoreTarget()
1436
+ // Stowing the float needs its drawer row on screen, whatever the target.
1437
+ // The forced drawer is folded into the target itself: a separate toggle
1438
+ // would be undone by the retry pass that follows it.
1439
+ const target = base === null ? null : forceDrawer ? { ...base, leftCollapsed: false } : base
1440
+ if (target !== null) {
1441
+ applyChromeTarget(target)
1442
+ return
538
1443
  }
1444
+ if (!forceDrawer) return
539
1445
  try {
540
- if (sidebarRight !== null && sidebarRight.isExpanded?.() === false) sidebarRight.toggleExpanded?.()
1446
+ if (leftCollapsed()) layout?.toggleSidebar?.()
541
1447
  } catch (error) {
542
- console.warn('[conversation-float] could not expand the right sidebar:', error)
1448
+ report('[conversation-float] could not expand the left sidebar:', error)
543
1449
  }
544
1450
  }
545
1451
 
@@ -566,7 +1472,7 @@ window.__ModuleLoader__.load({
566
1472
  sidebarRight?.toggleExpanded?.()
567
1473
  }
568
1474
  } catch (error) {
569
- console.warn('[conversation-float] could not restore the right sidebar:', error)
1475
+ report('[conversation-float] could not restore the right sidebar:', error)
570
1476
  }
571
1477
  try {
572
1478
  if (wantLeft !== null && wantLeft !== leftCollapsed()) {
@@ -574,7 +1480,7 @@ window.__ModuleLoader__.load({
574
1480
  layout?.toggleSidebar?.()
575
1481
  }
576
1482
  } catch (error) {
577
- console.warn('[conversation-float] could not restore the left sidebar:', error)
1483
+ report('[conversation-float] could not restore the left sidebar:', error)
578
1484
  }
579
1485
  return matched
580
1486
  }
@@ -607,23 +1513,6 @@ window.__ModuleLoader__.load({
607
1513
  return { leftCollapsed: leftCollapsed(), rightExpanded: rightExpanded() }
608
1514
  }
609
1515
 
610
- /** The plugin is about to move a column itself: ignore the fallout. */
611
- function holdOff(ms = 1200) {
612
- holdOffUntil = performance.now() + ms
613
- }
614
-
615
- /**
616
- * Only the user's own hand can author a column change: a press or a key
617
- * just before it does, DSH railing a column on its own does not. The
618
- * plugin's own entry button is excluded — it moves the columns by design.
619
- */
620
- function noteGesture(event) {
621
- if (performance.now() < holdOffUntil) return
622
- const target = event.target
623
- if (target instanceof Element && target.closest(`[${ANCHOR_ATTR}]`) !== null) return
624
- gestureAt = performance.now()
625
- }
626
-
627
1516
  /**
628
1517
  * Remember the sidebars as they were before the float forced them open.
629
1518
  * The capture happens once, before the plugin touches anything, and is
@@ -634,37 +1523,6 @@ window.__ModuleLoader__.load({
634
1523
  function saveChromeState() {
635
1524
  if (savedChrome !== null) return
636
1525
  savedChrome = chromeNow()
637
- chromeTouched = false
638
- // The force-open that follows is the plugin's doing, not the user's.
639
- holdOff(FORCE_SETTLE_MS)
640
- }
641
-
642
- /**
643
- * The float forces both sidebars open and hides them. A column that sits
644
- * away from the snapshot after that was either moved by the user or railed
645
- * by DSH on its own; only the first outranks the snapshot, and only a
646
- * press or a key just before the change tells the two apart. Both
647
- * directions count: closing a column the float opened, and opening one it
648
- * failed to open, are equally the user's choice.
649
- */
650
- function noteChromeChange() {
651
- if (savedChrome === null) return
652
- // While the columns are hidden their geometry says nothing: DSH rails the
653
- // left sidebar on its own there, and reading that as the user's choice
654
- // would cancel the restore the float promised.
655
- if (chromeless || pendingChromeless) return
656
- // A re-host (out of the drawer, a remounted body) leaves the column out
657
- // of the document and the right column reading "not expanded" for a
658
- // frame. That is the plugin moving, never the user choosing.
659
- if (dockedLeft || (floatPanel() !== null && movedColumn === null)) return
660
- const now = performance.now()
661
- if (now < holdOffUntil) return
662
- const current = chromeNow()
663
- // Back on the snapshot's own pair: there is nothing to remember, and the
664
- // restore would be a no-op anyway.
665
- if (current.leftCollapsed === savedChrome.leftCollapsed && current.rightExpanded === savedChrome.rightExpanded) return
666
- if (now - gestureAt > GESTURE_WINDOW) return
667
- chromeTouched = true
668
1526
  }
669
1527
 
670
1528
  /**
@@ -676,7 +1534,7 @@ window.__ModuleLoader__.load({
676
1534
  function scheduleRestoreChrome(depth = 0) {
677
1535
  window.requestAnimationFrame(() => {
678
1536
  // A host took the column back: the float is still open, not closed.
679
- if (dockedLeft || movedColumn !== null) return
1537
+ if (movedColumn !== null) return
680
1538
  // The panel is still on its way out; give it a few frames.
681
1539
  if (floatPanel() !== null) {
682
1540
  if (depth < 12) scheduleRestoreChrome(depth + 1)
@@ -686,120 +1544,133 @@ window.__ModuleLoader__.load({
686
1544
  })
687
1545
  }
688
1546
 
689
- /**
690
- * Put back what the user had, unless they changed it themselves. This runs
691
- * while the float's tab is still being torn down, and the dock kit can
692
- * swallow a toggle aimed at a surface that is on its way out: the snapshot
693
- * is reapplied until both columns match it or the attempts run out.
694
- */
695
- function restoreChrome() {
696
- const saved = savedChrome
697
- const touched = chromeTouched
698
- savedChrome = null
699
- chromeTouched = false
700
- if (saved === null || touched) return
701
- holdOff(1500)
702
- let tries = 0
1547
+ /** The pair a reveal or a close puts back: the snapshot taken on open. */
1548
+ function restoreTarget() {
1549
+ return savedChrome
1550
+ }
1551
+
1552
+ /** Match the sidebars to a target, retrying while the dock kit settles. */
1553
+ function applyChromeTarget(target) {
1554
+ // A toggle the dock kit queued needs a commit to land, so a retry fired
1555
+ // before that commit reads the old state and toggles straight back. The
1556
+ // retry therefore waits for the sidebars to STOP MOVING before it fires,
1557
+ // instead of firing on a fixed 200ms beat that was both too early (double
1558
+ // toggles) and too late (a visible lag on close).
1559
+ let attempts = 0
1560
+ let seen = null
1561
+ let stable = 0
703
1562
  const apply = () => {
704
- tries += 1
705
- if (applyChromeSnapshot(saved)) return
706
- // A toggle the dock kit queued needs a moment to land; retrying on the
707
- // next frame would read the old state and toggle straight back.
708
- if (tries < 8) window.setTimeout(apply, 200)
1563
+ if (chromeMatches(target)) return true
1564
+ attempts += 1
1565
+ if (attempts > 3) return true
1566
+ applyChromeSnapshot(target)
1567
+ return false
709
1568
  }
710
- window.requestAnimationFrame(apply)
1569
+ if (apply()) return
1570
+ chromeApplyStop = untilFrame(() => {
1571
+ if (chromeMatches(target)) return true
1572
+ const now = JSON.stringify(chromeNow())
1573
+ if (now === seen) stable += 1
1574
+ else { seen = now; stable = 0 }
1575
+ return stable >= 3 && apply()
1576
+ }, null, 3000)
1577
+ }
1578
+
1579
+ /** Whether the sidebars already stand where `target` wants them. */
1580
+ function chromeMatches(target) {
1581
+ if (target === null || target === undefined) return true
1582
+ const now = chromeNow()
1583
+ const wantRight = target.rightExpanded
1584
+ const wantLeft = target.leftCollapsed
1585
+ const rightOk = wantRight === null || wantRight === undefined ? true : now.rightExpanded === (wantRight === true)
1586
+ const leftOk = wantLeft === null || wantLeft === undefined ? true : now.leftCollapsed === wantLeft
1587
+ return rightOk && leftOk
1588
+ }
1589
+
1590
+ function restoreChrome() {
1591
+ const target = restoreTarget()
1592
+ savedChrome = null
1593
+ if (target === null) return
1594
+ applyChromeTarget(target)
711
1595
  }
712
1596
 
713
1597
  /** Open (or focus) the float at the dock kit's own default seat. */
1598
+ /**
1599
+ * Give this Conversation a window.
1600
+ *
1601
+ * The window is ours, so no sidebar has to be opened for it and nothing is
1602
+ * re-seated: the tab body mounts and the body is what owns the window. A tab
1603
+ * kept from an earlier run is reused — its body is still mounted, so only
1604
+ * the window has to come back.
1605
+ */
714
1606
  function openFloatAtDefault() {
1607
+ const sessionId = liveSession()
1608
+ if (sessionId === null) return
715
1609
  saveChromeState()
716
- // The left drawer is where "放进左栏" lands: a collapsed sidebar has no
717
- // room to grow the row, so open it first — the right column's rule.
718
- try {
719
- if (leftCollapsed()) layout?.toggleSidebar?.()
720
- } catch (error) {
721
- console.warn('[conversation-float] could not expand the left sidebar:', error)
722
- }
723
- // The docked side of the panel is where "收回到侧边栏" lands: keep it open
724
- // so the float always has a home to be returned to.
725
- try {
726
- if (sidebarRight !== null && sidebarRight.isExpanded?.() === false) sidebarRight.toggleExpanded?.()
727
- } catch (error) {
728
- console.warn('[conversation-float] could not expand the right sidebar:', error)
729
- }
730
- if (floatExistingTab()) {
731
- setChromeless(true)
1610
+ if (tabIdFor(sessionId) !== null) {
1611
+ // The tab exists. Floating it is the SAME tab moving, never a second
1612
+ // one: a docked page is floated through the dock kit's own intent, and
1613
+ // the re-hosted body then raises this Conversation's window.
1614
+ if (floatPanel() === null) {
1615
+ // Docked page: close it and open a fresh float, so the floating body
1616
+ // mounts against a clean tree and takes the column with it.
1617
+ closeTabFor(sessionId)
1618
+ // The new body must mount against a tree the old tab has left, so the
1619
+ // open waits for the tab to be gone rather than for 60ms to pass.
1620
+ // Close first, then open into the freed slot. The microtask is the
1621
+ // whole ordering guarantee: it runs after the commit that unmounts
1622
+ // the closed body, and before anything the user can see or press.
1623
+ queueMicrotask(() => {
1624
+ try {
1625
+ sidebarRight?.openResource(CHAT_ADDRESS, { kind: CHAT_KIND, destination: 'float' })
1626
+ } catch (error) {
1627
+ report('[conversation-float] could not open the floating tab:', error)
1628
+ }
1629
+ })
1630
+ notifyState()
1631
+ return
1632
+ }
1633
+ showWindow(sessionId)
1634
+ notifyState()
732
1635
  return
733
1636
  }
734
1637
  try {
735
1638
  sidebarRight?.openResource(CHAT_ADDRESS, { kind: CHAT_KIND, destination: 'float' })
736
1639
  } catch (error) {
737
- console.warn('[conversation-float] could not open the floating panel:', error)
1640
+ report('[conversation-float] could not open the floating tab:', error)
738
1641
  }
739
- // Opening the float leaves the window to the float alone.
740
- setChromeless(true)
1642
+ notifyState()
741
1643
  }
742
1644
 
1645
+ /** Open this Conversation's window, or bring it back from the taskbar. */
743
1646
  function openFloating() {
744
- if (!dockedLeft) {
745
- unstowFloat()
746
- openFloatAtDefault()
1647
+ const sessionId = liveSession()
1648
+ if (sessionId === null) return
1649
+ if (windows.has(sessionId)) {
1650
+ showWindow(sessionId)
1651
+ notifyState()
747
1652
  return
748
1653
  }
749
- // Out of the drawer the float is still mounted, holding the only copy of
750
- // the Conversation. Reopening it as a fresh panel raced the old one's
751
- // cleanup and left an empty window, so take it back as it stands.
752
- dockedLeft = false
753
- syncDockRow()
754
- unstowFloat()
755
- // The drawer row lives on a normal window: taking the float back out
756
- // puts it ON that window, not instead of it. Blanking the window here
757
- // is what made the drawer and the right column look collapsed.
1654
+ openFloatAtDefault()
758
1655
  }
759
1656
 
760
- /** The tab id of our floating occurrence, or null when it is not minted. */
761
- function floatTabId() {
762
- try {
763
- const active = sidebarRight?.active?.()
764
- if (active !== undefined && active !== null && active.kind === CHAT_KIND) return active.id
765
- } catch {
766
- /* fall through to the inventory */
767
- }
1657
+ /** A Conversation's stored title, as the sidebars and windows show it. */
1658
+ function sessionTitle(id) {
1659
+ if (id === null) return null
768
1660
  try {
769
- const snapshot = sidebarRight?.openTabs?.getSnapshot?.()
770
- const found = new Set()
771
- const walk = (value, depth) => {
772
- if (value === null || value === undefined || depth > 6) return
773
- if (Array.isArray(value)) {
774
- for (const item of value) walk(item, depth + 1)
775
- return
776
- }
777
- if (typeof value !== 'object') return
778
- if (value.kind === CHAT_KIND && typeof value.id === 'string') found.add(value.id)
779
- for (const key of Object.keys(value)) walk(value[key], depth + 1)
780
- }
781
- walk(snapshot, 0)
782
- const ids = Array.from(found)
783
- return ids.length === 1 ? ids[0] : (ids[ids.length - 1] ?? null)
1661
+ const title = sessions?.list?.getSnapshot?.()?.byId?.[id]?.title
1662
+ return typeof title === 'string' && title.trim() !== '' ? title.trim() : null
784
1663
  } catch {
785
1664
  return null
786
1665
  }
787
1666
  }
788
1667
 
789
- /** Close the float; the column comes home through the watcher. */
1668
+ /** Close this Conversation's window: its tab goes, the window with it. */
790
1669
  function closeFloat() {
791
- const id = floatTabId()
792
- if (id === null) {
793
- console.warn('[conversation-float] no floating tab id; the float stays open')
794
- return false
795
- }
796
- try {
797
- sidebarRight.hide(id)
798
- return true
799
- } catch (error) {
800
- console.warn('[conversation-float] could not hide the floating tab:', error)
801
- return false
802
- }
1670
+ const sessionId = liveSession()
1671
+ if (sessionId === null) return false
1672
+ closeWindow(sessionId)
1673
+ return true
803
1674
  }
804
1675
 
805
1676
  /* ---------------------------------------------------------------- bands */
@@ -827,6 +1698,10 @@ window.__ModuleLoader__.load({
827
1698
  const rightCol = frame.querySelector('[data-rightbar-col]')
828
1699
  if (rightCol !== null) right = Math.round(rightCol.getBoundingClientRect().left)
829
1700
  }
1701
+ // A collapsed right column measures at the window's edge, which would leave
1702
+ // the "dock right" band zero wide and unreachable; keep a third of the
1703
+ // window aimable there, and the docking itself opens the column.
1704
+ if (right >= width - 1) right = Math.round((width * 2) / 3)
830
1705
  // While the columns are hidden the measurements collapse; keep the last
831
1706
  // geometry that made sense so a drag does not land in nonsense bands.
832
1707
  const sane = left >= 0 && right > left + 80 && right <= width + 1
@@ -847,7 +1722,31 @@ window.__ModuleLoader__.load({
847
1722
  return 'center'
848
1723
  }
849
1724
 
850
- const ZONE_LABEL = { left: t('stow'), center: t('center'), right: t('dock') }
1725
+ /**
1726
+ * The band's caption, read at draw time. It used to be a table built once at
1727
+ * load: a language switch then left the preview saying the old words.
1728
+ */
1729
+ function zoneLabel(zone) {
1730
+ if (zone === 'left') return t('stow')
1731
+ if (zone === 'right') return t('dock')
1732
+ return t('center')
1733
+ }
1734
+
1735
+ /**
1736
+ * The band's caption for the window under the hand.
1737
+ *
1738
+ * A band moves the Conversation on screen, never the window the hand holds:
1739
+ * dragging a second float says nothing about which Conversation goes where.
1740
+ * So the outline names its cargo — the main one — whenever the window being
1741
+ * dragged is not itself that Conversation.
1742
+ *
1743
+ * @param zone the band under the pointer
1744
+ * @param own whether the dragged window carries the Conversation on screen
1745
+ */
1746
+ function previewLabel(zone, own) {
1747
+ const label = zoneLabel(zone)
1748
+ return own ? label : t('toMain') + label
1749
+ }
851
1750
 
852
1751
  function previewRect(zone, band) {
853
1752
  if (zone === 'left') return [0, 0, band.left, band.height]
@@ -860,7 +1759,7 @@ window.__ModuleLoader__.load({
860
1759
  * rewrote four styles (after a layout read) on every pointer move, and that
861
1760
  * is what made the drag stutter next to DSH's own dragging.
862
1761
  */
863
- function showPreview(zone, band) {
1762
+ function showPreview(zone, band, own = true) {
864
1763
  if (preview === null) {
865
1764
  const el = document.createElement('div')
866
1765
  el.className = 'dsw-preview'
@@ -868,16 +1767,24 @@ window.__ModuleLoader__.load({
868
1767
  label.className = 'dsw-preview-label'
869
1768
  el.appendChild(label)
870
1769
  document.body.appendChild(el)
871
- preview = { el, label, zone: null }
1770
+ preview = { el, label, zone: null, own: true }
872
1771
  }
873
- if (preview.zone === zone) return
1772
+ // The caption changes with OWNERSHIP as well as with the band: the same
1773
+ // band dropped from another window names a different Conversation.
1774
+ if (preview.zone === zone && preview.own === own) return
1775
+ // The outline marks the band the window will land in, so it has to sit
1776
+ // ABOVE every float window. The windows live in a band that starts at
1777
+ // 20000 and climbs as they are raised, so the outline takes the current
1778
+ // ceiling plus a margin instead of a fixed number that goes stale.
1779
+ preview.el.style.zIndex = String(Math.min(windowZ + 10, 950))
874
1780
  if (preview.el.style.display === 'none') preview.el.style.display = ''
875
1781
  preview.zone = zone
1782
+ preview.own = own
876
1783
  const [left, top, width, height] = previewRect(zone, band)
877
1784
  preview.el.style.transform = `translate3d(${left}px, ${top}px, 0)`
878
1785
  preview.el.style.width = `${width}px`
879
1786
  preview.el.style.height = `${height}px`
880
- preview.label.textContent = ZONE_LABEL[zone] ?? ''
1787
+ preview.label.textContent = previewLabel(zone, own)
881
1788
  }
882
1789
 
883
1790
  function hidePreview() {
@@ -900,64 +1807,193 @@ window.__ModuleLoader__.load({
900
1807
  function floatPanel() {
901
1808
  const column = movedColumn
902
1809
  const fromColumn = column === null ? null : column.closest(`[${FLOAT_ATTR}]`)
903
- return fromColumn ?? document.querySelector(`[${FLOAT_ATTR}]`)
1810
+ if (fromColumn !== null) return fromColumn
1811
+ // The right sidebar keeps one mounted panel per Session and hides the
1812
+ // ones the window has left. A foreign float is not *the* float: reading it
1813
+ // as one would make the entry believe a panel is on screen and hide DSH
1814
+ // around a window that holds nothing at all.
1815
+ const showing = liveSession()
1816
+ for (const el of document.querySelectorAll(`[${FLOAT_ATTR}]`)) {
1817
+ if (el.closest('[hidden], [aria-hidden="true"]') !== null) continue
1818
+ const owner = floatOwnerSession(el)
1819
+ if (owner !== null && showing !== null && owner !== showing) continue
1820
+ return el
1821
+ }
1822
+ return null
904
1823
  }
905
1824
 
906
- function stowFloat() {
907
- const el = floatPanel()
908
- if (el === null) return false
909
- el.setAttribute(STOW_ATTR, '')
1825
+ /**
1826
+ * Finish a stow that was asked for before its float existed. The first
1827
+ * request arrives while the conversation is still a docked tab — the tab's
1828
+ * body is retained, so floating it does NOT remount the body and
1829
+ * {@link attachColumn} never runs again. Without this the request would sit
1830
+ * in `pendingMinimise` forever: the conversation would come back on screen
1831
+ * instead of being put away, which is what the menu entry promised.
1832
+ *
1833
+ * @returns whether the window was minimised.
1834
+ */
1835
+ function flushPendingMinimise() {
1836
+ if (!pendingMinimise) return false
1837
+ const panel = floatPanel()
1838
+ if (panel === null) return false
1839
+ // A float of another Session cannot host this Conversation.
1840
+ if (!floatHostsSession(panel, liveSession())) return false
1841
+ pendingMinimise = false
1842
+ pendingChromeless = false
1843
+ // Minimise, not stow: the drawer row this used to build belonged to the
1844
+ // dock-kit panel of the old architecture. A window's taskbar row already
1845
+ // exists from the moment it opens, so hiding it IS the left-hand action.
1846
+ const shown = liveSession()
1847
+ if (shown === null || !windows.has(shown)) return false
1848
+ hideWindow(shown)
1849
+ if (chromeless) revealChrome()
1850
+ notifyState()
910
1851
  return true
911
1852
  }
912
1853
 
913
- function unstowFloat() {
914
- for (const el of document.querySelectorAll(`[${STOW_ATTR}]`)) el.removeAttribute(STOW_ATTR)
1854
+ /** Close this Conversation's tab for good: the next host mounts a new body. */
1855
+ function closeTabFor(sessionId) {
1856
+ const id = tabIdFor(sessionId)
1857
+ if (id === null) return false
1858
+ try {
1859
+ if (typeof sidebarRight?.closeIn === 'function') sidebarRight.closeIn(sessionId, id)
1860
+ else sidebarRight?.hide?.(id)
1861
+ return true
1862
+ } catch (error) {
1863
+ report('[conversation-float] could not close the tab:', error)
1864
+ return false
1865
+ }
1866
+ }
1867
+
1868
+ /**
1869
+ * The left band, asked of whichever host the main Conversation has.
1870
+ *
1871
+ * A band always acts on the Conversation on screen, never on the window the
1872
+ * hand happens to hold, so this has to work from all three seats it can be
1873
+ * in:
1874
+ *
1875
+ * its own window minimised — still mounted, hidden, its taskbar row
1876
+ * in the left sidebar is the way back
1877
+ * a docked tab floated, then minimised the moment its body mounts
1878
+ * the middle column the same: a window is opened and put away at once
1879
+ *
1880
+ * It used to read "no window, so close it" — which closed nothing while the
1881
+ * Conversation sat in the middle, and only sent it back to the middle when
1882
+ * it was docked. A drop on the left band then never reached the left.
1883
+ */
1884
+ function stowLiveConversation() {
1885
+ const shown = liveSession()
1886
+ if (shown !== null && windows.has(shown)) {
1887
+ hideWindow(shown)
1888
+ notifyState()
1889
+ } else if (floatPanel() !== null) {
1890
+ // A float this build did not create: closing it is all that is left.
1891
+ closeFloat()
1892
+ } else {
1893
+ // No window of its own yet. Opening one and minimising it before its
1894
+ // first paint is exactly what the sidebar's own row does.
1895
+ pendingMinimise = true
1896
+ openFloating()
1897
+ }
1898
+ // A minimised float must not leave an empty screen behind: the rest of
1899
+ // DSH only comes back if the float was the thing hiding it.
1900
+ if (chromeless) revealChrome()
915
1901
  }
916
1902
 
917
1903
  function drop(zone) {
918
1904
  if (zone === 'right') {
919
- dockedLeft = false
920
1905
  dockingRight = true
921
1906
  // The float leaves as an ordinary right-sidebar tab. The sidebar
922
1907
  // snapshot belonged to the float: keeping it would let a close of that
923
1908
  // tab — possibly hours later — move the sidebars back in time.
924
1909
  savedChrome = null
925
- chromeTouched = false
926
- unstowFloat()
927
- syncDockRow()
928
- try {
929
- sidebarRight?.openResource(CHAT_ADDRESS, { kind: CHAT_KIND, destination: 'sidebar' })
930
- } catch (error) {
931
- console.warn('[conversation-float] could not dock to the right sidebar:', error)
1910
+ // Our window and the right-sidebar page are the same tab: the window
1911
+ // goes first, or it would outlive the page it was showing and sit there
1912
+ // blank while the tab moves underneath it.
1913
+ const shown = liveSession()
1914
+ if (shown !== null) {
1915
+ // A re-hosted body keeps its React tree and loses the column's
1916
+ // bookkeeping with it; closing the tab first gives the page a fresh
1917
+ // body that attaches the column again.
1918
+ closeTabFor(shown)
1919
+ if (windows.has(shown)) destroyWindow(shown)
932
1920
  }
1921
+ // Same ordering rule as the float: after the unmount commit, nothing
1922
+ // visible in between.
1923
+ queueMicrotask(() => {
1924
+ try {
1925
+ sidebarRight?.openResource(CHAT_ADDRESS, { kind: CHAT_KIND, destination: 'sidebar' })
1926
+ } catch (error) {
1927
+ report('[conversation-float] could not dock to the right sidebar:', error)
1928
+ }
1929
+ })
933
1930
  return
934
1931
  }
935
1932
  if (zone === 'left') {
936
- dockedLeft = true
937
- syncDockRow()
938
- if (!stowFloat()) closeFloat()
939
- // The drawer row lives in the left sidebar: bring the chrome back so it
940
- // can be seen and clicked.
941
- revealChrome()
1933
+ stowLiveConversation()
942
1934
  return
943
1935
  }
944
- dockedLeft = false
945
- syncDockRow()
946
1936
  revealChrome()
947
1937
  closeFloat()
948
1938
  }
949
1939
 
1940
+ /* ------------------------------------------------------ the menu entries */
1941
+
1942
+ /**
1943
+ * Whether the live conversation is minimised into the left sidebar. Its
1944
+ * window is still mounted but hidden, and its taskbar row is the way back,
1945
+ * so the "stow here" row has nothing left to do.
1946
+ */
1947
+ function conversationInLeftbar() {
1948
+ const shown = liveSession()
1949
+ if (shown === null) return false
1950
+ const win = windows.get(shown)
1951
+ return win !== undefined && win.el.hidden
1952
+ }
1953
+
1954
+ /**
1955
+ * Whether the live conversation is a docked tab of the right sidebar. The
1956
+ * menu entry that says "move it here" has nothing to do when it is already.
1957
+ */
1958
+ function conversationInRightbar() {
1959
+ const column = movedColumn ?? findColumn()
1960
+ if (column === null) return false
1961
+ if (column.closest(`[${FLOAT_ATTR}]`) !== null) return false
1962
+ return column.closest('[data-rightbar-col]') !== null
1963
+ }
1964
+
1965
+ /** Dock the conversation in the right sidebar, exactly as a drop does. */
1966
+ function moveConversationRight() {
1967
+ drop('right')
1968
+ }
1969
+
1970
+ /**
1971
+ * Minimise the conversation's window, as a drop on the left band does.
1972
+ * Without a window there is nothing to minimise, so one is opened first and
1973
+ * the minimise runs the moment its body mounts — before the first paint —
1974
+ * which is why the window never flashes on screen on its way out.
1975
+ */
1976
+ function moveConversationLeft() {
1977
+ stowLiveConversation()
1978
+ }
1979
+
950
1980
  /**
951
1981
  * Watch the float's own drag. DSH owns the dragging; we only listen. A press
952
1982
  * on the float's chrome opens a sequence; a press inside the Conversation
953
1983
  * column does not, because that one is a text selection.
954
1984
  */
955
- function trackPanelDrag(container) {
1985
+ function trackPanelDrag(container, sessionId) {
956
1986
  let down = null
957
1987
  let band = null
958
1988
  let root = null
959
1989
  let frame = 0
960
1990
  let pending = null
1991
+ /**
1992
+ * Whether this window carries the Conversation on screen. The outline's
1993
+ * caption depends on it: a band acts on the main Conversation, so a drag
1994
+ * of any other window has to say whose Conversation is being moved.
1995
+ */
1996
+ const draggingMain = () => sessionId === null || sessionId === liveSession()
961
1997
  /** The band under the pointer right now. */
962
1998
  let hovered = null
963
1999
  /** The band the outline currently shows. */
@@ -971,7 +2007,9 @@ window.__ModuleLoader__.load({
971
2007
  /** Resolved per pointer sequence: the panel mounts after this body does. */
972
2008
  const floatRoot = () => {
973
2009
  if (root !== null && root.isConnected) return root
974
- root = container.isConnected ? container.closest(`[${FLOAT_ATTR}]`) : null
2010
+ // The float used to BE the dock kit's panel. It is a window of our own
2011
+ // now, drawn under the root, so the press may land in either.
2012
+ root = container.isConnected ? container.closest(`[${FLOAT_ATTR}], [${WINDOW_ATTR}]`) : null
975
2013
  return root
976
2014
  }
977
2015
 
@@ -986,7 +2024,7 @@ window.__ModuleLoader__.load({
986
2024
  if (!judging || drawn === hovered) return
987
2025
  drawn = hovered
988
2026
  if (drawn === null) hidePreview()
989
- else showPreview(drawn, band)
2027
+ else showPreview(drawn, band, draggingMain())
990
2028
  }
991
2029
 
992
2030
  const onDown = (event) => {
@@ -1039,6 +2077,9 @@ window.__ModuleLoader__.load({
1039
2077
  return
1040
2078
  }
1041
2079
  judging = true
2080
+ // Show the hold that armed it: without a visible change, a hold that
2081
+ // did nothing and a hold that armed look exactly the same.
2082
+ try { floatRoot()?.setAttribute(ARMED_ATTR, '') } catch { /* no window */ }
1042
2083
  // A still hold never produced a move, so take the band from where
1043
2084
  // the pointer is right now instead of leaving it unset.
1044
2085
  if (hovered === null) hovered = zoneAt(down.lastX ?? down.x, band)
@@ -1085,6 +2126,7 @@ window.__ModuleLoader__.load({
1085
2126
  if (pending !== null) flush()
1086
2127
  stopJudge()
1087
2128
  const target = judging ? hovered : null
2129
+ try { floatRoot()?.removeAttribute(ARMED_ATTR) } catch { /* already gone */ }
1088
2130
  down = null
1089
2131
  band = null
1090
2132
  pending = null
@@ -1159,28 +2201,601 @@ window.__ModuleLoader__.load({
1159
2201
 
1160
2202
  /* ----------------------------------------------------------- the drawer */
1161
2203
 
1162
- function syncDockRow() {
1163
- if (dockedLeft && dockRow === null) {
2204
+ let ctxRef = null
2205
+
2206
+ /* ------------------------------------------------------- the float window */
2207
+
2208
+ /**
2209
+ * A float is OUR window: one element per Conversation, parented to `#root`
2210
+ * rather than to a column, so it stays on screen while the window looks at
2211
+ * another Session or another page.
2212
+ *
2213
+ * The Conversation is rendered by DSH's own `conversation.content` factory
2214
+ * inside this Session's right-sidebar tab body. That body is registered
2215
+ * `keepMounted`, so DSH keeps it — and the Session subtree that owns it —
2216
+ * alive off screen (`SidebarSessionViews.prune` only retires a view without a
2217
+ * retained tab). The body's content node is then moved into this window.
2218
+ */
2219
+ const WINDOW_ATTR = 'data-dsh-conversation-float-window'
2220
+ const WINDOW_BODY_ATTR = 'data-dsh-conversation-float-window-body'
2221
+ const WINDOW_GRIP_ATTR = 'data-dsh-conversation-float-window-grip'
2222
+ const WINDOW_RESIZE_ATTR = 'data-dsh-conversation-float-window-resize'
2223
+ const WINDOW_TITLE_ATTR = 'data-dsh-conversation-float-window-title'
2224
+ const WINDOW_HIDE_PANE_ATTR = 'data-dsh-conversation-float-hide-pane'
2225
+ const WINDOW_KEY = 'dsh-conversation-float.window.'
2226
+ /**
2227
+ * One per-Session content epoch.
2228
+ *
2229
+ * DSH binds a Session's draft writer into a SINGLE slot
2230
+ * (`inputHub.shell(id).bindDraftPersistence`), so whichever Conversation
2231
+ * view mounted last owns typing. The window and the middle column therefore
2232
+ * hand the slot back and forth by remounting, never by fighting for it.
2233
+ */
2234
+ const contentEpochs = new Map()
2235
+ const epochListeners = new Set()
2236
+
2237
+ /** Keep a per-Session record from growing for Sessions nobody opened. */
2238
+ function capSessionMap(map, limit = 64) {
2239
+ while (map.size > limit) {
2240
+ const oldest = map.keys().next()
2241
+ if (oldest.done === true) return
2242
+ map.delete(oldest.value)
2243
+ }
2244
+ }
2245
+
2246
+ function bumpContentEpoch(sessionId) {
2247
+ if (sessionId === null) return
2248
+ contentEpochs.set(sessionId, (contentEpochs.get(sessionId) ?? 0) + 1)
2249
+ capSessionMap(contentEpochs)
2250
+ for (const listener of [...epochListeners]) {
2251
+ try { listener(sessionId) } catch { /* a listener may be unmounting */ }
2252
+ }
2253
+ }
2254
+
2255
+ /** sessionId -> { el, body, title, header, resizer, rect } */
2256
+ const windows = new Map()
2257
+ /**
2258
+ * The band the float windows live in.
2259
+ *
2260
+ * The band has to sit between two things measured in DSH's own stylesheets:
2261
+ *
2262
+ * below the popovers — menus, bubbles and the usage/stat dialogs are
2263
+ * portaled to document.body at z-index 1100, and modals at 1000. A window
2264
+ * above them paints over the panel it just opened, so clicking "model",
2265
+ * "permission" or "usage" looks like nothing happened.
2266
+ *
2267
+ * above the frame — the shell tops out around 71 and the dock kit's own
2268
+ * float layer is 60.
2269
+ */
2270
+ let windowZ = 700
2271
+ const WINDOW_Z_TOP = 900
2272
+
2273
+ function readWindowRect(sessionId) {
2274
+ try {
2275
+ const raw = window.localStorage.getItem(WINDOW_KEY + sessionId)
2276
+ if (raw === null) return null
2277
+ const r = JSON.parse(raw)
2278
+ if (!r || typeof r.x !== 'number' || typeof r.y !== 'number' || typeof r.width !== 'number' || typeof r.height !== 'number') return null
2279
+ return r
2280
+ } catch {
2281
+ return null
2282
+ }
2283
+ }
2284
+
2285
+ function writeWindowRect(sessionId, rect) {
2286
+ try {
2287
+ window.localStorage.setItem(WINDOW_KEY + sessionId, JSON.stringify(rect))
2288
+ } catch {
2289
+ /* a full quota must not break the float */
2290
+ }
2291
+ }
2292
+
2293
+ /**
2294
+ * Keep a window fully on screen.
2295
+ *
2296
+ * The composer is the last row of the Conversation, so a window whose bottom
2297
+ * hangs past the viewport hides exactly the control this float exists to
2298
+ * keep usable. A window taller than the viewport starts at the top instead.
2299
+ */
2300
+ /**
2301
+ * The strip at the top of the window that belongs to DSH, not to the page.
2302
+ *
2303
+ * On Windows the caption is an overlay drawn ON the web content, so a fixed
2304
+ * window whose header slides under it can no longer be grabbed: the window
2305
+ * is stuck. Every window therefore stops at this line, and none may start
2306
+ * above it.
2307
+ */
2308
+ function windowTopInset() {
2309
+ const root = getComputedStyle(document.documentElement)
2310
+ for (const name of ['--dsh-windows-titlebar-height', '--dsh-frame-top-clearance']) {
2311
+ const raw = root.getPropertyValue(name).trim()
2312
+ const px = Number.parseFloat(raw)
2313
+ if (Number.isFinite(px) && px > 0) return Math.round(px)
2314
+ }
2315
+ return 48
2316
+ }
2317
+
2318
+ function clampRect(rect) {
2319
+ const top = windowTopInset()
2320
+ const usable = Math.max(160, window.innerHeight - top)
2321
+ const width = Math.max(320, Math.min(rect.width, window.innerWidth))
2322
+ const height = Math.max(240, Math.min(rect.height, usable))
2323
+ const maxX = Math.max(0, window.innerWidth - width)
2324
+ const maxY = Math.max(top, window.innerHeight - height)
2325
+ const x = Math.max(0, Math.min(rect.x, maxX))
2326
+ const y = Math.max(top, Math.min(rect.y, maxY))
2327
+ return { x: Math.round(x), y: Math.round(y), width: Math.round(width), height: Math.round(height) }
2328
+ }
2329
+
2330
+ /** Re-fit every window after the application window itself changes size. */
2331
+ function reclampWindows() {
2332
+ for (const win of windows.values()) applyWindowRect(win, clampRect(win.rect))
2333
+ }
2334
+
2335
+ function defaultWindowRect() {
2336
+ const top = windowTopInset()
2337
+ const width = Math.min(920, Math.round(window.innerWidth * 0.62))
2338
+ const height = Math.min(720, Math.round((window.innerHeight - top) * 0.86))
2339
+ return clampRect({
2340
+ x: Math.round((window.innerWidth - width) / 2),
2341
+ y: Math.round(top + (window.innerHeight - top - height) / 2),
2342
+ width,
2343
+ height,
2344
+ })
2345
+ }
2346
+
2347
+ function applyWindowRect(win, rect) {
2348
+ win.rect = rect
2349
+ win.el.style.left = rect.x + 'px'
2350
+ win.el.style.top = rect.y + 'px'
2351
+ win.el.style.width = rect.width + 'px'
2352
+ win.el.style.height = rect.height + 'px'
2353
+ }
2354
+
2355
+ /**
2356
+ * Renumber the whole stack, keeping its order.
2357
+ *
2358
+ * The band the windows live in is bounded, so raising one past the ceiling
2359
+ * used to drop it straight onto the floor value: two windows could then
2360
+ * share a level, and "the window on top" would answer with whichever the map
2361
+ * happened to list last.
2362
+ */
2363
+ function restackWindows() {
2364
+ const stack = [...windows.values()].sort((a, b) => {
2365
+ const za = Number.parseFloat(a.el.style.zIndex)
2366
+ const zb = Number.parseFloat(b.el.style.zIndex)
2367
+ return (Number.isFinite(za) ? za : 0) - (Number.isFinite(zb) ? zb : 0)
2368
+ })
2369
+ let z = 700
2370
+ for (const win of stack) {
2371
+ z += 1
2372
+ win.el.style.zIndex = String(z)
2373
+ }
2374
+ windowZ = z
2375
+ }
2376
+
2377
+ function raiseWindow(sessionId) {
2378
+ const win = windows.get(sessionId)
2379
+ if (win === undefined) return
2380
+ if (windowZ >= WINDOW_Z_TOP) restackWindows()
2381
+ windowZ = Math.min(windowZ + 1, WINDOW_Z_TOP)
2382
+ win.el.style.zIndex = String(windowZ)
2383
+ refreshSwitchChips()
2384
+ }
2385
+
2386
+ /**
2387
+ * Offer the switch chip on the window at the top of the stack.
2388
+ *
2389
+ * A float of a Conversation that is not the one on screen is a transcript
2390
+ * and nothing else: it owns neither the header nor the composer, so the way
2391
+ * into it is to make it the current Conversation. That offer belongs to the
2392
+ * window the user just raised — by a press on its taskbar row or by dragging
2393
+ * it up — so it appears on one window, never on the one being read.
2394
+ */
2395
+ function refreshSwitchChips() {
2396
+ const live = liveSession()
2397
+ const top = topWindow()
2398
+ const label = t('switchTo')
2399
+ for (const [id, win] of windows) {
2400
+ const chip = win.switchChip
2401
+ if (chip === undefined) continue
2402
+ const show = id === top && id !== live
2403
+ if (chip.hidden !== !show) chip.hidden = !show
2404
+ if (chip.textContent !== label) chip.textContent = label
2405
+ if (chip.title !== label) chip.title = label
2406
+ }
2407
+ }
2408
+
2409
+ /** The id of the window at the top of the stack that is on screen, if any. */
2410
+ function topWindow() {
2411
+ let top = null
2412
+ let topZ = -Infinity
2413
+ for (const [id, win] of windows) {
2414
+ if (win.el.hidden) continue
2415
+ const z = Number.parseFloat(win.el.style.zIndex)
2416
+ if (!Number.isFinite(z)) continue
2417
+ if (z >= topZ) {
2418
+ topZ = z
2419
+ top = id
2420
+ }
2421
+ }
2422
+ return top
2423
+ }
2424
+
2425
+ function windowButton(label, glyph, onClick) {
2426
+ const button = document.createElement('button')
2427
+ button.type = 'button'
2428
+ button.setAttribute('aria-label', label)
2429
+ button.title = label
2430
+ button.textContent = glyph
2431
+ // 30px is the largest that fits the 34px header, and still far short of
2432
+ // the 44px a fingertip wants: the header would have to grow for that.
2433
+ button.style.cssText = 'width:30px;height:30px;flex:none;display:inline-flex;align-items:center;justify-content:center;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);font:14px/1 system-ui;cursor:pointer'
2434
+ button.addEventListener('pointerdown', (event) => {
2435
+ event.stopPropagation()
2436
+ })
2437
+ button.addEventListener('click', (event) => {
2438
+ event.stopPropagation()
2439
+ onClick()
2440
+ })
2441
+ return button
2442
+ }
2443
+
2444
+ /**
2445
+ * The header chip that makes this window's Conversation the current one.
2446
+ *
2447
+ * It stays hidden until the window is the one on top: every window would
2448
+ * otherwise carry the same offer, and the press would mean "bring this one
2449
+ * forward" on a window the user is not even looking at.
2450
+ */
2451
+ function switchChip(onClick) {
2452
+ const button = document.createElement('button')
2453
+ button.type = 'button'
2454
+ button.setAttribute('data-dsh-conversation-float-switch', '')
2455
+ button.textContent = t('switchTo')
2456
+ button.title = t('switchTo')
2457
+ button.hidden = true
2458
+ button.style.cssText = 'flex:none;height:22px;padding:0 8px;border:0;border-radius:6px;background:var(--dsw-alias-interactive-bg-hover, rgba(0,0,0,.08));color:var(--dsw-alias-label-primary, #111);font:11px/1 ui-sans-serif,system-ui;white-space:nowrap;cursor:pointer'
2459
+ button.addEventListener('pointerdown', (event) => event.stopPropagation())
2460
+ button.addEventListener('click', (event) => {
2461
+ event.stopPropagation()
2462
+ onClick()
2463
+ })
2464
+ return button
2465
+ }
2466
+
2467
+ /**
2468
+ * The Conversation's own page tabs — the ones the header draws.
2469
+ *
2470
+ * They live in the main column's header, which belongs to the Session on
2471
+ * screen. A press on one runs DSH's selectView, so the view ledger, the store
2472
+ * and both columns move together; nothing here re-implements that.
2473
+ */
2474
+ function nativeViewTabs() {
2475
+ return [...document.querySelectorAll('[role="tab"]')].filter((tab) => (
2476
+ tab.closest('[data-dockkit-tab]') === null &&
2477
+ tab.closest(`[${WINDOW_ATTR}]`) === null
2478
+ ))
2479
+ }
2480
+
2481
+ function ensureWindow(sessionId) {
2482
+ const existing = windows.get(sessionId)
2483
+ if (existing !== undefined) return existing
2484
+ const root = document.getElementById('root')
2485
+ if (root === null) return null
2486
+ const el = document.createElement('div')
2487
+ el.setAttribute(WINDOW_ATTR, sessionId)
2488
+ el.setAttribute('role', 'dialog')
2489
+ // Named by its own title, and focusable as a whole: a dialog announced
2490
+ // without a name is just "dialog" to a screen reader.
2491
+ const titleId = 'dsh-float-title-' + sessionId
2492
+ el.setAttribute('aria-labelledby', titleId)
2493
+ el.tabIndex = -1
2494
+ const header = document.createElement('div')
2495
+ header.setAttribute(WINDOW_GRIP_ATTR, '')
2496
+ header.tabIndex = -1
2497
+ const title = document.createElement('span')
2498
+ title.setAttribute(WINDOW_TITLE_ATTR, '')
2499
+ title.id = titleId
2500
+ title.style.cssText = 'flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:600 12px/1.2 ui-sans-serif,system-ui'
2501
+ title.textContent = sessionTitle(sessionId) ?? t('floatTitle')
2502
+ const body = document.createElement('div')
2503
+ body.setAttribute(WINDOW_BODY_ATTR, '')
2504
+ const resizer = document.createElement('div')
2505
+ resizer.setAttribute(WINDOW_RESIZE_ATTR, '')
2506
+ header.appendChild(title)
2507
+ // The title bar carries no page chips: the Conversation's own header,
2508
+ // which travels with the column, is the only copy of that switch.
2509
+ const chip = switchChip(() => switchToWindow(sessionId))
2510
+ header.appendChild(chip)
2511
+ header.appendChild(windowButton(t('minimize'), '—', () => hideWindow(sessionId)))
2512
+ header.appendChild(windowButton(t('close'), '✕', () => closeWindow(sessionId)))
2513
+ el.appendChild(header)
2514
+ el.appendChild(body)
2515
+ el.appendChild(resizer)
2516
+ el.hidden = true
2517
+ root.appendChild(el)
2518
+ const win = {
2519
+ el, body, title, header, resizer, switchChip: chip,
2520
+ rect: readWindowRect(sessionId) ?? defaultWindowRect(),
2521
+ }
2522
+ windows.set(sessionId, win)
2523
+ applyWindowRect(win, clampRect(win.rect))
2524
+ bindWindowDrag(sessionId, win)
2525
+ // The float carries the three drop bands: hold it still, then drag to the
2526
+ // left sidebar (stow), the middle (return) or the right sidebar (dock).
2527
+ win.stopBandDrag = trackPanelDrag(el, sessionId)
2528
+ refreshSwitchChips()
2529
+ // Slot registration must not run inside the commit that mounted the tab
2530
+ // body: a microtask leaves that commit behind without waiting a whole
2531
+ // macrotask for it.
2532
+ queueMicrotask(syncTaskbar)
2533
+ return win
2534
+ }
2535
+
2536
+ function bindWindowDrag(sessionId, win) {
2537
+ let grab = null
2538
+ win.el.addEventListener('pointerdown', () => raiseWindow(sessionId), true)
2539
+ win.header.addEventListener('pointerdown', (event) => {
2540
+ if (event.button !== 0) return
2541
+ grab = { x: event.clientX, y: event.clientY, rect: win.rect }
2542
+ try { win.header.setPointerCapture(event.pointerId) } catch { /* older engines */ }
2543
+ event.preventDefault()
2544
+ })
2545
+ win.header.addEventListener('pointermove', (event) => {
2546
+ if (grab === null) return
2547
+ applyWindowRect(win, clampRect({
2548
+ x: grab.rect.x + (event.clientX - grab.x),
2549
+ y: grab.rect.y + (event.clientY - grab.y),
2550
+ width: grab.rect.width,
2551
+ height: grab.rect.height,
2552
+ }))
2553
+ })
2554
+ const drop = () => {
2555
+ if (grab === null) return
2556
+ grab = null
2557
+ writeWindowRect(sessionId, win.rect)
2558
+ }
2559
+ win.header.addEventListener('pointerup', drop)
2560
+ win.header.addEventListener('pointercancel', drop)
2561
+
2562
+ let sizing = null
2563
+ win.resizer.addEventListener('pointerdown', (event) => {
2564
+ if (event.button !== 0) return
2565
+ sizing = { x: event.clientX, y: event.clientY, rect: win.rect }
2566
+ try { win.resizer.setPointerCapture(event.pointerId) } catch { /* older engines */ }
2567
+ event.preventDefault()
2568
+ event.stopPropagation()
2569
+ })
2570
+ win.resizer.addEventListener('pointermove', (event) => {
2571
+ if (sizing === null) return
2572
+ applyWindowRect(win, clampRect({
2573
+ x: sizing.rect.x,
2574
+ y: sizing.rect.y,
2575
+ width: sizing.rect.width + (event.clientX - sizing.x),
2576
+ height: sizing.rect.height + (event.clientY - sizing.y),
2577
+ }))
2578
+ })
2579
+ const settled = () => {
2580
+ if (sizing === null) return
2581
+ sizing = null
2582
+ writeWindowRect(sessionId, win.rect)
2583
+ }
2584
+ win.resizer.addEventListener('pointerup', settled)
2585
+ win.resizer.addEventListener('pointercancel', settled)
2586
+ }
2587
+
2588
+ /**
2589
+ * Make another Conversation the one on screen.
2590
+ *
2591
+ * DSH's own navigation entry does the switch, so the view ledger, the store
2592
+ * and both columns move together — the same call the sidebar's session rows
2593
+ * make. The window then re-decides its own mode on the next layout pass, and
2594
+ * the real column, header and composer follow it in.
2595
+ */
2596
+ function switchToWindow(sessionId) {
2597
+ let switched = false
2598
+ try {
2599
+ const workspace = typeof ctxRef?.get === 'function' ? ctxRef.get('uiWorkspace') : null
2600
+ if (workspace !== null && workspace !== undefined && typeof workspace.openSession === 'function') {
2601
+ workspace.openSession(sessionId)
2602
+ switched = true
2603
+ }
2604
+ } catch (error) {
2605
+ report('[conversation-float] could not switch the conversation:', error)
2606
+ }
2607
+ if (!switched) {
2608
+ report('[conversation-float] no uiWorkspace service to switch the Session')
2609
+ return
2610
+ }
2611
+ raiseWindow(sessionId)
2612
+ // Bodies re-decide on a slow safety net; a switch must not wait for it.
2613
+ // The column is what changes when the switch lands, so the wait ends on
2614
+ // that change: a pass is taken whenever the column shows a Session it did
2615
+ // not show last, and the wait finishes once it shows ours. Three guessed
2616
+ // delays could all fire before the column moved, or long after.
2617
+ notifyLayout()
2618
+ refreshSwitchChips()
2619
+ let lastSeen = '__start__'
2620
+ untilFrame(() => {
2621
+ const column = findColumn()
2622
+ const shown = column === null ? null : columnSession(column)
2623
+ if (shown !== lastSeen) {
2624
+ lastSeen = shown
2625
+ notifyLayout()
2626
+ refreshSwitchChips()
2627
+ }
2628
+ return shown === sessionId
2629
+ }, null, 2500)
2630
+ }
2631
+
2632
+ function showWindow(sessionId) {
2633
+ const win = ensureWindow(sessionId)
2634
+ if (win === null) return null
2635
+ win.el.hidden = false
2636
+ raiseWindow(sessionId)
2637
+ // Move focus into the window that was just opened, unless the user is
2638
+ // already working inside it: a window that opens without focus leaves a
2639
+ // keyboard user tabbing into a hidden subtree behind it.
2640
+ try {
2641
+ const active = document.activeElement
2642
+ if (active === null || !win.el.contains(active)) win.el.focus({ preventScroll: true })
2643
+ } catch { /* older engines */ }
2644
+ // Typing belongs to the view that just took the screen.
2645
+ bumpContentEpoch(sessionId)
2646
+ return win
2647
+ }
2648
+
2649
+ function hideWindow(sessionId) {
2650
+ const win = windows.get(sessionId)
2651
+ if (win === undefined) return
2652
+ win.el.hidden = true
2653
+ // The window keeps its body mounted while minimised, so the middle
2654
+ // column has to take the draft slot back for its own composer — once the
2655
+ // column is actually back home, not 60ms later.
2656
+ if (liveSession() === sessionId) {
2657
+ untilFrame(() => {
2658
+ const column = findColumn()
2659
+ return column !== null && column.isConnected && column.closest(`[${WINDOW_ATTR}]`) === null
2660
+ }, healComposerSoon, 1200)
2661
+ }
2662
+ refreshSwitchChips()
2663
+ }
2664
+
2665
+ function destroyWindow(sessionId) {
2666
+ const win = windows.get(sessionId)
2667
+ if (win === undefined) return
2668
+ windows.delete(sessionId)
2669
+ // The live column comes home before its host leaves: a node removed with
2670
+ // the window would be a Conversation nobody can find again.
2671
+ if (movedColumn !== null && win.el.contains(movedColumn)) detachColumn()
2672
+ if (typeof win.stopBandDrag === 'function') {
2673
+ try { win.stopBandDrag() } catch { /* listeners already gone */ }
2674
+ win.stopBandDrag = null
2675
+ }
2676
+ win.el.remove()
2677
+ queueMicrotask(syncTaskbar)
2678
+ refreshSwitchChips()
2679
+ }
2680
+
2681
+ /**
2682
+ * The id of OUR tab in one Session, asked of the Session's own tab list.
2683
+ *
2684
+ * Reading it from the markup was how the previous build got it, and that
2685
+ * routine could not tell one Session's tab from another's once the body had
2686
+ * been lifted out of the strip: closing a float then closed the wrong tab.
2687
+ */
2688
+ function tabIdFor(sessionId) {
2689
+ if (sessionId === null) return null
2690
+ try {
2691
+ const tabs = sidebarRight?.tabsIn?.(sessionId) ?? []
2692
+ const mine = tabs.find((tab) => tab && tab.kind === CHAT_KIND)
2693
+ return typeof mine?.id === 'string' ? mine.id : null
2694
+ } catch (error) {
2695
+ report('[conversation-float] could not read this Session tab list:', error)
2696
+ return null
2697
+ }
2698
+ }
2699
+
2700
+ /**
2701
+ * Close a Conversation's float for good.
2702
+ *
2703
+ * The TAB goes first. 'hide' only collapses a docked column, which left the
2704
+ * body mounted with an empty host — the next float opened into that body was
2705
+ * blank. Closing the tab unmounts the body, and the body's own cleanup takes
2706
+ * the window down with it.
2707
+ */
2708
+ function closeWindow(sessionId) {
2709
+ const id = tabIdFor(sessionId)
2710
+ if (id !== null) {
2711
+ try {
2712
+ if (typeof sidebarRight?.closeIn === 'function') sidebarRight.closeIn(sessionId, id)
2713
+ else sidebarRight?.hide?.(id)
2714
+ } catch (error) {
2715
+ report('[conversation-float] could not close the tab:', error)
2716
+ }
2717
+ }
2718
+ // A docked tab DSH refuses to close leaves the body alive: the window must
2719
+ // not outlive it as an orphan pointing at nothing.
2720
+ untilFrame(
2721
+ () => !windows.has(sessionId),
2722
+ () => { if (liveSession() === sessionId) healComposerSoon() },
2723
+ 600,
2724
+ () => {
2725
+ if (windows.has(sessionId)) destroyWindow(sessionId)
2726
+ if (liveSession() === sessionId) healComposerSoon()
2727
+ },
2728
+ )
2729
+ }
2730
+
2731
+ /* ------------------------------------------------------- the taskbar */
2732
+
2733
+ /** sessionId -> disposers for its sidebar row and the panel entry behind it. */
2734
+ const taskRows = new Map()
2735
+
2736
+ /**
2737
+ * The left sidebar is the taskbar: one row per open window, named after its
2738
+ * Conversation. The row is a panel row, so it needs a main-panel entry to
2739
+ * select; that entry shows the window and hands the centre back.
2740
+ */
2741
+ function syncTaskbar() {
2742
+ if (ctxRef === null) return
2743
+ for (const [sessionId] of windows) {
2744
+ if (taskRows.has(sessionId)) continue
2745
+ const rowId = 'conversation-window:' + sessionId
2746
+ const label = sessionTitle(sessionId) ?? t('floatTitle')
1164
2747
  try {
1165
- dockRow = ctxRef.slots.register(
1166
- { name: 'sidebar.panellist', id: DOCK_ROW_ID, order: 20, label: () => t('floatTitle') },
1167
- DockIcon,
2748
+ const disposePanel = ctxRef.slots.register({ name: 'main', key: rowId, locale: NS }, makeWindowPanel(sessionId))
2749
+ const disposeRow = ctxRef.slots.register(
2750
+ { name: 'sidebar.panellist', id: rowId, order: 20, label: () => label },
2751
+ makeDockIcon(sessionId),
1168
2752
  )
2753
+ taskRows.set(sessionId, [disposePanel, disposeRow])
1169
2754
  } catch (error) {
1170
- console.warn('[conversation-float] could not register the sidebar row:', error)
1171
- dockRow = null
2755
+ report('[conversation-float] could not register the taskbar row:', error)
1172
2756
  }
1173
- } else if (!dockedLeft && dockRow !== null) {
1174
- try {
1175
- dockRow()
1176
- } catch {
1177
- /* already disposed with the slot */
2757
+ }
2758
+ for (const [sessionId, disposers] of [...taskRows]) {
2759
+ if (windows.has(sessionId)) continue
2760
+ taskRows.delete(sessionId)
2761
+ for (const off of disposers) {
2762
+ try { off() } catch { /* the slot may be gone */ }
1178
2763
  }
1179
- dockRow = null
1180
2764
  }
1181
2765
  }
1182
2766
 
1183
- let ctxRef = null
2767
+ /**
2768
+ * A taskbar row is DSH's own main-panel button: selecting it replaces the
2769
+ * central entry, which would take a plugin or automation page away. When a
2770
+ * page owns the main slot the row means only "bring that window forward";
2771
+ * the page must stay where it is.
2772
+ */
2773
+ function taskbarRowPress(event) {
2774
+ const target = event.target
2775
+ if (!(target instanceof Element)) return
2776
+ const row = target.closest(`button[${ROW_MARK_ATTR}]`)
2777
+ if (row === null) return
2778
+ const sessionId = row.getAttribute(ROW_MARK_ATTR)
2779
+ if (sessionId === null || sessionId === '') return
2780
+ event.preventDefault()
2781
+ event.stopPropagation()
2782
+ showWindow(sessionId)
2783
+ }
2784
+
2785
+ /** Selecting a taskbar row shows that window and returns the centre. */
2786
+ function makeWindowPanel(sessionId) {
2787
+ return function WindowPanel() {
2788
+ React.useEffect(() => {
2789
+ showWindow(sessionId)
2790
+ try {
2791
+ layout?.selectPanel?.(null)
2792
+ } catch (error) {
2793
+ report('[conversation-float] could not restore the conversation panel:', error)
2794
+ }
2795
+ }, [])
2796
+ return null
2797
+ }
2798
+ }
1184
2799
 
1185
2800
  /* ---------------------------------------------------------- components */
1186
2801
 
@@ -1205,11 +2820,22 @@ window.__ModuleLoader__.load({
1205
2820
  const CSS = `
1206
2821
  .dsw-icon {
1207
2822
  display: inline-flex; align-items: center; justify-content: center;
1208
- width: 26px; height: 26px; padding: 0; border: 0; border-radius: 7px;
2823
+ /* Same box as the header's own ghost buttons: 28x28, 8px corner. */
2824
+ width: 28px; height: 28px; padding: 0; border: 0; border-radius: 8px;
1209
2825
  background: transparent; color: var(--dsw-alias-label-secondary); cursor: pointer;
1210
2826
  transition: background .12s ease, color .12s ease;
1211
2827
  }
1212
- .dsw-icon:hover { background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-primary); }
2828
+ /* Same hover surface as the Conversation header's own ghost buttons — a
2829
+ filled layer that is visible on light backgrounds too. */
2830
+ .dsw-icon:hover { background: var(--dsw-alias-interactive-bg-hover, var(--dsw-alias-bg-layer-2)); color: var(--dsw-alias-label-primary); }
2831
+ /* The menu row used only when the host carries no MenuItemButton primitive. */
2832
+ .dsw-menu-row {
2833
+ display: flex; align-items: center; width: 100%; min-height: 32px;
2834
+ padding: 6px 10px; border: 0; border-radius: 6px; background: transparent;
2835
+ font: inherit; text-align: left; color: var(--dsw-alias-label-primary); cursor: pointer;
2836
+ }
2837
+ .dsw-menu-row:hover { background: var(--dsw-alias-bg-layer-2); }
2838
+ .dsw-menu-row:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: -2px; }
1213
2839
  .dsw-icon:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
1214
2840
  .dsw-host {
1215
2841
  position: relative;
@@ -1217,8 +2843,12 @@ window.__ModuleLoader__.load({
1217
2843
  width: 100%; height: 100%; min-height: 0; overflow: hidden;
1218
2844
  background: var(--dsw-alias-bg-base);
1219
2845
  }
2846
+ /* Fallback only: showPreview() raises this above the windows' own band. */
1220
2847
  .dsw-preview {
1221
- position: fixed; left: 0; top: 0; z-index: 90; pointer-events: none;
2848
+ /* Same band as the windows (700..950). It used to claim 20050 while the code
2849
+ raised it to min(windowZ + 10, 950), so the two disagreed and the value
2850
+ that won depended on whether the inline style had been written yet. */
2851
+ position: fixed; left: 0; top: 0; z-index: 940; pointer-events: none;
1222
2852
  will-change: transform, width, height;
1223
2853
  border: 2px dashed var(--dsw-alias-brand-primary, #4d6bfe);
1224
2854
  border-radius: 12px;
@@ -1227,18 +2857,61 @@ window.__ModuleLoader__.load({
1227
2857
  display: flex; align-items: center; justify-content: center;
1228
2858
  transition: transform .09s ease, width .09s ease, height .09s ease;
1229
2859
  }
1230
- /* The float, stowed in the left drawer: mounted, so the centre stays empty. */
1231
- [data-dsh-conversation-float-stowed] {
1232
- opacity: 0 !important;
1233
- visibility: hidden !important;
1234
- pointer-events: none !important;
1235
- }
1236
2860
  /* Touch: the grip owns the gesture, so a press is not turned into a scroll. */
1237
2861
  [data-dsh-conversation-float-float] [data-dockkit-float-grip] {
1238
2862
  touch-action: none;
1239
2863
  -webkit-user-select: none; user-select: none;
1240
2864
  -webkit-touch-callout: none;
1241
2865
  }
2866
+
2867
+ /* The float window: a layer of our own, drawn above the frame's columns. */
2868
+ [data-dsh-conversation-float-window] {
2869
+ position: fixed; z-index: 700;
2870
+ display: flex; flex-direction: column;
2871
+ min-width: 320px; min-height: 240px;
2872
+ background: var(--dsw-alias-bg-base, #fff);
2873
+ border: 1px solid var(--dsw-alias-border-l3, rgba(0, 0, 0, .14));
2874
+ border-radius: 12px;
2875
+ box-shadow: 0 18px 48px rgba(15, 23, 42, .28);
2876
+ overflow: hidden;
2877
+ }
2878
+ [data-dsh-conversation-float-window][hidden] { display: none; }
2879
+ /* The hold that arms the bands, shown on the grip. */
2880
+ [data-dsh-conversation-float-armed] [data-dsh-conversation-float-window-grip] {
2881
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary, #4d6bfe) 16%, var(--dsw-alias-bg-layer-2, #f5f6f8));
2882
+ }
2883
+ [data-dsh-conversation-float-switch][hidden] { display: none; }
2884
+ [data-dsh-conversation-float-window-grip] {
2885
+ flex: none; display: flex; align-items: center; gap: 4px;
2886
+ height: 34px; padding: 0 6px 0 12px;
2887
+ background: var(--dsw-alias-bg-layer-2, #f5f6f8);
2888
+ border-bottom: 1px solid var(--dsw-alias-border-l4, rgba(0, 0, 0, .08));
2889
+ cursor: grab; user-select: none; touch-action: none;
2890
+ color: var(--dsw-alias-label-primary, #111);
2891
+ }
2892
+ [data-dsh-conversation-float-window-grip]:active { cursor: grabbing; }
2893
+ [data-dsh-conversation-float-window-body] {
2894
+ flex: 1 1 auto; min-height: 0; min-width: 0; display: flex; flex-direction: column;
2895
+ background: var(--dsw-alias-bg-base, #fff); overflow: hidden;
2896
+ }
2897
+ [data-dsh-conversation-float-window-body] > * { flex: 1 1 auto; min-height: 0; min-width: 0; }
2898
+ /* A body that renders its own Conversation is a transcript and nothing else.
2899
+ Exactly one composer exists on screen — the one that travels with the live
2900
+ column, the same way the Conversation header does — so the copies DSH builds
2901
+ for these bodies are taken out. They used to be live input boxes whose draft
2902
+ writer was a second claimant on the Session's single slot. */
2903
+ [data-dsh-conversation-float-factory] [data-composer-seat] { display: none !important; }
2904
+ [data-dsh-conversation-float-factory-live] [data-composer-seat] { display: flex !important; }
2905
+ [data-dsh-conversation-float-factory-live] [data-dsh-conversation-float-anchor] { display: none !important; }
2906
+ [data-dsh-conversation-float-window-resize] {
2907
+ position: absolute; right: 0; bottom: 0; width: 22px; height: 22px;
2908
+ cursor: nwse-resize; touch-action: none;
2909
+ background: linear-gradient(135deg, transparent 50%, var(--dsw-alias-border-l3, rgba(0, 0, 0, .22)) 50%);
2910
+ }
2911
+ [data-dsh-conversation-float-hide-pane] {
2912
+ visibility: hidden !important;
2913
+ pointer-events: none !important;
2914
+ }
1242
2915
  /* Everything the float hides while it is the only thing on screen. */
1243
2916
  [data-dsh-conversation-float-chromeless] {
1244
2917
  display: none !important;
@@ -1261,17 +2934,35 @@ window.__ModuleLoader__.load({
1261
2934
  * rest of DSH back — or hides it again.
1262
2935
  */
1263
2936
  function onEntryClick() {
1264
- // Docked in the right sidebar (or stowed in the drawer) there is no
1265
- // float panel to toggle: the button must bring the float back instead.
1266
- if (dockedLeft || floatPanel() === null) {
2937
+ const sessionId = liveSession()
2938
+ if (sessionId === null) return
2939
+ const win = windows.get(sessionId)
2940
+ if (win === undefined) {
1267
2941
  openFloating()
1268
2942
  return
1269
2943
  }
1270
- if (chromeless) revealChrome()
1271
- else setChromeless(true)
2944
+ // A window put away with its own dash comes back first: hiding the rest
2945
+ // of DSH around a hidden window would leave an empty screen.
2946
+ if (win.el.hidden) {
2947
+ showWindow(sessionId)
2948
+ notifyState()
2949
+ return
2950
+ }
2951
+ // The original design: this press does not collapse the float, it takes
2952
+ // the rest of DSH off the screen and leaves the float alone; the next
2953
+ // press brings the interface back.
2954
+ setChromeless(!chromeless)
2955
+ notifyState()
1272
2956
  }
1273
2957
 
1274
- /** Escape always brings DSH back: the way out of a hidden window. */
2958
+ /**
2959
+ * Escape: bring DSH back when the columns are hidden, close the window when
2960
+ * the hand is inside one.
2961
+ *
2962
+ * Only acts on our own surfaces. Escape is a shared key in DSH (menus,
2963
+ * dialogs, a running answer), and a capture-phase listener that took it
2964
+ * globally would be stealing it from the app.
2965
+ */
1275
2966
  function escapeOnKey(event) {
1276
2967
  if (event.key !== 'Escape' || !chromeless) return
1277
2968
  revealChrome()
@@ -1290,8 +2981,8 @@ window.__ModuleLoader__.load({
1290
2981
  {
1291
2982
  type: 'button',
1292
2983
  className: 'dsw-icon',
1293
- title: chromeless ? t('showDsh') : t('floatTitle'),
1294
- 'aria-label': chromeless ? t('showDsh') : t('floatTitle'),
2984
+ title: entryTitle(),
2985
+ 'aria-label': entryTitle(),
1295
2986
  [ANCHOR_ATTR]: '',
1296
2987
  onClick: onEntryClick,
1297
2988
  },
@@ -1300,45 +2991,310 @@ window.__ModuleLoader__.load({
1300
2991
  )
1301
2992
  }
1302
2993
 
1303
- /** The left sidebar row's glyph. The row itself is owned by the sidebar. */
1304
- function DockIcon({ size = 16 }) {
1305
- return h(Icon, { name: 'window', size })
2994
+ /**
2995
+ * The left sidebar row's glyph. The row itself is owned by the sidebar; we
2996
+ * mark its button so a capture listener can tell our taskbar from a shipped
2997
+ * row, and know which Session's window the row means.
2998
+ */
2999
+ function makeDockIcon(sessionId) {
3000
+ return function DockIcon({ size = 16 }) {
3001
+ const ref = React.useRef(null)
3002
+ React.useLayoutEffect(() => {
3003
+ const icon = ref.current
3004
+ const row = icon === null ? null : icon.closest('button')
3005
+ if (row !== null) row.setAttribute(ROW_MARK_ATTR, sessionId)
3006
+ })
3007
+ return h('span', { ref, style: { display: 'contents' } }, h(Icon, { name: 'window', size }))
3008
+ }
1306
3009
  }
1307
3010
 
1308
3011
  /**
1309
- * The main panel this row addresses. It only exists so a click on the row
1310
- * cannot leave the centre column on an empty page: the click re-opens the
1311
- * float and hands the centre back to the conversation.
3012
+ * The floating tab's body.
3013
+ *
3014
+ * ONE Conversation has ONE view. Its draft writer is a single slot
3015
+ * (`bindDraftPersistence`): the view that mounts last takes the slot, and
3016
+ * when that view unmounts it clears the slot while the first view — still on
3017
+ * screen — can never bind again. The composer then accepts text that never
3018
+ * reaches the store, which is the reported "typing does nothing" bug.
3019
+ *
3020
+ * So this body renders a Conversation of its own only while the live one
3021
+ * belongs to another Session. For its own Session it hosts the LIVE middle
3022
+ * column — the same node the middle column shows — so the composer keeps the
3023
+ * writer it always had.
1312
3024
  */
1313
- function DockPanel() {
1314
- React.useEffect(() => {
1315
- openFloating()
3025
+ function SessionPanel(props) {
3026
+ const host = React.useRef(null)
3027
+ const sessionRef = React.useRef(null)
3028
+ /** Where the live column goes while this body hosts it. */
3029
+ const hostEl = React.useRef(null)
3030
+ /** The dock-kit float pane this body was last seen in. */
3031
+ const paneRef = React.useRef(null)
3032
+ const [portalTarget, setPortalTarget] = React.useState(null)
3033
+ const [epoch, setEpoch] = React.useState(0)
3034
+ /**
3035
+ * 'column' the live middle column lives in this body
3036
+ * 'factory-live' the live Conversation is on a page: a full copy stays
3037
+ * here, with header, View tabs and composer
3038
+ * 'factory' a Conversation of a Session that is not live: record only
3039
+ * null the first layout pass has not decided yet — render
3040
+ * NOTHING, because a factory view that mounts and unmounts
3041
+ * for nothing would clear the draft slot on its way out.
3042
+ */
3043
+ const [mode, setMode] = React.useState(null)
3044
+ /** True while this body sits in a dock-kit float pane and has our window. */
3045
+ const [floating, setFloating] = React.useState(false)
3046
+ const content = React.useMemo(() => {
3047
+ if (typeof props.renderFactorySlot !== 'function') return null
1316
3048
  try {
1317
- layout?.selectPanel?.(null)
3049
+ // 'embedded', not 'main': the embedded variant is the one DSH gives a
3050
+ // Conversation that lives outside the main root. Its stylesheet keys on
3051
+ // [data-content-phase=active] to let the message list grow and pin the
3052
+ // composer to the bottom; as 'main' the list is squashed and the
3053
+ // composer is pushed thousands of pixels out of the window.
3054
+ return props.renderFactorySlot('conversation.content', { variant: 'embedded', phase: 'active', hero: false })
1318
3055
  } catch (error) {
1319
- console.warn('[conversation-float] could not restore the conversation panel:', error)
3056
+ report('[conversation-float] could not render the conversation content:', error)
3057
+ return null
1320
3058
  }
1321
- }, [])
1322
- return null
1323
- }
1324
-
1325
- /** The floating panel's body: it holds the live Conversation column. */
1326
- function SessionPanel() {
1327
- const host = React.useRef(null)
3059
+ }, [props.renderFactorySlot])
1328
3060
  React.useLayoutEffect(() => {
1329
3061
  const container = host.current
1330
3062
  if (container === null) return undefined
1331
- attachColumn(container)
1332
- // Only the floating occurrence is draggable; a tab docked in the right
1333
- // sidebar must not arm the drop bands at all. The panel element mounts
1334
- // after this body does, so the tracker resolves it per pointer sequence.
1335
- const stop = trackPanelDrag(container)
3063
+ const sessionId = container.closest('[data-sidebar-right-session]')?.getAttribute('data-sidebar-right-session') ?? null
3064
+ sessionRef.current = sessionId
3065
+ let disposed = false
3066
+ let seenPane = null
3067
+ const onEpoch = (id) => {
3068
+ if (id === sessionRef.current) setEpoch((value) => value + 1)
3069
+ }
3070
+ epochListeners.add(onEpoch)
3071
+ /**
3072
+ * DSH can move this very body between the float pane and a right-sidebar
3073
+ * page without remounting it, so the host is decided on every pass and
3074
+ * not once at mount.
3075
+ */
3076
+ const decide = () => {
3077
+ if (disposed) return
3078
+ const el = host.current
3079
+ if (el === null) return
3080
+ const pane = el.closest('[' + FLOAT_ATTR + ']')
3081
+ const paneChanged = pane !== seenPane
3082
+ seenPane = pane
3083
+ paneRef.current = pane
3084
+ let win = sessionId === null ? undefined : windows.get(sessionId)
3085
+ if (pane !== null && sessionId !== null) {
3086
+ let created = false
3087
+ if (win === undefined) {
3088
+ try {
3089
+ win = ensureWindow(sessionId)
3090
+ created = win !== undefined
3091
+ } catch (error) {
3092
+ report('[conversation-float] could not lift the conversation into its window:', error)
3093
+ win = undefined
3094
+ }
3095
+ }
3096
+ if (win !== undefined) {
3097
+ pane.setAttribute(WINDOW_HIDE_PANE_ATTR, '')
3098
+ if (created || paneChanged) showWindow(sessionId)
3099
+ }
3100
+ setFloating(win !== undefined)
3101
+ setPortalTarget(win === undefined ? null : win.body)
3102
+ } else {
3103
+ if (win !== undefined) {
3104
+ // The tab left the float for a sidebar page: our window has no
3105
+ // tenant behind it any more, and a stray empty window is worse
3106
+ // than none at all.
3107
+ destroyWindow(sessionId)
3108
+ win = undefined
3109
+ }
3110
+ setFloating(false)
3111
+ setPortalTarget(null)
3112
+ }
3113
+ // A column that belongs to another Conversation must not stay in this
3114
+ // float: switching Sessions would paint the new Conversation inside
3115
+ // it, and the Conversation's own page would then be blank.
3116
+ if (movedColumn !== null && sessionId !== null && win !== undefined && win.body.contains(movedColumn)) {
3117
+ const held = columnSession(movedColumn)
3118
+ if (held !== null && held !== sessionId) {
3119
+ // Only a float left on a LATER page has to put the column back on
3120
+ // the first one; one that was already on the first page must not
3121
+ // make the Session jump for no reason.
3122
+ const tabsBefore = nativeViewTabs()
3123
+ const onFirstPage = tabsBefore[0] === undefined || tabsBefore[0].getAttribute('aria-selected') === 'true'
3124
+ handOffColumn(selectedSession() ?? liveSession())
3125
+ if (!onFirstPage) {
3126
+ // The tab strip re-renders on the commit this pass is inside;
3127
+ // one frame later is the first moment its selection is readable.
3128
+ window.requestAnimationFrame(() => {
3129
+ const first = nativeViewTabs()[0]
3130
+ if (first === undefined) return
3131
+ if (first.getAttribute('aria-selected') === 'true') return
3132
+ try { first.click() } catch { /* the header may be gone */ }
3133
+ })
3134
+ }
3135
+ }
3136
+ }
3137
+ // DSH is mid-render during a Session change and the Session on screen
3138
+ // is momentarily unreadable. Flipping to "not mine" there would mount a
3139
+ // second view of the live Conversation, and a second view takes the
3140
+ // draft writer for good. When the answer is unknown, keep the last one.
3141
+ const live = liveSession()
3142
+ if (live === null) return
3143
+ const mine = live === sessionId
3144
+ const target = pane !== null && win !== undefined ? win.body : el
3145
+ hostEl.current = target
3146
+ // A page that is not a Conversation (plugins, automations, settings)
3147
+ // renders into the very slot the column carries. Hosting the column now
3148
+ // would paint that page inside this window, and the window would follow
3149
+ // the user out of the Conversation — the View tab strip turning into a
3150
+ // plugin page's header and the composer disappearing with it. The page
3151
+ // belongs to the middle column, so the column goes home and this body
3152
+ // shows the transcript of its own Session instead: the same thing a
3153
+ // window of a Session that is not the live one shows.
3154
+ const columnNow = findColumn()
3155
+ const page = mainPanelOpen() && (columnNow === null || columnSession(columnNow) === null)
3156
+ if (page && movedColumn !== null && win !== undefined && win.body.contains(movedColumn)) {
3157
+ try {
3158
+ detachColumn(true)
3159
+ } catch (error) {
3160
+ report('[conversation-float] could not hand the page its column:', error)
3161
+ }
3162
+ }
3163
+ // A floated body always hosts the live column. A docked page hosts it
3164
+ // too when there is a column to host — that is what puts the real
3165
+ // header, and its Conversation/Trajectory tabs, inside the page.
3166
+ // A minimised float KEEPS the column: the point of floating is that the
3167
+ // Conversation leaves DSH, and a hidden window is where it lives while
3168
+ // minimised. Only a body without a column to host renders its own view,
3169
+ // and so does every body while a page outside the Conversation is open.
3170
+ // A page outside the conversation takes the main slot, so the real
3171
+ // column goes home and the page lands in the ordinary frame. The live
3172
+ // Session's window stays on screen and keeps a full Conversation of
3173
+ // its own: header, View tabs and composer, not the read-only record a
3174
+ // window of another Session shows. The page is behind the window.
3175
+ if (page && mine && chromeless) revealChrome()
3176
+ const next = (mine && !page)
3177
+ ? (pane !== null ? 'column' : (findColumn() !== null ? 'column' : 'factory'))
3178
+ : (mine && page ? 'factory-live' : 'factory')
3179
+ setMode((prev) => (prev === next ? prev : next))
3180
+ // Never re-append a column that is already inside: that would re-size
3181
+ // the float under the user's hand.
3182
+ if (next === 'column' && (movedColumn === null || !target.contains(movedColumn))) {
3183
+ // Another float may still be holding it: that float's own pass sees a
3184
+ // foreign column and releases it, so wait for that instead of yanking
3185
+ // the Conversation out from under it.
3186
+ const holder = movedColumn === null ? null : movedColumn.closest(`[${WINDOW_ATTR}]`)
3187
+ const holderId = holder === null ? null : holder.getAttribute(WINDOW_ATTR)
3188
+ if (holderId === null || holderId === sessionId) {
3189
+ try { attachColumn(target) } catch (error) {
3190
+ report('[conversation-float] could not host the live column:', error)
3191
+ }
3192
+ }
3193
+ }
3194
+ }
3195
+ layoutListeners.add(decide)
3196
+ decide()
3197
+ // No clock of its own: this body re-decides when DSH says the Session
3198
+ // changed, when a window opens or closes.
1336
3199
  return () => {
1337
- stop()
1338
- detachColumn()
3200
+ try {
3201
+ disposed = true
3202
+ epochListeners.delete(onEpoch)
3203
+ layoutListeners.delete(decide)
3204
+ const pane = paneRef.current
3205
+ paneRef.current = null
3206
+ if (pane !== null) pane.removeAttribute(WINDOW_HIDE_PANE_ATTR)
3207
+ setPortalTarget(null)
3208
+ const gone = sessionRef.current
3209
+ sessionRef.current = null
3210
+ if (gone !== null) destroyWindow(gone)
3211
+ } catch (error) {
3212
+ report('[conversation-float] window cleanup failed:', error)
3213
+ }
1339
3214
  }
1340
3215
  }, [])
1341
- return h('div', { className: 'dsw-host', ref: host }, h(Styles))
3216
+ // Hosting the live column replaces the factory view: hand it back the
3217
+ // moment this Conversation stops being the one on screen.
3218
+ React.useLayoutEffect(() => {
3219
+ if (mode !== 'column') return undefined
3220
+ const target = hostEl.current
3221
+ if (target === null) return undefined
3222
+ if (movedColumn === null || !target.contains(movedColumn)) attachColumn(target)
3223
+ // The copy that was showing this Conversation until this commit can take
3224
+ // the composer's editor down with it, and the composer that survives is
3225
+ // the one the user is about to type into.
3226
+ healComposerSoon()
3227
+ return () => {
3228
+ // Only take the column home while THIS body still holds it: a page
3229
+ // that has already adopted it must not lose it to a window teardown.
3230
+ if (movedColumn !== null && target.contains(movedColumn)) detachColumn()
3231
+ }
3232
+ }, [mode, portalTarget, floating])
3233
+ const hostProps = { className: 'dsw-host', ref: host, [BODY_ATTR]: '' }
3234
+ let body = null
3235
+ // A body only ever renders a Conversation of its OWN when that
3236
+ // Conversation is not the live one — hosting the live column replaces it.
3237
+ if (mode === 'factory' || mode === 'factory-live') {
3238
+ // Marked, so the stylesheet can take the composer out of this body and
3239
+ // leave the transcript. A factory-live body is the exception: it is the
3240
+ // live Session while a page owns the main slot, so it keeps the header,
3241
+ // the View tabs and the composer instead of degrading to a record.
3242
+ const live = mode === 'factory-live'
3243
+ let header = null
3244
+ if (live && typeof props.renderSlot === 'function') {
3245
+ try {
3246
+ header = props.renderSlot('conversation.session.header', { hideChrome: false })
3247
+ } catch (error) {
3248
+ report('[conversation-float] could not render the live header:', error)
3249
+ }
3250
+ }
3251
+ const shell = h('div', {
3252
+ key: epoch,
3253
+ [FACTORY_ATTR]: '',
3254
+ [FACTORY_LIVE_ATTR]: live ? '' : undefined,
3255
+ style: { display: 'flex', flexDirection: 'column', flex: '1 1 auto', minHeight: 0, minWidth: 0, height: '100%' },
3256
+ }, header, content)
3257
+ body = floating && portalTarget !== null ? ReactDOM.createPortal(shell, portalTarget) : shell
3258
+ }
3259
+ return h('div', hostProps, h(Styles), body)
3260
+ }
3261
+
3262
+ /**
3263
+ * One menu row: the dock kit's own row component when the browser module
3264
+ * table carries it, a plain menu button otherwise. Selecting it closes the
3265
+ * menu first, the way every shipped row does.
3266
+ */
3267
+ function MoveRow({ onDismiss, label, onSelect }) {
3268
+ const select = () => {
3269
+ try {
3270
+ onDismiss?.()
3271
+ } catch {
3272
+ /* the menu may already be gone */
3273
+ }
3274
+ onSelect()
3275
+ }
3276
+ // The shipped rows lead with a 16px glyph; ours keeps the window one so the
3277
+ // row sits on the same grid instead of starting where the icons do.
3278
+ if (MenuItemButton !== null) return h(MenuItemButton, { icon: h(Icon, { name: 'window' }), onSelect: select }, label)
3279
+ return h('button', { type: 'button', role: 'menuitem', className: 'dsw-menu-row', onClick: select }, label)
3280
+ }
3281
+
3282
+ /**
3283
+ * The left sidebar's More menu: put the conversation's window away. The row
3284
+ * that brings it back lives in this same sidebar.
3285
+ */
3286
+ function MoveLeftRow({ onDismiss }) {
3287
+ if (conversationInLeftbar()) return null
3288
+ return h(MoveRow, { onDismiss, label: t('moveLeft'), onSelect: moveConversationLeft })
3289
+ }
3290
+
3291
+ /**
3292
+ * The right sidebar guide's More menu: dock the conversation as a tab there.
3293
+ * It hides itself once the conversation already is one.
3294
+ */
3295
+ function MoveRightRow({ onDismiss }) {
3296
+ if (conversationInRightbar()) return null
3297
+ return h(MoveRow, { onDismiss, label: t('moveRight'), onSelect: moveConversationRight })
1342
3298
  }
1343
3299
 
1344
3300
  /* --------------------------------------------------------------- wiring */
@@ -1347,6 +3303,9 @@ window.__ModuleLoader__.load({
1347
3303
  inject: ['slots', 'locale'],
1348
3304
  apply(ctx) {
1349
3305
  ctxRef = ctx
3306
+ // Build marker: lets a probe tell a re-imported client.js from the copy
3307
+ // the host still holds in memory (a page refresh does NOT reload it).
3308
+ try { window.__dshFloatBuild = 'rowguard-0.2.7' } catch { /* no window yet */ }
1350
3309
  ctx.effect(() => {
1351
3310
  try {
1352
3311
  return ctx.locale.register(NS, Object.fromEntries(LOCALES.map((id) => [id, { title: COPY[id].floatTitle, description: COPY[id].description }])))
@@ -1355,6 +3314,15 @@ window.__ModuleLoader__.load({
1355
3314
  }
1356
3315
  })
1357
3316
 
3317
+ // A language switch happens while the window is open: the entry's own
3318
+ // caption and an outline that is already drawn follow the new table.
3319
+ ctx.effect(() =>
3320
+ ctx.locale.subscribe(() => {
3321
+ notifyState()
3322
+ if (preview !== null && preview.zone !== null) preview.label.textContent = previewLabel(preview.zone, preview.own)
3323
+ }),
3324
+ )
3325
+
1358
3326
  const register = (slot, id, component, options = {}) =>
1359
3327
  ctx.effect(() =>
1360
3328
  ctx.slots.inject(slot, () =>
@@ -1363,22 +3331,27 @@ window.__ModuleLoader__.load({
1363
3331
  )
1364
3332
 
1365
3333
  register('conversation.session.header.utilities', 'conversation-float-control', HeaderAction, { order: 30 })
1366
-
1367
- ctx.effect(() => watchColumn())
3334
+ // The same two destinations a drop offers, as rows in the sidebars' own
3335
+ // More menus — below the shipped rows, which register at the default 0.
3336
+ register('sidebar.panellist.actions', 'conversation-float-stow', MoveLeftRow, { order: 100 })
3337
+ register('sidebar.right.tab.guide.actions', 'conversation-float-move', MoveRightRow, { order: 100 })
1368
3338
 
1369
3339
  ctx.effect(() => {
1370
3340
  window.addEventListener('keydown', escapeOnKey, true)
1371
- return () => window.removeEventListener('keydown', escapeOnKey, true)
1372
- })
1373
-
1374
- // A press or a key is the only evidence that a column moved by the
1375
- // user's hand rather than by DSH re-railing it.
1376
- ctx.effect(() => {
1377
- document.addEventListener('pointerdown', noteGesture, true)
1378
- document.addEventListener('keydown', noteGesture, true)
3341
+ document.addEventListener('click', taskbarRowPress, true)
3342
+ // A hand on the sidebars outranks any retry the plugin started: it
3343
+ // ends the retry instead of being read as a state that disagrees.
3344
+ const onHand = (event) => {
3345
+ const target = event.target
3346
+ if (!(target instanceof Element)) return
3347
+ if (target.closest(`[${FLOAT_ATTR}], [${WINDOW_ATTR}]`) !== null) return
3348
+ if (typeof chromeApplyStop === 'function') chromeApplyStop()
3349
+ }
3350
+ window.addEventListener('pointerdown', onHand, true)
1379
3351
  return () => {
1380
- document.removeEventListener('pointerdown', noteGesture, true)
1381
- document.removeEventListener('keydown', noteGesture, true)
3352
+ window.removeEventListener('keydown', escapeOnKey, true)
3353
+ document.removeEventListener('click', taskbarRowPress, true)
3354
+ window.removeEventListener('pointerdown', onHand, true)
1382
3355
  }
1383
3356
  })
1384
3357
 
@@ -1403,12 +3376,6 @@ window.__ModuleLoader__.load({
1403
3376
  setChromeless(false)
1404
3377
 
1405
3378
 
1406
- ctx.effect(() =>
1407
- ctx.slots.inject('main', () =>
1408
- ctx.slots.register({ name: 'main', key: DOCK_ROW_ID, locale: NS }, DockPanel),
1409
- ),
1410
- )
1411
-
1412
3379
  ctx.effect(() => {
1413
3380
  const dispose = ctx.inject(['layout'], (sub) => {
1414
3381
  layout = sub.layout ?? null
@@ -1419,28 +3386,74 @@ window.__ModuleLoader__.load({
1419
3386
  return dispose
1420
3387
  })
1421
3388
 
3389
+ // The Session list drives every re-decide: it supplies the titles the
3390
+ // sidebars and windows show, and a change to it means the layout moved.
3391
+ ctx.effect(() => {
3392
+ const dispose = ctx.inject(['sessions'], (sub) => {
3393
+ sessions = sub.sessions ?? null
3394
+ let off = null
3395
+ try {
3396
+ if (typeof sessions?.list?.subscribe === 'function') {
3397
+ off = sessions.list.subscribe(() => {
3398
+ notifyLayout()
3399
+ })
3400
+ }
3401
+ } catch (error) {
3402
+ report('[conversation-float] could not follow the Session list:', error)
3403
+ }
3404
+ return () => {
3405
+ try {
3406
+ off?.()
3407
+ } catch {
3408
+ /* the projection is already gone */
3409
+ }
3410
+ sessions = null
3411
+ }
3412
+ })
3413
+ return dispose
3414
+ })
3415
+
1422
3416
  ctx.effect(() =>
1423
3417
  ctx.inject(['sidebarRightTabs', 'sidebarRight'], (sub) => {
1424
3418
  sidebarRight = sub.sidebarRight ?? null
3419
+ // Each registration is fenced on its own: one refused registration
3420
+ // used to take the tab TYPE down with it, and a float that cannot
3421
+ // claim its tab cannot open at all.
3422
+ sub.effect(() => {
3423
+ try {
3424
+ return sub.sidebarRightTabs.register({
3425
+ id: CHAT_ID,
3426
+ kind: CHAT_KIND,
3427
+ title: () => t('conversation'),
3428
+ keepMounted: true,
3429
+ })
3430
+ } catch (error) {
3431
+ window.__dshFloatError = 'tab-type: ' + String(error && (error.stack || error))
3432
+ report('[conversation-float] tab type refused:', error)
3433
+ return () => {}
3434
+ }
3435
+ })
1425
3436
  sub.effect(() =>
1426
- sub.sidebarRightTabs.register({
1427
- id: CHAT_ID,
1428
- kind: CHAT_KIND,
1429
- title: () => t('conversation'),
3437
+ sub.slots.inject('sidebar.right.pane.tab', () => {
3438
+ try {
3439
+ return sub.slots.register({ name: 'sidebar.right.pane.tab', key: CHAT_ID, locale: NS, children: { 'conversation.session.header': { kind: 'single', scope: 'session' } } }, SessionPanel)
3440
+ } catch (error) {
3441
+ // A host that will not let this body own the header slot
3442
+ // still gets the body, with content and composer only.
3443
+ report('[conversation-float] header-capable body refused, retrying:', error)
3444
+ try {
3445
+ return sub.slots.register({ name: 'sidebar.right.pane.tab', key: CHAT_ID, locale: NS }, SessionPanel)
3446
+ } catch (fallbackError) {
3447
+ window.__dshFloatError = 'body: ' + String(fallbackError && (fallbackError.stack || fallbackError))
3448
+ report('[conversation-float] tab body refused:', fallbackError)
3449
+ return () => {}
3450
+ }
3451
+ }
1430
3452
  }),
1431
3453
  )
1432
- sub.effect(() =>
1433
- sub.slots.inject('sidebar.right.pane.tab', () =>
1434
- sub.slots.register({ name: 'sidebar.right.pane.tab', key: CHAT_ID, locale: NS }, SessionPanel),
1435
- ),
1436
- )
1437
3454
  return () => {
1438
3455
  sidebarRight = null
1439
3456
  hidePreview()
1440
- if (dockedLeft) {
1441
- dockedLeft = false
1442
- syncDockRow()
1443
- }
1444
3457
  detachColumn()
1445
3458
  }
1446
3459
  }),
@@ -1450,16 +3463,141 @@ window.__ModuleLoader__.load({
1450
3463
  open: openFloating,
1451
3464
  findColumn,
1452
3465
  bands,
3466
+ /** Test harness: the same moves the drag bands and the menus make. */
3467
+ moveRight: () => drop('right'),
3468
+ moveCentre: () => drop('centre'),
3469
+ /** Test harness: the same switch the window's own chip makes. */
3470
+ switchTo: (id) => switchToWindow(id),
3471
+ /**
3472
+ * Probe: what the plugin believes about the Conversation column. The
3473
+ * breaks this repairs — a column parked in a page the window has left,
3474
+ * a recorded node DSH already took away — are invisible from outside,
3475
+ * so they can only be read from here.
3476
+ */
3477
+ diag() {
3478
+ const column = movedColumn
3479
+ const page = column === null ? null : column.closest('[data-sidebar-right-session]')
3480
+ const scanned = scanColumn()
3481
+ return {
3482
+ build: window.__dshFloatBuild ?? null,
3483
+ followingSession: followingSelection,
3484
+ live: liveSession(),
3485
+ selected: selectedSession(),
3486
+ moved: column === null ? null : {
3487
+ connected: column.isConnected,
3488
+ session: columnSession(column),
3489
+ host: column.closest(`[${WINDOW_ATTR}]`) !== null ? 'window'
3490
+ : column.closest(`[${FLOAT_ATTR}]`) !== null ? 'float'
3491
+ : page !== null ? 'docked' : 'frame',
3492
+ page: page === null ? null : page.getAttribute('data-sidebar-right-session'),
3493
+ pageVisible: page === null ? null : panelVisible(page),
3494
+ },
3495
+ scanned: scanned === null ? null : columnSession(scanned),
3496
+ columns: document.querySelectorAll('[data-conversation-session]').length,
3497
+ windows: windows.size,
3498
+ compat: compatReport(),
3499
+ lastError: window.__dshFloatLastError ?? null,
3500
+ waits: pendingWaits.size,
3501
+ }
3502
+ },
3503
+ /** Test harness: which window carries the switch chip, and what the
3504
+ * drop outline currently says. */
3505
+ get chips() {
3506
+ const out = {}
3507
+ for (const [id, win] of windows) out[id] = win.switchChip === undefined ? null : !win.switchChip.hidden && win.switchChip.textContent
3508
+ return { top: topWindow(), live: liveSession(), shown: out }
3509
+ },
3510
+ get preview() {
3511
+ return preview === null || preview.zone === null
3512
+ ? null
3513
+ : { zone: preview.zone, own: preview.own, label: preview.label.textContent }
3514
+ },
1453
3515
  get moved() {
1454
3516
  return movedColumn !== null
1455
3517
  },
1456
- get dockedLeft() {
1457
- return dockedLeft
3518
+ /** What the sidebars restore is working from, for the test harness. */
3519
+ get chrome() {
3520
+ return { saved: savedChrome, chromeless, retrying: typeof chromeApplyStop === 'function' }
1458
3521
  },
1459
3522
  }
3523
+ // The probe is READ-ONLY unless a page asked for the harness. The
3524
+ // mutating entries below move a Session on any script's say-so, which
3525
+ // is a test surface, not an API, and shipped builds should not hand it
3526
+ // to whatever else happens to run on this origin.
3527
+ if (!floatDebugEnabled()) {
3528
+ for (const key of ['open', 'moveRight', 'moveCentre', 'switchTo']) {
3529
+ delete window.__dshSessionWindow[key]
3530
+ }
3531
+ }
3532
+ ctx.effect(() => {
3533
+ window.addEventListener('resize', reclampWindows)
3534
+ return () => window.removeEventListener('resize', reclampWindows)
3535
+ })
3536
+
3537
+ // The Session on screen is DSH's own state, and DSH publishes it: one
3538
+ // store, written by every navigation. Listening to it replaces the polls
3539
+ // that used to stand in for it — a Session switch is a layout pass now,
3540
+ // not a wait for the next tick.
3541
+ ctx.effect(() => {
3542
+ followSelection()
3543
+ return () => {}
3544
+ })
3545
+
3546
+ // Leaving the Conversation for a page outside it (plugins, automations,
3547
+ // settings) swaps the main slot's children and tells no service: the
3548
+ // Session is still "selected", so neither the workspace store nor the
3549
+ // Session list moves. Watch the slot itself, so a window stops following
3550
+ // the user out of the Conversation in the same turn it happens instead
3551
+ // of whenever something else happens to fire.
3552
+ ctx.effect(() => {
3553
+ const inMain = (node) => node instanceof Element
3554
+ && (node.hasAttribute('data-slot')
3555
+ || node.closest('[data-slot="main"]') !== null
3556
+ || node.querySelector('[data-slot="main"]') !== null)
3557
+ const carries = (node) => node instanceof Element
3558
+ && (node.hasAttribute('data-conversation-session')
3559
+ || node.querySelector('[data-conversation-session]') !== null
3560
+ || inMain(node))
3561
+ // Reading the main slot's own shape is what keeps this cheap: a
3562
+ // streaming answer mutates the transcript hundreds of times a second,
3563
+ // and a layout pass per token would cost more than it ever buys. Only
3564
+ // a change to WHAT the slot carries — or to whether a Conversation is
3565
+ // drawn at all — counts, and one pass per 200ms at most.
3566
+ const shape = () => {
3567
+ const slot = document.querySelector('[data-slot="main"]')
3568
+ const kinds = slot === null ? '' : [...slot.children].map((child) => child.getAttribute('data-slot') ?? child.tagName).join(',')
3569
+ return kinds + '|' + (document.querySelector('[data-conversation-session]') === null ? 'none' : 'conversation')
3570
+ }
3571
+ let seen = shape()
3572
+ let lastKick = 0
3573
+ const observer = new MutationObserver((records) => {
3574
+ let interesting = false
3575
+ for (const record of records) {
3576
+ if (record.type !== 'childList') continue
3577
+ if (inMain(record.target)) { interesting = true; break }
3578
+ for (const node of record.addedNodes) if (carries(node)) { interesting = true; break }
3579
+ if (interesting) break
3580
+ for (const node of record.removedNodes) if (carries(node)) { interesting = true; break }
3581
+ if (interesting) break
3582
+ }
3583
+ if (!interesting) return
3584
+ const now = Date.now()
3585
+ if (now - lastKick < 200) return
3586
+ const next = shape()
3587
+ if (next === seen) return
3588
+ seen = next
3589
+ lastKick = now
3590
+ kickLayout(1)
3591
+ })
3592
+ observer.observe(document.body, { childList: true, subtree: true })
3593
+ return () => observer.disconnect()
3594
+ })
3595
+
1460
3596
  ctx.effect(() => () => {
3597
+ // Nothing this instance scheduled may outlive it: every wait is a
3598
+ // frame loop, and a frame loop left running holds a dead closure.
3599
+ cancelWaits()
1461
3600
  hidePreview()
1462
- unstowFloat()
1463
3601
  // Unloading is not a user close: leave the sidebars alone.
1464
3602
  suspendRestore = true
1465
3603
  detachColumn()