@ggboy123/dsh-paper-reader 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -33,8 +33,8 @@
33
33
  * 阅读器是同源 iframe,但它的 <head> 首帧判定发生在网络请求之前 ⇒ 必须有一个**同步**可读的镜像。
34
34
  * 配置的权威来源仍是服务端 /api/theme/config;这里只是镜像,写失败(隐私模式)不影响功能。
35
35
  */
36
- const DPR_THEME_PREF_KEY = 'dpr.pdfTheme'
37
- const DPR_THEME_MIRROR_KEY = 'dpr.pdfThemeCfg'
36
+ // classic script 会在更新 / 停用再启用时整文件重执行:顶层只放 function 声明,
37
+ // 禁止 const / let / class(旧版本的全局 lexical 也可能还在,var 同样会撞)。
38
38
  function dprThemeMirror(cfg) {
39
39
  if (!cfg || typeof cfg !== 'object') return null
40
40
  const mode = ['follow', 'off', 'light', 'dark'].includes(cfg.pdfTheme) ? cfg.pdfTheme : 'follow'
@@ -45,8 +45,8 @@ function writeThemeMirror(cfg) {
45
45
  const mir = dprThemeMirror(cfg)
46
46
  if (!mir) return null
47
47
  try {
48
- localStorage.setItem(DPR_THEME_PREF_KEY, mir.mode)
49
- localStorage.setItem(DPR_THEME_MIRROR_KEY, JSON.stringify(mir))
48
+ localStorage.setItem('dpr.pdfTheme', mir.mode)
49
+ localStorage.setItem('dpr.pdfThemeCfg', JSON.stringify(mir))
50
50
  } catch { /* 隐私模式:写不了镜像,阅读器仍可从服务端/宿主 postMessage 拿到 */ }
51
51
  return mir
52
52
  }
@@ -174,7 +174,7 @@ function dprClearRetryNeeded(err) {
174
174
  * 反例:若塞进 `dpr.variant.<topic>/<name>`(按篇),改名搬家会搬它,而「全局」语义就破了。
175
175
  * ③ 缺省 = 开:与改造前「分屏两列被 rAF 强行同步」的既有行为一致(老用户升级后观感不变)。
176
176
  */
177
- const DPR_SYNC_SCROLL_KEY = 'dpr.syncScroll'
177
+ function dprSyncScrollKey() { return 'dpr.syncScroll' }
178
178
  /** 只认显式的 '0' 为关;缺失 / 脏值 / 隐私模式都算开(与 reader 的 readSyncPref 逐字同义)。 */
179
179
  function dprSyncScrollFromRaw(raw) { return raw !== '0' }
180
180
  function dprSyncScrollRaw(on) { return on ? '1' : '0' }
@@ -186,7 +186,7 @@ window.__ModuleLoader__.load({
186
186
  factory: (require) => {
187
187
  const React = require('react')
188
188
  const { createPortal } = require('react-dom')
189
- const { useState, useEffect, useCallback } = React
189
+ const { useState, useEffect, useCallback, useRef } = React
190
190
  const h = React.createElement
191
191
 
192
192
  const NS = 'dsh-paper-reader'
@@ -207,8 +207,29 @@ window.__ModuleLoader__.load({
207
207
  setRerankDesc: 'search_paper 检索的语义重排:关键词先捞候选,Jev 逐个判断「这段能否回答这个问题」再排序——大白话提问也能命中论文里的术语段落。不配则退回纯关键词排序。',
208
208
  setEmbedTitle: '嵌入模型检索(可选)',
209
209
  setEmbedDesc: 'search_paper 的语义召回:分块文本会发送到该 OpenAI 兼容 /embeddings 端点,用向量把「关键词一个字都没命中」的语义相近片段也捞进候选(与关键词结果融合,不替代)。留空即关闭,检索行为与现在完全一致。注意:分块文本(论文正文)会发往该端点。',
210
- setTranslateTitle: '翻译端点',
211
- setTranslateDesc: '「生成中文版」(babeldoc)与划词翻译共用的 OpenAI 兼容端点,三项必填。OpenCode Go 填 https://opencode.ai/inference/go/openai/v1(插件会自动带 x-opencode-session)。保存前会先测连接。',
210
+ setTranslateTitle: '全文翻译模型',
211
+ setTranslateDesc: '生成中文版与划词翻译共用。默认跟随 Harness;专用配置只作用于翻译,不改变宿主模型设置。',
212
+ setTranslateFollow: '跟随 Harness', setTranslateCustom: '使用自定义模型', setTranslateDefault: '默认',
213
+ setTranslateFollowDesc: '与 Harness 当前模型保持一致', setTranslateCustomDesc: '翻译任务单独使用另一套配置',
214
+ setTranslateCurrentFollow: '当前跟随',
215
+ setTranslateFollowNote: 'Harness 切换模型后,下次翻译自动跟随;进行中的整篇翻译不变。',
216
+ setTranslateUnavailable: 'Harness 当前模型不可用,请先在 Harness 中完成模型设置。',
217
+ setTranslateProviders: '翻译服务商', setTranslateApplyKey: '申请 API Key',
218
+ setTranslateKeyAuto: '粘贴 Key 后自动验证并获取模型;选择模型后保存。',
219
+ setTranslateDiscovering: '正在验证 Key 并获取模型…', setTranslateModels: '选择翻译模型',
220
+ setTranslateRefresh: '刷新列表', setTranslateAdvanced: '高级设置:整篇 PDF 翻译参数',
221
+ setTranslateSplitTokens: '单段上下文上限(tokens)', setTranslateSplitHint: '超过后自动拆段;调小可减少单次上下文,调大可减少拆段次数。',
222
+ setTranslateMaxOutput: '单次输出上限(tokens)', setTranslateMaxOutputHint: '0 表示跟随端点默认,不传 max_tokens。',
223
+ setTranslateQps: '并发请求数(QPS)', setTranslateQpsHint: '过高容易触发端点限流;遇到 429 时可调低。',
224
+ setTranslateOptionsSave: '保存翻译参数', setTranslateOptionsSaved: '翻译参数已保存,下一篇 PDF 起生效',
225
+ setTranslateManualModel: '手动模型名', setTranslateUse: '使用', setTranslateUsing: '使用中',
226
+ setTranslateFollowSet: '已恢复为跟随 Harness,自定义配置已保留',
227
+ setTranslateScopeFollow: '跟随模式不保存或复制 Harness 的 Key,也不会改写 Harness 配置。',
228
+ setTranslateScopeCustom: '自定义配置仅用于翻译,不会写入或改变 Harness 的模型设置。',
229
+ setTranslateDelete: '删除此配置', setTranslateDeleteConfirm: '确认删除?', setTranslateDeleted: '已删除专用配置',
230
+ setTranslateEmpty: '填写 API Key 后,模型列表会自动出现在这里。',
231
+ setTranslateDiscovered: '已获取 {n} 个模型,请选择翻译模型', setTranslateSaved: '翻译模型已保存,仅影响翻译',
232
+ setTranslateConnected: '已连接', setTranslateSavedShort: '已保存', setTranslateSavedCount: '已保存 {n} 个', setTranslateNoModels: '暂无模型',
212
233
  setBaseUrl: '端点 URL', setModel: '模型', setKey: 'API Key',
213
234
  setSave: '测试并保存', setSaving: '测试连接中…', setClear: '清除自填配置',
214
235
  setSaved: '已保存,立即生效', setCleared: '已清除,回落到部署方默认',
@@ -315,8 +336,29 @@ window.__ModuleLoader__.load({
315
336
  setRerankDesc: 'Semantic rerank for search_paper: keyword search shortlists candidates, Jev judges "can this passage answer the question" and reorders — plain-language questions hit terminology passages. Without it, plain keyword ranking is used.',
316
337
  setEmbedTitle: 'Embedding search (optional)',
317
338
  setEmbedDesc: 'Semantic recall for search_paper: chunk texts are sent to this OpenAI-compatible /embeddings endpoint so passages that share no keywords but are semantically close still enter the candidate set (fused with keyword hits, never replacing them). Leave empty to keep it off — search behaviour stays exactly as today. Note: chunk texts (paper body) are sent to this endpoint.',
318
- setTranslateTitle: 'Translate endpoint',
319
- setTranslateDesc: 'OpenAI-compatible endpoint shared by "Generate Chinese version" (babeldoc) and selection translation; all three fields required. For OpenCode Go use https://opencode.ai/inference/go/openai/v1 (the plugin adds x-opencode-session automatically). Connection is tested before saving.',
339
+ setTranslateTitle: 'Translation model',
340
+ setTranslateDesc: 'Shared by generated Chinese PDFs and selection translation. Follow Harness by default, or override only translation without changing Harness settings.',
341
+ setTranslateFollow: 'Follow Harness', setTranslateCustom: 'Use a custom model', setTranslateDefault: 'Default',
342
+ setTranslateFollowDesc: 'Track the current Harness model', setTranslateCustomDesc: 'Use a separate endpoint only for translation',
343
+ setTranslateCurrentFollow: 'Currently following',
344
+ setTranslateFollowNote: 'New translations follow Harness model changes; an in-flight PDF keeps its original model.',
345
+ setTranslateUnavailable: 'The current Harness model is unavailable. Finish Harness model setup first.',
346
+ setTranslateProviders: 'Translation provider', setTranslateApplyKey: 'Get an API key',
347
+ setTranslateKeyAuto: 'Paste a key to validate and fetch models automatically; choose a model to save.',
348
+ setTranslateDiscovering: 'Validating key and fetching models…', setTranslateModels: 'Translation model',
349
+ setTranslateRefresh: 'Refresh', setTranslateAdvanced: 'Advanced: whole-PDF translation options',
350
+ setTranslateSplitTokens: 'Context per chunk (tokens)', setTranslateSplitHint: 'Longer chunks are split automatically. Lower this to reduce per-request context; raise it for fewer requests.',
351
+ setTranslateMaxOutput: 'Output cap per request (tokens)', setTranslateMaxOutputHint: '0 uses the provider default and omits max_tokens.',
352
+ setTranslateQps: 'Requests per second (QPS)', setTranslateQpsHint: 'High values can trigger rate limits. Lower this after HTTP 429 responses.',
353
+ setTranslateOptionsSave: 'Save translation options', setTranslateOptionsSaved: 'Translation options saved; applies to the next PDF task',
354
+ setTranslateManualModel: 'Manual model ID', setTranslateUse: 'Use', setTranslateUsing: 'In use',
355
+ setTranslateFollowSet: 'Translation now follows Harness; custom endpoints are kept',
356
+ setTranslateScopeFollow: 'Follow mode never copies Harness keys or changes Harness configuration.',
357
+ setTranslateScopeCustom: 'This endpoint is used only for translation and never changes Harness model settings.',
358
+ setTranslateDelete: 'Delete this endpoint', setTranslateDeleteConfirm: 'Confirm delete?', setTranslateDeleted: 'Custom endpoint deleted',
359
+ setTranslateEmpty: 'Enter an API key above and available models will appear here.',
360
+ setTranslateDiscovered: 'Found {n} models. Choose one for translation.', setTranslateSaved: 'Translation model saved; Harness is unchanged',
361
+ setTranslateConnected: 'Connected', setTranslateSavedShort: 'Saved', setTranslateSavedCount: '{n} saved', setTranslateNoModels: 'No models yet',
320
362
  setBaseUrl: 'Endpoint URL', setModel: 'Model', setKey: 'API Key',
321
363
  setSave: 'Test & save', setSaving: 'Testing…', setClear: 'Clear my config',
322
364
  setSaved: 'Saved, effective immediately', setCleared: 'Cleared, falling back to deployment defaults',
@@ -423,7 +465,7 @@ window.__ModuleLoader__.load({
423
465
  function pushThemeToReader() {
424
466
  const payload = { type: 'dpr:theme' }
425
467
  try {
426
- const mir = JSON.parse(localStorage.getItem(DPR_THEME_MIRROR_KEY) || 'null')
468
+ const mir = JSON.parse(localStorage.getItem('dpr.pdfThemeCfg') || 'null')
427
469
  if (mir) { payload.mode = mir.mode; payload.strength = mir.strength; payload.chrome = mir.chrome; payload.curve = mir.curve }
428
470
  } catch { /* 镜像损坏:仍然推宿主亮暗 */ }
429
471
  const effective = payload.mode === 'dark' || (payload.mode !== 'off' && payload.mode !== 'light' && dprHostDark) ? 'dark' : 'light'
@@ -432,6 +474,7 @@ window.__ModuleLoader__.load({
432
474
  }
433
475
  function jumpToPaperPage(topic, name, page, q) {
434
476
  // 阅读器页签若关着尽量展开(seat 未绑定时静默失败,跳转本身仍生效)
477
+ noteSwapIntent()
435
478
  try { clientApi?.sidebarRight?.openTab('dpr-reader', { revealIfOpened: true }) } catch {}
436
479
  const cur = JSON.parse(localStorage.getItem('dpr.last') || 'null')
437
480
  const tp = topic || cur?.topic, nm = name || cur?.name
@@ -539,13 +582,43 @@ window.__ModuleLoader__.load({
539
582
  (applySwap 照跑:新面板的 maxWidth 钳制要尽快钉上,防左溢盖侧栏);
540
583
  ③ [data-rightbar-instant] 连带杀掉面板 transform 过渡(官方只管 grid/handle)。
541
584
  窗口结束对账:若右栏面板确实没开着(护栏期间被收起/开页签失败),
542
- 补一次真实 close,让 grid 回到真状态。 */
543
- const SWITCH_GUARD_MS = 1500
585
+ 补一次真实 close,让 grid 回到真状态。
586
+ 窗口长度取「首帧 + 1~2 帧」(450ms):护栏原来 1500ms 是为了压住 seat 重绑的
587
+ 百毫秒级暂态,收窄后 PDF 消失又出现的回归靠「只在已有 PDF 在显示时冻结」+
588
+ 退出护栏立刻重测一次几何来兜(P7)。 */
589
+ const SWITCH_GUARD_MS = 400
544
590
  let switching = false
545
591
  let switchTimer = 0
546
592
  let realCloseRightbar = null
547
593
  let layoutService = null
548
594
 
595
+ /* ---------- P5:先钉轨、再开页签 ----------
596
+ 历史顺序:openTab → 右栏轨撑开 → overlay 先按「换轨前」的锚点把 iframe 画在右边 →
597
+ 下一拍 applySwap 钉列 → iframe 再挪到左边(用户实测:PDF 右边先出现再跳左边),
598
+ 阅读器还要按新宽度重画一次。现在改成:点论文的**同一时刻**记一个「换轨意图」,
599
+ applySwap 据此在右栏轨还没撑开时先把列钉好 —— 等轨撑开时列已经换完,没有翻位。
600
+ 安全网:页签 3s 内没出现(或阅读器回报 dpr:open-failed)就撤钉回滚,绝不留下
601
+ 「宽轨空着、对话被挤窄」的错位;官方其它右栏页签(文件预览/present)不触发意图。 */
602
+ const SWAP_INTENT_MS = 3000
603
+ let swapIntentAt = 0
604
+ let swapIntentTimer = 0
605
+ let requestOverlayTick = null // ReaderOverlay 把它的 rAF 合并 tick 挂进来
606
+ function noteSwapIntent() {
607
+ swapIntentAt = Date.now()
608
+ clearTimeout(swapIntentTimer)
609
+ swapIntentTimer = setTimeout(() => {
610
+ swapIntentAt = 0
611
+ swapIntentTimer = 0
612
+ try { requestOverlayTick?.() } catch { /* 已卸载 */ }
613
+ }, SWAP_INTENT_MS)
614
+ }
615
+ function clearSwapIntent() {
616
+ swapIntentAt = 0
617
+ clearTimeout(swapIntentTimer)
618
+ swapIntentTimer = 0
619
+ try { requestOverlayTick?.() } catch { /* 已卸载 */ }
620
+ }
621
+
549
622
  function beginSwitchGuard() {
550
623
  switching = true
551
624
  document.querySelector('[data-rightbar-col]')?.parentElement?.setAttribute('data-rightbar-instant', '')
@@ -564,24 +637,52 @@ window.__ModuleLoader__.load({
564
637
  if (!panelOpen) {
565
638
  try { layoutService.closeRightbar() } catch { /* 上下文已销毁 */ }
566
639
  }
640
+ // 撤护栏立刻重测一次:否则要等下一拍(≤1s)几何才归位
641
+ try { requestOverlayTick?.() } catch { /* 已卸载 */ }
567
642
  }, SWITCH_GUARD_MS)
568
643
  }
569
644
 
570
- /* ---------- 阅读器悬浮层:一个跨会话永不重建的 iframe ----------
645
+ /* ---------- 阅读器悬浮层:一个跨会话、跨论文永不重建的 iframe ----------
571
646
  rightbar 页签内容跟随会话 seat 重绑整体重建(TabSlot 以 tab.id 为 key,
572
647
  新会话的 rightbar 布局里没有旧 tab)——iframe 每次重载,滚动/缩放全丢
573
648
  ("新建对话整页都动")。改为:PdfTab 只渲染占位锚点;真正的 iframe 由
574
649
  ReaderOverlay 常驻渲染(挂在 LibraryTree 下,不随会话变),fixed 覆盖在锚点矩形上,
575
- 200ms 轮询跟随;锚点消失(关页签/收右栏/全屏)时隐藏但 iframe 存活。 */
650
+ 锚点消失(关页签/收右栏/全屏)时隐藏但 iframe 存活。
651
+ P1(论文切换性能):src 只在**首次创建**时定稿,之后换论文不再导航 —— 走
652
+ postMessage `{type:'dpr:open', topic, name, page?, q?}` 让阅读器原地 openPaper。
653
+ 阅读器载完回 `{type:'dpr:ready'}` 握手;没握手(首开/回退)或原地换失败
654
+ (回 `{type:'dpr:open-failed'}`)时退回「改 src 整页导航」的旧路径,保证一定切得过去。 */
655
+ const readerSrcOf = (c) => `/paper-reader/?topic=${encodeURIComponent(c.topic)}&name=${encodeURIComponent(c.name)}${c.page ? '&page=' + c.page : ''}${c.q ? '&q=' + encodeURIComponent(c.q) : ''}`
656
+ function sendReaderOpen(c) {
657
+ const win = readerIframeEl && readerIframeEl.contentWindow
658
+ if (!win) return false
659
+ try {
660
+ // 只投给同源阅读器;payload 只有论文坐标与跳转参数,不带路径/凭据
661
+ win.postMessage({ type: 'dpr:open', topic: c.topic, name: c.name, page: c.page || 0, q: c.q || '' }, location.origin)
662
+ return true
663
+ } catch { return false }
664
+ }
576
665
  function ReaderOverlay() {
577
666
  const [cur, setCur] = useState(() => JSON.parse(localStorage.getItem('dpr.last') || 'null'))
667
+ // src 定稿后不再随 cur 变(只有回退路径会显式改它)
668
+ const [src, setSrc] = useState(() => {
669
+ try {
670
+ const c = JSON.parse(localStorage.getItem('dpr.last') || 'null')
671
+ return c && c.topic && c.name ? readerSrcOf(c) : null
672
+ } catch { return null }
673
+ })
578
674
  const [geo, setGeo] = useState({ visible: false, left: 0, top: 0, width: 0, height: 0 })
579
675
  const lastShownRef = React.useRef(0)
676
+ const readyRef = React.useRef(false) // 阅读器已握手:可以收 dpr:open 原地换文献
677
+ const bootRef = React.useRef(null) // 当前文档 boot 的是哪一篇(决定握手后要不要补发)
678
+ const failedRef = React.useRef('') // 最近一次原地换失败的「topic/name」:重载后不再自动重试,防死循环
679
+ const curRef = React.useRef(cur)
680
+ curRef.current = cur
580
681
  useEffect(() => {
581
682
  const on = (e) => {
582
683
  // 空库(最后一篇被删):撤掉阅读器 iframe,回到「从文献库选择一篇论文」占位
583
684
  if (e.detail.empty) { try { localStorage.removeItem('dpr.last') } catch {}; setCur(null); return }
584
- // 跳转链接挂的页码/引文(jumpToPaperPage 的跨论文路径):随 src 传给阅读器 bootstrap
685
+ // 跳转链接挂的页码/引文(jumpToPaperPage 的跨论文路径):随请求传给阅读器
585
686
  const j = pendingJump
586
687
  pendingJump = null
587
688
  setCur({ topic: e.detail.topic, name: e.detail.name, page: j?.page, q: j?.q })
@@ -589,6 +690,54 @@ window.__ModuleLoader__.load({
589
690
  window.addEventListener('dpr:paper', on)
590
691
  return () => window.removeEventListener('dpr:paper', on)
591
692
  }, [])
693
+ // 阅读器握手 / 原地换失败回退(只认本插件 iframe 的同源消息)
694
+ useEffect(() => {
695
+ const onMsg = (e) => {
696
+ if (e.origin !== location.origin) return
697
+ const win = readerIframeEl && readerIframeEl.contentWindow
698
+ if (!win || e.source !== win) return
699
+ const d = e.data
700
+ if (!d || typeof d !== 'object') return
701
+ if (d.type === 'dpr:ready') {
702
+ readyRef.current = true
703
+ // 握手前用户已经切过论文 / 带了跳转参数:补发一次,否则 iframe 里还停在 boot 那篇
704
+ const c = curRef.current
705
+ const b = bootRef.current
706
+ // 刚原地换失败过的那一篇不再自动补发:否则重载后又发一次同样的坏请求,
707
+ // src 也没得改 → 死在「加载 PDF…」。重载后的 bootstrap 会按库回落到好论文。
708
+ const tried = c ? c.topic + '/' + c.name : ''
709
+ if (c && failedRef.current !== tried && (!b || c.topic !== b.topic || c.name !== b.name || c.page || c.q)) sendReaderOpen(c)
710
+ return
711
+ }
712
+ if (d.type === 'dpr:open-failed') {
713
+ // 原地换失败:退回旧路径(改 src 重新导航),保证一定能切过去;并撤掉换轨意图
714
+ clearSwapIntent()
715
+ readyRef.current = false
716
+ const c = curRef.current
717
+ if (c && c.topic && c.name) {
718
+ failedRef.current = c.topic + '/' + c.name
719
+ bootRef.current = { topic: c.topic, name: c.name }
720
+ setSrc(readerSrcOf(c))
721
+ }
722
+ }
723
+ }
724
+ window.addEventListener('message', onMsg)
725
+ return () => window.removeEventListener('message', onMsg)
726
+ }, [])
727
+ // cur 变化:握手了就 postMessage 原地换;没握手就沿用「改 src 整页导航」(行为与旧版一致)
728
+ useEffect(() => {
729
+ if (!cur) {
730
+ readyRef.current = false
731
+ bootRef.current = null
732
+ setSrc(null)
733
+ return
734
+ }
735
+ failedRef.current = '' // 换了目标就不再记着上次的失败,允许重新尝试原地换
736
+ if (readyRef.current && sendReaderOpen(cur)) return
737
+ bootRef.current = { topic: cur.topic, name: cur.name }
738
+ const want = readerSrcOf(cur)
739
+ setSrc((prev) => (prev === want ? prev : want))
740
+ }, [cur])
592
741
  useEffect(() => {
593
742
  let alive = true
594
743
  // 布局换位:rightbar 列(PDF) ↔ center 列(对话) 交换视觉位置。列+行都钉
@@ -611,8 +760,14 @@ window.__ModuleLoader__.load({
611
760
  const tracks = getComputedStyle(frame).gridTemplateColumns.split(' ').map(parseFloat)
612
761
  const tabEl = document.querySelector('[data-dpr-tab]')
613
762
  if (tabEl) lastPdfTabAt = Date.now()
614
- const eff = (!!tabEl || Date.now() - lastPdfTabAt < 1500) && (tracks[2] ?? 0) >= 50 && !frame.hasAttribute('data-rightbar-fullscreen')
615
- // 所有写入带值守卫:重复写同值也会触发样式重算,200ms 轮询下会闪
763
+ // P5:意图期内、页签还没出现 → 右栏轨还是 0 也先钉(等它撑开时列已经换好,无翻位)。
764
+ // 页签一旦出现,仍然要求轨宽 ≥50(seat 重绑的空窗期轨会瞬时塌成 0,那时钉列 =
765
+ // 对话被挤成 0 宽,「整屏闪」回归)。意图超时 / 原地换失败会自动撤掉,见 noteSwapIntent。
766
+ const preSwap = swapIntentAt !== 0 && Date.now() - swapIntentAt < SWAP_INTENT_MS && !tabEl
767
+ const eff = (!!tabEl || Date.now() - lastPdfTabAt < 1500 || preSwap)
768
+ && (preSwap || (tracks[2] ?? 0) >= 50)
769
+ && !frame.hasAttribute('data-rightbar-fullscreen')
770
+ // 所有写入带值守卫:重复写同值也会触发样式重算,轮询下会闪
616
771
  setStyle(col, 'gridColumn', eff ? '2' : '')
617
772
  setStyle(col, 'gridRow', eff ? '1' : '')
618
773
  setStyle(center, 'gridColumn', eff ? '3' : '')
@@ -637,8 +792,12 @@ window.__ModuleLoader__.load({
637
792
  setStyle(readerIframeEl, 'zIndex', frame.hasAttribute('data-rightbar-fullscreen') ? String(dockLayer + 2) : '10')
638
793
  }
639
794
  }
795
+ let lastGood = false
640
796
  const tick = () => {
641
797
  if (!alive) return
798
+ // P6:先钉列、再量锚点。applySwap 改的是 gridColumn,后面的 getBoundingClientRect
799
+ // 会同步拿新布局 —— iframe 第一帧就落在左侧轨,不再「右边先出现 → 再跳左边」。
800
+ applySwap()
642
801
  // 切换护栏期:锚点测量/overlay 几何冻结 —— 锚点消失、被面板 transform
643
802
  // 带着滑动、未钳制时左溢错位,都是 seat 重绑的暂态,追着跑 = overlay 乱跳
644
803
  // (实测)。只冻结"正在显示"的场景;首开(从未显示过)不冻结,PDF 照常出现。
@@ -652,6 +811,7 @@ window.__ModuleLoader__.load({
652
811
  next = { visible: true, left: Math.round(r.left), top: Math.round(r.top), width: Math.round(r.width), height: Math.round(r.height) }
653
812
  }
654
813
  }
814
+ lastGood = !!next
655
815
  // 锚点消失只藏不拆,且隐藏带 900ms 迟滞:seat 重绑的百毫秒间隙里
656
816
  // PDF 保持原位显示,不闪(iframe 常驻存活,拆了再挂就重载丢滚动)
657
817
  setGeo((prev) => {
@@ -663,20 +823,73 @@ window.__ModuleLoader__.load({
663
823
  return prev.visible ? { ...prev, visible: false } : prev
664
824
  })
665
825
  }
666
- // applySwap 冻结期照跑(值守卫幂等):新 seat 的面板是全新 DOM,宽度钳制
667
- // (maxWidth)必须尽快钉上,否则面板按内联宽左溢盖住侧栏(实测锚点 x=168)
668
- applySwap()
826
+ }
827
+ // P3:几何跟随从 200ms 轮询改成事件驱动(锚点 ResizeObserver + 右栏 MutationObserver
828
+ // + window resize/scroll),只在**还没显示出来**时按 200ms 快追(首开延迟不变),
829
+ // 稳定显示后退到 1000ms 兜底 —— 稳态每拍不再强制 layout。
830
+ let raf = 0
831
+ let lastEventAt = 0
832
+ const schedule = () => {
833
+ lastEventAt = Date.now()
834
+ if (!alive || raf) return
835
+ raf = requestAnimationFrame(() => { raf = 0; tick() })
836
+ }
837
+ requestOverlayTick = schedule // 护栏结束/回滚撤钉后立刻重测一次几何
838
+ let observed = null
839
+ const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(schedule) : null
840
+ let mo = null
841
+ let moTarget = null
842
+ const watch = () => {
843
+ const col = document.querySelector('[data-rightbar-col]')
844
+ if (col !== moTarget) {
845
+ try { mo?.disconnect() } catch {}
846
+ moTarget = col
847
+ mo = null
848
+ if (col && typeof MutationObserver === 'function') {
849
+ mo = new MutationObserver(schedule)
850
+ // 只盯右栏子树:seat 重绑/页签换人/全屏都在这里冒泡;对话区的流式输出不在此列
851
+ mo.observe(col, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'data-rightbar-fullscreen', 'data-sidebar-right-open'] })
852
+ }
853
+ }
854
+ const anchor = document.querySelector('[data-dsh-surface="rightbar-tab-anchor"]')
855
+ if (ro && anchor !== observed) {
856
+ try { ro.disconnect() } catch {}
857
+ observed = anchor
858
+ if (anchor) ro.observe(anchor)
859
+ }
860
+ }
861
+ let timer = 0
862
+ const arm = () => {
863
+ if (!alive) return
864
+ clearTimeout(timer)
865
+ // 有事件(resize/滚动/右栏 DOM 变)后 2.5s 内保持 200ms 跟随 —— 面板开合/拖拽的
866
+ // 过渡动画期间仍然跟手;稳定下来(且已显示过)才退到 1000ms 兜底。
867
+ const active = Date.now() - lastEventAt < 2500
868
+ timer = setTimeout(() => { watch(); tick(); arm() }, active || !lastGood ? 200 : 1000)
669
869
  }
670
870
  tick()
671
- const timer = setInterval(tick, 200)
672
- return () => { alive = false; clearInterval(timer) }
871
+ watch()
872
+ window.addEventListener('resize', schedule)
873
+ document.addEventListener('scroll', schedule, true)
874
+ arm()
875
+ return () => {
876
+ alive = false
877
+ if (requestOverlayTick === schedule) requestOverlayTick = null
878
+ if (raf) cancelAnimationFrame(raf)
879
+ clearTimeout(timer)
880
+ try { ro?.disconnect() } catch {}
881
+ try { mo?.disconnect() } catch {}
882
+ window.removeEventListener('resize', schedule)
883
+ document.removeEventListener('scroll', schedule, true)
884
+ }
673
885
  }, [])
674
886
  if (!cur) return null
675
- const src = `/paper-reader/?topic=${encodeURIComponent(cur.topic)}&name=${encodeURIComponent(cur.name)}${cur.page ? '&page=' + cur.page : ''}${cur.q ? '&q=' + encodeURIComponent(cur.q) : ''}`
887
+ // 首次创建用 src 定稿;之后恒为同一个 src(原地换论文走 postMessage)
888
+ const bootSrc = src || readerSrcOf(cur)
676
889
  return createPortal(
677
890
  h('iframe', {
678
891
  ref: (el) => { readerIframeEl = el },
679
- src, title: t('pdfTab'),
892
+ src: bootSrc, title: t('pdfTab'),
680
893
  'data-dsh-plugin': 'dsh-paper-reader', 'data-dsh-surface': 'reader-overlay',
681
894
  style: {
682
895
  position: 'fixed', left: geo.left + 'px', top: geo.top + 'px',
@@ -755,11 +968,46 @@ window.__ModuleLoader__.load({
755
968
  } catch { /* 目录未就绪 */ }
756
969
  setAnchor((prev) => (prev && next && prev.top === next.top && prev.right === next.right) || (!prev && !next) ? prev : next)
757
970
  }
971
+ // P3:会话切换 → 订阅目录 store;换位/拖拽/折叠 → resize/scroll;
972
+ // 兜底定时器在「还没对齐到对话列」时保持 200ms 快追(首开与整页渲染不迟到),
973
+ // 对齐稳定后退到 1000ms —— 稳态不再每 200ms 强制 layout。
974
+ let raf = 0
975
+ let lastEventAt = 0
976
+ const schedule = () => {
977
+ lastEventAt = Date.now()
978
+ if (!alive || raf) return
979
+ raf = requestAnimationFrame(() => { raf = 0; tick() })
980
+ }
981
+ let offSessions = null
982
+ try {
983
+ offSessions = uiWorkspace.sessions?.list?.subscribe?.(() => {
984
+ schedule()
985
+ // 目录更新时对话列往往还没换完 DOM:补两拍把按钮对准新头部
986
+ setTimeout(schedule, 150)
987
+ setTimeout(schedule, 600)
988
+ })
989
+ } catch { /* 旧版宿主没有 subscribe:退回纯兜底定时器 */ }
990
+ window.addEventListener('resize', schedule)
991
+ document.addEventListener('scroll', schedule, true)
992
+ let timer = 0
993
+ const arm = () => {
994
+ if (!alive) return
995
+ clearTimeout(timer)
996
+ const col = document.querySelector('[data-rightbar-col]')?.previousElementSibling
997
+ const conv = col?.querySelector('[data-phase]')
998
+ const settled = !!(col && conv && col.getBoundingClientRect().width > 200)
999
+ const active = Date.now() - lastEventAt < 2500
1000
+ timer = setTimeout(() => { tick(); arm() }, settled && !active ? 1000 : 200)
1001
+ }
758
1002
  tick()
759
- const timer = setInterval(tick, 200)
1003
+ arm()
760
1004
  return () => {
761
1005
  alive = false
762
- clearInterval(timer)
1006
+ if (raf) cancelAnimationFrame(raf)
1007
+ clearTimeout(timer)
1008
+ try { offSessions?.() } catch { /* 已释放 */ }
1009
+ window.removeEventListener('resize', schedule)
1010
+ document.removeEventListener('scroll', schedule, true)
763
1011
  const padded = document.querySelector('[data-dpr-pad]')
764
1012
  if (padded) { delete padded.dataset.dprPad; padded.style.marginLeft = '' }
765
1013
  }
@@ -1235,6 +1483,8 @@ window.__ModuleLoader__.load({
1235
1483
  } catch { /* 目录未就绪就不归档(host 侧对账会兜底) */ }
1236
1484
  setCur({ topic, name, n: target.n })
1237
1485
  setCurrentPaper(topic, name, target.n)
1486
+ // P5:在 openTab 之前就声明「本插件页签要开」——applySwap 据此提前钉列
1487
+ noteSwapIntent()
1238
1488
  // 切换护栏:冻结右栏轨道/阅读器几何/面板过渡,只有对话区换内容(见 beginSwitchGuard)
1239
1489
  beginSwitchGuard()
1240
1490
  preOpenPdfTab(target.sessionId, () => activateSession(target.sessionId))
@@ -1933,6 +2183,295 @@ window.__ModuleLoader__.load({
1933
2183
  )
1934
2184
  }
1935
2185
 
2186
+ /* ---------- 全文翻译模型:默认跟随 Harness,可选插件内专用覆盖 ----------
2187
+ 跟随只在每次任务开始时读 agentDefaultModel,由服务端经 ctx.llm 调用;
2188
+ 自定义端点仍写插件自己的 translate.json,两个方向都不调用 Harness saveSelection。 */
2189
+ const TRANSLATE_PROVIDERS = [
2190
+ { id: 'deepseek', name: 'DeepSeek', mark: 'DS', icon: 'deepseek.svg', baseUrl: 'https://api.deepseek.com/v1', keyUrl: 'https://platform.deepseek.com/api_keys' },
2191
+ { id: 'openai', name: 'OpenAI', mark: '◎', icon: 'openai.svg', mono: true, baseUrl: 'https://api.openai.com/v1', keyUrl: 'https://platform.openai.com/api-keys' },
2192
+ { id: 'anthropic', name: 'Anthropic', mark: 'A', icon: 'anthropic.svg', baseUrl: 'https://api.anthropic.com/v1', keyUrl: 'https://console.anthropic.com/settings/keys' },
2193
+ { id: 'gemini', name: 'Gemini', mark: '✦', icon: 'gemini.svg', baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai', keyUrl: 'https://aistudio.google.com/app/apikey' },
2194
+ { id: 'zhipu', name: '智谱 GLM', mark: 'GL', icon: 'zhipu.svg', baseUrl: 'https://open.bigmodel.cn/api/coding/paas/v4', keyUrl: 'https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys' },
2195
+ { id: 'custom', name: '自定义', mark: '+', baseUrl: '', keyUrl: '' },
2196
+ ]
2197
+ function translateProviderFor(baseUrl) {
2198
+ const u = (baseUrl || '').toLowerCase()
2199
+ if (/deepseek/.test(u)) return 'deepseek'
2200
+ if (/openai\.com/.test(u)) return 'openai'
2201
+ if (/anthropic/.test(u)) return 'anthropic'
2202
+ if (/googleapis\.com/.test(u)) return 'gemini'
2203
+ if (/bigmodel|z\.ai/.test(u)) return 'zhipu'
2204
+ return 'custom'
2205
+ }
2206
+ function TranslateProviderIcon({ provider, size = 22 }) {
2207
+ if (!provider.icon) return provider.mark || '+'
2208
+ return h('img', {
2209
+ src: '/paper-reader/vendor/' + provider.icon, alt: '', 'aria-hidden': 'true',
2210
+ 'data-dpr-provider-icon': provider.id,
2211
+ style: { width: size, height: size, objectFit: 'contain', display: 'block', background: '#fff', borderRadius: 4 },
2212
+ })
2213
+ }
2214
+ function TranslateSettingsCard() {
2215
+ const [cfg, setCfg] = useState(null)
2216
+ const [mode, setMode] = useState('follow')
2217
+ const [providerId, setProviderId] = useState('deepseek')
2218
+ const [draft, setDraft] = useState({ id: 'new', baseUrl: TRANSLATE_PROVIDERS[0].baseUrl, model: '', apiKey: '' })
2219
+ const [models, setModels] = useState([])
2220
+ const [options, setOptions] = useState({ splitTokens: 100000, maxOutputTokens: 32768, qps: 16 })
2221
+ const [manualModel, setManualModel] = useState(false)
2222
+ const [busy, setBusy] = useState('')
2223
+ const [msg, setMsg] = useState(null)
2224
+ const [deleteArmed, setDeleteArmed] = useState(false)
2225
+ const modelRequest = useRef(0)
2226
+ const provider = TRANSLATE_PROVIDERS.find((p) => p.id === providerId) || TRANSLATE_PROVIDERS[0]
2227
+ const endpoints = (cfg?.endpoints || []).filter((e) => e.source !== 'harness')
2228
+ const endpointProvider = (e) => TRANSLATE_PROVIDERS.some((p) => p.id === e?.provider) ? e.provider : translateProviderFor(e?.baseUrl)
2229
+ const load = useCallback(() => {
2230
+ modelRequest.current += 1
2231
+ return api('/translate/config').then((d) => {
2232
+ setCfg(d)
2233
+ setOptions(d.options || { splitTokens: 100000, maxOutputTokens: 32768, qps: 16 })
2234
+ setMode(d.mode === 'follow' ? 'follow' : 'custom')
2235
+ const saved = (d.endpoints || []).filter((e) => e.source !== 'harness')
2236
+ const active = saved.find((e) => e.id === d.activeId) || saved[0] || null
2237
+ if (active) {
2238
+ setProviderId(TRANSLATE_PROVIDERS.some((p) => p.id === active.provider) ? active.provider : translateProviderFor(active.baseUrl))
2239
+ setDraft({ id: active.id, baseUrl: active.baseUrl || '', model: active.model || '', apiKey: '' })
2240
+ setModels(active.model ? [active.model] : [])
2241
+ } else {
2242
+ setProviderId('deepseek')
2243
+ setDraft({ id: 'new', baseUrl: TRANSLATE_PROVIDERS[0].baseUrl, model: '', apiKey: '' })
2244
+ setModels([])
2245
+ }
2246
+ setMsg(null)
2247
+ setDeleteArmed(false)
2248
+ }).catch((e) => setMsg({ ok: false, text: String(e.message || e) }))
2249
+ }, [])
2250
+ useEffect(load, [load])
2251
+
2252
+ const chooseProvider = (id) => {
2253
+ modelRequest.current += 1
2254
+ setBusy('')
2255
+ setProviderId(id)
2256
+ const preset = TRANSLATE_PROVIDERS.find((p) => p.id === id) || TRANSLATE_PROVIDERS[0]
2257
+ const saved = endpoints.find((e) => e.source === 'file' && endpointProvider(e) === id)
2258
+ setDraft({
2259
+ id: saved?.id || 'new',
2260
+ baseUrl: saved?.baseUrl || preset.baseUrl,
2261
+ model: saved?.model || '',
2262
+ apiKey: '',
2263
+ })
2264
+ setModels(saved?.model ? [saved.model] : [])
2265
+ setManualModel(false)
2266
+ setMsg(null)
2267
+ setDeleteArmed(false)
2268
+ }
2269
+ const discover = async () => {
2270
+ if (busy === 'save' || busy === 'follow') return
2271
+ const seq = ++modelRequest.current
2272
+ setBusy('models'); setMsg(null)
2273
+ try {
2274
+ const d = await api('/translate/models', {
2275
+ method: 'POST', headers: { 'content-type': 'application/json' },
2276
+ body: JSON.stringify({ id: draft.id, baseUrl: draft.baseUrl.trim(), apiKey: draft.apiKey.trim() }),
2277
+ })
2278
+ if (seq !== modelRequest.current) return
2279
+ setModels(d.models || [])
2280
+ setManualModel(false)
2281
+ setDraft((old) => ({ ...old, model: d.models?.includes(old.model) ? old.model : (d.models?.[0] || old.model) }))
2282
+ setMsg({ ok: true, text: t('setTranslateDiscovered').replace('{n}', String(d.models?.length || 0)) })
2283
+ } catch (e) {
2284
+ if (seq === modelRequest.current) { setManualModel(true); setMsg({ ok: false, text: String(e.message || e) }) }
2285
+ } finally {
2286
+ if (seq === modelRequest.current) setBusy('')
2287
+ }
2288
+ }
2289
+ // 输入停顿后自动获取;已有 Key 的端点不会仅因打开设置页就发请求。
2290
+ useEffect(() => {
2291
+ if (mode !== 'custom' || !draft.apiKey.trim()) return
2292
+ const timer = setTimeout(() => { void discover() }, 700)
2293
+ return () => clearTimeout(timer)
2294
+ }, [draft.apiKey, draft.baseUrl, providerId, mode])
2295
+
2296
+ const follow = async () => {
2297
+ if (mode === 'follow') return
2298
+ modelRequest.current += 1
2299
+ setBusy('follow'); setMsg(null)
2300
+ try {
2301
+ await api('/translate/config/selection', {
2302
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: 'harness' }),
2303
+ })
2304
+ await load()
2305
+ setMode('follow')
2306
+ toast(t('setTranslateFollowSet'))
2307
+ } catch (e) { setMsg({ ok: false, text: String(e.message || e) }) } finally { setBusy('') }
2308
+ }
2309
+ const saveModel = async (model) => {
2310
+ const name = (model || '').trim()
2311
+ if (!name) return
2312
+ modelRequest.current += 1
2313
+ setBusy('save'); setMsg(null)
2314
+ try {
2315
+ await api('/translate/config', {
2316
+ method: 'POST', headers: { 'content-type': 'application/json' },
2317
+ body: JSON.stringify({
2318
+ id: draft.id, label: provider.name, provider: provider.id,
2319
+ baseUrl: draft.baseUrl.trim(), apiKey: draft.apiKey.trim(), model: name,
2320
+ }),
2321
+ })
2322
+ await load()
2323
+ setMode('custom')
2324
+ setMsg({ ok: true, text: t('setTranslateSaved') })
2325
+ toast(t('setTranslateSaved'))
2326
+ } catch (e) { setMsg({ ok: false, text: String(e.message || e) }) } finally { setBusy('') }
2327
+ }
2328
+ const saveOptions = async () => {
2329
+ setBusy('options'); setMsg(null)
2330
+ try {
2331
+ const d = await api('/translate/config/options', {
2332
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ splitTokens: Number(options.splitTokens), maxOutputTokens: Number(options.maxOutputTokens), qps: Number(options.qps) }),
2333
+ })
2334
+ setOptions(d.options)
2335
+ setMsg({ ok: true, text: t('setTranslateOptionsSaved') })
2336
+ toast(t('setTranslateOptionsSaved'))
2337
+ } catch (e) { setMsg({ ok: false, text: String(e.message || e) }) } finally { setBusy('') }
2338
+ }
2339
+ const remove = async () => {
2340
+ if (!draft.id || draft.id === 'new' || draft.id === 'profile') return
2341
+ if (!deleteArmed) { setDeleteArmed(true); return }
2342
+ setBusy('delete'); setMsg(null)
2343
+ try {
2344
+ await api('/translate/config?id=' + encodeURIComponent(draft.id), { method: 'DELETE' })
2345
+ await api('/translate/config/selection', {
2346
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: 'harness' }),
2347
+ })
2348
+ await load()
2349
+ setMode('follow')
2350
+ toast(t('setTranslateDeleted'))
2351
+ } catch (e) { setMsg({ ok: false, text: String(e.message || e) }) } finally { setBusy(''); setDeleteArmed(false) }
2352
+ }
2353
+
2354
+ const modeStyle = (selected) => ({
2355
+ flex: 1, minWidth: 0, display: 'flex', alignItems: 'flex-start', gap: 9, textAlign: 'left',
2356
+ padding: '12px', borderRadius: '9px', cursor: 'pointer',
2357
+ border: `1px solid ${selected ? 'var(--dsw-alias-button-primary-fill, #5269d8)' : 'var(--dsw-alias-border-l1, #d8dce4)'}`,
2358
+ background: selected ? 'var(--dsw-alias-button-primary-fill-alpha-10, #fafaff)' : 'var(--dsw-alias-bg-layer-1, #fff)',
2359
+ boxShadow: selected ? '0 0 0 1px var(--dsw-alias-button-primary-fill, #5269d8)' : 'none',
2360
+ })
2361
+ const radio = (selected) => h('span', { style: { width: '15px', height: '15px', marginTop: 2, flex: 'none', borderRadius: '50%', border: `1.5px solid ${selected ? 'var(--dsw-alias-button-primary-fill, #5269d8)' : '#b8bec9'}`, display: 'grid', placeItems: 'center' } },
2362
+ selected ? h('span', { style: { width: 7, height: 7, borderRadius: '50%', background: 'var(--dsw-alias-button-primary-fill, #5269d8)' } }) : null)
2363
+ const small = { fontSize: '11px', lineHeight: 1.55, color: 'var(--dsw-alias-label-secondary, #6d7480)' }
2364
+ const badge = { width: 29, height: 29, flex: 'none', display: 'grid', placeItems: 'center', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l1, #e5e7ec)', color: 'var(--dsw-alias-label-secondary, #5269d8)', background: 'var(--dsw-alias-bg-layer-2, #fff)', fontSize: 10, fontWeight: 650 }
2365
+ const savedForProvider = endpoints.some((e) => e.source === 'file' && endpointProvider(e) === providerId)
2366
+ const savedCount = endpoints.filter((e) => e.source === 'file').length
2367
+ const optionField = (key, label, hint, min, max) => h('div', { style: { marginTop: 10 } },
2368
+ h('label', { style: { ...SET.label, margin: '0 0 4px' } }, label),
2369
+ h('input', {
2370
+ type: 'number', min, max, step: 1, value: options[key], 'data-dpr-translate-option': key,
2371
+ style: SET.input,
2372
+ onChange: (e) => setOptions({ ...options, [key]: e.target.value }),
2373
+ }),
2374
+ h('p', { style: { ...small, margin: '5px 0 0' } }, hint),
2375
+ )
2376
+
2377
+ return h('div', { style: { ...SET.card, padding: 0, overflow: 'hidden' }, 'data-dsh-plugin': 'dsh-paper-reader', 'data-dsh-part': 'settings-card', 'data-dpr-translate-settings': mode },
2378
+ h('div', { style: { padding: '16px 16px 14px', borderBottom: '1px solid var(--dsw-alias-border-l1, #e5e7ec)' } },
2379
+ h('h3', { style: SET.title }, t('setTranslateTitle')),
2380
+ h('p', { style: { ...SET.desc, margin: 0 } }, t('setTranslateDesc')),
2381
+ ),
2382
+ h('div', { style: { display: 'flex', gap: 9, padding: '14px 16px' }, role: 'radiogroup', 'aria-label': t('setTranslateTitle') },
2383
+ h('button', { type: 'button', role: 'radio', 'aria-checked': mode === 'follow', 'data-dpr-translate-follow': '', style: modeStyle(mode === 'follow'), onClick: follow },
2384
+ radio(mode === 'follow'),
2385
+ h('span', null,
2386
+ h('span', { style: { display: 'block', fontSize: 12, fontWeight: 650 } }, t('setTranslateFollow'), ' ', h('span', { style: { ...small, color: 'var(--dsw-alias-button-primary-fill, #5269d8)' } }, t('setTranslateDefault'))),
2387
+ h('span', { style: { ...small, display: 'block', marginTop: 5 } }, t('setTranslateFollowDesc')),
2388
+ ),
2389
+ ),
2390
+ h('button', { type: 'button', role: 'radio', 'aria-checked': mode === 'custom', 'data-dpr-translate-custom': '', style: modeStyle(mode === 'custom'), onClick: () => { setMode('custom'); setMsg(null) } },
2391
+ radio(mode === 'custom'),
2392
+ h('span', null,
2393
+ h('span', { style: { display: 'block', fontSize: 12, fontWeight: 650 } }, t('setTranslateCustom')),
2394
+ h('span', { style: { ...small, display: 'block', marginTop: 5 } }, t('setTranslateCustomDesc')),
2395
+ ),
2396
+ ),
2397
+ ),
2398
+ mode === 'follow' ? h('div', { style: { margin: '0 16px 16px', padding: 14, display: 'flex', alignItems: 'center', gap: 12, borderRadius: 9, border: '1px solid var(--dsw-alias-border-l1, #dce1f4)', background: 'var(--dsw-alias-button-primary-fill-alpha-10, #f0f2ff)' } },
2399
+ h('span', { style: { ...badge, width: 36, height: 36 } }, h(TranslateProviderIcon, { provider: TRANSLATE_PROVIDERS.find((p) => p.id === translateProviderFor(cfg?.harness?.providerName)) || TRANSLATE_PROVIDERS[5], size: 24 })),
2400
+ h('div', { style: { minWidth: 0 } },
2401
+ h('div', { style: small }, '● ', t('setTranslateCurrentFollow')),
2402
+ cfg?.harness ? h('div', { style: { marginTop: 4, fontSize: 13, fontWeight: 650, overflowWrap: 'anywhere' } }, cfg.harness.model, ' ', h('span', { style: { color: 'var(--dsw-alias-label-secondary, #6d7480)', fontWeight: 450 } }, '· ' + cfg.harness.providerName)) : h('div', { style: { ...SET.err, marginTop: 4 } }, t('setTranslateUnavailable')),
2403
+ h('div', { style: { ...small, marginTop: 5 } }, t('setTranslateFollowNote')),
2404
+ ),
2405
+ ) : h('div', null,
2406
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 16px 10px' } },
2407
+ h('strong', { style: { fontSize: 12 } }, t('setTranslateProviders')),
2408
+ h('span', { style: small }, t('setTranslateSavedCount').replace('{n}', String(savedCount))),
2409
+ ),
2410
+ h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 7, padding: '0 16px 14px' } },
2411
+ TRANSLATE_PROVIDERS.map((p) => {
2412
+ const selected = p.id === providerId
2413
+ const saved = endpoints.some((e) => e.source === 'file' && endpointProvider(e) === p.id)
2414
+ return h('button', { key: p.id, type: 'button', 'data-dpr-translate-provider': p.id, onClick: () => chooseProvider(p.id), style: { minWidth: 0, display: 'flex', alignItems: 'center', gap: 8, padding: 9, textAlign: 'left', cursor: 'pointer', borderRadius: 8, border: `1px solid ${selected ? 'var(--dsw-alias-button-primary-fill, #5269d8)' : 'var(--dsw-alias-border-l1, #e5e7ec)'}`, background: selected ? 'var(--dsw-alias-button-primary-fill-alpha-10, #fafaff)' : 'var(--dsw-alias-bg-layer-1, #fff)', boxShadow: selected ? '0 0 0 1px var(--dsw-alias-button-primary-fill, #5269d8)' : 'none' } },
2415
+ h('span', { style: badge }, h(TranslateProviderIcon, { provider: p, size: 22 })),
2416
+ h('span', { style: { minWidth: 0 } },
2417
+ h('span', { style: { display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: 11, fontWeight: 600 } }, p.name),
2418
+ h('span', { style: { ...small, color: saved ? 'var(--dsw-alias-state-success-primary, #27845d)' : small.color } }, saved ? t('setTranslateSavedShort') : (p.id === 'custom' ? 'OpenAI API' : t('setOptional'))),
2419
+ ),
2420
+ )
2421
+ }),
2422
+ ),
2423
+ h('div', { style: { margin: '0 16px 16px', border: '1px solid var(--dsw-alias-border-l1, #e5e7ec)', borderRadius: 9, overflow: 'hidden' } },
2424
+ h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 12px 8px', gap: 10 } },
2425
+ h('strong', { style: { fontSize: 12 } }, provider.name, savedForProvider ? h('span', { style: { ...small, marginLeft: 7, color: 'var(--dsw-alias-state-success-primary, #27845d)' } }, '● ' + t('setTranslateSavedShort')) : null),
2426
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 9 } },
2427
+ provider.keyUrl ? h('a', { href: provider.keyUrl, target: '_blank', rel: 'noreferrer', style: { fontSize: 11, color: 'var(--dsw-alias-button-primary-fill, #5269d8)', textDecoration: 'none', whiteSpace: 'nowrap' } }, t('setTranslateApplyKey') + ' ↗') : null,
2428
+ draft.id !== 'new' && draft.id !== 'profile' ? h('button', { type: 'button', 'data-dpr-translate-delete': '', style: { ...SET.btnGhost, padding: '2px 5px', fontSize: 10, color: 'var(--dsw-alias-state-error-primary, #f85149)' }, disabled: busy === 'delete', onClick: remove }, deleteArmed ? t('setTranslateDeleteConfirm') : t('setTranslateDelete')) : null,
2429
+ ),
2430
+ ),
2431
+ h('div', { style: { padding: '0 12px 12px' } },
2432
+ h('label', { style: SET.label, htmlFor: 'dpr-translate-key' }, t('setKey')),
2433
+ h('input', { id: 'dpr-translate-key', 'data-dpr-translate-key': '', style: SET.input, type: 'password', autoComplete: 'off', disabled: busy === 'save', value: draft.apiKey, placeholder: savedForProvider ? t('setKeyKeep') + (endpoints.find((e) => e.id === draft.id)?.apiKeyHint || '') : 'sk-...', onChange: (e) => setDraft({ ...draft, apiKey: e.target.value }) }),
2434
+ h('p', { style: { ...small, margin: '6px 0 0', color: busy === 'models' ? 'var(--dsw-alias-button-primary-fill, #5269d8)' : small.color } }, busy === 'models' ? t('setTranslateDiscovering') : t('setTranslateKeyAuto')),
2435
+ provider.id === 'custom' ? h('div', null,
2436
+ h('label', { style: SET.label, htmlFor: 'dpr-translate-url' }, t('setBaseUrl')),
2437
+ h('input', { id: 'dpr-translate-url', 'data-dpr-translate-url': '', style: SET.input, type: 'text', value: draft.baseUrl, onChange: (e) => setDraft({ ...draft, baseUrl: e.target.value }) }),
2438
+ ) : null,
2439
+ h('details', { style: { marginTop: 9 } },
2440
+ h('summary', { style: { ...small, cursor: 'pointer' } }, t('setTranslateAdvanced')),
2441
+ manualModel ? h('div', null,
2442
+ h('label', { style: SET.label, htmlFor: 'dpr-translate-manual-model' }, t('setTranslateManualModel')),
2443
+ h('div', { style: { display: 'flex', gap: 7 } },
2444
+ h('input', { id: 'dpr-translate-manual-model', 'data-dpr-translate-manual-model': '', style: { ...SET.input, flex: 1, minWidth: 0 }, type: 'text', value: draft.model, placeholder: 'deepseek-chat', onChange: (e) => setDraft({ ...draft, model: e.target.value }) }),
2445
+ h('button', { type: 'button', style: { ...SET.btnGhost, flex: 'none', whiteSpace: 'nowrap' }, disabled: busy === 'save' || !draft.model.trim(), onClick: () => saveModel(draft.model) }, busy === 'save' ? t('setSaving') : t('setTranslateUse')),
2446
+ ),
2447
+ ) : null,
2448
+ optionField('splitTokens', t('setTranslateSplitTokens'), t('setTranslateSplitHint'), 200, 128000),
2449
+ optionField('maxOutputTokens', t('setTranslateMaxOutput'), t('setTranslateMaxOutputHint'), 0, 32768),
2450
+ optionField('qps', t('setTranslateQps'), t('setTranslateQpsHint'), 1, 32),
2451
+ h('button', { type: 'button', 'data-dpr-translate-options-save': '', style: { ...SET.btnGhost, marginTop: 12 }, disabled: busy === 'options', onClick: saveOptions }, busy === 'options' ? t('setSaving') : t('setTranslateOptionsSave')),
2452
+ ),
2453
+ ),
2454
+ h('div', { style: { borderTop: '1px solid var(--dsw-alias-border-l1, #e5e7ec)', padding: 12 } },
2455
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 } },
2456
+ h('strong', { style: { fontSize: 12 } }, t('setTranslateModels'), ' ', h('span', { style: { ...small, fontWeight: 400 } }, models.length ? `(${models.length})` : '')),
2457
+ h('button', { type: 'button', 'data-dpr-translate-refresh': '', style: { ...SET.btnGhost, padding: '3px 7px', fontSize: 11 }, disabled: busy === 'models' || busy === 'save', onClick: discover }, t('setTranslateRefresh')),
2458
+ ),
2459
+ models.length ? h('div', { style: { display: 'grid', gap: 6, maxHeight: 260, overflowY: 'auto' } }, models.map((model) => {
2460
+ const using = cfg?.activeId === draft.id && cfg?.source !== 'harness' && draft.model === model
2461
+ return h('button', { key: model, type: 'button', 'data-dpr-translate-model': model, disabled: busy === 'save', onClick: () => saveModel(model), style: { display: 'flex', alignItems: 'center', gap: 9, width: '100%', padding: 10, textAlign: 'left', cursor: 'pointer', borderRadius: 7, border: `1px solid ${using ? 'var(--dsw-alias-button-primary-fill, #aeb9ee)' : 'var(--dsw-alias-border-l1, #e5e7ec)'}`, background: using ? 'var(--dsw-alias-button-primary-fill-alpha-10, #fafaff)' : 'var(--dsw-alias-bg-layer-1, #fff)' } },
2462
+ radio(using),
2463
+ h('span', { style: { flex: 1, minWidth: 0, overflowWrap: 'anywhere', fontSize: 12, fontWeight: 600 } }, model),
2464
+ h('span', { style: { ...small, color: using ? 'var(--dsw-alias-button-primary-fill, #5269d8)' : small.color } }, using ? t('setTranslateUsing') : t('setTranslateUse')),
2465
+ )
2466
+ })) : h('div', { style: { ...small, padding: 14, textAlign: 'center', border: '1px dashed var(--dsw-alias-border-l1, #d8dce4)', borderRadius: 7 } }, t('setTranslateEmpty')),
2467
+ ),
2468
+ ),
2469
+ ),
2470
+ h('div', { style: { padding: '0 16px 13px', textAlign: 'center', ...small } }, mode === 'follow' ? t('setTranslateScopeFollow') : t('setTranslateScopeCustom')),
2471
+ msg ? h('div', { style: { padding: '0 16px 13px', textAlign: 'center', ...(msg.ok ? SET.ok : SET.err) } }, msg.text) : null,
2472
+ )
2473
+ }
2474
+
1936
2475
  /* ---------- 分屏同步滚动卡片(模式 B 的**全局**偏好)----------
1937
2476
  本卡片与阅读器是**两个文档**(阅读器是同源 iframe ~ /paper-reader/),共享同一个 localStorage:
1938
2477
  · 这里勾/取消 → 写 `dpr.syncScroll` → 阅读器收到 storage 事件 → 开关与滚动行为立即跟着变
@@ -1941,11 +2480,11 @@ window.__ModuleLoader__.load({
1941
2480
  ⇒ 两处入口互相同步,且都是**同一个键**(键名与 '1'/'0' 编码由文件顶层的纯函数定义,
1942
2481
  与 reader/index.html 逐字一致)。默认开 = 缺省值(与改造前行为一致)。 */
1943
2482
  function SyncScrollCard() {
1944
- const readPref = () => { try { return dprSyncScrollFromRaw(localStorage.getItem(DPR_SYNC_SCROLL_KEY)) } catch { return true } }
2483
+ const readPref = () => { try { return dprSyncScrollFromRaw(localStorage.getItem(dprSyncScrollKey())) } catch { return true } }
1945
2484
  const [on, setOn] = useState(readPref)
1946
2485
  useEffect(() => {
1947
2486
  const onStorage = (e) => {
1948
- if (!e || e.key !== DPR_SYNC_SCROLL_KEY) return
2487
+ if (!e || e.key !== dprSyncScrollKey()) return
1949
2488
  setOn(dprSyncScrollFromRaw(e.newValue)) // 另一处(阅读器/另一个窗口)改了 → 立即反映
1950
2489
  }
1951
2490
  window.addEventListener('storage', onStorage)
@@ -1953,7 +2492,7 @@ window.__ModuleLoader__.load({
1953
2492
  }, [])
1954
2493
  const apply = (v) => {
1955
2494
  setOn(v)
1956
- try { localStorage.setItem(DPR_SYNC_SCROLL_KEY, dprSyncScrollRaw(v)) } catch { /* 隐私模式写不了:阅读器里仍可单独改 */ }
2495
+ try { localStorage.setItem(dprSyncScrollKey(), dprSyncScrollRaw(v)) } catch { /* 隐私模式写不了:阅读器里仍可单独改 */ }
1957
2496
  }
1958
2497
  return h('div', { style: SET.card, 'data-dsh-plugin': 'dsh-paper-reader', 'data-dsh-part': 'settings-card' },
1959
2498
  h('h3', { style: SET.title }, t('setSyncScrollTitle')),
@@ -2046,10 +2585,7 @@ window.__ModuleLoader__.load({
2046
2585
  baseUrlPlaceholder: 'https://api.openai.com/v1', modelPlaceholder: 'text-embedding-3-small', keyPlaceholder: 'sk-...',
2047
2586
  batchSize: true,
2048
2587
  }),
2049
- h(EndpointCard, {
2050
- path: '/translate/config', title: t('setTranslateTitle'), desc: t('setTranslateDesc'),
2051
- baseUrlPlaceholder: 'https://api.deepseek.com/v1', modelPlaceholder: 'deepseek-chat', keyPlaceholder: 'sk-...',
2052
- }),
2588
+ h(TranslateSettingsCard, null),
2053
2589
  h(MineruCard, null),
2054
2590
  h(ThemeCard, null),
2055
2591
  h(SyncScrollCard, null),
@@ -2178,7 +2714,10 @@ window.__ModuleLoader__.load({
2178
2714
  if (!document.getElementById('dpr-switch-instant')) {
2179
2715
  const styleEl = document.createElement('style')
2180
2716
  styleEl.id = 'dpr-switch-instant'
2181
- styleEl.textContent = '[data-rightbar-instant] [data-sidebar-right-panel]{transition:none!important}'
2717
+ // P5:面板本体之外,dsh 的页签格(._tabCell)自己带 `transform .3s` 过渡——换轨后
2718
+ // 它会把 tab 内容从旧轨位置「滑」到新轨位置(实测 1001→281 滑 300ms),阅读器是贴在
2719
+ // 锚点上的,于是 PDF 先出现在右边再滑到左边。护栏窗口内把面板子树的过渡一起瞬时化。
2720
+ styleEl.textContent = '[data-rightbar-instant] [data-sidebar-right-panel],[data-rightbar-instant] [data-sidebar-right-panel] *{transition:none!important}'
2182
2721
  document.head.appendChild(styleEl)
2183
2722
  }
2184
2723
  // 自绘元素里 :hover 这类伪类内联 style 表达不了。内联仍写死态(注入失败时有个安全默认),