@ggboy123/dsh-paper-reader 1.6.1 → 1.8.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 +7 -4
- package/dist/host.js +480 -46
- package/dist/library-manage.js +628 -122
- package/dist/library.js +337 -55
- package/dist/migrate.js +981 -0
- package/dist/notes.js +184 -0
- package/dist/opencode.js +123 -0
- package/dist/scope.js +379 -0
- package/dist/search.js +21 -12
- package/dist/theme-config.js +123 -0
- package/dist/tools.js +8 -2
- package/dist/translate-config.js +8 -1
- package/dist/translate-selection.js +6 -0
- package/dist/translate.js +7 -1
- package/lib/client.js +419 -87
- package/package.json +2 -1
- package/reader/index.html +1117 -39
- package/runtime/babeldoc-driver.py +5 -0
package/dist/host.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
// host.ts — webServer 路由:阅读器页面 + PDF 文件 + 转录数据接口 + 选中即问。
|
|
2
2
|
// 壳层代码:只做 HTTP ↔ 纯函数核心(library/transcribe)的转接。
|
|
3
|
-
import { createReadStream, existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { createReadStream, existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
4
4
|
import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
|
|
5
5
|
import { randomUUID } from 'node:crypto';
|
|
6
|
-
import { basename, join, resolve } from 'node:path';
|
|
7
|
-
import { listPapers, listTopics, resolveDataDir, resolvePaper, resolveUploadTopic, validateEntryBoundary, validateEntryName, } from "./library.js";
|
|
8
|
-
import { ManageError, assertInside, clearTopic, planTopicClear, deletePaper, deleteTopic, isManageError, planPaperDelete, planTopicDelete, realDataDir, renamePaper, renameTopic, resolveTopicDir,
|
|
6
|
+
import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
7
|
+
import { caseVariantCollisions, existingEntryName, flatArtifactNames, isPaperDir, listPapers, listTopicTree, listTopics, paperDirAncestor, paperPdfPath, paperRefFor, resolveDataDir, resolvePaper, resolveUploadTopic, validateEntryBoundary, validateEntryName, } from "./library.js";
|
|
8
|
+
import { ManageError, assertInside, clearTopic, planTopicClear, deletePaper, deleteTopic, isManageError, planPaperDelete, planTopicDelete, realDataDir, renamePaper, renameTopic, resolveTopicDir, validateTopicPath, } from "./library-manage.js";
|
|
9
9
|
import { readFormulaIndex, readTextBlockIndex } from "./formulas.js";
|
|
10
|
+
import { buildScopeContext } from "./scope.js";
|
|
10
11
|
import { MAX_CHUNKS, MAX_LATEX_CHARS, MAX_TEXT_CHARS, MAX_TOTAL_CHARS, SelectionTranslateError, assembleSource, formulaStatusOf, translateSelection, } from "./translate-selection.js";
|
|
11
12
|
import { MineruError, sanitizeDetail } from "./mineru.js";
|
|
12
13
|
import { readTranscript, transcribePaper, ScannedPdfError, ShortTextError } from "./transcribe.js";
|
|
@@ -15,7 +16,13 @@ import { clearTranslateConfig, maskApiKey, readTranslateConfig, resolveTranslate
|
|
|
15
16
|
import { clearTypesafeConfig, readTypesafeConfig, resolveTypesafeConfig, testTypesafeEndpoint, writeTypesafeConfig, } from "./typesafe-config.js";
|
|
16
17
|
import { clearEmbedConfig, maskApiKey as maskEmbedApiKey, readEmbedConfig, resolveEmbedConfig, testEmbedEndpoint, writeEmbedConfig, } from "./embed-config.js";
|
|
17
18
|
import { clearMineruConfig, mergeMineruBody, precheckMineruConfig, resolveMineruConfig, testMineruCloud, testMineruLocal, writeMineruConfig, } from "./mineru-config.js";
|
|
19
|
+
// preset 已随 dsh 0.2.x 迁移到 cordis.patch.yml 声明式注册(main a675b9f):
|
|
20
|
+
// host 不再安装 preset,会话创建也不默认套用任何 preset。
|
|
21
|
+
import { MigrationAborted, MigrationError, formatMigrationReport, lastMigrationLog, migrationLogDir, planMigration, rollbackMigration, runMigrationAsync, } from "./migrate.js";
|
|
18
22
|
import { noteOrigin } from "./origin.js";
|
|
23
|
+
import { deleteNote, isNoteError, readNotes, upsertNote } from "./notes.js";
|
|
24
|
+
import { isOpenCodeEndpoint, openCodeSessionId } from "./opencode.js";
|
|
25
|
+
import { clearThemeConfig, readThemeConfig, themePayload, validateThemePatch, writeThemeConfig, } from "./theme-config.js";
|
|
19
26
|
function json(res, status, body) {
|
|
20
27
|
const buf = Buffer.from(JSON.stringify(body), 'utf8');
|
|
21
28
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': buf.length });
|
|
@@ -142,6 +149,15 @@ export function registerRoutes(ctx, config) {
|
|
|
142
149
|
};
|
|
143
150
|
/** 专题目录 → dsh 工作区(幂等,进程内缓存)。会话挂到工作区后原生 composer 才可用。 */
|
|
144
151
|
const workspaceCache = new Map();
|
|
152
|
+
/** 删/改/清空一个专题(可能是路径)后,把**整棵子树**的工作区缓存键清掉(方案 §B2.4)。 */
|
|
153
|
+
const dropWorkspaceCache = (topicPath) => {
|
|
154
|
+
const base = join(dataDir, ...topicPath.split('/').filter(Boolean));
|
|
155
|
+
const prefix = base.endsWith(sep) ? base : base + sep;
|
|
156
|
+
for (const k of [...workspaceCache.keys()]) {
|
|
157
|
+
if (k === base || k.startsWith(prefix))
|
|
158
|
+
workspaceCache.delete(k);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
145
161
|
const ensureTopicWorkspace = async (topic) => {
|
|
146
162
|
const dir = join(dataDir, topic);
|
|
147
163
|
const cached = workspaceCache.get(dir);
|
|
@@ -263,6 +279,52 @@ export function registerRoutes(ctx, config) {
|
|
|
263
279
|
inflight.delete(key);
|
|
264
280
|
}
|
|
265
281
|
};
|
|
282
|
+
/** 正在转录的文献(`topic\u0000name`):/migrate 的 busy 门用(评审 E3)。 */
|
|
283
|
+
const activeTranscribes = new Set();
|
|
284
|
+
/**
|
|
285
|
+
* 该范围(或其子树)是否有写操作在途。读路径**不阻塞**(方案 §B3.2:fail-soft),
|
|
286
|
+
* 只在提示里如实说「正在被修改,本次只给了 N 篇」。
|
|
287
|
+
*
|
|
288
|
+
* 修 G3(评审 G 次级):inflight 的 key 是 `paper\u0000<topic>\u0000<name>` /
|
|
289
|
+
* `topic\u0000<topicPath>`,旧实现拿 `scopePath`(`topic/name`,斜杠分隔)做 `k.includes(...)`
|
|
290
|
+
* ⇒ paper 范围**永远匹配不上**,busy 提示是死代码。现在先把 key 解析成「被操作的路径」再做
|
|
291
|
+
* 双向前缀判定:范围包含在途操作(自己的子树正在被改)或被在途操作包含(祖先专题正在被
|
|
292
|
+
* 清空/改名/迁移)。`migrate` 在途同样视为「正在被修改」(它确实在动整个库的文件)。
|
|
293
|
+
*/
|
|
294
|
+
const scopeBusy = (scopePath) => {
|
|
295
|
+
for (const k of inflight) {
|
|
296
|
+
const parts = k.split('\u0000');
|
|
297
|
+
let subject = null;
|
|
298
|
+
if (parts[0] === 'migrate')
|
|
299
|
+
return true;
|
|
300
|
+
if (parts[0] === 'topic' && parts.length === 2)
|
|
301
|
+
subject = parts[1] ?? null;
|
|
302
|
+
else if (parts[0] === 'paper' && parts.length === 3)
|
|
303
|
+
subject = `${parts[1] ?? ''}/${parts[2] ?? ''}`;
|
|
304
|
+
if (!subject)
|
|
305
|
+
continue;
|
|
306
|
+
if (subject === scopePath || subject.startsWith(scopePath + '/') || scopePath.startsWith(subject + '/'))
|
|
307
|
+
return true;
|
|
308
|
+
}
|
|
309
|
+
return false;
|
|
310
|
+
};
|
|
311
|
+
/** 全库在飞译文(评审 E3 的 busy 门):迁移会搬走这些论文的产物,必须等它们完成。 */
|
|
312
|
+
const translationBusyPapers = () => {
|
|
313
|
+
const out = [];
|
|
314
|
+
for (const p of listPapers(dataDir)) {
|
|
315
|
+
try {
|
|
316
|
+
if (zhStatus(paperRefFor(dataDir, p.topic, p.name)).busy)
|
|
317
|
+
out.push(`${p.topic}/${p.name}`);
|
|
318
|
+
}
|
|
319
|
+
catch { /* 读不到的单篇不阻塞迁移(迁移自己会如实报 unreadable/冲突) */ }
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
};
|
|
323
|
+
/** 清空单元树 → 逐篇清单(评审 D:占用巡检与确认清单都必须覆盖整棵子树,不能只看根层 papers)。 */
|
|
324
|
+
const flattenClearPapers = (unit) => [
|
|
325
|
+
...unit.papers,
|
|
326
|
+
...unit.subtopics.flatMap((s) => flattenClearPapers(s)),
|
|
327
|
+
];
|
|
266
328
|
/** 「文献不存在」的统一出口:404 + 不含服务端绝对路径的文案(原先普通 Error 会冒泡成 500 并带路径)。 */
|
|
267
329
|
const notFound = (what) => new ManageError('not-found', 404, what);
|
|
268
330
|
/**
|
|
@@ -356,8 +418,11 @@ export function registerRoutes(ctx, config) {
|
|
|
356
418
|
return;
|
|
357
419
|
}
|
|
358
420
|
if (sub === '/api/library' && req.method === 'GET') {
|
|
359
|
-
|
|
360
|
-
|
|
421
|
+
// F-C:pdfPath 必须按**该篇实际所在布局**给(新布局论文夹 / 旧布局平铺)。
|
|
422
|
+
// 写死新布局会让未迁移旧库里的平铺论文 pdfPath 指向不存在的路径(直接影响用户现在正在用的库)。
|
|
423
|
+
const papers = listPapers(dataDir).map((p) => ({ ...p, pdfPath: paperPdfPath(dataDir, p.topic, p.name) }));
|
|
424
|
+
// topics 保持「一级子目录」语义(既有调用方/测试),新增 tree = 完整嵌套树(子专题 UI 用)
|
|
425
|
+
json(res, 200, { dataDir, topics: listTopics(dataDir), papers, tree: listTopicTree(dataDir) });
|
|
361
426
|
return;
|
|
362
427
|
}
|
|
363
428
|
// 新建专题(目录)。校验与 upload / rename 的 to 侧同一套(validateName:边界 + 命名规范),
|
|
@@ -366,9 +431,46 @@ export function registerRoutes(ctx, config) {
|
|
|
366
431
|
if (sub === '/api/library/topic' && req.method === 'POST') {
|
|
367
432
|
const body = (await readBody(req));
|
|
368
433
|
try {
|
|
369
|
-
|
|
434
|
+
// name 是**相对路径**(`A` / `A/B`):逐段词法校验 + 「已存在的祖先必须是库内真目录」。
|
|
435
|
+
// mkdir(recursive) 天然能一次建多级(方案 §B2.2「天然建多级」);这里挡的是父链里**已存在**的那几段
|
|
436
|
+
// ——符号链接 / 指向库外的段一律拒(不隐式穿越),不存在的段交给 mkdir 创建。
|
|
437
|
+
const name = validateTopicPath(body.name, false);
|
|
370
438
|
const root = realDataDir(dataDir);
|
|
371
|
-
const
|
|
439
|
+
const segs = name.split('/');
|
|
440
|
+
const leaf = segs[segs.length - 1];
|
|
441
|
+
const parentSegs = segs.slice(0, -1);
|
|
442
|
+
// C1(评审 C1):已存在的祖先段若是**论文目录** → 409。论文目录不能再当专题父:
|
|
443
|
+
// listPapers 在论文目录处停止递归,在其下新建的专题会整体从列表/树/范围提问里消失。
|
|
444
|
+
const paperParent = paperDirAncestor(root, parentSegs);
|
|
445
|
+
if (paperParent) {
|
|
446
|
+
throw new ManageError('target-exists', 409, `父级是论文目录,不能在其下创建专题:${paperParent}`, { conflicts: [paperParent] });
|
|
447
|
+
}
|
|
448
|
+
// C2(评审 C2):同层已有同名**旧平铺论文**产物 → 409。建出同名目录后「文件夹优先」规则
|
|
449
|
+
// 会把旧平铺论文永久遮蔽(列表/树看不见、planPaperDelete 404、产物从 API 不可删)。
|
|
450
|
+
// 只看 topic 内部(parentSegs 非空):dataDir 根层的平铺文件不是文献,不构成遮蔽。
|
|
451
|
+
if (parentSegs.length > 0) {
|
|
452
|
+
const flat = flatArtifactNames(join(root, ...parentSegs), leaf);
|
|
453
|
+
if (flat.length > 0) {
|
|
454
|
+
throw new ManageError('target-exists', 409, `同层已有旧布局论文:${flat.join('、')}(请先迁移或改名,否则它会被同名专题遮蔽)`, { conflicts: flat });
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
// 评审 REV1-① / t11:目标同级已有**仅大小写不同**的条目 ⇒ 409 并点名磁盘真名。
|
|
458
|
+
// 不敏感盘上 mkdir 会命中既有目录别名(旧实现 return 200 = 假成功);敏感盘上会并存
|
|
459
|
+
// `CaseTopic` + `casetopic` 两个近同名专题。upload 已经拒这类(B4),此处对齐同一口径。
|
|
460
|
+
const caseClash = caseVariantCollisions(join(root, ...parentSegs), leaf);
|
|
461
|
+
if (caseClash.length > 0) {
|
|
462
|
+
throw new ManageError('target-exists', 409, `同层已有仅大小写不同的同名对象:${caseClash.join('、')}(大小写不敏感的文件系统上会互相吞掉)`, { conflicts: caseClash });
|
|
463
|
+
}
|
|
464
|
+
for (let i = 1; i < segs.length; i++) {
|
|
465
|
+
if (!existsSync(join(root, ...segs.slice(0, i))))
|
|
466
|
+
break;
|
|
467
|
+
resolveTopicDir(dataDir, segs.slice(0, i).join('/'));
|
|
468
|
+
}
|
|
469
|
+
const dir = join(root, ...segs);
|
|
470
|
+
// 目标本身已是论文目录(嵌套层)→ 409:它在列表里会被当成论文,永远不是可用的专题。
|
|
471
|
+
if (parentSegs.length > 0 && isPaperDir(dir)) {
|
|
472
|
+
throw new ManageError('target-exists', 409, `已存在同名论文:${leaf}(不能当专题)`, { conflicts: [leaf] });
|
|
473
|
+
}
|
|
372
474
|
// 已存在 → 必须是真目录且不是符号链接(与 upload 同一条链路);不存在 → 词法层已保证不越界
|
|
373
475
|
if (existsSync(dir))
|
|
374
476
|
resolveTopicDir(dataDir, name);
|
|
@@ -392,10 +494,14 @@ export function registerRoutes(ctx, config) {
|
|
|
392
494
|
json(res, 400, { error: '缺少 x-dpr-topic / x-dpr-name 头', code: 'bad-request' });
|
|
393
495
|
return;
|
|
394
496
|
}
|
|
395
|
-
//
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
497
|
+
// 词法层:topic 是**相对路径**,逐段同强度校验(../ / \ 隐藏名 控制字符 超长 空串/层级上限)
|
|
498
|
+
let topicPath;
|
|
499
|
+
try {
|
|
500
|
+
topicPath = validateTopicPath(topic, false);
|
|
501
|
+
}
|
|
502
|
+
catch (err) {
|
|
503
|
+
if (!manageFail(res, err))
|
|
504
|
+
throw err;
|
|
399
505
|
return;
|
|
400
506
|
}
|
|
401
507
|
if (!filename.toLowerCase().endsWith('.pdf')) {
|
|
@@ -416,7 +522,7 @@ export function registerRoutes(ctx, config) {
|
|
|
416
522
|
// 顺序:目标目录的全部校验都在**读 body 之前**——越界目标不消费请求体、不碰盘。
|
|
417
523
|
let dir;
|
|
418
524
|
try {
|
|
419
|
-
dir = resolveUploadTopic(dataDir,
|
|
525
|
+
dir = resolveUploadTopic(dataDir, topicPath);
|
|
420
526
|
}
|
|
421
527
|
catch (err) {
|
|
422
528
|
json(res, 400, { error: readableError(err), code: 'escape-rejected' });
|
|
@@ -425,7 +531,7 @@ export function registerRoutes(ctx, config) {
|
|
|
425
531
|
// 我们的加严:上游放行「real 落在库内」的符号链接专题,我们一律拒(评审 §B 点名表扬)。
|
|
426
532
|
try {
|
|
427
533
|
if (existsSync(dir))
|
|
428
|
-
resolveTopicDir(dataDir,
|
|
534
|
+
resolveTopicDir(dataDir, topicPath);
|
|
429
535
|
else
|
|
430
536
|
assertInside(realDataDir(dataDir), dir);
|
|
431
537
|
}
|
|
@@ -434,6 +540,53 @@ export function registerRoutes(ctx, config) {
|
|
|
434
540
|
return;
|
|
435
541
|
throw err;
|
|
436
542
|
}
|
|
543
|
+
// ── 写侧布局碰撞预检(评审 B/C1):**在消费请求体之前**完成(既有约定:越界/碰撞目标不读 body、不碰盘)──
|
|
544
|
+
// ① C1:topic 路径上任何一段(第 2 段起)已是**论文目录** ⇒ 409。论文目录不会再被递归,
|
|
545
|
+
// 往里上传的新论文会从列表/树/范围提问里整体消失。
|
|
546
|
+
// ② B1/B2:目标 `<topicDir>/<stem>/` 已存在(子专题目录 / 论文目录 / 同名文件)⇒ 409。
|
|
547
|
+
// 把子专题变成论文目录会让其下论文整体消失;覆盖已有论文目录会吞数据。
|
|
548
|
+
// ③ B2:同层已有**旧平铺论文**同名产物(`<stem>.pdf/.txt/.study.json/...`)⇒ 409。
|
|
549
|
+
// 「文件夹优先」规则会永久遮蔽它们(学习进度不可见、产物从 API 不可删)。
|
|
550
|
+
// ④ B3:仅大小写不同的同名目录 / 平铺文件 ⇒ 409,文案点名磁盘上的真实冲突对象。
|
|
551
|
+
try {
|
|
552
|
+
const root = realDataDir(dataDir);
|
|
553
|
+
const paperSeg = paperDirAncestor(root, topicPath.split('/'));
|
|
554
|
+
if (paperSeg) {
|
|
555
|
+
throw new ManageError('target-exists', 409, `专题路径落在论文目录里,不能上传:${paperSeg}`, { conflicts: [paperSeg] });
|
|
556
|
+
}
|
|
557
|
+
const targetPaperDir = join(dir, stem);
|
|
558
|
+
let targetStat = null;
|
|
559
|
+
try {
|
|
560
|
+
targetStat = lstatSync(targetPaperDir);
|
|
561
|
+
}
|
|
562
|
+
catch { /* 目标尚不存在 → 继续查同层产物 */ }
|
|
563
|
+
if (targetStat) {
|
|
564
|
+
const actual = existingEntryName(dir, stem);
|
|
565
|
+
if (targetStat.isSymbolicLink()) {
|
|
566
|
+
throw new ManageError('escape-rejected', 400, `路径越界:目标论文路径是符号链接,已拒绝:${actual}`);
|
|
567
|
+
}
|
|
568
|
+
if (targetStat.isDirectory()) {
|
|
569
|
+
if (isPaperDir(targetPaperDir)) {
|
|
570
|
+
throw new ManageError('target-exists', 409, `已存在同名论文目录:${actual}(上传会覆盖/合并它)`, { conflicts: [actual] });
|
|
571
|
+
}
|
|
572
|
+
throw new ManageError('target-exists', 409, `已存在同名子专题:${actual}(上传会把它变成论文目录,其下文献将整体消失)`, { conflicts: [actual] });
|
|
573
|
+
}
|
|
574
|
+
throw new ManageError('target-exists', 409, `已存在同名文件:${actual}(上传会覆盖它)`, { conflicts: [actual] });
|
|
575
|
+
}
|
|
576
|
+
const flat = flatArtifactNames(dir, stem);
|
|
577
|
+
if (flat.length > 0) {
|
|
578
|
+
throw new ManageError('target-exists', 409, `同层已有旧布局论文产物:${flat.join('、')}(新建论文文件夹会把它永久遮蔽,请先迁移)`, { conflicts: flat });
|
|
579
|
+
}
|
|
580
|
+
const caseVariants = caseVariantCollisions(dir, stem);
|
|
581
|
+
if (caseVariants.length > 0) {
|
|
582
|
+
throw new ManageError('target-exists', 409, `同层已有仅大小写不同的同名对象:${caseVariants.join('、')}(大小写不敏感的文件系统上会互相吞掉)`, { conflicts: caseVariants });
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
catch (err) {
|
|
586
|
+
if (libFail(res, err))
|
|
587
|
+
return;
|
|
588
|
+
throw err;
|
|
589
|
+
}
|
|
437
590
|
const chunks = [];
|
|
438
591
|
for await (const c of req)
|
|
439
592
|
chunks.push(c);
|
|
@@ -443,14 +596,15 @@ export function registerRoutes(ctx, config) {
|
|
|
443
596
|
return;
|
|
444
597
|
}
|
|
445
598
|
try {
|
|
446
|
-
|
|
447
|
-
await
|
|
599
|
+
// 新布局(方案 §B1.3 #20):先建**论文文件夹** `<topicDir>/<论文名>/`,PDF 落在里面
|
|
600
|
+
await mkdir(join(dir, stem), { recursive: true });
|
|
601
|
+
await writeFile(join(dir, stem, safeName), buf);
|
|
448
602
|
}
|
|
449
603
|
catch (err) {
|
|
450
604
|
fsError(res, err);
|
|
451
605
|
return;
|
|
452
606
|
}
|
|
453
|
-
json(res, 200, { ok: true, topic:
|
|
607
|
+
json(res, 200, { ok: true, topic: topicPath, name: stem, bytes: buf.length });
|
|
454
608
|
return;
|
|
455
609
|
}
|
|
456
610
|
/* ── 路由名兼容层 ─────────────────────────────────────────────────────
|
|
@@ -478,6 +632,21 @@ export function registerRoutes(ctx, config) {
|
|
|
478
632
|
json(res, 400, { error: err, code: 'bad-name' });
|
|
479
633
|
return true;
|
|
480
634
|
};
|
|
635
|
+
/**
|
|
636
|
+
* 专题**路径**的入参门(方案 §B2.2):topic 升级为相对路径(`A` / `A/B`)后,**全部** topic
|
|
637
|
+
* 入参统一走这里——先逐段词法校验、再解析真目录,禁止保留两套并存的入参语义
|
|
638
|
+
* (否则会出现「同一个 topic 在 clear-plan 能过、在 clear 过不了」的不对称)。
|
|
639
|
+
*/
|
|
640
|
+
const badTopicPath = (res, raw, boundaryOnly) => {
|
|
641
|
+
try {
|
|
642
|
+
return validateTopicPath(raw, boundaryOnly);
|
|
643
|
+
}
|
|
644
|
+
catch (err) {
|
|
645
|
+
if (!manageFail(res, err))
|
|
646
|
+
throw err;
|
|
647
|
+
return null;
|
|
648
|
+
}
|
|
649
|
+
};
|
|
481
650
|
// 删除预览(dry-run):确认弹窗的文件清单必须来自这里,不许前端自己拼
|
|
482
651
|
if (sub === '/api/library/paper/delete-plan' && req.method === 'GET') {
|
|
483
652
|
const topic = url.searchParams.get('topic') ?? '';
|
|
@@ -512,11 +681,14 @@ export function registerRoutes(ctx, config) {
|
|
|
512
681
|
// 别名 = /api/library/paper/delete。词法门走 badEntry(topic) + badEntryBoundary(name)。
|
|
513
682
|
if ((sub === '/api/library/delete-paper' || sub === '/api/library/paper/delete') && req.method === 'POST') {
|
|
514
683
|
const body = (await readBody(req));
|
|
515
|
-
if (
|
|
684
|
+
if (badEntryBoundary(res, body.name))
|
|
516
685
|
return;
|
|
517
686
|
if (rejectWritePath(body, res))
|
|
518
687
|
return;
|
|
519
|
-
|
|
688
|
+
const topicPath = badTopicPath(res, body.topic, true);
|
|
689
|
+
if (topicPath === null)
|
|
690
|
+
return;
|
|
691
|
+
await withInflight(`paper\u0000${topicPath}\u0000${String(body.name ?? '')}`, res, async () => {
|
|
520
692
|
try {
|
|
521
693
|
const plan = planPaperDelete(dataDir, body.topic, body.name);
|
|
522
694
|
const ref = resolveLibraryPaper(plan.topic, plan.name);
|
|
@@ -542,11 +714,14 @@ export function registerRoutes(ctx, config) {
|
|
|
542
714
|
if ((sub === '/api/library/rename-paper' || sub === '/api/library/paper/rename') && req.method === 'POST') {
|
|
543
715
|
const body = (await readBody(req));
|
|
544
716
|
const rawTo = body.newName ?? body.to;
|
|
545
|
-
if (
|
|
717
|
+
if (badEntryBoundary(res, body.name) || badEntry(res, rawTo))
|
|
546
718
|
return;
|
|
547
719
|
if (rejectWritePath(body, res))
|
|
548
720
|
return;
|
|
549
|
-
|
|
721
|
+
const topicPath = badTopicPath(res, body.topic, true);
|
|
722
|
+
if (topicPath === null)
|
|
723
|
+
return;
|
|
724
|
+
await withInflight(`paper\u0000${topicPath}\u0000${String(body.name ?? '')}`, res, async () => {
|
|
550
725
|
try {
|
|
551
726
|
// 先校验名称/越界/存在(planPaperDelete 内部做全套检查)——不能先 resolvePaper:
|
|
552
727
|
// 非法名会在那里抛出非 ManageError 的普通错误,被外层记成 500。
|
|
@@ -582,7 +757,8 @@ export function registerRoutes(ctx, config) {
|
|
|
582
757
|
badEntry(res, rawName);
|
|
583
758
|
return;
|
|
584
759
|
}
|
|
585
|
-
|
|
760
|
+
const topicPath = badTopicPath(res, rawName, true);
|
|
761
|
+
if (topicPath === null)
|
|
586
762
|
return;
|
|
587
763
|
// 词法门两段式(4 条路由都必须在文件系统操作之前过 badEntry,见 upstream V12 的结构性断言):
|
|
588
764
|
// ① badEntry(上游 #4 的 validateEntryName)挡**类型 / 空值**——非字符串、空串在任何模式下都非法;
|
|
@@ -590,9 +766,9 @@ export function registerRoutes(ctx, config) {
|
|
|
590
766
|
// 走 badEntryBoundary(分层理由见其定义:历史遗留的不规范名必须能清掉,否则是删不掉的孤儿)。
|
|
591
767
|
if (rejectWritePath(body, res))
|
|
592
768
|
return;
|
|
593
|
-
await withInflight(`topic\u0000${
|
|
769
|
+
await withInflight(`topic\u0000${topicPath}`, res, async () => {
|
|
594
770
|
try {
|
|
595
|
-
const name =
|
|
771
|
+
const name = topicPath;
|
|
596
772
|
// confirmName 是**可选**栅栏:给了就必须一致(400 confirm-mismatch);没给也照走全部前置——
|
|
597
773
|
// 空专题免确认(上游 delete-topic {topic} 契约:没有数据可毁),非空专题一律
|
|
598
774
|
// 409 topic-not-empty(我们的加固,比上游「一点递归删光」保守,见 docs/reader-ux-requirements.md)。
|
|
@@ -619,7 +795,7 @@ export function registerRoutes(ctx, config) {
|
|
|
619
795
|
if (busy > 0)
|
|
620
796
|
throw new ManageError('translation-busy', 409, '该专题有正在生成译文的文献,请等待完成后再删除', {});
|
|
621
797
|
const r = deleteTopic(dataDir, plan.name);
|
|
622
|
-
|
|
798
|
+
dropWorkspaceCache(plan.name); // 清掉指向已删目录(含子树)的工作区缓存
|
|
623
799
|
json(res, 200, { ...r, archivedSessionsNote: true });
|
|
624
800
|
}
|
|
625
801
|
catch (err) {
|
|
@@ -638,15 +814,21 @@ export function registerRoutes(ctx, config) {
|
|
|
638
814
|
badEntry(res, rawName);
|
|
639
815
|
return;
|
|
640
816
|
}
|
|
641
|
-
// from 侧同 delete-topic
|
|
817
|
+
// from 侧同 delete-topic:先挡类型/空值,命名规范只在改名**目标**(to)上强制
|
|
642
818
|
// ——这样「历史遗留的怪名专题 → 改成规范名」这条路不被自己的校验堵死。
|
|
643
|
-
|
|
819
|
+
const topicPath = badTopicPath(res, rawName, true);
|
|
820
|
+
if (topicPath === null)
|
|
821
|
+
return;
|
|
822
|
+
// F4:`to` 是**路径**(`A/B`)——「移动到另一父」必须能走通。与 topic 创建/清空同一条门:
|
|
823
|
+
// 逐段命名规范类校验 + 深度/段长/总长上限 + 编码变形拒绝(绝不退回单段的 validateEntryName)。
|
|
824
|
+
const toPath = badTopicPath(res, rawTo, false);
|
|
825
|
+
if (toPath === null)
|
|
644
826
|
return;
|
|
645
827
|
if (rejectWritePath(body, res))
|
|
646
828
|
return;
|
|
647
|
-
await withInflight(`topic\u0000${
|
|
829
|
+
await withInflight(`topic\u0000${topicPath}`, res, async () => {
|
|
648
830
|
try {
|
|
649
|
-
const name =
|
|
831
|
+
const name = topicPath;
|
|
650
832
|
const plan = planTopicDelete(dataDir, name); // 复用同一个「存在且合法」校验
|
|
651
833
|
if (!(await requireTopicSessionsClear(plan.name, res)))
|
|
652
834
|
return;
|
|
@@ -665,8 +847,8 @@ export function registerRoutes(ctx, config) {
|
|
|
665
847
|
}
|
|
666
848
|
if (busy > 0)
|
|
667
849
|
throw new ManageError('translation-busy', 409, '该专题有正在生成译文的文献,请等待完成后再重命名', {});
|
|
668
|
-
const r = renameTopic(dataDir, plan.name,
|
|
669
|
-
|
|
850
|
+
const r = renameTopic(dataDir, plan.name, toPath);
|
|
851
|
+
dropWorkspaceCache(plan.name);
|
|
670
852
|
// 响应补 `topic`(上游 UI/文档读法)——我们的 RenameResult 用 from/to
|
|
671
853
|
json(res, 200, { ...r, topic: r.to, detachedSessions: detached });
|
|
672
854
|
}
|
|
@@ -681,20 +863,29 @@ export function registerRoutes(ctx, config) {
|
|
|
681
863
|
// 形状与 /api/library/paper/delete-plan 对齐(files/totalBytes/notDeleted),逐篇额外给
|
|
682
864
|
// sessions/translation,让 UI 在用户点确认**之前**就能提示「第 7 篇正在翻译」。
|
|
683
865
|
if (sub === '/api/library/topic/clear-plan' && req.method === 'GET') {
|
|
684
|
-
const
|
|
866
|
+
const rawTopic = url.searchParams.get('topic') ?? '';
|
|
685
867
|
if (url.searchParams.get('path')) {
|
|
686
868
|
json(res, 400, { error: '不接受 path 参数,请用 topic', code: 'escape-rejected' });
|
|
687
869
|
return;
|
|
688
870
|
}
|
|
871
|
+
// topic 类路由统一入参门(与 delete/rename/clear 同一条):逐段词法 + 编码变形 + 深度/长度上限
|
|
872
|
+
const topic = badTopicPath(res, rawTopic, true);
|
|
873
|
+
if (topic === null)
|
|
874
|
+
return;
|
|
689
875
|
try {
|
|
690
876
|
const plan = planTopicClear(dataDir, topic);
|
|
877
|
+
// D(评审 D2):确认框必须逐篇列出**整棵子树**的论文。旧实现只遍历根层 `plan.papers`
|
|
878
|
+
// ⇒ 子专题里的论文不在「将删除什么」清单里,而 `papersCount` 却包含子树(两个数字自相矛盾,
|
|
879
|
+
// 用户在确认框里根本看不到要删的子专题论文)。
|
|
880
|
+
const allPapers = flattenClearPapers(plan);
|
|
691
881
|
const papers = [];
|
|
692
|
-
for (const p of
|
|
693
|
-
const ref = resolveLibraryPaper(
|
|
882
|
+
for (const p of allPapers) {
|
|
883
|
+
const ref = resolveLibraryPaper(p.topic, p.name);
|
|
694
884
|
const sessions = await sessionInfo(ref);
|
|
695
885
|
const zh = zhStatus(ref);
|
|
696
886
|
papers.push({
|
|
697
887
|
name: p.name,
|
|
888
|
+
topic: p.topic,
|
|
698
889
|
files: p.files,
|
|
699
890
|
totalBytes: p.totalBytes,
|
|
700
891
|
sessions: toWire(sessions),
|
|
@@ -704,10 +895,13 @@ export function registerRoutes(ctx, config) {
|
|
|
704
895
|
json(res, 200, {
|
|
705
896
|
topic: plan.topic,
|
|
706
897
|
papers,
|
|
707
|
-
|
|
898
|
+
// 与清单严格一致(清单已含子树;两者相等,任一处漂移都会让确认框说谎)
|
|
899
|
+
papersCount: allPapers.length,
|
|
708
900
|
filesCount: plan.filesCount,
|
|
709
901
|
totalBytes: plan.totalBytes,
|
|
710
902
|
hidden: plan.hidden,
|
|
903
|
+
subtopics: plan.subtopics.map((s) => ({ topic: s.topic, papersCount: s.papersCount, filesCount: s.filesCount, totalBytes: s.totalBytes })),
|
|
904
|
+
subtopicsCount: plan.subtopics.length,
|
|
711
905
|
trashRoot: plan.trashRoot,
|
|
712
906
|
notDeleted: plan.notDeleted,
|
|
713
907
|
clearEndpoint: '/api/library/topic/clear',
|
|
@@ -730,35 +924,40 @@ export function registerRoutes(ctx, config) {
|
|
|
730
924
|
badEntry(res, rawTopic);
|
|
731
925
|
return;
|
|
732
926
|
}
|
|
733
|
-
|
|
927
|
+
const topicPath = badTopicPath(res, rawTopic, true);
|
|
928
|
+
if (topicPath === null)
|
|
734
929
|
return;
|
|
735
930
|
if (rejectWritePath(body, res))
|
|
736
931
|
return;
|
|
737
|
-
if (body.confirmName !==
|
|
932
|
+
if (typeof body.confirmName !== 'string' || body.confirmName.trim() !== topicPath) {
|
|
738
933
|
json(res, 400, { error: '需要 confirmName 与专题名完全一致才允许清空', code: 'confirm-mismatch' });
|
|
739
934
|
return;
|
|
740
935
|
}
|
|
741
|
-
await withInflight(`topic\u0000${
|
|
936
|
+
await withInflight(`topic\u0000${topicPath}`, res, async () => {
|
|
742
937
|
try {
|
|
743
|
-
const plan = planTopicClear(dataDir,
|
|
938
|
+
const plan = planTopicClear(dataDir, topicPath); // 存在性 404 / 越界 400 / 符号链接专题 400
|
|
744
939
|
if (plan.papersCount === 0) {
|
|
745
940
|
throw new ManageError('bad-request', 400, '专题已为空,请用删除专题', { clearEndpoint: '/api/library/delete-topic' });
|
|
746
941
|
}
|
|
747
942
|
let detached = 0;
|
|
748
943
|
const busyTrans = [];
|
|
749
|
-
|
|
750
|
-
|
|
944
|
+
// D(评审 D1):clearTopic 删的是**整棵子树**,占用巡检也必须遍历整棵子树。
|
|
945
|
+
// 旧实现只遍历根层 `plan.papers` ⇒ 子专题里有活跃会话/生成中译文的论文照删不误。
|
|
946
|
+
for (const p of flattenClearPapers(plan)) {
|
|
947
|
+
// 逐篇用**它自己的**专题路径定位(子树清空时根 topic 不再是每篇的父级)
|
|
948
|
+
const ref = resolveLibraryPaper(p.topic, p.name);
|
|
949
|
+
const label = p.topic === plan.topic ? p.name : `${p.topic}/${p.name}`;
|
|
751
950
|
if (!(await requireSessionClear(ref, res)))
|
|
752
951
|
return; // unknown→503 / running→409(同一套 code)
|
|
753
952
|
detached += (await sessionInfo(ref)).total;
|
|
754
953
|
if (zhStatus(ref).busy)
|
|
755
|
-
busyTrans.push(
|
|
954
|
+
busyTrans.push(label);
|
|
756
955
|
}
|
|
757
956
|
if (busyTrans.length > 0) {
|
|
758
957
|
throw new ManageError('translation-busy', 409, `以下文献正在生成译文,请等待完成后再清空:${busyTrans.join('、')}`, { papers: busyTrans });
|
|
759
958
|
}
|
|
760
959
|
const r = clearTopic(dataDir, plan.topic);
|
|
761
|
-
|
|
960
|
+
dropWorkspaceCache(plan.topic); // 清掉指向已清空目录(含子树)的工作区缓存
|
|
762
961
|
json(res, 200, { ...r, detachedSessions: detached, archivedSessionsNote: true });
|
|
763
962
|
}
|
|
764
963
|
catch (err) {
|
|
@@ -768,12 +967,141 @@ export function registerRoutes(ctx, config) {
|
|
|
768
967
|
});
|
|
769
968
|
return;
|
|
770
969
|
}
|
|
970
|
+
/* ── 布局迁移(旧平铺 → 按论文分文件夹):方案 §B1.2 的只读预检 + 显式执行 + 回滚 ──
|
|
971
|
+
铁律:默认**只读**;执行必须带 confirm=migrate-library(UI/CLI 先让人核对干跑报告);
|
|
972
|
+
回滚日志必须在我们的 migration-logs 目录内(不认任意路径,防被当成任意文件读写口)。 */
|
|
973
|
+
if (sub === '/api/library/migrate-plan' && req.method === 'GET') {
|
|
974
|
+
try {
|
|
975
|
+
const plan = planMigration(dataDir);
|
|
976
|
+
json(res, 200, { ok: true, plan, report: formatMigrationReport(plan) });
|
|
977
|
+
}
|
|
978
|
+
catch (err) {
|
|
979
|
+
if (!libFail(res, err))
|
|
980
|
+
throw err;
|
|
981
|
+
}
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
if (sub === '/api/library/migrate' && req.method === 'POST') {
|
|
985
|
+
const body = (await readBody(req));
|
|
986
|
+
if (body.confirm !== 'migrate-library') {
|
|
987
|
+
json(res, 400, { error: '需要 confirm=migrate-library 才允许执行迁移(请先 GET /api/library/migrate-plan 人工核对报告)', code: 'confirm-mismatch' });
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
await withInflight('migrate\u0000library', res, async () => {
|
|
991
|
+
try {
|
|
992
|
+
// E3(评审 E):迁移会搬动全库文件,与 delete/rename 同口径——对**在飞转录/译文**加 busy 门。
|
|
993
|
+
// 旧实现直接开跑:正在转录的临时产物会被当成论文产物复制/删除,正在翻译的论文也可能被搬走。
|
|
994
|
+
const transcribing = [...activeTranscribes].map((k) => k.split('\u0000').join('/'));
|
|
995
|
+
const translating = translationBusyPapers();
|
|
996
|
+
const busy = [...transcribing, ...translating];
|
|
997
|
+
if (busy.length > 0) {
|
|
998
|
+
throw new ManageError('busy', 409, `有文献正在转录/生成译文,请等待完成后再执行迁移:${busy.slice(0, 3).join('、')}${busy.length > 3 ? ' 等' : ''}`, { papers: busy });
|
|
999
|
+
}
|
|
1000
|
+
// E3:用异步执行体(每复制/删除一个文件让出事件循环),大库迁移期间 PDF 流 / SSE / 读接口仍可响应。
|
|
1001
|
+
const r = await runMigrationAsync(dataDir);
|
|
1002
|
+
json(res, 200, r);
|
|
1003
|
+
}
|
|
1004
|
+
catch (err) {
|
|
1005
|
+
if (err instanceof MigrationAborted) {
|
|
1006
|
+
json(res, 409, { ...err.detail, error: err.message, code: err.code });
|
|
1007
|
+
return;
|
|
1008
|
+
}
|
|
1009
|
+
if (err instanceof MigrationError) {
|
|
1010
|
+
json(res, 409, { error: err.message, code: err.code });
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (!libFail(res, err))
|
|
1014
|
+
throw err;
|
|
1015
|
+
}
|
|
1016
|
+
});
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
if (sub === '/api/library/migrate-rollback' && req.method === 'POST') {
|
|
1020
|
+
const body = (await readBody(req));
|
|
1021
|
+
if (body.confirm !== 'rollback-library') {
|
|
1022
|
+
json(res, 400, { error: '需要 confirm=rollback-library 才允许回滚', code: 'confirm-mismatch' });
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
const logDir = migrationLogDir();
|
|
1026
|
+
const logPath = body.logPath?.trim() || lastMigrationLog();
|
|
1027
|
+
if (!logPath) {
|
|
1028
|
+
json(res, 400, { error: '没有可用的迁移日志(请在 body 里给 logPath)', code: 'bad-request' });
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
// G(评审 G 次级):旧判断用裸 `startsWith`(没有路径分隔符)——`<logDir>-evil/x.jsonl` 会被
|
|
1032
|
+
// `<logDir>` 前缀误判通过(`/a/bc` 冒充 `/a/b` 的子路径)。用 relative 判定:必须在目录**内部**。
|
|
1033
|
+
const relLog = relative(resolve(logDir), resolve(logPath));
|
|
1034
|
+
if (!relLog || relLog === '..' || relLog.startsWith('..' + sep) || isAbsolute(relLog)) {
|
|
1035
|
+
json(res, 400, { error: 'logPath 必须是迁移日志目录内的文件', code: 'escape-rejected' });
|
|
1036
|
+
return;
|
|
1037
|
+
}
|
|
1038
|
+
await withInflight('migrate\u0000library', res, async () => {
|
|
1039
|
+
try {
|
|
1040
|
+
const r = rollbackMigration(dataDir, logPath);
|
|
1041
|
+
json(res, 200, r);
|
|
1042
|
+
}
|
|
1043
|
+
catch (err) {
|
|
1044
|
+
// E1:坏行/不可读日志是 MigrationError(带 migrate-log-* 机器码)。必须**如实**回答,
|
|
1045
|
+
// 不能落到 fsError 的「系统错误,请稍后重试」把行号/原因吞掉(那又成了「假成功」的变体)。
|
|
1046
|
+
if (err instanceof MigrationError) {
|
|
1047
|
+
json(res, 409, { error: err.message, code: err.code });
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
if (!libFail(res, err))
|
|
1051
|
+
throw err;
|
|
1052
|
+
}
|
|
1053
|
+
});
|
|
1054
|
+
return;
|
|
1055
|
+
}
|
|
771
1056
|
// 公式索引:MinerU content_list 的 equation 块(LaTeX + bbox),供阅读器画热区/列表面板
|
|
772
1057
|
if (sub === '/api/formulas' && req.method === 'GET') {
|
|
773
1058
|
const ref = locate(url); // 只读路径,沿用 path/topic/name 三种定位
|
|
774
1059
|
json(res, 200, await readFormulaIndex(ref));
|
|
775
1060
|
return;
|
|
776
1061
|
}
|
|
1062
|
+
/* ── 笔记(每篇一个 <论文>.notes.json,与 .txt/.study.json 同目录)──────────────
|
|
1063
|
+
读只读、写要过写路径边界;笔记是用户数据,格式错误只回 400 + 可读中文文案。
|
|
1064
|
+
笔记文件不存在 → 返回空列表(而不是 404):新论文天然没有笔记,阅读器不必特判。 */
|
|
1065
|
+
if (sub === '/api/notes' && req.method === 'GET') {
|
|
1066
|
+
// 笔记只认 topic + name(与写路由同一口径):不接受 path 直指任意文件,
|
|
1067
|
+
// 否则用户数据可以被一个 URL 参数带到库外。其余读路由的 404 语义保持不变。
|
|
1068
|
+
const u = new URL(url);
|
|
1069
|
+
u.searchParams.delete('path');
|
|
1070
|
+
const ref = locate(u);
|
|
1071
|
+
json(res, 200, await readNotes(ref.pdfPath));
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
1074
|
+
if (sub === '/api/notes' && req.method === 'POST') {
|
|
1075
|
+
const rawBody = await readBody(req);
|
|
1076
|
+
if (!(typeof rawBody === 'object' && rawBody !== null)) {
|
|
1077
|
+
json(res, 400, { error: '非法请求体', code: 'bad-request' });
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
const body = rawBody;
|
|
1081
|
+
try {
|
|
1082
|
+
if (typeof body.topic !== 'string' || !body.topic || typeof body.name !== 'string' || !body.name) {
|
|
1083
|
+
json(res, 400, { error: '缺少 topic / name', code: 'bad-request' });
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
// 写路径只认 topic + name:显式拒绝 path(与删除/重命名路由同一形态)
|
|
1087
|
+
if (rejectWritePath(body, res))
|
|
1088
|
+
return;
|
|
1089
|
+
const ref = locateForWrite({ topic: body.topic, name: body.name });
|
|
1090
|
+
const file = body.action === 'delete'
|
|
1091
|
+
? await deleteNote(ref.pdfPath, body.id)
|
|
1092
|
+
: await upsertNote(ref.pdfPath, body.note);
|
|
1093
|
+
json(res, 200, file);
|
|
1094
|
+
}
|
|
1095
|
+
catch (err) {
|
|
1096
|
+
if (isNoteError(err)) {
|
|
1097
|
+
json(res, 400, { error: err.message, code: err.code });
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
if (!manageFail(res, err))
|
|
1101
|
+
throw err;
|
|
1102
|
+
}
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
777
1105
|
/* ── 划词翻译(公式保留,契约 docs/selection-translate-requirements.md §3.9)─────
|
|
778
1106
|
客户端只送「按页 + 按 display 归属切好的 chunk」;行内公式的还原(选区文本 ↔ MinerU
|
|
779
1107
|
text 块对齐)在服务端做,所以请求体里**没有任何矩形/bbox/pageSize**。
|
|
@@ -843,8 +1171,12 @@ export function registerRoutes(ctx, config) {
|
|
|
843
1171
|
}
|
|
844
1172
|
const index = await readTextBlockIndex(ref);
|
|
845
1173
|
const asm = assembleSource(chunks, index);
|
|
1174
|
+
// OpenCode Go:同一篇论文的划词翻译共用一个稳定会话 ID(与整篇译文同一 scope)
|
|
1175
|
+
const ocSession = isOpenCodeEndpoint(endpoint.baseUrl)
|
|
1176
|
+
? await openCodeSessionId(`paper:${ref.topic}/${ref.name}`)
|
|
1177
|
+
: '';
|
|
846
1178
|
try {
|
|
847
|
-
const r = await translateSelection(endpoint, asm.source);
|
|
1179
|
+
const r = await translateSelection(endpoint, asm.source, ocSession ? { openCodeSessionId: ocSession } : {});
|
|
848
1180
|
json(res, 200, {
|
|
849
1181
|
translation: r.translation,
|
|
850
1182
|
model: r.model,
|
|
@@ -1072,6 +1404,34 @@ export function registerRoutes(ctx, config) {
|
|
|
1072
1404
|
json(res, 200, { ok: true });
|
|
1073
1405
|
return;
|
|
1074
1406
|
}
|
|
1407
|
+
/* ── 阅读器深色模式配置(方案 §A2.3):设置面板卡片与阅读器 ⚙ 浮层**共用同一个后端配置** ──
|
|
1408
|
+
无密钥 ⇒ GET 直接回生效值 + 实测曲线(前端据此算 CSS 变量);POST 严格校验后落盘;
|
|
1409
|
+
DELETE 回落默认(follow)。 */
|
|
1410
|
+
if (sub === '/api/theme/config' && req.method === 'GET') {
|
|
1411
|
+
const cfg = await readThemeConfig();
|
|
1412
|
+
json(res, 200, { ...themePayload(cfg), source: 'file' });
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
if (sub === '/api/theme/config' && req.method === 'POST') {
|
|
1416
|
+
const body = (await readBody(req));
|
|
1417
|
+
let next;
|
|
1418
|
+
try {
|
|
1419
|
+
const prev = await readThemeConfig();
|
|
1420
|
+
next = validateThemePatch({ ...prev, ...body });
|
|
1421
|
+
}
|
|
1422
|
+
catch (err) {
|
|
1423
|
+
json(res, 400, { error: err instanceof Error ? err.message : '配置非法', code: 'bad-request' });
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1426
|
+
await writeThemeConfig(next);
|
|
1427
|
+
json(res, 200, { ok: true, ...themePayload(next) });
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
if (sub === '/api/theme/config' && req.method === 'DELETE') {
|
|
1431
|
+
await clearThemeConfig();
|
|
1432
|
+
json(res, 200, { ok: true, ...themePayload(await readThemeConfig()) });
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1075
1435
|
// ── 嵌入模型端点配置(设置面板第三张端点卡片)─────────────────────────
|
|
1076
1436
|
// 与 translate/typesafe 完全同一套约定:GET 只回掩码 key;POST 预检通过才落盘;DELETE 回落。
|
|
1077
1437
|
if (sub === '/api/embed/config' && req.method === 'GET') {
|
|
@@ -1253,7 +1613,17 @@ export function registerRoutes(ctx, config) {
|
|
|
1253
1613
|
}
|
|
1254
1614
|
const mineru = await resolveMineruConfig(config.mineru);
|
|
1255
1615
|
const source = MINERU_SOURCES.has(body.source ?? 'auto') ? body.source : 'auto';
|
|
1256
|
-
|
|
1616
|
+
// E3:登记在飞转录 —— /migrate 会据此 409(与 delete/rename 的 busy 门同口径),
|
|
1617
|
+
// 否则迁移可能复制/清理正在写的 `.tmp-*` 或半成品缓存。
|
|
1618
|
+
const transcribeKey = `${ref.topic}\u0000${ref.name}`;
|
|
1619
|
+
activeTranscribes.add(transcribeKey);
|
|
1620
|
+
let t;
|
|
1621
|
+
try {
|
|
1622
|
+
t = await transcribePaper(ref, { force: body.force === true, source, mineru });
|
|
1623
|
+
}
|
|
1624
|
+
finally {
|
|
1625
|
+
activeTranscribes.delete(transcribeKey);
|
|
1626
|
+
}
|
|
1257
1627
|
json(res, 200, { chars: t.chars, pageCount: t.pageCount, hasPageIndex: t.pages.length > 0, source: t.source, producer: t.producer, backend: t.backend });
|
|
1258
1628
|
return;
|
|
1259
1629
|
}
|
|
@@ -1330,6 +1700,41 @@ export function registerRoutes(ctx, config) {
|
|
|
1330
1700
|
await createPaperSession(sessionId, ref.topic);
|
|
1331
1701
|
}
|
|
1332
1702
|
catch { /* 已存在则复用 */ }
|
|
1703
|
+
// ── 范围(方案 §B3.1):缺省/无效一律按「当前论文」;给了非法结构则显式 400 ──
|
|
1704
|
+
let scope = null;
|
|
1705
|
+
if (body.scope !== undefined && body.scope !== null) {
|
|
1706
|
+
const raw = body.scope;
|
|
1707
|
+
if (typeof raw !== 'object') {
|
|
1708
|
+
json(res, 400, { error: 'scope 必须是对象', code: 'bad-request' });
|
|
1709
|
+
return;
|
|
1710
|
+
}
|
|
1711
|
+
if (raw.kind === 'paper') {
|
|
1712
|
+
const args = {};
|
|
1713
|
+
if (raw.topic !== undefined)
|
|
1714
|
+
args.topic = raw.topic;
|
|
1715
|
+
if (raw.name !== undefined)
|
|
1716
|
+
args.name = raw.name;
|
|
1717
|
+
if (body.topic === undefined && args.topic === undefined && args.name === undefined) {
|
|
1718
|
+
json(res, 400, { error: 'scope.kind=paper 需要 topic/name(或省略 scope 用当前论文)', code: 'bad-request' });
|
|
1719
|
+
return;
|
|
1720
|
+
}
|
|
1721
|
+
scope = { kind: 'paper', ...args };
|
|
1722
|
+
}
|
|
1723
|
+
else if (raw.kind === 'topic') {
|
|
1724
|
+
try {
|
|
1725
|
+
scope = { kind: 'topic', topic: validateTopicPath(raw.topic, false) };
|
|
1726
|
+
}
|
|
1727
|
+
catch (err) {
|
|
1728
|
+
if (!manageFail(res, err))
|
|
1729
|
+
throw err;
|
|
1730
|
+
return;
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
else {
|
|
1734
|
+
json(res, 400, { error: "scope.kind 只能是 'paper' 或 'topic'", code: 'bad-request' });
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1333
1738
|
const hasQuote = typeof body.selectedText === 'string' && body.selectedText.trim() !== '';
|
|
1334
1739
|
// 公式引用(kind='equation'):引用内容来自 MinerU 的 LaTeX,不是文本层乱码(契约 §1.3);
|
|
1335
1740
|
// 非公式路径的文案必须与改造前逐字一致(回归项 A11)。
|
|
@@ -1343,6 +1748,35 @@ export function registerRoutes(ctx, config) {
|
|
|
1343
1748
|
? `用户在阅读器里引用了${body.page ? `第 ${body.page} 页的` : ''}一个公式(LaTeX 源,来自 MinerU 版面解析):`
|
|
1344
1749
|
: `用户在阅读器里选中了一段文字${where}:`, `"""${body.selectedText.trim()}"""`);
|
|
1345
1750
|
}
|
|
1751
|
+
// 范围块:**追加**(不传 scope 时这段完全不存在 ⇒ 既有文案逐字不变,回归项 C2)
|
|
1752
|
+
let scopeInfo = null;
|
|
1753
|
+
if (scope) {
|
|
1754
|
+
try {
|
|
1755
|
+
const ctx = buildScopeContext(dataDir, ref, scope, body.question);
|
|
1756
|
+
lines.push(ctx.block);
|
|
1757
|
+
if (scopeBusy(ctx.scopePath)) {
|
|
1758
|
+
lines.push(`(提示:该范围内的目录正在被修改,本次只给了 ${ctx.papers.length - ctx.omitted} 篇)`);
|
|
1759
|
+
}
|
|
1760
|
+
scopeInfo = {
|
|
1761
|
+
kind: scope.kind,
|
|
1762
|
+
path: ctx.scopePath,
|
|
1763
|
+
papers: ctx.papers.length - ctx.omitted,
|
|
1764
|
+
omitted: ctx.omitted,
|
|
1765
|
+
truncated: ctx.truncated,
|
|
1766
|
+
chars: ctx.totalChars,
|
|
1767
|
+
coverage: ctx.papers.map((p) => ({ path: p.path, coverage: p.coverage })),
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
catch (err) {
|
|
1771
|
+
if (isManageError(err)) {
|
|
1772
|
+
libFail(res, err);
|
|
1773
|
+
return;
|
|
1774
|
+
}
|
|
1775
|
+
// 读路径 fail-soft:范围装配失败不阻断提问,降级成「只说范围、不给内容」并如实标注
|
|
1776
|
+
lines.push(`【提问范围】${scope.kind === 'topic' ? scope.topic : '当前论文'}(范围内容装配失败,已在无范围内容的情况下提问)`);
|
|
1777
|
+
scopeInfo = { kind: scope.kind, path: scope.kind === 'topic' ? scope.topic : `${ref.topic}/${ref.name}`, degraded: true };
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1346
1780
|
lines.push(`用户的问题:${body.question}`);
|
|
1347
1781
|
const prompt = lines.join('\n');
|
|
1348
1782
|
await sc.prompt({
|
|
@@ -1350,7 +1784,7 @@ export function registerRoutes(ctx, config) {
|
|
|
1350
1784
|
content: [{ type: 'text', text: prompt }],
|
|
1351
1785
|
requestId: randomUUID(),
|
|
1352
1786
|
}, AbortSignal.timeout(30_000));
|
|
1353
|
-
json(res, 200, { ok: true, sessionId, n });
|
|
1787
|
+
json(res, 200, { ok: true, sessionId, n, ...(scopeInfo ? { scope: scopeInfo } : {}) });
|
|
1354
1788
|
return;
|
|
1355
1789
|
}
|
|
1356
1790
|
json(res, 404, { error: 'not found: ' + url.pathname });
|