Files
schihei 2a601058f4 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.
2026-11-27 20:21:30 +01:00

684 lines
36 KiB
Markdown
Raw Permalink 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.
# Sprachmittler — Architecture
Status: Draft v1.0 · Target: macOS 14+ on Apple Silicon · Language: Swift 6 · Development agent: OpenCode 2.x
Sprachmittler is a native macOS menu-bar app. The user selects text in any application and presses **⌘C twice**. A non-activating panel shows a translation produced by a local Ollama Hy-MT3 model. The panel offers **Copy** and an explicit **Replace** button; the app never replaces text on its own. The source application keeps the keyboard focus throughout.
This document is the authoritative technical reference. If code and this document disagree, fix one of them in the same change and record the decision in `docs/DECISIONS.md`.
---
## 1. Goals and non-goals
### Goals
| ID | Goal |
|---|---|
| G1 | Translate the current selection in any app with one gesture: **⌘C twice**. |
| G2 | Show the translation quickly in a floating panel that does not steal focus from the source app. |
| G3 | Let the user **Copy** the translation or **Replace** the selection — explicitly, never automatically. |
| G4 | Local-first: default endpoint `http://127.0.0.1:11434`; no text leaves the Mac unless the user configures a remote endpoint. |
| G5 | Use Tencent's documented Hy-MT3 prompts and settings; no free-form prompting. |
| G6 | Preserve structure: URLs, e-mail addresses, placeholders, code spans, Markdown, JSON and line/paragraph breaks. |
| G7 | Fail visibly and actionably: "Ollama is not running", "Model not installed", "Text is already German", "The model added an explanation", "The source app is no longer active". |
| G8 | No history, no telemetry, no persistence of source text or translations. |
### Non-goals (v1)
- No document translation, file translation, image OCR or PDF handling. That is Schriftleser's job.
- No speech, no dictation, no text-to-speech. That is Vorleser's job.
- No writing assistant, grammar correction or "improve my text" mode.
- No translation memory, glossary management or cloud accounts.
- No automatic replacement, auto-copy, or background translation of the clipboard.
- No Intel Macs, Linux, Windows or iOS.
- No Mac App Store distribution in v1; the Accessibility-based Replace needs a non-sandboxed app (ADR-003).
- No in-process inference (MLX, Core ML, llama.cpp). Ollama is the only backend in v1 (ADR-001).
---
## 2. System context
```mermaid
flowchart LR
User((User))
Src[Source app<br/>Safari · Mail · Word · Notes · editor]
S[Sprachmittler.app<br/>menu-bar agent]
P[Floating panel<br/>non-activating NSPanel]
O[Ollama server<br/>127.0.0.1:11434]
M[Hy-MT3 model<br/>7B Q4_K_M / 1.8B Q4_K_M]
PB[(NSPasteboard)]
AX[(macOS Accessibility)]
SV[(macOS Services)]
User -- select + ⌘C twice --> Src
Src -- copy --> PB
S -- poll changeCount, read text --> PB
S -- POST /api/chat --> O --> M
S -- show streaming translation --> P
User -- click Copy / Replace --> P
P -- Replace: AX set or ⌘V --> AX --> Src
Src -- Services ▸ Translate --> SV --> S
```
### External contracts
| Dependency | Contract | Doc |
|---|---|---|
| Ollama 0.40+ | `POST /api/chat` (streaming NDJSON), `/api/tags`, `/api/show`, `/api/ps`, `/api/version` | `docs/OLLAMA_TRANSLATION_API.md` |
| Hy-MT3 | Documented prompts, language names, sampling, 8192 context | `docs/HYMT3_MODEL.md` |
| NSPasteboard | `changeCount`, `string(forType:)`, item snapshot/restore, transient types | `docs/SELECTION_AND_CLIPBOARD.md` |
| Accessibility | `AXIsProcessTrusted`, focused element, `kAXSelectedTextAttribute`, `kAXSelectedTextRangeAttribute` | `docs/SELECTION_AND_CLIPBOARD.md` |
| AppKit / SwiftUI | `MenuBarExtra`, `NSPanel` (`.nonactivatingPanel`), `Settings` scene | `docs/ARCHITECTURE.md` §11 |
| Services | `NSServices` in Info.plist, `NSApp.servicesProvider` | `docs/SELECTION_AND_CLIPBOARD.md` |
---
## 3. Repository layout
The code is split into a **SwiftPM package (`SprachmittlerKit`)** that holds all logic and is testable with `swift test`, a thin **app target** generated by XcodeGen, and a **CLI harness** for headless translation and evaluation.
```
Sprachmittler/
├── AGENTS.md · opencode.json · .opencode/ # OpenCode 2.x instructions, agents, commands, skills
├── project.yml # XcodeGen spec → Sprachmittler.xcodeproj (generated, git-ignored)
├── Makefile · scripts/ # bootstrap, verify, privacy-check, capture-fixtures, smoke-ollama, manifest
├── App/ # macOS app target (SwiftUI + AppKit glue only)
│ ├── SprachmittlerApp.swift
│ ├── AppDelegate.swift # composition root, Services provider, watcher lifecycle
│ ├── MenuBar/ # status item menu
│ ├── Panel/ # non-activating floating panel and view model
│ ├── Settings/ # General, Model, Translation, Privacy, Diagnostics
│ ├── Onboarding/ # Ollama, model, target language, optional Accessibility
│ ├── Info.plist # LSUIElement, NSServices, ATS local networking
│ └── Sprachmittler.entitlements
├── Packages/SprachmittlerKit/
│ ├── Package.swift
│ ├── Sources/
│ │ ├── SprachmittlerText/ # detection, chunking, protected tokens, normalisation
│ │ ├── SprachmittlerOllama/ # HTTP client, catalog, streaming chat
│ │ ├── SprachmittlerEngines/ # Hy-MT3 prompts, language names, options, validators
│ │ ├── SprachmittlerCore/ # domain, settings, session, error taxonomy, protocols
│ │ ├── SprachmittlerCapture/ # double-copy watcher, pasteboard, Accessibility insertion
│ │ ├── SprachmittlerEval/ # corpus, metrics, reports (CLI only)
│ │ ├── SprachmittlerTestSupport/# fakes shared by tests
│ │ └── sprachmittler-cli/ # languages, models, show, detect, translate, eval
│ └── Tests/
│ ├── SprachmittlerTextTests/ # + Fixtures/ (synthetic EN/DE/Markdown/placeholder texts)
│ ├── SprachmittlerOllamaTests/ # URLProtocol stubs + Fixtures/ (recorded by scripts/capture-fixtures.sh)
│ ├── SprachmittlerEnginesTests/ # prompt golden files, language mapping, options
│ ├── SprachmittlerCoreTests/
│ ├── SprachmittlerCaptureTests/
│ ├── SprachmittlerEvalTests/
│ └── SprachmittlerLiveTests/ # opt-in, real Ollama (SPRACHMITTLER_LIVE=1)
├── evaluation/ # corpus manifest schema + example; corpus/ and results/ are git-ignored
└── docs/
```
The local package lives in a subfolder rather than the repository root, so Xcode does not treat the whole repository as a package when it opens the generated project.
---
## 4. Module structure and dependency rules
```mermaid
flowchart TD
App --> Core
App --> Capture
CLI[sprachmittler-cli] --> Core
CLI --> Eval
CLI --> Ollama
CLI --> Engines
Eval --> Core
Core --> Text
Core --> Ollama
Core --> Engines
Engines --> Text
Engines --> Ollama
Capture --> Core
```
- **Leaf modules** `SprachmittlerText` and `SprachmittlerOllama` must not depend on each other or on any other package module.
- `SprachmittlerText` is pure Foundation plus `NaturalLanguage`. No AppKit, no networking.
- `SprachmittlerOllama` is the only module that uses `URLSession`.
- `SprachmittlerEngines` is the only module that knows model names, tags, prompts, language names and output dialects. It depends on `SprachmittlerOllama` (request types) and `SprachmittlerText` (chunk and token types).
- `SprachmittlerCore` composes everything through **protocols** so each part can be faked in tests. It contains no model-specific branches and no AppKit.
- `SprachmittlerCapture` is the only module that imports `ApplicationServices`/`Accessibility` and touches `NSPasteboard`. It depends on `SprachmittlerCore` for domain types and protocols.
- `SprachmittlerEval` is linked into the CLI only, never into the app. It may use the leaf `SprachmittlerText`, `SprachmittlerEngines` and `SprachmittlerOllama` types for metrics and pipeline construction; it does not add an app dependency.
- `sprachmittler-cli` links `SprachmittlerOllama` and `SprachmittlerEngines` directly for the M1 commands; it is never linked into the app.
- `SprachmittlerTestSupport` is test-only and depends on `SprachmittlerCore`, `SprachmittlerCapture` and `SprachmittlerOllama`; it is never linked into the app.
- The `App` target holds no business logic. Anything with a branch worth testing belongs in a package module.
### Third-party dependencies
| Package | Purpose | Note |
|---|---|---|
| `apple/swift-argument-parser` | `sprachmittler-cli` argument parsing (CLI target only) | Never linked into the app. |
All other functionality uses Apple frameworks. No keyboard-shortcut library is needed: the trigger is the double-copy pasteboard gesture. Adding a dependency requires an ADR and user approval.
---
## 5. Core domain model
```swift
// SprachmittlerCore
// Defined in SprachmittlerEngines; re-exported by SprachmittlerCore.
public typealias LanguageCode = String // "de", "en", "zh-Hant", "pt-BR", "kk-Cyrl"
public struct ModelLanguage: Hashable, Codable, Sendable, Identifiable {
public let code: LanguageCode
public let modelName: String // exact English name from the model card, e.g. "German"
public let displayName: String // English fallback; localizedDisplayName for UI
public let isRTL: Bool
public let usesDenseScript: Bool
public var id: String { code }
}
public typealias TargetLanguage = ModelLanguage
public struct CapturedText: Sendable, Equatable {
public let text: String
public let capturedAt: Date
public let source: CaptureSource // .doubleCopy, .services, .menu
}
public enum CaptureSource: String, Sendable, Codable {
case doubleCopy, services, menu
}
public struct TranslationRequest: Sendable, Equatable {
public let id: UUID
public let text: String
public let target: TargetLanguage
public let model: String // opaque to Core, e.g. "hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M"
public let sourceLanguageHint: LanguageCode?
}
public struct TranslationChunk: Sendable, Equatable {
public let index: Int
public let text: String
public let separatorAfter: String // "\n\n", "\n" or ""
}
public struct TranslationResult: Sendable, Equatable {
public let id: UUID
public let sourceText: String
public let translation: String
public let target: TargetLanguage
public let model: String
public let warnings: [TranslationWarning]
public let timing: TranslationTiming
public let createdAt: Date
}
public enum TranslationWarning: Sendable, Equatable {
case preambleDetected(firstLine: String)
case truncated
case repetitionLoop
case missingProtectedToken(String)
case emptyOutput
case sameLanguage(source: String, target: String)
case numericMismatch
case chunkFailed(index: Int)
}
public struct TranslationTiming: Sendable, Equatable {
public let firstTokenMs: Int?
public let totalMs: Int
public let promptTokens: Int?
public let outputTokens: Int?
}
public enum InsertionOutcome: Sendable, Equatable {
case replaced(using: InsertionMethod) // .accessibility, .paste
case copiedOnly
case failed(SprachmittlerError)
}
public enum InsertionMethod: String, Sendable {
case accessibility, paste
}
```
Language and warning value types live in `SprachmittlerEngines`, because they carry model-card names and validation results: `ModelLanguage` (re-exported as `TargetLanguage`) and `TranslationWarning`. `SprachmittlerCore` re-exports both for the session and UI. `TranslationPipeline` in Core owns chunk orchestration, the one documented retry and timing.
### Error taxonomy
```swift
public enum SprachmittlerError: Error, Sendable, Equatable {
// Capture
case noSelection
case emptyText
case textTooLong(characters: Int, limit: Int)
case pasteboardUnavailable
// Translation
case ollamaUnreachable(url: URL)
case ollamaTooOld(found: String, required: String)
case endpointRejected(reason: EndpointRejection)
case modelNotInstalled(model: String)
case noAdapter(model: String)
case badRequest(message: String)
case server(status: Int, message: String)
case timeout(phase: TimeoutPhase) // connect, firstToken, idle, total
case emptyOutput
case truncated
case repetitionLoop
case preambleDetected
case protectedTokenLost(token: String)
// Insertion
case accessibilityNotTrusted
case accessibilityUnsupported(app: String?)
case insertionTargetChanged
case pasteboardRestoreFailed
// General
case cancelled
}
```
Each error has a `userMessage` and an optional `recoveryAction` (e.g. "Start Ollama", "Copy `ollama pull …`", "Open System Settings", "Copy the translation instead", "Shorten the selection"). The UI shows only these strings and never raw `localizedDescription`.
---
## 6. Runtime flow
### 6.1 Double copy → translate → panel → Copy or Replace
```mermaid
sequenceDiagram
autonumber
actor U as User
participant Src as Source app
participant W as DoubleCopyWatcher
participant S as TranslationSession
participant A as HyMT3Adapter
participant O as OllamaChatClient
participant V as OutputValidator
participant P as PanelController
participant I as InsertionCoordinator
U->>Src: select text
U->>Src: ⌘C twice
Src-->>W: two pasteboard changes within 500 ms, same text
W-->>S: CapturedText(source: .doubleCopy)
S->>P: show panel (source preview, "Translating…")
S->>A: makeRequest(text, target, model)
A->>O: POST /api/chat (stream)
O-->>S: deltas
S->>P: append streaming translation
O-->>S: done(reason, metrics)
S->>V: validate translation + protected tokens
V-->>S: warnings
S->>P: show translation, enable Copy/Replace if safe
U->>P: click Replace
P->>I: replace(selection, translation, targetApp)
I-->>U: AX set or ⌘V fallback; clipboard restored
```
### 6.2 Rules
1. **One translation in flight.** A new trigger cancels the previous request and replaces the panel content. Results tagged with an old epoch are discarded.
2. **Read the pasteboard only after a change.** The watcher polls `changeCount`; it reads the string only when the count changes, and keeps at most the last two strings in memory.
3. **Never translate our own clipboard writes.** Writes performed by Copy or Replace carry a custom marker and a suppression window.
4. **Never auto-insert.** Replace is a user action. The panel never sends ⌘V or sets AX text on its own.
5. **Keep the prompt prefix stable.** The prefix depends only on the target language. Do not add timestamps, app names, source language or dynamic instructions.
6. **Validate before enabling Replace.** Truncated, looping, empty, preamble-flagged or token-losing output keeps Replace disabled by default and shows the reason.
7. **Chunk before the context limit.** Preserve paragraph boundaries and join with the original separators.
8. **Cancel propagates to URLSession** and stops the stream promptly.
9. **No Accessibility prompt on the trigger path.** `AXIsProcessTrustedWithOptions` is called only from onboarding or when the user clicks Replace.
10. **The panel is non-activating.** It never calls `NSApp.activate` or `makeKeyAndOrderFront`.
---
## 7. Capture and insertion
Full detail: `docs/SELECTION_AND_CLIPBOARD.md`.
### 7.1 Double-copy watcher (`SprachmittlerCapture`)
```swift
@MainActor public protocol PasteboardAccessing: AnyObject {
var changeCount: Int { get }
func string() -> String?
func containsOwnWriteMarkers() -> Bool
func snapshot() -> ClipboardSnapshot?
func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches: Int) -> Bool
@discardableResult func write(_ text: String) -> Int
}
public struct DoubleCopyDetector { /* pure state machine */ }
@MainActor public final class PasteboardWatcher {
init(pasteboard: any PasteboardAccessing,
ticker: any PasteboardTicking = TimerPasteboardTicker())
func start(onEvent: @escaping @MainActor (PasteboardWatcherEvent) -> Void)
func stop()
func clear()
func noteOwnWrite(at: Date)
}
```
- 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 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`.
### 7.2 Services entry point
Info.plist declares `NSServices` with `NSMessage = translateSelection` and `NSSendTypes = public.utf8-plain-text`. `AppDelegate` sets `NSApp.servicesProvider` to a `ServicesProvider` in `SprachmittlerCapture`. This path needs no Accessibility permission and no pasteboard polling. It is the fallback for apps that do not expose copy properly.
### 7.3 Replacement (`SprachmittlerCapture`)
```swift
public protocol TextInserting: Sendable {
func replace(selection: CapturedText, with translation: String,
target: InsertionTarget) async throws -> InsertionOutcome
}
```
Strategy order:
1. **Accessibility direct replacement** (preferred): get the focused element, verify its `kAXSelectedTextAttribute` still equals the source, then set `kAXSelectedTextAttribute` to the translation. No clipboard mutation.
2. **Synthetic paste fallback**: snapshot the full pasteboard (all items and types), write the translation with a transient marker, post ⌘V with `CGEvent.postToPid`, wait for the paste, then restore the snapshot if the pasteboard still contains our write and no other app changed it.
Safety rules:
- The source app must still be frontmost (`NSWorkspace.shared.frontmostApplication?.processIdentifier == target.pid`) or the insertion must be addressed to the original PID only after explicit confirmation.
- If Accessibility is available, verify the selected text is unchanged; otherwise abort with `insertionTargetChanged`.
- Never replace in secure input fields, password fields or apps that report no settable selection.
- The replacement is one undoable operation in apps that support undo; document that this is app-dependent.
- If both strategies fail, keep the panel open, show the reason and offer Copy.
### 7.4 Permissions
| Permission | Needed for | Requested when |
|---|---|---|
| Accessibility | Replace (AX direct set or synthetic ⌘V) | Only when the user clicks Replace, or from onboarding if they choose to enable it |
| Input Monitoring | Nothing | Never |
| Screen Recording | Nothing | Never |
| Camera / Microphone | Nothing | Never |
| Apple Events | Nothing | Never |
Double copy, translation, Copy and Services work with **no** permission.
---
## 8. Ollama integration
Full contract: `docs/OLLAMA_TRANSLATION_API.md`.
### 8.1 Client (`SprachmittlerOllama`)
```swift
public protocol OllamaCatalog: Sendable {
func serverVersion() async throws -> String
func installedModels() async throws -> [InstalledModel]
func show(model: String) async throws -> ModelDetails
func loadedModels() async throws -> [LoadedModel]
func refresh() async
func checkMinimumVersion() async throws
}
public protocol OllamaChatting: Sendable {
func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error>
}
public enum ChatEvent: Sendable, Equatable {
case delta(String)
case done(reason: String?, metrics: ChatMetrics)
}
```
Implementation rules:
- `URLSession` with an **ephemeral** configuration, no cookies, no URL cache, no credential storage, and a delegate that **refuses redirects**.
- `URLSession.bytes(for:)` and line-by-line NDJSON decoding; carry partial lines across chunks.
- Cancellation: cancelling the consuming task cancels the URL task (`onTermination` → `task.cancel()`).
- Timeouts per phase, injectable: connect and first token 120 s (includes cold model load; `URLSession` has no separate connect hook); idle 20 s; total per chunk 180 s.
- No `system` message, no `images`, no `think` (the model reports only `completion`). Send exactly one user message with the prompt.
- `keep_alive` comes from settings (`30m` default; `0` unloads after the request).
- `/api/show` results are cached per model digest for the app lifetime and invalidated on "Refresh models".
### 8.2 Sampling and context
| Publisher setting | Ollama option | Value |
|---|---|---|
| `temperature` | `temperature` | 0.7 (evaluate 0.2 in M7) |
| `top_p` | `top_p` | 0.6 |
| `top_k` | `top_k` | 20 |
| `repetition_penalty` | `repeat_penalty` | 1.05 |
| `max_tokens` | `num_predict` | 4096 |
| `max_context` | `num_ctx` | 8192 |
Set `num_ctx` explicitly. The GGUF metadata reports a large base context (262144), but the model card documents 8192 for translation; the smaller value is the memory-safe choice.
### 8.3 Failure detection
The `TranslationGuard` runs on the delta stream and the final output:
| Check | Rule | Result |
|---|---|---|
| Empty | Final output after trimming is empty | `failed(emptyOutput)` |
| Truncated | `done_reason == "length"` | warning `truncated`; Replace disabled by default |
| Repetition loop | Same normalised line (≥ 8 chars) repeats ≥ 6 times, or a 64-char window repeats ≥ 8 times in the last 2048 chars | cancel stream, warning `repetitionLoop` |
| Preamble | A short first line ending in `:` followed by a blank line and more text | warning `preambleDetected`; Replace disabled by default |
| Protected token lost | Any URL, e-mail, placeholder or code span from the source is missing | warning `missingProtectedToken`; retry once with the documented Delimiters prompt, then disable Replace |
| Numeric mismatch | A normalised numeric token from the source is absent | warning `numericMismatch`; user reviews |
| Transport | Connection, timeout or 5xx before any delta | retry once; then error |
Thresholds are constants in one file and covered by tests. Quality failures are never retried automatically except the documented delimiter retry.
---
## 9. Translation pipeline
Full detail: `docs/TRANSLATION_OUTPUT.md`.
`TranslationPipeline` in `SprachmittlerCore` is the shared implementation used by the CLI and the M4 session: it normalises input, detects the language, classifies content, scans protected tokens, chunks, calls the adapter, joins chunk results with the original separators, validates once, and enforces the single documented retry.
### 9.1 Input analysis (`SprachmittlerText`)
1. Normalise line endings to `\n`; strip NUL and other C0 controls except `\t` and `\n`; NFC.
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 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`)
| Content | Prompt |
|---|---|
| Plain prose | Documented **Default Translation** |
| Markdown / JSON / HTML | Documented **Default Translation** first; **Structured Data 1** is the single fallback after a lost token |
| Placeholder- or delimiter-heavy | Documented **Default Translation** first; **Delimiters** is the single fallback after a lost token |
| User glossary (future) | Documented **Terminology** |
| User style (future) | Documented **Style** |
v1 defaults to the Default Translation template for all text. It handles light Markdown, JSON and URLs well; validation catches the rest. The other templates are documented fallbacks, selected only by the policy above, never invented.
### 9.3 Output rules T1–T4
| Rule | Transformation | Default |
|---|---|---|
| T1 | Strip leading/trailing whitespace and NUL; normalise line endings to `\n`. | on |
| T2 | Preserve internal whitespace, line breaks, Markdown, HTML, LaTeX and code exactly as the model produced them. | always |
| T3 | No spelling, grammar, style or terminology edits. No de-duplication. No "cleanup" of model wording. | always |
| T4 | Do not silently strip a preamble or explanation. Detect it, show a warning, keep the raw text, and disable Replace by default. | always |
The exact model output is what the user sees and what Copy/Replace use after T1. There is no hidden rewrite.
### 9.4 Same-language handling
If the detected source language equals the target with reasonable confidence, the panel shows "This text already appears to be in German" and still offers Translate anyway. Do not silently skip: short or mixed text is often misdetected.
---
## 10. Translation session and state machine
`TranslationSession` is an actor in `SprachmittlerCore`; `PanelViewModel` is `@MainActor @Observable` in Core and mirrors it. The App target owns the non-activating `NSPanel` controller.
```mermaid
stateDiagram-v2
[*] --> idle
idle --> capturing: double copy / Services / menu
capturing --> translating: text captured
capturing --> idle: empty / too long
translating --> streaming: first delta
translating --> failed: transport / model error
streaming --> ready: done + validated
streaming --> failed: empty / loop / timeout
ready --> inserting: Replace clicked
inserting --> done: replaced
inserting --> ready: insertion failed (panel stays open)
ready --> done: Copy clicked / panel closed
failed --> idle: dismissed
translating --> idle: cancelled by new trigger / Esc
streaming --> idle: cancelled by new trigger / Esc
```
- Every session has an epoch (`UInt64`). A new trigger increments it; events from an older epoch are ignored.
- `Copy` never changes the session state; it writes the clipboard and keeps the panel open.
- `Replace` is disabled while `.translating` or `.failed`, and when validation found a blocking warning.
- The session owns no disk state. Its working copy is released when the panel closes; `AppEnvironment` may keep the last source, translation and insertion target in memory until quit, solely for the status menu's Copy/Replace Last actions (ADR-007). Nothing is written to disk.
---
## 11. User interface
| Surface | Implementation | Contents |
|---|---|---|
| Status item | `MenuBarExtra` | Translate clipboard text, Target language submenu, Copy last translation, Replace last translation (if safe), Settings, Set up Sprachmittler, Diagnostics, Quit |
| Panel | `NSPanel` with `.nonactivatingPanel`, `becomesKeyOnlyIfNeeded = false` | Header (source → target, language picker, gear), collapsible source preview, streaming translation (Markdown rendered when detected), warnings, Copy (left) and **Replace** (right, primary) |
| Settings | SwiftUI `Settings` scene | General, Model, Translation, Privacy, Diagnostics |
| Onboarding | `NSWindow` (not a SwiftUI `Window` scene) | Ollama reachable + version, Hy-MT3 installed, target language, optional Accessibility for Replace; each with a fix button |
| Diagnostics | Window from the menu | Server version, model digests, last 50 timings and error kinds; copy as text; no text or translations |
The saved target is the **mother tongue** and the default target for every source. Optional source-language to target-language rules override it when the source is confidently detected; otherwise the mother tongue is used. The mother tongue and the effective target are separate: the header and language picker show the effective target, a banner explains a rule-driven direction and offers a one-capture override back to the mother tongue, and the panel picker is a session-only override. Persistent rules live in Settings. Detection remains advisory and uses the same high-confidence rule as the same-language advisory.
Panel keyboard: **Esc** close, **⌘C** copy translation, **⌘↩** Replace, **⌘R** retry, **⌘,** Settings. The panel is made key when shown (unless the setting is off) so Esc and the shortcuts work without a click; the app is still not activated, the source app remains frontmost and owns the menu bar, and clicking the source app takes keyboard focus back. A click sent to another app dismisses the panel; while the panel is visible a transient mouse-down monitor observes only that the click went to another app, discards the event and is removed on close. While the panel is key it receives keystrokes, so a user who types immediately after triggering should disable the Esc-on-show setting. The whole header bar (full width, flush with the top edge) moves the panel; the drag view moves the window itself from the screen-space mouse delta because `performDrag` does nothing while the app is inactive; moving it keeps its position while it stays open, and a newly shown panel is placed near the cursor (DeepL-like transient position). The translation text size is a Settings value.
Accessibility: every control has an `accessibilityLabel`; the panel exposes source and translation as read-only text elements; full keyboard navigation; respects Reduce Motion and Increase Contrast.
---
## 12. Configuration
`AppSettings` (Codable, stored in `UserDefaults` under one key, versioned):
| Key | Type | Default |
|---|---|---|
| `endpoint` | URL | `http://127.0.0.1:11434` |
| `allowRemoteEndpoint` | Bool | false |
| `model` | String | `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` (provisional until T7.4) |
| `fastModel` | String? | `hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M` (if installed) |
| `targetLanguage` | LanguageCode | system language if supported, else `en` |
| `recentTargetLanguages` | [String] | last three targets, most recent first |
| `doubleCopyWindowMs` | Int | 500 (300–1000) |
| `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 |
| `topP` | Double | 0.6 |
| `topK` | Int | 20 |
| `repeatPenalty` | Double | 1.05 |
| `keepModelLoaded` | String | `30m` (`5m`, `30m`, `1h`, `0`) |
| `warmUpOnLaunch` | Bool | true (local endpoint only) |
| `promptVariantPolicy` | `.defaultOnly` / `.contentAware` | `.defaultOnly` until M7 |
| `autoCopy` | Bool | **false** (never copy automatically) |
| `showSourcePreview` | Bool | true |
| `translationFontSize` | Int | 17 pt (12–28) |
| `languageRoutes` | [LanguageRoute] | `[]` (everything translates into the mother tongue unless a rule matches) |
| `renderMarkdown` | Bool | true (presentation only; raw text is copied and replaced) |
| `closeWithEscape` | Bool | true (make the panel key on show; no app activation) |
| `launchAtLogin` | Bool | false |
| `keepRecentTranslationInMemory` | Bool | true (cleared on quit; no disk) |
| `hasCompletedOnboarding` | Bool | false |
| `settingsVersion` | Int | 1 |
Never store source text, translations, pasteboard contents or app names in settings.
---
## 13. Build, distribution and platform
| Item | Decision |
|---|---|
| Minimum OS | macOS 14.0 (Sonoma) — `@Observable`, `Settings` scene, modern SwiftUI |
| Architecture | arm64 only |
| Toolchain | Xcode 16+ / Swift 6 language mode, strict concurrency |
| Project generation | XcodeGen from `project.yml`; `.xcodeproj` is generated and git-ignored |
| App type | Menu-bar agent (`LSUIElement = YES`), no Dock icon |
| Sandbox | **Off** (ADR-003): Accessibility replacement. Hardened Runtime **on**, no exceptions |
| Signing | Development: "Sign to Run Locally". Release: Developer ID + notarisation |
| ATS | `NSAllowsLocalNetworking = YES`; remote endpoints must be HTTPS |
| Distribution | Signed, notarised DMG; local `make dmg` for testing; Mac App Store not in v1 |
`make install` copies the app to `/Applications` and ad-hoc signs it. macOS ties Accessibility permission to the app's signature and location; after a reinstall the user may have to remove and re-add the app in System Settings.
---
## 14. Performance budgets
These targets are validated on named hardware. Translation speed depends on the model and the Mac; it is measured, not promised.
| Metric | Budget | How measured |
|---|---|---|
| Second copy → session start | ≤ 150 ms | signpost `capture` |
| Panel visible | ≤ 250 ms after trigger | signpost `panel` |
| First translation token (warm 7B) | ≤ 1.5 s | signpost `firstToken` |
| 250 output tokens (warm 7B) | ≤ 8 s on an M-series Pro | CLI bench / reference run |
| Copy to clipboard | ≤ 100 ms | signpost `copy` |
| Replace (AX direct) | ≤ 300 ms after click | signpost `insert` |
| Idle CPU | < 0.5% (120 ms pasteboard poll) | Activity Monitor / `powermetrics` |
| Idle memory (app, excluding Ollama) | ≤ 90 MB | `footprint` |
| Main-thread hang | none > 100 ms | Instruments Hangs |
| Model resident memory (7B, 8K context) | about 6.5 GB | `ollama ps` |
---
## 15. Observability
- `os.Logger` subsystem = bundle ID; categories: `capture`, `pasteboard`, `session`, `ollama`, `engine`, `validate`, `insert`, `panel`, `settings`.
- Never log selected text, translations, prompt text, pasteboard strings, app names or paths without `privacy: .private`; prefer counts, lengths, short hashes, timings and error kinds.
- `os_signpost` intervals: `capture`, `panel`, `request`, `firstToken`, `translate`, `validate`, `copy`, `insert`.
- Diagnostics shows server version, model names/digests, memory, last 50 timings and error kinds. It never stores text.
---
## 16. Risks and mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| Double-copy false positives (two different copies) | Translates the wrong text | Require identical text within 500 ms; ignore own writes; 750 ms suppression |
| Apps that copy the current line on empty selection | Translates text the user did not select | Document; do not fall back to AX; user can clear the clipboard |
| Pasteboard privacy prompts on newer macOS | Trigger friction | Test on the target OS; the app reads only after a change; document the system prompt |
| Accessibility replacement rejected by Electron/canvas apps | Replace fails | AX first, ⌘V fallback, clear error and Copy fallback |
| Clipboard restore races with clipboard managers | User loses clipboard | Snapshot all items; restore only if changeCount still ours; transient/concealed markers |
| 7B latency on smaller Macs | Sluggish UX | Stream; keep warm; offer 1.8B Fast preset; evaluate |
| Translation quality varies with temperature | Inconsistent output | Publisher defaults; evaluate 0.2; show warnings, never rewrite |
| Prompt drift breaks cache and quality | Slower, different output | Prompt literals only in Engines; byte-exact tests; stable prefix |
| Long text exceeds context | Truncation | Chunk before sending; `done_reason: length` warning; Replace disabled |
| Model adds explanations | Bad insertion | Preamble detection; warning; Replace disabled by default |
| Non-sandboxed app | Wider capability | Hardened runtime, privacy invariants, no file watching, no telemetry, notarisation |
| Model licence changes | Distribution risk | Show licence and digest; re-check before release; no bundled weights |
---
## 17. Glossary
| Term | Meaning |
|---|---|
| Double copy | Pressing ⌘C twice within the configured window; the trigger. |
| Panel | The non-activating floating window that shows the translation. |
| Replace | The explicit user action that replaces the selection with the translation. |
| Prefix | The part of the prompt before the source text; stable for prompt caching. |
| Chunk | A piece of a long selection translated in one request. |
| Protected token | A URL, e-mail, placeholder or code span that must survive translation. |
| Preamble | A model-added explanation such as "Here is the translation:" before the actual translation. |
| Epoch | Counter used to discard stale results after cancel or a new trigger. |
| Warm-up | A fixed synthetic request that loads the model at launch. |
| Default-model gate | The rule that the 7B/1.8B default is decided by the M7 evaluation, not by assumption. |