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.
This commit is contained in:
schihei committed 2026-11-26 18:31:45 +01:00
1 parent 41f1cea769
commit 940abcc996
24 files changed
+454 -336

No files matched your search

+1 -2
View File
@@ -217,8 +217,7 @@ final class AppEnvironment {
translationFontSize: settings.translationFontSize,
renderMarkdown: settings.renderMarkdown,
closeWithEscape: settings.closeWithEscape,
autoSwitchTarget: settings.autoSwitchTarget,
fallbackTarget: settings.fallbackTargetModel,
languageRoutes: settings.languageRoutes,
recentTargets: settings.recentTargets
)
}
+6 -6
View File
@@ -66,23 +66,23 @@ extension PanelView {
}
}
private func autoSwitchMessage(from original: ModelLanguage) -> String {
let source = original.localizedDisplayName
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 original = model.autoSwitchedFrom {
if let routedSource = model.routedSource {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "arrow.left.arrow.right.circle.fill")
.foregroundStyle(.blue)
.accessibilityHidden(true)
Text(autoSwitchMessage(from: original))
Text(routedMessage(from: routedSource))
.font(.callout)
Spacer()
Button(String(localized: "Translate to \(original.localizedDisplayName)")) {
Task { await model.overrideTarget(original) }
Button(String(localized: "Translate to \(model.configuration.target.localizedDisplayName)")) {
Task { await model.overrideTarget(model.configuration.target) }
}
.controlSize(.small)
}
+1 -1
View File
@@ -84,7 +84,7 @@ struct PanelView: View {
selection: Binding(
get: { model.effectiveTarget },
set: { language in
Task { await model.setTarget(language) }
Task { await model.overrideTarget(language) }
}
),
recent: model.configuration.recentTargets
+8 -4
View File
@@ -104,10 +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.";
"Translate the other direction when the text is already in the target language" = "In die andere Richtung übersetzen, wenn der Text bereits in der Zielsprache ist";
"Translate the other direction" = "In die andere Richtung übersetzen";
"Fallback target language" = "Ausweich-Zielsprache";
"Used only when the text is confidently detected as the target language." = "Wird nur verwendet, wenn der Text sicher als Zielsprache erkannt wird.";
"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.";
+8 -4
View File
@@ -104,10 +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.";
"Translate the other direction when the text is already in the target language" = "Translate the other direction when the text is already in the target language";
"Translate the other direction" = "Translate the other direction";
"Fallback target language" = "Fallback target language";
"Used only when the text is confidently detected as the target language." = "Used only when the text is confidently detected as the target language.";
"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.";
-54
View File
@@ -1,54 +0,0 @@
import SprachmittlerCore
import SprachmittlerEngines
import SwiftUI
/// The optional reverse-direction controls in Settings ▸ General.
struct FallbackTargetSettings: View {
@Binding var autoSwitchTarget: Bool
@Binding var fallbackTargetLanguage: String
let targetLanguage: String
let recentTargets: [ModelLanguage]
@State private var showLanguagePicker = false
private var fallbackTarget: ModelLanguage {
HyMT3Languages.resolve(fallbackTargetLanguage) ?? HyMT3Languages.english
}
var body: some View {
Toggle(
String(
localized: "Translate the other direction when the text is already in the target language"
),
isOn: $autoSwitchTarget
)
.accessibilityLabel(String(localized: "Translate the other direction"))
if autoSwitchTarget {
LabeledContent(String(localized: "Fallback target language")) {
Button {
showLanguagePicker.toggle()
} label: {
HStack {
Text(fallbackTarget.localizedDisplayName)
Image(systemName: "chevron.up.chevron.down")
.font(.caption)
}
}
.popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) {
LanguagePickerView(
selection: Binding(
get: { fallbackTarget },
set: { fallbackTargetLanguage = $0.code }
),
recent: recentTargets,
excluding: targetLanguage
)
}
.accessibilityLabel(String(localized: "Fallback target language"))
}
Text(String(localized: "Used only when the text is confidently detected as the target language."))
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
+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 -7
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,11 +126,7 @@ struct SettingsView: View {
)
.font(.caption)
.foregroundStyle(.secondary)
FallbackTargetSettings(
autoSwitchTarget: $draft.autoSwitchTarget,
fallbackTargetLanguage: $draft.fallbackTargetLanguage,
targetLanguage: draft.targetLanguage, recentTargets: draft.recentTargets
)
LanguageRulesSettings(routes: $draft.languageRoutes, motherTongue: draft.targetLanguageModel)
}
Section(String(localized: "Double copy")) {
+22 -21
View File
@@ -18,7 +18,7 @@ c989a2513d0b926f3a202b0616426c7443594ce72896ee91c29c4e83451d433c ./.opencode/sk
2c0c375f3f6704a43e1042b250e0b633ba740aa7bc2fbf5518891a7b5464507e ./.swiftlint.yml
3222c8553505401c967cc302e2d46a99db95f98d92650f6b245e2a1dc901bea9 ./AGENTS.md
593745fab27436e91148de34b7e0e530cef5137e2c566cb479caed033602b949 ./App/AppDelegate.swift
6b939be53c45030f2b72c8a7a9f818528feeaad5b8e82822227df5cba601a163 ./App/AppEnvironment.swift
3bb34a310ed421fa3e5eeb16817dab7b237adb177029d81cfe3018c35da5eb65 ./App/AppEnvironment.swift
dc41f554a88b5b499840f72ef676b31530e6ebfcc5da636155001c52ca48d8a1 ./App/Diagnostics/DiagnosticsView.swift
69f0c24937507ed7a9137abfa95fdcd2798cd909dd74642d4b5e6a859da94253 ./App/Info.plist
36aec6e936e6ffff104908b370a7231b9283e178df8d0a453639dca9c573460d ./App/LaunchAtLoginController.swift
@@ -30,8 +30,8 @@ ba9467153908c81fbb2497d5679642ae15c7b9fa23a10ca9b9ab678042aab222 ./App/Onboardi
382661bb55524acd7a686f215f8dd1cfdd4127dc19629dd637204c5b1e0734e9 ./App/Panel/LanguagePickerView.swift
76dcf59e01ae8319d4f0aabc5e600c549adaf56b6db802794804c3215be9377c ./App/Panel/MarkdownTranslationView.swift
0d8e9dd5c361987e717e5425cb3a4bef2849a3ba5f40d302a4074f4847abf45b ./App/Panel/PanelController.swift
1887d05e9b6e24658787f57cb0fcc347352a831b8c8322a4af54d18720d264b7 ./App/Panel/PanelView+Content.swift
41c47cba0a4ff81a8e97210c91642fcc1e15330d5917e44cfd01792c0b13c623 ./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,11 +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
63f4c90b4347e48a7e7bd81bafee1e2f8c251e220b463f3fdb19c82b33ab43b3 ./App/Resources/de.lproj/Localizable.strings
679983eb225cd2de1b996168bdee527018b1f2a3130e51ab7a5224e115d15af4 ./App/Resources/en.lproj/Localizable.strings
d24fada1051cf3412ceac9d0da308cf510c450b4891fa14d0c8c3defd08a9d3d ./App/Settings/FallbackTargetSettings.swift
ce0c088300a0a739ecc0a73892aad6b9538397d637760962a810dbf65692f62b ./App/Resources/de.lproj/Localizable.strings
ac67edd346d0828cd0e86cae4e3da719a9e574d22217f0f15a6d30558bd76e14 ./App/Resources/en.lproj/Localizable.strings
5c2e5222430e1822c3e13cdfed202f54cabc32beefb7651af78475b29494dcf2 ./App/Settings/LanguageRulesSettings.swift
dcdaf8761f3b195e8c8d8889b2b792aa3dabbaa47b0c641fb4db4cdc09436026 ./App/Settings/README.md
d0e25575fc43e42b8fa5da74499396499a3112334f80edeebaaa0a715c505b30 ./App/Settings/SettingsView.swift
b686d5d282bf569af3985099546195815c2bb5be1db74a2895d9c1b7eda12df1 ./App/Settings/SettingsView.swift
d3dcb4365c3d9ec39fa379b8e5cc0813745acc68dc851a85b4ab277896a2a5b1 ./App/Sprachmittler.entitlements
ddda3377a2e130e25195da349dd0964cfca8a401464b7b0cd8fcec6bfb575fa3 ./App/SprachmittlerApp.swift
c3d0de679f6d151f46cfdd11577eba65e1cff1f82be669be32e42a99fba302ba ./Makefile
@@ -70,8 +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
37f715a9755db8c21bde2f9e957a5023c8892b2c90282bb2fdd5495302c121a9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift
fe257f0e38b0b6b65eae175d8f6360358ab7956b8c611b460e66259926770eb7 ./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
@@ -86,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
20e2a546fad6ccfee5458889d5c0a6601af0d8602eedc44a29a1da69f3eb3416 ./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
@@ -106,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
@@ -116,7 +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
b09e5a629c23405f1097a79c6a2ba13dbd93cdca307ee885e47c79fff8f239c5 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationDirection.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
@@ -197,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
d8347d9f17250e5e6a130596855dce10e4a8ea37305ac3fd2019ec3fc5b31b07 ./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
954dd7e4c6b06603a3619c3f112bb67049cdff32038c5cdea2ecd9b79fd07f61 ./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
@@ -218,7 +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
7df7f5675c61b74f752870cb56824054fdbb73878ccc35f99c105fd55c442af4 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/TranslationDirectionTests.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
@@ -255,11 +256,11 @@ b0a7d3451d8830654fe79476b8d32d95709d956817a4436f58c0f73bbd8d3194 ./Packages/Spr
8c5c21634d749ad05da8b6a0fc1d8e132a494177a697ba0a1338a7a6b5dba50c ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/PlaceholderTests.swift
67c0f9ba9e818267e99c1756b82643f7e59effa6783325675386aba0a1002cb3 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ProtectedTokenScannerTests.swift
c3294d486cfe44a6f0a69a1ec05cff33a8eccf090fce04fadffa96b6b2563d6f ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/TextNormalizationTests.swift
ae0f9746adc229ad1140b6961fd392c8cb7a9b3ccddc83236d2d8ef88232f393 ./README.md
615bd4d905b4f5c3330749444475ae601d542c6225cae28ad103928107c66fc0 ./README.md
f1dbc2fb876d909b8486239e9b75b09ed68516c341d586e96d8626715c86a88c ./dist/Sprachmittler-0.1.0-local.dmg
2b6df8cf5b6637e217288c87c51f981b8d84c60de336aff72986115f302d704a ./docs/ARCHITECTURE.md
7e3d7e96941603d6838739080abc64d6c77d09efac28a4eda1591da57e6a6336 ./docs/ARCHITECTURE.md
018c5faf1a5d2e8d851ab209d45e64993cbd6b7976c4aa90c571359c83e83264 ./docs/CODING_STANDARDS.md
5cc9fcccdf45a55e6be22c4e19faa8f1bb07bc7a8e8b64a43532a8fe627c131d ./docs/DECISIONS.md
3678c5d63ed05f279fb7a4923e677dff08353c898b65679107819b7c03228ff7 ./docs/DECISIONS.md
5b80ea8994519f2be34aa10abb345ac3029d3d3a29705dcfa0a1cb344f4b95d2 ./docs/HYMT3_MODEL.md
d87fc9df926f6ba77ce67b2731b83f48f2b49848c637f12d0fdfb5f27f3c6775 ./docs/IMPLEMENTATION_PLAN.md
c3a1838fb0a06acf6b7826f6ff278e15065af198dab22ffb1435dacdc064ad69 ./docs/KICKOFF.md
@@ -269,12 +270,12 @@ a28161210fbabe27d1348f3552851fe7b30c9dccc658272f2cc79af5e085ec40 ./docs/MODEL_E
e6dbccc3cb4c7a169a6daaa563066a6764a76b6b7649738b839dcbd9b2400ee5 ./docs/OPENCODE_V2.md
e2b785807ecb56eb1e7c02aaa6a487ce7c1be421865685bed4be2e973269bdce ./docs/PERFORMANCE.md
4a37cf1815071b3afdd10443ec9e05a5a78411d615c42f51117c5873922531c4 ./docs/PRD.md
be500879c3170a776dbe15697a8138d18b8961312c95be6373c665a575804ab9 ./docs/PROGRESS.md
4166d08311ac386f89d6732302bfe6493730f7f00380565c1d188e3695640218 ./docs/PROGRESS.md
c72f39e7e5e1fb9c45c32f0741a379564debca4b408e702615d162f360d47ecf ./docs/SECURITY_PRIVACY.md
2e6c7ba67d857db7cddf1e31b5a6516f70b8094e9115094b58156f9e6626452c ./docs/SELECTION_AND_CLIPBOARD.md
8720e8bf79ba7ab051bb8bd09f55b7766f98941904f354cbe3ab7b88c941e860 ./docs/TESTING.md
c3c232d61ad70ebf375d1a7ad3cfcfd51810c86ff89d7a01fcd10c9bf3440fb6 ./docs/TRANSLATION_OUTPUT.md
ff36cf983bfb0ee16730ae9229d32a607b95ccb054d1069ffc090c2edc5b0311 ./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
@@ -1,13 +1,8 @@
import Foundation
import SprachmittlerEngines
private struct DecodedDirection {
let autoSwitch: Bool
let fallback: String
}
extension AppSettings {
public init(from decoder: any Decoder) throws {
public extension AppSettings {
init(from decoder: any Decoder) throws {
let defaults = AppSettings()
let container = try decoder.container(keyedBy: CodingKeys.self)
@@ -21,9 +16,9 @@ extension AppSettings {
let decodedTarget = try container.decodeIfPresent(String.self, forKey: .targetLanguage)
?? defaults.targetLanguage
targetLanguage = HyMT3Languages.resolve(decodedTarget)?.code ?? defaults.targetLanguage
let direction = try Self.decodeDirection(from: container, defaults: defaults, target: targetLanguage)
autoSwitchTarget = direction.autoSwitch
fallbackTargetLanguage = direction.fallback
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
@@ -60,15 +55,14 @@ extension AppSettings {
settingsVersion = Self.currentVersion
}
public func encode(to encoder: any Encoder) throws {
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(autoSwitchTarget, forKey: .autoSwitchTarget)
try container.encode(fallbackTargetLanguage, forKey: .fallbackTargetLanguage)
try container.encode(languageRoutes, forKey: .languageRoutes)
try container.encode(recentTargetLanguages, forKey: .recentTargetLanguages)
try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs)
try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin)
@@ -93,21 +87,6 @@ extension AppSettings {
try container.encode(settingsVersion, forKey: .settingsVersion)
}
private static func decodeDirection(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings,
target: String
) throws -> DecodedDirection {
let autoSwitch = try container.decodeIfPresent(Bool.self, forKey: .autoSwitchTarget)
?? defaults.autoSwitchTarget
let code = try container.decodeIfPresent(String.self, forKey: .fallbackTargetLanguage)
?? defaults.fallbackTargetLanguage
return DecodedDirection(
autoSwitch: autoSwitch,
fallback: AppSettings.normalizedFallback(code, target: target)
)
}
private static func decodeRecentTargets(
from container: KeyedDecodingContainer<CodingKeys>
) throws -> [String] {
@@ -27,12 +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
/// Translate into the fallback when the source is already the target.
public var autoSwitchTarget: Bool
/// The fallback target BCP-47 code used by `autoSwitchTarget`.
public var fallbackTargetLanguage: 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).
@@ -86,10 +84,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
model = HyMT3ModelPreset.defaultModel
fastModel = HyMT3ModelPreset.fastModel
targetLanguage = systemCode ?? HyMT3Languages.english.code
autoSwitchTarget = true
fallbackTargetLanguage = targetLanguage == HyMT3Languages.english.code
? HyMT3Languages.german.code
: HyMT3Languages.english.code
languageRoutes = []
recentTargetLanguages = []
doubleCopyWindowMs = 500
maxCharactersLatin = 4000
@@ -119,11 +114,6 @@ public struct AppSettings: Codable, Sendable, Equatable {
HyMT3Languages.resolve(targetLanguage) ?? HyMT3Languages.english
}
/// The fallback target, always a catalogue entry.
public var fallbackTargetModel: ModelLanguage {
HyMT3Languages.resolve(fallbackTargetLanguage) ?? HyMT3Languages.english
}
/// The recent targets that still exist in the catalogue.
public var recentTargets: [ModelLanguage] {
recentTargetLanguages.compactMap(HyMT3Languages.resolve)
@@ -136,9 +126,6 @@ public struct AppSettings: Codable, Sendable, Equatable {
/// Records a target as recent, keeping at most three unique codes.
public mutating func noteTarget(_ language: ModelLanguage) {
if language.code != targetLanguage, language.code == fallbackTargetLanguage {
fallbackTargetLanguage = targetLanguage
}
targetLanguage = language.code
recentTargetLanguages.removeAll { $0 == language.code }
recentTargetLanguages.insert(language.code, at: 0)
@@ -148,7 +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
fallbackTargetLanguage = Self.normalizedFallback(fallbackTargetLanguage, target: targetLanguage)
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)
@@ -255,8 +242,8 @@ public struct AppSettings: Codable, Sendable, Equatable {
}
enum CodingKeys: String, CodingKey {
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, autoSwitchTarget
case fallbackTargetLanguage, recentTargetLanguages
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
@@ -264,12 +251,18 @@ public struct AppSettings: Codable, Sendable, Equatable {
case settingsVersion
}
static func normalizedFallback(_ code: String, target: String) -> String {
let resolved = HyMT3Languages.resolve(code)?.code ?? HyMT3Languages.english.code
guard resolved == target else { return resolved }
return target == HyMT3Languages.english.code
? HyMT3Languages.german.code
: HyMT3Languages.english.code
static func normalizedRoutes(_ routes: [LanguageRoute]) -> [LanguageRoute] {
var seen = Set<String>()
return routes.compactMap { route in
guard let source = HyMT3Languages.resolve(route.source)?.code,
let target = HyMT3Languages.resolve(route.target)?.code,
source.caseInsensitiveCompare(target) != .orderedSame,
seen.insert(source.lowercased()).inserted
else {
return nil
}
return LanguageRoute(source: source, target: target)
}
}
static func clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
@@ -21,10 +21,8 @@ public enum PanelPhase: Sendable, Equatable {
public struct PanelConfiguration: Sendable, Equatable {
/// The selected target language.
public var target: ModelLanguage
/// Whether the source-equals-target direction switches to `fallbackTarget`.
public var autoSwitchTarget: Bool
/// The fallback target used when the source is already the target.
public var fallbackTarget: 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.
@@ -52,8 +50,7 @@ public struct PanelConfiguration: Sendable, Equatable {
translationFontSize: Int = 17,
renderMarkdown: Bool = true,
closeWithEscape: Bool = true,
autoSwitchTarget: Bool = true,
fallbackTarget: ModelLanguage? = HyMT3Languages.english,
languageRoutes: [LanguageRoute] = [],
recentTargets: [ModelLanguage] = []
) {
self.target = target
@@ -64,8 +61,7 @@ public struct PanelConfiguration: Sendable, Equatable {
self.translationFontSize = translationFontSize
self.renderMarkdown = renderMarkdown
self.closeWithEscape = closeWithEscape
self.autoSwitchTarget = autoSwitchTarget
self.fallbackTarget = fallbackTarget
self.languageRoutes = languageRoutes
self.recentTargets = recentTargets
}
}
@@ -96,8 +92,8 @@ public final class PanelViewModel {
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 saved target that was replaced by `effectiveTarget`, or nil.
public private(set) var autoSwitchedFrom: 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
@@ -217,13 +213,12 @@ public final class PanelViewModel {
sourceLanguage = detection?.code
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: configuration.target,
fallbackTarget: configuration.fallbackTarget,
routes: configuration.languageRoutes,
detection: detection,
autoSwitch: configuration.autoSwitchTarget,
override: directionOverride
)
effectiveTarget = direction.target
autoSwitchedFrom = direction.didSwitch ? direction.originalTarget : nil
routedSource = direction.didRoute ? direction.source : nil
sameLanguageDismissed = directionOverride
phase = .translating
}
@@ -262,7 +257,7 @@ public final class PanelViewModel {
timing = nil
sourceLanguage = nil
effectiveTarget = configuration.target
autoSwitchedFrom = nil
routedSource = nil
directionOverride = false
}
@@ -271,7 +266,7 @@ public final class PanelViewModel {
guard language.code != effectiveTarget.code else { return }
configuration.target = language
effectiveTarget = language
autoSwitchedFrom = nil
routedSource = nil
directionOverride = true
onTargetChanged(language)
if let lastCaptured {
@@ -283,7 +278,7 @@ public final class PanelViewModel {
public func overrideTarget(_ language: ModelLanguage) async {
guard language.code != effectiveTarget.code else { return }
effectiveTarget = language
autoSwitchedFrom = nil
routedSource = nil
directionOverride = true
sameLanguageDismissed = true
if let lastCaptured {
@@ -326,7 +321,7 @@ public final class PanelViewModel {
self.configuration = configuration
if targetChanged || source == nil {
effectiveTarget = configuration.target
autoSwitchedFrom = nil
routedSource = nil
directionOverride = false
}
}
@@ -345,7 +340,7 @@ public final class PanelViewModel {
isReplacing = false
sameLanguageDismissed = false
effectiveTarget = configuration.target
autoSwitchedFrom = nil
routedSource = nil
directionOverride = false
lastCaptured = 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)
}
}
@@ -4,16 +4,16 @@ import SprachmittlerText
public struct TranslationDirection: Sendable, Equatable {
/// The language the request will translate into.
public let target: ModelLanguage
/// True when the configured target was replaced by the fallback target.
public let didSwitch: Bool
/// The configured target when `didSwitch` is true.
public let originalTarget: 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, didSwitch: Bool, originalTarget: ModelLanguage?) {
public init(target: ModelLanguage, didRoute: Bool, source: ModelLanguage?) {
self.target = target
self.didSwitch = didSwitch
self.originalTarget = originalTarget
self.didRoute = didRoute
self.source = source
}
}
@@ -23,25 +23,30 @@ public enum TranslationDirectionPolicy {
/// Resolves the target.
///
/// - Parameters:
/// - configuredTarget: The user's saved target language.
/// - fallbackTarget: The language to use when the source is already the configured target.
/// - configuredTarget: The user's mother tongue, used when no rule matches.
/// - routes: The source-to-target rules.
/// - detection: The advisory source-language detection.
/// - autoSwitch: Whether the fallback is enabled.
/// - override: True after an explicit target choice for the current capture.
public static func resolve(
configuredTarget: ModelLanguage,
fallbackTarget: ModelLanguage?,
routes: [LanguageRoute],
detection: LanguageDetection?,
autoSwitch: Bool,
override: Bool
) -> TranslationDirection {
guard autoSwitch, !override, let fallbackTarget,
fallbackTarget.code.caseInsensitiveCompare(configuredTarget.code) != .orderedSame,
let detection,
LanguageMatching.isSameLanguage(detection, target: configuredTarget)
else {
return TranslationDirection(target: configuredTarget, didSwitch: false, originalTarget: nil)
guard !override, let detection else {
return TranslationDirection(target: configuredTarget, didRoute: false, source: nil)
}
return TranslationDirection(target: fallbackTarget, didSwitch: true, originalTarget: configuredTarget)
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)
}
}
@@ -18,9 +18,7 @@ struct AppSettingsTests {
#expect(settings.maxCharactersCJK == 2000)
#expect(settings.numCtx == 8192)
#expect(settings.translationFontSize == 17)
#expect(settings.autoSwitchTarget)
#expect(HyMT3Languages.resolve(settings.fallbackTargetLanguage) != nil)
#expect(settings.fallbackTargetLanguage != settings.targetLanguage)
#expect(settings.languageRoutes.isEmpty)
#expect(settings.renderMarkdown)
#expect(settings.closeWithEscape)
#expect(!settings.autoCopy)
@@ -35,8 +33,7 @@ struct AppSettingsTests {
settings.noteTarget(HyMT3Languages.german)
settings.temperature = 0.2
settings.translationFontSize = 22
settings.autoSwitchTarget = false
settings.fallbackTargetLanguage = "fr"
settings.languageRoutes = [LanguageRoute(source: "zh", target: "en")]
settings.renderMarkdown = false
settings.closeWithEscape = false
settings.launchAtLogin = true
@@ -54,6 +51,8 @@ struct AppSettingsTests {
"settingsVersion": 0,
"endpoint": "http://127.0.0.1:11434",
"targetLanguage": "de",
"autoSwitchTarget": true,
"fallbackTargetLanguage": "en",
"autoCopy": true,
"unknownFutureKey": "ignored"
}
@@ -62,9 +61,7 @@ struct AppSettingsTests {
#expect(decoded.settingsVersion == AppSettings.currentVersion)
#expect(decoded.targetLanguage == "de")
#expect(decoded.model == HyMT3ModelPreset.defaultModel)
#expect(decoded.autoSwitchTarget)
#expect(HyMT3Languages.resolve(decoded.fallbackTargetLanguage) != nil)
#expect(decoded.fallbackTargetLanguage != decoded.targetLanguage)
#expect(decoded.languageRoutes.isEmpty)
#expect(decoded.renderMarkdown)
#expect(decoded.closeWithEscape)
#expect(!decoded.autoCopy)
@@ -99,7 +96,6 @@ struct AppSettingsTests {
"repeatPenalty": 9,
"keepModelLoaded": "forever",
"translationFontSize": 99,
"fallbackTargetLanguage": "xx",
"targetLanguage": "xx"
}
"""
@@ -115,8 +111,7 @@ struct AppSettingsTests {
#expect(decoded.repeatPenalty == 2)
#expect(decoded.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
#expect(decoded.translationFontSize == 28)
#expect(HyMT3Languages.resolve(decoded.fallbackTargetLanguage) != nil)
#expect(decoded.fallbackTargetLanguage != decoded.targetLanguage)
#expect(decoded.languageRoutes.isEmpty)
#expect(HyMT3Languages.resolve(decoded.targetLanguage) != nil)
}
@@ -128,7 +123,12 @@ struct AppSettingsTests {
settings.topK = 0
settings.keepModelLoaded = "forever"
settings.translationFontSize = 99
settings.fallbackTargetLanguage = "de"
settings.languageRoutes = [
LanguageRoute(source: "xx", target: "en"),
LanguageRoute(source: "de", target: "de"),
LanguageRoute(source: "de", target: "en"),
LanguageRoute(source: "zh-Hans", target: "en"),
]
settings.autoCopy = true
settings.targetLanguage = "de"
settings.sanitize()
@@ -139,33 +139,14 @@ struct AppSettingsTests {
#expect(settings.topK == 1)
#expect(settings.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
#expect(settings.translationFontSize == 28)
#expect(settings.fallbackTargetLanguage == "en")
#expect(settings.languageRoutes == [
LanguageRoute(source: "de", target: "en"),
LanguageRoute(source: "zh", target: "en"),
])
#expect(!settings.autoCopy)
#expect(HyMT3Languages.resolve(settings.targetLanguage) != nil)
}
@Test func changingToTheFallbackSwapsThePair() {
var settings = AppSettings()
settings.targetLanguage = HyMT3Languages.german.code
settings.fallbackTargetLanguage = HyMT3Languages.english.code
settings.noteTarget(HyMT3Languages.english)
#expect(settings.targetLanguage == HyMT3Languages.english.code)
#expect(settings.fallbackTargetLanguage == HyMT3Languages.german.code)
}
@Test func sanitizeKeepsTheFallbackDifferentFromTheTarget() {
var settings = AppSettings()
settings.targetLanguage = HyMT3Languages.german.code
settings.fallbackTargetLanguage = HyMT3Languages.german.code
settings.sanitize()
#expect(settings.fallbackTargetLanguage == HyMT3Languages.english.code)
settings.targetLanguage = HyMT3Languages.english.code
settings.fallbackTargetLanguage = HyMT3Languages.english.code
settings.sanitize()
#expect(settings.fallbackTargetLanguage == HyMT3Languages.german.code)
}
@Test func endpointPolicyIsEnforced() throws {
var settings = AppSettings()
settings.endpoint = try #require(URL(string: "http://192.168.1.10:11434"))
@@ -88,26 +88,66 @@ struct PanelViewModelTests {
#expect(panel.sameLanguageWarning == nil)
}
@Test func autoSwitchesWhenTheSourceIsTheTarget() async {
@Test func appliesAMatchingLanguageRule() async {
let detector = FixedDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true)
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.autoSwitchedFrom == HyMT3Languages.german)
#expect(panel.routedSource == HyMT3Languages.german)
#expect(panel.configuration.target == HyMT3Languages.german)
#expect(panel.translation == "en")
}
@Test func autoSwitchOverrideIsSessionOnly() async {
@Test func noRuleKeepsTheMotherTongue() async {
let detector = FixedDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, targets) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true)
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 }
@@ -115,16 +155,20 @@ struct PanelViewModelTests {
await waitFor { panel.phase == .ready && panel.translation == "de" }
#expect(panel.effectiveTarget == HyMT3Languages.german)
#expect(panel.autoSwitchedFrom == nil)
#expect(panel.routedSource == nil)
#expect(panel.configuration.target == HyMT3Languages.german)
#expect(targets.codes.isEmpty)
}
@Test func explicitTargetPersistsAndDisablesAutoSwitch() async {
@Test func explicitTargetPersistsAndDisablesTheRule() async {
let detector = FixedDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, targets) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true)
let (panel, _, targets) = makePanel(
streaming: EchoStreaming(),
detector: detector,
routes: [LanguageRoute(source: "de", target: "en")]
)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
@@ -133,7 +177,7 @@ struct PanelViewModelTests {
#expect(targets.codes == ["de"])
#expect(panel.effectiveTarget == HyMT3Languages.german)
#expect(panel.autoSwitchedFrom == nil)
#expect(panel.routedSource == nil)
}
@Test func retryKeepsTheManualTarget() async {
@@ -141,7 +185,11 @@ struct PanelViewModelTests {
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let streaming = EchoStreaming()
let (panel, _, _) = makePanel(streaming: streaming, detector: detector, autoSwitch: true)
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)
@@ -158,7 +206,11 @@ struct PanelViewModelTests {
let detector = FixedDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true)
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)
@@ -168,7 +220,7 @@ struct PanelViewModelTests {
await waitFor { panel.phase == .ready && panel.translation == "en" }
#expect(panel.effectiveTarget == HyMT3Languages.english)
#expect(panel.autoSwitchedFrom == HyMT3Languages.german)
#expect(panel.routedSource == HyMT3Languages.german)
}
@Test func changingTargetRetranslatesAndNotifies() async {
@@ -237,9 +289,8 @@ struct PanelViewModelTests {
replacement: (@MainActor () async -> InsertionOutcome)? = nil,
onClose: @escaping @MainActor () -> Void = {},
detector: any LanguageDetecting = FixedDetector(detection: nil),
autoSwitch: Bool = false,
target: ModelLanguage = HyMT3Languages.german,
fallback: ModelLanguage? = HyMT3Languages.english
routes: [LanguageRoute] = []
) -> (PanelViewModel, CopiedTextBox, TargetBox) {
let session = TranslationSession(pipelineFactory: { streaming })
let copies = CopiedTextBox()
@@ -250,8 +301,7 @@ struct PanelViewModelTests {
target: target,
model: "test-hy-mt3",
keepAlive: "30m",
autoSwitchTarget: autoSwitch,
fallbackTarget: fallback
languageRoutes: routes
),
copy: { copies.text = $0 },
replace: replacement,
@@ -15,103 +15,111 @@ struct TranslationDirectionTests {
LanguageDetection(code: code, confidence: confidence, alternatives: alternatives ?? [code])
}
@Test func keepsTheConfiguredTargetWhenTheSourceIsDifferent() {
@Test func usesTheMotherTongueWithoutRules() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
routes: [],
detection: detection("en"),
autoSwitch: true,
override: false
)
#expect(direction == TranslationDirection(target: german, didSwitch: false, originalTarget: nil))
#expect(direction == TranslationDirection(target: german, didRoute: false, source: nil))
}
@Test func switchesWhenTheSourceIsConfidentlyTheTarget() {
@Test func appliesAMatchingRule() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
routes: [LanguageRoute(source: "de", target: "en")],
detection: detection("de"),
autoSwitch: true,
override: false
)
#expect(direction == TranslationDirection(target: english, didSwitch: true, originalTarget: german))
#expect(direction == TranslationDirection(target: english, didRoute: true, source: german))
}
@Test func doesNotSwitchWhenDisabled() {
@Test func appliesAnArbitrarySourceRule() throws {
let french = try #require(HyMT3Languages.resolve("fr"))
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
detection: detection("de"),
autoSwitch: false,
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.didSwitch)
#expect(!direction.didRoute)
}
@Test func doesNotSwitchAfterAManualOverride() {
@Test func ignoresARuleWhoseTargetEqualsItsSource() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
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"),
autoSwitch: true,
override: true
)
#expect(direction.target == german)
#expect(!direction.didSwitch)
#expect(!direction.didRoute)
}
@Test func doesNotSwitchWithLowConfidence() {
@Test func noDetectionUsesTheMotherTongue() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
detection: detection("de", confidence: 0.49),
autoSwitch: true,
routes: [LanguageRoute(source: "de", target: "en")],
detection: nil,
override: false
)
#expect(direction.target == german)
}
@Test func doesNotSwitchWhenTheAlternativesDisagree() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
detection: detection("de", alternatives: ["de", "en"]),
autoSwitch: true,
override: false
)
#expect(direction.target == german)
}
@Test func doesNotSwitchWhenTheFallbackIsTheTarget() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: german,
detection: detection("de"),
autoSwitch: true,
override: false
)
#expect(direction.target == german)
}
@Test func doesNotSwitchWithoutAFallbackOrDetection() {
#expect(
TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: nil,
detection: detection("de"),
autoSwitch: true,
override: false
).target == german
)
#expect(
TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
detection: nil,
autoSwitch: true,
override: false
).target == german
)
}
}
+13 -4
View File
@@ -13,7 +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.
- Automatic reverse direction: with target German and fallback English, German text is translated to English and English text to German.
- 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.
@@ -103,9 +103,18 @@ The panel takes keyboard focus while it is visible by default, so Esc and the sh
| Replace the selection | **⌘↩** |
| Settings | **⌘,** |
### Translating the other direction
### Mother tongue and language rules
When the source is confidently detected as the saved target language, the panel translates into the configured fallback language instead. The header and banner show the effective direction, and the banner offers a one-capture override. **Settings ▸ General ▸ Translation** controls this; it is on by default with English as the fallback (German when the target is English).
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
@@ -117,7 +126,7 @@ Replace verifies the source app and, when available, the selected text before to
### Settings
- **General** — target language, fallback 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.
+2 -3
View File
@@ -554,7 +554,7 @@ 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 |
When the source is confidently detected as the saved target language, the panel can translate into the configured fallback target instead. The saved target and the effective target are separate: the header and language picker show the effective target, a banner explains the switch and offers a one-capture override, and the language picker still changes the saved target. Detection remains advisory and uses the same high-confidence rule as the same-language advisory.
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.
@@ -589,8 +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) |
| `autoSwitchTarget` | Bool | true (optional reverse direction when the source is already the target) |
| `fallbackTargetLanguage` | String | `en` (or `de` when the target is English; always differs from the target) |
| `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 |
+4 -4
View File
@@ -151,9 +151,9 @@ Context: Hy-MT3 preserves Markdown structure, but a plain `Text` showed `**bold*
Decision: Parse presentation Markdown in `SprachmittlerText` with Foundation's inline Markdown parser plus a small, conservative block parser (headings, lists, quotes, fenced code, rules, paragraphs). `MarkdownPresentation.shouldRender` rejects JSON, HTML and code sources and otherwise requires block or inline Markdown markers. The panel renders only when the setting `renderMarkdown` is on (default). Copy and Replace use the raw translation unchanged. Only `http` and `https` links open, on an explicit click; image syntax is reduced to alt text and no remote resource is fetched. Tables, raw HTML and nested lists/quotes remain plain text in this pass.
Consequences: Rendering never rewrites the translation or weakens validation. Literal markers can be interpreted as formatting, so the setting is the escape hatch; Copy always returns the raw Markdown. The block layout makes text selection per block, while Copy remains the whole-translation path. No new dependency is added.
## ADR-022 — Optional reverse direction for source-equals-target text
## ADR-022 — Language routing: mother tongue plus source-to-target rules
Status: Accepted
Context: A single saved target language is simple, but selecting text that is already in that language produced a same-language translation and an advisory. Users working in a two-language pair want the opposite direction automatically: with target German and fallback English, German text should become English and English text should become German.
Decision: Add `autoSwitchTarget` (default true) and `fallbackTargetLanguage` (default English, or the other language when the target is English). Detect the source before the request and, only when the existing high-confidence same-language rule holds, use the fallback as the effective target. Keep the saved target separate from the effective target; the header and language picker show the effective one, and a panel banner offers a one-capture override that does not persist. A language-picker change persists the saved target. The fallback is kept different from the target; changing the target to the fallback swaps the pair to the previous target.
Consequences: Confident two-language text translates in the useful direction without extra clicks. Uncertain, short or mixed text keeps the saved target, and the same-language advisory still appears when no switch occurs. Detection is advisory, so a wrong dominant language can choose the wrong direction; the banner and the language picker make it visible and recoverable. The effective target is what the prompt, chunking and validation use; Copy and Replace are unaffected. No key tap, permission or new dependency is added.
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 -1
View File
@@ -156,4 +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.
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.
+7 -3
View File
@@ -81,11 +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 meaningful candidates agree, the source is considered to be in the target language. Near-zero hypotheses (below 0.05) are ignored, so a confident single-language text is not treated as mixed.
`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`.
With `autoSwitchTarget` on (default), a confident same-language source is translated into `fallbackTargetLanguage` instead of the saved target. The prompt, chunking and validation use that effective target. The panel shows "German → English" (or the configured pair), a banner explains the switch, and "Translate to German" overrides the direction for that capture only. The same-language advisory is shown only when no switch happens. Detection is advisory: uncertain or mixed text keeps the saved target, and the user can change it with the language picker.
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
+19 -11
View File
@@ -43,20 +43,28 @@ 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.
### Translating the other direction
### Mother tongue and language rules
By default the panel also handles the opposite direction. With target **German** and fallback
**English**, English text becomes German and German text becomes English. This is controlled in
**Settings ▸ General ▸ Translation**:
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:
- **Translate the other direction when the text is already in the target language** (on by default).
- **Fallback target language** (English by default).
```text
Mother tongue: German
Language rules:
Chinese (Simplified) → English
Traditional Chinese → English
German → English
```
The header shows the actual direction, and a banner explains an automatic switch. **Translate to
German** (or the original target) overrides the direction for that result only; the saved target
does not change. Choosing a language from the panel's picker does change the saved target. The
switch happens only when the text is confidently detected as the target language; short or mixed
text keeps the normal direction.
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