dsh-deepseek-webchat 0.0.0-stage → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,2335 @@
1
+ /**
2
+ * dsh-deepseek-webchat — browser half.
3
+ *
4
+ * A sidebar tab that shows the **real** chat.deepseek.com web app and lets you
5
+ * push selected DSH messages into it by hand.
6
+ *
7
+ * ## Why this is not an iframe
8
+ *
9
+ * `chat.deepseek.com` answers with `Content-Security-Policy: frame-ancestors
10
+ * 'none'`, so an `<iframe>` is refused by the page itself. The only supported
11
+ * way in is the desktop shell's own browser guest channel: this bundle asks
12
+ * `globalThis.dshDesktop.browser.acquire(workspace)` for a reservation, then
13
+ * attaches a `<webview>` whose `src` is `about:blank#<lease>` and whose
14
+ * `partition` is the one the shell issued. The shell's `will-attach-webview`
15
+ * matches the lease, rewrites the element with hardened web preferences and
16
+ * lets the navigation through. That is the same channel the built-in side-card
17
+ * browser uses, so `frame-ancestors` never enters into it.
18
+ *
19
+ * ## Why the guest lives outside React
20
+ *
21
+ * A `<webview>` is destroyed when it leaves the document. If the slot owned it,
22
+ * every look at another tab would tear down the page and reload it — losing a
23
+ * half-typed question and re-running the site's boot. So the element lives in a
24
+ * container this plugin owns at the document root, and the slot's body only
25
+ * *measures* its area: the persistent guest is positioned onto that rectangle
26
+ * while this tab is showing, and hidden when it is not. The tab type declares
27
+ * `keepMounted: true` so the body itself survives tab switches and can keep
28
+ * reporting that rectangle.
29
+ *
30
+ * ## One DeepSeek conversation per DSH Session
31
+ *
32
+ * DeepSeek's own routes (read from its shipped bundle) are
33
+ * `/a/:agentId/s/:sessionId`, so a conversation is addressable as a plain URL.
34
+ * The mapping DSH Session → DeepSeek conversation id is learned by watching the
35
+ * guest's URL (the id only appears once the first message is sent, because
36
+ * DeepSeek creates conversations lazily) and is persisted by the host half,
37
+ * which is where a durable file can live.
38
+ *
39
+ * ## What this half never does
40
+ *
41
+ * It never sends anything to DeepSeek on its own. Selecting messages composes a
42
+ * blockquote and *fills the composer*; pressing Enter is the human's move. It
43
+ * never reads a DeepSeek answer back into the DSH conversation, and it never
44
+ * quotes system, developer or injected-prompt events — those are filtered by the
45
+ * host half before they reach the picker.
46
+ */
47
+
48
+ window.__ModuleLoader__.load({
49
+ id: 'dsh-deepseek-webchat',
50
+ factory: (require) => {
51
+ // The loader passes `require` but no `module`, so every bundle declares
52
+ // its own CommonJS-ish pair, exactly as the shipped bundles do.
53
+ const module = { exports: {} }
54
+ const exports = module.exports
55
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
56
+
57
+ const React = require('react')
58
+
59
+ const h = React.createElement
60
+
61
+ /** Locale namespace, and the i18n key for this plugin's copy. */
62
+ const NS = 'dsh-deepseek-webchat'
63
+
64
+ /** The tab type id; the slot dispatch key for this plugin's body. */
65
+ const TAB_ID = 'dsh-deepseek-webchat'
66
+
67
+ /** The tab kind. Unique per profile — the type registry keys on it. */
68
+ const TAB_KIND = 'deepseek-webchat'
69
+
70
+ /** The real web app. Never an API host, never an iframe. */
71
+ const PAGE_URL = 'https://chat.deepseek.com/'
72
+
73
+ /** DeepSeek's default agent, so a conversation URL is `/a/chat/s/<id>`. */
74
+ const AGENT_ID = 'chat'
75
+
76
+ /**
77
+ * The storage account asked of the shell. A constant on purpose: the shell
78
+ * caches one partition per workspace key for the whole app run, so one
79
+ * identity means one DeepSeek login shared by every DSH Session, with the
80
+ * per-Session split living in the conversation URL instead.
81
+ */
82
+ const WORKSPACE = 'deepseek-webchat'
83
+
84
+ /** How often the guest's storage is snapshotted, in ms. */
85
+ const SAVE_INTERVAL_MS = 30000
86
+
87
+ /** How often the guest's URL is re-read as a fallback, in ms. */
88
+ const URL_POLL_MS = 2000
89
+
90
+ /**
91
+ * How often the guest is re-parked as a fallback, in ms.
92
+ *
93
+ * The ResizeObserver catches size changes; this only has to catch a pane
94
+ * that moved without resizing. Every tick forces a layout read, so a fast
95
+ * timer here is real work — the previous 250 ms was four forced layouts a
96
+ * second for something the observer already covers.
97
+ */
98
+ const PANE_POLL_MS = 2000
99
+
100
+ /**
101
+ * How many rows the picker mounts per page.
102
+ *
103
+ * A session can hold hundreds of rows — one measured at 555 — and building
104
+ * plus laying out all of them blocks the main thread: 73 ms for 555, mostly
105
+ * the forced layout. The list opens on the newest few, which is what a
106
+ * person actually picks from, and older rows are loaded a page at a time
107
+ * from the top. Selection is by `seq`, so the bulk actions still cover the
108
+ * whole session rather than only what is mounted.
109
+ */
110
+ const LIST_PAGE_SIZE = 10
111
+
112
+ /** Attribute marking this plugin's document-root guest container. */
113
+ const OVERLAY_ATTR = 'data-dsh-deepseek-webchat-overlay'
114
+
115
+ /**
116
+ * The host half's routes.
117
+ *
118
+ * Both halves keep their own copy of this table, and a missing entry fails
119
+ * silently: the call becomes `fetch(undefined)`, which rejects into whatever
120
+ * catch swallows it, so the feature simply never happens. A test asserts the
121
+ * two lists agree.
122
+ */
123
+ const ROUTES = {
124
+ state: '/api/dsh-deepseek-webchat/state',
125
+ messages: '/api/dsh-deepseek-webchat/messages',
126
+ binding: '/api/dsh-deepseek-webchat/binding',
127
+ sessionRestore: '/api/dsh-deepseek-webchat/session/restore',
128
+ sessionSave: '/api/dsh-deepseek-webchat/session/save',
129
+ diag: '/api/dsh-deepseek-webchat/diag',
130
+ }
131
+
132
+ /** Locale-owned copy. */
133
+ const zh = {
134
+ 'type.label': 'DeepSeek 网页版',
135
+ 'guide.title': 'DeepSeek 网页版',
136
+ 'guide.description': '在侧边栏打开 chat.deepseek.com',
137
+ 'action.send': '引用上下文',
138
+ 'action.back': '返回网页',
139
+ 'action.reload': '刷新',
140
+ 'action.rebind': '解除绑定',
141
+ 'action.refresh': '重新读取',
142
+ 'action.all': '全选',
143
+ 'action.none': '清除',
144
+ 'action.last': '选末尾',
145
+ 'action.fill': '填入并发送',
146
+ 'action.fillOnly': '仅填入',
147
+ 'action.copy': '复制',
148
+ 'picker.title': '选择要引用的消息',
149
+ 'picker.empty': '这个会话还没有可引用的消息。',
150
+ 'picker.emptyAdvanced': '这个会话还没有可引用的内容。',
151
+ 'picker.loading': '正在读取会话…',
152
+ 'picker.selected': '已选 {count} 条',
153
+ 'picker.hiddenEarlier': '上面还有 {count} 条更早的',
154
+ 'action.loadEarlier': '加载更早的 {count} 条',
155
+ 'picker.role.user': '用户',
156
+ 'picker.role.assistant': '助手',
157
+ 'picker.role.tool': '工具',
158
+ 'picker.advanced': '高级:包含思考过程与工具调用',
159
+ 'picker.advancedHint': '默认只列你与助手的对话,以及 AI 向你提的问题和选项。打开后会额外列出思考过程、工具调用、工具结果、待办、命令与压缩摘要。',
160
+ 'picker.kind.question': '提问',
161
+ 'picker.kind.answer': '回答',
162
+ 'picker.kind.reasoning': '思考',
163
+ 'picker.kind.toolCall': '调用',
164
+ 'picker.kind.toolResult': '结果',
165
+ 'picker.kind.todo': '待办',
166
+ 'picker.kind.command': '命令',
167
+ 'picker.kind.summary': '摘要',
168
+ 'picker.preamble': '附上说明',
169
+ 'picker.preambleHint': '在引用内容前面加一小段说明,告诉 DeepSeek 这些内容是什么、来自哪里。',
170
+ 'picker.preambleText': '以下是我在另一个 AI 助手(DSH)里的对话片段,引用给你作为背景参考。以「> 」开头的行是原文,【】里标出的是这段内容属于谁(用户、助手、提问、回答、工具调用等)。请先理解这些背景,再回答我最下面的问题;如果背景里有不清楚的地方,请直接指出。',
171
+ 'picker.lastCount': '末尾条数',
172
+ 'picker.question': '要一起发送的问题或指令(可选)',
173
+ 'picker.questionPlaceholder': '例如:请基于以上内容,帮我补充一个更完整的方案。',
174
+ 'picker.preview': '将填入 DeepSeek 输入框的内容',
175
+ 'picker.hint': '点「填入并发送」会直接把预览内容发给 DeepSeek;想先自己确认就点「仅填入」。两种情况都不会改动 DSH 里的对话。',
176
+ 'toast.sent': '已发送到 DeepSeek({count} 字)。',
177
+ 'toast.sendPending': '已填入 DeepSeek 输入框,但自动发送没有生效 —— 请手动按 Enter。',
178
+ 'status.bound': '已绑定 DeepSeek 会话 {id}',
179
+ 'status.unbound': '未绑定 —— 在 DeepSeek 里发出第一条消息后自动绑定',
180
+ 'status.nobridge': '当前环境没有桌面浏览器通道,无法嵌入真实网页版。',
181
+ 'status.nobridgeHint': '请在 DSH 桌面版里使用;`dsh web` 之类的普通网页 profile 不带这个通道。',
182
+ 'status.failed': '嵌入失败:{error}',
183
+ 'status.filling': '正在填入…',
184
+ 'toast.filled': '已填入 DeepSeek 输入框({count} 字),请手动按 Enter 发送。',
185
+ 'toast.nocomposer': '没找到 DeepSeek 输入框,请先在网页里打开一个对话。',
186
+ 'toast.copied': '已复制到剪贴板。',
187
+ 'toast.rebound': '已解除绑定,下次打开将新建对话。',
188
+ }
189
+
190
+ const en = {
191
+ 'type.label': 'DeepSeek Web',
192
+ 'guide.title': 'DeepSeek Web',
193
+ 'guide.description': 'Open chat.deepseek.com in the sidebar',
194
+ 'action.send': 'Quote context',
195
+ 'action.back': 'Back to page',
196
+ 'action.reload': 'Reload',
197
+ 'action.rebind': 'Unbind',
198
+ 'action.refresh': 'Read again',
199
+ 'action.all': 'Select all',
200
+ 'action.none': 'Clear',
201
+ 'action.last': 'Last',
202
+ 'action.fill': 'Fill and send',
203
+ 'action.fillOnly': 'Fill only',
204
+ 'action.copy': 'Copy',
205
+ 'picker.title': 'Choose messages to quote',
206
+ 'picker.empty': 'This session has no quotable messages yet.',
207
+ 'picker.emptyAdvanced': 'This session has nothing quotable yet.',
208
+ 'picker.loading': 'Reading the session…',
209
+ 'picker.selected': '{count} selected',
210
+ 'picker.hiddenEarlier': '{count} earlier rows above',
211
+ 'action.loadEarlier': 'Load {count} earlier',
212
+ 'picker.role.user': 'User',
213
+ 'picker.role.assistant': 'Assistant',
214
+ 'picker.role.tool': 'Tool',
215
+ 'picker.advanced': 'Advanced: include thinking and tool calls',
216
+ 'picker.advancedHint': 'By default this lists your conversation with the assistant plus the questions it asked you and their options. Turning this on also lists thinking, tool calls, tool results, todos, commands and compaction summaries.',
217
+ 'picker.kind.question': 'Question',
218
+ 'picker.kind.answer': 'Answer',
219
+ 'picker.kind.reasoning': 'Thinking',
220
+ 'picker.kind.toolCall': 'Call',
221
+ 'picker.kind.toolResult': 'Result',
222
+ 'picker.kind.todo': 'Todo',
223
+ 'picker.kind.command': 'Command',
224
+ 'picker.kind.summary': 'Summary',
225
+ 'picker.preamble': 'Add a note',
226
+ 'picker.preambleHint': 'Put a short note in front of the quoted text, telling DeepSeek what it is and where it came from.',
227
+ 'picker.preambleText': 'Below are excerpts from a conversation I had with another AI assistant (DSH), quoted as background. Lines starting with "> " are the original text, and 【...】 marks who that piece came from (user, assistant, question, answer, tool call, and so on). Please read them for context, then answer my question at the very end; say so if anything in the background is unclear.',
228
+ 'picker.lastCount': 'How many',
229
+ 'picker.question': 'Question or instruction to send along (optional)',
230
+ 'picker.questionPlaceholder': 'e.g. Based on the above, help me draft a more complete plan.',
231
+ 'picker.preview': 'What will be sent to DeepSeek',
232
+ 'picker.hint': 'Fill and send puts the preview straight into DeepSeek and submits it; use Fill only if you want to check it first. Neither touches your DSH conversation.',
233
+ 'toast.sent': 'Sent to DeepSeek ({count} chars).',
234
+ 'toast.sendPending': 'Filled the DeepSeek composer, but the automatic send did not take — press Enter there yourself.',
235
+ 'status.bound': 'Bound to DeepSeek conversation {id}',
236
+ 'status.unbound': 'Unbound — binds automatically after the first message is sent in DeepSeek',
237
+ 'status.nobridge': 'No desktop browser channel here, so the real web app cannot be embedded.',
238
+ 'status.nobridgeHint': 'Use the DSH desktop app; a plain `dsh web` profile does not carry this channel.',
239
+ 'status.failed': 'Embedding failed: {error}',
240
+ 'status.filling': 'Filling…',
241
+ 'toast.filled': 'Filled the DeepSeek composer ({count} chars) — press Enter yourself to send.',
242
+ 'toast.nocomposer': 'No DeepSeek composer found. Open a conversation in the page first.',
243
+ 'toast.copied': 'Copied to the clipboard.',
244
+ 'toast.rebound': 'Binding cleared; the next visit starts a new conversation.',
245
+ }
246
+
247
+ //#region urls
248
+
249
+ /**
250
+ * The DeepSeek conversation URL for one conversation id.
251
+ * @param sessionId - DeepSeek conversation id.
252
+ * @returns the absolute URL.
253
+ */
254
+ function conversationUrl(sessionId) {
255
+ return PAGE_URL + 'a/' + AGENT_ID + '/s/' + encodeURIComponent(sessionId)
256
+ }
257
+
258
+ /**
259
+ * Reduce a DSH Session id to the one form everything else compares against.
260
+ *
261
+ * DSH names the same Session two ways — the bare uuid that events carry
262
+ * (`e07a9659-…`) and the `session-e07a9659-…` form its store uses — and
263
+ * which one arrives here depends on the caller. The host canonicalises
264
+ * what it stores, so comparing a raw id against the host's answer would
265
+ * silently mismatch and make a bound Session look unbound.
266
+ * @param value - a Session id in either form.
267
+ * @returns the canonical id, or '' when there is none.
268
+ */
269
+ function canonicalSessionId(value) {
270
+ if (typeof value !== 'string') return ''
271
+ const trimmed = value.trim()
272
+ if (trimmed === '') return ''
273
+ return trimmed.startsWith('session-') ? trimmed.slice('session-'.length) : trimmed
274
+ }
275
+
276
+ /**
277
+ * The DeepSeek conversation id inside a chat.deepseek.com URL.
278
+ * @param value - any URL string.
279
+ * @returns the conversation id, or undefined.
280
+ */
281
+ function sessionIdOf(value) {
282
+ if (typeof value !== 'string' || value === '') return undefined
283
+ let url
284
+ try {
285
+ url = new URL(value)
286
+ } catch (error) {
287
+ return undefined
288
+ }
289
+ if (url.hostname !== 'chat.deepseek.com') return undefined
290
+ const match = /^\/a\/[^/]+\/s\/([^/?#]+)\/?$/.exec(url.pathname)
291
+ if (match === null) return undefined
292
+ try {
293
+ return decodeURIComponent(match[1])
294
+ } catch (error) {
295
+ return match[1]
296
+ }
297
+ }
298
+
299
+ //#endregion
300
+
301
+ //#region copy
302
+
303
+ /**
304
+ * Interpolate `{name}` placeholders.
305
+ * @param template - the copy string.
306
+ * @param values - substitution values.
307
+ * @returns the filled string.
308
+ */
309
+ function format(template, values) {
310
+ return String(template).replace(/\{(\w+)\}/g, (whole, key) => (
311
+ Object.prototype.hasOwnProperty.call(values, key) ? String(values[key]) : whole
312
+ ))
313
+ }
314
+
315
+ /**
316
+ * The copy function to use when the framework's `t` seat is absent.
317
+ *
318
+ * A registration that declares `locale` receives a bound `t`, so this is
319
+ * only a backstop — but it resolves real copy rather than rendering raw
320
+ * keys like `action.send` if the seat ever fails to arrive.
321
+ * @returns a translate function over this plugin's dictionaries.
322
+ */
323
+ function fallbackTranslate() {
324
+ const language = typeof navigator === 'object' && typeof navigator.language === 'string'
325
+ ? navigator.language
326
+ : 'en'
327
+ const dictionary = language.toLowerCase().startsWith('zh') ? zh : en
328
+ return (key, values) => {
329
+ const template = dictionary[key] ?? en[key] ?? key
330
+ return values === undefined ? template : format(template, values)
331
+ }
332
+ }
333
+
334
+ //#endregion
335
+
336
+ //#region guest plumbing
337
+
338
+ /** The live guest, once one has been reserved. */
339
+ let guest = null
340
+ /** In-flight reservation, so concurrent callers share one attempt. */
341
+ let acquiring = null
342
+ /** Why the guest could not be created, or ''. */
343
+ let failure = ''
344
+ /** The DSH Session the guest is currently following. */
345
+ let activeSessionId = undefined
346
+ /** The last URL observed, so a binding is only taken from a settled URL. */
347
+ let lastSeenUrl = ''
348
+ /** The last URL this plugin asked the guest for, honoured at `dom-ready`. */
349
+ let lastRequestedUrl = PAGE_URL
350
+ /** True while the picker is open; the guest hides behind it. */
351
+ let overlaySuppressed = false
352
+ /** Subscribers told when the binding state changes. */
353
+ const watchers = new Set()
354
+ /** Session/conversation pairs already written, so polling does not rewrite. */
355
+ const boundPairs = new Set()
356
+
357
+ /** @returns a snapshot of the guest state for the UI. */
358
+ function guestState() {
359
+ return {
360
+ ready: guest !== null,
361
+ failure,
362
+ hasBridge: hasBridge(),
363
+ }
364
+ }
365
+
366
+ /** Notify every subscriber that the guest state changed. */
367
+ function notify() {
368
+ diag.notify += 1
369
+ diagEvent('notify', { n: diag.notify })
370
+ for (const watcher of [...watchers]) {
371
+ try {
372
+ watcher()
373
+ } catch (error) {
374
+ // A broken subscriber must not stop the others.
375
+ }
376
+ }
377
+ }
378
+
379
+ /** A pending coalesced notify, so a burst of events re-renders once. */
380
+ let notifyQueued = false
381
+
382
+ /**
383
+ * Counters for the diagnostics route.
384
+ *
385
+ * The guest is a `<webview>` this plugin cannot inspect from outside, so a
386
+ * flicker in there is otherwise invisible: the only way to tell a real
387
+ * hide/show cycle from a merely redundant one is to count them in the page
388
+ * and read the numbers back.
389
+ */
390
+ const diag = {
391
+ update: 0,
392
+ shown: 0,
393
+ hidden: 0,
394
+ moved: 0,
395
+ skipped: 0,
396
+ misses: 0,
397
+ hits: 0,
398
+ notify: 0,
399
+ // A flicker is either the guest being hidden and shown in a loop, or the
400
+ // panel body being torn down and remounted by the shell. These tell those
401
+ // apart, which no snapshot of the counters above can.
402
+ mounts: 0,
403
+ unmounts: 0,
404
+ renders: 0,
405
+ flickers: 0,
406
+ /** How long the last hide took, in ms: the suspect for a blocked window. */
407
+ lastHideMs: 0,
408
+ events: [],
409
+ }
410
+
411
+ /** Recent visibility flips, so a flicker can be detected as a rate. */
412
+ const flipTimes = []
413
+
414
+ /**
415
+ * Whether the diagnostics channel is collecting.
416
+ *
417
+ * Off unless asked for. It exists to make a flicker in the guest measurable
418
+ * from outside, which was worth a layout read and a JSON POST every second
419
+ * while diagnosing one — but not afterwards. Turn it on by loading the GUI
420
+ * with `?diag=1` (or setting `localStorage['dsh-deepseek-webchat:diag']`).
421
+ * The plugin behaves identically either way; only the reporting differs.
422
+ */
423
+ const diagnosticsOn = diagnosticsEnabled()
424
+
425
+ /**
426
+ * Whether the diagnostics channel is collecting.
427
+ *
428
+ * On by default, because it is measured to be cheap — a layout read and a
429
+ * 1 KB POST every couple of seconds, a few microseconds — and it is the only
430
+ * way to see inside the guest, which is a `<webview>` this plugin cannot
431
+ * otherwise inspect. It was briefly made opt-in on the theory that it caused
432
+ * the lag; measurement disproved that, and switching off the instrument
433
+ * while still hunting the problem was the wrong trade. `?diag=0`, or
434
+ * localStorage `'dsh-deepseek-webchat:diag' = '0'`, turns it off.
435
+ * @returns whether diagnostics were requested for this page load.
436
+ */
437
+ function diagnosticsEnabled() {
438
+ try {
439
+ const query = new URLSearchParams(location.search).get('diag')
440
+ if (query === '0' || query === 'off') return false
441
+ if (query !== null) return true
442
+ return globalThis.localStorage?.getItem('dsh-deepseek-webchat:diag') !== '0'
443
+ } catch (error) {
444
+ return true
445
+ }
446
+ }
447
+
448
+ /**
449
+ * Record a visibility flip, and flag a burst.
450
+ *
451
+ * A flicker is a rate, so one reading of the counters cannot show it — they
452
+ * have to be read against the clock. Three flips within two seconds is taken
453
+ * as a burst.
454
+ * @param kind - `show` or `hide`.
455
+ * @param detail - whatever the caller knows about this flip.
456
+ */
457
+ function noteFlip(kind, detail) {
458
+ if (!diagnosticsOn) return
459
+ const now = Date.now()
460
+ flipTimes.push(now)
461
+ while (flipTimes.length > 0 && now - flipTimes[0] > 2000) flipTimes.shift()
462
+ if (flipTimes.length < 3) return
463
+ diag.flickers += 1
464
+ diagEvent('FLICKER', { kind, flips: flipTimes.length, ...detail })
465
+ }
466
+
467
+ /** Record one visibility transition, keeping only the recent tail. */
468
+ function diagEvent(kind, detail) {
469
+ // Cheap early-out when diagnostics are off: this is called on every
470
+ // parking pass and every notify, and building an event object plus a
471
+ // Date.now() each time is pure overhead in normal use.
472
+ if (!diagnosticsOn) return
473
+ diag.events.push({ t: Date.now(), kind, detail })
474
+ if (diag.events.length > 40) diag.events.splice(0, diag.events.length - 40)
475
+ }
476
+
477
+ /** Post the counters so the host can serve them from the diag route. */
478
+ function postDiagnostics(extra) {
479
+ if (!diagnosticsOn) return
480
+ try {
481
+ void fetch(ROUTES.diag, {
482
+ method: 'POST',
483
+ headers: { 'content-type': 'application/json' },
484
+ body: JSON.stringify({ ...diag, ...extra }),
485
+ }).catch(() => undefined)
486
+ } catch (error) {
487
+ // Diagnostics must never break the plugin.
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Notify at most once per frame.
493
+ *
494
+ * A single page load raises several of the events that call this
495
+ * (`did-navigate`, `did-navigate-in-page`, `did-finish-load`, plus the
496
+ * poll), and each one re-rendered the whole panel. Coalescing them keeps a
497
+ * burst from being a burst of renders — which is what a flicker is.
498
+ */
499
+ function notifySoon() {
500
+ if (notifyQueued) return
501
+ notifyQueued = true
502
+ queueMicrotask(() => {
503
+ notifyQueued = false
504
+ notify()
505
+ })
506
+ }
507
+
508
+ /** @returns the desktop browser bridge, or undefined off the desktop shell. */
509
+ function bridge() {
510
+ const carrier = globalThis.dshDesktop
511
+ if (carrier === null || carrier === undefined) return undefined
512
+ if (carrier.protocolVersion !== 1) return undefined
513
+ const browser = carrier.browser
514
+ if (browser === null || browser === undefined) return undefined
515
+ if (typeof browser.acquire !== 'function') return undefined
516
+ return browser
517
+ }
518
+
519
+ /** @returns whether the desktop browser channel is available. */
520
+ function hasBridge() {
521
+ return bridge() !== undefined
522
+ }
523
+
524
+ /**
525
+ * A plain Chrome user agent for the guest, derived from this renderer's
526
+ * own so the Chrome major version stays truthful.
527
+ *
528
+ * chat.deepseek.com greets an `electron` token in the user agent with an
529
+ * "使用环境异常 / Abnormal usage environment" dialog, and dismissing it is
530
+ * stored per guest partition — process-lifetime here, so it would come
531
+ * back on every restart. Its check is literally
532
+ * `navigator.userAgent.toLowerCase().includes("electron")`, so not
533
+ * advertising Electron is what keeps the page clean.
534
+ * @returns a Chrome user agent, or '' when this renderer reports none.
535
+ */
536
+ function cleanUserAgent() {
537
+ const ua = typeof navigator === 'object' && typeof navigator.userAgent === 'string'
538
+ ? navigator.userAgent
539
+ : ''
540
+ const platform = (ua.match(/^Mozilla\/5\.0 \([^)]*\)/) || [])[0]
541
+ const chrome = (ua.match(/Chrome\/([0-9]+)/) || [])[1]
542
+ if (platform === undefined || chrome === undefined) return ''
543
+ return platform + ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/' + chrome + '.0.0.0 Safari/537.36'
544
+ }
545
+
546
+ /**
547
+ * Inject this plugin's stylesheet once.
548
+ *
549
+ * Colours come from the shell's own design tokens (`--dsw-*`), which is
550
+ * what makes the panel and its header door sit in the same visual system
551
+ * as the built-in UI. Every token is paired with a literal fallback: the
552
+ * `--dsh-color-*` family this file used to reference does not exist in
553
+ * DSH at all, so those declarations were silently falling through to
554
+ * `inherit` and rendering the header glyph pure white instead of the
555
+ * muted ink the rest of that row uses.
556
+ */
557
+ function ensureStyle() {
558
+ if (document.querySelector('style[' + OVERLAY_ATTR + '-style]') !== null) return
559
+ const tag = document.createElement('style')
560
+ tag.setAttribute(OVERLAY_ATTR + '-style', '')
561
+ tag.textContent = [
562
+ // The persistent guest, parked on the measured slot area.
563
+ // The guest container is taken out of the page's layout, so showing it
564
+ // cannot change what the pane it covers measures. That matters because
565
+ // the parking code decides whether to show the guest from that very
566
+ // rectangle, and a container that perturbs it set up a
567
+ // show/measure-zero/hide/measure-real oscillation.
568
+ '[' + OVERLAY_ATTR + ']{position:fixed;display:none;z-index:40;overflow:hidden;background:#fff;contain:layout size paint style}',
569
+ '[' + OVERLAY_ATTR + '] webview{-webkit-app-region:no-drag;border:0;display:flex;width:100%;height:100%}',
570
+ // The panel itself.
571
+ '.dswc-root{display:flex;flex-direction:column;width:100%;height:100%;min-height:0;font-size:12px;color:var(--dsw-alias-label-primary,inherit)}',
572
+ // The toolbar carries the panel's top rule, so its height is not a taste
573
+ // decision: the shell puts the conversation header's horizontal line at
574
+ // the bottom of a 38px tab strip (`_tabStrip` is `height:28px;
575
+ // padding:10px 6px 0`), and every sidebar tab the shell ships opens with
576
+ // a `height:38px; border-bottom:.5px` header. A tab body starts at y=38,
577
+ // so a 38px header puts its rule at 76 — the same row as the
578
+ // conversation's. Measured against the live app: 6px of padding around
579
+ // 24px buttons plus a 1px border came to 36px, leaving this rule two
580
+ // pixels above the one it is meant to continue.
581
+ '.dswc-toolbar{box-sizing:border-box;display:flex;align-items:center;gap:6px;height:38px;padding:0 8px;border-bottom:.5px solid var(--dsw-alias-border-l3,rgba(128,128,128,.24));flex:none}',
582
+ '.dswc-status{font-size:11px;line-height:1;color:var(--dsw-alias-label-tertiary,#adb2b8)}',
583
+ '.dswc-status[data-state="bound"]{color:#2ea043}',
584
+ '.dswc-status[data-state="error"]{color:#d1242f}',
585
+ '.dswc-gap{flex:1 1 auto}',
586
+ '.dswc-button{font:inherit;font-size:11px;padding:3px 8px;border-radius:var(--dsw-radius-sm,8px);border:1px solid var(--dsw-alias-border-l4,rgba(128,128,128,.35));background:transparent;color:inherit;cursor:pointer;white-space:nowrap}',
587
+ '.dswc-button:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.12))}',
588
+ '.dswc-button:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe);outline-offset:1px}',
589
+ '.dswc-button:disabled{opacity:.45;cursor:default}',
590
+ '.dswc-primary{border-color:transparent;background:var(--dsw-alias-state-business-primary,#4d6bfe);color:#fff}',
591
+ '.dswc-primary:hover:not(:disabled){background:var(--dsw-alias-state-business-primary,#4d6bfe);opacity:.88}',
592
+ '.dswc-host{position:relative;flex:1 1 auto;min-height:0}',
593
+ '.dswc-picker{display:flex;flex-direction:column;flex:1 1 auto;min-height:0;gap:6px;padding:8px}',
594
+ '.dswc-pickerHead{display:flex;align-items:center;gap:6px;row-gap:4px;flex-wrap:wrap;flex:none}',
595
+ '.dswc-pickerTitle{font-weight:600}',
596
+ '.dswc-muted{color:var(--dsw-alias-label-tertiary,#adb2b8);font-size:11px}',
597
+ '.dswc-more{position:sticky;top:0;display:flex;align-items:center;gap:8px;padding:6px 8px;background:var(--dsw-alias-bg-layer-1,#fff);border-bottom:1px solid var(--dsw-alias-border-l4,rgba(128,128,128,.25))}',
598
+ '.dswc-list{flex:1 1 auto;min-height:60px;overflow:auto;border:1px solid var(--dsw-alias-border-l4,rgba(128,128,128,.25));border-radius:var(--dsw-radius-md,12px)}',
599
+ '.dswc-row{display:flex;gap:6px;padding:6px 8px;cursor:pointer;border-bottom:1px solid var(--dsw-alias-border-l4,rgba(128,128,128,.15))}',
600
+ '.dswc-row:last-child{border-bottom:0}',
601
+ '.dswc-row:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.08))}',
602
+ // The row marker is an icon from the shell's own set plus a short
603
+ // word, inside a fixed-width column so the text of every row starts
604
+ // at the same place however long the label is.
605
+ '.dswc-role{display:inline-flex;align-items:center;gap:4px;flex:none;width:58px;font-size:10px;line-height:1.2;color:var(--dsw-alias-label-tertiary,#adb2b8);padding-top:1px}',
606
+ '.dswc-kindIcon{flex:none;display:block}',
607
+ '.dswc-roleLabel{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
608
+ // A question and its answer are what the default set exists for, so
609
+ // their markers carry the accent ink the answer badge uses. The
610
+ // assistant's row uses it too: its marker is DeepSeek's own logo,
611
+ // which is a solid mark and reads as a grey blob when muted.
612
+ '.dswc-row[data-kind="question"] .dswc-role,.dswc-row[data-kind="answer"] .dswc-role{color:var(--dsw-alias-state-business-primary,#4d6bfe)}',
613
+ '.dswc-row[data-kind="assistant"] .dswc-role{color:var(--dsw-alias-state-business-primary,#4d6bfe)}',
614
+ '.dswc-select{font:inherit;font-size:11px;padding:2px 4px;border-radius:var(--dsw-radius-sm,8px);border:1px solid var(--dsw-alias-border-l4,rgba(128,128,128,.35));background:transparent;color:inherit}',
615
+ // Advanced rows are the machinery behind the conversation, so they
616
+ // are inked down rather than competing with the actual dialogue.
617
+ '.dswc-row[data-kind="reasoning"] .dswc-text,.dswc-row[data-kind="tool-call"] .dswc-text,.dswc-row[data-kind="tool-result"] .dswc-text,.dswc-row[data-kind="todo"] .dswc-text,.dswc-row[data-kind="command"] .dswc-text,.dswc-row[data-kind="summary"] .dswc-text{color:var(--dsw-alias-label-tertiary,#adb2b8);font-size:11px}',
618
+ '.dswc-row[data-kind="reasoning"] .dswc-text{font-style:italic}',
619
+ '.dswc-row[data-kind="tool-call"] .dswc-text,.dswc-row[data-kind="tool-result"] .dswc-text,.dswc-row[data-kind="command"] .dswc-text{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}',
620
+ // The question and its answer are the point of the default set, so
621
+ // they read as slightly more than the surrounding dialogue.
622
+ '.dswc-row[data-kind="question"] .dswc-text{color:var(--dsw-alias-state-business-primary,#4d6bfe)}',
623
+ '.dswc-advanced{display:flex;align-items:center;gap:6px;flex:none;font-size:11px;color:var(--dsw-alias-label-tertiary,#adb2b8);cursor:pointer}',
624
+ '.dswc-advanced:hover{color:var(--dsw-alias-label-secondary,#cfd3d6)}',
625
+ '.dswc-text{flex:1 1 auto;white-space:pre-wrap;word-break:break-word;max-height:96px;overflow:hidden}',
626
+ '.dswc-compose{display:flex;flex-direction:column;gap:4px;flex:none}',
627
+ '.dswc-label{font-size:11px;color:var(--dsw-alias-label-tertiary,#adb2b8)}',
628
+ '.dswc-question,.dswc-preview{font:inherit;width:100%;box-sizing:border-box;padding:6px;border-radius:var(--dsw-radius-sm,8px);border:1px solid var(--dsw-alias-border-l4,rgba(128,128,128,.3));background:transparent;color:inherit;resize:vertical}',
629
+ '.dswc-preview{margin:0;max-height:150px;overflow:auto;white-space:pre-wrap;word-break:break-word;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}',
630
+ '.dswc-actions{display:flex;gap:6px}',
631
+ '.dswc-notice{padding:12px;color:var(--dsw-alias-label-tertiary,#adb2b8);display:flex;flex-direction:column;gap:6px}',
632
+ '.dswc-toast{flex:none;margin:0 8px 8px;padding:6px 8px;border-radius:var(--dsw-radius-sm,8px);background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.14));font-size:11px}',
633
+ // The header door. Sized and inked like the built-in icon buttons in
634
+ // that row (24px hit area, 8px radius, muted ink, translucent hover),
635
+ // rather than inheriting the header's near-white text colour.
636
+ '.dswc-headerButton{box-sizing:border-box;display:inline-flex;flex:none;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:0;border-radius:var(--dsw-radius-sm,8px);background:transparent;color:var(--dsw-alias-label-secondary,#cfd3d6);cursor:pointer}',
637
+ '.dswc-headerButton:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08));color:var(--dsw-alias-label-primary,#fff)}',
638
+ '.dswc-headerButton:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe);outline-offset:1px}',
639
+ ].join('\n')
640
+ document.head.appendChild(tag)
641
+ }
642
+
643
+ /**
644
+ * @returns the document-root container that keeps the guest alive.
645
+ *
646
+ * The stylesheet is injected first, and that is not incidental: without the
647
+ * `position: fixed` rule this element is an ordinary block-level div, so a
648
+ * bare one appended to `<body>` claims the full document width and shoves
649
+ * the whole app sideways — and the guest's own white page sits on top of it.
650
+ * That is the "the entire page flashes" symptom, and it appeared whenever the
651
+ * guest was rebuilt before the sheet existed.
652
+ */
653
+ function overlayContainer() {
654
+ ensureStyle()
655
+ const existing = document.querySelector('[' + OVERLAY_ATTR + ']')
656
+ if (existing !== null && existing !== undefined) return existing
657
+ const box = document.createElement('div')
658
+ box.setAttribute(OVERLAY_ATTR, '')
659
+ // Hidden at birth so there is never a frame where it is in the document
660
+ // and visible but not yet sized.
661
+ box.style.display = 'none'
662
+ document.body.appendChild(box)
663
+ return box
664
+ }
665
+
666
+ /**
667
+ * Hide the guest without unmounting it.
668
+ *
669
+ * Idempotent on purpose: setting `display` on a `<webview>` that is already
670
+ * in that state still makes the guest re-composite, which reads as a
671
+ * flicker. Any redundant pass over the parking code must therefore be a
672
+ * no-op rather than a hide/show cycle.
673
+ */
674
+ function hideOverlay() {
675
+ if (guest === null) return
676
+ if (guest.container.style.display === 'none') {
677
+ diag.skipped += 1
678
+ return
679
+ }
680
+ diag.hidden += 1
681
+ diagEvent('hide')
682
+ noteFlip('hide')
683
+ // Timed because hiding a guest running a full SPA is the one operation
684
+ // here that can plausibly block the window, and a report of "it freezes
685
+ // when I open the picker" has to be attributable to a specific step.
686
+ const t0 = Date.now()
687
+ guest.container.style.display = 'none'
688
+ const ms = Date.now() - t0
689
+ diag.lastHideMs = ms
690
+ if (ms > 4) diagEvent('hide:slow', { ms })
691
+ }
692
+
693
+ /**
694
+ * Park the guest on one measured rectangle.
695
+ *
696
+ * The order here is load-bearing. The container is `position: fixed` with a
697
+ * white background, and a block-level fixed box with `width: auto` spans the
698
+ * whole viewport. Making it visible before its geometry is set therefore
699
+ * paints a full-window white slab over the app for a frame — which is what
700
+ * "the whole page flashes" was. Geometry first, visibility last.
701
+ * @param rect - the slot area, in viewport coordinates.
702
+ */
703
+ function showOverlay(rect) {
704
+ if (guest === null) return
705
+ const style = guest.container.style
706
+ // A zero-sized rectangle is a pane that has not been laid out yet;
707
+ // parking on it would show a sliver, so wait for the next pass.
708
+ if (!(rect.width > 0) || !(rect.height > 0)) return
709
+ // Rounded to whole pixels before anything is written.
710
+ //
711
+ // `getBoundingClientRect()` returns fractions (705.4000244140625), while
712
+ // the style object hands back the browser's own normalised form. Comparing
713
+ // the raw float string against that never matches, so every single pass
714
+ // looked like a change and rewrote all four properties — and on a
715
+ // `<webview>` a geometry write re-composites. Four writes a second is the
716
+ // flicker that was still visible after the hide/show loop was fixed.
717
+ // Rounding makes an unchanged rectangle compare equal, so it is written
718
+ // once and then left alone.
719
+ const left = Math.round(rect.left) + 'px'
720
+ const top = Math.round(rect.top) + 'px'
721
+ const width = Math.round(rect.width) + 'px'
722
+ const height = Math.round(rect.height) + 'px'
723
+ const moved = style.left !== left || style.top !== top
724
+ || style.width !== width || style.height !== height
725
+ // Written only when it actually changed.
726
+ if (style.left !== left) style.left = left
727
+ if (style.top !== top) style.top = top
728
+ if (style.width !== width) style.width = width
729
+ if (style.height !== height) style.height = height
730
+ // Only now, with a real size in place, is it safe to show.
731
+ if (style.display !== 'block') {
732
+ diag.shown += 1
733
+ diagEvent('show', { left, top, width, height })
734
+ noteFlip('show', { width, height })
735
+ style.display = 'block'
736
+ } else if (moved) {
737
+ diag.moved += 1
738
+ diagEvent('move', { left, top, width, height })
739
+ } else {
740
+ diag.skipped += 1
741
+ }
742
+ }
743
+
744
+ /**
745
+ * Suppress or release the guest while the picker is open.
746
+ * @param value - whether the picker is showing.
747
+ */
748
+ function setOverlaySuppressed(value) {
749
+ overlaySuppressed = value
750
+ if (value) hideOverlay()
751
+ }
752
+
753
+ /** Ask the host to put the saved login back before the page is navigated. */
754
+ async function restoreGuestSession() {
755
+ try {
756
+ const response = await fetch(ROUTES.sessionRestore, { method: 'POST' })
757
+ const payload = await response.json()
758
+ if (payload === null || typeof payload !== 'object') return null
759
+ const storage = Array.isArray(payload.storage) ? payload.storage : []
760
+ const cookie = typeof payload.cookie === 'string' ? payload.cookie : ''
761
+ if (storage.length === 0 && cookie === '') return null
762
+ return { storage, cookie }
763
+ } catch (error) {
764
+ return null
765
+ }
766
+ }
767
+
768
+ /**
769
+ * Read the guest's own storage and cookie string.
770
+ *
771
+ * That string cannot carry HttpOnly cookies, but DeepSeek keeps its
772
+ * credential in `localStorage.userToken` and sends it as a bearer token,
773
+ * so replaying site storage is what actually restores a login.
774
+ * @param element - the live webview.
775
+ * @returns the guest state as JSON text.
776
+ */
777
+ function readGuestState(element) {
778
+ return element.executeJavaScript(
779
+ 'JSON.stringify({ storage: Object.keys(localStorage).map(function (key) { return [key, localStorage.getItem(key)] }), cookie: document.cookie })',
780
+ )
781
+ }
782
+
783
+ /**
784
+ * Write a guest state back into the page.
785
+ * @param element - the live webview.
786
+ * @param state - `{ storage, cookie }`.
787
+ */
788
+ function writeGuestState(element, state) {
789
+ return element.executeJavaScript(
790
+ '(function () { var state = ' + JSON.stringify(state) + ';'
791
+ + ' var storage = Array.isArray(state.storage) ? state.storage : [];'
792
+ + ' for (var i = 0; i < storage.length; i++) { try { localStorage.setItem(storage[i][0], storage[i][1]) } catch (error) {} }'
793
+ + " if (typeof state.cookie === 'string' && state.cookie !== '') {"
794
+ + " var parts = state.cookie.split('; ');"
795
+ + ' for (var j = 0; j < parts.length; j++) {'
796
+ + ' var pair = parts[j];'
797
+ + " if (pair.indexOf('=') === -1) continue;"
798
+ + " try { document.cookie = pair + '; path=/' } catch (error) {}"
799
+ + ' } }'
800
+ + ' return true })()',
801
+ )
802
+ }
803
+
804
+ /**
805
+ * Whether a guest element is currently on the DeepSeek origin.
806
+ *
807
+ * This guard is what protects the saved login. The guest starts on
808
+ * `about:blank#<lease>` and reaches DeepSeek a navigation later, so an
809
+ * early `did-finish-load` can fire while the page is still on the opaque
810
+ * origin — where `localStorage` throws and `document.cookie` is empty.
811
+ * Reading state there would return nothing, and saving that nothing would
812
+ * overwrite the snapshot the next launch needs. So both directions of the
813
+ * snapshot are confined to the real origin.
814
+ * @param element - the live webview.
815
+ * @returns true when its URL is on chat.deepseek.com.
816
+ */
817
+ function onDeepSeekOrigin(element) {
818
+ try {
819
+ return new URL(element.getURL()).hostname === 'chat.deepseek.com'
820
+ } catch (error) {
821
+ return false
822
+ }
823
+ }
824
+
825
+ /**
826
+ * Ask the host to refresh the stored login snapshot.
827
+ *
828
+ * The partition is deliberately not sent: it is a fresh
829
+ * `dsh-sidebar-browser-<uuid>` every run, so it identifies nothing across
830
+ * restarts and the snapshot is keyed to this plugin instead.
831
+ * @param withState - whether to include what only the guest can read.
832
+ */
833
+ async function saveGuestSession(withState) {
834
+ if (guest === null) return
835
+ // Never let an off-origin read blank the snapshot.
836
+ if (!onDeepSeekOrigin(guest.element)) return
837
+ let state = null
838
+ if (withState) {
839
+ try {
840
+ state = JSON.parse(await readGuestState(guest.element))
841
+ } catch (error) {
842
+ // Not ready: keep whatever the host already has.
843
+ return
844
+ }
845
+ }
846
+ try {
847
+ await fetch(ROUTES.sessionSave, {
848
+ method: 'POST',
849
+ headers: { 'content-type': 'application/json' },
850
+ body: JSON.stringify({
851
+ storage: Array.isArray(state?.storage) ? state.storage : [],
852
+ cookie: typeof state?.cookie === 'string' ? state.cookie : '',
853
+ }),
854
+ })
855
+ } catch (error) {
856
+ // Best effort: a snapshot that fails costs a login, not the page.
857
+ }
858
+ }
859
+
860
+ /**
861
+ * Record one DSH Session → DeepSeek conversation binding.
862
+ *
863
+ * The host is the authority, not this cache: the cache only exists so the
864
+ * poll does not re-POST the same pair every couple of seconds (each write
865
+ * notifies the panel and re-renders it). So the host's answer is what the
866
+ * cache is reconciled against — if the host says this Session is now
867
+ * bound to a different conversation, the cache follows rather than
868
+ * insisting on the stale pair.
869
+ *
870
+ * Re-binding is allowed and is the point: when the user's conversation in
871
+ * the page changes, the Session should follow the new one. The host
872
+ * refuses only a conversation another Session already owns.
873
+ * @param dshSessionId - DSH Session id.
874
+ * @param deepseekSessionId - DeepSeek conversation id.
875
+ */
876
+ async function bind(rawSessionId, deepseekSessionId) {
877
+ const dshSessionId = canonicalSessionId(rawSessionId)
878
+ if (dshSessionId === '') return
879
+ const pair = dshSessionId + '\u0000' + deepseekSessionId
880
+ if (boundPairs.has(pair)) return
881
+ try {
882
+ const response = await fetch(ROUTES.binding, {
883
+ method: 'POST',
884
+ headers: { 'content-type': 'application/json' },
885
+ body: JSON.stringify({ dshSessionId, deepseekSessionId }),
886
+ })
887
+ const payload = await response.json()
888
+ if (payload?.ok !== true) {
889
+ // Refused — the conversation belongs to another Session. Leave
890
+ // the claim off so a later observation can retry, and do not
891
+ // mark it as bound.
892
+ return
893
+ }
894
+ // The host echoes the binding it now holds, so the cache records
895
+ // what is actually stored rather than what was merely requested.
896
+ const stored = typeof payload.deepseekSessionId === 'string'
897
+ ? payload.deepseekSessionId
898
+ : deepseekSessionId
899
+ boundPairs.add(dshSessionId + '\u0000' + stored)
900
+ notifySoon()
901
+ } catch (error) {
902
+ // The next observation retries, so leave the claim off.
903
+ }
904
+ }
905
+
906
+ /**
907
+ * Forget the write cache for one DSH Session.
908
+ *
909
+ * The prefix is canonicalised to match how `bind` keys the cache; a raw id
910
+ * here would leave the entry behind, and the next visit would be silently
911
+ * treated as "already bound" and never re-registered.
912
+ * @param dshSessionId - DSH Session id, in either form.
913
+ */
914
+ function forgetBoundPairs(dshSessionId) {
915
+ const canonical = canonicalSessionId(dshSessionId)
916
+ if (canonical === '') return
917
+ const prefix = canonical + '\u0000'
918
+ for (const pair of [...boundPairs]) {
919
+ if (pair.startsWith(prefix)) boundPairs.delete(pair)
920
+ }
921
+ }
922
+
923
+ /**
924
+ * @param dshSessionId - DSH Session id.
925
+ * @returns the bound DeepSeek conversation id, or null.
926
+ */
927
+ async function readBinding(dshSessionId) {
928
+ if (typeof dshSessionId !== 'string' || dshSessionId === '') return null
929
+ try {
930
+ const response = await fetch(
931
+ ROUTES.binding + '?sessionId=' + encodeURIComponent(dshSessionId),
932
+ )
933
+ const payload = await response.json()
934
+ const value = payload?.deepseekSessionId
935
+ return typeof value === 'string' && value !== '' ? value : null
936
+ } catch (error) {
937
+ return null
938
+ }
939
+ }
940
+
941
+ /**
942
+ * Observe the guest's URL, requiring it to have settled before trusting it.
943
+ *
944
+ * DeepSeek creates a conversation only when the first message is sent, so
945
+ * the id appears by navigation rather than by any API this plugin can
946
+ * call. Requiring two identical readings keeps a transient URL during a
947
+ * session switch from being bound to the wrong DSH Session.
948
+ *
949
+ * The settle counter is deliberately *not* reset by the ordinary polling
950
+ * path — only by a deliberate navigation — so that a page which is simply
951
+ * sitting still does reach its second reading.
952
+ */
953
+ function observeUrl() {
954
+ if (guest === null || activeSessionId === undefined) return
955
+ let url
956
+ try {
957
+ url = guest.element.getURL()
958
+ } catch (error) {
959
+ return
960
+ }
961
+ if (url === '' || url === 'about:blank') return
962
+ if (url !== lastSeenUrl) {
963
+ lastSeenUrl = url
964
+ return
965
+ }
966
+ const deepseekSessionId = sessionIdOf(url)
967
+ if (deepseekSessionId === undefined) return
968
+ // Only adopt a conversation nobody owns.
969
+ //
970
+ // Binding unconditionally here re-pointed the active Session at whatever
971
+ // the guest happened to be showing. During a restore that is the *old*
972
+ // conversation — the navigation to the right one has not landed yet — so
973
+ // the poll undid the restore and the binding looked broken. A
974
+ // conversation another Session owns is never adopted; focusSession is
975
+ // what decides those.
976
+ void adoptIfUnowned(activeSessionId, deepseekSessionId)
977
+ }
978
+
979
+ /**
980
+ * Bind a conversation to a Session only when nobody owns it yet.
981
+ *
982
+ * A conversation already owned by *this* Session needs no write, and one
983
+ * owned by another must not be stolen. The already-ours case is checked
984
+ * against the write cache first, because this runs from the URL poll and
985
+ * from every navigation event: without that, the steady state — the guest
986
+ * sitting in the conversation this Session already owns — would cost a
987
+ * round trip to the host every couple of seconds, for an answer that cannot
988
+ * have changed.
989
+ * @param dshSessionId - DSH Session id.
990
+ * @param deepseekSessionId - DeepSeek conversation id.
991
+ */
992
+ async function adoptIfUnowned(dshSessionId, deepseekSessionId) {
993
+ if (boundPairs.has(dshSessionId + '\u0000' + deepseekSessionId)) return
994
+ const owner = await ownerOf(deepseekSessionId)
995
+ if (owner !== null && owner !== dshSessionId) return
996
+ await bind(dshSessionId, deepseekSessionId)
997
+ }
998
+
999
+ /**
1000
+ * Point the guest at the conversation this DSH Session should be showing.
1001
+ *
1002
+ * Called when the DSH Session changes, and once on mount. The rule is that
1003
+ * an existing binding wins: a Session that already owns a conversation is
1004
+ * taken back to it, whatever the guest happens to be showing.
1005
+ *
1006
+ * Only a Session with no binding adopts what the guest is already displaying
1007
+ * (which is how its first message lands in the conversation already open).
1008
+ * Adopting is deliberately second, because DeepSeek redirects its root into
1009
+ * the user's last conversation, so the guest is frequently sitting somewhere
1010
+ * unowned when a switch arrives — and adopting then would re-point the
1011
+ * Session instead of restoring it.
1012
+ *
1013
+ * Following a conversation the user opens *within* a Session is observeUrl's
1014
+ * job: it sees the new URL and claims it if it is unowned.
1015
+ * @param rawSessionId - the DSH Session the guest should follow, in either
1016
+ * id form.
1017
+ */
1018
+ async function focusSession(rawSessionId) {
1019
+ const dshSessionId = canonicalSessionId(rawSessionId)
1020
+ if (dshSessionId === '') return
1021
+ activeSessionId = dshSessionId
1022
+ if (guest === null) return
1023
+ let current
1024
+ try {
1025
+ current = guest.element.getURL()
1026
+ } catch (error) {
1027
+ current = ''
1028
+ }
1029
+ const currentId = sessionIdOf(current)
1030
+ const bound = await readBinding(dshSessionId)
1031
+ // An existing binding wins, and this is the whole point of focusing.
1032
+ //
1033
+ // Adopting an unowned conversation used to be checked first, which meant
1034
+ // a Session that already owned a conversation could have that binding
1035
+ // silently replaced: DeepSeek redirects its root into the user's last
1036
+ // conversation, so the guest frequently arrives somewhere unowned, and
1037
+ // that branch would adopt it and re-point the Session instead of going
1038
+ // back to its own conversation. That is the "binding failed" symptom.
1039
+ //
1040
+ // Following a conversation the user opens *within* a Session is
1041
+ // observeUrl's job, not this one's: it sees the new URL and re-points
1042
+ // the binding, so nothing is lost by restoring here.
1043
+ if (bound !== null) {
1044
+ if (currentId !== bound) navigate(conversationUrl(bound))
1045
+ return
1046
+ }
1047
+ // No binding yet, so this Session has nothing to restore. Adopt what the
1048
+ // guest is already showing, which is how a Session's first message lands
1049
+ // in the conversation already open.
1050
+ if (currentId === undefined) return
1051
+ const owner = await ownerOf(currentId)
1052
+ if (owner === null) {
1053
+ await bind(dshSessionId, currentId)
1054
+ return
1055
+ }
1056
+ // Another Session owns it and this one owns nothing: start fresh rather
1057
+ // than typing into someone else's conversation.
1058
+ navigate(PAGE_URL)
1059
+ }
1060
+
1061
+ /**
1062
+ * @param deepseekSessionId - DeepSeek conversation id.
1063
+ * @returns the DSH Session that owns it, or null when unbound.
1064
+ */
1065
+ async function ownerOf(deepseekSessionId) {
1066
+ try {
1067
+ const response = await fetch(
1068
+ ROUTES.binding + '?deepseekSessionId=' + encodeURIComponent(deepseekSessionId),
1069
+ )
1070
+ const payload = await response.json()
1071
+ const value = payload?.dshSessionId
1072
+ return typeof value === 'string' && value !== '' ? value : null
1073
+ } catch (error) {
1074
+ return null
1075
+ }
1076
+ }
1077
+
1078
+ /**
1079
+ * Navigate the guest, tolerating a navigation already in flight.
1080
+ * @param url - absolute URL.
1081
+ */
1082
+ function navigate(url) {
1083
+ if (guest === null) return
1084
+ lastSeenUrl = ''
1085
+ lastRequestedUrl = url
1086
+ try {
1087
+ const pending = guest.element.loadURL(url)
1088
+ if (pending !== undefined && typeof pending.catch === 'function') {
1089
+ pending.catch(() => undefined)
1090
+ }
1091
+ } catch (error) {
1092
+ // A navigation superseded by another one is not an error worth showing.
1093
+ }
1094
+ }
1095
+
1096
+ /**
1097
+ * Reserve a guest and attach its webview, once per app run.
1098
+ * @returns a promise resolving once the attempt settled.
1099
+ */
1100
+ function ensureGuest() {
1101
+ if (guest !== null) return Promise.resolve()
1102
+ const browser = bridge()
1103
+ if (browser === undefined) {
1104
+ failure = ''
1105
+ notify()
1106
+ return Promise.resolve()
1107
+ }
1108
+ if (acquiring !== null) return acquiring
1109
+ acquiring = (async () => {
1110
+ try {
1111
+ const reservation = await browser.acquire(WORKSPACE)
1112
+ if (reservation === null || typeof reservation !== 'object'
1113
+ || typeof reservation.lease !== 'string'
1114
+ || typeof reservation.partition !== 'string') {
1115
+ throw new Error('the desktop browser bridge returned no reservation')
1116
+ }
1117
+ const restored = await restoreGuestSession()
1118
+ const element = document.createElement('webview')
1119
+ element.setAttribute('name', reservation.lease)
1120
+ element.setAttribute('partition', reservation.partition)
1121
+ element.setAttribute('src', 'about:blank#' + reservation.lease)
1122
+ const userAgent = cleanUserAgent()
1123
+ if (userAgent !== '') element.setAttribute('useragent', userAgent)
1124
+ const record = {
1125
+ lease: reservation.lease,
1126
+ partition: reservation.partition,
1127
+ element,
1128
+ container: overlayContainer(),
1129
+ storageState: restored === null ? 'none' : 'pending',
1130
+ timer: 0,
1131
+ poller: 0,
1132
+ }
1133
+ // The guest exists by `dom-ready` and nothing has been navigated
1134
+ // yet, so this is the user agent the page actually loads with.
1135
+ element.addEventListener('dom-ready', () => {
1136
+ if (userAgent !== '') {
1137
+ try {
1138
+ element.setUserAgent(userAgent)
1139
+ } catch (error) {
1140
+ // The attribute above already covers most of it.
1141
+ }
1142
+ }
1143
+ navigate(lastRequestedUrl)
1144
+ }, { once: true })
1145
+ // Storage and cookies can only be written while the page is on
1146
+ // its own origin, so both are restored after the first load of
1147
+ // the real site and the page is then asked to load once more —
1148
+ // this time already signed in. The origin check matters: the
1149
+ // guest's first document is `about:blank#<lease>`, where writing
1150
+ // storage throws, and treating that as the restore would burn
1151
+ // the one attempt. Until this settles, snapshots are skipped:
1152
+ // the freshly loaded page still has empty storage, and saving
1153
+ // that would erase the very snapshot being restored.
1154
+ element.addEventListener('did-finish-load', () => {
1155
+ if (record.storageState !== 'pending') return
1156
+ if (!onDeepSeekOrigin(element)) return
1157
+ record.storageState = 'restoring'
1158
+ Promise.resolve(writeGuestState(element, restored))
1159
+ .then(() => {
1160
+ record.storageState = 'done'
1161
+ element.reload()
1162
+ })
1163
+ .catch(() => {
1164
+ record.storageState = 'done'
1165
+ })
1166
+ })
1167
+ element.addEventListener('did-finish-load', () => {
1168
+ if (record.storageState === 'pending' || record.storageState === 'restoring') return
1169
+ void saveGuestSession(true)
1170
+ })
1171
+ for (const event of ['did-navigate', 'did-navigate-in-page', 'did-finish-load']) {
1172
+ element.addEventListener(event, () => {
1173
+ // A navigation means the URL is worth re-reading, but it
1174
+ // must not clear the settle marker: the poll below settles
1175
+ // by seeing the same URL twice, and wiping it on every
1176
+ // event meant a still page never settled and its
1177
+ // conversation was never bound.
1178
+ observeUrl()
1179
+ })
1180
+ }
1181
+ record.container.appendChild(element)
1182
+ guest = record
1183
+ record.timer = setInterval(() => {
1184
+ void saveGuestSession(true)
1185
+ }, SAVE_INTERVAL_MS)
1186
+ record.poller = setInterval(observeUrl, URL_POLL_MS)
1187
+ failure = ''
1188
+ } catch (error) {
1189
+ failure = error instanceof Error ? error.message : String(error)
1190
+ } finally {
1191
+ acquiring = null
1192
+ notify()
1193
+ }
1194
+ })()
1195
+ return acquiring
1196
+ }
1197
+
1198
+ /** Release the guest and detach everything it owns. */
1199
+ function disposeGuest() {
1200
+ if (guest === null) return
1201
+ const record = guest
1202
+ guest = null
1203
+ clearInterval(record.timer)
1204
+ clearInterval(record.poller)
1205
+ try {
1206
+ record.element.remove()
1207
+ } catch (error) {
1208
+ // Already gone.
1209
+ }
1210
+ try {
1211
+ record.container.remove()
1212
+ } catch (error) {
1213
+ // Already gone.
1214
+ }
1215
+ const browser = bridge()
1216
+ if (browser !== undefined && typeof browser.release === 'function') {
1217
+ try {
1218
+ browser.release(record.lease)
1219
+ } catch (error) {
1220
+ // The shell owns the lease's real lifetime.
1221
+ }
1222
+ }
1223
+ notify()
1224
+ }
1225
+
1226
+ //#endregion
1227
+
1228
+ //#region composing
1229
+
1230
+ /**
1231
+ * One message as a blockquote block, so every line stays quoted.
1232
+ * @param label - the role label.
1233
+ * @param text - the message text.
1234
+ * @returns the blockquote, or '' for an empty message.
1235
+ */
1236
+ function quoteBlock(label, text) {
1237
+ const body = String(text).trim()
1238
+ if (body === '') return ''
1239
+ const lines = body.split(/\r?\n/)
1240
+ return ['> 【' + label + '】' + lines[0]]
1241
+ .concat(lines.slice(1).map((line) => '> ' + line))
1242
+ .join('\n')
1243
+ }
1244
+
1245
+ /**
1246
+ * Compose the blockquote plus the user's own question.
1247
+ * @param rows - the selected messages, in log order.
1248
+ * @param labels - role and kind labels.
1249
+ * @param question - the user's question or instruction.
1250
+ * @param options - `{ preamble }`, a note explaining what is being quoted.
1251
+ * @returns the text to place in the DeepSeek composer.
1252
+ */
1253
+ function compose(rows, labels, question, options = {}) {
1254
+ const blocks = []
1255
+ for (const row of rows) {
1256
+ // Every row is labelled by what it is, not just by who said it:
1257
+ // once the advanced switch is on, a quoted tool result and a
1258
+ // quoted answer would otherwise look identical in the blockquote.
1259
+ const label = kindLabel(row, labels)
1260
+ const block = quoteBlock(label, row.text)
1261
+ if (block !== '') blocks.push(block)
1262
+ }
1263
+ const quoted = blocks.join('\n\n')
1264
+ const asked = String(question ?? '').trim()
1265
+ const note = String(options.preamble ?? '').trim()
1266
+ const chunks = []
1267
+ // The note explains the blockquotes, so it is pointless without them —
1268
+ // a bare question needs no account of where it came from.
1269
+ if (quoted !== '') chunks.push(note === '' ? quoted : note + '\n\n' + quoted)
1270
+ if (asked !== '') chunks.push(asked)
1271
+ return chunks.join('\n\n---\n\n')
1272
+ }
1273
+
1274
+ /**
1275
+ * The label for one row, used both in the list and in the blockquote.
1276
+ * @param row - a picker row.
1277
+ * @param labels - `{ user, assistant, tool, kind }`.
1278
+ * @returns the label text.
1279
+ */
1280
+ function kindLabel(row, labels) {
1281
+ const kind = row.kind ?? row.role
1282
+ if (kind === 'user') return labels.user
1283
+ if (kind === 'assistant') return labels.assistant
1284
+ // Every remaining kind has a two-character label, which is what keeps
1285
+ // the role column a fixed narrow width in both locales.
1286
+ return labels.kind?.[kind] ?? (row.role === 'tool' ? labels.tool : labels.assistant)
1287
+ }
1288
+
1289
+ /**
1290
+ * The shell's own artwork for each row kind.
1291
+ *
1292
+ * Lifted from `@deepseek-ai/dsh-client-ui-primitives`, which is inlined
1293
+ * into every client bundle at build time and so cannot be `require`d at
1294
+ * runtime. Each glyph is drawn on that set's `0 0 16 16` grid and stroked
1295
+ * at the Regular 1px weight in `currentColor`, so a row marker reads as
1296
+ * one of the shell's icons rather than as a drawing of its own. Entries
1297
+ * that are objects are solid glyphs, because their source artwork is.
1298
+ */
1299
+ const KIND_ARTWORK = {
1300
+ user: [
1301
+ 'M8 8.25C9.51878 8.25 10.75 7.01878 10.75 5.5C10.75 3.98122 9.51878 2.75 8 2.75C6.48122 2.75 5.25 3.98122 5.25 5.5C5.25 7.01878 6.48122 8.25 8 8.25Z',
1302
+ 'M2.5 14.5C2.5 11.5 5.25 10.25 8 10.25C10.75 10.25 13.5 11.5 13.5 14.5',
1303
+ ],
1304
+ assistant: [
1305
+ 'M5.875 3C5.875 6.33333 7.54167 8 10.875 8C7.54167 8 5.875 9.66667 5.875 13C5.875 9.66667 4.20833 8 0.875 8C4.20833 8 5.875 6.33333 5.875 3Z',
1306
+ 'M12.375 1.55823C12.375 3.39156 13.2917 4.30823 15.125 4.30823C13.2917 4.30823 12.375 5.22489 12.375 7.05823C12.375 5.22489 11.4583 4.30823 9.625 4.30823C11.4583 4.30823 12.375 3.39156 12.375 1.55823Z',
1307
+ 'M12.375 10.4418C12.375 11.7751 13.0417 12.4418 14.375 12.4418C13.0417 12.4418 12.375 13.1084 12.375 14.4418C12.375 13.1084 11.7083 12.4418 10.375 12.4418C11.7083 12.4418 12.375 11.7751 12.375 10.4418Z',
1308
+ ],
1309
+ question: [
1310
+ 'M8 14.5C11.5899 14.5 14.5 11.5899 14.5 8C14.5 4.41015 11.5899 1.5 8 1.5C4.41015 1.5 1.5 4.41015 1.5 8C1.5 11.5899 4.41015 14.5 8 14.5Z',
1311
+ 'M5.75 6.69646C5.75 6.29865 5.88196 5.90976 6.12919 5.57899C6.37643 5.24821 6.72783 4.99041 7.13896 4.83817C7.5501 4.68593 8.0025 4.6461 8.43895 4.72371C8.87541 4.80132 9.27632 4.99289 9.59099 5.27419C9.90566 5.55549 10.12 5.91388 10.2068 6.30406C10.2936 6.69423 10.249 7.09866 10.0787 7.4662C9.90843 7.83373 9.62004 8.14787 9.25003 8.36889C9.19476 8.4019 9.13803 8.43262 9.08004 8.46099C8.52566 8.73217 8 9.20817 8 9.82532',
1312
+ 'M8 10.7416V11.7416',
1313
+ ],
1314
+ answer: [
1315
+ 'M2.25 8.5L5.49732 11.7473C5.90519 12.1552 6.57263 12.1344 6.95426 11.7018L13.75 4',
1316
+ ],
1317
+ reasoning: [
1318
+ 'M10.2854 5.71481C12.9673 8.39663 14.1182 11.5938 12.8562 12.8559C11.5942 14.1179 8.39706 12.9669 5.71518 10.2851C3.03333 7.60323 1.88236 4.40608 3.14441 3.14403C4.40644 1.882 7.6036 3.03297 10.2854 5.71481Z',
1319
+ 'M10.2854 10.2851C7.6036 12.9669 4.40644 14.1179 3.14441 12.8559C1.88236 11.5938 3.03333 8.39663 5.71518 5.71481C8.39706 3.03297 11.5942 1.882 12.8562 3.14403C14.1182 4.40608 12.9673 7.60323 10.2854 10.2851Z',
1320
+ {
1321
+ d: 'M8.86291 8.0002C8.86291 8.47549 8.47762 8.86087 8.00224 8.86087C7.52694 8.86087 7.1416 8.47549 7.1416 8.0002C7.1416 7.52485 7.52694 7.13953 8.00224 7.13953C8.47762 7.13953 8.86291 7.52485 8.86291 8.0002Z',
1322
+ fill: true,
1323
+ },
1324
+ ],
1325
+ 'tool-call': [
1326
+ 'M6.27612 1.5L4.52612 14.5',
1327
+ 'M11.4739 1.5L9.72388 14.5',
1328
+ 'M2.39868 5.5H14.0681',
1329
+ 'M1.93188 10.5H13.6013',
1330
+ ],
1331
+ 'tool-result': [
1332
+ 'M6.15479 4.91687H9.84543',
1333
+ 'M11.8798 9.55347V2.71525C11.8798 2.37416 11.564 2.09766 11.1744 2.09766H4.82577C4.43618 2.09766 4.12036 2.37416 4.12036 2.71525V9.55347',
1334
+ 'M2.28735 13.8022V8.84792C2.28735 8.77514 2.36262 8.72673 2.42884 8.75693L13.2936 13.7112C13.3914 13.7558 13.3596 13.9022 13.2521 13.9022H2.38735C2.33213 13.9022 2.28735 13.8575 2.28735 13.8022Z',
1335
+ 'M7.46929 10.979L13.5783 8.7416C13.6435 8.7177 13.7126 8.76601 13.7126 8.83551L13.7125 13.8022C13.7125 13.8574 13.6678 13.9022 13.6125 13.9022H7.99999',
1336
+ 'M6.15479 7.2395H9.05644',
1337
+ ],
1338
+ todo: [
1339
+ 'M3.75 6.25C4.7165 6.25 5.5 5.4665 5.5 4.5C5.5 3.5335 4.7165 2.75 3.75 2.75C2.7835 2.75 2 3.5335 2 4.5C2 5.4665 2.7835 6.25 3.75 6.25Z',
1340
+ 'M7.5 4.5H13.5',
1341
+ 'M3.75 13.25C4.7165 13.25 5.5 12.4665 5.5 11.5C5.5 10.5335 4.7165 9.75 3.75 9.75C2.7835 9.75 2 10.5335 2 11.5C2 12.4665 2.7835 13.25 3.75 13.25Z',
1342
+ 'M7.5 11.5H13.5',
1343
+ ],
1344
+ command: [
1345
+ 'M8 14.5C11.5899 14.5 14.5 11.5899 14.5 8C14.5 4.41015 11.5899 1.5 8 1.5C4.41015 1.5 1.5 4.41015 1.5 8C1.5 11.5899 4.41015 14.5 8 14.5Z',
1346
+ 'M10.3329 7.91346C10.3996 7.95195 10.3996 8.04818 10.3329 8.08667L6.78304 10.1362C6.71638 10.1747 6.63304 10.1266 6.63304 10.0496L6.63304 5.95055C6.63304 5.87357 6.71638 5.82546 6.78304 5.86395L10.3329 7.91346Z',
1347
+ ],
1348
+ summary: [
1349
+ 'M8 14.5C11.5899 14.5 14.5 11.5899 14.5 8C14.5 4.41015 11.5899 1.5 8 1.5C4.41015 1.5 1.5 4.41015 1.5 8C1.5 11.5899 4.41015 14.5 8 14.5Z',
1350
+ 'M8 1.5C8.85359 1.5 9.69883 1.66813 10.4874 1.99478C11.2761 2.32144 11.9926 2.80022 12.5962 3.40381C13.1998 4.00739 13.6786 4.72394 14.0052 5.51256C14.3319 6.30117 14.5 7.14641 14.5 8',
1351
+ ],
1352
+ }
1353
+
1354
+ /**
1355
+ * DeepSeek's own logo, for the assistant's rows.
1356
+ *
1357
+ * Taken from its favicon (`fe-static.deepseek.com/chat/favicon.svg`), so
1358
+ * the marker is the mark of the assistant being quoted rather than a
1359
+ * generic sparkle. It is a solid glyph on a `0 0 50 50` grid, so it keeps
1360
+ * its own viewBox instead of joining KIND_ARTWORK's 16px stroked set.
1361
+ */
1362
+ const DEEPSEEK_LOGO = 'M48.8354 10.0479C48.3232 9.79199 48.1025 10.2798 47.8032 10.5278C47.7007 10.6079 47.6143 10.7119 47.5273 10.8076C46.7793 11.624 45.9048 12.1597 44.7622 12.0957C43.0923 12 41.666 12.5356 40.4058 13.8398C40.1377 12.2319 39.2476 11.272 37.8926 10.6558C37.1836 10.3359 36.4668 10.0156 35.9702 9.31982C35.6235 8.82373 35.5293 8.27197 35.356 7.72754C35.2456 7.3999 35.1353 7.06396 34.7651 7.00781C34.3633 6.94385 34.2056 7.2876 34.0479 7.57568C33.418 8.75195 33.1733 10.0479 33.1973 11.3599C33.2524 14.312 34.4736 16.6641 36.8999 18.3359C37.1758 18.5278 37.2466 18.7197 37.1597 19C36.9946 19.5757 36.7974 20.1357 36.624 20.7119C36.5137 21.0801 36.3486 21.1597 35.9624 21C34.6309 20.4321 33.481 19.5918 32.4644 18.5757C30.7393 16.8721 29.1792 14.9917 27.2334 13.52C26.7764 13.1758 26.3193 12.856 25.8467 12.5518C23.8618 10.584 26.1069 8.96777 26.627 8.77588C27.1704 8.57568 26.8159 7.8877 25.0591 7.896C23.3022 7.90381 21.6953 8.50391 19.647 9.30371C19.3477 9.42383 19.0322 9.51172 18.7095 9.58398C16.8501 9.22363 14.9199 9.14355 12.9033 9.37598C9.10596 9.80762 6.07275 11.6396 3.84326 14.7681C1.16455 18.5278 0.53418 22.7998 1.30664 27.2559C2.11768 31.9521 4.46582 35.8398 8.07373 38.8799C11.8159 42.0322 16.1255 43.5762 21.041 43.2803C24.0269 43.104 27.3516 42.6963 31.1016 39.4561C32.0469 39.936 33.0396 40.1279 34.686 40.272C35.9546 40.3921 37.1758 40.208 38.1211 40.0078C39.6021 39.688 39.4995 38.2881 38.9639 38.0322C34.623 35.9678 35.5762 36.8081 34.71 36.1279C36.9155 33.4639 40.2402 30.6958 41.54 21.728C41.6426 21.0161 41.5557 20.5679 41.54 19.9917C41.5322 19.6396 41.6108 19.5039 42.0049 19.4639C43.0923 19.3359 44.1479 19.0317 45.1167 18.4878C47.9292 16.9199 49.064 14.3438 49.3315 11.2559C49.3711 10.7837 49.3237 10.2959 48.8354 10.0479ZM24.3262 37.8398C20.1196 34.4639 18.0791 33.3521 17.2358 33.3999C16.4482 33.4482 16.5898 34.3682 16.7632 34.9678C16.9443 35.5601 17.1812 35.9683 17.5117 36.4878C17.7402 36.832 17.8979 37.3442 17.2832 37.728C15.9282 38.584 13.5728 37.4399 13.4624 37.3838C10.7207 35.7358 8.42822 33.5601 6.81348 30.584C5.25342 27.7197 4.34766 24.6479 4.19775 21.3677C4.1582 20.5757 4.38672 20.2959 5.15869 20.1519C6.17529 19.96 7.22314 19.9199 8.23926 20.0718C12.5327 20.7119 16.1885 22.6719 19.2529 25.7759C21.002 27.5439 22.3252 29.6558 23.6885 31.7202C25.1377 33.9121 26.6978 36 28.6831 37.7119C29.3843 38.312 29.9434 38.7681 30.479 39.104C28.8643 39.2881 26.1699 39.3281 24.3262 37.8398ZM26.3433 24.6001C26.3433 24.248 26.6191 23.9678 26.9658 23.9678C27.0444 23.9678 27.1152 23.9839 27.1782 24.0078C27.2651 24.04 27.3438 24.0879 27.4067 24.1602C27.5171 24.272 27.5801 24.4321 27.5801 24.6001C27.5801 24.9521 27.3042 25.2319 26.9575 25.2319C26.6108 25.2319 26.3433 24.9521 26.3433 24.6001ZM32.6064 27.8799C32.2046 28.0479 31.8027 28.1919 31.4165 28.208C30.8179 28.2397 30.1641 27.9922 29.8096 27.688C29.2583 27.2158 28.8643 26.9521 28.6987 26.1279C28.6279 25.7759 28.6675 25.2319 28.7305 24.9199C28.8721 24.248 28.7144 23.8159 28.2495 23.4238C27.8716 23.104 27.3911 23.0161 26.8633 23.0161C26.666 23.0161 26.4849 22.9277 26.3511 22.856C26.1304 22.7441 25.9492 22.4639 26.1226 22.1201C26.1777 22.0078 26.4458 21.7358 26.5088 21.688C27.2256 21.272 28.0527 21.4077 28.8169 21.7197C29.5259 22.0161 30.0615 22.5601 30.834 23.3281C31.6216 24.2559 31.7632 24.5117 32.2124 25.208C32.5669 25.752 32.8901 26.312 33.1104 26.9521C33.2446 27.3521 33.0713 27.6802 32.6064 27.8799Z'
1363
+
1364
+ /**
1365
+ * One row kind's icon, at the row marker's size.
1366
+ * @param kind - a row kind such as `user` or `tool-call`.
1367
+ * @returns an inline SVG element.
1368
+ */
1369
+ function KindIcon(kind) {
1370
+ // The assistant is DeepSeek's own mark rather than one of the shell's
1371
+ // outline glyphs: a row that says "assistant" is quoting DeepSeek, and
1372
+ // a generic sparkle there read as just another tool.
1373
+ if (kind === 'assistant') {
1374
+ return h('svg', {
1375
+ className: 'dswc-kindIcon',
1376
+ width: 13,
1377
+ height: 13,
1378
+ viewBox: '0 0 50 50',
1379
+ fill: 'none',
1380
+ xmlns: 'http://www.w3.org/2000/svg',
1381
+ 'aria-hidden': 'true',
1382
+ }, h('path', { d: DEEPSEEK_LOGO, fill: 'currentColor', fillRule: 'nonzero' }))
1383
+ }
1384
+ const art = KIND_ARTWORK[kind] ?? KIND_ARTWORK.assistant
1385
+ return h('svg', {
1386
+ className: 'dswc-kindIcon',
1387
+ width: 13,
1388
+ height: 13,
1389
+ viewBox: '0 0 16 16',
1390
+ fill: 'none',
1391
+ xmlns: 'http://www.w3.org/2000/svg',
1392
+ 'aria-hidden': 'true',
1393
+ strokeWidth: 1,
1394
+ }, art.map((entry, index) => {
1395
+ const path = typeof entry === 'string' ? { d: entry } : entry
1396
+ return h('path', {
1397
+ key: index,
1398
+ d: path.d,
1399
+ stroke: path.fill === true ? 'none' : 'currentColor',
1400
+ fill: path.fill === true ? 'currentColor' : 'none',
1401
+ })
1402
+ }))
1403
+ }
1404
+
1405
+ /** How the guest finds the composer, most specific selector first. */
1406
+ const COMPOSER_PICK = 'document.querySelector("textarea.ds-textarea__textarea")'
1407
+ + ' || document.querySelector("textarea[placeholder]")'
1408
+ + ' || document.querySelector("textarea")'
1409
+
1410
+ /**
1411
+ * The script that fills the DeepSeek composer.
1412
+ *
1413
+ * The composer is a React-controlled `<textarea class="ds-textarea__textarea">`
1414
+ * (the class is built as `"ds" + "-textarea__textarea"` in DeepSeek's own
1415
+ * bundle). Writing `.value` directly is ignored by React, so the native
1416
+ * value setter is used and an `input` event is dispatched, which is what
1417
+ * makes React commit the change.
1418
+ * @param text - the text to place in the composer.
1419
+ * @returns a self-contained script expression.
1420
+ */
1421
+ function fillScript(text) {
1422
+ return '(function () {'
1423
+ + ' try {'
1424
+ + ' var text = ' + JSON.stringify(text) + ';'
1425
+ + ' var el = ' + COMPOSER_PICK + ';'
1426
+ + ' if (!el) return { ok: false, error: "no-composer" };'
1427
+ + ' el.focus();'
1428
+ + ' var proto = Object.getPrototypeOf(el);'
1429
+ + ' var desc = Object.getOwnPropertyDescriptor(proto, "value")'
1430
+ + ' || Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value");'
1431
+ + ' if (desc && desc.set) desc.set.call(el, text); else el.value = text;'
1432
+ + ' el.dispatchEvent(new Event("input", { bubbles: true }));'
1433
+ + ' el.dispatchEvent(new Event("change", { bubbles: true }));'
1434
+ + ' el.selectionStart = el.value.length;'
1435
+ + ' el.selectionEnd = el.value.length;'
1436
+ + ' return { ok: true, length: el.value.length };'
1437
+ + ' } catch (error) {'
1438
+ + ' return { ok: false, error: String(error && error.message || error) };'
1439
+ + ' }'
1440
+ + ' })()'
1441
+ }
1442
+
1443
+ /**
1444
+ * The script that submits the composer through DeepSeek's own handler.
1445
+ *
1446
+ * Its composer runs `onKeyDown` and, for a plain Enter, calls the very
1447
+ * function its send button calls. Dispatching a bubbling Enter therefore
1448
+ * runs the user's own code path — no invented shortcut, and no need to
1449
+ * guess at the send button's generated class name.
1450
+ * @returns a self-contained script expression.
1451
+ */
1452
+ function sendScript() {
1453
+ return '(function () {'
1454
+ + ' try {'
1455
+ + ' var el = ' + COMPOSER_PICK + ';'
1456
+ + ' if (!el) return { ok: false, error: "no-composer" };'
1457
+ + ' el.focus();'
1458
+ + ' el.dispatchEvent(new KeyboardEvent("keydown", {'
1459
+ + ' key: "Enter", code: "Enter", keyCode: 13, which: 13,'
1460
+ + ' bubbles: true, cancelable: true, composed: true'
1461
+ + ' }));'
1462
+ + ' return { ok: true };'
1463
+ + ' } catch (error) {'
1464
+ + ' return { ok: false, error: String(error && error.message || error) };'
1465
+ + ' }'
1466
+ + ' })()'
1467
+ }
1468
+
1469
+ /**
1470
+ * The script that reports what the composer currently holds.
1471
+ *
1472
+ * DeepSeek clears its textarea once a send has been accepted, so an empty
1473
+ * composer is the receipt that the message actually went out — a much
1474
+ * better signal than assuming the click worked.
1475
+ * @returns a self-contained script expression.
1476
+ */
1477
+ function probeScript() {
1478
+ return '(function () {'
1479
+ + ' try {'
1480
+ + ' var el = ' + COMPOSER_PICK + ';'
1481
+ + ' if (!el) return { ok: false, error: "no-composer" };'
1482
+ + ' var value = String(el.value == null ? "" : el.value);'
1483
+ + ' return { ok: true, empty: value.trim() === "", length: value.length };'
1484
+ + ' } catch (error) {'
1485
+ + ' return { ok: false, error: String(error && error.message || error) };'
1486
+ + ' }'
1487
+ + ' })()'
1488
+ }
1489
+
1490
+ /**
1491
+ * The script that clicks DeepSeek's own send button.
1492
+ *
1493
+ * The fallback for when the Enter path is refused. The button's class name
1494
+ * is a build-time hash, so it is found by its accessible name instead —
1495
+ * and it is never clicked when the composer was already cleared, which is
1496
+ * what stops a double send.
1497
+ * @returns a self-contained script expression.
1498
+ */
1499
+ function clickSendScript() {
1500
+ return '(function () {'
1501
+ + ' try {'
1502
+ + ' var wanted = /send|submit|发送/i;'
1503
+ + ' var nodes = document.querySelectorAll("button, [role=button]");'
1504
+ + ' for (var i = 0; i < nodes.length; i += 1) {'
1505
+ + ' var node = nodes[i];'
1506
+ + ' if (node.disabled === true) continue;'
1507
+ + ' var name = String(node.getAttribute("aria-label") || "") + " "'
1508
+ + ' + String(node.getAttribute("title") || "") + " "'
1509
+ + ' + String(node.getAttribute("data-testid") || "") + " "'
1510
+ + ' + String(node.textContent || "");'
1511
+ + ' if (!wanted.test(name)) continue;'
1512
+ + ' var rect = node.getBoundingClientRect();'
1513
+ + ' if (rect.width <= 0 || rect.height <= 0) continue;'
1514
+ + ' node.click();'
1515
+ + ' return { ok: true, found: true };'
1516
+ + ' }'
1517
+ + ' return { ok: true, found: false };'
1518
+ + ' } catch (error) {'
1519
+ + ' return { ok: false, error: String(error && error.message || error) };'
1520
+ + ' }'
1521
+ + ' })()'
1522
+ }
1523
+
1524
+ /**
1525
+ * Run one script in the guest's page and normalise the answer.
1526
+ * @param script - a self-contained script expression.
1527
+ * @returns the script's own result object.
1528
+ */
1529
+ async function runInGuest(script) {
1530
+ if (guest === null) return { ok: false, error: 'no-guest' }
1531
+ try {
1532
+ const result = await guest.element.executeJavaScript(script)
1533
+ if (result === null || typeof result !== 'object') return { ok: false, error: 'no-result' }
1534
+ return result
1535
+ } catch (error) {
1536
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
1537
+ }
1538
+ }
1539
+
1540
+ /**
1541
+ * Fill the guest's composer.
1542
+ * @param text - the text to place there.
1543
+ * @returns a result describing what happened.
1544
+ */
1545
+ async function fillComposer(text) {
1546
+ return runInGuest(fillScript(text))
1547
+ }
1548
+
1549
+ /**
1550
+ * Wait, then ask the composer whether the send landed.
1551
+ * @param delayMs - how long to give DeepSeek to accept the message.
1552
+ * @returns true once the composer has been cleared.
1553
+ */
1554
+ async function composerCleared(delayMs) {
1555
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
1556
+ const probe = await runInGuest(probeScript())
1557
+ return probe.ok === true && probe.empty === true
1558
+ }
1559
+
1560
+ /**
1561
+ * Put text into DeepSeek's composer and, when asked, submit it.
1562
+ * @param text - the text to place in the composer.
1563
+ * @param options - `{ send }` to submit it as well.
1564
+ * @returns `{ ok, length, sent, via?, error? }`.
1565
+ */
1566
+ async function pushToDeepSeek(text, options = {}) {
1567
+ const filled = await fillComposer(text)
1568
+ if (filled.ok !== true) return filled
1569
+ if (options.send !== true) return { ...filled, sent: false }
1570
+ // React commits the new value asynchronously, so pressing Enter in the
1571
+ // same tick would submit whatever was there before.
1572
+ await new Promise((resolve) => setTimeout(resolve, 120))
1573
+ const pressed = await runInGuest(sendScript())
1574
+ if (pressed.ok !== true) return { ...filled, sent: false, error: pressed.error }
1575
+ if (await composerCleared(800)) return { ...filled, sent: true, via: 'enter' }
1576
+ // The Enter path was refused (its handler is a no-op when the composer
1577
+ // reads as unsubmittable). Try DeepSeek's own button before giving up.
1578
+ const clicked = await runInGuest(clickSendScript())
1579
+ if (clicked.found === true && await composerCleared(800)) {
1580
+ return { ...filled, sent: true, via: 'button' }
1581
+ }
1582
+ return { ...filled, sent: false, error: 'not-sent' }
1583
+ }
1584
+
1585
+ //#endregion
1586
+
1587
+ //#region ui
1588
+
1589
+ /**
1590
+ * The chat-bubble glyph this plugin uses for both of its doors.
1591
+ *
1592
+ * Drawn to the shell's own icon spec rather than to taste, because the
1593
+ * icon sits in a row of built-in glyphs and any deviation reads as a
1594
+ * mistake: a `0 0 16 16` viewBox, a 1px stroke (the icon set's
1595
+ * `Regular` weight; `Medium` is 1.3), `fill: none` on the frame, and
1596
+ * `currentColor` throughout so the ink comes from whatever the host
1597
+ * paints — `--dsw-alias-label-secondary` in the guide's 26px icon box,
1598
+ * `--dsw-alias-label-tertiary` in the tab title.
1599
+ *
1600
+ * @param props - `{ size, className }`; the shell supplies both.
1601
+ * @returns the glyph.
1602
+ */
1603
+ function ChatBubbleGlyph(props) {
1604
+ const size = props?.size ?? 16
1605
+ return h('svg', {
1606
+ width: size, height: size, viewBox: '0 0 16 16',
1607
+ className: props?.className,
1608
+ fill: 'none', xmlns: 'http://www.w3.org/2000/svg',
1609
+ strokeWidth: 1,
1610
+ 'aria-hidden': 'true',
1611
+ }, [
1612
+ // Frame: a rounded bubble with a tail on the lower left.
1613
+ h('path', {
1614
+ key: 'frame',
1615
+ d: 'M4.5 2.5H11.5C12.6 2.5 13.5 3.4 13.5 4.5V9C13.5 10.1 12.6 11 11.5 11H7.25L4.5 13.25V11H4.5C3.4 11 2.5 10.1 2.5 9V4.5C2.5 3.4 3.4 2.5 4.5 2.5Z',
1616
+ stroke: 'currentColor', strokeLinejoin: 'round',
1617
+ }),
1618
+ // One message line, so the glyph reads as a conversation.
1619
+ h('path', { key: 'line', d: 'M5.5 6.75H10.5', stroke: 'currentColor', strokeLinecap: 'round' }),
1620
+ ])
1621
+ }
1622
+
1623
+ /**
1624
+ * The guide door's artwork. The shell sizes a guide icon itself, so the
1625
+ * glyph reads the `size`/`className` it is handed.
1626
+ * @param props - `{ size, className }` from the guide entry.
1627
+ */
1628
+ function GuideArtwork(props) {
1629
+ return ChatBubbleGlyph(props)
1630
+ }
1631
+
1632
+ /**
1633
+ * The tab body: a toolbar, and either the picker or the measured guest area.
1634
+ * @param props - standard slot props plus the injected session id.
1635
+ */
1636
+ function DeepSeekBody(props) {
1637
+ const useTabInfo = props.useTabInfo
1638
+ const tabInfo = typeof useTabInfo === 'function' ? useTabInfo() : undefined
1639
+ const sessionId = props.sessionId ?? tabInfo?.tab?.sessionId
1640
+ // The framework's own answer to "is this tab the one on screen". Guarded
1641
+ // with `!== false` so a shell that does not publish the flag keeps the
1642
+ // old always-park behaviour rather than hiding the guest forever.
1643
+ const tabVisible = tabInfo?.tab?.visible !== false
1644
+ const t = props.t ?? fallbackTranslate()
1645
+
1646
+ const hostRef = React.useRef(null)
1647
+ const [version, setVersion] = React.useState(0)
1648
+ const [pickerOpen, setPickerOpen] = React.useState(false)
1649
+ const [bound, setBound] = React.useState(null)
1650
+ const [messages, setMessages] = React.useState(null)
1651
+ const [loadError, setLoadError] = React.useState('')
1652
+ const [selected, setSelected] = React.useState(() => new Set())
1653
+ const [question, setQuestion] = React.useState('')
1654
+ const [advanced, setAdvanced] = React.useState(false)
1655
+ const [preamble, setPreamble] = React.useState(true)
1656
+ const [lastN, setLastN] = React.useState(10)
1657
+ const [busy, setBusy] = React.useState(false)
1658
+ const [toast, setToast] = React.useState('')
1659
+ // Bumped only by the explicit 「重新读取」 button. It is separate from
1660
+ // `version` (guest state) so that a guest notification cannot re-run the
1661
+ // message fetch, which would blank the list to its loading state.
1662
+ const [reload, setReload] = React.useState(0)
1663
+ // How many of the newest rows are mounted. Grows a page at a time from
1664
+ // the top of the list, so a long session never builds every row at once.
1665
+ const [pageSize, setPageSize] = React.useState(LIST_PAGE_SIZE)
1666
+ const listRef = React.useRef(null)
1667
+ // The row to hold in place while a page of earlier rows is inserted above.
1668
+ const anchoredRef = React.useRef(null)
1669
+
1670
+ // React to the guest coming up, failing, or binding.
1671
+ React.useEffect(() => {
1672
+ const watcher = () => setVersion((value) => value + 1)
1673
+ watchers.add(watcher)
1674
+ return () => {
1675
+ watchers.delete(watcher)
1676
+ }
1677
+ }, [])
1678
+
1679
+ // Count mounts and renders. A flicker of the panel area is either the
1680
+ // guest being hidden and shown in a loop, or the shell tearing this body
1681
+ // down and building it again; only these counters distinguish the two.
1682
+ diag.renders += 1
1683
+ React.useEffect(() => {
1684
+ diag.mounts += 1
1685
+ diagEvent('mount', { sessionId: String(sessionId ?? '') })
1686
+ return () => {
1687
+ diag.unmounts += 1
1688
+ diagEvent('unmount', { sessionId: String(sessionId ?? '') })
1689
+ }
1690
+ }, [])
1691
+
1692
+ // Bring the guest up once the shell has a bridge for it.
1693
+ React.useEffect(() => {
1694
+ if (!hasBridge()) return
1695
+ void ensureGuest()
1696
+ }, [])
1697
+
1698
+ // Follow the DSH Session this pane belongs to.
1699
+ //
1700
+ // This depends on `sessionId` alone. It used to depend on `version`
1701
+ // too, which is bumped by every notify() — and notify() fires from the
1702
+ // guest's own navigation events. That made the effect re-run on every
1703
+ // navigation, navigate again, and so notify itself: an endless
1704
+ // navigate/notify ping-pong that showed up as the panel flickering.
1705
+ React.useEffect(() => {
1706
+ if (sessionId === undefined) return undefined
1707
+ let cancelled = false
1708
+ void (async () => {
1709
+ await ensureGuest()
1710
+ if (cancelled) return
1711
+ await focusSession(sessionId)
1712
+ if (cancelled) return
1713
+ setBound(await readBinding(sessionId))
1714
+ })()
1715
+ return () => {
1716
+ cancelled = true
1717
+ }
1718
+ }, [sessionId])
1719
+
1720
+ // Park the guest on the measured area, and keep it parked.
1721
+ //
1722
+ // Visibility comes from the framework, never from measuring. The tab
1723
+ // record carries `visible`, which the sidebar computes as "this tab is
1724
+ // the one on screen" — exactly the question. The old code inferred it
1725
+ // from the host element's own rectangle, and that was the flicker: the
1726
+ // guest is parked in a `position:fixed` container covering that very
1727
+ // element, so showing the guest could make it measure empty, which hid
1728
+ // the guest, which made it measure fine again. A signal derived from
1729
+ // the thing it controls oscillates; rounding and hysteresis only move
1730
+ // the loop around.
1731
+ //
1732
+ // Geometry is now read solely to place the guest. A zero rectangle means
1733
+ // "not laid out yet — wait", and is not a reason to hide.
1734
+ //
1735
+ // Depends on `pickerOpen` and `tabVisible` alone: re-running this effect
1736
+ // is itself a hide/show cycle.
1737
+ React.useEffect(() => {
1738
+ if (!tabVisible) {
1739
+ hideOverlay()
1740
+ return undefined
1741
+ }
1742
+ const host = hostRef.current
1743
+ if (host === null) return undefined
1744
+ const update = () => {
1745
+ diag.update += 1
1746
+ if (overlaySuppressed || guest === null) {
1747
+ diagEvent('update', { why: overlaySuppressed ? 'suppressed' : 'no-guest' })
1748
+ hideOverlay()
1749
+ return
1750
+ }
1751
+ // One layout read, not two. `getBoundingClientRect()` and
1752
+ // `getClientRects()` both force the browser to flush pending
1753
+ // layout, and an empty rect is already detectable from the
1754
+ // bounding rect alone: a box that is not laid out measures 0x0.
1755
+ // The old pair doubled the cost of every tick for the same answer.
1756
+ const rect = host.getBoundingClientRect()
1757
+ if (!(rect.width > 2) || !(rect.height > 2)) {
1758
+ diag.misses += 1
1759
+ diagEvent('update', {
1760
+ why: 'not-laid-out', w: rect.width, h: rect.height,
1761
+ })
1762
+ return
1763
+ }
1764
+ diag.hits += 1
1765
+ showOverlay(rect)
1766
+ }
1767
+ update()
1768
+ const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(update) : null
1769
+ if (observer !== null) observer.observe(host)
1770
+ window.addEventListener('resize', update)
1771
+ // The 250 ms poll is a fallback for the cases the observer cannot see:
1772
+ // a pane whose position changed without its size changing (the
1773
+ // sidebar widening, the header growing) moves the host rect but fires
1774
+ // no resize. Two seconds is often enough for that, and each tick
1775
+ // forces a layout read, so a fast timer here is real work for no
1776
+ // benefit.
1777
+ const timer = setInterval(update, PANE_POLL_MS)
1778
+ // Diagnostics are opt-in. They were a debugging tool, and leaving them
1779
+ // on in normal use cost a layout read plus a JSON POST every second —
1780
+ // measured lag on a panel this small. `?diag=1` on the GUI URL turns
1781
+ // them on; the plugin works identically either way.
1782
+ let reporter = 0
1783
+ if (diagnosticsEnabled()) {
1784
+ const snapshot = () => {
1785
+ let url = ''
1786
+ try {
1787
+ url = guest === null ? '' : guest.element.getURL()
1788
+ } catch (error) {
1789
+ url = ''
1790
+ }
1791
+ const rect = host.getBoundingClientRect()
1792
+ return {
1793
+ url,
1794
+ suppressed: overlaySuppressed,
1795
+ display: guest === null ? '' : guest.container.style.display,
1796
+ host: {
1797
+ l: Math.round(rect.left), t: Math.round(rect.top),
1798
+ w: Math.round(rect.width), h: Math.round(rect.height),
1799
+ },
1800
+ rects: host.getClientRects().length,
1801
+ pane: pickerOpen,
1802
+ }
1803
+ }
1804
+ reporter = setInterval(() => postDiagnostics(snapshot()), 2000)
1805
+ postDiagnostics(snapshot())
1806
+ }
1807
+ return () => {
1808
+ if (observer !== null) observer.disconnect()
1809
+ window.removeEventListener('resize', update)
1810
+ clearInterval(timer)
1811
+ if (reporter !== 0) clearInterval(reporter)
1812
+ hideOverlay()
1813
+ }
1814
+ }, [pickerOpen, tabVisible])
1815
+
1816
+ // Hide the guest behind the picker.
1817
+ React.useEffect(() => {
1818
+ setOverlaySuppressed(pickerOpen)
1819
+ }, [pickerOpen])
1820
+
1821
+ // Read the session's messages when the picker opens, when the advanced
1822
+ // switch flips, when the Session changes, and when the user asks for a
1823
+ // re-read. Deliberately *not* on `version`: that is bumped by notify(),
1824
+ // and every pass blanks the list to its loading state first — so a guest
1825
+ // notification (a binding landing, the guest coming up) wiped the list
1826
+ // out from under whoever was reading it. `reload` is the explicit
1827
+ // re-read, and it is the only thing that should blank the list.
1828
+ React.useEffect(() => {
1829
+ if (!pickerOpen || sessionId === undefined) return undefined
1830
+ let cancelled = false
1831
+ // Timed, because "getting the context freezes the whole app" is a
1832
+ // report about one specific click and the numbers have to say which
1833
+ // step it is. The fetch is measured separately from the state write,
1834
+ // so a slow host query is distinguishable from a slow render.
1835
+ const t0 = Date.now()
1836
+ diagEvent('picker:open', { sessionId: String(sessionId) })
1837
+ // A new fetch starts a new window: without this, paging a long session
1838
+ // and then opening another one would begin already expanded.
1839
+ setPageSize(LIST_PAGE_SIZE)
1840
+ anchoredRef.current = null
1841
+ setMessages(null)
1842
+ setLoadError('')
1843
+ void (async () => {
1844
+ try {
1845
+ const response = await fetch(
1846
+ ROUTES.messages
1847
+ + '?sessionId=' + encodeURIComponent(sessionId)
1848
+ + (advanced ? '&advanced=1' : ''),
1849
+ )
1850
+ const payload = await response.json()
1851
+ const fetched = Date.now() - t0
1852
+ if (cancelled) return
1853
+ if (payload?.ok !== true) {
1854
+ diagEvent('picker:error', { ms: fetched, error: String(payload?.error ?? 'unknown') })
1855
+ setLoadError(String(payload?.error ?? 'unknown'))
1856
+ setMessages([])
1857
+ return
1858
+ }
1859
+ const rows = Array.isArray(payload.messages) ? payload.messages : []
1860
+ setMessages(rows)
1861
+ diagEvent('picker:loaded', {
1862
+ fetchMs: fetched,
1863
+ rows: rows.length,
1864
+ bytes: JSON.stringify(rows).length,
1865
+ })
1866
+ } catch (error) {
1867
+ if (cancelled) return
1868
+ diagEvent('picker:throw', { ms: Date.now() - t0, error: String(error) })
1869
+ setLoadError(error instanceof Error ? error.message : String(error))
1870
+ setMessages([])
1871
+ }
1872
+ })()
1873
+ return () => {
1874
+ cancelled = true
1875
+ }
1876
+ }, [pickerOpen, sessionId, reload, advanced])
1877
+
1878
+ const labels = React.useMemo(() => ({
1879
+ user: t('picker.role.user'),
1880
+ assistant: t('picker.role.assistant'),
1881
+ tool: t('picker.role.tool'),
1882
+ kind: {
1883
+ question: t('picker.kind.question'),
1884
+ answer: t('picker.kind.answer'),
1885
+ reasoning: t('picker.kind.reasoning'),
1886
+ 'tool-call': t('picker.kind.toolCall'),
1887
+ 'tool-result': t('picker.kind.toolResult'),
1888
+ todo: t('picker.kind.todo'),
1889
+ command: t('picker.kind.command'),
1890
+ summary: t('picker.kind.summary'),
1891
+ },
1892
+ }), [t])
1893
+
1894
+ const chosen = React.useMemo(() => {
1895
+ if (messages === null) return []
1896
+ return messages.filter((row) => selected.has(row.seq))
1897
+ }, [messages, selected])
1898
+
1899
+ // The note travels with the quoted rows, so it is composed here rather
1900
+ // than baked into the blockquote: a bare question needs no account of
1901
+ // where it came from, and compose() knows whether anything is quoted.
1902
+ const note = React.useMemo(
1903
+ () => (preamble ? t('picker.preambleText') : ''),
1904
+ [preamble, t],
1905
+ )
1906
+
1907
+ const preview = React.useMemo(
1908
+ () => compose(chosen, labels, question, { preamble: note }),
1909
+ [chosen, labels, question, note],
1910
+ )
1911
+
1912
+ // The list opens on the newest rows, which is what a person wants to
1913
+ // quote and where they expect to be looking.
1914
+ //
1915
+ // It must not also do that when a page of *earlier* rows is inserted
1916
+ // above: jumping to the bottom there would throw away the position the
1917
+ // reader just scrolled to in order to click the button. So when an
1918
+ // anchor was recorded, the previously-topmost row is held at the same
1919
+ // offset and the anchor is consumed; otherwise the list goes to the end,
1920
+ // which is right for a fresh fetch or the picker opening.
1921
+ React.useEffect(() => {
1922
+ const node = listRef.current
1923
+ if (node === null) return
1924
+ const anchorSeq = anchoredRef.current
1925
+ if (anchorSeq !== null) {
1926
+ anchoredRef.current = null
1927
+ const anchor = node.querySelector(`[data-seq="${anchorSeq}"]`)
1928
+ if (anchor !== null) {
1929
+ node.scrollTop = anchor.offsetTop - node.offsetTop
1930
+ return
1931
+ }
1932
+ }
1933
+ node.scrollTop = node.scrollHeight
1934
+ }, [messages, pickerOpen, pageSize])
1935
+
1936
+ const toggle = React.useCallback((seq) => {
1937
+ setSelected((current) => {
1938
+ const next = new Set(current)
1939
+ if (next.has(seq)) next.delete(seq)
1940
+ else next.add(seq)
1941
+ return next
1942
+ })
1943
+ }, [])
1944
+
1945
+ const push = React.useCallback(async (send) => {
1946
+ if (preview.trim() === '') return
1947
+ setBusy(true)
1948
+ setToast('')
1949
+ try {
1950
+ setPickerOpen(false)
1951
+ // Let the guest become visible again before scripting it.
1952
+ await new Promise((resolve) => setTimeout(resolve, 120))
1953
+ const result = await pushToDeepSeek(preview, { send })
1954
+ if (result.ok !== true) {
1955
+ setToast(result.error === 'no-composer'
1956
+ ? t('toast.nocomposer')
1957
+ : format(t('status.failed'), { error: String(result.error) }))
1958
+ return
1959
+ }
1960
+ // The selection has been consumed either way — it is in
1961
+ // DeepSeek's composer now — so leaving it ticked would only make
1962
+ // the next push repeat this one.
1963
+ setSelected(new Set())
1964
+ setQuestion('')
1965
+ if (send && result.sent === true) {
1966
+ setToast(format(t('toast.sent'), { count: result.length ?? preview.length }))
1967
+ } else if (send) {
1968
+ setToast(t('toast.sendPending'))
1969
+ } else {
1970
+ setToast(format(t('toast.filled'), { count: result.length ?? preview.length }))
1971
+ }
1972
+ } finally {
1973
+ setBusy(false)
1974
+ }
1975
+ }, [preview, t])
1976
+
1977
+ const copy = React.useCallback(async () => {
1978
+ try {
1979
+ await navigator.clipboard.writeText(preview)
1980
+ setToast(t('toast.copied'))
1981
+ } catch (error) {
1982
+ setToast(String(error))
1983
+ }
1984
+ }, [preview, t])
1985
+
1986
+ const unbind = React.useCallback(async () => {
1987
+ if (sessionId === undefined) return
1988
+ await fetch(ROUTES.binding, {
1989
+ method: 'POST',
1990
+ headers: { 'content-type': 'application/json' },
1991
+ body: JSON.stringify({ dshSessionId: sessionId, forget: true }),
1992
+ })
1993
+ // Drop the write cache too, or a later visit to the same
1994
+ // conversation would be silently skipped as "already bound".
1995
+ forgetBoundPairs(sessionId)
1996
+ setBound(null)
1997
+ setToast(t('toast.rebound'))
1998
+ navigate(PAGE_URL)
1999
+ }, [sessionId, t])
2000
+
2001
+ const state = guestState()
2002
+ const statusText = state.failure !== ''
2003
+ ? format(t('status.failed'), { error: state.failure })
2004
+ : (bound !== null ? format(t('status.bound'), { id: bound }) : t('status.unbound'))
2005
+
2006
+ // A glyph, not a sentence: the full status is the tooltip, because a
2007
+ // failure message is far too long for a toolbar.
2008
+ const statusGlyph = state.failure !== '' ? '⚠' : (bound !== null ? '●' : '○')
2009
+
2010
+ const toolbar = h('div', { className: 'dswc-toolbar' }, [
2011
+ h('span', {
2012
+ key: 'status',
2013
+ className: 'dswc-status',
2014
+ title: statusText,
2015
+ role: 'img',
2016
+ 'aria-label': statusText,
2017
+ 'data-state': state.failure !== '' ? 'error' : (bound !== null ? 'bound' : 'unbound'),
2018
+ }, statusGlyph),
2019
+ h('span', { key: 'gap', className: 'dswc-gap' }),
2020
+ h('button', {
2021
+ key: 'send',
2022
+ type: 'button',
2023
+ className: 'dswc-button',
2024
+ onClick: () => setPickerOpen((open) => !open),
2025
+ }, pickerOpen ? t('action.back') : t('action.send')),
2026
+ h('button', {
2027
+ key: 'reload',
2028
+ type: 'button',
2029
+ className: 'dswc-button',
2030
+ onClick: () => {
2031
+ if (guest !== null) {
2032
+ try {
2033
+ guest.element.reload()
2034
+ } catch (error) {
2035
+ // Nothing to reload.
2036
+ }
2037
+ }
2038
+ },
2039
+ }, t('action.reload')),
2040
+ h('button', {
2041
+ key: 'unbind',
2042
+ type: 'button',
2043
+ className: 'dswc-button',
2044
+ disabled: bound === null,
2045
+ onClick: () => void unbind(),
2046
+ }, t('action.rebind')),
2047
+ ])
2048
+
2049
+ const toastRow = toast === ''
2050
+ ? null
2051
+ : h('div', { className: 'dswc-toast' }, toast)
2052
+
2053
+ if (!state.hasBridge) {
2054
+ return h('div', { className: 'dswc-root' }, [
2055
+ toolbar,
2056
+ h('div', { key: 'notice', className: 'dswc-notice' }, [
2057
+ h('p', { key: 'a' }, t('status.nobridge')),
2058
+ h('p', { key: 'b', className: 'dswc-muted' }, t('status.nobridgeHint')),
2059
+ ]),
2060
+ ])
2061
+ }
2062
+
2063
+ if (!pickerOpen) {
2064
+ return h('div', { className: 'dswc-root' }, [
2065
+ toolbar,
2066
+ h('div', { key: 'host', className: 'dswc-host', ref: hostRef }),
2067
+ toastRow,
2068
+ ])
2069
+ }
2070
+
2071
+ // Paged from the newest rows backwards. The list opens scrolled to the
2072
+ // bottom, so the newest few are what a person reads and picks from;
2073
+ // older rows are pulled in a page at a time from the top. Selection is
2074
+ // by `seq`, not by mounted row, so 全选 and 选末尾 still act on the whole
2075
+ // session however few rows are on screen.
2076
+ const total = messages === null ? 0 : messages.length
2077
+ const start = Math.max(0, total - pageSize)
2078
+ const hiddenEarlier = start > 0
2079
+ const shown = messages === null ? null : messages.slice(start)
2080
+ const list = shown === null
2081
+ ? h('div', { className: 'dswc-notice' }, t('picker.loading'))
2082
+ : shown.length === 0
2083
+ ? h('div', { className: 'dswc-notice' }, [
2084
+ h('p', { key: 'a' }, advanced ? t('picker.emptyAdvanced') : t('picker.empty')),
2085
+ loadError === '' ? null : h('p', { key: 'b', className: 'dswc-muted' }, loadError),
2086
+ ])
2087
+ : h('div', { className: 'dswc-list', ref: listRef }, [
2088
+ hiddenEarlier
2089
+ ? h('div', { key: 'more', className: 'dswc-more' }, [
2090
+ h('button', {
2091
+ key: 'load',
2092
+ type: 'button',
2093
+ className: 'dswc-button',
2094
+ onClick: () => {
2095
+ // Remember the topmost visible row, so the effect
2096
+ // above can hold the reader's place while the
2097
+ // earlier rows are inserted above it.
2098
+ const node = listRef.current
2099
+ const first = node === null
2100
+ ? null
2101
+ : node.querySelector('.dswc-row')
2102
+ anchoredRef.current = first === null
2103
+ ? null
2104
+ : first.getAttribute('data-seq')
2105
+ setPageSize((size) => size + LIST_PAGE_SIZE)
2106
+ },
2107
+ }, format(t('action.loadEarlier'), {
2108
+ count: Math.min(LIST_PAGE_SIZE, start),
2109
+ })),
2110
+ h('span', { key: 'left', className: 'dswc-muted' },
2111
+ format(t('picker.hiddenEarlier'), { count: start })),
2112
+ ])
2113
+ : null,
2114
+ ...shown.map((row) => h('label', {
2115
+ key: row.seq,
2116
+ className: 'dswc-row',
2117
+ 'data-role': row.role,
2118
+ 'data-kind': row.kind ?? row.role,
2119
+ 'data-seq': String(row.seq),
2120
+ }, [
2121
+ h('input', {
2122
+ key: 'box',
2123
+ type: 'checkbox',
2124
+ checked: selected.has(row.seq),
2125
+ onChange: () => toggle(row.seq),
2126
+ }),
2127
+ h('span', {
2128
+ key: 'role',
2129
+ className: 'dswc-role',
2130
+ title: kindLabel(row, labels),
2131
+ }, [
2132
+ KindIcon(row.kind ?? row.role),
2133
+ h('span', { key: 'label', className: 'dswc-roleLabel' }, kindLabel(row, labels)),
2134
+ ]),
2135
+ h('span', { key: 'text', className: 'dswc-text' }, row.text),
2136
+ ])),
2137
+ ])
2138
+
2139
+ return h('div', { className: 'dswc-root' }, [
2140
+ toolbar,
2141
+ h('div', { key: 'picker', className: 'dswc-picker' }, [
2142
+ h('div', { key: 'head', className: 'dswc-pickerHead' }, [
2143
+ h('span', { key: 'title', className: 'dswc-pickerTitle' }, t('picker.title')),
2144
+ h('span', { key: 'count', className: 'dswc-muted' },
2145
+ format(t('picker.selected'), { count: chosen.length })),
2146
+ h('span', { key: 'gap', className: 'dswc-gap' }),
2147
+ h('button', {
2148
+ key: 'all',
2149
+ type: 'button',
2150
+ className: 'dswc-button',
2151
+ onClick: () => setSelected(new Set((messages ?? []).map((row) => row.seq))),
2152
+ }, t('action.all')),
2153
+ h('button', {
2154
+ key: 'none',
2155
+ type: 'button',
2156
+ className: 'dswc-button',
2157
+ onClick: () => setSelected(new Set()),
2158
+ }, t('action.none')),
2159
+ // Quoting the tail of a conversation is the common case, so
2160
+ // it gets its own control instead of asking for hand-ticking.
2161
+ h('select', {
2162
+ key: 'lastN',
2163
+ className: 'dswc-select',
2164
+ title: t('picker.lastCount'),
2165
+ 'aria-label': t('picker.lastCount'),
2166
+ value: String(lastN),
2167
+ onChange: (event) => setLastN(Number(event.target.value)),
2168
+ }, [5, 10, 20, 50].map((n) => h('option', { key: n, value: String(n) }, String(n)))),
2169
+ h('button', {
2170
+ key: 'last',
2171
+ type: 'button',
2172
+ className: 'dswc-button',
2173
+ disabled: (messages ?? []).length === 0,
2174
+ onClick: () => {
2175
+ const rows = messages ?? []
2176
+ setSelected(new Set(
2177
+ rows.slice(Math.max(0, rows.length - lastN)).map((row) => row.seq),
2178
+ ))
2179
+ },
2180
+ }, t('action.last')),
2181
+ h('button', {
2182
+ key: 'refresh',
2183
+ type: 'button',
2184
+ className: 'dswc-button',
2185
+ onClick: () => setReload((value) => value + 1),
2186
+ }, t('action.refresh')),
2187
+ // The advanced switch swaps the whole row set rather than
2188
+ // revealing hidden rows: the host filters, so a tool result the
2189
+ // user never opted into is never sent to the browser at all.
2190
+ h('label', {
2191
+ key: 'advanced',
2192
+ className: 'dswc-advanced',
2193
+ title: t('picker.advancedHint'),
2194
+ }, [
2195
+ h('input', {
2196
+ key: 'box',
2197
+ type: 'checkbox',
2198
+ checked: advanced,
2199
+ onChange: (event) => {
2200
+ setAdvanced(event.target.checked)
2201
+ // Selections refer to rows that may no longer exist.
2202
+ setSelected(new Set())
2203
+ },
2204
+ }),
2205
+ h('span', { key: 'text' }, t('picker.advanced')),
2206
+ ]),
2207
+ h('label', {
2208
+ key: 'preamble',
2209
+ className: 'dswc-advanced',
2210
+ title: t('picker.preambleHint'),
2211
+ }, [
2212
+ h('input', {
2213
+ key: 'box',
2214
+ type: 'checkbox',
2215
+ checked: preamble,
2216
+ onChange: (event) => setPreamble(event.target.checked),
2217
+ }),
2218
+ h('span', { key: 'text' }, t('picker.preamble')),
2219
+ ]),
2220
+ ]),
2221
+ list,
2222
+ h('div', { key: 'compose', className: 'dswc-compose' }, [
2223
+ h('label', { key: 'qlabel', className: 'dswc-label' }, t('picker.question')),
2224
+ h('textarea', {
2225
+ key: 'question',
2226
+ className: 'dswc-question',
2227
+ rows: 3,
2228
+ value: question,
2229
+ placeholder: t('picker.questionPlaceholder'),
2230
+ onChange: (event) => setQuestion(event.target.value),
2231
+ }),
2232
+ h('label', { key: 'plabel', className: 'dswc-label' }, t('picker.preview')),
2233
+ h('pre', { key: 'preview', className: 'dswc-preview' }, preview),
2234
+ h('p', { key: 'hint', className: 'dswc-muted' }, t('picker.hint')),
2235
+ h('div', { key: 'actions', className: 'dswc-actions' }, [
2236
+ h('button', {
2237
+ key: 'send',
2238
+ type: 'button',
2239
+ className: 'dswc-button dswc-primary',
2240
+ disabled: busy || preview.trim() === '',
2241
+ onClick: () => void push(true),
2242
+ }, busy ? t('status.filling') : t('action.fill')),
2243
+ h('button', {
2244
+ key: 'fill',
2245
+ type: 'button',
2246
+ className: 'dswc-button',
2247
+ disabled: busy || preview.trim() === '',
2248
+ onClick: () => void push(false),
2249
+ }, t('action.fillOnly')),
2250
+ h('button', {
2251
+ key: 'copy',
2252
+ type: 'button',
2253
+ className: 'dswc-button',
2254
+ disabled: preview.trim() === '',
2255
+ onClick: () => void copy(),
2256
+ }, t('action.copy')),
2257
+ ]),
2258
+ ]),
2259
+ ]),
2260
+ toastRow,
2261
+ ])
2262
+ }
2263
+
2264
+ //#endregion
2265
+
2266
+ /**
2267
+ * A one-click door in the conversation header, so the tab does not have to
2268
+ * be reached through the column's guide.
2269
+ *
2270
+ * The chrome comes from `.dswc-headerButton`, which copies the built-in
2271
+ * icon buttons in that row: a 24px square, an 8px radius, muted ink and a
2272
+ * translucent hover. The glyph is the same 16px/1px bubble the guide uses.
2273
+ *
2274
+ * @param props - standard props plus the injected `open`.
2275
+ */
2276
+ function HeaderButton(props) {
2277
+ const t = props.t ?? fallbackTranslate()
2278
+ const label = t('action.send')
2279
+ return h('button', {
2280
+ type: 'button',
2281
+ className: 'dswc-headerButton',
2282
+ title: label,
2283
+ 'aria-label': label,
2284
+ onClick: () => props.open(),
2285
+ }, ChatBubbleGlyph({}))
2286
+ }
2287
+
2288
+ /** Register the tab type, its guide door, and its body. */
2289
+ function apply(ctx) {
2290
+ ensureStyle()
2291
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'deepseek-webchat: copy')
2292
+ const t = ctx.locale.bind(NS)
2293
+ ctx.effect(() => ctx.sidebarRightTabs.register({
2294
+ id: TAB_ID,
2295
+ kind: TAB_KIND,
2296
+ title: () => t('type.label'),
2297
+ // A `<webview>` dies when it leaves the document, so the body must
2298
+ // outlive a tab switch for the page (and a half-typed question) to
2299
+ // survive one.
2300
+ keepMounted: true,
2301
+ guide: [{
2302
+ id: 'open',
2303
+ order: 40,
2304
+ title: () => t('guide.title'),
2305
+ description: () => t('guide.description'),
2306
+ icon: GuideArtwork,
2307
+ }],
2308
+ }), 'deepseek-webchat: tab type')
2309
+ ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
2310
+ name: 'sidebar.right.pane.tab',
2311
+ key: TAB_ID,
2312
+ locale: NS,
2313
+ inject: (sessionId) => ({ sessionId }),
2314
+ }, DeepSeekBody)), 'deepseek-webchat: body')
2315
+ ctx.effect(() => ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({
2316
+ name: 'conversation.session.header.utilities',
2317
+ id: 'deepseek-webchat',
2318
+ order: 20,
2319
+ locale: NS,
2320
+ inject: (sessionId) => ({
2321
+ open: () => ctx.sidebarRight.openTabIn(sessionId, TAB_KIND, { revealIfOpened: true }),
2322
+ }),
2323
+ }, HeaderButton)), 'deepseek-webchat: header door')
2324
+ ctx.effect(() => () => {
2325
+ disposeGuest()
2326
+ }, 'deepseek-webchat: guest lifetime')
2327
+ }
2328
+
2329
+ const inject = ['slots', 'locale', 'sidebarRight', 'sidebarRightTabs']
2330
+
2331
+ exports.apply = apply
2332
+ exports.inject = inject
2333
+ return module.exports
2334
+ },
2335
+ })