dsh-chat-embed 0.6.15 → 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 +1 -0
  2. package/client.js +1428 -4
  3. package/index.js +14 -4
  4. package/package.json +1 -1
package/client.js CHANGED
@@ -117,7 +117,7 @@ window.__ModuleLoader__.load({
117
117
  let activeCtx = undefined
118
118
 
119
119
  /** Build identity, surfaced in the panel so a packaged app can be diagnosed. */
120
- const BUILD = '0.6.15'
120
+ const BUILD = '0.6.16'
121
121
 
122
122
  /** Where a re-applied instance finds the one it must take over from. */
123
123
  const INSTANCE_KEY = '__DSH_CHAT_EMBED_INSTANCE__'
@@ -131,6 +131,1296 @@ let activeCtx = undefined
131
131
  /** Where the set of enabled providers is remembered. */
132
132
  const ENABLED_KEY = 'dsh-chat-embed:enabled'
133
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
+
134
1424
  /**
135
1425
  * The services this surface can host. Order is the tab order.
136
1426
  *
@@ -263,6 +1553,26 @@ let activeCtx = undefined
263
1553
  dismiss: 'Dismiss',
264
1554
  dragHint: 'Drag to reorder',
265
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',
266
1576
  menuTitle: 'Chat tabs',
267
1577
  lastTabHint: 'At least one tab must stay enabled',
268
1578
  logging: 'Debug log',
@@ -372,6 +1682,26 @@ let activeCtx = undefined
372
1682
  dismiss: '知道了',
373
1683
  dragHint: '拖动可排序',
374
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} · 整段对话',
375
1705
  menuTitle: '对话窗口',
376
1706
  lastTabHint: '至少保留一个对话窗口',
377
1707
  logging: '调试日志',
@@ -1127,6 +2457,7 @@ let activeCtx = undefined
1127
2457
  * @property {any} element
1128
2458
  * @property {string | undefined} lease
1129
2459
  * @property {string | undefined} partition
2460
+ * @property {string} importNonce
1130
2461
  * @property {any} layer
1131
2462
  * @property {boolean} mounting
1132
2463
  * @property {number} generation
@@ -1209,6 +2540,10 @@ let activeCtx = undefined
1209
2540
  reloadTimer: undefined,
1210
2541
  handoff: '',
1211
2542
  selfTest: '',
2543
+ importNonce: '',
2544
+ lastPush: undefined,
2545
+ notice: '',
2546
+ noticeTimer: undefined,
1212
2547
  }
1213
2548
  guests.set(key, record)
1214
2549
  }
@@ -1279,6 +2614,13 @@ let activeCtx = undefined
1279
2614
  record.lastEvent = ''
1280
2615
  record.diagOpen = false
1281
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 = ''
1282
2624
  // `oauthBlocked` is deliberately kept: the explanation must survive the
1283
2625
  // recovery reload that replaces the stuck guest.
1284
2626
 
@@ -1324,6 +2666,7 @@ let activeCtx = undefined
1324
2666
  element.removeEventListener('did-stop-loading', handlers.stop)
1325
2667
  element.removeEventListener('render-process-gone', handlers.crash)
1326
2668
  element.removeEventListener('crashed', handlers.crash)
2669
+ element.removeEventListener('console-message', handlers.importMessage)
1327
2670
  }
1328
2671
  } catch (error) {
1329
2672
  void error
@@ -1516,6 +2859,7 @@ let activeCtx = undefined
1516
2859
  navigateInPage: (event) => onGuestLocation(id, event !== undefined && event !== null ? event.url : '', which),
1517
2860
  stop: () => onGuestStopped(id, which),
1518
2861
  crash: () => onGuestCrashed(id, which),
2862
+ importMessage: (event) => onGuestImportMessage(id, event, which),
1519
2863
  }
1520
2864
  element.addEventListener('dom-ready', handlers.ready)
1521
2865
  element.addEventListener('did-fail-load', handlers.failed)
@@ -1524,10 +2868,12 @@ let activeCtx = undefined
1524
2868
  element.addEventListener('did-stop-loading', handlers.stop)
1525
2869
  element.addEventListener('render-process-gone', handlers.crash)
1526
2870
  element.addEventListener('crashed', handlers.crash)
2871
+ element.addEventListener('console-message', handlers.importMessage)
1527
2872
 
1528
2873
  record.element = element
1529
2874
  record.lease = lease
1530
2875
  record.partition = partition
2876
+ record.importNonce = newImportNonce()
1531
2877
  record.navigated = false
1532
2878
  record.handlers = handlers
1533
2879
  record.mounts += 1
@@ -1728,6 +3074,9 @@ let activeCtx = undefined
1728
3074
 
1729
3075
  // The initial `about:blank#<lease>` load is blank by design.
1730
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)
1731
3080
  notify()
1732
3081
  }
1733
3082
 
@@ -1762,6 +3111,23 @@ let activeCtx = undefined
1762
3111
  if (element === undefined || element === null) return
1763
3112
  if (typeof url !== 'string' || url.indexOf('https://') !== 0) return
1764
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
+
1765
3131
  // Google/Apple complete sign-in but their callback page cannot finish in
1766
3132
  // an embedded WebContents, so arm the dead-end tracking from here.
1767
3133
  if (isOAuthUrl(url)) {
@@ -3386,6 +4752,7 @@ let activeCtx = undefined
3386
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))}',
3387
4753
  '.dce-icon-button:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}',
3388
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}',
3389
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}',
3390
4757
  // A pending patch keeps the tab bar pinned open, and the tab bar sits on
3391
4758
  // the same top edge with a higher z-index — so the strip has to move below
@@ -4113,8 +5480,6 @@ let activeCtx = undefined
4113
5480
  },
4114
5481
  externalIcon(),
4115
5482
  ),
4116
-
4117
-
4118
5483
  h(
4119
5484
  'button',
4120
5485
  {
@@ -4301,6 +5666,42 @@ let activeCtx = undefined
4301
5666
  },
4302
5667
  ),
4303
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
+ ),
4304
5705
  )
4305
5706
  : null,
4306
5707
  confirmOpen
@@ -4442,6 +5843,7 @@ let activeCtx = undefined
4442
5843
  'div',
4443
5844
  { className: 'dce-surface' },
4444
5845
  h('div', { className: 'dce-viewport', ref: hostRef }),
5846
+ record.notice !== '' ? h('div', { className: 'dce-import-notice', role: 'status' }, record.notice) : null,
4445
5847
  snapshot.phase === PHASE.UNSUPPORTED
4446
5848
  ? hintCard(t('statusUnsupported'), t('unsupportedHint'), t, snapshot, undefined, provider.url)
4447
5849
  : null,
@@ -4698,6 +6100,28 @@ let activeCtx = undefined
4698
6100
  runSeatSelfTest,
4699
6101
  seatReportData,
4700
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,
4701
6125
  formatRect,
4702
6126
  translator,
4703
6127
  rightTabType,
@@ -4710,7 +6134,7 @@ let activeCtx = undefined
4710
6134
  }
4711
6135
 
4712
6136
  return {
4713
- inject: ['slots', 'locale'],
6137
+ inject: ['slots', 'locale', 'sessions', 'uiSession', 'uiWorkspace', 'conversation'],
4714
6138
  apply(ctx) {
4715
6139
  // A hot reload can apply this bundle again while the previous instance is
4716
6140
  // still alive. Its slots, tab type and observers would then block or