@ggboy123/dsh-paper-reader 1.5.1 → 1.6.1

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/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
@@ -88,6 +88,7 @@ window.__ModuleLoader__.load({
88
88
  setSave: '测试并保存', setSaving: '测试连接中…', setClear: '清除自填配置',
89
89
  setSaved: '已保存,立即生效', setCleared: '已清除,回落到部署方默认',
90
90
  setKeyKeep: '留空沿用已保存的 ', setOptional: '可选',
91
+ setEmbedBatchSize: '批大小(每次请求的分块数,端点限制更小时调低,如百炼部分模型 10/20)',
91
92
  setSourceFile: '当前来源:设置页', setSourceProfile: '当前来源:配置文件(部署方默认)',
92
93
  setSourceEnv: '当前来源:环境变量', setSourceNone: '未配置',
93
94
  setMineruTitle: 'MinerU 解析后端',
@@ -169,6 +170,7 @@ window.__ModuleLoader__.load({
169
170
  setSave: 'Test & save', setSaving: 'Testing…', setClear: 'Clear my config',
170
171
  setSaved: 'Saved, effective immediately', setCleared: 'Cleared, falling back to deployment defaults',
171
172
  setKeyKeep: 'Leave empty to keep saved ', setOptional: 'optional',
173
+ setEmbedBatchSize: 'Batch size (chunks per request; lower it when the endpoint caps inputs, e.g. 10/20 on some Bailian models)',
172
174
  setSourceFile: 'Source: settings page', setSourceProfile: 'Source: config file (deployment default)',
173
175
  setSourceEnv: 'Source: environment variable', setSourceNone: 'Not configured',
174
176
  setMineruTitle: 'MinerU parser',
@@ -399,16 +401,23 @@ window.__ModuleLoader__.load({
399
401
  // (auto-placement 只钉列会重叠/塌行,实测);面板锚列右缘且内联宽度=rightbar
400
402
  // 配置宽度,列进窄轨会左溢盖侧栏 → 钉 max-width(⚠️ 不抢 width:dsh 在会话 store
401
403
  // 每次提交都重写内联 width,互写同属性 = 持续闪烁,实测)。
402
- // 钉住条件按**右栏轨宽**自判断:右栏折叠(第 3 轨≈0)时撤钉 —— 否则 seat 重绑的
403
- // 空窗期 PDF 列会吃掉对话列的宽度,双双消失又出现("整屏闪",实测)。
404
+ // 钉住条件 = **dpr 页签锚点存在** + 右栏轨宽自判断:右栏折叠(第 3 轨≈0)时撤钉
405
+ // —— 否则 seat 重绑的空窗期 PDF 列会吃掉对话列的宽度,双双消失又出现("整屏闪",实测)。
406
+ // 只看轨宽不够(#10):任何右侧栏页签(官方文件预览/present 卡片)都会撑开第 3 轨,
407
+ // 普通会话里会把对话挤到最右。锚点在 seat 重绑/切换护栏的空窗期会瞬时消失(同下方
408
+ // overlay 测量的暂态),按 lastSeen 加 1500ms(=切换护栏窗口宽)迟滞,免得换位
409
+ // 撤钉又回钉,闪回当初修掉的整屏闪。
404
410
  const setStyle = (el, prop, val) => { if (el.style[prop] !== val) el.style[prop] = val }
411
+ let lastPdfTabAt = 0
405
412
  const applySwap = () => {
406
413
  const col = document.querySelector('[data-rightbar-col]')
407
414
  const center = col?.previousElementSibling // DOM 序固定:sidebar | center | rightbar
408
415
  const frame = col?.parentElement
409
416
  if (!col || !center || !frame) return
410
417
  const tracks = getComputedStyle(frame).gridTemplateColumns.split(' ').map(parseFloat)
411
- const eff = (tracks[2] ?? 0) >= 50 && !frame.hasAttribute('data-rightbar-fullscreen')
418
+ const tabEl = document.querySelector('[data-dpr-tab]')
419
+ if (tabEl) lastPdfTabAt = Date.now()
420
+ const eff = (!!tabEl || Date.now() - lastPdfTabAt < 1500) && (tracks[2] ?? 0) >= 50 && !frame.hasAttribute('data-rightbar-fullscreen')
412
421
  // 所有写入带值守卫:重复写同值也会触发样式重算,200ms 轮询下会闪
413
422
  setStyle(col, 'gridColumn', eff ? '2' : '')
414
423
  setStyle(col, 'gridRow', eff ? '1' : '')
@@ -491,10 +500,13 @@ window.__ModuleLoader__.load({
491
500
 
492
501
  /* ---------- rightbar PDF 页签(只剩占位锚点 + 布局换位) ---------- */
493
502
  function PdfTab() {
494
- // 真正的阅读器是 ReaderOverlay 的常驻 iframe;这里只提供定位锚点
503
+ // 真正的阅读器是 ReaderOverlay 的常驻 iframe;这里只提供定位锚点。
504
+ // data-dpr-tab 标记 = 「dpr 页签在本会话开着」,applySwap 据此判断是否换位(#10:
505
+ // 不能只看右栏轨宽,否则官方文件预览页签也会把对话挤到最右)。
495
506
  const hasPaper = !!localStorage.getItem('dpr.last')
496
507
  return h('div', {
497
508
  'data-dsh-surface': 'rightbar-tab-anchor',
509
+ 'data-dpr-tab': '1',
498
510
  style: { width: '100%', height: '100%' },
499
511
  }, hasPaper ? null : h('div', { style: { padding: '16px', fontSize: '13px', color: 'var(--dsw-alias-label-secondary, #656d76)' } }, '← 从文献库选择一篇论文'))
500
512
  }
@@ -1395,13 +1407,19 @@ window.__ModuleLoader__.load({
1395
1407
 
1396
1408
  function EndpointCard(props) {
1397
1409
  const [cfg, setCfg] = useState(null) // GET 结果(含 apiKeyHint/source)
1398
- const [form, setForm] = useState({ baseUrl: '', model: '', apiKey: '' })
1410
+ const [form, setForm] = useState({ baseUrl: '', model: '', apiKey: '', batchSize: '' })
1399
1411
  const [busy, setBusy] = useState(false)
1400
1412
  const [msg, setMsg] = useState(null) // { ok, text }
1401
1413
  const load = useCallback(() => {
1402
1414
  api(props.path).then((d) => {
1403
1415
  setCfg(d)
1404
- setForm({ baseUrl: d.baseUrl || '', model: d.model || '', apiKey: '' })
1416
+ setForm({
1417
+ baseUrl: d.baseUrl || '',
1418
+ model: d.model || '',
1419
+ apiKey: '',
1420
+ // null = 未显式配置(回落 profile / 默认 10),输入框留空展示占位符
1421
+ ...(props.batchSize ? { batchSize: d.batchSize != null ? String(d.batchSize) : '' } : {}),
1422
+ })
1405
1423
  }).catch((e) => setMsg({ ok: false, text: String(e.message || e) }))
1406
1424
  }, [props.path])
1407
1425
  useEffect(load, [load])
@@ -1438,6 +1456,8 @@ window.__ModuleLoader__.load({
1438
1456
  field('baseUrl', t('setBaseUrl'), props.baseUrlPlaceholder),
1439
1457
  field('model', t('setModel'), props.modelPlaceholder),
1440
1458
  field('apiKey', t('setKey'), cfg?.hasApiKey ? t('setKeyKeep') + cfg.apiKeyHint : props.keyPlaceholder, 'password'),
1459
+ // 批大小仅嵌入卡片有(issue #14):预检会按这个值真打一批,端点限流当场暴露而不是首次检索才失败
1460
+ props.batchSize ? field('batchSize', t('setEmbedBatchSize'), '10') : null,
1441
1461
  h('div', { style: SET.row },
1442
1462
  h('button', { type: 'button', style: SET.btn, disabled: busy, onClick: save }, busy ? t('setSaving') : t('setSave')),
1443
1463
  cfg?.source === 'file' ? h('button', { type: 'button', style: SET.btnGhost, disabled: busy, onClick: clear }, t('setClear')) : null,
@@ -1496,6 +1516,7 @@ window.__ModuleLoader__.load({
1496
1516
  h(EndpointCard, {
1497
1517
  path: '/embed/config', title: t('setEmbedTitle'), desc: t('setEmbedDesc'), optional: true,
1498
1518
  baseUrlPlaceholder: 'https://api.openai.com/v1', modelPlaceholder: 'text-embedding-3-small', keyPlaceholder: 'sk-...',
1519
+ batchSize: true,
1499
1520
  }),
1500
1521
  h(EndpointCard, {
1501
1522
  path: '/translate/config', title: t('setTranslateTitle'), desc: t('setTranslateDesc'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ggboy123/dsh-paper-reader",
3
- "version": "1.5.1",
3
+ "version": "1.6.1",
4
4
  "description": "DeepSeek Harness 插件:论文伴读工作台 — PDF 转录 / 检索 / 原生对话伴读 + 内置阅读器页面。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -26,7 +26,7 @@
26
26
  "dist",
27
27
  "lib",
28
28
  "reader",
29
- "presets",
29
+ "runtime",
30
30
  "cordis.patch.yml"
31
31
  ],
32
32
  "dsh": {
@@ -43,13 +43,14 @@
43
43
  }
44
44
  },
45
45
  "scripts": {
46
- "build": "tsc -p tsconfig.json",
46
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
47
+ "build": "npm run clean && tsc -p tsconfig.json",
47
48
  "typecheck": "tsc -p tsconfig.json --noEmit",
48
49
  "pretest": "npm run build",
49
50
  "test": "node --test --test-timeout=60000 --test-concurrency=1 \"test/*.test.mjs\"",
50
51
  "smoke:engine": "node scripts/engine-smoke.mjs",
51
52
  "release": "node scripts/release.mjs",
52
- "prepublishOnly": "tsc -p tsconfig.json"
53
+ "prepublishOnly": "npm run build"
53
54
  },
54
55
  "keywords": [
55
56
  "dsh-plugin",
@@ -74,11 +75,11 @@
74
75
  },
75
76
  "peerDependencies": {
76
77
  "@deepseek-ai/cordis": "^4.0.2",
77
- "@deepseek-ai/dsh-tools": ">=0.1.5-rc.1 <0.3.0-0"
78
+ "@deepseek-ai/dsh-tools": ">=0.2.0-rc.2 <0.3.0-0"
78
79
  },
79
80
  "devDependencies": {
80
81
  "@deepseek-ai/cordis": "^4.0.2",
81
- "@deepseek-ai/dsh-tools": "0.1.5-rc.2",
82
+ "@deepseek-ai/dsh-tools": "0.2.0-rc.2",
82
83
  "@types/node": "^22.10.0",
83
84
  "typescript": "^5.6.0"
84
85
  }