Files
Sprachmittler/docs/DECISIONS.md
T
schihei a78572adc3 feat(m4-m6): session, panel, Replace, settings and onboarding
M4: TranslationSession actor with epochs/one-in-flight streaming, PanelViewModel, non-activating NSPanel, streaming panel UI, searchable/recent target languages, warnings/errors and Copy/Retry/Replace actions.

M5: InsertionCoordinator with target capture, AX direct replacement, secure-field/own-PID refusal, frontmost and selected-text verification, snapshot/⌘V/restore fallback, cancellation-safe restore and blocking-warning gate.

M6: versioned AppSettings/SettingsStore, onboarding for Ollama/model/target/Accessibility, General/Model/Translation/Privacy/Diagnostics settings, launch-at-login via SMAppService, status menu (target, copy/replace last, setup, diagnostics, about), text-free diagnostics and first-run setup.

Docs: PROGRESS M4–M6, ARCHITECTURE §10–§12, ADR-019/020, SELECTION_AND_CLIPBOARD and TESTING. Manual 10-app matrices, real AX/paste delivery, VoiceOver and focus checks remain open.

Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, 217 package tests); app launches and a two-copy clipboard smoke test opens the panel.
2026-11-26 14:03:16 +01:00

146 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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 (decided in T7.5)
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
Context: The app must be available over any app and must not take focus from the selection. A regular Dock app with a window would interrupt the workflow.
Decision: Use `LSUIElement = YES`, a `MenuBarExtra`, and a floating `NSPanel` with `.nonactivatingPanel` and `becomesKeyOnlyIfNeeded = true`. Never call `NSApp.activate` or `makeKeyAndOrderFront` for the translation panel. Onboarding and Settings are the only surfaces that activate the app.
Consequences: The source app keeps focus, so Replace can target it. Keyboard shortcuts inside the panel require a click first; every action also 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.