@li-canghai/dsh-paper 0.0.0-stage → 0.8.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.
Files changed (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -2
  3. package/cordis.patch.yml +4 -0
  4. package/lib/annotate-tool.js +334 -0
  5. package/lib/arxiv-id.js +74 -0
  6. package/lib/asset-routes.js +210 -0
  7. package/lib/bibliography-formats.js +126 -0
  8. package/lib/bibliography-import.js +105 -0
  9. package/lib/bibliography-service.js +43 -0
  10. package/lib/bibliography.js +42 -0
  11. package/lib/block-authors.js +292 -0
  12. package/lib/block-cache.js +39 -0
  13. package/lib/blocks-markdown.js +157 -0
  14. package/lib/blocks-reconcile.js +218 -0
  15. package/lib/blocks.js +1344 -0
  16. package/lib/citation-metadata.js +260 -0
  17. package/lib/citation-styles.js +120 -0
  18. package/lib/client-parts/01-pure-helpers.js +2762 -0
  19. package/lib/client-parts/02-author-year.js +95 -0
  20. package/lib/client.js +10381 -0
  21. package/lib/code-source.js +68 -0
  22. package/lib/concurrency-gate.js +91 -0
  23. package/lib/context.js +233 -0
  24. package/lib/csl/SOURCES.md +10 -0
  25. package/lib/csl/gb-t-7714.csl +441 -0
  26. package/lib/csl/ieee.csl +520 -0
  27. package/lib/csl/locales-zh-CN.xml +438 -0
  28. package/lib/csl/nature.csl +190 -0
  29. package/lib/discussion.js +400 -0
  30. package/lib/documents.js +67 -0
  31. package/lib/export.js +848 -0
  32. package/lib/file-lock.js +177 -0
  33. package/lib/gloss.js +181 -0
  34. package/lib/glossary.js +279 -0
  35. package/lib/index.js +3862 -0
  36. package/lib/inline-html.js +53 -0
  37. package/lib/install-dependency.js +120 -0
  38. package/lib/item-ops.js +83 -0
  39. package/lib/job-facade.js +58 -0
  40. package/lib/json-store.js +54 -0
  41. package/lib/library-model.js +132 -0
  42. package/lib/library-service.js +180 -0
  43. package/lib/library-tool.js +982 -0
  44. package/lib/library.js +814 -0
  45. package/lib/markdown-assets.js +138 -0
  46. package/lib/markdown-literals.js +93 -0
  47. package/lib/metadata-enrichment.js +516 -0
  48. package/lib/metadata-fetch.js +146 -0
  49. package/lib/metadata-node.js +158 -0
  50. package/lib/metadata-proxy.ps1 +35 -0
  51. package/lib/mineru-config.js +95 -0
  52. package/lib/mineru-sdk-helper.py +123 -0
  53. package/lib/mineru-sdk.js +182 -0
  54. package/lib/mineru.js +268 -0
  55. package/lib/mirror-export.js +240 -0
  56. package/lib/outline.js +296 -0
  57. package/lib/page-image-helper.py +308 -0
  58. package/lib/page-image.js +454 -0
  59. package/lib/paper-metadata.js +242 -0
  60. package/lib/parse-export.js +631 -0
  61. package/lib/pdf-analysis-tool.js +750 -0
  62. package/lib/pdf-metadata-helper.py +75 -0
  63. package/lib/pdf-metadata.js +141 -0
  64. package/lib/pdf-page.js +261 -0
  65. package/lib/pdf-scan.js +134 -0
  66. package/lib/pdf-text.js +68 -0
  67. package/lib/picker.js +305 -0
  68. package/lib/portable.js +379 -0
  69. package/lib/purge.js +170 -0
  70. package/lib/read-tool.js +660 -0
  71. package/lib/reader-store.js +497 -0
  72. package/lib/reading-order.js +207 -0
  73. package/lib/rename-document.js +480 -0
  74. package/lib/rename.js +372 -0
  75. package/lib/renderer-status.js +161 -0
  76. package/lib/resolver.js +1152 -0
  77. package/lib/result-archive.js +157 -0
  78. package/lib/revisions.js +330 -0
  79. package/lib/search-database.js +62 -0
  80. package/lib/search-index.js +601 -0
  81. package/lib/search-scan.js +185 -0
  82. package/lib/search-source.js +23 -0
  83. package/lib/search-terms.js +539 -0
  84. package/lib/section-audit.js +209 -0
  85. package/lib/selection-message.js +332 -0
  86. package/lib/serial-tail.js +21 -0
  87. package/lib/slicing.js +425 -0
  88. package/lib/source-resolver.js +581 -0
  89. package/lib/stem-repair.js +189 -0
  90. package/lib/storage.js +562 -0
  91. package/lib/store-paths.js +253 -0
  92. package/lib/table-gfm.js +236 -0
  93. package/lib/tasks.js +270 -0
  94. package/lib/tex-align.js +509 -0
  95. package/lib/tex-blocks.js +653 -0
  96. package/lib/tex-fetch.js +455 -0
  97. package/lib/tex-figures.js +140 -0
  98. package/lib/tex-inline.js +166 -0
  99. package/lib/tex-merge.js +279 -0
  100. package/lib/tex-pipeline.js +242 -0
  101. package/lib/tex-prepare.js +746 -0
  102. package/lib/tex-tables.js +210 -0
  103. package/lib/text-similarity.js +85 -0
  104. package/lib/tool-contract.js +86 -0
  105. package/lib/tool-host.js +1058 -0
  106. package/lib/tool-identity.js +214 -0
  107. package/lib/translatable-text.js +48 -0
  108. package/lib/translate-prompts.js +709 -0
  109. package/lib/translate-queue.js +418 -0
  110. package/lib/translate-task.js +158 -0
  111. package/lib/translate.js +909 -0
  112. package/lib/update-check.js +438 -0
  113. package/lib/update-contracts.js +75 -0
  114. package/lib/usage.js +282 -0
  115. package/package.json +55 -4
package/lib/index.js ADDED
@@ -0,0 +1,3862 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
4
+ import { homedir } from 'node:os'
5
+ import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path'
6
+ import { visibleHeadingIndexes } from './blocks.js'
7
+ import { normalizeBlockId } from './slicing.js'
8
+ import { buildContextMessage, deliveredPaperState, isProducerSource } from './context.js'
9
+ import { comparablePath, scanPdfFolder, scanRiskOf } from './pdf-scan.js'
10
+ import { pickFolder, pickPdfFiles } from './picker.js'
11
+ import { inspectPdf } from './documents.js'
12
+ import { documentPaths, hydrateDocument, readDocumentManifest } from './portable.js'
13
+ import { createDocumentReader } from './revisions.js'
14
+ import { PaperResolver, RETRYABLE_JOB_STATUSES } from './resolver.js'
15
+ import { mineruSdkConfig, parseWithConfiguredMineruSdk } from './mineru-sdk.js'
16
+ import { isWithin, mirrorParseResult } from './mirror-export.js'
17
+ import { normalizeCanvas, renderPageImages } from './page-image.js'
18
+ import { cropPdfGroups, pdfPageGroups, readPdfPage } from './pdf-page.js'
19
+ import { probeRenderer } from './renderer-status.js'
20
+ import { installDependency } from './install-dependency.js'
21
+ import { createUpdateService } from './update-check.js'
22
+ import { createAssetRoutes } from './asset-routes.js'
23
+ import { createTranslateQueue } from './translate-queue.js'
24
+ import { createConcurrencyGate } from './concurrency-gate.js'
25
+ import { mergeUsage, readUsage, summarizeUsage, usagePathOf, writeUsage } from './usage.js'
26
+ import { planTranslation, translateDocumentToDisk, translationPathOf } from './translate-task.js'
27
+ import { pendingForIncremental, readTranslation, sourceHashOf } from './translate.js'
28
+ import { MAX_MINERU_KEY_LENGTH, maskMineruKey, mineruKeyPath, readMineruKey, readMineruKeySync, writeMineruKey } from './mineru-config.js'
29
+ import { attachDocument, attachedDocumentIds, DEFAULT_SETTINGS, jobKindOf, PaperRepository, pruneStaleSelections, sessionDocumentIds, TRANSLATION_PROTOCOLS, TRANSLATION_SCOPES } from './storage.js'
30
+ import { plainInlineText } from './inline-html.js'
31
+ import { documentReferenceOf, titleFromBlocks, TRANSLATION_LANGUAGES } from './translate-prompts.js'
32
+ import { glossUsageKey, translateSelection } from './gloss.js'
33
+ import { buildGlossaryBlock, emptyGlossary, glossaryPathOf, MAX_GLOSSARY_ENTRIES, readGlossary, readGlossaryForWrite, removeEntry, upsertEntry, writeGlossary } from './glossary.js'
34
+ import { makeMark, readReaderStore, readReaderStoreForWrite, readerPathOf, READER_COLORS, resolveMarks, summarizeNotes, writeReaderStore } from './reader-store.js'
35
+ import { answerThread, appendThread, buildQuestionMessage, deleteThread, discussionPathOf, readDiscussion, readDiscussionForWrite, resolveThreads, writeDiscussion } from './discussion.js'
36
+ import { createBlockReader } from './block-cache.js'
37
+ import { createSerialTail } from './serial-tail.js'
38
+ import { effectiveMetadata, enrichMetadata } from './paper-metadata.js'
39
+ import { createMetadataResolver } from './metadata-enrichment.js'
40
+ import { paperOutput, publicPaperTool } from './tool-contract.js'
41
+ import { MAX_STEM_CHARS } from './rename.js'
42
+ import { buildMetadataConflictMessage, buildSelectionMessage } from './selection-message.js'
43
+ import { canPurge, DEFAULT_SORT, itemPathOf, libraryPathOf, MAX_CATEGORIES, moveCategory, normalizeItem, readItem, readLibrary, READ_STATUSES, removeCategory, renameCategory, setCategoryHidden, setCategoryPinned, setTrashed, setViewHidden, setViewPinned, SORT_MODES, upsertCategory, VIEW_KEYS, writeItem, writeLibrary } from './library.js'
44
+ import { purgeDocument } from './purge.js'
45
+ import { readPdfMetadata } from './pdf-metadata.js'
46
+ import { bibliographyOf } from './bibliography.js'
47
+ import { createLibraryService } from './library-service.js'
48
+ import { renameAfterParse, renameDocument } from './rename-document.js'
49
+ import { pageImageCacheRoot } from './store-paths.js'
50
+ import { resolvePdfSource } from './source-resolver.js'
51
+ import { createParseExport } from './parse-export.js'
52
+ import { createTaskStore } from './tasks.js'
53
+ import { createJobFacade } from './job-facade.js'
54
+ import { createPdfAnalysisTool } from './pdf-analysis-tool.js'
55
+ import { createAnnotateTool } from './annotate-tool.js'
56
+ import { createLibraryTool } from './library-tool.js'
57
+ import { createReadTool } from './read-tool.js'
58
+ import { identifyDocument, identityRecordOf } from './tool-identity.js'
59
+ import { applyItemAction } from './item-ops.js'
60
+ import { createToolHost } from './tool-host.js'
61
+ import { createBibliographyService } from './bibliography-service.js'
62
+
63
+ export { pruneStaleSelections }
64
+
65
+ /**
66
+ * 插件内部标识。**不要跟着 npm 包名改。**
67
+ *
68
+ * 🔴 它是 `runtimeRoot()` 的末段:数据落在 `$DSH_HOME/runtime/<这个值>/`。npm 包名是
69
+ * `@li-canghai/dsh-paper`,而这个值保持 `dsh-paper` —— 改了它,插件就会去读一个不存在的新目录,
70
+ * 用户既有的文献库、划线、译文、MinerU Key 全部`看不见`(旧目录还在,但没有任何代码去读)。
71
+ * Cordis 只把它当 fiber 诊断与 logger 名用(`Plugin.name` 的注释),不参与模块解析,
72
+ * 所以与包名不一致是合法的;已发布的 `dsh-archived-conversation` 就是同一种拆法。
73
+ */
74
+ export const name = 'dsh-paper'
75
+ export const inject = ['sessionPersistence']
76
+ export const API_BASE = '/api/dsh-paper'
77
+ /** /usage 的明细条数上限:面板只画最近几条,全量返回会让批量翻译回一份几千条的 JSON。 */
78
+ const MAX_USAGE_RECORDS = 50
79
+ /** 单张导出图片的字节上限:一张几 MB 的原页图内联进 HTML 会让产物大到打不开。 */
80
+ const MAX_EXPORT_ASSET_BYTES = 2 * 1024 * 1024
81
+ /** 单篇导出最多内联几页原页图。50 页的论文全内联能到十几 MB,这里按页序取前若干页。 */
82
+ const MAX_EXPORT_PAGES = 12
83
+ /** 导出的原页图取 UI 那一档宽度(与阅读器同一渲染链,见 D49)。 */
84
+ const DEFAULT_PAGE_WIDTH = 1200
85
+
86
+ /** 扩展名 → MIME。导出内联用;认不出的一律当二进制流(浏览器仍会按内容嗅探)。 */
87
+ const EXPORT_IMAGE_TYPES = new Map([
88
+ ['.png', 'image/png'], ['.jpg', 'image/jpeg'], ['.jpeg', 'image/jpeg'],
89
+ ['.gif', 'image/gif'], ['.webp', 'image/webp'], ['.bmp', 'image/bmp'], ['.svg', 'image/svg+xml'],
90
+ ])
91
+
92
+ function mimeOfPath(path) {
93
+ return EXPORT_IMAGE_TYPES.get(extname(path).toLowerCase()) ?? 'application/octet-stream'
94
+ }
95
+
96
+ function runtimeRoot(config = {}) {
97
+ if (typeof config.runtimeDir === 'string' && config.runtimeDir !== '') return config.runtimeDir
98
+ const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
99
+ return join(dshHome, 'runtime', name)
100
+ }
101
+
102
+ function json(value, status = 200) {
103
+ return new Response(JSON.stringify(value), {
104
+ status,
105
+ headers: { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
106
+ })
107
+ }
108
+
109
+ function errorText(error) {
110
+ return String(error?.message ?? error).slice(0, 500)
111
+ }
112
+
113
+ /**
114
+ * 「整篇一块都没译出来」时的任务错误文案。
115
+ *
116
+ * 🔴 必须带**模型路由**与**块级的真实原因**。只说一句「翻译失败」,用户能做的只有再点一次
117
+ * 同一个按钮;而看到「模型 minimax-code/X 没有返回任何文本」时,他知道该换模型。
118
+ * 原因取自块上那条 error(translate.js 的批次失败文案 + 模型原始回复摘要)。
119
+ *
120
+ * @param {{stats?: object, blocks?: object[]}} outcome translateDocumentToDisk 的产物。
121
+ * @param {{model?: {provider?: string, model?: string}}} [batch] 本次入队的批次。
122
+ * @returns {string}
123
+ */
124
+ export function translationFailureText(outcome, batch = {}) {
125
+ const stats = outcome?.stats ?? {}
126
+ const blocks = Array.isArray(outcome?.blocks) ? outcome.blocks : []
127
+ const failed = Number.isInteger(stats.failed) ? stats.failed : blocks.filter(block => block?.status === 'failed').length
128
+ const route = typeof batch?.model?.provider === 'string' && typeof batch?.model?.model === 'string'
129
+ ? `${batch.model.provider}/${batch.model.model}`
130
+ : '未指定模型'
131
+ const first = blocks.find(block => block?.status === 'failed' && typeof block?.error === 'string' && block.error !== '')
132
+ const head = `${failed} 个块全部翻译失败(模型 ${route})`
133
+ return first === undefined ? head : `${head}:${first.error}`
134
+ }
135
+
136
+ // 侧栏进度条口径:同一个文档会留下多条任务记录(重试把旧记录标成 retried,再建一条
137
+ // queued),所以只按 createdAt 取每个文档最新的一条来算。status 之外的取值(interrupted /
138
+ // retried)一律计入 blocked,由"全部重试"处理。
139
+ // readyDocumentIds 用来兜住批量导入的另一个坑:compact 会把终态任务裁到 MAX_TERMINAL_JOBS,
140
+ // 几百篇里先完成的那批已经没有任务记录可数,只按 jobs 算就会把"共 N"算少、百分比虚高。
141
+ // 会话仍关联且存在论文记录(解析完成才会产生)的,就按已完成补一条;已有任务记录的文档不重复计。
142
+ //
143
+ // kind 是后加的过滤维度,默认值让老调用点的口径一字不变。解析与翻译任务共用一个 documentId
144
+ // 命名空间,不过滤就会把翻译任务的 running 算进解析进度条——而两类任务的并发位是分开的,
145
+ // 数字叠加后两边都对不上。⚠️ readyDocumentIds 是解析侧的兜底(有论文记录即已完成),只在
146
+ // kind === "parse" 时展开;翻译任务另算,由调用方自己准备那一侧的兜底集合。
147
+ export function summarizeProgress(jobs = [], { readyDocumentIds = [], kind = 'parse' } = {}) {
148
+ const newest = new Map()
149
+ for (const job of [...jobs]
150
+ .filter(job => jobKindOf(job) === kind)
151
+ .sort((left, right) => String(right.createdAt ?? '').localeCompare(String(left.createdAt ?? '')))) {
152
+ const key = job.documentId ?? job.id
153
+ if (!newest.has(key)) newest.set(key, job)
154
+ }
155
+ if (kind === 'parse') {
156
+ for (const documentId of readyDocumentIds) {
157
+ if (!newest.has(documentId)) newest.set(documentId, { status: 'ready' })
158
+ }
159
+ }
160
+ const counts = { finished: 0, running: 0, pending: 0, blocked: 0 }
161
+ for (const job of newest.values()) {
162
+ if (job.status === 'ready') counts.finished += 1
163
+ else if (job.status === 'running') counts.running += 1
164
+ else if (job.status === 'queued') counts.pending += 1
165
+ else counts.blocked += 1
166
+ }
167
+ const total = newest.size
168
+ return { total, ...counts, percent: total === 0 ? 0 : Math.round((counts.finished / total) * 100) }
169
+ }
170
+
171
+ function validId(value) {
172
+ return typeof value === 'string' && value.length > 0 && value.length <= 256 && /^[A-Za-z0-9._:-]+$/.test(value)
173
+ }
174
+
175
+ const SELECTION_SWEEP_MIN_INTERVAL_MS = 10 * 60 * 1000
176
+ // 右栏「解析」Tab 一次能加多少篇:与批量注入同一个量级,再大就该分批点。
177
+ const MAX_PARSE_ADD = 500
178
+ // 批量重试(MCP 一样按量计费):一个文档只重排最新的一次,且限制单次请求的规模。
179
+ // 可重排的终态取自 resolver.js 的 RETRYABLE_JOB_STATUSES,与 retry() 的接受面同源。
180
+ const MAX_BATCH_RETRY = 200
181
+ const BATCH_RETRY_CONCURRENCY = 4
182
+ // 扫描文件夹后的逐篇入队:与批量重试同一口径——这一段只做哈希、analysis/便携结果探测和排队,
183
+ // 真正的解析由宿主级 worker 池(默认 4 路并发)按并发位跑,所以这里的并发只影响响应快慢。
184
+ const SCAN_ADD_CONCURRENCY = 4
185
+ // 失败清单只回传前若干条:整目录扫描可能上百篇,侧栏要的是"哪几篇没进去",不是全量转储。
186
+ const MAX_SCAN_FAILURES = 10
187
+ // 扫描授权的有效期与在库数量:够用户在选完目录后从容地点一次「开始解析」或一次「仍要扫描」,
188
+ // 又不会让一枚泄漏的凭据长期有效。
189
+ const SCAN_GRANT_TTL_MS = 15 * 60 * 1000
190
+ const MAX_SCAN_GRANTS = 32
191
+ // 批量注入/删除的单次上界:侧栏整目录扫描能留下几百张卡片,一次请求要把整批做完(只写一次
192
+ // 状态),但入参规模仍要有界——请求体 1 MiB 装得下,真正的代价是逐篇读 Markdown。
193
+ const MAX_BATCH_DOCUMENTS = 500
194
+ // 批量注入前的可注入性判定并发:每篇都要读一遍 Markdown 才知道能不能注入(与单篇时代同一口径)。
195
+ const BATCH_CHECK_CONCURRENCY = 8
196
+ // 失败明细只回传前若干条:整批可能几百篇,侧栏要的是"哪几篇没动",不是全量转储。
197
+ const MAX_BATCH_FAILURES = 10
198
+ // 一键翻译(D177)逐篇判定"这一篇还有没有待译的块"的并发。判定要读块列表与译文两份文件,
199
+ // 串行跑几百篇会让按钮按下去之后卡住不动;真正的翻译由队列按全局闸门放行,与这里无关。
200
+ const BATCH_TRANSLATE_CONCURRENCY = 4
201
+ // 记住的会话工作目录条数:只用于给系统选择窗口定初始位置,最旧的会话先丢,重开窗口不影响任何功能。
202
+ export const MAX_SESSION_CWDS = 64
203
+ // 一条注入消息的字节帽可配置区间:下限保证放得下一篇完整目录,上限防把整本文库塞进一次请求。
204
+ export const CONTEXT_BUDGET_MIN_BYTES = 16 * 1024
205
+ export const CONTEXT_BUDGET_MAX_BYTES = 512 * 1024
206
+
207
+ /**
208
+ * 把 `/selection` 与 `/delete` 的入参归一成去重后的 documentIds 数组。
209
+ *
210
+ * 单篇写法 `documentId` 保留:老侧栏与手工排障都还在用它;两种写法同时给出时宁可拒绝也不猜。
211
+ */
212
+ function batchDocumentIds(body) {
213
+ if (body.documentIds !== undefined && body.documentId !== undefined) return { error: 'documentId 与 documentIds 不能同时给出' }
214
+ if (body.documentIds === undefined && body.documentId === undefined) return { error: '未选择论文' }
215
+ const raw = body.documentIds !== undefined ? body.documentIds : [body.documentId]
216
+ if (!Array.isArray(raw) || raw.length === 0) return { error: '未选择论文' }
217
+ if (raw.length > MAX_BATCH_DOCUMENTS) return { error: `一次最多处理 ${MAX_BATCH_DOCUMENTS} 篇论文` }
218
+ if (raw.some(id => !/^[a-f0-9]{64}$/.test(String(id ?? '')))) return { error: '论文 ID 无效' }
219
+ return { ids: [...new Set(raw)] }
220
+ }
221
+
222
+ async function bodyOf(request) {
223
+ if (!/^application\/json(?:;|$)/i.test(request.headers.get('content-type') ?? '')) {
224
+ const error = new Error('请求必须使用 application/json')
225
+ error.status = 415
226
+ throw error
227
+ }
228
+ const text = await request.text()
229
+ const path = new URL(request.url).pathname
230
+ const limit = path === API_BASE + '/bibliography-import' ? 16 * 1024 * 1024
231
+ : path === API_BASE + '/citation-styles' ? 4 * 1024 * 1024 : 1024 * 1024
232
+ if (text.length > limit) {
233
+ const error = new Error('请求体过大')
234
+ error.status = 413
235
+ throw error
236
+ }
237
+ let value
238
+ try { value = JSON.parse(text || '{}') } catch {
239
+ const error = new Error('JSON 请求体无效')
240
+ error.status = 400
241
+ throw error
242
+ }
243
+ // 只收 JSON 对象:数组、字符串、null 会一路穿透到 `body.sessionId` 这类属性读取,抛 TypeError
244
+ // 变成 500 并把整栈写进宿主日志——那是请求方能给宿主制造噪声的最短路径。
245
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
246
+ const error = new Error('请求体必须是 JSON 对象')
247
+ error.status = 400
248
+ throw error
249
+ }
250
+ return value
251
+ }
252
+
253
+ function sameOrigin(request) {
254
+ const origin = request.headers.get('origin')
255
+ if (!origin) return true
256
+ try {
257
+ // Connection uses dsh.internal for the URL after validating the original Host/Origin.
258
+ const host = request.headers.get('host')
259
+ const target = host ? new URL(`http://${host}`) : new URL(request.url)
260
+ return new URL(origin).host === target.host
261
+ } catch { return false }
262
+ }
263
+
264
+ function selectionView(state, sessionId) {
265
+ const entry = state.selections[sessionId] ?? { desired: [], delivered: [] }
266
+ return {
267
+ documentIds: sessionDocumentIds(state, sessionId),
268
+ desired: entry.desired ?? [],
269
+ delivered: entry.delivered ?? [],
270
+ deliveredUnavailable: entry.deliveredUnavailable ?? [],
271
+ }
272
+ }
273
+
274
+ /**
275
+ * A session id → working directory map with a bound.
276
+ *
277
+ * The dialogs open at the session's directory; entries only ever grow with the number of
278
+ * distinct sessions this host has seen, so the oldest are dropped past the cap.
279
+ */
280
+ function createSessionCwdStore(limit = MAX_SESSION_CWDS) {
281
+ const cwds = new Map()
282
+ return {
283
+ remember(sessionId, cwd) {
284
+ // Re-remembering refreshes the entry's position, so eviction drops the least
285
+ // recently seen session rather than the least recently first-seen one.
286
+ if (cwds.has(sessionId)) cwds.delete(sessionId)
287
+ else if (cwds.size >= limit) cwds.delete(cwds.keys().next().value)
288
+ cwds.set(sessionId, cwd)
289
+ },
290
+ get: sessionId => cwds.get(sessionId),
291
+ size: () => cwds.size,
292
+ }
293
+ }
294
+
295
+ /**
296
+ * 以固定并发跑完一批条目,单个条目失败不影响其余,返回值按输入顺序给出
297
+ * `{ ok: true, value }` / `{ ok: false, error }`。批量重试与批量扫描共用这一份,
298
+ * 免得两处各自维护游标 + 补位逻辑。
299
+ */
300
+ export async function mapWithConcurrency(items, limit, worker) {
301
+ const results = new Array(items.length)
302
+ let cursor = 0
303
+ await Promise.all(Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
304
+ while (cursor < items.length) {
305
+ const index = cursor++
306
+ try { results[index] = { ok: true, value: await worker(items[index]) } }
307
+ catch (error) { results[index] = { ok: false, error: errorText(error) } }
308
+ }
309
+ }))
310
+ return results
311
+ }
312
+
313
+ function createSweepScheduler({ minimumIntervalMs, ready, run, onError }) {
314
+ let lastRunAt = 0
315
+ let running = false
316
+ return () => {
317
+ if (running || Date.now() - lastRunAt < minimumIntervalMs) return
318
+ lastRunAt = Date.now()
319
+ running = true
320
+ void (async () => {
321
+ try {
322
+ await ready
323
+ await run()
324
+ } catch (error) {
325
+ onError(error)
326
+ } finally {
327
+ running = false
328
+ }
329
+ })()
330
+ }
331
+ }
332
+
333
+ /**
334
+ * 阅读器块里**按存在带上**的派生键。取值来自 splitBlocks,这里只是过一道白名单 ——
335
+ * 基础五字段(id / type / page / sourceText / zh)在上面显式构造,其余按这张表放行。
336
+ * 🔴 与 blocks.js 的 blockOf 成对:那边产出什么键,这边就得放行什么键,漏一个就是静默丢字段。
337
+ * 🔴 `bbox` 必须在列(P21):主栏原页的高亮框按它换算百分比。它一度不在这张表里 ——
338
+ * 症状是「高亮一条都不显示」:客户端拿到 row.bbox 恒为 undefined,pageHighlights 恒为空数组,
339
+ * 界面上不报任何错(CSS 补得再全也没有框可画)。漏字段这种错只有真机看得出来。
340
+ */
341
+ const READER_BLOCK_KEYS = ['math', 'caption', 'html', 'footnote', 'imagePath', 'bbox', 'displayTitle']
342
+
343
+ /**
344
+ * 一条笔记的长度上限(字符)。
345
+ *
346
+ * 笔记与划线同文件、同一次读写:一条失控的长笔记会把整个文件撑大,而 resolveMarks 每次
347
+ * /reader 都要读它。10000 字符远超"一段批注"的实际需要,正常使用碰不到这条边界。
348
+ */
349
+ const MAX_NOTE_LENGTH = 10000
350
+
351
+ /**
352
+ * 读并切一篇论文的块列表。
353
+ *
354
+ * 读不到(老产物没有 contentPath、文件被删)、JSON 坏、顶层不是数组,一律按「这篇没有块列表」
355
+ * 返回 —— 与 translate-task.js 的 blocksOfDocument 同一口径,不把一次坏读变成整篇打不开。
356
+ *
357
+ * @param {string} contentPath portable.js 的 documentPaths 给出的绝对路径。
358
+ * @returns {Promise<{blocks: object[], notice: string}>} notice 非空即"为什么没有块"。
359
+ */
360
+ const readerBlocksOf = createBlockReader()
361
+
362
+ /**
363
+ * 把译文合并进块:**块顺序与字段一律以块列表为准**,译文只贡献一个 `zh`。
364
+ *
365
+ * 译文的键集与块列表不是包含关系:增量翻译只写这一次翻的块,块列表变过之后还会留下
366
+ * 旧 id 的条目。所以只按键取译文,取不到就是空串 —— 不因为译文里有块列表没有的 id
367
+ * 就凭空多出一个块(那会让阅读器渲染出正文里不存在的段落)。
368
+ *
369
+ * @param {object[]} blocks splitBlocks 的产物。
370
+ * @param {object|null} translation readTranslation 的结果(可能为 null)。
371
+ * @returns {object[]} 阅读器要的块,顺序与入参一致。
372
+ */
373
+ function mergeReaderBlocks(blocks, translation) {
374
+ // 块 id 由「页码 + 页内同类型序号」派生,低页在前;跨页重复 id 在原理上不可能,兜底取先出现的那条。
375
+ const translationsById = new Map()
376
+ for (const entry of Array.isArray(translation?.blocks) ? translation.blocks : []) {
377
+ if (entry === null || typeof entry !== 'object') continue
378
+ if (typeof entry.id !== 'string' || translationsById.has(entry.id)) continue
379
+ translationsById.set(entry.id, entry)
380
+ }
381
+ return (Array.isArray(blocks) ? blocks : []).map(block => {
382
+ const translation = translationsById.get(block.id)
383
+ const stale = typeof translation?.sourceHash === 'string' && translation.sourceHash !== sourceHashOf(block)
384
+ const view = { id: block.id, type: block.type, page: block.page, sourceText: block.sourceText,
385
+ zh: !stale && typeof translation?.zh === 'string' ? translation.zh : '' }
386
+ if (stale) view.translationStale = true
387
+ if (block.level !== undefined) view.level = block.level
388
+ for (const key of READER_BLOCK_KEYS) {
389
+ if (block[key] !== undefined) view[key] = block[key]
390
+ }
391
+ return view
392
+ })
393
+ }
394
+
395
+ /** 日志里的文档 id 截断:state 记录可能来自手工改过的文件,不能拿它拼无上限的日志行。 */
396
+ function truncateForLog(value, max = 64) {
397
+ const text = String(value ?? '')
398
+ return text.length > max ? `${text.slice(0, max)}…` : text
399
+ }
400
+
401
+ export function apply(ctx, config = {}) {
402
+ const discussionGate = createConcurrencyGate(1)
403
+ const repository = new PaperRepository(runtimeRoot(config))
404
+ const metadataResolver = config.metadataResolver ?? createMetadataResolver({ networkMode: config.metadataNetworkMode ?? 'auto' })
405
+ if (!config.metadataResolver) ctx.effect?.(() => () => metadataResolver.dispose())
406
+ const resolver = new PaperResolver(repository, {
407
+ logger: ctx.logger,
408
+ // Bookkeeping lookup failure must not fail an already published parse.
409
+ // Translation on publication remains opt-in; opening a paper owns the default trigger.
410
+ onPublished: async ({ document, sessionId }) => {
411
+ if (config.metadataAutoFill !== false) {
412
+ try {
413
+ const stored = (await repository.snapshot()).documents[document.id] ?? await repository.archivedDocument(document.id)
414
+ const current = stored ? await readDocumentManifest(stored) ?? stored : null
415
+ // 有标识 → 精确查询;没有标识 → Crossref + arXiv 题名检索。两条路都只在
416
+ // 「题名与登记记录完全一致(且首位作者不冲突)」时才写入,其余留空等人工确认。
417
+ // 导入侧尤其需要它:本地 PDF 没有标识,以前永远补不上,作者和年份一直空着。
418
+ if (current) await enrichMetadata(repository, document.id, metadataResolver, { dryRun: false })
419
+ } catch (error) { ctx.logger.warn('dsh-paper metadata: ' + errorText(error)) }
420
+ }
421
+ if (config.autoTranslateOnParse === true) await autoTranslate(document, sessionId)
422
+ },
423
+ // D156:解析完成后按元数据改名(默认开,与自动翻译无关)。
424
+ // 回退链:目录元数据(arXiv/DOI 采集)→ PDF Info dict → MinerU 正文首个 heading。
425
+ // 三级都没有标题时安静跳过,保持原名。
426
+ onRenamed: async ({ document, metadata }) => {
427
+ // 第三级兜底:正文首个 heading。实测某篇 Mem0 论文 Info dict 里 Title/Author 全空,
428
+ // 而正文首行就是 `# Mem0: Building Production-Ready AI Agents…` —— 有它才救得回来。
429
+ // 读块列表失败不算错(老产物没有 content.json),那一级就自然缺席。
430
+ let heading = ''
431
+ try {
432
+ const paths = documentPaths(document)
433
+ heading = titleFromBlocks((await readerBlocksOf(paths.contentPath)).blocks)
434
+ } catch (error) {
435
+ ctx.logger.warn(`dsh-paper rename: 读取正文标题失败 ${errorText(error)}`)
436
+ }
437
+ return renameAfterParse({
438
+ repository,
439
+ document,
440
+ metadata,
441
+ heading,
442
+ // 注入读 PDF 元数据的实现;测试里换替身,不真的起 uvx。
443
+ readPdfMetadata: typeof config.readPdfMetadata === 'function' ? config.readPdfMetadata : readPdfMetadata,
444
+ logger: ctx.logger,
445
+ })
446
+ },
447
+ // 桥接本身可注入(测试与排障);不注入走真实 SDK 桥接。
448
+ sdkParse: typeof config.sdkParse === 'function' ? config.sdkParse : parseWithConfiguredMineruSdk,
449
+ // 桥接配置每次现算:用户在设置页存/清 Key 之后,下一个任务就该按新 Key 走,不必重启宿主。
450
+ // 读不出来(文件被删、被写坏)一律当未配置,由 resolver 报「未配置」而不是 5xx。
451
+ sdkConfig: () => mineruSdkConfig({
452
+ // 路径要拼到文件本身:readMineruKeySync 收的是 mineru.json,不是 runtime 目录。
453
+ secret: readMineruKeySync(mineruKeyPath(runtimeRoot(config))),
454
+ command: config.mineruCommand,
455
+ }),
456
+ // 并发与提交额度可用插件 config 覆盖:一次批量添加几十篇时调大并发,或按 MinerU 套餐
457
+ // 收紧提交频控(两者都不需要改代码)。非法值由 resolver 回落到默认。
458
+ maxConcurrent: config.parseConcurrency,
459
+ submissionsPerMinute: config.submissionsPerMinute,
460
+ })
461
+ // Session working directories and paper-file reads are both bounded caches now: the
462
+ // former used to grow with every session this host touched, the latter used to re-read
463
+ // every Markdown of every selected paper on every pre-step and every 2s sidebar poll.
464
+ const sessionCwds = createSessionCwdStore()
465
+ const documentReader = createDocumentReader()
466
+ // ---- 翻译执行(宿主级共享,与解析池分开)----
467
+ // 🔴 并发默认 2:翻译是远程模型调用,同时开太多会让限流与成本一起失控;两条并行已能
468
+ // 盖住单篇 20 页的等待。可用插件 config 覆盖,非法值会被队列拒绝(不静默回落)。
469
+ //
470
+ // 队列的 taskId 用 documentId —— 同一个 documentId 只允许一个驱动,"重复点翻译"由队列
471
+ // 自己拒绝。批次里带的是**这篇论文要翻什么**(scope / 增量 / 模型快照),不是块本身:
472
+ // 块由 translate-task.js 在读盘时现取,免得把几百个块对象挂在队列记录上。
473
+ // 并发翻译数(D136):**设置页优先**,插件 config 次之,最后默认 4。
474
+ // 每次入队现算(见 startTranslation)—— 用户在设置页改完立刻生效,不必重启宿主。
475
+ const configConcurrency = Number.isInteger(config.translateConcurrency) && config.translateConcurrency > 0
476
+ ? config.translateConcurrency
477
+ : 4
478
+ const concurrencyOf = settings => {
479
+ const value = settings?.translateConcurrency
480
+ return Number.isInteger(value) && value >= 1 && value <= 8 ? value : configConcurrency
481
+ }
482
+ // 🔴 全局并发闸门(D157):设置页那个数 = **整个宿主同时在飞的模型请求数**。
483
+ //
484
+ // 在这之前它实际只管住"同时在翻几篇"(队列的 taskId 是 documentId,每篇只占一个队列位),
485
+ // 而每篇内部又各有自己的批次并发(translate.js 的 mapLimit,用的是同一个数)——
486
+ // 两层相乘 = 4 × N。10 篇同时进来就是 40 个请求打给模型提供方,本地推理服务被压垮后
487
+ // 回复被截断成畸形 JSON,表现为「一批里只有几行有译文」。
488
+ //
489
+ // 闸门挂在**每一次模型请求**上(translate.js 的 attemptBatch 外层),所以重试也算数。
490
+ // 上限在每次入队时按当前设置刷新 —— 用户在设置页改完立刻生效,不必重启宿主。
491
+ const translationGate = createConcurrencyGate(configConcurrency)
492
+ // 输出协议(D138):`lines` 给专用机器翻译模型(本地 hy-mt2 这类),它们不吐 JSON 数组,
493
+ // 只吐「每行一条 [id] 译文」的方言。默认 `json`,与加这个开关之前逐字节一致。
494
+ // 与并发同一口径:**每次入队现算**,设置页改完下一个任务就按新的走。
495
+ const protocolOf = settings => (TRANSLATION_PROTOCOLS.includes(settings?.translationProtocol) ? settings.translationProtocol : 'json')
496
+ // 目标语言(D140):设置页那一档;白名单的唯一真相在 translate-prompts.js。
497
+ const TRANSLATION_LANGUAGE_CODES = TRANSLATION_LANGUAGES.map(entry => entry.code)
498
+ // 🔴 宿主能力用 `ctx.get()` 惰性取,**不上 inject** —— llm / attachments 是可选的:
499
+ // 写进 inject 会让"没装这两个服务的宿主"整个插件加载失败,而翻译只是插件的一项能力,
500
+ // 不该有这种否决权(宿主规范:可选服务用 ctx.get,保留 ctx.<name> 给已声明的注入)。
501
+ //
502
+ // 页面图渲染复用 T9 的 renderPageImages,缓存落在插件自己的 runtime 目录下 ——
503
+ // 它按 (内容标识, 页码, 宽度) 分目录,与 UI 的高清变体互不干扰。
504
+ const pageImageCacheDir = pageImageCacheRoot(runtimeRoot(config))
505
+ /**
506
+ * 页面图渲染器:translate.js 只交出 `{ pages, width }`,所以 PDF 路径必须在**建批次时**
507
+ * 就绑好(见 {@link makeTranslateBatch})—— 渲染器本身是无状态的,同一篇的多个批次共用它。
508
+ */
509
+ const pageImagesFor = pdfPath => async ({ pages, width }) => renderPageImages(
510
+ { pdfPath, pages, width },
511
+ { cacheDir: pageImageCacheDir, command: config.mineruCommand },
512
+ )
513
+
514
+ /**
515
+ * 阅读器资源路由的查表函数:**必须走 hydrateDocument**。
516
+ *
517
+ * state.documents[id] 里的 pdfPath / markdownPath 是**相对 portable artifact 的路径**,不 hydrate
518
+ * 拿到的值既不能读也不能渲染(这不是防御式编程,是这两条路由唯一的正确取法)。
519
+ * 查不到返回 null —— 与 /reader 的 404 同口径。
520
+ */
521
+ const assetDocumentFor = async documentId => {
522
+ const raw = await readerDocumentOf(await repository.snapshot(), documentId)
523
+ if (!raw) return null
524
+ const document = hydrateDocument(raw)
525
+ return { markdownPath: document.markdownPath, pdfPath: document.pdfPath }
526
+ }
527
+ // 与 tool 那一路同样**惰性构造**:apply 期 ctx.get('jobs') 之类还没注册,构造时做断言会污染日志。
528
+ let assetRoutesInstance
529
+ function assetRoutesFor() {
530
+ assetRoutesInstance ??= createAssetRoutes({
531
+ documentFor: assetDocumentFor,
532
+ renderPageImages,
533
+ cacheDir: pageImageCacheDir,
534
+ command: config.mineruCommand,
535
+ })
536
+ return assetRoutesInstance
537
+ }
538
+
539
+ /**
540
+ * 两条字节路由不走下面那段 JSON dispatch:它们回的是原始字节,而 dispatch 的 json() 只发 JSON
541
+ * (浏览器 <img> 不认),异常也要保持同样的响应类型而不是被收成 JSON 信封。
542
+ */
543
+ async function assetDispatch(request, name) {
544
+ const url = new URL(request.url)
545
+ try {
546
+ await repositoryReady
547
+ if (!sameOrigin(request)) return new Response('拒绝跨源请求\n', { status: 403, headers: { 'Content-Type': 'text/plain; charset=utf-8' } })
548
+ return await assetRoutesFor()[name](request, url)
549
+ } catch (error) {
550
+ ctx.logger.error(`dsh-paper asset ${name}: ${error?.stack ?? error}`)
551
+ return new Response('资源读取失败\n', { status: 500, headers: { 'Content-Type': 'text/plain; charset=utf-8' } })
552
+ }
553
+ }
554
+ const translateHostOptions = typeof config.translateHost === 'function'
555
+ ? config.translateHost
556
+ : () => ({ llm: ctx.get('llm'), attachments: ctx.get('attachments') })
557
+ let stoppingTranslations = false
558
+ const translationSettlements = new Set()
559
+ function trackTranslationSettlement(operation) {
560
+ const settled = operation.catch(error => ctx.logger.warn(`dsh-paper translate: 结算失败:${errorText(error)}`))
561
+ translationSettlements.add(settled)
562
+ void settled.then(() => translationSettlements.delete(settled))
563
+ return settled
564
+ }
565
+ const translateQueue = createTranslateQueue({
566
+ concurrency: configConcurrency,
567
+ runBatch: async (batch, jobCtx) => {
568
+ // 宿主能力(llm / attachments)取不到时报错而不是静默跳过 —— 否则用户点了翻译,
569
+ // 界面一直"排队中",日志里什么都没有。
570
+ const host = translateHostOptions() ?? {}
571
+ if (typeof host.llm?.prepareCall !== 'function') {
572
+ return { ok: false, error: '宿主没有可用的 llm 服务,无法翻译' }
573
+ }
574
+ // 术语表片段在**每次批次执行时现取**:用户在设置里改完术语表,下一次翻译就按新的走,
575
+ // 不必重启宿主(与 MinerU Key 的现算口径一致)。读取失败降级成空串 —— 术语是增强,
576
+ // 一个坏掉的术语表文件不能让整篇论文翻不了。
577
+ const glossary = await glossaryBlockFor()
578
+ const outcome = await translateDocumentToDisk(batch.document, {
579
+ reader: documentReader,
580
+ llm: host.llm,
581
+ attachments: host.attachments,
582
+ glossary,
583
+ // 渲染器绑到**这篇论文自己的 PDF**:一个批次只翻一篇,缓存键里也带内容标识,
584
+ // 所以同一份 PDF 被替换后旧图不会被误命中。
585
+ renderPages: host.renderPages ?? pageImagesFor(batch.document.pdfPath),
586
+ model: batch.model,
587
+ scope: batch.scope,
588
+ incremental: batch.incremental,
589
+ translateAll: batch.translateAll,
590
+ batchPages: batch.batchPages,
591
+ targetLanguage: batch.targetLanguage,
592
+ // 输出协议(D138 / D139):专用翻译模型用 lines / plain,通用模型用默认 json。
593
+ protocol: batch.protocol,
594
+ // 🔴 单篇内的**批次并发**(D139):队列的并发数是跨文档的(taskId 是 documentId),
595
+ // 一篇论文只占一个队列位 —— 不让批次并发的话,20 个批次要串行跑(实测单批 22–35 秒)。
596
+ concurrency: batch.concurrency,
597
+ // 🔴 全局闸门(D157):它把"同时几个模型请求"真正收到设置页那个数上。
598
+ // 批次并发(上面那个 concurrency)现在只是**单篇内最多排几个等待者**,
599
+ // 实际放行由闸门统一决定 —— 两层不再相乘。
600
+ gate: translationGate,
601
+ signal: jobCtx?.signal,
602
+ logger: ctx.logger,
603
+ // 记账的幂等键是 **jobId**(一次「点翻译」= 一个 job),不是 documentId:
604
+ // 同一篇重译两次是两笔开销,用 documentId 会让后一次覆盖前一次。
605
+ // taskId 在这里正好就是 documentId(队列的约定),所以另取 jobCtx 之外的那个。
606
+ onUsage: (usage, meta) => recordUsage(usage, { jobId: batch.jobId, documentId: batch.documentId, model: meta?.model }),
607
+ })
608
+ if (typeof batch.onDone === 'function') await batch.onDone(outcome)
609
+ // 🔴 「批次跑完」不等于「译出来了」:模型回复解析不了时**每个块都是 status:'failed'**,
610
+ // 而 translateDocument 自己不抛错。这里若一律回 ok:true,任务会以 ready 收尾 ——
611
+ // 用户看到的是「点一下就说完成、译文一个字没变」,连一条失败记录都留不下(实测踩过:
612
+ // 435 个块全失败的任务报到界面上是「翻译完成」)。零译出必须当场算失败,并把原因带出去。
613
+ if ((outcome?.stats?.translated ?? 0) === 0 && (outcome?.stats?.failed ?? 0) > 0) {
614
+ return { ok: false, error: translationFailureText(outcome, batch) }
615
+ }
616
+ return { ok: true }
617
+ },
618
+ })
619
+ // ---- Paper_analysis 工具(P4)----
620
+ // 🔴 ctx.jobs 用 ctx.get() **惰性取**,不上 inject:后台任务服务在部分组合里根本没有,
621
+ // 写进 inject 会让那些宿主上整个插件加载失败,而工具没它只是少一个进度查询入口。
622
+ // 拿不到时 job-facade 返回 { jobId: null, reason },工具如实告诉模型「无法跟踪进度」,
623
+ // 不伪造一个查不到的 jobId(D80)。
624
+ // 🔴 boot nonce 在 apply 期算一次并固定:kind 决定了宿主 jobId 的命名空间,
625
+ // 每次现算会让同一次运行里的 id 前缀漂移,旧 id 立刻查不到。
626
+ const jobKindNonce = randomUUID().slice(0, 8)
627
+ /**
628
+ * 门面**惰性构造**,第一次真要起任务时才建。
629
+ *
630
+ * 两个原因都来自 apply 期的时序:
631
+ * ① 宿主服务注册可能晚于插件加载,此刻 ctx.get('jobs') 拿到 undefined 是正常现象,
632
+ * 不是「这个宿主没有后台任务」;早构造会把一次时序问题固化成永久不可用;
633
+ * ② 门面构造函数在服务缺失时会写一行 warn,而 apply 期的这行 warn 会污染
634
+ * 「本次请求只记了一行日志」这类既有断言。
635
+ */
636
+ let jobFacadeInstance
637
+ const jobFacade = {
638
+ get available() { return jobFacadeFor().available },
639
+ get kind() { return jobFacadeFor().kind },
640
+ start: spec => jobFacadeFor().start(spec),
641
+ }
642
+ function jobFacadeFor() {
643
+ jobFacadeInstance ??= createJobFacade({ jobs: ctx.get('jobs'), bootNonce: jobKindNonce, logger: ctx.logger })
644
+ return jobFacadeInstance
645
+ }
646
+ // 任务清单服务:工具用它登记任务,purge 用它摘掉已永久删除论文的条目 —— 同一个实例,
647
+ // 否则两条路径各拿一份 store,摘除就会对着另一份锁写另一份文件。
648
+ const taskStore = createTaskStore({ root: runtimeRoot(config), logger: ctx.logger })
649
+ /**
650
+ * 右栏「解析」Tab 的宿主服务:一条**不写文献库**的 PDF → md + images 通路。
651
+ *
652
+ * 它把 `resolver` 当 `slots` 传进去 —— 抢并发位(runSlot)、取提交额度(limiter)、
653
+ * 调远端(sdkParse/sdkConfig)全部走文献库那**同一个**实例,这样「两处解析加起来不超过
654
+ * parseConcurrency 路、submissionsPerMinute 次/分」是结构上的保证,不是两边各自守约。
655
+ */
656
+ const parseExport = createParseExport({
657
+ root: runtimeRoot(config),
658
+ repository,
659
+ slots: resolver,
660
+ logger: ctx.logger,
661
+ })
662
+ const pdfAnalysisTool = createPdfAnalysisTool({
663
+ publicMessage: paperOutput(runtimeRoot(config)).message,
664
+ repository,
665
+ resolver,
666
+ sessionCwds,
667
+ reader: documentReader,
668
+ resolveSource: resolvePdfSource,
669
+ tasks: taskStore,
670
+ jobFacade,
671
+ // library=false 走右栏「解析」那条独立通路:传同一个实例,所以与文献库共用并发位与提交额度。
672
+ parseExport,
673
+ // 独立解析只收本地 PDF 路径,要在排队前 stat 一次说清「这不是 PDF」。
674
+ inspectPdf,
675
+ // 下载落盘放在插件自己的 runtime 下:与页面图缓存同源,卸载时一起清。
676
+ tmpRoot: runtimeRoot(config),
677
+ // 章节树预算:与 DEFAULT_SETTINGS 同值,**不是第二处默认值**(那里导出什么这里传什么)。
678
+ // ⚠️ 已知缺口:用户改过 outlineBudgetBytes 后,工具这一路仍按默认值走 ——
679
+ // 该字段在工具构造时被读一次,要跟随运行期设置需把 deps 改成取值函数,留待有需求时再动。
680
+ outlineBudgetBytes: DEFAULT_SETTINGS.outlineBudgetBytes,
681
+ logger: ctx.logger,
682
+ })
683
+ /**
684
+ * Paper_annotate:把 agent 的回答/笔记写回某一段旁边(D11 的「工具写回页边」)。
685
+ *
686
+ * 依赖全部经 deps 注入 —— 工具模块不 import 同目录协作者,与 Paper_analysis 同一分工。
687
+ * `pathOf` 用 reader-store 的 `readerPathOf` 会写进划线文件,所以这里用边注自己的路径函数。
688
+ */
689
+ const annotateTool = createAnnotateTool({
690
+ // 与 Paper_read / Paper_library 同一套指认:注入上下文里没有 documentId,只能按篇名/路径认。
691
+ findPaper: async reference => {
692
+ // 指认字段只从 identityRecordOf 取(与 Paper_read / Paper_library 同一份),
693
+ // 这里只额外挂上已 hydrate 的 document 供写回时使用。
694
+ const list = (await rawDocuments()).map(raw => {
695
+ const document = hydrateDocument(raw)
696
+ return { ...identityRecordOf({ ...raw, ...document, id: raw.id }), document }
697
+ })
698
+ const hit = identifyDocument(list, reference)
699
+ if (hit.document === undefined) return { error: hit.error, code: hit.code }
700
+ return { documentId: hit.document.id, document: hit.document.document }
701
+ },
702
+ pathOf: document => discussionPathOf(document),
703
+ readPayload: path => readDiscussionForWrite(path),
704
+ writePayload: (path, payload) => writeDiscussion(path, payload),
705
+ serialize: operation => discussionGate.run(operation),
706
+ deleteThread,
707
+ appendThread,
708
+ answerThread,
709
+ // 目录里印的是 [b:p2-h1 .. b:p4-p7] 这种区间写法,块 id 本身没有 b: 前缀 ——
710
+ // 照目录抄下来的地址必须能直接用(否则 section 报找不到、annotate 写成孤儿)。
711
+ normalizeBlockId,
712
+ // 块 id 存在性校验:notice 非空时无法核实锚点,工具保留原文件并返回可重试失败。
713
+ blockIdsOf: async document => {
714
+ const { blocks, notice } = await readerBlocksOf(documentPaths(document).contentPath)
715
+ if (notice !== '') return null
716
+ return blocks.map(block => block.id)
717
+ },
718
+ // 目录里的 `#序号` 指第几节:按**同一份层级**(headingLevels 排序后的文档顺序)
719
+ // 折成那一节的块 id。用原始块顺序会让序号与目录对不上 —— 两者必须同一口径。
720
+ headingIdsOf: async document => {
721
+ const { blocks, notice } = await readerBlocksOf(documentPaths(document).contentPath)
722
+ if (notice !== '') return null
723
+ // 与目录同一口径:被上游误标成标题的正文不进目录,也不占序号。
724
+ return visibleHeadingIndexes(blocks).map(index => blocks[index].id)
725
+ },
726
+ })
727
+
728
+ /**
729
+ * Paper_library:模型侧的文献库入口。
730
+ *
731
+ * 读走 libraryView(与侧栏同一份视图,冷归档也算),写走 runLibraryRequest
732
+ * (与 /library、/item、/rename、/export 同一套函数与写锁)—— 工具不留自己的状态。
733
+ */
734
+ /**
735
+ * 一篇论文的引用元数据。
736
+ *
737
+ * 🔴 `Paper_library get` 与 `Paper_library citation` 必须走同一份实现:两条路径各拼一遍输入
738
+ * 时,同一条论文在一边是 5 位作者、在另一边是「首作者 + 等」—— 审计看到的与导出的不是
739
+ * 同一套值,而两边都「看起来正常」。
740
+ *
741
+ * 冷归档记录同样支持:`rawDocuments` 的口径是热记录 + archive/。
742
+ */
743
+ async function citationMetadataOf(documentId) {
744
+ const raw = (await rawDocuments()).find(record => record?.id === documentId)
745
+ if (raw === undefined) return undefined
746
+ return await effectiveMetadata(raw)
747
+ }
748
+
749
+ const libraryTool = createLibraryTool({
750
+ view: async ({ sessionId } = {}) => {
751
+ const view = await libraryView()
752
+ const state = sessionId ? await repository.snapshot() : null
753
+ return { library: view.library, items: view.items, injectedIds: state?.selections[sessionId]?.desired ?? [] }
754
+ },
755
+ metadataOf: citationMetadataOf,
756
+ run: request => toolHost.runLibraryRequest(request),
757
+ // list 的 unbound 过滤要问「这个文件夹还在不在」。只在开着那一个过滤时才会逐条调用 ——
758
+ // 每次库视图都 stat 一遍七十多条记录,是给侧栏轮询白付的钱。
759
+ dirExists: async dir => {
760
+ if (typeof dir !== 'string' || dir === '') return false
761
+ try { return (await stat(dir)).isDirectory() } catch { return false }
762
+ },
763
+ })
764
+
765
+ /**
766
+ * Paper_read:模型侧的「按结构读一篇」。
767
+ *
768
+ * papers 用 rawDocuments(热记录 + 冷归档),与文献库列表同一口径 —— 模型不该因为某篇
769
+ * 久未打开被驱逐进 archive/ 就「找不到」。冷记录的路径要先 hydrate。
770
+ */
771
+ const readTool = createReadTool({
772
+ // 跨篇检索走执行侧的同一个函数:候选池、集合范围、块切分都在那边(工具侧零 IO)。
773
+ search: request => toolHost.searchPapers(request),
774
+ papers: async () => (await rawDocuments()).map(raw => {
775
+ const document = hydrateDocument(raw)
776
+ return {
777
+ id: raw.id,
778
+ pdfName: document.pdfName ?? raw.pdfName,
779
+ pdfPath: document.pdfPath,
780
+ markdownPath: document.markdownPath,
781
+ // 与库视图同一口径:模型读到一篇时也该知道它的工作区文件夹在哪。
782
+ sourceDir: typeof document.sourceDir === 'string' ? document.sourceDir : '',
783
+ sourcePdfPath: typeof document.sourcePdfPath === 'string' ? document.sourcePdfPath : '',
784
+ title: document.title ?? raw.title,
785
+ authors: document.authors ?? raw.authors,
786
+ year: document.year ?? raw.year,
787
+ }
788
+ }),
789
+ read: request => toolHost.readPdf(request),
790
+ })
791
+
792
+ const paperTools = [pdfAnalysisTool, annotateTool, libraryTool, readTool].map(tool => publicPaperTool(tool, runtimeRoot(config)))
793
+ ctx.inject(['tools'], toolsCtx => {
794
+ const disposers = []
795
+ try {
796
+ for (const tool of paperTools) disposers.push(toolsCtx.tools.register(tool))
797
+ } catch (error) {
798
+ for (const dispose of disposers.reverse()) if (typeof dispose === 'function') dispose()
799
+ throw error
800
+ }
801
+ })
802
+
803
+ // 系统选择窗口同时只开一个:文件框与文件夹框各自去重(测试可注入 pick / pickFolder 实现)。
804
+ const pickPdf = typeof config.pick === 'function' ? config.pick : pickPdfFiles
805
+ const pickFolderDialog = typeof config.pickFolder === 'function' ? config.pickFolder : pickFolder
806
+ // 目录扫描器也留注入缝:与 pickFolder 同理,让 /scan 能测到"子目录读不动"这类真实分支
807
+ // (os 层的不可读目录在 Windows 上要靠 ACL,测试里造不出来)。
808
+ const scanFolder = typeof config.scanFolder === 'function' ? config.scanFolder : scanPdfFolder
809
+ // MinerU 令牌只住在插件自己的 runtime 目录里,页面与 HTTP 响应一律只见打码值:
810
+ // GET 与 POST 共用同一个响应形状,免得两处各写一份"配没配"的口径。
811
+ // ---- 术语表(T22)----
812
+ // 🔴 存**插件 runtime**、全局生效(访谈结论):术语是跨论文的稳定译法,一篇一份要重复维护。
813
+ // 它不跟 PDF 走,所以也不能指望"拷贝论文目录"带走它 —— 这是与划线/笔记刻意相反的一处。
814
+ const glossaryFile = glossaryPathOf(runtimeRoot(config))
815
+ const glossaryView = async () => {
816
+ const payload = await readGlossary(glossaryFile)
817
+ return { entries: payload.entries, limit: MAX_GLOSSARY_ENTRIES }
818
+ }
819
+ /**
820
+ * 术语表读取的**降级口径**:读不出来(文件被删、被写坏、权限问题)一律当空表,
821
+ * 由调用方决定是"没有术语"还是报错。翻译路径必须用它 —— 一个坏掉的术语表文件
822
+ * 绝不能让整篇论文翻不了(术语是增强,不是前置条件)。
823
+ */
824
+ const glossaryBlockFor = async () => {
825
+ try {
826
+ return buildGlossaryBlock((await readGlossary(glossaryFile)).entries)
827
+ } catch (error) {
828
+ ctx.logger.warn(`dsh-paper glossary: 术语表读取失败,本次翻译按无术语处理:${errorText(error)}`)
829
+ return ''
830
+ }
831
+ }
832
+
833
+ // ---- 导出(T23)----
834
+ /**
835
+ * 把一篇论文的图片读成 export.js 要的 `assets` 映射。
836
+ *
837
+ * 🔴 图片**必须由调用方读盘**:export.js 是纯函数、零 IO(它自己的注释就是这么写的)。
838
+ * 两类图各按 export.js 认得的键组织:
839
+ * - 正文图:块里的 `imagePath` 是相对 `analysis/` 的相对路径 —— 原样当键;
840
+ * - 原页图:export.js 按 `pages/<页码>.<ext>` 与 `page-<页码>.<ext>` 试取,
841
+ * 所以这里把渲染出来的页图按前一种键塞进去(见它自己那句"这是唯一一处猜")。
842
+ *
843
+ * 读不出来的图**直接不进映射** —— export.js 对缺失的图会退化成占位句,不抛。
844
+ * 单张图有上限:一篇 50 页的论文把全部页图内联进来能到十几 MB,导出的 HTML 会大到打不开。
845
+ */
846
+ async function exportAssetsOf(document, blocks) {
847
+ const assets = {}
848
+ const readInto = async (key, path) => {
849
+ try {
850
+ const data = await readFile(path)
851
+ if (data.byteLength === 0 || data.byteLength > MAX_EXPORT_ASSET_BYTES) return
852
+ assets[key] = { mime: mimeOfPath(path), base64: data.toString('base64') }
853
+ } catch {
854
+ // 缺图 / 读不动都只是"这张不进导出",不影响其余内容。
855
+ }
856
+ }
857
+ const paths = documentPaths(document)
858
+ const base = dirname(paths.markdownPath)
859
+ for (const block of Array.isArray(blocks) ? blocks : []) {
860
+ const value = typeof block?.imagePath === 'string' ? block.imagePath : ''
861
+ if (value === '') continue
862
+ await readInto(value, resolve(base, value))
863
+ }
864
+ // 原页图:与阅读器同一条渲染链、同一个缓存族(D49),只是宽度取 UI 那一档。
865
+ const pages = [...new Set((Array.isArray(blocks) ? blocks : [])
866
+ .map(block => (Number.isInteger(block?.page) && block.page > 0 ? block.page : null))
867
+ .filter(page => page !== null))].sort((a, b) => a - b).slice(0, MAX_EXPORT_PAGES)
868
+ if (pages.length > 0 && typeof document.pdfPath === 'string' && document.pdfPath !== '') {
869
+ try {
870
+ const rendered = await renderPageImages(
871
+ { pdfPath: document.pdfPath, pages, width: DEFAULT_PAGE_WIDTH, documentId: document.id },
872
+ { cacheDir: pageImageCacheDir, command: config.mineruCommand },
873
+ )
874
+ for (const image of Array.isArray(rendered?.images) ? rendered.images : []) {
875
+ if (!(image?.data instanceof Uint8Array) || image.data.byteLength === 0) continue
876
+ if (image.data.byteLength > MAX_EXPORT_ASSET_BYTES) continue
877
+ assets[`pages/${image.page}.webp`] = { mime: 'image/webp', base64: Buffer.from(image.data).toString('base64') }
878
+ }
879
+ } catch (error) {
880
+ // 渲染器不可用(uvx 缺失 / 超时)不该让整篇导不出来 —— 正文、译文、笔记照常导出,
881
+ // 只是没有原页图。与 /page-image 的 503 是同一条降级口径。
882
+ ctx.logger.warn(`dsh-paper export: 原页图渲染失败,导出不含原页图:${errorText(error)}`)
883
+ }
884
+ }
885
+ return assets
886
+ }
887
+
888
+ // ---- 全局文献库(T21)----
889
+ // 🔴 库级数据存 runtime/dsh-paper/library.json,篇级标记存 <PDF目录>/analysis/<主名>.item.json。
890
+ // 两者都是**用户数据**,绝不进 state.json —— 那个文件会被 compact() 重写(D21/D37)。
891
+ const libraryFile = libraryPathOf(runtimeRoot(config))
892
+ /**
893
+ * 库视图:把热记录与冷归档合成一份全局列表,逐篇附上它的 item.json。
894
+ *
895
+ * 🔴 **两种记录都要收**:compact() 会把久未使用的论文驱逐到 archive/(storage.js:372),
896
+ * 只读 state.documents 会让用户发现"我的文献少了"。冷记录同样可能是非 sidecar 形态,
897
+ * 而 itemPathOf 对非 sidecar 返回 ''(不抛)—— 这正是 D101 那条:一篇冷记录不该让整库 500。
898
+ *
899
+ * 读盘一律走降级口径:库文件坏了当空库、某篇的条目坏了当默认条目。库列表是**只读视图**,
900
+ * 任何一篇的坏数据都不该让整个列表打不开。
901
+ */
902
+ const rawDocuments = async () => {
903
+ const state = await repository.snapshot()
904
+ const hot = Object.values(state.documents).filter(document => document && typeof document.id === 'string')
905
+ const hotIds = new Set(hot.map(document => document.id))
906
+ // 🔴 先按 id 过滤,再只给**真正冷**的那几条读 manifest。
907
+ //
908
+ // `archivedDocuments()` 会给 archive 里每一条都读 manifest,而 manifest 读取要读整份
909
+ // Markdown 并逐张校验图片 —— 实测 73 篇 103–126 ms。可热记录**同时**也躺在 archive 里
910
+ // (compact 只是复制过去,热表并不因此少一条),所以先过滤之后一条都不剩:那 100 ms
911
+ // 是纯白花的,而且它挂在每一次检索与每一次库列表上。
912
+ //
913
+ // 冷记录只在热表里没有它时才补进来;「先滤后读」与原口径等价,只是不再为被丢掉的那些付钱。
914
+ // 热记录已有快照,连对应归档 JSON 也跳过;冷记录仍现读。
915
+ const rawCold = (await repository.rawArchivedDocuments({ excludeIds: hotIds }))
916
+ .filter(document => document && typeof document.id === 'string' && !hotIds.has(document.id))
917
+ const cold = []
918
+ for (const document of rawCold) {
919
+ // 单条 manifest 读不出来不算错:退回原始定位记录,与 archivedDocuments() 同一口径。
920
+ try { cold.push(await readDocumentManifest(document, { validateArtifacts: false }) ?? document) } catch { cold.push(document) }
921
+ }
922
+ return [...hot, ...cold]
923
+ }
924
+ /**
925
+ * 「这篇能不能读」的判定缓存:`markdownPath` → { mtimeMs, size, marked }。
926
+ *
927
+ * 判据是「存在、非空、且带 `<!-- b:... -->` 块标记」—— 没有标记的正文虽然读得出来,
928
+ * 但跨篇检索看不见它(`markedSegments` 找不到任何段),对调用方来说等于「读不了」。
929
+ *
930
+ * 🔴 为什么要缓存:判据要读全文(标记散落在正文里,取头部不算数),73 篇是 7.4 MB / 27 ms。
931
+ * 库视图是显式刷新与切视图时拉的,每次都读一遍全文是白花的钱;用 mtime+size 当键,
932
+ * 文件被重新解析(重写)时自然失效,不需要任何显式清理。
933
+ */
934
+ const readableCache = new Map()
935
+ const readableOf = async document => {
936
+ const markdownPath = typeof document.markdownPath === 'string' ? document.markdownPath : ''
937
+ if (markdownPath === '') return false
938
+ let info
939
+ try {
940
+ info = await stat(markdownPath)
941
+ } catch {
942
+ return false
943
+ }
944
+ if (!info.isFile() || info.size === 0) return false
945
+ const cached = readableCache.get(markdownPath)
946
+ if (cached !== undefined && cached.mtimeMs === info.mtimeMs && cached.size === info.size) return cached.marked
947
+ let marked = false
948
+ try {
949
+ marked = (await readFile(markdownPath, 'utf8')).includes('<!-- b:')
950
+ } catch {
951
+ marked = false
952
+ }
953
+ readableCache.set(markdownPath, { mtimeMs: info.mtimeMs, size: info.size, marked })
954
+ return marked
955
+ }
956
+ /**
957
+ * 读一篇的条目,顺手把它**孤儿化的旧条目文件**收干净(一次性、幂等)。
958
+ *
959
+ * 🔴 为什么会有孤儿:`itemPathOf` 用记录上**冻结的 pdfName** 派生 `<主名>.item.json`,
960
+ * 而改名历史里主名的变化不止「换个名字」—— 规范化会把标题里的 `:` 换成 `-`、
961
+ * 补上 ` - 年份 - ` 段,于是同一篇的目录里会留下上一代主名的条目文件。
962
+ * `renameDocument` 的 movePlan 只搬「当前主名 → 新主名」那一对,更早的孤儿没人管。
963
+ * 实测真实库:STALE / Mem0 / ClawVM 各多一份。
964
+ *
965
+ * 🔴 不能「删掉非现役的那份」了事:两份内容可能**不一样**(实测 Mem0 一份 status=reading、
966
+ * 另一份 status=read,added 也不同)。直接删等于静默丢用户的阅读状态。
967
+ * 所以先把孤儿里**现役没有的值**并进来,再删 —— 合并只补空、不覆盖。
968
+ *
969
+ * 🔴 **先提交、回读确认、再清理**。孤儿是那些标签 / 阅读状态 / 阅读位置的**唯一副本**,
970
+ * 先删后写的话,写一旦失败(磁盘满、现役是更新版本的格式、目录不可写)就再也拿不回来 ——
971
+ * 而且失败还会被一个空 `catch` 吞掉,调用方照样看到"合并成功"。实测:现役文件是
972
+ * `schemaVersion 2` 时,旧主名的条目已被删掉,而它带的独有标签一个都没迁过来。
973
+ *
974
+ * @param {string} path 现役条目路径(`itemPathOf` 的产物)
975
+ * @param {{warn?: Function}} [logger] 只在"该迁的迁不过去"时报一次(同一路径只报一次)
976
+ * @returns {Promise<object>} 合并后的条目视图
977
+ */
978
+ async function readItemSettling(path, logger) {
979
+ const live = await readItem(path)
980
+ const dir = dirname(path)
981
+ const liveName = path.slice(dir.length + 1)
982
+ let names = []
983
+ try { names = await readdir(dir) } catch { return live }
984
+ const orphans = []
985
+ for (const name of names) {
986
+ if (name === liveName || !name.endsWith('.item.json')) continue
987
+ orphans.push(join(dir, name))
988
+ }
989
+ if (orphans.length === 0) return live
990
+
991
+ let merged = live
992
+ let changed = false
993
+ for (const orphan of orphans) {
994
+ let stale
995
+ try { stale = await readItem(orphan) } catch { continue }
996
+ for (const key of ITEM_MERGE_KEYS) {
997
+ // 现役是默认值(未设置)而孤儿有值时,才从孤儿取。
998
+ if (!hasMeaningfulValue(merged[key]) && hasMeaningfulValue(stale[key])) {
999
+ merged = { ...merged, [key]: stale[key] }
1000
+ changed = true
1001
+ }
1002
+ }
1003
+ }
1004
+
1005
+ if (changed) {
1006
+ try {
1007
+ await writeItem(path, merged)
1008
+ } catch (error) {
1009
+ // 写不进去就一格都不删:孤儿是它们那些字段唯一的副本。
1010
+ // 返回值仍用合并后的视图 —— 用户看得见自己的数据,下次写入成功时会真正落盘。
1011
+ warnSettleOnce(logger, path, `条目合并写入失败,已保留旧条目文件:${errorText(error)}`)
1012
+ return merged
1013
+ }
1014
+ // 回读确认:写入走的是原子替换,成功即已落盘;这一步挡的是"以为写成了"。
1015
+ const confirmed = await readItem(path).catch(() => null)
1016
+ if (confirmed === null || ITEM_MERGE_KEYS.some(key => JSON.stringify(confirmed[key]) !== JSON.stringify(merged[key]))) {
1017
+ warnSettleOnce(logger, path, '条目合并后回读与预期不一致,已保留旧条目文件')
1018
+ return merged
1019
+ }
1020
+ }
1021
+
1022
+ for (const orphan of orphans) {
1023
+ try { await rm(orphan, { force: true }) } catch {}
1024
+ }
1025
+ return merged
1026
+ }
1027
+
1028
+ /**
1029
+ * 合并时从孤儿补的字段。其余字段各有各的盖章方(schemaVersion 由写侧收口、`added` 由
1030
+ * {@link writeItem} 盖),不在这张表里搬。
1031
+ */
1032
+ const ITEM_MERGE_KEYS = ['status', 'tags', 'starred', 'pinned', 'trashed', 'added', 'lastOpened', 'progress']
1033
+
1034
+ /**
1035
+ * 同一个条目文件只报一次:库列表每次刷新都会走一遍 {@link readItemSettling},
1036
+ * 一个永久写不进去的条目不该把日志刷成一片。
1037
+ */
1038
+ const settleWarned = new Set()
1039
+
1040
+ function warnSettleOnce(logger, path, message) {
1041
+ if (settleWarned.has(path)) return
1042
+ settleWarned.add(path)
1043
+ try { logger?.warn?.(`dsh-paper item: ${message}`) } catch {}
1044
+ }
1045
+
1046
+ /** 条目字段里「算得上有值」—— 默认值不算,避免把默认值当成用户的选择。 */
1047
+ function hasMeaningfulValue(value) {
1048
+ if (value === undefined || value === null) return false
1049
+ if (typeof value === 'string') return value !== '' && value !== 'unread'
1050
+ if (Array.isArray(value)) return value.length > 0
1051
+ if (typeof value === 'boolean') return value === true
1052
+ if (typeof value === 'object') return Object.keys(value).length > 0
1053
+ return true
1054
+ }
1055
+ const libraryItems = async () => {
1056
+ const documents = await rawDocuments()
1057
+ const items = new Array(documents.length)
1058
+ let cursor = 0
1059
+ // 限定四路文件读取;按原索引回填,完成先后不改变列表顺序。
1060
+ const readItems = async () => {
1061
+ while (cursor < documents.length) {
1062
+ const index = cursor++
1063
+ const raw = documents[index]
1064
+ const document = hydrateDocument(raw)
1065
+ const path = itemPathOf(runtimeRoot(config), raw)
1066
+ const item = path === '' ? normalizeItem(null) : await readItemSettling(path, ctx.logger)
1067
+ items[index] = {
1068
+ documentId: raw.id,
1069
+ kind: raw.kind,
1070
+ pdfName: typeof raw.pdfName === 'string' ? raw.pdfName : '',
1071
+ pdfPath: typeof raw.pdfPath === 'string' ? raw.pdfPath : '',
1072
+ markdownPath: typeof document.markdownPath === 'string' ? document.markdownPath : '',
1073
+ // 热记录才有这些;冷记录读完 manifest 也会带上。
1074
+ available: document.available !== false,
1075
+ title: document.title || raw.title || raw.pdfName || '',
1076
+ authors: document.authors ?? raw.authors ?? [],
1077
+ year: document.year ?? raw.year ?? '',
1078
+ // 用户工作区里那篇论文的文件夹(D128 之后 PDF 本体只在 runtime,这是原件位置唯一的记录)。
1079
+ // 冷记录同样可能有:它随记录一起进了 archive/。缺就空串,由回读面决定要不要挂这个键。
1080
+ sourceDir: typeof document.sourceDir === 'string' ? document.sourceDir
1081
+ : (typeof raw.sourceDir === 'string' ? raw.sourceDir : ''),
1082
+ sourcePdfPath: document.sourcePdfPath ?? raw.sourcePdfPath ?? '',
1083
+ // 能不能读:Markdown 存在且非空。**现 stat**,不信记录上的字段 —— 文件可能被删、被搬。
1084
+ // 代价是每篇一次 stat;同一轮里本来就要 readItem 读一次条目文件,stat 比它便宜一个量级。
1085
+ readable: await readableOf(document),
1086
+ bibliography: bibliographyOf(document.bibliography, document.metadata, document, raw),
1087
+ item,
1088
+ }
1089
+ }
1090
+ }
1091
+ const outcomes = await Promise.allSettled(Array.from({ length: Math.min(4, documents.length) }, readItems))
1092
+ const failure = outcomes.find(result => result.status === 'rejected')
1093
+ if (failure) throw failure.reason
1094
+ return items
1095
+ }
1096
+ const libraryService = createLibraryService({ path: libraryFile, items: libraryItems,
1097
+ // 跨实例那一层:界面 /library、集合服务、工具偏好动作全部落在同一把「library」锁上。
1098
+ withWrite: operation => repository.withNamedWrite('library', operation),
1099
+ itemPath: async id => {
1100
+ const raw = await libraryDocumentOf(id)
1101
+ return raw ? itemPathOf(runtimeRoot(config), raw) : ''
1102
+ } })
1103
+ const serializeLibrary = createSerialTail()
1104
+ const bibliographyService = createBibliographyService({ repository, allDocuments: rawDocuments, libraryService })
1105
+ // Mark actions read and replace one store; serialize them across reader tabs.
1106
+ const serializeMarks = createSerialTail()
1107
+ const checkImportCollection = async id => {
1108
+ if (id === undefined || id === null || id === '') return
1109
+ if (!(await serializeLibrary(() => libraryService.load())).collections.some(row => row.id === id)) throw new Error('目标集合不存在')
1110
+ }
1111
+ const libraryView = async () => {
1112
+ const library = await libraryService.load()
1113
+ const items = await libraryItems()
1114
+ return {
1115
+ library,
1116
+ items,
1117
+ readStatuses: READ_STATUSES,
1118
+ sortModes: SORT_MODES,
1119
+ maxCategories: MAX_CATEGORIES,
1120
+ // 内置视图桶的键。客户端左栏照它渲染固定分组,不自己编一套名单 ——
1121
+ // 名单只有一份(library.js 的 VIEW_KEYS),两边各写一份迟早对不上。
1122
+ viewKeys: VIEW_KEYS,
1123
+ }
1124
+ }
1125
+ /** 找到一篇论文的**原始**记录(热优先、冷兜底),与 /reader 同一口径。 */
1126
+ const libraryDocumentOf = async documentId => {
1127
+ const state = await repository.snapshot()
1128
+ const raw = await readerDocumentOf(state, documentId)
1129
+ return raw === undefined || raw === null ? null : raw
1130
+ }
1131
+
1132
+ // ---- token 用量账本(T24)----
1133
+ // 与 glossary 同位置、同口径:全局一份,不进 state.json(那个文件会被 compact() 重写)。
1134
+ // 采集点在 lib/translate.js(宿主每次调用发一个 usage chunk),这里只负责把它记进账本。
1135
+ const usageFile = usagePathOf(runtimeRoot(config))
1136
+ /**
1137
+ * 把一次整篇翻译的用量并入账本。
1138
+ *
1139
+ * 🔴 **读-改-写必须串行**:同一篇的两个批次、或两篇同时翻完时会并发调用,
1140
+ * 各自读到同一份旧账再各写一次,后写的那次会把前一次的记录整片抹掉(丢更新)。
1141
+ * 队列在结算时一次性回调,但这里不赌调用时序 —— 用一个 promise 链把写入排成一队。
1142
+ *
1143
+ * 记账失败**不影响翻译**:调用方(translate.js)已经把异常收成一行警告。
1144
+ *
1145
+ * 🔴 排队用 `createSerialTail`:尾链吞掉失败,返回的 promise 照旧 reject。
1146
+ * 两者混成一个(`tail = tail.then(...)`)时,一次写盘失败会让**后续每一次记账**都被跳过。
1147
+ */
1148
+ const enqueueUsage = createSerialTail()
1149
+ const recordUsage = (usage, meta) => {
1150
+ const jobId = String(meta?.jobId ?? '')
1151
+ const documentId = String(meta?.documentId ?? '')
1152
+ const model = meta?.model ?? {}
1153
+ return enqueueUsage(async () => {
1154
+ const store = await readUsage(usageFile)
1155
+ const next = mergeUsage(store, {
1156
+ jobId,
1157
+ documentId,
1158
+ provider: typeof model.provider === 'string' ? model.provider : '',
1159
+ model: typeof model.model === 'string' ? model.model : '',
1160
+ usage,
1161
+ })
1162
+ await writeUsage(usageFile, next)
1163
+ })
1164
+ }
1165
+
1166
+ const mineruKeyFile = mineruKeyPath(runtimeRoot(config))
1167
+ const mineruKeyView = async () => {
1168
+ const key = await readMineruKey(mineruKeyFile)
1169
+ return { configured: key !== '', maskedKey: maskMineruKey(key) }
1170
+ }
1171
+ const pickCacheDir = join(runtimeRoot(config), 'cache')
1172
+ const pickCacheReady = mkdir(pickCacheDir, { recursive: true }).catch(() => {})
1173
+ let pickInFlight = null
1174
+ let folderPickInFlight = null
1175
+ // 对话框的初始位置:调用方给的绝对路径优先,否则回落到该会话最近一轮的工作目录。
1176
+ const initialPickDir = body => (typeof body.dir === 'string' && isAbsolute(body.dir)
1177
+ ? body.dir
1178
+ : (validId(body.sessionId) ? sessionCwds.get(body.sessionId) : '') || '')
1179
+ // 扫描授权:/pick-folder 选定目录后签发一枚带 TTL 的凭据,/scan 必须用它换取一次扫描,
1180
+ // 且只能扫凭据绑定的那个目录。没有这层绑定,“只扫描用户显式选中的文件夹”就只是侧栏约定,
1181
+ // 任何能发同源请求的脚本都能拿任意绝对路径枚举 PDF 并整批推给按量计费的 MinerU。
1182
+ const scanGrants = new Map()
1183
+ // TTL 可用插件 config 覆盖(仅测试与排障用),非法值回落默认,不静默变成"永不过期"。
1184
+ const scanGrantTtlMs = Number.isInteger(config.scanGrantTtlMs) && config.scanGrantTtlMs > 0 ? config.scanGrantTtlMs : SCAN_GRANT_TTL_MS
1185
+ const mintScanGrant = dir => {
1186
+ const now = Date.now()
1187
+ for (const [token, grant] of scanGrants) if (grant.expiresAt <= now) scanGrants.delete(token)
1188
+ while (scanGrants.size >= MAX_SCAN_GRANTS) scanGrants.delete(scanGrants.keys().next().value)
1189
+ const token = randomUUID()
1190
+ scanGrants.set(token, { dir, expiresAt: now + scanGrantTtlMs })
1191
+ return token
1192
+ }
1193
+ // 用户主目录与磁盘根本身不该被整目录扫描(见 scanRiskOf);DSH 数据目录里还有会话与凭据。
1194
+ // 额外高危前缀可由 config 补:测试用它把某个临时目录判成高危,不必拿真盘根做实验。
1195
+ const riskyScanRoots = [
1196
+ ...(Array.isArray(config.scanRiskRoots) ? config.scanRiskRoots : []),
1197
+ { path: process.env.DSH_HOME || join(homedir(), '.dsh'), label: 'DSH 数据目录' },
1198
+ ]
1199
+ const repositoryReady = repository.recoverInterruptedJobs().then(async recovery => {
1200
+ const migration = await repository.migratePortableDocuments()
1201
+ for (const failure of migration.failures) {
1202
+ ctx.logger.warn(`dsh-paper manifest migration: 论文 ${failure.id} 迁移失败,保留原记录:${failure.error}`)
1203
+ }
1204
+ // D178:把"资产被劈成两套主名"的论文搬回记录那一套。必须在 compact 之前 —— 补上的
1205
+ // artifact.contentPath 要随记录一起落盘。自己吞掉异常:这是对账,不是启动前置条件,
1206
+ // 一次修不动不该把整个就绪链(续跑解析、解析清单)一起拖下水。
1207
+ try {
1208
+ await repository.repairSplitStems(ctx.logger)
1209
+ } catch (error) {
1210
+ ctx.logger.warn(`dsh-paper stem repair: ${errorText(error)}`)
1211
+ }
1212
+ await repository.compact()
1213
+ const outlineState = await repository.snapshot()
1214
+ const outlineMigration = await documentReader.migrateOutlines(await rawDocuments(), outlineState.settings.outlineBudgetBytes)
1215
+ for (const failure of outlineMigration.failures) ctx.logger.warn(`dsh-paper outline migration: ${failure.id}: ${failure.error}`)
1216
+ // Scratch left behind by jobs whose record has already been trimmed out of the terminal
1217
+ // window has no owner left to delete it, so startup reconciliation reclaims it.
1218
+ const orphans = await resolver.pruneOrphanScratch()
1219
+ if (orphans > 0) ctx.logger.info(`dsh-paper scratch prune: 回收了 ${orphans} 个没有任务记录的临时输出目录`)
1220
+ // 排队中(从未开始)的任务在重启后继续:它们还没提交给远端,重排不会重复计费。
1221
+ // resumable 是两种 kind 混在一起的 id,分流必须重新读一次记录 —— 只按 id 排队会把
1222
+ // 翻译任务塞进解析池,由解析 worker 去读一条它根本不认识的记录。
1223
+ const resumable = recovery?.resumable ?? []
1224
+ // 快照只读一次:整目录扫描留下的排队任务可能上百条,逐条 snapshot 会把 state.json 读上百遍。
1225
+ const resumableState = resumable.length > 0 ? await repository.snapshot() : undefined
1226
+ let resumedParses = 0
1227
+ for (const jobId of resumable) {
1228
+ const job = resumableState.jobs[jobId]
1229
+ if (jobKindOf(job) === 'translate') {
1230
+ // 翻译队列在 T12 落地,这里只留**这一处**接线点:给了钩子就交给它,没给就记一行
1231
+ // 日志,绝不报错也绝不丢弃 —— 被丢掉的 id 会连同它的 queued 状态一起烂在 state.json 里。
1232
+ if (typeof config.resumeTranslate === 'function') await config.resumeTranslate(jobId)
1233
+ else await resumeTranslation(jobId).catch(error => ctx.logger.warn(`dsh-paper translate: 续跑 ${jobId} 失败:${errorText(error)}`))
1234
+ continue
1235
+ }
1236
+ resolver.enqueue(jobId)
1237
+ resumedParses += 1
1238
+ }
1239
+ if (resumedParses > 0) ctx.logger.info(`dsh-paper recovery: 继续 ${resumedParses} 个排队中的解析任务`)
1240
+ // 右栏「解析」Tab 的清单与 state.json 无关,自己读自己对账(queued 续跑、running 判中断)。
1241
+ // 放在同一个就绪链里:两者都要等 MinerU 配置与并发池可用,且都要在首个请求之前完成。
1242
+ await parseExport.start()
1243
+ }).catch(error => {
1244
+ ctx.logger.warn(`dsh-paper recovery: ${errorText(error)}`)
1245
+ })
1246
+
1247
+ // Disposal joins the persisted settlement, including compaction after the terminal state write.
1248
+ ctx.effect?.(() => async () => {
1249
+ stoppingTranslations = true
1250
+ await repositoryReady
1251
+ translateQueue.pauseAll()
1252
+ await Promise.allSettled(translateQueue.trackedIds().map(id => translateQueue.cancel(id, '论文插件已停止,翻译已取消')))
1253
+ while (translationSettlements.size > 0) await Promise.all([...translationSettlements])
1254
+ // 🔴 **解析也要接管**(HMR / 禁用插件)。过去这里只结算翻译:dispose 已经完成时解析任务仍
1255
+ // 是 running,等 SDK 边界放开后,已经被替换掉的旧实例继续发布并写成 ready —— 与新实例的
1256
+ // 启动恢复判断(running → 判中断)打架。两条队列各自停新提交、等在飞的收尾,之后旧实例
1257
+ // 的任何发布都不再写入(解析池会在超时后关闭;超时没跑完的结果丢弃,日志里说明)。
1258
+ try {
1259
+ const stopped = await resolver.stop()
1260
+ if (!stopped.drained) ctx.logger.warn(`dsh-paper stop: 解析池仍有 ${stopped.active} 个任务在飞,已进入关闭状态`)
1261
+ } catch (error) {
1262
+ ctx.logger.warn(`dsh-paper stop: 停止解析池失败:${errorText(error)}`)
1263
+ }
1264
+ try {
1265
+ await parseExport.stop()
1266
+ } catch (error) {
1267
+ ctx.logger.warn(`dsh-paper stop: 停止独立解析队列失败:${errorText(error)}`)
1268
+ }
1269
+ await repository.tail
1270
+ })
1271
+
1272
+ const scheduleSelectionSweep = createSweepScheduler({
1273
+ minimumIntervalMs: SELECTION_SWEEP_MIN_INTERVAL_MS,
1274
+ ready: repositoryReady,
1275
+ run: () => pruneStaleSelections(repository, ctx.sessionPersistence, ctx.logger),
1276
+ onError: error => ctx.logger.warn(`dsh-paper selection sweep: ${errorText(error)}`),
1277
+ })
1278
+ scheduleSelectionSweep()
1279
+
1280
+ ctx.on('session/event', (session, event) => {
1281
+ if (event?.type !== 'user/message' || !isProducerSource(event.data?.source, name)) return
1282
+ const delivered = deliveredPaperState({ snapshotEvents: () => [event] })
1283
+ if (!event.data.source.sections?.some(section => section?.name === 'dsh-paper-state')) return
1284
+ void repository.update(state => {
1285
+ const current = state.selections[session.id] ?? { desired: [], delivered: [] }
1286
+ state.selections[session.id] = {
1287
+ ...current,
1288
+ delivered: delivered.active,
1289
+ deliveredUnavailable: delivered.unavailable,
1290
+ }
1291
+ }).catch(error => ctx.logger.warn(`dsh-paper delivery state: ${errorText(error)}`))
1292
+ })
1293
+
1294
+ ctx.on('agent/pre-step', async ({ agent, step, signal }, next) => {
1295
+ const decision = await next()
1296
+ if (decision === undefined || decision.kind === 'reject' || step !== 1 || signal?.aborted) return decision
1297
+ const session = agent?.session
1298
+ if (!session || !validId(String(session.id))) return decision
1299
+ if (isAbsolute(session.header?.cwd ?? '')) sessionCwds.remember(String(session.id), session.header.cwd)
1300
+ try {
1301
+ await repositoryReady
1302
+ const state = await repository.snapshot()
1303
+ const selection = selectionView(state, String(session.id))
1304
+ const deliveredState = deliveredPaperState(session)
1305
+ const documents = new Map()
1306
+ for (const id of new Set([...selection.desired, ...deliveredState.active, ...deliveredState.unavailable])) {
1307
+ const document = state.documents[id]
1308
+ documents.set(id, document
1309
+ ? await documentReader.usableDocument(document, state.settings.outlineBudgetBytes)
1310
+ : { id, pdfName: id, markdownPath: '', unavailable: true })
1311
+ }
1312
+ const message = buildContextMessage({
1313
+ desiredIds: selection.desired,
1314
+ deliveredState,
1315
+ documents,
1316
+ id: randomUUID(),
1317
+ contextBudgetBytes: state.settings.contextBudgetBytes,
1318
+ })
1319
+ if (!message) return decision
1320
+ return { ...decision, messages: [message, ...(decision.messages ?? [])] }
1321
+ } catch (error) {
1322
+ ctx.logger.warn(`dsh-paper context: ${errorText(error)}`)
1323
+ return decision
1324
+ }
1325
+ }, { prepend: true })
1326
+
1327
+ /**
1328
+ * 把一批论文挂到会话侧栏:整批一次状态写入。
1329
+ *
1330
+ * 逐篇 attach 会在 state.json 最大的时候(任务已全部入队)多写 N 遍全量状态,实测 300 篇
1331
+ * 里约三分之一的时间花在这上面;关联动作本身没有单篇成败的差别,合成一次也就能一次失败,
1332
+ * 那时如实报"这批都没挂上"比逐篇伪造独立成败更准。
1333
+ */
1334
+ async function attachDocumentsToSession(sessionId, documentIds) {
1335
+ if (documentIds.length === 0) return
1336
+ await repository.update(state => {
1337
+ for (const documentId of documentIds) attachDocument(state, sessionId, documentId)
1338
+ })
1339
+ }
1340
+
1341
+ /**
1342
+ * 添加一篇 PDF 并把结果挂到会话侧栏:`/add` 与 `/scan` 走同一对动作(解析/入队 → 关联会话)。
1343
+ *
1344
+ * 关联失败与解析/入队失败必须分开返回:走到关联这一步时任务已经入队、远端可能已经受理并按量
1345
+ * 计费,把它混进"没能添加"会让用户以为无事发生——而那篇论文在面板里既看不见,又因为
1346
+ * `hidden:false` 不会被 compact 回收。调用方拿到 `attachError` 要如实说"已入队但没显示"。
1347
+ */
1348
+ async function addPdfToSession(pdfPath, sessionId) {
1349
+ const result = await resolver.add(pdfPath, sessionId)
1350
+ const documentId = result.document?.id ?? result.job?.documentId
1351
+ if (typeof documentId !== 'string') return { result, attachError: '解析结果缺少论文 ID,未能挂到侧栏' }
1352
+ try {
1353
+ await attachDocumentsToSession(sessionId, [documentId])
1354
+ } catch (error) {
1355
+ return { result, attachError: errorText(error) }
1356
+ }
1357
+ return { result }
1358
+ }
1359
+
1360
+ /**
1361
+ * 把一篇论文排进翻译队列,并在队列结算后把任务记录改成终态。
1362
+ *
1363
+ * 🔴 **不 await 队列的 promise**:它要等整篇跑完(可能十几分钟),HTTP 请求不能挂在那里。
1364
+ * 结算由 `.then` 收尾 —— 失败也必须收尾,否则记录永远停在 running,侧栏那条卡片就再也动不了。
1365
+ *
1366
+ * @param {object} job state.jobs 里的翻译任务记录
1367
+ * @param {object} document 已 hydrate 的文档记录
1368
+ * @param {object} body /translate 的请求体(scope / incremental / translateAll / batchPages)
1369
+ */
1370
+ /**
1371
+ * 重启后续跑一条翻译任务。
1372
+ *
1373
+ * 必须重新 hydrate 文档记录:document 在 state.json 里是相对形态,直接拿来用会拼出
1374
+ * 一个不存在的 Markdown 路径。默认走增量 —— 已译好的块在断点里,全量重译等于让用户
1375
+ * 为同样的内容再付一次模型费用。
1376
+ */
1377
+ async function resumeTranslation(jobId) {
1378
+ const state = await repository.snapshot()
1379
+ const job = state.jobs[jobId]
1380
+ if (job === undefined || jobKindOf(job) !== 'translate') return
1381
+ const raw = state.documents[job.documentId] ?? await repository.archivedDocument(job.documentId)
1382
+ if (raw === undefined || raw === null) {
1383
+ await settleTranslation(jobId, { status: 'failed', error: '论文记录已不在,无法续跑' })
1384
+ return
1385
+ }
1386
+ await startTranslation(job, hydrateDocument(raw), { incremental: true })
1387
+ }
1388
+ /** 把设置里的范围三档折成 selectScope 认识的 options(D68)。 */
1389
+ function translationScopeOf(settings) {
1390
+ const mode = TRANSLATION_SCOPES.includes(settings?.translationScope) ? settings.translationScope : 'pages'
1391
+ if (mode !== 'pages') return { mode }
1392
+ const pages = Number.isInteger(settings?.translationPages) && settings.translationPages > 0 ? settings.translationPages : 20
1393
+ return { mode: 'pages', pageFrom: 1, pageTo: pages }
1394
+ }
1395
+
1396
+ /**
1397
+ * 把一篇论文排进自动翻译(D67 的执行体,D73 定的触发点是「文献库中打开文献」)。
1398
+ *
1399
+ * 🔴 现在**没有**任何生产路径默认调它:解析完成那条被 `config.autoTranslateOnParse`
1400
+ * 挡着(默认 false,见 D73)。T21 文献库落地时,把「打开文献」事件接到这里即为终态。
1401
+ *
1402
+ * 设置关了就整篇跳过;模型解析不到时也跳过并记一行 —— 那会让用户看到「没翻但其实成功了」,
1403
+ * 所以这里必须响一声。
1404
+ */
1405
+ async function autoTranslate(document, sessionId) {
1406
+ const state = await repository.snapshot()
1407
+ if (state.settings?.translationAuto !== true) return { skipped: 'auto-off' }
1408
+ // 宿主没有可用的 llm 服务时同样整篇跳过,理由与上面那条一致:排进队列只会在下一次调度里
1409
+ // 被 runBatch 的开头判死,用户看到的是「已开始」紧跟一张失败卡片,中间什么都没发生过。
1410
+ // 响应里那声 reason 就是给这种情况用的。
1411
+ if (typeof (translateHostOptions() ?? {}).llm?.prepareCall !== 'function') return { skipped: 'no-llm' }
1412
+ // 🔴 已经在翻这一篇了:直接说一声就走,**不建任务记录**(D157)。
1413
+ // 不预判的后果实测过:先写一条 queued 记录,紧接着 enqueue 抛「已在队列中」,
1414
+ // 那条记录被就地结清成 failed —— 一篇**正在正常翻译**的论文因此在侧栏多出一张
1415
+ // 「翻译失败:任务 … 已在队列中,不能重复入队」的卡片。同一篇留下过 7 条。
1416
+ if (translateQueue.has(document.id)) return { skipped: 'already-queued' }
1417
+ // 🔴 已经译完了就**不要再排一次**(D157)。文献库里每打开一篇都会走到这里,而增量翻一篇
1418
+ // 已译完的论文一个块都不需要翻 —— 排进去只会产出零译出的空任务,用户看到的是
1419
+ // 「都翻译完了为什么还有排队」。判据与真正翻译时**同一套**(planTranslation +
1420
+ // pendingForIncremental),所以这里说"没得翻"时,真跑一遍也确实是零个块。
1421
+ const scope = translationScopeOf(state.settings)
1422
+ const pending = await translationPendingOf(document, scope)
1423
+ if (pending.error === '' && pending.pending === 0) return { skipped: 'already-translated' }
1424
+ const hydrated = hydrateDocument(document)
1425
+ const job = {
1426
+ id: `job-${randomUUID()}`,
1427
+ kind: 'translate',
1428
+ documentId: document.id,
1429
+ sessionId,
1430
+ pdfPath: hydrated.pdfPath,
1431
+ pdfName: hydrated.pdfName,
1432
+ status: 'queued',
1433
+ error: '',
1434
+ createdAt: new Date().toISOString(),
1435
+ updatedAt: new Date().toISOString(),
1436
+ }
1437
+ await repository.update(current => { current.jobs[job.id] = job })
1438
+ // 复用上面算好的 scope:同一个快照里现算两次没有意义,两次之间用户改了设置
1439
+ // 只会让"判定要不要翻"与"实际翻哪些"用的是两个范围。
1440
+ return startTranslation(job, hydrated, { scope, incremental: true })
1441
+ }
1442
+
1443
+ /**
1444
+ * 一篇论文在 scope 下**还有多少块没译、已经译了多少块**(D177 的一键翻译靠它决定哪几篇要排队)。
1445
+ *
1446
+ * 判据与 autoTranslate 的 already-translated 分支完全同源(planTranslation + pendingForIncremental),
1447
+ * 所以这里报 0 时真排一遍也确实是零个块、零笔开销。
1448
+ *
1449
+ * @returns {Promise<{pending: number, translated: number, total: number, error: string}>} error 非空 = 这篇现在翻不了(缺 Markdown / 缺块列表)。
1450
+ */
1451
+ async function translationPendingOf(document, scope) {
1452
+ const planned = await planTranslation({ document, scope })
1453
+ if (planned.error !== undefined) return { pending: 0, translated: 0, total: 0, error: planned.error }
1454
+ const pending = pendingForIncremental(planned.blocks, planned.existing)
1455
+ let translated = 0
1456
+ for (const block of planned.blocks) {
1457
+ const id = typeof block?.id === 'string' ? block.id : ''
1458
+ if (id === '') continue
1459
+ const zh = planned.existing?.[id]?.zh
1460
+ if (typeof zh === 'string' && zh.trim() !== '') translated += 1
1461
+ }
1462
+ return { pending: pending.length, translated, total: planned.blocks.length, error: '' }
1463
+ }
1464
+
1465
+ /**
1466
+ * 重排**已经失败**的翻译(D179)。
1467
+ *
1468
+ * 🔴 为什么不是"重试那条记录":一条翻译任务的失败**不会**让它所属的论文变成"没译完"——
1469
+ * pendingForIncremental 只看译文里有没有那一块,失败块照旧算没译。所以真正要做的事
1470
+ * 与一键翻译完全相同(把还没译的块排上),差别只在**范围**:只挑现在挂着 failed 记录的论文。
1471
+ * 另起一条重试通道会让"失败"与"重排"两套判据各说各话,最后总有一边对不上。
1472
+ *
1473
+ * 单篇用 documentId;不给就取范围里所有还挂着 failed 翻译记录的论文。
1474
+ */
1475
+ async function retryFailedTranslations(sessionId, documentId) {
1476
+ const snapshot = await repository.snapshot()
1477
+ const scope = translationScopeOf(snapshot.settings)
1478
+ let targets = []
1479
+ // 每篇最新的那条翻译记录:单篇形态从 snapshot 里找,会话形态顺手就在 latestJob 里。
1480
+ // 「其实已经译完」的失败记录要靠它结案(见下面 pending === 0 分支)。
1481
+ const latestJob = new Map()
1482
+ if (typeof documentId === 'string' && documentId !== '') {
1483
+ targets = [documentId]
1484
+ for (const job of Object.values(snapshot.jobs)) {
1485
+ if (jobKindOf(job) !== 'translate' || job.documentId !== documentId) continue
1486
+ const seen = latestJob.get(documentId)
1487
+ if (seen === undefined || String(job.createdAt ?? '') > String(seen.createdAt ?? '')) latestJob.set(documentId, job)
1488
+ }
1489
+ } else {
1490
+ const attached = new Set(selectionView(snapshot, sessionId).documentIds)
1491
+ for (const job of Object.values(snapshot.jobs)) {
1492
+ if (jobKindOf(job) !== 'translate') continue
1493
+ // 🔴 范围与 /state 里「需手动重试 N」的统计同源(sessionId 匹配 **或** 在侧栏)。
1494
+ // 曾经只认侧栏:统计把「带本会话 sessionId、但论文已被移出侧栏」的失败也数进去,
1495
+ // 动作却够不着它们 —— 实测 3 篇全军覆没,targets 空、queued=0,点按钮毫无反应。
1496
+ if (job.sessionId !== sessionId && !attached.has(job.documentId)) continue
1497
+ const seen = latestJob.get(job.documentId)
1498
+ if (seen === undefined || String(job.createdAt ?? '') > String(seen.createdAt ?? '')) latestJob.set(job.documentId, job)
1499
+ }
1500
+ targets = [...latestJob.values()].filter(job => RETRYABLE_JOB_STATUSES.includes(job.status)).map(job => job.documentId)
1501
+ }
1502
+ const failures = []
1503
+ const entries = await mapWithConcurrency(targets, BATCH_TRANSLATE_CONCURRENCY, id => translationBatchEntry(snapshot, id, scope))
1504
+ const probed = entries.map((result, index) => (result.ok ? result.value : { documentId: targets[index], pdfName: '', document: undefined, pending: 0, translated: 0, total: 0, error: result.error }))
1505
+ const planned = []
1506
+ const settled = []
1507
+ let unchanged = 0
1508
+ for (const entry of probed) {
1509
+ if (entry.error !== '') { failures.push({ documentId: entry.documentId, pdfName: entry.pdfName, error: entry.error }); continue }
1510
+ if (entry.pending === 0) {
1511
+ unchanged += 1
1512
+ // 「失败」只是那一次的结论:这篇现在没有待译块了(后来补齐了,或原文变了)。
1513
+ // 记录不结案的话,统计永远显示「需手动重试 N」,而按钮每次都判"已翻完" —— 死循环。
1514
+ const job = latestJob.get(entry.documentId)
1515
+ if (job !== undefined && job.status !== 'ready') settled.push(job.id)
1516
+ continue
1517
+ }
1518
+ planned.push(entry)
1519
+ }
1520
+ // 与 /translate-batch 同一口径:预检在**建记录之前**,整批只写一次 state.json。
1521
+ const queueable = planned.filter(entry => !translateQueue.has(entry.documentId))
1522
+ let skipped = planned.length - queueable.length
1523
+ const jobs = queueable.map(entry => ({ id: `job-${randomUUID()}`, kind: 'translate', documentId: entry.documentId, sessionId: sessionId ?? '', pdfPath: hydrateDocument(entry.document).pdfPath, pdfName: entry.pdfName, status: 'queued', error: '', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }))
1524
+ if (jobs.length > 0 || settled.length > 0) {
1525
+ await repository.update(current => {
1526
+ for (const job of jobs) current.jobs[job.id] = job
1527
+ // 结案:这篇已经没有待译块,那条 failed 记录只是历史结论,留着会让统计永远显示「需手动重试」。
1528
+ for (const id of settled) {
1529
+ const job = current.jobs[id]
1530
+ if (job === undefined) continue
1531
+ job.status = 'ready'
1532
+ job.error = ''
1533
+ job.updatedAt = new Date().toISOString()
1534
+ }
1535
+ })
1536
+ }
1537
+ let queued = 0
1538
+ let queuedBlocks = 0
1539
+ for (let index = 0; index < queueable.length; index += 1) {
1540
+ const entry = queueable[index]
1541
+ try {
1542
+ await startTranslation(jobs[index], hydrateDocument(entry.document), { scope, incremental: true })
1543
+ queued += 1
1544
+ queuedBlocks += entry.pending
1545
+ } catch (error) {
1546
+ if (error?.reason === 'already-queued') { skipped += 1; continue }
1547
+ await settleTranslation(jobs[index].id, { status: 'failed', error: errorText(error) })
1548
+ failures.push({ documentId: entry.documentId, pdfName: entry.pdfName, error: errorText(error) })
1549
+ }
1550
+ }
1551
+ if (queued > 0) { try { await repository.compact() } catch { /* 整理失败不影响已排队的任务 */ } }
1552
+ return { scanned: targets.length, queued, blocks: queuedBlocks, unchanged, skipped, failures }
1553
+ }
1554
+
1555
+ /**
1556
+ * 一键翻译(D177)的单篇探测:这一篇是谁、还有多少块没译、已译多少、翻不了的话为什么。
1557
+ *
1558
+ * 用 readerDocumentOf 而不是直接查 state.documents —— 冷论文(已归档、不在热表里)同样要能翻,
1559
+ * 而八条论文路由共用这一处查找(见 readerDocumentOf 的注释)。
1560
+ *
1561
+ * @returns {Promise<{documentId: string, pdfName: string, document: object|undefined, pending: number, translated: number, total: number, error: string}>}
1562
+ */
1563
+ async function translationBatchEntry(snapshot, documentId, scope) {
1564
+ const document = await readerDocumentOf(snapshot, documentId)
1565
+ if (!document) return { documentId, pdfName: '', document: undefined, pending: 0, translated: 0, total: 0, error: '论文已被移除' }
1566
+ const pdfName = typeof document.pdfName === 'string' ? document.pdfName : ''
1567
+ const counts = await translationPendingOf(document, scope)
1568
+ return { documentId, pdfName, document, pending: counts.pending, translated: counts.translated, total: counts.total, error: counts.error }
1569
+ }
1570
+
1571
+ /**
1572
+ * 建一条 translate 任务记录并把它排进队列。
1573
+ *
1574
+ * 抽出来给「一键翻译」(D177)用:批量那条路要按同一个口径入队,否则 /translate 与它
1575
+ * 迟早漂移成两种行为(一边先建记录、一边先判队列)。
1576
+ *
1577
+ * @returns {Promise<{started: boolean, reason?: string, result?: object}>}
1578
+ * started=false 只可能是 already-queued —— 那是**预期状态**,不是故障(D157)。
1579
+ */
1580
+ async function beginTranslation(documentId, hydrated, sessionId, body = {}) {
1581
+ const job = {
1582
+ id: `job-${randomUUID()}`,
1583
+ kind: 'translate',
1584
+ documentId,
1585
+ sessionId,
1586
+ pdfPath: hydrated.pdfPath,
1587
+ pdfName: hydrated.pdfName,
1588
+ status: 'queued',
1589
+ error: '',
1590
+ createdAt: new Date().toISOString(),
1591
+ updatedAt: new Date().toISOString(),
1592
+ }
1593
+ await repository.update(current => { current.jobs[job.id] = job })
1594
+ try {
1595
+ return { started: true, result: await startTranslation(job, hydrated, body) }
1596
+ } catch (error) {
1597
+ // 预检与入队之间的竞态窗口(连点、或撞上 /open 的自动翻译):startTranslation 已经
1598
+ // 把那条第 409 版的记录撤掉了,这里收成与预检同一个结果,调用方按良性处理。
1599
+ if (error?.reason === 'already-queued') return { started: false, reason: 'already-queued' }
1600
+ throw error
1601
+ }
1602
+ }
1603
+
1604
+ async function startTranslation(job, document, body = {}) {
1605
+ // 并发数与输出协议都从**当前设置**现算(D136 / D138):用户在设置页改完,下一个任务就按新的走。
1606
+ const settings = (await repository.snapshot()).settings
1607
+ // 🔴 全局闸门的上限也在每次入队时刷新(D157)。设置页那个数答的是"同时几个模型请求",
1608
+ // 与这里现算的批次并发**是同一个数**;闸门是唯一真正限流的那一层。
1609
+ translationGate.setLimit(concurrencyOf(settings))
1610
+ const batch = {
1611
+ document,
1612
+ // 记账要用它当幂等键(见 runBatch 的 onUsage)。队列只认 batches 数组的形状,
1613
+ // 多带两个自己的字段不影响它 —— 它从头到尾只把 batch 原样回调给 runBatch。
1614
+ jobId: job.id,
1615
+ documentId: document.id,
1616
+ model: await resolveTranslationModel(),
1617
+ scope: body.scope === undefined ? undefined : { mode: body.scope.mode, pageFrom: body.scope.pageFrom, pageTo: body.scope.pageTo },
1618
+ incremental: body.incremental === true,
1619
+ translateAll: body.translateAll === true,
1620
+ batchPages: Number.isInteger(body.batchPages) && body.batchPages > 0 ? body.batchPages : undefined,
1621
+ // 目标语言(D140):请求体可覆盖(脚本用),否则按设置页那一档。
1622
+ targetLanguage: typeof body.targetLanguage === 'string' && body.targetLanguage !== '' ? body.targetLanguage : settings.translationLanguage,
1623
+ protocol: protocolOf(settings),
1624
+ // 同一个「并发」数同时管两层:队列的跨文档并发(下面 enqueue 的 options)与
1625
+ // 单篇内的批次并发(runBatch → translateDocument)。用户在设置页调的就是"同时几个请求"。
1626
+ concurrency: concurrencyOf(settings),
1627
+ }
1628
+ let queued
1629
+ if (stoppingTranslations) throw new Error('论文插件正在停止,翻译任务留待下次启动。')
1630
+ try {
1631
+ // 🔴 **不 await 这个 promise**:它要等整篇翻译跑完(可能十几分钟),HTTP 请求不能挂在那里。
1632
+ // 结算由 .then 收尾;失败也必须收尾,否则记录永远停在 queued,侧栏那条卡片再也动不了。
1633
+ queued = translateQueue.enqueue(document.id, [batch], { concurrency: concurrencyOf(settings) })
1634
+ } catch (error) {
1635
+ // 🔴 重复入队 = **另一条任务正在正常翻译这一篇**,不是这篇坏了(D157)。
1636
+ // 这条刚建的记录必须**撤掉**而不是标成 failed —— 标成 failed 会在侧栏渲染成
1637
+ // 「需手动重试」,把一篇好论文报成需要人工介入。请求本身照旧 409,让调用方知道自己没排上。
1638
+ if (translateQueue.has(document.id)) {
1639
+ await repository.update(current => { delete current.jobs[job.id] })
1640
+ await repository.compact()
1641
+ // 给调用方一个**可判定的**标记,而不是让它去正则匹配那句中文。
1642
+ // 这是预检与入队之间的竞态窗口留下的唯一线索(见 /open 的 catch)。
1643
+ error.reason = 'already-queued'
1644
+ } else {
1645
+ // 其余入队当场失败(批次不合法):记录落失败,不留一条卡在 queued 的幽灵。
1646
+ await settleTranslation(job.id, { status: 'failed', error: errorText(error) })
1647
+ }
1648
+ error.status = 409
1649
+ throw error
1650
+ }
1651
+ trackTranslationSettlement(queued.then(
1652
+ summary => settleTranslation(job.id, summaryOutcome(summary)),
1653
+ error => settleTranslation(job.id, { status: 'failed', error: errorText(error) }),
1654
+ ))
1655
+ return { taskId: document.id, jobId: document.id, job: job.id, state: translateQueue.stats(document.id) }
1656
+ }
1657
+
1658
+ /** 把队列的结算摘要折成任务记录的终态字段。 */
1659
+ function summaryOutcome(summary) {
1660
+ if (summary?.cancelled === true) return { status: 'interrupted', error: '翻译已取消' }
1661
+ const failed = summary?.results?.filter(entry => entry.status === 'failed') ?? []
1662
+ if (failed.length > 0 && (summary?.completed ?? 0) === 0) {
1663
+ return { status: 'failed', error: failed[0]?.error ?? '翻译失败' }
1664
+ }
1665
+ return { status: 'ready', error: '' }
1666
+ }
1667
+
1668
+ /** 写回翻译任务的终态(status / error / 计数 / updatedAt),顺带整理一次状态文件。 */
1669
+ async function settleTranslation(jobId, outcome) {
1670
+ await repository.update(state => {
1671
+ const current = state.jobs[jobId]
1672
+ if (!current) return
1673
+ current.status = outcome.status
1674
+ current.error = outcome.error ?? ''
1675
+ current.updatedAt = new Date().toISOString()
1676
+ if (outcome.completed !== undefined) current.completed = outcome.completed
1677
+ if (outcome.failed !== undefined) current.failed = outcome.failed
1678
+ })
1679
+ await repository.compact()
1680
+ }
1681
+
1682
+ /**
1683
+ * 翻译用的模型路由。设置里给了 provider/model 就用它;否则跟随宿主的默认 agent 模型。
1684
+ *
1685
+ * 🔴 取不到时**不抛错**:返回 undefined,由 translateBatch 的 prepareCall 去报「模型不可用」——
1686
+ * 那一层离失败点更近,文案也更准(这里抛只会让用户看到一个没有上下文的 500)。
1687
+ */
1688
+ /**
1689
+ * 供插件详情页的模型下拉用(D72)。
1690
+ *
1691
+ * 🔴 客户端半碰不到 `ctx.llm`,所以「有哪些模型可选」只能由宿主这边列。
1692
+ * 取不到 llm 服务时返回空列表 + default:null,前端按「只能跟随默认」渲染,不报错。
1693
+ */
1694
+ async function translationModelsView() {
1695
+ const models = []
1696
+ const seen = new Set()
1697
+ try {
1698
+ const llm = ctx.get('llm')
1699
+ const providers = typeof llm?.listProviders === 'function' ? (llm.listProviders() ?? []) : []
1700
+ for (const provider of providers) {
1701
+ const id = typeof provider === 'string' ? provider : provider?.id
1702
+ if (typeof id !== 'string' || id === '') continue
1703
+ const owned = typeof llm?.listModels === 'function' ? (await llm.listModels(id)) ?? [] : []
1704
+ for (const model of owned) {
1705
+ const key = `${id}/${model?.id}`
1706
+ if (seen.has(key)) continue
1707
+ seen.add(key)
1708
+ models.push({ provider: id, model: model?.id, name: model?.name ?? model?.id })
1709
+ }
1710
+ }
1711
+ } catch (error) {
1712
+ ctx.logger.warn(`dsh-paper translate: 列出模型失败:${errorText(error)}`)
1713
+ }
1714
+ let fallback = null
1715
+ try {
1716
+ const selection = ctx.get('agentDefaultModel')?.currentSelection?.()
1717
+ if (selection !== null && typeof selection === 'object' && typeof selection.provider === 'string' && typeof selection.model === 'string') {
1718
+ fallback = { provider: selection.provider, model: selection.model }
1719
+ }
1720
+ } catch { /* 取不到就只给空列表 */ }
1721
+ // 目标语言选项也在这里下发:客户端不抄一份白名单,免得两边漂移(D140)。
1722
+ return { models, default: fallback, languages: TRANSLATION_LANGUAGES }
1723
+ }
1724
+
1725
+ async function resolveTranslationModel() {
1726
+ const state = await repository.snapshot()
1727
+ const configured = state.settings?.translationModel
1728
+ if (configured !== null && typeof configured === 'object') {
1729
+ const provider = typeof configured.provider === 'string' ? configured.provider : ''
1730
+ const model = typeof configured.model === 'string' ? configured.model : ''
1731
+ if (provider !== '' && model !== '') return { provider, model }
1732
+ }
1733
+ try {
1734
+ const selection = ctx.get('agentDefaultModel')?.currentSelection?.()
1735
+ if (selection !== null && typeof selection === 'object' && typeof selection.provider === 'string' && typeof selection.model === 'string') {
1736
+ return { provider: selection.provider, model: selection.model }
1737
+ }
1738
+ } catch (error) {
1739
+ ctx.logger.warn(`dsh-paper translate: 读取默认模型失败:${errorText(error)}`)
1740
+ }
1741
+ return undefined
1742
+ }
1743
+
1744
+ /**
1745
+ * 按 documentId 找当前在跑的那条翻译任务记录。
1746
+ *
1747
+ * 队列的 taskId 用的是 documentId,而 state.jobs 的记录 id 是 job-<uuid> —— 两套 id 必须
1748
+ * 在这里对齐一次,否则取消/结算会写到一条不存在的记录上(静默丢更新)。
1749
+ * @returns {Promise<object|null>} 那条记录,找不到时为 null。
1750
+ */
1751
+ async function findTranslationJob(documentId) {
1752
+ const state = await repository.snapshot()
1753
+ const jobs = Object.values(state.jobs).filter(job => job.documentId === documentId)
1754
+ if (jobs.length === 0) return null
1755
+ // 同一篇可能有历史记录(重试过)。取最新的那条 —— createdAt 相同则看 id 兜底。
1756
+ return jobs.sort((left, right) => String(right.createdAt ?? '').localeCompare(String(left.createdAt ?? '')) || String(right.id).localeCompare(String(left.id)))[0]
1757
+ }
1758
+
1759
+ /**
1760
+ * 阅读器/打开动作要的那篇论文:先找热记录,再回冷归档。
1761
+ *
1762
+ * `/state` 只渲染热记录,所以侧栏里点得到的一定在热表里;一次宿主重启之外的进程
1763
+ * (或 compact 刚把它挪进 archive/)会留下"卡片还在、热记录没了"的窗口期。docs 的
1764
+ * 同一条路径(resumeTranslation)就是这么兜的,这里保持一致:能按 id 读回来的论文
1765
+ * 就不该报 404。
1766
+ *
1767
+ * @returns {Promise<object|undefined>} 原始(未 hydrate)的文档记录。
1768
+ */
1769
+ async function readerDocumentOf(state, documentId) {
1770
+ const hot = state.documents[documentId]
1771
+ if (hot !== undefined) return hot
1772
+ // 🔴 冷归档的路径是按 **64 位十六进制** 拼的,repository.archivedDocument 对别的形状直接抛
1773
+ // (archivePath 里的 ID 校验)。而 validId 只查字符集,'not-a-hash' 这类能过它 ——
1774
+ // 于是任何一条带非哈希 documentId 的请求都会变成 500。这里先按同一条形状收口:
1775
+ // 不是哈希就根本没有冷记录可找,直接当"不存在",由调用方回 404。
1776
+ // 这一处是 /reader、/marks、/discuss、/open、/ask、/export、/item、/library 共用的入口,
1777
+ // 所以修在这里等于八条路由一起修好。
1778
+ if (!/^[a-f0-9]{64}$/.test(String(documentId))) return undefined
1779
+ return await repository.archivedDocument(documentId) ?? undefined
1780
+ }
1781
+
1782
+ /**
1783
+ * 一篇论文的章节树文本,**从磁盘上的 .outline.md 读**。
1784
+ *
1785
+ * 🔴 outlineText 是缓存字段,热记录里可能根本没有:它不进 state.json(storage 的
1786
+ * writeArchivedRecord 显式剔除、compact 也会 delete),冷归档读回来同样没有。所以
1787
+ * "记录上有就取、没有就当空" 会让目录抽屉对**每一篇**都显示「没有可用的章节树」——
1788
+ * 这正是用户截图报的那条。唯一正确的取法是走 documentView:它按 mtime+size 缓存读盘。
1789
+ *
1790
+ * 读不出来(没有 outlinePath、文件被删、内容为空)一律给空串,让调用方按"没有目录"降级,
1791
+ * 不让一次目录读取变成 500。
1792
+ *
1793
+ * @param {object} document 已 hydrate 的文档记录。
1794
+ * @returns {Promise<string>} 章节树文本;没有就是空串。
1795
+ */
1796
+ /**
1797
+ * 当前配置的目录字节预算。
1798
+ *
1799
+ * 读不到状态时退回默认值:一次状态读失败不该让目录变成空的 —— 那看起来像「这篇没有章节树」。
1800
+ */
1801
+ async function configuredOutlineBudget() {
1802
+ try {
1803
+ return (await repository.snapshot()).settings.outlineBudgetBytes
1804
+ } catch { return DEFAULT_SETTINGS.outlineBudgetBytes }
1805
+ }
1806
+
1807
+ async function outlineTextOf(document, outlineBudgetBytes) {
1808
+ const budget = Number.isFinite(outlineBudgetBytes) ? outlineBudgetBytes : await configuredOutlineBudget()
1809
+ const view = await documentReader.documentView(document, budget)
1810
+ return typeof view.outlineText === 'string' ? view.outlineText : ''
1811
+ }
1812
+
1813
+ /**
1814
+ * 一篇论文的划线视图:读盘 → 与**当前**块列表对齐 → 排好序。
1815
+ *
1816
+ * 🔴 两条路由共用它(/reader 与 /marks 的每次写入),所以"解析口径"只有一份:
1817
+ * 两处各写一遍必然漂移成"刚存的划线在响应里和刷新后不一样"。
1818
+ *
1819
+ * 读不出来(文件被删、被写坏)一律当"还没有划线" —— 用户内容缺失不该让正文打不开,
1820
+ * 也不该让一次写入变成 500。没有块列表时返回空数组:那种论文定位不了划线,
1821
+ * 把它们全标成 orphan 只会让面板显示一堆"找不到段落"。
1822
+ *
1823
+ * @param {object} document 已 hydrate 的文档记录。
1824
+ * @param {object[]} blocks 已合并译文的块列表。
1825
+ * @returns {Promise<object[]>} resolveMarks 的产物。
1826
+ */
1827
+ async function readerMarksOf(document, blocks) {
1828
+ if (!Array.isArray(blocks) || blocks.length === 0) return []
1829
+ try {
1830
+ const store = await readReaderStore(readerPathOf(document))
1831
+ return store === null ? [] : resolveMarks(store, blocks)
1832
+ } catch (error) {
1833
+ ctx.logger.warn(`dsh-paper marks: 划线读取失败,本篇按无划线处理:${errorText(error)}`)
1834
+ return []
1835
+ }
1836
+ }
1837
+
1838
+ /**
1839
+ * 把一条边注提问投递进当前会话。
1840
+ *
1841
+ * 🔴 **必须用 `followup`,不能用 `inject`。** 宿主 `packages/core/agent/README.md:47` 写得很清楚:
1842
+ * `inject` 是 "without waking the driver" —— 它把消息挂进下一步的上下文,但**不唤醒**驱动。
1843
+ * 用户提问之后如果没有下一条消息,这条提问就永远躺在收件箱里,agent 不会作答。
1844
+ * `followup` 排队一个独立的后续轮次并唤醒驱动,这才是"提问 → 得到回答"的语义。
1845
+ *
1846
+ * 拿不到 agent(会话没在跑、宿主没有 agents 服务)时**不抛错**:提问已经落盘,
1847
+ * 面板上看得见,返回一句原因让用户知道"这条还没送出去"。把它变成 500 会让用户
1848
+ * 以为提问丢了 —— 而它并没有。
1849
+ *
1850
+ * @param {string} sessionId 当前会话。
1851
+ * @param {object} message buildQuestionMessage 的产物。
1852
+ * @returns {{delivered: boolean, reason?: string}}
1853
+ */
1854
+ function deliverToSession(sessionId, message) {
1855
+ // 与 llm / attachments 同口径:可选服务用 ctx.get 惰性取,不上 inject ——
1856
+ // 写进 inject 会让没有 agents 服务的宿主整个插件加载失败。
1857
+ const agents = ctx.get('agents')
1858
+ if (typeof agents?.get !== 'function') return { delivered: false, reason: '宿主没有 agents 服务,提问只留在面板里' }
1859
+ const agent = agents.get(sessionId)
1860
+ if (agent === undefined || agent === null) return { delivered: false, reason: '当前会话没有在跑的 agent,提问只留在面板里' }
1861
+ if (typeof agent.followup !== 'function') return { delivered: false, reason: '当前 agent 不接受后续消息,提问只留在面板里' }
1862
+ agent.followup(message)
1863
+ return { delivered: true }
1864
+ }
1865
+
1866
+ /**
1867
+ * 一篇论文的边注视图:读盘 → 与**当前**块列表对齐。
1868
+ *
1869
+ * 与 {@link readerMarksOf} 同口径(读不出来当空、没有块列表当空),两处行为一致:
1870
+ * 用户内容缺失永远只是"暂时看不到",不会让阅读器打不开。
1871
+ *
1872
+ * @param {object} document 已 hydrate 的文档记录。
1873
+ * @param {object[]} blocks 已合并译文的块列表。
1874
+ * @returns {Promise<object[]>} resolveThreads 的产物。
1875
+ */
1876
+ async function readerThreadsOf(document, blocks) {
1877
+ if (!Array.isArray(blocks) || blocks.length === 0) return []
1878
+ try {
1879
+ const payload = await readDiscussion(discussionPathOf(document))
1880
+ return payload === null ? [] : resolveThreads(payload, blocks)
1881
+ } catch (error) {
1882
+ ctx.logger.warn(`dsh-paper discussion: 边注读取失败,本篇按无边注处理:${errorText(error)}`)
1883
+ return []
1884
+ }
1885
+ }
1886
+
1887
+ /** pause / resume / cancel 三条路由的共用体:队列侧直接按 documentId 操作,结算侧要落到 job 记录上。 */
1888
+ async function translationControl(action, documentId, reason) {
1889
+ // 缺省 documentId = 全局刹车(D70)。
1890
+ if (documentId === undefined || documentId === null || documentId === '') {
1891
+ if (action === 'pause') translateQueue.pauseAll()
1892
+ else if (action === 'resume') translateQueue.resumeAll()
1893
+ else {
1894
+ // 全局取消要逐篇收尾,否则那些任务的记录会永远停在 queued/running。
1895
+ const ids = translateTrackedIds()
1896
+ for (const id of ids) {
1897
+ trackTranslationSettlement(translateQueue.cancel(id, reason).then(async summary => {
1898
+ const current = await findTranslationJob(id)
1899
+ if (current !== null) await settleTranslation(current.id, summaryOutcome(summary))
1900
+ }))
1901
+ }
1902
+ }
1903
+ return { state: null, paused: translateQueue.isPaused(), running: translateQueue.runningCount() }
1904
+ }
1905
+ if (!validId(documentId)) {
1906
+ const error = new Error('论文 ID 无效')
1907
+ error.status = 400
1908
+ throw error
1909
+ }
1910
+ if (action === 'pause') translateQueue.pause(documentId)
1911
+ else if (action === 'resume') translateQueue.resume(documentId)
1912
+ else {
1913
+ trackTranslationSettlement(translateQueue.cancel(documentId, reason).then(async summary => {
1914
+ const current = await findTranslationJob(documentId)
1915
+ if (current !== null) await settleTranslation(current.id, summaryOutcome(summary))
1916
+ }))
1917
+ }
1918
+ return { state: translateQueue.stats(documentId) }
1919
+ }
1920
+
1921
+ /** 队列当前跟踪的 documentId 集合(全局取消用;不含已结算被摘掉的)。 */
1922
+ function translateTrackedIds() {
1923
+ return translateQueue.trackedIds()
1924
+ }
1925
+ /** 只读路由分组:每一项都能独立答完,返回 undefined 表示不是它的路径。 */
1926
+ async function readRoutes(request, url, rest) {
1927
+ if (request.method === 'GET' && rest === '/citation-styles') {
1928
+ try { return json(await bibliographyService.styles.list()) }
1929
+ catch (error) { return json({ error: errorText(error) }, 400) }
1930
+ }
1931
+ if (request.method === 'GET' && rest === '/export') {
1932
+ const file = url.searchParams.get('file')
1933
+ if (file !== null) {
1934
+ if (!/^[a-f0-9]{64}\.(bib|ris|json|txt)$/.test(file)) return json({ error: '书目导出地址无效' }, 400)
1935
+ try {
1936
+ return new Response(await readFile(join(runtimeRoot(config), 'exports', file)), { headers: {
1937
+ 'Content-Type': file.endsWith('.json') ? 'application/json; charset=utf-8' : 'text/plain; charset=utf-8',
1938
+ 'Content-Disposition': 'attachment; filename="bibliography.' + file.split('.').at(-1) + '"',
1939
+ 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store',
1940
+ } })
1941
+ } catch (error) {
1942
+ if (error.code === 'ENOENT') return json({ error: '书目导出不存在,请重新导出。' }, 404)
1943
+ throw error
1944
+ }
1945
+ }
1946
+ const documentId = url.searchParams.get('documentId') ?? ''
1947
+ const action = url.searchParams.get('action') ?? ''
1948
+ if (!/^[0-9a-f]{64}$/.test(documentId) || !['html', 'notes'].includes(action)) return json({ error: '导出地址无效' }, 400)
1949
+ const suffix = action === 'html' ? '.html' : '.notes.md'
1950
+ try {
1951
+ const bytes = await readFile(join(runtimeRoot(config), 'exports', documentId + suffix))
1952
+ return new Response(bytes, { headers: {
1953
+ 'Content-Type': action === 'html' ? 'text/html; charset=utf-8' : 'text/markdown; charset=utf-8',
1954
+ 'Content-Disposition': 'attachment; filename="paper' + suffix + '"',
1955
+ 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store',
1956
+ } })
1957
+ } catch (error) {
1958
+ if (error?.code === 'ENOENT') return json({ error: '导出不存在,请重新调用 Paper_library 导出。' }, 404)
1959
+ throw error
1960
+ }
1961
+ }
1962
+ for (const group of [adminReadRoutes, readerReadRoutes, libraryReadRoutes, parseReadRoutes]) {
1963
+ const response = await group(request, url, rest)
1964
+ if (response !== undefined) return response
1965
+ }
1966
+ return undefined
1967
+ }
1968
+
1969
+ /** 写入路由分组:同上,多一个已解析的 body。 */
1970
+ async function writeRoutes(request, url, rest, body) {
1971
+ for (const group of [parseWriteRoutes, translateWriteRoutes, libraryWriteRoutes, readerWriteRoutes, adminWriteRoutes]) {
1972
+ const response = await group(request, url, rest, body)
1973
+ if (response !== undefined) return response
1974
+ }
1975
+ return undefined
1976
+ }
1977
+
1978
+ /** 只读路由(在解析 body 之前):设置与运行状态。 */
1979
+ async function adminReadRoutes(request, url, rest) {
1980
+ if (request.method === 'GET' && rest === '/state') {
1981
+ scheduleSelectionSweep()
1982
+ const sessionId = url.searchParams.get('sessionId') ?? ''
1983
+ const state = await repository.snapshot()
1984
+ const selection = validId(sessionId) ? selectionView(state, sessionId) : { documentIds: [], desired: [], delivered: [] }
1985
+ const documentIds = new Set(selection.documentIds)
1986
+ const jobs = Object.values(state.jobs).filter(job => job.sessionId === sessionId || documentIds.has(job.documentId)).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
1987
+ // 解析 worker 是宿主级共享的(默认 4 路并发):本会话之外排队的论文同样占着并发位,
1988
+ // 所以进度条用的 progress 只算本会话,queue 给全机口径(侧栏据此提示"还有多少待处理")。
1989
+ //
1990
+ // 解析与翻译两类任务的并发位是分开的,所以进度与队列都按 kind 各报一份 —— 合成一个
1991
+ // 数字会让"待处理"两边都对不上。口径的选择:
1992
+ // progress / queue —— 解析,字段名与今天完全一致(老侧栏不用改也能跑)
1993
+ // translationProgress / translationQueue —— 翻译,T12 的翻译队列接这里
1994
+ // ⚠️ queue / translationQueue 保持"全机"口径:worker 池是宿主级共享的,别的会话排队的
1995
+ // 论文同样占着解析并发位,侧栏正靠这个差值提示"含其他会话"。
1996
+ //
1997
+ // jobs 仍然是本会话的全部任务(两种 kind 都在,每条都带着自己的 kind):侧栏要按 kind
1998
+ // 分成两组卡片,宿主只回一类就等于让另一类在面板上凭空消失。
1999
+ const allJobs = Object.values(state.jobs)
2000
+ const machineParses = summarizeProgress(allJobs)
2001
+ const machineTranslations = summarizeProgress(allJobs, { kind: 'translate' })
2002
+ // 会话仍关联、未隐藏的论文:既是要渲染的卡片,也是进度口径的"已完成"兜底来源。
2003
+ const attachedDocuments = Object.values(state.documents).filter(document => documentIds.has(document.id) && !document.hidden)
2004
+ const readyDocumentIds = attachedDocuments.map(document => document.id)
2005
+ return json({
2006
+ documents: await Promise.all(attachedDocuments.map(document => documentReader.documentView(document, state.settings.outlineBudgetBytes))),
2007
+ jobs,
2008
+ progress: summarizeProgress(jobs, { readyDocumentIds }),
2009
+ // 翻译任务的"已完成"兜底集合不能复用论文记录:翻译完成不改 documents 的 ready 语义。
2010
+ // T12 有翻译侧的持久证据时在这里补上 readyTranslationDocumentIds,现在只能按任务记录算。
2011
+ translationProgress: summarizeProgress(jobs, { kind: 'translate' }),
2012
+ queue: { pending: machineParses.pending, running: machineParses.running },
2013
+ // 全局刹车态(D70):侧栏据此决定显示「暂停翻译」还是「继续翻译」。
2014
+ translationPaused: translateQueue.isPaused(),
2015
+ translationQueue: { pending: machineTranslations.pending, running: machineTranslations.running },
2016
+ selection,
2017
+ mineru: resolver.describeMineru(),
2018
+ })
2019
+ }
2020
+
2021
+ if (request.method === 'GET' && rest === '/job') {
2022
+ const state = await repository.snapshot()
2023
+ const job = state.jobs[url.searchParams.get('id') ?? '']
2024
+ return job ? json({ job }) : json({ error: '任务不存在' }, 404)
2025
+ }
2026
+
2027
+ if (request.method === 'GET' && rest === '/settings') {
2028
+ return json({ settings: (await repository.snapshot()).settings })
2029
+ }
2030
+
2031
+ // 打码值只有前端回显用:完整 Key 不出这个进程,也不进日志。
2032
+ if (request.method === 'GET' && rest === '/mineru-key') return json(await mineruKeyView())
2033
+
2034
+ // 「这台电脑能不能渲染原页 / 解析」的自检。换台电脑最常见的失败是**没装 uv**,
2035
+ // 而界面上原来只有一句「页面图暂不可用」,用户不知道该装什么、装完要不要重启。
2036
+ // 只读、不安装、不写盘;探测失败也回 200 + available:false(自检本身不该报错)。
2037
+ if (request.method === 'GET' && rest === '/renderer-status') {
2038
+ return json(await probeRenderer({ command: config.mineruCommand }))
2039
+ }
2040
+
2041
+ // 一键装依赖(D191)。**这是本插件唯一会执行安装的地方**,所以输入面只有「选一条预置命令」:
2042
+ // 客户端传的 id 必须命中 install-dependency.js 里的白名单,命令本身由服务端决定 ——
2043
+ // 否则任何能发同源请求的东西都能让这台机器执行任意命令。
2044
+ // 装完**立刻重探一次**:真正该回报的是「现在能用了吗」,而不是「命令退出码 0」。
2045
+ if (request.method === 'POST' && rest === '/install-dependency') {
2046
+ const body = await request.json().catch(() => ({}))
2047
+ const id = typeof body?.id === 'string' ? body.id : ''
2048
+ const outcome = await installDependency({ id })
2049
+ const status = await probeRenderer({ command: config.mineruCommand })
2050
+ return json({ ...outcome, status })
2051
+ }
2052
+
2053
+ // 检查更新(D193)。**只读**:问 registry 一句、报告这一份是怎么装的,不改任何东西。
2054
+ // 用 GET 而不是 POST,正是为了让「检查」永远不会意外改动机器状态。
2055
+ if (request.method === 'GET' && rest === '/update/check') {
2056
+ return json(await updateService.check())
2057
+ }
2058
+
2059
+ // 一键升级。**这是本插件唯一会替换自己的动作**,因此:
2060
+ // 装的 spec 写死在 update-check.js(UPDATE_INSTALL_SPEC),请求体一个字段都不读;
2061
+ // 本地 link: 安装一律拒绝 —— 那会覆盖开发者正在编辑的工作树。
2062
+ if (request.method === 'POST' && rest === '/update/apply') {
2063
+ const outcome = await updateService.apply()
2064
+ if (outcome.ok === true) return json(outcome)
2065
+ return json({ ok: false, error: { code: outcome.code, message: outcome.message, rollback: outcome.rollback, restoredVersion: outcome.restoredVersion } }, outcome.status ?? 502)
2066
+ }
2067
+
2068
+ // 术语表(T22)。全局一份,不进 state.json,也不跟论文目录走。
2069
+ if (request.method === 'GET' && rest === '/glossary') return json(await glossaryView())
2070
+
2071
+ return undefined
2072
+ }
2073
+
2074
+ /** 只读路由(在解析 body 之前):阅读器与批注。 */
2075
+ async function readerReadRoutes(request, url, rest) {
2076
+ if (request.method === 'GET' && rest === '/pdf-page') {
2077
+ const documentId = url.searchParams.get('documentId') ?? ''
2078
+ const page = Number(url.searchParams.get('page') ?? 1)
2079
+ if (!validId(documentId) || !Number.isSafeInteger(page) || page < 1) return json({ error: '论文 ID 或 PDF 页码无效' }, 400)
2080
+ const raw = await readerDocumentOf(await repository.snapshot(), documentId)
2081
+ if (!raw) return json({ error: '论文不存在' }, 404)
2082
+ // 裁边开关由客户端按当前视图带下来(?crop=1);缺省是不裁,与接入前逐字节一致。
2083
+ const crop = url.searchParams.get('crop') === '1'
2084
+ try { return json(await pdfPageFor(hydrateDocument(raw), page, undefined, crop)) }
2085
+ catch (error) { return json({ error: errorText(error) }, error.status ?? 503) }
2086
+ }
2087
+ // 阅读器数据面(D76):打开时拉一次,不挂在每 2 秒轮询的 /state 上——把一篇论文的
2088
+ // 全文块塞进轮询会让侧栏一直拖着整篇正文。纯读:译文缺失、块列表缺失、JSON 损坏
2089
+ // 都在这里降级成"能看多少看多少",没有一条会让阅读器打不开。
2090
+ if (request.method === 'GET' && rest === '/reader') {
2091
+ const sessionId = url.searchParams.get('sessionId') ?? ''
2092
+ const documentId = url.searchParams.get('documentId') ?? ''
2093
+ if (!validId(sessionId)) return json({ error: '会话 ID 无效' }, 400)
2094
+ if (!validId(documentId)) return json({ error: '论文 ID 无效' }, 400)
2095
+ const state = await repository.snapshot()
2096
+ const raw = await readerDocumentOf(state, documentId)
2097
+ if (!raw) return json({ error: '论文不存在' }, 404)
2098
+ const document = hydrateDocument(raw)
2099
+ // 续读(D163):这一篇存下的阅读位置随 /reader 一起下发,面板据此回到上次读到的**段落**。
2100
+ // 🔴 走 readItem 而不是直接读文件:条目缺失 / 写坏 / 比本插件更新的版本都降级成默认条目
2101
+ // (progress 为 null),与库列表同一口径 —— 读不出来只是"从开头读",不能让 /reader 变成 500。
2102
+ const itemPath = itemPathOf(runtimeRoot(config), raw)
2103
+ const storedProgress = itemPath === '' ? null : (await readItem(itemPath)).progress
2104
+ const { blocks, notice } = await readerBlocksOf(documentPaths(document).contentPath)
2105
+ // 没有 Markdown 路径的论文翻译路径是空串,readTranslation('') 只会白读一次盘。
2106
+ const path = translationPathOf(document)
2107
+ const translation = path === '' ? null : await readTranslation(path)
2108
+ const merged = mergeReaderBlocks(blocks, translation)
2109
+ // 划线与笔记跟着 /reader 一起下发:它们是阅读器的一部分,分两次往返会让面板先空一帧。
2110
+ const marks = await readerMarksOf(document, merged)
2111
+ // 边注与划线一起下发:两者都是"挂在块上的用户/AI 内容",分两次往返只会让面板闪两下。
2112
+ const threads = await readerThreadsOf(document, merged)
2113
+ // 用量(T24)跟着阅读器一起下发:它是"这一篇翻过多少次、花了多少 token",
2114
+ // 与译文同源,分两次往返只会让面板先空一帧。读不出来是空账(readUsage 的降级)。
2115
+ const usage = summarizeUsage(await readUsage(usageFile), { documentId: document.id })
2116
+ return json({
2117
+ document: { id: document.id, pdfName: document.pdfName, markdownPath: document.markdownPath },
2118
+ blocks: merged,
2119
+ // 阅读位置(D163):面板打开时用它回到上次读到的段落。没读过是 null(不是 0)。
2120
+ progress: storedProgress,
2121
+ marks,
2122
+ threads,
2123
+ usage,
2124
+ // 章节树(P6)跟着阅读器一起下发:阅读页的目录抽屉要用它。
2125
+ // 🔴 现读盘,**不是**读记录上的缓存字段 —— 那个字段不进 state.json,照抄它会让
2126
+ // 每一篇的抽屉都显示「没有可用的章节树」(用户截图报的正是这条)。
2127
+ outlineText: await outlineTextOf(document),
2128
+ stats: translation?.stats ?? null,
2129
+ notice,
2130
+ })
2131
+ }
2132
+
2133
+ // 单篇条目(T21)。与 /library 分开是因为面板改一个标签后只想回这一篇,
2134
+ // 不必重拉整库(一篇论文一个文件,整库读取是 N 次读盘)。
2135
+ if (request.method === 'GET' && rest === '/item') {
2136
+ const documentId = url.searchParams.get('documentId') ?? ''
2137
+ if (!validId(documentId)) return json({ error: '论文 ID 无效' }, 400)
2138
+ const raw = await libraryDocumentOf(documentId)
2139
+ if (raw === null) return json({ error: '论文不存在' }, 404)
2140
+ const path = itemPathOf(runtimeRoot(config), raw)
2141
+ return json({ documentId, item: path === '' ? normalizeItem(null) : await readItem(path) })
2142
+ }
2143
+
2144
+ // token 用量(T24)。documentId 可选:不带就是全机口径,带上就是这一篇。
2145
+ // 读不出来一律空账本(readUsage 的降级),所以这条路由不会因为账本坏掉而 500。
2146
+ if (request.method === 'GET' && rest === '/usage') {
2147
+ const documentId = url.searchParams.get('documentId') ?? ''
2148
+ const store = await readUsage(usageFile)
2149
+ return json({
2150
+ summary: summarizeUsage(store, validId(documentId) ? { documentId } : {}),
2151
+ // 明细按时间倒序给最近若干条:面板要能说清"这些数字是哪几次调用攒出来的"。
2152
+ // 全量返回会让一次 200 篇的批量翻译回一份几千条的 JSON,而面板只画最近几条。
2153
+ recent: Object.values(store.records)
2154
+ .sort((left, right) => String(right.at).localeCompare(String(left.at)))
2155
+ .slice(0, MAX_USAGE_RECORDS)
2156
+ .map(record => ({ documentId: record.documentId, provider: record.provider, model: record.model, usage: record.usage, at: record.at })),
2157
+ total: Object.keys(store.records).length,
2158
+ })
2159
+ }
2160
+
2161
+ return undefined
2162
+ }
2163
+
2164
+ /**
2165
+ * 一页的「原页数据」:文字层 + 段落归属,附带裁边后的画布。
2166
+ *
2167
+ * 🔴 画布**必须与页面图同源**。两者各自去问 helper 会撞上先后顺序的问题(图先到、画布还没
2168
+ * 算出来,那一帧的选字层就按满页铺,等画布回来再跳一下)。这里先取画布(渲染器命中缓存时
2169
+ * 只读盘上的 canvas.json),再据此平移坐标 —— 一次请求里两件事用同一份画布。
2170
+ */
2171
+ async function pdfPageFor(document, page, blocks, crop = false) {
2172
+ const native = await readPdfPage({ documentId: document.id, pdfPath: document.pdfPath, page }, {
2173
+ cacheDir: pageImageCacheDir, command: config.mineruCommand,
2174
+ })
2175
+ let canvas = null
2176
+ if (crop === true) {
2177
+ try {
2178
+ const rendered = await renderPageImages(
2179
+ { pdfPath: document.pdfPath, pages: [page], width: DEFAULT_PAGE_WIDTH, documentId: document.id, crop: true },
2180
+ { cacheDir: pageImageCacheDir, command: config.mineruCommand },
2181
+ )
2182
+ canvas = normalizeCanvas(rendered?.canvas)
2183
+ } catch {
2184
+ // 渲染不可用(uvx 缺失 / 超时)不该让文字层也读不出来:退回满页坐标,
2185
+ // 与页面图那条 503 降级是同一口径 —— 少一层裁边,不少一次阅读。
2186
+ canvas = null
2187
+ }
2188
+ }
2189
+ const list = blocks ?? (await readerBlocksOf(documentPaths(document).contentPath)).blocks
2190
+ // 段落归属按满页口径算,再把结果整体换算到画布上(顺序反了匹配判据会失真)。
2191
+ const base = { page: native.page, pageCount: native.pageCount, width: native.width, height: native.height }
2192
+ const positioned = cropPdfGroups(base, pdfPageGroups(native, list), canvas)
2193
+ return { ...base, width: positioned.width, height: positioned.height,
2194
+ hasText: native.words.length > 0, canvas: positioned.canvas, groups: positioned.groups }
2195
+ }
2196
+
2197
+ /** 只读路由(在解析 body 之前):文献库。 */
2198
+ async function libraryReadRoutes(request, url, rest) {
2199
+ // 全局文献库(T21)。列表从「按会话」提升为「全局」——换会话看到同一份。
2200
+ // 会话维度只记「我关注哪几篇」(那是 state.selections 的事),这里给的是全部论文。
2201
+ if (request.method === 'GET' && rest === '/library') {
2202
+ const view = await libraryView()
2203
+ // 注入集合按会话给(?sessionId=)。库本身是全局的,只有「当前会话关注哪几篇」随会话
2204
+ // 变化 —— 主栏批量条的注入按钮要按它切换「注入所选 / 取消注入」两态。
2205
+ const sessionId = url.searchParams.get('sessionId') ?? ''
2206
+ if (sessionId === '') return json(view)
2207
+ const state = await repository.snapshot()
2208
+ return json({ ...view, injectedIds: state?.selections?.[sessionId]?.desired ?? [] })
2209
+ }
2210
+
2211
+ return undefined
2212
+ }
2213
+
2214
+ /** 只读路由(在解析 body 之前):解析与导入。 */
2215
+ async function parseReadRoutes(request, url, rest) {
2216
+ // 右栏「解析」Tab 的清单(GET,无请求体):与上面那批 GET 同一条规矩 —— 必须在
2217
+ // `bodyOf` 之前处理,否则一个不带 `Content-Type: application/json` 的调用方会拿到 415,
2218
+ // 而它根本没有请求体可讲。
2219
+ if (request.method === 'GET' && rest === '/parse-list') {
2220
+ await parseExport.start()
2221
+ return json(parseExport.list())
2222
+ }
2223
+
2224
+ return undefined
2225
+ }
2226
+
2227
+ /** 写入路由(需要 body):解析与导入。 */
2228
+ async function parseWriteRoutes(request, url, rest, body) {
2229
+ if (request.method === 'POST' && rest === '/pick') {
2230
+ await pickCacheReady
2231
+ const paths = await (pickInFlight ??= pickPdf({ initialDir: initialPickDir(body), cacheDir: pickCacheDir }).finally(() => { pickInFlight = null }))
2232
+ // 选择窗口到底回了几个路径,是「一篇还是一整批」的唯一事实来源 —— 侧栏拿到这个数组
2233
+ // 就逐篇 /add。用户报过「只选了一篇却像整目录都进来了」,没有这行日志就只能靠猜。
2234
+ ctx.logger.info(`dsh-paper pick: 系统窗口返回 ${paths.length} 个路径${paths.length === 0 ? '' : `,例如 ${paths.slice(0, 3).join('、')}${paths.length > 3 ? ` 等 ${paths.length} 个` : ''}`}`)
2235
+ return json({ paths })
2236
+ }
2237
+
2238
+ // ---- 右栏「解析」Tab(独立通路,POST 部分)----
2239
+ //
2240
+ // 🔴 这一族路由**只**碰 `parse-export` 自己的那份清单:不建文档记录、不动 state.json 的
2241
+ // selections、不写 item.json。用户原话:「不执行其他记录和论文库添加」。
2242
+ //
2243
+ // 选文件复用 /pick(那条路本来就支持多选),只有"把它加进清单"是新的;
2244
+ // 文件夹扫描同样复用 /pick-folder + /scan 的授权与高危确认模型,只是不落库。
2245
+ // GET 那一条(/parse-list)与其它 GET 一样排在 `bodyOf` **之前**,见上面 `/usage` 那段。
2246
+ //
2247
+ // 🔴 **加进清单 ≠ 开始花钱**:`/parse-add` 与 `/parse-scan` 只把条目写成 `pending`,
2248
+ // 真正的提交在 `/parse-start`(面板上那一个「开始解析」)。用户要能在花钱前复核这一批。
2249
+ if (request.method === 'POST' && rest === '/parse-add') {
2250
+ const paths = Array.isArray(body.paths) ? body.paths.filter(path => typeof path === 'string' && path !== '') : []
2251
+ if (paths.length === 0) return json({ error: '没有可解析的 PDF 路径' }, 400)
2252
+ if (paths.length > MAX_PARSE_ADD) return json({ error: `一次最多添加 ${MAX_PARSE_ADD} 篇` }, 400)
2253
+ // 每个路径都先 stat 一次:不存在 / 不是 PDF 的输入要在这里说清,不能等到排队才发现。
2254
+ const accepted = []
2255
+ const failures = []
2256
+ for (const path of paths) {
2257
+ try {
2258
+ const inspected = await inspectPdf(path)
2259
+ accepted.push(path)
2260
+ void inspected
2261
+ } catch (error) {
2262
+ failures.push({ path, error: errorText(error) })
2263
+ }
2264
+ }
2265
+ const added = accepted.length === 0 ? { added: [], skipped: 0 } : await parseExport.add(accepted)
2266
+ return json({ ...parseExport.list(), added: added.added.map(item => item.id), skipped: added.skipped, failures })
2267
+ }
2268
+
2269
+ // 文件夹扫描:与 /scan 同一套授权与高危确认,差别只在"扫出来的 PDF 进哪个清单"。
2270
+ // 共用一个授权表 —— 授权绑定的是"用户刚在窗口里选中的那个目录",与去哪条通路无关。
2271
+ if (request.method === 'POST' && rest === '/parse-scan') {
2272
+ const grant = scanGrants.get(typeof body.grant === 'string' ? body.grant : '')
2273
+ if (!grant || grant.expiresAt <= Date.now()) return json({ error: '扫描授权无效或已过期,请先用「选择文件夹」选一次' }, 403)
2274
+ if (typeof body.dir !== 'string' || comparablePath(body.dir) !== comparablePath(grant.dir)) {
2275
+ return json({ error: '只能扫描刚才在窗口里选中的文件夹' }, 403)
2276
+ }
2277
+ const risk = scanRiskOf(grant.dir, { extra: riskyScanRoots })
2278
+ if (risk && body.confirm !== true) {
2279
+ return json({ error: `${risk}范围太大,确认后才扫描`, risky: true, reason: risk, dir: grant.dir, grant: body.grant }, 409)
2280
+ }
2281
+ const { pdfs, unreadable } = await scanFolder(grant.dir)
2282
+ const added = await parseExport.add(pdfs)
2283
+ return json({ ...parseExport.list(), added: added.added.length, skipped: added.skipped, unreadable })
2284
+ }
2285
+
2286
+ // 「开始解析」:把待办(pending)那批下令开跑。**这是唯一会花钱的那一下**
2287
+ // (用户裁定:加进来只是排进清单,先在面板上复核,再点火)。
2288
+ if (request.method === 'POST' && rest === '/parse-start') {
2289
+ const started = await parseExport.startRun(typeof body.id === 'string' ? body.id : '')
2290
+ return json({ ...started, ...parseExport.list() })
2291
+ }
2292
+
2293
+ if (request.method === 'POST' && rest === '/parse-remove') {
2294
+ const removed = await parseExport.remove(body.id)
2295
+ return json({ ...removed, ...parseExport.list() })
2296
+ }
2297
+
2298
+ if (request.method === 'POST' && rest === '/parse-retry') {
2299
+ const result = await parseExport.requeue(typeof body.id === 'string' ? body.id : '')
2300
+ // 回整份清单(含内存态的 done):只回 items 会让刚导出那几行的灰字在界面上闪没。
2301
+ return json({ ...result, ...parseExport.list() })
2302
+ }
2303
+
2304
+ if (request.method === 'POST' && rest === '/pick-folder') {
2305
+ await pickCacheReady
2306
+ // 授权在在飞 Promise 内签发:一次窗口结果只换一枚授权,并发请求共享同一枚;
2307
+ // 每个请求各签一枚会让"一次选择"在授权表里留下多份可复用凭据。
2308
+ const picked = await (folderPickInFlight ??= pickFolderDialog({ initialDir: initialPickDir(body), cacheDir: pickCacheDir })
2309
+ .then(dir => ({ dir, grant: dir ? mintScanGrant(dir) : '' }))
2310
+ .finally(() => { folderPickInFlight = null }))
2311
+ return json(picked)
2312
+ }
2313
+
2314
+ if (request.method === 'POST' && rest === '/scan') {
2315
+ if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
2316
+ try { await checkImportCollection(body.collectionId) } catch (error) { return json({ error: errorText(error) }, 400) }
2317
+ // 扫描必须由刚才那次「选择文件夹」换来的授权背书,且只能扫授权绑定的目录:否则
2318
+ // "只扫描用户显式选中的文件夹"只是侧栏约定,任何同源请求都能拿任意路径枚举 PDF 并整批推给 MinerU。
2319
+ const grant = scanGrants.get(typeof body.grant === 'string' ? body.grant : '')
2320
+ if (!grant || grant.expiresAt <= Date.now()) return json({ error: '扫描授权无效或已过期,请先用「选择文件夹」选一次' }, 403)
2321
+ if (typeof body.dir !== 'string' || comparablePath(body.dir) !== comparablePath(grant.dir)) {
2322
+ return json({ error: '只能扫描刚才在窗口里选中的文件夹' }, 403)
2323
+ }
2324
+ // 盘根、用户主目录这类位置深度 2 也照样能命中成千上万个目录,要多确认一次才扫。
2325
+ const risk = scanRiskOf(grant.dir, { extra: riskyScanRoots })
2326
+ if (risk && body.confirm !== true) {
2327
+ return json({ error: `${risk}范围太大,确认后才扫描`, risky: true, reason: risk, dir: grant.dir, grant: body.grant }, 409)
2328
+ }
2329
+ const { root, pdfs, unreadable } = await scanFolder(body.dir)
2330
+ // 逐篇走与 /add 相同的 resolver.add 路径(analysis/ 便携结果 → runtime 记录 → 排队):createQueuedJob
2331
+ // 只复用同一文档 queued/running 的任务,所以扫描时没解析完的论文不会重复提交远端;
2332
+ // 已失败/中断的那篇会按与单篇重试相同的语义再提交一次(与 README 的说明一致)。
2333
+ // 与 /add 的差别只有两处批量收口:关联会话合成一次写入、compact 留到批末。
2334
+ const results = await mapWithConcurrency(pdfs, SCAN_ADD_CONCURRENCY, path => resolver.add(path, body.sessionId, { deferCompaction: true }))
2335
+ const outcome = { reused: 0, queued: 0, blocked: 0 }
2336
+ const failures = []
2337
+ const associated = []
2338
+ results.forEach((result, index) => {
2339
+ if (!result.ok) {
2340
+ failures.push({ path: pdfs[index], error: result.error })
2341
+ return
2342
+ }
2343
+ const added = result.value
2344
+ const documentId = added.document?.id ?? added.job?.documentId
2345
+ if (typeof documentId === 'string') associated.push({ path: pdfs[index], documentId })
2346
+ const status = added.document ? 'reused' : ['queued', 'running'].includes(added.job?.status) ? 'queued' : 'blocked'
2347
+ outcome[status] += 1
2348
+ })
2349
+ // 整批一次关联(理由见 attachDocumentsToSession)。这一步失败不改上面四个桶的口径
2350
+ // (found 恒等于四桶之和),单独列 unattached:任务已入队、远端可能已受理计费,
2351
+ // 报成"没能添加"会让用户以为无事发生。
2352
+ const unattached = []
2353
+ const classificationFailures = []
2354
+ if (body.collectionId && associated.length) {
2355
+ try { await serializeLibrary(() => libraryService.attachImported(body.collectionId, associated.map(row => row.documentId))) }
2356
+ catch (error) { classificationFailures.push({ error: errorText(error) }) }
2357
+ }
2358
+ try {
2359
+ await attachDocumentsToSession(body.sessionId, associated.map(entry => entry.documentId))
2360
+ } catch (error) {
2361
+ const reason = errorText(error)
2362
+ for (const entry of associated) unattached.push({ path: entry.path, error: reason })
2363
+ }
2364
+ ctx.logger.info(`dsh-paper scan: ${root} 下找到 ${pdfs.length} 篇 PDF,排队 ${outcome.queued} 篇、复用 ${outcome.reused} 篇${failures.length > 0 ? `、失败 ${failures.length} 篇` : ''}`)
2365
+ if (unattached.length > 0) ctx.logger.warn(`dsh-paper scan: ${unattached.length} 篇已入队但没挂上会话侧栏,例如 ${unattached[0].path}:${unattached[0].error}`)
2366
+ if (unreadable.length > 0) {
2367
+ // 只回计数给侧栏:读不动的子目录可能成千上万,路径留在宿主日志里。
2368
+ ctx.logger.warn(`dsh-paper scan: ${unreadable.length} 个子目录无法读取,例如 ${unreadable.slice(0, MAX_SCAN_FAILURES).map(entry => entry.path).join('、')}`)
2369
+ }
2370
+ // 整批只在结束时统一整理一次:逐篇 compact 会把整份 state.json 重写 N 遍、逐篇抢跨进程
2371
+ // 状态锁。这一步失败只推迟回收(下一次 /state 的整理或下一批的 compact 会补上),
2372
+ // 不能把已经成功入队的批量报成失败。
2373
+ try { await repository.compact() } catch (error) { ctx.logger.warn(`dsh-paper scan: 批量整理失败,留待下次:${errorText(error)}`) }
2374
+ return json({
2375
+ dir: root,
2376
+ found: pdfs.length,
2377
+ ...outcome,
2378
+ failed: failures.length,
2379
+ failures: failures.slice(0, MAX_SCAN_FAILURES),
2380
+ unreadable: unreadable.length,
2381
+ unattached: unattached.length,
2382
+ unattachedDetail: unattached.slice(0, 3),
2383
+ classificationFailures,
2384
+ }, 202)
2385
+ }
2386
+
2387
+ if (request.method === 'POST' && rest === '/add') {
2388
+ if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
2389
+ try { await checkImportCollection(body.collectionId) } catch (error) { return json({ error: errorText(error) }, 400) }
2390
+ const { result, attachError } = await addPdfToSession(body.path, body.sessionId)
2391
+ if (body.collectionId) {
2392
+ const id = result.document?.id ?? result.job?.documentId
2393
+ if (id) {
2394
+ try { await serializeLibrary(() => libraryService.attachImported(body.collectionId, [id])) }
2395
+ catch (error) { return json({ ...result, classificationFailures: [{ documentId: id, error: errorText(error) }] }, 202) }
2396
+ }
2397
+ }
2398
+ if (attachError) {
2399
+ ctx.logger.warn(`dsh-paper add: ${attachError}(${body.path})`)
2400
+ return json({ ...result, error: `论文已入队,但没能显示到侧栏(${attachError});再添加一次同一文件即可,不会重复解析` }, 500)
2401
+ }
2402
+ return json(result, 202)
2403
+ }
2404
+
2405
+ if (request.method === 'POST' && rest === '/retry') {
2406
+ if (!validId(body.jobId)) return json({ error: '任务 ID 无效' }, 400)
2407
+ return json(await resolver.retry(body.jobId), 202)
2408
+ }
2409
+
2410
+ if (request.method === 'POST' && rest === '/retry-all') {
2411
+ if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
2412
+ const snapshot = await repository.snapshot()
2413
+ const attached = new Set(selectionView(snapshot, body.sessionId).documentIds)
2414
+ // 同一文档可能留下多条失败记录(重启后重试又被打断):只重排最新的一条,
2415
+ // 否则会为同一篇论文重复提交远端解析。
2416
+ const newestPerDocument = new Map()
2417
+ for (const job of Object.values(snapshot.jobs)
2418
+ // 🔴 只重排**解析**任务:解析与翻译共用 state.jobs,不过滤就会把翻译失败也送给
2419
+ // resolver.retry(那里只认解析任务),而"取最新一条"的规则还会让较新的翻译失败
2420
+ // 顶掉本该重试的解析记录。缺 kind 的老记录由 jobKindOf 读作 parse,兼容语义不变。
2421
+ .filter(job => jobKindOf(job) === 'parse' && RETRYABLE_JOB_STATUSES.includes(job.status))
2422
+ .filter(job => job.sessionId === body.sessionId || attached.has(job.documentId))
2423
+ .sort((left, right) => String(left.createdAt).localeCompare(String(right.createdAt)))) {
2424
+ newestPerDocument.set(job.documentId, job)
2425
+ }
2426
+ const queue = [...newestPerDocument.values()].slice(0, MAX_BATCH_RETRY).map(job => job.id)
2427
+ const results = await mapWithConcurrency(queue, BATCH_RETRY_CONCURRENCY, jobId => resolver.retry(jobId))
2428
+ const failures = results.map((result, index) => (result.ok ? undefined : { id: queue[index], error: result.error })).filter(Boolean)
2429
+ const retried = results.length - failures.length
2430
+ ctx.logger.info(`dsh-paper retry-all: 会话 ${body.sessionId} 重新排队 ${retried} 个解析任务${failures.length > 0 ? `,${failures.length} 个无法重试` : ''}`)
2431
+ return json({ scheduled: results.length, retried, skipped: failures.length, failures }, 202)
2432
+ }
2433
+
2434
+ if (request.method === 'POST' && rest === '/reparse') {
2435
+ if (!validId(body.sessionId) || !/^[a-f0-9]{64}$/.test(body.documentId ?? '')) return json({ error: '重新解析参数无效' }, 400)
2436
+ const snapshot = await repository.snapshot()
2437
+ // 🔴 冷归档也算「论文存在」:长期没用的论文会被 compact() 挪进 archive/,而 /library
2438
+ // 与 resolver.reparse 都认冷记录 —— 这里只查热层就会造出「列表里点得到、点下去 404
2439
+ // 论文不存在」的死角。判定与 reparse 内部同源(热优先、冷兜底)。
2440
+ const stored = snapshot.documents[body.documentId] ?? await repository.archivedDocument(body.documentId)
2441
+ if (!stored) return json({ error: '论文不存在' }, 404)
2442
+ // 🔴 不检查「是否在这个会话的侧栏里」(D133,用户裁定):解析与翻译是针对**论文本身**的动作,
2443
+ // 产物落在论文自己的资产目录里,与哪个会话在看它无关;文献库本身就是跨会话的全集,拦在这里
2444
+ // 只会造出「列表里点得到、点下去被拒」的死角。侧栏归属只决定要不要把目录注入模型上下文。
2445
+ return json(await resolver.reparse(body.documentId, body.sessionId), 202)
2446
+ }
2447
+
2448
+ return undefined
2449
+ }
2450
+
2451
+ /** 写入路由(需要 body):翻译。 */
2452
+ async function translateWriteRoutes(request, url, rest, body) {
2453
+ // ---- 一键翻译(D177)----
2454
+ // 用户裁定:文献库当前分类里**没有译文的块**,点一下全排上。
2455
+ //
2456
+ // 与单篇 /translate 的分工:这里只排**增量**,不改判据 —— 「这一篇还有没有块要翻」
2457
+ // 与 autoTranslate / translationPendingOf 是同一套判据(planTranslation + pendingForIncremental),
2458
+ // 所以「跳过 K 篇」不是猜的,真排一遍它们也确实是零个块。
2459
+ //
2460
+ // 逐篇先探测再入队,探测并发 BATCH_TRANSLATE_CONCURRENCY(读块列表 + 译文两份文件,
2461
+ // 串行跑几百篇会让按钮按下去之后长时间没有反应);真正翻译由队列按全局闸门放行,与探测无关。
2462
+ if (request.method === 'POST' && rest === '/translate-batch') {
2463
+ const batch = batchDocumentIds(body)
2464
+ if (batch.error !== undefined) return json({ error: batch.error }, 400)
2465
+ const snapshot = await repository.snapshot()
2466
+ const scope = translationScopeOf(snapshot.settings)
2467
+ const probed = await mapWithConcurrency(batch.ids, BATCH_TRANSLATE_CONCURRENCY, documentId => translationBatchEntry(snapshot, documentId, scope))
2468
+ const entries = probed.map((result, index) => (result.ok
2469
+ ? result.value
2470
+ : { documentId: batch.ids[index], pdfName: '', document: undefined, pending: 0, translated: 0, total: 0, error: result.error }))
2471
+ const failures = []
2472
+ const planned = []
2473
+ let unchanged = 0
2474
+ for (const entry of entries) {
2475
+ if (entry.error !== '') {
2476
+ failures.push({ documentId: entry.documentId, pdfName: entry.pdfName, error: entry.error })
2477
+ continue
2478
+ }
2479
+ if (entry.pending === 0) { unchanged += 1; continue }
2480
+ planned.push(entry)
2481
+ }
2482
+ // 🔴 预检在**建记录之前**(与 /translate 同一个教训):已经在跑的论文根本不写任务记录,
2483
+ // 否则那条记录要先落盘、再靠 startTranslation 的竞态分支撤掉 —— 多一次写盘,
2484
+ // 而且「谁负责撤掉这条记录」被摊到了两个函数里。下面循环里不再重复查一次。
2485
+ const queueable = planned.filter(entry => !translateQueue.has(entry.documentId))
2486
+ let skipped = planned.length - queueable.length
2487
+ // 🔴 整批只写一次 state.json:逐篇 update 会把整份状态重写 N 遍、逐篇抢跨进程状态锁
2488
+ // (与 /scan、/selection 同一个口径)。
2489
+ const jobs = queueable.map(entry => ({
2490
+ id: `job-${randomUUID()}`,
2491
+ kind: 'translate',
2492
+ documentId: entry.documentId,
2493
+ sessionId: body.sessionId ?? '',
2494
+ pdfPath: hydrateDocument(entry.document).pdfPath,
2495
+ pdfName: entry.pdfName,
2496
+ status: 'queued',
2497
+ error: '',
2498
+ createdAt: new Date().toISOString(),
2499
+ updatedAt: new Date().toISOString(),
2500
+ }))
2501
+ if (jobs.length > 0) await repository.update(current => { for (const job of jobs) current.jobs[job.id] = job })
2502
+ let queued = 0
2503
+ let queuedBlocks = 0
2504
+ for (let index = 0; index < queueable.length; index += 1) {
2505
+ const entry = queueable[index]
2506
+ try {
2507
+ await startTranslation(jobs[index], hydrateDocument(entry.document), { scope, incremental: true })
2508
+ queued += 1
2509
+ queuedBlocks += entry.pending
2510
+ } catch (error) {
2511
+ // 预检与入队之间的竞态窗口(用户同时点了单篇翻译、或另一路刚排上):
2512
+ // startTranslation 已经把那条第 409 版的记录撤掉了,这里按良性计入 skipped。
2513
+ if (error?.reason === 'already-queued') { skipped += 1; continue }
2514
+ // 其余是真故障:那条 job 记录还在状态里,就地结清成 failed,免得侧栏留一张永远 queued 的卡片。
2515
+ await settleTranslation(jobs[index].id, { status: 'failed', error: errorText(error) })
2516
+ failures.push({ documentId: entry.documentId, pdfName: entry.pdfName, error: errorText(error) })
2517
+ }
2518
+ }
2519
+ ctx.logger.info(`dsh-paper translate-batch: 会话 ${body.sessionId ?? ''} 排队 ${queued} 篇(${queuedBlocks} 个块)、已翻完 ${unchanged} 篇、已在队列 ${skipped} 篇、无法翻译 ${failures.length} 篇`)
2520
+ // 整批只在结束时统一整理一次(理由同 /scan)。失败只推迟回收,不能把已经入队的报成失败。
2521
+ if (jobs.length > 0) {
2522
+ try { await repository.compact() } catch (error) { ctx.logger.warn(`dsh-paper translate-batch: 批量整理失败,留待下次:${errorText(error)}`) }
2523
+ }
2524
+ return json({ scanned: entries.length, queued, blocks: queuedBlocks, unchanged, skipped, failures }, 202)
2525
+ }
2526
+
2527
+ // 重排**失败**的翻译(D179)。判据与 /translate-batch 同源(还差几块没译),
2528
+ // 差别只在范围:只挑现在挂着 failed / interrupted 记录的论文。
2529
+ // documentId 缺省 = 会话侧栏里所有还没译完的失败论文。
2530
+ if (request.method === 'POST' && rest === '/translate-retry') {
2531
+ if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
2532
+ if (body.documentId !== undefined && !/^[a-f0-9]{64}$/.test(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
2533
+ const outcome = await retryFailedTranslations(body.sessionId, body.documentId)
2534
+ ctx.logger.info(`dsh-paper translate-retry: 会话 ${body.sessionId} 重排 ${outcome.queued} 篇(${outcome.blocks} 个块)、已翻完 ${outcome.unchanged} 篇、已在队列 ${outcome.skipped} 篇、无法翻译 ${outcome.failures.length} 篇`)
2535
+ return json(outcome, 202)
2536
+ }
2537
+
2538
+ if (request.method === 'POST' && rest === '/translate') {
2539
+ if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
2540
+ if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
2541
+ const state = await repository.snapshot()
2542
+ const document = state.documents[body.documentId]
2543
+ if (!document) return json({ error: '论文不存在' }, 404)
2544
+ // 路径字段是相对的:必须 hydrate 才能拿到可用的 pdfPath / markdownPath。
2545
+ const hydrated = hydrateDocument(document)
2546
+ // 「自动」档(文献库右栏那一个「翻译」按钮):**由服务端看译文现状决定怎么翻**,
2547
+ // 客户端不必先知道翻译过没有。判据是译文里**真的有已译块**,不是文件存在 ——
2548
+ // 一次只写了空壳的中断(`{ blocks: [] }`)仍算没译过,否则会拿整篇重译去覆盖它。
2549
+ // 译过 → 整篇重译(translateAll,覆盖旧译文、revision 递增);没译过 → 增量(省额度)。
2550
+ // 🔴 必须在**拷贝**上改:`body` 是 `const`(1329 行),就地赋值会抛 TypeError。
2551
+ // 而且下游的 `startTranslation(job, hydrated, …)` 读的是这个物化后的对象。
2552
+ let request_ = { ...body }
2553
+ if (body.auto === true && body.incremental !== true && body.translateAll !== true) {
2554
+ const path = translationPathOf(hydrated)
2555
+ const translated = path === '' ? null : await readTranslation(path)
2556
+ const already = Array.isArray(translated?.blocks)
2557
+ && translated.blocks.some(block => typeof block?.zh === 'string' && block.zh.trim() !== '')
2558
+ request_ = { ...request_, ...(already ? { translateAll: true } : { incremental: true }) }
2559
+ }
2560
+ // 🔴 已经在翻这一篇了:别再建一条记录、也别再用 409 把它报成故障(D157)。
2561
+ // 右栏「翻译 / 整篇重译」是**手工**入口,同样会撞上这个状态 —— 连点两下就会走到
2562
+ // startTranslation 的 409,客户端把它渲染成红字。与 autoTranslate 同一个判据、同一个 reason。
2563
+ // 预检与入队之间的竞态窗口(两次点击并发、或撞上 /open 的自动翻译)由 beginTranslation
2564
+ // 自己收成同一个结果:否则同样的状态会有两种表现(200 静默 / 409 红字),
2565
+ // 而客户端只按结构化 reason 判良性。
2566
+ const outcome = await beginTranslation(body.documentId, hydrated, body.sessionId, request_)
2567
+ if (!outcome.started) {
2568
+ return json({ started: false, reason: 'already-queued', state: translateQueue.stats(body.documentId) })
2569
+ }
2570
+ return json(outcome.result)
2571
+ }
2572
+
2573
+ if (request.method === 'GET' && rest === '/translate-models') {
2574
+ return json(await translationModelsView())
2575
+ }
2576
+
2577
+ // 三条刹车路由:body.documentId **可选**。给了就是单篇,缺省就是全局(D70)——
2578
+ // 自动翻译默认开,一次文件夹扫描能留下几十个任务,单篇暂停不可用。
2579
+ if (request.method === 'POST' && rest === '/translate-pause') {
2580
+ return json(await translationControl('pause', body.documentId))
2581
+ }
2582
+
2583
+ if (request.method === 'POST' && rest === '/translate-resume') {
2584
+ return json(await translationControl('resume', body.documentId))
2585
+ }
2586
+
2587
+ if (request.method === 'POST' && rest === '/translate-cancel') {
2588
+ return json(await translationControl('cancel', body.documentId, body.reason))
2589
+ }
2590
+
2591
+ return undefined
2592
+ }
2593
+
2594
+ /** 写入路由(需要 body):文献库。 */
2595
+ /**
2596
+ * 目录 → 记录:把用户工作区里的论文文件夹绑到库记录上。
2597
+ *
2598
+ * D128 之后 PDF 本体只在 runtime(`library/<sha256>/`),记录里的 pdfPath 指向那份副本。
2599
+ * 于是「这篇论文在用户工作区的哪个文件夹」不记下来就再也推不出来 —— 而配套的 .md、
2600
+ * Source/、Reproduction/、Thought.md 全按它定位。
2601
+ *
2602
+ * 这里**只读**用户目录、**只写**库记录:不解析、不旁挂、不改用户文件一个字节。
2603
+ * 按内容哈希匹配,所以文件夹改名、记录改名、PDF 改名都不影响命中;代价是 PDF 内容
2604
+ * 变过就匹配不上(那种情况应当重新入库,而不是绑一个错的目录)。
2605
+ *
2606
+ * 🔴 模型侧(Paper_library 的 bind)与界面侧(/library 的 bind)调的都是这一个函数。
2607
+ *
2608
+ * 🔴 反方向(记录 → 目录)见 setSourceDir:换版本之后哈希变了、这条路上永远匹配不上,
2609
+ * 那种情况要靠用户指认,而不是靠内容猜。
2610
+ *
2611
+ * @param {string} dirText 文件夹绝对路径,一行一个(可以是分类根目录)
2612
+ * @param {{dryRun?: boolean}} [options] dryRun 只报账不写记录(先看会绑成什么再决定)
2613
+ * @returns {Promise<{ok: boolean, dryRun?: boolean, scanned: number, already: number,
2614
+ * bound: Array<{documentId: string, pdfName: string, sourceDir: string}>,
2615
+ * unknown: string[], failures: string[], unboundCount?: number}>} 逐项报账,调用方决定怎么排版
2616
+ */
2617
+ async function bindSourceDirs(dirText, options = {}) {
2618
+ const dryRun = options.dryRun === true
2619
+ const dirs = (typeof dirText === 'string' ? dirText : '')
2620
+ .split(/\r?\n/).map(line => line.trim()).filter(line => line !== '')
2621
+ if (dirs.length === 0) {
2622
+ const error = new Error('需要 dir:要绑定的绝对文件夹路径')
2623
+ error.status = 400
2624
+ throw error
2625
+ }
2626
+ for (const dir of dirs) {
2627
+ if (!isAbsolute(dir)) {
2628
+ const error = new Error(`dir 必须是绝对路径:${dir}`)
2629
+ error.status = 400
2630
+ throw error
2631
+ }
2632
+ }
2633
+ const state = await repository.snapshot()
2634
+ const seen = new Set()
2635
+ const bound = []
2636
+ const unknown = []
2637
+ const failures = []
2638
+ let scanned = 0
2639
+ let already = 0
2640
+ for (const dir of dirs) {
2641
+ let result
2642
+ try {
2643
+ result = await scanFolder(dir)
2644
+ } catch (error) {
2645
+ failures.push(`${dir}:${errorText(error)}`)
2646
+ continue
2647
+ }
2648
+ for (const entry of result?.unreadable ?? []) {
2649
+ failures.push(`${entry.path}:无法读取子目录(${entry.error})`)
2650
+ }
2651
+ for (const pdfPath of result?.pdfs ?? []) {
2652
+ scanned += 1
2653
+ let inspected
2654
+ try {
2655
+ inspected = await inspectPdf(pdfPath)
2656
+ } catch (error) {
2657
+ failures.push(`${pdfPath}:${errorText(error)}`)
2658
+ continue
2659
+ }
2660
+ // 同一篇可能从两层目录都扫到(用户把分类根和子目录一起给):只认第一次。
2661
+ if (seen.has(inspected.hash)) continue
2662
+ seen.add(inspected.hash)
2663
+ const record = state.documents?.[inspected.hash]
2664
+ if (record === undefined) {
2665
+ unknown.push(pdfPath)
2666
+ continue
2667
+ }
2668
+ const sourceDir = dirname(resolve(pdfPath))
2669
+ if (record.sourceDir === sourceDir && record.sourcePdfPath === resolve(pdfPath)) {
2670
+ already += 1
2671
+ continue
2672
+ }
2673
+ // dryRun 只报「会绑成什么」:用户看到清单之前不该先被写进记录。
2674
+ if (!dryRun) await repository.updateDocument(inspected.hash, document => { document.sourceDir = sourceDir; document.sourcePdfPath = resolve(pdfPath) })
2675
+ bound.push({ documentId: inspected.hash, pdfName: record.pdfName, sourceDir })
2676
+ }
2677
+ }
2678
+ // 「库里有、磁盘上没有」是这条路由自己看不见的那一半(它从磁盘出发找记录)。
2679
+ // 报个总数出去,免得又得去翻库文件才发现漏了一篇。
2680
+ const unboundCount = dryRun
2681
+ ? undefined
2682
+ : (await rawDocuments()).filter(document => typeof document.sourceDir !== 'string' || document.sourceDir === '').length
2683
+ return {
2684
+ ok: true,
2685
+ ...(dryRun ? { dryRun: true } : {}),
2686
+ scanned,
2687
+ already,
2688
+ bound,
2689
+ unknown,
2690
+ failures,
2691
+ ...(unboundCount === undefined ? {} : { unboundCount }),
2692
+ }
2693
+ }
2694
+
2695
+ /**
2696
+ * 记录 → 目录:把某条记录的 sourceDir 显式指到一个文件夹,或清空(`dir` 为空)。
2697
+ *
2698
+ * 与 bindSourceDirs 方向相反,判据也不同:bind 按**内容哈希**认篇,PDF 换过版本就永远
2699
+ * 匹配不上;这里按**用户指认**认篇 —— 改的是「这条记录属于哪个文件夹」,不是「这个
2700
+ * 文件夹里的 PDF 是哪条记录」。于是换版之后旧记录(连同划线、笔记、译文)能继续用,
2701
+ * 不必删掉重入。
2702
+ *
2703
+ * 🔴 只改记录里的一个字段:不解析、不复制、不碰用户目录里的任何文件。
2704
+ * 落盘前过与 publishDocument 同一条 isWithin 判据 —— runtime 里的副本不能当用户目录记下来。
2705
+ *
2706
+ * @param {string} documentId 论文 id
2707
+ * @param {string} dir 文件夹绝对路径;空串表示解绑
2708
+ * @returns {Promise<{ok: boolean, notice: string, sourceDir?: string}>} 一句话回执
2709
+ */
2710
+ async function setSourceDir(documentId, dir) {
2711
+ const wanted = typeof dir === 'string' ? dir.trim() : ''
2712
+ const reject = (message, status) => {
2713
+ const error = new Error(message)
2714
+ error.status = status
2715
+ throw error
2716
+ }
2717
+ if (wanted !== '') {
2718
+ if (!isAbsolute(wanted)) reject('dir 必须是绝对路径:' + wanted, 400)
2719
+ if (isWithin(resolve(repository.root), resolve(wanted))) reject('这是插件自己的运行目录,不能记成论文的源目录', 400)
2720
+ let info
2721
+ try { info = await stat(wanted) } catch { info = null }
2722
+ if (info === null || !info.isDirectory()) reject('这个文件夹不存在或不是目录:' + wanted, 400)
2723
+ }
2724
+ const record = await libraryDocumentOf(documentId)
2725
+ if (record === null) reject('找不到这篇论文。', 404)
2726
+
2727
+ const apply = document => {
2728
+ if (wanted === '') delete document.sourceDir
2729
+ else document.sourceDir = wanted
2730
+ delete document.sourcePdfPath
2731
+ }
2732
+ const state = await repository.snapshot()
2733
+ if (state.documents?.[documentId] !== undefined) {
2734
+ await repository.updateDocument(documentId, apply)
2735
+ } else {
2736
+ // 冷归档记录不在 state.documents 里,updateDocument 会抛;直接重写它自己的归档记录。
2737
+ const next = { ...record }
2738
+ apply(next)
2739
+ await repository.writeArchivedDocument(next)
2740
+ }
2741
+
2742
+ if (wanted === '') return { ok: true, notice: '已解绑这篇的源目录(划线与笔记都在,没有动)。' }
2743
+
2744
+ // 指认的文件夹里有没有这篇的 PDF:一致时说明白,不一致时更要说明白 ——
2745
+ // 「换版本后指过去」正是这个动作最常见的用法,别让人以为记录里那份正文也跟着换了。
2746
+ let note = ''
2747
+ try {
2748
+ const scanned = await scanFolder(wanted)
2749
+ const pdfs = Array.isArray(scanned?.pdfs) ? scanned.pdfs : []
2750
+ if (pdfs.length === 0) {
2751
+ note = '(这个文件夹里没有 PDF)'
2752
+ } else {
2753
+ // 只试前几个:一份分类根目录下可能有几十篇,逐份算哈希会把一次改名拖成几十秒。
2754
+ const same = (await Promise.all(pdfs.slice(0, 5).map(path => inspectPdf(path).then(info => info.hash === documentId, () => false))))
2755
+ .some(Boolean)
2756
+ note = same
2757
+ ? '(内容与库记录一致)'
2758
+ : '(文件夹里的 PDF 与库记录内容不同:库里的仍是旧那份,要换正文得重新入库)'
2759
+ }
2760
+ } catch { /* 目录读不动不影响绑定本身 */ }
2761
+ return { ok: true, notice: '已把源目录指到 ' + wanted + note, sourceDir: wanted }
2762
+ }
2763
+
2764
+ async function libraryWriteRoutes(request, url, rest, body) {
2765
+ if (request.method === 'POST' && ['/bibliography-import', '/bibliography-export', '/citation-styles'].includes(rest)) {
2766
+ try {
2767
+ if (rest === '/bibliography-import') return json(await bibliographyService.run({ ...body, action: 'import' }))
2768
+ if (rest === '/citation-styles') {
2769
+ if (!['install', 'select'].includes(body.action)) return json({ error: '样式操作必须是 install / select' }, 400)
2770
+ return json(await bibliographyService.run({ ...body, action: 'style-' + body.action }))
2771
+ }
2772
+ const result = await bibliographyService.exportRecords(body.documentIds, body.format, body)
2773
+ const file = await toolHost.writeExportFile(result.exportId, '.' + result.extension, result.text)
2774
+ return json({ ...result, url: API_BASE + '/export?file=' + encodeURIComponent(basename(file)) })
2775
+ } catch (error) { return json({ error: errorText(error) }, 400) }
2776
+ }
2777
+ if (request.method === 'POST' && rest === '/metadata') {
2778
+ if (!/^[a-f0-9]{64}$/.test(body.documentId ?? '')) return json({ error: '论文 ID 无效' }, 400)
2779
+ try {
2780
+ return json(await toolHost.runLibraryRequest({ action: 'metadata', documentIds: [body.documentId],
2781
+ enrich: body.enrich === true, identifier: body.identifier, fields: body.fields, keep: body.keep, dryRun: body.dryRun !== false }))
2782
+ } catch (error) { return json({ error: errorText(error) }, 400) }
2783
+ }
2784
+ // D156:按文章名重命名(手动入口)。解析完成时已自动改过一次,这里是兜底 ——
2785
+ // 元数据当时没拿到、或用户之后想重来一次时用。
2786
+ if (request.method === 'POST' && rest === '/rename') {
2787
+ if (!/^[a-f0-9]{64}$/.test(body.documentId ?? '')) return json({ error: '重命名参数无效' }, 400)
2788
+ const snapshot = await repository.snapshot()
2789
+ const record = snapshot.documents[body.documentId] ?? await repository.archivedDocument(body.documentId)
2790
+ if (!record) return json({ error: '论文不存在' }, 404)
2791
+ const document = hydrateDocument(record)
2792
+ /**
2793
+ * 用户键入的名字(D181)。给了它就走**文件层改名**,与元数据那条路不共用推导:
2794
+ * - 不读 PDF 元数据、不抢先补标题 —— 用户已经给出了唯一依据;
2795
+ * - 不静默兜底(撞名/超长都拒绝),磁盘上的名字必须与打进去的一致。
2796
+ * 没给则维持下面的「按文章名重命名」,两条入口共用一个路由(旧面板没有任何改动)。
2797
+ */
2798
+ if (typeof body.name === 'string') {
2799
+ const typed = await renameDocument({
2800
+ repository,
2801
+ documentId: body.documentId,
2802
+ stem: body.name,
2803
+ logger: ctx.logger,
2804
+ })
2805
+ if (typed.reason === 'invalid-name' || typed.reason === 'no-name') {
2806
+ return json({ error: '名字不能为空,也不能只由文件名非法字符组成' }, 400)
2807
+ }
2808
+ if (typed.reason === 'name-too-long') {
2809
+ return json({ error: `名字太长了(上限 ${MAX_STEM_CHARS} 个字符),请缩短后再试` }, 400)
2810
+ }
2811
+ // 撞名是**可预期的拒绝**:409 让人自己换个名字,而不是替他加一串哈希。
2812
+ if (typed.reason === 'occupied') return json({ error: '这个名字已经被同目录的另一篇论文占用,请换一个' }, 409)
2813
+ // 记录在这两步之间被移除(另一个宿主 compact / 删除):说清楚没改,别让面板以为成功了。
2814
+ if (typed.reason === 'not-found') return json({ error: '论文不存在' }, 404)
2815
+ if (typed.reason === 'invalid-id') return json({ error: '重命名参数无效' }, 400)
2816
+ // 🔴 回读一次:`renameDocument` 可能只改了显示名(文件名本来就对),这时
2817
+ // 光看 `renamed` 会让面板报"未变"。title 才是界面显示的那个字段。
2818
+ // 用 readerDocumentOf 而不是直接查 state.documents:冷归档的论文不在热表里,
2819
+ // 直接查会把刚写进去的显示名读成空串。
2820
+ const after = await repository.snapshot()
2821
+ const afterRecord = await readerDocumentOf(after, body.documentId)
2822
+ return json({
2823
+ documentId: body.documentId,
2824
+ renamed: typed.renamed === true,
2825
+ // 文件名不变但显示名改掉了,同样是**成功了**,必须让面板说人话。
2826
+ titleUpdated: typed.titleUpdated === true,
2827
+ pdfName: typed.renamed === true ? typed.to : document.pdfName,
2828
+ title: typeof afterRecord?.title === 'string' && afterRecord.title !== '' ? afterRecord.title : '',
2829
+ source: 'typed',
2830
+ })
2831
+ }
2832
+ // 与自动改名同一条回退链:记录里的元数据 → PDF Info dict → 正文首个 heading。
2833
+ let heading = ''
2834
+ try {
2835
+ heading = titleFromBlocks((await readerBlocksOf(documentPaths(document).contentPath)).blocks)
2836
+ } catch (error) {
2837
+ ctx.logger.warn(`dsh-paper rename: 读取正文标题失败 ${errorText(error)}`)
2838
+ }
2839
+ const outcome = await renameAfterParse({
2840
+ repository,
2841
+ document,
2842
+ metadata: { title: record.title, authors: record.authors, year: record.year },
2843
+ heading,
2844
+ readPdfMetadata: typeof config.readPdfMetadata === 'function' ? config.readPdfMetadata : readPdfMetadata,
2845
+ logger: ctx.logger,
2846
+ // 🔴 手动点击 = 明确的用户意图,所以覆盖粘性标记(与自动改名不同)。
2847
+ force: true,
2848
+ })
2849
+ // 没有标题是**可预期的拒绝**,不是服务器错误:409 让面板能显示一句人话。
2850
+ if (outcome.reason === 'no-title') return json({ error: '这篇论文没有可用的标题,无法按文章名重命名' }, 409)
2851
+ return json({
2852
+ documentId: body.documentId,
2853
+ renamed: outcome.renamed === true,
2854
+ pdfName: outcome.renamed === true ? outcome.to : document.pdfName,
2855
+ // 改名依据来自哪一级(catalog / pdf / heading):面板据此提示"为什么改成了这个名字"。
2856
+ source: outcome.source ?? 'none',
2857
+ })
2858
+ }
2859
+
2860
+ if (request.method === 'POST' && rest === '/selection') {
2861
+ if (!validId(body.sessionId) || typeof body.selected !== 'boolean') return json({ error: '选择参数无效' }, 400)
2862
+ const batch = batchDocumentIds(body)
2863
+ if (batch.error) return json({ error: batch.error }, 400)
2864
+ const snapshot = await repository.snapshot()
2865
+ // 判定阶段一篇都不写:任何一篇不合格都只进失败清单,不会留下半套 desired。注入前必须
2866
+ // 读一遍 Markdown 确认非空(与单篇同一口径),所以并发判完再一次性落状态。
2867
+ // D176:**论文有没有挂在本会话侧栏**不再算不合格。
2868
+ //
2869
+ // 阅读器可以从**全局**文献库打开任何一篇(/reader 是库级查找、不看会话归属),
2870
+ // 于是「打开 → 点注入」这条路上,用户面对的是一篇本来就不在本会话侧栏的论文。
2871
+ // 旧口径在这里回 409「论文不在当前会话侧栏」,而按钮没有任何反馈 —— 用户报的
2872
+ // 「注入按钮点击无反应」就是它。这也违反 D133 定下的口径(「拦在这里只会造出
2873
+ // 『列表里点得到、点下去被拒』的死角」):这里改成**注入即关联**,与本会话挂上是
2874
+ // 这次动作的隐含结果(点「注入这个会话」本就是在说「把这篇挂到这个会话」)。
2875
+ //
2876
+ // 🔴 只放宽**本机库里已经有**的论文:库里没有的 id 仍然 409。区分靠 snapshot.documents,
2877
+ // 而不是靠 `attached` —— 后者会把这篇论文在别的会话里也一并放行。
2878
+ // 提示语也据此分开:库外是「论文不在本机文献库」,没挂到本会话不再是一种失败。
2879
+ const checked = await mapWithConcurrency(batch.ids, BATCH_CHECK_CONCURRENCY, async documentId => {
2880
+ const document = hydrateDocument(snapshot.documents[documentId])
2881
+ if (!document) return { documentId, error: '论文不在本机文献库', status: 409 }
2882
+ if (!body.selected) return { documentId }
2883
+ const markdown = await readFile(document.markdownPath, 'utf8').catch(() => '')
2884
+ if (markdown.trim() === '') return { documentId, pdfName: document.pdfName, error: 'Markdown 不存在或为空,不能注入', status: 409 }
2885
+ return { documentId }
2886
+ })
2887
+ const entries = checked.map((result, index) => (result.ok ? result.value : { documentId: batch.ids[index], error: result.error }))
2888
+ const accepted = entries.filter(entry => !entry.error).map(entry => entry.documentId)
2889
+ const failures = entries.filter(entry => entry.error)
2890
+ // 一篇都没接受时保持单篇时代的错误码语义:侧栏直接把这一行原因画出来。
2891
+ if (accepted.length === 0) return json({ error: failures[0]?.error ?? '没有可处理的论文' }, failures[0]?.status ?? 409)
2892
+ const { selection, updated, dropped } = await repository.update(state => {
2893
+ // 判定与写入之间另一个宿主可能删掉记录(两面共用同一份 runtime 状态),
2894
+ // 所以记录必须在锁内再核一次。
2895
+ //
2896
+ // 🔴 这里**不再**核会话归属(D176):归属在这一次动作里被主动建立,不是前置条件。
2897
+ // 以前的第二道核对读的是 `sessionDocumentIds(state, sessionId)` —— 那是从
2898
+ // `desired ∪ delivered` 反推出来的,**在 desired 还没写进去的时候它算不出来**,
2899
+ // 于是第一道门一放宽、第二道门照样把每一篇都判掉。
2900
+ const current = state.selections[body.sessionId] ?? { desired: [], delivered: [] }
2901
+ const attachedNow = new Set(sessionDocumentIds(state, body.sessionId))
2902
+ const desired = new Set(current.desired ?? [])
2903
+ const updated = []
2904
+ const dropped = []
2905
+ const newlyAttached = []
2906
+ for (const documentId of accepted) {
2907
+ if (!state.documents[documentId]) dropped.push({ documentId, error: '论文已被移除' })
2908
+ else {
2909
+ // D176:注入即关联。取消注入**不**动关联 —— 那只是「下一轮别再带它」,
2910
+ // 不是「从侧栏拿掉」(拿掉有 /delete 那条路)。
2911
+ // 🔴 同时写进 attachedNow:下面那次写回用的就是它。只 push 不改,
2912
+ // documentIds 永远不含新挂的这几篇(实测:desired 有了、侧栏里却没有)。
2913
+ if (body.selected && !attachedNow.has(documentId)) { newlyAttached.push(documentId); attachedNow.add(documentId) }
2914
+ const before = desired.has(documentId)
2915
+ if (body.selected) desired.add(documentId); else desired.delete(documentId)
2916
+ if (before !== desired.has(documentId)) updated.push(documentId)
2917
+ }
2918
+ }
2919
+ state.selections[body.sessionId] = {
2920
+ ...current,
2921
+ documentIds: [...attachedNow],
2922
+ desired: [...desired],
2923
+ delivered: current.delivered ?? [],
2924
+ }
2925
+ // 与 attachDocument 同一条口径:新挂上来的那几篇顺带解开 hidden —— 否则会出现
2926
+ // 「已注入但侧栏里看不见」的半套状态。只碰这一次新挂的,不横扫已有归属。
2927
+ for (const documentId of newlyAttached) state.documents[documentId].hidden = false
2928
+ return { selection: state.selections[body.sessionId], updated, dropped }
2929
+ })
2930
+ const rejected = [...failures, ...dropped]
2931
+ return json({
2932
+ selection,
2933
+ updated: updated.length,
2934
+ unchanged: accepted.length - updated.length - dropped.length,
2935
+ skipped: rejected.length,
2936
+ failures: rejected.slice(0, MAX_BATCH_FAILURES),
2937
+ })
2938
+ }
2939
+
2940
+ if (request.method === 'POST' && rest === '/delete') {
2941
+ if (!validId(body.sessionId)) return json({ error: '删除参数无效' }, 400)
2942
+ const batch = batchDocumentIds(body)
2943
+ if (batch.error) return json({ error: batch.error }, 400)
2944
+ const snapshot = await repository.snapshot()
2945
+ const attached = new Set(selectionView(snapshot, body.sessionId).documentIds)
2946
+ const entries = batch.ids.map(documentId => (!snapshot.documents[documentId]
2947
+ ? { documentId, error: '论文不存在' }
2948
+ : (!attached.has(documentId)
2949
+ ? { documentId, pdfName: snapshot.documents[documentId].pdfName, error: '论文不在当前会话侧栏' }
2950
+ : { documentId })))
2951
+ const accepted = entries.filter(entry => !entry.error).map(entry => entry.documentId)
2952
+ const rejected = entries.filter(entry => entry.error)
2953
+ // 与 /selection 同理:全批都没可摘的条目时回到单篇时代的 404,侧栏显示那一行原因。
2954
+ if (accepted.length === 0) return json({ error: rejected[0]?.error ?? '没有可处理的论文' }, 404)
2955
+ // 整批一次状态写入:摘关联与标 hidden 没有单篇成败的差别,逐篇 update 会把 state.json
2956
+ // 重写 N 遍、逐篇抢跨进程状态锁(与 /scan 的批量收口同一个理由)。
2957
+ const { removed, dropped } = await repository.update(state => {
2958
+ const drop = new Set(accepted)
2959
+ const current = state.selections[body.sessionId] ?? { desired: [], delivered: [] }
2960
+ state.selections[body.sessionId] = {
2961
+ ...current,
2962
+ documentIds: sessionDocumentIds(state, body.sessionId).filter(id => !drop.has(id)),
2963
+ desired: (current.desired ?? []).filter(id => !drop.has(id)),
2964
+ delivered: (current.delivered ?? []).filter(id => !drop.has(id)),
2965
+ deliveredUnavailable: (current.deliveredUnavailable ?? []).filter(id => !drop.has(id)),
2966
+ }
2967
+ // 关联已重写,所以此后还挂着的就是别的会话:整批算一次,逐篇 documentIsAttached
2968
+ // 会退化成 O(篇数 × 任务数) 的重扫(compact 当年踩过同一个坑)。
2969
+ const stillAttached = attachedDocumentIds(state)
2970
+ const removed = []
2971
+ const dropped = []
2972
+ for (const documentId of accepted) {
2973
+ const document = state.documents[documentId]
2974
+ if (!document) { dropped.push({ documentId, error: '论文已被移除' }); continue }
2975
+ document.hidden = !stillAttached.has(documentId)
2976
+ removed.push(documentId)
2977
+ }
2978
+ return { removed, dropped }
2979
+ })
2980
+ await repository.compact()
2981
+ return json({
2982
+ ok: true,
2983
+ removed: removed.length,
2984
+ skipped: rejected.length + dropped.length,
2985
+ failures: [...rejected, ...dropped].slice(0, MAX_BATCH_FAILURES),
2986
+ })
2987
+ }
2988
+
2989
+ // 文献库与篇级标记的写入(T21)。动作分两类:
2990
+ // - 库级(category-add / category-remove / sort):改 runtime/dsh-paper/library.json;
2991
+ // - 篇级(star / status / tag / untag / trash / restore / opened):改该篇的 item.json。
2992
+ // 两类共用一条路由,因为校验与"找到这篇"完全一致;分成两条只会让客户端多一处分支。
2993
+ if (request.method === 'POST' && rest === '/library') {
2994
+ const action = typeof body.action === 'string' ? body.action : ''
2995
+ // 目录 → 记录(bind):与 Paper_library 的 bind 同一份实现(见 bindSourceDirs)。
2996
+ if (action === 'bind') {
2997
+ try {
2998
+ return json(await bindSourceDirs(body.dir, { dryRun: body.dryRun === true }))
2999
+ } catch (error) {
3000
+ return json({ error: errorText(error) }, error?.status === 400 ? 400 : 500)
3001
+ }
3002
+ }
3003
+ try {
3004
+ const result = await libraryService.handle(body)
3005
+ if (result !== null) return json(result)
3006
+ } catch (error) { return json({ error: errorText(error) }, 400) }
3007
+ if (['category-add', 'category-remove', 'category-rename', 'category-move', 'group-hide', 'group-pin', 'sort'].includes(action)) {
3008
+ const library = await readLibrary(libraryFile)
3009
+ if (action === 'sort') {
3010
+ if (!SORT_MODES.includes(body.sort)) return json({ error: '排序方式无效' }, 400)
3011
+ await writeLibrary(libraryFile, { ...library, sort: body.sort })
3012
+ return json({ library: await readLibrary(libraryFile) })
3013
+ }
3014
+ // 库级动作分两族:改分类清单(add / remove / rename / move)与改侧栏标记
3015
+ // (group-hide / group-pin,对象既可以是内置视图桶也可以是自建分类)。
3016
+ // 它们的校验与"找到这篇论文"无关,所以都在 validId 之前返回。
3017
+ const named = typeof body.category === 'string' && body.category.trim() !== ''
3018
+ let next
3019
+ try {
3020
+ if (action === 'group-hide' || action === 'group-pin') {
3021
+ const pin = action === 'group-pin'
3022
+ const flag = pin ? body.pinned !== false : body.hidden !== false
3023
+ const view = typeof body.view === 'string' ? body.view.trim() : ''
3024
+ if (view !== '') next = pin ? setViewPinned(library, view, flag) : setViewHidden(library, view, flag)
3025
+ else {
3026
+ if (!named) return json({ error: '分类名不能为空' }, 400)
3027
+ next = pin ? setCategoryPinned(library, body.category, flag) : setCategoryHidden(library, body.category, flag)
3028
+ }
3029
+ } else if (action === 'category-rename') {
3030
+ if (!named) return json({ error: '分类名不能为空' }, 400)
3031
+ if (typeof body.next !== 'string' || body.next.trim() === '') return json({ error: '新分类名不能为空' }, 400)
3032
+ next = renameCategory(library, body.category, body.next)
3033
+ } else if (action === 'category-move') {
3034
+ if (!named) return json({ error: '分类名不能为空' }, 400)
3035
+ next = moveCategory(library, body.category, Number.isInteger(body.delta) ? body.delta : 0)
3036
+ } else {
3037
+ if (!named) return json({ error: '分类名不能为空' }, 400)
3038
+ // 超上限由 upsertCategory 抛错(它知道"已满但改的是既有条目仍放行"这条细则),
3039
+ // 这里只把它收成 400,不让一次用户输入变成 500。
3040
+ next = action === 'category-add' ? upsertCategory(library, body.category) : removeCategory(library, body.category)
3041
+ }
3042
+ } catch (error) {
3043
+ return json({ error: errorText(error) }, 400)
3044
+ }
3045
+ await writeLibrary(libraryFile, next)
3046
+ if (action !== 'category-rename') return json({ library: await readLibrary(libraryFile) })
3047
+ // 🔴 改名还要把**每一篇的 tags**一起改。库级三处(清单 / hidden / pinned)由
3048
+ // renameCategory 负责,逐篇这一步只能落在这里 —— 纯函数不碰磁盘(D114)。
3049
+ const from = body.category.trim().toLowerCase()
3050
+ const to = body.next.trim()
3051
+ let renamed = 0
3052
+ const failures = []
3053
+ for (const raw of await rawDocuments()) {
3054
+ const path = itemPathOf(runtimeRoot(config), raw)
3055
+ if (path === '') continue
3056
+ const current = await readItem(path)
3057
+ if (!current.tags.some(tag => tag.toLowerCase() === from)) continue
3058
+ try {
3059
+ await writeItem(path, { ...current, tags: current.tags.map(tag => (tag.toLowerCase() === from ? to : tag)) })
3060
+ renamed += 1
3061
+ } catch (error) {
3062
+ // 单篇写失败不回滚:清单已经改了。如实报出哪几篇没跟上,好过整次操作失败却说不清状态。
3063
+ failures.push({ documentId: raw.id, error: errorText(error) })
3064
+ }
3065
+ }
3066
+ return json({ library: await readLibrary(libraryFile), renamed, failures: failures.slice(0, MAX_BATCH_FAILURES) })
3067
+ }
3068
+ // 清空回收站:逐篇按 purge 删 runtime 目录。一篇失败不影响其余,最后如实回报成败数。
3069
+ // 不放「超过 N 天自动清空」—— 插件的既有裁定是不做任何按天数的自动删除(P1/T5)。
3070
+ if (action === 'empty-trash') {
3071
+ const root = runtimeRoot(config)
3072
+ const purged = []
3073
+ const failures = []
3074
+ for (const raw of await rawDocuments()) {
3075
+ const itemPath = itemPathOf(root, raw)
3076
+ if (itemPath === '') continue
3077
+ const item = await readItem(itemPath)
3078
+ if (!canPurge(item).ok) continue
3079
+ try {
3080
+ const result = await purgeDocument({
3081
+ runtimeRoot: root,
3082
+ repository,
3083
+ logger: ctx.logger,
3084
+ documentId: raw.id,
3085
+ pdfName: typeof raw.pdfName === 'string' ? raw.pdfName : '',
3086
+ tasks: taskStore,
3087
+ })
3088
+ purged.push({ documentId: raw.id, files: result.files })
3089
+ } catch (error) {
3090
+ failures.push({ documentId: raw.id, error: errorText(error) })
3091
+ }
3092
+ }
3093
+ if (purged.length > 0) ctx.logger.info(`dsh-paper empty-trash: 永久删除 ${purged.length} 篇`)
3094
+ if (purged.length > 0) await libraryService.forget(purged.map(row => row.documentId))
3095
+ // 逐篇失败不吞:面板据 failures 如实显示,而不是回一句「已清空」。
3096
+ return json({ purged: purged.length, files: purged.reduce((sum, one) => sum + one.files, 0), failures: failures.slice(0, MAX_BATCH_FAILURES) })
3097
+ }
3098
+ if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
3099
+ const raw = await libraryDocumentOf(body.documentId)
3100
+ if (raw === null) return json({ error: '论文不存在' }, 404)
3101
+ const root = runtimeRoot(config)
3102
+ // 永久删除必须在 `path === ''` 那个兜底分支**之前**处理:单篇真删不依赖 item.json 的
3103
+ // 位置(非 sidecar 的冷记录同样有资产目录),落到下面那条分支就永远删不掉了。
3104
+ // 🔴 只有回收站里的能删(canPurge,fail closed);删的是 runtime 里的目录,不碰论文目录。
3105
+ if (action === 'purge') {
3106
+ const itemPath = itemPathOf(root, raw)
3107
+ const item = itemPath === '' ? normalizeItem(null) : await readItem(itemPath)
3108
+ const allowed = canPurge(item)
3109
+ if (!allowed.ok) return json({ error: allowed.reason }, 409)
3110
+ try {
3111
+ const purged = await purgeDocument({
3112
+ runtimeRoot: root,
3113
+ repository,
3114
+ logger: ctx.logger,
3115
+ documentId: body.documentId,
3116
+ pdfName: typeof raw.pdfName === 'string' ? raw.pdfName : '',
3117
+ tasks: taskStore,
3118
+ })
3119
+ ctx.logger.info(`dsh-paper purge: 已永久删除 ${body.documentId}(${purged.files} 个文件、${purged.jobs} 条任务记录)`)
3120
+ await libraryService.forget([body.documentId])
3121
+ return json({ documentId: body.documentId, purged: true, files: purged.files, jobs: purged.jobs })
3122
+ } catch (error) {
3123
+ ctx.logger.warn(`dsh-paper purge: ${errorText(error)}`)
3124
+ return json({ error: `永久删除失败:${errorText(error)}` }, 500)
3125
+ }
3126
+ }
3127
+ const path = itemPathOf(root, raw)
3128
+ // 🔴 写路径上「没有条目位置」绝不能降级成成功:条目文件是标记的唯一落点,定位不到就
3129
+ // 意味着这次写入一定不会发生。旧写法回 200 + 默认条目,于是「移入回收站」报成功、
3130
+ // 实际一个字节都没写、回收站里也看不到它 —— 假成功比报错坏得多。
3131
+ // 例外只有 opened / progress:它们是阅读时的被动记账,每一屏都可能发一次,为一条
3132
+ // 旧记录把面板刷满 409 没有意义;这两个仍然如实回 stored: false(D101 的降级只针对读)。
3133
+ if (path === '') {
3134
+ if (body.action === 'opened' || body.action === 'progress') {
3135
+ return json({ documentId: body.documentId, item: normalizeItem(null), stored: false })
3136
+ }
3137
+ const verb = {
3138
+ trash: '移入回收站',
3139
+ restore: '从回收站还原',
3140
+ star: '修改星标',
3141
+ pin: '修改置顶',
3142
+ status: '修改阅读状态',
3143
+ tag: '添加标签',
3144
+ untag: '移除标签',
3145
+ }[body.action]
3146
+ return json({
3147
+ error: '这篇论文没有条目位置(D127 之前的非 sidecar 记录),无法' + (verb ?? '保存标记'),
3148
+ reason: 'no-item-store',
3149
+ }, 409)
3150
+ }
3151
+ const current = await readItem(path)
3152
+ // 与 Paper_library 工具共用同一份算法(lib/item-ops.js):星标/置顶/状态/标签/回收站/
3153
+ // 打开时间/阅读进度都只在这里定义一次,两处不会再各写一遍去重或校验。
3154
+ let next
3155
+ try {
3156
+ next = applyItemAction(current, {
3157
+ action,
3158
+ starred: body.starred,
3159
+ pinned: body.pinned,
3160
+ status: body.status,
3161
+ tag: body.tag,
3162
+ advanceStatus: body.advanceStatus,
3163
+ ratio: body.ratio,
3164
+ block: body.block,
3165
+ })
3166
+ } catch (error) {
3167
+ return json({ error: errorText(error) }, 400)
3168
+ }
3169
+ const stored = await writeItem(path, next)
3170
+ return json({ documentId: body.documentId, item: stored, stored: true })
3171
+ }
3172
+
3173
+ // 导出(T23)。三个动作:
3174
+ // - html:离线单文件 HTML(含译文、公式、原页图、划线笔记),**双击可读、不需要插件**;
3175
+ // - citation:三种引用格式之一;
3176
+ // - notes:笔记 Markdown。
3177
+ // 三者都要读同一份块列表 / 译文 / 划线 / 边注,所以共用一条路由 —— 分三条会让同一套
3178
+ // 读取逻辑写三遍,而它们的失败口径完全相同。
3179
+ if (request.method === 'POST' && rest === '/export') {
3180
+ if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
3181
+ // 实现收在 exportFor 里:Paper_library 的 citation / notes / html 走同一份,
3182
+ // 否则「界面导出的」和「模型导出的」迟早会在某一格式上分叉。
3183
+ try {
3184
+ return json(await toolHost.exportFor(
3185
+ body.documentId,
3186
+ typeof body.action === 'string' ? body.action : 'html',
3187
+ typeof body.format === 'string' ? body.format : 'gb-t-7714',
3188
+ { style: body.style, locale: body.locale, mode: body.mode },
3189
+ ))
3190
+ } catch (error) {
3191
+ const message = errorText(error)
3192
+ return json({ error: message }, message === '论文不存在' ? 404 : 400)
3193
+ }
3194
+ }
3195
+
3196
+ // 把这篇的 Markdown 与正文引用的图片复制到它的**源文件夹**(文献库右键触发)。
3197
+ //
3198
+ // 🔴 这是全插件**唯一**会往用户目录写文件的入口:入库时的自动旁挂已按用户裁定删除
3199
+ // (见 resolver.publishDocument 的注释)。理由很直接 —— 用户的项目目录是他的仓库,
3200
+ // 派生文件该不该出现在那里,只有他自己点那一下才能决定。
3201
+ //
3202
+ // 🔴 源文件夹必须**已经在**:它可能被移动或删掉了,此时报错而不是替用户在那里
3203
+ // 新建一个同名目录 —— 「按记录里的路径凭空造出目录」比失败更难解释。
3204
+ if (request.method === 'POST' && rest === '/mirror') {
3205
+ if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
3206
+ const state = await repository.snapshot()
3207
+ const raw = await readerDocumentOf(state, body.documentId)
3208
+ if (!raw) return json({ error: '论文不存在' }, 404)
3209
+ const document = hydrateDocument(raw)
3210
+ const sourceDir = typeof document.sourceDir === 'string' ? document.sourceDir.trim() : ''
3211
+ if (sourceDir === '') {
3212
+ return json({ error: '这篇没有源文件夹:它来自链接 / arXiv 下载,或还没有绑定目录' }, 400)
3213
+ }
3214
+ try {
3215
+ if (!(await stat(resolve(sourceDir))).isDirectory()) throw new Error('not-a-directory')
3216
+ } catch {
3217
+ return json({ error: '源文件夹已不在了:' + sourceDir }, 400)
3218
+ }
3219
+ try {
3220
+ // 目标 md 的主名取**用户磁盘上的原件名**(`sourcePdfPath` 的 basename),不用记录里
3221
+ // 那个可能已被 D156 改名成「作者 - 年份 - 标题」的 `pdfName` —— 否则写出去的 md 与
3222
+ // 用户文件夹里那个 PDF 同名不上,一眼看不出是一对。
3223
+ const sourceName = basename(document.sourcePdfPath || document.pdfPath || '') || document.pdfName
3224
+ const result = await mirrorParseResult({
3225
+ markdownPath: document.markdownPath,
3226
+ sourceName,
3227
+ sourceDir,
3228
+ runtimeRoot: repository.root,
3229
+ logger: ctx.logger,
3230
+ })
3231
+ return json({ ...result, sourceDir })
3232
+ } catch (error) {
3233
+ return json({ error: errorText(error) }, 400)
3234
+ }
3235
+ }
3236
+
3237
+ return undefined
3238
+ }
3239
+
3240
+ /** 写入路由(需要 body):阅读器与批注。 */
3241
+ async function readerWriteRoutes(request, url, rest, body) {
3242
+ // D73 的自动翻译触发点(D77 把它定在宿主侧,客户端只负责说一声"打开了这篇")。
3243
+ // 🔴 **绝不因翻译失败而失败**:打开是主路径,翻译是副产物,副产物不能挡住主路径。
3244
+ // 设置关着、宿主没有 llm、队列重复入队、模型解析不到——全都在这里收成一句 reason。
3245
+ if (request.method === 'POST' && rest === '/open') {
3246
+ if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
3247
+ if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
3248
+ const state = await repository.snapshot()
3249
+ const raw = await readerDocumentOf(state, body.documentId)
3250
+ if (!raw) return json({ error: '论文不存在' }, 404)
3251
+ const translation = { started: false, reason: undefined }
3252
+ try {
3253
+ const outcome = await autoTranslate(raw, body.sessionId)
3254
+ translation.started = outcome?.skipped === undefined
3255
+ if (typeof outcome?.skipped === 'string') translation.reason = outcome.skipped
3256
+ } catch (error) {
3257
+ // 🔴 预检 already-queued 与**入队时**被拒是同一个状态,只是后者发生在两次调用之间的
3258
+ // 窗口里(两次 /open 并发,或 /open 撞上 /translate)。这里必须回同一个结构化 reason ——
3259
+ // 拼原始消息的话,客户端会把它渲染成红字「自动翻译没能排上队:任务 … 已在队列中」,
3260
+ // 而那恰恰是「都翻译完了为什么还有排队」那类误报的来源。
3261
+ const benignRace = error?.reason === 'already-queued'
3262
+ const reason = benignRace ? 'already-queued' : errorText(error)
3263
+ if (!benignRace) ctx.logger.warn(`dsh-paper open: 论文 ${truncateForLog(body.documentId)} 自动翻译未能开始:${reason}`)
3264
+ translation.reason = reason
3265
+ }
3266
+ return json({ opened: true, translation })
3267
+ }
3268
+
3269
+ // 打开原 PDF(详情页与侧栏的「打开原 PDF」)。客户端页面跑在 http://127.0.0.1,
3270
+ // window.open('file:///…') 会被浏览器按 "Not allowed to load local resource" 静默拦掉,
3271
+ // 所以必须在宿主侧用系统默认程序打开。只认 documentId、路径从仓库记录里解析 ——
3272
+ // 不接受调用方递来的任意路径。
3273
+ if (request.method === 'POST' && rest === '/open-pdf') {
3274
+ if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
3275
+ const state = await repository.snapshot()
3276
+ const record = state.documents[body.documentId] ?? await repository.archivedDocument(body.documentId)
3277
+ if (!record) return json({ error: '论文不存在' }, 404)
3278
+ const pdfPath = hydrateDocument(record).pdfPath
3279
+ if (typeof pdfPath !== 'string' || pdfPath === '') return json({ error: '这篇论文没有 PDF 路径' }, 404)
3280
+ try {
3281
+ await stat(pdfPath)
3282
+ } catch {
3283
+ return json({ error: `PDF 文件不在磁盘上:${pdfPath}` }, 404)
3284
+ }
3285
+ // rundll32 url.dll,FileProtocolHandler = 让 Windows 按文件关联的默认程序打开(等价双击)。
3286
+ // 不走 cmd /c start:cmd /c 的引号剥离规则会吃掉带空格路径的引号、按空格截断(实测复现:
3287
+ // "Ashish Rana et al. - ….pdf" 被截成 …\Ashish 报"找不到文件")。
3288
+ const child = spawn('rundll32', ['url.dll,FileProtocolHandler', pdfPath], { stdio: 'ignore', detached: true })
3289
+ // spawn 的异步失败走 error 事件;不挂监听会变成宿主的未捕获异常。
3290
+ child.on('error', error => ctx.logger.warn(`dsh-paper open-pdf: ${errorText(error)}`))
3291
+ child.unref()
3292
+ return json({ ok: true })
3293
+ }
3294
+
3295
+ // 选区即时释义(D160)。读者在正文里选中一小段,条上当场多出一行译文。
3296
+ //
3297
+ // 🔴 它**排进与整篇翻译同一道全局闸门**(D157):那一档的上限就是"整个宿主同时在飞的
3298
+ // 模型请求数",再开一条独立的并发路等于把用户刚裁定过的那个数又撕开一个口子。
3299
+ // 代价写在明处——长篇翻译正占满名额时这条短译要排队等,客户端显示「排队中…」。
3300
+ //
3301
+ // 🔴 一次请求**不重试**:结果是给读者"顺手看一眼"的,自动重试让最坏延迟翻倍,
3302
+ // 而畸形回复在界面上的表现只是多一次点击「重试」。
3303
+ if (request.method === 'POST' && rest === '/gloss') {
3304
+ if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
3305
+ if (typeof body.quote !== 'string' || body.quote.trim() === '') return json({ error: '没有选中内容' }, 400)
3306
+ // 折掉行内标签**且只折一次**:提示词与记账键必须看到同一个串,否则同一个选区会记成两笔。
3307
+ const glossQuote = plainInlineText(body.quote)
3308
+ const state = await repository.snapshot()
3309
+ const raw = await readerDocumentOf(state, body.documentId)
3310
+ if (!raw) return json({ error: '论文不存在' }, 404)
3311
+ const document = hydrateDocument(raw)
3312
+ // 参考段分两半,来源不同:
3313
+ // · 论文标题 + 摘要 —— 由**磁盘上的块列表**现算(与整篇翻译同一函数,D140);
3314
+ // · 选区所在整段 —— 按客户端给的块 id 取**磁盘上的 sourceText**,不信任客户端的正文
3315
+ // (它可能被改过、也可能是另一篇的)。取不到就整段不带,不是错误。
3316
+ let blocks = (await readerBlocksOf(documentPaths(document).contentPath)).blocks
3317
+ const blockId = typeof body.blockId === 'string' ? body.blockId : ''
3318
+ let block = Array.isArray(blocks) ? blocks.find(item => item?.id === blockId) : undefined
3319
+ let sourceContext = plainInlineText(typeof block?.sourceText === 'string' ? block.sourceText : '')
3320
+ let nativeContext = ''
3321
+ if (body.pdfPage !== undefined) {
3322
+ if (!Number.isSafeInteger(body.pdfPage) || body.pdfPage < 1) return json({ error: 'PDF 页码无效' }, 400)
3323
+ const native = await pdfPageFor(document, body.pdfPage, blocks)
3324
+ nativeContext = native.groups.find(group => group.id === blockId)?.text ?? ''
3325
+ if (nativeContext) sourceContext = nativeContext
3326
+ }
3327
+ let counterpart = ''
3328
+ let selectedContext = ''
3329
+ if (body.align === true) {
3330
+ const store = await readReaderStore(readerPathOf(document))
3331
+ const mark = (Array.isArray(store?.marks)?store.marks:[]).find(mark=>mark.id===body.markId && mark.blockId===blockId && plainInlineText(mark.quote)===glossQuote)
3332
+ if (!mark) return json({reason:'no-match',error:'划线已删除或改变'})
3333
+ selectedContext = plainInlineText((mark.prefix ?? '') + mark.quote + (mark.suffix ?? ''))
3334
+ blocks = mergeReaderBlocks(blocks, await readTranslation(translationPathOf(document)))
3335
+ block = blocks.find(row => row.id === blockId)
3336
+ const source = nativeContext || plainInlineText(block?.sourceText ?? ''), translated = plainInlineText(block?.zh ?? '')
3337
+ if (!source || !translated || !glossQuote.trim()) return json({reason:'no-match'})
3338
+ // Anchor against the selected language; the model must copy from the other one.
3339
+ const inSource = source.includes(glossQuote), inTranslation = translated.includes(glossQuote)
3340
+ const fromSource = mark.sourceLanguage === 'source' ? true : mark.sourceLanguage === 'translation' ? false : inSource
3341
+ if (!mark.sourceLanguage && inSource && inTranslation) return json({reason:'already-matched'})
3342
+ if (fromSource ? !inSource : !inTranslation) return json({reason:'no-match'})
3343
+ sourceContext = fromSource ? source : translated
3344
+ counterpart = fromSource ? translated : source
3345
+ if (Math.max(sourceContext.length,counterpart.length) > 60000) return json({reason:'no-match',error:'段落过长,未执行自动匹配'})
3346
+ }
3347
+ const settings = state.settings
3348
+ const model = await resolveTranslationModel()
3349
+ translationGate.setLimit(concurrencyOf(settings))
3350
+ const outcome = await translateSelection({
3351
+ quote: glossQuote,
3352
+ context: sourceContext,
3353
+ counterpart,
3354
+ selectedContext,
3355
+ reference: documentReferenceOf(Array.isArray(blocks) ? blocks : []),
3356
+ targetLanguage: settings?.translationLanguage,
3357
+ }, {
3358
+ llm: (translateHostOptions() ?? {}).llm,
3359
+ model,
3360
+ glossary: await glossaryBlockFor(),
3361
+ gate: translationGate,
3362
+ })
3363
+ // 记账与翻译同一口径(T24):键是(文档 + 原话)的确定性哈希,所以同一个词翻两次
3364
+ // 在账本里仍是一条 —— 这一档本就分辨不出"两次真实调用"与"同一次被观测两遍"。
3365
+ // 记账失败不影响结果(recordUsage 自己收异常)。
3366
+ if (outcome.usage !== undefined) {
3367
+ // 这一档**不等**记账(释义不该等一次写盘),所以必须自己登记拒绝处理:
3368
+ // `void promise` 对 rejected promise 不做事,等于一个未处理拒绝(审查 F30 实测两条)。
3369
+ void recordUsage(outcome.usage, { jobId: glossUsageKey(body.documentId, glossQuote) + (body.align === true ? ':align' : ''), documentId: body.documentId, model }).catch(() => {})
3370
+ }
3371
+ if (body.align === true && outcome.ok) {
3372
+ return await serializeMarks(async () => {
3373
+ const path = readerPathOf(document)
3374
+ if (!path) return json({reason:'no-match'})
3375
+ // 写入路径必须用严格读:这里要基于文件内容改写,坏读降级成空表等于把整篇划线换掉。
3376
+ const store = await readReaderStoreForWrite(path)
3377
+ const marks = Array.isArray(store?.marks) ? [...store.marks] : []
3378
+ const index = marks.findIndex(mark => mark.id === body.markId && mark.blockId === blockId && plainInlineText(mark.quote) === glossQuote)
3379
+ if (index < 0) return json({reason:'no-match',error:'划线已删除或改变'})
3380
+ const latestBlocks = mergeReaderBlocks((await readerBlocksOf(documentPaths(document).contentPath)).blocks, await readTranslation(translationPathOf(document)))
3381
+ const latest = latestBlocks.find(row=>row.id===blockId)
3382
+ const latestNative = nativeContext ? (await pdfPageFor(document, body.pdfPage, latestBlocks)).groups.find(group => group.id === blockId)?.text : ''
3383
+ const latestSource = latestNative || plainInlineText(latest?.sourceText ?? ''), latestTranslation = plainInlineText(latest?.zh ?? '')
3384
+ if (!([latestSource,latestTranslation].includes(sourceContext) && [latestSource,latestTranslation].includes(counterpart))) return json({reason:'no-match',error:'正文或译文已更新,请重新匹配'})
3385
+ marks[index] = {...marks[index],parallelQuote:outcome.zh}
3386
+ await writeReaderStore(path,{...store,marks})
3387
+ return json({markId:body.markId,parallelQuote:outcome.zh})
3388
+ })
3389
+ }
3390
+ if (outcome.ok) return json({ zh: outcome.zh })
3391
+ // 失败一律 200 + 结构化 reason:条上那一行要显示「说明 + 重试」,而 HTTP 错误会被
3392
+ // 客户端渲染成红字 —— 释义失败不该让整篇正文顶着一条红色告警。
3393
+ return json({ reason: outcome.reason, error: outcome.error })
3394
+ }
3395
+
3396
+ // 把「读者选中的那一部分」送进当前会话(P6)。
3397
+ //
3398
+ // 🔴 与 P5 的 /ask 的**语义差别**:那条是「插件自己的篇级问答」,用户裁定不要 ——
3399
+ // **对话一律走 DSH 官方对话框,插件不做自己的问答面板**。
3400
+ // 这条只做一件事:读者选中了一段内容时,把什么交给 agent。
3401
+ //
3402
+ // 两种范围(用户原话):
3403
+ // 没选内容 → 客户端根本不调这里,走 /selection 注入(论文 id + 论文名 + 章节树)
3404
+ // 选中内容 → 这条:上面全部 **+ 块 id + 选中原话 + 该段所在段落**
3405
+ //
3406
+ // 🔴 与 /discuss 同一条投递口径(D95):必须用 followup 唤醒驱动,投递失败不算 HTTP 失败。
3407
+ if (request.method === 'POST' && rest === '/select-ask') {
3408
+ if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
3409
+ if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
3410
+ if (typeof body.quote !== 'string' || body.quote.trim() === '') {
3411
+ return json({ error: '没有选中内容;就整篇提问请直接把论文注入会话' }, 400)
3412
+ }
3413
+ const state = await repository.snapshot()
3414
+ const raw = await readerDocumentOf(state, body.documentId)
3415
+ if (!raw) return json({ error: '论文不存在' }, 404)
3416
+ const document = hydrateDocument(raw)
3417
+ if (typeof document.markdownPath !== 'string' || document.markdownPath === '') {
3418
+ return json({ error: '这篇论文没有可用的 Markdown,无法送出选中内容' }, 400)
3419
+ }
3420
+ // 选中原话所在的那一段正文:客户端传来块 id,这里**从磁盘上的块列表取**它对应的
3421
+ // sourceText/zh —— 不信任客户端传来的正文(它可能被改过、也可能是另一篇的)。
3422
+ // 取不到就整段不带(消息里仍有块 id 与选中原话),不是错误。
3423
+ const blocks = (await readerBlocksOf(documentPaths(document).contentPath)).blocks
3424
+ const block = Array.isArray(blocks) ? blocks.find(item => item?.id === body.blockId) : undefined
3425
+ const message = buildSelectionMessage({
3426
+ document,
3427
+ // 🔴 章节树现读盘:记录上的 outlineText 是不落盘的缓存字段,照抄它等于每条
3428
+ // 选中消息都按"没有目录"降级。读不出来时仍可通过论文 id 调用 Paper_read。
3429
+ outlineText: await outlineTextOf(document),
3430
+ glossaryBlock: await glossaryBlockFor(),
3431
+ quote: body.quote,
3432
+ // 🔴 读者在确认条里敲的问题**必须原样带上**:它曾经在这里被丢掉 —— 客户端一路
3433
+ // 发到宿主,宿主却没读,于是界面显示「已送进会话」而问题根本没进上下文。
3434
+ question: typeof body.question === 'string' ? body.question : '',
3435
+ blockId: typeof body.blockId === 'string' ? body.blockId : '',
3436
+ blockText: plainInlineText(typeof block?.sourceText === 'string' ? block.sourceText : ''),
3437
+ id: randomUUID(),
3438
+ })
3439
+ const delivery = deliverToSession(body.sessionId, message)
3440
+ return json({ delivered: delivery.delivered, reason: delivery.reason })
3441
+ }
3442
+
3443
+ // 书目冲突交给 AI 处理(用户裁定):插件**不自己调模型**,把冲突表注入会话,
3444
+ // 由 agent 用自己的 Paper_library(action="metadata")判断并写入 —— 每一步都留在
3445
+ // 对话里可追溯,也不需要在插件里再养一套结构化输出契约。
3446
+ //
3447
+ // 🔴 冲突以**服务端此刻重新预览的判定**为准,不采信客户端回传的那份:界面上那份
3448
+ // 可能已经过期(这期间论文被别的入口改过),注入一份旧冲突只会让 agent 写错。
3449
+ if (request.method === 'POST' && rest === '/metadata-conflict-ask') {
3450
+ if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
3451
+ if (!/^[a-f0-9]{64}$/.test(body.documentId ?? '')) return json({ error: '论文 ID 无效' }, 400)
3452
+ const state = await repository.snapshot()
3453
+ const raw = await readerDocumentOf(state, body.documentId)
3454
+ if (!raw) return json({ error: '论文不存在' }, 404)
3455
+ let enrichment
3456
+ try {
3457
+ enrichment = await enrichMetadata(repository, body.documentId, metadataResolver, {
3458
+ dryRun: true,
3459
+ identifier: typeof body.identifier === 'string' && body.identifier !== '' ? body.identifier : undefined,
3460
+ })
3461
+ } catch (error) {
3462
+ return json({ error: '重新核对书目失败:' + errorText(error) }, 502)
3463
+ }
3464
+ // 三种「有东西要决定」都算:字段级冲突、版本级冲突(预印本 ↔ 正式出版,常常没有
3465
+ // 字段级 conflicts)、以及只有候选(没有一条题名完全一致,要判断哪条是同一篇)。
3466
+ const hasConflicts = Array.isArray(enrichment?.conflicts) && enrichment.conflicts.length > 0
3467
+ const hasCandidates = Array.isArray(enrichment?.candidates) && enrichment.candidates.length > 0
3468
+ if (!hasConflicts && enrichment?.status !== 'version-conflict' && !hasCandidates) {
3469
+ return json({ delivered: false, reason: '这篇论文当前没有书目冲突,无需交给 AI' })
3470
+ }
3471
+ const message = buildMetadataConflictMessage({
3472
+ document: hydrateDocument(raw),
3473
+ conflicts: enrichment.conflicts,
3474
+ proposed: enrichment.proposed,
3475
+ candidates: enrichment.candidates,
3476
+ sources: enrichment.sources,
3477
+ queryIdentifier: enrichment.queryIdentifier,
3478
+ })
3479
+ const delivery = deliverToSession(body.sessionId, message)
3480
+ return json({ delivered: delivery.delivered, reason: delivery.reason,
3481
+ conflicts: Array.isArray(enrichment.conflicts) ? enrichment.conflicts.length : 0,
3482
+ candidates: hasCandidates ? enrichment.candidates.length : 0 })
3483
+ }
3484
+
3485
+ // 划线与笔记的写入(T19)。三条动作共用一条实现:它们都是"改这一篇的划线文件",
3486
+ // 分三条只会让客户端多两处分支,而路径解析与文档存在性校验完全相同。
3487
+ //
3488
+ // 🔴 **定位、校验、读改写全部在这篇论文的写锁里**(与改名、发布、润色同一把锁):
3489
+ // 进程内队列挡不住跨实例的并发读改写,也挡不住与改名的竞争 —— 实测的伤害是改名之后
3490
+ // 新划线写进**旧主名**文件,阅读器再也读不到它;两个实例各加一条时只留下一条。
3491
+ const writeMarksLocked = documentId => repository.withDocumentWrite(documentId, async () => {
3492
+ // 锁内重新取记录:改名会换掉 pdfName,路径必须按最新记录现算,不能沿用锁外的结论。
3493
+ const state = await repository.snapshot()
3494
+ const raw = await readerDocumentOf(state, documentId)
3495
+ if (!raw) return json({ error: '论文不存在' }, 404)
3496
+ const document = hydrateDocument(raw)
3497
+ const path = readerPathOf(document)
3498
+ if (path === '') return json({ error: '这篇论文没有可标注的正文' }, 400)
3499
+ // 🔴 严格读:坏文件必须整条失败,而不是被当成"还没有划线"再写回去。
3500
+ const store = (await readReaderStoreForWrite(path)) ?? { marks: [] }
3501
+ const marks = Array.isArray(store.marks) ? [...store.marks] : []
3502
+ // 响应里回**解析后**的划线(带 anchor / offset),与 /reader 同一口径:
3503
+ // 客户端不必为"刚存的这条"再走一遍不同的解析路径。
3504
+ const viewOf = async () => readerMarksOf(document, mergeReaderBlocks(
3505
+ (await readerBlocksOf(documentPaths(document).contentPath)).blocks,
3506
+ path === '' ? null : await readTranslation(translationPathOf(document)),
3507
+ ))
3508
+ // 一组划线 = 一次跨块选择(D46)。组上的动作作用于**整组**:用户看到的是一次选择,
3509
+ // 不是 N 条碎片,所以删除/改笔记都不该留下半截。
3510
+ const groupIdsOf = id => {
3511
+ const mark = marks.find(mark => mark?.id === id)
3512
+ const groupId = typeof mark?.groupId === 'string' ? mark.groupId : ''
3513
+ if (groupId === '') return [id]
3514
+ return marks.filter(mark => mark?.groupId === groupId).map(mark => mark?.id)
3515
+ }
3516
+ if (body.action === 'remove') {
3517
+ if (typeof body.id !== 'string' || body.id === '') return json({ error: '要删除的划线 ID 无效' }, 400)
3518
+ const doomed = new Set(groupIdsOf(body.id))
3519
+ const kept = marks.filter(mark => !doomed.has(mark?.id))
3520
+ if (kept.length === marks.length) return json({ error: '划线不存在' }, 404)
3521
+ await writeReaderStore(path, { marks: kept })
3522
+ return json({ marks: await viewOf() })
3523
+ }
3524
+ if (body.action === 'update') {
3525
+ if (typeof body.id !== 'string' || body.id === '') return json({ error: '划线 ID 无效' }, 400)
3526
+ if (!READER_COLORS.includes(body.color) || typeof body.note !== 'string') return json({ error: '划线颜色或笔记无效' }, 400)
3527
+ const targets = new Set(groupIdsOf(body.id))
3528
+ const found = marks.some(mark => targets.has(mark?.id))
3529
+ if (!found) return json({ error: '划线不存在' }, 404)
3530
+ for (let index = 0; index < marks.length; index += 1) {
3531
+ if (!targets.has(marks[index]?.id)) continue
3532
+ marks[index] = { ...marks[index], color: body.color, note: body.note.slice(0, MAX_NOTE_LENGTH) }
3533
+ }
3534
+ await writeReaderStore(path, { marks })
3535
+ return json({ marks: await viewOf() })
3536
+ }
3537
+ if (body.action === 'note') {
3538
+ if (typeof body.id !== 'string' || body.id === '') return json({ error: '划线 ID 无效' }, 400)
3539
+ if (typeof body.note !== 'string') return json({ error: '笔记必须是字符串' }, 400)
3540
+ const targets = new Set(groupIdsOf(body.id))
3541
+ const found = marks.some(mark => targets.has(mark?.id))
3542
+ if (!found) return json({ error: '划线不存在' }, 404)
3543
+ // 只换 note,其余字段(含锚点)一律原样 —— 改笔记绝不能让划线换位置。
3544
+ // 组上一处笔记就是整组那一份(面板合并显示),所以整组一起换。
3545
+ for (let index = 0; index < marks.length; index += 1) {
3546
+ if (!targets.has(marks[index]?.id)) continue
3547
+ marks[index] = { ...marks[index], note: body.note.slice(0, MAX_NOTE_LENGTH) }
3548
+ }
3549
+ await writeReaderStore(path, { marks })
3550
+ return json({ marks: await viewOf() })
3551
+ }
3552
+ if (body.action !== undefined && body.action !== 'add') return json({ error: '划线操作必须是 add / remove / note / update' }, 400)
3553
+ // 🔴 一次跨块拖选 = **一组**划线(D46):同一次写入里逐段落盘,共用 uid。
3554
+ // 不拆成 N 次请求 —— 拆开至少要处理「前两条成了、第三条失败」这种半截状态,
3555
+ // 而这里本来就在同一把论文写锁里。
3556
+ const segments = Array.isArray(body.segments)
3557
+ ? body.segments.filter(segment => segment !== null && typeof segment === 'object'
3558
+ && typeof segment.blockId === 'string' && segment.blockId !== ''
3559
+ && typeof segment.quote === 'string' && segment.quote.trim() !== '')
3560
+ : []
3561
+ if (segments.length > 0) {
3562
+ if (typeof body.sourceLanguage !== 'undefined' && !['source', 'translation'].includes(body.sourceLanguage)) return json({ error: 'PDF 标注语言无效' }, 400)
3563
+ if (body.pdfPage !== undefined && (!Number.isSafeInteger(body.pdfPage) || body.pdfPage < 1)) return json({ error: 'PDF 页码无效' }, 400)
3564
+ const native = body.pdfPage !== undefined ? await pdfPageFor(document, body.pdfPage) : null
3565
+ for (const segment of segments) {
3566
+ // 与单段同一条校验:PDF 标注必须确实存在于原页那一段的文字里。
3567
+ if (native === null) continue
3568
+ const group = native.groups.find(group => group.id === segment.blockId)
3569
+ if (!group?.text.includes(segment.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
3570
+ }
3571
+ const groupId = randomUUID()
3572
+ const created = segments.map(segment => makeMark({
3573
+ blockId: segment.blockId,
3574
+ quote: segment.quote,
3575
+ prefix: segment.prefix,
3576
+ suffix: segment.suffix,
3577
+ color: body.color,
3578
+ // 笔记挂在组上:每段各存一份,面板按组合并后只显示一次(改一处即改全组)。
3579
+ note: body.note,
3580
+ // 逐段译文:每段各存自己那段(D46)。
3581
+ gloss: segment.gloss,
3582
+ sourceLanguage: body.sourceLanguage,
3583
+ pdfPage: body.pdfPage,
3584
+ groupId,
3585
+ }))
3586
+ marks.push(...created)
3587
+ await writeReaderStore(path, { marks })
3588
+ return json({ marks: await viewOf(), added: created[0]?.id, groupId })
3589
+ }
3590
+ if (typeof body.blockId !== 'string' || body.blockId === '') return json({ error: '划线的段落 ID 无效' }, 400)
3591
+ if (body.pdfPage !== undefined) {
3592
+ if (!Number.isSafeInteger(body.pdfPage) || body.pdfPage < 1 || body.sourceLanguage !== 'source') return json({ error: 'PDF 标注页码或语言无效' }, 400)
3593
+ const native = await pdfPageFor(document, body.pdfPage)
3594
+ const group = native.groups.find(group => group.id === body.blockId)
3595
+ if (typeof body.quote !== 'string' || !body.quote.trim() || !group?.text.includes(body.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
3596
+ }
3597
+ const mark = makeMark({
3598
+ blockId: body.blockId,
3599
+ quote: body.quote,
3600
+ prefix: body.prefix,
3601
+ suffix: body.suffix,
3602
+ color: body.color,
3603
+ note: body.note,
3604
+ // 选区即时释义(D160):条上那一行译文随这条划线一起落盘。客户端不给就是空串
3605
+ // (老版本、或用户没等它译出来就划了),readResolve 一律降级成"这条没有释义"。
3606
+ gloss: body.gloss,
3607
+ sourceLanguage: body.sourceLanguage,
3608
+ pdfPage: body.pdfPage,
3609
+ })
3610
+ marks.push(mark)
3611
+ await writeReaderStore(path, { marks })
3612
+ return json({ marks: await viewOf(), added: mark.id })
3613
+ })
3614
+
3615
+ if (request.method === 'POST' && rest === '/marks') {
3616
+ if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
3617
+ return await writeMarksLocked(body.documentId)
3618
+ }
3619
+
3620
+ // 边注讨论(T20)。两个动作:提问(投递当前会话)与写回回答。
3621
+ //
3622
+ // 🔴 与 /marks 同一把论文写锁、同一套锁内重定位:边注文件与划线文件并排放在同一篇的
3623
+ // 资产目录里,改名同样会换路径。实测的伤害是改名之后工具写回的边注留在旧主名文件里,
3624
+ // 面板上一条都看不到。
3625
+ const writeThreadsLocked = documentId => repository.withDocumentWrite(documentId, async () => {
3626
+ const state = await repository.snapshot()
3627
+ const raw = await readerDocumentOf(state, documentId)
3628
+ if (!raw) return json({ error: '论文不存在' }, 404)
3629
+ const document = hydrateDocument(raw)
3630
+ const path = discussionPathOf(document)
3631
+ if (path === '') return json({ error: '这篇论文没有可讨论的正文' }, 400)
3632
+ const payload = (await readDiscussionForWrite(path)) ?? { threads: [] }
3633
+ const blocks = (await readerBlocksOf(documentPaths(document).contentPath)).blocks
3634
+ if (body.action === 'answer') {
3635
+ if (typeof body.id !== 'string' || body.id === '') return json({ error: '边注 ID 无效' }, 400)
3636
+ if (typeof body.answer !== 'string') return json({ error: '回答必须是字符串' }, 400)
3637
+ const outcome = answerThread(payload, { id: body.id, answer: body.answer })
3638
+ if (!outcome.found) return json({ error: '边注不存在' }, 404)
3639
+ await writeDiscussion(path, outcome.payload)
3640
+ return json({ threads: resolveThreads(outcome.payload, blocks) })
3641
+ }
3642
+ if (body.action !== undefined && body.action !== 'ask') return json({ error: '边注操作必须是 ask / answer' }, 400)
3643
+ if (typeof body.blockId !== 'string' || body.blockId === '') return json({ error: '要提问的段落 ID 无效' }, 400)
3644
+ if (typeof body.question !== 'string' || body.question.trim() === '') return json({ error: '问题不能为空' }, 400)
3645
+ // 幂等:同一 (blockId, question) 重复提问只留一条。命中时不写盘,也不重复投递 ——
3646
+ // 重复投一条消息等于让 agent 答两遍同一个问题。
3647
+ const appended = appendThread(payload, { blockId: body.blockId, quote: body.quote, question: body.question })
3648
+ if (!appended.added) {
3649
+ return json({ threads: resolveThreads(appended.payload, blocks), thread: appended.thread, delivered: false, reason: '同样的问题已经问过了' })
3650
+ }
3651
+ // 🔴 先落盘再投递:投递失败时这条提问仍然留在面板上(用户看得见、能重试),
3652
+ // 反过来(先投递后落盘)会留下"agent 答了、面板里没有"的悬空回答。
3653
+ await writeDiscussion(path, appended.payload)
3654
+ const block = blocks.find(item => item?.id === body.blockId)
3655
+ const message = buildQuestionMessage({ document, block, quote: body.quote, question: body.question })
3656
+ const delivery = deliverToSession(body.sessionId, message)
3657
+ return json({ threads: resolveThreads(appended.payload, blocks), thread: appended.thread, delivered: delivery.delivered, reason: delivery.reason })
3658
+ })
3659
+
3660
+ if (request.method === 'POST' && rest === '/discuss') {
3661
+ if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
3662
+ if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
3663
+ return await writeThreadsLocked(body.documentId)
3664
+ }
3665
+
3666
+ return undefined
3667
+ }
3668
+
3669
+ /** 写入路由(需要 body):设置与运行状态。 */
3670
+ async function adminWriteRoutes(request, url, rest, body) {
3671
+ // 术语表增删。两动作共用一条路由:它们都是"改这一份全局表",
3672
+ // 分成两条只会让客户端多一处分支,而校验逻辑完全相同。
3673
+ // 🔴 读、校验、修改、写在**同一把具名写锁**里。唯一临时名 + 原子 rename 只防半写,
3674
+ // 不防两个旧快照互相覆盖整表 —— 实测:两个请求各加一个词,两次都返回 200,最终只留一个。
3675
+ if (request.method === 'POST' && rest === '/glossary') {
3676
+ return await repository.withNamedWrite('glossary', async () => {
3677
+ // 🔴 严格读:术语表损坏时这一次增删必须整条失败,不能把原表换成只剩新写的那一条。
3678
+ const current = await readGlossaryForWrite(glossaryFile)
3679
+ if (body.action === 'remove') {
3680
+ if (typeof body.source !== 'string' || body.source.trim() === '') return json({ error: '要删除的术语不能为空' }, 400)
3681
+ const next = removeEntry(current, body.source)
3682
+ await writeGlossary(glossaryFile, next)
3683
+ return json(await glossaryView())
3684
+ }
3685
+ if (body.action !== undefined && body.action !== 'upsert') return json({ error: '术语表操作必须是 upsert 或 remove' }, 400)
3686
+ if (typeof body.source !== 'string' || body.source.trim() === '') return json({ error: '原词不能为空' }, 400)
3687
+ if (typeof body.target !== 'string' || body.target.trim() === '') return json({ error: '指定译法不能为空' }, 400)
3688
+ // 条目数上限在 upsertEntry 里按**是否新增**判定:已经满了但改的是既有条目仍然放行,
3689
+ // 否则用户会陷入"表满了,连改一个错别字都改不了"的死结。
3690
+ const next = upsertEntry(current, { source: body.source, target: body.target })
3691
+ if (next.entries.length > MAX_GLOSSARY_ENTRIES) return json({ error: `术语表最多 ${MAX_GLOSSARY_ENTRIES} 条,请先删除不用的条目` }, 400)
3692
+ await writeGlossary(glossaryFile, next)
3693
+ return json(await glossaryView())
3694
+ })
3695
+ }
3696
+
3697
+ if (request.method === 'POST' && rest === '/mineru-key') {
3698
+ // 空串是"清除"而不是缺省:清除与没带 key 必须区分得开。
3699
+ if (typeof body.key !== 'string') return json({ error: 'key 必须是字符串' }, 400)
3700
+ if (body.key.length > MAX_MINERU_KEY_LENGTH) return json({ error: `key 长度不能超过 ${MAX_MINERU_KEY_LENGTH}` }, 400)
3701
+ await writeMineruKey(mineruKeyFile, body.key)
3702
+ return json(await mineruKeyView())
3703
+ }
3704
+
3705
+ if (request.method === 'POST' && rest === '/settings') {
3706
+ const allowed = new Set(['parseTimeoutMs', 'parseLanguage', 'parseOcr', 'outlineBudgetBytes', 'contextBudgetBytes', 'readerMultipleTabs', 'texSourceEnabled', 'translationAuto', 'translationScope', 'translationPages', 'translateConcurrency', 'translationProtocol', 'translationLanguage', 'translationModel'])
3707
+ if (Object.keys(body).some(key => !allowed.has(key))) return json({ error: '包含未知设置' }, 400)
3708
+ if (body.parseTimeoutMs !== undefined && (!Number.isInteger(body.parseTimeoutMs) || body.parseTimeoutMs < 60000 || body.parseTimeoutMs > 1800000)) return json({ error: '解析超时必须为 60000–1800000 毫秒' }, 400)
3709
+ if (body.parseLanguage !== undefined && (typeof body.parseLanguage !== 'string' || !/^[a-z][a-z_]{0,31}$/.test(body.parseLanguage))) return json({ error: '解析语言须为 MinerU 语言代码,例如 ch、en、japan、latin' }, 400)
3710
+ if (body.parseOcr !== undefined && typeof body.parseOcr !== 'boolean') return json({ error: '强制 OCR 必须是布尔值' }, 400)
3711
+ if (body.outlineBudgetBytes !== undefined && (!Number.isInteger(body.outlineBudgetBytes) || body.outlineBudgetBytes < 4096 || body.outlineBudgetBytes > 131072)) return json({ error: '目录预算必须为 4096–131072 字节' }, 400)
3712
+ if (body.contextBudgetBytes !== undefined && (!Number.isInteger(body.contextBudgetBytes)
3713
+ || body.contextBudgetBytes < CONTEXT_BUDGET_MIN_BYTES || body.contextBudgetBytes > CONTEXT_BUDGET_MAX_BYTES)) {
3714
+ return json({ error: `单条注入上限必须为 ${CONTEXT_BUDGET_MIN_BYTES}–${CONTEXT_BUDGET_MAX_BYTES} 字节` }, 400)
3715
+ }
3716
+ // ---- 翻译(D67–D72)----
3717
+ // 每一项都按同一个原则:非法值拒绝并说清合法区间,不静默回落成另一种语义。
3718
+ if (body.texSourceEnabled !== undefined && typeof body.texSourceEnabled !== 'boolean') return json({ error: '源码优先必须是布尔值' }, 400)
3719
+ if (body.translationAuto !== undefined && typeof body.translationAuto !== 'boolean') return json({ error: '自动翻译必须是布尔值' }, 400)
3720
+ if (body.readerMultipleTabs !== undefined && typeof body.readerMultipleTabs !== 'boolean') return json({ error: '阅读器多页签设置必须是布尔值' }, 400)
3721
+ if (body.translationScope !== undefined && !TRANSLATION_SCOPES.includes(body.translationScope)) {
3722
+ return json({ error: `翻译范围必须是 ${TRANSLATION_SCOPES.join(' / ')}` }, 400)
3723
+ }
3724
+ if (body.translationPages !== undefined
3725
+ && (!Number.isInteger(body.translationPages) || body.translationPages < 1 || body.translationPages > 500)) {
3726
+ return json({ error: '前 N 页的 N 必须是 1–500 的整数' }, 400)
3727
+ }
3728
+ // D136:并发翻译数 1–8。上限收窄是有意的 —— 它是打给模型提供方的并发,
3729
+ // 开太大只会撞限流,不该让一个手滑的数字把整条链路拖垮。
3730
+ if (body.translateConcurrency !== undefined
3731
+ && (!Number.isInteger(body.translateConcurrency) || body.translateConcurrency < 1 || body.translateConcurrency > 8)) {
3732
+ return json({ error: '并发翻译数必须是 1–8 的整数' }, 400)
3733
+ }
3734
+ // D140:目标语言取白名单(唯一真相在 translate-prompts.js,客户端选项由 /translate-models 下发)。
3735
+ if (body.translationLanguage !== undefined && !TRANSLATION_LANGUAGE_CODES.includes(body.translationLanguage)) {
3736
+ return json({ error: `目标语言必须是 ${TRANSLATION_LANGUAGE_CODES.join(' / ')}` }, 400)
3737
+ }
3738
+ // D138:输出协议有三档(json / lines / plain)。专用机器翻译模型(本地 hy-mt2 这类)不吐
3739
+ // JSON 数组,只吐「每行一条 [id] 译文」的方言或纯文本 —— 给它 JSON 指令会整篇解析失败。
3740
+ if (body.translationProtocol !== undefined && !TRANSLATION_PROTOCOLS.includes(body.translationProtocol)) {
3741
+ return json({ error: `翻译输出协议必须是 ${TRANSLATION_PROTOCOLS.join(' / ')}` }, 400)
3742
+ }
3743
+ if (body.translationModel !== undefined && body.translationModel !== null
3744
+ && (typeof body.translationModel !== 'object'
3745
+ || typeof body.translationModel.provider !== 'string' || body.translationModel.provider === ''
3746
+ || typeof body.translationModel.model !== 'string' || body.translationModel.model === '')) {
3747
+ return json({ error: '翻译模型必须是 { provider, model } 或 null(跟随默认模型)' }, 400)
3748
+ }
3749
+ const settings = await repository.update(state => Object.assign(state.settings, body))
3750
+ return json({ settings })
3751
+ }
3752
+
3753
+ return undefined
3754
+ }
3755
+
3756
+ async function dispatch(request) {
3757
+ const url = new URL(request.url)
3758
+ const rest = url.pathname.slice(API_BASE.length)
3759
+ try {
3760
+ await repositoryReady
3761
+ if (request.method !== 'GET' && !sameOrigin(request)) return json({ error: '拒绝跨源请求' }, 403)
3762
+ // 只读路由一律在解析 body 之前:不带 Content-Type 的 GET 调用方不该被 415 挡掉,
3763
+ // 而后面的 /translate-models 虽然是 GET,却要等 body 解析之后(与改造前同一顺序)。
3764
+ const early = await readRoutes(request, url, rest)
3765
+ if (early !== undefined) return early
3766
+ const body = await bodyOf(request)
3767
+ const late = await writeRoutes(request, url, rest, body)
3768
+ if (late !== undefined) return late
3769
+ return json({ error: '接口不存在' }, 404)
3770
+ } catch (error) {
3771
+ const status = typeof error?.status === 'number' ? error.status : 500
3772
+ // 4xx 是请求方的输入问题,只记一行原因、不带栈:否则任何同源脚本 POST 一段坏 JSON 就能
3773
+ // 把宿主日志刷满栈轨迹。真正意料之外的 5xx 才需要栈来定位。
3774
+ if (status >= 500) ctx.logger.error(`dsh-paper api: ${error?.stack ?? error}`)
3775
+ else if (error?.reason === undefined) ctx.logger.warn(`dsh-paper api: ${status} ${errorText(error)}`)
3776
+ // 🔴 带上机器可读的 reason(如果抛出方给了)。客户端不能靠正则去认那句中文,
3777
+ // 而「任务 … 已在队列中」这种**预期状态**必须能被它区分出来 —— 否则预检与入队之间的
3778
+ // 竞态窗口会把它渲染成红字(见 /open 与 /translate 各自的 already-queued 分支)。
3779
+ return json({ error: errorText(error), ...(typeof error?.reason === 'string' ? { reason: error.reason } : {}) }, status)
3780
+ }
3781
+ }
3782
+
3783
+ /**
3784
+ * 工具的执行侧:导出 / 文献库写入 / 原页图 / 按结构读取。
3785
+ *
3786
+ * 四个函数由 tool-host.js 持有,这里只把宿主能力递进去 —— index.js 不再自己实现
3787
+ * 「一次工具调用要读什么、写哪里」。界面路由与工具因此共用同一批底层函数。
3788
+ */
3789
+ const toolHost = createToolHost({
3790
+ ctx,
3791
+ root: runtimeRoot(config),
3792
+ repository,
3793
+ metadataResolver,
3794
+ bibliographyService,
3795
+ libraryService,
3796
+ serializeLibrary,
3797
+ libraryFile,
3798
+ libraryDocumentOf,
3799
+ attachDocumentsToSession,
3800
+ readerDocumentOf,
3801
+ readerBlocksOf,
3802
+ readerMarksOf,
3803
+ readerThreadsOf,
3804
+ outlineTextOf,
3805
+ exportAssetsOf,
3806
+ mergeReaderBlocks,
3807
+ pageImageCacheDir,
3808
+ mineruCommand: config.mineruCommand,
3809
+ bindSourceDirs,
3810
+ setSourceDir,
3811
+ allDocuments: rawDocuments,
3812
+ })
3813
+
3814
+ /**
3815
+ * 检查更新 / 一键升级的服务(D193)。
3816
+ *
3817
+ * 🔴 `manager` 走 **`ctx.get('pluginManager')`** 而不是 `ctx.pluginManager`:后者要求
3818
+ * 把它写进 `inject`,而老宿主根本没有这个服务 —— 声明一个不存在的依赖会让整个
3819
+ * plugin tree 起不来。`ctx.get` 拿不到就回 undefined,卡片据此说「只能手装」。
3820
+ */
3821
+ const updateService = createUpdateService({
3822
+ manager: () => {
3823
+ const lookup = ctx.get?.bind(ctx)
3824
+ if (typeof lookup !== 'function') return null
3825
+ return lookup('pluginManager') ?? null
3826
+ },
3827
+ })
3828
+
3829
+ const routes = [
3830
+ ['/state', ['GET']], ['/pick', ['POST']], ['/pick-folder', ['POST']], ['/scan', ['POST']], ['/add', ['POST']], ['/job', ['GET']],
3831
+ ['/selection', ['POST']], ['/retry', ['POST']], ['/retry-all', ['POST']], ['/reparse', ['POST']], ['/rename', ['POST']], ['/settings', ['GET', 'POST']], ['/delete', ['POST']],
3832
+ ['/mineru-key', ['GET', 'POST']], ['/glossary', ['GET', 'POST']], ['/marks', ['POST']], ['/discuss', ['POST']],
3833
+ ['/renderer-status', ['GET']], ['/install-dependency', ['POST']],
3834
+ ['/update/check', ['GET']], ['/update/apply', ['POST']],
3835
+ ['/translate', ['POST']], ['/translate-batch', ['POST']], ['/translate-retry', ['POST']], ['/translate-pause', ['POST']], ['/translate-resume', ['POST']], ['/translate-cancel', ['POST']], ['/translate-models', ['GET']],
3836
+ ['/open', ['POST']], ['/open-pdf', ['POST']], ['/reader', ['GET']], ['/pdf-page', ['GET']], ['/usage', ['GET']], ['/select-ask', ['POST']], ['/gloss', ['POST']],
3837
+ ['/library', ['GET', 'POST']], ['/metadata', ['POST']], ['/metadata-conflict-ask', ['POST']], ['/item', ['GET']], ['/export', ['GET', 'POST']], ['/mirror', ['POST']],
3838
+ ['/bibliography-import', ['POST']], ['/bibliography-export', ['POST']], ['/citation-styles', ['GET', 'POST']],
3839
+ // 右栏「解析」Tab(独立通路;见 /parse-add 那段注释)。
3840
+ ['/parse-list', ['GET']], ['/parse-add', ['POST']], ['/parse-scan', ['POST']],
3841
+ ['/parse-start', ['POST']], ['/parse-remove', ['POST']], ['/parse-retry', ['POST']],
3842
+ ]
3843
+ ctx.inject(['connection'], connectionCtx => {
3844
+ for (const [path, methods] of routes) connectionCtx.connection.registerFetchRoute(ctx, {
3845
+ path: API_BASE + path,
3846
+ methods,
3847
+ requestBody: 'buffered',
3848
+ fetch: path === '/discuss' ? request => discussionGate.run(() => dispatch(request))
3849
+ : path === '/library' ? request => serializeLibrary(() => dispatch(request))
3850
+ : path === '/marks' ? request => serializeMarks(() => dispatch(request)) : dispatch,
3851
+ })
3852
+ // 阅读器资源(字节响应,不经 JSON dispatch)。
3853
+ for (const [path, name] of [['/analysis-asset', 'analysis-asset'], ['/page-image', 'page-image']]) {
3854
+ connectionCtx.connection.registerFetchRoute(ctx, {
3855
+ path: API_BASE + path,
3856
+ methods: ['GET'],
3857
+ requestBody: 'buffered',
3858
+ fetch: request => assetDispatch(request, name),
3859
+ })
3860
+ }
3861
+ })
3862
+ }