Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift
T
schihei 2a601058f4 feat(capture): translate long selections in parts
The capture gate and the chunk size were the same number, so a selection above one chunk was rejected before the pipeline could split it; the Settings sliders moved both thresholds together. Add maximumPartsPerSelection (1-8, default 1, so existing behaviour is unchanged). The capture limit is now part size x parts and travels on TranslationSessionRequest, so the watcher, CapturePolicy and TranslationSession agree for that capture. TranslationStreaming gained an optional per-part callback; the session emits chunkStarted and the panel shows 'Part 2 of 4' while streaming and '2 parts' when finished. textTooLong now points at Settings and offers an Open Settings button. Lower the dense-script part-size maximum to 4000 because 5000 dense characters plus a 4096-token output can overflow the 8192-token context. Tests cover capture limits, watcher limits, pipeline part callbacks, session events and limits, panel progress, settings clamping and migration. Docs updated: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES and README. Verified: make verify green; live 4355-character German text showed Part 1 of 2, Part 2 of 2 and '2 parts'; with one part the panel showed the too-long message and Open Settings.
2026-11-27 20:21:30 +01:00

459 lines
16 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]
/// The chunk and capture limits accepted for this capture.
public var captureLimits: CaptureLimits
/// 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] = [],
captureLimits: CaptureLimits = CaptureLimits()
) {
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
self.captureLimits = captureLimits
}
}
/// 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 number of parts in the last finished translation.
public private(set) var chunkCount = 1
/// The current part while a multi-part request runs.
public private(set) var currentChunk: Int?
/// The total parts of the current multi-part request.
public private(set) var totalChunks: Int?
/// 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
chunkCount = 1
currentChunk = nil
totalChunks = nil
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
chunkCount = 1
currentChunk = nil
totalChunks = 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
chunkCount = 1
currentChunk = nil
totalChunks = nil
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,
captureLimits: configuration.captureLimits
)
}
}
private extension PanelViewModel {
private func handle(_ event: TranslationSessionEvent) {
switch event {
case let .started(epoch, request):
handleStarted(epoch: epoch, request: request)
case let .chunkStarted(epoch, index, total):
handleChunkStarted(epoch: epoch, index: index, total: total)
case let .delta(epoch, text):
handleDelta(epoch: epoch, text: text)
case let .finished(epoch, result):
handleFinished(epoch: epoch, result: result)
case let .failed(epoch, error):
handleFailed(epoch: epoch, error: error)
case let .cancelled(epoch):
handleCancelled(epoch: epoch)
}
eventObserver?(event)
}
private func handleStarted(epoch: UInt64, request: TranslationSessionRequest) {
currentEpoch = epoch
source = request.captured
effectiveTarget = request.target
translation = ""
warnings = []
error = nil
chunkCount = 1
currentChunk = nil
totalChunks = nil
phase = .translating
}
private func handleChunkStarted(epoch: UInt64, index: Int, total: Int) {
guard epoch == currentEpoch else { return }
currentChunk = index
totalChunks = total
}
private func handleDelta(epoch: UInt64, text: String) {
guard epoch == currentEpoch else { return }
translation += text
phase = .streaming
}
private func handleFinished(epoch: UInt64, result: PipelineResult) {
guard epoch == currentEpoch else { return }
translation = result.translation
warnings = result.warnings
timing = result.timing
sourceLanguage = result.sourceLanguage
chunkCount = result.chunkCount
currentChunk = nil
totalChunks = nil
if result.warnings.contains(.emptyOutput) {
error = .emptyOutput
phase = .failed
} else {
phase = .ready
}
}
private func handleFailed(epoch: UInt64, error: SprachmittlerError) {
guard epoch == currentEpoch else { return }
self.error = error
currentChunk = nil
phase = .failed
}
private func handleCancelled(epoch: UInt64) {
guard epoch == currentEpoch else { return }
phase = .idle
error = nil
}
}