Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift
T
schihei 940abcc996 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.
2026-11-26 18:31:45 +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 an optional reverse-direction switch.
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 directionOverride = false
/// 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 {
directionOverride = false
}
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: directionOverride
)
effectiveTarget = direction.target
routedSource = direction.didRoute ? direction.source : nil
sameLanguageDismissed = directionOverride
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
directionOverride = false
}
/// 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
directionOverride = true
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
directionOverride = true
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
directionOverride = false
}
}
/// 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
directionOverride = false
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)
}
}