Compare commits

...
7 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
45 changed files with 1862 additions and 495 deletions

No files matched your search

+13 -6
View File
@@ -88,7 +88,8 @@ final class AppEnvironment {
pasteboard: pasteboard,
configuration: DoubleCopyDetector.Configuration(
window: Double(windowMs) / 1000
)
),
limits: store.current().captureLimits
)
let factoryStore = store
@@ -217,20 +218,25 @@ final class AppEnvironment {
translationFontSize: settings.translationFontSize,
renderMarkdown: settings.renderMarkdown,
closeWithEscape: settings.closeWithEscape,
recentTargets: settings.recentTargets
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
if targetChanged {
let routesChanged = previousRoutes != settings.languageRoutes && panelViewModel.source != nil
if targetChanged || routesChanged {
Task { await panelViewModel.retranslate() }
}
onStateChange?()
@@ -247,7 +253,8 @@ final class AppEnvironment {
pasteboard: pasteboard,
configuration: DoubleCopyDetector.Configuration(
window: Double(watcherWindowMs) / 1000
)
),
limits: settingsStore.current().captureLimits
)
if let sink = watcherEventSink {
watcher.start(onEvent: sink)
@@ -276,7 +283,7 @@ final class AppEnvironment {
lastWarnings = []
onStateChange?()
switch CapturePolicy.validate(captured.text) {
switch CapturePolicy.validate(captured.text, limits: settingsStore.current().captureLimits) {
case .valid:
lastCaptureFailure = nil
case .empty:
@@ -401,7 +408,7 @@ extension AppEnvironment {
await diagnostics.record(kind: "error", detail: error.diagnosticCode)
}
onStateChange?()
case .started, .delta, .cancelled:
case .started, .chunkStarted, .delta, .cancelled:
break
}
}
+7 -2
View File
@@ -5,6 +5,7 @@ import SwiftUI
struct LanguagePickerView: View {
@Binding var selection: ModelLanguage
var recent: [ModelLanguage] = []
var excluding: String?
@Environment(\.dismiss) private var dismiss
@State private var query = ""
@@ -45,8 +46,12 @@ struct LanguagePickerView: View {
let all = LanguageCatalogue.all.sorted {
$0.localizedDisplayName.localizedCaseInsensitiveCompare($1.localizedDisplayName) == .orderedAscending
}
guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return all }
return all.filter {
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)
+50
View File
@@ -8,6 +8,8 @@ import SwiftUI
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) {
@@ -20,6 +22,12 @@ final class PanelController: NSObject, NSWindowDelegate {
)
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
@@ -54,15 +62,57 @@ final class PanelController: NSObject, NSWindowDelegate {
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() }
}
+38 -3
View File
@@ -36,7 +36,7 @@ extension PanelView {
MarkdownTranslationView(
markdown: model.translation,
fontSize: model.configuration.translationFontSize,
isRTL: model.configuration.target.isRTL
isRTL: model.effectiveTarget.isRTL
)
} else {
Text(translationText)
@@ -46,7 +46,7 @@ extension PanelView {
.foregroundStyle(model.translation.isEmpty ? .secondary : .primary)
.environment(
\.layoutDirection,
model.configuration.target.isRTL ? .rightToLeft : .leftToRight
model.effectiveTarget.isRTL ? .rightToLeft : .leftToRight
)
.accessibilityLabel(String(localized: "Translation"))
}
@@ -66,11 +66,34 @@ extension PanelView {
}
}
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.configuration.target.localizedDisplayName).")
Text("This text already appears to be in \(model.effectiveTarget.localizedDisplayName).")
.font(.callout)
Spacer()
Button(String(localized: "Translate anyway")) {
@@ -197,6 +220,18 @@ extension PanelView {
.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 {
+4 -4
View File
@@ -62,7 +62,7 @@ struct PanelView: View {
VStack(alignment: .leading, spacing: 1) {
Text(String(localized: "Translate"))
.font(.headline)
Text("\(sourceLanguageLabel) → \(model.configuration.target.localizedDisplayName)")
Text("\(sourceLanguageLabel) → \(model.effectiveTarget.localizedDisplayName)")
.font(.caption)
.foregroundStyle(.secondary)
}
@@ -75,16 +75,16 @@ struct PanelView: View {
Button {
showLanguagePicker.toggle()
} label: {
Label(model.configuration.target.localizedDisplayName, systemImage: "globe")
Label(model.effectiveTarget.localizedDisplayName, systemImage: "globe")
.labelStyle(.titleAndIcon)
}
.accessibilityLabel(String(localized: "Target language"))
.popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) {
LanguagePickerView(
selection: Binding(
get: { model.configuration.target },
get: { model.effectiveTarget },
set: { language in
Task { await model.setTarget(language) }
Task { await model.overrideTarget(language) }
}
),
recent: model.configuration.recentTargets
@@ -104,3 +104,14 @@
"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.";
@@ -104,3 +104,14 @@
"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)
}
}
}
+7 -16
View File
@@ -74,7 +74,7 @@ struct SettingsView: View {
private var generalTab: some View {
Form {
Section(String(localized: "Translation")) {
LabeledContent(String(localized: "Target language")) {
LabeledContent(String(localized: "Mother tongue")) {
Button {
showLanguagePicker.toggle()
} label: {
@@ -93,8 +93,11 @@ struct SettingsView: View {
recent: draft.recentTargets
)
}
.accessibilityLabel(String(localized: "Target language"))
.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(
@@ -123,6 +126,7 @@ struct SettingsView: View {
)
.font(.caption)
.foregroundStyle(.secondary)
LanguageRulesSettings(routes: $draft.languageRoutes, motherTongue: draft.targetLanguageModel)
}
Section(String(localized: "Double copy")) {
@@ -235,20 +239,7 @@ struct SettingsView: View {
}
}
Section(String(localized: "Chunking")) {
Stepper(
String(localized: "Latin limit: \(draft.maxCharactersLatin)"),
value: $draft.maxCharactersLatin,
in: 1000 ... 10000,
step: 500
)
Stepper(
String(localized: "Dense-script limit: \(draft.maxCharactersCJK)"),
value: $draft.maxCharactersCJK,
in: 500 ... 5000,
step: 250
)
}
LongSelectionsSettings(draft: $draft)
Section(String(localized: "Prompt policy")) {
Text(String(localized: "Default translation is fixed for v1."))
+44 -35
View File
@@ -18,7 +18,7 @@ c989a2513d0b926f3a202b0616426c7443594ce72896ee91c29c4e83451d433c ./.opencode/sk
2c0c375f3f6704a43e1042b250e0b633ba740aa7bc2fbf5518891a7b5464507e ./.swiftlint.yml
3222c8553505401c967cc302e2d46a99db95f98d92650f6b245e2a1dc901bea9 ./AGENTS.md
593745fab27436e91148de34b7e0e530cef5137e2c566cb479caed033602b949 ./App/AppDelegate.swift
57bb84de7d482ba5a4a51126b647a99f595b1af8e3739a5db63dd4d6006f28bd ./App/AppEnvironment.swift
1461fb881c44cee037051e78a4ea1e36ad459abbab1fc7d530ad993687520d11 ./App/AppEnvironment.swift
dc41f554a88b5b499840f72ef676b31530e6ebfcc5da636155001c52ca48d8a1 ./App/Diagnostics/DiagnosticsView.swift
69f0c24937507ed7a9137abfa95fdcd2798cd909dd74642d4b5e6a859da94253 ./App/Info.plist
36aec6e936e6ffff104908b370a7231b9283e178df8d0a453639dca9c573460d ./App/LaunchAtLoginController.swift
@@ -27,11 +27,11 @@ dc41f554a88b5b499840f72ef676b31530e6ebfcc5da636155001c52ca48d8a1 ./App/Diagnost
3b001166f13cac42136917cfde0277c6cd8cfa922280832a4065081b822b3f9d ./App/MenuBar/StatusMenuView.swift
c4a25b6c1207197109d12ea740dc15ad8aa75b6304d901110aa3e10570cd65a0 ./App/Onboarding/OnboardingView.swift
ba9467153908c81fbb2497d5679642ae15c7b9fa23a10ca9b9ab678042aab222 ./App/Onboarding/README.md
eaf54c09c3df9847f456cb81f198df3b82fa53f02f1fad4918af5549e92ddc7c ./App/Panel/LanguagePickerView.swift
382661bb55524acd7a686f215f8dd1cfdd4127dc19629dd637204c5b1e0734e9 ./App/Panel/LanguagePickerView.swift
76dcf59e01ae8319d4f0aabc5e600c549adaf56b6db802794804c3215be9377c ./App/Panel/MarkdownTranslationView.swift
267c008ba680bc49f2397bf01a667fa7594177cdb2333ea190cfff36a5fa3174 ./App/Panel/PanelController.swift
aa364e7cb6373cdeaea0c24f59c959ebcdca228be21a27c6fae431463a6d2c04 ./App/Panel/PanelView+Content.swift
278b9bd96ffe8c322703dec7c660632351c8e9a1996b0ee5713299f3de4ae082 ./App/Panel/PanelView.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
@@ -47,10 +47,12 @@ f7fb7b04d7936a965befe202545fdaccb69d7c0c95a99449a27c9119d0326991 ./App/Resource
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
1da14ac15fda89935795e6a9faa5274cf6a2047de56f635be7d6da01699c2cdf ./App/Resources/de.lproj/Localizable.strings
3fcec362d3bd5776af97259d92f9e6349a927d8730fb06f3f8776c97b7a10606 ./App/Resources/en.lproj/Localizable.strings
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
13ded50c5202ce32bbe6d8432f0701f7d71bf9bc99e4b5e02e688b51416053b9 ./App/Settings/SettingsView.swift
3066bb45d7b90e3ad07931f56dc234b4b3481c40459842e00430b6a66ef28308 ./App/Settings/SettingsView.swift
d3dcb4365c3d9ec39fa379b8e5cc0813745acc68dc851a85b4ab277896a2a5b1 ./App/Sprachmittler.entitlements
ddda3377a2e130e25195da349dd0964cfca8a401464b7b0cd8fcec6bfb575fa3 ./App/SprachmittlerApp.swift
c3d0de679f6d151f46cfdd11577eba65e1cff1f82be669be32e42a99fba302ba ./Makefile
@@ -64,14 +66,15 @@ ec2f66d1a2d8ebb308427802f54cc70c6bdead8c31a57ed87648446d6bda9ce1 ./Packages/Spr
85abecf8ca1b15fe1a9d5dbaa0caee16a38a4408e932f6115975d9823a2ac47c ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/InsertionCoordinator.swift
0b8a8223e67d0c94551c1dd68609858602069d0ecd4eda736f988880d1e04464 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardAccessing.swift
4ca88b4f08515057738a45c9ae475260e3a840c1d5bb3d4622a57ce04f5b8cb1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardTicking.swift
543efb54825e2851528efd0c2a4b068929b79c3e0276c1314e6b5414480f893a ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.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
ec9fea234c3ba2b1d3ef3b308537071bb1e72bd913da9271f4b291c26f62d5d8 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift
7921d56341b4b6fe4392989b30de91bb2aeb91a8d52d840dc9602a3d5a6134dd ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift
5159e03a08507c4d6f61479cd4ce389e9541a8df4540ef6540cedaba6e8133a1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.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
@@ -84,7 +87,7 @@ cc89553a898735a1288bdd1c67a04fbcd282f99ee812a83c8b18eff9627ab65d ./Packages/Spr
39cec81db2748fd5e01c5d6ade00bae5babf4a68d7d472a69e98b20884585c5f ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Loggers.swift
83b6c93fc950df1fa8e4942521187a0ee3ecb319b5ffec6deef6047ef8d2b171 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OllamaErrorMapping.swift
b7dfab9b2c613071b97bc329378eae47b97305cae758221fba787c8be4eb52f5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OnboardingViewModel.swift
e46605bc2ff74d4a122ac23bce763b847b9930abbe2b9d2a5f1ea1ed0cb5d6e7 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.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
@@ -94,17 +97,18 @@ e33ebfeeeb27b88029c20f212769852c5c0a697abaeb1bc249d350e7ad649273 ./Packages/Spr
20e3977534de6e1c1af8bcc3049318007213a034aa2e8d2d24032b22e1bacba0 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Signposts.swift
b6580ae5a0f5e18b6b527766cb5acd5de4d828df3badac44ae294dd72acfc436 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerCore.swift
2864b92feb24a0616fa546ea2683fbdc9f73352ca64ab84da110e19fd7c6a926 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerError.swift
c54f853a63db2f71fb5e574976e0f6b3ed39ae768adb644a0e245c5844fa2b5c ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift
359faa0524007bb58a504b073c854c04736482b893e9509e56843a6850d9e7ac ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift
f75ae67b262e18b53721d070acc0e8d7bdfca94698f10c1a5780ef948ef72912 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TextInserting.swift
b7d4bf8d2a1ab24b26dfa3e091e9fa7e92f8460f8850f9f086af4814537b1f4a ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift
d01aaf98c054bd3d14ce4d6055f576738d83b63037f246b0ec3cc302b130c12b ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.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
34b21987ac51e045a4ce9d3aaa324f1e2a6a8abdf3f9f2908e9ceca3c0581862 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/LanguageMatching.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
@@ -114,6 +118,7 @@ c473fa0f2c89d4a4f75307e81a6a5d28f1f21f3bffcc8911bb30487d27f64486 ./Packages/Spr
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
@@ -158,10 +163,10 @@ c32d05b70ba04d525064a2ed71f5ea67d1655d72c56f9d185aefe4250840321b ./Packages/Spr
03d570bc4022f205abb52da509bd68444879308b14f46bad497cadf9f80f3845 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeSettingsAndPermissions.swift
16e6ae7d693df1ee6532affec1fa687aeed1e709595b929f2a4e1f00e1b9d88a ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/ManualPasteboardTicker.swift
c0f87a5320fe715f5dbc7c9bbc7c0fb19a5b64d1c145c45b26f060c151eccada ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/ManualSleeper.swift
3443a4e2a7d3d493b9d604875f0abec2f3a515fd162f6af41e25f48c78185b57 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift
0ea5a0c60c2185262e52f71c78538f9b1bb308c9835dc2362f70929da9bc42cd ./Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift
b639d452d78dcda9e9f3b5ac3298e8499a7837a955839ae5203b508944df2c63 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClass.swift
b768d43f50bd4fcede0f3c654787771a605b6ea2648cac722d0e78dd913b4fa5 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClassifier.swift
983997717ee3a06b7355a9611a27f7c93a631a8434fd9bcfc79f8497c4a3696d ./Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.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
@@ -190,21 +195,24 @@ e7ec098ecc2e0c3f62ba53cd44afc0659b77b7baf2d5ab307cb4238c1f6efa5c ./Packages/Spr
d4e110c510cac46c1acecc68f28ef8b30daaf1f9b623f0533ad359a6a13680aa ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/ClipboardSnapshotTests.swift
23e0c52e3f5f9b5848ff9118bfe3baf474a21c830560be382b978328e794218e ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/DoubleCopyDetectorTests.swift
efac77b258ef29cca1cc61311ef8d167e45ad5680a73396a1b4bc6d99d9a3f45 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/InsertionCoordinatorTests.swift
6ff42653fd8b3bf33407249c9a482397bd6fbf953b149ad51136ea2a16f29c45 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PasteboardWatcherTests.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
4d5776174be0ae5a17d3414b410671c83b492029af47a9204311be066d0f9119 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift
4ca70a674a35b723f7608bfe9b250b8572586ce4923e9965245626588935bb6e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.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
caa6eb7016ecd217811761530af2dcc1f6abbc03548b4267e6a94ed691c2a0fd ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.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
9a1a9671fdde945d3dd8356ea4dab8b6c30120d868970507883a77657701c500 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift
304cc5262dd6713041bb12cfa5502e5971c1c7e486c33be79818985bc0545232 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.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
615de4459d2d77dac87809bb33af42d32ab624cb5367d1b3b9de6841d4935bc3 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/delimiters-prompt.txt
@@ -215,6 +223,7 @@ e56dc9de2741d731b02ff3bb39ee74532ac4350d232eb66fac86ffb770cb7a86 ./Packages/Spr
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
@@ -246,31 +255,31 @@ a90dc29af451dac1557a88081a53defcffa8d21fdc0029d7fc19bc3a34d81598 ./Packages/Spr
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
60f1c5ea4134593dc721650f32c48b9cf20c02fd6e8b692d8bb1da9e02490518 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift
436ed18c9c1cd8bf15df11e2c2f9ca974f9a6f17ca8b894e5ffef999458653fa ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift
80d28cb607b67a35cda89d86e2819e29e71b38e8234557683cb7c96f611037d1 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/MarkdownPresentationTests.swift
8c5c21634d749ad05da8b6a0fc1d8e132a494177a697ba0a1338a7a6b5dba50c ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/PlaceholderTests.swift
67c0f9ba9e818267e99c1756b82643f7e59effa6783325675386aba0a1002cb3 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ProtectedTokenScannerTests.swift
c3294d486cfe44a6f0a69a1ec05cff33a8eccf090fce04fadffa96b6b2563d6f ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/TextNormalizationTests.swift
a212d7f39aadba95375bdc14786ee12ffc43b4555e4a591f60ce5da0dfd7c5b0 ./README.md
2d902ce53c14b6d64a578bdcc99845b6375a69ced37f503423c9df6cbf3c15f0 ./README.md
f1dbc2fb876d909b8486239e9b75b09ed68516c341d586e96d8626715c86a88c ./dist/Sprachmittler-0.1.0-local.dmg
38541779aa6190cc99d81ad16f98693a6fa00f14e9fa166dd36339cfe23865fc ./docs/ARCHITECTURE.md
b100978fe55c5afbf6b3c987b34e17f3413329d3fd580a2cfcd616f71a564aa9 ./docs/ARCHITECTURE.md
018c5faf1a5d2e8d851ab209d45e64993cbd6b7976c4aa90c571359c83e83264 ./docs/CODING_STANDARDS.md
c39bba389cc023831dab2244f475eb7707320686f98633b6923ea04347b83aed ./docs/DECISIONS.md
0eddd31ac7f4ad295720b9081896200d622f28ed3a17bdab30f57f557d980bdd ./docs/DECISIONS.md
5b80ea8994519f2be34aa10abb345ac3029d3d3a29705dcfa0a1cb344f4b95d2 ./docs/HYMT3_MODEL.md
d87fc9df926f6ba77ce67b2731b83f48f2b49848c637f12d0fdfb5f27f3c6775 ./docs/IMPLEMENTATION_PLAN.md
c3a1838fb0a06acf6b7826f6ff278e15065af198dab22ffb1435dacdc064ad69 ./docs/KICKOFF.md
20a87dc7cf8cb593445c89d334e123f6275232524598ac71a21ca32766cedfb7 ./docs/LANGUAGES.md
b1d9fcfffd9d0e6b3a9792633ad71acdef29a344eea0dea778e132a7c0330322 ./docs/LANGUAGES.md
a28161210fbabe27d1348f3552851fe7b30c9dccc658272f2cc79af5e085ec40 ./docs/MODEL_EVALUATION.md
6f94dfe4f2146ce0b9e066198c9e05ce659faf4318513ce586c966989fd3d1c0 ./docs/OLLAMA_TRANSLATION_API.md
e6dbccc3cb4c7a169a6daaa563066a6764a76b6b7649738b839dcbd9b2400ee5 ./docs/OPENCODE_V2.md
e2b785807ecb56eb1e7c02aaa6a487ce7c1be421865685bed4be2e973269bdce ./docs/PERFORMANCE.md
4a37cf1815071b3afdd10443ec9e05a5a78411d615c42f51117c5873922531c4 ./docs/PRD.md
70b7be815282fa6d25beb4ce805f6ac47f45878b16621798ed6a4ac1e294011f ./docs/PROGRESS.md
7e55a36c4785c77009797f32ef0837be68168d35feab9bf4803484b4df8cd203 ./docs/SECURITY_PRIVACY.md
2e6c7ba67d857db7cddf1e31b5a6516f70b8094e9115094b58156f9e6626452c ./docs/SELECTION_AND_CLIPBOARD.md
6ea3e3881a9f6a7de968128e660a897c648d8e01af77b3e831228b809d0d94e2 ./docs/PROGRESS.md
c72f39e7e5e1fb9c45c32f0741a379564debca4b408e702615d162f360d47ecf ./docs/SECURITY_PRIVACY.md
f140344de55d11eb450961639ba85a1ff479cf2e0cfb3c8bd3c4cdb2220a11ea ./docs/SELECTION_AND_CLIPBOARD.md
8720e8bf79ba7ab051bb8bd09f55b7766f98941904f354cbe3ab7b88c941e860 ./docs/TESTING.md
d86aa67b08549ecce44e14d1e4fde0050ea5e89f77643733efd312fa42ef4e25 ./docs/TRANSLATION_OUTPUT.md
8a5dce4b34d9c4630dcf42006970c7cc624e16281af37b023e3563c946d1aa7a ./docs/USER_GUIDE.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
@@ -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,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)
}
}
@@ -27,8 +27,10 @@ public struct AppSettings: Codable, Sendable, Equatable {
public var model: String
/// The optional Fast model tag.
public var fastModel: String?
/// The selected target BCP-47 code.
/// 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).
@@ -37,6 +39,8 @@ public struct AppSettings: Codable, Sendable, Equatable {
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`.
@@ -82,10 +86,12 @@ public struct AppSettings: Codable, Sendable, Equatable {
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
@@ -132,9 +138,11 @@ public struct AppSettings: Codable, Sendable, Equatable {
/// 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 ... 5000)
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)
@@ -165,23 +173,29 @@ public struct AppSettings: Codable, Sendable, Equatable {
Chunker(latinLimit: maxCharactersLatin, denseLimit: maxCharactersCJK)
}
private struct DecodedLimits {
/// 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
}
private struct DecodedSampling {
struct DecodedSampling {
let temperature: Double
let topP: Double
let topK: Int
let repeatPenalty: Double
}
private static func decodeLimits(
static func decodeLimits(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings
) throws -> DecodedLimits {
@@ -199,7 +213,12 @@ public struct AppSettings: Codable, Sendable, Equatable {
cjk: clamp(
container.decodeIfPresent(Int.self, forKey: .maxCharactersCJK)
?? defaults.maxCharactersCJK,
to: 500 ... 5000
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,
@@ -217,7 +236,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
)
}
private static func decodeSampling(
static func decodeSampling(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings
) throws -> DecodedSampling {
@@ -237,104 +256,32 @@ public struct AppSettings: Codable, Sendable, Equatable {
)
}
private enum CodingKeys: String, CodingKey {
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, recentTargetLanguages
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict
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
}
/// Decodes with v0 migration: missing or unknown fields fall back to defaults, and an old
/// `settingsVersion` is upgraded to the current one. Unknown keys are ignored by Codable.
public 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
let recents = try container.decodeIfPresent([String].self, forKey: .recentTargetLanguages) ?? []
static func normalizedRoutes(_ routes: [LanguageRoute]) -> [LanguageRoute] {
var seen = Set<String>()
recentTargetLanguages = recents.compactMap { HyMT3Languages.resolve($0)?.code }
.filter { seen.insert($0).inserted }
.prefix(3)
.map(\.self)
let limits = try Self.decodeLimits(from: container, defaults: defaults)
doubleCopyWindowMs = limits.window
maxCharactersLatin = limits.latin
maxCharactersCJK = limits.cjk
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
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)
}
}
public 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(recentTargetLanguages, forKey: .recentTargetLanguages)
try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs)
try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin)
try container.encode(maxCharactersCJK, forKey: .maxCharactersCJK)
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 clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
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)
@@ -1,6 +1,7 @@
import Foundation
import Observation
import SprachmittlerEngines
import SprachmittlerText
/// The panel phase from `docs/ARCHITECTURE.md` §10.
public enum PanelPhase: Sendable, Equatable {
@@ -20,6 +21,8 @@ public enum PanelPhase: Sendable, Equatable {
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.
@@ -36,6 +39,8 @@ public struct PanelConfiguration: Sendable, Equatable {
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(
@@ -47,7 +52,9 @@ public struct PanelConfiguration: Sendable, Equatable {
translationFontSize: Int = 17,
renderMarkdown: Bool = true,
closeWithEscape: Bool = true,
recentTargets: [ModelLanguage] = []
languageRoutes: [LanguageRoute] = [],
recentTargets: [ModelLanguage] = [],
captureLimits: CaptureLimits = CaptureLimits()
) {
self.target = target
self.model = model
@@ -57,7 +64,9 @@ public struct PanelConfiguration: Sendable, Equatable {
self.translationFontSize = translationFontSize
self.renderMarkdown = renderMarkdown
self.closeWithEscape = closeWithEscape
self.languageRoutes = languageRoutes
self.recentTargets = recentTargets
self.captureLimits = captureLimits
}
}
@@ -83,10 +92,20 @@ public final class PanelViewModel {
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.
/// 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
@@ -100,9 +119,11 @@ public final class PanelViewModel {
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(
@@ -112,10 +133,13 @@ public final class PanelViewModel {
replace: (@MainActor () async -> InsertionOutcome)? = nil,
onCloseRequest: @escaping @MainActor () -> Void = {},
eventObserver: (@MainActor (TranslationSessionEvent) -> Void)? = nil,
onTargetChanged: @escaping @MainActor (ModelLanguage) -> Void = { _ in }
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
@@ -180,8 +204,8 @@ public final class PanelViewModel {
error?.recoveryAction
}
/// Synchronously resets the visible state before the panel is shown.
public func prepare(_ captured: CapturedText) {
/// 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
@@ -189,29 +213,49 @@ public final class PanelViewModel {
warnings = []
error = nil
timing = nil
sourceLanguage = nil
didCopy = false
isReplacing = false
sameLanguageDismissed = 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 {
prepare(captured)
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.
/// Retries the last captured text without discarding a manual direction choice.
public func retry() async {
guard let lastCaptured else { return }
await begin(lastCaptured)
await begin(lastCaptured, resetDirectionOverride: false)
}
/// Retranslates after an external target change.
/// Retranslates after an external target change and re-evaluates the direction.
public func retranslate() async {
guard let lastCaptured else { return }
await begin(lastCaptured)
await begin(lastCaptured, resetDirectionOverride: true)
}
/// Shows a capture-time error such as a too-long selection.
@@ -225,15 +269,36 @@ public final class PanelViewModel {
warnings = []
timing = nil
sourceLanguage = nil
chunkCount = 1
currentChunk = nil
totalChunks = nil
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
}
/// Changes the target and retranslates the current selection.
/// Changes the saved target from the panel and retranslates the current selection.
public func setTarget(_ language: ModelLanguage) async {
guard language.code != configuration.target.code else { return }
guard language.code != effectiveTarget.code else { return }
configuration.target = language
effectiveTarget = language
routedSource = nil
targetOverride = language
onTargetChanged(language)
if let lastCaptured {
await begin(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)
}
}
@@ -268,7 +333,13 @@ public final class PanelViewModel {
/// 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.
@@ -284,6 +355,12 @@ public final class PanelViewModel {
didCopy = false
isReplacing = false
sameLanguageDismissed = false
chunkCount = 1
currentChunk = nil
totalChunks = nil
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
lastCaptured = nil
}
@@ -296,48 +373,86 @@ public final class PanelViewModel {
private func request(for captured: CapturedText) -> TranslationSessionRequest {
TranslationSessionRequest(
captured: captured,
target: configuration.target,
target: effectiveTarget,
model: configuration.model,
keepAlive: configuration.keepAlive,
sampling: configuration.sampling
sampling: configuration.sampling,
captureLimits: configuration.captureLimits
)
}
}
private extension PanelViewModel {
private func handle(_ event: TranslationSessionEvent) {
switch event {
case let .started(epoch, request):
currentEpoch = epoch
source = request.captured
configuration.target = request.target
translation = ""
warnings = []
error = nil
phase = .translating
handleStarted(epoch: epoch, request: request)
case let .chunkStarted(epoch, index, total):
handleChunkStarted(epoch: epoch, index: index, total: total)
case let .delta(epoch, text):
guard epoch == currentEpoch else { return }
translation += text
phase = .streaming
handleDelta(epoch: epoch, text: text)
case let .finished(epoch, result):
guard epoch == currentEpoch else { return }
translation = result.translation
warnings = result.warnings
timing = result.timing
sourceLanguage = result.sourceLanguage
if result.warnings.contains(.emptyOutput) {
error = .emptyOutput
phase = .failed
} else {
phase = .ready
}
case let .failed(epoch, failure):
guard epoch == currentEpoch else { return }
error = failure
phase = .failed
handleFinished(epoch: epoch, result: result)
case let .failed(epoch, error):
handleFailed(epoch: epoch, error: error)
case let .cancelled(epoch):
guard epoch == currentEpoch else { return }
phase = .idle
error = nil
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
}
}
@@ -28,7 +28,7 @@ public extension SprachmittlerError {
case .emptyText:
"No text was copied."
case let .textTooLong(_, limit):
"This selection is too long (limit \(limit) characters)."
"This selection is too long (limit \(limit) characters). You can raise the limit in Settings."
case .pasteboardUnavailable:
"The clipboard is unavailable."
case .ollamaUnreachable:
@@ -108,7 +108,7 @@ public extension SprachmittlerError {
case .ollamaTooOld, .endpointRejected:
.openSettings
case .textTooLong:
.shortenText
.openSettings
case .accessibilityNotTrusted:
.openSettings
case .accessibilityUnsupported, .insertionTargetChanged, .pasteboardRestoreFailed:
@@ -94,7 +94,8 @@ public struct TranslationPipeline: Sendable {
model: String,
keepAlive: String,
sampling: SamplingOptions = .publisherDefault,
onDelta: (@Sendable (String) async -> Void)? = nil
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 {
@@ -118,7 +119,7 @@ public struct TranslationPipeline: Sendable {
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(
@@ -168,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
@@ -10,6 +10,24 @@ public protocol TranslationStreaming: Sendable {
_ 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 {}
@@ -28,6 +46,22 @@ public extension TranslationPipeline {
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.
@@ -42,6 +76,8 @@ public struct TranslationSessionRequest: Sendable, Equatable {
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(
@@ -49,13 +85,15 @@ public struct TranslationSessionRequest: Sendable, Equatable {
target: ModelLanguage,
model: String,
keepAlive: String,
sampling: SamplingOptions = .publisherDefault
sampling: SamplingOptions = .publisherDefault,
captureLimits: CaptureLimits = CaptureLimits()
) {
self.captured = captured
self.target = target
self.model = model
self.keepAlive = keepAlive
self.sampling = sampling
self.captureLimits = captureLimits
}
}
@@ -63,6 +101,8 @@ public struct TranslationSessionRequest: Sendable, Equatable {
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.
@@ -102,16 +142,7 @@ public actor TranslationSession {
let currentEpoch = epoch
continuation.yield(.started(epoch: currentEpoch, request: request))
switch CapturePolicy.validate(request.captured.text) {
case .valid:
break
case .empty:
continuation.yield(.failed(epoch: currentEpoch, error: .emptyText))
return currentEpoch
case let .textTooLong(characters, limit):
continuation.yield(
.failed(epoch: currentEpoch, error: .textTooLong(characters: characters, limit: limit))
)
guard validate(request, epoch: currentEpoch) else {
return currentEpoch
}
@@ -122,6 +153,9 @@ public actor TranslationSession {
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)
@@ -166,11 +200,31 @@ public actor TranslationSession {
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
@@ -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)
}
}
@@ -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
lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value
}.map(\.key.rawValue)
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)
let alternatives = ordered.isEmpty ? [dominant.rawValue] : ordered
return LanguageDetection(
code: dominant.rawValue,
@@ -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)
@@ -16,14 +16,28 @@ struct AppSettingsTests {
#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"))
@@ -32,10 +46,12 @@ struct AppSettingsTests {
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)
@@ -49,6 +65,8 @@ struct AppSettingsTests {
"settingsVersion": 0,
"endpoint": "http://127.0.0.1:11434",
"targetLanguage": "de",
"autoSwitchTarget": true,
"fallbackTargetLanguage": "en",
"autoCopy": true,
"unknownFutureKey": "ignored"
}
@@ -57,9 +75,11 @@ struct AppSettingsTests {
#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 {
@@ -97,7 +117,8 @@ struct AppSettingsTests {
let decoded = try JSONDecoder().decode(AppSettings.self, from: Data(json.utf8))
#expect(decoded.doubleCopyWindowMs == 300)
#expect(decoded.maxCharactersLatin == 500)
#expect(decoded.maxCharactersCJK == 5000)
#expect(decoded.maxCharactersCJK == 4000)
#expect(decoded.maximumPartsPerSelection == 1)
#expect(decoded.numCtx == 1024)
#expect(decoded.numPredict == 8192)
#expect(decoded.temperature == 2)
@@ -106,6 +127,7 @@ struct AppSettingsTests {
#expect(decoded.repeatPenalty == 2)
#expect(decoded.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
#expect(decoded.translationFontSize == 28)
#expect(decoded.languageRoutes.isEmpty)
#expect(HyMT3Languages.resolve(decoded.targetLanguage) != nil)
}
@@ -117,8 +139,16 @@ struct AppSettingsTests {
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 = "xx"
settings.targetLanguage = "de"
settings.maxCharactersCJK = 9999
settings.maximumPartsPerSelection = 99
settings.sanitize()
#expect(settings.doubleCopyWindowMs == 300)
@@ -127,6 +157,12 @@ struct AppSettingsTests {
#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)
}
@@ -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,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
}
}
@@ -1,5 +1,6 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerText
import Testing
@testable import SprachmittlerCore
@@ -139,135 +140,4 @@ struct PanelViewModelTests {
#expect(panel.translation.isEmpty)
#expect(panel.warnings.isEmpty)
}
// The helper returns the panel and two small test captures; a struct would add noise here.
// swiftlint:disable large_tuple
private func makePanel(
streaming: any TranslationStreaming,
replacement: (@MainActor () async -> InsertionOutcome)? = nil,
onClose: @escaping @MainActor () -> Void = {}
) -> (PanelViewModel, CopiedTextBox, TargetBox) {
let session = TranslationSession(pipelineFactory: { streaming })
let copies = CopiedTextBox()
let targets = TargetBox()
let panel = PanelViewModel(
session: session,
configuration: PanelConfiguration(
target: HyMT3Languages.german,
model: "test-hy-mt3",
keepAlive: "30m"
),
copy: { copies.text = $0 },
replace: replacement,
onCloseRequest: onClose,
onTargetChanged: { targets.codes.append($0.code) }
)
panel.startObserving()
return (panel, copies, targets)
}
// swiftlint:enable large_tuple
private func waitFor(_ condition: @MainActor () -> Bool) async {
for _ in 0 ..< 10000 {
if condition() {
return
}
await Task.yield()
}
Issue.record("panel condition was not reached")
}
private 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
)
}
}
private 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
}
}
private struct FailingStreaming: TranslationStreaming {
let error: SprachmittlerError
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
throw error
}
}
private 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
}
}
private 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
}
}
private final class CopiedTextBox: @unchecked Sendable {
var text: String?
}
private final class TargetBox: @unchecked Sendable {
var codes: [String] = []
}
private final class ReplaceBox: @unchecked Sendable {
var called = false
}
private final class CloseBox: @unchecked Sendable {
var closed = false
}
@@ -50,6 +50,28 @@ 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)],
@@ -165,6 +165,67 @@ struct TranslationSessionTests {
#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,
@@ -176,6 +237,34 @@ struct TranslationSessionTests {
}
}
/// 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 {
@@ -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)
}
}
@@ -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 {
+183 -100
View File
@@ -1,134 +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.
Sprachmittler is the companion to Schriftleser and Vorleser: Vorleser reads text aloud, Schriftleser reads documents into text, Sprachmittler translates the text you select.
It is the companion to **Schriftleser** and **Vorleser**: Vorleser reads text aloud, Schriftleser turns documents into text, and Sprachmittler translates the text you select.
A user-facing installation, permission and troubleshooting guide is in [docs/USER_GUIDE.md](docs/USER_GUIDE.md).
## How it works
## Features
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.
**Translate**
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.
- 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.
## Prerequisites
**The panel**
| Requirement | Version |
- 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 |
|---|---|
| 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`) |
| 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 |
## Getting started
## Install from source
```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 # format, lint, privacy, tests, Debug + Release builds
make app # builds and launches the Debug app
make install # builds Release, installs in /Applications and launches
make dmg # local unnotarised DMG from the Release build
make icon # regenerate the app icon assets
opencode # start OpenCode in the repo root
git clone <repository-url>
cd Sprachmittler
make bootstrap
```
Then paste the prompt from `docs/KICKOFF.md` into OpenCode, or simply run:
Start Ollama and download the model once:
```text
/next
```bash
ollama serve
ollama pull hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M
```
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.
Then build, install and launch the Release app:
## What's inside
```bash
make install
```
| Path | Purpose |
`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 |
|---|---|
| `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` |
| Translate the selection | **⌘C** twice |
| Close the panel | **Esc**, or click outside |
| Copy the translation | **⌘C** |
| Retry | **⌘R** |
| Replace the selection | **⌘↩** |
| Settings | **⌘,** |
## The canonical prompt
### Mother tongue and language rules
All translation prompts live in `SprachmittlerEngines`. The default is Tencent's documented English template, byte for byte:
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
Translate the following text into {target_lang}. Note that you should **only output the translated result without any additional explanation**:
{source_text}
Mother tongue: German
Chinese (Simplified) → English
Traditional Chinese → English
German → English
```
`{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.
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.
## Recommended way to work with OpenCode
### Markdown
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.
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.
## Placeholders to change
### Replace
- 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.
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.
## Licensing note
### 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
```text
select text → ⌘C twice → pasteboard capture → validate → chunk
→ documented Hy-MT3 prompt → Ollama /api/chat (streaming)
→ validate → floating panel
```
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.
| Module | Responsibility |
|---|---|
| `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 |
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
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
```
The package builds and tests without Xcode UI:
```bash
swift build --package-path Packages/SprachmittlerKit
swift test --package-path Packages/SprachmittlerKit
```
`swift run --package-path Packages/SprachmittlerKit sprachmittler-cli --help` exposes the language catalogue, model inspection, translation and evaluation commands.
### Working with OpenCode
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.
OpenCode is a development tool. The app builds and runs without it.
### Forking
- 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.
## 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.
+9 -5
View File
@@ -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`)
@@ -554,7 +554,9 @@ stateDiagram-v2
| 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 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. 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.
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.
@@ -573,8 +575,9 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour
| `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 |
@@ -587,6 +590,7 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour
| `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 |
+12 -5
View File
@@ -65,7 +65,7 @@ Status: Accepted (amended 2026-11-26: Esc without a click)
Context: The app must be available over any app and must not activate itself or take application focus from the selection. A regular Dock app with a window would interrupt the workflow. Users also expect Esc to dismiss a transient panel immediately, which requires the panel to be the key window.
Decision: Use `LSUIElement = YES`, a `MenuBarExtra`, and a floating `NSPanel` with `.nonactivatingPanel` and `becomesKeyOnlyIfNeeded = false`. Never call `NSApp.activate` or `makeKeyAndOrderFront` for the translation panel. Onboarding and Settings are the only surfaces that activate the app. By default the panel calls `makeKey()` when shown, so Esc and the keyboard shortcuts work immediately; the setting `closeWithEscape` can restore click-first behaviour. The panel's SwiftUI exit command handles Esc and calls the same close path that cancels an in-flight request.
Consequences: The app stays unactivated: `NSWorkspace.frontmostApplication` and the menu bar stay with the source app, and Replace still re-verifies that app. While the panel is visible it holds keyboard focus, so keystrokes and shortcuts go to the panel until the user clicks back into the source app; the setting turns this off. Every action still has a button.
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
@@ -149,4 +149,11 @@ 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.
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
+5
View File
@@ -155,3 +155,8 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
2026-11-26 · Panel · Fixed dragging: `performDrag` was a no-op while the non-activating panel's app is inactive, so `WindowDragArea` now moves the window from the screen-space mouse delta. The drag surface is a full-width 56 pt header bar flush with the panel top; buttons stay clickable above it. Verified with synthetic drags from the title, top edge, empty header and grip while Finder was frontmost.
2026-11-26 · Panel · Esc now closes the panel without a click: `TranslationPanel` becomes key on show without activating the app (`frontmostApplication` and the menu bar stay with the source app), and `keyDown` handles keyCode 53. Added the `closeWithEscape` setting (default on) and amended ADR-009.
2026-11-26 · Panel · Markdown translations render with headings, bold/italic, inline code, lists, quotes, fenced code, rules and http/https links. `MarkdownPresentation` rejects JSON/HTML/code and only renders with the `renderMarkdown` setting (default on); Copy/Replace stay raw. Added ADR-021 and tests.
2026-11-26 · Panel · A click outside the panel now closes it. The panel observes `didResignKey` and installs a transient global mouse-down monitor while visible; global monitors ignore events sent to this app, so panel/popover clicks are unaffected, and the monitor is removed on close. Verified: inside click keeps it open, outside click closes it with and without `closeWithEscape`, and an outside click while the language popover is open closes both.
2026-11-26 · Panel · Added an optional reverse direction: with the saved target German and fallback English, confidently German text is translated to English automatically, and vice versa. The saved target and effective target are separate; a banner offers a one-capture override, and the language picker still changes the saved target. `autoSwitchTarget` defaults on and `fallbackTargetLanguage` defaults to English/the opposite language. Filtered near-zero detector hypotheses so the high-confidence same-language rule works. Added resolver, settings, view-model and detector tests. (Superseded by the routing entry below.)
2026-11-26 · Settings · Replaced the single reverse-direction pair with language routing: the saved target is the mother tongue and the default for every source; an empty `languageRoutes` table means everything goes to the mother tongue. Optional source→target rules (for example Chinese → English) apply only to confidently detected sources. The panel shows the effective direction, offers a one-capture override, and keeps the picker session-only; persistent rules live in Settings. Removed the old fallback settings.
2026-11-27 · Panel · Fixed the header language picker: an override now carries the chosen language instead of only disabling routing. `TranslationDirectionPolicy.resolve` takes `override: ModelLanguage?`, and `PanelViewModel` stores the override target, so picking a language other than the mother tongue retranslates into it; a new capture still returns to the rule/mother tongue. Added picker and rule-override tests.
2026-11-27 · T3.2/T4.1/Settings · Long selections can now be translated in parts. The capture gate and the chunk size were the same number, so text over one chunk was rejected before the pipeline could split it. Added `maximumPartsPerSelection` (1–8, default 1, so existing behaviour is unchanged); the capture limit is now part size × parts, carried on `TranslationSessionRequest` and applied by the watcher, `CapturePolicy` and the session. `TranslationStreaming` can report each part, the session emits `chunkStarted`, and the panel shows “Part 2 of 4” while streaming and “3 parts” when finished. `textTooLong` now points at Settings and offers the Settings button. Lowered the dense-script part size maximum to 4000 (5000 dense characters plus a 4096-token output can overflow the 8192 context). Tests: capture limits, watcher limits, pipeline part callbacks, session events, panel progress and settings clamping. Docs: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES, README.
+1
View File
@@ -40,6 +40,7 @@ These are hard requirements. The `swift-reviewer` agent checks every change agai
| Screen Recording | Nothing | Never requested. No screenshots, no `CGWindowListCreateImage`, no `SCStream`. |
| Camera / Microphone | Nothing | Never requested. No `AVCaptureDevice`. |
| Apple Events | Nothing | Never requested. No `NSAppleScript` / `AEDeterminePermissionToAutomateTarget`. |
| Global mouse-down monitor | Dismiss the translation panel when the click goes to another app | Installed only while the panel is visible and removed on close. The event is discarded; no key events, location, text or app identity are read. Not a key tap and needs no Input Monitoring. |
## Clipboard rules
+2 -2
View File
@@ -33,7 +33,7 @@ Rules:
- Window: **500 ms** default, configurable 300–1000 ms.
- Identical text: compare normalized line endings and trimming only; do not collapse internal whitespace.
- Non-empty: at least one non-whitespace character.
- Length: 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts; above the limit, show `textTooLong` with the limit and no request.
- Length: part size 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts, multiplied by `maximumPartsPerSelection` (1–8, default 1); above that capture limit, show `textTooLong` with the limit, offer Settings and make no request.
- A new trigger during an active translation cancels the old one (ADR-015).
- Copying two different things quickly does not trigger; this is deliberate.
- Copying the same text twice slowly does not trigger; increase the window if needed.
@@ -160,7 +160,7 @@ Info.plist:
**This table is filled in by a person, on a real Mac.** Double copy, Accessibility replacement and clipboard restoration differ in every app and cannot be tested headlessly. Until a row is tested its cells stay ☐; an untested cell is not a claim.
Implementation status (2026-11-26): T3.1–T3.4 and T5.1–T5.4 are implemented and covered by component tests (`DoubleCopyDetector`, `PasteboardWatcher`, `ClipboardSnapshot`, `ServicesProvider`, `InsertionCoordinator`). The 4000/2000 limit and own-marker check apply to double copy, the menu item and Services (`CapturePolicy`). Replace captures the target at trigger time, re-verifies it, prefers AX and falls back to a snapshot/⌘V/restore path. The 10-app double-copy and insertion matrices remain untested; they are the T3.5/T5.5 manual tasks.
Implementation status (2026-11-26): T3.1–T3.4 and T5.1–T5.4 are implemented and covered by component tests (`DoubleCopyDetector`, `PasteboardWatcher`, `ClipboardSnapshot`, `ServicesProvider`, `InsertionCoordinator`). The script-aware part size × `maximumPartsPerSelection` capture limit and own-marker check apply to double copy, the menu item and Services (`CapturePolicy`). Replace captures the target at trigger time, re-verifies it, prefers AX and falls back to a snapshot/⌘V/restore path. The 10-app double-copy and insertion matrices remain untested; they are the T3.5/T5.5 manual tasks.
For each app test:
+13 -5
View File
@@ -24,10 +24,12 @@ The prompt prefix depends only on the target language. Append the source last. D
- Paragraph boundaries (blank lines) first.
- Then sentence boundaries (`.`, `!`, `?`, `。`, `!`, `?`, `…` followed by whitespace/end).
- Then word boundaries; never split a grapheme cluster.
- Limits: **4000 characters** for Latin/Cyrillic/Greek; **2000** for CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts. The limit is script-based, not language-based.
- Part size: **4000 characters** for Latin/Cyrillic/Greek; **2000** for CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts. The limit is script-based, not language-based.
- Capture limit: part size × `maximumPartsPerSelection` (1–8, default **1**). `1` rejects a selection longer than one part; higher values accept it and translate it part by part. The dense part size is configurable up to 4000.
- Reassemble with the original separators (usually `\n\n`). Do not collapse or invent paragraph breaks.
- Translate chunks sequentially; one request in flight.
- A chunk failure stops the sequence and is shown as `chunkFailed(index:)`; the panel keeps the partial translation and disables Replace.
- Translate parts sequentially; one request in flight.
- Show “Part i of n” while a multi-part request streams and “n parts” when it finishes.
- A part failure stops the sequence and is shown as `chunkFailed(index:)`; the panel keeps the partial translation and disables Replace.
## 4. Protected tokens
@@ -81,9 +83,15 @@ If detected: warning `preambleDetected(firstLine:)`; the panel shows a banner; R
- Repetition: the same normalised line (≥ 8 chars) repeated ≥ 6 times consecutively, or a 64-character window repeated ≥ 8 times in the last 2048 characters. Cancel the stream early and warn `repetitionLoop`.
- Empty output after T1 → `emptyOutput`; no Copy/Replace of an empty string.
## 8. Same-language input
## 8. Same-language input and language routing
If `NLLanguageRecognizer` reports the target language with confidence ≥ 0.5 and all detected candidates agree, show "This text already appears to be in {language}" and offer "Translate anyway". Do not block: short text, names and mixed text are often misdetected.
`NLLanguageRecognizer` reports the dominant language with a confidence and several candidates. Hypotheses below 0.05 are ignored, so a confident single-language text is not treated as mixed. The source is considered to be language `X` only when the confidence is at least 0.5 and every meaningful candidate resolves to `X`.
The saved target is the **mother tongue**. Every source language without a rule is translated into the mother tongue. Optional `languageRoutes` map a source language to a target language; a rule is used only when its source is confidently detected. Rules with source equal to target are ignored, and routes are deduplicated by source.
When a rule applies, the prompt, chunking and validation use its target. The panel shows the effective direction (for example "French → English"), a banner explains the rule, and "Translate to German" (the mother tongue) overrides the direction for that capture only. The panel's language picker is a session-only override; persistent rules are managed in Settings. When no rule applies, the same-language advisory appears if the source is the mother tongue.
Detection is advisory: short, mixed or uncertain text keeps the mother tongue, and the user can change the target for that result.
## 9. Numbers and units
+24 -1
View File
@@ -35,7 +35,7 @@ the Hy-MT3 model and the target language. You can reopen setup from the menu bar
1. Select text in any app.
2. Press **⌘C** twice quickly (within 500 ms).
3. The floating panel appears near the mouse. The source app stays frontmost; the panel takes keyboard focus while it is visible so Esc and the shortcuts work immediately. Clicking the source app takes focus back.
3. The floating panel appears near the mouse. The source app stays frontmost; the panel takes keyboard focus while it is visible so Esc and the shortcuts work immediately. Clicking the source app takes focus back. Clicking anywhere outside the panel closes it; Esc also closes it.
4. The translation streams in. Use the language picker to change the target.
5. Click **Copy** to put the translation on the clipboard, or **Replace** to replace the selection.
6. **Esc** closes the panel. **⌘C** copies, **⌘↩** replaces, **⌘R** retries and **⌘,** opens Settings.
@@ -43,6 +43,29 @@ the Hy-MT3 model and the target language. You can reopen setup from the menu bar
Replace is explicit; nothing is inserted automatically. Replace needs the macOS Accessibility
permission. Double copy, translation, Copy and the Services menu work without it.
### Mother tongue and language rules
The **mother tongue** is the default target for every source language. In
**Settings ▸ General ▸ Translation**, you can add **language rules** that override the default for
specific source languages:
```text
Mother tongue: German
Language rules:
Chinese (Simplified) → English
Traditional Chinese → English
German → English
```
With the table above, Chinese and German text go to English, and every other language goes to
German. An empty table means everything goes to the mother tongue.
Rules run in the order shown; a source language appears at most once. Rules apply only when the
source is confidently detected; short or mixed text keeps the mother tongue. When a rule applies,
the panel header shows the effective direction and a banner offers a one-capture override back to
the mother tongue. Choosing a language from the panel picker also overrides the current result only;
manage persistent rules in Settings.
## 4. Services and the menu bar
- **Services ▸ Translate with Sprachmittler** translates the current selection without polling