Add opt-in automatic reverse translation for a two-language pair. autoSwitchTarget defaults on with fallbackTargetLanguage English (or German when the target is English); the saved target and the effective request target are separate. Confident source-equals-target text uses the fallback, the header and a panel banner show the effective direction, and the banner can override the direction for one capture without changing the saved target. The language picker still changes the saved target, and changing the target to the fallback swaps the pair. JSON/HTML/code handling is unchanged.\n\nFilter near-zero NLLanguageRecognizer hypotheses so the existing high-confidence same-language rule works for real text. Add resolver, settings, view-model, detector and persistence tests; document ADR-022, the panel, settings and user guide. Verified: make verify green; German text with target German/fallback English renders German → English with the banner, English text stays English → German, a real click on the override shows German → German, and a new German capture switches back to English.
159 lines
21 KiB
Markdown
159 lines
21 KiB
Markdown
# Architecture decision records
|
||
|
||
Format: one section per ADR. Status: Proposed · Accepted · Superseded by ADR-n. Add new ADRs at the end with `/adr <title>`.
|
||
|
||
---
|
||
|
||
## ADR-001 — Ollama `/api/chat` as the translation backend
|
||
Status: Accepted
|
||
|
||
Context: The product's core value is local, private translation. Hy-MT3 is available as an official Tencent GGUF and runs in Ollama. Ollama's native chat endpoint applies the model's chat template, streams NDJSON and exposes `done_reason` and timing metrics. The model is text-only and has no thinking mode.
|
||
Decision: Use Ollama over HTTP with `POST /api/chat`, one user message, `stream: true`. Do not embed MLX, llama.cpp or Core ML. Do not use the OpenAI-compatible endpoint in v1, because the native endpoint exposes the template, `keep_alive` and metrics directly.
|
||
Consequences: The user must install Ollama and pull a model, so onboarding must handle this. The app stays small and redistributes no weights. Another backend would need a second client behind the same protocol.
|
||
|
||
## ADR-002 — Hy-MT3's documented default prompt, with a stable prefix
|
||
Status: Accepted
|
||
|
||
Context: Hy-MT3 ships with documented prompt templates. Ad-hoc prompting changes behaviour unpredictably. Ollama reuses the prompt prefix cache; a dynamic prefix makes every request cold.
|
||
Decision: The default prompt is Tencent's English **Default Translation** template, byte for byte, with the exact model language name and the source text appended. The prefix depends only on the target language. No system message, no source-language field, no timestamps, no app name. Prompt strings live only in `SprachmittlerEngines`.
|
||
Consequences: Byte-exact golden tests are mandatory. Changing the prompt requires an ADR and a new adapter version. The measured 177/178 cached prompt tokens are preserved.
|
||
|
||
## ADR-003 — Non-sandboxed app; Accessibility optional
|
||
Status: Accepted
|
||
|
||
Context: Replacing another app's selection requires Accessibility trust, which App Sandbox does not allow for this use. The core flow (double copy, translate, Copy, Services) needs no permission.
|
||
Decision: Ship without App Sandbox, with Hardened Runtime and Developer ID + notarisation. Request Accessibility only when the user clicks Replace, or from onboarding if they choose to enable it. No Mac App Store in v1.
|
||
Consequences: Wider capability, and with it more responsibility: SECURITY_PRIVACY.md invariants are mandatory and checked in `make verify`. A future sandboxed "Services-only, copy-only" edition remains possible.
|
||
|
||
## ADR-004 — Double copy detected through the pasteboard, not a key tap
|
||
Status: Accepted
|
||
|
||
Context: A global ⌘C key tap needs Input Monitoring or Accessibility and widens permissions. DeepL-style double copy can be detected from `NSPasteboard.changeCount` without any permission.
|
||
Decision: Poll `NSPasteboard.general.changeCount` every 120 ms on the main actor. A trigger is two changes within 500 ms (300–1000 configurable) whose string values are identical and non-empty. Read the string only after a change. Ignore our own writes and transient/concealed pasteboard items. Keep at most the last two strings in memory.
|
||
Consequences: No Input Monitoring. False positives are bounded by the identical-text rule. The app must document that copying two different things quickly does not trigger. Polling costs less than 0.5% CPU at 120 ms.
|
||
|
||
## ADR-005 — Explicit Replace only; Accessibility first, paste fallback
|
||
Status: Accepted
|
||
|
||
Context: Automatic replacement is destructive and surprising. A synthetic ⌘V mutates the user's clipboard; AX direct replacement avoids that but is not supported everywhere.
|
||
Decision: The panel never replaces or copies automatically. **Replace** is an explicit button in the lower right. It tries AX direct replacement first (verify the selected text still matches), then a synthetic ⌘V with a full clipboard snapshot/restore. It aborts if the source app is no longer frontmost or the selection changed. Blocking warnings disable Replace by default.
|
||
Consequences: Replace works in more apps, and the clipboard is preserved. Some Electron/canvas apps still fail; they get a clear Copy fallback. Replacement is one undoable operation in apps that support undo, which is documented as app-dependent.
|
||
|
||
## ADR-006 — XcodeGen + SwiftPM package for agent-friendly development
|
||
Status: Accepted
|
||
|
||
Context: Coding agents edit `.pbxproj` files unreliably.
|
||
Decision: All logic lives in a SwiftPM package (`swift build` / `swift test` from the CLI). The app target is defined in `project.yml` and generated with XcodeGen. `.xcodeproj` is git-ignored and denied to agent edits in `opencode.json`.
|
||
Consequences: Agents can build and test without the Xcode UI. Adding files needs no project edits.
|
||
|
||
## ADR-007 — No history and no persistence of text
|
||
Status: Accepted
|
||
|
||
Context: Selected text is often confidential. A translation history is a privacy liability and a sync/backup risk.
|
||
Decision: Source text, translations, pasteboard snapshots and app names are never written to disk. Settings contain only configuration. The last translation may stay in memory for the panel's Copy/Replace actions and is released when the panel closes or the app quits. No analytics, no crash-reporting SDK, no accounts.
|
||
Consequences: The user cannot look up an old translation after closing the panel; that is the intended trade-off. A future opt-in history needs an ADR, explicit consent and encrypted storage.
|
||
|
||
## ADR-008 — Default model chosen by evaluation
|
||
Status: Proposed (T7.5 blocked on the private corpus and the 1.8B comparison)
|
||
|
||
Context: Publisher benchmarks do not cover the user's texts, and 7B vs 1.8B is a quality/latency trade-off. The 7B is the owner's requested default, but the 1.8B may be better on smaller Macs.
|
||
Decision: Ship with `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` as the provisional default and the 1.8B Q4_K_M as the Fast preset. Decide the default, the sampling temperature and the prompt policy with `sprachmittler-cli eval` on the user's corpus using the rule in `docs/MODEL_EVALUATION.md` §5. Record the outcome as a new ADR.
|
||
Consequences: Until the gate, the 7B is labelled provisional in Settings. The decision is re-run when a model, Ollama or the prompt policy changes.
|
||
|
||
## ADR-009 — Menu-bar agent with a non-activating panel
|
||
Status: Accepted (amended 2026-11-26: Esc without a click)
|
||
|
||
Context: The app must be available over any app and must not activate itself or take application focus from the selection. A regular Dock app with a window would interrupt the workflow. Users also expect Esc to dismiss a transient panel immediately, which requires the panel to be the key window.
|
||
Decision: Use `LSUIElement = YES`, a `MenuBarExtra`, and a floating `NSPanel` with `.nonactivatingPanel` and `becomesKeyOnlyIfNeeded = false`. Never call `NSApp.activate` or `makeKeyAndOrderFront` for the translation panel. Onboarding and Settings are the only surfaces that activate the app. By default the panel calls `makeKey()` when shown, so Esc and the keyboard shortcuts work immediately; the setting `closeWithEscape` can restore click-first behaviour. The panel's SwiftUI exit command handles Esc and calls the same close path that cancels an in-flight request.
|
||
Consequences: The app stays unactivated: `NSWorkspace.frontmostApplication` and the menu bar stay with the source app, and Replace still re-verifies that app. While the panel is visible it holds keyboard focus, so keystrokes and shortcuts go to the panel until the user clicks back into the source app; the setting turns this off. A click outside the panel dismisses it: the panel observes `didResignKey` and, while visible, a transient global mouse-down monitor. Global monitors do not receive events sent to this app, so clicks in the panel and its popover are ignored; the event is discarded and the monitor is removed on close. The monitor is not a key tap and needs no Input Monitoring. Every action still has a button.
|
||
|
||
## ADR-010 — Native OpenCode 2.x configuration
|
||
Status: Accepted
|
||
|
||
Context: The kit targets OpenCode 2.x. V2 still accepts V1 configuration, but native V2 uses an ordered `permissions` list with `action`/`resource`/`effect` rules (last match wins), `shell` instead of `bash`, `subagent` instead of `task`, and V2 agent fields. In V2, access to external directories is allowed by default, and agent `temperature` is no longer sent.
|
||
Decision: Use native V2 only: `opencode.json` with `$schema`, `instructions` and `permissions`; agents in `.opencode/agents/` with V2 frontmatter (`description`, `mode`, `steps`, `permissions`) and no `temperature`; commands in `.opencode/commands/`; skills in `.opencode/skills/<id>/SKILL.md`. Restore `external_directory: ask` explicitly. Check with `make doctor`.
|
||
Consequences: No mixed V1/V2 files. Sampling settings for agents, if wanted, go on a model variant in the user's global config.
|
||
|
||
## 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.
|
||
|
||
## ADR-012 — Only documented prompt variants; no free-form prompts
|
||
Status: Accepted
|
||
|
||
Context: The model card documents Default, Terminology, Style, Personalization, Delimiters, Structured Data 1/2 and Background Information templates. Text with Markdown, JSON, URLs or placeholders may benefit from a structured template.
|
||
Decision: v1 uses the Default Translation template for everything. The Structured Data 1, Delimiters, Terminology and Style templates are the only allowed alternatives, selected by a deterministic content policy or as a documented fallback after validation. No other prompt text is allowed. The user cannot type a prompt in v1.
|
||
Consequences: Predictable behaviour and a small attack surface. A future glossary or style feature uses the existing documented templates, not new instructions.
|
||
|
||
## ADR-013 — Validation gates Replace, never rewrites output
|
||
Status: Accepted
|
||
|
||
Context: Translation models occasionally add an explanation, truncate, loop or drop a URL/placeholder. Silently "fixing" the output hides errors and can corrupt meaning.
|
||
Decision: Show the model output after only T1 (outer whitespace/line endings). Detect preamble, truncation, repetition, empty output, lost protected tokens and numeric mismatch. Retry once with the documented Delimiters prompt only when a protected token is lost. Blocking warnings disable Replace by default; Copy remains available. Never strip a preamble or edit the wording automatically.
|
||
Consequences: The user sees the truth and decides. Some outputs need manual cleanup; that is preferable to silent damage.
|
||
|
||
## ADR-014 — Model language names come from the model card; English prompts are canonical
|
||
Status: Accepted
|
||
|
||
Context: Hy-MT3 expects full language names, with Chinese names in Chinese prompts and English names in English prompts. The table has variants such as `Chinese` vs `Traditional Chinese`, `Norwegian` vs `Norwegian Nynorsk`, `Arabic Kazakh` vs `Cyrillic Kazakh`.
|
||
Decision: Store the exact model-card English name with every `TargetLanguage`. Build prompts in English regardless of the UI language. Localise display names separately with `Locale`, but never feed a localised name into the prompt. Unknown BCP-47 codes are not silently mapped; the UI offers the supported list.
|
||
Consequences: The prompt stays stable across UI languages and matches the model's training data. Adding a language requires updating `LANGUAGES.md`, the catalogue and a test.
|
||
|
||
## ADR-015 — One translation in flight; epochs discard stale results
|
||
Status: Accepted
|
||
|
||
Context: The user may double-copy again, change the target language or close the panel while a request is streaming. Two overlapping streams would confuse the panel and waste compute.
|
||
Decision: `TranslationSession` is an actor with one active request. A new trigger or target change increments an epoch and cancels the previous URL task. Events from an older epoch are discarded. Chunks are translated sequentially. Copy does not change the session; Replace only runs from a `.ready` state with no blocking warnings.
|
||
Consequences: Fast, predictable updates and no orphaned requests. The previous translation is lost when the user triggers a new one; that is intentional and avoids history.
|
||
|
||
## ADR-016 — Provisional M1 Engines slice for the CLI
|
||
Status: Superseded by ADR-017
|
||
|
||
Context: T1.6 needs the documented Default prompt and the exact model language name before T2.2/T2.3 exist. Putting either in the CLI target would violate documented-prompts-only and the lint rule that prompt and language literals live in `SprachmittlerEngines`.
|
||
Decision: Add a provisional `ModelLanguage` with the 15 common targets from `LANGUAGES.md` §5, the byte-exact Default Translation prompt, the documented sampling values and `HyMT3RequestFactory` in `SprachmittlerEngines`. T2.3 replaces the table with all 102 languages; T2.1/T2.2 replace the factory with `TranslationAdapter`/`HyMT3Adapter`.
|
||
Consequences: The M1 CLI translates en→de and the other common targets without a free-form prompt. Unknown codes fail before the network. Only 15 targets resolve until T2.3, and no prompt literal or model tag appears outside Engines.
|
||
|
||
## ADR-017 — Adapter registry in Engines; one pipeline in Core
|
||
Status: Accepted
|
||
|
||
Context: M1 needed a prompt and a request factory for the CLI before the model-family adapter existed. T2.1/T2.2 replace that factory, and both the CLI and the future panel must use the same chunking, validation and retry rules. Prompt strings must stay in `SprachmittlerEngines`; validation results must be visible to Core and the UI.
|
||
Decision: `TranslationAdapter` and `AdapterRegistry` live in `SprachmittlerEngines`. An `AdapterRequest` carries text, target, model, keep-alive, prompt variant and sampling. `HyMT3Adapter` is the only family adapter in v1; it sets the publisher sampling, `num_ctx: 8192`, exactly one user message and no system/think field. `TranslationWarning` and `ModelLanguage` (re-exported as `TargetLanguage`) also live in Engines, and `LanguageMatching` owns the canonical-code comparison. `TranslationPipeline` in `SprachmittlerCore` does normalisation, detection, classification, chunking, one documented retry after a lost protected token, validation and timing; the keep-alive value is supplied by the composition root. Core re-exports the warning and language types.
|
||
Consequences: The CLI and M4 session share one implementation. Prompt bytes and language names have one home. Adapter selection is explicit and unknown families fail with `noAdapter`. The M1 `HyMT3RequestFactory` and its 15-language table are removed. A second model family adds an adapter, not a branch in Core.
|
||
|
||
## ADR-018 — Capture behind a pasteboard protocol; Services is a first-class trigger
|
||
Status: Accepted
|
||
|
||
Context: Double copy, clipboard snapshot/restore and Services all touch `NSPasteboard`, but the state machine and watcher need deterministic tests without real time or the user's clipboard. The Services path must work with no Accessibility permission.
|
||
Decision: `SprachmittlerCapture` defines `PasteboardAccessing` and `PasteboardTicking`. `SystemPasteboard` is the only production `NSPasteboard` user; `FakePasteboard` and `ManualPasteboardTicker` live in `SprachmittlerTestSupport`. `DoubleCopyDetector` is a pure state machine over change events and an injected date. `PasteboardWatcher` polls every 120 ms, reads the string only after `changeCount` changes, suppresses own/transient changes for 750 ms, and enforces the 4000/2000 limit. `ServicesProvider` receives the system pasteboard and needs no polling or Accessibility. `AppDelegate` installs it and calls `NSUpdateDynamicServices`.
|
||
Consequences: Capture logic is unit-testable and no global key tap is needed. The Services and double-copy paths both produce `CapturedText`. The 10-app compatibility matrix remains a manual task.
|
||
|
||
## ADR-019 — AX first, paste fallback, target re-verified at Replace
|
||
Status: Accepted
|
||
|
||
Context: Replace must be safe and reversible, but Accessibility support differs by app. AX calls can block, so they must stay off the main actor. Tests need deterministic insertion without a real app or clipboard.
|
||
Decision: `InsertionCoordinator` lives in `SprachmittlerCapture` and uses `AccessibilityTextEditing` and `EventPosting` seams. At trigger time the app captures the frontmost PID/bundle and, when trusted, reads only the focused selection; at Replace it re-verifies the frontmost app and the selected text (`InsertionPolicy`). It refuses secure fields and its own PID. AX direct replacement is tried first; if unsupported, it snapshots the clipboard, writes the translation with own/transient markers, posts ⌘V to the target PID, waits up to 300 ms and restores only when `changeCount` still matches the write. Blocking warnings disable Replace; failures keep the panel open and offer Copy.
|
||
Consequences: Most apps use the no-clipboard AX path; the fallback preserves the previous clipboard in the common case. Manual testing is still required because AX support and paste delivery are app-specific.
|
||
|
||
## ADR-020 — UI state models in Core, AppKit controllers in App
|
||
Status: Accepted
|
||
|
||
Context: Panel, Settings, Onboarding and Diagnostics contain branching worth testing, but their windows are AppKit/SwiftUI. The app target must stay thin.
|
||
Decision: `PanelViewModel`, `SettingsViewModel`, `OnboardingViewModel` and `DiagnosticsViewModel` are `@MainActor @Observable` types in `SprachmittlerCore`; `SettingsStore` uses a `SettingsDataStoring` seam. `App` owns only `NSPanel`/`NSWindow` controllers, SwiftUI views, the composition root (`AppEnvironment`) and lifecycle glue. `TranslationSession` uses an injected pipeline factory so endpoint/settings changes apply on the next request without rebuilding the UI.
|
||
Consequences: Logic is covered by package tests; AppKit remains untested by `make verify` and requires the manual checklist.
|
||
|
||
## ADR-021 — Markdown is rendered as presentation only
|
||
Status: Accepted
|
||
|
||
Context: Hy-MT3 preserves Markdown structure, but a plain `Text` showed `**bold**`, headings and lists literally. Users translating Markdown want the formatting rendered, while Copy and Replace must keep the Markdown that the model produced and the validator checked.
|
||
Decision: Parse presentation Markdown in `SprachmittlerText` with Foundation's inline Markdown parser plus a small, conservative block parser (headings, lists, quotes, fenced code, rules, paragraphs). `MarkdownPresentation.shouldRender` rejects JSON, HTML and code sources and otherwise requires block or inline Markdown markers. The panel renders only when the setting `renderMarkdown` is on (default). Copy and Replace use the raw translation unchanged. Only `http` and `https` links open, on an explicit click; image syntax is reduced to alt text and no remote resource is fetched. Tables, raw HTML and nested lists/quotes remain plain text in this pass.
|
||
Consequences: Rendering never rewrites the translation or weakens validation. Literal markers can be interpreted as formatting, so the setting is the escape hatch; Copy always returns the raw Markdown. The block layout makes text selection per block, while Copy remains the whole-translation path. No new dependency is added.
|
||
|
||
## ADR-022 — Optional reverse direction for source-equals-target text
|
||
Status: Accepted
|
||
|
||
Context: A single saved target language is simple, but selecting text that is already in that language produced a same-language translation and an advisory. Users working in a two-language pair want the opposite direction automatically: with target German and fallback English, German text should become English and English text should become German.
|
||
Decision: Add `autoSwitchTarget` (default true) and `fallbackTargetLanguage` (default English, or the other language when the target is English). Detect the source before the request and, only when the existing high-confidence same-language rule holds, use the fallback as the effective target. Keep the saved target separate from the effective target; the header and language picker show the effective one, and a panel banner offers a one-capture override that does not persist. A language-picker change persists the saved target. The fallback is kept different from the target; changing the target to the fallback swaps the pair to the previous target.
|
||
Consequences: Confident two-language text translates in the useful direction without extra clicks. Uncertain, short or mixed text keeps the saved target, and the same-language advisory still appears when no switch occurs. Detection is advisory, so a wrong dominant language can choose the wrong direction; the banner and the language picker make it visible and recoverable. The effective target is what the prompt, chunking and validation use; Copy and Replace are unaffected. No key tap, permission or new dependency is added. |