dsh-paper-workbench 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -76,6 +76,7 @@ import {
76
76
  } from './store.js'
77
77
  import { buildScopePrompt } from './conv.js'
78
78
  import { createPaperContext, mergeUiState } from './paper-context.js'
79
+ import { normalizeHistoryItem, normalizeBrowseHistory } from './history.js'
79
80
  import { cropRegion, extractText as pdfText, findPython, info as pdfInfo, loadText, outline as pdfOutline, pageLines, renderPage, searchText } from './pdf.js'
80
81
  import { createHandler, json } from './server.js'
81
82
  import { registerTools } from './tools.js'
@@ -277,7 +278,8 @@ export function setPaperContextRuntime(next) {
277
278
  globalThis.__pbUiChain ||= Promise.resolve()
278
279
  function updateUiState(patch) {
279
280
  const run = globalThis.__pbUiChain.then(async () => {
280
- const state = mergeUiState(await readUiState(), patch)
281
+ const previous = await readUiState()
282
+ const state = mergeUiState(previous, typeof patch === 'function' ? patch(previous) : patch)
281
283
  return { ok: true, state: await writeUiState(state) }
282
284
  })
283
285
  globalThis.__pbUiChain = run.then(() => undefined, () => undefined)
@@ -321,6 +323,23 @@ async function getTranslateJobs() {
321
323
  return holder.manager
322
324
  }
323
325
 
326
+ async function getZhPdfJobs() {
327
+ const holder = (globalThis.__pbZhPdfJobs ||= { manager: null, tag: '', root: '', pending: null })
328
+ if (holder.manager && holder.tag === LOAD_TAG && holder.root === DATA_ROOT) return holder.manager
329
+ if (!holder.pending) holder.pending = (async () => {
330
+ const [jobsModule, zhModule, storeModule, pdfModule, docModule, translateJobs] = await Promise.all([
331
+ mod('zhpdf-jobs'), mod('zhpdf'), mod('store'), mod('pdf'), mod('doc'), getTranslateJobs(),
332
+ ])
333
+ const manager = jobsModule.createZhPdfJobManager({
334
+ store: storeModule, doc: docModule, zhpdf: zhModule.createZhPdf({ store: storeModule, pdf: pdfModule }), translateJobs,
335
+ })
336
+ await manager.ready()
337
+ Object.assign(holder, { manager, tag: LOAD_TAG, root: DATA_ROOT })
338
+ return manager
339
+ })().finally(() => { holder.pending = null })
340
+ return holder.pending
341
+ }
342
+
324
343
  /** 日志模块自己坏掉不能拖垮业务:包一层,永不抛。 */
325
344
  async function safeJob(fn) {
326
345
  try {
@@ -636,7 +655,9 @@ async function submitOcr(id, modelArg, generation) {
636
655
  if (!live()) return // 期间用户点了「清除 OCR」:不要再把结果写回去
637
656
  await writeOcr(id, result.markdown)
638
657
  // 扫描件建模依赖 ocr.md:OCR 换了内容必须让 doc 重建
639
- ;(await mod('doc')).invalidateDocCache(id, { dropDoc: true })
658
+ const docModule = await mod('doc')
659
+ docModule.invalidateDocCache(id)
660
+ await docModule.getDoc(id, { rebuild: true })
640
661
  record.state = 'done'
641
662
  record.finishedAt = new Date().toISOString()
642
663
  record.pages = result.pages.length
@@ -1472,16 +1493,14 @@ export function createApi({ fetchTopicFeed } = {}) {
1472
1493
  },
1473
1494
 
1474
1495
  // --- 在线检索
1475
- 'search.online': async (args) => {
1476
- const arxiv = await mod('arxiv')
1477
- const query = String((args && args.query) || '').trim()
1496
+ 'search.online': async (args, { signal } = {}) => {
1497
+ const [arxiv, config] = await Promise.all([mod('arxiv'), getConfig()])
1498
+ const query = String(args?.query || '').trim()
1478
1499
  if (!query) throw new Error('请输入关键词或 arXiv ID / DOI')
1479
- const limit = Math.min(25, Math.max(1, Number((args && args.limit) || 8)))
1480
- const source = (args && args.source) || 'both'
1481
- if (source === 'arxiv') return { items: (await arxiv.searchArxiv({ query, limit })).items, source }
1482
- if (source === 'openalex') return { items: (await arxiv.searchOpenAlex({ query, limit })).items, source }
1483
- const both = await arxiv.searchBoth({ query, limit })
1484
- return { items: both.items, ...(both.warnings ? { warnings: both.warnings } : {}), source: 'both' }
1500
+ const source = args?.source || 'both'
1501
+ const limit = Math.min(100, Math.max(1, Math.trunc(Number(args?.limit) || 100)))
1502
+ const result = await arxiv.searchOnlinePage({ query, source, limit, cursor: args?.cursor, networkConfig: config?.network, signal })
1503
+ return { ...result, source }
1485
1504
  },
1486
1505
 
1487
1506
  'search.import': async (args) => {
@@ -1526,7 +1545,7 @@ export function createApi({ fetchTopicFeed } = {}) {
1526
1545
  }
1527
1546
  },
1528
1547
 
1529
- 'search.latest': async (args) => {
1548
+ 'search.latest': async (args, { signal } = {}) => {
1530
1549
  const [arxiv, config] = await Promise.all([mod('arxiv'), getConfig()])
1531
1550
  const cfgTopics = arxiv.normalizeTopicsConfig(config && config.topics)
1532
1551
  const topicId = args && args.topicId ? String(args.topicId).trim() : ''
@@ -1547,68 +1566,23 @@ export function createApi({ fetchTopicFeed } = {}) {
1547
1566
  : {}),
1548
1567
  })
1549
1568
  : cfgTopics
1550
- const source = (args && args.source) || effectiveTopicsCfg.feedSource || 'arxiv'
1551
- const limit = Math.min(40, Math.max(1, Number((args && args.limit) || 18)))
1552
- const force = Boolean(args && args.force)
1553
- const networkConfig = config && config.network
1554
- const networkFingerprint = createHash('sha256').update(JSON.stringify(networkConfig || null)).digest('hex')
1555
- const cacheKey = JSON.stringify({
1556
- topics: effectiveTopicsCfg,
1557
- topicId,
1558
- domainId,
1559
- category,
1560
- source,
1561
- limit,
1562
- networkFingerprint,
1563
- })
1564
- const cacheFile = path.join(DATA_ROOT, '.tmp', 'feed-cache.json')
1565
- const CACHE_VERSION = 2
1566
- const CACHE_TTL_MS = 15 * 60 * 1000
1567
- // 旧缓存键可能含代理凭据,强刷也要在拉取前清理。
1568
- const cached = await fsp.readFile(cacheFile, 'utf8').then(async (text) => {
1569
- let entry
1570
- try {
1571
- entry = JSON.parse(text)
1572
- } catch {
1573
- // 旧写入中断后可能留下含明文的残缺 JSON,也要清理。
1574
- }
1575
- if (entry?.version === CACHE_VERSION) return entry
1576
- await fsp.rm(cacheFile, { force: true }).catch(() => {
1577
- throw new Error('清理旧订阅缓存失败,请检查工作台数据目录是否可写')
1578
- })
1579
- return null
1580
- }, async (error) => {
1581
- if (error.code !== 'ENOENT') {
1582
- await fsp.rm(cacheFile, { force: true }).catch(() => {
1583
- throw new Error('清理旧订阅缓存失败,请检查工作台数据目录是否可写')
1584
- })
1585
- }
1586
- return null
1569
+ const source = args?.source || effectiveTopicsCfg.feedSource || 'arxiv'
1570
+ const limit = Math.min(100, Math.max(1, Math.trunc(Number(args?.limit) || 100)))
1571
+ // 无需读取旧结果。文件可能含代理凭据,清理失败时不要继续拉取。
1572
+ await fsp.rm(path.join(DATA_ROOT, '.tmp', 'feed-cache.json'), { force: true }).catch(() => {
1573
+ throw new Error('清理旧订阅缓存失败,请检查工作台数据目录是否可写')
1587
1574
  })
1588
- if (
1589
- !force &&
1590
- cached &&
1591
- cached.key === cacheKey &&
1592
- typeof cached.savedAt === 'number' &&
1593
- Date.now() - cached.savedAt < CACHE_TTL_MS &&
1594
- cached.value &&
1595
- Array.isArray(cached.value.items) &&
1596
- cached.value.items.length > 0
1597
- ) {
1598
- return { ...cached.value, cached: true }
1599
- }
1600
- const value = await (fetchTopicFeed ?? arxiv.fetchTopicFeed)({
1575
+ const value = await (fetchTopicFeed ?? arxiv.fetchTopicFeedPage)({
1601
1576
  topicsConfig: effectiveTopicsCfg,
1602
1577
  topicId: topicId || undefined,
1603
1578
  domainId: domainId || undefined,
1604
1579
  category: category || undefined,
1605
1580
  source,
1606
1581
  limit,
1607
- networkConfig,
1582
+ cursor: args?.cursor,
1583
+ networkConfig: config?.network,
1584
+ signal,
1608
1585
  })
1609
- if (value && Array.isArray(value.items) && value.items.length > 0) {
1610
- await writeJsonAtomic(cacheFile, { version: CACHE_VERSION, key: cacheKey, savedAt: Date.now(), value }).catch(() => {})
1611
- }
1612
1586
  return { ...value, cached: false }
1613
1587
  },
1614
1588
 
@@ -2089,7 +2063,7 @@ export function createApi({ fetchTopicFeed } = {}) {
2089
2063
  })
2090
2064
  const docModule = await mod('doc')
2091
2065
  docModule.invalidateDocCache(id)
2092
- await storeModule.clearDocCache(id).catch(() => {})
2066
+ await docModule.getDoc(id, { rebuild: true })
2093
2067
  record.state = 'done'
2094
2068
  record.stage = '完成'
2095
2069
  record.finishedAt = new Date().toISOString()
@@ -2143,7 +2117,7 @@ export function createApi({ fetchTopicFeed } = {}) {
2143
2117
  // 这里必须等 doc.json 真删掉再返回:删盘是异步的,不等就会出现「刚解析完还是旧文本」。
2144
2118
  const docModule = await mod('doc')
2145
2119
  docModule.invalidateDocCache(id)
2146
- await storeModule.clearDocCache(id).catch(() => {})
2120
+ await docModule.getDoc(id, { rebuild: true })
2147
2121
  if (job) await safeJob((logger) => logger.finish(job, 'ok', { blocks: (layout.blocks || []).length }))
2148
2122
  return { layout: layoutModule.layoutSummary(layout) }
2149
2123
  } catch (error) {
@@ -2157,7 +2131,29 @@ export function createApi({ fetchTopicFeed } = {}) {
2157
2131
  const id = String((args && args.id) || '')
2158
2132
  if (!id) throw new Error('缺少 id')
2159
2133
  const [zhModule, storeModule] = await Promise.all([mod('zhpdf'), mod('store')])
2160
- return zhModule.createZhPdf({ store: storeModule }).status(id)
2134
+ const [status, manager] = await Promise.all([zhModule.createZhPdf({ store: storeModule }).status(id), getZhPdfJobs()])
2135
+ return { ...status, job: await manager.status(id) }
2136
+ },
2137
+ 'zhpdf.inspect': async (args) => {
2138
+ const id = String(args?.id || '')
2139
+ if (!id) throw new Error('缺少 id')
2140
+ const [zh, store, doc, pdf] = await Promise.all([mod('zhpdf'), mod('store'), mod('doc'), mod('pdf')])
2141
+ return zh.createZhPdf({ store, pdf }).inspect(id, (await doc.getDoc(id)).doc)
2142
+ },
2143
+ 'zhpdf.prepare': async (args) => {
2144
+ const id = String(args?.id || '')
2145
+ if (!id) throw new Error('缺少 id')
2146
+ return { job: await (await getZhPdfJobs()).prepare(id, { model: sanitizeModelChoice(args?.model) }) }
2147
+ },
2148
+ 'zhpdf.pause': async (args) => {
2149
+ const id = String(args?.id || '')
2150
+ if (!id) throw new Error('缺少 id')
2151
+ return { job: await (await getZhPdfJobs()).pause(id) }
2152
+ },
2153
+ 'zhpdf.resume': async (args) => {
2154
+ const id = String(args?.id || '')
2155
+ if (!id) throw new Error('缺少 id')
2156
+ return { job: await (await getZhPdfJobs()).resume(id) }
2161
2157
  },
2162
2158
  'zhpdf.build': async (args) => {
2163
2159
  const id = String((args && args.id) || '')
@@ -2165,6 +2161,7 @@ export function createApi({ fetchTopicFeed } = {}) {
2165
2161
  // 两个请求同时进来会各起一个 pdf_tool 写同一个 .tmp:单飞,第二次直接等结果
2166
2162
  const pending = zhpdfBuilds.get(id)
2167
2163
  if (pending) return pending
2164
+ if ((await (await getZhPdfJobs()).status(id))?.status === 'running') throw new Error('中文版生成任务正在运行,请等待完成')
2168
2165
  const task = (async () => {
2169
2166
  const [zhModule, storeModule, pdfModule, docModule] = await Promise.all([
2170
2167
  mod('zhpdf'), mod('store'), mod('pdf'), mod('doc'),
@@ -2208,7 +2205,7 @@ export function createApi({ fetchTopicFeed } = {}) {
2208
2205
  await fsp.rm(storeModule2.paperFile(id, 'layout.job.json'), { force: true }).catch(() => {})
2209
2206
  const [docModule, storeModule] = await Promise.all([mod('doc'), mod('store')])
2210
2207
  docModule.invalidateDocCache(id)
2211
- await storeModule.clearDocCache(id).catch(() => {})
2208
+ await docModule.getDoc(id, { rebuild: true })
2212
2209
  return { cleared }
2213
2210
  },
2214
2211
 
@@ -2223,7 +2220,7 @@ export function createApi({ fetchTopicFeed } = {}) {
2223
2220
  const result = await runner.refreshTables(id)
2224
2221
  const docModule = await mod('doc')
2225
2222
  docModule.invalidateDocCache(id)
2226
- await storeModule.clearDocCache(id).catch(() => {})
2223
+ await docModule.getDoc(id, { rebuild: true })
2227
2224
  return result
2228
2225
  },
2229
2226
 
@@ -2240,7 +2237,7 @@ export function createApi({ fetchTopicFeed } = {}) {
2240
2237
  if (result.changed > 0) {
2241
2238
  const docModule = await mod('doc')
2242
2239
  docModule.invalidateDocCache(id)
2243
- await storeModule.clearDocCache(id).catch(() => {})
2240
+ await docModule.getDoc(id, { rebuild: true })
2244
2241
  }
2245
2242
  return result
2246
2243
  },
@@ -2596,6 +2593,29 @@ export function createApi({ fetchTopicFeed } = {}) {
2596
2593
  return b.ask(id, text, { cwd })
2597
2594
  },
2598
2595
 
2596
+ // 历史记录使用同一串行状态队列,防止并发阅读定位把历史或会话状态覆盖。
2597
+ 'history.list': async () => ({ items: normalizeBrowseHistory((await readUiState()).browseHistory) }),
2598
+
2599
+ 'history.record': async (args) => {
2600
+ const item = normalizeHistoryItem(args?.item)
2601
+ const result = await updateUiState(previous => ({
2602
+ browseHistory: normalizeBrowseHistory([item, ...normalizeBrowseHistory(previous.browseHistory)]),
2603
+ }))
2604
+ return { item: result.state.browseHistory[0], items: result.state.browseHistory }
2605
+ },
2606
+
2607
+ 'history.remove': async (args) => {
2608
+ const id = String(args?.id || '')
2609
+ if (!id || id.length > 2100) throw new Error('缺少有效的浏览记录标识')
2610
+ const result = await updateUiState(previous => ({ browseHistory: normalizeBrowseHistory(previous.browseHistory).filter(item => item.id !== id) }))
2611
+ return { items: result.state.browseHistory }
2612
+ },
2613
+
2614
+ 'history.clear': async () => {
2615
+ await updateUiState({ browseHistory: [] })
2616
+ return { items: [] }
2617
+ },
2618
+
2599
2619
  // 界面状态(当前论文 / 页签 / 页码 / 滚动位置):存服务端,桌面端重启换了端口也不丢
2600
2620
  'ui.get': async () => ({ state: mergeUiState(await readUiState()) }),
2601
2621
 
@@ -2758,6 +2778,7 @@ export function apply(ctx) {
2758
2778
  // 宿主模型服务:可选依赖。headless 或没配模型适配器时缺席,阅读功能不受影响。
2759
2779
  ctx.inject(['llm', 'agentDefaultModel'], (rctx) => {
2760
2780
  setAiRuntime({ llm: rctx.llm, agentDefaultModel: rctx.agentDefaultModel })
2781
+ void getZhPdfJobs().catch(error => console.error('[dsh-paper-workbench] 恢复中文版任务失败:' + error.message))
2761
2782
  try {
2762
2783
  rctx.effect(() => () => setAiRuntime({ llm: null, agentDefaultModel: null }))
2763
2784
  } catch {
@@ -2791,8 +2812,8 @@ export function apply(ctx) {
2791
2812
  // Serial agent/created runs before the first turn for startup/resume/clear/compact.
2792
2813
  // Inject ['agents'] only and resolve agentPresets optionally so DSH versions with or without agentPresets work.
2793
2814
  ctx.inject(['agents'], rctx => {
2794
- let presets = rctx.agentPresets || null
2795
- if (!presets && typeof rctx.get === 'function') {
2815
+ let presets = null
2816
+ if (typeof rctx.get === 'function') {
2796
2817
  try {
2797
2818
  presets = rctx.get('agentPresets') || null
2798
2819
  } catch {
package/lib/layout-ir.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /** Pure, offline layout IR. Never import layout.js: it owns the integration boundary. */
2
2
  import { createHash } from 'node:crypto'
3
3
 
4
- const BUILD = 'ir-3'
4
+ const BUILD = 'ir-4'
5
5
  const kinds = { text: 'body', abstract: 'body', content: 'body', paragraph_title: 'heading', doc_title: 'heading', figure_title: 'caption', table_title: 'caption', footnote: 'footnote', formula: 'formula', formula_number: 'formula_number', image: 'figure', chart: 'figure', table: 'table', list: 'list', algorithm: 'algorithm', reference: 'body', aside_text: 'body' }
6
6
  const decorations = new Set(['header', 'footer', 'number', 'page_number'])
7
7
  const list = value => Array.isArray(value) ? value : []
@@ -61,6 +61,70 @@ function garbled(value) {
61
61
  return /[\uFFFD\u0000-\u0008\uE000-\uF8FF]/u.test(s) || (words.length >= 6 && words.filter(w => /^[a-z]$/i.test(w)).length / words.length > 0.6)
62
62
  }
63
63
 
64
+ /** 只在目录上下文/点引导线和多条页码共同佐证时识别;正文数字不构成目录。 */
65
+ export function tocEntryInfo(value) {
66
+ const s = text(value)
67
+ const target = /(?:\s|[..…·])+(\d{1,4})\s*$/.exec(s)
68
+ if (!target) return null
69
+ const title = s.slice(0, target.index).replace(/[\s..…·]+$/g, '')
70
+ if (!/[\p{L}]/u.test(title)) return null
71
+ const number = /^(\d+(?:\.\d+)*|[A-Z](?:\.\d+)+|[A-Z](?=[.、]?\s|\p{Script=Han}))[.、]?\s*/u.exec(title)
72
+ return { tocLevel: number ? number[1].split('.').length : 1, tocTargetPage: Number(target[1]), numbered: Boolean(number), leader: /(?:[..·]\s*){2,}|…/u.test(s) }
73
+ }
74
+
75
+ export function structureTocRows(rows, context = false) {
76
+ const values = rows.filter(r => text(r.text))
77
+ const parsed = values.map(r => tocEntryInfo(r.text))
78
+ const hits = parsed.filter(Boolean)
79
+ if (hits.length < 3 || hits.length < values.length * 0.6 ||
80
+ !(context || hits.filter(p => p.leader).length >= 2) || hits.filter(p => p.numbered || p.leader).length < 3) return null
81
+ return values.map((row, i) => ({ ...row, ...(parsed[i] ? { tocLevel: parsed[i].tocLevel, tocTargetPage: parsed[i].tocTargetPage } : { tocLevel: 1 }) }))
82
+ }
83
+
84
+ function geometricRows(lines) {
85
+ const rows = []
86
+ for (const line of [...lines].sort((a, b) => a.bbox.y - b.bbox.y || a.bbox.x - b.bbox.x)) {
87
+ const box = line.bbox
88
+ const prev = rows.at(-1)
89
+ const overlap = prev ? Math.min(prev.bbox.y + prev.bbox.height, box.y + box.height) - Math.max(prev.bbox.y, box.y) : 0
90
+ if (prev && overlap >= Math.min(prev.bbox.height, box.height) * 0.45 && box.x >= prev.bbox.x + prev.bbox.width - 3) {
91
+ prev.text = joinLines([prev.text, line.text])
92
+ prev.bbox = union(prev.bbox, box)
93
+ prev.lineIds.push(line.lineId)
94
+ } else rows.push({ text: text(line.text), bbox: { ...box }, lineIds: [line.lineId] })
95
+ }
96
+ return rows
97
+ }
98
+
99
+ function tocRowsForBlock(block, lines, context) {
100
+ if (!['body', 'list', 'heading'].includes(block.kind)) return null
101
+ const rows = geometricRows(lines)
102
+ const geometric = structureTocRows(rows, context || block.label === 'content')
103
+ for (const candidate of block.candidates) {
104
+ const modelRows = String(candidate.text).split(/\r?\n/).filter(s => s.trim()).map(s => ({ text: text(s), bbox: { ...block.bbox }, lineIds: [] }))
105
+ const structured = structureTocRows(modelRows, context || block.label === 'content')
106
+ if (!structured) continue
107
+ if (geometric) {
108
+ // PDF 漏了整条而服务候选完整时,逐行严格对齐;已存在的 PDF 字符仍全部保留。
109
+ const key = value => value.replace(/\s/g, '')
110
+ let cursor = 0
111
+ const aligned = structured.map(row => {
112
+ const pdf = rows[cursor]
113
+ if (pdf && key(pdf.text) === key(row.text)) { cursor += 1; return { ...row, ...pdf, source: 'pdf' } }
114
+ return { ...row, source: candidate.source }
115
+ })
116
+ if (cursor === rows.length && structured.length > rows.length) return aligned
117
+ continue
118
+ }
119
+ // 单个 PDF 行失去几何分隔时,只有逐字守恒才允许借用服务换行。
120
+ const pdfText = joinLines(rows.map(r => r.text))
121
+ if (rows.length && pdfText.replace(/\s/g, '') !== structured.map(r => r.text).join('').replace(/\s/g, '')) continue
122
+ if (rows.length) structured[0].lineIds = rows.flatMap(r => r.lineIds)
123
+ return structured
124
+ }
125
+ return geometric
126
+ }
127
+
64
128
  function choose(block) {
65
129
  const nonempty = block.candidates.filter(c => c.text)
66
130
  // 图注的正文价值是「模型认出的图题/表题」;PDF 文本层常把图内标签一起抠进来。
@@ -388,8 +452,12 @@ function assignLines(page, blocks, pdf, sha256) {
388
452
  const role = isVisual(owner) ? owner.kind + '-internal' : 'text'
389
453
  page.lineAssignments.push({ lineId: line.lineId, blockId: owner.blockId, role, text: text(line.text), bbox: { ...line.bbox }, candidates: ranked.map(c => ({ blockId: c.block.blockId, geometry: c.overlap, agreement: c.agreement, score: c.score })) })
390
454
  }
455
+ const tocContext = blocks.some(b => b.candidates.some(c => /^(?:contents|table of contents|目\s*录)\s*$/i.test(text(c.text))))
456
+ const tocBlocks = new Map()
391
457
  for (const block of blocks) {
392
458
  const lines = owned.get(block).sort((a, b) => a.y - b.y || a.x - b.x)
459
+ const tocRows = tocRowsForBlock(block, lines, tocContext)
460
+ if (tocRows) tocBlocks.set(block, tocRows)
393
461
  block.fragments[0].lineIds = lines.map(l => l.lineId)
394
462
  if (lines.length) {
395
463
  const pdfJoined = block.kind === 'algorithm' ? formatAlgorithmLines(lines) : joinLines(lines.map(l => l.text))
@@ -411,6 +479,33 @@ function assignLines(page, blocks, pdf, sha256) {
411
479
  }
412
480
  if (block.kind === 'figure') block.text = ''
413
481
  }
482
+ // 目录条目是原生块:每条有稳定身份,PDF 行仍恰好归属一次;保留原候选以便审计。
483
+ const entries = blocks.flatMap(block => {
484
+ const rows = tocBlocks.get(block)
485
+ if (!rows) return [block]
486
+ return rows.map((row, index) => {
487
+ const entry = { ...block, kind: 'list', role: 'toc-entry', tocLevel: row.tocLevel,
488
+ ...(row.tocTargetPage !== undefined ? { tocTargetPage: row.tocTargetPage } : {}),
489
+ parentBlockId: block.blockId, blockId: 'b-' + hash([block.blockId, 'toc-entry', index]).slice(0, 24),
490
+ sourceOrder: (block.sourceOrder ?? block.bbox.y) + index / (rows.length + 1), bbox: { ...row.bbox },
491
+ text: row.text, sourceHash: hash(text(row.text)), selectedSource: row.source || (owned.get(block).length ? 'pdf' : block.selectedSource),
492
+ selectionReason: row.source && row.source !== 'pdf' ? 'toc-model-line-without-pdf' : owned.get(block).length ? 'toc-pdf-lines-preserved' : 'toc-model-lines-preserved',
493
+ fragments: [{ page: page.n, bbox: { ...row.bbox }, lineIds: row.lineIds }],
494
+ quality: quality(block.quality.issues.map(i => ({ ...i }))) }
495
+ if (row.source && row.source !== 'pdf') {
496
+ entry.geometryTrusted = false
497
+ issue(entry, 'unverified-model-text')
498
+ }
499
+ entry.quality.issues.forEach(i => { i.blockId = entry.blockId })
500
+ for (const assignment of page.lineAssignments.filter(a => row.lineIds.includes(a.lineId))) {
501
+ assignment.sourceBlockId = block.blockId
502
+ assignment.blockId = entry.blockId
503
+ assignment.role = 'toc-entry'
504
+ }
505
+ return entry
506
+ })
507
+ })
508
+ blocks.splice(0, blocks.length, ...entries)
414
509
  return lines.length
415
510
  }
416
511
 
package/lib/layout.js CHANGED
@@ -24,7 +24,7 @@ export const LAYOUT_FILE = 'layout.json'
24
24
  // 断点:每批完成就落盘,进程被杀/客户端断开后可以接着跑(不重新上传已完成的页)
25
25
  export const LAYOUT_PARTIAL = 'layout.partial.json'
26
26
  /** 从 layout.json 构建文档模型/配图清单的算法版本:清理规则一改就加一,旧 doc.json 自动失效重算。 */
27
- export const LAYOUT_BUILD = 'ir-3'
27
+ export const LAYOUT_BUILD = 'ir-4'
28
28
  // 后台任务状态:面板轮询它显示进度,重启后据此判断「上次跑到哪、要不要续」
29
29
  export const LAYOUT_JOB = 'layout.job.json'
30
30
  export const LAYOUT_MODEL = 'PP-StructureV3'
@@ -1,4 +1,5 @@
1
1
  /** Native paper-chat scope. Storage and Host services are injected; no model calls. */
2
+ import { normalizeBrowseHistory } from './history.js'
2
3
  const object = value => value && typeof value === 'object' && !Array.isArray(value)
3
4
  const optionalText = (value, maxLen = 200) => {
4
5
  if (typeof value !== 'string') return null
@@ -32,6 +33,8 @@ export function mergeUiState(previous, patch = {}) {
32
33
  const base = object(previous) ? previous : {}
33
34
  const next = { ...base, version: 2 }
34
35
  const update = object(patch) ? patch : {}
36
+ next.browseHistory = normalizeBrowseHistory(Object.hasOwn(update, 'browseHistory') ? update.browseHistory : base.browseHistory)
37
+ if (typeof update.onlineNavCollapsed === 'boolean') next.onlineNavCollapsed = update.onlineNavCollapsed
35
38
  for (const key of ['paperId', 'tab', 'page', 'scrollTop', 'sectionId', 'layout', 'expanded']) {
36
39
  if (Object.hasOwn(update, key)) next[key] = update[key]
37
40
  }
package/lib/pdf.js CHANGED
@@ -40,7 +40,7 @@ let pythonCache = null // { at, value }
40
40
  let pythonInflight = null
41
41
 
42
42
 
43
- function run(command, args, { input = '', timeoutMs = 60000, maxBytes = 96 * 1024 * 1024 } = {}) {
43
+ function run(command, args, { input = '', timeoutMs = 60000, maxBytes = 96 * 1024 * 1024, signal } = {}) {
44
44
  return new Promise((resolve) => {
45
45
  const child = spawn(command, args, {
46
46
  windowsHide: true,
@@ -54,8 +54,13 @@ function run(command, args, { input = '', timeoutMs = 60000, maxBytes = 96 * 102
54
54
  if (done) return
55
55
  done = true
56
56
  clearTimeout(timer)
57
+ signal?.removeEventListener('abort', onAbort)
57
58
  resolve(result)
58
59
  }
60
+ const onAbort = () => {
61
+ child.kill()
62
+ finish({ code: -4, stdout: '', stderr: '已暂停 PDF 处理' })
63
+ }
59
64
  const timer = setTimeout(() => {
60
65
  try {
61
66
  child.kill()
@@ -82,6 +87,9 @@ function run(command, args, { input = '', timeoutMs = 60000, maxBytes = 96 * 102
82
87
  child.on('error', (error) => finish({ code: -3, stdout: '', stderr: error.message }))
83
88
  child.on('close', (code) => finish({ code, stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8') }))
84
89
 
90
+ if (signal?.aborted) onAbort()
91
+ else signal?.addEventListener('abort', onAbort, { once: true })
92
+
85
93
  if (input) child.stdin.end(input)
86
94
  else child.stdin.end()
87
95
  })
@@ -130,6 +138,7 @@ export function resetPython() {
130
138
 
131
139
  /** 调一次 Python 工具;返回解析后的 JSON,失败抛中文错误。 */
132
140
  export async function callTool(command, payload, options = {}) {
141
+ options.signal?.throwIfAborted()
133
142
  const found = await findPython()
134
143
  if (!found) {
135
144
  throw new Error(
@@ -140,7 +149,9 @@ export async function callTool(command, payload, options = {}) {
140
149
  input: JSON.stringify(payload || {}),
141
150
  timeoutMs: options.timeoutMs || 60000,
142
151
  maxBytes: options.maxBytes || 96 * 1024 * 1024,
152
+ signal: options.signal,
143
153
  })
154
+ options.signal?.throwIfAborted()
144
155
  const text = String(result.stdout || '').trim()
145
156
  let parsed = null
146
157
  if (text) {
package/lib/server.js CHANGED
@@ -401,8 +401,23 @@ export function createHandler({ api, appDir, prefix, streams }) {
401
401
  }
402
402
  const limit = method === 'conv.attach' ? ATTACH_BODY_LIMIT : JSON_BODY_LIMIT
403
403
  const args = await readJsonBody(req, limit)
404
- const value = await fn(args || {})
405
- json(res, 200, { ok: true, value })
404
+ if (method !== 'search.online' && method !== 'search.latest') {
405
+ const value = await fn(args || {})
406
+ json(res, 200, { ok: true, value })
407
+ return
408
+ }
409
+ const controller = new AbortController()
410
+ const onClose = () => { if (!res.writableEnded) controller.abort() }
411
+ res.once('close', onClose)
412
+ try {
413
+ if (res.destroyed) return
414
+ const value = await fn(args || {}, { signal: controller.signal })
415
+ if (!controller.signal.aborted) json(res, 200, { ok: true, value })
416
+ } catch (error) {
417
+ if (!controller.signal.aborted) throw error
418
+ } finally {
419
+ res.off('close', onClose)
420
+ }
406
421
  } catch (error) {
407
422
  const message = error && error.message ? error.message : String(error)
408
423
  console.error('[paper-workbench] 请求失败:' + message)
@@ -204,6 +204,7 @@ export function createTranslateJobManager({ ai, store, dbBackendOrDb, jobs, broa
204
204
  ...(job.sectionIds ? { sectionIds: job.sectionIds.slice() } : {}),
205
205
  ...(job.keys ? { keys: job.keys.slice() } : {}),
206
206
  ...(job.titles ? { titles: true } : {}),
207
+ ...(job.purpose ? { purpose: job.purpose } : {}),
207
208
  target: job.target,
208
209
  model: job.model,
209
210
  status: job.status,
@@ -295,6 +296,7 @@ export function createTranslateJobManager({ ai, store, dbBackendOrDb, jobs, broa
295
296
  sectionIds,
296
297
  keys,
297
298
  titles: Boolean(raw.titles),
299
+ purpose: raw.purpose === 'zhpdf' ? 'zhpdf' : '',
298
300
  retranslate: Boolean(raw.retranslate),
299
301
  target: String(raw.target || 'zh'),
300
302
  model: String(raw.model || ''),
@@ -771,6 +773,7 @@ export function createTranslateJobManager({ ai, store, dbBackendOrDb, jobs, broa
771
773
  sectionIds,
772
774
  keys,
773
775
  titles: Boolean(params.titles) || Boolean(sectionIds && sectionIds.includes('*titles')),
776
+ purpose: params.purpose,
774
777
  retranslate: params.retranslate === true,
775
778
  target: params.target || 'zh',
776
779
  requestedModel: params.model !== undefined ? params.model : null,