Compare commits

..
15 Commits
Author SHA1 Message Date
schihei 2a601058f4 feat(capture): translate long selections in parts
The capture gate and the chunk size were the same number, so a selection above one chunk was rejected before the pipeline could split it; the Settings sliders moved both thresholds together. Add maximumPartsPerSelection (1-8, default 1, so existing behaviour is unchanged). The capture limit is now part size x parts and travels on TranslationSessionRequest, so the watcher, CapturePolicy and TranslationSession agree for that capture. TranslationStreaming gained an optional per-part callback; the session emits chunkStarted and the panel shows 'Part 2 of 4' while streaming and '2 parts' when finished. textTooLong now points at Settings and offers an Open Settings button. Lower the dense-script part-size maximum to 4000 because 5000 dense characters plus a 4096-token output can overflow the 8192-token context. Tests cover capture limits, watcher limits, pipeline part callbacks, session events and limits, panel progress, settings clamping and migration. Docs updated: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES and README. Verified: make verify green; live 4355-character German text showed Part 1 of 2, Part 2 of 2 and '2 parts'; with one part the panel showed the too-long message and Open Settings.
2026-11-27 20:21:30 +01:00
schihei 9f89000b0d fix(panel): keep the picked language when overriding the target
The header language picker set the effective target and then re-ran prepare, where TranslationDirectionPolicy only knew a Bool override and returned the mother tongue. Any picked language other than the mother tongue was discarded, so the panel appeared not to change. The policy now takes the override target itself, and PanelViewModel stores it, so a picker choice wins over a rule for that capture; a new capture returns to the rule/mother tongue. Move the shared panel test scaffolding into PanelTestSupport and the routing tests into PanelRoutingTests, and add picker and rule-override tests. Verified: make verify green; live checks with a German -> English rule show the picker switching to French, the next capture back to English with the banner, and the banner override to German.
2026-11-27 10:38:16 +01:00
schihei bd8e3db82d fix(settings): retranslate when language rules change
When Settings saves a changed languageRoutes table, retranslate an open panel so the new rule is visible immediately. Verified with make verify.
2026-11-26 18:32:40 +01:00
schihei 940abcc996 feat(settings): mother-tongue language routing table
Replace the single reverse-direction pair with a general routing table. The saved target is the mother tongue and the default target for every source; languageRoutes is an empty-by-default, source-unique list of source-to-target rules (for example Chinese -> English, Traditional Chinese -> English, German -> English). Rules apply only when the source is confidently detected; otherwise the mother tongue is used. Same-language rules are dropped.\n\nThe panel shows the effective direction and a banner explaining a rule, with a one-capture override back to the mother tongue; the panel picker is now a session-only override. Persistent rules are edited in Settings. The old autoSwitchTarget/fallbackTargetLanguage keys are ignored, so the default after migration is everything -> mother tongue.\n\nAdd LanguageRoute, generalize the direction policy and tests, add the rules UI, and update ADR-022, architecture, translation output, user guide, README and progress. Verified: make verify green; empty rules translate French -> German, a Chinese -> English rule produces Chinese (Simplified) -> English with the banner, and the rules table renders in Settings.
2026-11-26 18:31:45 +01:00
schihei 41f1cea769 feat(panel): optional reverse direction for target-language text
Add opt-in automatic reverse translation for a two-language pair. autoSwitchTarget defaults on with fallbackTargetLanguage English (or German when the target is English); the saved target and the effective request target are separate. Confident source-equals-target text uses the fallback, the header and a panel banner show the effective direction, and the banner can override the direction for one capture without changing the saved target. The language picker still changes the saved target, and changing the target to the fallback swaps the pair. JSON/HTML/code handling is unchanged.\n\nFilter near-zero NLLanguageRecognizer hypotheses so the existing high-confidence same-language rule works for real text. Add resolver, settings, view-model, detector and persistence tests; document ADR-022, the panel, settings and user guide. Verified: make verify green; German text with target German/fallback English renders German → English with the banner, English text stays English → German, a real click on the override shows German → German, and a new German capture switches back to English.
2026-11-26 17:34:11 +01:00
schihei 7c9cece201 docs(readme): present the app instead of the starter kit
Rewrite README.md around the shipped menu-bar app: features, requirements, install from source, usage (Esc, click-outside, Markdown, Replace), privacy, architecture, status and a compact development section. Remove the starter-kit framing, placeholder/stub claims and the kit verification section; update the ADR/module counts and document the transient outside-click monitor.
2026-11-26 17:19:13 +01:00
schihei 39ec191348 feat(panel): dismiss when clicking outside
Close the panel when a mouse-down is sent to another app. The panel observes didResignKey for clicks that make another window key, and installs a transient global mouse-down monitor while visible for clicks outside an open popover or when the panel was not made key. Global monitors ignore events sent to this app, so clicks in the panel and its popover are unaffected; the event is discarded and the monitor is removed on close. Add the dialog guards for recursive close and document the monitor in ADR-009, the architecture, the privacy table and the user guide.\n\nVerified: make verify green; inside clicks keep the panel open; outside clicks close it with closeWithEscape on and off; an outside click while the language popover is open closes both. Replace still works.
2026-11-26 15:34:56 +01:00
schihei a3e544fbe4 feat(panel): close with Esc without a click and render Markdown
Esc: make the panel key when shown (closeWithEscape, default on) without activating the app; the source app stays frontmost and Replace still targets it. Handle Esc with SwiftUI's exit command, which also works from the popover and after clicking controls. Add TranslationPanel.canBecomeKey and amend ADR-009.\n\nMarkdown: add MarkdownPresentation in SprachmittlerText (Foundation inline parser plus a conservative block parser for headings, lists, quotes, fenced code and rules), a SwiftUI MarkdownTranslationView, and a renderMarkdown setting (default on). JSON, HTML and code sources are never rendered; only http/https links open; images become alt text; Copy and Replace keep the raw Markdown (ADR-021).\n\nVerified: make verify green; synthetic Esc closes the panel and closes an open language popover first; a live Markdown translation rendered heading, bold/italic, inline code, list, quote, code block and link; Copy returned the raw Markdown; Replace still changed the TextEdit selection with the panel key.
2026-11-26 15:26:30 +01:00
schihei d126124f97 fix(panel): drag the window manually and make the whole header a drag bar
performDrag did nothing while the app was inactive (verified: mouseDown reached the drag view, performDrag returned, the frame never changed). Move the window from the screen-space mouse delta in mouseDown/mouseDragged instead.

Make the header a full-width 56 pt bar flush with the panel top, with the drag view behind it and the language/gear buttons above, so the whole top area moves the panel.

Verified: make verify green; synthetic drags from the title, top edge, empty header and grip moved the panel by the full delta while Finder was frontmost; body drag does not move it.
2026-11-26 15:03:31 +01:00
schihei f8064ac430 fix(panel): keep source available after it is collapsed
Render the source disclosure whenever the source-preview setting is enabled, instead of hiding it when its expanded state is false. The collapsed label becomes 'Show source' with a matching tooltip and localized English/German strings, so the source can be reopened.

Verified: make verify green.
2026-11-26 14:47:04 +01:00
schihei f466e6dd1c fix(panel): enlarge drag surface to the header block
The 18x28 grip was too small. Wrap the grip, icon, title and language subtitle in a 44 pt-high native performDrag area; the SwiftUI content is hit-testing-disabled so the whole left header block starts a window drag. Make the grip a visible 24x32 capsule with an open-hand cursor and a localized tooltip.

Verified: make verify green; a synthetic drag starting on the title area moved the panel by the full delta, and the panel screenshot confirms the larger grip and 17 pt translation text.
2026-11-26 14:42:58 +01:00
schihei 40733473c5 fix(panel): draggable header and configurable translation text size
Add a native AppKit drag grip to the non-activating panel header; it accepts the first mouse and calls performDrag, so the panel can be moved before it becomes key. Keep a moved position while the panel stays visible and only recenter near the cursor when it is shown again (DeepL-like transient position).

Add persisted translationFontSize (default 17 pt, range 12–28) to AppSettings and PanelConfiguration, apply it to the translation text, and expose a native Settings stepper. Add English/German strings and AppSettings clamp/round-trip tests.

Verified: make verify green; synthetic double-copy opened the panel, dragging the grip moved the window, and a 22 pt capture showed the larger translation text.
2026-11-26 14:35:34 +01:00
schihei 2cce12ff17 feat(app): family app icon, Release install and local dmg
Add a committed AppIcon asset catalog generated from scripts/generate-app-icon.swift, using the same indigo tile/grid/text-bar family as Vorleser and Schriftleser with a two-speech-bubble translation motif. Wire CFBundleIconName/ASSETCATALOG_COMPILER_APPICON_NAME and add make icon.

Change make install to use the Release build and the same signature checks as the DMG. Add make dmg/scripts/make-dmg.sh: stage the Release app with an Applications link, create and verify a local unnotarised DMG, mount it, and re-check the signature.

Verified: make verify green; make dmg produced dist/Sprachmittler-0.1.0-local.dmg with a valid signature; make install installed and launched /Applications/Sprachmittler.app.
2026-11-26 14:19:44 +01:00
schihei 0ab5ae78bf feat(m7-m8): evaluation harness, privacy self-test, localisation and release
M7: corpus manifest loader/validation, chrF/BLEU/token/numeric metrics, raw-output and report.md/report.json writer, and sprachmittler-cli languages/detect/eval. A synthetic 4-segment run with the 7B validated the harness; the private-corpus and 1.8B evaluation and the default-model ADR remain open.

M8: privacy-check root fixture + seeded self-test wired into make verify; English/German localisation for the app shell; end-user USER_GUIDE; release.sh (unsigned archive, Developer ID sign, notarise/staple, DMG, --dry-run); idle CPU/memory and warm 7B measurements in PERFORMANCE.

Docs: PROGRESS M7–M8, MODEL_EVALUATION results log/gate status, PERFORMANCE measurements, TESTING evaluation cases, ADR-008 status. Compatibility/VoiceOver/notarisation gates remain manual.

Verified: make verify green (format, strict lint, privacy self-test, Debug+Release signatures, 227 package tests); CLI languages/detect/eval run; release dry-run.
2026-11-26 14:16:21 +01:00
schihei a78572adc3 feat(m4-m6): session, panel, Replace, settings and onboarding
M4: TranslationSession actor with epochs/one-in-flight streaming, PanelViewModel, non-activating NSPanel, streaming panel UI, searchable/recent target languages, warnings/errors and Copy/Retry/Replace actions.

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

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

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

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

No files matched your search

+2
View File
@@ -2,11 +2,13 @@
*.xcodeproj/
!*.xcodeproj/project.xcworkspace/xcshareddata/
.build/
build/
DerivedData/
xcuserdata/
*.xcuserstate
.swiftpm/
Packages/SprachmittlerKit/.build/
build/
Packages/SprachmittlerKit/.swiftpm/
dist/
out/
+84 -12
View File
@@ -1,40 +1,112 @@
import AppKit
import Combine
import os
import SprachmittlerCore
/// Lifecycle glue: composition root, Services provider, double-copy watcher, termination.
/// Lifecycle glue: composition root, Services provider, watcher, panel and windows.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
final class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
let environment: AppEnvironment
private let loggers = Loggers(subsystem: Bundle.main.bundleIdentifier ?? "Sprachmittler")
private var environment: AppEnvironment?
@Published private(set) var menuState = StatusMenuState(
targetCode: "",
hasTranslation: false,
canReplace: false
)
private lazy var onboardingWindow = OnboardingWindowController(
model: environment.onboarding,
onCopyCommand: { [weak self] text in self?.environment.copyText(text) },
onFinished: { [weak self] in
self?.environment.settingsDidChange()
self?.refreshMenuState()
}
)
private lazy var diagnosticsWindow = DiagnosticsWindowController(
model: environment.diagnosticsModel,
onCopy: { [weak self] text in self?.environment.copyText(text) }
)
override init() {
environment = AppEnvironment()
super.init()
refreshMenuState()
}
func applicationDidFinishLaunching(_ notification: Notification) {
loggers.logger(.session).notice("Sprachmittler launched")
let environment = AppEnvironment()
self.environment = environment
environment.onStateChange = { [weak self] in self?.refreshMenuState() }
environment.start { [weak self] captured in
self?.handle(captured)
}
NSApp.servicesProvider = environment.servicesProvider
NSUpdateDynamicServices()
if !environment.settingsStore.current().hasCompletedOnboarding {
showOnboarding()
}
}
func applicationWillTerminate(_ notification: Notification) {
environment?.stop()
environment = nil
environment.stop()
}
/// Menu-bar action: translate the current clipboard text.
/// Menu action: translate the current clipboard text.
func captureClipboardText() {
environment?.captureClipboardText()
environment.captureClipboardText()
}
/// Menu action: change the target language.
func selectTarget(_ language: TargetLanguage) {
environment.selectTarget(language)
refreshMenuState()
}
/// Menu action: copy the last translation.
func copyLastTranslation() {
environment.copyLastTranslation()
}
/// Menu action: replace the last selection with the last translation.
func replaceLastTranslation() {
environment.replaceLastTranslation()
}
/// Menu action: open setup.
func showOnboarding() {
onboardingWindow.show()
}
/// Menu action: open diagnostics.
func showDiagnostics() {
diagnosticsWindow.show()
}
/// Menu action: About and licence notice.
func showAbout() {
NSApp.activate(ignoringOtherApps: true)
NSApp.orderFrontStandardAboutPanel(options: [
.applicationName: "Sprachmittler",
.credits: NSAttributedString(
string: "Local translation with Hy-MT3. No text leaves this Mac.\n"
+ "Hy-MT3 is Apache-2.0 per the model card; Sprachmittler bundles no weights."
),
])
}
private func handle(_ captured: CapturedText) {
// The M4 session will replace this log-only sink. Log counts and source only.
loggers.logger(.capture).notice(
"Captured \(captured.text.count) characters from \(captured.source.rawValue, privacy: .public)"
)
refreshMenuState()
}
private func refreshMenuState() {
menuState = StatusMenuState(
targetCode: environment.currentTarget.code,
hasTranslation: environment.lastTranslation != nil,
canReplace: environment.canReplaceLast
)
}
}
+366 -15
View File
@@ -1,19 +1,34 @@
import AppKit
import Foundation
import SprachmittlerCapture
import SprachmittlerCore
/// The app composition root for capture. It owns the watcher, pasteboard and Services provider.
/// The app composition root: settings, Ollama clients, session, panel, capture and diagnostics.
@MainActor
final class AppEnvironment {
let settingsStore: SettingsStore
let pasteboard: SystemPasteboard
let watcher: PasteboardWatcher
var watcher: PasteboardWatcher
let accessibility: AccessibilityPermission
let launchAtLogin: LaunchAtLoginController
let diagnostics: DiagnosticsStore
let targetProvider: FrontmostTargetProvider
let session: TranslationSession
let settingsModel: SettingsViewModel
let onboarding: OnboardingViewModel
let diagnosticsModel: DiagnosticsViewModel
private var onCapture: ((CapturedText) -> Void)?
/// The most recent capture, kept in memory only for the M4 panel.
private(set) var lastCaptured: CapturedText?
/// The most recent capture rejection, for the M4 panel and diagnostics.
private(set) var lastTranslation: String?
private(set) var lastWarnings: [TranslationWarning] = []
private(set) var insertionTarget: InsertionTarget?
private var insertionTargetGeneration = 0
private(set) var lastCaptureFailure: CaptureValidation?
var onCapture: ((CapturedText) -> Void)?
var onStateChange: (() -> Void)?
private var watcherEventSink: (@MainActor (PasteboardWatcherEvent) -> Void)?
private var watcherWindowMs: Int
/// The Services provider, created lazily so it can capture `self` weakly.
lazy var servicesProvider = ServicesProvider { [weak self] captured in
@@ -22,25 +37,105 @@ final class AppEnvironment {
}
}
/// Creates the capture stack.
/// The insertion coordinator, created on first use.
lazy var insertionCoordinator = InsertionCoordinator(
pasteboard: pasteboard,
accessibility: AXTextEditor(),
ownWrite: { [weak self] in self?.watcher.noteOwnWrite(at: Date()) },
frontmostPID: { NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0 }
)
/// The panel model, created on first use.
lazy var panelViewModel: PanelViewModel = {
let model = PanelViewModel(
session: session,
configuration: configuration(for: settingsStore.current()),
copy: { [weak self] text in
self?.copyToPasteboard(text, remember: self?.panelViewModel.translation == text)
},
replace: { [weak self] in
guard let self else { return .failed(.cancelled) }
return await performReplace()
},
onCloseRequest: { [weak self] in self?.panelController.close() },
eventObserver: { [weak self] event in self?.observe(event) },
onTargetChanged: { [weak self] language in self?.applyTarget(language) }
)
model.startObserving()
return model
}()
/// The panel window controller, created on first use.
lazy var panelController = PanelController(viewModel: panelViewModel)
/// Creates the environment.
init() {
let store = SettingsStore()
let pasteboard = SystemPasteboard()
let access = AccessibilityPermission()
let launch = LaunchAtLoginController()
let diagnostics = DiagnosticsStore()
let windowMs = store.current().doubleCopyWindowMs
settingsStore = store
self.pasteboard = pasteboard
watcher = PasteboardWatcher(pasteboard: pasteboard)
accessibility = access
targetProvider = FrontmostTargetProvider()
launchAtLogin = launch
self.diagnostics = diagnostics
watcherWindowMs = windowMs
watcher = PasteboardWatcher(
pasteboard: pasteboard,
configuration: DoubleCopyDetector.Configuration(
window: Double(windowMs) / 1000
),
limits: store.current().captureLimits
)
let factoryStore = store
session = TranslationSession(pipelineFactory: {
try AppOllama.makePipeline(settings: factoryStore.current())
})
let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog = { settings in
try AppOllama.makeCatalog(settings: settings)
}
settingsModel = SettingsViewModel(
store: store,
catalogProvider: catalogProvider,
launchAtLogin: launch
)
onboarding = OnboardingViewModel(
settingsStore: store,
catalogProvider: catalogProvider,
accessibility: access
)
diagnosticsModel = DiagnosticsViewModel(
store: diagnostics,
catalogProvider: catalogProvider,
settingsProvider: { factoryStore.current() }
)
}
/// Starts the watcher and delivers every capture to `onCapture`.
/// Starts the watcher and optional warm-up.
func start(onCapture: @escaping (CapturedText) -> Void) {
self.onCapture = onCapture
watcher.start { [weak self] event in
let sink: @MainActor (PasteboardWatcherEvent) -> Void = { [weak self] event in
self?.handle(event)
}
watcherEventSink = sink
watcher.start(onEvent: sink)
warmUpIfNeeded()
}
/// Stops the watcher and releases the in-memory text.
/// Stops the watcher, panel and event stream.
func stop() {
watcher.stop()
panelViewModel.shutdown()
Task { await panelViewModel.close() }
lastCaptured = nil
lastTranslation = nil
lastWarnings = []
}
/// Reads the clipboard once for the menu-bar item.
@@ -54,24 +149,280 @@ final class AppEnvironment {
deliver(CapturedText(text: text, capturedAt: Date(), source: .menu))
}
/// Copies arbitrary text with the app's own-write markers.
func copyText(_ text: String) {
copyToPasteboard(text, remember: false)
}
/// Copies the last translation for the status menu.
func copyLastTranslation() {
guard let lastTranslation else { return }
copyToPasteboard(lastTranslation, remember: false)
}
/// True when the last translation can safely be inserted.
var canReplaceLast: Bool {
lastTranslation != nil
&& lastCaptured != nil
&& insertionTarget != nil
&& !InsertionPolicy.isBlocked(by: lastWarnings)
}
/// Replaces the last selection from the status menu.
func replaceLastTranslation() {
guard let captured = lastCaptured,
let translation = lastTranslation,
let target = insertionTarget
else {
return
}
Task {
do {
_ = try await insertionCoordinator.replace(
selection: captured,
with: translation,
target: target
)
} catch let error as SprachmittlerError {
showPanelError(error, source: captured)
} catch {
showPanelError(.server(status: 0, message: "Insertion failed"), source: captured)
}
}
}
/// The current target code, for the status menu.
var currentTarget: ModelLanguage {
settingsStore.current().targetLanguageModel
}
/// Changes the target from the status menu and retranslates the open panel.
func selectTarget(_ language: ModelLanguage) {
try? settingsStore.update { $0.noteTarget(language) }
applySettings()
}
/// Called after Settings or Onboarding saves. Updates the panel and watcher.
func settingsDidChange() {
applySettings()
settingsModel.reload()
}
private func configuration(for settings: AppSettings) -> PanelConfiguration {
PanelConfiguration(
target: settings.targetLanguageModel,
model: settings.model,
keepAlive: settings.keepModelLoaded,
sampling: settings.samplingOptions,
showSourcePreview: settings.showSourcePreview,
translationFontSize: settings.translationFontSize,
renderMarkdown: settings.renderMarkdown,
closeWithEscape: settings.closeWithEscape,
languageRoutes: settings.languageRoutes,
recentTargets: settings.recentTargets,
captureLimits: settings.captureLimits
)
}
private func applySettings() {
let settings = settingsStore.current()
let previousTarget = panelViewModel.configuration.target.code
let previousRoutes = panelViewModel.configuration.languageRoutes
panelViewModel.updateConfiguration(configuration(for: settings))
watcher.limits = settings.captureLimits
if settings.doubleCopyWindowMs != watcherWindowMs {
watcherWindowMs = settings.doubleCopyWindowMs
restartWatcher()
}
let targetChanged = previousTarget != settings.targetLanguage && panelViewModel.source != nil
let routesChanged = previousRoutes != settings.languageRoutes && panelViewModel.source != nil
if targetChanged || routesChanged {
Task { await panelViewModel.retranslate() }
}
onStateChange?()
}
private func applyTarget(_ language: ModelLanguage) {
try? settingsStore.update { $0.noteTarget(language) }
applySettings()
}
private func restartWatcher() {
watcher.stop()
watcher = PasteboardWatcher(
pasteboard: pasteboard,
configuration: DoubleCopyDetector.Configuration(
window: Double(watcherWindowMs) / 1000
),
limits: settingsStore.current().captureLimits
)
if let sink = watcherEventSink {
watcher.start(onEvent: sink)
}
}
private func handle(_ event: PasteboardWatcherEvent) {
switch event {
case let .captured(captured):
deliver(captured)
case .textTooLong, .noText, .ignoredOwnWrite:
case let .textTooLong(characters, limit):
let error = SprachmittlerError.textTooLong(characters: characters, limit: limit)
lastTranslation = nil
lastWarnings = []
onStateChange?()
lastCaptureFailure = .textTooLong(characters: characters, limit: limit)
showPanelError(error)
case .noText, .ignoredOwnWrite:
break
}
}
private func deliver(_ captured: CapturedText) {
switch CapturePolicy.validate(captured.text) {
// A new capture invalidates the previous result for the status-menu actions.
lastTranslation = nil
lastWarnings = []
onStateChange?()
switch CapturePolicy.validate(captured.text, limits: settingsStore.current().captureLimits) {
case .valid:
lastCaptureFailure = nil
case let failure:
lastCaptureFailure = failure
case .empty:
lastCaptureFailure = .empty
return
case let .textTooLong(characters, limit):
lastCaptureFailure = .textTooLong(characters: characters, limit: limit)
showPanelError(
.textTooLong(characters: characters, limit: limit),
source: captured
)
return
}
lastCaptured = captured
captureInsertionTarget()
onCapture?(captured)
panelViewModel.updateConfiguration(configuration(for: settingsStore.current()))
panelViewModel.prepare(captured)
panelController.show()
Task { await panelViewModel.begin(captured) }
}
}
extension AppEnvironment {
private func performReplace() async -> InsertionOutcome {
guard let captured = lastCaptured,
let target = insertionTarget,
!panelViewModel.translation.isEmpty
else {
return .failed(.insertionTargetChanged)
}
if let warning = panelViewModel.blockingWarnings.first {
return .failed(warning.insertionError)
}
do {
if let selected = target.selectedText {
let frontmost = NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0
try InsertionPolicy.verify(
frontmostPID: frontmost,
target: target,
selectedText: selected,
source: captured.text
)
}
return try await insertionCoordinator.replace(
selection: captured,
with: panelViewModel.translation,
target: target
)
} catch let error as SprachmittlerError {
return .failed(error)
} catch is CancellationError {
return .failed(.cancelled)
} catch {
return .failed(.server(status: 0, message: "Insertion failed"))
}
}
private func captureInsertionTarget() {
guard let base = targetProvider.captureTarget() else {
insertionTarget = nil
return
}
insertionTarget = base
Task {
let editor = AXTextEditor()
guard await editor.isTrusted(),
let selected = await editor.selectedText(pid: base.pid),
insertionTarget?.pid == base.pid
else {
return
}
insertionTarget = InsertionTarget(
pid: base.pid,
bundleID: base.bundleID,
selectedText: selected,
capturedAt: base.capturedAt
)
}
}
private func showPanelError(_ error: SprachmittlerError, source: CapturedText? = nil) {
panelViewModel.updateConfiguration(configuration(for: settingsStore.current()))
panelViewModel.showError(error, source: source)
panelController.show()
}
private func copyToPasteboard(_ text: String, remember: Bool) {
pasteboard.write(text)
watcher.noteOwnWrite(at: Date())
let shouldRemember = remember
&& panelViewModel.phase == .ready
&& settingsStore.current().keepRecentTranslationInMemory
if shouldRemember {
lastTranslation = text
}
onStateChange?()
}
private func observe(_ event: TranslationSessionEvent) {
switch event {
case let .finished(_, result):
lastWarnings = result.warnings
if settingsStore.current().keepRecentTranslationInMemory {
lastTranslation = result.translation
} else {
lastTranslation = nil
}
let detail = result.warnings.map(\.code).joined(separator: ",")
let duration = result.timing.totalMs
Task {
await diagnostics.record(
kind: "translation",
durationMs: duration,
detail: detail.isEmpty ? nil : detail
)
}
onStateChange?()
case let .failed(_, error):
Task {
await diagnostics.record(kind: "error", detail: error.diagnosticCode)
}
onStateChange?()
case .started, .chunkStarted, .delta, .cancelled:
break
}
}
private func warmUpIfNeeded() {
let settings = settingsStore.current()
guard settings.warmUpOnLaunch else { return }
Task {
do {
try await AppOllama.warmUp(settings: settings)
await diagnostics.record(kind: "warmup")
} catch {
await diagnostics.record(kind: "warmupFailed", detail: "unavailable")
}
}
}
}
+95
View File
@@ -0,0 +1,95 @@
import AppKit
import SprachmittlerCore
import SwiftUI
/// The diagnostics window. It shows no text, only versions, digests, timings and error kinds.
struct DiagnosticsView: View {
@Bindable var model: DiagnosticsViewModel
let onCopy: @MainActor (String) -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text(String(localized: "Diagnostics"))
.font(.title2.bold())
Spacer()
Button(String(localized: "Refresh")) {
Task { await model.refresh() }
}
.disabled(model.isRefreshing)
Button(String(localized: "Copy report")) {
onCopy(model.report())
}
Button(String(localized: "Clear")) {
Task { await model.clear() }
}
}
GroupBox(String(localized: "Ollama")) {
VStack(alignment: .leading, spacing: 4) {
Text("Version: \(model.serverVersion ?? String(localized: "unknown"))")
Text(
"Models: "
+ model.models.map { "\($0.name) [\($0.digest.prefix(12))]" }
.joined(separator: ", ")
)
if let error = model.error {
Text(error).foregroundStyle(.red)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
Text(String(localized: "Last 50 events"))
.font(.headline)
List {
ForEach(Array(model.events.enumerated()), id: \.offset) { _, event in
HStack {
Text(event.kind)
Spacer()
if let duration = event.durationMs {
Text("\(duration) ms").foregroundStyle(.secondary)
}
if let detail = event.detail {
Text(detail).foregroundStyle(.secondary)
}
}
.font(.callout)
}
}
.frame(minHeight: 220)
}
.padding(20)
.frame(width: 620, height: 520)
.task {
await model.refresh()
}
}
}
/// The diagnostics window controller.
@MainActor
final class DiagnosticsWindowController {
private let window: NSWindow
init(model: DiagnosticsViewModel, onCopy: @escaping @MainActor (String) -> Void) {
let window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 620, height: 520),
styleMask: [.titled, .closable, .resizable],
backing: .buffered,
defer: false
)
self.window = window
window.title = String(localized: "Sprachmittler Diagnostics")
window.isReleasedWhenClosed = false
window.contentViewController = NSHostingController(
rootView: DiagnosticsView(model: model, onCopy: onCopy)
)
window.center()
}
func show() {
NSApp.activate(ignoringOtherApps: true)
window.makeKeyAndOrderFront(nil)
}
}
+7
View File
@@ -10,8 +10,15 @@
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleIconName</key>
<string>AppIcon</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleLocalizations</key>
<array>
<string>en</string>
<string>de</string>
</array>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
+21
View File
@@ -0,0 +1,21 @@
import Foundation
import ServiceManagement
import SprachmittlerCore
/// The production launch-at-login controller backed by `SMAppService.mainApp`.
@MainActor
final class LaunchAtLoginController: LaunchAtLoginControlling {
var isEnabled: Bool {
SMAppService.mainApp.status == .enabled
}
func setEnabled(_ enabled: Bool) throws {
if enabled {
if SMAppService.mainApp.status != .enabled {
try SMAppService.mainApp.register()
}
} else if SMAppService.mainApp.status == .enabled {
try SMAppService.mainApp.unregister()
}
}
}
+8
View File
@@ -0,0 +1,8 @@
import Foundation
/// The small observable state the status menu needs.
struct StatusMenuState: Equatable {
var targetCode: String
var hasTranslation: Bool
var canReplace: Bool
}
+68
View File
@@ -0,0 +1,68 @@
import AppKit
import SprachmittlerCore
import SwiftUI
/// The menu-bar status menu.
struct StatusMenuView: View {
@ObservedObject var delegate: AppDelegate
var body: some View {
Button(String(localized: "Translate Clipboard Text")) {
delegate.captureClipboardText()
}
Menu(String(localized: "Target Language")) {
ForEach(LanguageCatalogue.common) { language in
Button {
delegate.selectTarget(language)
} label: {
HStack {
Text(language.localizedDisplayName)
if language.code == delegate.menuState.targetCode {
Image(systemName: "checkmark")
}
}
}
}
Divider()
SettingsLink {
Text(String(localized: "More languages…"))
}
}
Divider()
Button(String(localized: "Copy Last Translation")) {
delegate.copyLastTranslation()
}
.disabled(!delegate.menuState.hasTranslation)
Button(String(localized: "Replace Last Translation")) {
delegate.replaceLastTranslation()
}
.disabled(!delegate.menuState.canReplace)
Divider()
Button(String(localized: "Set up Sprachmittler…")) {
delegate.showOnboarding()
}
Button(String(localized: "Diagnostics…")) {
delegate.showDiagnostics()
}
Button(String(localized: "About Sprachmittler")) {
delegate.showAbout()
}
SettingsLink {
Text(String(localized: "Settings…"))
}
Divider()
Button(String(localized: "Quit Sprachmittler")) {
NSApplication.shared.terminate(nil)
}
.keyboardShortcut("q")
}
}
+231
View File
@@ -0,0 +1,231 @@
import AppKit
import SprachmittlerCore
import SwiftUI
/// The first-run setup window.
struct OnboardingView: View {
@Bindable var model: OnboardingViewModel
let onCopyCommand: @MainActor (String) -> Void
let onFinished: @MainActor () -> Void
@State private var showLanguagePicker = false
@State private var errorMessage: String?
var body: some View {
VStack(alignment: .leading, spacing: 16) {
VStack(alignment: .leading, spacing: 4) {
Text(String(localized: "Set up Sprachmittler"))
.font(.title2.bold())
Text(String(localized: "Local translation with Ollama. Nothing leaves this Mac."))
.foregroundStyle(.secondary)
}
checkRow(
title: String(localized: "Ollama"),
state: model.ollama,
detail: ollamaDetail
) {
Button(String(localized: "Check again")) {
Task { await model.refresh() }
}
.controlSize(.small)
if case .failed = model.ollama, let url = URL(string: "https://ollama.com/download") {
Link(String(localized: "Download Ollama"), destination: url)
.controlSize(.small)
}
}
checkRow(
title: String(localized: "Hy-MT3 model"),
state: model.model,
detail: modelDetail
) {
Button(String(localized: "Refresh")) {
Task { await model.refresh() }
}
.controlSize(.small)
if case .failed = model.model {
Button(String(localized: "Copy pull command")) {
onCopyCommand(model.pullCommand)
}
.controlSize(.small)
}
}
VStack(alignment: .leading, spacing: 6) {
Text(String(localized: "Target language"))
.font(.headline)
Button {
showLanguagePicker.toggle()
} label: {
HStack {
Text(model.target.localizedDisplayName)
Image(systemName: "chevron.up.chevron.down")
.font(.caption)
}
}
.popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) {
LanguagePickerView(
selection: Binding(
get: { model.target },
set: { model.setTarget($0) }
)
)
}
.accessibilityLabel(String(localized: "Target language"))
}
VStack(alignment: .leading, spacing: 6) {
Text(String(localized: "Accessibility (optional)"))
.font(.headline)
Text(String(localized: "Only Replace needs it. Double copy, translation and Copy work without it."))
.font(.caption)
.foregroundStyle(.secondary)
HStack {
if model.accessibilityTrusted {
Label(String(localized: "Granted"), systemImage: "checkmark.circle.fill")
.foregroundStyle(.green)
} else {
Button(String(localized: "Enable Accessibility")) {
model.requestAccessibility()
}
Button(String(localized: "Open System Settings")) {
model.openAccessibilitySettings()
}
}
}
}
if let errorMessage {
Text(errorMessage)
.font(.callout)
.foregroundStyle(.red)
}
Spacer()
HStack {
Button(String(localized: "Check again")) {
Task { await model.refresh() }
}
Spacer()
Button(String(localized: "Done")) {
do {
try model.complete()
onFinished()
} catch {
errorMessage = String(localized: "Setup could not be saved.")
}
}
.keyboardShortcut(.defaultAction)
.buttonStyle(.borderedProminent)
.disabled(!model.canFinish)
}
}
.padding(24)
.frame(width: 540, height: 560)
.task {
await model.refresh()
}
}
private var ollamaDetail: String? {
switch model.ollama {
case let .ok(version): String(localized: "Running, version \(version)")
case let .failed(message): message
case .checking: String(localized: "Checking…")
case .idle: nil
}
}
private var modelDetail: String? {
switch model.model {
case let .ok(tags): tags
case let .failed(message): message
case .checking: String(localized: "Checking…")
case .idle: nil
}
}
private func checkRow(
title: String,
state: OnboardingCheck,
detail: String?,
@ViewBuilder actions: () -> some View
) -> some View {
HStack(alignment: .top, spacing: 10) {
Image(systemName: icon(for: state))
.foregroundStyle(color(for: state))
.font(.title3)
VStack(alignment: .leading, spacing: 2) {
Text(title).font(.headline)
if let detail {
Text(detail)
.font(.callout)
.foregroundStyle(.secondary)
}
}
Spacer()
HStack(spacing: 8) {
actions()
}
}
.padding(10)
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 10))
}
private func icon(for state: OnboardingCheck) -> String {
switch state {
case .ok: "checkmark.circle.fill"
case .failed: "xmark.octagon.fill"
case .checking: "clock"
case .idle: "circle"
}
}
private func color(for state: OnboardingCheck) -> Color {
switch state {
case .ok: .green
case .failed: .red
case .checking: .secondary
case .idle: .secondary
}
}
}
/// The onboarding window controller.
@MainActor
final class OnboardingWindowController {
private let window: NSWindow
init(
model: OnboardingViewModel,
onCopyCommand: @escaping @MainActor (String) -> Void,
onFinished: @escaping @MainActor () -> Void
) {
let window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 540, height: 560),
styleMask: [.titled, .closable],
backing: .buffered,
defer: false
)
self.window = window
window.title = String(localized: "Set up Sprachmittler")
window.isReleasedWhenClosed = false
window.contentViewController = NSHostingController(
rootView: OnboardingView(
model: model,
onCopyCommand: onCopyCommand,
onFinished: { [weak window] in
window?.close()
onFinished()
}
)
)
window.center()
}
func show() {
NSApp.activate(ignoringOtherApps: true)
window.makeKeyAndOrderFront(nil)
}
}
+60
View File
@@ -0,0 +1,60 @@
import SprachmittlerCore
import SwiftUI
/// A searchable language list used by the panel and Settings.
struct LanguagePickerView: View {
@Binding var selection: ModelLanguage
var recent: [ModelLanguage] = []
var excluding: String?
@Environment(\.dismiss) private var dismiss
@State private var query = ""
var body: some View {
VStack(alignment: .leading, spacing: 8) {
TextField(String(localized: "Search languages"), text: $query)
.textFieldStyle(.roundedBorder)
.accessibilityLabel(String(localized: "Search languages"))
ScrollView {
LazyVStack(alignment: .leading, spacing: 2) {
ForEach(filtered) { language in
Button {
selection = language
dismiss()
} label: {
HStack {
Text(language.localizedDisplayName)
Spacer()
if language.code == selection.code {
Image(systemName: "checkmark")
}
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.padding(.vertical, 4)
.padding(.horizontal, 6)
}
}
}
}
.padding(12)
.frame(width: 320, height: 380)
}
private var filtered: [ModelLanguage] {
let all = LanguageCatalogue.all.sorted {
$0.localizedDisplayName.localizedCaseInsensitiveCompare($1.localizedDisplayName) == .orderedAscending
}
let available = all.filter { language in
guard let excluding else { return true }
return language.code.caseInsensitiveCompare(excluding) != .orderedSame
}
guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return available }
return available.filter {
$0.localizedDisplayName.localizedCaseInsensitiveContains(query)
|| $0.modelName.localizedCaseInsensitiveContains(query)
|| $0.code.localizedCaseInsensitiveContains(query)
}
}
}
+136
View File
@@ -0,0 +1,136 @@
import AppKit
import SprachmittlerText
import SwiftUI
/// Renders a translation as formatted Markdown. Copy and Replace still use the raw translation.
struct MarkdownTranslationView: View {
let markdown: String
let fontSize: Int
let isRTL: Bool
private let blocks: [MarkdownBlock]
init(markdown: String, fontSize: Int, isRTL: Bool) {
self.markdown = markdown
self.fontSize = fontSize
self.isRTL = isRTL
blocks = MarkdownPresentation.blocks(in: markdown)
}
var body: some View {
VStack(alignment: .leading, spacing: 8) {
ForEach(blocks.indices, id: \.self) { index in
block(blocks[index])
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.environment(\.layoutDirection, isRTL ? .rightToLeft : .leftToRight)
.environment(\.openURL, OpenURLAction { url in
guard MarkdownPresentation.isAllowedLink(url) else { return .discarded }
NSWorkspace.shared.open(url)
return .handled
})
.accessibilityElement(children: .contain)
.accessibilityLabel(String(localized: "Translation"))
}
private var baseSize: CGFloat {
CGFloat(fontSize)
}
@ViewBuilder private func block(_ block: MarkdownBlock) -> some View {
switch block {
case let .paragraph(text):
inlineText(text, size: baseSize)
case let .heading(level, text):
inlineText(text, size: baseSize * headingScale(level), weight: .bold)
.accessibilityAddTraits(.isHeader)
case let .listItem(ordered, number, indent, text):
HStack(alignment: .firstTextBaseline, spacing: 6) {
Text(ordered ? "\(number)." : "•")
.font(.system(size: baseSize, weight: ordered ? .regular : .bold))
.foregroundStyle(.secondary)
.frame(minWidth: ordered ? 18 : 12, alignment: .trailing)
.accessibilityHidden(true)
inlineText(text, size: baseSize)
}
.padding(.leading, CGFloat(indent) * 14)
case let .quote(text):
HStack(alignment: .top, spacing: 8) {
Rectangle()
.fill(.secondary.opacity(0.35))
.frame(width: 3)
.accessibilityHidden(true)
inlineText(text, size: baseSize)
.foregroundStyle(.secondary)
}
case let .codeBlock(_, text):
ScrollView(.horizontal, showsIndicators: false) {
Text(verbatim: text)
.font(.system(size: baseSize * 0.95, design: .monospaced))
.textSelection(.enabled)
.fixedSize(horizontal: true, vertical: false)
.padding(10)
}
.frame(maxWidth: .infinity, alignment: .leading)
.background(.primary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))
.environment(\.layoutDirection, .leftToRight)
case .rule:
Divider()
.padding(.vertical, 2)
}
}
private func inlineText(_ text: String, size: CGFloat, weight: Font.Weight = .regular) -> some View {
Text(styled(text, size: size))
.font(.system(size: size, weight: weight))
.textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
private func styled(_ text: String, size: CGFloat) -> AttributedString {
var attributed = MarkdownPresentation.inline(text)
let runs = attributed.runs.compactMap { run -> (Range<AttributedString.Index>, InlinePresentationIntent)? in
guard let intent = run.inlinePresentationIntent else { return nil }
let relevant = intent.contains(.stronglyEmphasized)
|| intent.contains(.emphasized)
|| intent.contains(.code)
return relevant ? (run.range, intent) : nil
}
for (range, intent) in runs {
if intent.contains(.code) {
var font = Font.system(size: size * 0.95, design: .monospaced)
if intent.contains(.stronglyEmphasized) {
font = font.bold()
}
if intent.contains(.emphasized) {
font = font.italic()
}
attributed[range].font = font
} else {
var font = Font.system(
size: size,
weight: intent.contains(.stronglyEmphasized) ? .bold : .regular
)
if intent.contains(.emphasized) {
font = font.italic()
}
attributed[range].font = font
}
}
return attributed
}
private func headingScale(_ level: Int) -> CGFloat {
switch level {
case 1: 1.6
case 2: 1.45
case 3: 1.3
case 4: 1.2
case 5: 1.12
default: 1.06
}
}
}
+146
View File
@@ -0,0 +1,146 @@
import AppKit
import SprachmittlerCore
import SwiftUI
/// The non-activating floating panel. It never activates the app. While visible it can be the key
/// window so Esc and the keyboard shortcuts work without a click.
@MainActor
final class PanelController: NSObject, NSWindowDelegate {
private let panel: TranslationPanel
private let viewModel: PanelViewModel
private var isClosing = false
private var outsideClickMonitor: Any?
/// Creates the panel and its SwiftUI content.
init(viewModel: PanelViewModel) {
self.viewModel = viewModel
panel = TranslationPanel(
contentRect: NSRect(x: 0, y: 0, width: 540, height: 520),
styleMask: [.titled, .fullSizeContentView, .nonactivatingPanel],
backing: .buffered,
defer: false
)
super.init()
panel.delegate = self
NotificationCenter.default.addObserver(
self,
selector: #selector(panelDidResignKey(_:)),
name: NSWindow.didResignKeyNotification,
object: panel
)
panel.isFloatingPanel = true
panel.isMovable = true
panel.becomesKeyOnlyIfNeeded = false
panel.level = .floating
panel.hidesOnDeactivate = false
panel.isMovableByWindowBackground = true
panel.isReleasedWhenClosed = false
panel.titleVisibility = .hidden
panel.titlebarAppearsTransparent = true
panel.backgroundColor = .clear
panel.isOpaque = false
panel.hasShadow = true
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
panel.standardWindowButton(.closeButton)?.isHidden = true
panel.standardWindowButton(.miniaturizeButton)?.isHidden = true
panel.standardWindowButton(.zoomButton)?.isHidden = true
panel.contentView = PanelHostingView(
rootView: PanelView(
model: viewModel,
onClose: { [weak self] in self?.close() }
)
)
panel.setContentSize(NSSize(width: 540, height: 520))
}
/// Shows the panel near the mouse without activating the app.
func show() {
if !panel.isVisible {
positionNearMouse()
}
panel.orderFrontRegardless()
if viewModel.configuration.closeWithEscape {
panel.makeKey()
}
installOutsideClickMonitor()
}
/// Hides the panel and cancels/releases its content.
func close() {
guard !isClosing else { return }
isClosing = true
defer { isClosing = false }
removeOutsideClickMonitor()
panel.orderOut(nil)
Task { await viewModel.close() }
}
/// A click outside the panel makes another window key. Treat that as a dismissal, but not
/// while the language popover (a child window) is open.
@objc private func panelDidResignKey(_ notification: Notification) {
guard panel.isVisible, !isClosing else { return }
if panel.childWindows?.contains(where: \.isVisible) == true {
return
}
close()
}
/// While the panel is visible, a click sent to another app dismisses it. Global monitors do not
/// receive events sent to this app, so clicks in the panel and its popover are ignored. The
/// event itself is never read.
private func installOutsideClickMonitor() {
guard outsideClickMonitor == nil else { return }
outsideClickMonitor = NSEvent.addGlobalMonitorForEvents(
matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]
) { [weak self] _ in
Task { @MainActor [weak self] in
guard let self, panel.isVisible else { return }
close()
}
}
}
private func removeOutsideClickMonitor() {
if let outsideClickMonitor {
NSEvent.removeMonitor(outsideClickMonitor)
self.outsideClickMonitor = nil
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func windowWillClose(_ notification: Notification) {
removeOutsideClickMonitor()
Task { await viewModel.close() }
}
private final class PanelHostingView: NSHostingView<PanelView> {
required init(rootView: PanelView) {
super.init(rootView: rootView)
}
required init?(coder: NSCoder) {
nil
}
override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
true
}
}
private func positionNearMouse() {
let mouse = NSEvent.mouseLocation
let screen = NSScreen.screens.first { $0.frame.contains(mouse) } ?? NSScreen.main
guard let visible = screen?.visibleFrame else {
panel.setFrameOrigin(mouse)
return
}
let size = panel.frame.size
var origin = NSPoint(x: mouse.x - size.width / 2, y: mouse.y + 16)
origin.x = max(visible.minX + 12, min(origin.x, visible.maxX - size.width - 12))
origin.y = max(visible.minY + 12, min(origin.y, visible.maxY - size.height - 12))
panel.setFrameOrigin(origin)
}
}
+257
View File
@@ -0,0 +1,257 @@
import AppKit
import SprachmittlerCore
import SprachmittlerText
import SwiftUI
extension PanelView {
private var rendersMarkdown: Bool {
!model.translation.isEmpty
&& model.configuration.renderMarkdown
&& MarkdownPresentation.shouldRender(
source: model.source?.text ?? "",
translation: model.translation
)
}
var translationArea: some View {
ScrollView {
translationContent
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(minHeight: 120, maxHeight: 260)
.padding(10)
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8))
.overlay(alignment: .topTrailing) {
if model.phase == .translating || model.phase == .streaming {
ProgressView()
.controlSize(.small)
.padding(8)
.accessibilityLabel(String(localized: "Translating"))
}
}
}
@ViewBuilder var translationContent: some View {
if rendersMarkdown {
MarkdownTranslationView(
markdown: model.translation,
fontSize: model.configuration.translationFontSize,
isRTL: model.effectiveTarget.isRTL
)
} else {
Text(translationText)
.font(.system(size: CGFloat(model.configuration.translationFontSize)))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundStyle(model.translation.isEmpty ? .secondary : .primary)
.environment(
\.layoutDirection,
model.effectiveTarget.isRTL ? .rightToLeft : .leftToRight
)
.accessibilityLabel(String(localized: "Translation"))
}
}
var translationText: String {
if !model.translation.isEmpty {
return model.translation
}
switch model.phase {
case .translating, .streaming:
return String(localized: "Translating…")
case .failed:
return String(localized: "No translation.")
case .idle, .ready:
return String(localized: "No translation yet.")
}
}
private func routedMessage(from routedSource: ModelLanguage) -> String {
let source = routedSource.localizedDisplayName
let target = model.effectiveTarget.localizedDisplayName
return String(localized: "Detected \(source). Translating to \(target).")
}
@ViewBuilder var warningArea: some View {
if let routedSource = model.routedSource {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "arrow.left.arrow.right.circle.fill")
.foregroundStyle(.blue)
.accessibilityHidden(true)
Text(routedMessage(from: routedSource))
.font(.callout)
Spacer()
Button(String(localized: "Translate to \(model.configuration.target.localizedDisplayName)")) {
Task { await model.overrideTarget(model.configuration.target) }
}
.controlSize(.small)
}
.padding(8)
.background(.blue.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
}
if model.sameLanguageWarning != nil {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "info.circle.fill").foregroundStyle(.blue)
Text("This text already appears to be in \(model.effectiveTarget.localizedDisplayName).")
.font(.callout)
Spacer()
Button(String(localized: "Translate anyway")) {
model.dismissSameLanguageWarning()
}
.controlSize(.small)
}
.padding(8)
.background(.blue.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
}
ForEach(Array(visibleWarnings.enumerated()), id: \.offset) { _, warning in
HStack(alignment: .top, spacing: 8) {
Image(systemName: warning.isBlocking ? "exclamationmark.triangle.fill" : "exclamationmark.circle")
.foregroundStyle(warning.isBlocking ? .orange : .secondary)
Text(warning.panelMessage)
.font(.callout)
Spacer()
}
.padding(8)
.background(
(warning.isBlocking ? Color.orange : Color.secondary)
.opacity(0.08),
in: RoundedRectangle(cornerRadius: 8)
)
.accessibilityLabel(warning.panelMessage)
}
}
var visibleWarnings: [TranslationWarning] {
model.warnings.filter { warning in
if case .sameLanguage = warning {
return false
}
return true
}
}
@ViewBuilder var errorArea: some View {
if let message = model.errorMessage, model.phase == .failed {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "exclamationmark.octagon.fill")
.foregroundStyle(.red)
VStack(alignment: .leading, spacing: 6) {
Text(message)
.font(.callout)
if let action = model.recoveryAction {
recoveryButton(action)
}
}
Spacer()
}
.padding(8)
.background(.red.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
.accessibilityLabel(message)
}
}
@ViewBuilder func recoveryButton(_ action: RecoveryAction) -> some View {
switch action {
case .startOllama:
if let url = URL(string: "https://ollama.com/download") {
Link(String(localized: "Download Ollama"), destination: url)
.controlSize(.small)
}
case let .pullModel(modelName):
Button(String(localized: "Copy pull command")) {
model.copy("ollama pull \(modelName)")
}
.controlSize(.small)
case .openSettings:
if model.error == .accessibilityNotTrusted, let url = accessibilitySettingsURL {
Button(String(localized: "Open Accessibility Settings")) {
NSWorkspace.shared.open(url)
}
.controlSize(.small)
} else {
Button(String(localized: "Open Settings")) {
openSettings()
}
.controlSize(.small)
}
case .copyInstead:
Button(String(localized: "Copy instead")) {
model.copyTranslation()
}
.controlSize(.small)
case .shortenText:
EmptyView()
case .retry:
Button(String(localized: "Retry")) {
Task { await model.retry() }
}
.controlSize(.small)
case .none:
EmptyView()
}
}
var accessibilitySettingsURL: URL? {
URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
}
var footer: some View {
HStack(spacing: 10) {
Button {
model.copyTranslation()
} label: {
Label(
model.didCopy ? String(localized: "Copied") : String(localized: "Copy"),
systemImage: "doc.on.doc"
)
}
.keyboardShortcut("c", modifiers: .command)
.disabled(!model.canCopy)
.accessibilityLabel(String(localized: "Copy translation"))
Button {
Task { await model.retry() }
} label: {
Label(String(localized: "Retry"), systemImage: "arrow.clockwise")
}
.keyboardShortcut("r", modifiers: .command)
.disabled(model.source == nil)
.accessibilityLabel(String(localized: "Retry translation"))
if let current = model.currentChunk, let total = model.totalChunks, total > 1 {
Text(String(localized: "Part \(current) of \(total)"))
.font(.caption)
.foregroundStyle(.secondary)
.accessibilityLabel(String(localized: "Part \(current) of \(total)"))
} else if model.chunkCount > 1 {
Text(String(localized: "\(model.chunkCount) parts"))
.font(.caption)
.foregroundStyle(.secondary)
.accessibilityLabel(String(localized: "Translated in \(model.chunkCount) parts"))
}
Spacer()
Button {
onClose()
} label: {
Text(String(localized: "Close"))
}
.keyboardShortcut(.cancelAction)
.accessibilityLabel(String(localized: "Close panel"))
Button {
Task { await model.replaceSelection() }
} label: {
Text(String(localized: "Replace"))
}
.keyboardShortcut(.return, modifiers: .command)
.buttonStyle(.borderedProminent)
.disabled(!model.canReplace)
.help(model.replaceUnavailableReason ?? String(localized: "Replace the selection"))
.accessibilityLabel(String(localized: "Replace selection"))
}
}
}
+131
View File
@@ -0,0 +1,131 @@
import AppKit
import SprachmittlerCore
import SprachmittlerText
import SwiftUI
/// The translation panel view. It never activates the app.
struct PanelView: View {
@Bindable var model: PanelViewModel
let onClose: @MainActor () -> Void
@Environment(\.openSettings) var openSettings
@State private var showLanguagePicker = false
@State private var showSource = true
var body: some View {
VStack(alignment: .leading, spacing: 0) {
header
VStack(alignment: .leading, spacing: 10) {
if model.configuration.showSourcePreview, let source = model.source {
sourcePreview(source)
}
translationArea
warningArea
errorArea
footer
}
.padding(.horizontal, 16)
.padding(.top, 10)
.padding(.bottom, 16)
}
.frame(width: 540)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 14, style: .continuous)
.strokeBorder(.separator, lineWidth: 1)
)
.ignoresSafeArea(.container, edges: .top)
.onAppear { showSource = model.configuration.showSourcePreview }
.onChange(of: model.configuration.showSourcePreview) { _, newValue in
showSource = newValue
}
.onExitCommand(perform: onClose)
.accessibilityElement(children: .contain)
.accessibilityLabel(String(localized: "Translation panel"))
}
private var header: some View {
ZStack {
WindowDragArea()
Color.primary.opacity(0.04).allowsHitTesting(false)
HStack(spacing: 10) {
HStack(spacing: 10) {
Image(systemName: "line.3.horizontal")
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(.secondary)
.frame(width: 24, height: 32)
.background(.quaternary, in: RoundedRectangle(cornerRadius: 7))
Image(systemName: "character.bubble")
.font(.title2)
.foregroundStyle(.tint)
VStack(alignment: .leading, spacing: 1) {
Text(String(localized: "Translate"))
.font(.headline)
Text("\(sourceLanguageLabel) → \(model.effectiveTarget.localizedDisplayName)")
.font(.caption)
.foregroundStyle(.secondary)
}
}
.allowsHitTesting(false)
.accessibilityElement(children: .combine)
.accessibilityLabel(String(localized: "Move panel"))
Spacer().allowsHitTesting(false)
Button {
showLanguagePicker.toggle()
} label: {
Label(model.effectiveTarget.localizedDisplayName, systemImage: "globe")
.labelStyle(.titleAndIcon)
}
.accessibilityLabel(String(localized: "Target language"))
.popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) {
LanguagePickerView(
selection: Binding(
get: { model.effectiveTarget },
set: { language in
Task { await model.overrideTarget(language) }
}
),
recent: model.configuration.recentTargets
)
}
Button {
openSettings()
} label: {
Image(systemName: "gearshape")
}
.accessibilityLabel(String(localized: "Settings"))
}
.padding(.horizontal, 16)
}
.frame(height: 56)
.frame(maxWidth: .infinity)
.help(String(localized: "Drag to move panel"))
}
private var sourceLanguageLabel: String {
guard let code = model.sourceLanguage, let language = LanguageCatalogue.resolve(code) else {
return String(localized: "Detected language")
}
return language.localizedDisplayName
}
private func sourcePreview(_ source: CapturedText) -> some View {
DisclosureGroup(isExpanded: $showSource) {
ScrollView {
Text(source.text)
.font(.callout)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxHeight: 100)
} label: {
Text(showSource ? String(localized: "Source") : String(localized: "Show source"))
.font(.caption.weight(.semibold))
.foregroundStyle(.secondary)
}
.help(showSource ? String(localized: "Hide source") : String(localized: "Show source"))
.accessibilityLabel(String(localized: "Source text"))
}
}
+13
View File
@@ -0,0 +1,13 @@
import AppKit
/// The translation panel. It can become the key window without activating the app, so Esc and the
/// keyboard shortcuts work as soon as it is shown.
final class TranslationPanel: NSPanel {
override var canBecomeKey: Bool {
true
}
override var canBecomeMain: Bool {
false
}
}
+52
View File
@@ -0,0 +1,52 @@
import AppKit
import SwiftUI
/// An AppKit drag surface for the non-activating panel. SwiftUI's hosting view consumes mouse
/// events, and `performDrag` is unreliable while the app is inactive, so the view moves the
/// window itself from the screen-space mouse delta.
struct WindowDragArea: NSViewRepresentable {
func makeNSView(context: Context) -> NSView {
DragView()
}
func updateNSView(_ nsView: NSView, context: Context) {}
}
private final class DragView: NSView {
private var startMouse = NSPoint.zero
private var startOrigin = NSPoint.zero
override var mouseDownCanMoveWindow: Bool {
false
}
override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
true
}
override func mouseDown(with event: NSEvent) {
guard let window else { return }
startMouse = NSEvent.mouseLocation
startOrigin = window.frame.origin
NSCursor.closedHand.push()
}
override func mouseDragged(with event: NSEvent) {
guard let window else { return }
let mouse = NSEvent.mouseLocation
window.setFrameOrigin(
NSPoint(
x: startOrigin.x + mouse.x - startMouse.x,
y: startOrigin.y + mouse.y - startMouse.y
)
)
}
override func mouseUp(with event: NSEvent) {
NSCursor.pop()
}
override func resetCursorRects() {
addCursorRect(bounds, cursor: .openHand)
}
}
@@ -0,0 +1,15 @@
{
"images" : [
{ "filename" : "icon_16x16.png", "idiom" : "mac", "scale" : "1x", "size" : "16x16" },
{ "filename" : "icon_16x16@2x.png", "idiom" : "mac", "scale" : "2x", "size" : "16x16" },
{ "filename" : "icon_32x32.png", "idiom" : "mac", "scale" : "1x", "size" : "32x32" },
{ "filename" : "icon_32x32@2x.png", "idiom" : "mac", "scale" : "2x", "size" : "32x32" },
{ "filename" : "icon_128x128.png", "idiom" : "mac", "scale" : "1x", "size" : "128x128" },
{ "filename" : "icon_128x128@2x.png", "idiom" : "mac", "scale" : "2x", "size" : "128x128" },
{ "filename" : "icon_256x256.png", "idiom" : "mac", "scale" : "1x", "size" : "256x256" },
{ "filename" : "icon_256x256@2x.png", "idiom" : "mac", "scale" : "2x", "size" : "256x256" },
{ "filename" : "icon_512x512.png", "idiom" : "mac", "scale" : "1x", "size" : "512x512" },
{ "filename" : "icon_512x512@2x.png", "idiom" : "mac", "scale" : "2x", "size" : "512x512" }
],
"info" : { "author" : "xcode", "version" : 1 }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 641 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

@@ -0,0 +1,3 @@
{
"info" : { "author" : "xcode", "version" : 1 }
}
+117
View File
@@ -0,0 +1,117 @@
/* Sprachmittler UI — Deutsch */
"Translate Clipboard Text" = "Zwischenablage übersetzen";
"Target Language" = "Zielsprache";
"More languages…" = "Weitere Sprachen…";
"Copy Last Translation" = "Letzte Übersetzung kopieren";
"Replace Last Translation" = "Letzte Übersetzung ersetzen";
"Set up Sprachmittler…" = "Sprachmittler einrichten…";
"Diagnostics…" = "Diagnose…";
"About Sprachmittler" = "Über Sprachmittler";
"Settings…" = "Einstellungen…";
"Quit Sprachmittler" = "Sprachmittler beenden";
"Translate" = "Übersetzen";
"Move panel" = "Panel verschieben";
"Drag to move panel" = "Zum Verschieben ziehen";
"Translation text size" = "Schriftgröße der Übersetzung";
"Source" = "Quelle";
"Show source" = "Quelle anzeigen";
"Hide source" = "Quelle ausblenden";
"Settings" = "Einstellungen";
"Search languages" = "Sprachen suchen";
"Copy" = "Kopieren";
"Copied" = "Kopiert";
"Retry" = "Erneut versuchen";
"Close" = "Schließen";
"Replace" = "Ersetzen";
"Translation" = "Übersetzung";
"Translating…" = "Wird übersetzt…";
"No translation." = "Keine Übersetzung.";
"No translation yet." = "Noch keine Übersetzung.";
"Close panel" = "Panel schließen";
"Copy translation" = "Übersetzung kopieren";
"Retry translation" = "Übersetzung erneut versuchen";
"Replace selection" = "Auswahl ersetzen";
"Open Accessibility Settings" = "Bedienungshilfen öffnen";
"Open Settings" = "Einstellungen öffnen";
"Download Ollama" = "Ollama herunterladen";
"Copy pull command" = "Pull-Befehl kopieren";
"Copy instead" = "Stattdessen kopieren";
"Translate anyway" = "Trotzdem übersetzen";
"Target language" = "Zielsprache";
"Detected language" = "Erkannte Sprache";
"Replace the selection" = "Die Auswahl ersetzen";
"Replace is not available." = "Ersetzen ist nicht verfügbar.";
"General" = "Allgemein";
"Model" = "Modell";
"Privacy" = "Datenschutz";
"Diagnostics" = "Diagnose";
"Reset" = "Zurücksetzen";
"Save" = "Speichern";
"Show source preview" = "Quellenvorschau anzeigen";
"Launch at login" = "Bei der Anmeldung starten";
"Warm up the model on launch" = "Modell beim Start vorwärmen";
"Ollama" = "Ollama";
"Endpoint" = "Endpunkt";
"Allow a remote HTTPS endpoint" = "Entfernten HTTPS-Endpunkt erlauben";
"Refresh installed models" = "Installierte Modelle aktualisieren";
"Translation model" = "Übersetzungsmodell";
"Fast model tag (optional)" = "Tag des schnellen Modells (optional)";
"Keep model loaded" = "Modell geladen halten";
"5 minutes" = "5 Minuten";
"30 minutes" = "30 Minuten";
"1 hour" = "1 Stunde";
"Unload after each request" = "Nach jeder Anfrage entladen";
"Digest" = "Digest";
"Context and output" = "Kontext und Ausgabe";
"Sampling" = "Sampling";
"Temperature" = "Temperatur";
"Top P" = "Top P";
"Repetition penalty" = "Wiederholungsstrafe";
"Chunking" = "Aufteilung";
"Prompt policy" = "Prompt-Richtlinie";
"Default translation is fixed for v1." = "Die Standardübersetzung ist für v1 festgelegt.";
"Content-aware prompt selection is decided in M7." = "Die inhaltsabhängige Prompt-Auswahl wird in M7 entschieden.";
"Local and private" = "Lokal und privat";
"Permissions" = "Berechtigungen";
"Accessibility is optional and used only for Replace." = "Bedienungshilfen sind optional und werden nur für Ersetzen benötigt.";
"Open Diagnostics…" = "Diagnose öffnen…";
"Versions, model digests, timings and error kinds only. No text." = "Nur Versionen, Modell-Digests, Zeiten und Fehlerarten. Kein Text.";
"Enter a valid endpoint URL." = "Geben Sie eine gültige Endpunkt-URL ein.";
"Settings could not be saved." = "Einstellungen konnten nicht gespeichert werden.";
"Launch at login could not be changed." = "Der Start bei der Anmeldung konnte nicht geändert werden.";
"Set up Sprachmittler" = "Sprachmittler einrichten";
"Local translation with Ollama. Nothing leaves this Mac." = "Lokale Übersetzung mit Ollama. Nichts verlässt diesen Mac.";
"Check again" = "Erneut prüfen";
"Hy-MT3 model" = "Hy-MT3-Modell";
"Refresh" = "Aktualisieren";
"Accessibility (optional)" = "Bedienungshilfen (optional)";
"Only Replace needs it. Double copy, translation and Copy work without it." = "Nur Ersetzen benötigt sie. Doppelkopie, Übersetzung und Kopieren funktionieren ohne.";
"Granted" = "Erteilt";
"Enable Accessibility" = "Bedienungshilfen aktivieren";
"Open System Settings" = "Systemeinstellungen öffnen";
"Done" = "Fertig";
"Checking…" = "Wird geprüft…";
"Setup could not be saved." = "Einrichtung konnte nicht gespeichert werden.";
"unknown" = "unbekannt";
"Last 50 events" = "Letzte 50 Ereignisse";
"Sprachmittler Diagnostics" = "Sprachmittler-Diagnose";
"Sprachmittler diagnostics" = "Sprachmittler-Diagnose";
"Ollama details are unavailable." = "Ollama-Details sind nicht verfügbar.";
"Copy report" = "Bericht kopieren";
"Clear" = "Leeren";
"Open Diagnostics…" = "Diagnose öffnen…";
"Render Markdown formatting" = "Markdown-Formatierung anzeigen";
"Render bold, italic, headings, lists, code and links when the source is Markdown." = "Fett, kursiv, Überschriften, Listen, Code und Links anzeigen, wenn die Quelle Markdown ist.";
"Close with Esc without clicking" = "Mit Esc schließen, ohne zu klicken";
"The panel takes keyboard focus while it is visible. The source app stays frontmost." = "Das Panel übernimmt die Tastatureingabe, solange es sichtbar ist. Die Quell-App bleibt im Vordergrund.";
"Detected %@. Translating to %@." = "%@ erkannt. Übersetzung nach %@.";
"Translate to %@" = "Nach %@ übersetzen";
"This text already appears to be in %@ (detected %@)." = "Dieser Text scheint bereits auf %@ zu sein (erkannt: %@).";
"Mother tongue" = "Muttersprache";
"The default target for every language unless a rule matches." = "Das Standardziel für jede Sprache, wenn keine Regel passt.";
"Language rules" = "Sprachregeln";
"Add rule" = "Regel hinzufügen";
"No rules. Every language translates to your mother tongue." = "Keine Regeln. Jede Sprache wird in Ihre Muttersprache übersetzt.";
"Source language" = "Ausgangssprache";
"Remove rule" = "Regel entfernen";
"Rules apply only to confidently detected sources; otherwise the mother tongue is used." = "Regeln gelten nur für sicher erkannte Ausgangssprachen; sonst wird die Muttersprache verwendet.";
+117
View File
@@ -0,0 +1,117 @@
/* Sprachmittler UI — English base */
"Translate Clipboard Text" = "Translate Clipboard Text";
"Target Language" = "Target Language";
"More languages…" = "More languages…";
"Copy Last Translation" = "Copy Last Translation";
"Replace Last Translation" = "Replace Last Translation";
"Set up Sprachmittler…" = "Set up Sprachmittler…";
"Diagnostics…" = "Diagnostics…";
"About Sprachmittler" = "About Sprachmittler";
"Settings…" = "Settings…";
"Quit Sprachmittler" = "Quit Sprachmittler";
"Translate" = "Translate";
"Move panel" = "Move panel";
"Drag to move panel" = "Drag to move panel";
"Translation text size" = "Translation text size";
"Source" = "Source";
"Show source" = "Show source";
"Hide source" = "Hide source";
"Settings" = "Settings";
"Search languages" = "Search languages";
"Copy" = "Copy";
"Copied" = "Copied";
"Retry" = "Retry";
"Close" = "Close";
"Replace" = "Replace";
"Translation" = "Translation";
"Translating…" = "Translating…";
"No translation." = "No translation.";
"No translation yet." = "No translation yet.";
"Close panel" = "Close panel";
"Copy translation" = "Copy translation";
"Retry translation" = "Retry translation";
"Replace selection" = "Replace selection";
"Open Accessibility Settings" = "Open Accessibility Settings";
"Open Settings" = "Open Settings";
"Download Ollama" = "Download Ollama";
"Copy pull command" = "Copy pull command";
"Copy instead" = "Copy instead";
"Translate anyway" = "Translate anyway";
"Target language" = "Target language";
"Detected language" = "Detected language";
"Replace the selection" = "Replace the selection";
"Replace is not available." = "Replace is not available.";
"General" = "General";
"Model" = "Model";
"Privacy" = "Privacy";
"Diagnostics" = "Diagnostics";
"Reset" = "Reset";
"Save" = "Save";
"Show source preview" = "Show source preview";
"Launch at login" = "Launch at login";
"Warm up the model on launch" = "Warm up the model on launch";
"Ollama" = "Ollama";
"Endpoint" = "Endpoint";
"Allow a remote HTTPS endpoint" = "Allow a remote HTTPS endpoint";
"Refresh installed models" = "Refresh installed models";
"Translation model" = "Translation model";
"Fast model tag (optional)" = "Fast model tag (optional)";
"Keep model loaded" = "Keep model loaded";
"5 minutes" = "5 minutes";
"30 minutes" = "30 minutes";
"1 hour" = "1 hour";
"Unload after each request" = "Unload after each request";
"Digest" = "Digest";
"Context and output" = "Context and output";
"Sampling" = "Sampling";
"Temperature" = "Temperature";
"Top P" = "Top P";
"Repetition penalty" = "Repetition penalty";
"Chunking" = "Chunking";
"Prompt policy" = "Prompt policy";
"Default translation is fixed for v1." = "Default translation is fixed for v1.";
"Content-aware prompt selection is decided in M7." = "Content-aware prompt selection is decided in M7.";
"Local and private" = "Local and private";
"Permissions" = "Permissions";
"Accessibility is optional and used only for Replace." = "Accessibility is optional and used only for Replace.";
"Open Diagnostics…" = "Open Diagnostics…";
"Versions, model digests, timings and error kinds only. No text." = "Versions, model digests, timings and error kinds only. No text.";
"Enter a valid endpoint URL." = "Enter a valid endpoint URL.";
"Settings could not be saved." = "Settings could not be saved.";
"Launch at login could not be changed." = "Launch at login could not be changed.";
"Set up Sprachmittler" = "Set up Sprachmittler";
"Local translation with Ollama. Nothing leaves this Mac." = "Local translation with Ollama. Nothing leaves this Mac.";
"Check again" = "Check again";
"Hy-MT3 model" = "Hy-MT3 model";
"Refresh" = "Refresh";
"Accessibility (optional)" = "Accessibility (optional)";
"Only Replace needs it. Double copy, translation and Copy work without it." = "Only Replace needs it. Double copy, translation and Copy work without it.";
"Granted" = "Granted";
"Enable Accessibility" = "Enable Accessibility";
"Open System Settings" = "Open System Settings";
"Done" = "Done";
"Checking…" = "Checking…";
"Setup could not be saved." = "Setup could not be saved.";
"unknown" = "unknown";
"Last 50 events" = "Last 50 events";
"Sprachmittler Diagnostics" = "Sprachmittler Diagnostics";
"Sprachmittler diagnostics" = "Sprachmittler diagnostics";
"Ollama details are unavailable." = "Ollama details are unavailable.";
"Copy report" = "Copy report";
"Clear" = "Clear";
"Open Diagnostics…" = "Open Diagnostics…";
"Render Markdown formatting" = "Render Markdown formatting";
"Render bold, italic, headings, lists, code and links when the source is Markdown." = "Render bold, italic, headings, lists, code and links when the source is Markdown.";
"Close with Esc without clicking" = "Close with Esc without clicking";
"The panel takes keyboard focus while it is visible. The source app stays frontmost." = "The panel takes keyboard focus while it is visible. The source app stays frontmost.";
"Detected %@. Translating to %@." = "Detected %@. Translating to %@.";
"Translate to %@" = "Translate to %@";
"This text already appears to be in %@ (detected %@)." = "This text already appears to be in %@ (detected %@).";
"Mother tongue" = "Mother tongue";
"The default target for every language unless a rule matches." = "The default target for every language unless a rule matches.";
"Language rules" = "Language rules";
"Add rule" = "Add rule";
"No rules. Every language translates to your mother tongue." = "No rules. Every language translates to your mother tongue.";
"Source language" = "Source language";
"Remove rule" = "Remove rule";
"Rules apply only to confidently detected sources; otherwise the mother tongue is used." = "Rules apply only to confidently detected sources; otherwise the mother tongue is used.";
+93
View File
@@ -0,0 +1,93 @@
import SprachmittlerCore
import SprachmittlerEngines
import SwiftUI
/// The source-to-target rules in Settings ▸ General. An empty table means everything goes to the
/// mother tongue.
struct LanguageRulesSettings: View {
@Binding var routes: [LanguageRoute]
let motherTongue: ModelLanguage
private var languages: [ModelLanguage] {
LanguageCatalogue.all.sorted {
$0.localizedDisplayName.localizedCaseInsensitiveCompare($1.localizedDisplayName) == .orderedAscending
}
}
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text(String(localized: "Language rules"))
Spacer()
Button(String(localized: "Add rule")) {
addRule()
}
.controlSize(.small)
}
if routes.isEmpty {
Text(String(localized: "No rules. Every language translates to your mother tongue."))
.font(.caption)
.foregroundStyle(.secondary)
}
ForEach($routes) { $route in
HStack(spacing: 8) {
Picker(String(localized: "Source language"), selection: $route.source) {
ForEach(sourceOptions(for: route.source)) { language in
Text(language.localizedDisplayName).tag(language.code)
}
}
.labelsHidden()
.accessibilityLabel(String(localized: "Source language"))
Image(systemName: "arrow.right")
.foregroundStyle(.secondary)
.accessibilityHidden(true)
Picker(String(localized: "Target language"), selection: $route.target) {
ForEach(targetOptions(for: route.source)) { language in
Text(language.localizedDisplayName).tag(language.code)
}
}
.labelsHidden()
.accessibilityLabel(String(localized: "Target language"))
Button {
routes.removeAll { $0.id == route.id }
} label: {
Image(systemName: "trash")
}
.buttonStyle(.borderless)
.accessibilityLabel(String(localized: "Remove rule"))
}
}
Text(
String(
localized: "Rules apply only to confidently detected sources; otherwise the mother tongue is used."
)
)
.font(.caption)
.foregroundStyle(.secondary)
}
}
private func sourceOptions(for current: String) -> [ModelLanguage] {
let used = Set(routes.map(\.source))
return languages.filter { $0.code == current || !used.contains($0.code) }
}
private func targetOptions(for source: String) -> [ModelLanguage] {
languages.filter { $0.code.caseInsensitiveCompare(source) != .orderedSame }
}
private func addRule() {
let used = Set(routes.map(\.source))
let source = languages.first {
!used.contains($0.code) && $0.code.caseInsensitiveCompare(motherTongue.code) != .orderedSame
} ?? languages.first { !used.contains($0.code) }
guard let source else { return }
routes.append(LanguageRoute(source: source, target: motherTongue))
}
}
+39
View File
@@ -0,0 +1,39 @@
import SprachmittlerCore
import SwiftUI
/// The long-selection settings: part size and the number of parts one capture may use.
struct LongSelectionsSettings: View {
@Binding var draft: AppSettings
var body: some View {
Section(String(localized: "Long selections")) {
Stepper(
String(localized: "Latin part size: \(draft.maxCharactersLatin)"),
value: $draft.maxCharactersLatin,
in: 1000 ... 10000,
step: 500
)
Stepper(
String(localized: "Dense-script part size: \(draft.maxCharactersCJK)"),
value: $draft.maxCharactersCJK,
in: 500 ... 4000,
step: 250
)
Stepper(
String(localized: "Maximum parts per selection: \(draft.maximumPartsPerSelection)"),
value: $draft.maximumPartsPerSelection,
in: 1 ... 8
)
Text(
String(
localized: """
One part rejects text longer than a single part. Higher values translate \
long selections one part at a time, which takes longer.
"""
)
)
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
+309
View File
@@ -0,0 +1,309 @@
import SprachmittlerCore
import SwiftUI
/// The Settings window: General, Model, Translation, Privacy and Diagnostics.
@MainActor
struct SettingsView: View {
@Bindable var model: SettingsViewModel
let onOpenDiagnostics: @MainActor () -> Void
let onSaved: @MainActor () -> Void
@State private var draft: AppSettings
@State private var endpointText: String
@State private var saveMessage: String?
@State private var showLanguagePicker = false
init(
model: SettingsViewModel,
onOpenDiagnostics: @escaping @MainActor () -> Void,
onSaved: @escaping @MainActor () -> Void = {}
) {
self.model = model
self.onOpenDiagnostics = onOpenDiagnostics
self.onSaved = onSaved
_draft = State(initialValue: model.draft)
_endpointText = State(initialValue: model.draft.endpoint.absoluteString)
}
var body: some View {
VStack(spacing: 0) {
TabView {
generalTab
.tabItem { Label(String(localized: "General"), systemImage: "gearshape") }
modelTab
.tabItem { Label(String(localized: "Model"), systemImage: "cpu") }
translationTab
.tabItem { Label(String(localized: "Translation"), systemImage: "text.bubble") }
privacyTab
.tabItem { Label(String(localized: "Privacy"), systemImage: "lock") }
diagnosticsTab
.tabItem { Label(String(localized: "Diagnostics"), systemImage: "stethoscope") }
}
.padding(16)
Divider()
HStack {
if let saveMessage {
Text(saveMessage)
.font(.callout)
.foregroundStyle(.red)
} else if let launchError = model.launchError {
Text(launchError)
.font(.callout)
.foregroundStyle(.orange)
}
Spacer()
Button(String(localized: "Reset")) {
model.reset()
draft = model.draft
endpointText = model.draft.endpoint.absoluteString
saveMessage = nil
onSaved()
}
Button(String(localized: "Save")) {
save()
}
.keyboardShortcut("s", modifiers: .command)
.buttonStyle(.borderedProminent)
}
.padding(12)
}
.frame(width: 660, height: 520)
}
private var generalTab: some View {
Form {
Section(String(localized: "Translation")) {
LabeledContent(String(localized: "Mother tongue")) {
Button {
showLanguagePicker.toggle()
} label: {
HStack {
Text(draft.targetLanguageModel.localizedDisplayName)
Image(systemName: "chevron.up.chevron.down")
.font(.caption)
}
}
.popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) {
LanguagePickerView(
selection: Binding(
get: { draft.targetLanguageModel },
set: { draft.targetLanguage = $0.code }
),
recent: draft.recentTargets
)
}
.accessibilityLabel(String(localized: "Mother tongue"))
}
Text(String(localized: "The default target for every language unless a rule matches."))
.font(.caption)
.foregroundStyle(.secondary)
Toggle(String(localized: "Show source preview"), isOn: $draft.showSourcePreview)
Stepper(value: $draft.translationFontSize, in: 12 ... 28) {
LabeledContent(
String(localized: "Translation text size"),
value: "\(draft.translationFontSize) pt"
)
}
.accessibilityLabel(String(localized: "Translation text size"))
Toggle(String(localized: "Render Markdown formatting"), isOn: $draft.renderMarkdown)
.accessibilityLabel(String(localized: "Render Markdown formatting"))
Text(
String(
localized: """
Render bold, italic, headings, lists, code and links when the source is Markdown.
"""
)
)
.font(.caption)
.foregroundStyle(.secondary)
Toggle(String(localized: "Close with Esc without clicking"), isOn: $draft.closeWithEscape)
.accessibilityLabel(String(localized: "Close with Esc without clicking"))
Text(
String(
localized: "The panel takes keyboard focus while it is visible. The source app stays frontmost."
)
)
.font(.caption)
.foregroundStyle(.secondary)
LanguageRulesSettings(routes: $draft.languageRoutes, motherTongue: draft.targetLanguageModel)
}
Section(String(localized: "Double copy")) {
LabeledContent(String(localized: "Window: \(draft.doubleCopyWindowMs) ms")) {
Slider(
value: Binding(
get: { Double(draft.doubleCopyWindowMs) },
set: { draft.doubleCopyWindowMs = Int($0) }
),
in: 300 ... 1000,
step: 50
)
}
Text(String(localized: "Two identical copies inside this window trigger a translation."))
.font(.caption)
.foregroundStyle(.secondary)
}
Section(String(localized: "Startup")) {
Toggle(String(localized: "Launch at login"), isOn: $draft.launchAtLogin)
Toggle(String(localized: "Warm up the model on launch"), isOn: $draft.warmUpOnLaunch)
}
}
.formStyle(.grouped)
}
private var modelTab: some View {
Form {
Section(String(localized: "Ollama")) {
TextField(String(localized: "Endpoint"), text: $endpointText)
.accessibilityLabel(String(localized: "Ollama endpoint"))
Toggle(String(localized: "Allow a remote HTTPS endpoint"), isOn: $draft.allowRemoteEndpoint)
Button(String(localized: "Refresh installed models")) {
guard let endpoint = URL(string: endpointText) else {
saveMessage = String(localized: "Enter a valid endpoint URL.")
return
}
draft.endpoint = endpoint
model.draft = draft
Task {
await model.refreshModels()
draft.fastModel = model.detectedFastModel ?? draft.fastModel
}
}
}
Section(String(localized: "Model")) {
Picker(String(localized: "Translation model"), selection: $draft.model) {
ForEach(model.modelChoices, id: \.self) { tag in
Text(tag).tag(tag)
}
}
TextField(
String(localized: "Fast model tag (optional)"),
text: Binding(
get: { draft.fastModel ?? "" },
set: { draft.fastModel = $0.isEmpty ? nil : $0 }
)
)
Picker(String(localized: "Keep model loaded"), selection: $draft.keepModelLoaded) {
Text("5 minutes").tag("5m")
Text("30 minutes").tag("30m")
Text("1 hour").tag("1h")
Text("Unload after each request").tag("0")
}
if let digest = model.selectedDigest {
LabeledContent(String(localized: "Digest"), value: String(digest.prefix(12)))
}
Text(model.licenceNote)
.font(.caption)
.foregroundStyle(.secondary)
}
Section(String(localized: "Context and output")) {
Stepper(
String(localized: "Context: \(draft.numCtx)"),
value: $draft.numCtx,
in: 1024 ... 32768,
step: 1024
)
Stepper(
String(localized: "Maximum output: \(draft.numPredict)"),
value: $draft.numPredict,
in: 256 ... 8192,
step: 256
)
}
}
.formStyle(.grouped)
}
private var translationTab: some View {
Form {
Section(String(localized: "Sampling")) {
LabeledContent(String(localized: "Temperature")) {
TextField("", value: $draft.temperature, format: .number.precision(.fractionLength(0 ... 2)))
.frame(width: 80)
.accessibilityLabel(String(localized: "Temperature"))
}
LabeledContent(String(localized: "Top P")) {
TextField("", value: $draft.topP, format: .number.precision(.fractionLength(0 ... 2)))
.frame(width: 80)
.accessibilityLabel(String(localized: "Top P"))
}
Stepper(String(localized: "Top K: \(draft.topK)"), value: $draft.topK, in: 1 ... 100)
LabeledContent(String(localized: "Repetition penalty")) {
TextField("", value: $draft.repeatPenalty, format: .number.precision(.fractionLength(0 ... 2)))
.frame(width: 80)
.accessibilityLabel(String(localized: "Repetition penalty"))
}
}
LongSelectionsSettings(draft: $draft)
Section(String(localized: "Prompt policy")) {
Text(String(localized: "Default translation is fixed for v1."))
Text(String(localized: "Content-aware prompt selection is decided in M7."))
.font(.caption)
.foregroundStyle(.secondary)
}
}
.formStyle(.grouped)
}
private var privacyTab: some View {
Form {
Section(String(localized: "Local and private")) {
Text(
String(
localized: "Selected text, translations, the clipboard and app names are never written to disk."
)
)
Text(String(localized: "No telemetry, no analytics and no accounts."))
Text(
String(
localized: "The clipboard is read only after a change; the last translation stays in memory."
)
)
}
Section(String(localized: "Permissions")) {
Text(String(localized: "Accessibility is optional and used only for Replace."))
Text(String(localized: "Input Monitoring, Screen Recording, Camera, Microphone and Apple Events"))
Text(String(localized: "are never requested."))
}
}
.formStyle(.grouped)
}
private var diagnosticsTab: some View {
Form {
Section {
Button(String(localized: "Open Diagnostics…")) {
onOpenDiagnostics()
}
Text(String(localized: "Versions, model digests, timings and error kinds only. No text."))
.font(.caption)
.foregroundStyle(.secondary)
}
}
.formStyle(.grouped)
}
private func save() {
guard let endpoint = URL(string: endpointText) else {
saveMessage = String(localized: "Enter a valid endpoint URL.")
return
}
draft.endpoint = endpoint
model.draft = draft
model.save()
if let error = model.saveError {
saveMessage = error
return
}
draft = model.draft
endpointText = draft.endpoint.absoluteString
saveMessage = nil
onSaved()
}
}
+10 -20
View File
@@ -1,35 +1,25 @@
import AppKit
import SwiftUI
/// Entry point. Keep this file thin: scenes only, no business logic (ARCHITECTURE §3).
/// Entry point. Scenes and glue only; business logic lives in the package.
@main
struct SprachmittlerApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
var body: some Scene {
MenuBarExtra("Sprachmittler", systemImage: "translate") {
Button(String(localized: "Translate Clipboard Text")) {
(NSApp.delegate as? AppDelegate)?.captureClipboardText()
}
Divider()
Button(String(localized: "Set up Sprachmittler…")) {}
.disabled(true)
SettingsLink {
Text(String(localized: "Settings…"))
}
Divider()
Button(String(localized: "Quit Sprachmittler")) {
NSApplication.shared.terminate(nil)
}
.keyboardShortcut("q")
MenuBarExtra {
StatusMenuView(delegate: appDelegate)
} label: {
Label("Sprachmittler", systemImage: "translate")
}
.menuBarExtraStyle(.menu)
Settings {
// Replaced by Settings/SettingsView.swift.
Text("Settings")
.padding()
.frame(width: 480, height: 320)
SettingsView(
model: appDelegate.environment.settingsModel,
onOpenDiagnostics: { appDelegate.showDiagnostics() },
onSaved: { appDelegate.environment.settingsDidChange() }
)
}
}
}
+245 -38
View File
@@ -1,4 +1,4 @@
f6951b1dfd3273d8b320f489125b01f6cdbac708f6e6a6a1af1c35fd43f224ce ./.gitignore
ac3b5df584dabe8c38d8dde42e1871198e11c0512e1ed57b45b8cbcdfc5e35f6 ./.gitignore
b6f32f48809b596fa90c724e986bc78f220cac1928039eb57b8f7c13ea9a3081 ./.opencode/agents/architect.md
a58c2194b2a853d0e418ea68b6816e8cde60a007b5fab596819a5cdf77dc4140 ./.opencode/agents/swift-reviewer.md
f58fbb98fbe250169d903f3f3233564ebab9ec73db96418adf0a5d9db26ed389 ./.opencode/agents/test-engineer.md
@@ -17,76 +17,283 @@ c989a2513d0b926f3a202b0616426c7443594ce72896ee91c29c4e83451d433c ./.opencode/sk
57f91677056a59e48748c63557672361cdb24bfa39264560df0209bcff0fd919 ./.swiftformat
2c0c375f3f6704a43e1042b250e0b633ba740aa7bc2fbf5518891a7b5464507e ./.swiftlint.yml
3222c8553505401c967cc302e2d46a99db95f98d92650f6b245e2a1dc901bea9 ./AGENTS.md
52b02a06a5fa40eb610a19c4e83564fb6c5b3592e25a63f271bc42eb75a25924 ./App/AppDelegate.swift
c36aade859ae4432a04f5fb050322e1c78a6e535c206a18b61971809c0fef4dd ./App/Info.plist
593745fab27436e91148de34b7e0e530cef5137e2c566cb479caed033602b949 ./App/AppDelegate.swift
1461fb881c44cee037051e78a4ea1e36ad459abbab1fc7d530ad993687520d11 ./App/AppEnvironment.swift
dc41f554a88b5b499840f72ef676b31530e6ebfcc5da636155001c52ca48d8a1 ./App/Diagnostics/DiagnosticsView.swift
69f0c24937507ed7a9137abfa95fdcd2798cd909dd74642d4b5e6a859da94253 ./App/Info.plist
36aec6e936e6ffff104908b370a7231b9283e178df8d0a453639dca9c573460d ./App/LaunchAtLoginController.swift
553ade6c51a4532be13593e95684c0cc3403e7222f1208bb36200f96915d5e83 ./App/MenuBar/README.md
3099e4feba33120e9ce41e3b8701d8fb8f305b4fdd965336950c3bb7e0e38c50 ./App/MenuBar/StatusMenuState.swift
3b001166f13cac42136917cfde0277c6cd8cfa922280832a4065081b822b3f9d ./App/MenuBar/StatusMenuView.swift
c4a25b6c1207197109d12ea740dc15ad8aa75b6304d901110aa3e10570cd65a0 ./App/Onboarding/OnboardingView.swift
ba9467153908c81fbb2497d5679642ae15c7b9fa23a10ca9b9ab678042aab222 ./App/Onboarding/README.md
382661bb55524acd7a686f215f8dd1cfdd4127dc19629dd637204c5b1e0734e9 ./App/Panel/LanguagePickerView.swift
76dcf59e01ae8319d4f0aabc5e600c549adaf56b6db802794804c3215be9377c ./App/Panel/MarkdownTranslationView.swift
0d8e9dd5c361987e717e5425cb3a4bef2849a3ba5f40d302a4074f4847abf45b ./App/Panel/PanelController.swift
6b84571bda2bd12e4990430d098d081871c6e239782f5c2e07650e3f7cde6dbc ./App/Panel/PanelView+Content.swift
5a76a652c8f5b03421f475211a4beff98037092004dfbfb54fcaab18fab67b36 ./App/Panel/PanelView.swift
bd37b327672595d55c263f109005b816406cce5928ac58c66286cee0f5d16531 ./App/Panel/README.md
9e09591204b9ca4518a031fc856b0cd01245fe8c4e14aa7238e75a83ab05d4c3 ./App/Panel/TranslationPanel.swift
9e8223452ecc9eb20a4e0395d225b93871c4fd2cccbdfe58880620c30d3bb047 ./App/Panel/WindowDragArea.swift
718f35bba5763975e162109095348661d4edfa1d8f167da04376fbdc71cfc7ad ./App/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json
183606ef4431a2099a26983fac8261ab4d8fbf5fb6ff0204367d3a51e11212ce ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_128x128.png
5e90d81c2decbf8a5c4fd5624e976cd4591f4f53c4c4a40e146d8bb1872d2353 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png
968a49a8667ed72ccb608b39fe28afc3f95cd4ee8689d567983ae0dafd6978aa ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_16x16.png
f7fb7b04d7936a965befe202545fdaccb69d7c0c95a99449a27c9119d0326991 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png
5e90d81c2decbf8a5c4fd5624e976cd4591f4f53c4c4a40e146d8bb1872d2353 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_256x256.png
182c8e94854779aefc2f19115d04abb2c66493537bd68f7c5448ae9b9161e38f ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png
f7fb7b04d7936a965befe202545fdaccb69d7c0c95a99449a27c9119d0326991 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_32x32.png
77e828091f2a32d6e233182320842921ae6770c33db8b1dd25800c2e88bfb835 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_32x32@2x.png
182c8e94854779aefc2f19115d04abb2c66493537bd68f7c5448ae9b9161e38f ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_512x512.png
2c8e82d99378ff2fe0ca98754a3ef29861f0130c54008634106532d0754760d6 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_512x512@2x.png
f23266b9672263c92ced1d26fe4dafa75a14d530eb9bc5fc1f599034d597ab48 ./App/Resources/Assets.xcassets/Contents.json
ce0c088300a0a739ecc0a73892aad6b9538397d637760962a810dbf65692f62b ./App/Resources/de.lproj/Localizable.strings
ac67edd346d0828cd0e86cae4e3da719a9e574d22217f0f15a6d30558bd76e14 ./App/Resources/en.lproj/Localizable.strings
5c2e5222430e1822c3e13cdfed202f54cabc32beefb7651af78475b29494dcf2 ./App/Settings/LanguageRulesSettings.swift
0be6586ef0653cd8e5dd12a1b195c236d54fd1aeaf09bbef48da43195e78b6c7 ./App/Settings/LongSelectionsSettings.swift
dcdaf8761f3b195e8c8d8889b2b792aa3dabbaa47b0c641fb4db4cdc09436026 ./App/Settings/README.md
3066bb45d7b90e3ad07931f56dc234b4b3481c40459842e00430b6a66ef28308 ./App/Settings/SettingsView.swift
d3dcb4365c3d9ec39fa379b8e5cc0813745acc68dc851a85b4ab277896a2a5b1 ./App/Sprachmittler.entitlements
3a384017b5b54049c946a674f8263be61f445b8f1ff6f48cdefd70a4bfbe2b00 ./App/SprachmittlerApp.swift
8bad14fa182903bd8f17cca19edceb0b779246f9ce858ede63cd6b575c2b2265 ./Makefile
ddda3377a2e130e25195da349dd0964cfca8a401464b7b0cd8fcec6bfb575fa3 ./App/SprachmittlerApp.swift
c3d0de679f6d151f46cfdd11577eba65e1cff1f82be669be32e42a99fba302ba ./Makefile
0608007aa6ef1a3533d5e5b4d021e753efe89d24dea881d5ed443429a43a9de2 ./Packages/SprachmittlerKit/Package.resolved
8222951112a60723d1d9a65aa00a152f9138d10c4c8b3dc6e7c47bf2b5c46bf5 ./Packages/SprachmittlerKit/Package.swift
44627d4034cde7e11afff37e9b7b99b8384b2291db657f9914a5312ff8f5eac8 ./Packages/SprachmittlerKit/Package.swift
a6b0221a7c806cfbcb6007c960772ee1c063c0b85727a1d1fc42097baf6dcd70 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AXTextEditor.swift
9c7c19d9ea7d8369244447772a3fa0c3fac21cec0ec22b9df700555f4113a22f ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AccessibilityPermission.swift
348b56aa312a253c6a4de1e1af51ca6b9b5c4e49b86aaf7525f43c180ed17937 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/ClipboardSnapshot.swift
2386c6d9f5637e4be701eec1296240dad71211509c971bc7dcc334c975f4b9cf ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/DoubleCopyDetector.swift
ec2f66d1a2d8ebb308427802f54cc70c6bdead8c31a57ed87648446d6bda9ce1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/FrontmostTargetProvider.swift
85abecf8ca1b15fe1a9d5dbaa0caee16a38a4408e932f6115975d9823a2ac47c ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/InsertionCoordinator.swift
0b8a8223e67d0c94551c1dd68609858602069d0ecd4eda736f988880d1e04464 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardAccessing.swift
4ca88b4f08515057738a45c9ae475260e3a840c1d5bb3d4622a57ce04f5b8cb1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardTicking.swift
dc5f5b08ec537ac917c96b7ba4c1881bfdfb7c21e166a4f9ee1f6d9e1289b351 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.swift
26aeb81883b8216f364215602b804a2d6e6994a221f9c910c0ed52cc70d4c3aa ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/ServicesProvider.swift
dada1b00037d12da0df03a24d1140e428beb9488fde7e0a9d99d0cca58d1a4ca ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/SprachmittlerCapture.swift
728ab857854f1f2bb46f032a13f6d47edd491ee0d6ca0aa8bf2b98f91ccb3c23 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/SystemPasteboard.swift
7c580669d76ca3154889a2f3045a1e2689c8984398163496e0ce4cdcad9ae880 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppOllama.swift
9030a1f039515cd92b2178f90649cb028d248a941f16e2d1fc9d52663d7239d9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift
e2ced0cedfdbea4621ba9d01907a56e80001770af0e7e41b31712a042d0c451e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift
a150f68cc08fddc17c09dea5bdb4d85b1b4c3035fa4a9f8a24c48efd1fc0f313 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift
d711719fa15d25c28c7e29c1a8773da9da61ff0372917ecf684fe27538e1decf ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift
02421321864ecf0540a96b55a692e91eacb9364d579735d20b9ca94ebcf99a80 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureText.swift
3ce80227fe4f6cfb9efc00d83cb4bff28e870fd72aa29d8cc03a723e8694a34e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturedText.swift
2a8c7b261b3c955547fd88520a9582c5c31a1e86a4c13d8bebfbe1d4b8f752bc ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsStore.swift
3275711919331a617e9db199e89d6ba5a9c28d518eea4a590fd9dac74c7bd876 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsViewModel.swift
d81ffb9aedc1feef70af050f55f3d0bfd85a828bda80d54d32e5a0667e05bef9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/InsertionTarget.swift
56037f9dc0096e9e5e0a44365fb29ecd3185e8c39bb7ee156f31ec08e1326ff5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageAliases.swift
5d78b5e2aafd267d0e6eba66ae7257dabfc1dfb4b913e78754f7ae128bddfd4d ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageCatalogue.swift
c2fcbae9e59d203f90c7f21a92d3c46ffa9c04d916a1565d16b90e4fa1b361fb ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LogCategory.swift
cc89553a898735a1288bdd1c67a04fbcd282f99ee812a83c8b18eff9627ab65d ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LogRedaction.swift
39cec81db2748fd5e01c5d6ade00bae5babf4a68d7d472a69e98b20884585c5f ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Loggers.swift
83b6c93fc950df1fa8e4942521187a0ee3ecb319b5ffec6deef6047ef8d2b171 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OllamaErrorMapping.swift
b7dfab9b2c613071b97bc329378eae47b97305cae758221fba787c8be4eb52f5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OnboardingViewModel.swift
0e08aac528b2a8da63f2b2cccbc2a4a134c1dbc49927f3d78115b3faaa2944ef ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift
c52e182fdc6806a06f7b516806140ef26aad8c44e72f9e5beb9135acbe28b878 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelWarningMessages.swift
563d79ceae06a20e8a5b78e155bfe8489bac8f5267a8c3d064fd5c50ecc66cf5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PermissionProtocols.swift
761c20b4a1c063ac39648c3d24d8864a0329ff348eaf45db4fb27c573f15e44a ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsStore.swift
afd0db8a53c0afb37bafc8647e2da0a8f741e0b7396c018f95c63a80484ea80e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsViewModel.swift
b126a8164e50da9c4f276efbc2f591fb94a587b9855a5c9379485ab7d334864e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SignpostInterval.swift
e33ebfeeeb27b88029c20f212769852c5c0a697abaeb1bc249d350e7ad649273 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SignpostName.swift
20e3977534de6e1c1af8bcc3049318007213a034aa2e8d2d24032b22e1bacba0 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Signposts.swift
b6580ae5a0f5e18b6b527766cb5acd5de4d828df3badac44ae294dd72acfc436 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerCore.swift
fa4aeb76903a93335817a71e80829c6a950288c3575deddc0dd3f89d7a59ce79 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/SprachmittlerEngines.swift
2864b92feb24a0616fa546ea2683fbdc9f73352ca64ab84da110e19fd7c6a926 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerError.swift
359faa0524007bb58a504b073c854c04736482b893e9509e56843a6850d9e7ac ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift
f75ae67b262e18b53721d070acc0e8d7bdfca94698f10c1a5780ef948ef72912 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TextInserting.swift
98de162fc7be182a5832e81f12b2bf72c336abf1a65a6a2c94821b4bf51b39d9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift
d3511504a464cb986ffad56ef31f5723cf6451fdef04b1e2bf6c58d2be21a6be ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift
480503eea4bc64f3125560c91d47e56cd9905e957af189a54cdf8b816a380ec2 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationWarning.swift
5a721207611b9aa6228bc288f5f5e0c57dd26c593ab3aec9bd38c91f9a9e0fd2 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Adapter.swift
06bf6da9127b3a010cb33b3db091e4301b32aca44f8cc7181ed1c34b00ece7b5 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Languages.swift
0b5e6571d378577091f8ce3b86020545b45ca2c3400afe88ebeed7b4aa8b68f8 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3ModelPreset.swift
dfbbd5cfa397340a38b844307621c26e28708eb36aa91095739e492838124c9f ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Options.swift
021919b8ff8e27bde4f02b4ada08e2b70463225afdc749d4604db6f84efa85cc ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Prompt.swift
fd9c98abd3fccbb77154a5ec7822e3eac3624134b377719078f5549f2081eeaa ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/LanguageMatching.swift
90c3ab7c90331c97ff18cd8a00fe2fcf5101b1915c45d5217a7edab95e612ac7 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/LanguageRoute.swift
1ad2760062b723e41d46c38fe7b1b4cbe959af417f9657aa12c6f3a6c08f406f ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/ModelLanguage.swift
ab9d4fcd37731131646decc9bb9a25b1e2338613ee6b093427c89287a2e9b762 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/NumericTokenNormalizer.swift
f00f88c07fc06f2abbf5a17554cb3cb7915f4e60fd32cdf98cdeeb810875add6 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/OutputValidator.swift
c473fa0f2c89d4a4f75307e81a6a5d28f1f21f3bffcc8911bb30487d27f64486 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/PreambleDetector.swift
50394e1fd104b4fd85cd2b206b146addca15fa21d7cadc5e3cef4ea7f88436a9 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/PromptPolicy.swift
5c5b1bfa5f10e2be6ce52f13e7c13143cbcbd7ab3e2af53edd3b13badc228f5a ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/PromptVariant.swift
dfe9d284e76ae67a42418c69dae4f84810b9ac7e6d3af675ded1625dd083282b ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/RepetitionDetector.swift
5ddee40aab9a5e099ffdb3c7844ae9d19ea44c885a89a774335c66b6927de62d ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/SamplingOptions.swift
1a0d4d9149432f7771a84060377eda2589d14b9041d9f296b871dc4ae3e92718 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationAdapter.swift
edf6c7617410a9ef2f6f0ea4cdf22e12842543d77f88f268075baad0749b74ba ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationDirection.swift
8969928cf7b9a71d9aeb2ee36fd6a70cec1c7ba9fdd5f42c23d4bf28e49a43b6 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationWarning.swift
418b1f3737fcf926815055c4f4f3409b292e6afcf0d6b81f37d1160b9f65ac35 ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationManifest.swift
43d7f19f92767fb2109dadf939ec4e829a58bd738f81c8abe7b8f3c92e58f9bd ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationMetrics.swift
dde82951a4e969628d80b224771124fa70caaa2ba0b447366343d5a99dc0361e ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationReportWriter.swift
dd445421272beed0c28e0c2f853d267fb6c8832a313cf836f6c2e47cf024b574 ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationRunner.swift
83f6c78029abb6c43c78039773f601752411f0f8f23ec3a9891e8008b70387b6 ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/SprachmittlerEval.swift
887b767c70d1c765fc73553439980c4216bdc278d4b27f923bde04378cd6d6e9 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/SprachmittlerOllama.swift
a517bee61c90ae280f6d8893e998aeff3ea4ccdcfca08a006287e1b4750275fd ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/SprachmittlerTestSupport.swift
c5a26fded64056855f876a6a2c0c466afbc3f5fce1de2323eb073da9ec09f256 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/AsyncSleeper.swift
58160c8c41ba81d72aa96dee583fa0ffc5fc64654da3a56f608c67c62aa49352 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatEvent.swift
0817f2102a866ce7c0bfc06fa8504a73294e75a6fca70ee0578ce78216b42147 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatMessage.swift
363bb249519c2b2d67a6a0c516bb5b113298545cad1a575593b5212702418acd ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatMetrics.swift
38a5c0272aff387a1ba70a073559a97d2b31b4b9c4550c0540a7ddbcd8a93705 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatOptions.swift
7ecf5e465e8cb14182396e850ba8640c74d1a0d1fec3f8c39d288d0ff89cf750 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatRequest.swift
f22c1caae9a722373605504cf9a3a268497f3d8683548e0b75b417042d3af9ed ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatStreamContext.swift
9944f8e250c2b334a9129a82281fef45663043a5b0a3bf01acdb114b68c565bc ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatTimeoutController.swift
4f850d29de8d81ff85e0a3602cc72029f675ea37d56481e75aea7d5b5e0d087d ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatTimeouts.swift
f158a61553f38138d6e8a08e02c15de949b882898273d9c13b857401a01df7a5 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/EndpointPolicy.swift
eb3bdca89e3e15d2c9300e0f92ddd36dfde28d6105e87ee3c4ca29171ca2152d ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/EndpointRejection.swift
157abae634245d3646f16e2742ecaeae72adead8c10f6d1ab3dcaa02b5766ff6 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/InstalledModel.swift
312b3919d01d0128b57db111a579b0add5b89d7e8010ec270aecdd9a3ef38dac ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/LoadedModel.swift
88ea1a3e0617aef24ddcff51073fc30b27974b9bf8454ab8288e9f003240cc11 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ModelDetails.swift
ab586304f68d4e46146577438db1560107eb8f713cd0f4244fb0ae3344496742 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaCatalog.swift
68491c3709467eb22a9d9c21ea72d7ef3a37ab04b6acde496a714e772fd3c3f8 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaCatalogClient.swift
1ff7419acc3a2401faa719eb0e8955a318ebade41b8718a8bf7c52abc5be2c7b ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaChatClient.swift
ba536c52aa94cf7e48dd98b741a41234b3f8709a38503ab264998da281d44dbe ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaChatting.swift
5f4ee95364526a59e0776207a1e93ce6cea5eed3473bd5686a8674a425824401 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaError.swift
711780019b33a02bf048968196f04b04a4f996ea9d0e1128140b153524a0ddf9 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaErrorBody.swift
0020db5fc620a8a188ec0e6feb8d903bd4d849c87808efb8b85449c4056e4bf7 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPClient.swift
d76d67d55efc70289aeed9626265c3f6d183b001c4d36047f4e8962180a18ce1 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPRequest.swift
c32d05b70ba04d525064a2ed71f5ea67d1655d72c56f9d185aefe4250840321b ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPResponse.swift
232e1e3d1eb070a353e72f301c82a4f3ce56c874f8754fddb98bf71a5a816798 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPTransport.swift
92753142b6151ff867de64d1ce93ef1e975c3b0e7cf15f36b23828f3346e0275 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaSessionFactory.swift
15038cb5553980b00888fb763a8950da29e9c976fdc5288c0421053e84aefe4d ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaVersion.swift
58d527fdb66f62fb6b7009bf454b94ba0f6ebd19c3686d91c5f598154533c830 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaWarmUpPolicy.swift
443eefc6de2a8196735ba2deb207bfc36f46b1217e7873db9115c69f6db26921 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaWarmUpRunner.swift
314982eecd8a75575e2c25fc776ac785c8d9e99d035a645480e68b946d007a43 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/RedirectRefusingDelegate.swift
2c4ec4c3422d65987661842420f313b48c17bb5785b6b8be28ea07cd8f95d02f ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/StreamLineAction.swift
54c856650277c61b2e6dde34120eaae59a7b354d0ed621f5ac8634684211b030 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/TimeoutPhase.swift
9a8d1d437e08462d0f063ac0784812b0f8183dce5b4251b28c5c064e4a47d3fe ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeOllamaCatalog.swift
54076808b76b6efd5ecb174403210c331d1b674b15120400323c0623e9e3ac85 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeOllamaChat.swift
1cd84966052430f540220cd7bd22203b8a77574540a66700288e588e9b8efb52 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeOllamaHTTPTransport.swift
524e816552afe34f8844a1c01bb56b6bc81fc5a83cc96889a25bd044e73dc0c0 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakePasteboard.swift
03d570bc4022f205abb52da509bd68444879308b14f46bad497cadf9f80f3845 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeSettingsAndPermissions.swift
16e6ae7d693df1ee6532affec1fa687aeed1e709595b929f2a4e1f00e1b9d88a ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/ManualPasteboardTicker.swift
c0f87a5320fe715f5dbc7c9bbc7c0fb19a5b64d1c145c45b26f060c151eccada ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/ManualSleeper.swift
0ea5a0c60c2185262e52f71c78538f9b1bb308c9835dc2362f70929da9bc42cd ./Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift
b639d452d78dcda9e9f3b5ac3298e8499a7837a955839ae5203b508944df2c63 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClass.swift
b768d43f50bd4fcede0f3c654787771a605b6ea2648cac722d0e78dd913b4fa5 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClassifier.swift
9eebbc1339104d8a0b0f9f579d0c9f0bf69b05b5ad1a4550cf645ca3197686dd ./Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.swift
41aeff6d807caa027f9496a4bd6048bdde55d6eeb4a11b2acdf445dff39735bc ./Packages/SprachmittlerKit/Sources/SprachmittlerText/MarkdownPresentation.swift
c7591458a2fcf4813a166cf4f15aaca69688a85e319cf71ebd5c2dcffba756b8 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ProtectedToken.swift
2ec31538fe5a2ed98fcce6b815c1844cfd30a53073f4987eda8043bcd222d58d ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ProtectedTokenScanner.swift
6ea915648616c12b9b2ae3bbb97838a512c6c3a91b2bccfc13e144d950d4bb6e ./Packages/SprachmittlerKit/Sources/SprachmittlerText/SprachmittlerText.swift
8a349b1fdbd3755bec2f6ef45ebec31af96be8857923e3d0f79696f5c98eeffb ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/SprachmittlerCLI.swift
4e05396e9e2f915d450af13f57dde523b961d1ba204bffdb5c94db4ba0d82941 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/TextChunk.swift
f528068c473ed46c7daec43a1306b7bd50aec76bf3fc353bfd86fd5e18388854 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/TextNormalization.swift
383da4ec8485cf7457d9e336978ec8b4a6d9f49cbfab8db70db45dc833decb56 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/TextScript.swift
b2f837437ba28548e74d43a2a88bdc3f2e79d3d1e6ec16b381af04256909174d ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/CLIEnvironment.swift
d775cfc21b88687a443118fc0d12f6c4837f712ab674b12286f87470a33bee8f ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/CLIError.swift
7475168734bec7883f4f911af91e4a7184da55849b853eaf7429ae20171d3db9 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/CLIOutput.swift
9c0e6beeffe1ac02e5f32d24f2fe78159183719414978a5c9bb9752313805777 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/DetectCommand.swift
d4ea1f2538934b1c2ffa69fd905c42194760a535a54ac4d241daa616530f976e ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/EndpointOptions.swift
57a104206b2e662d3fd8e5040b422242744752a90133f2f902771d1d73e6d62e ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/EvalCommand.swift
48a9061c6c40d9bd32a55635873e64f5ed7f97edc97827f78979c7b74eb55a85 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/LanguagesCommand.swift
aa686ae5d4b40d290b7963a2ba97dab4e3ae8c2054c0df09e9093448408dbcfc ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ModelSummary.swift
97d119e9c05d62a527bb255ac67dff9049d76a7c11ac292b7ed0ce11b63c1cbe ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ModelsCommand.swift
b8645b487845964dbc060c2a99081d7f89ca5026fb6ab5be82433bf1aa0c1b18 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ModelsRunner.swift
b0125112472bc642661bf0233f0b7cf1bce3ef7f511c333f73364152b0527213 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ShowCommand.swift
a2e96139102375e8586a1568f22d44317cb0034e62c977ae45fc691126c4114c ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ShowRunner.swift
1c9b3e180e4ce78c5cf10bba99edd6c36fa9fbac85e4062dce84d396693e1776 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/SprachmittlerCLI.swift
78d1933ed58d565c2cc5b5463e8c99b3dbcc379f77ec956c645085912441282c ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/TranslateCommand.swift
d0e8bf434a42ce93fba7e611b26797dd5b7d20cd0c9468524fc14ef84b3abcc1 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/TranslateOutcome.swift
e7ec098ecc2e0c3f62ba53cd44afc0659b77b7baf2d5ab307cb4238c1f6efa5c ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/TranslateRunner.swift
3466e030b39a884371d10ba4a2b9ea1a05b7b053af1bd0cb88aa046ba1af2067 ./Packages/SprachmittlerKit/Tests/SprachmittlerCLITests/CLITests.swift
57fbb191c4bf3a9325d5fdab1cdc950bc6e2579f12ea64442c8b2dbd56b79cf4 ./Packages/SprachmittlerKit/Tests/SprachmittlerCLITests/SmokeTests.swift
d4e110c510cac46c1acecc68f28ef8b30daaf1f9b623f0533ad359a6a13680aa ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/ClipboardSnapshotTests.swift
23e0c52e3f5f9b5848ff9118bfe3baf474a21c830560be382b978328e794218e ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/DoubleCopyDetectorTests.swift
efac77b258ef29cca1cc61311ef8d167e45ad5680a73396a1b4bc6d99d9a3f45 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/InsertionCoordinatorTests.swift
c23c58fa553049241f4c40193d41aba4fed8261f1ece4f32bcdf65af25abf099 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PasteboardWatcherTests.swift
87e92d608b14675873a6554a3bcce951fb62b45b95ce32972df978cada697a43 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PlaceholderTests.swift
d2d3507f437c7126bf15ebcba7be6d03794a73a637089c511c99096bc564cc5a ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/ServicesProviderTests.swift
f7375e2cd08709d7b590ae4f6d70be3edb88f122f9fb3aeaac37c826ff637d12 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/SystemPasteboardTests.swift
8eb9ab1b8b15568295aff0b90640afad7f1a38ceaf3dfa2145a0a338f7071d57 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift
2ea18f23e2328110fa6d61e51ecf4607eea7bb82d1c8eeac5dfd844f07c3a6e0 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.swift
2d5742a1fbbb65044455cea92b9f95b9d39f5236e92e4f152b141bcf964c639e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMappingTests.swift
c584df764e9fa0a029ed9f17c1a3b27cb4e3b91005f27171d5553aaf51edb48a ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMessageTests.swift
95ca20f1c4cf0fd68f29a488770a1d6d7911c534913a0f88515ea1fe4f4cdb9e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/LogRedactionTests.swift
6610797e6dd77401d1bce624d65e84db9bdda95820b1f56add1d24cea1f5df91 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/LoggingContractTests.swift
8c0462d50ff3796aba6024349083d8b1ede654b495790d7610f95aecc8870001 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/OnboardingAndSettingsTests.swift
fa5572b8825c7cff4c21f45e5381cb746606c270a45dee75e304be684b64ce1d ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelChunkingTests.swift
f8f1ecfe58f003a0713ee2948c06a7b0ea18272319336025a31f87618bd56f0d ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelRoutingTests.swift
f2071269097a49ddd38a23a213920d09a7786201ef7eb68199a8eb90a4bee303 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelTestSupport.swift
667624e7bc610bbecf323d4401787082bec3e3a2397bd1de86d1dca897e1082b ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift
e9fe1b63792e610bac81153c6bc79d4c836c36c4c9538b26887daf62e9684d80 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PlaceholderTests.swift
5671265556115fe93adb7ee3ccd39a9f31786c7da2e022fe9914db06e5555e24 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift
641482d5c4e8540861775d67d007d6820e1849f6e7b3d2b0456ef462434ada79 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift
988eb93a5d1483a6db061c1a11d5b06d7632157c076352c435418152f47910a5 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/README.md
86bae20b590f03748a5b498a0ae402d7bb10fb0b7ba7bbccc821fcbbcba8ab37 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/default-prompt.txt
86fafc88be2c581fb3eeaaace4320c9e6eb8bda2d89b757cfcb3ce1b4540fe74 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PlaceholderTests.swift
615de4459d2d77dac87809bb33af42d32ab624cb5367d1b3b9de6841d4935bc3 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/delimiters-prompt.txt
4cb7a5de7d493e2b21826322dc38b4d31415352c609f3b68b4786bd12bbdac42 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/structured-data-1-prompt.txt
cb657108c3f9b6f1b3a743313d2b6622ecf7b039ce80b8b2a1da3bce78451751 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/HyMT3AdapterTests.swift
ada2bbfcf0213001077d55b475c3c2ec764623ddf6bd70e62d73d3dc08c99dad ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/LanguageCatalogueTests.swift
e56dc9de2741d731b02ff3bb39ee74532ac4350d232eb66fac86ffb770cb7a86 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/OutputValidatorTests.swift
7d1c6fd3193bcd169be2421a56e42fca82e7e44a5a288dd6482957ab6c50af21 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptFixtureTests.swift
8bb2e2310a40e5923fa77014ac5209cf09cc8a52056a22cae9544f3468e1d2cc ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptGoldenTests.swift
d93aa1ae54f4a6f49aba4f2badb065a86d29c335afb6efd0890684759718a3c3 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptPolicyTests.swift
1824f05ed6f704263fbfb70cdbe07fec85812745b1b71133be2781c380963db7 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/TranslationDirectionTests.swift
b921811eb2bad2cde5a5c199b9c5e4fac710740193789d324d73580d2b8c7abf ./Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/PlaceholderTests.swift
78fd25235b625f82115f3d14c6a9863949055fbead95c9ef83668866bf255d10 ./Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/SprachmittlerEvalTests.swift
e9fe1b63792e610bac81153c6bc79d4c836c36c4c9538b26887daf62e9684d80 ./Packages/SprachmittlerKit/Tests/SprachmittlerLiveTests/PlaceholderTests.swift
bf9501d4defd98c8249b5524c2113f00e27e05a279548a8cae4fd441b370d256 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/EndpointPolicyTests.swift
1581a9133daf1294fb224820af9c8c265a03b73eac959ff921b213107881940b ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/EphemeralSessionTests.swift
3552c16d0da451db9b8d9cad3375d9dc4d716003dfb6afb89b6ca92c99d4fa2d ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/FixtureContractTests.swift
c48ac2946761e46da0d2eed81204e97a7fd96361b55b44a289ccb56587f6a83b ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/README.md
0c2d6cdb4ea5255e9266dee670a8a1d84ad4a27549c6e8a4f8d99eccf6677eab ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/capture-meta.json
4157b4206f99f974ce4a6d54f1816f8912f409368f63206d7cc65abf6426d50d ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-de-en.ndjson
944d0baa3a932e0bc42ed0eff59a055f2cf01e1a1e2cc66a051ba3a82e8e1f84 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-en-de.ndjson
398ae470bf8bc88df8a2d1c1f15289e62cc941f162774d3a5469dd6e3b907378 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-markdown.ndjson
e5a38a0283dad14969131052bd8daf60132c783af10945b6d03aff71b89e4b58 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-truncated.ndjson
4bafec6db42fb16e1901cb8f4de666c52d9a270c8fadb5e3359b10be7ebec80d ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/capture-meta.json
b735e23f9edd09a19969869fe5db53b9924214eabd57932a3a371f8cbafc30de ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-de-en.ndjson
7f6f9589c6ce4f4bc542d940f1eb72210acdab4ae39c93e79df40df1b87a2270 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-en-de.ndjson
568503e59cf16924996dbfb2ee50a944eed20768fa637d595caa358a91a4ce88 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-markdown.ndjson
1a9c3e41b0fc5dbd6d97f1b9bdff0d3db365ccb2621785b8ad34454381cafc99 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-truncated.ndjson
2f0cfe6365fe218b3c9ecb2f2a712bb53ebfea811982a5a0d9e4f32076ef3bfe ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/error-missing-model.json
a8f7899f295520b026b56e103486fe3ff8e66eb35db9c457f44e36c8a45d8fc2 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/ps.json
f1410d0bb4a28d89c049fd9f9cd7df5cef24780f246225de6f1a7c38db5f41d5 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/show-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M.json
4e7e6b8cc3ec35a6e3e69d96335ae12fff289374e9cbdedfe0563ec3db8941eb ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/tags.json
fbb02594028ba766fe5f93bf8a5b62236841fb9d051277e0dc633f87e2c2d396 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/ps.json
e3844615abca9419b448745038c8fe2f9813ea0a56eccb1e34c57be879071a1c ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/show-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M.json
dec441bad497eeb245c9b28d2a231a4859762b82b8a4b0b07ab0211f5595ea24 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/tags.json
672856105eb7e7811ecbae8fcd189743b8fd44aece7baad3a1a781b5a41c43eb ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/version.json
a32b7bdc7476fc1521d3161560ee83a3c7c2ceb83c0ac7c2c0ee22d8c869240e ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/PlaceholderTests.swift
a4a387099e42bc0bf9ebc1ffb43e3a0aab843d70ef3d5a09590b72ec9d53fe15 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaCatalogTests.swift
da75e1c796f1889f594e9cd8bb4d32b1a11d7d4977647cae7e97d352b1545b55 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaChatClientTests.swift
6ed315b6389a479f0bc25865182e76ebe32a6bbca5c3be63c847a0ecac91ca90 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaErrorBodyTests.swift
ec4e2973a3933903563b1955da6213f2931b4e961fdc2bd8d40ab1d5577cff48 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaTransportTests.swift
4f388b8c70fb6b890d4b2fb86c338b837a7991a3592c3995038946c2df8e2e40 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaWarmUpPolicyTests.swift
4442060cc5810f0a0332a0abd05b1b9b54a73bf0045fe0fdc94b543a56238106 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaWarmUpRunnerTests.swift
deb3801d380aaa32228732c60b70ac576ebc2563f1dee8854215f2ee1a1004d7 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Support/ChatStubURLProtocol.swift
ecedbb779b022a8d87a385903040d49aa9d1ee144c2ffb58dc50ea58d297f630 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Support/StubURLProtocol.swift
766a76be19e12928f2cc39cb1e905de6da07eea86a68f19247464af6a163708c ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ChunkerTests.swift
a90dc29af451dac1557a88081a53defcffa8d21fdc0029d7fc19bc3a34d81598 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ContentClassifierTests.swift
74e7640a50e5cdc77207700b4a76b608abc88de48464ee76e40c07d9db8c4bf1 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/de-sample.txt
f9ede3201de7a3d092b2f114dd7f131dafd3b2d6614c0ba91d6181e326ab005b ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/en-sample.txt
b0a7d3451d8830654fe79476b8d32d95709d956817a4436f58c0f73bbd8d3194 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/markdown-sample.md
6ceff5d7b34dc4f4099c1ac8415f89b680f64608c3b9e140c4dee1737cf2477b ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/placeholders.txt
436ed18c9c1cd8bf15df11e2c2f9ca974f9a6f17ca8b894e5ffef999458653fa ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift
80d28cb607b67a35cda89d86e2819e29e71b38e8234557683cb7c96f611037d1 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/MarkdownPresentationTests.swift
8c5c21634d749ad05da8b6a0fc1d8e132a494177a697ba0a1338a7a6b5dba50c ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/PlaceholderTests.swift
dc45614d3b3268dd5081f8678f1bd4231dd73b067b49b088271b29362563bb8c ./README.md
de21f0e9556ed2d25289c10041a913d1ea55470a4951d05880921cc1e809d964 ./docs/ARCHITECTURE.md
67c0f9ba9e818267e99c1756b82643f7e59effa6783325675386aba0a1002cb3 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ProtectedTokenScannerTests.swift
c3294d486cfe44a6f0a69a1ec05cff33a8eccf090fce04fadffa96b6b2563d6f ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/TextNormalizationTests.swift
2d902ce53c14b6d64a578bdcc99845b6375a69ced37f503423c9df6cbf3c15f0 ./README.md
f1dbc2fb876d909b8486239e9b75b09ed68516c341d586e96d8626715c86a88c ./dist/Sprachmittler-0.1.0-local.dmg
b100978fe55c5afbf6b3c987b34e17f3413329d3fd580a2cfcd616f71a564aa9 ./docs/ARCHITECTURE.md
018c5faf1a5d2e8d851ab209d45e64993cbd6b7976c4aa90c571359c83e83264 ./docs/CODING_STANDARDS.md
c17e0eee0e06c0ee1e3e073545b80eef55142cd1859cfc541e195447b00f68f1 ./docs/DECISIONS.md
0186c9d6ccd86c745b0d78068283c7dd786b4329185ef9022f4169e2d4ec1a60 ./docs/HYMT3_MODEL.md
7da97c74eb82432130e4cf91b3175504bd2c0fc3b1227be0efb872df922feaa6 ./docs/IMPLEMENTATION_PLAN.md
0eddd31ac7f4ad295720b9081896200d622f28ed3a17bdab30f57f557d980bdd ./docs/DECISIONS.md
5b80ea8994519f2be34aa10abb345ac3029d3d3a29705dcfa0a1cb344f4b95d2 ./docs/HYMT3_MODEL.md
d87fc9df926f6ba77ce67b2731b83f48f2b49848c637f12d0fdfb5f27f3c6775 ./docs/IMPLEMENTATION_PLAN.md
c3a1838fb0a06acf6b7826f6ff278e15065af198dab22ffb1435dacdc064ad69 ./docs/KICKOFF.md
20a87dc7cf8cb593445c89d334e123f6275232524598ac71a21ca32766cedfb7 ./docs/LANGUAGES.md
96c63103091dc9c53c4629e5bc830b2ce92eae04e74096ac1ab15d6c3615528b ./docs/MODEL_EVALUATION.md
1abe88261cb0c46df94b195db3307ac2eff8ad0c610c1f3683b306eda67ae243 ./docs/OLLAMA_TRANSLATION_API.md
b1d9fcfffd9d0e6b3a9792633ad71acdef29a344eea0dea778e132a7c0330322 ./docs/LANGUAGES.md
a28161210fbabe27d1348f3552851fe7b30c9dccc658272f2cc79af5e085ec40 ./docs/MODEL_EVALUATION.md
6f94dfe4f2146ce0b9e066198c9e05ce659faf4318513ce586c966989fd3d1c0 ./docs/OLLAMA_TRANSLATION_API.md
e6dbccc3cb4c7a169a6daaa563066a6764a76b6b7649738b839dcbd9b2400ee5 ./docs/OPENCODE_V2.md
1251f24645cbe526b015c5b683e55073cd61a7ee9a34a1a613167b5d1fdba925 ./docs/PERFORMANCE.md
e2b785807ecb56eb1e7c02aaa6a487ce7c1be421865685bed4be2e973269bdce ./docs/PERFORMANCE.md
4a37cf1815071b3afdd10443ec9e05a5a78411d615c42f51117c5873922531c4 ./docs/PRD.md
8f73b8056f62e3310adaa0252dcab035888772f163e03792f88171e4039da5d4 ./docs/PROGRESS.md
d69d08cd64f6ae6c6779692c7e2e04dca6ede7729f53790c0e3e71b6fc8aa367 ./docs/SECURITY_PRIVACY.md
8707e5bd7db8f5981c49bdfe739be3ca2da9370efd39e8f3450db29b95ffcbb6 ./docs/SELECTION_AND_CLIPBOARD.md
c7609798be659d3d96c0b4e1226bbfd66cc0c0b0d583eaba47df37c3ddb70ddc ./docs/TESTING.md
381bf8425054d8b4eb6722ecbff4f6d4a4b0ec868bad8793441ed1246b5153e4 ./docs/TRANSLATION_OUTPUT.md
6ea3e3881a9f6a7de968128e660a897c648d8e01af77b3e831228b809d0d94e2 ./docs/PROGRESS.md
c72f39e7e5e1fb9c45c32f0741a379564debca4b408e702615d162f360d47ecf ./docs/SECURITY_PRIVACY.md
f140344de55d11eb450961639ba85a1ff479cf2e0cfb3c8bd3c4cdb2220a11ea ./docs/SELECTION_AND_CLIPBOARD.md
8720e8bf79ba7ab051bb8bd09f55b7766f98941904f354cbe3ab7b88c941e860 ./docs/TESTING.md
14677683317de607406997825d4ee239ec042c9872f0b44c29ebdf00f6540aa5 ./docs/TRANSLATION_OUTPUT.md
5c4d63f01581cdbc21d7ff9da8604adf8230e280b42512e3375cd0a72a225f5a ./docs/USER_GUIDE.md
373b20746a6ed145ee598786458a97cead5cacd97a339db14b3e2341645c6c8d ./evaluation/README.md
a60f1917c64ac8c3df0d01dd55818652ae100a6d750c34be24675b33226cad45 ./evaluation/corpus.example.json
a5c4b95257aa02eca20ae98acf68dee329acb870f16fb3ac549038627327da71 ./evaluation/corpus.schema.json
6a54dadd3426cfc011c8b02b9c9b935f6ba4bbbdc5db38ee59377d71a8919833 ./opencode.json
2b065f1791c31305ba1e9c018ffd439a04f82110e96a55f05e67311926cfd6e0 ./project.yml
e0628748753d6c8952f05c7da78a632632c2fedd6c9632bc8d9c7bba42127e51 ./project.yml
749bfb269c22aed25e67b73abfda7055aee645b68a9907f292ef5c1c38366eae ./scripts/bootstrap.sh
443548848c9ce9edb9ce54efac6158e6cc63e69b40259dab4edb6ead89972373 ./scripts/capture-fixtures.sh
aa9531690d41071e34dfcb33241bb576f7349092d52c36242cedf55af7ca9c46 ./scripts/capture-fixtures.sh
495f78822630ac48a91e21a06c5d96f4ffbb4a38b8b7ee5b591faeaeb1fdbbd0 ./scripts/check-signature.sh
fb00d11b43730fd5a22a2b9c9d2bb19dda9933507972071d5cf68fe19f09d60f ./scripts/generate-app-icon.swift
ff66487399a93eb08890b8b85027df2db6572c85a183baec823b1f697014a7a7 ./scripts/make-dmg.sh
85eef8a97a24d834b7119788f11559c3fc5ab40be87ca2a244abae85801d8cac ./scripts/manifest.sh
d8f5a7fd6907772e961e129920af66290257b3299beae867639abcf956d71fb8 ./scripts/opencode-check.sh
50d0a6b4f78eca45363a7dded4efd1e6332628127e5f634b0bbba1215a499830 ./scripts/privacy-check.sh
480dee8c4969ed231f5d58e8c66999940aae2fa707ac964fd19b4671ce1ad83a ./scripts/privacy-check.sh
eba6aa14e31e41da73792503e946251691d635a45124d7150433227a218dc330 ./scripts/privacy-self-test.sh
52a752481678227da453b0487043f2d0950862791ef75dab71f695f78950a514 ./scripts/release.sh
0cf1aee371a3a98429906be86de2832c5649e8212f2eb35a5433990a0b15ad5d ./scripts/smoke-ollama.sh
dca61cd7f7833ecb5c72347c526a69bafab7499fe05c21c67f0b8dee71d50245 ./scripts/verify.sh
1a17309daafb04fc4880d74df39ab711c33694b6405cc375681d4fdfd9af9f9c ./scripts/verify.sh
+25 -5
View File
@@ -4,9 +4,11 @@ PROJECT := Sprachmittler.xcodeproj
SCHEME := Sprachmittler
DERIVED := .build/xcode
APP_PATH := $(DERIVED)/Build/Products/Debug/Sprachmittler.app
RELEASE_APP := .build/xcode-release/Build/Products/Release/Sprachmittler.app
INSTALL_DIR ?= /Applications
DMG_DIR ?= dist
.PHONY: bootstrap doctor generate build build-pkg build-app test live-test verify app install fixtures smoke privacy-check format manifest clean
.PHONY: bootstrap doctor generate build build-pkg build-app test live-test verify app install release-build dmg release icon fixtures smoke privacy-check format manifest clean
bootstrap:
@scripts/bootstrap.sh
@@ -17,6 +19,9 @@ doctor:
generate:
xcodegen generate --spec project.yml
icon:
swift scripts/generate-app-icon.swift
build: build-pkg build-app
build-pkg:
@@ -39,14 +44,29 @@ app: build-app
@pkill -x Sprachmittler 2>/dev/null || true
open "$(APP_PATH)"
install: build-app
release:
@scripts/release.sh --dry-run
release-build: generate
xcodebuild -project $(PROJECT) -scheme $(SCHEME) -configuration Release \
-derivedDataPath .build/xcode-release -destination 'platform=macOS,arch=arm64' -quiet build
# Build Release, replace $(INSTALL_DIR)/Sprachmittler.app and start it. Not `cp -r`: ditto keeps
# symlinks and attributes. Remove the old copy first, because ditto merges.
install: release-build
@test -d "$(RELEASE_APP)" || { echo "error: $(RELEASE_APP) not found"; exit 1; }
@test -d "$(INSTALL_DIR)" || { echo "error: $(INSTALL_DIR) does not exist"; exit 1; }
scripts/check-signature.sh "$(RELEASE_APP)" install
@pkill -x Sprachmittler 2>/dev/null || true
ditto "$(APP_PATH)" "$(INSTALL_DIR)/Sprachmittler.app"
codesign --force --sign - --options runtime \
--entitlements App/Sprachmittler.entitlements "$(INSTALL_DIR)/Sprachmittler.app"
rm -rf "$(INSTALL_DIR)/Sprachmittler.app"
ditto "$(RELEASE_APP)" "$(INSTALL_DIR)/Sprachmittler.app"
scripts/check-signature.sh "$(INSTALL_DIR)/Sprachmittler.app" install
open "$(INSTALL_DIR)/Sprachmittler.app"
# Local, unnotarised DMG from the same Release build. Use scripts/release.sh for distribution.
dmg: release-build
@DMG_DIR="$(DMG_DIR)" scripts/make-dmg.sh
fixtures:
@scripts/capture-fixtures.sh
+11 -2
View File
@@ -14,6 +14,7 @@ let package = Package(
products: [
.library(name: "SprachmittlerCore", targets: ["SprachmittlerCore"]),
.library(name: "SprachmittlerCapture", targets: ["SprachmittlerCapture"]),
.library(name: "SprachmittlerText", targets: ["SprachmittlerText"]),
.executable(name: "sprachmittler-cli", targets: ["sprachmittler-cli"]),
],
dependencies: [
@@ -45,7 +46,11 @@ let package = Package(
.target(name: "SprachmittlerCapture", dependencies: ["SprachmittlerCore"], swiftSettings: strictSettings),
// Evaluation harness — linked into the CLI only, never into the app.
.target(name: "SprachmittlerEval", dependencies: ["SprachmittlerCore"], swiftSettings: strictSettings),
.target(
name: "SprachmittlerEval",
dependencies: ["SprachmittlerCore", "SprachmittlerEngines", "SprachmittlerText", "SprachmittlerOllama"],
swiftSettings: strictSettings
),
// Fakes shared by tests (FakePasteboard, FakeClock, FakeOllamaTransport, FakeTextInserter, …).
.target(
@@ -61,6 +66,7 @@ let package = Package(
"SprachmittlerEngines",
"SprachmittlerEval",
"SprachmittlerOllama",
"SprachmittlerText",
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
swiftSettings: strictSettings
@@ -94,7 +100,10 @@ let package = Package(
),
.testTarget(
name: "SprachmittlerEvalTests",
dependencies: ["SprachmittlerEval", "SprachmittlerTestSupport"]
dependencies: [
"SprachmittlerEval", "SprachmittlerCore", "SprachmittlerEngines", "SprachmittlerText",
"SprachmittlerOllama", "SprachmittlerTestSupport",
]
),
.testTarget(
name: "SprachmittlerCLITests",
@@ -0,0 +1,99 @@
import ApplicationServices
import CoreGraphics
import Foundation
/// The Accessibility operations Replace needs, behind a seam for tests.
public protocol AccessibilityTextEditing: Sendable {
/// Whether the app is trusted for Accessibility.
func isTrusted() async -> Bool
/// The focused element's selected text, or nil when unsupported.
func selectedText(pid: pid_t) async -> String?
/// True for a secure/password field.
func isSecureField(pid: pid_t) async -> Bool
/// Sets the focused selection. Returns false when the app does not accept it.
func setSelectedText(pid: pid_t, to text: String) async -> Bool
}
/// Posts the synthetic paste. Tests replace it with a fake.
public protocol EventPosting: Sendable {
/// Posts ⌘V to a PID. Returns false when events cannot be created.
func postPaste(to pid: pid_t) -> Bool
}
/// The production Accessibility editor. AX calls run on this actor, never on the main actor.
public actor AXTextEditor: AccessibilityTextEditing {
/// Creates the editor.
public init() {}
public func isTrusted() -> Bool {
AXIsProcessTrusted()
}
public func selectedText(pid: pid_t) -> String? {
guard let focused = focusedElement(pid: pid) else { return nil }
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(
focused,
kAXSelectedTextAttribute as CFString,
&value
) == .success else {
return nil
}
return value as? String
}
public func isSecureField(pid: pid_t) -> Bool {
guard let focused = focusedElement(pid: pid) else { return false }
if attribute(focused, kAXSubroleAttribute) == "AXSecureTextField" {
return true
}
return attribute(focused, kAXRoleAttribute) == "AXSecureTextField"
}
private func attribute(_ element: AXUIElement, _ name: String) -> String? {
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success else {
return nil
}
return value as? String
}
public func setSelectedText(pid: pid_t, to text: String) async -> Bool {
guard let focused = focusedElement(pid: pid) else { return false }
return AXUIElementSetAttributeValue(
focused,
kAXSelectedTextAttribute as CFString,
text as CFTypeRef
) == .success
}
private func focusedElement(pid: pid_t) -> AXUIElement? {
let application = AXUIElementCreateApplication(pid)
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(
application,
kAXFocusedUIElementAttribute as CFString,
&value
) == .success, let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil }
return unsafeDowncast(value, to: AXUIElement.self)
}
}
/// The production ⌘V poster.
public struct CGEventPoster: EventPosting {
/// Creates a poster.
public init() {}
public func postPaste(to pid: pid_t) -> Bool {
guard let keyDown = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: true),
let keyUp = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: false)
else {
return false
}
keyDown.flags = .maskCommand
keyUp.flags = .maskCommand
keyDown.postToPid(pid)
keyUp.postToPid(pid)
return true
}
}
@@ -0,0 +1,27 @@
import AppKit
import ApplicationServices
import SprachmittlerCore
/// The production Accessibility permission gate. It is never called on the capture path.
@MainActor
public final class AccessibilityPermission: AccessibilityPermissionChecking {
/// Creates the gate.
public init() {}
public var isTrusted: Bool {
AXIsProcessTrusted()
}
public func requestTrust() {
// Use the public option key literal: the ApplicationServices global is not
// concurrency-safe under Swift 6, and this is the same documented key.
let options = ["AXTrustedCheckOptionPrompt": true] as CFDictionary
_ = AXIsProcessTrustedWithOptions(options)
}
public func openSettings() {
let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
?? URL(fileURLWithPath: "/System/Applications/System Settings.app")
NSWorkspace.shared.open(url)
}
}
@@ -0,0 +1,20 @@
import AppKit
import Foundation
import SprachmittlerCore
/// Captures the frontmost app at trigger time. It never reads a full document value.
@MainActor
public final class FrontmostTargetProvider: InsertionTargetProviding {
/// Creates a provider.
public init() {}
public func captureTarget() -> InsertionTarget? {
guard let application = NSWorkspace.shared.frontmostApplication else { return nil }
return InsertionTarget(
pid: application.processIdentifier,
bundleID: application.bundleIdentifier,
selectedText: nil,
capturedAt: Date()
)
}
}
@@ -0,0 +1,110 @@
import Darwin
import Foundation
import SprachmittlerCore
/// Replaces the selection with Accessibility first and a clipboard paste as fallback.
public actor InsertionCoordinator: TextInserting {
private let pasteboard: any PasteboardAccessing
private let accessibility: any AccessibilityTextEditing
private let poster: any EventPosting
private let delay: @Sendable (Duration) async throws -> Void
private let ownWrite: @MainActor @Sendable () -> Void
private let frontmostPID: @MainActor @Sendable () -> pid_t
/// Creates the coordinator.
public init(
pasteboard: any PasteboardAccessing,
accessibility: any AccessibilityTextEditing,
poster: any EventPosting = CGEventPoster(),
delay: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) },
ownWrite: @escaping @MainActor @Sendable () -> Void,
frontmostPID: @escaping @MainActor @Sendable () -> pid_t
) {
self.pasteboard = pasteboard
self.accessibility = accessibility
self.poster = poster
self.delay = delay
self.ownWrite = ownWrite
self.frontmostPID = frontmostPID
}
public func replace(
selection: CapturedText,
with translation: String,
target: InsertionTarget
) async throws -> InsertionOutcome {
guard target.pid != getpid() else {
throw SprachmittlerError.insertionTargetChanged
}
let pid = await frontmostPID()
try InsertionPolicy.verify(
frontmostPID: pid,
target: target,
selectedText: nil,
source: selection.text
)
guard await accessibility.isTrusted() else {
throw SprachmittlerError.accessibilityNotTrusted
}
if await accessibility.isSecureField(pid: target.pid) {
throw SprachmittlerError.accessibilityUnsupported(app: target.bundleID)
}
if let selected = await accessibility.selectedText(pid: target.pid) {
try InsertionPolicy.verify(
frontmostPID: pid,
target: target,
selectedText: selected,
source: selection.text
)
if await accessibility.setSelectedText(pid: target.pid, to: translation) {
return .replaced(using: .accessibility)
}
}
return try await pasteFallback(selection: selection, translation: translation, target: target, pid: pid)
}
private func pasteFallback(
selection: CapturedText,
translation: String,
target: InsertionTarget,
pid: pid_t
) async throws -> InsertionOutcome {
// Re-check the selection after a failed AX set before mutating the clipboard.
if let selected = await accessibility.selectedText(pid: target.pid) {
try InsertionPolicy.verify(
frontmostPID: pid,
target: target,
selectedText: selected,
source: selection.text
)
}
guard let snapshot = await pasteboard.snapshot() else {
throw SprachmittlerError.pasteboardUnavailable
}
let written = await pasteboard.write(translation)
await ownWrite()
do {
guard poster.postPaste(to: target.pid) else {
throw SprachmittlerError.accessibilityUnsupported(app: target.bundleID)
}
try await delay(.milliseconds(300))
guard await pasteboard.restore(snapshot, onlyIfChangeCountMatches: written) else {
throw SprachmittlerError.pasteboardRestoreFailed
}
} catch {
// SP-9: restore even when the paste or the settle delay is cancelled/fails.
_ = await pasteboard.restore(snapshot, onlyIfChangeCountMatches: written)
throw error
}
return .replaced(using: .paste)
}
/// Whether Accessibility is currently available; the panel uses this for hints.
public func isAccessibilityTrusted() async -> Bool {
await accessibility.isTrusted()
}
}
@@ -3,7 +3,7 @@ import Foundation
/// The pasteboard operations `SprachmittlerCapture` needs. Tests use a fake; the app uses
/// `SystemPasteboard`. Every member is main-actor isolated because `NSPasteboard` is.
@MainActor
public protocol PasteboardAccessing: AnyObject {
public protocol PasteboardAccessing: AnyObject, Sendable {
/// The current pasteboard change count.
var changeCount: Int { get }
@@ -30,6 +30,9 @@ public final class PasteboardWatcher {
private var suppressUntil = Date.distantPast
private var task: Task<Void, Never>?
/// The capture limits used by the next poll.
public var limits: CaptureLimits
/// True while the poll task is running.
public private(set) var isRunning = false
@@ -38,11 +41,13 @@ public final class PasteboardWatcher {
pasteboard: any PasteboardAccessing,
configuration: DoubleCopyDetector.Configuration = DoubleCopyDetector.Configuration(),
ticker: any PasteboardTicking = TimerPasteboardTicker(),
limits: CaptureLimits = CaptureLimits(),
now: @escaping @MainActor () -> Date = { Date() }
) {
self.pasteboard = pasteboard
detector = DoubleCopyDetector(configuration: configuration)
self.ticker = ticker
self.limits = limits
self.now = now
lastChangeCount = pasteboard.changeCount
}
@@ -102,7 +107,7 @@ public final class PasteboardWatcher {
case .empty:
return .noText
case let .captured(text):
let limit = CaptureLimits.characters(for: text)
let limit = limits.captureLimit(for: text)
guard text.count <= limit else {
detector.reset()
return .textTooLong(characters: text.count, limit: limit)
@@ -0,0 +1,44 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
/// Builds the Ollama clients and pipeline from a settings snapshot. This keeps every concrete
/// client in one composition helper and away from the app target.
public typealias OllamaCatalog = SprachmittlerOllama.OllamaCatalog
public enum AppOllama {
/// A catalog for the configured endpoint.
public static func makeCatalog(settings: AppSettings) throws -> any OllamaCatalog {
let http = try OllamaHTTPClient(
baseURL: settings.endpoint,
allowRemote: settings.allowRemoteEndpoint
)
return OllamaCatalogClient(http: http)
}
/// A translation pipeline for the configured endpoint and chunk limits.
public static func makePipeline(settings: AppSettings) throws -> TranslationPipeline {
let http = try OllamaHTTPClient(
baseURL: settings.endpoint,
allowRemote: settings.allowRemoteEndpoint
)
let chat = OllamaChatClient(http: http)
let registry = AdapterRegistry(adapters: [HyMT3Adapter()])
return TranslationPipeline(chat: chat, registry: registry, chunker: settings.chunker)
}
/// Warms the selected model with fixed synthetic text. Only for a loopback endpoint.
public static func warmUp(settings: AppSettings) async throws {
guard settings.warmUpOnLaunch, EndpointPolicy.isLoopback(settings.endpoint) else { return }
let http = try OllamaHTTPClient(
baseURL: settings.endpoint,
allowRemote: settings.allowRemoteEndpoint
)
let chat = OllamaChatClient(http: http)
let request = HyMT3Adapter().warmUpRequest(
model: settings.model,
keepAlive: settings.keepModelLoaded
)
try await OllamaWarmUpRunner(chat: chat).run(request)
}
}
@@ -0,0 +1,102 @@
import Foundation
import SprachmittlerEngines
public extension AppSettings {
init(from decoder: any Decoder) throws {
let defaults = AppSettings()
let container = try decoder.container(keyedBy: CodingKeys.self)
endpoint = try container.decodeIfPresent(URL.self, forKey: .endpoint) ?? defaults.endpoint
allowRemoteEndpoint = try container.decodeIfPresent(Bool.self, forKey: .allowRemoteEndpoint)
?? defaults.allowRemoteEndpoint
model = try container.decodeIfPresent(String.self, forKey: .model) ?? defaults.model
fastModel = container.contains(.fastModel)
? try container.decodeIfPresent(String.self, forKey: .fastModel)
: defaults.fastModel
let decodedTarget = try container.decodeIfPresent(String.self, forKey: .targetLanguage)
?? defaults.targetLanguage
targetLanguage = HyMT3Languages.resolve(decodedTarget)?.code ?? defaults.targetLanguage
languageRoutes = try AppSettings.normalizedRoutes(
container.decodeIfPresent([LanguageRoute].self, forKey: .languageRoutes) ?? []
)
recentTargetLanguages = try Self.decodeRecentTargets(from: container)
let limits = try Self.decodeLimits(from: container, defaults: defaults)
doubleCopyWindowMs = limits.window
maxCharactersLatin = limits.latin
maxCharactersCJK = limits.cjk
maximumPartsPerSelection = limits.parts
numCtx = limits.numCtx
numPredict = limits.numPredict
translationFontSize = limits.fontSize
let sampling = try Self.decodeSampling(from: container, defaults: defaults)
temperature = sampling.temperature
topP = sampling.topP
topK = sampling.topK
repeatPenalty = sampling.repeatPenalty
let keep = try container.decodeIfPresent(String.self, forKey: .keepModelLoaded)
?? defaults.keepModelLoaded
keepModelLoaded = ["5m", "30m", "1h", "0"].contains(keep) ? keep : defaults.keepModelLoaded
warmUpOnLaunch = try container.decodeIfPresent(Bool.self, forKey: .warmUpOnLaunch) ?? defaults.warmUpOnLaunch
let policy = try container.decodeIfPresent(PromptVariantPolicy.self, forKey: .promptVariantPolicy)
?? defaults.promptVariantPolicy
promptVariantPolicy = policy
// Auto-copy is a hard invariant: decoding cannot turn it on.
autoCopy = false
showSourcePreview = try container.decodeIfPresent(Bool.self, forKey: .showSourcePreview)
?? defaults.showSourcePreview
renderMarkdown = try container.decodeIfPresent(Bool.self, forKey: .renderMarkdown) ?? defaults.renderMarkdown
closeWithEscape = try container.decodeIfPresent(Bool.self, forKey: .closeWithEscape) ?? defaults.closeWithEscape
launchAtLogin = try container.decodeIfPresent(Bool.self, forKey: .launchAtLogin) ?? defaults.launchAtLogin
keepRecentTranslationInMemory = try container.decodeIfPresent(
Bool.self,
forKey: .keepRecentTranslationInMemory
) ?? defaults.keepRecentTranslationInMemory
hasCompletedOnboarding = try container.decodeIfPresent(Bool.self, forKey: .hasCompletedOnboarding)
?? defaults.hasCompletedOnboarding
settingsVersion = Self.currentVersion
}
func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(endpoint, forKey: .endpoint)
try container.encode(allowRemoteEndpoint, forKey: .allowRemoteEndpoint)
try container.encode(model, forKey: .model)
try container.encode(fastModel, forKey: .fastModel)
try container.encode(targetLanguage, forKey: .targetLanguage)
try container.encode(languageRoutes, forKey: .languageRoutes)
try container.encode(recentTargetLanguages, forKey: .recentTargetLanguages)
try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs)
try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin)
try container.encode(maxCharactersCJK, forKey: .maxCharactersCJK)
try container.encode(maximumPartsPerSelection, forKey: .maximumPartsPerSelection)
try container.encode(numCtx, forKey: .numCtx)
try container.encode(numPredict, forKey: .numPredict)
try container.encode(temperature, forKey: .temperature)
try container.encode(topP, forKey: .topP)
try container.encode(topK, forKey: .topK)
try container.encode(repeatPenalty, forKey: .repeatPenalty)
try container.encode(keepModelLoaded, forKey: .keepModelLoaded)
try container.encode(warmUpOnLaunch, forKey: .warmUpOnLaunch)
try container.encode(promptVariantPolicy, forKey: .promptVariantPolicy)
try container.encode(autoCopy, forKey: .autoCopy)
try container.encode(showSourcePreview, forKey: .showSourcePreview)
try container.encode(translationFontSize, forKey: .translationFontSize)
try container.encode(renderMarkdown, forKey: .renderMarkdown)
try container.encode(closeWithEscape, forKey: .closeWithEscape)
try container.encode(launchAtLogin, forKey: .launchAtLogin)
try container.encode(keepRecentTranslationInMemory, forKey: .keepRecentTranslationInMemory)
try container.encode(hasCompletedOnboarding, forKey: .hasCompletedOnboarding)
try container.encode(settingsVersion, forKey: .settingsVersion)
}
private static func decodeRecentTargets(
from container: KeyedDecodingContainer<CodingKeys>
) throws -> [String] {
let recents = try container.decodeIfPresent([String].self, forKey: .recentTargetLanguages) ?? []
var seen = Set<String>()
return recents.compactMap { HyMT3Languages.resolve($0)?.code }
.filter { seen.insert($0).inserted }
.prefix(3)
.map(\.self)
}
}
@@ -0,0 +1,287 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
import SprachmittlerText
/// The documented prompt policy. `contentAware` is reserved for M7.
public enum PromptVariantPolicy: String, Codable, Sendable, Equatable {
/// Default Translation only (v1).
case defaultOnly
/// Content-aware prompt selection (reserved for M7).
case contentAware
}
/// The versioned, text-free application settings from `docs/ARCHITECTURE.md` §12.
public struct AppSettings: Codable, Sendable, Equatable {
/// The loopback default endpoint; a compile-time constant.
public static let defaultEndpoint = URL(string: "http://127.0.0.1:11434")!
/// The current settings schema version.
public static let currentVersion = 1
/// Ollama base URL.
public var endpoint: URL
/// Whether a non-loopback endpoint is allowed (HTTPS only).
public var allowRemoteEndpoint: Bool
/// The selected Hy-MT3 model tag.
public var model: String
/// The optional Fast model tag.
public var fastModel: String?
/// The mother tongue BCP-47 code; the default target when no rule matches.
public var targetLanguage: String
/// Source-language to target-language rules. Empty means everything goes to the mother tongue.
public var languageRoutes: [LanguageRoute]
/// Up to three recent target codes, most recent first.
public var recentTargetLanguages: [String]
/// The double-copy window in milliseconds (300–1000).
public var doubleCopyWindowMs: Int
/// The Latin/Cyrillic/Greek chunk limit.
public var maxCharactersLatin: Int
/// The dense-script chunk limit.
public var maxCharactersCJK: Int
/// How many chunks one capture may contain (1–8). `1` rejects text longer than one chunk.
public var maximumPartsPerSelection: Int
/// `num_ctx`.
public var numCtx: Int
/// `num_predict`.
public var numPredict: Int
/// `temperature`.
public var temperature: Double
/// `top_p`.
public var topP: Double
/// `top_k`.
public var topK: Int
/// `repeat_penalty`.
public var repeatPenalty: Double
/// `keep_alive` value: `5m`, `30m`, `1h` or `0`.
public var keepModelLoaded: String
/// Warm the model after launch (loopback only).
public var warmUpOnLaunch: Bool
/// Prompt policy; `defaultOnly` in v1.
public var promptVariantPolicy: PromptVariantPolicy
/// Always false; never copy automatically.
public var autoCopy: Bool
/// Show the source preview in the panel.
public var showSourcePreview: Bool
/// Translation text size in points (12–28).
public var translationFontSize: Int
/// Render Markdown formatting in the translation panel.
public var renderMarkdown: Bool
/// Make the panel key when shown so Esc and the shortcuts work without a click.
public var closeWithEscape: Bool
/// Reflect the login-item setting.
public var launchAtLogin: Bool
/// Keep the last translation in memory for the panel.
public var keepRecentTranslationInMemory: Bool
/// Whether first-run onboarding has been completed.
public var hasCompletedOnboarding: Bool
/// The settings schema version.
public var settingsVersion: Int
/// Creates the defaults. The system language becomes the target when supported.
public init() {
let systemCode = Locale.preferredLanguages.first.flatMap { HyMT3Languages.resolve($0)?.code }
endpoint = Self.defaultEndpoint
allowRemoteEndpoint = false
model = HyMT3ModelPreset.defaultModel
fastModel = HyMT3ModelPreset.fastModel
targetLanguage = systemCode ?? HyMT3Languages.english.code
languageRoutes = []
recentTargetLanguages = []
doubleCopyWindowMs = 500
maxCharactersLatin = 4000
maxCharactersCJK = 2000
maximumPartsPerSelection = 1
numCtx = 8192
numPredict = 4096
temperature = 0.7
topP = 0.6
topK = 20
repeatPenalty = 1.05
keepModelLoaded = HyMT3ModelPreset.defaultKeepAlive
warmUpOnLaunch = true
promptVariantPolicy = .defaultOnly
autoCopy = false
showSourcePreview = true
translationFontSize = 17
renderMarkdown = true
closeWithEscape = true
launchAtLogin = false
keepRecentTranslationInMemory = true
hasCompletedOnboarding = false
settingsVersion = Self.currentVersion
}
/// The target language value, always a catalogue entry.
public var targetLanguageModel: ModelLanguage {
HyMT3Languages.resolve(targetLanguage) ?? HyMT3Languages.english
}
/// The recent targets that still exist in the catalogue.
public var recentTargets: [ModelLanguage] {
recentTargetLanguages.compactMap(HyMT3Languages.resolve)
}
/// Validates the configured endpoint against the remote policy.
public func validatedEndpoint() throws -> URL {
try EndpointPolicy.validate(endpoint, allowRemote: allowRemoteEndpoint)
}
/// Records a target as recent, keeping at most three unique codes.
public mutating func noteTarget(_ language: ModelLanguage) {
targetLanguage = language.code
recentTargetLanguages.removeAll { $0 == language.code }
recentTargetLanguages.insert(language.code, at: 0)
recentTargetLanguages = Array(recentTargetLanguages.prefix(3))
}
/// Clamps values edited outside the decoder (Settings UI) to the safe ranges.
public mutating func sanitize() {
targetLanguage = HyMT3Languages.resolve(targetLanguage)?.code ?? HyMT3Languages.english.code
languageRoutes = Self.normalizedRoutes(languageRoutes)
doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000)
maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000)
maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 4000)
maximumPartsPerSelection = Self.clamp(maximumPartsPerSelection, to: 1 ... 8)
numCtx = Self.clamp(numCtx, to: 1024 ... 32768)
numPredict = Self.clamp(numPredict, to: 1 ... 8192)
temperature = min(max(temperature, 0), 2)
topP = min(max(topP, 0), 1)
topK = Self.clamp(topK, to: 1 ... 100)
repeatPenalty = min(max(repeatPenalty, 0.5), 2)
translationFontSize = Self.clamp(translationFontSize, to: 12 ... 28)
if !["5m", "30m", "1h", "0"].contains(keepModelLoaded) {
keepModelLoaded = HyMT3ModelPreset.defaultKeepAlive
}
autoCopy = false
}
/// The documented sampling values as an options value.
public var samplingOptions: SamplingOptions {
SamplingOptions(
temperature: temperature,
topP: topP,
topK: topK,
repeatPenalty: repeatPenalty,
numPredict: numPredict,
numCtx: numCtx
)
}
/// The chunker limits.
public var chunker: Chunker {
Chunker(latinLimit: maxCharactersLatin, denseLimit: maxCharactersCJK)
}
/// The chunk and capture limits derived from the settings.
public var captureLimits: CaptureLimits {
CaptureLimits(chunker: chunker, maximumParts: maximumPartsPerSelection)
}
struct DecodedLimits {
let window: Int
let latin: Int
let cjk: Int
let parts: Int
let numCtx: Int
let numPredict: Int
let fontSize: Int
}
struct DecodedSampling {
let temperature: Double
let topP: Double
let topK: Int
let repeatPenalty: Double
}
static func decodeLimits(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings
) throws -> DecodedLimits {
try DecodedLimits(
window: clamp(
container.decodeIfPresent(Int.self, forKey: .doubleCopyWindowMs)
?? defaults.doubleCopyWindowMs,
to: 300 ... 1000
),
latin: clamp(
container.decodeIfPresent(Int.self, forKey: .maxCharactersLatin)
?? defaults.maxCharactersLatin,
to: 500 ... 10000
),
cjk: clamp(
container.decodeIfPresent(Int.self, forKey: .maxCharactersCJK)
?? defaults.maxCharactersCJK,
to: 500 ... 4000
),
parts: clamp(
container.decodeIfPresent(Int.self, forKey: .maximumPartsPerSelection)
?? defaults.maximumPartsPerSelection,
to: 1 ... 8
),
numCtx: clamp(
container.decodeIfPresent(Int.self, forKey: .numCtx) ?? defaults.numCtx,
to: 1024 ... 32768
),
numPredict: clamp(
container.decodeIfPresent(Int.self, forKey: .numPredict) ?? defaults.numPredict,
to: 1 ... 8192
),
fontSize: clamp(
container.decodeIfPresent(Int.self, forKey: .translationFontSize)
?? defaults.translationFontSize,
to: 12 ... 28
)
)
}
static func decodeSampling(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings
) throws -> DecodedSampling {
let temperature = try container.decodeIfPresent(Double.self, forKey: .temperature)
?? defaults.temperature
let topP = try container.decodeIfPresent(Double.self, forKey: .topP) ?? defaults.topP
let repeatPenalty = try container.decodeIfPresent(Double.self, forKey: .repeatPenalty)
?? defaults.repeatPenalty
return try DecodedSampling(
temperature: min(max(temperature, 0), 2),
topP: min(max(topP, 0), 1),
topK: clamp(
container.decodeIfPresent(Int.self, forKey: .topK) ?? defaults.topK,
to: 1 ... 100
),
repeatPenalty: min(max(repeatPenalty, 0.5), 2)
)
}
enum CodingKeys: String, CodingKey {
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, languageRoutes
case recentTargetLanguages
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, maximumPartsPerSelection
case numCtx, numPredict
case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown
case closeWithEscape, launchAtLogin, keepRecentTranslationInMemory, hasCompletedOnboarding
case settingsVersion
}
static func normalizedRoutes(_ routes: [LanguageRoute]) -> [LanguageRoute] {
var seen = Set<String>()
return routes.compactMap { route in
guard let source = HyMT3Languages.resolve(route.source)?.code,
let target = HyMT3Languages.resolve(route.target)?.code,
source.caseInsensitiveCompare(target) != .orderedSame,
seen.insert(source.lowercased()).inserted
else {
return nil
}
return LanguageRoute(source: source, target: target)
}
}
static func clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
min(max(value, range.lowerBound), range.upperBound)
}
}
@@ -1,9 +1,28 @@
import SprachmittlerText
/// The capture character limit for a text, based on its script (`docs/TRANSLATION_OUTPUT.md` §3).
public enum CaptureLimits {
/// 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts.
public static func characters(for text: String) -> Int {
Chunker().limit(for: text)
/// The per-request chunk size and the total size one capture may have.
///
/// `maximumParts == 1` rejects anything longer than one chunk. Higher values accept up to
/// `maximumParts` chunks and translate them sequentially (`docs/TRANSLATION_OUTPUT.md` §3).
public struct CaptureLimits: Sendable, Equatable {
/// The per-request chunk size.
public let chunker: Chunker
/// How many chunks one capture may contain (at least 1).
public let maximumParts: Int
/// Creates limits.
public init(chunker: Chunker = Chunker(), maximumParts: Int = 1) {
self.chunker = chunker
self.maximumParts = max(1, maximumParts)
}
/// The per-chunk character limit for `text`.
public func chunkLimit(for text: String) -> Int {
chunker.limit(for: text)
}
/// The total character limit for one capture.
public func captureLimit(for text: String) -> Int {
chunkLimit(for: text) * maximumParts
}
}
@@ -12,10 +12,10 @@ public enum CaptureValidation: Sendable, Equatable {
/// Applies the capture rules shared by double copy, the menu and Services.
public enum CapturePolicy {
/// Validates non-emptiness and the 4000/2000 script-aware limit.
public static func validate(_ text: String) -> CaptureValidation {
/// Validates non-emptiness and the capture limit (`chunk size × maximum parts`).
public static func validate(_ text: String, limits: CaptureLimits = CaptureLimits()) -> CaptureValidation {
guard text.contains(where: { !$0.isWhitespace }) else { return .empty }
let limit = CaptureLimits.characters(for: text)
let limit = limits.captureLimit(for: text)
let characters = text.count
guard characters <= limit else {
return .textTooLong(characters: characters, limit: limit)
@@ -0,0 +1,55 @@
import Foundation
/// One in-memory diagnostic entry. It never contains selected text or a translation.
public struct DiagnosticEvent: Sendable, Equatable, Codable {
/// When the event happened.
public let timestamp: Date
/// A short kind such as `translation`, `error` or `capture`.
public let kind: String
/// A duration in milliseconds, when relevant.
public let durationMs: Int?
/// A non-text detail such as a warning code or error kind.
public let detail: String?
/// Creates an event.
public init(timestamp: Date, kind: String, durationMs: Int? = nil, detail: String? = nil) {
self.timestamp = timestamp
self.kind = kind
self.durationMs = durationMs
self.detail = detail
}
}
/// A bounded in-memory diagnostics log (`docs/ARCHITECTURE.md` §15).
public actor DiagnosticsStore {
/// The maximum number of retained events.
public static let capacity = 50
private var events: [DiagnosticEvent] = []
private let clock: @Sendable () -> Date
/// Creates a store.
public init(clock: @escaping @Sendable () -> Date = { Date() }) {
self.clock = clock
}
/// Records one non-text event, dropping the oldest beyond the capacity.
public func record(kind: String, durationMs: Int? = nil, detail: String? = nil) {
events.append(
DiagnosticEvent(timestamp: clock(), kind: kind, durationMs: durationMs, detail: detail)
)
if events.count > Self.capacity {
events.removeFirst(events.count - Self.capacity)
}
}
/// The current events, oldest first.
public func snapshot() -> [DiagnosticEvent] {
events
}
/// Clears the in-memory list.
public func clear() {
events.removeAll()
}
}
@@ -0,0 +1,76 @@
import Foundation
import Observation
import SprachmittlerEngines
import SprachmittlerOllama
/// The diagnostics window model. It formats versions, digests, timings and error kinds only.
@MainActor
@Observable
public final class DiagnosticsViewModel {
/// The last events, oldest first.
public private(set) var events: [DiagnosticEvent] = []
/// The Ollama version.
public private(set) var serverVersion: String?
/// The installed Hy-MT3 models.
public private(set) var models: [InstalledModel] = []
/// A short error when the refresh failed.
public private(set) var error: String?
/// True while refreshing.
public private(set) var isRefreshing = false
private let store: DiagnosticsStore
private let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog
private let settingsProvider: @Sendable () -> AppSettings
/// Creates the diagnostics model.
public init(
store: DiagnosticsStore,
catalogProvider: @escaping @Sendable (AppSettings) throws -> any OllamaCatalog,
settingsProvider: @escaping @Sendable () -> AppSettings
) {
self.store = store
self.catalogProvider = catalogProvider
self.settingsProvider = settingsProvider
}
/// Reloads events and, when possible, server/model details.
public func refresh() async {
isRefreshing = true
defer { isRefreshing = false }
events = await store.snapshot()
do {
let catalog = try catalogProvider(settingsProvider())
serverVersion = try await catalog.serverVersion()
models = try await catalog.installedModels()
.filter { HyMT3ModelPreset.isHyMT3($0.name) }
error = nil
} catch let rejection as EndpointRejection {
self.error = SprachmittlerError.endpointRejected(reason: rejection).userMessage
} catch {
self.error = "Ollama details are unavailable."
}
}
/// Clears the in-memory event list.
public func clear() async {
await store.clear()
events = []
}
/// A text-only report for the clipboard; no source text or translation is included.
public func report() -> String {
var lines = [
"Sprachmittler diagnostics",
"Ollama: \(serverVersion ?? "unknown")",
"Endpoint: \(settingsProvider().endpoint.absoluteString)",
"Models: \(models.map { "\($0.name) [\($0.digest.prefix(12))]" }.joined(separator: ", "))",
]
for event in events {
let duration = event.durationMs.map { " \($0) ms" } ?? ""
let detail = event.detail.map { " [\($0)]" } ?? ""
lines.append("\(event.kind)\(duration)\(detail)")
}
return lines.joined(separator: "\n")
}
}
@@ -6,3 +6,6 @@ public typealias LanguageCode = String
/// The UI-facing name for a target language. The value type lives in `SprachmittlerEngines` because
/// it carries the exact model-card name used by prompts (ADR-014, ADR-017).
public typealias TargetLanguage = SprachmittlerEngines.ModelLanguage
/// The language value type, re-exported for app views.
public typealias ModelLanguage = SprachmittlerEngines.ModelLanguage
@@ -0,0 +1,19 @@
import SprachmittlerEngines
/// The app-facing language catalogue. It re-exports the model-name data owned by Engines.
public enum LanguageCatalogue {
/// All 102 supported languages.
public static var all: [ModelLanguage] {
HyMT3Languages.all
}
/// The common first-run list.
public static var common: [ModelLanguage] {
HyMT3Languages.common
}
/// Resolves a BCP-47 code.
public static func resolve(_ code: String) -> ModelLanguage? {
HyMT3Languages.resolve(code)
}
}
@@ -0,0 +1,135 @@
import Foundation
import Observation
import SprachmittlerEngines
import SprachmittlerOllama
/// One onboarding check.
public enum OnboardingCheck: Sendable, Equatable {
/// Not checked yet.
case idle
/// A check is running.
case checking
/// The check passed; the value is a short detail.
case ok(String)
/// The check failed; the value is a user-facing message.
case failed(String)
}
/// First-run onboarding state and actions (`docs/IMPLEMENTATION_PLAN.md` T6.2).
@MainActor
@Observable
public final class OnboardingViewModel {
/// Ollama reachability and version.
public private(set) var ollama: OnboardingCheck = .idle
/// Hy-MT3 installation.
public private(set) var model: OnboardingCheck = .idle
/// Accessibility trust (optional, for Replace).
public private(set) var accessibilityTrusted = false
/// The selected target.
public private(set) var target: ModelLanguage
/// The installed Hy-MT3 tags.
public private(set) var installedModels: [String] = []
/// True while any check is running.
public private(set) var isChecking = false
private let settingsStore: SettingsStore
private let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog
private let accessibility: any AccessibilityPermissionChecking
/// Creates the onboarding model.
public init(
settingsStore: SettingsStore,
catalogProvider: @escaping @Sendable (AppSettings) throws -> any OllamaCatalog,
accessibility: any AccessibilityPermissionChecking
) {
self.settingsStore = settingsStore
self.catalogProvider = catalogProvider
self.accessibility = accessibility
let settings = settingsStore.current()
target = settings.targetLanguageModel
accessibilityTrusted = accessibility.isTrusted
}
/// The command shown when the model is missing.
public var pullCommand: String {
"ollama pull \(settingsStore.current().model)"
}
/// True when the essential checks passed; the app can be used.
public var canFinish: Bool {
if case .ok = ollama, case .ok = model {
return true
}
return false
}
/// Runs all checks.
public func refresh() async {
isChecking = true
ollama = .checking
model = .checking
accessibilityTrusted = accessibility.isTrusted
do {
let settings = settingsStore.current()
let catalog = try catalogProvider(settings)
let version = try await catalog.serverVersion()
ollama = .ok(version)
let models = try await catalog.installedModels()
let tags = models.map(\.name).filter { HyMT3ModelPreset.isHyMT3($0) }
installedModels = tags
if tags.isEmpty {
model = .failed(SprachmittlerError.modelNotInstalled(model: settings.model).userMessage)
} else {
if !tags.contains(settings.model), let first = tags.first {
try? settingsStore.update { $0.model = first }
}
model = .ok(tags.joined(separator: ", "))
}
} catch let error as OllamaError {
let domain = SprachmittlerError(ollama: error)
ollama = .failed(domain.userMessage)
model = .failed(domain.userMessage)
} catch let error as SprachmittlerError {
ollama = .failed(error.userMessage)
model = .failed(error.userMessage)
} catch let rejection as EndpointRejection {
let message = SprachmittlerError.endpointRejected(reason: rejection).userMessage
ollama = .failed(message)
model = .failed(message)
} catch {
let message = "Ollama could not be reached."
ollama = .failed(message)
model = .failed(message)
}
isChecking = false
}
/// Saves the chosen target.
public func saveTarget() throws {
try settingsStore.update { $0.noteTarget(target) }
}
/// Sets the target; the caller saves.
public func setTarget(_ language: ModelLanguage) {
target = language
}
/// Requests Accessibility trust. Only call from onboarding.
public func requestAccessibility() {
accessibility.requestTrust()
accessibilityTrusted = accessibility.isTrusted
}
/// Opens the Accessibility settings page.
public func openAccessibilitySettings() {
accessibility.openSettings()
}
/// Marks onboarding complete after a successful setup.
public func complete() throws {
try saveTarget()
try settingsStore.update { $0.hasCompletedOnboarding = true }
}
}
@@ -0,0 +1,458 @@
import Foundation
import Observation
import SprachmittlerEngines
import SprachmittlerText
/// The panel phase from `docs/ARCHITECTURE.md` §10.
public enum PanelPhase: Sendable, Equatable {
/// Nothing captured.
case idle
/// A request is queued or running.
case translating
/// Deltas are arriving.
case streaming
/// A validated translation is ready.
case ready
/// The request failed.
case failed
}
/// The settings snapshot used by the panel for one translation.
public struct PanelConfiguration: Sendable, Equatable {
/// The selected target language.
public var target: ModelLanguage
/// Source-to-target rules. Empty means everything goes to `target` (the mother tongue).
public var languageRoutes: [LanguageRoute]
/// The selected model tag.
public var model: String
/// The Ollama keep-alive value.
public var keepAlive: String
/// The sampling values.
public var sampling: SamplingOptions
/// Whether to show the source preview.
public var showSourcePreview: Bool
/// Translation text size in points.
public var translationFontSize: Int
/// Render Markdown formatting for Markdown sources.
public var renderMarkdown: Bool
/// Make the panel key when shown so Esc works without a click.
public var closeWithEscape: Bool
/// Recent targets, most recent first.
public var recentTargets: [ModelLanguage]
/// The chunk and capture limits accepted for this capture.
public var captureLimits: CaptureLimits
/// Creates a configuration.
public init(
target: ModelLanguage,
model: String,
keepAlive: String,
sampling: SamplingOptions = .publisherDefault,
showSourcePreview: Bool = true,
translationFontSize: Int = 17,
renderMarkdown: Bool = true,
closeWithEscape: Bool = true,
languageRoutes: [LanguageRoute] = [],
recentTargets: [ModelLanguage] = [],
captureLimits: CaptureLimits = CaptureLimits()
) {
self.target = target
self.model = model
self.keepAlive = keepAlive
self.sampling = sampling
self.showSourcePreview = showSourcePreview
self.translationFontSize = translationFontSize
self.renderMarkdown = renderMarkdown
self.closeWithEscape = closeWithEscape
self.languageRoutes = languageRoutes
self.recentTargets = recentTargets
self.captureLimits = captureLimits
}
}
/// The panel presentation model. It mirrors `TranslationSession` and owns no disk state.
@MainActor
@Observable
public final class PanelViewModel {
/// The current phase.
public private(set) var phase: PanelPhase = .idle
/// The captured source.
public private(set) var source: CapturedText?
/// The streamed and final translation.
public private(set) var translation = ""
/// Validation warnings for the current result.
public private(set) var warnings: [TranslationWarning] = []
/// The current error, if any.
public private(set) var error: SprachmittlerError?
/// The last timing.
public private(set) var timing: TranslationTiming?
/// The advisory source language code.
public private(set) var sourceLanguage: String?
/// True after a successful Copy.
public private(set) var didCopy = false
/// True while a Replace action is running.
public private(set) var isReplacing = false
/// The current target, model and prompt settings. `target` is the user's saved preference.
public private(set) var configuration: PanelConfiguration
/// The target used by the current request, after a language rule or an explicit picker choice.
public private(set) var effectiveTarget: ModelLanguage
/// The matched rule source when `effectiveTarget` differs from the mother tongue, or nil.
public private(set) var routedSource: ModelLanguage?
/// True after the user dismisses the same-language advisory.
public private(set) var sameLanguageDismissed = false
/// The number of parts in the last finished translation.
public private(set) var chunkCount = 1
/// The current part while a multi-part request runs.
public private(set) var currentChunk: Int?
/// The total parts of the current multi-part request.
public private(set) var totalChunks: Int?
/// The copy action. The composition root writes with own-write markers.
public let copy: @MainActor (String) -> Void
/// The optional Replace action; nil until the insertion module is available.
public let replace: (@MainActor () async -> InsertionOutcome)?
/// Called when a successful Replace should close the panel.
public let onCloseRequest: @MainActor () -> Void
/// Called with every session event for diagnostics.
public let eventObserver: (@MainActor (TranslationSessionEvent) -> Void)?
/// Called when the user changes the target from the panel.
public let onTargetChanged: @MainActor (ModelLanguage) -> Void
private let session: TranslationSession
private let detector: any LanguageDetecting
private var eventTask: Task<Void, Never>?
private var currentEpoch: UInt64 = 0
private var lastCaptured: CapturedText?
private var targetOverride: ModelLanguage?
/// Creates a panel model.
public init(
session: TranslationSession,
configuration: PanelConfiguration,
copy: @escaping @MainActor (String) -> Void,
replace: (@MainActor () async -> InsertionOutcome)? = nil,
onCloseRequest: @escaping @MainActor () -> Void = {},
eventObserver: (@MainActor (TranslationSessionEvent) -> Void)? = nil,
onTargetChanged: @escaping @MainActor (ModelLanguage) -> Void = { _ in },
detector: any LanguageDetecting = NaturalLanguageDetector()
) {
self.session = session
self.configuration = configuration
effectiveTarget = configuration.target
self.detector = detector
self.copy = copy
self.replace = replace
self.onCloseRequest = onCloseRequest
self.eventObserver = eventObserver
self.onTargetChanged = onTargetChanged
}
/// Starts consuming session events. Call once after init.
public func startObserving() {
guard eventTask == nil else { return }
let session = session
eventTask = Task { [weak self] in
for await event in await session.events() {
guard let self else { return }
handle(event)
}
}
}
/// True when Copy can write the current translation.
public var canCopy: Bool {
!translation.isEmpty && (phase == .ready || phase == .failed)
}
/// True when Replace is safe and the insertion module is available.
public var canReplace: Bool {
phase == .ready
&& !isReplacing
&& !warnings.contains(where: \.blocksReplacement)
&& replace != nil
}
/// The replacement is unavailable until M5 in this build.
public var replaceUnavailableReason: String? {
replace == nil ? "Replace is not available." : nil
}
/// Warnings that disable Replace.
public var blockingWarnings: [TranslationWarning] {
warnings.filter(\.blocksReplacement)
}
/// The same-language advisory, if present and not dismissed.
public var sameLanguageWarning: TranslationWarning? {
guard !sameLanguageDismissed else { return nil }
return warnings.first { warning in
if case .sameLanguage = warning {
true
} else {
false
}
}
}
/// The user-facing error message.
public var errorMessage: String? {
error?.userMessage
}
/// The error's recovery action.
public var recoveryAction: RecoveryAction? {
error?.recoveryAction
}
/// Synchronously resets the visible state before the panel is shown and resolves the direction.
public func prepare(_ captured: CapturedText, resetDirectionOverride: Bool = true) {
currentEpoch = 0
lastCaptured = captured
source = captured
translation = ""
warnings = []
error = nil
timing = nil
didCopy = false
isReplacing = false
chunkCount = 1
currentChunk = nil
totalChunks = nil
if resetDirectionOverride {
targetOverride = nil
}
let normalized = TextNormalization.normalizeInput(captured.text)
let detection = detector.detect(normalized)
sourceLanguage = detection?.code
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: configuration.target,
routes: configuration.languageRoutes,
detection: detection,
override: targetOverride
)
effectiveTarget = direction.target
routedSource = direction.didRoute ? direction.source : nil
sameLanguageDismissed = targetOverride != nil
phase = .translating
}
/// Starts a translation for a captured text.
public func begin(_ captured: CapturedText) async {
await begin(captured, resetDirectionOverride: true)
}
private func begin(_ captured: CapturedText, resetDirectionOverride: Bool) async {
prepare(captured, resetDirectionOverride: resetDirectionOverride)
_ = await session.start(request(for: captured))
}
/// Retries the last captured text without discarding a manual direction choice.
public func retry() async {
guard let lastCaptured else { return }
await begin(lastCaptured, resetDirectionOverride: false)
}
/// Retranslates after an external target change and re-evaluates the direction.
public func retranslate() async {
guard let lastCaptured else { return }
await begin(lastCaptured, resetDirectionOverride: true)
}
/// Shows a capture-time error such as a too-long selection.
public func showError(_ error: SprachmittlerError, source: CapturedText? = nil) {
currentEpoch = 0
Task { await session.reset() }
phase = .failed
self.error = error
self.source = source
translation = ""
warnings = []
timing = nil
sourceLanguage = nil
chunkCount = 1
currentChunk = nil
totalChunks = nil
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
}
/// Changes the saved target from the panel and retranslates the current selection.
public func setTarget(_ language: ModelLanguage) async {
guard language.code != effectiveTarget.code else { return }
configuration.target = language
effectiveTarget = language
routedSource = nil
targetOverride = language
onTargetChanged(language)
if let lastCaptured {
await begin(lastCaptured, resetDirectionOverride: false)
}
}
/// Uses another language for this capture only. It does not change the saved target.
public func overrideTarget(_ language: ModelLanguage) async {
guard language.code != effectiveTarget.code else { return }
effectiveTarget = language
routedSource = nil
targetOverride = language
sameLanguageDismissed = true
if let lastCaptured {
await begin(lastCaptured, resetDirectionOverride: false)
}
}
/// Copies the translation and keeps the panel open (R023).
public func copyTranslation() {
guard canCopy else { return }
copy(translation)
didCopy = true
}
/// Runs the optional Replace action.
public func replaceSelection() async {
guard canReplace, let replace else { return }
isReplacing = true
let outcome = await replace()
isReplacing = false
switch outcome {
case .replaced:
onCloseRequest()
case .copiedOnly:
break
case let .failed(insertionError):
error = insertionError
phase = .failed
}
}
/// Dismisses the same-language advisory; translation stays available.
public func dismissSameLanguageWarning() {
sameLanguageDismissed = true
}
/// Updates the settings snapshot without restarting the current request.
public func updateConfiguration(_ configuration: PanelConfiguration) {
let targetChanged = configuration.target.code != self.configuration.target.code
self.configuration = configuration
if targetChanged || source == nil {
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
}
}
/// Resets the panel and cancels the active request. The event stream stays open.
public func close() async {
await session.reset()
phase = .idle
source = nil
translation = ""
warnings = []
error = nil
timing = nil
sourceLanguage = nil
didCopy = false
isReplacing = false
sameLanguageDismissed = false
chunkCount = 1
currentChunk = nil
totalChunks = nil
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
lastCaptured = nil
}
/// Stops the event consumer for app termination.
public func shutdown() {
eventTask?.cancel()
eventTask = nil
}
private func request(for captured: CapturedText) -> TranslationSessionRequest {
TranslationSessionRequest(
captured: captured,
target: effectiveTarget,
model: configuration.model,
keepAlive: configuration.keepAlive,
sampling: configuration.sampling,
captureLimits: configuration.captureLimits
)
}
}
private extension PanelViewModel {
private func handle(_ event: TranslationSessionEvent) {
switch event {
case let .started(epoch, request):
handleStarted(epoch: epoch, request: request)
case let .chunkStarted(epoch, index, total):
handleChunkStarted(epoch: epoch, index: index, total: total)
case let .delta(epoch, text):
handleDelta(epoch: epoch, text: text)
case let .finished(epoch, result):
handleFinished(epoch: epoch, result: result)
case let .failed(epoch, error):
handleFailed(epoch: epoch, error: error)
case let .cancelled(epoch):
handleCancelled(epoch: epoch)
}
eventObserver?(event)
}
private func handleStarted(epoch: UInt64, request: TranslationSessionRequest) {
currentEpoch = epoch
source = request.captured
effectiveTarget = request.target
translation = ""
warnings = []
error = nil
chunkCount = 1
currentChunk = nil
totalChunks = nil
phase = .translating
}
private func handleChunkStarted(epoch: UInt64, index: Int, total: Int) {
guard epoch == currentEpoch else { return }
currentChunk = index
totalChunks = total
}
private func handleDelta(epoch: UInt64, text: String) {
guard epoch == currentEpoch else { return }
translation += text
phase = .streaming
}
private func handleFinished(epoch: UInt64, result: PipelineResult) {
guard epoch == currentEpoch else { return }
translation = result.translation
warnings = result.warnings
timing = result.timing
sourceLanguage = result.sourceLanguage
chunkCount = result.chunkCount
currentChunk = nil
totalChunks = nil
if result.warnings.contains(.emptyOutput) {
error = .emptyOutput
phase = .failed
} else {
phase = .ready
}
}
private func handleFailed(epoch: UInt64, error: SprachmittlerError) {
guard epoch == currentEpoch else { return }
self.error = error
currentChunk = nil
phase = .failed
}
private func handleCancelled(epoch: UInt64) {
guard epoch == currentEpoch else { return }
phase = .idle
error = nil
}
}
@@ -0,0 +1,49 @@
import Foundation
/// UI-facing warning helpers re-exported by Core.
public extension TranslationWarning {
/// A short panel message. It never rewrites the translation.
var panelMessage: String {
switch self {
case let .preambleDetected(line):
String(localized: "The model added an explanation: “\(line)”")
case .truncated:
String(localized: "The translation was cut off.")
case .repetitionLoop:
String(localized: "The translation started repeating.")
case let .missingProtectedToken(token):
String(localized: "A protected token was lost: \(token)")
case .emptyOutput:
String(localized: "The model returned an empty translation.")
case let .sameLanguage(source, target):
String(localized: "This text already appears to be in \(target) (detected \(source)).")
case .numericMismatch:
String(localized: "A number may have changed.")
case let .chunkFailed(index):
String(localized: "Chunk \(index + 1) failed; the translation is incomplete.")
}
}
/// True when the warning should disable Replace by default.
/// The domain error that blocks Replace for this warning.
var insertionError: SprachmittlerError {
switch self {
case .truncated: .truncated
case .repetitionLoop: .repetitionLoop
case .preambleDetected: .preambleDetected
case let .missingProtectedToken(token): .protectedTokenLost(token: token)
case .emptyOutput: .emptyOutput
case .chunkFailed: .server(status: 0, message: "Chunk failed")
case .sameLanguage, .numericMismatch: .cancelled
}
}
var isBlocking: Bool {
switch self {
case .preambleDetected, .truncated, .repetitionLoop, .missingProtectedToken, .emptyOutput, .chunkFailed:
true
case .sameLanguage, .numericMismatch:
false
}
}
}
@@ -0,0 +1,19 @@
/// Accessibility is optional and used only for Replace (SEE: docs/SELECTION_AND_CLIPBOARD.md).
@MainActor
public protocol AccessibilityPermissionChecking: AnyObject {
/// Whether the app is currently trusted for Accessibility.
var isTrusted: Bool { get }
/// Shows the system prompt. Call only from onboarding or an explicit Replace click.
func requestTrust()
/// Opens System Settings ▸ Privacy & Security ▸ Accessibility.
func openSettings()
}
/// The login-item seam; production uses `SMAppService.mainApp`.
@MainActor
public protocol LaunchAtLoginControlling: AnyObject {
/// The current system state.
var isEnabled: Bool { get }
/// Registers or unregisters the app.
func setEnabled(_ enabled: Bool) throws
}
@@ -0,0 +1,100 @@
import Foundation
/// The minimal persistence seam for settings. Production uses `UserDefaults`; tests use memory.
public protocol SettingsDataStoring: Sendable {
/// Returns the stored data, if any.
func data(forKey key: String) -> Data?
/// Stores or removes data.
func set(_ data: Data?, forKey key: String)
}
/// The production `UserDefaults` adapter. `UserDefaults` is thread-safe; the unchecked
/// conformance records that no additional mutable state lives here.
public final class UserDefaultsSettingsDataStore: SettingsDataStoring, @unchecked Sendable {
private let defaults: UserDefaults
/// Creates an adapter.
public init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
public func data(forKey key: String) -> Data? {
defaults.data(forKey: key)
}
public func set(_ data: Data?, forKey key: String) {
if let data {
defaults.set(data, forKey: key)
} else {
defaults.removeObject(forKey: key)
}
}
}
/// Loads, caches, migrates and saves `AppSettings` as one JSON blob.
///
/// `@unchecked Sendable` is safe: every cached value is guarded by `lock`, and the storage seam is
/// itself Sendable.
public final class SettingsStore: @unchecked Sendable {
/// The single defaults key; only configuration is stored here.
public static let storageKey = "com.schihei.sprachmittler.settings"
private let storage: any SettingsDataStoring
private let lock = NSLock()
private var cached: AppSettings?
/// Creates a store.
public init(storage: any SettingsDataStoring = UserDefaultsSettingsDataStore()) {
self.storage = storage
}
/// The current settings, loading and migrating once.
public func current() -> AppSettings {
lock.lock()
defer { lock.unlock() }
if let cached {
return cached
}
let settings = loadLocked()
cached = settings
return settings
}
/// Saves settings and updates the cache.
public func save(_ settings: AppSettings) throws {
let data = try JSONEncoder().encode(settings)
lock.lock()
storage.set(data, forKey: Self.storageKey)
cached = settings
lock.unlock()
}
/// Mutates and saves atomically.
public func update(_ transform: (inout AppSettings) -> Void) throws {
lock.lock()
defer { lock.unlock() }
var settings = cached ?? loadLocked()
transform(&settings)
let data = try JSONEncoder().encode(settings)
storage.set(data, forKey: Self.storageKey)
cached = settings
}
/// Deletes the stored blob and returns defaults.
@discardableResult
public func reset() -> AppSettings {
lock.lock()
storage.set(nil, forKey: Self.storageKey)
let settings = AppSettings()
cached = settings
lock.unlock()
return settings
}
private func loadLocked() -> AppSettings {
guard let data = storage.data(forKey: Self.storageKey) else {
return AppSettings()
}
return (try? JSONDecoder().decode(AppSettings.self, from: data)) ?? AppSettings()
}
}
@@ -0,0 +1,119 @@
import Foundation
import Observation
import SprachmittlerEngines
import SprachmittlerOllama
/// Settings presentation model. It never stores source text or translations.
@MainActor
@Observable
public final class SettingsViewModel {
/// The editable draft.
public var draft: AppSettings
/// A settings validation or save error.
public private(set) var saveError: String?
/// A launch-at-login error; the other settings still saved.
public private(set) var launchError: String?
/// Installed Hy-MT3 tags, loaded on demand.
public private(set) var installedModels: [InstalledModel] = []
/// True while refreshing the model list.
public private(set) var isRefreshingModels = false
private let store: SettingsStore
private let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog
private let launchAtLogin: any LaunchAtLoginControlling
/// Creates the settings model.
public init(
store: SettingsStore,
catalogProvider: @escaping @Sendable (AppSettings) throws -> any OllamaCatalog,
launchAtLogin: any LaunchAtLoginControlling
) {
self.store = store
self.catalogProvider = catalogProvider
self.launchAtLogin = launchAtLogin
draft = store.current()
draft.launchAtLogin = launchAtLogin.isEnabled
}
/// Reloads the draft from storage.
public func reload() {
draft = store.current()
draft.launchAtLogin = launchAtLogin.isEnabled
saveError = nil
}
/// Validates and saves the draft. The remote endpoint policy is enforced here.
public func save() {
draft.sanitize()
saveError = nil
launchError = nil
do {
_ = try draft.validatedEndpoint()
try store.save(draft)
} catch let rejection as EndpointRejection {
saveError = SprachmittlerError.endpointRejected(reason: rejection).userMessage
return
} catch {
saveError = "Settings could not be saved."
return
}
do {
try launchAtLogin.setEnabled(draft.launchAtLogin)
} catch {
launchError = "Launch at login could not be changed."
}
}
/// Resets stored settings and the login item.
public func reset() {
draft = store.reset()
try? launchAtLogin.setEnabled(false)
saveError = nil
launchError = nil
}
/// Refreshes the installed model list using the draft endpoint.
public func refreshModels() async {
isRefreshingModels = true
defer { isRefreshingModels = false }
do {
let catalog = try catalogProvider(draft)
installedModels = try await catalog.installedModels()
.filter { HyMT3ModelPreset.isHyMT3($0.name) }
saveError = nil
} catch let rejection as EndpointRejection {
saveError = SprachmittlerError.endpointRejected(reason: rejection).userMessage
} catch let error as OllamaError {
saveError = SprachmittlerError(ollama: error).userMessage
} catch let error as SprachmittlerError {
saveError = error.userMessage
} catch {
saveError = "Models could not be loaded."
}
}
/// The model tags offered to the picker, including the current values.
public var modelChoices: [String] {
var tags = Set(installedModels.map(\.name))
tags.insert(draft.model)
if let fast = draft.fastModel {
tags.insert(fast)
}
return tags.sorted()
}
/// The licence text from the model card, not the Ollama field.
public var licenceNote: String {
"Hy-MT3 is Apache-2.0 per the model card. Sprachmittler bundles no weights."
}
/// The selected model digest, when installed.
public var selectedDigest: String? {
installedModels.first { $0.name == draft.model }?.digest
}
/// The installed Fast model candidate, if any.
public var detectedFastModel: String? {
installedModels.first { HyMT3ModelPreset.isFastModel($0.name) }?.name
}
}
@@ -0,0 +1,139 @@
import Foundation
import SprachmittlerOllama
/// A user-facing recovery action. The UI never shows a raw `localizedDescription`.
public enum RecoveryAction: Sendable, Equatable {
/// Start Ollama.
case startOllama
/// Copy and run `ollama pull <model>`.
case pullModel(String)
/// Open the relevant System Settings page.
case openSettings
/// Copy the translation instead.
case copyInstead
/// Shorten the selection.
case shortenText
/// Retry the translation.
case retry
/// Nothing to do.
case none
}
public extension SprachmittlerError {
/// A short, non-technical message for the panel and onboarding.
var userMessage: String {
switch self {
case .noSelection:
"No text was selected."
case .emptyText:
"No text was copied."
case let .textTooLong(_, limit):
"This selection is too long (limit \(limit) characters). You can raise the limit in Settings."
case .pasteboardUnavailable:
"The clipboard is unavailable."
case .ollamaUnreachable:
"Ollama is not running."
case let .ollamaTooOld(_, required):
"Ollama is too old. Version \(required) or newer is required."
case let .endpointRejected(reason):
"The endpoint is not allowed: \(reason.userMessage)"
case .modelNotInstalled:
"The Hy-MT3 model is not installed."
case .noAdapter:
"This model is not supported."
case .badRequest:
"Ollama rejected the request."
case .server:
"Ollama returned an error."
case .timeout:
"Ollama took too long to answer."
case .emptyOutput:
"The model returned an empty translation."
case .truncated:
"The translation was cut off."
case .repetitionLoop:
"The translation started repeating."
case .preambleDetected:
"The model added an explanation."
case .protectedTokenLost:
"A URL, placeholder or code token was lost."
case .accessibilityNotTrusted:
"Replace needs the Accessibility permission."
case .accessibilityUnsupported:
"This app did not accept the replacement."
case .insertionTargetChanged:
"The selection changed before Replace."
case .pasteboardRestoreFailed:
"The previous clipboard could not be restored."
case .cancelled:
"Translation cancelled."
}
}
/// A stable non-text code for diagnostics.
var diagnosticCode: String {
switch self {
case .noSelection: "noSelection"
case .emptyText: "emptyText"
case .textTooLong: "textTooLong"
case .pasteboardUnavailable: "pasteboardUnavailable"
case .ollamaUnreachable: "ollamaUnreachable"
case .ollamaTooOld: "ollamaTooOld"
case .endpointRejected: "endpointRejected"
case .modelNotInstalled: "modelNotInstalled"
case .noAdapter: "noAdapter"
case .badRequest: "badRequest"
case .server: "server"
case .timeout: "timeout"
case .emptyOutput: "emptyOutput"
case .truncated: "truncated"
case .repetitionLoop: "repetitionLoop"
case .preambleDetected: "preambleDetected"
case .protectedTokenLost: "protectedTokenLost"
case .accessibilityNotTrusted: "accessibilityNotTrusted"
case .accessibilityUnsupported: "accessibilityUnsupported"
case .insertionTargetChanged: "insertionTargetChanged"
case .pasteboardRestoreFailed: "pasteboardRestoreFailed"
case .cancelled: "cancelled"
}
}
/// The primary recovery action, if any.
var recoveryAction: RecoveryAction {
switch self {
case .ollamaUnreachable:
.startOllama
case let .modelNotInstalled(model):
.pullModel(model)
case .ollamaTooOld, .endpointRejected:
.openSettings
case .textTooLong:
.openSettings
case .accessibilityNotTrusted:
.openSettings
case .accessibilityUnsupported, .insertionTargetChanged, .pasteboardRestoreFailed:
.copyInstead
case .timeout, .server, .emptyOutput, .truncated, .repetitionLoop, .preambleDetected:
.retry
default:
.none
}
}
}
private extension EndpointRejection {
var userMessage: String {
switch self {
case .scheme:
"only http and https are supported"
case .form:
"it must not contain credentials, a query or a fragment"
case .remoteNotAllowed:
"remote endpoints are disabled"
case .remoteRequiresHTTPS:
"remote endpoints require HTTPS"
case .redirect:
"redirects are refused"
}
}
}
@@ -0,0 +1,52 @@
import Foundation
/// A text replacement implementation. Accessibility direct replacement is preferred; the paste
/// fallback is the second strategy (`docs/SELECTION_AND_CLIPBOARD.md` §4).
public protocol TextInserting: Sendable {
/// Replaces the captured selection with `translation`.
func replace(
selection: CapturedText,
with translation: String,
target: InsertionTarget
) async throws -> InsertionOutcome
}
/// Captures the source app and, when Accessibility is trusted, the focused selection at trigger
/// time. Never reads a full document value.
@MainActor
public protocol InsertionTargetProviding {
/// Returns the target, or nil when no app is frontmost.
func captureTarget() -> InsertionTarget?
}
/// The safety checks shared by AX and paste insertion.
public enum InsertionPolicy {
/// Verifies the frontmost app and, when available, the selected text.
public static func verify(
frontmostPID: pid_t,
target: InsertionTarget,
selectedText: String?,
source: String
) throws {
guard frontmostPID == target.pid else {
throw SprachmittlerError.insertionTargetChanged
}
guard let selectedText else { return }
let expected = selectedText
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
.trimmingCharacters(in: .whitespacesAndNewlines)
let actual = source
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
.trimmingCharacters(in: .whitespacesAndNewlines)
guard expected == actual else {
throw SprachmittlerError.insertionTargetChanged
}
}
/// True when the text should not be replaced because a blocking warning exists.
public static func isBlocked(by warnings: [TranslationWarning]) -> Bool {
warnings.contains(where: \.blocksReplacement)
}
}
@@ -92,7 +92,10 @@ public struct TranslationPipeline: Sendable {
text: String,
target: ModelLanguage,
model: String,
keepAlive: String
keepAlive: String,
sampling: SamplingOptions = .publisherDefault,
onDelta: (@Sendable (String) async -> Void)? = nil,
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)? = nil
) async throws -> PipelineResult {
let normalized = TextNormalization.normalizeInput(text)
guard !normalized.isEmpty else {
@@ -112,9 +115,11 @@ public struct TranslationPipeline: Sendable {
target: target,
model: model,
keepAlive: keepAlive,
tokens: tokens
sampling: sampling,
tokens: tokens,
onDelta: onDelta
)
let accumulator = try await translateAll(chunks, context: context)
let accumulator = try await translateAll(chunks, context: context, onChunk: onChunk)
let final = TextNormalization.normalizeOutput(accumulator.joined)
let validation = validator.validate(
@@ -150,7 +155,9 @@ public struct TranslationPipeline: Sendable {
let target: ModelLanguage
let model: String
let keepAlive: String
let sampling: SamplingOptions
let tokens: [ProtectedToken]
let onDelta: (@Sendable (String) async -> Void)?
}
private struct Accumulator {
@@ -162,11 +169,16 @@ public struct TranslationPipeline: Sendable {
var sawLength = false
}
private func translateAll(_ chunks: [TextChunk], context: TranslationContext) async throws -> Accumulator {
private func translateAll(
_ chunks: [TextChunk],
context: TranslationContext,
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)?
) async throws -> Accumulator {
var accumulator = Accumulator()
do {
for chunk in chunks {
for (offset, chunk) in chunks.enumerated() {
try Task.checkCancellation()
await onChunk?(offset + 1, chunks.count)
let result = try await translateChunk(chunk, context: context)
if accumulator.firstTokenAt == nil {
accumulator.firstTokenAt = result.firstTokenAt
@@ -180,6 +192,9 @@ public struct TranslationPipeline: Sendable {
accumulator.sawLength = true
}
accumulator.joined += result.text + chunk.separatorAfter
if !chunk.separatorAfter.isEmpty {
await context.onDelta?(chunk.separatorAfter)
}
}
} catch is CancellationError {
throw SprachmittlerError.cancelled
@@ -214,16 +229,10 @@ public struct TranslationPipeline: Sendable {
var outputTokens: Int?
while true {
let request = try registry.makeRequest(
AdapterRequest(
text: chunk.text,
target: context.target,
model: context.model,
keepAlive: context.keepAlive,
prompt: prompt
)
)
let attempt = try await stream(request)
let request = try makeRequest(chunk: chunk, prompt: prompt, context: context)
// A retry replaces the first attempt; do not stream both into the panel.
let deltaHandler = retried ? nil : context.onDelta
let attempt = try await stream(request, onDelta: deltaHandler)
response = attempt
promptTokens = sum(promptTokens, attempt.metrics.promptEvalCount)
outputTokens = sum(outputTokens, attempt.metrics.evalCount)
@@ -255,6 +264,23 @@ public struct TranslationPipeline: Sendable {
)
}
private func makeRequest(
chunk: TextChunk,
prompt: PromptVariant,
context: TranslationContext
) throws -> ChatRequest {
try registry.makeRequest(
AdapterRequest(
text: chunk.text,
target: context.target,
model: context.model,
keepAlive: context.keepAlive,
prompt: prompt,
sampling: context.sampling
)
)
}
private struct StreamResult {
let text: String
let doneReason: String?
@@ -263,7 +289,10 @@ public struct TranslationPipeline: Sendable {
let looped: Bool
}
private func stream(_ request: ChatRequest) async throws -> StreamResult {
private func stream(
_ request: ChatRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> StreamResult {
var text = ""
var doneReason: String?
var metrics = ChatMetrics.empty
@@ -280,6 +309,7 @@ public struct TranslationPipeline: Sendable {
firstTokenAt = clock()
}
text += delta
await onDelta?(delta)
if repetition.append(delta) {
looped = true
}
@@ -0,0 +1,245 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
/// The streaming translation seam used by `TranslationSession`. The production implementation is
/// `TranslationPipeline`; tests provide a controlled fake.
public protocol TranslationStreaming: Sendable {
/// Translates one captured selection, optionally forwarding deltas.
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult
/// Translates one captured selection, forwarding deltas and the start of each chunk.
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?,
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)?
) async throws -> PipelineResult
}
public extension TranslationStreaming {
/// Fakes that do not report chunk progress use this fallback.
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?,
onChunk: (@Sendable (Int, Int) async -> Void)?
) async throws -> PipelineResult {
try await translate(request, onDelta: onDelta)
}
}
extension TranslationPipeline: TranslationStreaming {}
public extension TranslationPipeline {
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
try await translate(
text: request.captured.text,
target: request.target,
model: request.model,
keepAlive: request.keepAlive,
sampling: request.sampling,
onDelta: onDelta
)
}
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?,
onChunk: (@Sendable (Int, Int) async -> Void)?
) async throws -> PipelineResult {
try await translate(
text: request.captured.text,
target: request.target,
model: request.model,
keepAlive: request.keepAlive,
sampling: request.sampling,
onDelta: onDelta,
onChunk: onChunk
)
}
}
/// One translation request, including the settings snapshot it was built from.
public struct TranslationSessionRequest: Sendable, Equatable {
/// The captured text.
public let captured: CapturedText
/// The target language.
public let target: ModelLanguage
/// The installed model tag.
public let model: String
/// The Ollama keep-alive value.
public let keepAlive: String
/// The sampling values.
public let sampling: SamplingOptions
/// The chunk and capture limits accepted for this capture.
public let captureLimits: CaptureLimits
/// Creates a request.
public init(
captured: CapturedText,
target: ModelLanguage,
model: String,
keepAlive: String,
sampling: SamplingOptions = .publisherDefault,
captureLimits: CaptureLimits = CaptureLimits()
) {
self.captured = captured
self.target = target
self.model = model
self.keepAlive = keepAlive
self.sampling = sampling
self.captureLimits = captureLimits
}
}
/// An event from the translation session. The epoch lets the panel drop stale events.
public enum TranslationSessionEvent: Sendable, Equatable {
/// A request started.
case started(epoch: UInt64, request: TranslationSessionRequest)
/// One chunk of a multi-part request started (`index` is 1-based).
case chunkStarted(epoch: UInt64, index: Int, total: Int)
/// One streamed delta.
case delta(epoch: UInt64, text: String)
/// The final validated result.
case finished(epoch: UInt64, result: PipelineResult)
/// A domain error.
case failed(epoch: UInt64, error: SprachmittlerError)
/// The request was cancelled or replaced.
case cancelled(epoch: UInt64)
}
/// The only translation actor: one request in flight, epochs discard stale events (ADR-015).
public actor TranslationSession {
private let pipelineFactory: @Sendable () throws -> any TranslationStreaming
private let eventsStream: AsyncStream<TranslationSessionEvent>
private let continuation: AsyncStream<TranslationSessionEvent>.Continuation
private var epoch: UInt64 = 0
private var task: Task<Void, Never>?
/// Creates a session. The factory reads a settings snapshot and builds a pipeline.
public init(pipelineFactory: @escaping @Sendable () throws -> any TranslationStreaming) {
self.pipelineFactory = pipelineFactory
let pair = AsyncStream<TranslationSessionEvent>.makeStream()
eventsStream = pair.stream
continuation = pair.continuation
}
/// The event stream. It has one consumer, normally `PanelViewModel`.
public func events() -> AsyncStream<TranslationSessionEvent> {
eventsStream
}
/// Starts a request, cancelling any active one, and returns its epoch.
@discardableResult
public func start(_ request: TranslationSessionRequest) -> UInt64 {
task?.cancel()
epoch &+= 1
let currentEpoch = epoch
continuation.yield(.started(epoch: currentEpoch, request: request))
guard validate(request, epoch: currentEpoch) else {
return currentEpoch
}
task = Task { [pipelineFactory] in
do {
let pipeline = try pipelineFactory()
let result = try await pipeline.translate(
request,
onDelta: { delta in
await self.forwardDelta(epoch: currentEpoch, text: delta)
},
onChunk: { index, total in
await self.forwardChunk(epoch: currentEpoch, index: index, total: total)
}
)
self.finish(epoch: currentEpoch, result: result)
} catch let error as SprachmittlerError {
if error == .cancelled {
self.cancelEvent(epoch: currentEpoch)
} else {
self.fail(epoch: currentEpoch, error: error)
}
} catch let error as OllamaError {
self.fail(epoch: currentEpoch, error: SprachmittlerError(ollama: error))
} catch let rejection as EndpointRejection {
self.fail(
epoch: currentEpoch,
error: .endpointRejected(reason: rejection)
)
} catch is CancellationError {
self.cancelEvent(epoch: currentEpoch)
} catch {
self.fail(
epoch: currentEpoch,
error: .server(status: 0, message: "Translation failed")
)
}
}
return currentEpoch
}
/// Cancels the active request and emits a cancellation for its epoch.
public func cancel() {
let previous = epoch
epoch &+= 1
task?.cancel()
task = nil
continuation.yield(.cancelled(epoch: previous))
}
/// Cancels without emitting. Use when the panel closes.
public func reset() {
epoch &+= 1
task?.cancel()
task = nil
}
private func validate(_ request: TranslationSessionRequest, epoch eventEpoch: UInt64) -> Bool {
switch CapturePolicy.validate(request.captured.text, limits: request.captureLimits) {
case .valid:
return true
case .empty:
continuation.yield(.failed(epoch: eventEpoch, error: .emptyText))
return false
case let .textTooLong(characters, limit):
continuation.yield(
.failed(epoch: eventEpoch, error: .textTooLong(characters: characters, limit: limit))
)
return false
}
}
private func forwardDelta(epoch eventEpoch: UInt64, text: String) {
guard eventEpoch == epoch else { return }
continuation.yield(.delta(epoch: eventEpoch, text: text))
}
private func forwardChunk(epoch eventEpoch: UInt64, index: Int, total: Int) {
guard eventEpoch == epoch else { return }
continuation.yield(.chunkStarted(epoch: eventEpoch, index: index, total: total))
}
private func finish(epoch eventEpoch: UInt64, result: PipelineResult) {
guard eventEpoch == epoch else { return }
task = nil
continuation.yield(.finished(epoch: eventEpoch, result: result))
}
private func fail(epoch eventEpoch: UInt64, error: SprachmittlerError) {
guard eventEpoch == epoch else { return }
task = nil
continuation.yield(.failed(epoch: eventEpoch, error: error))
}
private func cancelEvent(epoch eventEpoch: UInt64) {
guard eventEpoch == epoch else { return }
task = nil
continuation.yield(.cancelled(epoch: eventEpoch))
}
}
@@ -14,4 +14,9 @@ public enum HyMT3ModelPreset {
public static func isHyMT3(_ model: String) -> Bool {
model.lowercased().contains("hy-mt3")
}
/// True for the 1.8B Fast tag, without hard-coding the full tag in UI code.
public static func isFastModel(_ model: String) -> Bool {
model.lowercased().contains("hy-mt3-1.8b")
}
}
@@ -3,14 +3,14 @@ import SprachmittlerText
/// Family-neutral same-language check used by the pipeline. The canonical-code mapping stays in
/// Engines, next to the catalogue that defines it.
public enum LanguageMatching {
/// True when detection is confident and every alternative resolves to the target language.
public static func isSameLanguage(_ detection: LanguageDetection, target: ModelLanguage) -> Bool {
/// True when detection is confident and every meaningful alternative resolves to `language`.
public static func isLanguage(_ detection: LanguageDetection, _ language: ModelLanguage) -> Bool {
guard detection.confidence >= 0.5, !detection.alternatives.isEmpty else { return false }
let targetCode = HyMT3Languages.resolve(target.code)?.code ?? target.code
let targetCode = HyMT3Languages.resolve(language.code)?.code ?? language.code
var agreed = false
for code in detection.alternatives {
guard let language = HyMT3Languages.resolve(code),
language.code.caseInsensitiveCompare(targetCode) == .orderedSame
guard let resolved = HyMT3Languages.resolve(code),
resolved.code.caseInsensitiveCompare(targetCode) == .orderedSame
else {
return false
}
@@ -18,4 +18,9 @@ public enum LanguageMatching {
}
return agreed
}
/// True when detection is confident and every meaningful alternative is the target language.
public static func isSameLanguage(_ detection: LanguageDetection, target: ModelLanguage) -> Bool {
isLanguage(detection, target)
}
}
@@ -0,0 +1,35 @@
import Foundation
/// A source-language to target-language rule. The mother tongue is the default when no rule matches.
public struct LanguageRoute: Codable, Sendable, Equatable, Hashable, Identifiable {
/// The canonical BCP-47 source code.
public var source: String
/// The canonical BCP-47 target code.
public var target: String
/// The source code is unique in the rule table.
public var id: String {
source
}
/// Creates a route from canonical codes.
public init(source: String, target: String) {
self.source = source
self.target = target
}
/// Creates a route from catalogue entries.
public init(source: ModelLanguage, target: ModelLanguage) {
self.init(source: source.code, target: target.code)
}
/// The catalogue entry for the source, or nil when the code is unknown.
public var sourceLanguage: ModelLanguage? {
HyMT3Languages.resolve(source)
}
/// The catalogue entry for the target, or nil when the code is unknown.
public var targetLanguage: ModelLanguage? {
HyMT3Languages.resolve(target)
}
}
@@ -0,0 +1,55 @@
import SprachmittlerText
/// The effective target for one translation, after a language rule or an explicit override.
public struct TranslationDirection: Sendable, Equatable {
/// The language the request will translate into.
public let target: ModelLanguage
/// True when a language rule changed the target.
public let didRoute: Bool
/// The rule source when `didRoute` is true.
public let source: ModelLanguage?
/// Creates a direction.
public init(target: ModelLanguage, didRoute: Bool, source: ModelLanguage?) {
self.target = target
self.didRoute = didRoute
self.source = source
}
}
/// Chooses the direction for a capture. Detection stays advisory: a switch needs the same
/// high-confidence agreement as the same-language advisory.
public enum TranslationDirectionPolicy {
/// Resolves the target.
///
/// - Parameters:
/// - configuredTarget: The user's mother tongue, used when no rule matches.
/// - routes: The source-to-target rules.
/// - detection: The advisory source-language detection.
/// - override: An explicit target choice for the current capture, or nil to use the routes.
public static func resolve(
configuredTarget: ModelLanguage,
routes: [LanguageRoute],
detection: LanguageDetection?,
override: ModelLanguage?
) -> TranslationDirection {
if let override {
return TranslationDirection(target: override, didRoute: false, source: nil)
}
guard let detection else {
return TranslationDirection(target: configuredTarget, didRoute: false, source: nil)
}
for route in routes {
guard let source = route.sourceLanguage,
let target = route.targetLanguage,
target.code.caseInsensitiveCompare(source.code) != .orderedSame,
target.code.caseInsensitiveCompare(configuredTarget.code) != .orderedSame,
LanguageMatching.isLanguage(detection, source)
else {
continue
}
return TranslationDirection(target: target, didRoute: true, source: source)
}
return TranslationDirection(target: configuredTarget, didRoute: false, source: nil)
}
}
@@ -0,0 +1,196 @@
import Foundation
/// The corpus categories from `docs/MODEL_EVALUATION.md` §1.
public enum EvaluationCategory: String, Codable, CaseIterable, Sendable {
/// EN→DE prose.
case enDeProse = "en-de-prose"
/// DE→EN prose.
case deEnProse = "de-en-prose"
/// Technical text.
case technical
/// Legal text.
case legal
/// Short UI strings.
case uiStrings = "ui"
/// Markdown structure.
case markdown
/// JSON keys and values.
case json
/// URLs, placeholders and e-mail addresses.
case placeholders
/// Numbers and units.
case numbers
/// Non-literal meaning.
case idioms
/// Long, chunked text.
case long
/// CJK text.
case cjk
/// Right-to-left text.
case rtl
}
/// One manifest segment, before paths are resolved.
public struct EvaluationSegment: Codable, Sendable, Equatable {
/// Stable identifier matching the schema pattern.
public let id: String
/// Source path relative to the manifest.
public let source: String
/// Source BCP-47 code.
public let sourceLanguage: String
/// Target BCP-47 code.
public let targetLanguage: String
/// Evaluation category.
public let category: EvaluationCategory
/// Reference path relative to the manifest.
public let reference: String
/// `human` or `public`.
public let referenceKind: String
/// Optional notes.
public let notes: String?
}
/// The corpus manifest from `evaluation/corpus.schema.json`.
public struct EvaluationManifest: Codable, Sendable, Equatable {
/// Schema version; must be 1.
public let version: Int
/// Optional description.
public let description: String?
/// The segments.
public let segments: [EvaluationSegment]
}
/// A segment with its source and reference text loaded.
public struct ResolvedSegment: Sendable, Equatable {
/// The manifest segment.
public let segment: EvaluationSegment
/// Source text.
public let sourceText: String
/// Human/public reference.
public let referenceText: String
}
/// A manifest with all paths resolved and text loaded.
public struct ResolvedManifest: Sendable, Equatable {
/// The original manifest.
public let manifest: EvaluationManifest
/// The selected segments.
public let segments: [ResolvedSegment]
}
/// Precise manifest failures for the CLI.
public enum ManifestError: Error, Equatable, CustomStringConvertible {
case unreadable(String)
case invalidJSON(String)
case unsupportedVersion(Int)
case emptySegments
case invalidID(String)
case duplicateID(String)
case invalidLanguage(String)
case invalidReferenceKind(String)
case missingFile(String)
case emptyFile(String)
case noMatchingTarget(String)
public var description: String {
switch self {
case let .unreadable(path): "The manifest could not be read: \(path)"
case let .invalidJSON(detail): "The manifest is not valid JSON: \(detail)"
case let .unsupportedVersion(version): "Unsupported manifest version \(version); expected 1."
case .emptySegments: "The manifest has no segments."
case let .invalidID(id): "Invalid segment ID '\(id)'; use lowercase letters, digits and hyphens."
case let .duplicateID(id): "Duplicate segment ID '\(id)'."
case let .invalidLanguage(code): "Invalid BCP-47 language code '\(code)'."
case let .invalidReferenceKind(kind): "Invalid referenceKind '\(kind)'; use human or public."
case let .missingFile(path): "Missing corpus file: \(path)"
case let .emptyFile(path): "Empty corpus file: \(path)"
case let .noMatchingTarget(target): "No segments target '\(target)'."
}
}
}
/// Loads and validates a corpus manifest without reading any private path implicitly.
public enum EvaluationManifestLoader {
private static let idPattern = try? NSRegularExpression(pattern: "^[a-z0-9][a-z0-9-]{1,63}$")
private static let languagePattern = try? NSRegularExpression(
pattern: "^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$"
)
/// Loads `url`, resolves every source/reference path and filters to `target` when supplied.
public static func load(manifestURL url: URL, target: String? = nil) throws -> ResolvedManifest {
let data: Data
do {
data = try Data(contentsOf: url)
} catch {
throw ManifestError.unreadable(url.path)
}
let manifest: EvaluationManifest
do {
manifest = try JSONDecoder().decode(EvaluationManifest.self, from: data)
} catch {
throw ManifestError.invalidJSON(String(describing: error))
}
guard manifest.version == 1 else {
throw ManifestError.unsupportedVersion(manifest.version)
}
guard !manifest.segments.isEmpty else {
throw ManifestError.emptySegments
}
let base = url.deletingLastPathComponent()
var seen = Set<String>()
var resolved: [ResolvedSegment] = []
for segment in manifest.segments {
try validate(segment)
guard seen.insert(segment.id).inserted else {
throw ManifestError.duplicateID(segment.id)
}
if let target, segment.targetLanguage != target {
continue
}
let sourceURL = URL(fileURLWithPath: segment.source, relativeTo: base).standardizedFileURL
let referenceURL = URL(fileURLWithPath: segment.reference, relativeTo: base).standardizedFileURL
let source = try read(sourceURL)
let reference = try read(referenceURL)
resolved.append(
ResolvedSegment(segment: segment, sourceText: source, referenceText: reference)
)
}
if let target, resolved.isEmpty {
throw ManifestError.noMatchingTarget(target)
}
return ResolvedManifest(manifest: manifest, segments: resolved)
}
private static func validate(_ segment: EvaluationSegment) throws {
let idRange = NSRange(location: 0, length: (segment.id as NSString).length)
guard idPattern?.firstMatch(in: segment.id, range: idRange) != nil else {
throw ManifestError.invalidID(segment.id)
}
for code in [segment.sourceLanguage, segment.targetLanguage] {
let range = NSRange(location: 0, length: (code as NSString).length)
guard languagePattern?.firstMatch(in: code, range: range) != nil else {
throw ManifestError.invalidLanguage(code)
}
}
guard ["human", "public"].contains(segment.referenceKind) else {
throw ManifestError.invalidReferenceKind(segment.referenceKind)
}
}
private static func read(_ url: URL) throws -> String {
guard FileManager.default.fileExists(atPath: url.path) else {
throw ManifestError.missingFile(url.path)
}
let text: String
do {
text = try String(contentsOf: url, encoding: .utf8)
} catch {
throw ManifestError.unreadable(url.path)
}
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw ManifestError.emptyFile(url.path)
}
return text
}
}
@@ -0,0 +1,98 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerText
/// chrF and BLEU metrics with no Python dependency (`docs/MODEL_EVALUATION.md` §3).
public enum EvaluationMetrics {
/// Character n-gram F-score. The beta is 2; spaces and punctuation count as characters.
public static func chrF(reference: String, hypothesis: String) -> Double {
let ref = Array(reference.lowercased())
let hyp = Array(hypothesis.lowercased())
guard !ref.isEmpty || !hyp.isEmpty else { return 100 }
var scores: [Double] = []
for size in 1 ... 6 {
let refGrams = ngrams(ref, size: size)
let hypGrams = ngrams(hyp, size: size)
guard !refGrams.isEmpty, !hypGrams.isEmpty else { continue }
let matched = min(min(refGrams.count, hypGrams.count), matchingCount(refGrams, hypGrams))
let precision = Double(matched) / Double(hypGrams.count)
let recall = Double(matched) / Double(refGrams.count)
guard precision + recall > 0 else {
scores.append(0)
continue
}
let beta = 2.0
let betaSquared = beta * beta
scores.append((1 + betaSquared) * precision * recall / (betaSquared * precision + recall))
}
guard !scores.isEmpty else { return 100 }
return 100 * scores.reduce(0, +) / Double(scores.count)
}
/// A corpus-style BLEU percentage for one hypothesis/reference pair.
public static func bleu(reference: String, hypothesis: String) -> Double {
let ref = reference.lowercased().split(whereSeparator: \.isWhitespace).map(String.init)
let hyp = hypothesis.lowercased().split(whereSeparator: \.isWhitespace).map(String.init)
guard !hyp.isEmpty else { return 0 }
var logSum = 0.0
for size in 1 ... 4 {
let hypGrams = wordNgrams(hyp, size: size)
let refGrams = wordNgrams(ref, size: size)
guard !hypGrams.isEmpty else { return 0 }
let matched = min(min(hypGrams.count, refGrams.count), matchingCount(hypGrams, refGrams))
guard matched > 0 else { return 0 }
logSum += log(Double(matched) / Double(hypGrams.count))
}
let penalty = hyp.count < ref.count ? exp(1 - Double(ref.count) / Double(hyp.count)) : 1
return 100 * penalty * exp(logSum / 4)
}
/// Share of protected-token kinds that survive exactly; 1.0 when the source has none.
public static func tokenRetention(source: String, translation: String) -> Double {
let tokens = ProtectedTokenScanner().scan(source)
guard !tokens.isEmpty else { return 1 }
let retained = tokens.filter { token in
translation.components(separatedBy: token.value).count - 1
>= source.components(separatedBy: token.value).count - 1
}
return Double(retained.count) / Double(tokens.count)
}
/// Share of source numeric values present after locale normalisation; 1.0 when none.
public static func numericConsistency(source: String, translation: String) -> Double {
let sourceNumbers = Set(NumericTokenNormalizer.numbers(in: source))
guard !sourceNumbers.isEmpty else { return 1 }
let translated = Set(NumericTokenNormalizer.numbers(in: translation))
return Double(sourceNumbers.intersection(translated).count) / Double(sourceNumbers.count)
}
private static func ngrams(_ characters: [Character], size: Int) -> [String] {
guard characters.count >= size else { return [] }
return (0 ... characters.count - size).map { index in
String(characters[index ..< index + size])
}
}
private static func wordNgrams(_ words: [String], size: Int) -> [String] {
guard words.count >= size else { return [] }
return (0 ... words.count - size).map { index in
words[index ..< index + size].joined(separator: " ")
}
}
private static func matchingCount(_ lhs: [String], _ rhs: [String]) -> Int {
var rhsCounts: [String: Int] = [:]
for gram in rhs {
rhsCounts[gram, default: 0] += 1
}
var matched = 0
for gram in lhs {
guard let count = rhsCounts[gram], count > 0 else { continue }
matched += 1
rhsCounts[gram] = count - 1
}
return matched
}
}
@@ -0,0 +1,116 @@
import Foundation
/// Writes `report.md` and `report.json` (`docs/MODEL_EVALUATION.md` §4).
public enum EvaluationReportWriter {
/// Writes both report files into `directory`.
public static func write(_ report: EvaluationReport, to directory: URL) throws {
let fileManager = FileManager.default
try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
let json = try JSONEncoder.reportEncoder.encode(report)
try json.write(to: directory.appendingPathComponent("report.json"), options: .atomic)
try markdown(report).write(
to: directory.appendingPathComponent("report.md"),
atomically: true,
encoding: .utf8
)
}
/// The Markdown report.
public static func markdown(_ report: EvaluationReport) -> String {
var lines = [
"# Sprachmittler evaluation",
"",
"Generated: \(ISO8601DateFormatter().string(from: report.generatedAt))",
"",
"## Environment",
"",
]
lines.append(contentsOf: environmentLines(report.environment))
lines.append("")
for model in report.models {
lines.append(contentsOf: modelLines(model))
lines.append("")
}
lines.append(contentsOf: observations)
return lines.joined(separator: "\n")
}
private static func environmentLines(_ environment: EvaluationEnvironment) -> [String] {
var lines = [
"| Key | Value |",
"|---|---|",
"| Ollama | \(environment.ollamaVersion) |",
"| Server | \(environment.serverVersion) |",
"| Hardware | \(environment.hardware) |",
"| macOS | \(environment.macOS) |",
]
for (model, digest) in environment.models.sorted(by: { $0.key < $1.key }) {
lines.append("| \(model) | \(digest) |")
}
return lines
}
private static func modelLines(_ model: ModelRunResult) -> [String] {
var lines = [
"## \(model.model)",
"",
"Temperature \(format(model.temperature)), \(model.runs) run(s) per segment.",
"",
"| Model | Temp | Category | Segments | Fail % | chrF | BLEU | Token retention | "
+ "Num. consistency | First token p50/p90 | Warm s/seg p50/p90 |",
"|---|---|---|---|---|---|---|---|---|---|---|",
]
for category in model.categories {
lines.append(
"| \(model.model) | \(format(model.temperature)) | \(category.category.rawValue) | "
+ "\(category.segments) | \(format(category.failureRate)) | \(format(category.chrF)) | "
+ "\(format(category.bleu)) | \(format(category.tokenRetention)) | "
+ "\(format(category.numericConsistency)) | "
+ "\(latency(category.firstTokenP50, category.firstTokenP90)) | "
+ "\(seconds(category.totalP50, category.totalP90)) |"
)
}
return lines
}
private static var observations: [String] {
[
"## Observations",
"",
"- Automated metrics only; review a sample in the panel and record correction minutes.",
"- Token retention below 1.0 or a failure rate above 2% disqualifies a default candidate.",
"",
"## Limitations",
"",
"- chrF/BLEU are mechanical and do not judge meaning or style.",
"- Memory is not included in this report; use `ollama ps` and record it in PERFORMANCE.md.",
"- Private corpus text and raw outputs stay under the ignored results directory.",
"",
]
}
private static func format(_ value: Double) -> String {
String(format: "%.2f", value)
}
private static func latency(_ p50: Int?, _ p90: Int?) -> String {
let left = p50.map(String.init) ?? "—"
let right = p90.map(String.init) ?? "—"
return "\(left)/\(right) ms"
}
private static func seconds(_ p50: Int?, _ p90: Int?) -> String {
let left = p50.map { String(format: "%.2f", Double($0) / 1000) } ?? "—"
let right = p90.map { String(format: "%.2f", Double($0) / 1000) } ?? "—"
return "\(left)/\(right) s"
}
}
private extension JSONEncoder {
static var reportEncoder: JSONEncoder {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .iso8601
return encoder
}
}
@@ -0,0 +1,321 @@
import Foundation
import SprachmittlerCore
import SprachmittlerEngines
/// Fixed environment facts for a report.
public struct EvaluationEnvironment: Codable, Sendable, Equatable {
/// Ollama server version.
public var serverVersion: String
/// Ollama executable version, when known.
public var ollamaVersion: String
/// Hardware description.
public var hardware: String
/// macOS version.
public var macOS: String
/// Model tags and digests.
public var models: [String: String]
/// Creates an environment block.
public init(
serverVersion: String,
ollamaVersion: String,
hardware: String,
macOS: String,
models: [String: String]
) {
self.serverVersion = serverVersion
self.ollamaVersion = ollamaVersion
self.hardware = hardware
self.macOS = macOS
self.models = models
}
}
/// The settings for one evaluation run.
public struct EvaluationConfiguration: Sendable, Equatable {
/// Model tags to evaluate.
public var models: [String]
/// Number of repeated runs per segment.
public var runs: Int
/// Keep-alive for the evaluation requests.
public var keepAlive: String
/// Sampling values.
public var sampling: SamplingOptions
/// Output directory.
public var outputDirectory: URL
/// Creates a configuration.
public init(
models: [String],
runs: Int = 3,
keepAlive: String = "30m",
sampling: SamplingOptions = .publisherDefault,
outputDirectory: URL
) {
self.models = models
self.runs = max(1, runs)
self.keepAlive = keepAlive
self.sampling = sampling
self.outputDirectory = outputDirectory
}
}
/// One segment/run measurement. It contains no source or translation text.
public struct SegmentResult: Codable, Sendable, Equatable {
/// Segment ID.
public let id: String
/// Category.
public let category: EvaluationCategory
/// Run index.
public let run: Int
/// chrF percentage.
public let chrF: Double
/// BLEU percentage.
public let bleu: Double
/// Protected-token retention.
public let tokenRetention: Double
/// Numeric consistency.
public let numericConsistency: Double
/// True for empty, blocked, or transport failure.
public let failed: Bool
/// Warning/error codes only.
public let warnings: [String]
/// First-token latency.
public let firstTokenMs: Int?
/// Total latency.
public let totalMs: Int?
/// Output character count.
public let outputCharacters: Int
}
/// Aggregate metrics for one model/category.
public struct CategorySummary: Codable, Sendable, Equatable {
/// Category.
public let category: EvaluationCategory
/// Number of segment runs.
public let segments: Int
/// Failure rate percentage.
public let failureRate: Double
/// Mean chrF.
public let chrF: Double
/// Mean BLEU.
public let bleu: Double
/// Mean token retention.
public let tokenRetention: Double
/// Mean numeric consistency.
public let numericConsistency: Double
/// First-token p50/p90.
public let firstTokenP50: Int?
public let firstTokenP90: Int?
/// Warm total p50/p90.
public let totalP50: Int?
public let totalP90: Int?
}
/// All results for one model.
public struct ModelRunResult: Codable, Sendable, Equatable {
/// Model tag.
public let model: String
/// Temperature.
public let temperature: Double
/// Number of repeats.
public let runs: Int
/// Raw segment results.
public let segments: [SegmentResult]
/// Category aggregates.
public let categories: [CategorySummary]
}
/// The complete evaluation report.
public struct EvaluationReport: Codable, Sendable, Equatable {
/// Environment facts.
public let environment: EvaluationEnvironment
/// Creation date.
public let generatedAt: Date
/// The model results.
public let models: [ModelRunResult]
}
/// Runs the corpus through the documented pipeline.
public struct EvaluationRunner: Sendable {
/// Builds a streaming pipeline for a model tag.
public typealias PipelineFactory = @Sendable (String) throws -> any TranslationStreaming
/// Warms a model with fixed synthetic text.
public typealias WarmUp = @Sendable (String) async throws -> Void
/// Unloads a model.
public typealias Unload = @Sendable (String) async throws -> Void
private let manifest: ResolvedManifest
private let configuration: EvaluationConfiguration
private let environment: EvaluationEnvironment
private let pipelineFactory: PipelineFactory
private let warmUp: WarmUp
private let unload: Unload
/// Creates a runner.
public init(
manifest: ResolvedManifest,
configuration: EvaluationConfiguration,
environment: EvaluationEnvironment,
pipelineFactory: @escaping PipelineFactory,
warmUp: @escaping WarmUp,
unload: @escaping Unload
) {
self.manifest = manifest
self.configuration = configuration
self.environment = environment
self.pipelineFactory = pipelineFactory
self.warmUp = warmUp
self.unload = unload
}
/// Runs every configured model and writes raw outputs plus the report.
public func run() async throws -> EvaluationReport {
try FileManager.default.createDirectory(
at: configuration.outputDirectory,
withIntermediateDirectories: true
)
var modelResults: [ModelRunResult] = []
for model in configuration.models {
try await unload(model)
try await warmUp(model)
var results: [SegmentResult] = []
let modelDirectory = configuration.outputDirectory.appendingPathComponent(slug(model))
try FileManager.default.createDirectory(at: modelDirectory, withIntermediateDirectories: true)
for segment in manifest.segments {
for run in 0 ..< configuration.runs {
let result = await evaluate(segment: segment, run: run, model: model, directory: modelDirectory)
results.append(result)
}
}
modelResults.append(
ModelRunResult(
model: model,
temperature: configuration.sampling.temperature,
runs: configuration.runs,
segments: results,
categories: summarize(results)
)
)
}
let report = EvaluationReport(
environment: environment,
generatedAt: Date(),
models: modelResults
)
try EvaluationReportWriter.write(report, to: configuration.outputDirectory)
return report
}
private func evaluate(
segment: ResolvedSegment,
run: Int,
model: String,
directory: URL
) async -> SegmentResult {
do {
let target = HyMT3Languages.resolve(segment.segment.targetLanguage)
?? HyMT3Languages.english
let pipeline = try pipelineFactory(model)
let request = TranslationSessionRequest(
captured: CapturedText(
text: segment.sourceText,
capturedAt: Date(),
source: .menu
),
target: target,
model: model,
keepAlive: configuration.keepAlive,
sampling: configuration.sampling
)
let result = try await pipeline.translate(request, onDelta: nil)
let output = result.translation
let failed = output.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|| result.warnings.contains(where: \.blocksReplacement)
let file = directory.appendingPathComponent("\(segment.segment.id)-run\(run).txt")
try? Data(output.utf8).write(to: file, options: .atomic)
return SegmentResult(
id: segment.segment.id,
category: segment.segment.category,
run: run,
chrF: EvaluationMetrics.chrF(reference: segment.referenceText, hypothesis: output),
bleu: EvaluationMetrics.bleu(reference: segment.referenceText, hypothesis: output),
tokenRetention: EvaluationMetrics.tokenRetention(
source: segment.sourceText,
translation: output
),
numericConsistency: EvaluationMetrics.numericConsistency(
source: segment.sourceText,
translation: output
),
failed: failed,
warnings: result.warnings.map(\.code),
firstTokenMs: result.timing.firstTokenMs,
totalMs: result.timing.totalMs,
outputCharacters: output.count
)
} catch let error as SprachmittlerError {
return failure(segment: segment, run: run, code: error.diagnosticCode)
} catch {
return failure(segment: segment, run: run, code: "transport")
}
}
private func failure(segment: ResolvedSegment, run: Int, code: String) -> SegmentResult {
SegmentResult(
id: segment.segment.id,
category: segment.segment.category,
run: run,
chrF: 0,
bleu: 0,
tokenRetention: 0,
numericConsistency: 0,
failed: true,
warnings: [code],
firstTokenMs: nil,
totalMs: nil,
outputCharacters: 0
)
}
private func summarize(_ results: [SegmentResult]) -> [CategorySummary] {
EvaluationCategory.allCases.compactMap { category in
let values = results.filter { $0.category == category }
guard !values.isEmpty else { return nil }
let first = values.compactMap(\.firstTokenMs)
let totals = values.compactMap(\.totalMs)
return CategorySummary(
category: category,
segments: values.count,
failureRate: 100 * Double(values.filter(\.failed).count) / Double(values.count),
chrF: mean(values.map(\.chrF)),
bleu: mean(values.map(\.bleu)),
tokenRetention: mean(values.map(\.tokenRetention)),
numericConsistency: mean(values.map(\.numericConsistency)),
firstTokenP50: percentile(first, 0.5),
firstTokenP90: percentile(first, 0.9),
totalP50: percentile(totals, 0.5),
totalP90: percentile(totals, 0.9)
)
}
}
private func mean(_ values: [Double]) -> Double {
guard !values.isEmpty else { return 0 }
return values.reduce(0, +) / Double(values.count)
}
private func percentile(_ values: [Int], _ fraction: Double) -> Int? {
guard !values.isEmpty else { return nil }
let sorted = values.sorted()
let index = min(sorted.count - 1, Int((Double(sorted.count - 1) * fraction).rounded()))
return sorted[index]
}
private func slug(_ model: String) -> String {
model.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: ":", with: "_")
}
}
@@ -0,0 +1,65 @@
import Foundation
import SprachmittlerCore
/// An in-memory settings backend for tests.
public final class InMemorySettingsDataStore: SettingsDataStoring, @unchecked Sendable {
private let lock = NSLock()
private var values: [String: Data] = [:]
/// Creates an empty store.
public init() {}
public func data(forKey key: String) -> Data? {
lock.lock()
defer { lock.unlock() }
return values[key]
}
public func set(_ data: Data?, forKey key: String) {
lock.lock()
values[key] = data
lock.unlock()
}
}
/// An Accessibility fake for onboarding and insertion tests.
@MainActor
public final class FakeAccessibilityPermission: AccessibilityPermissionChecking {
public var isTrusted: Bool
public private(set) var requestCount = 0
public private(set) var openSettingsCount = 0
/// Creates a fake.
public init(isTrusted: Bool = false) {
self.isTrusted = isTrusted
}
public func requestTrust() {
requestCount += 1
}
public func openSettings() {
openSettingsCount += 1
}
}
/// A launch-at-login fake.
@MainActor
public final class FakeLaunchAtLogin: LaunchAtLoginControlling {
public var isEnabled: Bool
public private(set) var requestedValues: [Bool] = []
public var error: (any Error)?
/// Creates a fake.
public init(isEnabled: Bool = false) {
self.isEnabled = isEnabled
}
public func setEnabled(_ enabled: Bool) throws {
requestedValues.append(enabled)
if let error {
throw error
}
isEnabled = enabled
}
}
@@ -4,7 +4,7 @@ import Foundation
///
/// Joining `chunks(for:)` with `reassemble(_:)` always returns the input exactly. The chunker does
/// not trim, normalise or invent separators; call `TextNormalization.normalizeInput` first.
public struct Chunker: Sendable {
public struct Chunker: Sendable, Equatable {
/// The limit for Latin, Cyrillic and Greek text.
public let latinLimit: Int
/// The limit for CJK, Arabic, Thai, Indic and other dense scripts.
@@ -37,10 +37,16 @@ public struct NaturalLanguageDetector: LanguageDetecting {
let recognizer = NLLanguageRecognizer()
recognizer.processString(trimmed)
guard let dominant = recognizer.dominantLanguage else { return nil }
let hypotheses = recognizer.languageHypotheses(withMaximum: 3)
let ordered = hypotheses.sorted { lhs, rhs in
let hypotheses = recognizer.languageHypotheses(withMaximum: 5)
// NLLanguageRecognizer returns many near-zero hypotheses. Keep only candidates that
// carry meaningful evidence, so a confident single-language text is not treated as mixed.
let minimumAlternativeConfidence = 0.05
let ordered = hypotheses
.filter { $0.value >= minimumAlternativeConfidence }
.sorted { lhs, rhs in
lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value
}.map(\.key.rawValue)
}
.map(\.key.rawValue)
let alternatives = ordered.isEmpty ? [dominant.rawValue] : ordered
return LanguageDetection(
code: dominant.rawValue,
@@ -0,0 +1,269 @@
import Foundation
/// A block-level element produced by the conservative Markdown presentation parser.
///
/// The cases carry raw inline Markdown; the app parses that with
/// ``MarkdownPresentation/inline(_:)``. The parser is presentation-only: it never changes the
/// translation that is validated, copied or inserted.
public enum MarkdownBlock: Equatable, Sendable {
/// A paragraph, with soft line breaks preserved.
case paragraph(String)
/// An ATX heading (`#`…`######`).
case heading(level: Int, text: String)
/// One list item. `indent` is a display indentation in steps, `number` is the ordinal for ordered lists.
case listItem(ordered: Bool, number: Int, indent: Int, text: String)
/// A block quote, with one level of `>` removed.
case quote(String)
/// A fenced code block.
case codeBlock(language: String?, text: String)
/// A thematic break (`---`, `***`, `___`).
case rule
}
/// Presentation-only Markdown parsing for the translation panel.
///
/// Inline formatting comes from Foundation's Markdown parser. Block structure is parsed here with a
/// deliberately small set of rules: anything that is not recognised stays visible as plain text
/// rather than being silently dropped.
public enum MarkdownPresentation {
private static let classifier = ContentClassifier()
private static let inlineDetectionPatterns = [
#"\*\*[^*\n]+\*\*"#,
#"(?<![\w*])\*[^*\s][^*\n]*\*(?![\w*])"#,
#"(?<![\w_])__[^_\n]+__(?![\w_])"#,
#"~~[^~\n]+~~"#,
#"`[^`\n]+`"#,
#"\[[^\]\n]+\]\([^)\s]+\)"#,
]
/// Whether the panel should render this source/translation pair as Markdown.
///
/// JSON, HTML and code are never rendered as Markdown, so their text is not mangled. Plain or
/// delimiter-heavy text is rendered only when it contains Markdown inline markers.
public static func shouldRender(source: String, translation: String) -> Bool {
let trimmed = source.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return false }
switch classifier.classify(trimmed) {
case .json, .html, .code:
return false
case .markdown:
return true
case .plain, .delimited:
break
}
return hasInlineMarkdown(trimmed) || hasInlineMarkdown(translation)
}
/// Splits `markdown` into display blocks. Unknown constructs stay in a paragraph.
public static func blocks(in markdown: String) -> [MarkdownBlock] {
let normalized = markdown
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
let lines = normalized.components(separatedBy: "\n")
var blocks: [MarkdownBlock] = []
var paragraph: [String] = []
var index = 0
func flushParagraph() {
guard !paragraph.isEmpty else { return }
let text = paragraph.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
if !text.isEmpty {
blocks.append(.paragraph(text))
}
paragraph.removeAll()
}
while index < lines.count {
let raw = lines[index]
let line = raw.trimmingCharacters(in: .whitespaces)
if line.isEmpty {
flushParagraph()
index += 1
} else if let fence = fenceMarker(line) {
flushParagraph()
blocks.append(fencedBlock(lines, index: &index, opening: line, fence: fence))
} else if let heading = heading(in: raw) {
flushParagraph()
blocks.append(heading)
index += 1
} else if isRule(line) {
flushParagraph()
blocks.append(.rule)
index += 1
} else if line.hasPrefix(">") {
flushParagraph()
blocks.append(quoteBlock(lines, index: &index))
} else if let item = listItem(in: raw) {
flushParagraph()
blocks.append(item)
index += 1
} else {
paragraph.append(line)
index += 1
}
}
flushParagraph()
return blocks
}
private static func fencedBlock(
_ lines: [String],
index: inout Int,
opening: String,
fence: (marker: Character, count: Int)
) -> MarkdownBlock {
var code: [String] = []
var closed = false
index += 1
while index < lines.count, !isClosingFence(lines[index], marker: fence.marker) {
code.append(lines[index])
index += 1
}
if index < lines.count {
index += 1
closed = true
}
let info = opening.dropFirst(fence.count).trimmingCharacters(in: .whitespaces)
let language = info.split(separator: " ").first.map(String.init)
var text = code.joined(separator: "\n")
if !closed {
text = text.trimmingCharacters(in: .newlines)
}
return .codeBlock(language: language, text: text)
}
private static func quoteBlock(_ lines: [String], index: inout Int) -> MarkdownBlock {
var quote: [String] = []
while index < lines.count {
let line = lines[index].trimmingCharacters(in: .whitespaces)
guard line.hasPrefix(">") else { break }
var content = String(line.dropFirst())
if content.hasPrefix(" ") {
content.removeFirst()
}
quote.append(content)
index += 1
}
return .quote(quote.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines))
}
/// Parses one inline Markdown fragment. Images are reduced to their alt text so no attachment
/// or remote resource can be requested; malformed input falls back to plain text.
public static func inline(_ text: String) -> AttributedString {
let cleaned = strippingImages(text)
let options = AttributedString.MarkdownParsingOptions(
interpretedSyntax: .inlineOnlyPreservingWhitespace,
failurePolicy: .returnPartiallyParsedIfPossible
)
if let attributed = try? AttributedString(markdown: cleaned, options: options) {
return attributed
}
return AttributedString(cleaned)
}
/// Only explicit web links may be opened. `file:`, `javascript:`, `data:` and app schemes stay inert.
public static func isAllowedLink(_ url: URL) -> Bool {
guard let scheme = url.scheme?.lowercased(), let host = url.host, !host.isEmpty else {
return false
}
return scheme == "http" || scheme == "https"
}
private static func hasInlineMarkdown(_ text: String) -> Bool {
inlineDetectionPatterns.contains { pattern in
text.range(of: pattern, options: .regularExpression) != nil
}
}
private static func strippingImages(_ text: String) -> String {
var result = text.replacingOccurrences(
of: #"!\[([^\]]*)\]\([^)]*\)"#,
with: "$1",
options: .regularExpression
)
result = result.replacingOccurrences(
of: #"<img\b[^>]*>"#,
with: "",
options: [.regularExpression, .caseInsensitive]
)
return result
}
private static func fenceMarker(_ line: String) -> (marker: Character, count: Int)? {
let stripped = line.drop(while: { $0 == " " })
guard let first = stripped.first, first == "`" || first == "~" else { return nil }
let count = stripped.prefix(while: { $0 == first }).count
guard count >= 3 else { return nil }
return (first, count)
}
private static func isClosingFence(_ line: String, marker: Character) -> Bool {
let stripped = line.trimmingCharacters(in: .whitespaces)
guard stripped.count >= 3 else { return false }
return stripped.allSatisfy { $0 == marker }
}
private static func heading(in raw: String) -> MarkdownBlock? {
let leading = raw.prefix(while: { $0 == " " }).count
guard leading <= 3 else { return nil }
let trimmed = raw.dropFirst(leading)
let hashes = trimmed.prefix(while: { $0 == "#" }).count
guard (1 ... 6).contains(hashes) else { return nil }
let rest = trimmed.dropFirst(hashes)
guard rest.isEmpty || rest.first == " " || rest.first == "\t" else { return nil }
var text = rest.trimmingCharacters(in: .whitespaces)
if text.hasSuffix("#") {
text = String(text.reversed().drop(while: { $0 == "#" }).reversed())
.trimmingCharacters(in: .whitespaces)
}
return .heading(level: hashes, text: text)
}
private static func isRule(_ line: String) -> Bool {
let compact = line.replacingOccurrences(of: " ", with: "")
guard compact.count >= 3, let first = compact.first, "-*_".contains(first) else {
return false
}
return compact.allSatisfy { $0 == first }
}
private static func listItem(in raw: String) -> MarkdownBlock? {
var columns = 0
for character in raw {
if character == " " {
columns += 1
} else if character == "\t" {
columns += 4
} else {
break
}
}
let indent = min(columns / 2, 8)
let trimmed = raw.trimmingCharacters(in: .whitespaces)
if let first = trimmed.first, "-*+".contains(first) {
let rest = trimmed.dropFirst()
guard rest.first == " " || rest.first == "\t" else { return nil }
let text = rest.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { return nil }
return .listItem(ordered: false, number: 0, indent: indent, text: text)
}
let digits = trimmed.prefix(while: { $0.isNumber })
guard !digits.isEmpty, digits.count <= 9 else { return nil }
let afterDigits = trimmed.dropFirst(digits.count)
guard let delimiter = afterDigits.first, delimiter == "." || delimiter == ")" else {
return nil
}
let rest = afterDigits.dropFirst()
guard rest.first == " " || rest.first == "\t", let number = Int(digits) else { return nil }
let text = rest.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { return nil }
return .listItem(ordered: true, number: number, indent: indent, text: text)
}
}
@@ -0,0 +1,56 @@
import ArgumentParser
import Foundation
import SprachmittlerText
struct DetectCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "detect",
abstract: "Detect the source language of text (advisory)."
)
@Option(name: .long, help: "Text to inspect.")
var text: String?
@Option(name: .long, help: "UTF-8 file to inspect.")
var file: String?
@Flag(name: .long, help: "Emit JSON.")
var json = false
func validate() throws {
if (text == nil) == (file == nil) {
throw ValidationError("Use exactly one of --text or --file.")
}
}
func run() throws {
let source: String
if let text {
source = text
} else if let file {
source = try String(contentsOfFile: file, encoding: .utf8)
} else {
return
}
let detection = NaturalLanguageDetector().detect(source)
guard let detection else {
if json {
print(#"{"language":null,"confidence":0,"alternatives":[]}"#)
} else {
print("unknown")
}
return
}
if json {
let object: [String: Any] = [
"language": detection.code,
"confidence": detection.confidence,
"alternatives": detection.alternatives,
]
let data = try JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys])
print(String(data: data, encoding: .utf8) ?? "{}")
} else {
print("\(detection.code)\t\(String(format: "%.2f", detection.confidence))")
}
}
}
@@ -0,0 +1,189 @@
import ArgumentParser
import Foundation
import SprachmittlerCore
import SprachmittlerEngines
import SprachmittlerEval
import SprachmittlerOllama
struct EvalCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "eval",
abstract: "Run the private-corpus evaluation and write report.md/report.json."
)
@Option(name: .long, help: "Corpus manifest JSON.")
var manifest: String
@Option(name: .long, help: "Comma-separated model tags.")
var models = HyMT3ModelPreset.defaultModel
@Option(name: .long, help: "Target BCP-47 code.")
var target = "de"
@Option(name: .long, help: "Runs per segment (default 3).")
var runs = 3
@Option(name: .long, help: "Sampling temperature override.")
var temperature: Double?
@Option(name: .long, help: "Ollama keep-alive during the run.")
var keepAlive = HyMT3ModelPreset.defaultKeepAlive
@Option(name: .long, help: "Output directory for raw outputs and reports.")
var out: String?
@OptionGroup var endpoint: EndpointOptions
func validate() throws {
guard (1 ... 5).contains(runs) else {
throw ValidationError("--runs must be between 1 and 5.")
}
if let temperature, !(0 ... 2).contains(temperature) {
throw ValidationError("--temperature must be between 0 and 2.")
}
guard HyMT3Languages.resolve(target) != nil else {
throw ValidationError("Unknown target language '\(target)'.")
}
guard !modelTags().isEmpty else {
throw ValidationError("Pass at least one model tag.")
}
}
func run() async throws {
try await CLIError.perform {
try await execute()
}
}
private func execute() async throws {
let manifestURL = URL(fileURLWithPath: manifest)
guard let language = HyMT3Languages.resolve(target) else {
throw ValidationError("Unknown target language '\(target)'.")
}
let resolved = try EvaluationManifestLoader.load(manifestURL: manifestURL, target: language.code)
let environment = try endpoint.makeEnvironment()
let settings = makeSettings(environment: environment, target: language)
let configuration = EvaluationConfiguration(
models: modelTags(),
runs: runs,
keepAlive: keepAlive,
sampling: settings.samplingOptions,
outputDirectory: outputDirectory()
)
let evaluationEnvironment = try await makeEnvironmentBlock(environment, settings: settings)
let evaluation = makeRunner(
resolved: resolved,
configuration: configuration,
environment: evaluationEnvironment,
settings: settings,
endpointEnvironment: environment
)
let report = try await evaluation.run()
printSummary(report, directory: configuration.outputDirectory)
}
private func makeSettings(environment: CLIEnvironment, target: ModelLanguage) -> AppSettings {
var draft = AppSettings()
draft.endpoint = environment.baseURL
draft.allowRemoteEndpoint = environment.allowRemote
draft.targetLanguage = target.code
draft.model = modelTags().first ?? HyMT3ModelPreset.defaultModel
draft.warmUpOnLaunch = false
draft.keepModelLoaded = keepAlive
if let temperature {
draft.temperature = temperature
}
return draft
}
private func makeEnvironmentBlock(
_ environment: CLIEnvironment,
settings: AppSettings
) async throws -> EvaluationEnvironment {
let catalog = try environment.makeCatalog()
let version = try await catalog.serverVersion()
let installed = try? await catalog.installedModels()
var digests: [String: String] = [:]
for model in installed ?? [] {
digests[model.name] = String(model.digest.prefix(12))
}
return EvaluationEnvironment(
serverVersion: version,
ollamaVersion: version,
hardware: hardware(),
macOS: ProcessInfo.processInfo.operatingSystemVersionString,
models: digests
)
}
private func makeRunner(
resolved: ResolvedManifest,
configuration: EvaluationConfiguration,
environment: EvaluationEnvironment,
settings: AppSettings,
endpointEnvironment: CLIEnvironment
) -> EvaluationRunner {
let registry = AdapterRegistry(adapters: [HyMT3Adapter()])
return EvaluationRunner(
manifest: resolved,
configuration: configuration,
environment: environment,
pipelineFactory: { model in
var snapshot = settings
snapshot.model = model
return try TranslationPipeline(
chat: endpointEnvironment.makeChatClient(),
registry: registry,
chunker: snapshot.chunker
)
},
warmUp: { model in
let chat = try endpointEnvironment.makeChatClient()
try await OllamaWarmUpRunner(chat: chat).run(
HyMT3Adapter().warmUpRequest(model: model, keepAlive: keepAlive)
)
},
unload: { model in
let chat = try endpointEnvironment.makeChatClient()
try await OllamaWarmUpRunner(chat: chat).run(
HyMT3Adapter().unloadRequest(model: model)
)
}
)
}
private func printSummary(_ report: EvaluationReport, directory: URL) {
print("Report: \(directory.path)")
for model in report.models {
for category in model.categories {
print(
"\(model.model)\t\(category.category.rawValue)\t"
+ String(
format: "fail %.1f%%\tchrF %.2f\tBLEU %.2f",
category.failureRate,
category.chrF,
category.bleu
)
)
}
}
}
private func modelTags() -> [String] {
models.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
}
private func outputDirectory() -> URL {
if let out {
return URL(fileURLWithPath: out)
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return URL(fileURLWithPath: "evaluation/results/\(formatter.string(from: Date()))")
}
private func hardware() -> String {
let memory = ProcessInfo.processInfo.physicalMemory / 1_073_741_824
return "Apple Silicon \(memory) GB, \(ProcessInfo.processInfo.processorCount) cores"
}
}
@@ -0,0 +1,24 @@
import ArgumentParser
import Foundation
import SprachmittlerEngines
struct LanguagesCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "languages",
abstract: "List the 102 supported target languages."
)
@Flag(name: .long, help: "Emit JSON.")
var json = false
func run() throws {
if json {
let data = try JSONEncoder().encode(HyMT3Languages.all)
print(String(data: data, encoding: .utf8) ?? "[]")
return
}
for language in HyMT3Languages.all {
print("\(language.code)\t\(language.modelName)\t\(language.localizedDisplayName)")
}
}
}
@@ -7,9 +7,12 @@ struct SprachmittlerCLI: AsyncParsableCommand {
commandName: "sprachmittler-cli",
abstract: "Headless translator and test harness for Sprachmittler.",
subcommands: [
LanguagesCommand.self,
DetectCommand.self,
ModelsCommand.self,
ShowCommand.self,
TranslateCommand.self,
EvalCommand.self,
]
)
}
@@ -0,0 +1,297 @@
import Darwin
import Foundation
import SprachmittlerCore
import SprachmittlerTestSupport
import Testing
@testable import SprachmittlerCapture
@Suite("Insertion coordinator")
@MainActor
struct InsertionCoordinatorTests {
private let source = CapturedText(
text: "Hello.",
capturedAt: Date(timeIntervalSince1970: 0),
source: .doubleCopy
)
private let target = InsertionTarget(
pid: 1234,
bundleID: "com.example.app",
selectedText: nil,
capturedAt: Date(timeIntervalSince1970: 0)
)
@Test func accessibilityDirectReplacementDoesNotTouchTheClipboard() async throws {
let pasteboard = makePasteboard()
let accessibility = FakeAccessibilityEditor(
trusted: true,
selected: "Hello.",
secure: false,
setResult: true
)
let poster = FakeEventPoster(result: true)
let coordinator = makeCoordinator(pasteboard: pasteboard, accessibility: accessibility, poster: poster)
let outcome = try await coordinator.replace(selection: source, with: "Hallo", target: target)
#expect(outcome == .replaced(using: .accessibility))
#expect(await accessibility.setCalls == ["Hallo"])
#expect(pasteboard.writtenTexts.isEmpty)
#expect(poster.pids.isEmpty)
}
@Test func unsupportedAccessibilityFallsBackToPasteAndRestoresTheClipboard() async throws {
let pasteboard = makePasteboard()
let accessibility = FakeAccessibilityEditor(
trusted: true,
selected: nil,
secure: false,
setResult: false
)
let poster = FakeEventPoster(result: true)
let coordinator = makeCoordinator(pasteboard: pasteboard, accessibility: accessibility, poster: poster)
let outcome = try await coordinator.replace(selection: source, with: "Hallo", target: target)
#expect(outcome == .replaced(using: .paste))
#expect(pasteboard.writtenTexts == ["Hallo"])
#expect(pasteboard.text == "Original")
#expect(!pasteboard.hasOwnWriteMarkers)
#expect(poster.pids == [1234])
}
@Test func wrongFrontmostAppAbortsBeforeTouchingAnything() async {
let pasteboard = makePasteboard()
let accessibility = FakeAccessibilityEditor(
trusted: true,
selected: "Hello.",
secure: false,
setResult: true
)
let coordinator = makeCoordinator(
pasteboard: pasteboard,
accessibility: accessibility,
poster: FakeEventPoster(result: true),
frontmost: 999
)
await #expect(throws: SprachmittlerError.insertionTargetChanged) {
_ = try await coordinator.replace(selection: source, with: "Hallo", target: target)
}
#expect(pasteboard.writtenTexts.isEmpty)
}
@Test func changedSelectionAborts() async {
let accessibility = FakeAccessibilityEditor(
trusted: true,
selected: "Different.",
secure: false,
setResult: true
)
let coordinator = makeCoordinator(
pasteboard: makePasteboard(),
accessibility: accessibility,
poster: FakeEventPoster(result: true)
)
await #expect(throws: SprachmittlerError.insertionTargetChanged) {
_ = try await coordinator.replace(selection: source, with: "Hallo", target: target)
}
}
@Test func deniedAccessibilityAborts() async {
let accessibility = FakeAccessibilityEditor(
trusted: false,
selected: nil,
secure: false,
setResult: false
)
let coordinator = makeCoordinator(
pasteboard: makePasteboard(),
accessibility: accessibility,
poster: FakeEventPoster(result: true)
)
await #expect(throws: SprachmittlerError.accessibilityNotTrusted) {
_ = try await coordinator.replace(selection: source, with: "Hallo", target: target)
}
}
@Test func secureFieldIsRefused() async {
let accessibility = FakeAccessibilityEditor(
trusted: true,
selected: nil,
secure: true,
setResult: false
)
let coordinator = makeCoordinator(
pasteboard: makePasteboard(),
accessibility: accessibility,
poster: FakeEventPoster(result: true)
)
await #expect(throws: SprachmittlerError.accessibilityUnsupported(app: "com.example.app")) {
_ = try await coordinator.replace(selection: source, with: "Hallo", target: target)
}
}
@Test func restoreFailureIsReported() async {
let pasteboard = makePasteboard()
pasteboard.restoreSucceeds = false
let accessibility = FakeAccessibilityEditor(
trusted: true,
selected: nil,
secure: false,
setResult: false
)
let coordinator = makeCoordinator(
pasteboard: pasteboard,
accessibility: accessibility,
poster: FakeEventPoster(result: true)
)
await #expect(throws: SprachmittlerError.pasteboardRestoreFailed) {
_ = try await coordinator.replace(selection: source, with: "Hallo", target: target)
}
#expect(pasteboard.text == "Hallo")
}
@Test func cancelledSettleDelayStillRestoresTheClipboard() async {
let pasteboard = makePasteboard()
let accessibility = FakeAccessibilityEditor(
trusted: true,
selected: nil,
secure: false,
setResult: false
)
let coordinator = makeCoordinator(
pasteboard: pasteboard,
accessibility: accessibility,
poster: FakeEventPoster(result: true),
delay: { _ in throw CancellationError() }
)
await #expect(throws: CancellationError.self) {
_ = try await coordinator.replace(selection: source, with: "Hallo", target: target)
}
#expect(pasteboard.text == "Original")
#expect(!pasteboard.hasOwnWriteMarkers)
}
@Test func eventPostingFailureRestoresAndReportsUnsupported() async {
let pasteboard = makePasteboard()
let accessibility = FakeAccessibilityEditor(
trusted: true,
selected: nil,
secure: false,
setResult: false
)
let coordinator = makeCoordinator(
pasteboard: pasteboard,
accessibility: accessibility,
poster: FakeEventPoster(result: false)
)
await #expect(throws: SprachmittlerError.accessibilityUnsupported(app: "com.example.app")) {
_ = try await coordinator.replace(selection: source, with: "Hallo", target: target)
}
#expect(pasteboard.text == "Original")
}
@Test func refusesToInsertIntoItsOwnApp() async {
let own = InsertionTarget(
pid: getpid(),
bundleID: "de.schihei.sprachmittler",
selectedText: nil,
capturedAt: Date()
)
let coordinator = makeCoordinator(
pasteboard: makePasteboard(),
accessibility: FakeAccessibilityEditor(
trusted: true,
selected: nil,
secure: false,
setResult: false
),
poster: FakeEventPoster(result: true)
)
await #expect(throws: SprachmittlerError.insertionTargetChanged) {
_ = try await coordinator.replace(selection: source, with: "Hallo", target: own)
}
}
private func makePasteboard() -> FakePasteboard {
let original = Data("Original".utf8)
return FakePasteboard(
changeCount: 1,
text: "Original",
items: [ClipboardItemData(data: ["public.utf8-plain-text": original])]
)
}
private func makeCoordinator(
pasteboard: FakePasteboard,
accessibility: FakeAccessibilityEditor,
poster: FakeEventPoster,
frontmost: pid_t = 1234,
delay: @escaping @Sendable (Duration) async throws -> Void = { _ in }
) -> InsertionCoordinator {
InsertionCoordinator(
pasteboard: pasteboard,
accessibility: accessibility,
poster: poster,
delay: delay,
ownWrite: {},
frontmostPID: { frontmost }
)
}
}
private actor FakeAccessibilityEditor: AccessibilityTextEditing {
let trusted: Bool
let selected: String?
let secure: Bool
let setResult: Bool
private(set) var setCalls: [String] = []
init(trusted: Bool, selected: String?, secure: Bool, setResult: Bool) {
self.trusted = trusted
self.selected = selected
self.secure = secure
self.setResult = setResult
}
func isTrusted() async -> Bool {
trusted
}
func selectedText(pid: pid_t) async -> String? {
selected
}
func isSecureField(pid: pid_t) async -> Bool {
secure
}
func setSelectedText(pid: pid_t, to text: String) async -> Bool {
setCalls.append(text)
return setResult
}
}
private final class FakeEventPoster: EventPosting, @unchecked Sendable {
private let lock = NSLock()
private(set) var pids: [pid_t] = []
let result: Bool
init(result: Bool) {
self.result = result
}
func postPaste(to pid: pid_t) -> Bool {
lock.lock()
pids.append(pid)
lock.unlock()
return result
}
}
@@ -67,6 +67,31 @@ struct PasteboardWatcherTests {
)
}
@Test func configuredPartsAcceptLongerText() {
let pasteboard = FakePasteboard()
let watcher = PasteboardWatcher(pasteboard: pasteboard, limits: CaptureLimits(maximumParts: 3))
let accepted = String(repeating: "a", count: 12000)
pasteboard.simulateCopy(accepted)
_ = watcher.poll(at: start)
pasteboard.simulateCopy(accepted)
guard case let .captured(captured) = watcher.poll(at: start.addingTimeInterval(0.1)) else {
Issue.record("expected a capture")
return
}
#expect(captured.text.count == 12000)
let tooLong = String(repeating: "a", count: 12001)
watcher.clear()
pasteboard.simulateCopy(tooLong)
_ = watcher.poll(at: start.addingTimeInterval(0.2))
pasteboard.simulateCopy(tooLong)
#expect(
watcher.poll(at: start.addingTimeInterval(0.3))
== .textTooLong(characters: 12001, limit: 12000)
)
}
@Test func ownWritesAreSuppressedFor750Milliseconds() {
let pasteboard = FakePasteboard()
let watcher = PasteboardWatcher(pasteboard: pasteboard)
@@ -0,0 +1,248 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
import SprachmittlerTestSupport
import Testing
@testable import SprachmittlerCore
@Suite("App settings")
struct AppSettingsTests {
@Test func defaultsAreValidAndTextFree() {
let settings = AppSettings()
#expect(settings.endpoint == AppSettings.defaultEndpoint)
#expect(!settings.allowRemoteEndpoint)
#expect(settings.model == HyMT3ModelPreset.defaultModel)
#expect(settings.targetLanguageModel.code == HyMT3Languages.resolve(settings.targetLanguage)?.code)
#expect(settings.doubleCopyWindowMs == 500)
#expect(settings.maxCharactersLatin == 4000)
#expect(settings.maxCharactersCJK == 2000)
#expect(settings.maximumPartsPerSelection == 1)
#expect(settings.numCtx == 8192)
#expect(settings.translationFontSize == 17)
#expect(settings.languageRoutes.isEmpty)
#expect(settings.renderMarkdown)
#expect(settings.closeWithEscape)
#expect(!settings.autoCopy)
#expect(!settings.hasCompletedOnboarding)
}
@Test func captureLimitsFollowPartsAndScript() {
var settings = AppSettings()
#expect(settings.captureLimits.chunkLimit(for: "a") == 4000)
#expect(settings.captureLimits.captureLimit(for: "a") == 4000)
#expect(settings.captureLimits.captureLimit(for: "你") == 2000)
settings.maximumPartsPerSelection = 4
#expect(settings.captureLimits.captureLimit(for: "a") == 16000)
#expect(settings.captureLimits.captureLimit(for: "你") == 8000)
#expect(settings.captureLimits.maximumParts == 4)
}
@Test func codableRoundTripPreservesValues() throws {
var settings = AppSettings()
settings.endpoint = try #require(URL(string: "https://example.com:11434"))
settings.allowRemoteEndpoint = true
settings.targetLanguage = "de"
settings.noteTarget(HyMT3Languages.german)
settings.temperature = 0.2
settings.translationFontSize = 22
settings.languageRoutes = [LanguageRoute(source: "zh", target: "en")]
settings.renderMarkdown = false
settings.closeWithEscape = false
settings.launchAtLogin = true
settings.hasCompletedOnboarding = true
settings.maximumPartsPerSelection = 4
let data = try JSONEncoder().encode(settings)
let decoded = try JSONDecoder().decode(AppSettings.self, from: data)
#expect(decoded == settings)
#expect(decoded.settingsVersion == AppSettings.currentVersion)
}
@Test func v0MigrationFillsDefaultsAndIgnoresUnknownKeys() throws {
let json = """
{
"settingsVersion": 0,
"endpoint": "http://127.0.0.1:11434",
"targetLanguage": "de",
"autoSwitchTarget": true,
"fallbackTargetLanguage": "en",
"autoCopy": true,
"unknownFutureKey": "ignored"
}
"""
let decoded = try JSONDecoder().decode(AppSettings.self, from: Data(json.utf8))
#expect(decoded.settingsVersion == AppSettings.currentVersion)
#expect(decoded.targetLanguage == "de")
#expect(decoded.model == HyMT3ModelPreset.defaultModel)
#expect(decoded.languageRoutes.isEmpty)
#expect(decoded.renderMarkdown)
#expect(decoded.closeWithEscape)
#expect(!decoded.autoCopy)
#expect(decoded.maximumPartsPerSelection == 1)
}
@Test func fastModelCanBeClearedExplicitly() throws {
var settings = AppSettings()
settings.fastModel = nil
let encoded = try JSONEncoder().encode(settings)
let decoded = try JSONDecoder().decode(AppSettings.self, from: encoded)
#expect(decoded.fastModel == nil)
let nullJSON = try JSONDecoder().decode(
AppSettings.self,
from: Data(#"{"settingsVersion":1,"fastModel":null}"#.utf8)
)
#expect(nullJSON.fastModel == nil)
}
@Test func invalidValuesAreClampedOrReset() throws {
let json = """
{
"settingsVersion": 0,
"doubleCopyWindowMs": 10,
"maxCharactersLatin": 1,
"maxCharactersCJK": 99999,
"numCtx": 1,
"numPredict": 99999,
"temperature": 9,
"topP": -1,
"topK": 0,
"repeatPenalty": 9,
"keepModelLoaded": "forever",
"translationFontSize": 99,
"targetLanguage": "xx"
}
"""
let decoded = try JSONDecoder().decode(AppSettings.self, from: Data(json.utf8))
#expect(decoded.doubleCopyWindowMs == 300)
#expect(decoded.maxCharactersLatin == 500)
#expect(decoded.maxCharactersCJK == 4000)
#expect(decoded.maximumPartsPerSelection == 1)
#expect(decoded.numCtx == 1024)
#expect(decoded.numPredict == 8192)
#expect(decoded.temperature == 2)
#expect(decoded.topP == 0)
#expect(decoded.topK == 1)
#expect(decoded.repeatPenalty == 2)
#expect(decoded.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
#expect(decoded.translationFontSize == 28)
#expect(decoded.languageRoutes.isEmpty)
#expect(HyMT3Languages.resolve(decoded.targetLanguage) != nil)
}
@Test func sanitizeClampsValuesEditedInTheUI() {
var settings = AppSettings()
settings.doubleCopyWindowMs = 10
settings.temperature = 9
settings.topP = -1
settings.topK = 0
settings.keepModelLoaded = "forever"
settings.translationFontSize = 99
settings.languageRoutes = [
LanguageRoute(source: "xx", target: "en"),
LanguageRoute(source: "de", target: "de"),
LanguageRoute(source: "de", target: "en"),
LanguageRoute(source: "zh-Hans", target: "en"),
]
settings.autoCopy = true
settings.targetLanguage = "de"
settings.maxCharactersCJK = 9999
settings.maximumPartsPerSelection = 99
settings.sanitize()
#expect(settings.doubleCopyWindowMs == 300)
#expect(settings.temperature == 2)
#expect(settings.topP == 0)
#expect(settings.topK == 1)
#expect(settings.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
#expect(settings.translationFontSize == 28)
#expect(settings.maxCharactersCJK == 4000)
#expect(settings.maximumPartsPerSelection == 8)
#expect(settings.languageRoutes == [
LanguageRoute(source: "de", target: "en"),
LanguageRoute(source: "zh", target: "en"),
])
#expect(!settings.autoCopy)
#expect(HyMT3Languages.resolve(settings.targetLanguage) != nil)
}
@Test func endpointPolicyIsEnforced() throws {
var settings = AppSettings()
settings.endpoint = try #require(URL(string: "http://192.168.1.10:11434"))
#expect(throws: EndpointRejection.remoteNotAllowed) {
try settings.validatedEndpoint()
}
settings.allowRemoteEndpoint = true
#expect(throws: EndpointRejection.remoteRequiresHTTPS) {
try settings.validatedEndpoint()
}
settings.endpoint = try #require(URL(string: "https://ollama.example.com"))
#expect(try settings.validatedEndpoint() == settings.endpoint)
}
@Test func recentTargetsAreUniqueAndCappedAtThree() throws {
var settings = AppSettings()
settings.noteTarget(HyMT3Languages.german)
settings.noteTarget(HyMT3Languages.english)
settings.noteTarget(HyMT3Languages.german)
try settings.noteTarget(#require(HyMT3Languages.resolve("fr")))
try settings.noteTarget(#require(HyMT3Languages.resolve("es")))
#expect(settings.recentTargetLanguages.count == 3)
#expect(settings.recentTargetLanguages == ["es", "fr", "de"])
#expect(settings.targetLanguage == "es")
}
}
@Suite("Settings store")
struct SettingsStoreTests {
private func makeStore() -> (SettingsStore, InMemorySettingsDataStore) {
let data = InMemorySettingsDataStore()
return (SettingsStore(storage: data), data)
}
@Test func saveUpdatesTheCache() throws {
let (store, _) = makeStore()
var settings = AppSettings()
settings.targetLanguage = "de"
try store.save(settings)
#expect(store.current() == settings)
}
@Test func valuesSurviveANewStoreOverTheSameBackend() throws {
let data = InMemorySettingsDataStore()
var settings = AppSettings()
settings.targetLanguage = "fr"
settings.hasCompletedOnboarding = true
try SettingsStore(storage: data).save(settings)
let reloaded = SettingsStore(storage: data).current()
#expect(reloaded.targetLanguage == "fr")
#expect(reloaded.hasCompletedOnboarding)
}
@Test func corruptOrUnknownDataFallsBackSafely() {
let data = InMemorySettingsDataStore()
data.set(Data("not json".utf8), forKey: SettingsStore.storageKey)
let store = SettingsStore(storage: data)
#expect(store.current() == AppSettings())
let unknown = Data(#"{"settingsVersion":1,"unknown":"x"}"#.utf8)
data.set(unknown, forKey: SettingsStore.storageKey)
let migrated = SettingsStore(storage: data).current()
#expect(migrated.settingsVersion == AppSettings.currentVersion)
}
@Test func updateAndReset() throws {
let (store, data) = makeStore()
try store.update { $0.targetLanguage = "de" }
#expect(store.current().targetLanguage == "de")
_ = store.reset()
#expect(store.current().targetLanguage == AppSettings().targetLanguage)
#expect(data.data(forKey: SettingsStore.storageKey) == nil)
}
}
@@ -1,4 +1,5 @@
import SprachmittlerCore
import SprachmittlerText
import Testing
@Suite("Capture policy")
@@ -25,4 +26,29 @@ struct CapturePolicyTests {
== .textTooLong(characters: 2001, limit: 2000)
)
}
@Test func partsRaiseTheCaptureLimit() {
let limits = CaptureLimits(maximumParts: 3)
#expect(CapturePolicy.validate(String(repeating: "a", count: 12000), limits: limits) == .valid)
#expect(
CapturePolicy.validate(String(repeating: "a", count: 12001), limits: limits)
== .textTooLong(characters: 12001, limit: 12000)
)
#expect(CapturePolicy.validate(String(repeating: "你", count: 6000), limits: limits) == .valid)
#expect(
CapturePolicy.validate(String(repeating: "你", count: 6001), limits: limits)
== .textTooLong(characters: 6001, limit: 6000)
)
}
@Test func maximumPartsIsAtLeastOne() {
#expect(CaptureLimits(maximumParts: 0).maximumParts == 1)
#expect(CaptureLimits(maximumParts: 0).captureLimit(for: "a") == 4000)
}
@Test func chunkerStillSplitsTheAcceptedText() {
let limits = CaptureLimits(maximumParts: 3)
let text = String(repeating: "a", count: 12000)
#expect(limits.chunker.chunks(for: text).count == 3)
}
}
@@ -0,0 +1,62 @@
import Foundation
import SprachmittlerOllama
import Testing
@testable import SprachmittlerCore
@Suite("User-facing errors")
struct ErrorMessageTests {
@Test func everyErrorHasAMessageAndARecoveryAction() throws {
let url = try #require(URL(string: "http://127.0.0.1:11434"))
let errors: [SprachmittlerError] = [
.noSelection,
.emptyText,
.textTooLong(characters: 5000, limit: 4000),
.pasteboardUnavailable,
.ollamaUnreachable(url: url),
.ollamaTooOld(found: "0.1", required: "0.40"),
.endpointRejected(reason: .remoteNotAllowed),
.modelNotInstalled(model: "m"),
.noAdapter(model: "m"),
.badRequest(message: "raw body"),
.server(status: 500, message: "raw body"),
.timeout(phase: .firstToken),
.emptyOutput,
.truncated,
.repetitionLoop,
.preambleDetected,
.protectedTokenLost(token: "https://example.com"),
.accessibilityNotTrusted,
.accessibilityUnsupported(app: "App"),
.insertionTargetChanged,
.pasteboardRestoreFailed,
.cancelled,
]
for error in errors {
#expect(!error.userMessage.isEmpty)
#expect(!error.userMessage.contains("raw body"))
_ = error.recoveryAction
}
#expect(SprachmittlerError.ollamaUnreachable(url: url).recoveryAction == .startOllama)
#expect(SprachmittlerError.accessibilityNotTrusted.recoveryAction == .openSettings)
}
}
@Suite("Diagnostics store")
struct DiagnosticsStoreTests {
@Test func keepsTheLastFiftyEventsAndClears() async {
let store = DiagnosticsStore(clock: { Date(timeIntervalSince1970: 0) })
for index in 0 ..< 60 {
await store.record(kind: "event-\(index)", durationMs: index, detail: "code")
}
let events = await store.snapshot()
#expect(events.count == DiagnosticsStore.capacity)
#expect(events.first?.kind == "event-10")
#expect(events.last?.kind == "event-59")
#expect(events.allSatisfy { $0.detail == "code" })
await store.clear()
let cleared = await store.snapshot()
#expect(cleared.isEmpty)
}
}
@@ -0,0 +1,169 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
import SprachmittlerTestSupport
import Testing
@testable import SprachmittlerCore
@Suite("Onboarding")
@MainActor
struct OnboardingViewModelTests {
private let hyModel = InstalledModel(name: "hy-mt3", model: "hy-mt3", digest: "abc")
@Test func refreshReportsOllamaAndModel() async {
let store = SettingsStore(storage: InMemorySettingsDataStore())
let catalog = FakeOllamaCatalog(version: "0.40.18", models: [hyModel])
let access = FakeAccessibilityPermission(isTrusted: false)
let model = OnboardingViewModel(
settingsStore: store,
catalogProvider: { _ in catalog },
accessibility: access
)
await model.refresh()
#expect(model.ollama == .ok("0.40.18"))
#expect(model.model == .ok("hy-mt3"))
#expect(!model.accessibilityTrusted)
#expect(!model.isChecking)
}
@Test func missingModelIsAFailedCheck() async {
let store = SettingsStore(storage: InMemorySettingsDataStore())
let other = InstalledModel(name: "llama3", model: "llama3", digest: "x")
let model = OnboardingViewModel(
settingsStore: store,
catalogProvider: { _ in FakeOllamaCatalog(models: [other]) },
accessibility: FakeAccessibilityPermission()
)
await model.refresh()
guard case let .failed(message) = model.model else {
Issue.record("expected a failed model check")
return
}
#expect(message.contains("not installed"))
}
@Test func unreachableOllamaIsAFailedCheck() async {
let store = SettingsStore(storage: InMemorySettingsDataStore())
let model = OnboardingViewModel(
settingsStore: store,
catalogProvider: { _ in throw FailingCatalog() },
accessibility: FakeAccessibilityPermission()
)
await model.refresh()
guard case let .failed(message) = model.ollama else {
Issue.record("expected a failed Ollama check")
return
}
#expect(!message.isEmpty)
}
@Test func targetAndCompletionArePersisted() throws {
let store = SettingsStore(storage: InMemorySettingsDataStore())
let model = OnboardingViewModel(
settingsStore: store,
catalogProvider: { _ in FakeOllamaCatalog() },
accessibility: FakeAccessibilityPermission()
)
model.setTarget(HyMT3Languages.german)
try model.complete()
#expect(store.current().targetLanguage == "de")
#expect(store.current().hasCompletedOnboarding)
}
}
@Suite("Settings view model")
@MainActor
struct SettingsViewModelTests {
private let hyModel = InstalledModel(name: "hy-mt3", model: "hy-mt3", digest: "abc")
@Test func saveValidatesEndpointPersistsAndUpdatesLoginItem() {
let store = SettingsStore(storage: InMemorySettingsDataStore())
let launch = FakeLaunchAtLogin()
let model = SettingsViewModel(
store: store,
catalogProvider: { _ in FakeOllamaCatalog() },
launchAtLogin: launch
)
model.draft.targetLanguage = "de"
model.draft.launchAtLogin = true
model.save()
#expect(model.saveError == nil)
#expect(store.current().targetLanguage == "de")
#expect(launch.requestedValues == [true])
}
@Test func invalidRemoteEndpointIsBlocked() throws {
let store = SettingsStore(storage: InMemorySettingsDataStore())
let model = SettingsViewModel(
store: store,
catalogProvider: { _ in FakeOllamaCatalog() },
launchAtLogin: FakeLaunchAtLogin()
)
model.draft.endpoint = try #require(URL(string: "http://192.168.1.10:11434"))
model.draft.allowRemoteEndpoint = false
model.save()
#expect(model.saveError?.contains("remote") == true)
#expect(store.current().endpoint == AppSettings.defaultEndpoint)
}
@Test func resetRestoresDefaultsAndDisablesLoginItem() {
let store = SettingsStore(storage: InMemorySettingsDataStore())
let launch = FakeLaunchAtLogin(isEnabled: true)
let model = SettingsViewModel(
store: store,
catalogProvider: { _ in FakeOllamaCatalog() },
launchAtLogin: launch
)
model.draft.targetLanguage = "de"
model.save()
model.reset()
#expect(store.current() == AppSettings())
#expect(launch.requestedValues.last == false)
}
@Test func refreshModelsFiltersToHyMT3() async {
let other = InstalledModel(name: "llama3", model: "llama3", digest: "x")
let model = SettingsViewModel(
store: SettingsStore(storage: InMemorySettingsDataStore()),
catalogProvider: { _ in FakeOllamaCatalog(models: [hyModel, other]) },
launchAtLogin: FakeLaunchAtLogin()
)
await model.refreshModels()
#expect(model.installedModels.map(\.name) == ["hy-mt3"])
#expect(model.modelChoices.contains("hy-mt3"))
}
}
private struct FailingCatalog: OllamaCatalog, Error {
private var unreachable: OllamaError {
let url = URLComponents(string: "http://127.0.0.1:11434")?.url ?? URL(fileURLWithPath: "/")
return .unreachable(url)
}
func serverVersion() async throws -> String {
throw unreachable
}
func installedModels() async throws -> [InstalledModel] {
throw unreachable
}
func show(model: String) async throws -> ModelDetails {
throw OllamaError.modelNotInstalled(model)
}
func loadedModels() async throws -> [LoadedModel] {
[]
}
func refresh() async {}
func checkMinimumVersion() async throws {}
}
@@ -0,0 +1,51 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerText
import Testing
@testable import SprachmittlerCore
@Suite("Panel chunk progress")
@MainActor
struct PanelChunkingTests {
private let longCaptured = CapturedText(
text: String(repeating: "a", count: 9000),
capturedAt: Date(timeIntervalSince1970: 0),
source: .doubleCopy
)
@Test func reportsPartsAndProgress() async {
let limits = CaptureLimits(maximumParts: 3)
let streaming = GatedMultiPartStreaming()
let (panel, _, _) = makePanel(streaming: streaming, captureLimits: limits)
await panel.begin(longCaptured)
await waitFor { panel.currentChunk == 1 && panel.totalChunks == 3 && !panel.translation.isEmpty }
#expect(panel.phase == .streaming)
#expect(panel.chunkCount == 1)
await streaming.release()
await waitFor { panel.phase == .ready }
#expect(panel.translation == "part1 part2 part3")
#expect(panel.chunkCount == 3)
#expect(panel.currentChunk == nil)
#expect(panel.totalChunks == nil)
#expect(await streaming.requests.first?.captureLimits == limits)
}
@Test func aSinglePartHasNoProgress() async {
let captured = CapturedText(
text: "Hallo.",
capturedAt: Date(timeIntervalSince1970: 0),
source: .doubleCopy
)
let (panel, _, _) = makePanel(streaming: EchoStreaming())
await panel.begin(captured)
await waitFor { panel.phase == .ready }
#expect(panel.chunkCount == 1)
#expect(panel.currentChunk == nil)
#expect(panel.totalChunks == nil)
}
}
@@ -0,0 +1,191 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerText
import Testing
@testable import SprachmittlerCore
@Suite("Panel language routing")
@MainActor
struct PanelRoutingTests {
private let germanCaptured = CapturedText(
text: "Hallo.",
capturedAt: Date(timeIntervalSince1970: 0),
source: .doubleCopy
)
@Test func appliesAMatchingLanguageRule() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
#expect(panel.effectiveTarget == HyMT3Languages.english)
#expect(panel.routedSource == HyMT3Languages.german)
#expect(panel.configuration.target == HyMT3Languages.german)
#expect(panel.translation == "en")
}
@Test func noRuleKeepsTheMotherTongue() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(streaming: EchoStreaming(), detector: detector)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
#expect(panel.effectiveTarget == HyMT3Languages.german)
#expect(panel.routedSource == nil)
#expect(panel.translation == "de")
}
@Test func routesAnArbitrarySourceLanguage() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "fr", confidence: 0.9, alternatives: ["fr"])
)
let (panel, _, _) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "fr", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
#expect(panel.effectiveTarget == HyMT3Languages.english)
#expect(panel.routedSource == HyMT3Languages.resolve("fr"))
#expect(panel.translation == "en")
}
@Test func routeOverrideIsSessionOnly() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, targets) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
await panel.overrideTarget(HyMT3Languages.german)
await waitFor { panel.phase == .ready && panel.translation == "de" }
#expect(panel.effectiveTarget == HyMT3Languages.german)
#expect(panel.routedSource == nil)
#expect(panel.configuration.target == HyMT3Languages.german)
#expect(targets.codes.isEmpty)
}
@Test func pickerChoosesANonMotherTongueTarget() async {
let (panel, _, targets) = makePanel(streaming: EchoStreaming())
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
await panel.overrideTarget(HyMT3Languages.english)
await waitFor { panel.phase == .ready && panel.translation == "en" }
#expect(panel.effectiveTarget == HyMT3Languages.english)
#expect(panel.routedSource == nil)
#expect(panel.configuration.target == HyMT3Languages.german)
#expect(targets.codes.isEmpty)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready && panel.translation == "de" }
#expect(panel.effectiveTarget == HyMT3Languages.german)
}
@Test func pickerOverridesAMatchingRule() async throws {
let french = try #require(HyMT3Languages.resolve("fr"))
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
#expect(panel.effectiveTarget == HyMT3Languages.english)
await panel.overrideTarget(french)
await waitFor { panel.phase == .ready && panel.translation == "fr" }
#expect(panel.effectiveTarget == french)
#expect(panel.routedSource == nil)
}
@Test func explicitTargetPersistsAndDisablesTheRule() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, targets) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
await panel.setTarget(HyMT3Languages.german)
await waitFor { panel.phase == .ready && panel.translation == "de" }
#expect(targets.codes == ["de"])
#expect(panel.effectiveTarget == HyMT3Languages.german)
#expect(panel.routedSource == nil)
}
@Test func retryKeepsTheManualTarget() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let streaming = EchoStreaming()
let (panel, _, _) = makePanel(
streaming: streaming,
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
await panel.setTarget(HyMT3Languages.german)
await waitFor { panel.phase == .ready && panel.translation == "de" }
await panel.retry()
await waitFor { panel.phase == .ready && panel.translation == "de" }
#expect(panel.effectiveTarget == HyMT3Languages.german)
#expect(await streaming.callCount == 3)
}
@Test func newCaptureReevaluatesTheDirection() async {
let detector = FixedLanguageDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
await panel.overrideTarget(HyMT3Languages.german)
await waitFor { panel.phase == .ready && panel.translation == "de" }
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready && panel.translation == "en" }
#expect(panel.effectiveTarget == HyMT3Languages.english)
#expect(panel.routedSource == HyMT3Languages.german)
}
}
@@ -0,0 +1,198 @@
import Foundation
import SprachmittlerCore
import SprachmittlerEngines
import SprachmittlerText
import Testing
// Shared scaffolding for the panel test suites. The fakes are small and local to the tests.
// The helper returns the panel plus two small test boxes; a struct would add noise here.
// swiftlint:disable large_tuple
@MainActor
func makePanel(
streaming: any TranslationStreaming,
replacement: (@MainActor () async -> InsertionOutcome)? = nil,
onClose: @escaping @MainActor () -> Void = {},
detector: any LanguageDetecting = FixedLanguageDetector(detection: nil),
target: ModelLanguage = HyMT3Languages.german,
routes: [LanguageRoute] = [],
captureLimits: CaptureLimits = CaptureLimits()
) -> (PanelViewModel, CopiedTextBox, TargetBox) {
let session = TranslationSession(pipelineFactory: { streaming })
let copies = CopiedTextBox()
let targets = TargetBox()
let panel = PanelViewModel(
session: session,
configuration: PanelConfiguration(
target: target,
model: "test-hy-mt3",
keepAlive: "30m",
languageRoutes: routes,
captureLimits: captureLimits
),
copy: { copies.text = $0 },
replace: replacement,
onCloseRequest: onClose,
onTargetChanged: { targets.codes.append($0.code) },
detector: detector
)
panel.startObserving()
return (panel, copies, targets)
}
// swiftlint:enable large_tuple
@MainActor
func waitFor(_ condition: @MainActor () -> Bool) async {
for _ in 0 ..< 10000 {
if condition() {
return
}
await Task.yield()
}
Issue.record("panel condition was not reached")
}
func makeResult(
_ translation: String,
warnings: [TranslationWarning] = []
) -> PipelineResult {
PipelineResult(
translation: translation,
warnings: warnings,
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 1
)
}
struct ImmediateStreaming: TranslationStreaming {
let deltas: [String]
let result: PipelineResult
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
for delta in deltas {
await onDelta?(delta)
}
return result
}
}
struct FailingStreaming: TranslationStreaming {
let error: SprachmittlerError
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
throw error
}
}
actor EchoStreaming: TranslationStreaming {
private(set) var callCount = 0
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
callCount += 1
let result = PipelineResult(
translation: request.target.code,
warnings: [],
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 1
)
await onDelta?(result.translation)
return result
}
}
actor CountingStreaming: TranslationStreaming {
private(set) var callCount = 0
let result: PipelineResult
init(result: PipelineResult) {
self.result = result
}
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
callCount += 1
await onDelta?(result.translation)
return result
}
}
final class CopiedTextBox: @unchecked Sendable {
var text: String?
}
final class TargetBox: @unchecked Sendable {
var codes: [String] = []
}
final class ReplaceBox: @unchecked Sendable {
var called = false
}
final class CloseBox: @unchecked Sendable {
var closed = false
}
struct FixedLanguageDetector: LanguageDetecting {
let detection: LanguageDetection?
func detect(_ text: String) -> LanguageDetection? {
detection
}
}
/// A fake that reports three parts and waits after the first until the test releases it.
actor GatedMultiPartStreaming: TranslationStreaming {
private(set) var requests: [TranslationSessionRequest] = []
private var releaseContinuation: CheckedContinuation<Void, Never>?
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
try await translate(request, onDelta: onDelta, onChunk: nil)
}
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?,
onChunk: (@Sendable (Int, Int) async -> Void)?
) async throws -> PipelineResult {
requests.append(request)
await onChunk?(1, 3)
await onDelta?("part1 ")
await withCheckedContinuation { releaseContinuation = $0 }
await onChunk?(2, 3)
await onDelta?("part2 ")
await onChunk?(3, 3)
await onDelta?("part3")
return PipelineResult(
translation: "part1 part2 part3",
warnings: [],
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 3
)
}
func release() async {
while releaseContinuation == nil {
await Task.yield()
}
releaseContinuation?.resume()
releaseContinuation = nil
}
}
@@ -0,0 +1,143 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerText
import Testing
@testable import SprachmittlerCore
@Suite("Panel view model")
@MainActor
struct PanelViewModelTests {
private let captured = CapturedText(
text: "Hello.",
capturedAt: Date(timeIntervalSince1970: 0),
source: .doubleCopy
)
@Test func streamsIntoThePanelAndCopyKeepsItOpen() async {
let (panel, copies, _) = makePanel(
streaming: ImmediateStreaming(deltas: ["Hal", "lo"], result: makeResult("Hallo"))
)
await panel.begin(captured)
await waitFor { panel.phase == .ready }
#expect(panel.translation == "Hallo")
#expect(panel.canCopy)
#expect(!panel.didCopy)
panel.copyTranslation()
#expect(panel.didCopy)
#expect(copies.text == "Hallo")
#expect(panel.phase == .ready)
}
@Test func blockingWarningsDisableReplace() async {
let replaceBox = ReplaceBox()
let (panel, _, _) = makePanel(
streaming: ImmediateStreaming(
deltas: ["Hallo"],
result: makeResult("Hallo", warnings: [.truncated])
),
replacement: {
replaceBox.called = true
return .replaced(using: .accessibility)
}
)
await panel.begin(captured)
await waitFor { panel.phase == .ready }
#expect(panel.blockingWarnings.contains(.truncated))
#expect(!panel.canReplace)
await panel.replaceSelection()
#expect(!replaceBox.called)
}
@Test func cleanResultEnablesReplaceAndClosesOnSuccess() async {
let closeBox = CloseBox()
let (panel, _, _) = makePanel(
streaming: ImmediateStreaming(deltas: ["Hallo"], result: makeResult("Hallo")),
replacement: { .replaced(using: .accessibility) },
onClose: { closeBox.closed = true }
)
await panel.begin(captured)
await waitFor { panel.phase == .ready }
#expect(panel.canReplace)
await panel.replaceSelection()
#expect(closeBox.closed)
}
@Test func sameLanguageWarningCanBeDismissed() async {
let warning = TranslationWarning.sameLanguage(source: "de", target: "de")
let (panel, _, _) = makePanel(
streaming: ImmediateStreaming(
deltas: ["Hallo"],
result: makeResult("Hallo", warnings: [warning])
)
)
await panel.begin(captured)
await waitFor { panel.phase == .ready }
#expect(panel.sameLanguageWarning == warning)
panel.dismissSameLanguageWarning()
#expect(panel.sameLanguageWarning == nil)
}
@Test func changingTargetRetranslatesAndNotifies() async {
let streaming = EchoStreaming()
let (panel, _, targets) = makePanel(streaming: streaming)
await panel.begin(captured)
await waitFor { panel.phase == .ready }
#expect(panel.translation == "de")
await panel.setTarget(HyMT3Languages.english)
await waitFor { panel.phase == .ready && panel.translation == "en" }
#expect(panel.configuration.target == HyMT3Languages.english)
#expect(targets.codes == ["en"])
#expect(await streaming.callCount == 2)
}
@Test func retryUsesTheLastCapture() async {
let streaming = CountingStreaming(result: makeResult("Hallo"))
let (panel, _, _) = makePanel(streaming: streaming)
await panel.begin(captured)
await waitFor { panel.phase == .ready }
await panel.retry()
for _ in 0 ..< 1000 {
if await streaming.callCount == 2 {
break
}
await Task.yield()
}
await waitFor { panel.phase == .ready }
#expect(panel.translation == "Hallo")
#expect(await streaming.callCount == 2)
}
@Test func failureShowsAUserMessage() async {
let error = SprachmittlerError.modelNotInstalled(model: "m")
let (panel, _, _) = makePanel(streaming: FailingStreaming(error: error))
await panel.begin(captured)
await waitFor { panel.phase == .failed }
#expect(panel.error == error)
#expect(panel.errorMessage == error.userMessage)
#expect(panel.recoveryAction == .pullModel("m"))
}
@Test func closeClearsStateAndCancels() async {
let (panel, _, _) = makePanel(
streaming: ImmediateStreaming(deltas: ["Hallo"], result: makeResult("Hallo"))
)
await panel.begin(captured)
await waitFor { panel.phase == .ready }
await panel.close()
#expect(panel.phase == .idle)
#expect(panel.source == nil)
#expect(panel.translation.isEmpty)
#expect(panel.warnings.isEmpty)
}
}
@@ -50,6 +50,70 @@ struct TranslationPipelineTests {
#expect(chat.recorded[1].messages.first?.content.contains("Second paragraph.") == true)
}
@Test func reportsEachChunkBeforeItStarts() async throws {
let chat = SequencedChat(responses: [
[.delta("Erster Absatz."), .done(reason: "stop", metrics: .empty)],
[.delta("Zweiter Absatz."), .done(reason: "stop", metrics: .empty)],
])
let collector = DeltaCollector()
let pipeline = makePipeline(
chat: chat,
chunker: Chunker(latinLimit: 20, denseLimit: 20),
detector: FixedDetector(code: "en", confidence: 0.9)
)
_ = try await pipeline.translate(
text: "First paragraph.\n\nSecond paragraph.",
target: german,
model: model,
keepAlive: "30m",
onChunk: { index, total in await collector.append("\(index)/\(total) ") }
)
#expect(await collector.text == "1/2 2/2 ")
}
@Test func streamedTextIncludesChunkSeparators() async throws {
let chat = SequencedChat(responses: [
[.delta("Erster Absatz."), .done(reason: "stop", metrics: .empty)],
[.delta("Zweiter Absatz."), .done(reason: "stop", metrics: .empty)],
])
let collector = DeltaCollector()
let pipeline = makePipeline(
chat: chat,
chunker: Chunker(latinLimit: 20, denseLimit: 20),
detector: FixedDetector(code: "en", confidence: 0.9)
)
let result = try await pipeline.translate(
text: "First paragraph.\n\nSecond paragraph.",
target: german,
model: model,
keepAlive: "30m",
onDelta: { await collector.append($0) }
)
#expect(await collector.text == result.translation)
#expect(await collector.text == "Erster Absatz.\n\nZweiter Absatz.")
}
@Test func retryDoesNotStreamBothAttempts() async throws {
let chat = SequencedChat(responses: [
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
[.delta("Öffne https://example.com jetzt."), .done(reason: "stop", metrics: .empty)],
])
let collector = DeltaCollector()
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
let result = try await pipeline.translate(
text: "Open https://example.com now.",
target: german,
model: model,
keepAlive: "30m",
onDelta: { await collector.append($0) }
)
#expect(await collector.text == "Öffne jetzt.")
#expect(result.translation == "Öffne https://example.com jetzt.")
}
@Test func retriesOnceWithTheDocumentedDelimitersPrompt() async throws {
let chat = SequencedChat(responses: [
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
@@ -182,6 +246,14 @@ private struct FixedDetector: LanguageDetecting {
}
}
private actor DeltaCollector {
private(set) var text = ""
func append(_ delta: String) {
text += delta
}
}
private struct FailingChat: OllamaChatting {
let error: OllamaError
@@ -0,0 +1,337 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
import SprachmittlerText
import Testing
@testable import SprachmittlerCore
@Suite("Translation session")
struct TranslationSessionTests {
private let request = TranslationSessionRequest(
captured: CapturedText(text: "Hello.", capturedAt: Date(timeIntervalSince1970: 0), source: .doubleCopy),
target: HyMT3Languages.german,
model: "test-hy-mt3",
keepAlive: "30m"
)
@Test func streamsThenFinishes() async {
let streaming = ScriptedStreaming()
let session = TranslationSession(pipelineFactory: { streaming })
var iterator = await session.events().makeAsyncIterator()
await session.start(request)
let started = await iterator.next()
guard case let .started(epoch, _) = started else {
Issue.record("expected started")
return
}
#expect(await streaming.waitForCalls(1))
await streaming.release(
call: 0,
outcome: .success(deltas: ["Hal", "lo"], result: result("Hallo"))
)
var deltas: [String] = []
var finished = false
while let event = await iterator.next() {
switch event {
case let .delta(eventEpoch, text) where eventEpoch == epoch:
deltas.append(text)
case let .finished(eventEpoch, pipelineResult) where eventEpoch == epoch:
#expect(pipelineResult.translation == "Hallo")
finished = true
default:
break
}
if finished {
break
}
}
#expect(deltas == ["Hal", "lo"])
#expect(finished)
}
@Test func newTriggerDropsLateEventsFromTheOldEpoch() async {
let streaming = ScriptedStreaming()
let session = TranslationSession(pipelineFactory: { streaming })
var iterator = await session.events().makeAsyncIterator()
await session.start(request)
_ = await iterator.next() // started A
#expect(await streaming.waitForCalls(1))
let second = TranslationSessionRequest(
captured: CapturedText(text: "Second.", capturedAt: Date(), source: .menu),
target: HyMT3Languages.german,
model: "test-hy-mt3",
keepAlive: "30m"
)
await session.start(second)
_ = await iterator.next() // started B
await streaming.release(call: 0, outcome: .success(deltas: ["old"], result: result("Old")))
#expect(await streaming.waitForCalls(2))
await streaming.release(call: 1, outcome: .success(deltas: ["new"], result: result("New")))
var sawOnlyNew = true
var finished = false
while let event = await iterator.next() {
switch event {
case let .delta(_, text):
if text == "old" {
sawOnlyNew = false
}
case let .finished(_, pipelineResult):
if pipelineResult.translation == "New" {
finished = true
}
default:
break
}
if finished {
break
}
}
#expect(sawOnlyNew)
#expect(finished)
}
@Test func explicitCancelEmitsCancelledForTheOldEpoch() async {
let streaming = ScriptedStreaming()
let session = TranslationSession(pipelineFactory: { streaming })
var iterator = await session.events().makeAsyncIterator()
let epoch = await session.start(request)
_ = await iterator.next() // started
await session.cancel()
let event = await iterator.next()
#expect(event == .cancelled(epoch: epoch))
}
@Test func failuresAreScopedToTheCurrentEpoch() async {
let streaming = ScriptedStreaming()
let session = TranslationSession(pipelineFactory: { streaming })
var iterator = await session.events().makeAsyncIterator()
let epoch = await session.start(request)
_ = await iterator.next()
#expect(await streaming.waitForCalls(1))
await streaming.release(call: 0, outcome: .failure(.modelNotInstalled(model: "m")))
let event = await iterator.next()
#expect(event == .failed(epoch: epoch, error: .modelNotInstalled(model: "m")))
}
@Test func emptyCaptureFailsBeforeTheFactory() async {
let streaming = ScriptedStreaming()
let session = TranslationSession(pipelineFactory: { streaming })
var iterator = await session.events().makeAsyncIterator()
let empty = TranslationSessionRequest(
captured: CapturedText(text: " ", capturedAt: Date(), source: .doubleCopy),
target: HyMT3Languages.german,
model: "test-hy-mt3",
keepAlive: "30m"
)
let epoch = await session.start(empty)
_ = await iterator.next()
let event = await iterator.next()
#expect(event == .failed(epoch: epoch, error: .emptyText))
#expect(await streaming.callCount == 0)
}
@Test func pipelineFactoryErrorsBecomeDomainFailures() async {
let session = TranslationSession(pipelineFactory: {
throw SprachmittlerError.endpointRejected(reason: .remoteNotAllowed)
})
var iterator = await session.events().makeAsyncIterator()
let epoch = await session.start(request)
_ = await iterator.next()
let event = await iterator.next()
#expect(event == .failed(epoch: epoch, error: .endpointRejected(reason: .remoteNotAllowed)))
}
@Test func factoryTransportErrorsAreMapped() async throws {
let url = try #require(URL(string: "http://127.0.0.1:9"))
let session = TranslationSession(pipelineFactory: {
throw OllamaError.unreachable(url)
})
var iterator = await session.events().makeAsyncIterator()
let epoch = await session.start(request)
_ = await iterator.next()
let event = await iterator.next()
#expect(event == .failed(epoch: epoch, error: .ollamaUnreachable(url: url)))
}
@Test func chunkProgressAndRequestLimitsAreForwarded() async {
let streaming = ChunkReportingStreaming()
let session = TranslationSession(pipelineFactory: { streaming })
var iterator = await session.events().makeAsyncIterator()
let longRequest = TranslationSessionRequest(
captured: CapturedText(
text: String(repeating: "a", count: 9000),
capturedAt: Date(),
source: .doubleCopy
),
target: HyMT3Languages.german,
model: "test-hy-mt3",
keepAlive: "30m",
captureLimits: CaptureLimits(maximumParts: 3)
)
let epoch = await session.start(longRequest)
var chunks: [String] = []
var finished = false
while let event = await iterator.next() {
switch event {
case let .chunkStarted(eventEpoch, index, total) where eventEpoch == epoch:
chunks.append("\(index)/\(total)")
case let .finished(eventEpoch, result) where eventEpoch == epoch:
#expect(result.chunkCount == 3)
finished = true
default:
break
}
if finished {
break
}
}
#expect(chunks == ["1/3", "2/3", "3/3"])
#expect(finished)
}
@Test func textAboveTheRequestCaptureLimitFailsBeforeTheFactory() async {
let streaming = ScriptedStreaming()
let session = TranslationSession(pipelineFactory: { streaming })
var iterator = await session.events().makeAsyncIterator()
let tooLong = TranslationSessionRequest(
captured: CapturedText(
text: String(repeating: "a", count: 8001),
capturedAt: Date(),
source: .doubleCopy
),
target: HyMT3Languages.german,
model: "test-hy-mt3",
keepAlive: "30m",
captureLimits: CaptureLimits(maximumParts: 2)
)
let epoch = await session.start(tooLong)
_ = await iterator.next()
let event = await iterator.next()
#expect(event == .failed(epoch: epoch, error: .textTooLong(characters: 8001, limit: 8000)))
#expect(await streaming.callCount == 0)
}
private func result(_ translation: String, warnings: [TranslationWarning] = []) -> PipelineResult {
PipelineResult(
translation: translation,
warnings: warnings,
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 1
)
}
}
/// A fake that reports three chunks and a matching result.
private actor ChunkReportingStreaming: TranslationStreaming {
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
try await translate(request, onDelta: onDelta, onChunk: nil)
}
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?,
onChunk: (@Sendable (Int, Int) async -> Void)?
) async throws -> PipelineResult {
for index in 1 ... 3 {
await onChunk?(index, 3)
await onDelta?("part\(index)")
}
return PipelineResult(
translation: "done",
warnings: [],
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
chunkCount: 3
)
}
}
/// A controlled streaming fake. Each call waits until the test releases its outcome.
private actor ScriptedStreaming: TranslationStreaming {
enum Outcome: Sendable {
case success(deltas: [String], result: PipelineResult)
case failure(SprachmittlerError)
}
private var requests: [TranslationSessionRequest] = []
private var waiters: [Int: CheckedContinuation<Void, any Error>] = [:]
private var outcomes: [Int: Outcome] = [:]
var callCount: Int {
requests.count
}
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
let index = requests.count
requests.append(request)
try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
if outcomes[index] != nil {
continuation.resume()
} else {
waiters[index] = continuation
}
}
} onCancel: {
Task { await self.cancel(index) }
}
guard let outcome = outcomes.removeValue(forKey: index) else {
throw CancellationError()
}
switch outcome {
case let .success(deltas, result):
for delta in deltas {
await onDelta?(delta)
}
return result
case let .failure(error):
throw error
}
}
func release(call index: Int, outcome: Outcome) {
outcomes[index] = outcome
if let waiter = waiters.removeValue(forKey: index) {
waiter.resume()
}
}
func waitForCalls(_ count: Int) async -> Bool {
for _ in 0 ..< 10000 {
if requests.count >= count {
return true
}
await Task.yield()
}
return false
}
private func cancel(_ index: Int) {
if let waiter = waiters.removeValue(forKey: index) {
waiter.resume(throwing: CancellationError())
}
}
}
@@ -0,0 +1,126 @@
import SprachmittlerEngines
import SprachmittlerText
import Testing
@Suite("Translation direction")
struct TranslationDirectionTests {
private let german = HyMT3Languages.german
private let english = HyMT3Languages.english
private func detection(
_ code: String,
confidence: Double = 0.9,
alternatives: [String]? = nil
) -> LanguageDetection {
LanguageDetection(code: code, confidence: confidence, alternatives: alternatives ?? [code])
}
@Test func usesTheMotherTongueWithoutRules() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [],
detection: detection("en"),
override: nil
)
#expect(direction == TranslationDirection(target: german, didRoute: false, source: nil))
}
@Test func appliesAMatchingRule() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: detection("de"),
override: nil
)
#expect(direction == TranslationDirection(target: english, didRoute: true, source: german))
}
@Test func appliesAnArbitrarySourceRule() throws {
let french = try #require(HyMT3Languages.resolve("fr"))
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "fr", target: "en")],
detection: detection("fr"),
override: nil
)
#expect(direction.target == english)
#expect(direction.didRoute)
#expect(direction.source == french)
}
@Test func supportsChineseToEnglish() throws {
let chinese = try #require(HyMT3Languages.resolve("zh"))
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "zh", target: "en")],
detection: detection("zh-Hans"),
override: nil
)
#expect(direction.target == english)
#expect(direction.source == chinese)
}
@Test func keepsTheMotherTongueWhenTheRuleTargetIsTheMotherTongue() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "en", target: "de")],
detection: detection("en"),
override: nil
)
#expect(direction.target == german)
#expect(!direction.didRoute)
}
@Test func ignoresARuleWhoseTargetEqualsItsSource() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "de")],
detection: detection("de"),
override: nil
)
#expect(direction.target == german)
#expect(!direction.didRoute)
}
@Test func ignoresRulesOnLowConfidence() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: detection("de", confidence: 0.49),
override: nil
)
#expect(direction.target == german)
}
@Test func ignoresRulesWhenTheAlternativesDisagree() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: detection("de", alternatives: ["de", "en"]),
override: nil
)
#expect(direction.target == german)
}
@Test func manualOverrideCarriesTheChosenLanguage() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: detection("de"),
override: english
)
#expect(direction.target == english)
#expect(!direction.didRoute)
#expect(direction.source == nil)
}
@Test func noDetectionUsesTheMotherTongue() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: nil,
override: nil
)
#expect(direction.target == german)
}
}
@@ -0,0 +1,275 @@
import Foundation
import SprachmittlerCore
import SprachmittlerEngines
import SprachmittlerOllama
import Testing
@testable import SprachmittlerEval
@Suite("Evaluation metrics")
struct EvaluationMetricsTests {
@Test func identicalTextScoresFullMarks() {
#expect(EvaluationMetrics.chrF(reference: "Hello world", hypothesis: "Hello world") == 100)
#expect(EvaluationMetrics.bleu(reference: "a b c d", hypothesis: "a b c d") == 100)
#expect(EvaluationMetrics.tokenRetention(source: "Hello", translation: "Hello") == 1)
#expect(EvaluationMetrics.numericConsistency(source: "1.5", translation: "1,5") == 1)
}
@Test func disjointTextScoresZero() {
#expect(EvaluationMetrics.chrF(reference: "abc", hypothesis: "xyz") == 0)
#expect(EvaluationMetrics.bleu(reference: "a b c d", hypothesis: "w x y z") == 0)
}
@Test func lostProtectedTokenIsCounted() {
let source = "Open https://example.com and use {{name}}."
#expect(
EvaluationMetrics.tokenRetention(
source: source,
translation: "Öffne https://example.com und nutze {{name}}."
) == 1
)
#expect(
EvaluationMetrics.tokenRetention(
source: source,
translation: "Öffne example.com und nutze name."
) == 0
)
}
@Test func localeNumbersAreNormalised() {
#expect(EvaluationMetrics.numericConsistency(source: "1.5 and 1 000", translation: "1,5 und 1000") == 1)
#expect(EvaluationMetrics.numericConsistency(source: "1.5", translation: "2.5") == 0)
}
}
@Suite("Manifest loading")
struct EvaluationManifestTests {
@Test func loadsRelativePathsAndFiltersTheTarget() throws {
let directory = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
try writeText("Hello.", to: directory.appendingPathComponent("source.txt"))
try writeText("Hallo.", to: directory.appendingPathComponent("reference.txt"))
let manifest = directory.appendingPathComponent("corpus.json")
try writeText(
#"""
{
"version": 1,
"segments": [
{
"id": "seg-1",
"source": "source.txt",
"sourceLanguage": "en",
"targetLanguage": "de",
"category": "en-de-prose",
"reference": "reference.txt",
"referenceKind": "human"
}
]
}
"""#,
to: manifest
)
let resolved = try EvaluationManifestLoader.load(manifestURL: manifest, target: "de")
#expect(resolved.segments.count == 1)
#expect(resolved.segments[0].sourceText == "Hello.")
#expect(resolved.segments[0].referenceText == "Hallo.")
#expect(throws: ManifestError.noMatchingTarget("fr")) {
try EvaluationManifestLoader.load(manifestURL: manifest, target: "fr")
}
}
@Test func rejectsDuplicateIDsAndMissingFiles() throws {
let directory = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
try writeText("x", to: directory.appendingPathComponent("source.txt"))
try writeText("y", to: directory.appendingPathComponent("reference.txt"))
let manifest = directory.appendingPathComponent("corpus.json")
let duplicate = manifestJSON([
segmentJSON(id: "seg-1"),
segmentJSON(id: "seg-1"),
])
try writeText(duplicate, to: manifest)
#expect(throws: ManifestError.duplicateID("seg-1")) {
try EvaluationManifestLoader.load(manifestURL: manifest)
}
let missing = manifestJSON([
segmentJSON(id: "seg-1", source: "missing.txt"),
])
try writeText(missing, to: manifest)
#expect(throws: ManifestError.missingFile(directory.appendingPathComponent("missing.txt").path)) {
try EvaluationManifestLoader.load(manifestURL: manifest)
}
}
@Test func rejectsBadIDsAndReferenceKinds() throws {
let directory = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
try writeText("x", to: directory.appendingPathComponent("source.txt"))
try writeText("y", to: directory.appendingPathComponent("reference.txt"))
let manifest = directory.appendingPathComponent("corpus.json")
let badID = manifestJSON([
segmentJSON(id: "Bad ID"),
])
try writeText(badID, to: manifest)
#expect(throws: ManifestError.invalidID("Bad ID")) {
try EvaluationManifestLoader.load(manifestURL: manifest)
}
let badKind = manifestJSON([
segmentJSON(id: "seg-1", referenceKind: "machine"),
])
try writeText(badKind, to: manifest)
#expect(throws: ManifestError.invalidReferenceKind("machine")) {
try EvaluationManifestLoader.load(manifestURL: manifest)
}
}
}
@Suite("Evaluation runner and report")
struct EvaluationRunnerTests {
@Test func runsSegmentsWritesRawOutputsAndReports() async throws {
let directory = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
try writeText("Hello.", to: directory.appendingPathComponent("source.txt"))
try writeText("Hallo.", to: directory.appendingPathComponent("reference.txt"))
let manifestURL = directory.appendingPathComponent("corpus.json")
try writeText(manifestJSON([segmentJSON(id: "seg-1")]), to: manifestURL)
let manifest = try EvaluationManifestLoader.load(manifestURL: manifestURL)
let output = directory.appendingPathComponent("results")
let configuration = EvaluationConfiguration(
models: ["test-model"],
runs: 1,
outputDirectory: output
)
let runner = EvaluationRunner(
manifest: manifest,
configuration: configuration,
environment: EvaluationEnvironment(
serverVersion: "0.40.18",
ollamaVersion: "0.40.18",
hardware: "Test",
macOS: "Test",
models: ["test-model": "abcdef"]
),
pipelineFactory: { _ in ImmediateStreaming(translation: "Hallo.") },
warmUp: { _ in },
unload: { _ in }
)
let report = try await runner.run()
#expect(report.models.count == 1)
#expect(report.models[0].categories.count == 1)
#expect(report.models[0].categories[0].failureRate == 0)
#expect(report.models[0].categories[0].chrF == 100)
#expect(FileManager.default.fileExists(atPath: output.appendingPathComponent("report.md").path))
#expect(FileManager.default.fileExists(atPath: output.appendingPathComponent("report.json").path))
#expect(FileManager.default.fileExists(
atPath: output.appendingPathComponent("test-model/seg-1-run0.txt").path
))
let markdown = try String(
contentsOf: output.appendingPathComponent("report.md"),
encoding: .utf8
)
#expect(markdown.contains("## Environment"))
#expect(markdown.contains("| test-model |"))
}
@Test func failureIsReportedAsAFailure() async throws {
let directory = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
try writeText("Hello.", to: directory.appendingPathComponent("source.txt"))
try writeText("Hallo.", to: directory.appendingPathComponent("reference.txt"))
let manifestURL = directory.appendingPathComponent("corpus.json")
try writeText(manifestJSON([segmentJSON(id: "seg-1")]), to: manifestURL)
let manifest = try EvaluationManifestLoader.load(manifestURL: manifestURL)
let runner = EvaluationRunner(
manifest: manifest,
configuration: EvaluationConfiguration(
models: ["test-model"],
runs: 1,
outputDirectory: directory.appendingPathComponent("results")
),
environment: EvaluationEnvironment(
serverVersion: "v",
ollamaVersion: "v",
hardware: "h",
macOS: "m",
models: [:]
),
pipelineFactory: { _ in FailingStreaming() },
warmUp: { _ in },
unload: { _ in }
)
let report = try await runner.run()
#expect(report.models[0].categories[0].failureRate == 100)
#expect(report.models[0].segments[0].failed)
}
}
private func manifestJSON(_ segments: [[String: String]]) -> String {
let object: [String: Any] = ["version": 1, "segments": segments]
guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let text = String(data: data, encoding: .utf8)
else {
return "{}"
}
return text
}
private func segmentJSON(
id: String,
source: String = "source.txt",
reference: String = "reference.txt",
referenceKind: String = "human"
) -> [String: String] {
[
"id": id,
"source": source,
"sourceLanguage": "en",
"targetLanguage": "de",
"category": "en-de-prose",
"reference": reference,
"referenceKind": referenceKind,
]
}
private func makeTemporaryDirectory() throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("sprachmittler-eval-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
}
private func writeText(_ text: String, to url: URL) throws {
try text.write(to: url, atomically: true, encoding: .utf8)
}
private struct ImmediateStreaming: TranslationStreaming {
let translation: String
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
PipelineResult(
translation: translation,
warnings: [],
sourceLanguage: request.captured.source.rawValue,
timing: TranslationTiming(firstTokenMs: 10, totalMs: 20, promptTokens: 3, outputTokens: 4),
chunkCount: 1
)
}
}
private struct FailingStreaming: TranslationStreaming {
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
throw SprachmittlerError.modelNotInstalled(model: request.model)
}
}
@@ -13,6 +13,8 @@ struct LanguageDetectorTests {
)
#expect(detection.code == "de")
#expect(detection.confidence > 0.5)
#expect(detection.alternatives.contains("de"))
#expect(detection.alternatives.count == 1)
}
@Test func detectsEnglish() throws {
@@ -0,0 +1,106 @@
import Foundation
import Testing
@testable import SprachmittlerText
@Suite("Markdown presentation")
struct MarkdownPresentationTests {
@Test func parsesHeadingsParagraphsAndRules() {
let blocks = MarkdownPresentation.blocks(in: """
# Title
First paragraph.
Second line.
---
""")
#expect(blocks == [
.heading(level: 1, text: "Title"),
.paragraph("First paragraph.\nSecond line."),
.rule,
])
}
@Test func parsesOrderedAndUnorderedLists() {
let blocks = MarkdownPresentation.blocks(in: """
- one
* two
3. three
4) four
""")
#expect(blocks == [
.listItem(ordered: false, number: 0, indent: 0, text: "one"),
.listItem(ordered: false, number: 0, indent: 0, text: "two"),
.listItem(ordered: true, number: 3, indent: 0, text: "three"),
.listItem(ordered: true, number: 4, indent: 0, text: "four"),
])
}
@Test func parsesQuotesAndFencedCode() {
let blocks = MarkdownPresentation.blocks(in: """
> quoted **text**
> second
```swift
let value = 1
```
""")
#expect(blocks == [
.quote("quoted **text**\nsecond"),
.codeBlock(language: "swift", text: "let value = 1"),
])
}
@Test func keepsUnclosedFenceAsCode() {
let blocks = MarkdownPresentation.blocks(in: "```\nstill code\n")
#expect(blocks == [.codeBlock(language: nil, text: "still code")])
}
@Test func recognisesInlineFormatting() {
let attributed = MarkdownPresentation.inline("**bold** and *italic* and `code`")
let intents = attributed.runs.compactMap(\.inlinePresentationIntent)
#expect(intents.contains { $0.contains(.stronglyEmphasized) })
#expect(intents.contains { $0.contains(.emphasized) })
#expect(intents.contains { $0.contains(.code) })
}
@Test func parsesLinksButNeverImages() throws {
let attributed = MarkdownPresentation
.inline("See [docs](https://example.com) and ![alt](https://example.com/x.png)")
let links = attributed.runs.compactMap(\.link)
#expect(try links == [#require(URL(string: "https://example.com"))])
#expect(String(attributed.characters).contains("alt"))
#expect(!String(attributed.characters).contains("x.png"))
}
@Test func malformedMarkdownFallsBackToText() {
let attributed = MarkdownPresentation.inline("**unclosed and <unterminated")
#expect(String(attributed.characters).contains("unclosed"))
}
@Test func onlyHTTPLinksAreAllowed() throws {
#expect(try MarkdownPresentation.isAllowedLink(#require(URL(string: "https://example.com"))))
#expect(try MarkdownPresentation.isAllowedLink(#require(URL(string: "http://example.com"))))
#expect(try !MarkdownPresentation.isAllowedLink(#require(URL(string: "file:///etc/passwd"))))
#expect(try !MarkdownPresentation.isAllowedLink(#require(URL(string: "javascript:alert(1)"))))
#expect(try !MarkdownPresentation.isAllowedLink(#require(URL(string: "sprachmittler://open"))))
}
@Test func rendersMarkdownSourcesButNotStructuredData() {
#expect(MarkdownPresentation.shouldRender(source: "# Title\n\n- item", translation: "x"))
#expect(MarkdownPresentation.shouldRender(source: "A **bold** sentence.", translation: "x"))
#expect(MarkdownPresentation.shouldRender(source: "plain", translation: "translated **bold**"))
#expect(!MarkdownPresentation.shouldRender(source: #"{"key": "value"}"#, translation: "x"))
#expect(!MarkdownPresentation.shouldRender(source: "<div><p>Hello</p></div>", translation: "x"))
#expect(!MarkdownPresentation.shouldRender(source: "```\nlet x = 1\n```", translation: "x"))
#expect(!MarkdownPresentation.shouldRender(source: "Just prose, no markers.", translation: "Nur Prosa."))
#expect(!MarkdownPresentation.shouldRender(source: "", translation: "**bold**"))
}
@Test func headingsWithDifferentLevelsAndClosingHashes() {
let blocks = MarkdownPresentation.blocks(in: "### Sub heading ###\n\n####### not a heading")
#expect(blocks == [
.heading(level: 3, text: "Sub heading"),
.paragraph("####### not a heading"),
])
}
}
+192 -104
View File
@@ -1,129 +1,217 @@
# Sprachmittler: OpenCode 2.x starter kit
# Sprachmittler
Sprachmittler is a native macOS menu-bar app for Apple Silicon. Select text in any app, press **⌘C twice**, and a small floating panel shows a translation produced by Tencent's **Hy-MT3-7B** translation model running locally through **Ollama**. The panel has **Copy** and an explicit **Replace** button in the lower right corner; nothing is ever replaced automatically.
Sprachmittler is a native macOS menu-bar app for Apple Silicon. Select text in any app, press **⌘C twice**, and a floating panel shows a translation from Tencent's **Hy-MT3** model running locally through **Ollama**. Copy it, or click **Replace** to put it over the selection. Nothing is replaced automatically, and nothing leaves your Mac by default.
This repository is the development kit for building the app with **OpenCode 2.x**. It contains the architecture, specifications, a task plan, an evaluation design, OpenCode agents, commands and skills in native V2 format, and a compilable scaffold.
It is the companion to **Schriftleser** and **Vorleser**: Vorleser reads text aloud, Schriftleser turns documents into text, and Sprachmittler translates the text you select.
Sprachmittler is the companion to Schriftleser and Vorleser: Vorleser reads text aloud, Schriftleser reads documents into text, Sprachmittler translates the text you select.
A user-facing installation, permission and troubleshooting guide is in [docs/USER_GUIDE.md](docs/USER_GUIDE.md).
## Features
**Translate**
- Double-copy trigger in any app: select, **⌘C**, **⌘C**.
- Streaming translations from a local Hy-MT3 model; no cloud API.
- 102 supported languages with a language picker and recent targets.
- Language routing: a mother tongue default (e.g. everything to German) plus optional source-to-target rules (e.g. Chinese → English).
- Markdown rendering for headings, bold, italic, lists, quotes, code and links.
- Configurable translation text size, source-preview toggle and an optional Fast model preset.
**The panel**
- Non-activating floating panel: the source app stays frontmost and keeps the menu bar.
- Draggable full-width header; the panel keeps its position while open and appears near the cursor when shown again.
- **Esc** closes it without clicking first; a click outside closes it too.
- Copy, Retry and explicit **Replace**, with validation warnings that disable Replace when the output is unsafe.
**System integration**
- Menu-bar actions: Translate Clipboard Text, target language, Copy Last Translation, Replace Last Translation, Settings, onboarding, diagnostics and Quit.
- macOS **Services** item: "Translate with Sprachmittler".
- First-run onboarding checks Ollama, the model and the optional Accessibility permission.
- Accessibility is used only for Replace and is never required for translation or Copy.
**Privacy**
- Local Ollama endpoint by default; a remote endpoint needs an explicit toggle and HTTPS.
- No history, telemetry or account. Source text and translations are never written to disk.
- No global key taps and no Input Monitoring.
## Requirements
| Requirement | Details |
|---|---|
| Mac | Apple Silicon, macOS 14 Sonoma or later |
| Ollama | Current release; verified with 0.40.18 |
| Translation model | `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` (about 5.15 GB, 16 GB unified memory recommended) |
| Fast preset (optional) | `hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M` (about 1.35 GB) |
| Accessibility | Optional; needed only for Replace |
| Build tools | Xcode 16 or later, Homebrew, XcodeGen, SwiftFormat and SwiftLint (`make bootstrap`) |
| OpenCode | Optional; **2.x** only when using the repository's agent workflow |
## Install from source
```bash
git clone <repository-url>
cd Sprachmittler
make bootstrap
```
Start Ollama and download the model once:
```bash
ollama serve
ollama pull hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M
```
Then build, install and launch the Release app:
```bash
make install
```
`make install` builds the Release configuration, replaces `/Applications/Sprachmittler.app` and opens it. For a local disk image instead:
```bash
make dmg
```
The DMG is ad-hoc signed for local use, not notarised. The app runs from the menu bar and has no Dock icon; open it and follow the first-run onboarding.
For a Debug build during development:
```bash
make app
```
## Usage
1. Select text in Safari, Mail, Notes, an editor or any other app.
2. Press **⌘C** twice quickly. The double-copy window is 500 ms by default and configurable.
3. The panel appears near the cursor and the translation streams in.
4. **Copy** puts the translation on the clipboard. **Replace** overwrites the selection only when you click it.
5. **Esc** or a click outside closes the panel.
The panel takes keyboard focus while it is visible by default, so Esc and the shortcuts work immediately. The app itself is not activated: the source app stays frontmost, and clicking it returns keyboard focus. The **Close with Esc without clicking** setting turns the focus-taking behaviour off.
| Action | Shortcut |
|---|---|
| Translate the selection | **⌘C** twice |
| Close the panel | **Esc**, or click outside |
| Copy the translation | **⌘C** |
| Retry | **⌘R** |
| Replace the selection | **⌘↩** |
| Settings | **⌘,** |
### Mother tongue and language rules
The **mother tongue** is the default target for every source. In **Settings ▸ General ▸ Translation** you can add **language rules** that override it for a specific source language, for example:
```text
Mother tongue: German
Chinese (Simplified) → English
Traditional Chinese → English
German → English
```
With no rules, every language goes to the mother tongue. Rules apply only when the source is confidently detected; otherwise the mother tongue is used. The panel header shows the effective direction, a banner explains a rule and offers a one-capture override, and the panel language picker is a session-only override. Persistent rules live in Settings.
### Markdown
When the source looks like Markdown and **Settings ▸ General ▸ Translation ▸ Render Markdown formatting** is on (the default), the translation is rendered with headings, bold, italic, lists, quotes, fenced code and links. JSON, HTML and code sources are never Markdown-rendered. **Copy** and **Replace** always use the raw Markdown translation, not the rendered text. Only `http` and `https` links open, and only on an explicit click.
### Replace
Replace verifies the source app and, when available, the selected text before touching it. It prefers a direct Accessibility write and falls back to a clipboard snapshot plus synthetic paste. Blocking validation warnings — a likely preamble, truncation, a repetition loop or a lost protected token — disable Replace by default. The previous clipboard is restored after the fallback paste when it is still safe to do so.
### Settings
- **General** — mother tongue, language rules, source preview, Markdown rendering, translation text size, Esc behaviour, double-copy window and startup.
- **Model** — model and Fast preset, Ollama endpoint, sampling and context settings.
- **Translation** — part size, maximum parts per selection and prompt policy. One part (the default) rejects longer text; higher values translate long selections sequentially and the panel shows the part progress.
- **Privacy** — local/remote endpoint policy and permissions.
- **Diagnostics** — server version, model digests, the last 50 timings and error kinds. No text or translations.
## Privacy
- The default endpoint is `http://127.0.0.1:11434`. A non-loopback endpoint requires an explicit setting and HTTPS.
- Source text, translations and pasteboard contents are never written to disk and are not kept as history.
- The clipboard snapshot for a Replace fallback lives in memory for that one replacement and is restored.
- Logs contain counts, timings, short hashes and error kinds, never the selected text or the translation.
- Markdown links are restricted to `http`/`https`; remote images are never fetched.
- The app does not install a key tap and never requests Input Monitoring. While the panel is visible, a transient mouse-down monitor dismisses it when a click goes to another app; the event is discarded and the monitor is removed when the panel closes.
The hard requirements are listed in [docs/SECURITY_PRIVACY.md](docs/SECURITY_PRIVACY.md).
## How it works
1. Select text in Safari, Mail, Word, Notes, an editor or any other app.
2. Press **⌘C** twice quickly (the DeepL-style double copy).
3. A non-activating panel appears; the source app keeps the keyboard focus.
4. The translation streams in while the local Hy-MT3 model works.
5. **Copy** puts the translation on the clipboard. **Replace** replaces the selected text with the translation — only when you click it.
6. **Esc** closes the panel. **⌘Z** in the source app undoes a Replace in apps that support undo.
```text
select text → ⌘C twice → pasteboard capture → validate → chunk
→ documented Hy-MT3 prompt → Ollama /api/chat (streaming)
→ validate → floating panel
```
Nothing is sent anywhere except the configured Ollama endpoint, which is `http://127.0.0.1:11434` by default. There is no history, no telemetry and no account.
The app is a menu-bar agent (`LSUIElement`) with a non-activating `NSPanel`. Replace re-verifies the frontmost app and the selected text before inserting. The translation pipeline, capture/insertion seams and UI state models are separate modules so they can be tested without the UI.
## Prerequisites
| Requirement | Version |
| Module | Responsibility |
|---|---|
| Apple Silicon Mac | macOS 14 Sonoma or later; 16 GB unified memory recommended for the 7B model |
| Xcode | 16 or later (Swift 6) |
| Ollama | current release; this kit was verified with 0.40.18 |
| Translation model | `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` (about 5.15 GB); optional fast model `hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M` (about 1.35 GB) |
| Homebrew | for `xcodegen`, `swiftformat`, `swiftlint`, `xcbeautify`, `ripgrep`, `jq` |
| OpenCode | **2.x** (check with `opencode --version`) |
| `App/` | Menu-bar app, panel, settings, onboarding, diagnostics and composition root |
| `Packages/SprachmittlerKit/` | Translation pipeline, prompt adapters, Ollama client, capture/insertion, text utilities and tests |
| `docs/` | Architecture, product requirements, model/API contracts, privacy, testing and decisions |
| `scripts/` | Build, verification, privacy, fixture, icon and release helpers |
| `evaluation/` | Corpus manifest schema, metrics and report format; the corpus itself stays out of git |
## Getting started
See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for the full design.
## Status
Sprachmittler is at **0.1.0**. M0–M8 are implemented, `make verify` is green, and local install and DMG builds are verified.
The 7B model is the provisional default; the default model and prompt policy are decided by the evaluation gate in [docs/MODEL_EVALUATION.md](docs/MODEL_EVALUATION.md). Manual macOS-only checks remain for the double-copy and insertion matrices, VoiceOver, and the 10-app compatibility matrix. Current task state is in [docs/PROGRESS.md](docs/PROGRESS.md).
Local builds are ad-hoc signed. `make release` is the Developer ID and notarisation path and needs the corresponding credentials.
## Development
```bash
git init && git add -A && git commit -m "chore: Sprachmittler OpenCode kit"
make bootstrap # installs xcodegen, swiftformat, swiftlint, jq, ripgrep
ollama pull hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M # about 5.15 GB
make smoke # translates one fixed synthetic sentence
make doctor # checks OpenCode 2.x and the resolved V2 config
make verify # the scaffold should already build and test
make app # builds and launches Sprachmittler.app
opencode # start OpenCode in the repo root
make bootstrap # install xcodegen, swiftformat, swiftlint, jq and ripgrep if missing
make doctor # check OpenCode 2.x and the resolved V2 configuration
make generate # regenerate Sprachmittler.xcodeproj from project.yml
make build # swift build plus the Debug app target
make test # package unit, contract and component tests
make app # build and launch the Debug app
make verify # format, lint, privacy, tests, Debug + Release builds
make install # build Release, install in /Applications and launch
make dmg # local unnotarised DMG from the Release build
make smoke # translate one fixed synthetic sentence
make live-test # tests against a real local Ollama
make fixtures # capture Ollama fixtures
make manifest # regenerate MANIFEST.sha256
make release # signed/notarised release dry-run; needs credentials
```
Then paste the prompt from `docs/KICKOFF.md` into OpenCode, or simply run:
The package builds and tests without Xcode UI:
```text
/next
```bash
swift build --package-path Packages/SprachmittlerKit
swift test --package-path Packages/SprachmittlerKit
```
The **Replace** button needs the macOS Accessibility permission. The app asks for it only when you use Replace; double-copy, translation and Copy work without any permission.
`swift run --package-path Packages/SprachmittlerKit sprachmittler-cli --help` exposes the language catalogue, model inspection, translation and evaluation commands.
## What's inside
### Working with OpenCode
| Path | Purpose |
|---|---|
| `AGENTS.md` | Project rules OpenCode loads automatically: commands, workflow, non-negotiables, doc map |
| `opencode.json` | Native OpenCode 2.x config: loads `docs/CODING_STANDARDS.md` and defines an ordered `permissions` list |
| `.opencode/agents/` | `architect` (plans, read-only), `swift-reviewer` (reviews, read-only), `test-engineer` (tests and fakes only), `translation-evaluator` (runs evaluations) |
| `.opencode/commands/` | `/next`, `/task T2.2`, `/plan …`, `/verify`, `/review`, `/adr …`, `/status`, `/manual-test …`, `/evaluate …` |
| `.opencode/skills/` | `translation-quality` (prompt fidelity, validation, judging output), `selection-capture` (double copy, pasteboard, insertion, permissions) |
| `docs/ARCHITECTURE.md` | Authoritative design: modules, capture/insertion flow, session state machine, budgets, risks |
| `docs/PRD.md` | User stories, requirements R001–R050, acceptance criteria |
| `docs/IMPLEMENTATION_PLAN.md` | 9 milestones (M0–M8), about 50 tasks, each with acceptance criteria and traceability |
| `docs/KICKOFF.md` | Ready-to-paste prompts for the first session and checkpoints |
| `docs/PROGRESS.md` | Checklist the agent updates after each task |
| `docs/HYMT3_MODEL.md` | Model tags, licence, all documented prompt templates, sampling, performance |
| `docs/OLLAMA_TRANSLATION_API.md` | HTTP contract for `/api/chat`, options mapping, error mapping, fixtures |
| `docs/SELECTION_AND_CLIPBOARD.md` | Double-copy algorithm, pasteboard restoration, Accessibility replacement, compatibility matrix |
| `docs/TRANSLATION_OUTPUT.md` | Prompt selection, chunking, protective token validation, output rules T1–T4 |
| `docs/LANGUAGES.md` | The 102 supported languages and their exact model names |
| `docs/SECURITY_PRIVACY.md` | Privacy invariants SP-1…SP-15, checked by `scripts/privacy-check.sh` |
| `docs/MODEL_EVALUATION.md` | Corpus, metrics, report format and the default-model gate |
| `docs/TESTING.md` | Test layers, required cases, manual release checklist |
| `docs/DECISIONS.md` | ADR-001…ADR-015 |
| `docs/CODING_STANDARDS.md` | Swift 6 concurrency, structure, logging, UI, style |
| `docs/OPENCODE_V2.md` | Why the OpenCode files look the way they do, and how to check them |
| `docs/PERFORMANCE.md` | Reference measurements and budgets |
| `evaluation/` | Corpus manifest schema and example; the corpus itself stays out of git |
| `project.yml` | XcodeGen spec for the app target |
| `Packages/SprachmittlerKit/` | SwiftPM package with module placeholders, test targets and synthetic fixtures |
| `App/` | Menu-bar app stubs, `Info.plist` (Services, ATS), non-sandboxed entitlements |
| `scripts/` | `bootstrap`, `verify`, `privacy-check`, `opencode-check`, `smoke-ollama`, `capture-fixtures`, `manifest` |
The repository is set up for the **OpenCode 2.x** development workflow. `AGENTS.md` contains the rules the agent loads, `opencode.json` is the native V2 config, and `.opencode/` contains the agents, commands and skills. Use `/next` for the next open task, `/task T4.2` for a named task, and `/verify` before calling work done. [docs/OPENCODE_V2.md](docs/OPENCODE_V2.md) explains the configuration and how to check it.
## The canonical prompt
OpenCode is a development tool. The app builds and runs without it.
All translation prompts live in `SprachmittlerEngines`. The default is Tencent's documented English template, byte for byte:
### Forking
```text
Translate the following text into {target_lang}. Note that you should **only output the translated result without any additional explanation**:
- Set your bundle identifier in `project.yml` (the default `de.schihei.sprachmittler` is a placeholder).
- Change model tags in `docs/HYMT3_MODEL.md` and the preset definitions in `SprachmittlerEngines`.
- Use your own Developer ID and notarisation credentials for `make release`.
- Do not commit `Sprachmittler.xcodeproj`, build products, `evaluation/corpus/` or evaluation results.
{source_text}
```
`{target_lang}` is the full English language name from the model card (for example `German`, `Chinese`, `Traditional Chinese`). The prefix is kept stable so Ollama can reuse its prompt cache; only the target language and the source text change. The model has no default system prompt, and the app sends none.
## Recommended way to work with OpenCode
1. **One task per session.** `/task T2.2` keeps context small and focused.
2. **Headless first.** M1–M2 build the Ollama client, the Hy-MT3 adapter, the language catalogue, chunking and validation. `sprachmittler-cli translate` gives you a working translation engine before any UI exists.
3. **Capture real fixtures early (T1.1).** The exact `/api/show` output, streaming shapes and prompt-cache behaviour are recorded from your Ollama. Recorded fixtures stop the agent from guessing.
4. **Measure before choosing.** The 7B is the provisional default; T7.4 is the evaluation gate. The 1.8B may be the better everyday choice on smaller Macs.
5. **You are the test rig for macOS-only behaviour.** Double copy, panel focus, Accessibility replacement, clipboard restoration, Services and VoiceOver need a human. Use `/manual-test <feature>` and report results back.
6. **Review gate.** `/next` already calls `@swift-reviewer`. Run `/review` yourself before committing larger changes.
7. **Record decisions.** When you deviate from the architecture, run `/adr <title>` so the docs stay true.
## Placeholders to change
- Bundle ID prefix `de.schihei` in `project.yml`.
- App name "Sprachmittler" if you prefer another. Search the repo for `Sprachmittler`.
- The default model tag in `docs/HYMT3_MODEL.md` and `docs/PROGRESS.md` once T7.4 is decided.
- Model tags for the fast preset once the 1.8B conversion has been verified on your Ollama.
## Licensing note
## Licensing
Sprachmittler bundles no models. Hy-MT3 is published by Tencent under **Apache-2.0**; the GGUF conversions used here are published by Tencent on Hugging Face. Settings shows the licence and the model digest. Re-check the model card before commercial distribution. The 30B-A3B model is not a preset: it needs far more memory than a 16 GB Mac has.
## Kit verification status (2026-11-26)
What was checked when the kit was assembled:
- `swift build` and `swift test --skip SprachmittlerLiveTests` pass for `Packages/SprachmittlerKit` with Swift 6.4.2 on macOS 27.2.1 (arm64).
- `xcodegen generate` and the Debug app build pass with Xcode 27.2.
- `scripts/privacy-check.sh` and `scripts/opencode-check.sh` (static part) pass; all scripts pass `bash -n`.
- `opencode.json`, the evaluation schema and the example parse as JSON; `plutil` accepts the Info.plist and entitlements.
- `make smoke` translated the fixed synthetic sentence into German with `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` on Ollama 0.40.18: 34 output tokens in 2.89 s, 45.81 tokens/s, cold load 2.05 s.
- The canonical prompt on the longer Hy-MT3 figure caption: 246 output tokens in 6.52 s, 44.6 tokens/s; 6.49 GB resident with `num_ctx` 8192.
- The owner's reference run with the same model: 255 output tokens, 43.07 tokens/s, 5.97 s warm, 177/178 prompt tokens cached.
Not yet checked: the double-copy gesture, panel focus, Accessibility replacement, clipboard restoration, Services, VoiceOver and real-world translation quality. Those are manual tasks in `docs/TESTING.md` and the compatibility matrices.
+19 -10
View File
@@ -143,7 +143,7 @@ flowchart TD
- `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.
- `SprachmittlerEval` is linked into the CLI only, never into the app. It may use the leaf `SprachmittlerText`, `SprachmittlerEngines` and `SprachmittlerOllama` types for metrics and pipeline construction; it does not add an app dependency.
- `sprachmittler-cli` links `SprachmittlerOllama` and `SprachmittlerEngines` directly for the M1 commands; it is never linked into the app.
- `SprachmittlerTestSupport` is test-only and depends on `SprachmittlerCore`, `SprachmittlerCapture` and `SprachmittlerOllama`; it is never linked into the app.
- The `App` target holds no business logic. Anything with a branch worth testing belongs in a package module.
@@ -359,7 +359,7 @@ public struct DoubleCopyDetector { /* pure state machine */ }
- Poll `NSPasteboard.general.changeCount` every **120 ms** on the main actor through `PasteboardTicking`.
- A candidate trigger is two changes within **500 ms** (range 300–1000 ms, setting) whose `.string` values are identical and non-empty after trimming.
- Require at least one non-whitespace character and at most `maxCharacters` (4000 Latin / 2000 CJK by default).
- Require at least one non-whitespace character and at most the capture limit (`maxCharacters` per part × `maximumPartsPerSelection`: 4000/2000 Latin/dense by default, one part).
- Ignore changes whose pasteboard contains the app's own marker (`com.schihei.sprachmittler.own`) or `org.nspasteboard.TransientType`, and ignore all changes for 750 ms after our own write.
- Keep only the last two strings and their hashes in memory; clear them after the window or after the session starts.
- Do not log the text. Log only `changeCount` deltas and a short hash at `privacy: .private`.
@@ -483,7 +483,7 @@ Full detail: `docs/TRANSLATION_OUTPUT.md`.
2. Detect the source language with `NLLanguageRecognizer` for display only. The prompt does not need it.
3. Classify content: `.plain`, `.markdown`, `.json`, `.html`, `.code`, `.delimited` (many URLs/placeholders).
4. Scan protected tokens: URLs, e-mail addresses, `{{var}}`, `${var}`, `%s`, `%d`, `%1$@`, Markdown code spans, fenced code blocks, HTML tags, JSON keys.
5. Plan chunks: paragraph boundaries first, then sentence, then word; script-aware limits (4000 characters for Latin/Cyrillic/Greek, 2000 for CJK/Arabic/Hebrew/Devanagari etc.). Never split a grapheme cluster.
5. Plan parts: paragraph boundaries first, then sentence, then word; script-aware part sizes (4000 characters for Latin/Cyrillic/Greek, 2000 for CJK/Arabic/Hebrew/Devanagari etc.). Never split a grapheme cluster. The capture gate accepts up to `maximumPartsPerSelection` parts.
### 9.2 Prompt selection (`SprachmittlerEngines`)
@@ -516,7 +516,7 @@ If the detected source language equals the target with reasonable confidence, th
## 10. Translation session and state machine
`TranslationSession` is an actor in `SprachmittlerCore`; `PanelViewModel` is `@MainActor @Observable` and mirrors it.
`TranslationSession` is an actor in `SprachmittlerCore`; `PanelViewModel` is `@MainActor @Observable` in Core and mirrors it. The App target owns the non-activating `NSPanel` controller.
```mermaid
stateDiagram-v2
@@ -540,7 +540,7 @@ stateDiagram-v2
- 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.
- The session owns no disk state. Its working copy is released when the panel closes; `AppEnvironment` may keep the last source, translation and insertion target in memory until quit, solely for the status menu's Copy/Replace Last actions (ADR-007). Nothing is written to disk.
---
@@ -549,12 +549,14 @@ stateDiagram-v2
| 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) |
| Panel | `NSPanel` with `.nonactivatingPanel`, `becomesKeyOnlyIfNeeded = false` | Header (source → target, language picker, gear), collapsible source preview, streaming translation (Markdown rendered when detected), warnings, Copy (left) and **Replace** (right, primary) |
| Settings | SwiftUI `Settings` scene | General, Model, Translation, Privacy, Diagnostics |
| Onboarding | `NSWindow` (not a SwiftUI `Window` scene) | Ollama reachable + version, Hy-MT3 installed, target language, optional Accessibility for Replace; each with a fix button |
| Diagnostics | Window from the menu | Server version, model digests, last 50 timings and error kinds; copy as text; no text or translations |
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.
The saved target is the **mother tongue** and the default target for every source. Optional source-language to target-language rules override it when the source is confidently detected; otherwise the mother tongue is used. The mother tongue and the effective target are separate: the header and language picker show the effective target, a banner explains a rule-driven direction and offers a one-capture override back to the mother tongue, and the panel picker is a session-only override. Persistent rules live in Settings. Detection remains advisory and uses the same high-confidence rule as the same-language advisory.
Panel keyboard: **Esc** close, **⌘C** copy translation, **⌘↩** Replace, **⌘R** retry, **⌘,** Settings. The panel is made key when shown (unless the setting is off) so Esc and the shortcuts work without a click; the app is still not activated, the source app remains frontmost and owns the menu bar, and clicking the source app takes keyboard focus back. A click sent to another app dismisses the panel; while the panel is visible a transient mouse-down monitor observes only that the click went to another app, discards the event and is removed on close. While the panel is key it receives keystrokes, so a user who types immediately after triggering should disable the Esc-on-show setting. The whole header bar (full width, flush with the top edge) moves the panel; the drag view moves the window itself from the screen-space mouse delta because `performDrag` does nothing while the app is inactive; moving it keeps its position while it stays open, and a newly shown panel is placed near the cursor (DeepL-like transient position). The translation text size is a Settings value.
Accessibility: every control has an `accessibilityLabel`; the panel exposes source and translation as read-only text elements; full keyboard navigation; respects Reduce Motion and Increase Contrast.
@@ -571,9 +573,11 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour
| `model` | String | `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` (provisional until T7.4) |
| `fastModel` | String? | `hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M` (if installed) |
| `targetLanguage` | LanguageCode | system language if supported, else `en` |
| `recentTargetLanguages` | [String] | last three targets, most recent first |
| `doubleCopyWindowMs` | Int | 500 (300–1000) |
| `maxCharactersLatin` | Int | 4000 |
| `maxCharactersCJK` | Int | 2000 |
| `maxCharactersLatin` | Int | 4000 (500–10000) |
| `maxCharactersCJK` | Int | 2000 (500–4000) |
| `maximumPartsPerSelection` | Int | 1 (1–8); 1 rejects text longer than one part |
| `numCtx` | Int | 8192 |
| `numPredict` | Int | 4096 |
| `temperature` | Double | 0.7 |
@@ -585,8 +589,13 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour
| `promptVariantPolicy` | `.defaultOnly` / `.contentAware` | `.defaultOnly` until M7 |
| `autoCopy` | Bool | **false** (never copy automatically) |
| `showSourcePreview` | Bool | true |
| `translationFontSize` | Int | 17 pt (12–28) |
| `languageRoutes` | [LanguageRoute] | `[]` (everything translates into the mother tongue unless a rule matches) |
| `renderMarkdown` | Bool | true (presentation only; raw text is copied and replaced) |
| `closeWithEscape` | Bool | true (make the panel key on show; no app activation) |
| `launchAtLogin` | Bool | false |
| `keepRecentTranslationInMemory` | Bool | true (cleared on quit; no disk) |
| `hasCompletedOnboarding` | Bool | false |
| `settingsVersion` | Int | 1 |
Never store source text, translations, pasteboard contents or app names in settings.
@@ -605,7 +614,7 @@ Never store source text, translations, pasteboard contents or app names in setti
| 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 |
| Distribution | Signed, notarised DMG; local `make dmg` for testing; Mac App Store not in v1 |
`make install` copies the app to `/Applications` and ad-hoc signs it. macOS ties Accessibility permission to the app's signature and location; after a reinstall the user may have to remove and re-add the app in System Settings.
+36 -8
View File
@@ -54,18 +54,18 @@ Decision: Source text, translations, pasteboard snapshots and app names are neve
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)
Status: Proposed (T7.5 blocked on the private corpus and the 1.8B comparison)
Context: Publisher benchmarks do not cover the user's texts, and 7B vs 1.8B is a quality/latency trade-off. The 7B is the owner's requested default, but the 1.8B may be better on smaller Macs.
Decision: Ship with `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` as the provisional default and the 1.8B Q4_K_M as the Fast preset. Decide the default, the sampling temperature and the prompt policy with `sprachmittler-cli eval` on the user's corpus using the rule in `docs/MODEL_EVALUATION.md` §5. Record the outcome as a new ADR.
Consequences: Until the gate, the 7B is labelled provisional in Settings. The decision is re-run when a model, Ollama or the prompt policy changes.
## ADR-009 — Menu-bar agent with a non-activating panel
Status: Accepted
Status: Accepted (amended 2026-11-26: Esc without a click)
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.
Context: The app must be available over any app and must not activate itself or take application focus from the selection. A regular Dock app with a window would interrupt the workflow. Users also expect Esc to dismiss a transient panel immediately, which requires the panel to be the key window.
Decision: Use `LSUIElement = YES`, a `MenuBarExtra`, and a floating `NSPanel` with `.nonactivatingPanel` and `becomesKeyOnlyIfNeeded = false`. Never call `NSApp.activate` or `makeKeyAndOrderFront` for the translation panel. Onboarding and Settings are the only surfaces that activate the app. By default the panel calls `makeKey()` when shown, so Esc and the keyboard shortcuts work immediately; the setting `closeWithEscape` can restore click-first behaviour. The panel's SwiftUI exit command handles Esc and calls the same close path that cancels an in-flight request.
Consequences: The app stays unactivated: `NSWorkspace.frontmostApplication` and the menu bar stay with the source app, and Replace still re-verifies that app. While the panel is visible it holds keyboard focus, so keystrokes and shortcuts go to the panel until the user clicks back into the source app; the setting turns this off. A click outside the panel dismisses it: the panel observes `didResignKey` and, while visible, a transient global mouse-down monitor. Global monitors do not receive events sent to this app, so clicks in the panel and its popover are ignored; the event is discarded and the monitor is removed on close. The monitor is not a key tap and needs no Input Monitoring. Every action still has a button.
## ADR-010 — Native OpenCode 2.x configuration
Status: Accepted
@@ -77,9 +77,9 @@ Consequences: No mixed V1/V2 files. Sampling settings for agents, if wanted, go
## ADR-011 — Chunk at paragraph boundaries with script-aware limits
Status: Accepted
Context: Hy-MT3's documented translation context is 8192 tokens. A long selection can exceed it; splitting mid-sentence harms quality; splitting mid-grapheme corrupts text.
Decision: Chunk at blank-line paragraph boundaries first, then sentence, then word. Use 4000 characters for Latin/Cyrillic/Greek and 2000 for CJK and other dense scripts. Never split a grapheme cluster. Reassemble with the original separators. Translate chunks sequentially with one request in flight.
Consequences: Most selections are one chunk. Very long selections lose some cross-paragraph context; the panel shows a chunk count and any failed chunk. `done_reason: "length"` is always a warning.
Context: Hy-MT3's documented translation context is 8192 tokens. A long selection can exceed it; splitting mid-sentence harms quality; splitting mid-grapheme corrupts text. The capture gate and the chunk size were the same number, so selections over one chunk were rejected before the pipeline could split them.
Decision: Chunk at blank-line paragraph boundaries first, then sentence, then word. Use 4000 characters per part for Latin/Cyrillic/Greek and 2000 for CJK and other dense scripts. Never split a grapheme cluster. Reassemble with the original separators. Translate parts sequentially with one request in flight. The capture limit is the part size multiplied by `maximumPartsPerSelection` (1–8, default 1); `1` rejects anything over one part, and higher values accept the selection and translate it in parts. The dense-script part size is capped at 4000 because 5000 dense characters plus a 4096-token output can overflow the context.
Consequences: Default behaviour is unchanged (one part). Users who opt into parts trade latency for reach: every extra part is another sequential request, and the panel shows “Part 2 of 4” while streaming and “3 parts” when finished. Very long selections lose some cross-paragraph context; the panel keeps the streamed partial text and disables Replace when a part fails. `done_reason: "length"` is always a warning.
## ADR-012 — Only documented prompt variants; no free-form prompts
Status: Accepted
@@ -129,3 +129,31 @@ Status: Accepted
Context: Double copy, clipboard snapshot/restore and Services all touch `NSPasteboard`, but the state machine and watcher need deterministic tests without real time or the user's clipboard. The Services path must work with no Accessibility permission.
Decision: `SprachmittlerCapture` defines `PasteboardAccessing` and `PasteboardTicking`. `SystemPasteboard` is the only production `NSPasteboard` user; `FakePasteboard` and `ManualPasteboardTicker` live in `SprachmittlerTestSupport`. `DoubleCopyDetector` is a pure state machine over change events and an injected date. `PasteboardWatcher` polls every 120 ms, reads the string only after `changeCount` changes, suppresses own/transient changes for 750 ms, and enforces the 4000/2000 limit. `ServicesProvider` receives the system pasteboard and needs no polling or Accessibility. `AppDelegate` installs it and calls `NSUpdateDynamicServices`.
Consequences: Capture logic is unit-testable and no global key tap is needed. The Services and double-copy paths both produce `CapturedText`. The 10-app compatibility matrix remains a manual task.
## ADR-019 — AX first, paste fallback, target re-verified at Replace
Status: Accepted
Context: Replace must be safe and reversible, but Accessibility support differs by app. AX calls can block, so they must stay off the main actor. Tests need deterministic insertion without a real app or clipboard.
Decision: `InsertionCoordinator` lives in `SprachmittlerCapture` and uses `AccessibilityTextEditing` and `EventPosting` seams. At trigger time the app captures the frontmost PID/bundle and, when trusted, reads only the focused selection; at Replace it re-verifies the frontmost app and the selected text (`InsertionPolicy`). It refuses secure fields and its own PID. AX direct replacement is tried first; if unsupported, it snapshots the clipboard, writes the translation with own/transient markers, posts ⌘V to the target PID, waits up to 300 ms and restores only when `changeCount` still matches the write. Blocking warnings disable Replace; failures keep the panel open and offer Copy.
Consequences: Most apps use the no-clipboard AX path; the fallback preserves the previous clipboard in the common case. Manual testing is still required because AX support and paste delivery are app-specific.
## ADR-020 — UI state models in Core, AppKit controllers in App
Status: Accepted
Context: Panel, Settings, Onboarding and Diagnostics contain branching worth testing, but their windows are AppKit/SwiftUI. The app target must stay thin.
Decision: `PanelViewModel`, `SettingsViewModel`, `OnboardingViewModel` and `DiagnosticsViewModel` are `@MainActor @Observable` types in `SprachmittlerCore`; `SettingsStore` uses a `SettingsDataStoring` seam. `App` owns only `NSPanel`/`NSWindow` controllers, SwiftUI views, the composition root (`AppEnvironment`) and lifecycle glue. `TranslationSession` uses an injected pipeline factory so endpoint/settings changes apply on the next request without rebuilding the UI.
Consequences: Logic is covered by package tests; AppKit remains untested by `make verify` and requires the manual checklist.
## ADR-021 — Markdown is rendered as presentation only
Status: Accepted
Context: Hy-MT3 preserves Markdown structure, but a plain `Text` showed `**bold**`, headings and lists literally. Users translating Markdown want the formatting rendered, while Copy and Replace must keep the Markdown that the model produced and the validator checked.
Decision: Parse presentation Markdown in `SprachmittlerText` with Foundation's inline Markdown parser plus a small, conservative block parser (headings, lists, quotes, fenced code, rules, paragraphs). `MarkdownPresentation.shouldRender` rejects JSON, HTML and code sources and otherwise requires block or inline Markdown markers. The panel renders only when the setting `renderMarkdown` is on (default). Copy and Replace use the raw translation unchanged. Only `http` and `https` links open, on an explicit click; image syntax is reduced to alt text and no remote resource is fetched. Tables, raw HTML and nested lists/quotes remain plain text in this pass.
Consequences: Rendering never rewrites the translation or weakens validation. Literal markers can be interpreted as formatting, so the setting is the escape hatch; Copy always returns the raw Markdown. The block layout makes text selection per block, while Copy remains the whole-translation path. No new dependency is added.
## ADR-022 — Language routing: mother tongue plus source-to-target rules
Status: Accepted
Context: A single target language is a good default, but users who work in several languages need different targets for different sources: German text to English, Chinese text to English, French text to German, and everything else to the mother tongue. The earlier single fallback only covered source-equals-target.
Decision: Keep the saved target as the **mother tongue** and the default target for every source. Add `languageRoutes`, an ordered, source-unique list of `source → target` rules; the default list is empty. Before a request, detect the source and apply the first rule whose source is confidently detected; otherwise use the mother tongue. The saved and effective targets are separate: the header and language picker show the effective target, a banner explains a rule-driven direction and offers a one-capture override back to the mother tongue, and the panel picker is a session-only override. Persistent rules are edited in Settings. Same-language rules are dropped and sources are deduplicated. The source detector ignores near-zero hypotheses so the high-confidence rule is meaningful.
Consequences: The default is "every language → mother tongue". Rules are explicit, arbitrary and can be added later (for example Chinese → English or Traditional Chinese → English) without code changes. Confident detections route automatically; short, mixed or uncertain text stays on the mother tongue. The mother tongue is unchanged by routing, and the panel override never rewrites the rules. Detection is advisory, so a wrong dominant language can select the wrong rule; the banner and picker make it visible and recoverable. No key tap, permission, network access or new dependency is added.
+1 -1
View File
@@ -138,7 +138,7 @@ Hy-MT3 supports **102 languages**. The exact English name matters: it is inserte
4. **Unknown codes are not silently mapped.** The UI shows only the 102 supported languages; an incoming detection result outside the list is displayed as "Unknown" and translation still proceeds (the prompt only needs the target).
5. **Source detection is advisory.** `NLLanguageRecognizer` supports fewer languages than Hy-MT3. A low-confidence or unsupported detection never blocks translation.
6. **RTL languages:** `ar`, `he`, `fa`, `ur`, `ps`, `sd`, `ug`, `ckb`, `yi`, and `kk` (Arabic Kazakh). The panel must render them right-to-left; the source and translation directions can differ.
7. **Dense-script chunk limit:** CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts use the 2000-character chunk limit; Latin/Cyrillic/Greek use 4000. The chunker uses Unicode script ranges, not the language code.
7. **Dense-script part size:** CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts use the 2000-character part size; Latin/Cyrillic/Greek use 4000. The chunker uses Unicode script ranges, not the language code.
## 5. UI ordering
+3
View File
@@ -80,8 +80,11 @@ Write ADR "Default model and sampling" with:
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.
Status 2026-11-26: the manifest, metrics and report harness are complete and validated on a synthetic manifest. T7.4 and T7.5 remain open because the private corpus is not present in this checkout and the 1.8B model is not installed. Do not select a default from the synthetic run.
## 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 |
| 2026-11-26 | synthetic harness validation | 7B Q4_K_M | Harness only (4 synthetic segments, 1 run): fail 0%, chrF 96.34/61.27/94.81/80.84, token retention 1.0, first token 57–102 ms, 0.45–0.91 s/segment. This is not a default-model decision. |
+14
View File
@@ -56,3 +56,17 @@ footprint -p $(pgrep -x Sprachmittler) # app memory, excluding Ollama
- 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.
## 6. App shell measurements (2026-11-26)
| Metric | Measurement | Budget | Status |
|---|---|---|---|
| Idle CPU, app only, panel closed | 0.1% after 6 s | < 0.5% | ✅ |
| Idle RSS, app only | 86,960 KB ≈ 84.9 MB | ≤ 90 MB | ✅ |
| First translation token, warm 7B (synthetic eval) | 57–102 ms | ≤ 1.5 s | ✅ |
| Warm segment, 7B (synthetic eval) | 0.45–0.91 s | 250 tokens ≤ 8 s | ✅ |
| Panel visible after a two-copy smoke | panel appeared; latency not instrumented | ≤ 250 ms | not measured |
| Copy / Replace / idle hangs | not instrumented | budgets in §2 | not measured |
| 1.8B latency and memory | model not installed | budgets in §2 | not measured |
The synthetic eval used four short segments, one run, 7B Q4_K_M, temperature 0.7, `num_ctx` 8192. It validates the harness and warm 7B behavior, not the private corpus. Measure panel signposts, Copy, Replace, cold load and the 1.8B model on the target Mac before release.
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more