Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift
T
schihei 9f89000b0d fix(panel): keep the picked language when overriding the target
The header language picker set the effective target and then re-ran prepare, where TranslationDirectionPolicy only knew a Bool override and returned the mother tongue. Any picked language other than the mother tongue was discarded, so the panel appeared not to change. The policy now takes the override target itself, and PanelViewModel stores it, so a picker choice wins over a rule for that capture; a new capture returns to the rule/mother tongue. Move the shared panel test scaffolding into PanelTestSupport and the routing tests into PanelRoutingTests, and add picker and rule-override tests. Verified: make verify green; live checks with a German -> English rule show the picker switching to French, the next capture back to English with the banner, and the banner override to German.
2026-11-27 10:38:16 +01:00

402 lines
14 KiB
Swift

import Foundation
import Observation
import SprachmittlerEngines
import SprachmittlerText
/// The panel phase from `docs/ARCHITECTURE.md` §10.
public enum PanelPhase: Sendable, Equatable {
/// Nothing captured.
case idle
/// A request is queued or running.
case translating
/// Deltas are arriving.
case streaming
/// A validated translation is ready.
case ready
/// The request failed.
case failed
}
/// The settings snapshot used by the panel for one translation.
public struct PanelConfiguration: Sendable, Equatable {
/// The selected target language.
public var target: ModelLanguage
/// Source-to-target rules. Empty means everything goes to `target` (the mother tongue).
public var languageRoutes: [LanguageRoute]
/// The selected model tag.
public var model: String
/// The Ollama keep-alive value.
public var keepAlive: String
/// The sampling values.
public var sampling: SamplingOptions
/// Whether to show the source preview.
public var showSourcePreview: Bool
/// Translation text size in points.
public var translationFontSize: Int
/// Render Markdown formatting for Markdown sources.
public var renderMarkdown: Bool
/// Make the panel key when shown so Esc works without a click.
public var closeWithEscape: Bool
/// Recent targets, most recent first.
public var recentTargets: [ModelLanguage]
/// Creates a configuration.
public init(
target: ModelLanguage,
model: String,
keepAlive: String,
sampling: SamplingOptions = .publisherDefault,
showSourcePreview: Bool = true,
translationFontSize: Int = 17,
renderMarkdown: Bool = true,
closeWithEscape: Bool = true,
languageRoutes: [LanguageRoute] = [],
recentTargets: [ModelLanguage] = []
) {
self.target = target
self.model = model
self.keepAlive = keepAlive
self.sampling = sampling
self.showSourcePreview = showSourcePreview
self.translationFontSize = translationFontSize
self.renderMarkdown = renderMarkdown
self.closeWithEscape = closeWithEscape
self.languageRoutes = languageRoutes
self.recentTargets = recentTargets
}
}
/// The panel presentation model. It mirrors `TranslationSession` and owns no disk state.
@MainActor
@Observable
public final class PanelViewModel {
/// The current phase.
public private(set) var phase: PanelPhase = .idle
/// The captured source.
public private(set) var source: CapturedText?
/// The streamed and final translation.
public private(set) var translation = ""
/// Validation warnings for the current result.
public private(set) var warnings: [TranslationWarning] = []
/// The current error, if any.
public private(set) var error: SprachmittlerError?
/// The last timing.
public private(set) var timing: TranslationTiming?
/// The advisory source language code.
public private(set) var sourceLanguage: String?
/// True after a successful Copy.
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. `target` is the user's saved preference.
public private(set) var configuration: PanelConfiguration
/// The target used by the current request, after a language rule or an explicit picker choice.
public private(set) var effectiveTarget: ModelLanguage
/// The matched rule source when `effectiveTarget` differs from the mother tongue, or nil.
public private(set) var routedSource: ModelLanguage?
/// True after the user dismisses the same-language advisory.
public private(set) var sameLanguageDismissed = false
/// The copy action. The composition root writes with own-write markers.
public let copy: @MainActor (String) -> Void
/// The optional Replace action; nil until the insertion module is available.
public let replace: (@MainActor () async -> InsertionOutcome)?
/// Called when a successful Replace should close the panel.
public let onCloseRequest: @MainActor () -> Void
/// Called with every session event for diagnostics.
public let eventObserver: (@MainActor (TranslationSessionEvent) -> Void)?
/// Called when the user changes the target from the panel.
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 targetOverride: ModelLanguage?
/// Creates a panel model.
public init(
session: TranslationSession,
configuration: PanelConfiguration,
copy: @escaping @MainActor (String) -> Void,
replace: (@MainActor () async -> InsertionOutcome)? = nil,
onCloseRequest: @escaping @MainActor () -> Void = {},
eventObserver: (@MainActor (TranslationSessionEvent) -> Void)? = nil,
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
self.eventObserver = eventObserver
self.onTargetChanged = onTargetChanged
}
/// Starts consuming session events. Call once after init.
public func startObserving() {
guard eventTask == nil else { return }
let session = session
eventTask = Task { [weak self] in
for await event in await session.events() {
guard let self else { return }
handle(event)
}
}
}
/// True when Copy can write the current translation.
public var canCopy: Bool {
!translation.isEmpty && (phase == .ready || phase == .failed)
}
/// True when Replace is safe and the insertion module is available.
public var canReplace: Bool {
phase == .ready
&& !isReplacing
&& !warnings.contains(where: \.blocksReplacement)
&& replace != nil
}
/// The replacement is unavailable until M5 in this build.
public var replaceUnavailableReason: String? {
replace == nil ? "Replace is not available." : nil
}
/// Warnings that disable Replace.
public var blockingWarnings: [TranslationWarning] {
warnings.filter(\.blocksReplacement)
}
/// The same-language advisory, if present and not dismissed.
public var sameLanguageWarning: TranslationWarning? {
guard !sameLanguageDismissed else { return nil }
return warnings.first { warning in
if case .sameLanguage = warning {
true
} else {
false
}
}
}
/// The user-facing error message.
public var errorMessage: String? {
error?.userMessage
}
/// The error's recovery action.
public var recoveryAction: RecoveryAction? {
error?.recoveryAction
}
/// 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
translation = ""
warnings = []
error = nil
timing = nil
didCopy = false
isReplacing = false
if resetDirectionOverride {
targetOverride = nil
}
let normalized = TextNormalization.normalizeInput(captured.text)
let detection = detector.detect(normalized)
sourceLanguage = detection?.code
let direction = TranslationDirectionPolicy.resolve(
configuredTarget: configuration.target,
routes: configuration.languageRoutes,
detection: detection,
override: targetOverride
)
effectiveTarget = direction.target
routedSource = direction.didRoute ? direction.source : nil
sameLanguageDismissed = targetOverride != nil
phase = .translating
}
/// Starts a translation for a captured text.
public func begin(_ captured: CapturedText) async {
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 without discarding a manual direction choice.
public func retry() async {
guard let lastCaptured else { return }
await begin(lastCaptured, resetDirectionOverride: false)
}
/// Retranslates after an external target change and re-evaluates the direction.
public func retranslate() async {
guard let lastCaptured else { return }
await begin(lastCaptured, resetDirectionOverride: true)
}
/// Shows a capture-time error such as a too-long selection.
public func showError(_ error: SprachmittlerError, source: CapturedText? = nil) {
currentEpoch = 0
Task { await session.reset() }
phase = .failed
self.error = error
self.source = source
translation = ""
warnings = []
timing = nil
sourceLanguage = nil
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
}
/// Changes the saved target from the panel and retranslates the current selection.
public func setTarget(_ language: ModelLanguage) async {
guard language.code != effectiveTarget.code else { return }
configuration.target = language
effectiveTarget = language
routedSource = nil
targetOverride = language
onTargetChanged(language)
if let lastCaptured {
await begin(lastCaptured, resetDirectionOverride: false)
}
}
/// Uses another language for this capture only. It does not change the saved target.
public func overrideTarget(_ language: ModelLanguage) async {
guard language.code != effectiveTarget.code else { return }
effectiveTarget = language
routedSource = nil
targetOverride = language
sameLanguageDismissed = true
if let lastCaptured {
await begin(lastCaptured, resetDirectionOverride: false)
}
}
/// Copies the translation and keeps the panel open (R023).
public func copyTranslation() {
guard canCopy else { return }
copy(translation)
didCopy = true
}
/// Runs the optional Replace action.
public func replaceSelection() async {
guard canReplace, let replace else { return }
isReplacing = true
let outcome = await replace()
isReplacing = false
switch outcome {
case .replaced:
onCloseRequest()
case .copiedOnly:
break
case let .failed(insertionError):
error = insertionError
phase = .failed
}
}
/// Dismisses the same-language advisory; translation stays available.
public func dismissSameLanguageWarning() {
sameLanguageDismissed = true
}
/// Updates the settings snapshot without restarting the current request.
public func updateConfiguration(_ configuration: PanelConfiguration) {
let targetChanged = configuration.target.code != self.configuration.target.code
self.configuration = configuration
if targetChanged || source == nil {
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
}
}
/// Resets the panel and cancels the active request. The event stream stays open.
public func close() async {
await session.reset()
phase = .idle
source = nil
translation = ""
warnings = []
error = nil
timing = nil
sourceLanguage = nil
didCopy = false
isReplacing = false
sameLanguageDismissed = false
effectiveTarget = configuration.target
routedSource = nil
targetOverride = nil
lastCaptured = nil
}
/// Stops the event consumer for app termination.
public func shutdown() {
eventTask?.cancel()
eventTask = nil
}
private func request(for captured: CapturedText) -> TranslationSessionRequest {
TranslationSessionRequest(
captured: captured,
target: effectiveTarget,
model: configuration.model,
keepAlive: configuration.keepAlive,
sampling: configuration.sampling
)
}
private func handle(_ event: TranslationSessionEvent) {
switch event {
case let .started(epoch, request):
currentEpoch = epoch
source = request.captured
effectiveTarget = request.target
translation = ""
warnings = []
error = nil
phase = .translating
case let .delta(epoch, text):
guard epoch == currentEpoch else { return }
translation += text
phase = .streaming
case let .finished(epoch, result):
guard epoch == currentEpoch else { return }
translation = result.translation
warnings = result.warnings
timing = result.timing
sourceLanguage = result.sourceLanguage
if result.warnings.contains(.emptyOutput) {
error = .emptyOutput
phase = .failed
} else {
phase = .ready
}
case let .failed(epoch, failure):
guard epoch == currentEpoch else { return }
error = failure
phase = .failed
case let .cancelled(epoch):
guard epoch == currentEpoch else { return }
phase = .idle
error = nil
}
eventObserver?(event)
}
}