Compare commits

...
3 Commits
Author SHA1 Message Date
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
26 changed files with 854 additions and 159 deletions

No files matched your search

+4 -1
View File
@@ -217,6 +217,7 @@ final class AppEnvironment {
translationFontSize: settings.translationFontSize,
renderMarkdown: settings.renderMarkdown,
closeWithEscape: settings.closeWithEscape,
languageRoutes: settings.languageRoutes,
recentTargets: settings.recentTargets
)
}
@@ -224,13 +225,15 @@ final class AppEnvironment {
private func applySettings() {
let settings = settingsStore.current()
let previousTarget = panelViewModel.configuration.target.code
let previousRoutes = panelViewModel.configuration.languageRoutes
panelViewModel.updateConfiguration(configuration(for: settings))
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?()
+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)
+26 -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")) {
+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))
}
}
+6 -2
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")) {
+25 -20
View File
@@ -18,7 +18,7 @@ c989a2513d0b926f3a202b0616426c7443594ce72896ee91c29c4e83451d433c ./.opencode/sk
2c0c375f3f6704a43e1042b250e0b633ba740aa7bc2fbf5518891a7b5464507e ./.swiftlint.yml
3222c8553505401c967cc302e2d46a99db95f98d92650f6b245e2a1dc901bea9 ./AGENTS.md
593745fab27436e91148de34b7e0e530cef5137e2c566cb479caed033602b949 ./App/AppDelegate.swift
57bb84de7d482ba5a4a51126b647a99f595b1af8e3739a5db63dd4d6006f28bd ./App/AppEnvironment.swift
ffecf629fcbe9b5d3f85e9834f5a9c3eb794304a7cc20a45691d1943eb57d18a ./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
0d8e9dd5c361987e717e5425cb3a4bef2849a3ba5f40d302a4074f4847abf45b ./App/Panel/PanelController.swift
aa364e7cb6373cdeaea0c24f59c959ebcdca228be21a27c6fae431463a6d2c04 ./App/Panel/PanelView+Content.swift
278b9bd96ffe8c322703dec7c660632351c8e9a1996b0ee5713299f3de4ae082 ./App/Panel/PanelView.swift
e8ac837a35076814985d3320e5996c8cee00074bb9e1c8073804e20ed0c76f33 ./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,11 @@ 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
dcdaf8761f3b195e8c8d8889b2b792aa3dabbaa47b0c641fb4db4cdc09436026 ./App/Settings/README.md
13ded50c5202ce32bbe6d8432f0701f7d71bf9bc99e4b5e02e688b51416053b9 ./App/Settings/SettingsView.swift
b686d5d282bf569af3985099546195815c2bb5be1db74a2895d9c1b7eda12df1 ./App/Settings/SettingsView.swift
d3dcb4365c3d9ec39fa379b8e5cc0813745acc68dc851a85b4ab277896a2a5b1 ./App/Sprachmittler.entitlements
ddda3377a2e130e25195da349dd0964cfca8a401464b7b0cd8fcec6bfb575fa3 ./App/SprachmittlerApp.swift
c3d0de679f6d151f46cfdd11577eba65e1cff1f82be669be32e42a99fba302ba ./Makefile
@@ -69,7 +70,8 @@ ec2f66d1a2d8ebb308427802f54cc70c6bdead8c31a57ed87648446d6bda9ce1 ./Packages/Spr
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
f916e53b45650e03f3ff112cb35b67d52de48164f22aa0656a51d4a3353fb9b4 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift
9be13be1a6fdeb0c0dccfd86fc57036a8d9decdcb36e8e61360c269f3824309a ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift
7921d56341b4b6fe4392989b30de91bb2aeb91a8d52d840dc9602a3d5a6134dd ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift
5159e03a08507c4d6f61479cd4ce389e9541a8df4540ef6540cedaba6e8133a1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift
02421321864ecf0540a96b55a692e91eacb9364d579735d20b9ca94ebcf99a80 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureText.swift
@@ -84,7 +86,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
7219c7aebb87b8bfef097a4a21edfe3b57fd48a9b7f51fc2fd6ac09210ef1d96 ./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
@@ -104,7 +106,8 @@ d01aaf98c054bd3d14ce4d6055f576738d83b63037f246b0ec3cc302b130c12b ./Packages/Spr
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 +117,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
6003286e6bf37e77be54358c957528f1f8d519f0cc91fe0362df43d919ea715b ./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
@@ -161,7 +165,7 @@ c0f87a5320fe715f5dbc7c9bbc7c0fb19a5b64d1c145c45b26f060c151eccada ./Packages/Spr
3443a4e2a7d3d493b9d604875f0abec2f3a515fd162f6af41e25f48c78185b57 ./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
@@ -194,14 +198,14 @@ efac77b258ef29cca1cc61311ef8d167e45ad5680a73396a1b4bc6d99d9a3f45 ./Packages/Spr
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
f6929d7db0379c53a7e32ec16b3f0e8e56b6aa48cdc570b68fa06f6541da0b1f ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift
4ca70a674a35b723f7608bfe9b250b8572586ce4923e9965245626588935bb6e ./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
4d38405576e19f6ca28fe5141a3d33ed4a855400aa3c58a50ab86234d7dd1fd7 ./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
@@ -215,6 +219,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
efb51461777088bb379c843eb6c9395339ebf59b343fba4b3108eabff92e4ecc ./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,16 +251,16 @@ 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
eeff058dee89a14f9c9207bc5a28d5f06a733c9f596af7bd4553a90c199780cf ./README.md
615bd4d905b4f5c3330749444475ae601d542c6225cae28ad103928107c66fc0 ./README.md
f1dbc2fb876d909b8486239e9b75b09ed68516c341d586e96d8626715c86a88c ./dist/Sprachmittler-0.1.0-local.dmg
3b7b1fe301c5f715c6f4f74cc553a907c1ae89e669d5625d414dc3dae51d0216 ./docs/ARCHITECTURE.md
7e3d7e96941603d6838739080abc64d6c77d09efac28a4eda1591da57e6a6336 ./docs/ARCHITECTURE.md
018c5faf1a5d2e8d851ab209d45e64993cbd6b7976c4aa90c571359c83e83264 ./docs/CODING_STANDARDS.md
017ff14372220594a25a9d139145fa6cf05a3b50ddd2d1f54f8e98b6fe6463c9 ./docs/DECISIONS.md
3678c5d63ed05f279fb7a4923e677dff08353c898b65679107819b7c03228ff7 ./docs/DECISIONS.md
5b80ea8994519f2be34aa10abb345ac3029d3d3a29705dcfa0a1cb344f4b95d2 ./docs/HYMT3_MODEL.md
d87fc9df926f6ba77ce67b2731b83f48f2b49848c637f12d0fdfb5f27f3c6775 ./docs/IMPLEMENTATION_PLAN.md
c3a1838fb0a06acf6b7826f6ff278e15065af198dab22ffb1435dacdc064ad69 ./docs/KICKOFF.md
@@ -265,12 +270,12 @@ a28161210fbabe27d1348f3552851fe7b30c9dccc658272f2cc79af5e085ec40 ./docs/MODEL_E
e6dbccc3cb4c7a169a6daaa563066a6764a76b6b7649738b839dcbd9b2400ee5 ./docs/OPENCODE_V2.md
e2b785807ecb56eb1e7c02aaa6a487ce7c1be421865685bed4be2e973269bdce ./docs/PERFORMANCE.md
4a37cf1815071b3afdd10443ec9e05a5a78411d615c42f51117c5873922531c4 ./docs/PRD.md
e6208158c5230a63ddcf5fca4f6a7f9559f34c7026a5310398891955c6277b89 ./docs/PROGRESS.md
4166d08311ac386f89d6732302bfe6493730f7f00380565c1d188e3695640218 ./docs/PROGRESS.md
c72f39e7e5e1fb9c45c32f0741a379564debca4b408e702615d162f360d47ecf ./docs/SECURITY_PRIVACY.md
2e6c7ba67d857db7cddf1e31b5a6516f70b8094e9115094b58156f9e6626452c ./docs/SELECTION_AND_CLIPBOARD.md
8720e8bf79ba7ab051bb8bd09f55b7766f98941904f354cbe3ab7b88c941e860 ./docs/TESTING.md
d86aa67b08549ecce44e14d1e4fde0050ea5e89f77643733efd312fa42ef4e25 ./docs/TRANSLATION_OUTPUT.md
d59e6bf414777e4a068b08c2e81fcc3dee220034f0916e3867f338c4b7e6f4a3 ./docs/USER_GUIDE.md
555a42e170353fff25e349f61b7aef40e5b2a7ea7493d47e8c77ce15f3a70d14 ./docs/TRANSLATION_OUTPUT.md
5c4d63f01581cdbc21d7ff9da8604adf8230e280b42512e3375cd0a72a225f5a ./docs/USER_GUIDE.md
373b20746a6ed145ee598786458a97cead5cacd97a339db14b3e2341645c6c8d ./evaluation/README.md
a60f1917c64ac8c3df0d01dd55818652ae100a6d750c34be24675b33226cad45 ./evaluation/corpus.example.json
a5c4b95257aa02eca20ae98acf68dee329acb870f16fb3ac549038627327da71 ./evaluation/corpus.schema.json
@@ -0,0 +1,100 @@
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
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(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).
@@ -82,6 +84,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
model = HyMT3ModelPreset.defaultModel
fastModel = HyMT3ModelPreset.fastModel
targetLanguage = systemCode ?? HyMT3Languages.english.code
languageRoutes = []
recentTargetLanguages = []
doubleCopyWindowMs = 500
maxCharactersLatin = 4000
@@ -132,6 +135,7 @@ 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)
@@ -165,7 +169,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
Chunker(latinLimit: maxCharactersLatin, denseLimit: maxCharactersCJK)
}
private struct DecodedLimits {
struct DecodedLimits {
let window: Int
let latin: Int
let cjk: Int
@@ -174,14 +178,14 @@ public struct AppSettings: Codable, Sendable, Equatable {
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 {
@@ -217,7 +221,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
)
}
private static func decodeSampling(
static func decodeSampling(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings
) throws -> DecodedSampling {
@@ -237,8 +241,9 @@ public struct AppSettings: Codable, Sendable, Equatable {
)
}
private enum CodingKeys: String, CodingKey {
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, recentTargetLanguages
enum CodingKeys: String, CodingKey {
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, languageRoutes
case recentTargetLanguages
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict
case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown
@@ -246,95 +251,21 @@ public struct AppSettings: Codable, Sendable, Equatable {
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,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.
@@ -47,6 +50,7 @@ public struct PanelConfiguration: Sendable, Equatable {
translationFontSize: Int = 17,
renderMarkdown: Bool = true,
closeWithEscape: Bool = true,
languageRoutes: [LanguageRoute] = [],
recentTargets: [ModelLanguage] = []
) {
self.target = target
@@ -57,6 +61,7 @@ public struct PanelConfiguration: Sendable, Equatable {
self.translationFontSize = translationFontSize
self.renderMarkdown = renderMarkdown
self.closeWithEscape = closeWithEscape
self.languageRoutes = languageRoutes
self.recentTargets = recentTargets
}
}
@@ -83,8 +88,12 @@ 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 an optional reverse-direction switch.
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
@@ -100,9 +109,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 directionOverride = false
/// Creates a panel model.
public init(
@@ -112,10 +123,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 +194,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 +203,46 @@ public final class PanelViewModel {
warnings = []
error = nil
timing = nil
sourceLanguage = nil
didCopy = false
isReplacing = false
sameLanguageDismissed = false
if resetDirectionOverride {
directionOverride = false
}
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: directionOverride
)
effectiveTarget = direction.target
routedSource = direction.didRoute ? direction.source : nil
sameLanguageDismissed = directionOverride
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 +256,33 @@ public final class PanelViewModel {
warnings = []
timing = nil
sourceLanguage = nil
effectiveTarget = configuration.target
routedSource = nil
directionOverride = false
}
/// 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
directionOverride = true
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
directionOverride = true
sameLanguageDismissed = true
if let lastCaptured {
await begin(lastCaptured, resetDirectionOverride: false)
}
}
@@ -268,7 +317,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
directionOverride = false
}
}
/// Resets the panel and cancels the active request. The event stream stays open.
@@ -284,6 +339,9 @@ public final class PanelViewModel {
didCopy = false
isReplacing = false
sameLanguageDismissed = false
effectiveTarget = configuration.target
routedSource = nil
directionOverride = false
lastCaptured = nil
}
@@ -296,7 +354,7 @@ 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
@@ -308,7 +366,7 @@ public final class PanelViewModel {
case let .started(epoch, request):
currentEpoch = epoch
source = request.captured
configuration.target = request.target
effectiveTarget = request.target
translation = ""
warnings = []
error = 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,52 @@
import SprachmittlerText
/// The effective target for one translation, after an optional reverse-direction switch.
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: True after an explicit target choice for the current capture.
public static func resolve(
configuredTarget: ModelLanguage,
routes: [LanguageRoute],
detection: LanguageDetection?,
override: Bool
) -> TranslationDirection {
guard !override, 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)
}
}
@@ -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,
@@ -18,6 +18,7 @@ struct AppSettingsTests {
#expect(settings.maxCharactersCJK == 2000)
#expect(settings.numCtx == 8192)
#expect(settings.translationFontSize == 17)
#expect(settings.languageRoutes.isEmpty)
#expect(settings.renderMarkdown)
#expect(settings.closeWithEscape)
#expect(!settings.autoCopy)
@@ -32,6 +33,7 @@ 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
@@ -49,6 +51,8 @@ struct AppSettingsTests {
"settingsVersion": 0,
"endpoint": "http://127.0.0.1:11434",
"targetLanguage": "de",
"autoSwitchTarget": true,
"fallbackTargetLanguage": "en",
"autoCopy": true,
"unknownFutureKey": "ignored"
}
@@ -57,6 +61,7 @@ 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)
@@ -106,6 +111,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 +123,14 @@ 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.sanitize()
#expect(settings.doubleCopyWindowMs == 300)
@@ -127,6 +139,10 @@ struct AppSettingsTests {
#expect(settings.topK == 1)
#expect(settings.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
#expect(settings.translationFontSize == 28)
#expect(settings.languageRoutes == [
LanguageRoute(source: "de", target: "en"),
LanguageRoute(source: "zh", target: "en"),
])
#expect(!settings.autoCopy)
#expect(HyMT3Languages.resolve(settings.targetLanguage) != nil)
}
@@ -1,5 +1,6 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerText
import Testing
@testable import SprachmittlerCore
@@ -12,6 +13,12 @@ struct PanelViewModelTests {
source: .doubleCopy
)
private let germanCaptured = CapturedText(
text: "Hallo.",
capturedAt: Date(timeIntervalSince1970: 0),
source: .doubleCopy
)
@Test func streamsIntoThePanelAndCopyKeepsItOpen() async {
let (panel, copies, _) = makePanel(
streaming: ImmediateStreaming(deltas: ["Hal", "lo"], result: makeResult("Hallo"))
@@ -81,6 +88,141 @@ struct PanelViewModelTests {
#expect(panel.sameLanguageWarning == nil)
}
@Test func appliesAMatchingLanguageRule() async {
let detector = FixedDetector(
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 = FixedDetector(
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 = FixedDetector(
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 = FixedDetector(
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 explicitTargetPersistsAndDisablesTheRule() async {
let detector = FixedDetector(
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 = FixedDetector(
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 = FixedDetector(
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)
}
@Test func changingTargetRetranslatesAndNotifies() async {
let streaming = EchoStreaming()
let (panel, _, targets) = makePanel(streaming: streaming)
@@ -145,7 +287,10 @@ struct PanelViewModelTests {
private func makePanel(
streaming: any TranslationStreaming,
replacement: (@MainActor () async -> InsertionOutcome)? = nil,
onClose: @escaping @MainActor () -> Void = {}
onClose: @escaping @MainActor () -> Void = {},
detector: any LanguageDetecting = FixedDetector(detection: nil),
target: ModelLanguage = HyMT3Languages.german,
routes: [LanguageRoute] = []
) -> (PanelViewModel, CopiedTextBox, TargetBox) {
let session = TranslationSession(pipelineFactory: { streaming })
let copies = CopiedTextBox()
@@ -153,14 +298,16 @@ struct PanelViewModelTests {
let panel = PanelViewModel(
session: session,
configuration: PanelConfiguration(
target: HyMT3Languages.german,
target: target,
model: "test-hy-mt3",
keepAlive: "30m"
keepAlive: "30m",
languageRoutes: routes
),
copy: { copies.text = $0 },
replace: replacement,
onCloseRequest: onClose,
onTargetChanged: { targets.codes.append($0.code) }
onTargetChanged: { targets.codes.append($0.code) },
detector: detector
)
panel.startObserving()
return (panel, copies, targets)
@@ -271,3 +418,11 @@ private final class ReplaceBox: @unchecked Sendable {
private final class CloseBox: @unchecked Sendable {
var closed = false
}
private struct FixedDetector: LanguageDetecting {
let detection: LanguageDetection?
func detect(_ text: String) -> LanguageDetection? {
detection
}
}
@@ -0,0 +1,125 @@
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: false
)
#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: false
)
#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: false
)
#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: false
)
#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: false
)
#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: false
)
#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: false
)
#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: false
)
#expect(direction.target == german)
}
@Test func manualOverrideWins() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: detection("de"),
override: true
)
#expect(direction.target == german)
#expect(!direction.didRoute)
}
@Test func noDetectionUsesTheMotherTongue() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
routes: [LanguageRoute(source: "de", target: "en")],
detection: nil,
override: false
)
#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 {
+15 -1
View File
@@ -13,6 +13,7 @@ A user-facing installation, permission and troubleshooting guide is in [docs/USE
- 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.
@@ -102,6 +103,19 @@ The panel takes keyboard focus while it is visible by default, so Esc and the sh
| Replace the selection | **⌘↩** |
| Settings | **⌘,** |
### Mother tongue and language rules
The **mother tongue** is the default target for every source. In **Settings ▸ General ▸ Translation** you can add **language rules** that override it for a specific source language, for example:
```text
Mother tongue: German
Chinese (Simplified) → English
Traditional Chinese → English
German → English
```
With no rules, every language goes to the mother tongue. Rules apply only when the source is confidently detected; otherwise the mother tongue is used. The panel header shows the effective direction, a banner explains a rule and offers a one-capture override, and the panel language picker is a session-only override. Persistent rules live in Settings.
### Markdown
When the source looks like Markdown and **Settings ▸ General ▸ Translation ▸ Render Markdown formatting** is on (the default), the translation is rendered with headings, bold, italic, lists, quotes, fenced code and links. JSON, HTML and code sources are never Markdown-rendered. **Copy** and **Replace** always use the raw Markdown translation, not the rendered text. Only `http` and `https` links open, and only on an explicit click.
@@ -112,7 +126,7 @@ Replace verifies the source app and, when available, the selected text before to
### Settings
- **General** — target language, source preview, Markdown rendering, translation text size, Esc behaviour, double-copy window and startup.
- **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** — chunking and prompt policy.
- **Privacy** — local/remote endpoint policy and permissions.
+3
View File
@@ -554,6 +554,8 @@ 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 |
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.
@@ -587,6 +589,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 |
+8 -1
View File
@@ -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.
+2
View File
@@ -156,3 +156,5 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
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.
+8 -2
View File
@@ -81,9 +81,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
+23
View File
@@ -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