feat(capture): translate long selections in parts

The capture gate and the chunk size were the same number, so a selection above one chunk was rejected before the pipeline could split it; the Settings sliders moved both thresholds together. Add maximumPartsPerSelection (1-8, default 1, so existing behaviour is unchanged). The capture limit is now part size x parts and travels on TranslationSessionRequest, so the watcher, CapturePolicy and TranslationSession agree for that capture. TranslationStreaming gained an optional per-part callback; the session emits chunkStarted and the panel shows 'Part 2 of 4' while streaming and '2 parts' when finished. textTooLong now points at Settings and offers an Open Settings button. Lower the dense-script part-size maximum to 4000 because 5000 dense characters plus a 4096-token output can overflow the 8192-token context. Tests cover capture limits, watcher limits, pipeline part callbacks, session events and limits, panel progress, settings clamping and migration. Docs updated: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES and README. Verified: make verify green; live 4355-character German text showed Part 1 of 2, Part 2 of 2 and '2 parts'; with one part the panel showed the too-long message and Open Settings.
This commit is contained in:
schihei committed 2026-11-27 20:21:30 +01:00
1 parent 9f89000b0d
commit 2a601058f4
29 files changed
+607 -122

No files matched your search

+5 -4
View File
@@ -359,7 +359,7 @@ public struct DoubleCopyDetector { /* pure state machine */ }
- Poll `NSPasteboard.general.changeCount` every **120 ms** on the main actor through `PasteboardTicking`.
- A candidate trigger is two changes within **500 ms** (range 300–1000 ms, setting) whose `.string` values are identical and non-empty after trimming.
- Require at least one non-whitespace character and at most `maxCharacters` (4000 Latin / 2000 CJK by default).
- Require at least one non-whitespace character and at most the capture limit (`maxCharacters` per part × `maximumPartsPerSelection`: 4000/2000 Latin/dense by default, one part).
- Ignore changes whose pasteboard contains the app's own marker (`com.schihei.sprachmittler.own`) or `org.nspasteboard.TransientType`, and ignore all changes for 750 ms after our own write.
- Keep only the last two strings and their hashes in memory; clear them after the window or after the session starts.
- Do not log the text. Log only `changeCount` deltas and a short hash at `privacy: .private`.
@@ -483,7 +483,7 @@ Full detail: `docs/TRANSLATION_OUTPUT.md`.
2. Detect the source language with `NLLanguageRecognizer` for display only. The prompt does not need it.
3. Classify content: `.plain`, `.markdown`, `.json`, `.html`, `.code`, `.delimited` (many URLs/placeholders).
4. Scan protected tokens: URLs, e-mail addresses, `{{var}}`, `${var}`, `%s`, `%d`, `%1$@`, Markdown code spans, fenced code blocks, HTML tags, JSON keys.
5. Plan chunks: paragraph boundaries first, then sentence, then word; script-aware limits (4000 characters for Latin/Cyrillic/Greek, 2000 for CJK/Arabic/Hebrew/Devanagari etc.). Never split a grapheme cluster.
5. Plan parts: paragraph boundaries first, then sentence, then word; script-aware part sizes (4000 characters for Latin/Cyrillic/Greek, 2000 for CJK/Arabic/Hebrew/Devanagari etc.). Never split a grapheme cluster. The capture gate accepts up to `maximumPartsPerSelection` parts.
### 9.2 Prompt selection (`SprachmittlerEngines`)
@@ -575,8 +575,9 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour
| `targetLanguage` | LanguageCode | system language if supported, else `en` |
| `recentTargetLanguages` | [String] | last three targets, most recent first |
| `doubleCopyWindowMs` | Int | 500 (300–1000) |
| `maxCharactersLatin` | Int | 4000 |
| `maxCharactersCJK` | Int | 2000 |
| `maxCharactersLatin` | Int | 4000 (500–10000) |
| `maxCharactersCJK` | Int | 2000 (500–4000) |
| `maximumPartsPerSelection` | Int | 1 (1–8); 1 rejects text longer than one part |
| `numCtx` | Int | 8192 |
| `numPredict` | Int | 4096 |
| `temperature` | Double | 0.7 |
+3 -3
View File
@@ -77,9 +77,9 @@ Consequences: No mixed V1/V2 files. Sampling settings for agents, if wanted, go
## ADR-011 — Chunk at paragraph boundaries with script-aware limits
Status: Accepted
Context: Hy-MT3's documented translation context is 8192 tokens. A long selection can exceed it; splitting mid-sentence harms quality; splitting mid-grapheme corrupts text.
Decision: Chunk at blank-line paragraph boundaries first, then sentence, then word. Use 4000 characters for Latin/Cyrillic/Greek and 2000 for CJK and other dense scripts. Never split a grapheme cluster. Reassemble with the original separators. Translate chunks sequentially with one request in flight.
Consequences: Most selections are one chunk. Very long selections lose some cross-paragraph context; the panel shows a chunk count and any failed chunk. `done_reason: "length"` is always a warning.
Context: Hy-MT3's documented translation context is 8192 tokens. A long selection can exceed it; splitting mid-sentence harms quality; splitting mid-grapheme corrupts text. The capture gate and the chunk size were the same number, so selections over one chunk were rejected before the pipeline could split them.
Decision: Chunk at blank-line paragraph boundaries first, then sentence, then word. Use 4000 characters per part for Latin/Cyrillic/Greek and 2000 for CJK and other dense scripts. Never split a grapheme cluster. Reassemble with the original separators. Translate parts sequentially with one request in flight. The capture limit is the part size multiplied by `maximumPartsPerSelection` (1–8, default 1); `1` rejects anything over one part, and higher values accept the selection and translate it in parts. The dense-script part size is capped at 4000 because 5000 dense characters plus a 4096-token output can overflow the context.
Consequences: Default behaviour is unchanged (one part). Users who opt into parts trade latency for reach: every extra part is another sequential request, and the panel shows “Part 2 of 4” while streaming and “3 parts” when finished. Very long selections lose some cross-paragraph context; the panel keeps the streamed partial text and disables Replace when a part fails. `done_reason: "length"` is always a warning.
## ADR-012 — Only documented prompt variants; no free-form prompts
Status: Accepted
+1 -1
View File
@@ -138,7 +138,7 @@ Hy-MT3 supports **102 languages**. The exact English name matters: it is inserte
4. **Unknown codes are not silently mapped.** The UI shows only the 102 supported languages; an incoming detection result outside the list is displayed as "Unknown" and translation still proceeds (the prompt only needs the target).
5. **Source detection is advisory.** `NLLanguageRecognizer` supports fewer languages than Hy-MT3. A low-confidence or unsupported detection never blocks translation.
6. **RTL languages:** `ar`, `he`, `fa`, `ur`, `ps`, `sd`, `ug`, `ckb`, `yi`, and `kk` (Arabic Kazakh). The panel must render them right-to-left; the source and translation directions can differ.
7. **Dense-script chunk limit:** CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts use the 2000-character chunk limit; Latin/Cyrillic/Greek use 4000. The chunker uses Unicode script ranges, not the language code.
7. **Dense-script part size:** CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts use the 2000-character part size; Latin/Cyrillic/Greek use 4000. The chunker uses Unicode script ranges, not the language code.
## 5. UI ordering
+1
View File
@@ -159,3 +159,4 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
2026-11-26 · Panel · Added an optional reverse direction: with the saved target German and fallback English, confidently German text is translated to English automatically, and vice versa. The saved target and effective target are separate; a banner offers a one-capture override, and the language picker still changes the saved target. `autoSwitchTarget` defaults on and `fallbackTargetLanguage` defaults to English/the opposite language. Filtered near-zero detector hypotheses so the high-confidence same-language rule works. Added resolver, settings, view-model and detector tests. (Superseded by the routing entry below.)
2026-11-26 · Settings · Replaced the single reverse-direction pair with language routing: the saved target is the mother tongue and the default for every source; an empty `languageRoutes` table means everything goes to the mother tongue. Optional source→target rules (for example Chinese → English) apply only to confidently detected sources. The panel shows the effective direction, offers a one-capture override, and keeps the picker session-only; persistent rules live in Settings. Removed the old fallback settings.
2026-11-27 · Panel · Fixed the header language picker: an override now carries the chosen language instead of only disabling routing. `TranslationDirectionPolicy.resolve` takes `override: ModelLanguage?`, and `PanelViewModel` stores the override target, so picking a language other than the mother tongue retranslates into it; a new capture still returns to the rule/mother tongue. Added picker and rule-override tests.
2026-11-27 · T3.2/T4.1/Settings · Long selections can now be translated in parts. The capture gate and the chunk size were the same number, so text over one chunk was rejected before the pipeline could split it. Added `maximumPartsPerSelection` (1–8, default 1, so existing behaviour is unchanged); the capture limit is now part size × parts, carried on `TranslationSessionRequest` and applied by the watcher, `CapturePolicy` and the session. `TranslationStreaming` can report each part, the session emits `chunkStarted`, and the panel shows “Part 2 of 4” while streaming and “3 parts” when finished. `textTooLong` now points at Settings and offers the Settings button. Lowered the dense-script part size maximum to 4000 (5000 dense characters plus a 4096-token output can overflow the 8192 context). Tests: capture limits, watcher limits, pipeline part callbacks, session events, panel progress and settings clamping. Docs: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES, README.
+2 -2
View File
@@ -33,7 +33,7 @@ Rules:
- Window: **500 ms** default, configurable 300–1000 ms.
- Identical text: compare normalized line endings and trimming only; do not collapse internal whitespace.
- Non-empty: at least one non-whitespace character.
- Length: 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts; above the limit, show `textTooLong` with the limit and no request.
- Length: part size 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts, multiplied by `maximumPartsPerSelection` (1–8, default 1); above that capture limit, show `textTooLong` with the limit, offer Settings and make no request.
- A new trigger during an active translation cancels the old one (ADR-015).
- Copying two different things quickly does not trigger; this is deliberate.
- Copying the same text twice slowly does not trigger; increase the window if needed.
@@ -160,7 +160,7 @@ Info.plist:
**This table is filled in by a person, on a real Mac.** Double copy, Accessibility replacement and clipboard restoration differ in every app and cannot be tested headlessly. Until a row is tested its cells stay ☐; an untested cell is not a claim.
Implementation status (2026-11-26): T3.1–T3.4 and T5.1–T5.4 are implemented and covered by component tests (`DoubleCopyDetector`, `PasteboardWatcher`, `ClipboardSnapshot`, `ServicesProvider`, `InsertionCoordinator`). The 4000/2000 limit and own-marker check apply to double copy, the menu item and Services (`CapturePolicy`). Replace captures the target at trigger time, re-verifies it, prefers AX and falls back to a snapshot/⌘V/restore path. The 10-app double-copy and insertion matrices remain untested; they are the T3.5/T5.5 manual tasks.
Implementation status (2026-11-26): T3.1–T3.4 and T5.1–T5.4 are implemented and covered by component tests (`DoubleCopyDetector`, `PasteboardWatcher`, `ClipboardSnapshot`, `ServicesProvider`, `InsertionCoordinator`). The script-aware part size × `maximumPartsPerSelection` capture limit and own-marker check apply to double copy, the menu item and Services (`CapturePolicy`). Replace captures the target at trigger time, re-verifies it, prefers AX and falls back to a snapshot/⌘V/restore path. The 10-app double-copy and insertion matrices remain untested; they are the T3.5/T5.5 manual tasks.
For each app test:
+5 -3
View File
@@ -24,10 +24,12 @@ The prompt prefix depends only on the target language. Append the source last. D
- Paragraph boundaries (blank lines) first.
- Then sentence boundaries (`.`, `!`, `?`, `。`, `!`, `?`, `…` followed by whitespace/end).
- Then word boundaries; never split a grapheme cluster.
- Limits: **4000 characters** for Latin/Cyrillic/Greek; **2000** for CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts. The limit is script-based, not language-based.
- Part size: **4000 characters** for Latin/Cyrillic/Greek; **2000** for CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts. The limit is script-based, not language-based.
- Capture limit: part size × `maximumPartsPerSelection` (1–8, default **1**). `1` rejects a selection longer than one part; higher values accept it and translate it part by part. The dense part size is configurable up to 4000.
- Reassemble with the original separators (usually `\n\n`). Do not collapse or invent paragraph breaks.
- Translate chunks sequentially; one request in flight.
- A chunk failure stops the sequence and is shown as `chunkFailed(index:)`; the panel keeps the partial translation and disables Replace.
- Translate parts sequentially; one request in flight.
- Show “Part i of n” while a multi-part request streams and “n parts” when it finishes.
- A part failure stops the sequence and is shown as `chunkFailed(index:)`; the panel keeps the partial translation and disables Replace.
## 4. Protected tokens