@li-canghai/dsh-paper 0.8.1 → 0.8.3

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 (43) hide show
  1. package/README.md +42 -93
  2. package/THIRD_PARTY_NOTICES.md +69 -0
  3. package/lib/annotate-tool.js +58 -10
  4. package/lib/block-cache.js +45 -26
  5. package/lib/blocks-reconcile.js +56 -17
  6. package/lib/client-parts/01-pure-helpers.js +410 -7
  7. package/lib/client-parts/02-author-year.js +111 -24
  8. package/lib/client-parts/03-pdf-stack.js +97 -0
  9. package/lib/client.js +1022 -112
  10. package/lib/code-source.js +8 -8
  11. package/lib/discussion.js +2 -101
  12. package/lib/export.js +228 -14
  13. package/lib/file-lock.js +128 -16
  14. package/lib/gloss.js +1030 -12
  15. package/lib/index.js +193 -68
  16. package/lib/inline-html.js +1 -1
  17. package/lib/item-ops.js +14 -2
  18. package/lib/library-service.js +32 -8
  19. package/lib/library-tool.js +6 -0
  20. package/lib/metadata-enrichment.js +8 -1
  21. package/lib/pdf-analysis-tool.js +72 -0
  22. package/lib/pdf-page.js +609 -13
  23. package/lib/picker.js +19 -5
  24. package/lib/reader-store.js +14 -10
  25. package/lib/rename-document.js +25 -3
  26. package/lib/search-index.js +0 -9
  27. package/lib/selection-message.js +2 -3
  28. package/lib/storage.js +122 -10
  29. package/lib/store-paths.js +0 -13
  30. package/lib/table-gfm.js +42 -14
  31. package/lib/tex-fetch.js +0 -1
  32. package/lib/tex-merge.js +0 -1
  33. package/lib/tex-prepare.js +74 -13
  34. package/lib/text-similarity.js +0 -9
  35. package/lib/tool-host.js +4 -1
  36. package/lib/translate-prompts.js +11 -1
  37. package/lib/translate-queue.js +1 -34
  38. package/lib/translate-task.js +1 -1
  39. package/lib/translate.js +57 -26
  40. package/lib/update-contracts.js +5 -5
  41. package/locale/en.json +6 -0
  42. package/locale/zh.json +6 -0
  43. package/package.json +7 -2
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, 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
@@ -392,6 +419,18 @@ function mergeReaderBlocks(blocks, translation) {
392
419
  })
393
420
  }
394
421
 
422
+ /**
423
+ * 两侧**折掉空白后**逐字相等。
424
+ *
425
+ * 只服务「整段选区」这一个判断:PDF 原页的 group.text 在行与行之间补了空格,而选区那侧
426
+ * (或 DOM 的 textContent)一个分隔符都没有,同一个覆盖范围在两侧差着几个空格。
427
+ */
428
+ function sameIgnoringSpace(left, right) {
429
+ const squeeze = value => String(value ?? '').replace(/[\s\u00ad\u200b\u200c\u200d\ufeff]+/gu, '')
430
+ const a = squeeze(left)
431
+ return a !== '' && a === squeeze(right)
432
+ }
433
+
395
434
  /** 日志里的文档 id 截断:state 记录可能来自手工改过的文件,不能拿它拼无上限的日志行。 */
396
435
  function truncateForLog(value, max = 64) {
397
436
  const text = String(value ?? '')
@@ -399,7 +438,6 @@ function truncateForLog(value, max = 64) {
399
438
  }
400
439
 
401
440
  export function apply(ctx, config = {}) {
402
- const discussionGate = createConcurrencyGate(1)
403
441
  const repository = new PaperRepository(runtimeRoot(config))
404
442
  const metadataResolver = config.metadataResolver ?? createMetadataResolver({ networkMode: config.metadataNetworkMode ?? 'auto' })
405
443
  if (!config.metadataResolver) ctx.effect?.(() => () => metadataResolver.dispose())
@@ -589,6 +627,8 @@ export function apply(ctx, config = {}) {
589
627
  translateAll: batch.translateAll,
590
628
  batchPages: batch.batchPages,
591
629
  targetLanguage: batch.targetLanguage,
630
+ // 请求身份(见 startTranslation 的说明):线路侧用它发会话头,模型侧看不到。
631
+ sessionId: batch.sessionId,
592
632
  // 输出协议(D138 / D139):专用翻译模型用 lines / plain,通用模型用默认 json。
593
633
  protocol: batch.protocol,
594
634
  // 🔴 单篇内的**批次并发**(D139):队列的并发数是跨文档的(taskId 是 documentId),
@@ -610,7 +650,15 @@ export function apply(ctx, config = {}) {
610
650
  // 而 translateDocument 自己不抛错。这里若一律回 ok:true,任务会以 ready 收尾 ——
611
651
  // 用户看到的是「点一下就说完成、译文一个字没变」,连一条失败记录都留不下(实测踩过:
612
652
  // 435 个块全失败的任务报到界面上是「翻译完成」)。零译出必须当场算失败,并把原因带出去。
613
- 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) {
614
662
  return { ok: false, error: translationFailureText(outcome, batch) }
615
663
  }
616
664
  return { ok: true }
@@ -702,7 +750,21 @@ export function apply(ctx, config = {}) {
702
750
  pathOf: document => discussionPathOf(document),
703
751
  readPayload: path => readDiscussionForWrite(path),
704
752
  writePayload: (path, payload) => writeDiscussion(path, payload),
705
- 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
+ }),
706
768
  deleteThread,
707
769
  appendThread,
708
770
  answerThread,
@@ -1613,6 +1675,10 @@ function hasMeaningfulValue(value) {
1613
1675
  // 多带两个自己的字段不影响它 —— 它从头到尾只把 batch 原样回调给 runBatch。
1614
1676
  jobId: job.id,
1615
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 : '',
1616
1682
  model: await resolveTranslationModel(),
1617
1683
  scope: body.scope === undefined ? undefined : { mode: body.scope.mode, pageFrom: body.scope.pageFrom, pageTo: body.scope.pageTo },
1618
1684
  incremental: body.incremental === true,
@@ -1773,7 +1839,7 @@ function hasMeaningfulValue(value) {
1773
1839
  // (archivePath 里的 ID 校验)。而 validId 只查字符集,'not-a-hash' 这类能过它 ——
1774
1840
  // 于是任何一条带非哈希 documentId 的请求都会变成 500。这里先按同一条形状收口:
1775
1841
  // 不是哈希就根本没有冷记录可找,直接当"不存在",由调用方回 404。
1776
- // 这一处是 /reader、/marks、/discuss、/open、/ask、/export、/item、/library 共用的入口,
1842
+ // 这一处是 /reader、/marks、/open、/export、/item、/library 共用的入口,
1777
1843
  // 所以修在这里等于八条路由一起修好。
1778
1844
  if (!/^[a-f0-9]{64}$/.test(String(documentId))) return undefined
1779
1845
  return await repository.archivedDocument(documentId) ?? undefined
@@ -1848,7 +1914,7 @@ function hasMeaningfulValue(value) {
1848
1914
  * 以为提问丢了 —— 而它并没有。
1849
1915
  *
1850
1916
  * @param {string} sessionId 当前会话。
1851
- * @param {object} message buildQuestionMessage 的产物。
1917
+ * @param {object} message 注入消息(buildSelectionMessage / buildMetadataConflictMessage 的产物)。
1852
1918
  * @returns {{delivered: boolean, reason?: string}}
1853
1919
  */
1854
1920
  function deliverToSession(sessionId, message) {
@@ -1999,12 +2065,32 @@ function hasMeaningfulValue(value) {
1999
2065
  const allJobs = Object.values(state.jobs)
2000
2066
  const machineParses = summarizeProgress(allJobs)
2001
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
+ }
2002
2083
  // 会话仍关联、未隐藏的论文:既是要渲染的卡片,也是进度口径的"已完成"兜底来源。
2003
2084
  const attachedDocuments = Object.values(state.documents).filter(document => documentIds.has(document.id) && !document.hidden)
2004
2085
  const readyDocumentIds = attachedDocuments.map(document => document.id)
2005
2086
  return json({
2006
2087
  documents: await Promise.all(attachedDocuments.map(document => documentReader.documentView(document, state.settings.outlineBudgetBytes))),
2007
- jobs,
2088
+ // taskId 只在解析任务上有意义(翻译任务不进任务清单)。没有对应编号的记录保持原样,
2089
+ // 少一个字段好过给一个查不到的编号。
2090
+ jobs: jobs.map(job => {
2091
+ const taskId = taskIdOfDocument.get(job.documentId)
2092
+ return taskId === undefined ? job : { ...job, taskId }
2093
+ }),
2008
2094
  progress: summarizeProgress(jobs, { readyDocumentIds }),
2009
2095
  // 翻译任务的"已完成"兜底集合不能复用论文记录:翻译完成不改 documents 的 ready 语义。
2010
2096
  // T12 有翻译侧的持久证据时在这里补上 readyTranslationDocumentIds,现在只能按任务记录算。
@@ -2012,15 +2098,29 @@ function hasMeaningfulValue(value) {
2012
2098
  queue: { pending: machineParses.pending, running: machineParses.running },
2013
2099
  // 全局刹车态(D70):侧栏据此决定显示「暂停翻译」还是「继续翻译」。
2014
2100
  translationPaused: translateQueue.isPaused(),
2015
- 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() },
2016
2110
  selection,
2017
2111
  mineru: resolver.describeMineru(),
2018
2112
  })
2019
2113
  }
2020
2114
 
2021
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)
2022
2122
  const state = await repository.snapshot()
2023
- const job = state.jobs[url.searchParams.get('id') ?? '']
2123
+ const job = state.jobs[jobId]
2024
2124
  return job ? json({ job }) : json({ error: '任务不存在' }, 404)
2025
2125
  }
2026
2126
 
@@ -2221,6 +2321,19 @@ function hasMeaningfulValue(value) {
2221
2321
  return json(parseExport.list())
2222
2322
  }
2223
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
+
2224
2337
  return undefined
2225
2338
  }
2226
2339
 
@@ -2462,6 +2575,11 @@ function hasMeaningfulValue(value) {
2462
2575
  if (request.method === 'POST' && rest === '/translate-batch') {
2463
2576
  const batch = batchDocumentIds(body)
2464
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)
2465
2583
  const snapshot = await repository.snapshot()
2466
2584
  const scope = translationScopeOf(snapshot.settings)
2467
2585
  const probed = await mapWithConcurrency(batch.ids, BATCH_TRANSLATE_CONCURRENCY, documentId => translationBatchEntry(snapshot, documentId, scope))
@@ -2490,6 +2608,9 @@ function hasMeaningfulValue(value) {
2490
2608
  id: `job-${randomUUID()}`,
2491
2609
  kind: 'translate',
2492
2610
  documentId: entry.documentId,
2611
+ // 会话 id 会进 job 记录、也会一路透传到模型请求的 `options.sessionId`(见 beginTranslation)。
2612
+ // 同族的 /translate、/translate-retry 都在入口用 validId 挡住脏值,这条没有 —— 非字符串
2613
+ // 落盘后每个消费者都要自己再收敛一次,而只要新增一个忘了收敛的消费者就是脏数据入口。
2493
2614
  sessionId: body.sessionId ?? '',
2494
2615
  pdfPath: hydrateDocument(entry.document).pdfPath,
2495
2616
  pdfName: entry.pdfName,
@@ -3321,11 +3442,37 @@ function hasMeaningfulValue(value) {
3321
3442
  if (body.pdfPage !== undefined) {
3322
3443
  if (!Number.isSafeInteger(body.pdfPage) || body.pdfPage < 1) return json({ error: 'PDF 页码无效' }, 400)
3323
3444
  const native = await pdfPageFor(document, body.pdfPage, blocks)
3324
- nativeContext = native.groups.find(group => group.id === blockId)?.text ?? ''
3445
+ nativeContext = pdfBlockText(native.groups, blockId)
3325
3446
  if (nativeContext) sourceContext = nativeContext
3326
3447
  }
3327
3448
  let counterpart = ''
3449
+ // counterpart 属于哪一侧。对齐分支里由 fromSource 定;非对齐分支留空(那时没有 counterpart)。
3450
+ let counterpartKind
3328
3451
  let selectedContext = ''
3452
+ /**
3453
+ * 把「另一语言的范围」写回这条划线。
3454
+ *
3455
+ * 🔴 写回前**按最新块重校验**:align 是一次模型调用,期间正文可能被重译、译文可能被改。
3456
+ * 拿旧的两侧去写 parallelQuote 会把一个已经不存在的位置记进盘里,下次打开就画错地方。
3457
+ * 校验口径与调用方一致:两侧都必须仍然是「latestSource 或 latestTranslation」之一。
3458
+ */
3459
+ const writeParallel = parallelQuote => serializeMarks(async () => {
3460
+ const path = readerPathOf(document)
3461
+ if (!path) return json({reason:'no-match'})
3462
+ // 写入路径必须用严格读:这里要基于文件内容改写,坏读降级成空表等于把整篇划线换掉。
3463
+ const store = await readReaderStoreForWrite(path)
3464
+ const marks = Array.isArray(store?.marks) ? [...store.marks] : []
3465
+ const index = marks.findIndex(mark => mark.id === body.markId && mark.blockId === blockId && plainInlineText(mark.quote) === glossQuote)
3466
+ if (index < 0) return json({reason:'no-match',error:'划线已删除或改变'})
3467
+ const latestBlocks = mergeReaderBlocks((await readerBlocksOf(documentPaths(document).contentPath)).blocks, await readTranslation(translationPathOf(document)))
3468
+ const latest = latestBlocks.find(row=>row.id===blockId)
3469
+ const latestNative = nativeContext ? pdfBlockText((await pdfPageFor(document, body.pdfPage, latestBlocks)).groups, blockId) : ''
3470
+ const latestSource = latestNative || plainInlineText(latest?.sourceText ?? ''), latestTranslation = plainInlineText(latest?.zh ?? '')
3471
+ if (!([latestSource,latestTranslation].includes(sourceContext) && [latestSource,latestTranslation].includes(counterpart))) return json({reason:'no-match',error:'正文或译文已更新,请重新匹配'})
3472
+ marks[index] = {...marks[index],parallelQuote}
3473
+ await writeReaderStore(path,{...store,marks})
3474
+ return json({markId:body.markId,parallelQuote})
3475
+ })
3329
3476
  if (body.align === true) {
3330
3477
  const store = await readReaderStore(readerPathOf(document))
3331
3478
  const mark = (Array.isArray(store?.marks)?store.marks:[]).find(mark=>mark.id===body.markId && mark.blockId===blockId && plainInlineText(mark.quote)===glossQuote)
@@ -3336,21 +3483,39 @@ function hasMeaningfulValue(value) {
3336
3483
  const source = nativeContext || plainInlineText(block?.sourceText ?? ''), translated = plainInlineText(block?.zh ?? '')
3337
3484
  if (!source || !translated || !glossQuote.trim()) return json({reason:'no-match'})
3338
3485
  // Anchor against the selected language; the model must copy from the other one.
3339
- const inSource = source.includes(glossQuote), inTranslation = translated.includes(glossQuote)
3486
+ // 🔴 原页那侧(source 来自 group.text)与选中串的行接缝口径不同,必须走
3487
+ // pdfQuoteInText 的空白无关比较,理由与 /marks 的校验完全一样:group.text 在
3488
+ // 行与行之间补一个空格,而 DOM 的 textContent 一个分隔符都没有。用裸 includes
3489
+ // 时,PDF 原页上的跨行选区一律判 no-match —— 界面报「另一语言暂未定位」,
3490
+ // 而两侧的文字其实都在。译文那侧是同一份 plainInlineText 产物,照旧精确比较。
3491
+ const inSource = pdfQuoteInText(source, glossQuote), inTranslation = translated.includes(glossQuote)
3340
3492
  const fromSource = mark.sourceLanguage === 'source' ? true : mark.sourceLanguage === 'translation' ? false : inSource
3341
3493
  if (!mark.sourceLanguage && inSource && inTranslation) return json({reason:'already-matched'})
3342
3494
  if (fromSource ? !inSource : !inTranslation) return json({reason:'no-match'})
3343
3495
  sourceContext = fromSource ? source : translated
3344
3496
  counterpart = fromSource ? translated : source
3497
+ counterpartKind = fromSource ? 'translation' : 'source'
3345
3498
  if (Math.max(sourceContext.length,counterpart.length) > 60000) return json({reason:'no-match',error:'段落过长,未执行自动匹配'})
3499
+ // 🔴 **整段选区不需要模型**:模型那一档要它「从译文里挑最短的唯一连续子串」,而选区
3500
+ // 覆盖整段时正确答案就是**整段译文**,没有任何可挑的余地。实测 ResNet 第 2 页
3501
+ // p2-p2:用户在 PDF 原页上从头划到尾(693 字,折空白后与 group.text 的 589 字全等),
3502
+ // 模型被问了两次都只回 6–9 个 token(输出 NONE 一类),验收的 indexOf 必然落空,
3503
+ // 界面报「另一语言暂未定位」—— 两侧的文字其实都在,而且一一对应。
3504
+ // 判据用折空白后的相等:group.text 在行接缝补了空格,选区那侧没有。
3505
+ if (fromSource ? sameIgnoringSpace(source, glossQuote) : sameIgnoringSpace(translated, glossQuote)) {
3506
+ return await writeParallel(counterpart)
3507
+ }
3346
3508
  }
3347
3509
  const settings = state.settings
3348
3510
  const model = await resolveTranslationModel()
3349
3511
  translationGate.setLimit(concurrencyOf(settings))
3512
+ // counterpart 是哪一侧这里**确定知道**(对齐分支按 fromSource 赋值),
3513
+ // 传下去就不必让 gloss.js 靠字符统计去猜 —— 猜错的代价见 counterpartLanguage 的说明。
3350
3514
  const outcome = await translateSelection({
3351
3515
  quote: glossQuote,
3352
3516
  context: sourceContext,
3353
3517
  counterpart,
3518
+ counterpartKind,
3354
3519
  selectedContext,
3355
3520
  reference: documentReferenceOf(Array.isArray(blocks) ? blocks : []),
3356
3521
  targetLanguage: settings?.translationLanguage,
@@ -3359,6 +3524,8 @@ function hasMeaningfulValue(value) {
3359
3524
  model,
3360
3525
  glossary: await glossaryBlockFor(),
3361
3526
  gate: translationGate,
3527
+ // 与整篇翻译同一条透传:释义同样打给同一条线路,opencode-go 靠它发会话头。
3528
+ sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
3362
3529
  })
3363
3530
  // 记账与翻译同一口径(T24):键是(文档 + 原话)的确定性哈希,所以同一个词翻两次
3364
3531
  // 在账本里仍是一条 —— 这一档本就分辨不出"两次真实调用"与"同一次被观测两遍"。
@@ -3379,7 +3546,7 @@ function hasMeaningfulValue(value) {
3379
3546
  if (index < 0) return json({reason:'no-match',error:'划线已删除或改变'})
3380
3547
  const latestBlocks = mergeReaderBlocks((await readerBlocksOf(documentPaths(document).contentPath)).blocks, await readTranslation(translationPathOf(document)))
3381
3548
  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 : ''
3549
+ const latestNative = nativeContext ? pdfBlockText((await pdfPageFor(document, body.pdfPage, latestBlocks)).groups, blockId) : ''
3383
3550
  const latestSource = latestNative || plainInlineText(latest?.sourceText ?? ''), latestTranslation = plainInlineText(latest?.zh ?? '')
3384
3551
  if (!([latestSource,latestTranslation].includes(sourceContext) && [latestSource,latestTranslation].includes(counterpart))) return json({reason:'no-match',error:'正文或译文已更新,请重新匹配'})
3385
3552
  marks[index] = {...marks[index],parallelQuote:outcome.zh}
@@ -3403,7 +3570,7 @@ function hasMeaningfulValue(value) {
3403
3570
  // 没选内容 → 客户端根本不调这里,走 /selection 注入(论文 id + 论文名 + 章节树)
3404
3571
  // 选中内容 → 这条:上面全部 **+ 块 id + 选中原话 + 该段所在段落**
3405
3572
  //
3406
- // 🔴 与 /discuss 同一条投递口径(D95):必须用 followup 唤醒驱动,投递失败不算 HTTP 失败。
3573
+ // 🔴 与 /selection 同一条投递口径(D95):必须用 followup 唤醒驱动,投递失败不算 HTTP 失败。
3407
3574
  if (request.method === 'POST' && rest === '/select-ask') {
3408
3575
  if (!validId(body.sessionId)) return json({ error: '会话 ID 无效' }, 400)
3409
3576
  if (!validId(body.documentId)) return json({ error: '论文 ID 无效' }, 400)
@@ -3565,8 +3732,7 @@ function hasMeaningfulValue(value) {
3565
3732
  for (const segment of segments) {
3566
3733
  // 与单段同一条校验:PDF 标注必须确实存在于原页那一段的文字里。
3567
3734
  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)
3735
+ if (!pdfQuoteInText(pdfBlockText(native.groups, segment.blockId), segment.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
3570
3736
  }
3571
3737
  const groupId = randomUUID()
3572
3738
  const created = segments.map(segment => makeMark({
@@ -3591,8 +3757,7 @@ function hasMeaningfulValue(value) {
3591
3757
  if (body.pdfPage !== undefined) {
3592
3758
  if (!Number.isSafeInteger(body.pdfPage) || body.pdfPage < 1 || body.sourceLanguage !== 'source') return json({ error: 'PDF 标注页码或语言无效' }, 400)
3593
3759
  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)
3760
+ if (typeof body.quote !== 'string' || !body.quote.trim() || !pdfQuoteInText(pdfBlockText(native.groups, body.blockId), body.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
3596
3761
  }
3597
3762
  const mark = makeMark({
3598
3763
  blockId: body.blockId,
@@ -3617,51 +3782,8 @@ function hasMeaningfulValue(value) {
3617
3782
  return await writeMarksLocked(body.documentId)
3618
3783
  }
3619
3784
 
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
- }
3785
+ // 边注的写入不在 HTTP 面上:提问走 '/select-ask'(把选区与问题送进会话),
3786
+ // 回答由 agent 用 Paper_annotate 写回(P6,用户裁定)。读侧仍走 /reader 的 threads。
3665
3787
 
3666
3788
  return undefined
3667
3789
  }
@@ -3829,7 +3951,7 @@ function hasMeaningfulValue(value) {
3829
3951
  const routes = [
3830
3952
  ['/state', ['GET']], ['/pick', ['POST']], ['/pick-folder', ['POST']], ['/scan', ['POST']], ['/add', ['POST']], ['/job', ['GET']],
3831
3953
  ['/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']],
3954
+ ['/mineru-key', ['GET', 'POST']], ['/glossary', ['GET', 'POST']], ['/marks', ['POST']],
3833
3955
  ['/renderer-status', ['GET']], ['/install-dependency', ['POST']],
3834
3956
  ['/update/check', ['GET']], ['/update/apply', ['POST']],
3835
3957
  ['/translate', ['POST']], ['/translate-batch', ['POST']], ['/translate-retry', ['POST']], ['/translate-pause', ['POST']], ['/translate-resume', ['POST']], ['/translate-cancel', ['POST']], ['/translate-models', ['GET']],
@@ -3839,14 +3961,17 @@ function hasMeaningfulValue(value) {
3839
3961
  // 右栏「解析」Tab(独立通路;见 /parse-add 那段注释)。
3840
3962
  ['/parse-list', ['GET']], ['/parse-add', ['POST']], ['/parse-scan', ['POST']],
3841
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']],
3842
3968
  ]
3843
3969
  ctx.inject(['connection'], connectionCtx => {
3844
3970
  for (const [path, methods] of routes) connectionCtx.connection.registerFetchRoute(ctx, {
3845
3971
  path: API_BASE + path,
3846
3972
  methods,
3847
3973
  requestBody: 'buffered',
3848
- fetch: path === '/discuss' ? request => discussionGate.run(() => dispatch(request))
3849
- : path === '/library' ? request => serializeLibrary(() => dispatch(request))
3974
+ fetch: path === '/library' ? request => serializeLibrary(() => dispatch(request))
3850
3975
  : path === '/marks' ? request => serializeMarks(() => dispatch(request)) : dispatch,
3851
3976
  })
3852
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,