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.
This commit is contained in:
schihei committed 2026-11-26 17:34:11 +01:00
1 parent 7c9cece201
commit 41f1cea769
24 files changed
+723 -148

No files matched your search

@@ -0,0 +1,121 @@
import Foundation
import SprachmittlerEngines
private struct DecodedDirection {
let autoSwitch: Bool
let fallback: String
}
extension AppSettings {
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 direction = try Self.decodeDirection(from: container, defaults: defaults, target: targetLanguage)
autoSwitchTarget = direction.autoSwitch
fallbackTargetLanguage = direction.fallback
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
}
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(autoSwitchTarget, forKey: .autoSwitchTarget)
try container.encode(fallbackTargetLanguage, forKey: .fallbackTargetLanguage)
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 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] {
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)
}
}
@@ -29,6 +29,10 @@ public struct AppSettings: Codable, Sendable, Equatable {
public var fastModel: String?
/// The selected target BCP-47 code.
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
/// Up to three recent target codes, most recent first.
public var recentTargetLanguages: [String]
/// The double-copy window in milliseconds (300–1000).
@@ -82,6 +86,10 @@ 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
recentTargetLanguages = []
doubleCopyWindowMs = 500
maxCharactersLatin = 4000
@@ -111,6 +119,11 @@ 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)
@@ -123,6 +136,9 @@ 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)
@@ -132,6 +148,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)
doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000)
maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000)
maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 5000)
@@ -165,7 +182,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 +191,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 +234,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
)
}
private static func decodeSampling(
static func decodeSampling(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings
) throws -> DecodedSampling {
@@ -237,8 +254,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, autoSwitchTarget
case fallbackTargetLanguage, recentTargetLanguages
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict
case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown
@@ -246,95 +264,15 @@ 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) ?? []
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
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
}
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,10 @@ 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?
/// The selected model tag.
public var model: String
/// The Ollama keep-alive value.
@@ -47,6 +52,8 @@ public struct PanelConfiguration: Sendable, Equatable {
translationFontSize: Int = 17,
renderMarkdown: Bool = true,
closeWithEscape: Bool = true,
autoSwitchTarget: Bool = true,
fallbackTarget: ModelLanguage? = HyMT3Languages.english,
recentTargets: [ModelLanguage] = []
) {
self.target = target
@@ -57,6 +64,8 @@ public struct PanelConfiguration: Sendable, Equatable {
self.translationFontSize = translationFontSize
self.renderMarkdown = renderMarkdown
self.closeWithEscape = closeWithEscape
self.autoSwitchTarget = autoSwitchTarget
self.fallbackTarget = fallbackTarget
self.recentTargets = recentTargets
}
}
@@ -83,8 +92,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 saved target that was replaced by `effectiveTarget`, or nil.
public private(set) var autoSwitchedFrom: ModelLanguage?
/// True after the user dismisses the same-language advisory.
public private(set) var sameLanguageDismissed = false
@@ -100,9 +113,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 +127,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 +198,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 +207,47 @@ 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,
fallbackTarget: configuration.fallbackTarget,
detection: detection,
autoSwitch: configuration.autoSwitchTarget,
override: directionOverride
)
effectiveTarget = direction.target
autoSwitchedFrom = direction.didSwitch ? direction.originalTarget : 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 +261,33 @@ public final class PanelViewModel {
warnings = []
timing = nil
sourceLanguage = nil
effectiveTarget = configuration.target
autoSwitchedFrom = 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
autoSwitchedFrom = 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
autoSwitchedFrom = nil
directionOverride = true
sameLanguageDismissed = true
if let lastCaptured {
await begin(lastCaptured, resetDirectionOverride: false)
}
}
@@ -268,7 +322,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
autoSwitchedFrom = nil
directionOverride = false
}
}
/// Resets the panel and cancels the active request. The event stream stays open.
@@ -284,6 +344,9 @@ public final class PanelViewModel {
didCopy = false
isReplacing = false
sameLanguageDismissed = false
effectiveTarget = configuration.target
autoSwitchedFrom = nil
directionOverride = false
lastCaptured = nil
}
@@ -296,7 +359,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 +371,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
@@ -0,0 +1,47 @@
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 the configured target was replaced by the fallback target.
public let didSwitch: Bool
/// The configured target when `didSwitch` is true.
public let originalTarget: ModelLanguage?
/// Creates a direction.
public init(target: ModelLanguage, didSwitch: Bool, originalTarget: ModelLanguage?) {
self.target = target
self.didSwitch = didSwitch
self.originalTarget = originalTarget
}
}
/// 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 saved target language.
/// - fallbackTarget: The language to use when the source is already the configured target.
/// - 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?,
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)
}
return TranslationDirection(target: fallbackTarget, didSwitch: true, originalTarget: configuredTarget)
}
}
@@ -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,9 @@ 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.renderMarkdown)
#expect(settings.closeWithEscape)
#expect(!settings.autoCopy)
@@ -32,6 +35,8 @@ struct AppSettingsTests {
settings.noteTarget(HyMT3Languages.german)
settings.temperature = 0.2
settings.translationFontSize = 22
settings.autoSwitchTarget = false
settings.fallbackTargetLanguage = "fr"
settings.renderMarkdown = false
settings.closeWithEscape = false
settings.launchAtLogin = true
@@ -57,6 +62,9 @@ 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.renderMarkdown)
#expect(decoded.closeWithEscape)
#expect(!decoded.autoCopy)
@@ -91,6 +99,7 @@ struct AppSettingsTests {
"repeatPenalty": 9,
"keepModelLoaded": "forever",
"translationFontSize": 99,
"fallbackTargetLanguage": "xx",
"targetLanguage": "xx"
}
"""
@@ -106,6 +115,8 @@ 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(HyMT3Languages.resolve(decoded.targetLanguage) != nil)
}
@@ -117,8 +128,9 @@ struct AppSettingsTests {
settings.topK = 0
settings.keepModelLoaded = "forever"
settings.translationFontSize = 99
settings.fallbackTargetLanguage = "de"
settings.autoCopy = true
settings.targetLanguage = "xx"
settings.targetLanguage = "de"
settings.sanitize()
#expect(settings.doubleCopyWindowMs == 300)
@@ -127,10 +139,33 @@ struct AppSettingsTests {
#expect(settings.topK == 1)
#expect(settings.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
#expect(settings.translationFontSize == 28)
#expect(settings.fallbackTargetLanguage == "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"))
@@ -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,89 @@ struct PanelViewModelTests {
#expect(panel.sameLanguageWarning == nil)
}
@Test func autoSwitchesWhenTheSourceIsTheTarget() async {
let detector = FixedDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, _) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true)
await panel.begin(germanCaptured)
await waitFor { panel.phase == .ready }
#expect(panel.effectiveTarget == HyMT3Languages.english)
#expect(panel.autoSwitchedFrom == HyMT3Languages.german)
#expect(panel.configuration.target == HyMT3Languages.german)
#expect(panel.translation == "en")
}
@Test func autoSwitchOverrideIsSessionOnly() async {
let detector = FixedDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, targets) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true)
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.autoSwitchedFrom == nil)
#expect(panel.configuration.target == HyMT3Languages.german)
#expect(targets.codes.isEmpty)
}
@Test func explicitTargetPersistsAndDisablesAutoSwitch() async {
let detector = FixedDetector(
detection: LanguageDetection(code: "de", confidence: 0.9, alternatives: ["de"])
)
let (panel, _, targets) = makePanel(streaming: EchoStreaming(), detector: detector, autoSwitch: true)
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.autoSwitchedFrom == 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, autoSwitch: true)
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, autoSwitch: true)
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.autoSwitchedFrom == HyMT3Languages.german)
}
@Test func changingTargetRetranslatesAndNotifies() async {
let streaming = EchoStreaming()
let (panel, _, targets) = makePanel(streaming: streaming)
@@ -145,7 +235,11 @@ 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),
autoSwitch: Bool = false,
target: ModelLanguage = HyMT3Languages.german,
fallback: ModelLanguage? = HyMT3Languages.english
) -> (PanelViewModel, CopiedTextBox, TargetBox) {
let session = TranslationSession(pipelineFactory: { streaming })
let copies = CopiedTextBox()
@@ -153,14 +247,17 @@ struct PanelViewModelTests {
let panel = PanelViewModel(
session: session,
configuration: PanelConfiguration(
target: HyMT3Languages.german,
target: target,
model: "test-hy-mt3",
keepAlive: "30m"
keepAlive: "30m",
autoSwitchTarget: autoSwitch,
fallbackTarget: fallback
),
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 +368,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,117 @@
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 keepsTheConfiguredTargetWhenTheSourceIsDifferent() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
detection: detection("en"),
autoSwitch: true,
override: false
)
#expect(direction == TranslationDirection(target: german, didSwitch: false, originalTarget: nil))
}
@Test func switchesWhenTheSourceIsConfidentlyTheTarget() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
detection: detection("de"),
autoSwitch: true,
override: false
)
#expect(direction == TranslationDirection(target: english, didSwitch: true, originalTarget: german))
}
@Test func doesNotSwitchWhenDisabled() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
detection: detection("de"),
autoSwitch: false,
override: false
)
#expect(direction.target == german)
#expect(!direction.didSwitch)
}
@Test func doesNotSwitchAfterAManualOverride() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
detection: detection("de"),
autoSwitch: true,
override: true
)
#expect(direction.target == german)
#expect(!direction.didSwitch)
}
@Test func doesNotSwitchWithLowConfidence() {
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: german,
fallbackTarget: english,
detection: detection("de", confidence: 0.49),
autoSwitch: true,
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,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 {