@ggboy123/dsh-paper-reader 1.5.1 → 1.6.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/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  **English**: [README_EN.md](README_EN.md)
9
9
 
10
- [DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 插件:**论文伴读工作台** —— 文献库 + PDF 阅读器 + AI 伴读,回答自带页码、点页码跳回原文。当前版本 **v1.5.1**。
10
+ [DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 插件:**论文伴读工作台** —— 文献库 + PDF 阅读器 + AI 伴读,回答自带页码、点页码跳回原文。当前版本 **v1.6.0**。
11
11
 
12
12
  > 💬 **QQ 交流群:1127244508** —— 安装/使用问题、功能建议、bug 反馈都欢迎来聊。
13
13
 
@@ -21,10 +21,11 @@
21
21
 
22
22
  - 📚 **三栏工作台**:专题文献库 + PDF 阅读器 + 右侧原生对话;安装后不改动官方界面,侧栏只多一行开关
23
23
  - 💬 **带页码的伴读**:回答必带页码,点页码跳回原文并高亮;选中文字即问;支持历史对话
24
- - 🤖 **教练式带读**:专用 preset 定分步阅读计划、逐节指导、出题批改,学习进度跨会话累积
24
+ - 🤖 **可选教练式带读**:专用 preset 制定分步计划;你读原文、作答,AI 点评追问,当前阶段答好才继续,学习进度跨会话累积
25
25
  - 🀄 **一键中文版**:原文 ↔ 纯中文原地切换,译文 PDF 一键导出(纯中文 / 中英对照),翻译引擎零预装自动安装
26
- - 🈯 **划词翻译(公式保留)**(v1.5.1):选中点「译」出纯译文气泡;选区含公式时用 MinerU 识别的 LaTeX 替换文本层乱码、要求模型原样保留
27
- - 🖥️ **中英对照 / 分屏**(v1.5.1):并排对照页或左右分屏同步滚动,随时切换、按文献记忆
26
+ - 📏 **长段落不截断 + 实时进度**:翻译由 `babeldoc-driver.py` 驱动 babeldoc —— 按输入估算输出预算(不再吃 babeldoc 写死的 2048),`finish_reason=length` 自动拆段重译;顶栏进度条实时显示「翻译段落 76%(521/798)」这样的阶段进度,端点拒绝关闭推理时自动降推理强度重试
27
+ - 🈯 **划词翻译(公式保留)**(v1.6.0):选中点「译」出纯译文气泡;选区含公式时用 MinerU 识别的 LaTeX 替换文本层乱码、要求模型原样保留
28
+ - 🖥️ **中英对照 / 分屏**(v1.6.0):并排对照页或左右分屏同步滚动,随时切换、按文献记忆
28
29
  - 🗂️ **文献管理**:专题/论文改名、删除进回收站可恢复
29
30
  - ➕ **可选增强**(默认关):MinerU 解析——扫描件可读、公式可点引用可检索;嵌入端点——大白话命中术语段落
30
31
 
@@ -43,7 +44,7 @@
43
44
 
44
45
  ![官方桌面端安装并使用论文伴读插件](https://raw.githubusercontent.com/GGboya/dsh-paper-reader/main/docs/desktop-official-use.gif)
45
46
 
46
- > 已在官方桌面端 V0.2.0-rc.2(内置 dsh 0.2.0-rc.2,macOS arm64)实测通过;插件需 ≥1.2.0。
47
+ > 需要官方桌面端 V0.2.0-rc.2 或更新版本(内置 dsh ≥0.2.0-rc.2);dsh 0.1.5 不再支持。
47
48
  > 想逛插件市场可另装社区插件 [`dshmarket`](https://github.com/dsh-market/dsh-market),本插件已在其目录中。
48
49
 
49
50
  **排坑**(都是实测踩过的):
package/cordis.patch.yml CHANGED
@@ -7,3 +7,76 @@
7
7
  - insert:
8
8
  - id: dsh-paper-reader
9
9
  name: '@ggboy123/dsh-paper-reader'
10
+
11
+ # dsh 0.2.x 的声明式 preset:随 bundle 安装并在 profile 启动时注册,
12
+ # 不再复制到已废弃的 $DSH_HOME/.agent-presets/。
13
+ - id: preset-paper-reader
14
+ name: '@deepseek-ai/dsh-agent-preset'
15
+ config:
16
+ id: paper-reader
17
+ name: 论文伴读
18
+ description: 可选的教练式论文伴读:你先独立阅读,AI 只负责出题、校验和追问薄弱点;每个阶段答好才继续,不灌输内容,只在你真正卡住时才讲解(每篇论文一份 .study.json 学习档案)。
19
+ order: 10
20
+ plugins:
21
+ # persona 是完整系统提示词,屏蔽编码 agent 身份与运行时上下文;
22
+ # 工具面只保留宿主注册的论文工具,不带 bash/fs/todo/web。
23
+ - id: persona
24
+ name: '@deepseek-ai/dsh-persona'
25
+ config:
26
+ complete: true
27
+ includeRuntimeContext: false
28
+ prefix: |
29
+ You are a paper-reading examiner and coach (论文伴读教练) powered by the {{model}} model. Your job is NOT to deliver the paper's content — the paper itself does that, and the student learns by reading it with their own eyes. Your job is to design good questions, send the student off to read independently, and then rigorously verify what they actually understood. You are more examiner than lecturer.
30
+
31
+ The cardinal rule: NEVER summarize, walk through, or pre-explain content the student hasn't read and answered questions on yet. Feeding conclusions before the student reads robs them of the learning — that is the failure mode of this role. Your default loop is: assign reading + questions → wait for the student's own answer → probe and grade → and ONLY if a real gap remains after they've genuinely tried, explain that specific missing point with a page reference.
32
+
33
+ Tools at your disposal:
34
+ - list_papers: list topics and papers in the library.
35
+ - transcribe_pdf: extract a paper's full text (cached, with a per-page index).
36
+ - search_paper: search one paper's transcript; returns chunks with page numbers.
37
+ - study_progress: read the student's learning record for a paper (plan + quiz history), stored in <论文>.study.json next to the PDF.
38
+ - study_update: update that record — set_plan (3~6 steps), complete_step (with your feedback note), record_quiz (score/total + weak-point summary).
39
+
40
+ Tool results carry a `阅读器链接基址` (readerUrl) line. EVERY page reference in your replies MUST be a clickable markdown link built from it: [链接文字](<readerUrl 原样照搬>&page=N) — e.g. [第 4 页](…&page=4). Clicking it jumps the student's built-in reader straight to that page, in whichever language version (原文/中英对照/纯中文) they are currently viewing — so never add any language/variant parameter yourself.
41
+
42
+ When pointing at a specific passage (a re-read assignment, the evidence for an answer), ALSO append a quote parameter so the reader highlights the exact passage: &q=<a verbatim 3~8 word phrase lifted from that passage, URL-encoded, e.g. &q=inexpensive%20commodity%20hardware>. Rules for q: copy it character-for-character from the search_paper/transcript text (never paraphrase), prefer a phrase at the START of the passage, no line breaks inside it, always percent-encode spaces (%20) and other non-ASCII characters. If you're unsure of the exact wording, omit q rather than guess — a wrong q silently degrades to a plain page jump. Bare "(第 N 页)" text citations are a formatting failure; always link. If the latest tool result has no readerUrl (null), fall back to plain text page numbers.
43
+
44
+ A paper-reader plugin session is bound to one paper: every paper tool auto-locates it when you omit topic/name, so NEVER ask the user which paper they mean there — just call the tool. If the user selected this preset for a standalone dsh conversation instead, do not guess: use list_papers and ask them to choose when the paper is unclear. Only pass topic/name explicitly when the user asks about a DIFFERENT paper.
45
+
46
+ Two modes:
47
+
48
+ 1) Quick Q&A. When the user asks an isolated factual question (often a passage selected in the reader, with its page number), just answer it: search_paper first, answer with explicit page links like [第 4 页](…&page=4), match the user's language. No lesson, no plan, no quiz. Quick Q&A never completes or advances a step in an active guided plan. A request to summarize the whole paper, walk through the next section, or bypass a guided checkpoint is NOT quick Q&A; handle it under the guided-learning gate below.
49
+
50
+ 2) Guided learning. When the user wants to LEARN the paper ("带我读", "我想学这篇", "继续", "检验我", or is working through a plan), act as the examiner-coach:
51
+ - Always start by calling study_progress to see where the student is.
52
+ - No plan yet: skim the paper yourself (transcribe/search the abstract, introduction, section headings), then design a 3~6 step plan with set_plan. The FIRST step is always an independent full read (独立通读) verified by 2~4 simple check questions; the remaining steps are theme-by-theme 精读, each verified by questions. After saving the plan, present ONLY the step-1 assignment: which pages to read and the check questions. Do NOT preview the paper — no abstract recap, no "this paper is about...". The questions themselves are the orientation.
53
+ - Step 1 (独立通读): pose 2~4 simple questions (e.g. 这篇论文要解决什么问题?方法用一句话怎么概括?最关键的实验结果/结论是什么?), point at the pages that matter if the paper is long, then STOP and wait. The student reads on their own and comes back with answers in their own words. Grade each answer specifically — what's right, what's vague, what's wrong, with page links. If an answer is hollow, ask ONE sharper follow-up on the same point before deciding.
54
+ - 精读 steps (question-driven): for each step, FIRST give the question(s) and the exact pages to read (as links), then let the student go read and answer. Questions must force engagement: "为什么这里用 X 而不是 Y?", "第 N 页的图/公式说明了什么?", "去掉这个设计会怎样?" — never "请总结第 N 节".
55
+ - 严格师傅原则(答案不如意时的固定动作): when an answer is vague, wrong, or smells pasted, your FIRST move is NOT to explain and NOT merely to follow up verbally — send the student back to the source: name the exact section and give a re-read link with q so the passage highlights on click ([重读 3.2 节(第 5 页)](…&page=5&q=…)), tell them what specific thing to look for, and have them re-answer the same question afterwards. Escalate up the hint ladder only across re-attempts: re-read assignment → a smaller sub-question → pointing at the exact paragraph. Explain directly ONLY after a genuine failed re-attempt — and then explain just that point, not the whole section.
56
+ - Stage gate (non-negotiable): a step passes only when the student's own-word answers show the understanding targeted by that step — the core idea is correct, the key reasoning or evidence is sound at the expected depth, and no major misconception remains. "我看完了", a pasted answer, or vague agreement never passes. If the step has not passed, do NOT call complete_step and do NOT assign, preview, or explain the next step; continue only with re-reading, probing, hints, or targeted remediation for the current step. Even after you explain a missing point, require a fresh check answer and wait for it — the explanation itself does not pass the student.
57
+ - Only after a pass, call complete_step with a short feedback note in the same turn as your specific grading, then present the next step's reading assignment and questions. If the student asks to skip a step, offer a short test-out check on that step instead of unconditional advancement; passing that check earns the same transition. If you skipped earlier bookkeeping, read study_progress and bring it up to date first.
58
+ - After the plan is done, or when the student asks to be tested: run a quiz — 3~5 questions grounded in the paper (mix recall, "why is it designed this way", and "apply it to a new case"); grade each answer specifically, and IN THE SAME TURN as the final grading call record_quiz with the score and a weak-point summary, then finish with targeted review advice — each weak point gets a re-read link to the exact page.
59
+ - Be warm but demanding. Praise genuine understanding; never wave through a wrong answer. If an answer smells pasted from the abstract or another AI, ask them to close the paper and re-answer from memory in their own words. Chinese students get Chinese, English students get English.
60
+
61
+ The conversation itself is durable (the harness persists it) — never offer to save, archive, or export the conversation, and never mention file paths or tool names in your reply.
62
+
63
+ # 与官方 standard preset 相同的压缩组,长会话可压缩并裁剪旧工具结果。
64
+ - id: compaction
65
+ name: cordis:group
66
+ group: true
67
+ isolate:
68
+ compaction: true
69
+ toolResultPruner: true
70
+ config:
71
+ - id: compaction-basic
72
+ name: '@deepseek-ai/dsh-compaction-basic'
73
+
74
+ - id: command-compact
75
+ name: '@deepseek-ai/dsh-command-compact'
76
+
77
+ - id: tool-result-pruner
78
+ name: '@deepseek-ai/dsh-compaction-tool-result-pruner'
79
+ config:
80
+ thresholdChars: 8192
81
+ headChars: 4096
82
+ tailChars: 1024
package/dist/host.js CHANGED
@@ -15,7 +15,6 @@ import { clearTranslateConfig, maskApiKey, readTranslateConfig, resolveTranslate
15
15
  import { clearTypesafeConfig, readTypesafeConfig, resolveTypesafeConfig, testTypesafeEndpoint, writeTypesafeConfig, } from "./typesafe-config.js";
16
16
  import { clearEmbedConfig, maskApiKey as maskEmbedApiKey, readEmbedConfig, resolveEmbedConfig, testEmbedEndpoint, writeEmbedConfig, } from "./embed-config.js";
17
17
  import { clearMineruConfig, mergeMineruBody, precheckMineruConfig, resolveMineruConfig, testMineruCloud, testMineruLocal, writeMineruConfig, } from "./mineru-config.js";
18
- import { installPaperPreset, PAPER_PRESET_ID } from "./preset.js";
19
18
  import { noteOrigin } from "./origin.js";
20
19
  function json(res, status, body) {
21
20
  const buf = Buffer.from(JSON.stringify(body), 'utf8');
@@ -74,9 +73,6 @@ export function registerRoutes(ctx, config) {
74
73
  const readerVendorDir = new URL('../reader/vendor/', import.meta.url);
75
74
  // 插件版本(读包根 package.json,注入阅读器顶栏——用户截图反馈时一眼可见)
76
75
  const pluginVersion = 'v' + JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
77
- // 自带「论文伴读」agent preset → $DSH_HOME/.agent-presets/(实时扫描,免重启);
78
- // 失败(旧版 dsh/无权限)则回退默认 preset,功能不受影响。
79
- const presetDir = installPaperPreset(new URL('../', import.meta.url));
80
76
  const locate = (url) => {
81
77
  const path = url.searchParams.get('path') ?? undefined;
82
78
  const topic = url.searchParams.get('topic') ?? undefined;
@@ -161,21 +157,14 @@ export function registerRoutes(ctx, config) {
161
157
  return undefined;
162
158
  }
163
159
  };
164
- /** 创建/复用会话:优先挂工作区 + 论文伴读 preset;失败(preset 缺失或旧会话 preset 冲突)逐级回退。 */
160
+ /** 创建/复用会话:论文伴读 preset 只注册到 dsh;论文入口不默认套用,避免替用户改变 agent。 */
165
161
  const createPaperSession = async (sessionId, topic) => {
166
162
  const workspaceId = await ensureTopicWorkspace(topic);
167
- const usePreset = (await presetDir) !== null;
168
163
  if (workspaceId) {
169
- if (usePreset) {
170
- try {
171
- return await sessionController.create({ sessionId, workspaceId, agentPreset: PAPER_PRESET_ID });
172
- }
173
- catch { /* preset 未注册或旧会话属另一 preset → 去掉 preset 重试 */ }
174
- }
175
164
  try {
176
165
  return await sessionController.create({ sessionId, workspaceId });
177
166
  }
178
- catch { /* 工作区挂载失败则回退 */ }
167
+ catch { /* 工作区挂载失败则回退 cwd */ }
179
168
  }
180
169
  return sessionController.create({ sessionId, cwd: join(dataDir, topic) });
181
170
  };
package/dist/tools.js CHANGED
@@ -435,7 +435,7 @@ export function registerTools(ctx, config) {
435
435
  name: 'study_update',
436
436
  description: '更新一篇论文的学习档案(老师用):' +
437
437
  'set_plan=制定阅读计划(steps 为 3~6 个分步标题,会重置计划但保留历史成绩);' +
438
- 'complete_step=学生完成某一步(step_id + 可选 note 点评,自动推进到下一步);' +
438
+ 'complete_step=当前步检查已通过后才可记录完成(step_id + 可选 note 点评,自动推进到下一步;未通过不得调用);' +
439
439
  'record_quiz=记录一次检验成绩(score/total + 可选 summary 薄弱点小结)。',
440
440
  parameters: {
441
441
  action: { type: 'string', required: true, enum: ['set_plan', 'complete_step', 'record_quiz'] },
package/dist/translate.js CHANGED
@@ -2,10 +2,16 @@
2
2
  // 移植 pdfqa 的 runPdf2zh:shell 调 babeldoc(pdf2zh 2.x),版式/图/公式原地保留,
3
3
  // 产出 <文献>-zh.pdf(纯中文)与 <文献>-dual.pdf(中英对照)。
4
4
  // babeldoc 只支持 OpenAI 兼容端点 → 端点/key/模型由插件配置提供。
5
- import { execFile } from 'node:child_process';
6
- import { existsSync } from 'node:fs';
5
+ //
6
+ // 注:本文件里 TranslatePaperRef / TranslateEndpoint 是「结构最小要求」,只声明本模块真正
7
+ // 用到的字段;仓库里若已有 library.ts 的 PaperRef 与 translate-config.ts 的端点类型,
8
+ // 直接把这两行 import 换成本地类型即可(形状是兼容子集)。
9
+ import { execFile, spawn } from 'node:child_process';
10
+ import { existsSync, closeSync, fstatSync, openSync, readSync } from 'node:fs';
7
11
  import { mkdir, rename, rm, readdir } from 'node:fs/promises';
8
12
  import { join, dirname, basename, extname, isAbsolute } from 'node:path';
13
+ import { StringDecoder } from 'node:string_decoder';
14
+ import { fileURLToPath } from 'node:url';
9
15
  import { dshHome } from "./library.js";
10
16
  import { ensureBabeldoc } from "./babeldoc-install.js";
11
17
  export function zhPdfPath(ref) {
@@ -15,8 +21,12 @@ export function dualPdfPath(ref) {
15
21
  return ref.pdfPath.slice(0, -extname(ref.pdfPath).length) + '-dual.pdf';
16
22
  }
17
23
  /** 进程内每篇文献一个翻译任务(幂等:进行中/已生成直接返回)。 */
18
- // key=pdfPath;null=进行中(无阶段说明);{phase}=进行中;{error}=已失败
24
+ // key=pdfPath;null=进行中(无阶段说明);{phase,progress}=进行中;{error}=已失败
19
25
  const busy = new Map();
26
+ /** 整篇翻译的硬超时(babeldoc 自己不死,靠这里收尸)。 */
27
+ const TRANSLATE_TIMEOUT_MS = 45 * 60 * 1000;
28
+ /** 失败时保留的日志尾巴长度。 */
29
+ const MAX_TAIL_CHARS = 1200;
20
30
  export function zhStatus(ref) {
21
31
  const zh = existsSync(zhPdfPath(ref));
22
32
  const dual = existsSync(dualPdfPath(ref));
@@ -27,6 +37,7 @@ export function zhStatus(ref) {
27
37
  busy: b === null || Boolean(b && !b.error),
28
38
  ...(b?.error ? { error: b.error } : {}),
29
39
  ...(b && !b.error && b.phase ? { phase: b.phase } : {}),
40
+ ...(b && !b.error && b.progress ? { progress: b.progress } : {}),
30
41
  };
31
42
  }
32
43
  /** 找 babeldoc 可执行文件:pdfqa venv(文献库同级 .venv-pdf2zh)→ PATH → miniconda(仅 macOS)。 */
@@ -66,15 +77,22 @@ function babeldocFlags(bin) {
66
77
  let p = flagSupport.get(bin);
67
78
  if (!p) {
68
79
  p = new Promise((res) => {
69
- execFile(bin, ['--help'], { timeout: 60000 }, (err, stdout, stderr) => {
70
- if (err)
71
- console.warn('[dsh-paper-reader] babeldoc --help 探测失败,按最老参数集运行');
72
- const flags = new Set();
73
- for (const m of (stdout + '\n' + stderr).matchAll(/--[a-z0-9-]+/g)) {
74
- flags.add(m[0].slice(2));
75
- }
76
- res(flags);
77
- });
80
+ try {
81
+ execFile(bin, ['--help'], { timeout: 60000 }, (err, stdout, stderr) => {
82
+ if (err)
83
+ console.warn('[dsh-paper-reader] babeldoc --help 探测失败,按最老参数集运行:', err.code ?? err.message);
84
+ const flags = new Set();
85
+ for (const m of ((stdout ?? '') + '\n' + (stderr ?? '')).matchAll(/--[a-z0-9-]+/g)) {
86
+ flags.add(m[0].slice(2));
87
+ }
88
+ res(flags);
89
+ });
90
+ }
91
+ catch (e) {
92
+ // 某些受限环境(沙箱里跑 node)连探测进程都起不来:只丢可选参数,别拖垮整次翻译
93
+ console.warn('[dsh-paper-reader] babeldoc --help 无法执行,按最老参数集运行:', e instanceof Error ? e.message : String(e));
94
+ res(new Set());
95
+ }
78
96
  });
79
97
  flagSupport.set(bin, p);
80
98
  }
@@ -116,7 +134,13 @@ async function runPipeline(ref, dataDir, endpoint) {
116
134
  const setPhase = (phase) => busy.set(ref.pdfPath, { phase });
117
135
  try {
118
136
  setPhase('正在检查翻译引擎…');
119
- const bin = await ensureBabeldoc(dataDir, dshHome(), () => findBabeldoc(dataDir), setPhase);
137
+ // DPR_SKIP_ENGINE_ENSURE=1:跳过「自检 + 缺失则自动安装」,只用现成的 babeldoc
138
+ // (受限环境里起不了探测子进程时手工兜底用,正常路径永远走 ensureBabeldoc)
139
+ const bin = process.env.DPR_SKIP_ENGINE_ENSURE === '1'
140
+ ? await findBabeldoc(dataDir)
141
+ : await ensureBabeldoc(dataDir, dshHome(), () => findBabeldoc(dataDir), setPhase);
142
+ if (!bin)
143
+ throw new Error('找不到 babeldoc 可执行文件');
120
144
  await launch(ref, dataDir, endpoint, bin);
121
145
  }
122
146
  catch (e) {
@@ -142,8 +166,84 @@ export async function restartTranslation(ref, dataDir, endpoint) {
142
166
  void runPipeline(ref, dataDir, endpoint);
143
167
  return { started: true, firstRun };
144
168
  }
169
+ /** 驱动脚本:包装 babeldoc(加结构化进度事件 + 解除单次请求的输出长度限制)。 */
170
+ const DRIVER_PATH = fileURLToPath(new URL('../runtime/babeldoc-driver.py', import.meta.url));
171
+ /** babeldoc 的阶段名 → 中文(进度条上给人看)。 */
172
+ const STAGE_LABELS = {
173
+ 'Parse PDF and Create Intermediate Representation': '解析 PDF',
174
+ DetectScannedFile: '检测扫描件',
175
+ 'Parse Page Layout': '分析版面',
176
+ 'Parse Table': '解析表格',
177
+ 'Parse Paragraphs': '解析段落',
178
+ 'Parse Formulas and Styles': '解析公式',
179
+ AutomaticTermExtractor: '抽取术语',
180
+ 'Automatic Term Extraction': '抽取术语',
181
+ 'Translate Paragraphs': '翻译段落',
182
+ Typesetting: '排版',
183
+ 'Add Fonts': '嵌入字体',
184
+ 'Generate drawing instructions': '生成绘图指令',
185
+ 'Subset font': '字体子集化',
186
+ 'Save PDF': '保存 PDF',
187
+ };
188
+ function stageLabel(stage) {
189
+ return (stage && STAGE_LABELS[stage]) || stage || '翻译';
190
+ }
191
+ /** 0..1 或 0..100 都归一成百分比。 */
192
+ function toPercent(v) {
193
+ if (typeof v !== 'number' || !Number.isFinite(v))
194
+ return null;
195
+ return Math.max(0, Math.min(100, v <= 1 ? v * 100 : v));
196
+ }
197
+ /**
198
+ * 把驱动脚本的一条 progress 事件变成前端能直接画的进度对象。
199
+ * babeldoc 的 overall_progress 只在 update 事件里有,start 阶段用阶段权重自己算。
200
+ */
201
+ function buildProgress(event, stages) {
202
+ const stage = typeof event.stage === 'string' && event.stage ? event.stage : null;
203
+ const stagePercent = toPercent(event.stagePercent);
204
+ let overall = toPercent(event.overall);
205
+ if (overall === null && stage && stagePercent !== null && stages.length) {
206
+ const weightOf = (s) => (typeof s.weight === 'number' && s.weight > 0 ? s.weight : 0);
207
+ const totalWeight = stages.reduce((a, s) => a + weightOf(s), 0) || 1;
208
+ const doneWeight = stages
209
+ .filter((s) => s.name !== stage)
210
+ .reduce((a, s) => a + weightOf(s), 0);
211
+ const mine = stages.find((s) => s.name === stage);
212
+ overall = ((doneWeight + weightOf(mine ?? {}) * (stagePercent / 100)) / totalWeight) * 100;
213
+ }
214
+ const stageCurrent = typeof event.stageCurrent === 'number' ? event.stageCurrent : null;
215
+ const stageTotal = typeof event.stageTotal === 'number' ? event.stageTotal : null;
216
+ const label = stageLabel(stage);
217
+ const fraction = stageTotal && stageCurrent !== null && stageTotal > 1
218
+ ? `(${Math.min(stageCurrent, stageTotal)}/${stageTotal})`
219
+ : '';
220
+ const percentText = overall === null ? '' : ` · ${Math.round(overall)}%`;
221
+ return {
222
+ stage,
223
+ label,
224
+ stagePercent,
225
+ stageCurrent,
226
+ stageTotal,
227
+ part: typeof event.part === 'number' ? event.part : null,
228
+ totalParts: typeof event.totalParts === 'number' ? event.totalParts : null,
229
+ overall,
230
+ text: `${label}${fraction}${percentText}`,
231
+ updatedAt: Date.now(),
232
+ };
233
+ }
234
+ /** 找与 babeldoc 同 venv 的 python(驱动脚本要 import babeldoc)。 */
235
+ function resolveDriverPython(bin) {
236
+ if (!bin || !isAbsolute(bin))
237
+ return null;
238
+ const candidates = process.platform === 'win32'
239
+ ? [join(dirname(bin), 'python.exe')]
240
+ : [join(dirname(bin), 'python'), join(dirname(bin), 'python3')];
241
+ return candidates.find((c) => existsSync(c)) ?? null;
242
+ }
145
243
  /** 真正拉起 babeldoc 子进程(bin 已就绪、产物不存在/已删)。 */
146
244
  async function launch(ref, dataDir, endpoint, bin) {
245
+ // 走到这里之前 precheck 已保证三项齐全;收窄一次,后续按 string 用
246
+ const ep = endpoint;
147
247
  const tmpDir = join(dataDir, '.pdf2zh-tmp');
148
248
  await mkdir(tmpDir, { recursive: true });
149
249
  busy.set(ref.pdfPath, null); // 清掉安装阶段说明,回到「翻译进行中」
@@ -155,55 +255,201 @@ async function launch(ref, dataDir, endpoint, bin) {
155
255
  // 可选参数统一过一遍探测:babeldoc 对不认识的参数直接报错退出,探测不到就不传(功能降级但不炸)。
156
256
  const supported = await babeldocFlags(bin);
157
257
  const opt = (flag) => (supported.has(flag) ? [`--${flag}`] : []);
158
- const noThink = /bigmodel|kimi|moonshot|deepseek/i.test(endpoint.baseUrl)
159
- ? opt('openai-thinking').flatMap((f) => [f, 'disabled'])
258
+ // 探测失败(支持集为空,比如受限环境里起不了子进程)时按现代版 babeldoc 猜:这两个参数
259
+ // 0.6.x 都有,没有的话 babeldoc 会立刻报 unrecognized arguments,比默默用错的临时目录好排查。
260
+ const assumeModern = supported.size === 0;
261
+ const hasFlag = (flag) => assumeModern || supported.has(flag);
262
+ const noThink = /bigmodel|kimi|moonshot|deepseek/i.test(ep.baseUrl) && hasFlag('openai-thinking')
263
+ ? ['--openai-thinking', 'disabled']
160
264
  : [];
161
- const child = execFile(bin, [
265
+ // 工作目录必须自己指定:babeldoc 默认在 cwd 下建 my_temp 并反复重建 PDF,
266
+ // cwd 只读(装上后从任意目录启动、或沙箱里)就会 code=2 Permission denied。
267
+ const workParent = hasFlag('working-dir') ? join(tmpDir, 'work') : null;
268
+ if (workParent)
269
+ await mkdir(workParent, { recursive: true });
270
+ const babelArgs = [
162
271
  '--files', ref.pdfPath,
163
272
  '--lang-in', 'en', '--lang-out', 'zh-CN',
164
- '--openai', '--openai-model', endpoint.model,
165
- '--openai-base-url', endpoint.baseUrl, '--openai-api-key', endpoint.apiKey,
273
+ '--openai', '--openai-model', ep.model,
274
+ '--openai-base-url', ep.baseUrl, '--openai-api-key', ep.apiKey,
166
275
  ...noThink,
167
276
  '--qps', '16', '--no-watermark', '--output', tmpDir,
277
+ ...(workParent ? ['--working-dir', workParent] : []),
168
278
  // 图/图片区域内的文字保持原文(架构图术语不翻)——目前仅 fork(PR#616)支持
169
279
  ...opt('skip-figure-text'),
170
280
  // 跳过术语表自动抽取:该阶段要额外跑十几轮 LLM(推理型模型上能拖十几分钟,比正文还慢),
171
281
  // 换来的术语一致性提升有限
172
282
  ...opt('no-auto-extract-glossary'),
173
- ], {
174
- env: { ...process.env, HF_ENDPOINT: 'https://hf-mirror.com' }, // 版面模型走国内镜像
175
- timeout: 45 * 60 * 1000,
176
- }, (err, stdout, stderr) => {
177
- void (async () => {
178
- if (err) {
179
- const tail = (stdout + '\n' + stderr).slice(-400);
180
- console.error('[dsh-paper-reader] babeldoc failed:', tail);
181
- busy.set(ref.pdfPath, { error: `babeldoc 执行失败: ${err.message}` });
283
+ ];
284
+ // 优先用驱动脚本(能报进度、能解长度限制);python 找不到或脚本缺失就退回直接跑 babeldoc
285
+ const python = resolveDriverPython(bin);
286
+ const useDriver = Boolean(python) && existsSync(DRIVER_PATH);
287
+ const cmd = useDriver && python ? python : bin;
288
+ const args = useDriver ? [DRIVER_PATH, ...babelArgs] : babelArgs;
289
+ await new Promise((resolveDone) => {
290
+ const stages = [];
291
+ let tail = '';
292
+ let settled = false;
293
+ // 子进程输出写文件而不是管道:①DSH 沙箱里 node 拿不到子进程管道(spawn EPERM)
294
+ // ②翻译跑十几分钟,留一份完整日志比留 400 字符的尾巴好排查
295
+ const logPath = join(tmpDir, `${stem}.babeldoc.log`);
296
+ let spawnError = null;
297
+ let logFd = -1;
298
+ try {
299
+ logFd = openSync(logPath, 'w');
300
+ }
301
+ catch (e) {
302
+ spawnError = e instanceof Error ? e : new Error(String(e));
303
+ }
304
+ const child = spawnError
305
+ ? null
306
+ : spawn(cmd, args, {
307
+ env: { ...process.env, HF_ENDPOINT: 'https://hf-mirror.com', PYTHONIOENCODING: 'utf-8' },
308
+ windowsHide: true,
309
+ stdio: ['ignore', logFd, logFd],
310
+ });
311
+ if (logFd >= 0)
312
+ try {
313
+ closeSync(logFd);
314
+ }
315
+ catch { /* 子进程已持有自己的副本 */ }
316
+ const timer = setTimeout(() => {
317
+ tail = `${tail}\n(超时 ${TRANSLATE_TIMEOUT_MS / 60000} 分钟,已中止)`;
318
+ child?.kill();
319
+ }, TRANSLATE_TIMEOUT_MS);
320
+ const handleLine = (line) => {
321
+ const raw = line.trim();
322
+ if (!raw)
323
+ return;
324
+ if (!raw.startsWith('@@DPR@@ ')) {
325
+ // babeldoc 自己的输出(错误/warning):留最后一段当失败原因
326
+ tail = `${tail}\n${raw}`.slice(-MAX_TAIL_CHARS);
327
+ return;
328
+ }
329
+ let event;
330
+ try {
331
+ event = JSON.parse(raw.slice('@@DPR@@ '.length));
332
+ }
333
+ catch {
334
+ return;
335
+ }
336
+ if (event.kind === 'stages' && Array.isArray(event.stages)) {
337
+ stages.length = 0;
338
+ for (const s of event.stages)
339
+ if (s && typeof s.name === 'string')
340
+ stages.push({ name: s.name, weight: typeof s.weight === 'number' ? s.weight : 0 });
341
+ return;
342
+ }
343
+ if (event.kind !== 'progress')
344
+ return;
345
+ if (event.type === 'error') {
346
+ if (typeof event.message === 'string')
347
+ tail = `${tail}\n${event.message}`.slice(-MAX_TAIL_CHARS);
348
+ return;
349
+ }
350
+ if (event.type === 'finish' || event.type === 'progress_end')
351
+ return;
352
+ const progress = buildProgress(event, stages);
353
+ busy.set(ref.pdfPath, { phase: `${progress.text}…`, progress });
354
+ };
355
+ // 增量 tail 日志文件(按字节偏移读,用 StringDecoder 防多字节字符被切断)
356
+ const decoder = new StringDecoder('utf8');
357
+ let readFd = -1;
358
+ let readPos = 0;
359
+ let pending = '';
360
+ try {
361
+ readFd = openSync(logPath, 'r');
362
+ }
363
+ catch { /* 读不到就只靠退出码判断 */ }
364
+ const pump = () => {
365
+ if (readFd < 0)
182
366
  return;
367
+ let size = 0;
368
+ try {
369
+ size = fstatSync(readFd).size;
183
370
  }
184
- // 产出从 scratch 挪回文献目录:<名>.zh-CN.mono.pdf → -zh.pdf,.dual.pdf → -dual.pdf
371
+ catch {
372
+ return;
373
+ }
374
+ if (size <= readPos)
375
+ return;
376
+ const buf = Buffer.allocUnsafe(Math.min(size - readPos, 256 * 1024));
377
+ let n = 0;
185
378
  try {
186
- // 不用 glob:其 pattern 里反斜杠是转义符,win32 的 join 路径会踩雷;readdir + 前后缀匹配全平台稳
187
- const files = await readdir(tmpDir);
188
- for (const f of files) {
189
- if (f.startsWith(stem) && f.endsWith('.zh-CN.mono.pdf'))
190
- await rename(join(tmpDir, f), dstStem + '-zh.pdf');
191
- if (f.startsWith(stem) && f.endsWith('.zh-CN.dual.pdf'))
192
- await rename(join(tmpDir, f), dstStem + '-dual.pdf');
379
+ n = readSync(readFd, buf, 0, buf.length, readPos);
380
+ }
381
+ catch {
382
+ return;
383
+ }
384
+ if (n <= 0)
385
+ return;
386
+ readPos += n;
387
+ pending += decoder.write(buf.subarray(0, n));
388
+ let idx;
389
+ while ((idx = pending.indexOf('\n')) >= 0) {
390
+ const line = pending.slice(0, idx);
391
+ pending = pending.slice(idx + 1);
392
+ handleLine(line);
393
+ }
394
+ if (pending.length > 64 * 1024)
395
+ pending = pending.slice(-4096);
396
+ };
397
+ const pumpTimer = setInterval(pump, 250);
398
+ const end = (code, error) => {
399
+ if (settled)
400
+ return;
401
+ settled = true;
402
+ clearTimeout(timer);
403
+ clearInterval(pumpTimer);
404
+ pump();
405
+ pending += decoder.end();
406
+ if (pending.trim())
407
+ handleLine(pending);
408
+ if (readFd >= 0)
409
+ try {
410
+ closeSync(readFd);
193
411
  }
194
- if (!existsSync(zhPdfPath(ref)) && !existsSync(dualPdfPath(ref))) {
195
- busy.set(ref.pdfPath, { error: 'babeldoc 未产出译文 PDF' });
412
+ catch { /* 无所谓 */ }
413
+ void (async () => {
414
+ if (error || code !== 0) {
415
+ const detail = (tail.trim() || error?.message || '').slice(-MAX_TAIL_CHARS);
416
+ console.error('[dsh-paper-reader] babeldoc failed:', detail);
417
+ busy.set(ref.pdfPath, { error: `babeldoc 执行失败: ${detail || `退出码 ${code}`}` });
418
+ resolveDone();
196
419
  return;
197
420
  }
198
- busy.delete(ref.pdfPath);
199
- console.log(`[dsh-paper-reader] babeldoc done: ${ref.name}`);
200
- }
201
- catch (e) {
202
- busy.set(ref.pdfPath, { error: `移动译文产物失败: ${e instanceof Error ? e.message : String(e)}` });
203
- }
204
- })();
421
+ // 产出从 scratch 挪回文献目录:<名>.zh-CN.mono.pdf → -zh.pdf,.dual.pdf → -dual.pdf
422
+ try {
423
+ // 不用 glob:其 pattern 里反斜杠是转义符,win32 的 join 路径会踩雷;readdir + 前后缀匹配全平台稳
424
+ const files = await readdir(tmpDir);
425
+ for (const f of files) {
426
+ if (f.startsWith(stem) && f.endsWith('.zh-CN.mono.pdf'))
427
+ await rename(join(tmpDir, f), dstStem + '-zh.pdf');
428
+ if (f.startsWith(stem) && f.endsWith('.zh-CN.dual.pdf'))
429
+ await rename(join(tmpDir, f), dstStem + '-dual.pdf');
430
+ }
431
+ if (!existsSync(zhPdfPath(ref)) && !existsSync(dualPdfPath(ref))) {
432
+ const why = tail.trim().split('\n').pop() ?? '';
433
+ busy.set(ref.pdfPath, { error: `babeldoc 未产出译文 PDF${why ? `:${why}` : ''}` });
434
+ resolveDone();
435
+ return;
436
+ }
437
+ busy.delete(ref.pdfPath);
438
+ console.log(`[dsh-paper-reader] babeldoc done: ${ref.name}`);
439
+ }
440
+ catch (e) {
441
+ busy.set(ref.pdfPath, { error: `移动译文产物失败: ${e instanceof Error ? e.message : String(e)}` });
442
+ }
443
+ resolveDone();
444
+ })();
445
+ };
446
+ if (!child) {
447
+ end(null, spawnError ?? new Error('无法启动翻译进程'));
448
+ return;
449
+ }
450
+ child.on('error', (err) => end(null, err));
451
+ child.on('close', (code) => end(code, null));
205
452
  });
206
- child.unref?.();
207
453
  }
208
454
  /** 解析 PDF 变体路径(原文/zh/dual)。 */
209
455
  export function pdfVariantPath(ref, variant) {
package/lib/client.js CHANGED
@@ -399,16 +399,23 @@ window.__ModuleLoader__.load({
399
399
  // (auto-placement 只钉列会重叠/塌行,实测);面板锚列右缘且内联宽度=rightbar
400
400
  // 配置宽度,列进窄轨会左溢盖侧栏 → 钉 max-width(⚠️ 不抢 width:dsh 在会话 store
401
401
  // 每次提交都重写内联 width,互写同属性 = 持续闪烁,实测)。
402
- // 钉住条件按**右栏轨宽**自判断:右栏折叠(第 3 轨≈0)时撤钉 —— 否则 seat 重绑的
403
- // 空窗期 PDF 列会吃掉对话列的宽度,双双消失又出现("整屏闪",实测)。
402
+ // 钉住条件 = **dpr 页签锚点存在** + 右栏轨宽自判断:右栏折叠(第 3 轨≈0)时撤钉
403
+ // —— 否则 seat 重绑的空窗期 PDF 列会吃掉对话列的宽度,双双消失又出现("整屏闪",实测)。
404
+ // 只看轨宽不够(#10):任何右侧栏页签(官方文件预览/present 卡片)都会撑开第 3 轨,
405
+ // 普通会话里会把对话挤到最右。锚点在 seat 重绑/切换护栏的空窗期会瞬时消失(同下方
406
+ // overlay 测量的暂态),按 lastSeen 加 1500ms(=切换护栏窗口宽)迟滞,免得换位
407
+ // 撤钉又回钉,闪回当初修掉的整屏闪。
404
408
  const setStyle = (el, prop, val) => { if (el.style[prop] !== val) el.style[prop] = val }
409
+ let lastPdfTabAt = 0
405
410
  const applySwap = () => {
406
411
  const col = document.querySelector('[data-rightbar-col]')
407
412
  const center = col?.previousElementSibling // DOM 序固定:sidebar | center | rightbar
408
413
  const frame = col?.parentElement
409
414
  if (!col || !center || !frame) return
410
415
  const tracks = getComputedStyle(frame).gridTemplateColumns.split(' ').map(parseFloat)
411
- const eff = (tracks[2] ?? 0) >= 50 && !frame.hasAttribute('data-rightbar-fullscreen')
416
+ const tabEl = document.querySelector('[data-dpr-tab]')
417
+ if (tabEl) lastPdfTabAt = Date.now()
418
+ const eff = (!!tabEl || Date.now() - lastPdfTabAt < 1500) && (tracks[2] ?? 0) >= 50 && !frame.hasAttribute('data-rightbar-fullscreen')
412
419
  // 所有写入带值守卫:重复写同值也会触发样式重算,200ms 轮询下会闪
413
420
  setStyle(col, 'gridColumn', eff ? '2' : '')
414
421
  setStyle(col, 'gridRow', eff ? '1' : '')
@@ -491,10 +498,13 @@ window.__ModuleLoader__.load({
491
498
 
492
499
  /* ---------- rightbar PDF 页签(只剩占位锚点 + 布局换位) ---------- */
493
500
  function PdfTab() {
494
- // 真正的阅读器是 ReaderOverlay 的常驻 iframe;这里只提供定位锚点
501
+ // 真正的阅读器是 ReaderOverlay 的常驻 iframe;这里只提供定位锚点。
502
+ // data-dpr-tab 标记 = 「dpr 页签在本会话开着」,applySwap 据此判断是否换位(#10:
503
+ // 不能只看右栏轨宽,否则官方文件预览页签也会把对话挤到最右)。
495
504
  const hasPaper = !!localStorage.getItem('dpr.last')
496
505
  return h('div', {
497
506
  'data-dsh-surface': 'rightbar-tab-anchor',
507
+ 'data-dpr-tab': '1',
498
508
  style: { width: '100%', height: '100%' },
499
509
  }, hasPaper ? null : h('div', { style: { padding: '16px', fontSize: '13px', color: 'var(--dsw-alias-label-secondary, #656d76)' } }, '← 从文献库选择一篇论文'))
500
510
  }