import Foundation import Observation import SprachmittlerEngines /// 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 /// 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, 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.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. public private(set) var configuration: PanelConfiguration /// 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 var eventTask: Task? private var currentEpoch: UInt64 = 0 private var lastCaptured: CapturedText? /// 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 } ) { self.session = session self.configuration = configuration 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. public func prepare(_ captured: CapturedText) { currentEpoch = 0 lastCaptured = captured source = captured translation = "" warnings = [] error = nil timing = nil sourceLanguage = nil didCopy = false isReplacing = false sameLanguageDismissed = false phase = .translating } /// Starts a translation for a captured text. public func begin(_ captured: CapturedText) async { prepare(captured) _ = await session.start(request(for: captured)) } /// Retries the last captured text. public func retry() async { guard let lastCaptured else { return } await begin(lastCaptured) } /// Retranslates after an external target change. public func retranslate() async { guard let lastCaptured else { return } await begin(lastCaptured) } /// 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 } /// Changes the target and retranslates the current selection. public func setTarget(_ language: ModelLanguage) async { guard language.code != configuration.target.code else { return } configuration.target = language onTargetChanged(language) if let lastCaptured { await begin(lastCaptured) } } /// 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) { self.configuration = configuration } /// 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 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: configuration.target, 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 configuration.target = 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) } }