chore: Sprachmittler OpenCode starter kit

This commit is contained in:
schihei committed 2026-11-26 11:59:38 +01:00
commit 374085ec2f
94 files changed
+4563

No files matched your search

+652
View File
@@ -0,0 +1,652 @@
# 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
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.
- 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
public struct LanguageCode: RawRepresentable, Hashable, Codable, Sendable {
public let rawValue: String // "de", "en", "zh-Hant", "pt-BR", "kk-Cyrl"
}
public struct TargetLanguage: 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 // localised UI name
public var id: String { code.rawValue }
}
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(line: String)
case truncated
case repetitionLoop
case missingProtectedToken(String)
case emptyOutput
case sameLanguage(source: LanguageCode, target: LanguageCode)
case chunkFailed(index: Int)
case numericMismatch
}
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(by: InsertionMethod) // .accessibility, .paste
case copiedOnly
case failed(SprachmittlerError)
}
public enum InsertionMethod: String, Sendable {
case accessibility, paste
}
```
### 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
public protocol PasteboardWatching: Sendable {
func events() -> AsyncStream<PasteboardEvent>
}
public enum PasteboardEvent: Sendable, Equatable {
case changed(changeCount: Int)
case textAvailable(String)
case ignoredOwnWrite
}
```
- Poll `NSPasteboard.general.changeCount` on a `@MainActor` timer every **120 ms**.
- 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).
- 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]
}
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 3 s; first token 120 s (includes cold model load); 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`.
### 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 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.
### 9.2 Prompt selection (`SprachmittlerEngines`)
| Content | Prompt |
|---|---|
| Plain prose | Documented **Default Translation** |
| Markdown / JSON / HTML | Documented **Structured Data 1** with `format_type` |
| Placeholder- or delimiter-heavy | Documented **Delimiters** |
| 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` and mirrors it.
```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. It releases source and translation when the panel closes.
---
## 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 = true` | Header (source → target, language picker, gear), collapsible source preview, streaming translation, 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 |
Panel keyboard: **Esc** close, **⌘C** copy translation, **⌘↩** Replace, **⌘R** retry, **⌘,** Settings. The panel becomes key only when clicked; the source app keeps focus until then.
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` |
| `doubleCopyWindowMs` | Int | 500 (300–1000) |
| `maxCharactersLatin` | Int | 4000 |
| `maxCharactersCJK` | Int | 2000 |
| `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 |
| `launchAtLogin` | Bool | false |
| `keepRecentTranslationInMemory` | Bool | true (cleared on quit; no disk) |
| `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; 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. |
+54
View File
@@ -0,0 +1,54 @@
# Coding standards
## Language and concurrency
- Swift 6 language mode, **complete** strict concurrency. Zero warnings policy: warnings are errors in Release.
- Model shared mutable state as an `actor` (`TranslationSession`, `SettingsStore`). UI-facing types are `@MainActor`.
- No `DispatchQueue.main.async` in new code. Use `@MainActor` / `MainActor.run`.
- `NSPasteboard` access is `@MainActor` only. Accessibility calls run on a dedicated serial queue wrapped in an async function; `AXUIElement` values never cross task boundaries as mutable state.
- No `@unchecked Sendable` without a comment explaining the invariant.
- Never block an actor or the main actor on networking, Accessibility calls or pasteboard snapshots. Every network call is async and cancellable.
- Respect cancellation: `try Task.checkCancellation()` in chunk loops, validation and insertion.
## Structure
- One primary type per file. The file name matches the type.
- Protocols at module boundaries (`OllamaCatalog`, `OllamaChatting`, `TranslationAdapter`, `PasteboardWatching`, `TextInserting`, `ClipboardSnapshotting`, `FileSystem`). Concrete types are `final class`, `struct` or `actor`.
- The composition root (`AppEnvironment` in the app, `CLIEnvironment` in the CLI) is the only place that instantiates concrete implementations.
- No singletons except Apple-provided ones (`FileManager.default`, `NSPasteboard.general`, `NSWorkspace.shared`); wrap them behind protocols where tests need them.
- `public` only for API used across modules.
- Model names, tags, prompts and language names only in `SprachmittlerEngines` (lint rule `no_prompt_literals_outside_engines`).
- `NSPasteboard` and Accessibility APIs only in `SprachmittlerCapture` (lint rules).
- `URLSession` / `URLRequest` only in `SprachmittlerOllama` (lint rule).
## Errors and logging
- Throw `SprachmittlerError` across module boundaries. Internal errors may be module-specific, but they are mapped at the boundary.
- `Logger` per category (ARCHITECTURE §15). Never interpolate selected text, translations, pasteboard strings, app names or paths without `privacy: .private`; prefer counts, lengths, short hashes, timings and error kinds.
- `fatalError` / `preconditionFailure` only for programmer errors that tests would catch.
## Files and persistence
- The app writes only settings (`UserDefaults`) and, at release time, the app bundle. It does not write source text or translations anywhere.
- Clipboard snapshots live in memory for one replacement. Restore them with `defer` where possible.
- If a future feature needs a file, all writes are atomic: temporary file in the same directory, then `replaceItemAt` / rename. That feature needs an ADR.
## UI
- SwiftUI for views; AppKit only where SwiftUI lacks support (`MenuBarExtra` menu, `NSPanel`, Services, Accessibility).
- Views have no logic beyond formatting. They bind to `PanelViewModel`, `SettingsViewModel`, `OnboardingViewModel`.
- Every interactive control has an `accessibilityLabel` and a keyboard path.
- Strings: `String(localized:)` from the start. English is the base, German (`de`) follows in M8.
- Never show raw model text as an error message; show `userMessage`.
- The translation panel never calls `NSApp.activate` or `makeKeyAndOrderFront`.
## Style
- SwiftFormat default rules with 4-space indent and 120-column limit (`.swiftformat`).
- SwiftLint with `.swiftlint.yml`. Warnings are fixed, not suppressed. A disable requires a reason comment.
- Doc comments (`///`) on all public API.
## Git
- Small commits; conventional commit messages, e.g. `feat(engines): Hy-MT3 request encoding (T2.2)`.
- Never commit `Sprachmittler.xcodeproj`, `.build/`, `DerivedData/`, `evaluation/corpus/`, `evaluation/results/*` or any private text.
+110
View File
@@ -0,0 +1,110 @@
# 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.
+179
View File
@@ -0,0 +1,179 @@
# Hy-MT3 model and adapter
Status: Draft v1.0, researched 2026-11-26. Model cards and conversions change; re-check tags, sizes and licences before T2.7 and before any release. Everything here is guidance for adapters, Settings hints and the evaluation. **Never hard-code this list as "available" in the app**; discover installed models at runtime.
Sources: [Hy-MT3-7B-GGUF](https://huggingface.co/tencent/Hy-MT3-7B-GGUF), [Hy-MT3-1.8B-GGUF](https://huggingface.co/tencent/Hy-MT3-1.8B-GGUF), [Hy-MT3 GitHub](https://github.com/Tencent-Hunyuan/Hy-MT3), [Hy-MT3 report](https://arxiv.org/pdf/2611.27673).
## 1. Family and tags
| Model | Role | Tag | Size | Notes |
|---|---|---|---|---|
| Hy-MT3-7B | **Default (provisional)** | `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` | 5.15 GB download; about 6.5 GB resident with 8K context | 7.5B parameters, `hunyuan-dense`, Q4_K_M |
| Hy-MT3-1.8B | **Fast preset** | `hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M` | 1.35 GB download | 2B-class, Q4_K_M; **VERIFY** on your Ollama |
| Hy-MT3-30B-A3B | Quality, not a preset | `hf.co/tencent/Hy-MT3-30B-A3B-GGUF:*` | far above 16 GB | MoE, 3B active; hidden unless installed |
- Licence: **Apache-2.0** per the Hugging Face model cards. `/api/show` reports `license: null` for the GGUF, so show the model-card licence in Settings, not the Ollama field.
- 102 supported languages. See `docs/LANGUAGES.md` for the exact model names.
- The model has **no default system prompt**. Do not send one.
- `/api/show` capabilities: `["completion"]`. No vision, no thinking. Do not send `images` or `think`.
- Chat template (verified): `{{ if .System }}<|startoftext|>{{ .System }}<|extra_4|>{{ end }}{{ if .Prompt }}<|startoftext|>{{ .Prompt }}<|extra_0|>{{ end }}{{ .Response }}<|eos|>`.
- Model card max context: **8192**. GGUF metadata reports `context_length = 262144`; that is the base model metadata, not the documented translation context. Set `num_ctx: 8192`.
## 2. Sampling
Publisher recommendation for 1.8B and 7B:
```json
{
"temperature": 0.7,
"top_p": 0.6,
"top_k": 20,
"repetition_penalty": 1.05,
"max_tokens": 4096
}
```
In Ollama:
| Ollama option | Value |
|---|---|
| `temperature` | 0.7 |
| `top_p` | 0.6 |
| `top_k` | 20 |
| `repeat_penalty` | 1.05 |
| `num_predict` | 4096 |
| `num_ctx` | 8192 |
`/api/show` reports only stop tokens, no sampling defaults, so the adapter must set these explicitly. The M7 evaluation compares temperature 0.7 with 0.2; a translation app may prefer lower variance, but the publisher default is the starting point.
## 3. The canonical default prompt
This is the only default in v1. It is byte-exact: keep the bold markers, the period after the target language, the colon and the blank line.
```text
Translate the following text into {target_lang}. Note that you should **only output the translated result without any additional explanation**:
{source_text}
```
- `{target_lang}` is the exact full English name from the model card (`German`, `Chinese`, `Traditional Chinese`, `Portuguese`, `Norwegian Nynorsk`, `Cyrillic Kazakh`, …).
- No source-language field, no system message, no timestamp, no app name.
- The prefix depends only on `{target_lang}`; append `{source_text}` last. This preserves Ollama's prompt-prefix cache.
- The owner's reference run reported **177/178 prompt tokens cached**; our run reported 178 prompt tokens, 246 output tokens, 44.6 tok/s, 6.52 s total on an M5 Pro 48 GB.
## 4. Other documented templates
These are the only allowed alternatives (ADR-012). v1 defaults to the template above for everything; the others are fallbacks selected by content class or validation.
### Terminology (future glossary)
```text
*Reference the following translations:*
{source_term} translates to {target_term}
{source_term} translates to {target_term}
Translate the following text into {target_lang}. Note that you must **ONLY output the translated result without any additional explanation**:
{source_text}
```
### Style (future style presets)
```text
Please translate the following text into {target_lang}. Note that the translation style must strictly conform to [**{target_style}**]:
{source_text}
```
### Personalization
```text
[Source Text]
{source_text}
[Translation Tasks]
1. **{user_preference}**
2. **{user_preference}**
3. ...
4. Translate the [Source Text] into {target_lang}.
```
### Delimiters (placeholder-heavy text)
```text
Please accurately translate the following text into {target_lang}. You must **retain the exact same number of delimiters in the translation. Strictly do not omit, escape, or translate these symbols, and pay close attention to their placement**.
{source_text}
```
### Structured Data 1 (Markdown, JSON, HTML)
```text
### Task
Translate the user-facing text within the following {format_type} data into {target_lang}.
### Strict Rules
1. **Structure Preservation:** You MUST preserve the original {format_type} data structure, nesting, hierarchy, and indentation exactly as they are.
2. **Selective Translation:** Translate ONLY the visible, user-facing text content/values.
3. **Strict Non-Translation:** NEVER translate or alter code tags, keys, properties, object names, or variable placeholders. Leave them exactly in their original English/code form.
### Source Data
{source_text}
```
### Structured Data 2 (background information)
```text
[Background Information]
{background_text}
Please translate the following text into {target_lang}, taking the provided background information into consideration.
[Source Text]
{source_text}
```
## 5. Content policy for v1
| Source content | Prompt |
|---|---|
| Plain prose, light Markdown, ordinary URLs | **Default** |
| JSON, HTML, Markdown tables, complex nesting | **Structured Data 1** with `format_type` (`JSON`, `HTML`, `Markdown`) |
| Many placeholders/delimiters, or a protected token was lost | **Delimiters** (one retry only) |
| User glossary (future) | **Terminology** |
| User style (future) | **Style** |
The default prompt already preserved a URL, an e-mail, `{{limit}}`, a code span and a JSON object in our checks. Validation is still mandatory; do not assume.
## 6. Known limitations
- **Literal compounds.** Technical English sometimes becomes a literal German compound ("thinking tokens" → "Denktokens", "non-thinking mode" → "nicht-denkenden Modus"). A style or terminology prompt may help; do not rewrite silently.
- **Preamble risk.** The model usually follows "only output the translation", but can add an explanation on unusual input. Detect and flag; never strip automatically.
- **Long input.** The card's context is 8192. Chunk before the limit; do not rely on the GGUF metadata's larger base context.
- **Numbers and units.** Locale formatting may change (`1.5` → `1,5`). Validate semantic numeric presence, not the exact string.
- **Code and keys.** The default template handles simple JSON well; use Structured Data 1 for real code or nested data. Never translate identifiers silently.
- **Same-language input.** A German→German request may return the text unchanged or "improved"; detect and warn.
- **No glossary in v1.** Terminology consistency across a document is not guaranteed.
## 7. Compatibility spike results (T2.7)
Fill in from the spike. One row per tag and direction.
| Tag | Digest (first 12) | Ollama | Direction | Works | Notes (quality, preamble, tokens, speed) |
|---|---|---|---|---|---|
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | | 0.40.18 | en→de | ☐ | |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | | 0.40.18 | de→en | ☐ | |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | | 0.40.18 | markdown | ☐ | |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | | 0.40.18 | json | ☐ | |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | | 0.40.18 | placeholders | ☐ | |
| hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M | | | en→de | ☐ | |
| hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M | | | de→en | ☐ | |
## 8. Adding a model
1. Capture fixtures (`make fixtures`) for the new tag.
2. Extend `HyMT3Adapter` only if the model family is still Hy-MT3; a different family needs its own adapter and documented prompts.
3. Bump the adapter `version`.
4. Add it to this document with sources and licence status.
5. Run `/evaluate` on the corpus before offering it as a preset.
+121
View File
@@ -0,0 +1,121 @@
# Implementation plan
Work milestone by milestone, task by task. Each task is sized for one OpenCode session, about 100–400 lines of change. A task is done only when its acceptance criteria pass **and** `make verify` is green. Track status in `docs/PROGRESS.md`.
Conventions: `T<milestone>.<n>`. "AC" = acceptance criteria. "Req" = requirement IDs from `docs/PRD.md` (R001–R050). Every requirement appears in at least one task.
---
## M0 — Scaffold and tooling
Goal: an empty but correctly configured project that builds, tests and launches as a menu-bar app, with OpenCode 2.x configured.
| Task | Description | AC | Req |
|---|---|---|---|
| T0.1 | The kit ships `Packages/SprachmittlerKit/Package.swift` with placeholder sources, tests and synthetic fixtures. Verify it resolves and builds; replace placeholder enums as modules gain real types. | `swift build --package-path Packages/SprachmittlerKit` and `make test` succeed; fixture-loading test passes. | R048 |
| T0.2 | Complete the `App/` sources (stubs shipped): `SprachmittlerApp` with a `MenuBarExtra`, `Settings` scene and quit item; `Info.plist` (`LSUIElement`, `NSServices`, ATS local networking); non-sandboxed entitlements. | `make app` builds; the menu-bar icon appears and no Dock icon is shown; `codesign -d --entitlements -` shows exactly `app-sandbox = false`. | R021, R041, R049 |
| T0.3 | Validate the shipped `project.yml` and `make generate`; set your own bundle ID prefix. | `xcodegen generate` produces a project that builds in Xcode and via `xcodebuild`. | R049 |
| T0.4 | Run the shipped `scripts/verify.sh`, `.swiftformat`, `.swiftlint.yml`; fix issues so the gate is green on the scaffold. Add `os.Logger` categories and an `OSSignposter` wrapper in `SprachmittlerCore`. | `make verify` runs end-to-end; logging helper used in a test. | R033, R050 |
| T0.5 | Run `make doctor`: OpenCode 2.x installed, `opencode.json` parses as native V2, agents/commands/skills discovered, `opencode debug config` shows the permission rules. | `make doctor` green; `/status` works in OpenCode. | R048 |
| T0.6 | Record the environment in `docs/PROGRESS.md`: OpenCode, Ollama, model digest, Mac chip/memory, Xcode/Swift, macOS. Run `make smoke`. | Environment table filled; smoke output recorded. | R013, R047 |
## M1 — Ollama text client
Goal: talk to Ollama, discover Hy-MT3 models and stream a translation headlessly.
| Task | Description | AC | Req |
|---|---|---|---|
| T1.1 | Run `scripts/capture-fixtures.sh` against a local Ollama with the 7B model; commit `SprachmittlerOllamaTests/Fixtures/*`. Resolve VERIFY items in `docs/OLLAMA_TRANSLATION_API.md` and record the digest. | Fixtures exist and are < 200 KB each; doc updated with "Verified against". | R009, R047 |
| T1.2 | `OllamaHTTPClient`: base URL, JSON encode/decode, ephemeral session, redirect refusal, error body parsing, `EndpointPolicy` (SP-5, SP-6). | `EndpointPolicyTests`, `RedirectRefusalTests`, `ErrorMappingTests` green. | R035, R048 |
| T1.3 | `OllamaCatalog`: `/api/version`, `/api/tags`, `/api/show` (capabilities, parameters, template), `/api/ps`; per-digest cache with refresh; version comparison. | Tests: model filter, `name:latest` normalisation, parameter parsing, minimum-version check. | R013, R016 |
| T1.4 | `OllamaChatClient`: streaming NDJSON over `URLSession.bytes`, partial-line carry, `ChatEvent` deltas and done metrics, phase timeouts with injected clock, cancellation propagation, mid-stream error lines. | `URLProtocol` stub tests: split lines, `done_reason` `stop` and `length`, idle timeout, first-token timeout, cancel mid-stream cancels the task. | R009, R019 |
| T1.5 | Warm-up and keep-alive: fixed synthetic sentence, `num_predict: 8`, discard; `keep_alive` from settings; optional unload. | Warm-up never uses user text; request shape tested; local-only rule. | R015, R050 |
| T1.6 | `sprachmittler-cli models`, `show <tag>`, `translate --text/--file --target --model [--json]`. | Prints installed Hy-MT3 models and capabilities; translates a fixture; exit code 3 when Ollama is unreachable. | R046 |
## M2 — Hy-MT3 adapter and text pipeline
Goal: one request shape per model family, documented prompts only, proven against the real model.
| Task | Description | AC | Req |
|---|---|---|---|
| T2.1 | `TranslationAdapter` protocol, `AdapterRegistry`, `SamplingOptions` merge, request encoding. Prompt-literal lint rule active. | Registry tests: Hy-MT3 tag matching, unknown model → no adapter, correct option names. | R010, R013, R014, R015 |
| T2.2 | `HyMT3Adapter`: default prompt byte-exact, 7B/1.8B tags, `num_ctx` 8192, publisher sampling, no system prompt, no `think`. | Golden-file prompt tests; request-encoding tests; no reasoning text stored. | R010, R011, R012, R013, R014, R015 |
| T2.3 | Language catalogue: 102 languages, BCP-47 mapping, exact model English names, localised display names, RTL/script notes. | Catalogue tests: all 102 entries; variants (`zh`/`zh-Hant`, `pt`/`pt-BR`, `nb`/`nn`, `kk`/`kk-Cyrl`, `mn`/`mn-Cyrl`, `ku`/`ckb`); unknown code errors. | R012, R045 |
| T2.4 | `LanguageDetector` (NaturalLanguage) and `Chunker` with script-aware limits and exact join. | Tests: EN/DE detection; paragraph boundaries; CJK limit; no grapheme split; join round-trip. | R016, R017 |
| T2.5 | `ProtectedTokenScanner` (URLs, e-mails, placeholders, code spans, HTML tags, JSON keys) and `OutputValidator` (missing token, preamble, truncation, repetition, numeric mismatch). | Tests: all token kinds; false-positive controls; preamble heuristics; repetition loop cancels. | R018, R019, R020 |
| T2.6 | Prompt policy: default for v1; documented Structured Data 1 and Delimiters fallbacks; one retry when a protected token is lost. | Policy tests: content class → prompt; fallback only on validation failure; no free-form prompt. | R010, R018 |
| T2.7 | **Compatibility spike**: `sprachmittler-cli translate` on EN→DE, DE→EN, Markdown, JSON, URL/placeholder text and a long paragraph. Record quality, timing and prompt-cache behaviour in `docs/HYMT3_MODEL.md` §7. | Table complete; any failure documented with the reason; user confirms before M3. | R009, R010, R018, R047 |
## M3 — Double-copy capture
Goal: turn the ⌘C+C gesture into a reliable `CapturedText` without extra permissions.
| Task | Description | AC | Req |
|---|---|---|---|
| T3.1 | `DoubleCopyDetector`: pure state machine over change events and a clock; 500 ms window, identical text, reset rules. | Tests: two copies, slow copies, different text, empty text, new trigger replaces. | R001, R002, R004 |
| T3.2 | `PasteboardWatcher`: 120 ms main-actor poll, read only on change, own-write suppression, last-two-strings memory, clear on session end. | Component tests with a fake pasteboard; no polling leaks; own writes ignored. | R001, R003, R008 |
| T3.3 | `ClipboardSnapshot`: snapshot all items/types, force lazy data, restore only if `changeCount` unchanged, transient/concealed markers. | Tests: rich text, image, multiple items, changed-by-another-app, restore failure. | R027, R037 |
| T3.4 | Services provider and menu-bar "Translate clipboard text". | Services menu item appears; same panel flow; no AX needed. | R006, R007 |
| T3.5 | **Manual compatibility matrix**: double copy in 10 apps, clipboard managers, empty selection, Universal Clipboard. | Matrix filled in `docs/SELECTION_AND_CLIPBOARD.md`; failures have tasks. | R048 |
## M4 — Translation session and panel
Goal: the DeepL-like panel, without focus theft and without automatic insertion.
| Task | Description | AC | Req |
|---|---|---|---|
| T4.1 | `TranslationSession` actor: one in flight, epochs, cancel/replace, streaming events, chunk orchestration. | Tests: new trigger cancels old; late events dropped; chunk failure surfaces; no second request. | R009, R017, R022 |
| T4.2 | `PanelController` (`NSPanel`, `.nonactivatingPanel`) and `PanelViewModel` (`@MainActor @Observable`). | Manual: source app keeps focus; panel appears near the mouse and is clamped to the screen. | R021 |
| T4.3 | Panel view: header, source preview, streaming translation, warnings, Copy (left), **Replace** (right, primary), Retry, Settings. | Manual: streaming, Copy, disabled Replace while translating, warning styling. | R022, R023, R024, R030 |
| T4.4 | Target language picker (searchable), recent languages, persistence, same-language warning and "Translate anyway". | Tests: persistence, same-language; manual: switch retranslates. | R005, R012, R020 |
| T4.5 | Error taxonomy and recovery actions for every case; no raw `localizedDescription`. | Exhaustive switch test; manual with Ollama stopped, model missing, text too long. | R019, R039 |
| T4.6 | Panel keyboard and accessibility: Esc, ⌘C, ⌘↩, ⌘R, ⌘,; labels; VoiceOver order. | Manual checklist; no focus steal. | R029, R043 |
## M5 — Replace
Goal: explicit, safe replacement of the selected text.
| Task | Description | AC | Req |
|---|---|---|---|
| T5.1 | `InsertionCoordinator` and `InsertionTarget` (PID, app name, AX element, selected text/range). Capture at trigger time when trusted. | Tests: target captured, frontmost check, stale target rejected. | R025, R026 |
| T5.2 | Accessibility trust check, focused element, direct `kAXSelectedTextAttribute` replacement. | Tests with fakes; manual in TextEdit, Notes, Safari, Mail. | R025, R031 |
| T5.3 | Synthetic-paste fallback: set clipboard, `CGEvent.postToPid` ⌘V, wait, restore snapshot, suppression window. | Tests with fake poster; manual clipboard restoration in 10 apps. | R025, R027 |
| T5.4 | Safety: verify selected text unchanged, never insert in secure fields, block on blocking warnings, Copy fallback. | Tests: changed selection, wrong app, preamble, token loss; manual. | R026, R028, R030 |
| T5.5 | **Manual insertion matrix** and permission onboarding: Accessibility denied, granted, revoked while running, app update. | Matrix filled; top failures have tasks. | R031, R039, R048 |
## M6 — Settings, onboarding, menu bar
Goal: a finished app shell that a person can set up and use.
| Task | Description | AC | Req |
|---|---|---|---|
| T6.1 | `AppSettings` (versioned, defaults, migration, reset) and `SettingsStore` over `UserDefaults`; no text fields. | Migration test from a v0 fixture; unknown keys ignored; reset restores defaults. | R040 |
| T6.2 | Onboarding: Ollama reachable + version, Hy-MT3 installed, target language, optional Accessibility; fix buttons. | Manual with Ollama stopped, model missing, AX denied; reopen from menu. | R039 |
| T6.3 | Settings UI: General, Model, Translation, Privacy, Diagnostics; endpoint input validated; licence/digest shown. | Invalid remote configurations blocked; no text stored; manual. | R035, R040, R042 |
| T6.4 | Status menu, launch at login (`SMAppService`), diagnostics window, About/licences. | Manual: menu actions, login item state, diagnostics has no text. | R041, R042, R044 |
| T6.5 | **Integration checkpoint**: double copy → panel → Copy/Replace end-to-end in 10 apps; verify no auto-insert and clipboard restoration. | User confirms before M7. | R001–R030, R048 |
## M7 — Evaluation and the default-model gate
Goal: decide the default model, sampling and prompt policy with data.
| Task | Description | AC | Req |
|---|---|---|---|
| T7.1 | Corpus manifest decoding and validation against `evaluation/corpus.schema.json`; `sprachmittler-cli eval --manifest --models --target --out`; cold/warm runs. | Validation errors are precise; eval runs on a synthetic manifest with a fake transport. | R046, R047 |
| T7.2 | Metrics: chrF, BLEU, protected-token retention, numeric consistency, sentence/paragraph count, failure rate, first-token/total latency, memory from `/api/ps`. | Unit tests with hand-computed values. | R047 |
| T7.3 | Report writer (`report.md`, `report.json`) with environment block, per-category tables, limitations. | Golden-file test; records digests, server version, hardware, settings. | R047 |
| T7.4 | **Evaluation run**: 7B vs 1.8B, temperature 0.7 vs 0.2, default vs structured prompt on the user's corpus; 3 runs at temperature 0.7. | Report produced; user reviews. | R013, R014, R047 |
| T7.5 | **Default-model gate**: draft ADR "Default model and sampling"; user decides; update presets, docs and settings. | ADR accepted with numbers; `HYMT3_MODEL.md`, `ARCHITECTURE.md` §12 and `PERFORMANCE.md` updated. | R013, R014, R047 |
## M8 — Hardening and release
Goal: private, accessible, measured and shippable.
| Task | Description | AC | Req |
|---|---|---|---|
| T8.1 | Privacy audit: extend `scripts/privacy-check.sh` for SP-1…SP-15; add a self-test that plants one violation per rule; review Console during a full session. | `make verify` fails on seeded violations; Console shows no text, translations or app names. | R031–R038 |
| T8.2 | Accessibility pass: labels, keyboard paths, VoiceOver, Reduce Motion, Increase Contrast. | Manual checklist in TESTING passes. | R043 |
| T8.3 | Performance pass against ARCHITECTURE §14 using signposts; measure idle CPU, panel latency, first token, 7B/1.8B, warm/cold; record in `docs/PERFORMANCE.md`. | Budgets met or ADR explaining the deviation. | R050 |
| T8.4 | German localisation (`de`) and end-user README: install Ollama, pull the model, permissions, privacy, troubleshooting. | Reviewed by the user. | R045 |
| T8.5 | `scripts/release.sh`: archive unsigned, Developer ID sign, notarise (`notarytool`), staple, DMG, `--dry-run`. | Notarised build launches on a clean Mac; no hardened-runtime exceptions. | R049 |
| T8.6 | Compatibility matrix completion and the three worst failures fixed or documented. | Matrix filled; follow-ups recorded. | R048 |
+76
View File
@@ -0,0 +1,76 @@
# Kickoff prompts for OpenCode 2.x
Check first: `opencode --version` must print 2.x, and `make doctor` must be green. The prompts below assume the agents, commands and skills in `.opencode/` are discovered (run `/status` once to see that commands work).
## First session (paste as-is)
```text
You are building Sprachmittler, a macOS 14+ Apple Silicon menu-bar app that translates the selected
text of any app with a local Ollama Hy-MT3 model. The user selects text, presses ⌘C twice, and a
non-activating panel shows the translation. The panel has Copy and an explicit Replace button in the
lower right; nothing is replaced automatically. The default model is
hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M.
1. Read AGENTS.md, then docs/ARCHITECTURE.md (read §1–§7 closely, the rest as an index),
docs/IMPLEMENTATION_PLAN.md (M0–M2), docs/PROGRESS.md, docs/HYMT3_MODEL.md and
docs/SELECTION_AND_CLIPBOARD.md.
2. Run `make doctor` and `make verify` on the shipped scaffold and report the results. Fix toolchain or
scaffold issues (T0.1–T0.6) without changing the architecture. If something in the scaffold
contradicts the docs, tell me before changing either.
3. Then propose your plan for M0 completion and T1.1–T1.2, using the @architect subagent.
Do not start M1 implementation until I confirm the plan.
```
## Every following session
```text
/next
```
or, to target a specific task:
```text
/task T2.2
```
## Compatibility spike (after M2, before M3)
```text
/task T2.7
Translate the synthetic fixtures and a few of my real samples into German and English with the 7B model:
plain prose, Markdown, JSON, URL/placeholder text, and a long paragraph. Record first-token and total
timings, prompt-cache behaviour, and any preamble or lost-token failures in docs/HYMT3_MODEL.md §7.
Tell me which prompt variant you propose for structured text. Do not continue to M3 until I confirm.
```
## Capture and panel checkpoint (after M4)
```text
Show me the double-copy flow end to end: copy the same paragraph twice in Safari, Mail and TextEdit,
confirm the panel appears without taking focus, the translation streams, Copy works, and Replace is
disabled while streaming. List every deviation from docs/SELECTION_AND_CLIPBOARD.md.
```
## Insertion checkpoint (after M5)
```text
Walk me through Replace in TextEdit, Notes, Safari and Mail: click Replace, verify the selection is
replaced, ⌘Z restores it, and the previous clipboard (including rich text) is back. Then deny
Accessibility and show that Copy still works and Replace explains what to enable.
```
## Evaluation gate (M7)
```text
/evaluate
Then draft the ADR "Default model and sampling" from the report, using the decision rule in
docs/MODEL_EVALUATION.md §5. I will decide; do not edit DECISIONS.md until I do.
```
## Before release (M8)
```text
/status
Then confirm that the privacy self-test, accessibility checklist, performance budgets and the manual
compatibility matrices are complete. List anything that would make a notarised build risky.
```
+147
View File
@@ -0,0 +1,147 @@
# Supported languages
Hy-MT3 supports **102 languages**. The exact English name matters: it is inserted into the prompt. Never use a localised name, an ISO display name, or a language code in the prompt.
`docs/HYMT3_MODEL.md` is the source for the prompt templates. This file is the source for the catalogue.
## 1. Languages supported since Hy-MT2 (33)
| Code | Model name (prompt) | Chinese name | Notes |
|---|---|---|---|
| `zh` | Chinese | 中文 | Simplified Chinese; display as "Chinese (Simplified)" |
| `en` | English | 英语 | |
| `fr` | French | 法语 | |
| `pt` | Portuguese | 葡萄牙语 | `pt-BR`/`pt-PT` also map here |
| `es` | Spanish | 西班牙语 | |
| `ja` | Japanese | 日语 | |
| `tr` | Turkish | 土耳其语 | |
| `ru` | Russian | 俄语 | |
| `ar` | Arabic | 阿拉伯语 | RTL |
| `ko` | Korean | 韩语 | |
| `th` | Thai | 泰语 | |
| `it` | Italian | 意大利语 | |
| `de` | German | 德语 | |
| `vi` | Vietnamese | 越南语 | |
| `ms` | Malay | 马来语 | |
| `id` | Indonesian | 印尼语 | legacy `in` maps here |
| `tl` | Filipino | 菲律宾语 | |
| `hi` | Hindi | 印地语 | |
| `zh-Hant` | Traditional Chinese | 繁体中文 | the model card writes `zh-TR`; prompt name is "Traditional Chinese" |
| `pl` | Polish | 波兰语 | |
| `cs` | Czech | 捷克语 | |
| `nl` | Dutch | 荷兰语 | |
| `km` | Khmer | 高棉语 | |
| `my` | Burmese | 缅甸语 | |
| `fa` | Persian | 波斯语 | RTL |
| `gu` | Gujarati | 古吉拉特语 | |
| `ur` | Urdu | 乌尔都语 | RTL |
| `te` | Telugu | 泰卢固语 | |
| `mr` | Marathi | 马拉地语 | |
| `he` | Hebrew | 希伯来语 | RTL; legacy `iw` maps here |
| `bn` | Bengali | 孟加拉语 | |
| `ta` | Tamil | 泰米尔语 | |
| `uk` | Ukrainian | 乌克兰语 | |
## 2. Chinese minority languages and dialects (5)
| Code | Model name (prompt) | Chinese name | Notes |
|---|---|---|---|
| `bo` | Tibetan | 藏语 | |
| `mn` | Traditional Mongolian | 传统蒙古语 | Mongolian script |
| `yue` | Cantonese | 粤语 | |
| `kk` | Arabic Kazakh | 阿拉伯字母哈萨克语 | Arabic script, RTL |
| `ug` | Uyghur | 维吾尔语 | RTL |
## 3. Newly supported in Hy-MT3 (64)
| Code | Model name (prompt) | Chinese name |
|---|---|---|
| `el` | Greek | 希腊语 |
| `cy` | Welsh | 威尔士语 |
| `si` | Sinhala | 僧伽罗语 |
| `ro` | Romanian | 罗马尼亚语 |
| `ca` | Catalan | 加泰罗尼亚语 |
| `pa` | Punjabi | 旁遮普语 |
| `hu` | Hungarian | 匈牙利语 |
| `gl` | Galician | 加利西亚语 |
| `sd` | Sindhi | 信德语 |
| `bg` | Bulgarian | 保加利亚语 |
| `eu` | Basque | 巴斯克语 |
| `as` | Assamese | 阿萨姆语 |
| `sr` | Serbian | 塞尔维亚语 |
| `af` | Afrikaans | 南非荷兰语 |
| `or` | Odia | 奥里亚语 |
| `hr` | Croatian | 克罗地亚语 |
| `lb` | Luxembourgish | 卢森堡语 |
| `kn` | Kannada | 卡纳达语 |
| `sk` | Slovak | 斯洛伐克语 |
| `mt` | Maltese | 马耳他语 |
| `ml` | Malayalam | 马拉雅拉姆语 |
| `sl` | Slovenian | 斯洛文尼亚语 |
| `eo` | Esperanto | 世界语 |
| `sa` | Sanskrit | 梵语 |
| `sq` | Albanian | 阿尔巴尼亚语 |
| `yi` | Yiddish | 意第绪语 |
| `lo` | Lao | 老挝语 |
| `mk` | Macedonian | 马其顿语 |
| `hy` | Armenian | 亚美尼亚语 |
| `jv` | Javanese | 爪哇语 |
| `be` | Belarusian | 白俄罗斯语 |
| `ka` | Georgian | 格鲁吉亚语 |
| `su` | Sundanese | 巽他语 |
| `lt` | Lithuanian | 立陶宛语 |
| `az` | Azerbaijani | 阿塞拜疆语 |
| `ceb` | Cebuano | 宿务语 |
| `lv` | Latvian | 拉脱维亚语 |
| `uz` | Uzbek | 乌兹别克语 |
| `war` | Waray | 瓦瑞语 |
| `et` | Estonian | 爱沙尼亚语 |
| `ky` | Kyrgyz | 吉尔吉斯语 |
| `sw` | Swahili | 斯瓦希里语 |
| `fi` | Finnish | 芬兰语 |
| `tk` | Turkmen | 土库曼语 |
| `am` | Amharic | 阿姆哈拉语 |
| `sv` | Swedish | 瑞典语 |
| `tg` | Tajik | 塔吉克语 |
| `so` | Somali | 索马里语 |
| `da` | Danish | 丹麦语 |
| `tt` | Tatar | 鞑靼语 |
| `mg` | Malagasy | 马达加斯加语 |
| `nb` | Norwegian | 挪威语 |
| `ba` | Bashkir | 巴什基尔语 |
| `ht` | Haitian Creole | 海地克里奥尔语 |
| `nn` | Norwegian Nynorsk | 新挪威语 |
| `ku` | Kurdish | 库尔德语 |
| `kk-Cyrl` | Cyrillic Kazakh | 西里尔哈萨克语 |
| `is` | Icelandic | 冰岛语 |
| `ckb` | Central Kurdish | 中库尔德语 |
| `mn-Cyrl` | Cyrillic Mongolian | 西里尔蒙古语 |
| `ga` | Irish | 爱尔兰语 |
| `ps` | Pashto | 普什图语 |
| `gd` | Scottish Gaelic | 苏格兰盖尔语 |
| `ne` | Nepali | 尼泊尔语 |
## 4. Mapping rules
1. **Prompt name = model card name.** `TargetLanguage.modelName` is one of the names above. It is never localised.
2. **Display name = localised.** `TargetLanguage.displayName` may be "Deutsch", "German", "Allemand", etc. It never enters the prompt.
3. **Variants collapse to the card's name.**
- `zh`, `zh-Hans`, `zh-CN`, `zh-SG` → `Chinese`.
- `zh-Hant`, `zh-TW`, `zh-HK`, `zh-TR` → `Traditional Chinese`.
- `pt`, `pt-BR`, `pt-PT` → `Portuguese`.
- `no`, `nb`, `nn` → `Norwegian` or `Norwegian Nynorsk` as appropriate; `no` defaults to `nb` (Norwegian).
- `kk` → `Arabic Kazakh`; `kk-Cyrl`, `kk-KZ` → `Cyrillic Kazakh`.
- `mn` → `Traditional Mongolian`; `mn-Cyrl` → `Cyrillic Mongolian`.
- `ku` → `Kurdish`; `ckb` → `Central Kurdish`.
- `tl`, `fil` → `Filipino`.
- `iw` → `he` (Hebrew); `in` → `id` (Indonesian).
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.
## 5. UI ordering
- Recent targets first (last three), then a searchable list grouped by "Common", "Europe", "Asia", "Middle East and Africa", "Other".
- Common defaults: English, German, French, Spanish, Italian, Portuguese, Dutch, Polish, Chinese, Japanese, Korean, Arabic, Turkish, Russian, Ukrainian.
- The system language is the first-run target if it is in the catalogue; otherwise English.
+87
View File
@@ -0,0 +1,87 @@
# Model evaluation
Status: Draft v1.0. Module: `SprachmittlerEval` (CLI only). Agent: `translation-evaluator`. Skill: `translation-quality`.
The default model is the one that works best on **your** texts on **your** Mac, at an acceptable speed. Publisher benchmarks (FLORES-200, WMT26, IFMTBench, WildMTBench) are context, not evidence for the default.
## 1. Corpus
- Manifest: `evaluation/corpus.json` (copy from `evaluation/corpus.example.json`; schema `evaluation/corpus.schema.json`).
- Texts: `evaluation/corpus/` (git-ignored, denied to agents). Use texts you are allowed to process; prefer public or your own.
- Size: about 60 segments. Suggested mix:
| Category | Segments | What it tests |
|---|---|---|
| `en-de-prose` | 10 | baseline EN→DE |
| `de-en-prose` | 10 | baseline DE→EN |
| `technical` | 8 | compounds, units, acronyms |
| `legal` | 4 | formality, terms |
| `ui` | 6 | short strings, buttons, placeholders |
| `markdown` | 5 | structure, links, code spans |
| `json` | 4 | keys vs values |
| `placeholders` | 5 | `{{var}}`, `%s`, `${x}`, URLs, e-mails |
| `numbers` | 4 | decimals, thousands, units |
| `idioms` | 4 | non-literal meaning |
| `long` | 2 | chunking and context |
| `cjk` | 3 | CJK direction, character density |
| `rtl` | 2 | Arabic/Hebrew direction |
- References: human translations written or corrected by you. For public texts, a published translation may be used with attribution. Mark `referenceKind: "human"` or `"public"`.
- Never commit private corpus material. The manifest is shared; the texts and results are not.
## 2. Procedure
1. Record hardware (chip, memory), macOS, Ollama version, model digests, `num_ctx`, sampling, prompt policy.
2. For each model: unload (`keep_alive: 0`), run one warm-up, then all segments warm, in manifest order.
3. Run 3 times at temperature 0.7 to measure variance; one run at 0.2 for comparison.
4. Compare 7B vs 1.8B. Compare default vs Structured Data 1 on the `markdown`, `json` and `ui` categories only.
5. Store raw outputs and metrics under `evaluation/results/<ISO date>/<model-slug>/`.
6. Generate `report.md` and `report.json`.
7. Review a sample in the panel and record correction minutes in `corrections.csv` (`segmentID,model,minutes,notes`).
Do not run other heavy workloads during measurement.
## 3. Metrics
| Metric | Definition |
|---|---|
| Failure rate | Share of segments with empty, truncated, loop, preamble or transport failure |
| chrF | Character n-gram F-score against the reference (primary, language-agnostic) |
| BLEU | SacreBLEU-style corpus BLEU (secondary; tokenisation documented) |
| Protected-token retention | Share of URLs, e-mails, placeholders and code spans present in the output; must be 1.0 |
| Numeric consistency | Share of normalised numeric values present; locale separators normalised |
| Structure | Paragraph/sentence count match; Markdown/JSON key preservation on structured categories |
| First-token latency | Median and p90 from request to first delta |
| Warm s/segment | Median and p90 total time |
| Cold load | `load_duration` of the first request after unload |
| Memory | `size` and `size_vram` from `/api/ps` after the first request |
| Human rating | 1–5 adequacy + fluency, or correction minutes |
chrF and BLEU are implemented in `SprachmittlerEval` with hand-computed unit tests. Do not add a Python dependency.
## 4. Report format
`report.md` starts with the environment block, then one table per direction/category:
| Model | Temp | Segments | Fail % | chrF | BLEU | Token retention | Num. consistency | First token p50/p90 | Warm s/seg p50/p90 |
|---|---|---|---|---|---|---|---|---|---|
Followed by "Observations" (max 10 bullets, no quotations above 15 words) and "Limitations".
## 5. Default-model gate (T7.5)
Write ADR "Default model and sampling" with:
- report location and date, corpus size per category, hardware;
- chosen default and Fast preset, with the numbers that justify them;
- rule used, for example: "no model may be default if protected-token retention < 1.0 or failure rate > 2%; then highest chrF on `en-de-prose` + `de-en-prose` + `technical`, then highest human rating, then lowest first-token latency";
- the chosen temperature and prompt policy;
- what triggers re-evaluation (new model version, Ollama upgrade, prompt change, user complaints).
Until the ADR is accepted, the 7B remains labelled provisional and the app may ask the user to pick a model on first run if both are installed.
## 6. Results log
| Date | Report | Models | Decision |
|---|---|---|---|
| 2026-11-26 | kit reference only | 7B Q4_K_M | 246 output tokens, 6.52 s, 44.6 tok/s; no corpus evaluation yet |
+193
View File
@@ -0,0 +1,193 @@
# Ollama translation API contract
Status: Draft v1.0 · Verified against **Ollama 0.40.18, 2026-11-26, Apple M5 Pro 48 GB, macOS 27.2.1**, model `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M`.
Items marked **VERIFY** must be confirmed against your Ollama with `make fixtures` (T1.1) before code depends on them. Record the Ollama version and model digest in `Fixtures/capture-meta.json`.
All networking lives in `SprachmittlerOllama`. Base URL comes from settings (default `http://127.0.0.1:11434`) and passes `EndpointPolicy.validate` (see `docs/SECURITY_PRIVACY.md`).
## 1. Translation request: `POST /api/chat`
One user message. No system message, no images, no `think` for Hy-MT3.
```json
{
"model": "hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M",
"messages": [
{
"role": "user",
"content": "Translate the following text into German. Note that you should **only output the translated result without any additional explanation**:\n\nThe figure above plots …"
}
],
"stream": true,
"keep_alive": "30m",
"options": {
"temperature": 0.7,
"top_p": 0.6,
"top_k": 20,
"repeat_penalty": 1.05,
"num_predict": 4096,
"num_ctx": 8192
}
}
```
Rules:
- `content` is the adapter's documented prompt for the selected variant (see `docs/HYMT3_MODEL.md`). The default template is byte-exact.
- `messages` contains exactly one user message. Do not add a system message: the model has no default system prompt, and the template uses `<|extra_4|>` only for a system message.
- Do not send `images`; Hy-MT3 is text-only.
- Do not send `think`; `/api/show` reports only `completion`, not `thinking`.
- `keep_alive` comes from settings. `"0"` unloads the model after the response; `"30m"` keeps it warm.
- `num_predict` is always set (output cap). `num_ctx` is always set to 8192 (the model card's translation context; see §7).
- Send only the option keys above. Do not rely on Ollama ignoring unknown keys.
- No `format` (JSON mode) in v1. The prompt itself preserves JSON when the source is JSON.
### 1.1 Streaming response
NDJSON, one object per line. A delta:
```json
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T09:00:00Z","message":{"role":"assistant","content":"Die obige Grafik"},"done":false}
```
The final line:
```json
{"model":"…","created_at":"…","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop",
"total_duration":6519029875,"load_duration":799545833,"prompt_eval_count":178,"prompt_eval_duration":199759000,
"eval_count":246,"eval_duration":5513836000}
```
- Durations are nanoseconds. Map them into `ChatMetrics` (load, prompt eval, eval, total; token counts).
- `done_reason`: `"stop"` = normal end; `"length"` = hit `num_predict` → warning `truncated`, Replace disabled by default. Treat any other value as `"stop"` but log it at `.info`. **VERIFY** the full set of values.
- A line `{"error":"…"}` may appear mid-stream. Map it with §5 and stop.
### 1.2 Decoding rules
- Read with `URLSession.bytes(for:)`, split on `\n`, decode each complete line; carry a partial line over to the next chunk.
- Append `message.content` deltas to a buffer and forward them to the session and the `TranslationGuard` as they arrive.
- Never assume one token per line.
- Cancellation: `AsyncThrowingStream.onTermination` cancels the URL task.
- The stream buffer is bounded by the chunk size; do not accumulate unbounded output.
### 1.3 Timeouts
| Phase | Default | Meaning |
|---|---|---|
| connect | 3 s | TCP connect plus TLS |
| firstToken | 120 s | request sent → first `message.content` byte; includes cold model load |
| idle | 20 s | gap between lines once streaming has started |
| totalPerChunk | 180 s | hard cap per chunk |
All injectable via a `Clock` for tests.
## 2. Model discovery
### 2.1 `GET /api/version`
`{"version":"0.40.18"}`. The minimum supported version is recorded in T1.1 and checked in onboarding.
### 2.2 `GET /api/tags`
```json
{"models":[{"name":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M",
"modified_at":"…","size":5150000000,"digest":"sha256…","details":{"format":"gguf","family":"hunyuan-dense",
"parameter_size":"7.5B","quantization_level":"Q4_K_M"}}]}
```
Store `name`, `digest`, `size` and `details`. Normalise `name:latest` ↔ `name` when comparing with presets. Detect the Hy-MT3 family by a case-insensitive `hy-mt3` match, not by a hard-coded installed list.
### 2.3 `POST /api/show`
Request `{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M"}`. Verified fields:
| Field | Observed value | Use |
|---|---|---|
| `capabilities` | `["completion"]` | Text-only; no vision, no thinking |
| `details` | family `hunyuan-dense`, parameter size `7.5B`, quantization `Q4_K_M` | UI metadata |
| `parameters` | only stop tokens (`<|startoftext|>`, `<|extra_4|>`, `<|extra_0|>`, `<|eos|>`) | No sampling defaults; the adapter must set them |
| `template` | `{{ if .System }}…{{ if .Prompt }}<|startoftext|>{{ .Prompt }}<|extra_0|>{{ end }}{{ .Response }}<|eos|>` | Confirms no default system prompt |
| `model_info` | `hunyuan-dense.context_length = 262144` | Informational; the card's translation context is 8192 |
| `license` | `null` in Ollama | Show the Hugging Face licence (Apache-2.0) in Settings |
**VERIFY** for the 1.8B tag and for future versions.
### 2.4 `GET /api/ps`
```json
{"models":[{"name":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","size":6488609259,"size_vram":6488609259,"expires_at":"…"}]}
```
Used by diagnostics and the evaluation harness for resident memory. Not polled by the app.
## 3. Warm-up
Optional (`warmUpOnLaunch`, local endpoint only): send `POST /api/chat` with the selected model, a fixed synthetic sentence (for example `Hello.`), `num_predict: 8`, and discard the output. **Never** use the user's text for warm-up. The request shape is the same as §1.
## 4. Option mapping
| Publisher setting | Ollama option | Default |
|---|---|---|
| `temperature` | `temperature` | 0.7 |
| `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 |
The names matter: Ollama does not read `repetition_penalty` or `max_tokens`. Do not send `do_sample`, `seed` or `stop` unless an ADR adds them.
## 5. Error classification
| Condition | HTTP / transport | Map to |
|---|---|---|
| Connection refused / host unreachable | `URLError.cannotConnectToHost`, `.cannotFindHost`, connect timeout | `ollamaUnreachable` |
| Redirect | 3xx (delegate refuses) | `endpointRejected(.redirect)` |
| Model not installed | typically 404 with body containing `not found` | `modelNotInstalled(model)` |
| Model has no Hy-MT3 adapter | discovery succeeds but name does not match | `noAdapter(model)` |
| Model is not text-capable | 400, or capabilities lack `completion` | `badRequest` / `noAdapter` |
| Out of memory / model failed to load | 500 with message containing `memory` or `load` | `server(status, message)` with recovery "Use the smaller 1.8B model or close other apps" |
| Context too small / prompt truncated | 400 or `done_reason: "length"` | `badRequest` / warning `truncated` |
| Error line mid-stream | `{"error":"…"}` | classify by message, else `server(0, message)` |
| First-token, idle or total timeout | timer | `timeout(phase)`; one retry before any delta |
| Task cancelled | `CancellationError` / `URLError.cancelled` | `cancelled`; not an error for the UI |
| Other 4xx/5xx | status | `server(status, message)` |
Error bodies are JSON `{"error":"…"}`. Fall back to the raw text (truncated to 500 characters, never containing translated text). The UI shows `userMessage`, never the raw body.
## 6. Fixtures
`scripts/capture-fixtures.sh` records into `Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/`:
- `version.json`, `tags.json`, `ps.json`
- `show-<model-slug>.json` for each installed Hy-MT3 tag
- `chat-<model-slug>-en-de.ndjson` for a fixed synthetic English sentence → German
- `chat-<model-slug>-de-en.ndjson` for a fixed synthetic German sentence → English
- `chat-<model-slug>-markdown.ndjson` for a Markdown/URL/placeholder sample
- `chat-<model-slug>-truncated.ndjson` with `num_predict: 16` → `done_reason: "length"`
- `error-missing-model.json`
- `capture-meta.json`: Ollama version, date, hardware, digests, options
Rules: synthetic inputs only; keep each fixture under 200 KB; never record private text. The recorded streams also become validator fixtures.
## 7. Prompt cache and context
- Ollama reuses the prompt prefix cache. The owner's run reported **177 of 178 prompt tokens cached**; our cold-ish run reported 178 prompt tokens with a 199 ms prompt eval. Keep the prefix byte-stable and append only the source text.
- The GGUF metadata reports `context_length = 262144`, but the model card documents **8192** for translation. Set `num_ctx: 8192`; do not rely on Ollama's default, which may be smaller and silently truncate.
- With `num_ctx: 8192`, `ollama ps` reported **6.49 GB** resident for the 7B Q4_K_M. Budget accordingly on 16 GB Macs.
## 8. Open VERIFY items
Resolved on 2026-11-26 (Ollama 0.40.18, digest `262ac792aeb5`, M5 Pro 48 GB):
- `done_reason` observed: `stop` and `length` (the truncated fixture with `num_predict: 16` ends with `length`). No `load` value seen.
- Cold/first load observed: 0.80 s and 2.05 s in two runs; warm load ~1 ms.
- A `system` message was not sent; v1 does not send one.
- Ollama strips the template's `<|eos|>` from the returned content (observed: yes).
Still open:
- Whether `keep_alive: "0"` fully unloads the model and how quickly `/api/ps` reflects it.
- The 1.8B tag behaviour: capabilities, context, memory, speed, quality.
- The full set of `done_reason` values on other inputs (e.g. an aborted stream).
+61
View File
@@ -0,0 +1,61 @@
# OpenCode 2.x notes
This kit is written for **OpenCode 2.x** in native V2 format. This page explains the choices, so you can adapt them without reintroducing V1 constructs. Checked against the OpenCode documentation on 2026-11-26.
## Files and locations
| File | Purpose |
|---|---|
| `opencode.json` | Project config: `$schema`, `instructions`, ordered `permissions` |
| `AGENTS.md` | Project rules, loaded automatically |
| `.opencode/agents/<name>.md` | Subagents: `architect`, `swift-reviewer`, `test-engineer`, `translation-evaluator` |
| `.opencode/commands/<name>.md` | Slash commands: `next`, `task`, `plan`, `verify`, `review`, `adr`, `status`, `manual-test`, `evaluate` |
| `.opencode/skills/<id>/SKILL.md` | Skills: `translation-quality`, `selection-capture` (the ID comes from the directory name) |
| `scripts/opencode-check.sh` | `make doctor`: version check, V1-key scan, resolved config |
`opencode.jsonc` would work as well; plain JSON is used so the doctor script can parse it with `jq`.
## Permissions
- Rules are `{ "action", "resource", "effect" }` with effects `allow`, `deny`, `ask`. They are evaluated in order and **the last matching rule wins**; if nothing matches, OpenCode asks. Agent rules are appended after project and global rules, so an agent's `shell * deny` followed by narrow allows overrides the project's broader allows.
- Wildcards: the documentation shows `src/**` as a resource example but does not define whether `*` crosses `/`. The kit therefore lists every folder rule twice (`dir/*` and `dir/**`), so nested files are covered either way. `make doctor` flags a `dir/*` rule without its `dir/**` twin.
- The project config starts with `shell *: ask`, then allows build, test, read-only git and inspection commands; asks for `git commit`, `ollama pull` and `codesign`; denies `git push`, `git reset --hard`, `rm -rf`, `sudo`, `ollama rm` and `xcrun notarytool`.
- `edit` is allowed in general but denied for the generated `Sprachmittler.xcodeproj/*` and for `evaluation/corpus/*`; recorded Ollama fixtures and the entitlements file ask first.
- `read` is allowed in general, asks for `*.env` and `*.env.*`, allows `*.env.example`, and is denied for `evaluation/corpus/*` (private texts). The `.env` rules are repeated because the project's `read * allow` comes after OpenCode's built-in base policy and would otherwise override its `.env` prompts.
- `external_directory` is set back to `ask`, because V2 allows it by default.
- `webfetch` and `websearch` ask.
- For machine-wide hard limits, add `policies` to your **global** config, e.g. `{ "action": "tool.use", "resource": "shell:sudo *", "effect": "deny" }`. Policies can only deny and override project rules.
## Agents
- V2 frontmatter fields used: `description`, `mode: subagent`, `steps`, `permissions` (a YAML list of rules). The Markdown body is the system prompt.
- No `model` is pinned, so agents inherit your session model. Pin one with `model: provider/model` or `provider/model#variant` if you want.
- No `temperature`: V2 does not send agent temperature. Put sampling on a model variant in your global config if you need it.
- An agent file that uses `permissions` is read as V2; V1 fields such as `permission`, `tools` or `temperature` in the same file would be ignored, so do not mix them.
## Commands
- Frontmatter fields used: `description`, optionally `agent`. `$ARGUMENTS` receives the text after the command.
- `/plan`, `/review` and `/evaluate` name a `mode: subagent` agent, so V2 runs them in a background child session and reports the result back to your session. Add `subagent: false` to a command file if you prefer it in the foreground.
- No command uses `!` shell blocks, because those run outside the permission flow.
- Command templates name files in backticks rather than `@path`, because V2 does not expand `@path` in stored templates; the agent reads the files itself.
## Skills
- `translation-quality` and `selection-capture` are loaded on demand by the `skill` tool. To restrict them, add `skill` permission rules, e.g. deny `*` and allow the two IDs.
## Checking the setup
```bash
opencode --version # must be 2.x
make doctor # runs scripts/opencode-check.sh
opencode debug config # prints the resolved V2 configuration
```
Inside OpenCode, `/status` should list progress, and `@architect` should be offered as a subagent.
## Not used on purpose
- No MCP servers: the kit needs none, and every server widens the attack surface.
- No todo tool settings: todos are off by default in V2 (`experimental.todo`); `docs/PROGRESS.md` is the task list.
- No terminal or theme settings: those belong in the global `~/.config/opencode/cli.json`.
+58
View File
@@ -0,0 +1,58 @@
# Performance
Status: Draft v1.0. Targets are validated on named hardware. Translation speed depends on the model and the Mac; it is measured, not promised.
## 1. Reference measurements
| Date | Hardware | macOS | Ollama | Model | Prompt tokens | Output tokens | First token | Total | Eval rate | Resident |
|---|---|---|---|---|---|---|---|---|---|---|
| 2026-11-26 | M5 Pro, 48 GB | 27.2.1 | 0.40.18 | 7B Q4_K_M | 178 (owner: 177 cached) | 255 (owner) | not recorded | 5.97 s (owner) | 43.07 tok/s | — |
| 2026-11-26 | M5 Pro, 48 GB | 27.2.1 | 0.40.18 | 7B Q4_K_M | 178 | 246 | not recorded | 6.52 s | 44.6 tok/s | 6.49 GB |
The owner's run and the verification run used the same canonical prompt and the same source paragraph (the Hy-MT3 figure caption). The difference is normal sampling variance.
## 2. Budgets
| 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 |
| Copy to clipboard | ≤ 100 ms | signpost `copy` |
| Replace via AX | ≤ 300 ms after click | signpost `insert` |
| Replace via paste | ≤ 700 ms including clipboard restore | signpost `insert` |
| Idle CPU | < 0.5% | Activity Monitor / `powermetrics` |
| Idle memory (app, excluding Ollama) | ≤ 90 MB | `footprint` |
| Main-thread hang | none > 100 ms | Instruments Hangs |
| 7B resident memory (8K context) | about 6.5 GB | `ollama ps` |
| 1.8B resident memory | about 1.6–2.0 GB | `ollama ps` (VERIFY) |
## 3. How to measure
```bash
make smoke # fixed synthetic sentence, 7B or all Hy-MT3 tags
swift run --package-path Packages/SprachmittlerKit sprachmittler-cli \
translate --file sample.txt --target de --model hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M --json
ollama ps # resident memory and expiry
footprint -p $(pgrep -x Sprachmittler) # app memory, excluding Ollama
```
- Run cold (after `keep_alive: 0` and a restart) and warm.
- Record prompt tokens, output tokens, first-token latency and total time; the CLI JSON includes them.
- For the panel, use `os_signpost` intervals and Instruments; do not estimate from wall-clock clicks.
- For idle CPU, leave the app running with the panel closed for 5 minutes and sample Activity Monitor. The pasteboard poll is 120 ms; if idle CPU exceeds 0.5%, increase the interval to 200 ms and re-measure.
## 4. Model choice
- The 7B Q4_K_M is the quality default. It needs about 6.5 GB resident plus the app and the rest of the system; on a 16 GB Mac it is usable but not comfortable alongside a browser with many tabs.
- The 1.8B Q4_K_M is the Fast preset: about 1.35 GB download and much lower memory. Evaluate quality before recommending it broadly.
- The 30B-A3B is not a preset. It is far above a 16 GB budget.
- Streaming and a warm model matter more for perceived speed than a few tokens per second. Warm up on launch when the endpoint is loopback.
## 5. Caching
- The prompt prefix cache is the main latency win: the owner's run reported 177/178 cached prompt tokens. Keep the prefix stable.
- Do not add a system message, a timestamp or dynamic context to the default prompt.
- Changing the target language changes the prefix and the cache; that is expected.
- `keep_alive: "30m"` keeps the model loaded between translations. A cold load can add seconds; measure it on the target Mac and record it here.
+100
View File
@@ -0,0 +1,100 @@
# Sprachmittler — Product requirements (v1)
## Problem
People read and write in more than one language all day. Switching to a browser translator breaks concentration, and cloud translators send the selected text to a third party. DeepL's macOS app solved the interaction problem with a double copy (⌘C twice), but it is a cloud service with accounts and limits. Running a strong local translation model through Ollama is possible, but it means a terminal, a prompt, manual copying and no reliable way to put the result back.
## Product statement
Select text in any app, press **⌘C twice**, and Sprachmittler shows a translation from a local Hy-MT3 model in a floating panel. Copy it, or click **Replace** to put it over the selection. The source app keeps the focus, nothing is sent to a third party, and nothing is replaced or copied behind your back.
## Persona
A technical professional on an Apple Silicon Mac who reads and writes English and German (and occasionally other languages), runs Ollama locally, cares about privacy, works with the keyboard and expects native macOS behaviour. They translate paragraphs in Mail, Safari, Word, Notes, Slack and an editor, and they do not want a document translator.
## User stories and acceptance criteria
| ID | Story | Acceptance criteria |
|---|---|---|
| US-1 | As a user, I select a paragraph in Safari and press ⌘C twice. | The panel appears within 250 ms; the source app stays active; the translation streams in. |
| US-2 | As a user, I click Copy and paste the translation somewhere. | The clipboard contains the translation; the panel stays open; the source app is unchanged. |
| US-3 | As a user, I click Replace. | The selected text in the source app is replaced; ⌘Z restores the original in apps that support undo; the panel closes. |
| US-4 | As a user, I do not want accidental replacements. | Nothing is inserted until Replace is clicked; Replace is disabled while translating or when validation blocks it. |
| US-5 | As a user, I switch the target language to German and back to English. | The translation is redone for the new target; the choice persists across launches. |
| US-6 | As a user, I translate a long selection. | It is chunked at paragraph boundaries and reassembled; no text is silently lost; a warning appears if a chunk fails. |
| US-7 | As a user, I translate text with a URL, an e-mail and `{{placeholders}}`. | All protected tokens survive; if one is lost, a warning appears and Replace is disabled. |
| US-8 | As a user, I translate Markdown or JSON. | Formatting and keys are preserved; user-facing values are translated. |
| US-9 | As a user, the model adds "Here is the translation:". | The panel shows a preamble warning; Replace is disabled by default; Copy still works. |
| US-10 | As a user, Ollama is not running or the model is missing. | The panel or onboarding names the problem and offers a fix; no raw error is shown. |
| US-11 | As a user, I use an app that does not accept Accessibility replacement. | Replace fails with a clear message and offers Copy; the app is not left in a broken state. |
| US-12 | As a user, I want to translate without granting Accessibility. | Double copy, translation, Copy and Services work; Replace explains the permission when clicked. |
| US-13 | As a user, I invoke Services ▸ Translate with Sprachmittler. | The selected text is translated in the same panel without clipboard polling or Accessibility. |
| US-14 | As a user, I translate from the terminal. | `sprachmittler-cli translate --text "…" --target de` prints the translation; `--json` emits structured output. |
| US-15 | As a user, I want certainty that my text stays local. | Default endpoint is loopback; remote requires an explicit toggle and HTTPS; logs contain no text; no history on disk. |
## Requirements
| ID | Area | Requirement | Verification |
|---|---|---|---|
| R001 | Capture | Two ⌘C copies within the configured window trigger a translation. | `DoubleCopyWatcherTests` |
| R002 | Capture | The two copies must contain identical, non-empty text. | `DoubleCopyWatcherTests` |
| R003 | Capture | The app ignores its own clipboard writes. | `OwnWriteSuppressionTests` |
| R004 | Capture | Whitespace-only selections are ignored with no panel. | `DoubleCopyWatcherTests` |
| R005 | Capture | Oversized text produces an actionable error before any request. | `TextLimitTests` |
| R006 | Capture | Services menu entry translates without clipboard polling. | Manual checklist |
| R007 | Capture | The menu bar can translate the current clipboard text on demand. | Manual checklist |
| R008 | Capture | No global key tap and no Input Monitoring permission. | Code review; privacy check |
| R009 | Translation | Ollama `/api/chat` with streaming NDJSON is the only backend. | `OllamaChatClientTests` |
| R010 | Translation | The Hy-MT3 default prompt is byte-exact. | `PromptGoldenTests` |
| R011 | Translation | The prompt prefix depends only on the target language and stays stable. | `PromptGoldenTests` |
| R012 | Translation | Target languages use the model card's exact English names. | `LanguageCatalogTests` |
| R013 | Translation | 7B Q4_K_M is the provisional default; 1.8B is offered as Fast. | `ModelCatalogTests` |
| R014 | Translation | Publisher sampling is mapped to Ollama option names. | `SamplingOptionsTests` |
| R015 | Translation | `num_ctx` is set to 8192 on every request. | `RequestEncodingTests` |
| R016 | Translation | Source language detection is for display only. | `LanguageDetectorTests` |
| R017 | Translation | Long text is chunked at paragraph boundaries and reassembled exactly. | `ChunkerTests` |
| R018 | Translation | Protected tokens are scanned and validated before Replace. | `ProtectedTokenTests` |
| R019 | Translation | Preamble, truncation and repetition produce warnings. | `OutputValidatorTests` |
| R020 | Translation | Same-language input produces a warning but can still be translated. | `SameLanguageTests` |
| R021 | Panel | The panel is non-activating and never steals focus. | Manual checklist |
| R022 | Panel | The translation streams into the panel. | Manual checklist |
| R023 | Panel | Copy writes the translation and keeps the panel open. | `PanelViewModelTests`, manual |
| R024 | Panel | Replace is an explicit button in the lower right; no auto-replace. | Manual checklist |
| R025 | Panel | Replace tries Accessibility first, then synthetic paste. | `InsertionCoordinatorTests` |
| R026 | Panel | Replace aborts if the source app or selection changed. | `InsertionTargetTests` |
| R027 | Panel | The previous clipboard is restored after a paste fallback. | `ClipboardSnapshotTests` |
| R028 | Panel | Replace is undoable in apps that support undo; this is documented. | Manual checklist |
| R029 | Panel | Esc closes; ⌘C copies; ⌘↩ replaces when safe. | Manual checklist |
| R030 | Panel | Blocking warnings disable Replace and are visible. | `PanelViewModelTests` |
| R031 | Permissions | Accessibility is optional and requested only for Replace. | Privacy check; manual |
| R032 | Privacy | No telemetry, analytics or accounts. | Privacy check |
| R033 | Privacy | Source text and translations are never logged in clear. | Privacy check |
| R034 | Privacy | No translation history; nothing text-related is persisted. | Code review; privacy check |
| R035 | Privacy | Loopback endpoint by default; remote needs HTTPS and an explicit toggle. | `EndpointPolicyTests` |
| R036 | Privacy | No Screen Recording, camera, microphone or Input Monitoring permission. | Info.plist/privacy check |
| R037 | Privacy | Clipboard snapshots live in memory for one replacement. | `ClipboardSnapshotTests` |
| R038 | Privacy | Selected and translated text is never executed or followed as instructions. | Code review |
| R039 | UX | Onboarding checks Ollama, model, target language and optional Accessibility. | Manual checklist |
| R040 | UX | Settings store no source text or translations. | `AppSettingsTests` |
| R041 | UX | Status menu exposes translate, language, copy, replace, settings, setup, quit. | Manual checklist |
| R042 | UX | Diagnostics shows versions, digests, timings and error kinds only. | Manual checklist |
| R043 | UX | The app UI is keyboard accessible and VoiceOver readable. | Manual checklist |
| R044 | UX | Launch at login is optional and reflects the system state. | Manual checklist |
| R045 | UX | English base and German localisation. | `LocalisationTests` |
| R046 | Tooling | CLI supports languages, models, show, detect, translate and eval. | CLI tests |
| R047 | Tooling | Evaluation corpus and metrics are documented and runnable. | Eval tests |
| R048 | Tooling | Unit, contract and component tests plus a manual compatibility matrix. | `make verify` |
| R049 | Release | Developer ID signing, notarisation and a DMG script. | Release checklist |
| R050 | Performance | Capture, panel, first token and insert budgets are met or re-recorded. | PERFORMANCE |
## Out of scope for v1
Document/file translation, image OCR, speech, dictation, writing improvement, translation memory, glossaries, cloud accounts, automatic replacement, automatic copy, background clipboard translation, Linux/Windows/iOS, Mac App Store.
## Success measures
- A selected paragraph is translated and shown in under 2 s from the second ⌘C on a warm M-series Mac (first token), and in under 8 s for 250 output tokens.
- Replace succeeds in at least 8 of 10 tested apps; the remaining apps get a clear Copy fallback.
- Zero lost URLs or placeholders in the evaluation corpus, or a visible warning.
- No source text, translation or app name appears in logs.
- The user prefers the panel flow over switching to a browser translator for at least 8 of 10 sampled translations.
+96
View File
@@ -0,0 +1,96 @@
# Progress
The agent updates this file at the end of every task: check the box, add the ISO date, add one line of notes (deviations, follow-ups). Do not delete history.
Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
## M0 — Scaffold and tooling
- [ ] T0.1 Package.swift, module placeholders, fixtures load
- [ ] T0.2 App sources, Info.plist, menu-bar stub, entitlements
- [ ] T0.3 project.yml / XcodeGen
- [ ] T0.4 verify script, format/lint, logging + signposts
- [ ] T0.5 OpenCode 2.x doctor
- [ ] T0.6 Environment record and smoke run
## M1 — Ollama text client
- [ ] T1.1 Capture fixtures, resolve VERIFY items
- [ ] T1.2 HTTP client, endpoint policy, redirects, error mapping
- [ ] T1.3 Catalog (version, tags, show, ps)
- [ ] T1.4 Streaming chat client (NDJSON, timeouts, cancellation)
- [ ] T1.5 Warm-up, keep-alive, unload
- [ ] T1.6 sprachmittler-cli models / show / translate
## M2 — Hy-MT3 adapter and text pipeline
- [ ] T2.1 Adapter protocol, registry, sampling merge
- [ ] T2.2 Hy-MT3 adapter and byte-exact prompt
- [ ] T2.3 Language catalogue (102 languages)
- [ ] T2.4 Language detection, content classifier, chunker
- [ ] T2.5 Protected tokens, output validator, preamble detector
- [ ] T2.6 Prompt policy and documented fallbacks
- [ ] T2.7 Compatibility spike (gate)
## M3 — Double-copy capture
- [ ] T3.1 DoubleCopyDetector state machine
- [ ] T3.2 Pasteboard watcher and own-write suppression
- [ ] T3.3 Clipboard snapshot and restore
- [ ] T3.4 Services provider and menu item
- [ ] T3.5 Manual double-copy matrix
## M4 — Translation session and panel
- [ ] T4.1 TranslationSession actor and epochs
- [ ] T4.2 Panel controller and view model
- [ ] T4.3 Panel view with Copy and Replace
- [ ] T4.4 Target language, persistence, same-language
- [ ] T4.5 Error messages and recovery actions
- [ ] T4.6 Panel keyboard and accessibility
## M5 — Replace
- [ ] T5.1 InsertionCoordinator and target capture
- [ ] T5.2 Accessibility direct replacement
- [ ] T5.3 Paste fallback and clipboard restore
- [ ] T5.4 Safety checks and Copy fallback
- [ ] T5.5 Manual insertion matrix and permission onboarding
## M6 — Settings, onboarding, menu bar
- [ ] T6.1 AppSettings and persistence
- [ ] T6.2 Onboarding checks and window
- [ ] T6.3 Settings UI
- [ ] T6.4 Status menu, launch at login, diagnostics
- [ ] T6.5 End-to-end integration checkpoint (gate)
## M7 — Evaluation and the default-model gate
- [ ] T7.1 Corpus manifest and eval CLI
- [ ] T7.2 Metrics
- [ ] T7.3 Reports
- [ ] T7.4 Evaluation run
- [ ] T7.5 Default-model ADR (gate)
## M8 — Hardening and release
- [ ] T8.1 Privacy audit and self-test
- [ ] T8.2 Accessibility pass
- [ ] T8.3 Performance pass
- [ ] T8.4 German localisation and end-user README
- [ ] T8.5 Release script
- [ ] T8.6 Compatibility matrix completion
## Environment record
| Item | Value | Date |
|---|---|---|
| OpenCode version | 2.4.1 | 2026-11-26 |
| Ollama version | 0.40.18 | 2026-11-26 |
| Translation model | `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` (7.5B, Q4_K_M) | 2026-11-26 |
| Model resident memory | 6.49 GB with `num_ctx` 8192 | 2026-11-26 |
| Mac (chip, memory) | Apple M5 Pro, 48 GB | 2026-11-26 |
| macOS | 27.2.1 (26B131) | 2026-11-26 |
| Xcode / Swift | Xcode 27.2 / Swift 6.4.2 | 2026-11-26 |
| Reference speed | 246 output tokens in 6.52 s, 44.6 tok/s | 2026-11-26 |
## Notes log
<!-- YYYY-MM-DD · T<m>.<n> · note -->
2026-11-26 · kit · Package scaffold, docs and OpenCode 2.x configuration created. Package build/test and app build verified.
2026-11-26 · kit · Canonical prompt validated against the real 7B model: 178 prompt tokens, 246 output tokens, 44.6 tok/s. URL, e-mail, `{{placeholder}}`, Markdown and JSON preservation checked with the default prompt.
2026-11-26 · kit · Owner reference run recorded: 255 output tokens, 43.07 tok/s, 5.97 s warm, 177/178 prompt tokens cached.
2026-11-26 · kit · `make smoke` passed with 7B Q4_K_M: 34 output tokens in 2.89 s, 45.81 tok/s, cold load 2.05 s.
2026-11-26 · kit · `make fixtures` captured version, tags, ps, show, en→de, de→en, Markdown, truncated and missing-model fixtures. Digest `262ac792aeb5`.
+77
View File
@@ -0,0 +1,77 @@
# Security and privacy requirements
These are hard requirements. The `swift-reviewer` agent checks every change against this list; `scripts/privacy-check.sh` automates what can be automated.
## Data handling
| ID | Requirement | How to verify |
|---|---|---|
| SP-1 | The pasteboard is read only after an explicit user action (double copy, menu item, Services). No background reading, no folder watching. | No `FSEventStream`, `NSFilePresenter` or timer that reads content without a change event. |
| SP-2 | Selected text, translations, prompt text, pasteboard strings, app names and paths never appear in logs in clear. | All `Logger` interpolations of such values use `privacy: .private`; grep for `\(text`, `\(translation`, `\(string`, `\(app`, `\(url`, `\(path` without `.private`. |
| SP-3 | No telemetry, analytics, crash-reporting SDKs or accounts. | `Package.resolved` contains only allowed dependencies; no SDK names in sources. |
| SP-4 | Network requests only to the configured Ollama endpoint. | `URLSession` and `URLRequest` appear only in `SprachmittlerOllama`. |
| SP-5 | Default endpoint is loopback. Non-loopback requires `allowRemoteEndpoint == true` and an `https` scheme. | `EndpointPolicyTests`. |
| SP-6 | Redirects are refused; the session is ephemeral (no cookies, no URL cache, no credential storage). | `RedirectRefusalTests`; grep for `URLSessionConfiguration.ephemeral`. |
| SP-7 | No translation history. Source text and translations are never written to disk, caches, logs or UserDefaults. | Code review; privacy check for text fields in settings; no file writes outside settings. |
| SP-8 | Copy writes the clipboard only when the user clicks Copy. Replace snapshots the clipboard, writes the translation, pastes, and restores the snapshot. | `ClipboardSnapshotTests`; manual checklist. |
| SP-9 | The clipboard snapshot lives in memory for one replacement, is restored even on failure, and is never logged. | `ClipboardSnapshotTests`; code review. |
| SP-10 | Permissions are minimal: Accessibility optional and only for Replace; no Input Monitoring, Screen Recording, Camera, Microphone or Apple Events. Entitlements are exactly `app-sandbox = false`. | `privacy-check.sh` compares the entitlements and Info.plist keys. |
| SP-11 | Selected and translated text is treated as data: never executed, never inserted into another prompt except as the user-initiated source, never used to choose actions. | Code review. |
| SP-12 | Warm-up and fixtures use only fixed synthetic text; no user text is sent anywhere except as the text being translated. | Code review; `capture-fixtures.sh` uses only fixtures. |
| SP-13 | Our own clipboard writes are marked and suppressed so the watcher cannot translate the translation. | `OwnWriteSuppressionTests`. |
| SP-14 | Replace verifies the source app and, when available, the selected text before changing it; it aborts on a mismatch. | `InsertionTargetTests`. |
| SP-15 | The app never requests Accessibility on the double-copy path and never prompts repeatedly. | Code review; manual checklist. |
## Entitlements and runtime
- App Sandbox: **disabled** (ADR-003), because Accessibility replacement requires it. Hardened Runtime: **enabled**.
- Entitlements are exactly `com.apple.security.app-sandbox = false`. No network entitlement is needed outside the sandbox.
- No `com.apple.security.cs.allow-unsigned-executable-memory`, `disable-library-validation`, `allow-jit` or other hardened-runtime exceptions.
- ATS: `NSAllowsLocalNetworking = true` only. No `NSAllowsArbitraryLoads`.
- Info.plist: `LSUIElement = true`, `NSServices` for "Translate with Sprachmittler", no microphone/camera/screen/Input Monitoring/Apple Events usage descriptions.
## Permissions
| Permission | Use | Request policy |
|---|---|---|
| Accessibility | Replace (AX direct set or synthetic ⌘V) | Only when the user clicks Replace, or from onboarding if they opt in. `AXIsProcessTrustedWithOptions` is never called on the trigger path. |
| Input Monitoring | Nothing | Never requested. The app does not install a key tap. |
| Screen Recording | Nothing | Never requested. No screenshots, no `CGWindowListCreateImage`, no `SCStream`. |
| Camera / Microphone | Nothing | Never requested. No `AVCaptureDevice`. |
| Apple Events | Nothing | Never requested. No `NSAppleScript` / `AEDeterminePermissionToAutomateTarget`. |
## Clipboard rules
1. Poll only `changeCount`; read `.string` only when it changes.
2. Require two changes within the window with identical, non-empty text.
3. Ignore our own writes (`com.schihei.sprachmittler.own`), `org.nspasteboard.TransientType` and `org.nspasteboard.ConcealedType`.
4. Keep at most two strings in memory; clear them after the session starts or the window expires.
5. Snapshot all pasteboard items and types before a paste fallback; force lazy data up front; restore only if `changeCount` still matches our write.
6. Never log clipboard content, not even truncated.
7. Copy is user-initiated; Replace restores the previous clipboard. There is no automatic clipboard mutation.
## Endpoint policy (pseudo-code)
```swift
func validate(_ url: URL, allowRemote: Bool) throws {
guard let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme) else { throw EndpointRejection.scheme }
guard url.user == nil, url.password == nil, url.query == nil, url.fragment == nil else { throw EndpointRejection.form }
let host = url.host?.lowercased() ?? ""
let isLoopback = ["127.0.0.1", "localhost", "::1"].contains(host)
if isLoopback { return }
guard allowRemote else { throw EndpointRejection.remoteNotAllowed }
guard scheme == "https" else { throw EndpointRejection.remoteRequiresHTTPS }
}
```
## Logging
- Allowed: model name, digest prefix, token counts, durations, character counts, chunk counts, warning kinds, error kinds, changeCount deltas, short SHA-256 hashes at `privacy: .private`.
- Forbidden: selected text, translations, prompt text, pasteboard strings, clipboard item types that identify content, app names, file paths, e-mail addresses, URLs.
- Diagnostics is an in-memory, bounded list of error kinds and timings. It has no text field.
## Licensing notice (product, not code)
- Sprachmittler bundles no models.
- Hy-MT3 is Apache-2.0 per the model card. Settings shows the licence status and model digest; this is guidance, not legal advice.
- Before commercial distribution, re-check the model card and the GGUF conversion provenance and record the result in an ADR.
+212
View File
@@ -0,0 +1,212 @@
# Selection, clipboard and replacement
Module: `SprachmittlerCapture`. This is the only module that may import `ApplicationServices` or touch `NSPasteboard`.
## 1. Principles
1. Capture only on an explicit user action: the double-copy gesture, the menu item, or Services.
2. No global key tap, no Input Monitoring, no Accessibility observers, no screen capture.
3. Read the pasteboard string only after `changeCount` changes.
4. Keep at most the last two strings in memory; never log them; clear them when the session starts or the window expires.
5. Never replace text without an explicit click on **Replace**.
6. Verify the source app and, when available, the selected text before replacing.
7. If anything is uncertain, offer Copy instead of guessing.
## 2. Double-copy trigger
```text
poll changeCount every 120 ms
│
├─ unchanged → nothing
│
└─ changed
├─ is our own write / transient? → ignore, suppress 750 ms
├─ read string; trim; empty? → reset
├─ first change? → remember (hash, string, time)
└─ second change?
├─ within 500 ms and identical text? → emit CapturedText
└─ otherwise → replace the remembered value with this copy
```
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.
- 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.
### State machine
```mermaid
stateDiagram-v2
[*] --> idle
idle --> firstCopy: change with text
firstCopy --> idle: window expires / empty / own write
firstCopy --> triggered: second change, same text, in window
triggered --> idle: session started
triggered --> triggered: new trigger replaces session
```
### Own-write suppression
Every clipboard write by Sprachmittler adds:
- `com.schihei.sprachmittler.own` (custom marker), and
- `org.nspasteboard.TransientType` plus `org.nspasteboard.ConcealedType` (nspasteboard.org conventions).
The watcher ignores a change if any of those types is present, and ignores all changes for **750 ms** after a write. This prevents translating the translation and prevents the Replace paste from re-triggering.
## 3. Clipboard snapshot and restore
Used only for the synthetic-paste **Replace** fallback.
```text
1. snapshot = every item of NSPasteboard.general, every type, with Data forced
2. changeCount c0 = current
3. clearContents(); write translation + own/transient markers; changeCount c1
4. post ⌘V to the target PID
5. wait up to 300 ms for the paste to be delivered
6. if current changeCount == c1: clearContents(); restore snapshot
7. else: leave the clipboard alone (the user or another app changed it)
```
Limits to document:
- Lazy pasteboard data is forced up front; a provider that never resolves cannot be restored.
- Types with no data cannot be restored.
- A copy that lands after the restore window is not undone.
- If restore fails, report `pasteboardRestoreFailed` and leave the translation on the clipboard; Copy remains available.
## 4. Replacement
```swift
public protocol TextInserting: Sendable {
func replace(selection: CapturedText, with translation: String,
target: InsertionTarget) async throws -> InsertionOutcome
}
public struct InsertionTarget: Sendable, Equatable {
public let pid: pid_t
public let bundleID: String?
public let selectedText: String?
public let capturedAt: Date
}
```
### Strategy order
1. **Accessibility direct replacement** (preferred)
- Requires Accessibility trust.
- Get the focused element (`kAXFocusedUIElementAttribute`).
- Read `kAXSelectedTextAttribute`; it must equal the captured source (after T1 normalization).
- Set `kAXSelectedTextAttribute` to the translation.
- No clipboard mutation; undo is app-dependent.
2. **Synthetic paste fallback**
- Requires Accessibility trust to post events.
- Verify the source app is still frontmost and the target PID matches.
- Snapshot the clipboard, write the translation, post ⌘V to the target PID, restore the snapshot.
- Undo is the source app's normal paste undo.
### Safety rules
- Abort with `insertionTargetChanged` if the frontmost app is not the target.
- Abort if Accessibility is trusted and the selected text no longer equals the source.
- Never insert into a secure input field or a field that reports no settable selection.
- Block Replace when validation has a blocking warning (preamble, truncation, repetition, lost protected token).
- On failure, keep the panel open, show `userMessage` and offer Copy.
## 5. Permissions
| Permission | Needed for | When requested |
|---|---|---|
| Accessibility | Replace only | On the first Replace click (or onboarding if the user opts in). Never on the double-copy path. |
| Input Monitoring | Nothing | Never |
| Screen Recording | Nothing | Never |
| Camera / Microphone | Nothing | Never |
| Apple Events | Nothing | Never |
Check with `AXIsProcessTrusted()`. Prompt with `AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt: true])` only from onboarding or an explicit Replace click. Deep link: `x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility`.
If Accessibility is denied:
- Double copy, translation, Copy and Services still work.
- The Replace button remains visible but explains "Replace needs the Accessibility permission" and offers "Open System Settings" and "Copy instead". Do not nag on every trigger.
## 6. Services entry point
Info.plist:
```xml
<key>NSServices</key>
<array>
<dict>
<key>NSMenuItem</key>
<dict><key>default</key><string>Translate with Sprachmittler</string></dict>
<key>NSMessage</key><string>translateSelection</string>
<key>NSPortName</key><string>Sprachmittler</string>
<key>NSSendTypes</key>
<array><string>public.utf8-plain-text</string><string>NSStringPboardType</string></array>
<key>NSRequiredContext</key><dict/>
</dict>
</array>
```
`AppDelegate` sets `NSApp.servicesProvider` to `ServicesProvider` in `SprachmittlerCapture` and calls `NSUpdateDynamicServices()`. The service receives an `NSPasteboard` from the system; it needs no polling and no Accessibility. Users can bind a shortcut under System Settings ▸ Keyboard ▸ Keyboard Shortcuts ▸ Services ▸ Text. After first install, a logout/login or `/System/Library/CoreServices/pbs -update` may be needed.
## 7. Compatibility matrix
**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.
For each app test:
1. A plain paragraph.
2. Several paragraphs.
3. Text with a hyphenated line break.
4. A URL and an e-mail.
5. An empty selection (nothing should be translated).
6. Copy, then Replace; check ⌘Z and the previous clipboard (rich text or image).
| App | Bundle ID | Double copy | Replace (AX) | Replace (paste) | Clipboard restored | Notes |
|---|---|---|---|---|---|---|
| Safari | com.apple.Safari | ☐ | ☐ | ☐ | ☐ | |
| Google Chrome | com.google.Chrome | ☐ | ☐ | ☐ | ☐ | Electron-like; `AXManualAccessibility` |
| Firefox | org.mozilla.firefox | ☐ | ☐ | ☐ | ☐ | |
| Preview | com.apple.Preview | ☐ | ☐ | ☐ | ☐ | PDF text |
| Pages | com.apple.iWork.Pages | ☐ | ☐ | ☐ | ☐ | |
| Microsoft Word | com.microsoft.Word | ☐ | ☐ | ☐ | ☐ | |
| Mail | com.apple.mail | ☐ | ☐ | ☐ | ☐ | |
| Notes | com.apple.Notes | ☐ | ☐ | ☐ | ☐ | |
| TextEdit | com.apple.TextEdit | ☐ | ☐ | ☐ | ☐ | Baseline |
| Visual Studio Code | com.microsoft.VSCode | ☐ | ☐ | ☐ | ☐ | Electron |
| Obsidian | md.obsidian | ☐ | ☐ | ☐ | ☐ | Electron |
| Slack | com.tinyspeck.slackmacgap | ☐ | ☐ | ☐ | ☐ | Electron |
| Terminal | com.apple.Terminal | ☐ | ☐ | ☐ | ☐ | Empty selection may copy the line |
Legend: ✅ works · ⚠️ partial (describe) · ❌ unsupported · ☐ not tested.
### Top failures to fix
| # | App | Path | What happens | Fix task |
|---|---|---|---|---|
| 1 | | | | |
| 2 | | | | |
| 3 | | | | |
## 8. Failure modes and messages
| Situation | User message | Recovery |
|---|---|---|
| No text after two copies | "No text was copied." | Nothing; copy again |
| Text too long | "This selection is too long (limit 4,000 characters)." | Shorten it or use the CLI |
| Ollama unreachable | "Ollama is not running." | Start Ollama |
| Model missing | "The Hy-MT3 model is not installed." | Copy the `ollama pull` command |
| Accessibility denied | "Replace needs the Accessibility permission." | Open System Settings / Copy instead |
| App does not accept replacement | "This app did not accept the replacement." | Copy instead |
| Selection changed | "The selection changed before Replace." | Copy instead |
| Pasteboard restore failed | "The previous clipboard could not be restored." | Translation is on the clipboard |
| Preamble warning | "The model added an explanation." | Review, Copy, or retry |
| Truncated | "The translation was cut off." | Retry or shorten |
| Repetition loop | "The translation started repeating." | Retry with the 1.8B or a shorter selection |
+75
View File
@@ -0,0 +1,75 @@
# Testing strategy
Framework: **Swift Testing** (`import Testing`, `@Test`, `#expect`) for all package tests. XCTest only where Swift Testing lacks support, e.g. performance `measure`.
## Layers
| Layer | Scope | Where | Runs in `make verify` |
|---|---|---|---|
| Unit | Pure logic: language mapping, chunking, token scanning, prompt building, option mapping, validation, settings, chrF/BLEU | `Packages/SprachmittlerKit/Tests/*Tests` | yes |
| Contract | Ollama client against recorded fixtures through `URLProtocol` stubs; request encoding | `SprachmittlerOllamaTests`, `SprachmittlerEnginesTests` | yes |
| Component | `TranslationSession` + `DoubleCopyDetector` + `InsertionCoordinator` with fakes, a manual clock and a fake pasteboard | `SprachmittlerCoreTests`, `SprachmittlerCaptureTests` | yes |
| Live integration | Real Ollama on localhost, opt-in via `SPRACHMITTLER_LIVE=1` | `SprachmittlerLiveTests` | no; `make live-test` |
| Evaluation | Model comparison on the private corpus | `sprachmittler-cli eval` | no; `/evaluate` |
| Manual | Double copy, panel focus, Accessibility replacement, clipboard restoration, Services, VoiceOver, real translation quality | checklist below | no |
## Rules
- Every bug fix starts with a failing test, unless it is only reproducible manually. In that case, add a manual checklist item.
- No test may depend on the network or a real model unless it is in `SprachmittlerLiveTests`.
- Time-dependent logic (double-copy window, timeouts) takes an injected clock. Tests use a manual clock; never `Task.sleep` with real time.
- Fakes live in `SprachmittlerTestSupport`: `FakePasteboard`, `FakeClock`, `FakeOllamaTransport`, `FakeTextInserter`, `FakeAccessibility`, `FakeSettingsStore`, `TemporaryDirectory`.
- Fixtures live inside their test target (SwiftPM resources must sit within the target) and are loaded with `Bundle.module`. All fixtures are **synthetic**; never add private text.
- Golden files for prompts, Markdown and JSON output live next to the tests (`Fixtures/golden/`); update them only with an explanation in the commit message.
## Required test cases (minimum)
Text:
- `Chunker` splits a 9000-character Latin text into paragraphs, never inside a grapheme; CJK text uses the 2000-character limit; join round-trips exactly.
- `ProtectedTokenScanner` finds URLs (with query and fragment), e-mails, `{{var}}`, `${var}`, `%s`, `%d`, `%1$@`, Markdown code spans, fenced blocks and HTML tags; does not flag ordinary punctuation.
- `LanguageDetector` identifies a German paragraph and an English paragraph; short/mixed text reports low confidence.
- `OutputValidator` flags a missing URL, a preamble, `done_reason: "length"`, a repetition loop and an empty output; clean output has no warnings.
Ollama client:
- NDJSON line split across chunks is decoded; `done_reason: "length"` reaches the caller; cancel mid-stream cancels the URL task; idle timeout fires with the manual clock; 404 missing model → `modelNotInstalled`; redirect is refused; `num_ctx` and option names are encoded exactly.
Engines:
- The default prompt equals the documented string byte for byte, including the blank line and the bold markers.
- The prompt prefix is identical for the same target language and differs only in the source text.
- `German`, `Chinese`, `Traditional Chinese`, `Portuguese`, `Norwegian`, `Norwegian Nynorsk`, `Arabic Kazakh` and `Cyrillic Kazakh` map correctly.
- Sampling merge: publisher values override model defaults; no unknown keys are sent.
- Structured Data 1 and Delimiters prompts are byte-exact fallbacks; no free-form prompt can be constructed.
Session and insertion:
- One translation in flight; a new trigger cancels the old task; late deltas from the old epoch are dropped.
- A blocking warning disables Replace; Copy stays enabled; a clean result enables Replace.
- Replace aborts when the source app changed, when the selected text changed, or when Accessibility is denied.
- AX direct replacement is preferred; paste fallback is used when AX fails; the clipboard snapshot is restored; own writes are suppressed.
- The double-copy detector requires identical text within the window and ignores empty/whitespace-only text.
Evaluation:
- chrF and BLEU match hand-computed values on a tiny pair.
- Protected-token retention is 1.0 for a clean pair and 0.0 for a lost URL.
- Numeric normalisation treats `1,5`, `1.5` and `1 5` as the same value only where documented.
## Manual release checklist
- [ ] First launch: onboarding shows correct states with Ollama stopped, model missing, Accessibility denied.
- [ ] Select a paragraph in Safari, Mail, TextEdit, Notes, Word, Pages, Slack, VS Code, Obsidian and Terminal; press ⌘C twice; the panel appears without stealing focus.
- [ ] Copy the translation; paste it into the source app; the source text is unchanged.
- [ ] Click Replace in TextEdit, Notes, Safari and Mail; the selection is replaced; ⌘Z restores it.
- [ ] Deny Accessibility: Copy and Services work; Replace explains what to enable and offers the right System Settings page.
- [ ] Replace with a rich-text or image clipboard: after the paste fallback, the previous clipboard is back.
- [ ] Copy two different things quickly: no translation is triggered.
- [ ] Copy the same text twice slowly: no translation is triggered. Change the window in Settings and repeat.
- [ ] Translate a long multi-paragraph text: chunks are joined with the original paragraph breaks; a failed chunk is visible.
- [ ] Translate text with a URL, an e-mail and `{{placeholder}}`: all survive or a warning appears.
- [ ] Translate Markdown and JSON: keys/formatting survive.
- [ ] Change the target language while streaming: the old request is cancelled and the new one starts.
- [ ] Services ▸ Translate with Sprachmittler works without Accessibility.
- [ ] VoiceOver can operate the panel and Settings; every action has a keyboard path.
- [ ] Console.app shows no selected text, translation, pasteboard content, app name or path.
- [ ] Quit during a translation: no orphaned request; `ollama ps` shows no hanging request.
- [ ] Reinstall the app and re-grant Accessibility if macOS requires it.
- [ ] Remote endpoint: `http://` remote refused; `https://` accepted only with the toggle.
- [ ] Launch at login mirrors the system setting.
+120
View File
@@ -0,0 +1,120 @@
# Translation output
Modules: `SprachmittlerText` (analysis, chunking), `SprachmittlerEngines` (prompt selection, validation). Load the `translation-quality` skill before changing anything here.
## 1. Prompt policy
- **Default Translation** is the canonical prompt for v1. It is byte-exact in `docs/HYMT3_MODEL.md` §3.
- **Structured Data 1** is used for JSON, HTML and Markdown tables when the content class says so, or as a fallback if a protected token is lost in a structured source.
- **Delimiters** is the single documented retry when a protected token is lost in plain/delimited text.
- **Terminology**, **Style** and **Structured Data 2** are reserved for future glossary/style/context features; not v1.
- No other prompt text is allowed. The user cannot type a prompt in v1.
The prompt prefix depends only on the target language. Append the source last. Do not add timestamps, app names, source language or dynamic instructions.
## 2. Input normalisation (N1–N3)
| Rule | Transformation | Notes |
|---|---|---|
| N1 | Line endings → `\n`; strip BOM, NUL and C0 controls except `\t` and `\n`; Unicode NFC. | Applied to the source before analysis and to the translation after T1. |
| N2 | Trim outer whitespace. | Internal whitespace is preserved. |
| N3 | Keep zero-width joiner/non-joiner; strip U+200B. | They matter in Indic scripts and emoji sequences. |
## 3. Chunking
- 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.
- 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.
## 4. Protected tokens
Scan the source for:
| Kind | Pattern examples |
|---|---|
| URL | `https://…`, `http://…`, `www.…` |
| E-mail | `name@example.com` |
| Mustache | `{{name}}`, `{{ name }}` |
| Template literal | `${name}` |
| printf | `%s`, `%d`, `%1$@`, `%02d` |
| Markdown code span | `` `code` `` |
| Fenced code block | ```` ```…``` ```` |
| HTML tag | `<a href="…">`, `</div>` |
| JSON key | a quoted string followed by `:` inside a JSON object |
| File path | `/Users/…`, `C:\…` (best effort) |
Validation: every protected token in the source must appear in the translation exactly once (or the same count). If one is missing:
1. Retry once with the documented **Delimiters** prompt (or **Structured Data 1** for JSON/HTML/Markdown).
2. If it is still missing, warning `missingProtectedToken`; Replace is disabled by default; Copy remains available.
Do not substitute tokens with sentinels in v1: sentinels can leak into the output and are harder to audit.
## 5. Output rules T1–T4
| Rule | Transformation | Default |
|---|---|---|
| T1 | Strip leading/trailing whitespace and NUL; line endings → `\n`. | on |
| T2 | Preserve internal whitespace, line breaks, Markdown, HTML, LaTeX and code exactly as produced. | always |
| T3 | No spelling, grammar, style, terminology or punctuation edits. No de-duplication. No "cleanup" of model wording. | always |
| T4 | Do not strip a preamble or explanation. Detect it, warn, keep the raw text, disable Replace by default. | always |
The panel shows the T1 output. There is no hidden rewrite. If the model returns a preamble, the user sees it.
## 6. Preamble detection
Heuristic (not a rewrite):
- The first non-empty line is at most 80 characters.
- It ends with `:` (or `:`).
- It is followed by a blank line and at least one more non-empty line.
- It matches common forms in the target language or English: "Here is the translation", "Translation", "Übersetzung", "Hier ist die Übersetzung", "Translation:", etc. A pure `:` heuristic with the length rule is enough for v1; keep the list in one file.
If detected: warning `preambleDetected(firstLine:)`; the panel shows a banner; Replace is disabled by default; the user can Copy the raw text or click Retry.
## 7. Truncation and repetition
- `done_reason == "length"` → warning `truncated`; Replace disabled by default.
- Repetition: the same normalised line (≥ 8 chars) repeated ≥ 6 times consecutively, or a 64-character window repeated ≥ 8 times in the last 2048 characters. Cancel the stream early and warn `repetitionLoop`.
- Empty output after T1 → `emptyOutput`; no Copy/Replace of an empty string.
## 8. Same-language input
If `NLLanguageRecognizer` reports the target language with confidence ≥ 0.5 and all detected candidates agree, show "This text already appears to be in {language}" and offer "Translate anyway". Do not block: short text, names and mixed text are often misdetected.
## 9. Numbers and units
Do not require exact string equality: locales legitimately change decimal and thousands separators. Normalise numeric tokens (remove spaces and thousands separators; map `,`/`.` in ambiguous cases) and require the numeric value to be present. Units may be translated (`tokens/s` → `Token/s`); human review covers meaning.
## 10. CLI JSON output
`sprachmittler-cli translate --json` emits:
```json
{
"schema": "sprachmittler-translation-v1",
"sourceLanguage": "en",
"targetLanguage": "de",
"model": "hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M",
"sourceCharacters": 148,
"translation": "Die obige Grafik …",
"warnings": [],
"timing": { "firstTokenMs": 980, "totalMs": 6520, "promptTokens": 178, "outputTokens": 246 }
}
```
No source text is included unless `--include-source` is passed explicitly for debugging. Never write this JSON to disk automatically.
## 11. Tests
- Prompt selection for each content class; default stays default.
- Chunker round-trip and limits.
- Every protected-token kind; missing-token retry; second failure blocks Replace.
- Preamble, truncation, repetition, empty output.
- Same-language warning.
- T1 only: internal whitespace, Markdown and code unchanged.
- Numeric normalisation.