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,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
}