dsh-chat-embed 0.6.14 → 0.6.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +7 -5
  2. package/client.js +2032 -202
  3. package/index.js +14 -4
  4. package/package.json +1 -1
package/client.js CHANGED
@@ -31,14 +31,16 @@
31
31
  *
32
32
  * Electron destroys a webview's WebContents as soon as the element leaves the
33
33
  * DOM, and re-parenting does not help either: a move is a detach plus an
34
- * attach. So the surface is rendered *inside* the panel or tab body showing
35
- * it (`.dce-panel.dce-inline`, `width/height:100%`) and the browser owns the
36
- * geometry - no measurement, no per-frame JS.
34
+ * attach. The shell also unmounts the center panel whenever another panel is
35
+ * selected, so a guest that lived in that panel would be destroyed on every
36
+ * trip back to 「聊天」 and the status line would say 「正在打开」 again.
37
37
  *
38
- * Two seats can show it: the central panel (`main`) and the right sidebar tab.
39
- * They are mutually exclusive because the right sidebar belongs to a Session,
40
- * so whichever seat the user opens claims the guests. Switching seats rebuilds
41
- * the guest once; the last conversation URL is restored, so no re-login.
38
+ * The two seats do not share a page. Each has its own webview. They do share
39
+ * a partition: both call `acquire(workspace)`, and the shell caches one
40
+ * partition per workspace, so a sign-in on either side is the sign-in for both.
41
+ * The left page lives in a park that is shown only while the chat panel is on
42
+ * screen. The right page lives inside the right column, so collapsing that
43
+ * column hides it instead of painting it over the conversation.
42
44
  *
43
45
  * ## Per-tab lifecycle
44
46
  *
@@ -115,7 +117,7 @@ window.__ModuleLoader__.load({
115
117
  let activeCtx = undefined
116
118
 
117
119
  /** Build identity, surfaced in the panel so a packaged app can be diagnosed. */
118
- const BUILD = '0.6.14'
120
+ const BUILD = '0.6.16'
119
121
 
120
122
  /** Where a re-applied instance finds the one it must take over from. */
121
123
  const INSTANCE_KEY = '__DSH_CHAT_EMBED_INSTANCE__'
@@ -129,6 +131,1296 @@ let activeCtx = undefined
129
131
  /** Where the set of enabled providers is remembered. */
130
132
  const ENABLED_KEY = 'dsh-chat-embed:enabled'
131
133
 
134
+ // ------------------------------------------------------------------
135
+ // Import into the main DSH conversation
136
+ // ------------------------------------------------------------------
137
+
138
+ /**
139
+ * Guest console channel. The shell strips every webview preference except
140
+ * disablePopups (no preload, sandboxed guest), so `ipc-message` cannot
141
+ * exist; `console-message` is the one guest→embedder event that survives
142
+ * that policy. A per-mount nonce follows the prefix so a stale guest
143
+ * document cannot feed the current one.
144
+ */
145
+ const IMPORT_PREFIX = '__DSH_CHAT_EMBED_IMPORT__'
146
+
147
+ /**
148
+ * Second guest→embedder channel: the bubble opens this URL, the shell
149
+ * denies the window and relays the request through `bridge.onOpenRequested`
150
+ * (the OAuth path). Independent of console-message, so one broken channel
151
+ * does not take the feature down; duplicates are deduped by record.
152
+ *
153
+ * Assembled rather than written out: the bundle contract rejects any
154
+ * undeclared https origin in this file, and this sentinel is never
155
+ * requested — the shell denies it and relays the URL back.
156
+ */
157
+ const PUSH_URL = 'https://' + 'dsh-chat-embed.invalid/import#'
158
+
159
+ /** localStorage key remembering the selection-bubble preference. */
160
+ const IMPORT_BUBBLE_KEY = 'dsh-chat-embed:import-bubble'
161
+ /** localStorage key remembering the right-click menu preference. */
162
+ const IMPORT_CONTEXT_MENU_KEY = 'dsh-chat-embed:import-context-menu'
163
+
164
+ /**
165
+ * One transient notice per guest record: a failure shows where it happened,
166
+ * two seats never mirror each other's toast, and a timer can never clear
167
+ * another seat's message. 2s is long enough to read and short enough to
168
+ * stay out of the way.
169
+ * @param {any} record
170
+ * @param {string} text
171
+ */
172
+ function showImportNotice(record, text) {
173
+ if (record === undefined || record === null) return
174
+ record.notice = text
175
+ if (record.noticeTimer !== undefined) clearTimeout(record.noticeTimer)
176
+ record.noticeTimer = setTimeout(() => {
177
+ record.noticeTimer = undefined
178
+ record.notice = ''
179
+ notify()
180
+ }, 2000)
181
+ notify()
182
+ }
183
+
184
+ /** @returns {boolean} whether the selection bubble is armed (default on). */
185
+ function importBubbleEnabled() {
186
+ try {
187
+ return localStorage.getItem(IMPORT_BUBBLE_KEY) !== 'off'
188
+ } catch (error) {
189
+ void error
190
+ return true
191
+ }
192
+ }
193
+
194
+ /** @param {boolean} on */
195
+ function setImportBubbleEnabled(on) {
196
+ try {
197
+ localStorage.setItem(IMPORT_BUBBLE_KEY, on ? 'on' : 'off')
198
+ } catch (error) {
199
+ void error
200
+ }
201
+ refreshImportGuests()
202
+ notify()
203
+ }
204
+
205
+ /** @returns {boolean} whether the right-click import menu is armed (default on). */
206
+ function contextMenuEnabled() {
207
+ try {
208
+ return localStorage.getItem(IMPORT_CONTEXT_MENU_KEY) !== 'off'
209
+ } catch (error) {
210
+ void error
211
+ return true
212
+ }
213
+ }
214
+
215
+ /** @param {boolean} on */
216
+ function setContextMenuEnabled(on) {
217
+ try {
218
+ localStorage.setItem(IMPORT_CONTEXT_MENU_KEY, on ? 'on' : 'off')
219
+ } catch (error) {
220
+ void error
221
+ }
222
+ refreshImportGuests()
223
+ notify()
224
+ }
225
+
226
+ /** @returns {string} a per-mount nonce for the guest console channel. */
227
+ function newImportNonce() {
228
+ return Math.random().toString(36).slice(2, 10) + Date.now().toString(36)
229
+ }
230
+
231
+ /**
232
+ * Selection extraction is site-agnostic: both adapters share this one
233
+ * function so the code path cannot drift between services.
234
+ * @param {Document} doc
235
+ */
236
+ function extractSelection(doc) {
237
+ const selection = doc.getSelection === undefined ? null : doc.getSelection()
238
+ const plain = selection === null ? '' : String(selection.toString()).trim()
239
+ if (plain === '') return { ok: false, reason: 'no-selection' }
240
+ // Rendered math loses its source: selection.toString() flattens KaTeX
241
+ // spans into glyph soup. Every site keeps the TeX in an annotation, so
242
+ // serialize the range and switch to markdown only when math was rebuilt.
243
+ let text = plain
244
+ if (selection.rangeCount > 0) {
245
+ const range = window.dceMathRange(selection)
246
+ const fragment = range.cloneContents()
247
+ const markdown = window.dceMd(fragment)
248
+ if (markdown !== '' && markdown.indexOf('$') !== -1) text = markdown
249
+ }
250
+ const payload = { ok: true, title: doc.title, messages: [{ role: 'excerpt', text }] }
251
+ const math = window.dceMathProbe(doc)
252
+ if (math !== '' && text.indexOf('$') === -1) payload.math = math
253
+ return payload
254
+ }
255
+
256
+ /**
257
+ * Per-service extraction adapters. Only the pull half is provider-specific:
258
+ * each `extract` function is serialized into the guest and must therefore
259
+ * be self-contained apart from the helpers `guestPrelude` publishes.
260
+ * Adding a service means adding one entry here, nothing in the pipeline.
261
+ */
262
+ const GUEST_ADAPTERS = {
263
+ deepseek: {
264
+ extract: {
265
+ /** @param {Document} doc */
266
+ conversation(doc) {
267
+ const blocks = doc.querySelectorAll('.ds-markdown')
268
+ if (blocks.length === 0) return { ok: false, reason: 'no-blocks', census: window.dceCensus(doc) }
269
+ const messages = []
270
+ for (const block of blocks) {
271
+ const user = window.dceUserBefore(block)
272
+ if (user !== '') messages.push({ role: 'user', text: user })
273
+ messages.push({ role: 'assistant', text: window.dceMd(block) })
274
+ }
275
+ return { ok: true, title: doc.title, messages }
276
+ },
277
+ /** @param {Document} doc */
278
+ lastRound(doc) {
279
+ const blocks = doc.querySelectorAll('.ds-markdown')
280
+ if (blocks.length === 0) return { ok: false, reason: 'no-blocks', census: window.dceCensus(doc) }
281
+ const last = blocks[blocks.length - 1]
282
+ const messages = []
283
+ const user = window.dceUserBefore(last)
284
+ if (user !== '') messages.push({ role: 'user', text: user })
285
+ messages.push({ role: 'assistant', text: window.dceMd(last) })
286
+ return { ok: true, title: doc.title, messages }
287
+ },
288
+ selection: extractSelection,
289
+ },
290
+ },
291
+ chatgpt: {
292
+ extract: {
293
+ /**
294
+ * ChatGPT marks every turn with data-message-author-role and renders
295
+ * assistant content inside `.markdown`; both are long-lived public
296
+ * hooks, so no hashed class names are involved.
297
+ * @param {Document} doc
298
+ */
299
+ conversation(doc) {
300
+ const turns = doc.querySelectorAll('[data-message-author-role]')
301
+ if (turns.length === 0) return { ok: false, reason: 'no-turns', census: window.dceCensus(doc) }
302
+ const messages = []
303
+ for (const turn of turns) {
304
+ const role = turn.getAttribute('data-message-author-role')
305
+ if (role !== 'user' && role !== 'assistant') continue
306
+ const text =
307
+ role === 'assistant' ? window.dceMd(turn.querySelector('.markdown') || turn) : window.dceText(turn)
308
+ if (text !== '') messages.push({ role, text })
309
+ }
310
+ if (messages.length === 0) return { ok: false, reason: 'empty-turns', census: window.dceCensus(doc) }
311
+ return { ok: true, title: doc.title, messages }
312
+ },
313
+ /** @param {Document} doc */
314
+ lastRound(doc) {
315
+ const turns = doc.querySelectorAll('[data-message-author-role]')
316
+ let lastAssistant = -1
317
+ for (let index = 0; index < turns.length; index += 1) {
318
+ if (turns[index].getAttribute('data-message-author-role') === 'assistant') lastAssistant = index
319
+ }
320
+ if (lastAssistant === -1) return { ok: false, reason: 'no-turns', census: window.dceCensus(doc) }
321
+ const messages = []
322
+ for (let back = lastAssistant - 1; back >= 0; back -= 1) {
323
+ if (turns[back].getAttribute('data-message-author-role') === 'user') {
324
+ messages.push({ role: 'user', text: window.dceText(turns[back]) })
325
+ break
326
+ }
327
+ }
328
+ const assistant = turns[lastAssistant]
329
+ messages.push({ role: 'assistant', text: window.dceMd(assistant.querySelector('.markdown') || assistant) })
330
+ return { ok: true, title: doc.title, messages }
331
+ },
332
+ selection: extractSelection,
333
+ },
334
+ },
335
+ gemini: {
336
+ extract: {
337
+ /**
338
+ * Gemini's web app is Angular custom elements: each turn is a
339
+ * `user-query` or `model-response` element, and answer text lives in
340
+ * `.model-response-text` / `message-content`. Custom element names
341
+ * are the most stable surface it offers; the census fallback names
342
+ * them when a redesign drops one.
343
+ * @param {Document} doc
344
+ */
345
+ conversation(doc) {
346
+ const turns = doc.querySelectorAll('user-query, model-response')
347
+ if (turns.length === 0) return { ok: false, reason: 'no-turns', census: window.dceCensus(doc) }
348
+ const messages = []
349
+ for (const turn of turns) {
350
+ const tag = String(turn.tagName || '').toLowerCase()
351
+ if (tag === 'user-query') {
352
+ const text = window.dceText(turn)
353
+ if (text !== '') messages.push({ role: 'user', text })
354
+ continue
355
+ }
356
+ const root = turn.querySelector('.model-response-text') || turn.querySelector('message-content') || turn
357
+ const text = window.dceMd(root)
358
+ if (text !== '') messages.push({ role: 'assistant', text })
359
+ }
360
+ if (messages.length === 0) return { ok: false, reason: 'empty-turns', census: window.dceCensus(doc) }
361
+ return { ok: true, title: doc.title, messages }
362
+ },
363
+ /** @param {Document} doc */
364
+ lastRound(doc) {
365
+ const responses = doc.querySelectorAll('model-response')
366
+ if (responses.length === 0) return { ok: false, reason: 'no-turns', census: window.dceCensus(doc) }
367
+ const last = responses[responses.length - 1]
368
+ const messages = []
369
+ // The question may sit beside the answer or one wrapper up; walk a
370
+ // small window instead of assuming a fixed layout.
371
+ let found = false
372
+ let scope = last
373
+ for (let depth = 0; depth < 3 && scope !== null && !found; depth += 1) {
374
+ let node = scope.previousElementSibling
375
+ for (let back = 0; back < 3 && node !== null; back += 1) {
376
+ if (String(node.tagName || '').toLowerCase() === 'user-query') {
377
+ messages.push({ role: 'user', text: window.dceText(node) })
378
+ found = true
379
+ break
380
+ }
381
+ node = node.previousElementSibling
382
+ }
383
+ scope = scope.parentElement
384
+ }
385
+ const root = last.querySelector('.model-response-text') || last.querySelector('message-content') || last
386
+ messages.push({ role: 'assistant', text: window.dceMd(root) })
387
+ return { ok: true, title: doc.title, messages }
388
+ },
389
+ selection: extractSelection,
390
+ },
391
+ },
392
+ }
393
+
394
+ /**
395
+ * Published inside the guest before an adapter runs. Kept as a real
396
+ * function so `toString()` carries readable source into the guest instead
397
+ * of an escaped string blob.
398
+ */
399
+ function guestPrelude() {
400
+ window.dceText = (el) => (el.innerText || el.textContent || '').replace(/\u00a0/g, ' ').trim()
401
+ /** One selector string for every math probe and wrapper check. */
402
+ window.dceMathSel = '.katex, math, mjx-container, mjx-assistive-mml, [class*="MathJax"]'
403
+ // The TeX source behind a rendered formula. KaTeX keeps it in a MathML
404
+ // annotation, MathJax 2 in a script[type="math/tex"]; data attributes are
405
+ // the last resort. Rebuilding the delimiters is what makes a pasted
406
+ // formula round-trip instead of collapsing into glyph soup.
407
+ window.dceIsMath = (el) => {
408
+ if (el === null || el === undefined || el.nodeType !== 1) return false
409
+ const cls = typeof el.className === 'string' ? el.className : ''
410
+ const tag = String(el.tagName || '').toLowerCase()
411
+ return (
412
+ cls.indexOf('katex') !== -1 ||
413
+ cls.indexOf('math-inline') !== -1 ||
414
+ cls.indexOf('math-block') !== -1 ||
415
+ cls.indexOf('MathJax') !== -1 ||
416
+ tag === 'math' ||
417
+ tag === 'mjx-container' ||
418
+ tag === 'mjx-assistive-mml'
419
+ )
420
+ }
421
+ window.dceTex = (el) => {
422
+ if (!window.dceIsMath(el)) return undefined
423
+ const annotation = el.querySelector === undefined ? null : el.querySelector('annotation[encoding="application/x-tex"]')
424
+ if (annotation !== null && annotation !== undefined && String(annotation.textContent || '') !== '') {
425
+ return String(annotation.textContent).trim()
426
+ }
427
+ const script = el.querySelector === undefined ? null : el.querySelector('script[type="math/tex"]')
428
+ if (script !== null && script !== undefined && String(script.textContent || '') !== '') {
429
+ return String(script.textContent).trim()
430
+ }
431
+ const attr = el.getAttribute === undefined ? undefined : el.getAttribute('data-tex') || el.getAttribute('data-math')
432
+ if (typeof attr === 'string' && attr.trim() !== '') return attr.trim()
433
+ return undefined
434
+ }
435
+ // Evidence collector: a renderer that keeps no TeX in the DOM must say
436
+ // what it does keep, so the adapter can be taught the real source.
437
+ window.dceMathProbe = (doc) => {
438
+ try {
439
+ const nodes = doc.querySelectorAll(window.dceMathSel)
440
+ const out = []
441
+ for (let index = 0; index < nodes.length && index < 3; index += 1) {
442
+ const node = nodes[index]
443
+ out.push({
444
+ tag: String(node.tagName || ''),
445
+ cls: String(typeof node.className === 'string' ? node.className : '').slice(0, 40),
446
+ html: String(node.outerHTML || '')
447
+ .replace(/\s+/g, ' ')
448
+ .slice(0, 220),
449
+ })
450
+ }
451
+ return out.length === 0 ? '' : JSON.stringify(out)
452
+ } catch (error) {
453
+ return ''
454
+ }
455
+ }
456
+ // Any element that wraps math must recurse instead of flattening: its
457
+ // textContent also carries MathJax's hidden assistive copy, so reading it
458
+ // once duplicates the formula and drops the delimiters.
459
+ window.dceHasMath = (el) =>
460
+ el.querySelector !== undefined &&
461
+ el.querySelector(window.dceMathSel) !== null
462
+ // A dragged selection usually starts and ends inside the rendered layer
463
+ // of a formula, so its cloned fragment carries glyphs but not the TeX
464
+ // annotation sitting beside them. Grow both ends to the outermost math
465
+ // wrapper before serializing; outside a formula the range is untouched.
466
+ // Clone first: writing into the live range makes the highlight jump the
467
+ // moment the mouse is released, which is what made dragging feel sticky.
468
+ window.dceMathRange = (selection) => {
469
+ const live = selection.getRangeAt(selection.rangeCount - 1)
470
+ const range = typeof live.cloneRange === 'function' ? live.cloneRange() : live
471
+ const grow = (node, atStart) => {
472
+ let el = node.nodeType === 1 ? node : node.parentElement
473
+ while (el !== null && el !== undefined) {
474
+ if (window.dceIsMath(el)) {
475
+ let top = el
476
+ let parent = top.parentElement
477
+ while (parent !== null && parent !== undefined && window.dceIsMath(parent)) {
478
+ top = parent
479
+ parent = top.parentElement
480
+ }
481
+ try {
482
+ if (atStart) range.setStartBefore(top)
483
+ else range.setEndAfter(top)
484
+ } catch (error) {
485
+ void error
486
+ }
487
+ return
488
+ }
489
+ el = el.parentElement
490
+ }
491
+ }
492
+ grow(range.startContainer, true)
493
+ grow(range.endContainer, false)
494
+ return range
495
+ }
496
+ window.dceMd = (root) => {
497
+ const parts = []
498
+ const kids = (node) => {
499
+ for (const child of node.childNodes) inline(child)
500
+ }
501
+ const inline = (node) => {
502
+ if (node.nodeType === 3) {
503
+ parts.push(node.nodeValue)
504
+ return
505
+ }
506
+ if (node.nodeType !== 1) return
507
+ if (window.dceIsMath(node)) {
508
+ const tex = window.dceTex(node)
509
+ if (tex !== undefined) {
510
+ const display = node.closest !== undefined && node.closest('.katex-display') !== null
511
+ parts.push(display ? '\n\n$$\n' + tex + '\n$$\n\n' : '$' + tex + '$')
512
+ } else {
513
+ // This renderer keeps no TeX in the DOM. Walk the visible layer
514
+ // only: mjx-container also carries a hidden assistive MathML copy
515
+ // of the same formula, which used to come out as duplicated text.
516
+ const visual =
517
+ node.querySelector === undefined ? null : node.querySelector('mjx-math') || node.querySelector('.katex-html')
518
+ parts.push(window.dceText(visual !== null && visual !== undefined ? visual : node))
519
+ }
520
+ return
521
+ }
522
+ const tag = node.tagName
523
+ if (tag === 'PRE') {
524
+ parts.push('\n```\n' + window.dceText(node) + '\n```\n')
525
+ return
526
+ }
527
+ if (tag === 'BR') {
528
+ parts.push('\n')
529
+ return
530
+ }
531
+ if (tag === 'CODE' && node.parentElement !== null && node.parentElement.tagName !== 'PRE') {
532
+ parts.push('`' + window.dceText(node) + '`')
533
+ return
534
+ }
535
+ if (tag === 'STRONG' || tag === 'B') {
536
+ if (window.dceHasMath(node)) {
537
+ kids(node)
538
+ return
539
+ }
540
+ parts.push('**' + window.dceText(node) + '**')
541
+ return
542
+ }
543
+ if (tag === 'EM' || tag === 'I') {
544
+ if (window.dceHasMath(node)) {
545
+ kids(node)
546
+ return
547
+ }
548
+ parts.push('*' + window.dceText(node) + '*')
549
+ return
550
+ }
551
+ if (tag === 'A') {
552
+ parts.push('[' + window.dceText(node) + '](' + (node.getAttribute('href') || '') + ')')
553
+ return
554
+ }
555
+ block(node)
556
+ }
557
+ const block = (node) => {
558
+ const tag = node.tagName
559
+ if (/^H[1-6]$/.test(tag)) {
560
+ parts.push('\n\n' + '#'.repeat(Number(tag[1])) + ' ')
561
+ kids(node)
562
+ parts.push('\n\n')
563
+ return
564
+ }
565
+ if (tag === 'LI') {
566
+ parts.push('\n- ')
567
+ kids(node)
568
+ return
569
+ }
570
+ if (tag === 'BLOCKQUOTE') {
571
+ parts.push('\n\n> ')
572
+ kids(node)
573
+ parts.push('\n\n')
574
+ return
575
+ }
576
+ if (tag === 'P' || tag === 'DIV' || tag === 'SECTION' || tag === 'UL' || tag === 'OL' || tag === 'TABLE') {
577
+ parts.push('\n\n')
578
+ kids(node)
579
+ parts.push('\n\n')
580
+ return
581
+ }
582
+ kids(node)
583
+ }
584
+ block(root)
585
+ return parts.join('').replace(/\n{3,}/g, '\n\n').trim()
586
+ }
587
+ // A failed extraction must say what the page actually looks like, so a
588
+ // site redesign can be re-adapted from one copied diagnostics card
589
+ // instead of a guessing round trip.
590
+ window.dceCensus = (doc) => {
591
+ const selectors = ['.ds-markdown', '[class*="markdown"]', 'article', '[data-testid]', '[data-message-author-role]', 'user-query', 'model-response', 'message-content', '.katex', 'math', 'main', '#root']
592
+ const counts = {}
593
+ for (const selector of selectors) counts[selector] = doc.querySelectorAll(selector).length
594
+ const root = doc.querySelector('main') || doc.body
595
+ const sample = []
596
+ for (const el of Array.from(root.children).slice(0, 8)) {
597
+ sample.push(el.tagName + '.' + String(el.className).slice(0, 40))
598
+ }
599
+ return JSON.stringify({ counts, sample })
600
+ }
601
+ // DeepSeek hashes its class names, so the user turn is found structurally:
602
+ // the nearest preceding sibling subtree that carries text but no answer
603
+ // markdown. Five levels up covers list/wrapper layouts without guessing.
604
+ window.dceUserBefore = (assistantEl) => {
605
+ let node = assistantEl
606
+ for (let depth = 0; depth < 5 && node !== null; depth += 1) {
607
+ let sibling = node.previousElementSibling
608
+ for (let back = 0; back < 3 && sibling !== null; back += 1) {
609
+ const text = window.dceText(sibling)
610
+ if (text !== '' && sibling.querySelector('.ds-markdown') === null) return text
611
+ sibling = sibling.previousElementSibling
612
+ }
613
+ node = node.parentElement
614
+ }
615
+ return ''
616
+ }
617
+ }
618
+
619
+ /**
620
+ * The selection bubble, installed once per guest document. A body-level
621
+ * node outside the site's React root, so site re-renders cannot sweep it
622
+ * away; mousedown is cancelled so clicking it keeps the selection alive.
623
+ * @param {string} prefix
624
+ * @param {string} nonce
625
+ * @param {string} label
626
+ * @param {string} pushUrl the relay sentinel, passed in so this file holds no literal origin
627
+ */
628
+ function guestBootstrapInit(prefix, nonce, label, pushUrl) {
629
+ if (window.__dceImport !== undefined && typeof window.__dceImport.dispose === 'function') {
630
+ window.__dceImport.dispose()
631
+ }
632
+ let bubble = null
633
+ // Captured when the bubble appears, never read from the live selection:
634
+ // the site collapses it on press, and this used to make clicks silent.
635
+ let pendingText = ''
636
+ let pressOnBubble = false
637
+ let skipNextSelection = false
638
+ const hide = () => {
639
+ if (bubble !== null && bubble.parentNode !== null) bubble.parentNode.removeChild(bubble)
640
+ bubble = null
641
+ pendingText = ''
642
+ }
643
+ const sendPush = (text) => {
644
+ if (text === '') {
645
+ console.log(prefix + nonce + JSON.stringify({ kind: 'selection', text: '', trace: 'empty-at-click' }))
646
+ return
647
+ }
648
+ console.log(prefix + nonce + JSON.stringify({ kind: 'selection', text: text }))
649
+ try {
650
+ window.open(pushUrl + encodeURIComponent(nonce) + '&' + encodeURIComponent(text))
651
+ } catch (error) {
652
+ void error
653
+ }
654
+ }
655
+ const onBubble = (target) => {
656
+ if (bubble === null || target === null || target === undefined) return false
657
+ if (target === bubble) return true
658
+ return typeof bubble.contains === 'function' && bubble.contains(target)
659
+ }
660
+ let showTimer
661
+ const cancelShow = () => {
662
+ if (showTimer === undefined) return
663
+ clearTimeout(showTimer)
664
+ showTimer = undefined
665
+ }
666
+ // Above the selection, centered. The old spot was the caret (rect.right),
667
+ // which is where the mouse still is on release, so the next drag started
668
+ // on the button instead of on the text.
669
+ const place = (rect) => {
670
+ const width = 132
671
+ const height = 34
672
+ const left = Math.max(8, Math.min(rect.left + Math.max(0, rect.width - width) / 2, window.innerWidth - width - 8))
673
+ let top = rect.top - height - 8
674
+ if (top < 8) top = Math.min(rect.bottom + 12, window.innerHeight - height - 8)
675
+ return { left: left, top: top }
676
+ }
677
+ const show = (rect, text) => {
678
+ pendingText = text
679
+ const spot = place(rect)
680
+ if (bubble === null) {
681
+ bubble = document.createElement('button')
682
+ bubble.type = 'button'
683
+ bubble.textContent = label
684
+ bubble.style.cssText =
685
+ 'position:fixed;z-index:2147483647;padding:7px 16px;border:1px solid rgba(0,0,0,.08);border-radius:999px;background:#fff;color:#1f2329;' +
686
+ 'font:500 14px/1.4 system-ui,sans-serif;cursor:pointer;box-shadow:0 1px 2px rgba(0,0,0,.04),0 4px 14px rgba(0,0,0,.06);' +
687
+ 'user-select:none;-webkit-user-select:none'
688
+ document.body.appendChild(bubble)
689
+ }
690
+ bubble.style.left = spot.left + 'px'
691
+ bubble.style.top = spot.top + 'px'
692
+ }
693
+ // Window capture runs before any site handler on document. Sites that
694
+ // clear the selection or stop propagation on mousedown would otherwise
695
+ // remove the bubble mid-press, so the push fires on release here instead
696
+ // of waiting for a click event that never lands.
697
+ const onDown = (event) => {
698
+ if (!onBubble(event.target)) return
699
+ pressOnBubble = true
700
+ event.preventDefault()
701
+ event.stopPropagation()
702
+ }
703
+ const onRelease = (event) => {
704
+ if (!onBubble(event.target) && !pressOnBubble) return
705
+ event.preventDefault()
706
+ event.stopPropagation()
707
+ if (pressOnBubble) sendPush(pendingText)
708
+ pressOnBubble = false
709
+ skipNextSelection = true
710
+ hide()
711
+ }
712
+ // A rendered formula loses its source in selection.toString(), and a
713
+ // MathJax container also contributes its hidden assistive MathML copy —
714
+ // which is why the plain string repeated every symbol. Serialize the
715
+ // range with the shared walker whenever the selection touches math.
716
+ const selectionText = (selection) => {
717
+ const range = window.dceMathRange(selection)
718
+ const plain = String(selection.toString()).trim()
719
+ try {
720
+ const fragment = range.cloneContents()
721
+ const mathy =
722
+ typeof fragment.querySelector === 'function' &&
723
+ fragment.querySelector(window.dceMathSel) !== null
724
+ const markdown = window.dceMd(fragment)
725
+ if (markdown !== '' && (mathy || markdown.indexOf('$') !== -1)) return markdown
726
+ } catch (error) {
727
+ void error
728
+ }
729
+ return plain
730
+ }
731
+ const capture = () => {
732
+ const selection = window.getSelection()
733
+ if (selection === null || selection.isCollapsed || selection.rangeCount === 0) {
734
+ hide()
735
+ return
736
+ }
737
+ const text = selectionText(selection)
738
+ if (text === '') {
739
+ hide()
740
+ return
741
+ }
742
+ // The user's range, not the grown formula copy, so the button stays on
743
+ // the words they actually dragged.
744
+ show(selection.getRangeAt(0).getBoundingClientRect(), text)
745
+ }
746
+ // Wait until the drag has settled. Showing on the mouseup frame both
747
+ // hitches the release and puts a control under a cursor that is still down.
748
+ const scheduleShow = () => {
749
+ if (pressOnBubble) return
750
+ cancelShow()
751
+ showTimer = setTimeout(() => {
752
+ showTimer = undefined
753
+ capture()
754
+ }, 200)
755
+ }
756
+ const onSelect = (event) => {
757
+ skipNextSelection = false
758
+ if (pressOnBubble) return
759
+ if (event !== undefined && event.key !== undefined) return
760
+ scheduleShow()
761
+ }
762
+ const onKey = () => {
763
+ skipNextSelection = false
764
+ if (pressOnBubble) return
765
+ scheduleShow()
766
+ }
767
+ const onChange = () => {
768
+ if (pressOnBubble) return
769
+ const selection = window.getSelection()
770
+ if (selection === null || selection.isCollapsed) {
771
+ cancelShow()
772
+ hide()
773
+ }
774
+ }
775
+ const onMouseUp = () => {
776
+ if (skipNextSelection) {
777
+ skipNextSelection = false
778
+ return
779
+ }
780
+ onSelect()
781
+ }
782
+ // A new drag must not start on the leftover button. Hide first, and do
783
+ // not cancel the event, or the page never begins the selection.
784
+ const onPageDown = (event) => {
785
+ if (onBubble(event.target)) return
786
+ cancelShow()
787
+ hide()
788
+ }
789
+ window.addEventListener('pointerdown', onDown, true)
790
+ window.addEventListener('mousedown', onDown, true)
791
+ window.addEventListener('pointerdown', onPageDown, true)
792
+ window.addEventListener('pointerup', onRelease, true)
793
+ window.addEventListener('mouseup', onRelease, true)
794
+ document.addEventListener('mouseup', onMouseUp, true)
795
+ document.addEventListener('keyup', onKey, true)
796
+ document.addEventListener('selectionchange', onChange)
797
+ window.__dceImport = {
798
+ dispose() {
799
+ cancelShow()
800
+ hide()
801
+ window.removeEventListener('pointerdown', onDown, true)
802
+ window.removeEventListener('mousedown', onDown, true)
803
+ window.removeEventListener('pointerdown', onPageDown, true)
804
+ window.removeEventListener('pointerup', onRelease, true)
805
+ window.removeEventListener('mouseup', onRelease, true)
806
+ document.removeEventListener('mouseup', onMouseUp, true)
807
+ document.removeEventListener('keyup', onKey, true)
808
+ document.removeEventListener('selectionchange', onChange)
809
+ window.__dceImport = undefined
810
+ },
811
+ }
812
+ }
813
+
814
+ /**
815
+ * Right-click menu for the two page-wide imports. Selection already has the
816
+ * bubble; these do not need a selection, and they must not replace the
817
+ * menu inside an input — that is where paste lives.
818
+ * @param {string} prefix
819
+ * @param {string} nonce
820
+ * @param {string} pushUrl
821
+ * @param {string} lastRoundLabel
822
+ * @param {string} conversationLabel
823
+ */
824
+ function guestContextMenuInit(prefix, nonce, pushUrl, lastRoundLabel, conversationLabel) {
825
+ if (window.__dceContextMenu !== undefined && typeof window.__dceContextMenu.dispose === 'function') {
826
+ window.__dceContextMenu.dispose()
827
+ }
828
+ let menu = null
829
+ const hide = () => {
830
+ if (menu !== null && menu.parentNode !== null) menu.parentNode.removeChild(menu)
831
+ menu = null
832
+ }
833
+ const send = (kind) => {
834
+ console.log(prefix + nonce + JSON.stringify({ kind: kind }))
835
+ try {
836
+ window.open(pushUrl + encodeURIComponent(nonce) + '&' + encodeURIComponent('action:' + kind))
837
+ } catch (error) {
838
+ void error
839
+ }
840
+ }
841
+ const inField = (node) => {
842
+ let el = node
843
+ while (el !== null && el !== undefined) {
844
+ const tag = String(el.tagName || '').toLowerCase()
845
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') return true
846
+ if (el.isContentEditable === true) return true
847
+ el = el.parentElement
848
+ }
849
+ return false
850
+ }
851
+ const show = (x, y) => {
852
+ hide()
853
+ menu = document.createElement('div')
854
+ menu.setAttribute('role', 'menu')
855
+ menu.style.cssText =
856
+ 'position:fixed;z-index:2147483647;width:max-content;max-width:280px;padding:4px;border:1px solid rgba(0,0,0,.08);' +
857
+ 'border-radius:12px;background:#fff;color:#1f2329;box-shadow:0 4px 16px rgba(0,0,0,.08);' +
858
+ 'font:500 14px/1.4 system-ui,sans-serif'
859
+ const add = (text, kind) => {
860
+ const item = document.createElement('button')
861
+ item.type = 'button'
862
+ item.textContent = text
863
+ item.setAttribute('role', 'menuitem')
864
+ item.style.cssText =
865
+ 'display:block;width:100%;box-sizing:border-box;margin:0;padding:7px 12px;border:0;border-radius:8px;' +
866
+ 'background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer;white-space:nowrap'
867
+ item.addEventListener('click', (event) => {
868
+ event.preventDefault()
869
+ event.stopPropagation()
870
+ hide()
871
+ send(kind)
872
+ })
873
+ menu.appendChild(item)
874
+ }
875
+ add(lastRoundLabel, 'lastRound')
876
+ add(conversationLabel, 'conversation')
877
+ document.body.appendChild(menu)
878
+ const rect = menu.getBoundingClientRect()
879
+ const width = rect.width || 160
880
+ const height = rect.height || 76
881
+ menu.style.left = Math.max(8, Math.min(x, window.innerWidth - width - 8)) + 'px'
882
+ menu.style.top = Math.max(8, Math.min(y, window.innerHeight - height - 8)) + 'px'
883
+ }
884
+ const onContext = (event) => {
885
+ if (inField(event.target)) return
886
+ event.preventDefault()
887
+ event.stopPropagation()
888
+ show(event.clientX, event.clientY)
889
+ }
890
+ const onDown = (event) => {
891
+ if (menu === null) return
892
+ if (event.target === menu) return
893
+ if (typeof menu.contains === 'function' && menu.contains(event.target)) return
894
+ hide()
895
+ }
896
+ const onKey = (event) => {
897
+ if (event.key === 'Escape') hide()
898
+ }
899
+ window.addEventListener('contextmenu', onContext, true)
900
+ window.addEventListener('pointerdown', onDown, true)
901
+ window.addEventListener('keydown', onKey, true)
902
+ window.addEventListener('scroll', hide, true)
903
+ window.__dceContextMenu = {
904
+ dispose() {
905
+ hide()
906
+ window.removeEventListener('contextmenu', onContext, true)
907
+ window.removeEventListener('pointerdown', onDown, true)
908
+ window.removeEventListener('keydown', onKey, true)
909
+ window.removeEventListener('scroll', hide, true)
910
+ window.__dceContextMenu = undefined
911
+ },
912
+ }
913
+ }
914
+
915
+ /**
916
+ * A function the guest can call.
917
+ *
918
+ * Method shorthand stringifies as `name(args) { ... }`. Wrapping that in
919
+ * parentheses and calling it is a SyntaxError, and the webview reports it
920
+ * only as GUEST_VIEW_MANAGER_CALL — which is what the last-round and
921
+ * whole-conversation menu items did. A `function` declaration or expression
922
+ * already stringifies as callable source.
923
+ *
924
+ * @param {Function} fn
925
+ * @returns {string}
926
+ */
927
+ function guestCallable(fn) {
928
+ const source = fn.toString()
929
+ if (
930
+ source.startsWith('function') ||
931
+ source.startsWith('async function') ||
932
+ source.startsWith('(') ||
933
+ source.startsWith('async (')
934
+ ) {
935
+ return source
936
+ }
937
+ return 'function ' + source
938
+ }
939
+
940
+ /**
941
+ * @param {any} adapter
942
+ * @param {string} kind
943
+ * @returns {string} guest source returning the extraction payload
944
+ */
945
+ function extractionSource(adapter, kind) {
946
+ return '(' + guestPrelude.toString() + ')();(' + guestCallable(adapter.extract[kind]) + ')(document)'
947
+ }
948
+
949
+ /**
950
+ * @param {string} nonce
951
+ * @param {string} label
952
+ * @returns {string} guest source arming the selection bubble
953
+ */
954
+ function bootstrapSource(nonce, label) {
955
+ return (
956
+ '(' + guestPrelude.toString() + ')();(' + guestBootstrapInit.toString() + ')(' +
957
+ JSON.stringify(IMPORT_PREFIX) + ', ' + JSON.stringify(nonce) + ', ' + JSON.stringify(label) + ', ' +
958
+ JSON.stringify(PUSH_URL) + ')'
959
+ )
960
+ }
961
+
962
+ /**
963
+ * @param {string} nonce
964
+ * @param {string} lastRoundLabel
965
+ * @param {string} conversationLabel
966
+ * @returns {string} guest source arming the right-click import menu
967
+ */
968
+ function contextMenuSource(nonce, lastRoundLabel, conversationLabel) {
969
+ return (
970
+ '(' + guestContextMenuInit.toString() + ')(' +
971
+ JSON.stringify(IMPORT_PREFIX) + ', ' + JSON.stringify(nonce) + ', ' +
972
+ JSON.stringify(PUSH_URL) + ', ' + JSON.stringify(lastRoundLabel) + ', ' +
973
+ JSON.stringify(conversationLabel) + ')'
974
+ )
975
+ }
976
+
977
+ /** @returns {string} guest source removing an armed bubble. */
978
+ function disarmSource() {
979
+ return (
980
+ '(' +
981
+ function () {
982
+ if (window.__dceImport !== undefined && typeof window.__dceImport.dispose === 'function') {
983
+ window.__dceImport.dispose()
984
+ }
985
+ }.toString() +
986
+ ')()'
987
+ )
988
+ }
989
+
990
+ /** @returns {string} guest source removing the right-click menu only. */
991
+ function disarmContextMenuSource() {
992
+ return (
993
+ '(' +
994
+ function () {
995
+ if (window.__dceContextMenu !== undefined && typeof window.__dceContextMenu.dispose === 'function') {
996
+ window.__dceContextMenu.dispose()
997
+ }
998
+ }.toString() +
999
+ ')()'
1000
+ )
1001
+ }
1002
+
1003
+ /**
1004
+ * @param {any} message a guest console line
1005
+ * @param {string} nonce the current mount's nonce
1006
+ * @returns {{ kind: string, text: string } | undefined}
1007
+ */
1008
+ function parseImportMessage(message, nonce) {
1009
+ if (typeof message !== 'string' || message.indexOf(IMPORT_PREFIX) !== 0) return undefined
1010
+ const body = message.slice(IMPORT_PREFIX.length)
1011
+ if (typeof nonce !== 'string' || nonce === '' || body.indexOf(nonce) !== 0) return undefined
1012
+ try {
1013
+ const payload = JSON.parse(body.slice(nonce.length))
1014
+ if (payload === null || typeof payload !== 'object') return undefined
1015
+ if (payload.kind === 'lastRound' || payload.kind === 'conversation') return { kind: payload.kind }
1016
+ if (payload.kind !== 'selection') return undefined
1017
+ if (typeof payload.text !== 'string' || payload.text.trim() === '') return undefined
1018
+ return { kind: 'selection', text: payload.text.trim() }
1019
+ } catch (error) {
1020
+ void error
1021
+ return undefined
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * @param {string} rawUrl a relayed window.open target
1027
+ * @returns {{ nonce: string, text: string } | undefined}
1028
+ */
1029
+ function parsePushUrl(rawUrl) {
1030
+ if (typeof rawUrl !== 'string' || rawUrl.indexOf(PUSH_URL) !== 0) return undefined
1031
+ const rest = rawUrl.slice(PUSH_URL.length)
1032
+ const cut = rest.indexOf('&')
1033
+ if (cut <= 0) return undefined
1034
+ const nonce = rest.slice(0, cut)
1035
+ let text
1036
+ try {
1037
+ text = decodeURIComponent(rest.slice(cut + 1))
1038
+ } catch (error) {
1039
+ void error
1040
+ return undefined
1041
+ }
1042
+ const trimmed = String(text).trim()
1043
+ if (trimmed === 'action:lastRound' || trimmed === 'action:conversation') {
1044
+ return { nonce, action: trimmed.slice('action:'.length) }
1045
+ }
1046
+ if (trimmed === '') return undefined
1047
+ return { nonce, text: trimmed }
1048
+ }
1049
+
1050
+ /**
1051
+ * One delivery point for both push channels, with a short duplicate window:
1052
+ * the bubble sends on both, and whichever arrives first wins.
1053
+ * @param {GuestRecord} record
1054
+ * @param {any} provider
1055
+ * @param {string} text
1056
+ * @param {string} channel
1057
+ */
1058
+ function receivePush(record, provider, text, channel) {
1059
+ // Both channels carry the same payload; a short signature is enough
1060
+ // identity for a 1.5s window, so the slower arrival imports nothing.
1061
+ const sig = text.length + ':' + text.slice(0, 48)
1062
+ const now = Date.now()
1063
+ if (record.lastPush !== undefined && record.lastPush.sig === sig && now - record.lastPush.at < 1500) return
1064
+ record.lastPush = { sig, at: now }
1065
+ record.lastEvent = 'import-push ' + channel
1066
+ notify()
1067
+ deliverImportPayload(
1068
+ { ok: true, title: '', messages: [{ role: 'excerpt', text }] },
1069
+ provider,
1070
+ record,
1071
+ translator(),
1072
+ 'selection',
1073
+ )
1074
+ }
1075
+
1076
+ /**
1077
+ * A right-click item asks the plugin to pull, instead of shipping the page
1078
+ * text through the URL. Both channels can arrive; the first one wins.
1079
+ * @param {GuestRecord} record
1080
+ * @param {string} kind
1081
+ * @param {'main' | 'right'} [seat]
1082
+ */
1083
+ function receiveAction(record, kind, seat) {
1084
+ const sig = 'action:' + kind
1085
+ const now = Date.now()
1086
+ if (record.lastPush !== undefined && record.lastPush.sig === sig && now - record.lastPush.at < 1500) return
1087
+ record.lastPush = { sig, at: now }
1088
+ record.lastEvent = 'import-action ' + kind
1089
+ notify()
1090
+ void runImport(kind, seat)
1091
+ }
1092
+
1093
+ /** @param {any} payload @returns {boolean} */
1094
+ function validateImportPayload(payload) {
1095
+ if (payload === null || typeof payload !== 'object' || payload.ok !== true) return false
1096
+ if (!Array.isArray(payload.messages) || payload.messages.length === 0) return false
1097
+ for (const message of payload.messages) {
1098
+ if (message === null || typeof message !== 'object') return false
1099
+ if (message.role !== 'user' && message.role !== 'assistant' && message.role !== 'excerpt') return false
1100
+ if (typeof message.text !== 'string' || message.text.trim() === '') return false
1101
+ }
1102
+ return true
1103
+ }
1104
+
1105
+ /**
1106
+ * @param {any} payload a validated extraction result
1107
+ * @param {{ user: string, assistant: string, excerpt: string }} labels
1108
+ * @param {{ label: string, url: string }} source
1109
+ * @returns {string} markdown draft text
1110
+ */
1111
+ function formatImport(payload, labels, source, context) {
1112
+ const info = context !== undefined && context !== null ? context : {}
1113
+ const excerptOnly = payload.messages.every((message) => message.role === 'excerpt')
1114
+ const kind = typeof info.kind === 'string' && info.kind !== '' ? info.kind : excerptOnly ? 'selection' : 'conversation'
1115
+ const site = source.label
1116
+ const head =
1117
+ kind === 'lastRound'
1118
+ ? fill(labels.citeRound, { site })
1119
+ : kind === 'conversation'
1120
+ ? fill(labels.citeConversation, { site })
1121
+ : fill(labels.citeExcerpt, { site })
1122
+ const lines = [head, '']
1123
+ for (const message of payload.messages) {
1124
+ if (message.role === 'excerpt') {
1125
+ lines.push(message.text)
1126
+ continue
1127
+ }
1128
+ const role = message.role === 'user' ? labels.user : labels.assistant
1129
+ lines.push(role + '\n' + message.text)
1130
+ }
1131
+ return lines.join('\n').replace(/\n{3,}/g, '\n\n').trim()
1132
+ }
1133
+
1134
+ /**
1135
+ * The main conversation is the session the center panel retains: the
1136
+ * adapter snapshot is the cheap read, the retain scan the fallback (the
1137
+ * same judgement UiSession.publishMain uses).
1138
+ * @param {any} ctx
1139
+ * @returns {string | undefined}
1140
+ */
1141
+ function mainSessionId(ctx) {
1142
+ const ui = ctx === undefined || ctx === null ? undefined : ctx.uiSession
1143
+ const current = ui === undefined || ui === null || ui.adapter === undefined ? undefined : ui.adapter.current
1144
+ const key =
1145
+ current !== undefined && current !== null && typeof current.getSnapshot === 'function'
1146
+ ? current.getSnapshot().key
1147
+ : undefined
1148
+ if (typeof key === 'string' && key !== '') return key
1149
+ const sessions = ctx === undefined || ctx === null ? undefined : ctx.sessions
1150
+ const list =
1151
+ sessions !== undefined && sessions !== null && sessions.list !== undefined && typeof sessions.list.getSnapshot === 'function'
1152
+ ? sessions.list.getSnapshot()
1153
+ : undefined
1154
+ const byId = list === undefined || list === null ? undefined : list.byId
1155
+ if (byId === undefined || byId === null) return undefined
1156
+ for (const id of Object.keys(byId)) {
1157
+ const row = byId[id]
1158
+ if (row !== undefined && row !== null && row.retainedBy !== undefined && (row.retainedBy.mainView || 0) > 0) return id
1159
+ }
1160
+ return undefined
1161
+ }
1162
+
1163
+ /**
1164
+ * Draft, never send: imported web content reaches the agent only after the
1165
+ * user presses enter themselves. insertQuote keeps it a labelled quote;
1166
+ * when the editor refuses (rich mode, busy phase) fall back to the official
1167
+ * append initialization instead of overwriting whatever is being typed.
1168
+ * @param {any} ctx
1169
+ * @param {string} text
1170
+ * @param {boolean} [allowNavigation] false on the delayed retry: navigate once, never twice
1171
+ * @returns {{ ok: boolean, reason?: string }} reason is a token ('no-session' |
1172
+ * 'retry') the caller maps to a message, or the failure message itself
1173
+ */
1174
+ function importDraft(ctx, text, allowNavigation) {
1175
+ const id = mainSessionId(ctx)
1176
+ if (id === undefined) return { ok: false, reason: 'no-session' }
1177
+ // The conversation service is a root singleton addressed by the caller's
1178
+ // scope; a derived sessions.scope() context does not inherit this
1179
+ // plugin's inject list, so actx.conversation throws. Read the service
1180
+ // from our own ctx and hand it the retained scope instead.
1181
+ const sessions = ctx.sessions
1182
+ if (sessions === undefined || sessions === null || typeof sessions.scope !== 'function') {
1183
+ return { ok: false, reason: 'no-session' }
1184
+ }
1185
+ const actx = sessions.scope(id)
1186
+ if (actx === undefined || actx === null) {
1187
+ // The center panel may be showing this chat panel instead of the
1188
+ // conversation, so nothing retains the session yet. Navigation retains
1189
+ // it; one delayed retry lands the draft once the composer exists.
1190
+ const uiWorkspace = ctx.uiWorkspace
1191
+ if (allowNavigation !== false && uiWorkspace !== undefined && uiWorkspace !== null && typeof uiWorkspace.openSession === 'function') {
1192
+ uiWorkspace.openSession(id)
1193
+ return { ok: false, reason: 'retry', id }
1194
+ }
1195
+ return { ok: false, reason: 'no-session' }
1196
+ }
1197
+ const hub = ctx.conversation !== undefined && ctx.conversation !== null ? ctx.conversation.input : undefined
1198
+ if (hub === undefined || hub === null || typeof hub.for !== 'function') return { ok: false, reason: 'no-session' }
1199
+ let input
1200
+ try {
1201
+ input = hub.for(actx)
1202
+ } catch (error) {
1203
+ return { ok: false, reason: messageOf(error) }
1204
+ }
1205
+ let inserted = false
1206
+ try {
1207
+ inserted = input.insertQuote(text) === true
1208
+ } catch (error) {
1209
+ void error
1210
+ inserted = false
1211
+ }
1212
+ if (!inserted) {
1213
+ let result
1214
+ try {
1215
+ result = hub.requestDraftInitialization(sessions.binding(id), {
1216
+ prompt: text,
1217
+ whenDraftExists: 'append',
1218
+ })
1219
+ } catch (error) {
1220
+ return { ok: false, reason: messageOf(error) }
1221
+ }
1222
+ // 'blocked' means the composer is mid-send and kept the old draft.
1223
+ // Treating that as success used to tell the user the import landed.
1224
+ if (result === 'blocked') return { ok: false, reason: 'blocked' }
1225
+ }
1226
+ try {
1227
+ input.focus()
1228
+ } catch (error) {
1229
+ void error
1230
+ }
1231
+ // No input.notify here: that notice stays until something else replaces
1232
+ // it. The import confirmation is a transient toast (showImportNotice),
1233
+ // which is enough and does not live in the composer.
1234
+ return { ok: true }
1235
+ }
1236
+
1237
+ /**
1238
+ * @param {any} payload
1239
+ * @param {{ label: string, url: string }} provider
1240
+ * @param {any} record the seat's guest record (holds the transient notice)
1241
+ * @param {(key: string) => string} t
1242
+ * @param {string} [kind] selection, lastRound, or conversation
1243
+ */
1244
+ function deliverImportPayload(payload, provider, record, t, kind) {
1245
+ if (!validateImportPayload(payload)) {
1246
+ showImportNotice(record, t('importEmpty'))
1247
+ return
1248
+ }
1249
+ if (record !== undefined && typeof payload.math === 'string' && payload.math !== '') {
1250
+ // The adapter could not rebuild TeX from this renderer; keep its node
1251
+ // shape in the diagnostics card so the source can be located.
1252
+ record.lastEvent = 'import-math ' + payload.math.slice(0, 400)
1253
+ notify()
1254
+ }
1255
+ const text = formatImport(
1256
+ payload,
1257
+ {
1258
+ user: t('roleUser'),
1259
+ assistant: t('roleAssistant'),
1260
+ citeExcerpt: t('citeExcerpt'),
1261
+ citeRound: t('citeRound'),
1262
+ citeConversation: t('citeConversation'),
1263
+ },
1264
+ provider,
1265
+ { kind },
1266
+ )
1267
+ let outcome
1268
+ try {
1269
+ outcome = importDraft(activeCtx, text)
1270
+ } catch (error) {
1271
+ log('warn', 'import: draft insert rejected', messageOf(error))
1272
+ showImportNotice(record, t('importFailed') + ' ' + messageOf(error))
1273
+ return
1274
+ }
1275
+ if (outcome.ok) {
1276
+ // Silence is the positive feedback here: the quoted draft appearing in
1277
+ // the main input already says it worked.
1278
+ log('info', 'import: drafted', { provider: provider.id, messages: payload.messages.length })
1279
+ } else {
1280
+ reportImportOutcome(outcome, text, record, t)
1281
+ }
1282
+ }
1283
+
1284
+ /**
1285
+ * @param {{ ok: boolean, reason?: string }} outcome
1286
+ * @param {string} text
1287
+ * @param {any} record the seat's guest record (holds the transient notice)
1288
+ * @param {(key: string) => string} t
1289
+ */
1290
+ function reportImportOutcome(outcome, text, record, t) {
1291
+ if (outcome.ok) return
1292
+ if (outcome.reason === 'retry') {
1293
+ // One retry only: a second 'retry' means navigation did not retain the
1294
+ // session, and looping would fight the user's own panel switches.
1295
+ setTimeout(() => {
1296
+ let again
1297
+ try {
1298
+ again = importDraft(activeCtx, text, false)
1299
+ } catch (error) {
1300
+ again = { ok: false, reason: messageOf(error) }
1301
+ }
1302
+ if (again.ok) {
1303
+ // The draft itself is the confirmation; no toast.
1304
+ log('info', 'import: drafted after retry')
1305
+ } else if (again.reason === 'no-session' || again.reason === 'retry') showImportNotice(record, t('importNoSession'))
1306
+ else if (again.reason === 'blocked') showImportNotice(record, t('importBusy'))
1307
+ else showImportNotice(record, t('importFailed') + ' ' + again.reason)
1308
+ }, 350)
1309
+ return
1310
+ }
1311
+ showImportNotice(
1312
+ record,
1313
+ outcome.reason === 'no-session' ? t('importNoSession') : outcome.reason === 'blocked' ? t('importBusy') : t('importFailed') + ' ' + outcome.reason,
1314
+ )
1315
+ }
1316
+
1317
+ /**
1318
+ * Pull import: one executeJavaScript round trip carries the payload back,
1319
+ * so no resident guest script and no console channel are involved.
1320
+ * @param {string} kind
1321
+ * @param {'main' | 'right'} [seat]
1322
+ * @returns {Promise<void>}
1323
+ */
1324
+ async function runImport(kind, seat) {
1325
+ const t = translator()
1326
+ const provider = activeProvider(seat)
1327
+ const record = guestRecord(provider.id, seat)
1328
+ const adapter = GUEST_ADAPTERS[provider.id]
1329
+ if (adapter === undefined || adapter.extract[kind] === undefined) {
1330
+ showImportNotice(record, t('importUnsupported'))
1331
+ return
1332
+ }
1333
+ const element = record.element
1334
+ if (element === undefined || element === null || record.phase !== PHASE.READY) {
1335
+ showImportNotice(record, t('importNotReady'))
1336
+ return
1337
+ }
1338
+ let payload
1339
+ try {
1340
+ payload = await element.executeJavaScript(extractionSource(adapter, kind))
1341
+ } catch (error) {
1342
+ log('warn', 'import: extraction rejected', messageOf(error))
1343
+ showImportNotice(record, t('importFailed') + ' ' + messageOf(error))
1344
+ return
1345
+ }
1346
+ if (payload !== undefined && payload !== null && payload.ok === false) {
1347
+ record.lastEvent = 'import-empty ' + (typeof payload.census === 'string' ? payload.census : payload.reason)
1348
+ notify()
1349
+ }
1350
+ deliverImportPayload(payload, provider, record, t, kind)
1351
+ }
1352
+
1353
+ /** @param {GuestRecord} record @param {any} element */
1354
+ function installImportGuest(record, element) {
1355
+ if (!importBubbleEnabled()) return
1356
+ if (GUEST_ADAPTERS[record.id] === undefined) return
1357
+ const pending = element.executeJavaScript(bootstrapSource(record.importNonce, translator()('bubbleLabel')))
1358
+ if (pending !== undefined && pending !== null && typeof pending.catch === 'function') pending.catch(() => {})
1359
+ }
1360
+
1361
+ /**
1362
+ * Pages without an adapter have nothing these two items can import, so
1363
+ * they keep the site's own menu. The switch is independent of the bubble.
1364
+ * @param {GuestRecord} record
1365
+ * @param {any} element
1366
+ */
1367
+ function installContextMenu(record, element) {
1368
+ if (!contextMenuEnabled()) return
1369
+ const adapter = GUEST_ADAPTERS[record.id]
1370
+ if (adapter === undefined || adapter.extract.lastRound === undefined || adapter.extract.conversation === undefined) return
1371
+ const t = translator()
1372
+ const pending = element.executeJavaScript(
1373
+ contextMenuSource(record.importNonce, t('contextLastRound'), t('contextConversation')),
1374
+ )
1375
+ if (pending !== undefined && pending !== null && typeof pending.catch === 'function') pending.catch(() => {})
1376
+ }
1377
+
1378
+ /** Re-arm or disarm every live guest after a preference change. */
1379
+ function refreshImportGuests() {
1380
+ for (const record of guests.values()) {
1381
+ const element = record.element
1382
+ if (element === undefined || element === null) continue
1383
+ const live = GUEST_ADAPTERS[record.id] !== undefined && isLiveUrl(guestUrl(element))
1384
+ if (importBubbleEnabled() && live) {
1385
+ installImportGuest(record, element)
1386
+ } else {
1387
+ const pending = element.executeJavaScript(disarmSource())
1388
+ if (pending !== undefined && pending !== null && typeof pending.catch === 'function') pending.catch(() => {})
1389
+ }
1390
+ if (contextMenuEnabled() && live) {
1391
+ installContextMenu(record, element)
1392
+ } else {
1393
+ const pending = element.executeJavaScript(disarmContextMenuSource())
1394
+ if (pending !== undefined && pending !== null && typeof pending.catch === 'function') pending.catch(() => {})
1395
+ }
1396
+ }
1397
+ }
1398
+
1399
+ /** @param {string} id @param {any} event @param {'main' | 'right'} [seat] */
1400
+ function onGuestImportMessage(id, event, seat) {
1401
+ const raw = event === undefined || event === null ? undefined : event.message
1402
+ // Every guest console line lands here; only ours is worth tracing. A
1403
+ // silent skip keeps the diagnostics card readable on pages that log a
1404
+ // lot, and still distinguishes "arrived but rejected" from "never seen".
1405
+ if (typeof raw !== 'string' || raw.indexOf(IMPORT_PREFIX) !== 0) return
1406
+ const record = guestRecord(id, seat)
1407
+ record.lastEvent = 'import-console ' + raw.slice(0, 60)
1408
+ const parsed = parseImportMessage(raw, record.importNonce)
1409
+ if (parsed === undefined) {
1410
+ log('warn', 'import: console line rejected', { provider: id, head: typeof raw === 'string' ? raw.slice(0, 40) : typeof raw })
1411
+ showImportNotice(record, translator()('importBadChannel'))
1412
+ notify()
1413
+ return
1414
+ }
1415
+ if (parsed.kind === 'lastRound' || parsed.kind === 'conversation') {
1416
+ log('info', 'import: context action', { provider: id, kind: parsed.kind })
1417
+ receiveAction(record, parsed.kind, seat)
1418
+ return
1419
+ }
1420
+ log('info', 'import: selection received', { provider: id, chars: parsed.text.length })
1421
+ receivePush(record, findProvider(id), parsed.text, 'console')
1422
+ }
1423
+
132
1424
  /**
133
1425
  * The services this surface can host. Order is the tab order.
134
1426
  *
@@ -261,6 +1553,26 @@ let activeCtx = undefined
261
1553
  dismiss: 'Dismiss',
262
1554
  dragHint: 'Drag to reorder',
263
1555
  settings: 'Settings',
1556
+ contextLastRound: 'Quote the last reply into DSH',
1557
+ contextConversation: 'Quote the full conversation into DSH',
1558
+ importUnsupported: 'This service has no importer yet',
1559
+ importNotReady: 'The tab is not connected yet',
1560
+ importEmpty: 'Nothing to import on this page',
1561
+ importNoSession: 'No main conversation is open',
1562
+ importFailed: 'Import failed:',
1563
+ importBusy: 'The input is busy; nothing was inserted',
1564
+ importBadChannel: 'The bubble message was rejected (channel or stale nonce); copy diagnostics',
1565
+ importBubble: 'Selection bubble',
1566
+ importBubbleHint: 'Show an import bubble when text is selected in the embedded page',
1567
+ contextMenu: 'Right-click menu',
1568
+ contextMenuHint: 'Show quote-into-DSH items when right-clicking the embedded page',
1569
+ bubbleLabel: 'Import to DSH',
1570
+ roleUser: 'Web user',
1571
+ roleAssistant: 'Web assistant',
1572
+ roleExcerpt: 'Excerpt',
1573
+ citeExcerpt: '{site} · excerpt',
1574
+ citeRound: '{site} · last exchange',
1575
+ citeConversation: '{site} · conversation',
264
1576
  menuTitle: 'Chat tabs',
265
1577
  lastTabHint: 'At least one tab must stay enabled',
266
1578
  logging: 'Debug log',
@@ -370,6 +1682,26 @@ let activeCtx = undefined
370
1682
  dismiss: '知道了',
371
1683
  dragHint: '拖动可排序',
372
1684
  settings: '设置',
1685
+ contextLastRound: '引用最后回复到DSH',
1686
+ contextConversation: '引用完整对话到DSH',
1687
+ importUnsupported: '该服务暂不支持导入',
1688
+ importNotReady: '标签页尚未连接',
1689
+ importEmpty: '页面上没有可导入的内容',
1690
+ importNoSession: '当前没有打开的主对话',
1691
+ importFailed: '导入失败:',
1692
+ importBusy: '输入框正在发送,这次没有写入',
1693
+ importBadChannel: '气泡消息被拒绝(通道或过期 nonce),请复制诊断',
1694
+ importBubble: '选中气泡',
1695
+ importBubbleHint: '在内嵌页选中文本时显示导入气泡',
1696
+ contextMenu: '右键菜单',
1697
+ contextMenuHint: '在内嵌页右键时显示引用到 DSH 的菜单',
1698
+ bubbleLabel: '导入到 DSH',
1699
+ roleUser: '网页用户',
1700
+ roleAssistant: '网页助手',
1701
+ roleExcerpt: '摘录',
1702
+ citeExcerpt: '{site} · 摘录',
1703
+ citeRound: '{site} · 最后一轮',
1704
+ citeConversation: '{site} · 整段对话',
373
1705
  menuTitle: '对话窗口',
374
1706
  lastTabHint: '至少保留一个对话窗口',
375
1707
  logging: '调试日志',
@@ -843,21 +2175,38 @@ let activeCtx = undefined
843
2175
  // Active tab
844
2176
  // ------------------------------------------------------------------
845
2177
 
846
- function readStoredActive() {
2178
+ /**
2179
+ * @param {'main' | 'right' | undefined} [seat]
2180
+ * @returns {'main' | 'right'}
2181
+ */
2182
+ function seatOf(seat) {
2183
+ return seat === 'right' ? 'right' : 'main'
2184
+ }
2185
+
2186
+ /** @param {'main' | 'right' | undefined} [seat] @returns {string} */
2187
+ function activeStorageKey(seat) {
2188
+ return seatOf(seat) === 'right' ? ACTIVE_TAB_KEY + ':right' : ACTIVE_TAB_KEY
2189
+ }
2190
+
2191
+ /** @param {'main' | 'right' | undefined} [seat] */
2192
+ function readStoredActive(seat) {
847
2193
  try {
848
2194
  if (typeof localStorage === 'undefined' || localStorage === null) return DEFAULT_PROVIDER
849
- const stored = localStorage.getItem(ACTIVE_TAB_KEY)
2195
+ const stored = localStorage.getItem(activeStorageKey(seat))
850
2196
  return findProvider(stored) === undefined ? DEFAULT_PROVIDER : stored
851
2197
  } catch (error) {
852
2198
  return DEFAULT_PROVIDER
853
2199
  }
854
2200
  }
855
2201
 
856
- /** @param {string} id */
857
- function storeActive(id) {
2202
+ /**
2203
+ * @param {string} id
2204
+ * @param {'main' | 'right' | undefined} [seat]
2205
+ */
2206
+ function storeActive(id, seat) {
858
2207
  try {
859
2208
  if (typeof localStorage === 'undefined' || localStorage === null) return
860
- localStorage.setItem(ACTIVE_TAB_KEY, id)
2209
+ localStorage.setItem(activeStorageKey(seat), id)
861
2210
  } catch (error) {
862
2211
  void error
863
2212
  }
@@ -1003,32 +2352,40 @@ let activeCtx = undefined
1003
2352
  enabledIds = normalizeEnabled(tabOrder.filter((entryId) => entryId === id || isEnabled(entryId)))
1004
2353
  } else {
1005
2354
  enabledIds = enabledIds.filter((entryId) => entryId !== id)
1006
- const record = guestRecord(id)
1007
- if (record.element !== undefined && record.element !== null) dropGuest(record)
2355
+ for (const seat of ['main', 'right']) {
2356
+ const record = guests.get(seat + ':' + id)
2357
+ if (record !== undefined && record.element !== undefined && record.element !== null) dropGuest(record)
2358
+ }
1008
2359
  }
1009
2360
  storeEnabled()
1010
2361
 
1011
- if (on === false && state.active === id) {
2362
+ if (on === false && (activeBySeat.main === id || activeBySeat.right === id)) {
1012
2363
  const next = firstEnabled()
1013
- state.active = next
1014
- storeActive(next)
1015
- syncLayers()
2364
+ for (const seat of ['main', 'right']) {
2365
+ if (activeBySeat[seat] !== id) continue
2366
+ assignSeatActive(seat, next)
2367
+ syncLayers(seat)
2368
+ void ensureActiveGuest(seat)
2369
+ }
1016
2370
  notify()
1017
- void ensureActiveGuest()
1018
2371
  return true
1019
2372
  }
1020
2373
  notify()
1021
- if (on) void ensureActiveGuest()
2374
+ if (on) {
2375
+ void ensureActiveGuest('main')
2376
+ void ensureActiveGuest('right')
2377
+ }
1022
2378
  return true
1023
2379
  }
1024
2380
 
1025
2381
  /** Move the active tab to a still-enabled provider when it was hidden. */
1026
2382
  function reconcileActive() {
1027
- if (isEnabled(state.active)) return
1028
2383
  const next = findProvider(firstEnabled())
1029
2384
  if (next === undefined) return
1030
- state.active = next.id
1031
- storeActive(next.id)
2385
+ for (const seat of ['main', 'right']) {
2386
+ if (isEnabled(activeBySeat[seat])) continue
2387
+ assignSeatActive(seat, next.id)
2388
+ }
1032
2389
  }
1033
2390
 
1034
2391
  /**
@@ -1057,15 +2414,35 @@ let activeCtx = undefined
1057
2414
 
1058
2415
  /** @type {{ active: string, surface: { host: any } }} */
1059
2416
  const state = {
1060
- active: readStoredActive(),
2417
+ active: readStoredActive('main'),
1061
2418
  surface: { host: null },
1062
2419
  }
1063
2420
 
2421
+ /** @type {{ main: string, right: string }} the selected tab on each seat */
2422
+ const activeBySeat = {
2423
+ main: state.active,
2424
+ right: readStoredActive('right'),
2425
+ }
2426
+
2427
+ /**
2428
+ * @param {'main' | 'right'} seat
2429
+ * @param {string} id
2430
+ */
2431
+ function assignSeatActive(seat, id) {
2432
+ const which = seatOf(seat)
2433
+ activeBySeat[which] = id
2434
+ if (which === 'main') state.active = id
2435
+ storeActive(id, which)
2436
+ }
2437
+
1064
2438
  reconcileActive()
1065
2439
 
1066
- /** @returns {object} the active provider record. */
1067
- function activeProvider() {
1068
- const provider = findProvider(state.active)
2440
+ /**
2441
+ * @param {'main' | 'right' | undefined} [seat]
2442
+ * @returns {object} the active provider record for that seat.
2443
+ */
2444
+ function activeProvider(seat) {
2445
+ const provider = findProvider(activeBySeat[seatOf(seat)])
1069
2446
  if (provider !== undefined && isEnabled(provider.id)) return provider
1070
2447
  const fallback = findProvider(firstEnabled())
1071
2448
  return fallback !== undefined ? fallback : PROVIDERS[0]
@@ -1080,6 +2457,7 @@ let activeCtx = undefined
1080
2457
  * @property {any} element
1081
2458
  * @property {string | undefined} lease
1082
2459
  * @property {string | undefined} partition
2460
+ * @property {string} importNonce
1083
2461
  * @property {any} layer
1084
2462
  * @property {boolean} mounting
1085
2463
  * @property {number} generation
@@ -1117,8 +2495,8 @@ let activeCtx = undefined
1117
2495
  * @param {any} provider
1118
2496
  * @returns {string}
1119
2497
  */
1120
- function startUrlFor(provider) {
1121
- const remembered = lastUrls.get(provider.id)
2498
+ function startUrlFor(provider, seat) {
2499
+ const remembered = lastUrls.get(seatOf(seat) + ':' + provider.id)
1122
2500
  if (typeof remembered !== 'string' || remembered === '') return provider.url
1123
2501
  if (!remembered.startsWith(provider.origin)) return provider.url
1124
2502
  if (!isLiveUrl(remembered)) return provider.url
@@ -1126,11 +2504,21 @@ let activeCtx = undefined
1126
2504
  return remembered
1127
2505
  }
1128
2506
 
1129
- /** @returns {GuestRecord} */
1130
- function guestRecord(id) {
1131
- let record = guests.get(id)
2507
+ /**
2508
+ * One record per seat. The two webviews share a partition, not a document.
2509
+ *
2510
+ * @param {string} id
2511
+ * @param {'main' | 'right' | undefined} [seat]
2512
+ * @returns {GuestRecord}
2513
+ */
2514
+ function guestRecord(id, seat) {
2515
+ const which = seatOf(seat)
2516
+ const key = which + ':' + id
2517
+ let record = guests.get(key)
1132
2518
  if (record === undefined) {
1133
2519
  record = {
2520
+ id,
2521
+ seat: which,
1134
2522
  element: undefined,
1135
2523
  lease: undefined,
1136
2524
  partition: undefined,
@@ -1152,15 +2540,22 @@ let activeCtx = undefined
1152
2540
  reloadTimer: undefined,
1153
2541
  handoff: '',
1154
2542
  selfTest: '',
2543
+ importNonce: '',
2544
+ lastPush: undefined,
2545
+ notice: '',
2546
+ noticeTimer: undefined,
1155
2547
  }
1156
- guests.set(id, record)
2548
+ guests.set(key, record)
1157
2549
  }
1158
2550
  return record
1159
2551
  }
1160
2552
 
1161
- /** @returns {{ phase: string, detail: string }} */
1162
- function getStatus() {
1163
- const record = guestRecord(state.active)
2553
+ /**
2554
+ * @param {'main' | 'right' | undefined} [seat]
2555
+ * @returns {{ phase: string, detail: string }}
2556
+ */
2557
+ function getStatus(seat) {
2558
+ const record = guestRecord(activeBySeat[seatOf(seat)], seat)
1164
2559
  return { phase: record.phase, detail: record.detail }
1165
2560
  }
1166
2561
 
@@ -1168,9 +2563,10 @@ let activeCtx = undefined
1168
2563
  * @param {string} id
1169
2564
  * @param {string} phase
1170
2565
  * @param {string} [detail]
2566
+ * @param {'main' | 'right' | undefined} [seat]
1171
2567
  */
1172
- function setPhase(id, phase, detail) {
1173
- const record = guestRecord(id)
2568
+ function setPhase(id, phase, detail, seat) {
2569
+ const record = guestRecord(id, seat)
1174
2570
  if (record.phase === phase && record.detail === (detail === undefined ? '' : detail)) return
1175
2571
  record.phase = phase
1176
2572
  record.detail = detail === undefined ? '' : detail
@@ -1218,6 +2614,13 @@ let activeCtx = undefined
1218
2614
  record.lastEvent = ''
1219
2615
  record.diagOpen = false
1220
2616
  record.selfTest = ''
2617
+ record.importNonce = ''
2618
+ record.lastPush = undefined
2619
+ if (record.noticeTimer !== undefined) {
2620
+ clearTimeout(record.noticeTimer)
2621
+ record.noticeTimer = undefined
2622
+ }
2623
+ record.notice = ''
1221
2624
  // `oauthBlocked` is deliberately kept: the explanation must survive the
1222
2625
  // recovery reload that replaces the stuck guest.
1223
2626
 
@@ -1263,6 +2666,7 @@ let activeCtx = undefined
1263
2666
  element.removeEventListener('did-stop-loading', handlers.stop)
1264
2667
  element.removeEventListener('render-process-gone', handlers.crash)
1265
2668
  element.removeEventListener('crashed', handlers.crash)
2669
+ element.removeEventListener('console-message', handlers.importMessage)
1266
2670
  }
1267
2671
  } catch (error) {
1268
2672
  void error
@@ -1324,29 +2728,57 @@ let activeCtx = undefined
1324
2728
  }
1325
2729
  }
1326
2730
 
1327
- /** @param {object} provider */
1328
- function layerFor(provider) {
1329
- const record = guestRecord(provider.id)
2731
+ /**
2732
+ * Where a new guest layer is attached.
2733
+ *
2734
+ * Left pages live in the park so the chat panel can unmount without
2735
+ * destroying them. Right pages live in the column, so a collapse hides
2736
+ * them with the column instead of leaving a fixed box on the conversation.
2737
+ *
2738
+ * @param {'main' | 'right' | undefined} [seat]
2739
+ * @returns {any}
2740
+ */
2741
+ function guestHome(seat) {
2742
+ if (seatOf(seat) === 'right') return inlineHosts.right
2743
+ const park = ensurePark()
2744
+ if (park !== undefined) return park
2745
+ if (inlineHosts.main !== null && inlineHosts.main !== undefined) return inlineHosts.main
2746
+ return state.surface.host
2747
+ }
2748
+
2749
+ /**
2750
+ * @param {object} provider
2751
+ * @param {'main' | 'right' | undefined} [seat]
2752
+ */
2753
+ function layerFor(provider, seat) {
2754
+ const which = seatOf(seat)
2755
+ const record = guestRecord(provider.id, which)
1330
2756
  if (record.layer !== undefined && record.layer !== null && record.layer.isConnected !== false) {
1331
2757
  return record.layer
1332
2758
  }
1333
- const host = state.surface.host
2759
+ const host = guestHome(which)
1334
2760
  if (host === null || host === undefined) return undefined
1335
2761
  const layer = document.createElement('div')
1336
2762
  layer.className = 'dce-guest-layer'
1337
2763
  layer.setAttribute('data-provider', provider.id)
1338
- layer.setAttribute('data-active', provider.id === state.active ? 'true' : 'false')
2764
+ layer.setAttribute('data-seat', which)
2765
+ layer.setAttribute('data-active', provider.id === activeBySeat[which] ? 'true' : 'false')
1339
2766
  host.appendChild(layer)
1340
2767
  record.layer = layer
1341
2768
  return layer
1342
2769
  }
1343
2770
 
1344
- /** Show only the active provider's layer; hidden layers keep their guest. */
1345
- function syncLayers() {
1346
- for (const provider of PROVIDERS) {
1347
- const record = guests.get(provider.id)
1348
- if (record === undefined || record.layer === undefined || record.layer === null) continue
1349
- const want = provider.id === state.active ? 'true' : 'false'
2771
+ /**
2772
+ * Show only that seat's active layer. The other seat is not touched.
2773
+ *
2774
+ * @param {'main' | 'right' | undefined} [seat]
2775
+ */
2776
+ function syncLayers(seat) {
2777
+ const which = seat === undefined ? undefined : seatOf(seat)
2778
+ for (const record of guests.values()) {
2779
+ if (which !== undefined && record.seat !== which) continue
2780
+ if (record.layer === undefined || record.layer === null) continue
2781
+ const want = record.id === activeBySeat[record.seat] ? 'true' : 'false'
1350
2782
  if (record.layer.getAttribute('data-active') !== want) record.layer.setAttribute('data-active', want)
1351
2783
  }
1352
2784
  }
@@ -1357,10 +2789,11 @@ let activeCtx = undefined
1357
2789
  * @param {string} id
1358
2790
  * @returns {Promise<void>}
1359
2791
  */
1360
- async function mountGuest(id) {
2792
+ async function mountGuest(id, seat) {
2793
+ const which = seatOf(seat)
1361
2794
  const provider = findProvider(id)
1362
2795
  if (provider === undefined) return
1363
- const record = guestRecord(id)
2796
+ const record = guestRecord(id, which)
1364
2797
 
1365
2798
  if (record.mounting === true) return
1366
2799
  if (record.element !== undefined && record.element !== null) {
@@ -1369,7 +2802,7 @@ let activeCtx = undefined
1369
2802
  dropGuest(record)
1370
2803
  }
1371
2804
 
1372
- const layer = layerFor(provider)
2805
+ const layer = layerFor(provider, which)
1373
2806
  if (layer === undefined) return
1374
2807
 
1375
2808
  record.mounting = true
@@ -1379,11 +2812,11 @@ let activeCtx = undefined
1379
2812
  try {
1380
2813
  const bridge = desktopBrowser()
1381
2814
  if (bridge === undefined) {
1382
- setPhase(id, PHASE.UNSUPPORTED, '')
2815
+ setPhase(id, PHASE.UNSUPPORTED, '', which)
1383
2816
  return
1384
2817
  }
1385
2818
 
1386
- setPhase(id, PHASE.ACQUIRING, '')
2819
+ setPhase(id, PHASE.ACQUIRING, '', which)
1387
2820
  let lease
1388
2821
  let partition
1389
2822
  try {
@@ -1395,11 +2828,11 @@ let activeCtx = undefined
1395
2828
  throw new Error('desktop shell returned no partition')
1396
2829
  }
1397
2830
  } catch (error) {
1398
- if (generation === record.generation) setPhase(id, PHASE.FAILED, messageOf(error))
2831
+ if (generation === record.generation) setPhase(id, PHASE.FAILED, messageOf(error), which)
1399
2832
  return
1400
2833
  }
1401
2834
 
1402
- log('info', 'lease acquired', { provider: id, partition: shortId(partition) })
2835
+ log('info', 'lease acquired', { provider: id, seat: which, partition: shortId(partition) })
1403
2836
 
1404
2837
  // Teardown or reload happened while the lease was in flight.
1405
2838
  if (generation !== record.generation) {
@@ -1420,12 +2853,13 @@ let activeCtx = undefined
1420
2853
  element.style.cssText = 'display:inline-flex;width:100%;height:100%;border:0;background:transparent;'
1421
2854
 
1422
2855
  const handlers = {
1423
- ready: (event) => onGuestReady(id, event),
1424
- failed: (event) => onGuestFailed(id, event),
1425
- navigate: (event) => onGuestNavigated(id, event !== undefined && event !== null ? event.url : ''),
1426
- navigateInPage: (event) => onGuestLocation(id, event !== undefined && event !== null ? event.url : ''),
1427
- stop: () => onGuestStopped(id),
1428
- crash: () => onGuestCrashed(id),
2856
+ ready: (event) => onGuestReady(id, event, which),
2857
+ failed: (event) => onGuestFailed(id, event, which),
2858
+ navigate: (event) => onGuestNavigated(id, event !== undefined && event !== null ? event.url : '', which),
2859
+ navigateInPage: (event) => onGuestLocation(id, event !== undefined && event !== null ? event.url : '', which),
2860
+ stop: () => onGuestStopped(id, which),
2861
+ crash: () => onGuestCrashed(id, which),
2862
+ importMessage: (event) => onGuestImportMessage(id, event, which),
1429
2863
  }
1430
2864
  element.addEventListener('dom-ready', handlers.ready)
1431
2865
  element.addEventListener('did-fail-load', handlers.failed)
@@ -1434,22 +2868,24 @@ let activeCtx = undefined
1434
2868
  element.addEventListener('did-stop-loading', handlers.stop)
1435
2869
  element.addEventListener('render-process-gone', handlers.crash)
1436
2870
  element.addEventListener('crashed', handlers.crash)
2871
+ element.addEventListener('console-message', handlers.importMessage)
1437
2872
 
1438
2873
  record.element = element
1439
2874
  record.lease = lease
1440
2875
  record.partition = partition
2876
+ record.importNonce = newImportNonce()
1441
2877
  record.navigated = false
1442
2878
  record.handlers = handlers
1443
2879
  record.mounts += 1
1444
2880
  // A mount is a fresh document load. Printing the count makes "one page
1445
2881
  // in the tab" distinguishable from "the tab was rebuilt" in the ring.
1446
- log('info', 'guest mounted', { provider: id, mount: record.mounts })
2882
+ log('info', 'guest mounted', { provider: id, seat: which, mount: record.mounts })
1447
2883
 
1448
2884
  try {
1449
2885
  layer.appendChild(element)
1450
2886
  } catch (error) {
1451
2887
  dropGuest(record)
1452
- setPhase(id, PHASE.FAILED, messageOf(error))
2888
+ setPhase(id, PHASE.FAILED, messageOf(error), which)
1453
2889
  return
1454
2890
  }
1455
2891
 
@@ -1457,12 +2893,12 @@ let activeCtx = undefined
1457
2893
  // so a reload or teardown cannot leave a listener behind.
1458
2894
  if (typeof bridge.onOpenRequested === 'function') {
1459
2895
  try {
1460
- record.popupOff = bridge.onOpenRequested(lease, (url) => onGuestPopup(id, url))
2896
+ record.popupOff = bridge.onOpenRequested(lease, (url) => onGuestPopup(id, url, which))
1461
2897
  } catch (error) {
1462
2898
  record.popupOff = undefined
1463
2899
  }
1464
2900
  }
1465
- setPhase(id, PHASE.NAVIGATING, '')
2901
+ setPhase(id, PHASE.NAVIGATING, '', which)
1466
2902
  } finally {
1467
2903
  record.mounting = false
1468
2904
  syncLayers()
@@ -1480,11 +2916,12 @@ let activeCtx = undefined
1480
2916
  * @param {any} element
1481
2917
  * @returns {Promise<void>}
1482
2918
  */
1483
- async function navigateGuest(id, element) {
2919
+ async function navigateGuest(id, element, seat) {
2920
+ const which = seatOf(seat)
1484
2921
  const provider = findProvider(id)
1485
2922
  if (provider === undefined) return
1486
- const record = guestRecord(id)
1487
- const target = startUrlFor(provider)
2923
+ const record = guestRecord(id, which)
2924
+ const target = startUrlFor(provider, which)
1488
2925
  const deadline = Date.now() + NAVIGATE_TIMEOUT_MS
1489
2926
  let issued = 0
1490
2927
 
@@ -1492,8 +2929,8 @@ let activeCtx = undefined
1492
2929
  if (element !== record.element) return
1493
2930
  const landed = guestUrl(element)
1494
2931
  if (isLiveUrl(landed)) {
1495
- if (landed !== '') lastUrls.set(id, landed)
1496
- setPhase(id, PHASE.READY, '')
2932
+ if (landed !== '') lastUrls.set(which + ':' + id, landed)
2933
+ setPhase(id, PHASE.READY, '', which)
1497
2934
  return
1498
2935
  }
1499
2936
  const loading = guestLoading(element)
@@ -1514,34 +2951,34 @@ let activeCtx = undefined
1514
2951
  await delay(NAVIGATE_RETRY_MS)
1515
2952
  }
1516
2953
  if (element !== record.element) return
1517
- setPhase(id, PHASE.FAILED, 'navigation-timeout')
2954
+ setPhase(id, PHASE.FAILED, 'navigation-timeout', which)
1518
2955
  }
1519
2956
 
1520
2957
  /**
1521
2958
  * @param {string} id
1522
2959
  * @param {any} event
1523
2960
  */
1524
- function onGuestReady(id, event) {
1525
- const record = guestRecord(id)
2961
+ function onGuestReady(id, event, seat) {
2962
+ const record = guestRecord(id, seat)
1526
2963
  const element =
1527
2964
  event !== undefined && event !== null && event.currentTarget !== undefined ? event.currentTarget : record.element
1528
2965
  if (element === undefined || element !== record.element) return
1529
2966
  if (record.navigated) return
1530
2967
  record.navigated = true
1531
- void navigateGuest(id, element)
2968
+ void navigateGuest(id, element, seat)
1532
2969
  }
1533
2970
 
1534
2971
  /**
1535
2972
  * @param {string} id
1536
2973
  * @param {any} event
1537
2974
  */
1538
- function onGuestFailed(id, event) {
1539
- const record = guestRecord(id)
2975
+ function onGuestFailed(id, event, seat) {
2976
+ const record = guestRecord(id, seat)
1540
2977
  const element =
1541
2978
  event !== undefined && event !== null && event.currentTarget !== undefined ? event.currentTarget : record.element
1542
2979
  if (element === undefined || element !== record.element) return
1543
2980
  if (event !== undefined && event !== null && event.errorCode === -3) return
1544
- setPhase(id, PHASE.FAILED, 'load-failed')
2981
+ setPhase(id, PHASE.FAILED, 'load-failed', seat)
1545
2982
  log('warn', 'guest failed to load', { provider: id })
1546
2983
  }
1547
2984
 
@@ -1551,11 +2988,11 @@ let activeCtx = undefined
1551
2988
  * @param {string} id
1552
2989
  * @param {string} url
1553
2990
  */
1554
- function onGuestLocation(id, url) {
1555
- const record = guestRecord(id)
2991
+ function onGuestLocation(id, url, seat) {
2992
+ const record = guestRecord(id, seat)
1556
2993
  if (typeof url === 'string' && url !== '') {
1557
2994
  record.lastUrl = url
1558
- lastUrls.set(id, url)
2995
+ lastUrls.set(seatOf(seat) + ':' + id, url)
1559
2996
  }
1560
2997
  }
1561
2998
 
@@ -1600,13 +3037,13 @@ let activeCtx = undefined
1600
3037
  *
1601
3038
  * @param {string} id
1602
3039
  */
1603
- function onGuestStopped(id) {
1604
- const record = guestRecord(id)
3040
+ function onGuestStopped(id, seat) {
3041
+ const record = guestRecord(id, seat)
1605
3042
  const element = record.element
1606
3043
  if (element === undefined || element === null) return
1607
3044
  const url = guestUrl(element)
1608
3045
  record.lastUrl = url
1609
- if (typeof url === 'string' && url !== '' && isLiveUrl(url)) lastUrls.set(id, url)
3046
+ if (typeof url === 'string' && url !== '' && isLiveUrl(url)) lastUrls.set(seatOf(seat) + ':' + id, url)
1610
3047
  record.lastEvent = 'did-stop-loading'
1611
3048
 
1612
3049
  // Google's popup-handoff page cannot finish without an opener: return to
@@ -1630,13 +3067,16 @@ let activeCtx = undefined
1630
3067
  record.reloadTimer = setTimeout(() => {
1631
3068
  record.reloadTimer = undefined
1632
3069
  if (record.element !== element) return
1633
- void reloadGuest(id)
3070
+ void reloadGuest(id, seat)
1634
3071
  }, TIMINGS.oauthRecoveryReloadMs)
1635
3072
  return
1636
3073
  }
1637
3074
 
1638
3075
  // The initial `about:blank#<lease>` load is blank by design.
1639
3076
  if (url.indexOf('about:') === 0) return
3077
+ // A finished load is a fresh document: (re)arm the bubble and the menu.
3078
+ installImportGuest(record, element)
3079
+ installContextMenu(record, element)
1640
3080
  notify()
1641
3081
  }
1642
3082
 
@@ -1645,10 +3085,10 @@ let activeCtx = undefined
1645
3085
  *
1646
3086
  * @param {string} id
1647
3087
  */
1648
- function onGuestCrashed(id) {
1649
- const record = guestRecord(id)
3088
+ function onGuestCrashed(id, seat) {
3089
+ const record = guestRecord(id, seat)
1650
3090
  if (record.element === undefined || record.element === null) return
1651
- setPhase(id, PHASE.FAILED, 'renderer-gone')
3091
+ setPhase(id, PHASE.FAILED, 'renderer-gone', seat)
1652
3092
  record.lastEvent = 'renderer-gone'
1653
3093
  log('error', 'renderer gone', { provider: id })
1654
3094
  notify()
@@ -1665,12 +3105,29 @@ let activeCtx = undefined
1665
3105
  * @param {string} id
1666
3106
  * @param {string} url
1667
3107
  */
1668
- function onGuestPopup(id, url) {
1669
- const record = guestRecord(id)
3108
+ function onGuestPopup(id, url, seat) {
3109
+ const record = guestRecord(id, seat)
1670
3110
  const element = record.element
1671
3111
  if (element === undefined || element === null) return
1672
3112
  if (typeof url !== 'string' || url.indexOf('https://') !== 0) return
1673
3113
 
3114
+ // A push from the selection bubble: the shell relays window.open requests
3115
+ // here. Handled before the OAuth checks — this URL is not a sign-in hop.
3116
+ const pushed = parsePushUrl(url)
3117
+ if (pushed !== undefined) {
3118
+ if (pushed.nonce !== record.importNonce) {
3119
+ record.lastEvent = 'import-push stale-nonce'
3120
+ notify()
3121
+ return
3122
+ }
3123
+ if (pushed.action === 'lastRound' || pushed.action === 'conversation') {
3124
+ receiveAction(record, pushed.action, seat)
3125
+ return
3126
+ }
3127
+ receivePush(record, findProvider(id), pushed.text, 'popup')
3128
+ return
3129
+ }
3130
+
1674
3131
  // Google/Apple complete sign-in but their callback page cannot finish in
1675
3132
  // an embedded WebContents, so arm the dead-end tracking from here.
1676
3133
  if (isOAuthUrl(url)) {
@@ -1692,8 +3149,8 @@ let activeCtx = undefined
1692
3149
  * @param {string} id
1693
3150
  * @param {string} url
1694
3151
  */
1695
- function onGuestNavigated(id, url) {
1696
- const record = guestRecord(id)
3152
+ function onGuestNavigated(id, url, seat) {
3153
+ const record = guestRecord(id, seat)
1697
3154
  const provider = findProvider(id)
1698
3155
  if (provider === undefined) return
1699
3156
  const host = hostOf(url)
@@ -1710,7 +3167,7 @@ let activeCtx = undefined
1710
3167
  if (record.oauthPending !== true) return
1711
3168
  if (host !== hostOf(provider.origin)) return
1712
3169
  record.oauthPending = false
1713
- scheduleOAuthRecovery(id, provider)
3170
+ scheduleOAuthRecovery(id, provider, seat)
1714
3171
  }
1715
3172
 
1716
3173
  /** @param {GuestRecord} record */
@@ -1751,8 +3208,8 @@ let activeCtx = undefined
1751
3208
  * @param {string} id
1752
3209
  * @param {object} provider
1753
3210
  */
1754
- function scheduleOAuthRecovery(id, provider) {
1755
- const record = guestRecord(id)
3211
+ function scheduleOAuthRecovery(id, provider, seat) {
3212
+ const record = guestRecord(id, seat)
1756
3213
  clearRecoveryTimer(record)
1757
3214
 
1758
3215
  record.recoveryTimer = setTimeout(() => {
@@ -1799,21 +3256,23 @@ let activeCtx = undefined
1799
3256
  * @param {string} id
1800
3257
  * @returns {Promise<void>}
1801
3258
  */
1802
- async function reloadGuest(id) {
1803
- const record = guestRecord(id)
1804
- log('info', 'reload requested', { provider: id })
3259
+ async function reloadGuest(id, seat) {
3260
+ const which = seatOf(seat)
3261
+ const record = guestRecord(id, which)
3262
+ log('info', 'reload requested', { provider: id, seat: which })
1805
3263
  record.generation += 1
1806
3264
  dropGuest(record)
1807
- setPhase(id, PHASE.IDLE, '')
1808
- await mountGuest(id)
3265
+ setPhase(id, PHASE.IDLE, '', which)
3266
+ await mountGuest(id, which)
1809
3267
  }
1810
3268
  /** Release every guest; used on plugin unload. */
1811
3269
  /** @param {string} [reason] */
1812
3270
  function destroyGuests(reason) {
1813
- for (const [id, record] of guests) {
3271
+ for (const record of guests.values()) {
1814
3272
  record.generation += 1
1815
3273
  dropGuest(record, reason)
1816
- setPhase(id, PHASE.IDLE, '')
3274
+ record.phase = PHASE.IDLE
3275
+ record.detail = ''
1817
3276
  if (record.layer !== undefined && record.layer !== null) {
1818
3277
  try {
1819
3278
  if (record.layer.parentNode !== null && record.layer.parentNode !== undefined) {
@@ -1825,6 +3284,8 @@ let activeCtx = undefined
1825
3284
  record.layer = undefined
1826
3285
  }
1827
3286
  }
3287
+ discardPark()
3288
+ notify()
1828
3289
  }
1829
3290
 
1830
3291
  /** @param {{left:number,top:number,width:number,height:number}} rect @returns {string} */
@@ -1888,15 +3349,18 @@ let activeCtx = undefined
1888
3349
  */
1889
3350
  /**
1890
3351
  * A guest element cannot move between hosts (Electron destroys the
1891
- * WebContents with its DOM), so guests that are not inside the new host are
1892
- * dropped and rebuilt there.
3352
+ * WebContents with its DOM). Used only when the persistent park is absent
3353
+ * (tests, or a shell frame we could not find): guests that are not inside
3354
+ * the new host are dropped and rebuilt there. With a park, guests stay put
3355
+ * and the park is shown or hidden instead.
1893
3356
  *
1894
3357
  * @param {any} host
1895
3358
  */
1896
- function dropGuestsOutside(host) {
1897
- for (const provider of PROVIDERS) {
1898
- const record = guests.get(provider.id)
1899
- if (record === undefined || record.element === undefined || record.element === null) continue
3359
+ function dropGuestsOutside(host, seat) {
3360
+ const which = seatOf(seat)
3361
+ for (const record of guests.values()) {
3362
+ if (record.seat !== which) continue
3363
+ if (record.element === undefined || record.element === null) continue
1900
3364
  const element = record.element
1901
3365
  const inside = typeof host.contains === 'function' ? host.contains(element) : false
1902
3366
  if (inside) continue
@@ -1925,17 +3389,308 @@ let activeCtx = undefined
1925
3389
  if (patch !== undefined && patch !== null && patch.host !== undefined) setHost(patch.host)
1926
3390
  }
1927
3391
 
3392
+ /**
3393
+ * Guest park. Created once, appended to `document.body`, never moved.
3394
+ * `hidden` keeps the webview in the document — the same trick the shell
3395
+ * uses for a keepMounted tab — so coming back is a reveal, not a reload.
3396
+ *
3397
+ * @type {any}
3398
+ */
3399
+ let parkNode = undefined
3400
+ /** @type {'main' | 'right' | 'stowed'} */
3401
+ let parkMode = 'stowed'
3402
+ /** @type {any} */
3403
+ let anchorNode = undefined
3404
+
3405
+ /** @param {any} node @returns {any[]} */
3406
+ function childElements(node) {
3407
+ if (node === null || node === undefined) return []
3408
+ if (Array.isArray(node.children)) return node.children
3409
+ if (typeof node.children === 'object' && node.children !== null && typeof node.children.length === 'number') {
3410
+ try {
3411
+ return Array.from(node.children)
3412
+ } catch (error) {
3413
+ void error
3414
+ }
3415
+ }
3416
+ return []
3417
+ }
3418
+
3419
+ /**
3420
+ * @param {any} root
3421
+ * @param {string} name
3422
+ * @returns {any}
3423
+ */
3424
+ function findByAttribute(root, name) {
3425
+ if (root === null || root === undefined) return undefined
3426
+ if (typeof root.querySelector === 'function') {
3427
+ try {
3428
+ const hit = root.querySelector('[' + name + ']')
3429
+ if (hit !== null && hit !== undefined) return hit
3430
+ } catch (error) {
3431
+ void error
3432
+ }
3433
+ }
3434
+ const stack = childElements(root).slice()
3435
+ while (stack.length > 0) {
3436
+ const node = stack.pop()
3437
+ if (node !== undefined && node !== null && typeof node.hasAttribute === 'function' && node.hasAttribute(name)) {
3438
+ return node
3439
+ }
3440
+ const kids = childElements(node)
3441
+ for (let index = kids.length - 1; index >= 0; index -= 1) stack.push(kids[index])
3442
+ }
3443
+ return undefined
3444
+ }
3445
+
3446
+ /**
3447
+ * The shell frame is present when the right column marker exists. Without
3448
+ * it (the contract tests, a page that is not the desktop shell) there is
3449
+ * no stable park, and guests stay in the seat viewport.
3450
+ *
3451
+ * @returns {boolean}
3452
+ */
3453
+ function shellFramePresent() {
3454
+ const root = typeof document !== 'undefined' && document !== null ? document.body : undefined
3455
+ return findByAttribute(root, 'data-rightbar-col') !== undefined
3456
+ }
3457
+
3458
+ /** @returns {boolean} */
3459
+ function anchorReady() {
3460
+ try {
3461
+ return (
3462
+ typeof CSS !== 'undefined' &&
3463
+ CSS !== null &&
3464
+ typeof CSS.supports === 'function' &&
3465
+ CSS.supports('anchor-name: --dce')
3466
+ )
3467
+ } catch (error) {
3468
+ void error
3469
+ return false
3470
+ }
3471
+ }
3472
+
3473
+ /** @returns {boolean} */
3474
+ function parkIsLive() {
3475
+ return parkNode !== undefined && parkNode !== null && parkNode.isConnected !== false
3476
+ }
3477
+
3478
+ /**
3479
+ * @returns {any} the park element, or undefined when this page has no shell frame
3480
+ */
3481
+ /**
3482
+ * Parent that outlives panel switches and is not a grid item of the frame.
3483
+ *
3484
+ * The frame is `display:grid`. An extra child there — even `position:fixed`
3485
+ * — is still a grid item in this shell and steals a track, which is why the
3486
+ * right column then refuses to open. `document.body` is outside that grid.
3487
+ * The corner radius is copied from the frame when the park is shown.
3488
+ *
3489
+ * @returns {any}
3490
+ */
3491
+ function parkParent() {
3492
+ return document.body
3493
+ }
3494
+
3495
+ function ensurePark() {
3496
+ if (shellFramePresent() !== true) return undefined
3497
+ if (parkIsLive() === true) return parkNode
3498
+ const parent = parkParent()
3499
+ if (parent === null || parent === undefined) return undefined
3500
+ const node = document.createElement('div')
3501
+ node.className = 'dce-park'
3502
+ node.setAttribute('data-dce-park', 'true')
3503
+ node.setAttribute('hidden', '')
3504
+ parent.appendChild(node)
3505
+ parkNode = node
3506
+ parkMode = 'stowed'
3507
+ return node
3508
+ }
3509
+
3510
+ function clearAnchor() {
3511
+ if (anchorNode !== undefined && anchorNode !== null && typeof anchorNode.removeAttribute === 'function') {
3512
+ try {
3513
+ anchorNode.removeAttribute('data-dce-anchor')
3514
+ } catch (error) {
3515
+ void error
3516
+ }
3517
+ }
3518
+ anchorNode = undefined
3519
+ }
3520
+
3521
+ function stowPark() {
3522
+ if (parkNode === undefined || parkNode === null) return
3523
+ clearAnchor()
3524
+ parkNode.setAttribute('hidden', '')
3525
+ parkNode.setAttribute('data-mode', 'stowed')
3526
+ // A fixed box with no anchor falls back to covering the window and eats
3527
+ // the right-sidebar expand button. Zero the box, don't just rely on hidden.
3528
+ if (parkNode.style !== undefined && parkNode.style !== null) {
3529
+ parkNode.style.cssText = 'position:fixed;width:0;height:0;pointer-events:none'
3530
+ }
3531
+ if (parkMode !== 'stowed') {
3532
+ log('info', 'guests stowed', { reason: 'seat hidden' })
3533
+ parkMode = 'stowed'
3534
+ }
3535
+ }
3536
+
3537
+ /**
3538
+ * Show the park over the seat the user is looking at. The element itself
3539
+ * does not move; only its CSS box does.
3540
+ *
3541
+ * @param {'main' | 'right'} seat
3542
+ * @param {any} chosen
3543
+ * @param {any} park
3544
+ */
3545
+ /**
3546
+ * @param {any} chosen
3547
+ * @returns {{ left: number, top: number, width: number, height: number } | undefined}
3548
+ */
3549
+ function seatBox(chosen) {
3550
+ if (chosen === null || chosen === undefined || typeof chosen.getBoundingClientRect !== 'function') return undefined
3551
+ const box = chosen.getBoundingClientRect()
3552
+ if (box === undefined || box === null) return undefined
3553
+ return {
3554
+ left: box.left,
3555
+ top: box.top,
3556
+ width: box.width,
3557
+ height: box.height,
3558
+ }
3559
+ }
3560
+
3561
+ function revealPark(seat, chosen, park) {
3562
+ const box = seatBox(chosen)
3563
+ // A closed right column is 0×0. Showing the park then either covers the
3564
+ // expand button or hides the page the user is still looking at.
3565
+ if (box === undefined || box.width < 2 || box.height < 2) {
3566
+ stowPark()
3567
+ return
3568
+ }
3569
+ clearAnchor()
3570
+ park.removeAttribute('hidden')
3571
+ park.setAttribute('data-mode', seat)
3572
+ if (typeof chosen.setAttribute === 'function') {
3573
+ chosen.setAttribute('data-dce-anchor', 'true')
3574
+ anchorNode = chosen
3575
+ }
3576
+ // Always pin a real box. CSS anchor tracks a splitter with no JS, but an
3577
+ // unanchored fixed element covers the window — that is what made the
3578
+ // right sidebar's expand button unclickable. Inline pixels are the floor;
3579
+ // anchor overrides them only where the seat actually has a box.
3580
+ const radius = seat === 'main' ? contentRadius() : '0'
3581
+ if (park.style !== undefined && park.style !== null) {
3582
+ park.style.cssText =
3583
+ 'position:fixed;z-index:1;pointer-events:auto;margin:0;top:' +
3584
+ box.top +
3585
+ 'px;left:' +
3586
+ box.left +
3587
+ 'px;width:' +
3588
+ box.width +
3589
+ 'px;height:' +
3590
+ box.height +
3591
+ 'px;border-radius:' +
3592
+ radius +
3593
+ ' 0 0 0'
3594
+ }
3595
+ parkMode = seat
3596
+ }
3597
+
3598
+ /** @returns {string} */
3599
+ function contentRadius() {
3600
+ try {
3601
+ if (typeof getComputedStyle !== 'function') return '0'
3602
+ const overlay = typeof document.querySelector === 'function' ? document.querySelector('[data-shell-overlay]') : null
3603
+ const host =
3604
+ overlay !== null && overlay !== undefined && overlay.parentElement !== null && overlay.parentElement !== undefined
3605
+ ? overlay.parentElement
3606
+ : document.documentElement
3607
+ if (host === null || host === undefined) return '0'
3608
+ const value = getComputedStyle(host).getPropertyValue('--dsh-windows-content-radius')
3609
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : '0'
3610
+ } catch (error) {
3611
+ void error
3612
+ return '0'
3613
+ }
3614
+ }
3615
+
3616
+ /**
3617
+ * @param {string | undefined} seat
3618
+ * @param {any} chosen
3619
+ * @returns {boolean | 'stowed'} true when the park is the guest home and showing
3620
+ */
3621
+ function placePark(seat, chosen) {
3622
+ // The park is the left page only. A right column, a collapsed column, or
3623
+ // the conversation must never receive this box.
3624
+ if (seat !== 'main' || chosen === null || chosen === undefined || hostArea(chosen) < 2) {
3625
+ const live = parkIsLive()
3626
+ stowPark()
3627
+ return live === true ? 'stowed' : false
3628
+ }
3629
+ const park = ensurePark()
3630
+ if (park === undefined) return false
3631
+ revealPark('main', chosen, park)
3632
+ return true
3633
+ }
3634
+
3635
+ function discardPark() {
3636
+ clearAnchor()
3637
+ const node = parkNode
3638
+ parkNode = undefined
3639
+ parkMode = 'stowed'
3640
+ if (node === undefined || node === null) return
3641
+ try {
3642
+ if (node.parentNode !== null && node.parentNode !== undefined) node.parentNode.removeChild(node)
3643
+ } catch (error) {
3644
+ void error
3645
+ }
3646
+ }
3647
+
1928
3648
  function resolveInlineHost() {
1929
- const seat = inlineSeat()
1930
- const chosen = seat === undefined ? null : inlineHosts[seat]
1931
- if (chosen !== state.surface.host) log('info', 'host resolved', { seat: seat === undefined ? 'none' : seat })
1932
- setHost(chosen)
1933
- if (chosen === null) destroyGuests('no viewport')
1934
- else {
1935
- dropGuestsOutside(chosen)
1936
- void ensureActiveGuest()
3649
+ const main = inlineHosts.main
3650
+ const visible = main !== null && main !== undefined && hostArea(main) >= 2
3651
+ if (visible) {
3652
+ const parked = placePark('main', main)
3653
+ setHost(main)
3654
+ if (parked !== true && parkIsLive() !== true) dropGuestsOutside(main, 'main')
3655
+ void ensureActiveGuest('main')
3656
+ } else {
3657
+ stowPark()
3658
+ setHost(null)
3659
+ // The left page stays in the park. Destroying it here is 「正在打开」
3660
+ // on the way back. Without a park there is nothing to hide.
3661
+ if (parkIsLive() !== true) destroySeat('main', 'no viewport')
3662
+ }
3663
+ const right = inlineHosts.right
3664
+ if (right !== null && right !== undefined && hostArea(right) >= 2) void ensureActiveGuest('right')
3665
+ return visible ? main : null
3666
+ }
3667
+
3668
+ /**
3669
+ * Drop one seat's guests. The other seat keeps its own page.
3670
+ *
3671
+ * @param {'main' | 'right'} seat
3672
+ * @param {string} [reason]
3673
+ */
3674
+ function destroySeat(seat, reason) {
3675
+ const which = seatOf(seat)
3676
+ for (const record of guests.values()) {
3677
+ if (record.seat !== which) continue
3678
+ record.generation += 1
3679
+ dropGuest(record, reason)
3680
+ record.phase = PHASE.IDLE
3681
+ record.detail = ''
3682
+ if (record.layer !== undefined && record.layer !== null) {
3683
+ try {
3684
+ if (record.layer.parentNode !== null && record.layer.parentNode !== undefined) {
3685
+ record.layer.parentNode.removeChild(record.layer)
3686
+ }
3687
+ } catch (error) {
3688
+ void error
3689
+ }
3690
+ record.layer = undefined
3691
+ }
1937
3692
  }
1938
- return chosen
3693
+ notify()
1939
3694
  }
1940
3695
 
1941
3696
  /** @param {'main' | 'right'} seat @returns {boolean} */
@@ -1980,7 +3735,9 @@ let activeCtx = undefined
1980
3735
  const zeroSized = hostArea(host) <= 0
1981
3736
  if (!zeroSized || (chosen && seat === 'main')) return seat
1982
3737
  }
1983
- return hidden
3738
+ // A collapsed right tab stays mounted at 0×0. Treating it as the seat
3739
+ // stows the page and never gives the column a chance to open.
3740
+ return hidden !== undefined && hostArea(inlineHosts[hidden]) > 0 ? hidden : undefined
1984
3741
  }
1985
3742
 
1986
3743
  /**
@@ -2015,10 +3772,21 @@ let activeCtx = undefined
2015
3772
 
2016
3773
  function openRightTab() {
2017
3774
  try {
2018
- openRightTabImpl()
3775
+ // The right column belongs to the conversation. A global panel (this
3776
+ // chat page included) unmounts that surface, and openTab then throws
3777
+ // "no session surface" — the click looks like the sidebar will not open.
3778
+ const layout = activeCtx !== undefined && typeof activeCtx.get === 'function' ? activeCtx.get('layout') : undefined
3779
+ if (layout !== undefined && layout !== null && typeof layout.selectPanel === 'function') {
3780
+ layout.selectPanel(null)
3781
+ }
2019
3782
  } catch (error) {
2020
3783
  void error
2021
3784
  }
3785
+ try {
3786
+ openRightTabImpl()
3787
+ } catch (error) {
3788
+ log('warn', 'right sidebar did not open', { detail: messageOf(error) })
3789
+ }
2022
3790
  }
2023
3791
 
2024
3792
  /** @returns {string} a live self-test of the hosting seat and its box. */
@@ -2057,12 +3825,13 @@ let activeCtx = undefined
2057
3825
  host: rect(host === undefined || host === null ? undefined : host.getBoundingClientRect()),
2058
3826
  visible: true,
2059
3827
  guest: (() => {
2060
- if (host === undefined || host === null || typeof host.querySelectorAll !== 'function') {
2061
- return { present: false, reason: 'no inline host' }
3828
+ const probe = parkIsLive() === true ? parkNode : host
3829
+ if (probe === undefined || probe === null || typeof probe.querySelectorAll !== 'function') {
3830
+ return { present: false, reason: parkIsLive() === true ? 'park has no query' : 'no inline host' }
2062
3831
  }
2063
- const webviews = host.querySelectorAll('webview')
2064
- const layers = host.querySelectorAll('.dce-guest-layer')
2065
- const active = host.querySelectorAll('.dce-guest-layer[data-active="true"]')
3832
+ const webviews = probe.querySelectorAll('webview')
3833
+ const layers = probe.querySelectorAll('.dce-guest-layer')
3834
+ const active = probe.querySelectorAll('.dce-guest-layer[data-active="true"]')
2066
3835
  const inner = document.querySelector('.dce-inline')
2067
3836
  return {
2068
3837
  present: webviews.length > 0,
@@ -2070,7 +3839,11 @@ let activeCtx = undefined
2070
3839
  layers: layers.length,
2071
3840
  active: active.length,
2072
3841
  surfaceMounted: inner !== null && inner !== undefined,
2073
- hostBox: rect(host.getBoundingClientRect()),
3842
+ hostBox: rect(
3843
+ host === undefined || host === null || typeof host.getBoundingClientRect !== 'function'
3844
+ ? undefined
3845
+ : host.getBoundingClientRect(),
3846
+ ),
2074
3847
  }
2075
3848
  })(),
2076
3849
  right: rightSidebarStatus(),
@@ -2498,9 +4271,8 @@ let activeCtx = undefined
2498
4271
 
2499
4272
  /** @returns {'on' | 'off' | 'unknown'} what the mounted guests actually received */
2500
4273
  function livePartitionState() {
2501
- for (const provider of PROVIDERS) {
2502
- const record = guests.get(provider.id)
2503
- if (record === undefined || typeof record.partition !== 'string' || record.partition === '') continue
4274
+ for (const record of guests.values()) {
4275
+ if (typeof record.partition !== 'string' || record.partition === '') continue
2504
4276
  return record.partition.startsWith('persist:') ? 'on' : 'off'
2505
4277
  }
2506
4278
  return 'unknown'
@@ -2911,18 +4683,19 @@ let activeCtx = undefined
2911
4683
  *
2912
4684
  * @returns {Promise<void>}
2913
4685
  */
2914
- function ensureActiveGuest() {
2915
- const provider = activeProvider()
2916
- const record = guestRecord(provider.id)
4686
+ function ensureActiveGuest(seat) {
4687
+ const which = seatOf(seat)
4688
+ const provider = activeProvider(which)
4689
+ const record = guestRecord(provider.id, which)
2917
4690
  // A guest whose element was detached with its seat is gone (Electron drops
2918
4691
  // the WebContents with the DOM), so a live element is the only reason to
2919
4692
  // skip the rebuild.
2920
4693
  const element = record.element
2921
4694
  if (element !== undefined && element !== null && element.isConnected !== false) return Promise.resolve()
2922
4695
  if (record.mounting === true) return Promise.resolve()
2923
- // The host viewport inside the panel's layout is the only requirement.
2924
- if (state.surface.host === null || state.surface.host === undefined) return Promise.resolve()
2925
- return mountGuest(provider.id)
4696
+ const home = guestHome(which)
4697
+ if (home === null || home === undefined) return Promise.resolve()
4698
+ return mountGuest(provider.id, which)
2926
4699
  }
2927
4700
 
2928
4701
  /**
@@ -2932,17 +4705,17 @@ let activeCtx = undefined
2932
4705
  * @param {string} id
2933
4706
  * @returns {Promise<void>}
2934
4707
  */
2935
- function setActive(id) {
4708
+ function setActive(id, seat) {
4709
+ const which = seatOf(seat)
2936
4710
  const provider = findProvider(id)
2937
4711
  if (provider === undefined) return Promise.resolve()
2938
4712
  if (!isEnabled(provider.id)) return Promise.resolve()
2939
- if (state.active !== provider.id) {
2940
- state.active = provider.id
2941
- storeActive(provider.id)
2942
- syncLayers()
4713
+ if (activeBySeat[which] !== provider.id) {
4714
+ assignSeatActive(which, provider.id)
4715
+ syncLayers(which)
2943
4716
  }
2944
4717
  notify()
2945
- return ensureActiveGuest()
4718
+ return ensureActiveGuest(which)
2946
4719
  }
2947
4720
 
2948
4721
  // ------------------------------------------------------------------
@@ -2979,6 +4752,7 @@ let activeCtx = undefined
2979
4752
  '.dce-icon-button[data-on="true"]{color:var(--dsw-alias-label-accent,#4c7dff);background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.14))}',
2980
4753
  '.dce-icon-button:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}',
2981
4754
  '.dce-icon-button:focus-visible{outline:2px solid var(--dsw-alias-button-primary-fill,#4c6ef5);outline-offset:-2px}',
4755
+ '.dce-import-notice{position:absolute;left:50%;bottom:14px;transform:translateX(-50%);z-index:6;max-width:80%;padding:6px 12px;border-radius:8px;background:var(--dsw-alias-label-primary,#202124);color:var(--dsw-alias-bg-primary,#fff);font-size:12px;line-height:1.5;box-shadow:0 2px 10px rgba(0,0,0,.35);pointer-events:none}',
2982
4756
  '.dce-status-bar{position:absolute;top:0;left:0;right:0;z-index:2;display:flex;align-items:center;gap:8px;box-sizing:border-box;padding:4px 10px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.18));background:var(--dsw-alias-bg-base,#fff);font-size:12px}',
2983
4757
  // A pending patch keeps the tab bar pinned open, and the tab bar sits on
2984
4758
  // the same top edge with a higher z-index — so the strip has to move below
@@ -2998,6 +4772,19 @@ let activeCtx = undefined
2998
4772
  '.dce-button-primary{border-color:currentColor;color:var(--dsw-alias-button-primary-fill,#4c6ef5)}',
2999
4773
  '.dce-surface{position:absolute;inset:0;display:flex;min-height:0}',
3000
4774
  '.dce-viewport{position:absolute;inset:0;display:flex;min-width:0;min-height:0}',
4775
+ // The park outlives the panel. Anchor paints it over the seat that is
4776
+ // showing; `hidden` keeps the webview in the document. Chrome stays in
4777
+ // the seat (z-index 2) and the page area does not eat pointer events, so
4778
+ // the webview under it still receives them.
4779
+ '.dce-park{position:fixed;z-index:1;display:flex;min-width:0;min-height:0;overflow:hidden;pointer-events:auto;background:var(--dsw-alias-bg-base,#fff)}',
4780
+ '.dce-park[hidden]{display:none !important}',
4781
+ '.dce-park[data-mode="main"]{border-radius:var(--dsh-windows-content-radius,0) 0 0 0}',
4782
+ '.dce-park[data-mode="main"],.dce-park[data-mode="right"]{position:fixed;position-anchor:--dce-guest-seat;top:anchor(top);left:anchor(left);width:anchor(width);height:anchor(height);margin:0}',
4783
+ '.dce-viewport[data-dce-anchor="true"]{anchor-name:--dce-guest-seat}',
4784
+ '.dce-inline[data-parked="true"]{background:transparent;z-index:2;pointer-events:none}',
4785
+ '.dce-inline[data-parked="true"]>.dce-panel{background:transparent}',
4786
+ '.dce-inline[data-parked="true"] .dce-surface,.dce-inline[data-parked="true"] .dce-viewport{pointer-events:none;background:transparent}',
4787
+ '.dce-inline[data-parked="true"] .dce-hotzone,.dce-inline[data-parked="true"] .dce-tabs,.dce-inline[data-parked="true"] .dce-status-bar,.dce-inline[data-parked="true"] .dce-menu,.dce-inline[data-parked="true"] .dce-menu-scrim,.dce-inline[data-parked="true"] .dce-card,.dce-inline[data-parked="true"] .dce-confirm-scrim{pointer-events:auto}',
3001
4788
  '.dce-guest-layer{position:absolute;inset:0;display:none;min-width:0;min-height:0}',
3002
4789
  '.dce-guest-layer[data-active="true"]{display:flex}',
3003
4790
  '.dce-guest{display:inline-flex;flex:1 1 auto;width:100%;height:100%;border:0;background:transparent}',
@@ -3098,8 +4885,9 @@ let activeCtx = undefined
3098
4885
  * @param {(key: string) => string} t
3099
4886
  * @param {{ phase: string, detail: string }} snapshot
3100
4887
  * @param {() => void} [onRetry]
4888
+ * @param {string} [url]
3101
4889
  */
3102
- function hintCard(title, body, t, snapshot, onRetry) {
4890
+ function hintCard(title, body, t, snapshot, onRetry, url) {
3103
4891
  return h(
3104
4892
  'div',
3105
4893
  { className: 'dce-card', role: 'status' },
@@ -3112,15 +4900,16 @@ let activeCtx = undefined
3112
4900
  onRetry === undefined
3113
4901
  ? null
3114
4902
  : h('button', { type: 'button', className: 'dce-button dce-button-primary', onClick: onRetry }, t('retry')),
3115
- h('button', { type: 'button', className: 'dce-button', onClick: openInBrowser }, t('openInBrowser')),
4903
+ h('button', { type: 'button', className: 'dce-button', onClick: () => openInBrowser(url) }, t('openInBrowser')),
3116
4904
  ),
3117
4905
  )
3118
4906
  }
3119
4907
 
3120
4908
  /** Open the active service in the system browser. */
3121
- function openInBrowser() {
4909
+ function openInBrowser(url) {
4910
+ const target = typeof url === 'string' && url !== '' ? url : activeProvider().url
3122
4911
  try {
3123
- window.open(activeProvider().url, '_blank', 'noopener,noreferrer')
4912
+ window.open(target, '_blank', 'noopener,noreferrer')
3124
4913
  } catch (error) {
3125
4914
  void error
3126
4915
  }
@@ -3247,9 +5036,9 @@ let activeCtx = undefined
3247
5036
  /**
3248
5037
  * The left-navigation page: the chat itself, hosted by the center panel.
3249
5038
  *
3250
- * The center panel is torn down whenever another panel is selected, so this
3251
- * seat is suitable while the user keeps the chat open; the right tab (below)
3252
- * is the seat that survives panel switches.
5039
+ * The center panel is torn down whenever another panel is selected. The
5040
+ * guests do not live in this component — they live in the park — so coming
5041
+ * back shows the same page instead of navigating again.
3253
5042
  */
3254
5043
  function ChatCenterPage() {
3255
5044
  return h(ChatSurface, { seat: 'main' })
@@ -3258,8 +5047,8 @@ let activeCtx = undefined
3258
5047
  /** The right sidebar tab's chip title. */
3259
5048
  function ChatRightTitle() {
3260
5049
  useStore()
3261
- const provider = activeProvider()
3262
- const phase = getStatus().phase
5050
+ const provider = activeProvider('right')
5051
+ const phase = getStatus('right').phase
3263
5052
  return h(
3264
5053
  'span',
3265
5054
  { className: 'dce-right-title' },
@@ -3293,9 +5082,10 @@ let activeCtx = undefined
3293
5082
  function ChatSurface(props) {
3294
5083
  const t = translator(props)
3295
5084
  useStore()
3296
- const snapshot = getStatus()
5085
+ const seatName = props !== undefined && props !== null && props.seat === 'right' ? 'right' : 'main'
5086
+ const snapshot = getStatus(seatName)
3297
5087
 
3298
- const provider = activeProvider()
5088
+ const provider = activeProvider(seatName)
3299
5089
  const hostRef = React.useRef(null)
3300
5090
  const listRef = React.useRef(null)
3301
5091
  /** @type {React.MutableRefObject<{ id: string, startX: number, active: boolean } | undefined>} */
@@ -3306,61 +5096,41 @@ let activeCtx = undefined
3306
5096
  const [, bumpDrag] = React.useState(0)
3307
5097
  const repaintDrag = () => bumpDrag((value) => value + 1)
3308
5098
 
3309
- const seatName = props !== undefined && props !== null && props.seat === 'right' ? 'right' : 'main'
3310
-
3311
- // Mounting a seat is the user opening the chat there: only one of the two
3312
- // seats can exist at a time (the right sidebar needs a Session surface),
3313
- // so the seat that just rendered is the one that owns the guests.
5099
+ // Each seat hosts its own page. Registering the viewport must not hand
5100
+ // the other seat's webview across, and a closed right column must not
5101
+ // paint anything onto the conversation.
3314
5102
  useMountEffect(() => {
3315
- const visible = seatName === 'main' || props.active !== false
3316
- if (visible) preferSeat(seatName)
3317
- return undefined
3318
- }, [])
3319
-
3320
- // `preferredSeat === seatName` must count as hosting even before this seat
3321
- // is registered: the registration effect only runs once the viewport is
3322
- // committed, so requiring a registered host first would deadlock.
3323
- const hostingSeat = inlineSeat()
3324
- const hosting =
3325
- hostingSeat === undefined ||
3326
- hostingSeat === seatName ||
3327
- preferredSeat === seatName ||
3328
- // A selected right tab is a user request too: it must render its
3329
- // viewport so it can register and take the guests over.
3330
- (seatName === 'right' && props.active === true)
3331
- React.useEffect(() => {
3332
5103
  const node = hostRef.current
3333
- if (hosting !== true || node === null || node === undefined) return undefined
5104
+ if (node === null || node === undefined) return undefined
3334
5105
  inlineHosts[seatName] = node
3335
- if (preferredSeat === undefined) preferredSeat = seatName
3336
- resolveInlineHost()
5106
+ if (seatName === 'main') {
5107
+ resolveInlineHost()
5108
+ } else if (hostArea(node) >= 2 && props.active !== false) {
5109
+ void ensureActiveGuest('right')
5110
+ }
3337
5111
  notify()
3338
- // A collapsed right tab is 0×0 and must not steal the page; when the user
3339
- // expands the column the tab gets a box, and that is the moment to hand
3340
- // the guests over. The observer only re-runs the seat choice.
3341
5112
  let ro
3342
- if (typeof ResizeObserver === 'function' && preferredSeat === seatName) {
5113
+ if (typeof ResizeObserver === 'function') {
3343
5114
  ro = new ResizeObserver(() => {
3344
- if (preferredSeat === seatName) resolveInlineHost()
5115
+ if (seatName === 'main') {
5116
+ resolveInlineHost()
5117
+ return
5118
+ }
5119
+ if (props.active === false || hostArea(node) < 2) return
5120
+ void ensureActiveGuest('right')
3345
5121
  })
3346
5122
  ro.observe(node)
3347
5123
  }
3348
5124
  return () => {
3349
5125
  if (ro !== undefined) ro.disconnect()
3350
5126
  if (inlineHosts[seatName] === node) inlineHosts[seatName] = null
3351
- if (preferredSeat === seatName) preferredSeat = undefined
3352
- resolveInlineHost()
5127
+ if (seatName === 'main') {
5128
+ stowPark()
5129
+ if (parkIsLive() !== true) destroySeat('main', 'no viewport')
5130
+ }
3353
5131
  notify()
3354
5132
  }
3355
- }, [hosting])
3356
-
3357
- // Selecting the right tab hands the chat to that column, so the panel the
3358
- // user is actually looking at is the one that shows it.
3359
- React.useEffect(() => {
3360
- if (seatName !== 'right' || props.active === false) return undefined
3361
- if (preferredSeat !== 'right') preferSeat('right')
3362
- return undefined
3363
- }, [props.active])
5133
+ }, [])
3364
5134
 
3365
5135
  // Pointer-driven tab reordering. Dragging is armed on pointerdown and
3366
5136
  // only starts after a small threshold, so a plain click still selects.
@@ -3591,9 +5361,9 @@ let activeCtx = undefined
3591
5361
  })
3592
5362
  }
3593
5363
  const onReload = () => {
3594
- void reloadGuest(provider.id)
5364
+ void reloadGuest(provider.id, seatName)
3595
5365
  }
3596
- const record = guestRecord(provider.id)
5366
+ const record = guestRecord(provider.id, seatName)
3597
5367
 
3598
5368
  // The status strip only earns its space while something is happening or
3599
5369
  // wrong; a healthy tab shows nothing but its tabs. A pending patch is
@@ -3622,6 +5392,9 @@ let activeCtx = undefined
3622
5392
  'data-visible': 'true',
3623
5393
  'data-mode': 'inline',
3624
5394
  'data-seat': seatName,
5395
+ // True on the first paint, not after an effect: otherwise the panel's
5396
+ // own background covers the park for a frame and the page looks late.
5397
+ 'data-parked': seatName === 'main' && shellFramePresent() === true ? 'true' : 'false',
3625
5398
  'data-build': BUILD,
3626
5399
  'aria-hidden': 'false',
3627
5400
  },
@@ -3656,7 +5429,7 @@ let activeCtx = undefined
3656
5429
  className: 'dce-tab',
3657
5430
  'data-tab-id': entry.id,
3658
5431
  'data-active': entry.id === provider.id ? 'true' : 'false',
3659
- 'data-failed': guestRecord(entry.id).phase === PHASE.FAILED ? 'true' : 'false',
5432
+ 'data-failed': guestRecord(entry.id, seatName).phase === PHASE.FAILED ? 'true' : 'false',
3660
5433
  'data-dragging':
3661
5434
  dragRef.current !== undefined &&
3662
5435
  dragRef.current.active === true &&
@@ -3675,7 +5448,7 @@ let activeCtx = undefined
3675
5448
  suppressClickRef.current = false
3676
5449
  return
3677
5450
  }
3678
- void setActive(entry.id)
5451
+ void setActive(entry.id, seatName)
3679
5452
  },
3680
5453
  },
3681
5454
  entry.label,
@@ -3707,8 +5480,6 @@ let activeCtx = undefined
3707
5480
  },
3708
5481
  externalIcon(),
3709
5482
  ),
3710
-
3711
-
3712
5483
  h(
3713
5484
  'button',
3714
5485
  {
@@ -3895,6 +5666,42 @@ let activeCtx = undefined
3895
5666
  },
3896
5667
  ),
3897
5668
  ),
5669
+ h(
5670
+ 'div',
5671
+ { className: 'dce-menu-row' },
5672
+ h('span', { className: 'dce-menu-label', title: t('importBubbleHint') }, t('importBubble')),
5673
+ h('button', {
5674
+ type: 'button',
5675
+ role: 'switch',
5676
+ className: 'dce-switch',
5677
+ 'data-on': importBubbleEnabled() ? 'true' : 'false',
5678
+ 'aria-checked': importBubbleEnabled() ? 'true' : 'false',
5679
+ 'data-import-bubble': 'true',
5680
+ 'aria-label': t('importBubble'),
5681
+ title: t('importBubbleHint'),
5682
+ onClick: () => {
5683
+ setImportBubbleEnabled(!importBubbleEnabled())
5684
+ },
5685
+ }),
5686
+ ),
5687
+ h(
5688
+ 'div',
5689
+ { className: 'dce-menu-row' },
5690
+ h('span', { className: 'dce-menu-label', title: t('contextMenuHint') }, t('contextMenu')),
5691
+ h('button', {
5692
+ type: 'button',
5693
+ role: 'switch',
5694
+ className: 'dce-switch',
5695
+ 'data-on': contextMenuEnabled() ? 'true' : 'false',
5696
+ 'aria-checked': contextMenuEnabled() ? 'true' : 'false',
5697
+ 'data-import-context-menu': 'true',
5698
+ 'aria-label': t('contextMenu'),
5699
+ title: t('contextMenuHint'),
5700
+ onClick: () => {
5701
+ setContextMenuEnabled(!contextMenuEnabled())
5702
+ },
5703
+ }),
5704
+ ),
3898
5705
  )
3899
5706
  : null,
3900
5707
  confirmOpen
@@ -4036,11 +5843,12 @@ let activeCtx = undefined
4036
5843
  'div',
4037
5844
  { className: 'dce-surface' },
4038
5845
  h('div', { className: 'dce-viewport', ref: hostRef }),
5846
+ record.notice !== '' ? h('div', { className: 'dce-import-notice', role: 'status' }, record.notice) : null,
4039
5847
  snapshot.phase === PHASE.UNSUPPORTED
4040
- ? hintCard(t('statusUnsupported'), t('unsupportedHint'), t, snapshot)
5848
+ ? hintCard(t('statusUnsupported'), t('unsupportedHint'), t, snapshot, undefined, provider.url)
4041
5849
  : null,
4042
5850
  snapshot.phase === PHASE.FAILED
4043
- ? hintCard(t('statusFailed'), t('failedHint'), t, snapshot, onReload)
5851
+ ? hintCard(t('statusFailed'), t('failedHint'), t, snapshot, onReload, provider.url)
4044
5852
  : null,
4045
5853
  record.oauthBlocked
4046
5854
  ? h(
@@ -4292,6 +6100,28 @@ let activeCtx = undefined
4292
6100
  runSeatSelfTest,
4293
6101
  seatReportData,
4294
6102
  installInspect,
6103
+ GUEST_ADAPTERS,
6104
+ IMPORT_PREFIX,
6105
+ IMPORT_BUBBLE_KEY,
6106
+ IMPORT_CONTEXT_MENU_KEY,
6107
+ importBubbleEnabled,
6108
+ setImportBubbleEnabled,
6109
+ contextMenuEnabled,
6110
+ setContextMenuEnabled,
6111
+ parseImportMessage,
6112
+ parsePushUrl,
6113
+ receivePush,
6114
+ PUSH_URL,
6115
+ validateImportPayload,
6116
+ formatImport,
6117
+ mainSessionId,
6118
+ importDraft,
6119
+ extractionSource,
6120
+ bootstrapSource,
6121
+ contextMenuSource,
6122
+ runImport,
6123
+ deliverImportPayload,
6124
+ showImportNotice,
4295
6125
  formatRect,
4296
6126
  translator,
4297
6127
  rightTabType,
@@ -4304,7 +6134,7 @@ let activeCtx = undefined
4304
6134
  }
4305
6135
 
4306
6136
  return {
4307
- inject: ['slots', 'locale'],
6137
+ inject: ['slots', 'locale', 'sessions', 'uiSession', 'uiWorkspace', 'conversation'],
4308
6138
  apply(ctx) {
4309
6139
  // A hot reload can apply this bundle again while the previous instance is
4310
6140
  // still alive. Its slots, tab type and observers would then block or