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

@@ -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