dsh-bilingual-reader 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -8,7 +8,7 @@
8
8
  [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
9
9
  [![node](https://img.shields.io/badge/node-%3E%3D22.12-2f6f4f)](package.json)
10
10
 
11
- ![Bilingual reader: original on the left, translation on the right, code blocks intact, glossary and cache](docs/demo.jpg)
11
+ ![Bilingual reader: translation directly under each paragraph, code blocks intact, glossary and cache](docs/demo.jpg)
12
12
 
13
13
  ## Why
14
14
 
@@ -17,6 +17,7 @@ DSH already has 297 translation-related plugins, but most cover a single entry p
17
17
  This plugin replicates the core experience of Immersive Translate and Read Frog, but in a DSH-native way:
18
18
 
19
19
  - **Bilingual next to the original** — every paragraph keeps its translation underneath; no separate translation window.
20
+ - **Read while it translates** — finished paragraphs appear in place, and progress updates replace only the blocks that changed, so your scroll position stays put.
20
21
  - **Structure preserved** — code blocks, inline code, LaTeX, link URLs, tables and heading levels are protected; dropped tokens are detected and retried.
21
22
  - **Token-efficient** — blocks are batched into one request; translations are cached by `original + target language + glossary hash`.
22
23
  - **Reusable** — a glossary enforces consistent terms; bilingual Markdown exports; agents read and write the same data.
@@ -26,7 +27,7 @@ This plugin replicates the core experience of Immersive Translate and Read Frog,
26
27
 
27
28
  Requires **DSH >= 0.2.0 < 0.3.0** and **Node.js >= 22.12**.
28
29
 
29
- From npm (after publishing):
30
+ From npm:
30
31
 
31
32
  ```sh
32
33
  dsh plugin --profile web add dsh-bilingual-reader
@@ -52,8 +53,9 @@ Restart DSH and open **Bilingual Reader** in the sidebar. The plugin uses the **
52
53
 
53
54
  Paste a public article URL, choose the target language (Simplified Chinese, Traditional Chinese, English, Japanese, Korean) and click **Read and translate**.
54
55
 
56
+ - **Inline** (default) — the translation sits directly under each paragraph, best for narrow windows and immersive reading.
55
57
  - **Bilingual** — original on the left, translation on the right.
56
- - **Original** / **Translation** — single-column reading.
58
+ - **Original** / **Translation** — single-column reading; the view choice is remembered.
57
59
  - **Glossary** — add terms such as `token → 令牌`; translations must use them.
58
60
  - **Export bilingual Markdown** — headings, lists, tables and code blocks are kept.
59
61
  - **Retry failed blocks** — completed blocks are not translated again.
@@ -82,9 +84,9 @@ The command returns a document id immediately; translation continues in the back
82
84
  2. Readability extracts the article; Turndown converts it to Markdown.
83
85
  3. `segmentMarkdown` splits it into blocks: headings, paragraphs, lists, tables and quotes are translatable; code fences, rules and image-only blocks are skipped.
84
86
  4. `protectInline` replaces inline code, LaTeX, link URLs, bare URLs and HTML tags with `⟦n⟧` tokens.
85
- 5. Up to 6 blocks / 3500 characters are sent per request; the model must return an ordered JSON array. A failed batch falls back to single-block requests.
87
+ 5. Up to 6 blocks / 3500 characters are sent per request; the model must return an ordered JSON array. A failed batch falls back to single-block requests, and 2 batches run at a time by default.
86
88
  6. Tokens are restored, heading prefixes are repaired, and translations are written to the cache by content hash.
87
- 7. Documents live under `~/.dsh-bilingual-reader/docs/<id>/`; the UI renders the bilingual view and exports bilingual Markdown.
89
+ 7. Documents live under `~/.dsh-bilingual-reader/docs/<id>/`; the UI defaults to inline bilingual view and exports bilingual Markdown.
88
90
 
89
91
  ## Configuration
90
92
 
@@ -94,6 +96,7 @@ The command returns a document id immediately; translation continues in the back
94
96
  | `DSH_BILINGUAL_TARGET_LANG` | `zh-CN` | Default target language |
95
97
  | `DSH_BILINGUAL_BATCH_BLOCKS` | `6` | Max blocks per request |
96
98
  | `DSH_BILINGUAL_BATCH_CHARS` | `3500` | Max characters per request |
99
+ | `DSH_BILINGUAL_CONCURRENCY` | `2` | Concurrent translation batches (1–4) |
97
100
  | `DSH_BILINGUAL_MAX_BLOCKS` | `400` | Max blocks per document |
98
101
  | `DSH_BILINGUAL_MAX_BYTES` | `5242880` | Page size cap |
99
102
  | `DSH_BILINGUAL_TIMEOUT_MS` | `20000` | Fetch timeout |
@@ -120,7 +123,7 @@ The command returns a document id immediately; translation continues in the back
120
123
 
121
124
  ```sh
122
125
  npm install
123
- npm test # 34 tests: segmentation, protection, prompts, cache, glossary, security, store/translator
126
+ npm test # 36 tests: segmentation, protection, prompts, cache, glossary, security, store/translator
124
127
  npm run verify # local HTTP fixture → fetch → translate → export → cache
125
128
  npm run dev # local UI with a demo model: http://127.0.0.1:4183/dsh-bilingual-reader/
126
129
  ```
@@ -133,6 +136,11 @@ Architecture and data layout: [docs/architecture.md](docs/architecture.md).
133
136
 
134
137
  Product shape inspired by [Immersive Translate](https://github.com/immersive-translate/immersive-translate), [Read Frog](https://github.com/tomode1/read-frog), [NextAI Translator](https://github.com/nextai-translator/nextai-translator) and [Saladict](https://github.com/crimx/ext-saladict). The implementation is independent; no affiliation.
135
138
 
139
+ ## Release notes
140
+
141
+ - [v0.1.1](docs/release-v0.1.1.md): inline bilingual view by default, incremental progress rendering, parallel batches, cache and write consistency fixes.
142
+ - [v0.1.0](docs/release-v0.1.0.md): first release — web/document bilingual reading, glossary, cache, export and agent tools.
143
+
136
144
  ## License
137
145
 
138
146
  MIT
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
  [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
9
9
  [![node](https://img.shields.io/badge/node-%3E%3D22.12-2f6f4f)](package.json)
10
10
 
11
- ![双语阅读界面:左原文、右译文,代码块保持原样,术语表与缓存](docs/demo.jpg)
11
+ ![双语阅读界面:上下对照,译文在每段原文下方,代码块保持原样,术语表与缓存](docs/demo.jpg)
12
12
 
13
13
  ## 为什么做这个
14
14
 
@@ -17,6 +17,7 @@ DSH 里已经有 297 个和翻译相关的插件,但大多只覆盖一个入
17
17
  这个插件复刻的是 Immersive Translate / 陪读蛙最核心的体验,但按 DSH 的方式做:
18
18
 
19
19
  - **双语贴着原文**:每段原文下方就是译文,不跳转到另一个翻译窗口。
20
+ - **边译边读**:完成的段落立即出现,进度更新只替换变化的段落,不会重置滚动位置。
20
21
  - **保结构**:代码块、行内代码、公式、链接 URL、表格、标题层级不翻译;模型丢失保护片段会被检测并重试。
21
22
  - **省 token**:多段合并成一次请求;按“原文 + 目标语言 + 术语表哈希”缓存,重复段落不再调用模型。
22
23
  - **可沉淀**:术语表强制统一译法;双语 Markdown 可导出;Agent 可以读写同一份数据。
@@ -26,7 +27,7 @@ DSH 里已经有 297 个和翻译相关的插件,但大多只覆盖一个入
26
27
 
27
28
  要求 **DSH >= 0.2.0 < 0.3.0**、**Node.js >= 22.12**。
28
29
 
29
- 从 npm 安装(发布后):
30
+ 从 npm 安装:
30
31
 
31
32
  ```sh
32
33
  dsh plugin --profile web add dsh-bilingual-reader
@@ -52,8 +53,9 @@ dsh plugin --profile web add file:C:/path/to/dsh-bilingual-reader
52
53
 
53
54
  粘贴公开网页链接,选择目标语言(简体中文 / 繁體中文 / English / 日本語 / 한국어),点击“读取并翻译”。
54
55
 
56
+ - **上下**(默认):原文在上,译文紧随其下,适合窄窗口和沉浸阅读。
55
57
  - **对照**:左原文、右译文。
56
- - **原文** / **译文**:单栏阅读。
58
+ - **原文** / **译文**:单栏阅读;视图选择会记住。
57
59
  - **术语表**:添加 `token → 令牌` 这类术语,翻译时强制使用。
58
60
  - **导出双语 Markdown**:保留标题、列表、表格和代码块。
59
61
  - 失败的段落可以“重试失败段”,不会重跑已完成的段落。
@@ -82,9 +84,9 @@ dsh plugin --profile web add file:C:/path/to/dsh-bilingual-reader
82
84
  2. Readability 抽取正文,Turndown 转成 Markdown。
83
85
  3. `segmentMarkdown` 按块切分:标题、段落、列表、表格、引用可翻译;代码块、分隔线、纯图片跳过。
84
86
  4. `protectInline` 把行内代码、LaTeX、链接 URL、裸 URL、HTML 标签替换成 `⟦n⟧` 占位符。
85
- 5. 默认每 6 段 / 3500 字符合并成一次模型请求,要求返回同序 JSON 数组;失败拆成单段重试。
87
+ 5. 默认每 6 段 / 3500 字符合并成一次模型请求,要求返回同序 JSON 数组;失败拆成单段重试。默认同时跑 2 个批次。
86
88
  6. 译文恢复占位符;标题补回 `#` 前缀;按内容哈希写入缓存。
87
- 7. 文档写入 `~/.dsh-bilingual-reader/docs/<id>/`,前端渲染对照视图,导出时生成双语 Markdown。
89
+ 7. 文档写入 `~/.dsh-bilingual-reader/docs/<id>/`,前端默认以“上下对照”逐段呈现,导出时生成双语 Markdown。
88
90
 
89
91
  ## 配置
90
92
 
@@ -94,6 +96,7 @@ dsh plugin --profile web add file:C:/path/to/dsh-bilingual-reader
94
96
  | `DSH_BILINGUAL_TARGET_LANG` | `zh-CN` | 默认目标语言 |
95
97
  | `DSH_BILINGUAL_BATCH_BLOCKS` | `6` | 每次请求最多段落数 |
96
98
  | `DSH_BILINGUAL_BATCH_CHARS` | `3500` | 每次请求最多字符数 |
99
+ | `DSH_BILINGUAL_CONCURRENCY` | `2` | 同时翻译的批次数(1–4) |
97
100
  | `DSH_BILINGUAL_MAX_BLOCKS` | `400` | 单篇最多段落数 |
98
101
  | `DSH_BILINGUAL_MAX_BYTES` | `5242880` | 页面大小上限 |
99
102
  | `DSH_BILINGUAL_TIMEOUT_MS` | `20000` | 抓取超时 |
@@ -120,7 +123,7 @@ dsh plugin --profile web add file:C:/path/to/dsh-bilingual-reader
120
123
 
121
124
  ```sh
122
125
  npm install
123
- npm test # 34 项单测:切分、保护、提示词、缓存、术语表、安全、store/translator
126
+ npm test # 36 项单测:切分、保护、提示词、缓存、术语表、安全、store/translator
124
127
  npm run verify # 本地 HTTP fixture → 抓取 → 翻译 → 导出 → 缓存
125
128
  npm run dev # 带示范模型的本地 UI:http://127.0.0.1:4183/dsh-bilingual-reader/
126
129
  ```
@@ -133,6 +136,11 @@ npm run dev # 带示范模型的本地 UI:http://127.0.0.1:4183/dsh-bili
133
136
 
134
137
  产品形态参考 [Immersive Translate](https://github.com/immersive-translate/immersive-translate)、[陪读蛙 Read Frog](https://github.com/tomode1/read-frog)、[NextAI Translator](https://github.com/nextai-translator/nextai-translator) 和 [Saladict](https://github.com/crimx/ext-saladict);代码为独立实现,与这些项目没有隶属关系。
135
138
 
139
+ ## 版本说明
140
+
141
+ - [v0.1.1](docs/release-v0.1.1.md):默认“上下对照”视图,逐段渐进更新,批量并行翻译,缓存与并发写入修正。
142
+ - [v0.1.0](docs/release-v0.1.0.md):首个版本,网页/文档双语阅读、术语表、缓存、导出与 Agent 工具。
143
+
136
144
  ## License
137
145
 
138
146
  MIT
@@ -11,11 +11,11 @@ URL ──fetchHtml──> HTML ──Readability + Turndown──> Markdown
11
11
  │
12
12
  ┌───────────────┬─────────────┴─────────────┐
13
13
  │ │ │
14
- cache 命中 批量翻译(默认 6 段 / 3500 字符) 单段重试
14
+ cache 命中 批量翻译(默认 6 段 / 3500 字符,2 批并行) 单段重试
15
15
  │ │ │
16
16
  └───────────────┴─────────────┬─────────────┘
17
17
  │
18
- doc.json + bilingual.md
18
+ doc.json(导出时生成 bilingual.md)
19
19
  ```
20
20
 
21
21
  ## 模块
@@ -29,7 +29,7 @@ URL ──fetchHtml──> HTML ──Readability + Turndown──> Markdown
29
29
  | `src/segment.js` | Markdown 块切分;代码块 / 分隔线 / 纯图片不翻译 |
30
30
  | `src/protect.js` | 行内代码、LaTeX、链接 URL、裸 URL、HTML 标签的占位保护与恢复 |
31
31
  | `src/prompt.js` | 批次切分、术语筛选、提示词、容错 JSON 解析 |
32
- | `src/translator.js` | 缓存优先、批量请求、单段回退、标题前缀修复、进度统计 |
32
+ | `src/translator.js` | 缓存优先、批量请求(默认 2 批并行)、单段回退、标题前缀修复、进度统计 |
33
33
  | `src/store.js` | 文档目录、任务状态、恢复中断、导出、术语表与缓存实例 |
34
34
  | `src/routes.js` | 回环限定的 HTTP API 与静态页面 |
35
35
  | `src/client.js` | DSH 侧栏入口 + iframe 主面板 |
@@ -50,7 +50,7 @@ URL ──fetchHtml──> HTML ──Readability + Turndown──> Markdown
50
50
  - 翻译任务在内存中运行;进程重启后 `recover()` 把 `running` 标记为 `interrupted`,用户可以重试。
51
51
  - 一个批次失败会拆成单段重试;单段仍失败只标记该段,不影响其他段落。
52
52
  - 模型丢失保护 token 时先重试单段;仍丢失则保留译文并给该段加 `warning`,不会静默删掉链接或代码。
53
- - 所有写文件使用临时文件 + rename,避免半截 JSON。
53
+ - 所有写文件使用唯一临时文件 + rename,避免半截 JSON;同一 store 的文档写入串行化,并行批次不会用旧快照覆盖新快照。
54
54
 
55
55
  ## 安全边界
56
56
 
package/docs/demo.jpg CHANGED
Binary file
@@ -0,0 +1,47 @@
1
+ # dsh-bilingual-reader v0.1.0 / 首个版本
2
+
3
+ 面向 DeepSeek Harness 的双语阅读工作台:把网页或 Markdown 文档读成“原文 + 译文”的结构化双语页面,代码、公式、链接和表格保持原样。
4
+
5
+ A bilingual reading workbench for DeepSeek Harness: read web articles or Markdown documents with the translation beside each block while code, formulas, links and tables stay intact.
6
+
7
+ - GitHub: <https://github.com/bit0620/dsh-bilingual-reader>
8
+ - npm: <https://www.npmjs.com/package/dsh-bilingual-reader>
9
+ - License: MIT
10
+
11
+ ## 亮点 / Highlights
12
+
13
+ - **网页双语**:URL → Readability 正文 → 段落翻译 → 对照 / 原文 / 译文三种视图。
14
+ - **保结构**:代码块不翻译;行内代码、LaTeX、链接 URL、HTML 标签用占位符保护,丢失会重试。
15
+ - **省 token**:默认 6 段 / 3500 字符合并请求;按“原文 + 目标语言 + 术语表哈希”缓存。
16
+ - **术语表**:本地 `glossary.json`,翻译时强制统一译法,Agent 可增删查。
17
+ - **双语导出**:保留标题层级、列表、表格和代码块。
18
+ - **Agent 工具**:`bilingual_read_url`、`bilingual_translate`、`bilingual_status`、`bilingual_glossary`。
19
+ - **本地优先**:数据在 `~/.dsh-bilingual-reader/`,无遥测,无独立 API key,使用 DSH 默认模型。
20
+
21
+ ## 安装 / Install
22
+
23
+ ```sh
24
+ dsh plugin --profile web add dsh-bilingual-reader
25
+ ```
26
+
27
+ 或从 GitHub:
28
+
29
+ ```sh
30
+ dsh plugin --profile web add github:Bit0620/dsh-bilingual-reader
31
+ ```
32
+
33
+ 重启 DSH,从侧栏打开“双语阅读”。
34
+
35
+ ## 验证 / Verification
36
+
37
+ - 34 项单测:切分、保护、提示词解析、缓存、术语表、SSRF、正文抽取、store/translator 集成。
38
+ - `npm run verify`:本地 HTTP fixture → 抓取 → 翻译 → 导出 → 缓存,端到端通过。
39
+ - GitHub Actions Node 22/24 矩阵、`npm pack --dry-run` 全部通过。
40
+ - 独立 `DSH_HOME` + `dsh plugin add` 安装后,`--dump-config` 能组合出插件条目。
41
+
42
+ ## 限制 / Limitations
43
+
44
+ - 只支持公开页面;登录墙、SPA、反爬页可能提取失败。
45
+ - 第一版不做 PDF / EPUB / DOCX 版面翻译、浏览器扩展、对话回复翻译。
46
+ - 翻译质量取决于 DSH 默认模型;批量解析失败会降级到单段。
47
+ - 缓存按段落跨文档共享;修改术语表会产生新的缓存键。
@@ -0,0 +1,31 @@
1
+ # dsh-bilingual-reader v0.1.1 / 阅读体验与翻译速度
2
+
3
+ v0.1.1 把默认阅读方式改成“上下对照”:译文紧跟在每一段原文下面,和 README 里承诺的沉浸式阅读一致;同时让翻译并行运行、进度逐段呈现。
4
+
5
+ v0.1.1 makes inline bilingual reading the default — the translation sits directly under each paragraph — and speeds up translation with bounded concurrency and incremental progress rendering.
6
+
7
+ - GitHub: <https://github.com/bit0620/dsh-bilingual-reader>
8
+ - npm: <https://www.npmjs.com/package/dsh-bilingual-reader>
9
+ - 版本:`0.1.1`
10
+ - 升级:`dsh plugin --profile web add dsh-bilingual-reader` 或重新安装 GitHub 源
11
+
12
+ ## 变化 / Changes
13
+
14
+ - **上下对照成为默认视图**:原文在上、译文紧随其下;新增“上下 / 对照 / 原文 / 译文”四个视图,选择会记在浏览器里。
15
+ - **边译边读**:轮询只替换发生变化的那几个段落,不再整页重绘;滚动位置和文本选择不会被打断。
16
+ - **并行翻译**:默认同时跑 2 个批次(`DSH_BILINGUAL_CONCURRENCY` 可调,范围 1–4),长文完成得更快;进度仍按批次保存。
17
+ - **缓存一致性**:一轮翻译固定使用开始时的术语表哈希,运行中修改术语表不会把结果写到错误的缓存键;保护片段重试成功后会清掉旧警告。
18
+ - **并发写入更稳**:文档写入串行化,临时文件名加入随机后缀,避免并行批次在 Windows 上互相覆盖。
19
+
20
+ ## 验证 / Verification
21
+
22
+ - 36 项单测:新增批量并发上限、运行中术语表哈希一致性两项;原有切分、保护、提示词、缓存、术语表、SSRF、抽取、store/translator 测试全部通过。
23
+ - `npm run verify`:本地 HTTP fixture → 抓取 → 翻译 → 导出 → 缓存,端到端通过。
24
+ - 本地演示 UI:默认 `上下` 视图;翻译过程中检查了 DOM 节点,未变化的代码块保持同一个节点,只有译文段落被替换。
25
+ - GitHub Actions Node 22/24 矩阵与 `npm pack --dry-run` 通过。
26
+
27
+ ## 兼容性 / Compatibility
28
+
29
+ - 环境变量新增 `DSH_BILINGUAL_CONCURRENCY`(默认 `2`)。
30
+ - 文档格式和缓存格式不变;0.1.0 的文档可以直接打开。
31
+ - 仅支持 DSH `>=0.2.0 <0.3.0`、Node.js `>=22.12`。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-bilingual-reader",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "面向 DeepSeek Harness 的双语阅读工作台:网页/文档 → 结构保留的双语对照,术语表与翻译缓存。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -41,7 +41,7 @@
41
41
  "verify": "node scripts/verify.mjs",
42
42
  "dev": "node scripts/dev-server.mjs",
43
43
  "build:client": "node scripts/build-client.mjs",
44
- "prepare": "node scripts/build-client.mjs"
44
+ "prepack": "node scripts/build-client.mjs"
45
45
  },
46
46
  "dependencies": {
47
47
  "@mozilla/readability": "^0.6.0",
package/src/config.js CHANGED
@@ -54,6 +54,7 @@ export function loadConfig(env = process.env) {
54
54
  maxBlocks: positiveInt(env.DSH_BILINGUAL_MAX_BLOCKS, 400),
55
55
  batchBlocks: positiveInt(env.DSH_BILINGUAL_BATCH_BLOCKS, 6),
56
56
  batchChars: positiveInt(env.DSH_BILINGUAL_BATCH_CHARS, 3_500),
57
+ concurrency: positiveInt(env.DSH_BILINGUAL_CONCURRENCY, 2),
57
58
  maxTranslateChars: positiveInt(env.DSH_BILINGUAL_MAX_TRANSLATE_CHARS, 20_000),
58
59
  cacheLimit: positiveInt(env.DSH_BILINGUAL_CACHE_LIMIT, 20_000),
59
60
  glossaryLimit: positiveInt(env.DSH_BILINGUAL_GLOSSARY_LIMIT, 500),
package/src/store.js CHANGED
@@ -30,6 +30,7 @@ export class BilingualStore {
30
30
  complete,
31
31
  })
32
32
  this.jobs = new Map()
33
+ this.saveQueue = Promise.resolve()
33
34
  this.loaded = false
34
35
  this.readyPromise = null
35
36
  }
@@ -161,9 +162,17 @@ export class BilingualStore {
161
162
  return doc
162
163
  }
163
164
 
164
- async saveDoc(doc) {
165
+ /**
166
+ * Serialize writes for the same store. Parallel translation batches finish at
167
+ * different times; without a queue an older snapshot could rename over a
168
+ * newer one and briefly hide finished blocks from the UI.
169
+ */
170
+ saveDoc(doc) {
165
171
  doc.updatedAt = nowIso()
166
- await writeJsonAtomic(this.docFile(doc.id), doc)
172
+ const file = this.docFile(doc.id)
173
+ const write = this.saveQueue.then(() => writeJsonAtomic(file, doc))
174
+ this.saveQueue = write.catch(() => {})
175
+ return write
167
176
  }
168
177
 
169
178
  async getDoc(id) {
package/src/translator.js CHANGED
@@ -192,13 +192,24 @@ export class Translator {
192
192
  maxBlocks: this.config.batchBlocks,
193
193
  maxChars: this.config.batchChars,
194
194
  })
195
-
196
- for (const batch of batches) {
197
- if (options.signal?.aborted) throw new Error('翻译已取消')
198
- await this.translateBatch(doc, batch, { glossaryTerms, glossaryHash, signal: options.signal })
199
- this.refreshStats(doc)
200
- await options.onProgress?.(doc)
195
+ const concurrency = Math.min(4, Math.max(1, Number(this.config.concurrency) || 1))
196
+ let nextBatch = 0
197
+ const worker = async () => {
198
+ while (true) {
199
+ if (options.signal?.aborted) throw new Error('翻译已取消')
200
+ const index = nextBatch
201
+ nextBatch += 1
202
+ if (index >= batches.length) return
203
+ await this.translateBatch(doc, batches[index], { glossaryTerms, glossaryHash, signal: options.signal })
204
+ this.refreshStats(doc)
205
+ await options.onProgress?.(doc)
206
+ }
201
207
  }
208
+ const settled = await Promise.allSettled(
209
+ Array.from({ length: Math.min(concurrency, batches.length) }, () => worker()),
210
+ )
211
+ const failure = settled.find(result => result.status === 'rejected')
212
+ if (failure !== undefined) throw failure.reason
202
213
 
203
214
  this.refreshStats(doc)
204
215
  if (doc.stats.translatable === 0) doc.status = 'done'
@@ -255,9 +266,16 @@ export class Translator {
255
266
  const retried = await this.translateSingle(doc, item, context, { retryOnly: true })
256
267
  if (retried) continue
257
268
  restored = item.protection.restore(value)
258
- item.block.warning = `模型丢失了保护片段:${restored.missing.length}`
269
+ this.finishBlock(
270
+ doc,
271
+ item.block,
272
+ restored.text,
273
+ context.glossaryHash,
274
+ `模型丢失了保护片段:${restored.missing.length}`,
275
+ )
276
+ continue
259
277
  }
260
- this.finishBlock(doc, item.block, restored.text)
278
+ this.finishBlock(doc, item.block, restored.text, context.glossaryHash)
261
279
  }
262
280
  }
263
281
 
@@ -278,10 +296,13 @@ export class Translator {
278
296
  const values = parseBatchResponse(result.text, 1)
279
297
  const restored = item.protection.restore(values[0] ?? '')
280
298
  if (restored.text.trim() === '') throw new Error('译文为空')
281
- if (restored.missing.length > 0) {
282
- item.block.warning = `模型丢失了保护片段:${restored.missing.length}`
283
- }
284
- this.finishBlock(doc, item.block, restored.text)
299
+ this.finishBlock(
300
+ doc,
301
+ item.block,
302
+ restored.text,
303
+ context.glossaryHash,
304
+ restored.missing.length > 0 ? `模型丢失了保护片段:${restored.missing.length}` : '',
305
+ )
285
306
  return true
286
307
  } catch (error) {
287
308
  if (options.retryOnly) return false
@@ -291,7 +312,7 @@ export class Translator {
291
312
  }
292
313
  }
293
314
 
294
- finishBlock(doc, block, translation) {
315
+ finishBlock(doc, block, translation, glossaryHash = this.glossary.hash(), warning = '') {
295
316
  const text = ensureHeadingPrefix(block.original, translation).trim()
296
317
  if (text === '') {
297
318
  block.status = 'failed'
@@ -301,7 +322,8 @@ export class Translator {
301
322
  block.translation = text
302
323
  block.status = 'done'
303
324
  block.error = ''
304
- const key = this.cache.key(block.original, doc.targetLang, this.glossary.hash())
325
+ block.warning = warning
326
+ const key = this.cache.key(block.original, doc.targetLang, glossaryHash)
305
327
  this.cache.set(key, text)
306
328
  }
307
329
 
package/src/util.js CHANGED
@@ -44,7 +44,7 @@ async function replaceFile(temp, file, content) {
44
44
  export async function writeJsonAtomic(file, value) {
45
45
  await fs.mkdir(path.dirname(file), { recursive: true })
46
46
  const content = `${JSON.stringify(value, null, 2)}\n`
47
- const temp = `${file}.tmp-${process.pid}-${Date.now()}`
47
+ const temp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
48
48
  await fs.writeFile(temp, content, 'utf8')
49
49
  await replaceFile(temp, file, content)
50
50
  }
@@ -52,7 +52,7 @@ export async function writeJsonAtomic(file, value) {
52
52
  export async function writeTextAtomic(file, text) {
53
53
  await fs.mkdir(path.dirname(file), { recursive: true })
54
54
  const content = String(text ?? '')
55
- const temp = `${file}.tmp-${process.pid}-${Date.now()}`
55
+ const temp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
56
56
  await fs.writeFile(temp, content, 'utf8')
57
57
  await replaceFile(temp, file, content)
58
58
  }
package/web/app.js CHANGED
@@ -1,18 +1,35 @@
1
1
  const API = '/dsh-bilingual-reader/api'
2
+ const VIEW_KEY = 'dsh-bilingual-reader:view'
3
+ const VIEWS = new Set(['inline', 'bilingual', 'original', 'translation'])
2
4
 
3
5
  const $ = (selector, root = document) => root.querySelector(selector)
4
6
  const $$ = (selector, root = document) => [...root.querySelectorAll(selector)]
5
7
 
8
+ function storedView() {
9
+ try {
10
+ const value = localStorage.getItem(VIEW_KEY)
11
+ if (VIEWS.has(value)) return value
12
+ } catch {
13
+ // localStorage can be unavailable in hardened webviews; default is fine.
14
+ }
15
+ return 'inline'
16
+ }
17
+
6
18
  const state = {
7
19
  health: null,
8
20
  docs: [],
9
21
  doc: null,
10
- view: 'bilingual',
22
+ view: storedView(),
11
23
  poll: null,
12
24
  busy: false,
13
25
  glossary: [],
14
26
  }
15
27
 
28
+ const rendered = {
29
+ docId: null,
30
+ signatures: [],
31
+ }
32
+
16
33
  const els = {
17
34
  form: $('#read-form'),
18
35
  url: $('#url-input'),
@@ -140,7 +157,7 @@ function startPolling() {
140
157
  try {
141
158
  const data = await api(`/docs/${encodeURIComponent(state.doc.id)}`)
142
159
  state.doc = data.doc
143
- renderDoc()
160
+ updateDocView()
144
161
  if (!['pending', 'running'].includes(state.doc.status)) {
145
162
  clearInterval(state.poll)
146
163
  state.poll = null
@@ -169,11 +186,12 @@ function blockPlaceholder(block) {
169
186
  }
170
187
 
171
188
  function renderBlock(block) {
189
+ const id = ` data-block-id="${escapeAttr(block.id)}"`
172
190
  if (block.type === 'code' || block.type === 'hr') {
173
- return `<section class="block block-code">${block.originalHtml}</section>`
191
+ return `<section class="block block-code"${id}>${block.originalHtml}</section>`
174
192
  }
175
193
  if (block.translatable !== true) {
176
- return `<section class="block block-plain">${block.originalHtml}</section>`
194
+ return `<section class="block block-plain"${id}>${block.originalHtml}</section>`
177
195
  }
178
196
  const warning = block.warning
179
197
  ? `<span class="badge warn" title="${escapeAttr(block.warning)}">保护片段丢失</span>`
@@ -182,19 +200,58 @@ function renderBlock(block) {
182
200
  ? block.translationHtml
183
201
  : blockPlaceholder(block)
184
202
  return `
185
- <section class="block">
203
+ <section class="block"${id}>
186
204
  <div class="orig">${block.originalHtml}</div>
187
205
  <div class="trans">${warning}${translation}</div>
188
206
  </section>
189
207
  `
190
208
  }
191
209
 
192
- function renderDoc() {
210
+ function blockSignature(block) {
211
+ return [block.status, block.translation ?? '', block.warning ?? '', block.error ?? ''].join('\u0000')
212
+ }
213
+
214
+ function renderBlocksFull(doc) {
215
+ els.blocks.innerHTML = doc.blocks.map(renderBlock).join('')
216
+ rendered.docId = doc.id
217
+ rendered.signatures = doc.blocks.map(blockSignature)
218
+ }
219
+
220
+ /**
221
+ * Polling returns the whole document, but only a few blocks change per tick.
222
+ * Replacing just those sections avoids resetting scroll and text selection.
223
+ */
224
+ function updateBlocks(doc) {
225
+ if (rendered.docId !== doc.id || rendered.signatures.length !== doc.blocks.length) {
226
+ renderBlocksFull(doc)
227
+ return
228
+ }
229
+ const nodes = [...els.blocks.children]
230
+ doc.blocks.forEach((block, index) => {
231
+ const signature = blockSignature(block)
232
+ if (signature === rendered.signatures[index]) return
233
+ const node = nodes[index]
234
+ if (node === undefined) return
235
+ node.outerHTML = renderBlock(block)
236
+ rendered.signatures[index] = signature
237
+ })
238
+ }
239
+
240
+ function updateActiveDocItem(doc) {
241
+ const button = els.docs.querySelector(`[data-doc-id="${CSS.escape(doc.id)}"]`)
242
+ if (button === null) return
243
+ const sub = button.querySelector('.doc-item-sub')
244
+ if (sub === null) return
245
+ const percent = Math.round((doc.progress ?? 0) * 100)
246
+ sub.textContent = `${statusLabel(doc.status)} · ${percent}% · ${formatDate(doc.createdAt)}`
247
+ }
248
+
249
+ function renderDocChrome() {
193
250
  const doc = state.doc
194
251
  if (doc === null) {
195
252
  els.empty.hidden = false
196
253
  els.docView.hidden = true
197
- return
254
+ return false
198
255
  }
199
256
  els.empty.hidden = true
200
257
  els.docView.hidden = false
@@ -218,15 +275,34 @@ function renderDoc() {
218
275
  els.exportLink.href = `${API}/docs/${encodeURIComponent(doc.id)}/export`
219
276
  els.exportLink.setAttribute('download', `${doc.id}.bilingual.md`)
220
277
  els.blocks.className = `blocks view-${state.view}`
221
- els.blocks.innerHTML = doc.blocks.map(renderBlock).join('')
278
+ updateActiveDocItem(doc)
279
+ return true
280
+ }
281
+
282
+ function renderDoc() {
283
+ if (!renderDocChrome()) return
284
+ renderBlocksFull(state.doc)
285
+ }
286
+
287
+ function updateDocView() {
288
+ if (!renderDocChrome()) return
289
+ updateBlocks(state.doc)
222
290
  }
223
291
 
224
292
  function setView(view) {
293
+ if (!VIEWS.has(view)) return
225
294
  state.view = view
226
295
  for (const button of $$('.view-switch button')) {
227
- button.classList.toggle('active', button.dataset.view === view)
296
+ const active = button.dataset.view === view
297
+ button.classList.toggle('active', active)
298
+ button.setAttribute('aria-pressed', String(active))
228
299
  }
229
300
  els.blocks.className = `blocks view-${view}`
301
+ try {
302
+ localStorage.setItem(VIEW_KEY, view)
303
+ } catch {
304
+ // Preference persistence is optional.
305
+ }
230
306
  }
231
307
 
232
308
  async function startRead(url) {
@@ -397,4 +473,5 @@ window.addEventListener('beforeunload', () => {
397
473
  if (state.poll !== null) clearInterval(state.poll)
398
474
  })
399
475
 
476
+ setView(state.view)
400
477
  void init()
package/web/index.html CHANGED
@@ -47,7 +47,7 @@
47
47
  <h2>把网页读成双语</h2>
48
48
  <p>粘贴一个公开文章链接,或让 Agent 调用 <code>bilingual_read_url</code>。代码、公式、链接和表格保持原样,只翻译正文。</p>
49
49
  <ul>
50
- <li>对照 / 原文 / 译文三种视图</li>
50
+ <li>上下 / 对照 / 原文 / 译文四种视图</li>
51
51
  <li>术语表 + 内容哈希缓存,重复段落不再调用模型</li>
52
52
  <li>导出双语 Markdown,保留标题层级与代码块</li>
53
53
  </ul>
@@ -61,7 +61,8 @@
61
61
  </div>
62
62
  <div class="doc-actions">
63
63
  <div class="view-switch" role="group" aria-label="视图">
64
- <button type="button" data-view="bilingual" class="active">对照</button>
64
+ <button type="button" data-view="inline" class="active">上下</button>
65
+ <button type="button" data-view="bilingual">对照</button>
65
66
  <button type="button" data-view="original">原文</button>
66
67
  <button type="button" data-view="translation">译文</button>
67
68
  </div>
@@ -72,7 +73,7 @@
72
73
  </div>
73
74
  <div class="progress" aria-hidden="true"><div id="progress-bar"></div></div>
74
75
  <p class="doc-status" id="doc-status"></p>
75
- <article id="blocks" class="blocks view-bilingual"></article>
76
+ <article id="blocks" class="blocks view-inline"></article>
76
77
  </div>
77
78
  </section>
78
79
  </main>
package/web/style.css CHANGED
@@ -398,6 +398,19 @@ select {
398
398
  .blocks.view-translation .orig { display: none; }
399
399
  .blocks.view-translation .trans { padding-left: 0; border-left: 0; }
400
400
 
401
+ /* Default reading mode: the translation sits directly under each paragraph. */
402
+ .blocks.view-inline .block {
403
+ display: block;
404
+ padding: 18px 0;
405
+ }
406
+ .blocks.view-inline .trans {
407
+ margin-top: 10px;
408
+ padding: 10px 14px;
409
+ border-left: 3px solid var(--accent);
410
+ border-radius: 0 10px 10px 0;
411
+ background: var(--accent-soft);
412
+ }
413
+
401
414
  .dialog {
402
415
  width: min(560px, calc(100vw - 40px));
403
416
  border: 1px solid var(--border);