@li-canghai/dsh-paper 0.8.2 → 0.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -15,7 +15,7 @@ import { PaperResolver, RETRYABLE_JOB_STATUSES } from './resolver.js'
15
15
  import { mineruSdkConfig, parseWithConfiguredMineruSdk } from './mineru-sdk.js'
16
16
  import { isWithin, mirrorParseResult } from './mirror-export.js'
17
17
  import { normalizeCanvas, renderPageImages } from './page-image.js'
18
- import { cropPdfGroups, pdfPageGroups, pdfQuoteInText, readPdfPage } from './pdf-page.js'
18
+ import { cropPdfGroups, pdfBlockText, pdfPageGroups, pdfQuoteInText, readPdfPage } from './pdf-page.js'
19
19
  import { probeRenderer } from './renderer-status.js'
20
20
  import { installDependency } from './install-dependency.js'
21
21
  import { createUpdateService } from './update-check.js'
@@ -32,7 +32,7 @@ import { documentReferenceOf, titleFromBlocks, TRANSLATION_LANGUAGES } from './t
32
32
  import { glossUsageKey, translateSelection } from './gloss.js'
33
33
  import { buildGlossaryBlock, emptyGlossary, glossaryPathOf, MAX_GLOSSARY_ENTRIES, readGlossary, readGlossaryForWrite, removeEntry, upsertEntry, writeGlossary } from './glossary.js'
34
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'
35
+ import { appendThread, answerThread, deleteThread, discussionPathOf, readDiscussion, readDiscussionForWrite, resolveThreads, writeDiscussion } from './discussion.js'
36
36
  import { createBlockReader } from './block-cache.js'
37
37
  import { createSerialTail } from './serial-tail.js'
38
38
  import { effectiveMetadata, enrichMetadata } from './paper-metadata.js'
@@ -49,7 +49,7 @@ import { renameAfterParse, renameDocument } from './rename-document.js'
49
49
  import { pageImageCacheRoot } from './store-paths.js'
50
50
  import { resolvePdfSource } from './source-resolver.js'
51
51
  import { createParseExport } from './parse-export.js'
52
- import { createTaskStore } from './tasks.js'
52
+ import { createTaskStore, summarizeTask } from './tasks.js'
53
53
  import { createJobFacade } from './job-facade.js'
54
54
  import { createPdfAnalysisTool } from './pdf-analysis-tool.js'
55
55
  import { createAnnotateTool } from './annotate-tool.js'
@@ -125,9 +125,17 @@ export function translationFailureText(outcome, batch = {}) {
125
125
  const stats = outcome?.stats ?? {}
126
126
  const blocks = Array.isArray(outcome?.blocks) ? outcome.blocks : []
127
127
  const failed = Number.isInteger(stats.failed) ? stats.failed : blocks.filter(block => block?.status === 'failed').length
128
+ const skipped = Number.isInteger(stats.skipped) ? stats.skipped : blocks.filter(block => block?.status === 'skipped').length
128
129
  const route = typeof batch?.model?.provider === 'string' && typeof batch?.model?.model === 'string'
129
130
  ? `${batch.model.provider}/${batch.model.model}`
130
131
  : '未指定模型'
132
+ // 一个块都没译出来有两条路:全是 failed,或全是 skipped(表格结构校验不通过是主因)。
133
+ // 后者 failed 是 0,照 failed 报会得到「0 个块全部翻译失败」这种自相矛盾的句子。
134
+ if (failed === 0 && skipped > 0) {
135
+ const skippedFirst = blocks.find(block => block?.status === 'skipped' && typeof block?.error === 'string' && block.error !== '')
136
+ const head = `${skipped} 个块都跳过了,没有译出内容(模型 ${route})`
137
+ return skippedFirst === undefined ? head : `${head}:${skippedFirst.error}`
138
+ }
131
139
  const first = blocks.find(block => block?.status === 'failed' && typeof block?.error === 'string' && block.error !== '')
132
140
  const head = `${failed} 个块全部翻译失败(模型 ${route})`
133
141
  return first === undefined ? head : `${head}:${first.error}`
@@ -168,8 +176,27 @@ export function summarizeProgress(jobs = [], { readyDocumentIds = [], kind = 'pa
168
176
  return { total, ...counts, percent: total === 0 ? 0 : Math.round((counts.finished / total) * 100) }
169
177
  }
170
178
 
179
+ /**
180
+ * 论文 id 与会话 id 的字符集校验。
181
+ *
182
+ * 🔴 除了字符集,还要挡掉三个**对象原型键**:`__proto__` / `constructor` / `prototype`。
183
+ * 它们能过正则(都是 `[A-Za-z0-9._:-]+`),而这个函数的产物会被当成
184
+ * `state.selections[sessionId]`、`state.documents[documentId]` 这类普通对象的键:
185
+ *
186
+ * - `selections['__proto__'] = {...}` **不建自有属性**,写的是原型 ——
187
+ * `JSON.stringify` 里看不到(不落盘),但同一个进程里再读 `selections['__proto__']`
188
+ * 会拿到那个对象,看起来"存住了",于是本次写入静默丢失、原型被污染;
189
+ * - `documents['__proto__']` 读回来是 `Object.prototype`(truthy),
190
+ * 后续 `.id` / `.pdfName` 全是 undefined。
191
+ *
192
+ * 真实的论文 id 是 64 位十六进制哈希、会话 id 形如 `session-…`,
193
+ * 这三个词一个都不可能是合法取值,挡掉不会误伤。
194
+ */
195
+ const PROTOTYPE_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
196
+
171
197
  function validId(value) {
172
- return typeof value === 'string' && value.length > 0 && value.length <= 256 && /^[A-Za-z0-9._:-]+$/.test(value)
198
+ return typeof value === 'string' && value.length > 0 && value.length <= 256
199
+ && /^[A-Za-z0-9._:-]+$/.test(value) && !PROTOTYPE_KEYS.has(value)
173
200
  }
174
201
 
175
202
  const SELECTION_SWEEP_MIN_INTERVAL_MS = 10 * 60 * 1000
@@ -411,7 +438,6 @@ function truncateForLog(value, max = 64) {
411
438
  }
412
439
 
413
440
  export function apply(ctx, config = {}) {
414
- const discussionGate = createConcurrencyGate(1)
415
441
  const repository = new PaperRepository(runtimeRoot(config))
416
442
  const metadataResolver = config.metadataResolver ?? createMetadataResolver({ networkMode: config.metadataNetworkMode ?? 'auto' })
417
443
  if (!config.metadataResolver) ctx.effect?.(() => () => metadataResolver.dispose())
@@ -601,6 +627,8 @@ export function apply(ctx, config = {}) {
601
627
  translateAll: batch.translateAll,
602
628
  batchPages: batch.batchPages,
603
629
  targetLanguage: batch.targetLanguage,
630
+ // 请求身份(见 startTranslation 的说明):线路侧用它发会话头,模型侧看不到。
631
+ sessionId: batch.sessionId,
604
632
  // 输出协议(D138 / D139):专用翻译模型用 lines / plain,通用模型用默认 json。
605
633
  protocol: batch.protocol,
606
634
  // 🔴 单篇内的**批次并发**(D139):队列的并发数是跨文档的(taskId 是 documentId),
@@ -622,7 +650,15 @@ export function apply(ctx, config = {}) {
622
650
  // 而 translateDocument 自己不抛错。这里若一律回 ok:true,任务会以 ready 收尾 ——
623
651
  // 用户看到的是「点一下就说完成、译文一个字没变」,连一条失败记录都留不下(实测踩过:
624
652
  // 435 个块全失败的任务报到界面上是「翻译完成」)。零译出必须当场算失败,并把原因带出去。
625
- if ((outcome?.stats?.translated ?? 0) === 0 && (outcome?.stats?.failed ?? 0) > 0) {
653
+ //
654
+ // 🔴 判据是「**零译出**」,不是「零译出**且有失败**」。原来的 `failed > 0` 这个附加条件
655
+ // 让另一条路漏了网:整篇都是表格块、且全部被结构校验判 skipped 时 `failed === 0`、
656
+ // `translated === 0`,任务照样以 ready 收尾 —— 用户看到「翻译完成」,实际上一个字
657
+ // 都没译出来,连 skipped 都不显眼。表格跳过是有意的设计(不写不合格译文),
658
+ // 但「全部跳过」必须如实报成没译成,否则界面上就是一句假话。
659
+ // `requested === 0` 是真没有可译内容,那种情况本来就不该有任务,不是这里的失败。
660
+ const stats = outcome?.stats ?? {}
661
+ if ((stats.translated ?? 0) === 0 && (stats.requested ?? 0) > 0) {
626
662
  return { ok: false, error: translationFailureText(outcome, batch) }
627
663
  }
628
664
  return { ok: true }
@@ -714,7 +750,21 @@ export function apply(ctx, config = {}) {
714
750
  pathOf: document => discussionPathOf(document),
715
751
  readPayload: path => readDiscussionForWrite(path),
716
752
  writePayload: (path, payload) => writeDiscussion(path, payload),
717
- serialize: operation => discussionGate.run(operation),
753
+ /**
754
+ * 边注写入在这篇论文的**文档写锁**里跑。
755
+ *
756
+ * 🔴 不能用进程内队列(曾经是 discussionGate):边注与 Markdown 同目录同主名,改名会换主名,
757
+ * 队列既挡不住第二个宿主,也挡不住同进程的改名 —— 那样写回的边注会留在旧主名文件里,
758
+ * 面板上一条都看不到。/marks 的写锁注释记的是同一条实测伤害,这里按同一把锁办。
759
+ *
760
+ * 锁内重新取记录交给 pathOfFresh:改名后路径要按锁内那份算,不能沿用锁外的结论。
761
+ */
762
+ serialize: (documentId, operation) => repository.withDocumentWrite(documentId, async () => {
763
+ // 🔴 readerDocumentOf 是 async 的(冷归档要读盘):漏掉 await 会把它当成"记录存在",
764
+ // 于是 pathOfFresh 拿到一个 Promise 算出的空路径,写回直接报"无处写回"。
765
+ const fresh = await readerDocumentOf(await repository.snapshot(), documentId)
766
+ return await operation(fresh === undefined || fresh === null ? undefined : hydrateDocument(fresh))
767
+ }),
718
768
  deleteThread,
719
769
  appendThread,
720
770
  answerThread,
@@ -1625,6 +1675,10 @@ function hasMeaningfulValue(value) {
1625
1675
  // 多带两个自己的字段不影响它 —— 它从头到尾只把 batch 原样回调给 runBatch。
1626
1676
  jobId: job.id,
1627
1677
  documentId: document.id,
1678
+ // 🔴 会话 id 一路透传到模型请求:opencode-go 那条线路靠 `options.sessionId` 发
1679
+ // `x-opencode-session`(网关据此选路并复用 prompt 缓存),不带就只是"没有这个头"。
1680
+ // 它不是调用配置,不参与宿主的逐字段比较,所以单独一层往下传,不进 model 路由。
1681
+ sessionId: typeof job.sessionId === 'string' ? job.sessionId : '',
1628
1682
  model: await resolveTranslationModel(),
1629
1683
  scope: body.scope === undefined ? undefined : { mode: body.scope.mode, pageFrom: body.scope.pageFrom, pageTo: body.scope.pageTo },
1630
1684
  incremental: body.incremental === true,
@@ -1785,7 +1839,7 @@ function hasMeaningfulValue(value) {
1785
1839
  // (archivePath 里的 ID 校验)。而 validId 只查字符集,'not-a-hash' 这类能过它 ——
1786
1840
  // 于是任何一条带非哈希 documentId 的请求都会变成 500。这里先按同一条形状收口:
1787
1841
  // 不是哈希就根本没有冷记录可找,直接当"不存在",由调用方回 404。
1788
- // 这一处是 /reader、/marks、/discuss、/open、/ask、/export、/item、/library 共用的入口,
1842
+ // 这一处是 /reader、/marks、/open、/export、/item、/library 共用的入口,
1789
1843
  // 所以修在这里等于八条路由一起修好。
1790
1844
  if (!/^[a-f0-9]{64}$/.test(String(documentId))) return undefined
1791
1845
  return await repository.archivedDocument(documentId) ?? undefined
@@ -1860,7 +1914,7 @@ function hasMeaningfulValue(value) {
1860
1914
  * 以为提问丢了 —— 而它并没有。
1861
1915
  *
1862
1916
  * @param {string} sessionId 当前会话。
1863
- * @param {object} message buildQuestionMessage 的产物。
1917
+ * @param {object} message 注入消息(buildSelectionMessage / buildMetadataConflictMessage 的产物)。
1864
1918
  * @returns {{delivered: boolean, reason?: string}}
1865
1919
  */
1866
1920
  function deliverToSession(sessionId, message) {
@@ -2011,12 +2065,32 @@ function hasMeaningfulValue(value) {
2011
2065
  const allJobs = Object.values(state.jobs)
2012
2066
  const machineParses = summarizeProgress(allJobs)
2013
2067
  const machineTranslations = summarizeProgress(allJobs, { kind: 'translate' })
2068
+ // 任务编号回填:jobs 里没有 taskId 字段(任务清单是另一份派生状态),而模型回执里
2069
+ // 给的是任务编号 —— 侧栏要把它显示出来,就得在这里按 documentId 反查一次。
2070
+ // 清单读失败不影响 /state:它是派生 UI 状态,缺了只是少显示一行编号。
2071
+ const taskIdOfDocument = new Map()
2072
+ try {
2073
+ for (const task of await taskStore.listTasks({ limit: 100 })) {
2074
+ for (const item of Array.isArray(task?.items) ? task.items : []) {
2075
+ if (typeof item?.documentId === 'string' && item.documentId !== '' && typeof task?.id === 'string') {
2076
+ taskIdOfDocument.set(item.documentId, task.id)
2077
+ }
2078
+ }
2079
+ }
2080
+ } catch (error) {
2081
+ ctx.logger.warn('[dsh-paper] 读任务清单失败(不影响 /state):' + errorText(error))
2082
+ }
2014
2083
  // 会话仍关联、未隐藏的论文:既是要渲染的卡片,也是进度口径的"已完成"兜底来源。
2015
2084
  const attachedDocuments = Object.values(state.documents).filter(document => documentIds.has(document.id) && !document.hidden)
2016
2085
  const readyDocumentIds = attachedDocuments.map(document => document.id)
2017
2086
  return json({
2018
2087
  documents: await Promise.all(attachedDocuments.map(document => documentReader.documentView(document, state.settings.outlineBudgetBytes))),
2019
- jobs,
2088
+ // taskId 只在解析任务上有意义(翻译任务不进任务清单)。没有对应编号的记录保持原样,
2089
+ // 少一个字段好过给一个查不到的编号。
2090
+ jobs: jobs.map(job => {
2091
+ const taskId = taskIdOfDocument.get(job.documentId)
2092
+ return taskId === undefined ? job : { ...job, taskId }
2093
+ }),
2020
2094
  progress: summarizeProgress(jobs, { readyDocumentIds }),
2021
2095
  // 翻译任务的"已完成"兜底集合不能复用论文记录:翻译完成不改 documents 的 ready 语义。
2022
2096
  // T12 有翻译侧的持久证据时在这里补上 readyTranslationDocumentIds,现在只能按任务记录算。
@@ -2024,15 +2098,29 @@ function hasMeaningfulValue(value) {
2024
2098
  queue: { pending: machineParses.pending, running: machineParses.running },
2025
2099
  // 全局刹车态(D70):侧栏据此决定显示「暂停翻译」还是「继续翻译」。
2026
2100
  translationPaused: translateQueue.isPaused(),
2027
- translationQueue: { pending: machineTranslations.pending, running: machineTranslations.running },
2101
+ // 🔴 running 必须读队列,不能从 state.jobs 数:翻译任务的 status 只被写成 queued 与
2102
+ // 终态,从来不写 running(全库唯一写 running 的是 resolver.js 的解析任务)。按 jobs 数
2103
+ // 会恒得 0,而那些按 running 分支的客户端消费者就全都白写了。
2104
+ //
2105
+ // 也不要在真正开跑时补写 job.status='running':storage.js 的 recoverInterruptedJobs
2106
+ // 会把 running 判成 interrupted,再用 neverStarted(job) 决定是否自动重排——而 attempts
2107
+ // 只有解析侧写,翻译任务恒为空数组,于是「跑到一半宿主退出」会变成自动重排、重复计费。
2108
+ // runningCount() 是队列既有的导出,测的是跨文档在飞批次的总数,正是这里该报的口径。
2109
+ translationQueue: { pending: machineTranslations.pending, running: translateQueue.runningCount() },
2028
2110
  selection,
2029
2111
  mineru: resolver.describeMineru(),
2030
2112
  })
2031
2113
  }
2032
2114
 
2033
2115
  if (request.method === 'GET' && rest === '/job') {
2116
+ const jobId = url.searchParams.get('id') ?? ''
2117
+ // 🔴 `state.jobs` 是 JSON.parse 出来的普通对象,它带 `Object.prototype`:
2118
+ // `?id=constructor` 取到的是构造函数本身(truthy),判真后就回 200 而不是 404。
2119
+ // 泄露不了数据(`JSON.stringify({job: Object})` 得到 `{}`),但契约是错的 ——
2120
+ // 「查不到」必须回 404。`validId` 的 PROTOTYPE_KEYS 正是为这一类读路径准备的。
2121
+ if (!validId(jobId)) return json({ error: '任务 ID 无效' }, 400)
2034
2122
  const state = await repository.snapshot()
2035
- const job = state.jobs[url.searchParams.get('id') ?? '']
2123
+ const job = state.jobs[jobId]
2036
2124
  return job ? json({ job }) : json({ error: '任务不存在' }, 404)
2037
2125
  }
2038
2126
 
@@ -2233,6 +2321,19 @@ function hasMeaningfulValue(value) {
2233
2321
  return json(parseExport.list())
2234
2322
  }
2235
2323
 
2324
+ // 模型拿到的 taskId 必须有地方查回来:SPEC 承诺它是持久编号,而 jobId 只活一个
2325
+ // 宿主周期。没有这条路由时,回执里那个编号对调用方是纯装饰。
2326
+ if (request.method === 'GET' && rest === '/task') {
2327
+ const rawId = url.searchParams.get('id')
2328
+ const taskId = typeof rawId === 'string' ? rawId.trim() : ''
2329
+ if (taskId === '') return json({ error: '缺少 id:要查的任务编号。' }, 400)
2330
+ const task = await taskStore.getTask(taskId)
2331
+ if (task === undefined) return json({ error: '任务不存在:它可能已被永久删除,或来自另一台机器。' }, 404)
2332
+ const state = await repository.snapshot()
2333
+ // 任务的 items 只登记了 documentId,进度仍从 jobs 现算(tasks.js 的既定分工)。
2334
+ return json({ task, progress: summarizeTask(task, state.jobs) })
2335
+ }
2336
+
2236
2337
  return undefined
2237
2338
  }
2238
2339
 
@@ -2474,6 +2575,11 @@ function hasMeaningfulValue(value) {
2474
2575
  if (request.method === 'POST' && rest === '/translate-batch') {
2475
2576
  const batch = batchDocumentIds(body)
2476
2577
  if (batch.error !== undefined) return json({ error: batch.error }, 400)
2578
+ // 与 /translate、/translate-retry 同一条口径:会话 id 要么是合法 id、要么索性没给。
2579
+ // 这条路由曾经只把 `body.sessionId ?? ''` 直接写进 job 记录,于是 `42`、`{...}`、`["a"]`
2580
+ // 都能原样落盘;下游每个消费者都得自己再收敛成字符串(beginTranslation 就是这么做才没出事)。
2581
+ // 一处入口挡掉,比每个消费者各挡一次可靠。
2582
+ if (body.sessionId !== undefined && body.sessionId !== '' && !validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
2477
2583
  const snapshot = await repository.snapshot()
2478
2584
  const scope = translationScopeOf(snapshot.settings)
2479
2585
  const probed = await mapWithConcurrency(batch.ids, BATCH_TRANSLATE_CONCURRENCY, documentId => translationBatchEntry(snapshot, documentId, scope))
@@ -2502,6 +2608,9 @@ function hasMeaningfulValue(value) {
2502
2608
  id: `job-${randomUUID()}`,
2503
2609
  kind: 'translate',
2504
2610
  documentId: entry.documentId,
2611
+ // 会话 id 会进 job 记录、也会一路透传到模型请求的 `options.sessionId`(见 beginTranslation)。
2612
+ // 同族的 /translate、/translate-retry 都在入口用 validId 挡住脏值,这条没有 —— 非字符串
2613
+ // 落盘后每个消费者都要自己再收敛一次,而只要新增一个忘了收敛的消费者就是脏数据入口。
2505
2614
  sessionId: body.sessionId ?? '',
2506
2615
  pdfPath: hydrateDocument(entry.document).pdfPath,
2507
2616
  pdfName: entry.pdfName,
@@ -3333,7 +3442,7 @@ function hasMeaningfulValue(value) {
3333
3442
  if (body.pdfPage !== undefined) {
3334
3443
  if (!Number.isSafeInteger(body.pdfPage) || body.pdfPage < 1) return json({ error: 'PDF 页码无效' }, 400)
3335
3444
  const native = await pdfPageFor(document, body.pdfPage, blocks)
3336
- nativeContext = native.groups.find(group => group.id === blockId)?.text ?? ''
3445
+ nativeContext = pdfBlockText(native.groups, blockId)
3337
3446
  if (nativeContext) sourceContext = nativeContext
3338
3447
  }
3339
3448
  let counterpart = ''
@@ -3357,7 +3466,7 @@ function hasMeaningfulValue(value) {
3357
3466
  if (index < 0) return json({reason:'no-match',error:'划线已删除或改变'})
3358
3467
  const latestBlocks = mergeReaderBlocks((await readerBlocksOf(documentPaths(document).contentPath)).blocks, await readTranslation(translationPathOf(document)))
3359
3468
  const latest = latestBlocks.find(row=>row.id===blockId)
3360
- const latestNative = nativeContext ? (await pdfPageFor(document, body.pdfPage, latestBlocks)).groups.find(group => group.id === blockId)?.text : ''
3469
+ const latestNative = nativeContext ? pdfBlockText((await pdfPageFor(document, body.pdfPage, latestBlocks)).groups, blockId) : ''
3361
3470
  const latestSource = latestNative || plainInlineText(latest?.sourceText ?? ''), latestTranslation = plainInlineText(latest?.zh ?? '')
3362
3471
  if (!([latestSource,latestTranslation].includes(sourceContext) && [latestSource,latestTranslation].includes(counterpart))) return json({reason:'no-match',error:'正文或译文已更新,请重新匹配'})
3363
3472
  marks[index] = {...marks[index],parallelQuote}
@@ -3415,6 +3524,8 @@ function hasMeaningfulValue(value) {
3415
3524
  model,
3416
3525
  glossary: await glossaryBlockFor(),
3417
3526
  gate: translationGate,
3527
+ // 与整篇翻译同一条透传:释义同样打给同一条线路,opencode-go 靠它发会话头。
3528
+ sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
3418
3529
  })
3419
3530
  // 记账与翻译同一口径(T24):键是(文档 + 原话)的确定性哈希,所以同一个词翻两次
3420
3531
  // 在账本里仍是一条 —— 这一档本就分辨不出"两次真实调用"与"同一次被观测两遍"。
@@ -3435,7 +3546,7 @@ function hasMeaningfulValue(value) {
3435
3546
  if (index < 0) return json({reason:'no-match',error:'划线已删除或改变'})
3436
3547
  const latestBlocks = mergeReaderBlocks((await readerBlocksOf(documentPaths(document).contentPath)).blocks, await readTranslation(translationPathOf(document)))
3437
3548
  const latest = latestBlocks.find(row=>row.id===blockId)
3438
- const latestNative = nativeContext ? (await pdfPageFor(document, body.pdfPage, latestBlocks)).groups.find(group => group.id === blockId)?.text : ''
3549
+ const latestNative = nativeContext ? pdfBlockText((await pdfPageFor(document, body.pdfPage, latestBlocks)).groups, blockId) : ''
3439
3550
  const latestSource = latestNative || plainInlineText(latest?.sourceText ?? ''), latestTranslation = plainInlineText(latest?.zh ?? '')
3440
3551
  if (!([latestSource,latestTranslation].includes(sourceContext) && [latestSource,latestTranslation].includes(counterpart))) return json({reason:'no-match',error:'正文或译文已更新,请重新匹配'})
3441
3552
  marks[index] = {...marks[index],parallelQuote:outcome.zh}
@@ -3459,7 +3570,7 @@ function hasMeaningfulValue(value) {
3459
3570
  // 没选内容 → 客户端根本不调这里,走 /selection 注入(论文 id + 论文名 + 章节树)
3460
3571
  // 选中内容 → 这条:上面全部 **+ 块 id + 选中原话 + 该段所在段落**
3461
3572
  //
3462
- // 🔴 与 /discuss 同一条投递口径(D95):必须用 followup 唤醒驱动,投递失败不算 HTTP 失败。
3573
+ // 🔴 与 /selection 同一条投递口径(D95):必须用 followup 唤醒驱动,投递失败不算 HTTP 失败。
3463
3574
  if (request.method === 'POST' && rest === '/select-ask') {
3464
3575
  if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
3465
3576
  if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
@@ -3621,8 +3732,7 @@ function hasMeaningfulValue(value) {
3621
3732
  for (const segment of segments) {
3622
3733
  // 与单段同一条校验:PDF 标注必须确实存在于原页那一段的文字里。
3623
3734
  if (native === null) continue
3624
- const group = native.groups.find(group => group.id === segment.blockId)
3625
- if (!pdfQuoteInText(group?.text, segment.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
3735
+ if (!pdfQuoteInText(pdfBlockText(native.groups, segment.blockId), segment.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
3626
3736
  }
3627
3737
  const groupId = randomUUID()
3628
3738
  const created = segments.map(segment => makeMark({
@@ -3647,8 +3757,7 @@ function hasMeaningfulValue(value) {
3647
3757
  if (body.pdfPage !== undefined) {
3648
3758
  if (!Number.isSafeInteger(body.pdfPage) || body.pdfPage < 1 || body.sourceLanguage !== 'source') return json({ error: 'PDF 标注页码或语言无效' }, 400)
3649
3759
  const native = await pdfPageFor(document, body.pdfPage)
3650
- const group = native.groups.find(group => group.id === body.blockId)
3651
- if (typeof body.quote !== 'string' || !body.quote.trim() || !pdfQuoteInText(group?.text, body.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
3760
+ if (typeof body.quote !== 'string' || !body.quote.trim() || !pdfQuoteInText(pdfBlockText(native.groups, body.blockId), body.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
3652
3761
  }
3653
3762
  const mark = makeMark({
3654
3763
  blockId: body.blockId,
@@ -3673,51 +3782,8 @@ function hasMeaningfulValue(value) {
3673
3782
  return await writeMarksLocked(body.documentId)
3674
3783
  }
3675
3784
 
3676
- // 边注讨论(T20)。两个动作:提问(投递当前会话)与写回回答。
3677
- //
3678
- // 🔴 与 /marks 同一把论文写锁、同一套锁内重定位:边注文件与划线文件并排放在同一篇的
3679
- // 资产目录里,改名同样会换路径。实测的伤害是改名之后工具写回的边注留在旧主名文件里,
3680
- // 面板上一条都看不到。
3681
- const writeThreadsLocked = documentId => repository.withDocumentWrite(documentId, async () => {
3682
- const state = await repository.snapshot()
3683
- const raw = await readerDocumentOf(state, documentId)
3684
- if (!raw) return json({ error: '论文不存在' }, 404)
3685
- const document = hydrateDocument(raw)
3686
- const path = discussionPathOf(document)
3687
- if (path === '') return json({ error: '这篇论文没有可讨论的正文' }, 400)
3688
- const payload = (await readDiscussionForWrite(path)) ?? { threads: [] }
3689
- const blocks = (await readerBlocksOf(documentPaths(document).contentPath)).blocks
3690
- if (body.action === 'answer') {
3691
- if (typeof body.id !== 'string' || body.id === '') return json({ error: '边注 ID 无效' }, 400)
3692
- if (typeof body.answer !== 'string') return json({ error: '回答必须是字符串' }, 400)
3693
- const outcome = answerThread(payload, { id: body.id, answer: body.answer })
3694
- if (!outcome.found) return json({ error: '边注不存在' }, 404)
3695
- await writeDiscussion(path, outcome.payload)
3696
- return json({ threads: resolveThreads(outcome.payload, blocks) })
3697
- }
3698
- if (body.action !== undefined && body.action !== 'ask') return json({ error: '边注操作必须是 ask / answer' }, 400)
3699
- if (typeof body.blockId !== 'string' || body.blockId === '') return json({ error: '要提问的段落 ID 无效' }, 400)
3700
- if (typeof body.question !== 'string' || body.question.trim() === '') return json({ error: '问题不能为空' }, 400)
3701
- // 幂等:同一 (blockId, question) 重复提问只留一条。命中时不写盘,也不重复投递 ——
3702
- // 重复投一条消息等于让 agent 答两遍同一个问题。
3703
- const appended = appendThread(payload, { blockId: body.blockId, quote: body.quote, question: body.question })
3704
- if (!appended.added) {
3705
- return json({ threads: resolveThreads(appended.payload, blocks), thread: appended.thread, delivered: false, reason: '同样的问题已经问过了' })
3706
- }
3707
- // 🔴 先落盘再投递:投递失败时这条提问仍然留在面板上(用户看得见、能重试),
3708
- // 反过来(先投递后落盘)会留下"agent 答了、面板里没有"的悬空回答。
3709
- await writeDiscussion(path, appended.payload)
3710
- const block = blocks.find(item => item?.id === body.blockId)
3711
- const message = buildQuestionMessage({ document, block, quote: body.quote, question: body.question })
3712
- const delivery = deliverToSession(body.sessionId, message)
3713
- return json({ threads: resolveThreads(appended.payload, blocks), thread: appended.thread, delivered: delivery.delivered, reason: delivery.reason })
3714
- })
3715
-
3716
- if (request.method === 'POST' && rest === '/discuss') {
3717
- if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
3718
- if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
3719
- return await writeThreadsLocked(body.documentId)
3720
- }
3785
+ // 边注的写入不在 HTTP 面上:提问走 '/select-ask'(把选区与问题送进会话),
3786
+ // 回答由 agent 用 Paper_annotate 写回(P6,用户裁定)。读侧仍走 /reader 的 threads。
3721
3787
 
3722
3788
  return undefined
3723
3789
  }
@@ -3885,7 +3951,7 @@ function hasMeaningfulValue(value) {
3885
3951
  const routes = [
3886
3952
  ['/state', ['GET']], ['/pick', ['POST']], ['/pick-folder', ['POST']], ['/scan', ['POST']], ['/add', ['POST']], ['/job', ['GET']],
3887
3953
  ['/selection', ['POST']], ['/retry', ['POST']], ['/retry-all', ['POST']], ['/reparse', ['POST']], ['/rename', ['POST']], ['/settings', ['GET', 'POST']], ['/delete', ['POST']],
3888
- ['/mineru-key', ['GET', 'POST']], ['/glossary', ['GET', 'POST']], ['/marks', ['POST']], ['/discuss', ['POST']],
3954
+ ['/mineru-key', ['GET', 'POST']], ['/glossary', ['GET', 'POST']], ['/marks', ['POST']],
3889
3955
  ['/renderer-status', ['GET']], ['/install-dependency', ['POST']],
3890
3956
  ['/update/check', ['GET']], ['/update/apply', ['POST']],
3891
3957
  ['/translate', ['POST']], ['/translate-batch', ['POST']], ['/translate-retry', ['POST']], ['/translate-pause', ['POST']], ['/translate-resume', ['POST']], ['/translate-cancel', ['POST']], ['/translate-models', ['GET']],
@@ -3895,14 +3961,17 @@ function hasMeaningfulValue(value) {
3895
3961
  // 右栏「解析」Tab(独立通路;见 /parse-add 那段注释)。
3896
3962
  ['/parse-list', ['GET']], ['/parse-add', ['POST']], ['/parse-scan', ['POST']],
3897
3963
  ['/parse-start', ['POST']], ['/parse-remove', ['POST']], ['/parse-retry', ['POST']],
3964
+ // 🔴 表格里漏一条 = 那条路径在宿主侧根本不存在:handler 写好了、回执也把地址发出去了,
3965
+ // 调用方拿到的却是 404「接口不存在」。spec 承诺 `Paper_analysis` 的 taskId 能查回来,
3966
+ // 兑现它的就是这一行。test/route-registry.test.js 逐条比对 handler 与这张表。
3967
+ ['/task', ['GET']],
3898
3968
  ]
3899
3969
  ctx.inject(['connection'], connectionCtx => {
3900
3970
  for (const [path, methods] of routes) connectionCtx.connection.registerFetchRoute(ctx, {
3901
3971
  path: API_BASE + path,
3902
3972
  methods,
3903
3973
  requestBody: 'buffered',
3904
- fetch: path === '/discuss' ? request => discussionGate.run(() => dispatch(request))
3905
- : path === '/library' ? request => serializeLibrary(() => dispatch(request))
3974
+ fetch: path === '/library' ? request => serializeLibrary(() => dispatch(request))
3906
3975
  : path === '/marks' ? request => serializeMarks(() => dispatch(request)) : dispatch,
3907
3976
  })
3908
3977
  // 阅读器资源(字节响应,不经 JSON dispatch)。
@@ -31,7 +31,7 @@ import { mapMarkdownProse } from './markdown-literals.js'
31
31
  * 只认这些名字:它们全是**行内**标记,剥掉外壳文字仍在句子里。表格 / 围栏这类块级结构
32
32
  * 不走这里(各自有 html / 转 GFM 的处理),所以不在名单里。
33
33
  */
34
- export const INLINE_TAG_RE = /<\/?\s*(?:sup|sub|i|em|b|strong|u|s|del|ins|mark|small|big|tt|code|abbr|cite|q|span|font)(?:\s[^<>]*)?\s*\/?>/gi
34
+ export const INLINE_TAG_RE = /<\/?\s*(?:sup|sub|i|em|b|strong|u|s|del|ins|mark|small|big|tt|code|abbr|cite|q|span|font)(?:\s+[a-z-]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))*\s*\/?>/gi
35
35
 
36
36
  /**
37
37
  * 把一段正文里的行内 HTML 折成可读纯文本:`<br>` → 空格,白名单标签剥壳、**保留标签内的文字**。
package/lib/item-ops.js CHANGED
@@ -10,7 +10,7 @@
10
10
  * HTTP 4xx 或工具的一句话。不读盘、不写盘、不看时间以外的外部状态。
11
11
  */
12
12
 
13
- import { READ_STATUSES, setProgress, setTrashed } from './library.js'
13
+ import { MAX_TAGS_PER_ITEM, READ_STATUSES, setProgress, setTrashed } from './library.js'
14
14
 
15
15
  /** 本模块认识的动作。`opened` / `progress` 只有界面会发,但同样收在这里 —— 路由不必为它们留分支。 */
16
16
  export const ITEM_ACTIONS = Object.freeze([
@@ -55,7 +55,19 @@ export function applyItemAction(current, request, now = new Date().toISOString()
55
55
  if (action === 'tag') {
56
56
  const tag = textOf(request.tag).trim()
57
57
  if (tag === '') throw new Error('标签不能为空')
58
- return { ...item, tags: [...tagsOf(item), tag] }
58
+ const current = tagsOf(item)
59
+ // 🔴 上限必须在这里就报错,不能留给落盘时的 normalizeTags 去砍。
60
+ // normalizeTags 是「收口」(丢空、丢超长、去重、截到上限),它的截断对调用方是**静默**的:
61
+ // 实测第 21 个标签 applyItemAction 返回 21 条、writeItem 落盘 20 条、新标签不在里面,
62
+ // 而 '/item' 与 'Paper_library' 两条路径都无条件回报成功 —— 用户看到「已添加」,刷新后没了。
63
+ // 与 library-service.js 的 tags-add 同一条口径:超限是用户的输入问题,要报出来。
64
+ // ⚠️ 这里**不做去重**:去重是 normalizeTags 的职责,本函数的契约是「只负责加上这一条」
65
+ // (既有用例明确钉着 `tag:'NLP'` 对 `['nlp']` 要得到 `['nlp','NLP']`)。所以只在
66
+ // 「这一条确实会新增、而集合已经满了」时报错;已经在集合里的标签再点一次是幂等的,
67
+ // 不能因为满了就报错 —— normalizeTags 会把它去重掉,落盘根本不会超。
68
+ const duplicate = current.some(value => value.toLowerCase() === tag.toLowerCase())
69
+ if (!duplicate && current.length >= MAX_TAGS_PER_ITEM) throw new Error(`每篇最多 ${MAX_TAGS_PER_ITEM} 个标签`)
70
+ return { ...item, tags: [...current, tag] }
59
71
  }
60
72
 
61
73
  if (action === 'untag') {
@@ -23,9 +23,32 @@ const tagOf = value => {
23
23
  export function createLibraryService({ path, items, itemPath, withWrite }) {
24
24
  /** 包一层写锁;没有注入时照旧执行(单独使用本模块的测试不需要)。 */
25
25
  const locked = operation => (typeof withWrite === 'function' ? withWrite(operation) : operation())
26
- async function load() {
26
+ /**
27
+ * 读文献库,顺便完成一次性迁移。
28
+ *
29
+ * 🔴 **迁移必须走跨实例写锁**(`withWrite`),和所有其他写路径一样。
30
+ * 它原本是「读 → 判断 → 写」写在锁外的:两个宿主共享同一个 `$DSH_HOME/runtime`
31
+ * (多 profile 是设计前提,见 AGENTS.md §1)时,A 刚建好一个集合、B 这时的 `load()`
32
+ * 用自己那份**迁移前**的快照整份覆盖,A 的集合就没了 —— 而且两边都报成功。
33
+ * 实测:A 建集合后盘上是 `["Methods","UserMade"]`,B 收尾后只剩 `["Methods"]`。
34
+ *
35
+ * 只有**真正要迁移**时才取锁:正常读路径(`collectionsMigrated` 已为真)不加锁,
36
+ * 否则每 2 秒一次的轮询读会去抢那把锁。
37
+ */
38
+ async function load(options = {}) {
27
39
  const library = await readLibrary(path)
28
40
  if (library.collectionsMigrated) return library
41
+ // `inLock` 为真表示调用方**已经持有**具名写锁(`handleLocked` 就是),
42
+ // 再取一次会自锁死:具名写锁不可重入,实测 4.6 秒后抛「正被另一个操作占用」、路由回 500。
43
+ if (options.inLock === true) return migrateLocked(library)
44
+ return locked(() => migrateLocked(library))
45
+ }
46
+ /** 迁移本体:调用方保证已持锁。 */
47
+ async function migrateLocked() {
48
+ // 拿到锁之后**重读一次**:等锁期间别人可能已经把迁移做完了,
49
+ // 也可能是别人刚写进一个新集合 —— 这次读到的才是要基于它迁移的那一份。
50
+ const current = await readLibrary(path)
51
+ if (current.collectionsMigrated) return current
29
52
  let original
30
53
  try { original = await readFile(path, 'utf8') } catch (error) { if (error.code !== 'ENOENT') throw error }
31
54
  if (original?.trim()) {
@@ -35,10 +58,10 @@ export function createLibraryService({ path, items, itemPath, withWrite }) {
35
58
  try { await writeFile(path + '.v1.bak', original, { flag: 'wx' }) } catch (error) { if (error.code !== 'EEXIST') throw error }
36
59
  }
37
60
  const entries = await items()
38
- const next = { ...library, collectionsMigrated: true, categories: [],
39
- hidden: library.hidden.filter(key => !key.startsWith('c:')),
40
- pinned: library.pinned.filter(key => !key.startsWith('c:')),
41
- collections: library.collections.length ? library.collections : library.categories.map(name => ({
61
+ const next = { ...current, collectionsMigrated: true, categories: [],
62
+ hidden: current.hidden.filter(key => !key.startsWith('c:')),
63
+ pinned: current.pinned.filter(key => !key.startsWith('c:')),
64
+ collections: current.collections.length ? current.collections : current.categories.map(name => ({
42
65
  id: randomUUID(), name, parentId: null,
43
66
  documentIds: entries.filter(entry => entry.item.tags.some(tag => model.lower(tag) === model.lower(name))).map(entry => entry.documentId),
44
67
  })) }
@@ -63,7 +86,8 @@ export function createLibraryService({ path, items, itemPath, withWrite }) {
63
86
  async function handleLocked(body) {
64
87
  const action = body.action
65
88
  if (!action?.startsWith('collection-') && !action?.startsWith('search-') && !action?.startsWith('tags-') && action !== 'library-preferences' && action !== 'items-batch') return null
66
- const library = await load()
89
+ // 已经在本函数的 locked(...) 里了,迁移不能再取一次锁。
90
+ const library = await load({ inLock: true })
67
91
  let next = { ...library }, report = {}
68
92
  const getCollection = () => {
69
93
  const row = model.collection(library, body.collectionId)
@@ -164,13 +188,13 @@ export function createLibraryService({ path, items, itemPath, withWrite }) {
164
188
  }
165
189
  async function forget(ids) {
166
190
  return locked(async () => {
167
- const library = await load()
191
+ const library = await load({ inLock: true })
168
192
  await writeLibrary(path, { ...library, collections: library.collections.map(row => ({ ...row, documentIds: row.documentIds.filter(id => !ids.includes(id)) })) })
169
193
  })
170
194
  }
171
195
  async function attachImported(collectionId, ids) {
172
196
  return locked(async () => {
173
- const library = await load()
197
+ const library = await load({ inLock: true })
174
198
  if (!model.collection(library, collectionId)) throw new Error('论文已导入,但目标集合已删除,请重新归类')
175
199
  await writeLibrary(path, { ...library, collections: library.collections.map(row => row.id === collectionId
176
200
  ? { ...row, documentIds: [...new Set([...row.documentIds, ...ids])] } : row) })
@@ -870,9 +870,12 @@ export function createLibraryTool(deps = {}) {
870
870
  let collectionId
871
871
  let parentId
872
872
  let sourceCollectionId
873
+ /** 来源集合的**名字**(不是 id):宿主侧回执要原样印出来,见下面 request.from。 */
874
+ let sourceCollectionName = ''
873
875
  if (action === 'collection-merge' || action === 'collection-move-items') {
874
876
  const from = textOf(args?.from) !== '' ? textOf(args?.from) : textOf(args?.sourceCollection)
875
877
  if (from.trim() === '') return fail(action, action + ' 需要 from(或 sourceCollection):来源集合名。')
878
+ sourceCollectionName = from.trim()
876
879
  const row = findCollection(library, from)
877
880
  if (row === undefined) return fail(action, '没有叫「' + from + '」的集合。用 collections 动作看现有集合。')
878
881
  sourceCollectionId = row.id
@@ -896,6 +899,9 @@ export function createLibraryTool(deps = {}) {
896
899
  collectionId,
897
900
  parentId,
898
901
  sourceCollectionId: sourceCollectionId,
902
+ // 来源集合的名字要一路带到宿主侧:collection-merge 的回执要印「已把「X」并入」,
903
+ // 只传 id 的话那句话永远是空引号(宿主读 request.from,见 tool-host.js)。
904
+ from: sourceCollectionName,
899
905
  keepInSource: args?.keepInSource === true,
900
906
  trashItems: args?.trashItems === true,
901
907
  documentIds: ids,
@@ -100,6 +100,14 @@ function canTryAnotherSource(error) {
100
100
  export function metadataIdentifier(value) {
101
101
  let input = text(value)
102
102
  if (!input || input.length > 2048) return null
103
+ // 🔴 前缀要在解析 URL **之前**剥掉。
104
+ //
105
+ // `doi:10.1234/x` 是个合法的 URI —— `new URL()` 会接受它并把 `protocol` 认成 `'doi:'`、
106
+ // `hostname` 认成空串。于是它既不是 doi.org、也不是 aclanthology、也不是 arxiv.org,
107
+ // 走进最后的 `else return null` —— 后面那句剥前缀的代码**永远执行不到**。
108
+ // 实测:模型按提示写 `doi:10.1234/test` 或 `arxiv:2101.00001` 一律 null,
109
+ // 而裸写同样的值能过,用户收到的却是一句「标识无效」。
110
+ input = input.replace(/^doi:\s*/i, '').replace(/^arxiv:\s*/i, '').trim()
103
111
  try {
104
112
  const url = new URL(input)
105
113
  if (url.username || url.password || url.port) return null
@@ -112,7 +120,6 @@ export function metadataIdentifier(value) {
112
120
  input = url.pathname.replace(/^\/(?:abs|pdf)\//, '').replace(/\.pdf$/, '')
113
121
  } else return null
114
122
  } catch { /* Bare identifiers have no URL scheme. */ }
115
- input = input.replace(/^doi:\s*/i, '').replace(/^arxiv:\s*/i, '')
116
123
  if (DOI.test(input) && !/[<>"\\]/.test(input)) return { type: 'doi', id: input.toLowerCase() }
117
124
  if (ARXIV.test(input)) return { type: 'arxiv', id: input }
118
125
  return null