import Foundation import SprachmittlerEngines import SprachmittlerOllama /// The streaming translation seam used by `TranslationSession`. The production implementation is /// `TranslationPipeline`; tests provide a controlled fake. public protocol TranslationStreaming: Sendable { /// Translates one captured selection, optionally forwarding deltas. func translate( _ request: TranslationSessionRequest, onDelta: (@Sendable (String) async -> Void)? ) async throws -> PipelineResult /// Translates one captured selection, forwarding deltas and the start of each chunk. func translate( _ request: TranslationSessionRequest, onDelta: (@Sendable (String) async -> Void)?, onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)? ) async throws -> PipelineResult } public extension TranslationStreaming { /// Fakes that do not report chunk progress use this fallback. func translate( _ request: TranslationSessionRequest, onDelta: (@Sendable (String) async -> Void)?, onChunk: (@Sendable (Int, Int) async -> Void)? ) async throws -> PipelineResult { try await translate(request, onDelta: onDelta) } } extension TranslationPipeline: TranslationStreaming {} public extension TranslationPipeline { func translate( _ request: TranslationSessionRequest, onDelta: (@Sendable (String) async -> Void)? ) async throws -> PipelineResult { try await translate( text: request.captured.text, target: request.target, model: request.model, keepAlive: request.keepAlive, sampling: request.sampling, onDelta: onDelta ) } func translate( _ request: TranslationSessionRequest, onDelta: (@Sendable (String) async -> Void)?, onChunk: (@Sendable (Int, Int) async -> Void)? ) async throws -> PipelineResult { try await translate( text: request.captured.text, target: request.target, model: request.model, keepAlive: request.keepAlive, sampling: request.sampling, onDelta: onDelta, onChunk: onChunk ) } } /// One translation request, including the settings snapshot it was built from. public struct TranslationSessionRequest: Sendable, Equatable { /// The captured text. public let captured: CapturedText /// The target language. public let target: ModelLanguage /// The installed model tag. public let model: String /// The Ollama keep-alive value. public let keepAlive: String /// The sampling values. public let sampling: SamplingOptions /// The chunk and capture limits accepted for this capture. public let captureLimits: CaptureLimits /// Creates a request. public init( captured: CapturedText, target: ModelLanguage, model: String, keepAlive: String, sampling: SamplingOptions = .publisherDefault, captureLimits: CaptureLimits = CaptureLimits() ) { self.captured = captured self.target = target self.model = model self.keepAlive = keepAlive self.sampling = sampling self.captureLimits = captureLimits } } /// An event from the translation session. The epoch lets the panel drop stale events. public enum TranslationSessionEvent: Sendable, Equatable { /// A request started. case started(epoch: UInt64, request: TranslationSessionRequest) /// One chunk of a multi-part request started (`index` is 1-based). case chunkStarted(epoch: UInt64, index: Int, total: Int) /// One streamed delta. case delta(epoch: UInt64, text: String) /// The final validated result. case finished(epoch: UInt64, result: PipelineResult) /// A domain error. case failed(epoch: UInt64, error: SprachmittlerError) /// The request was cancelled or replaced. case cancelled(epoch: UInt64) } /// The only translation actor: one request in flight, epochs discard stale events (ADR-015). public actor TranslationSession { private let pipelineFactory: @Sendable () throws -> any TranslationStreaming private let eventsStream: AsyncStream private let continuation: AsyncStream.Continuation private var epoch: UInt64 = 0 private var task: Task? /// Creates a session. The factory reads a settings snapshot and builds a pipeline. public init(pipelineFactory: @escaping @Sendable () throws -> any TranslationStreaming) { self.pipelineFactory = pipelineFactory let pair = AsyncStream.makeStream() eventsStream = pair.stream continuation = pair.continuation } /// The event stream. It has one consumer, normally `PanelViewModel`. public func events() -> AsyncStream { eventsStream } /// Starts a request, cancelling any active one, and returns its epoch. @discardableResult public func start(_ request: TranslationSessionRequest) -> UInt64 { task?.cancel() epoch &+= 1 let currentEpoch = epoch continuation.yield(.started(epoch: currentEpoch, request: request)) guard validate(request, epoch: currentEpoch) else { return currentEpoch } task = Task { [pipelineFactory] in do { let pipeline = try pipelineFactory() let result = try await pipeline.translate( request, onDelta: { delta in await self.forwardDelta(epoch: currentEpoch, text: delta) }, onChunk: { index, total in await self.forwardChunk(epoch: currentEpoch, index: index, total: total) } ) self.finish(epoch: currentEpoch, result: result) } catch let error as SprachmittlerError { if error == .cancelled { self.cancelEvent(epoch: currentEpoch) } else { self.fail(epoch: currentEpoch, error: error) } } catch let error as OllamaError { self.fail(epoch: currentEpoch, error: SprachmittlerError(ollama: error)) } catch let rejection as EndpointRejection { self.fail( epoch: currentEpoch, error: .endpointRejected(reason: rejection) ) } catch is CancellationError { self.cancelEvent(epoch: currentEpoch) } catch { self.fail( epoch: currentEpoch, error: .server(status: 0, message: "Translation failed") ) } } return currentEpoch } /// Cancels the active request and emits a cancellation for its epoch. public func cancel() { let previous = epoch epoch &+= 1 task?.cancel() task = nil continuation.yield(.cancelled(epoch: previous)) } /// Cancels without emitting. Use when the panel closes. public func reset() { epoch &+= 1 task?.cancel() task = nil } private func validate(_ request: TranslationSessionRequest, epoch eventEpoch: UInt64) -> Bool { switch CapturePolicy.validate(request.captured.text, limits: request.captureLimits) { case .valid: return true case .empty: continuation.yield(.failed(epoch: eventEpoch, error: .emptyText)) return false case let .textTooLong(characters, limit): continuation.yield( .failed(epoch: eventEpoch, error: .textTooLong(characters: characters, limit: limit)) ) return false } } private func forwardDelta(epoch eventEpoch: UInt64, text: String) { guard eventEpoch == epoch else { return } continuation.yield(.delta(epoch: eventEpoch, text: text)) } private func forwardChunk(epoch eventEpoch: UInt64, index: Int, total: Int) { guard eventEpoch == epoch else { return } continuation.yield(.chunkStarted(epoch: eventEpoch, index: index, total: total)) } private func finish(epoch eventEpoch: UInt64, result: PipelineResult) { guard eventEpoch == epoch else { return } task = nil continuation.yield(.finished(epoch: eventEpoch, result: result)) } private func fail(epoch eventEpoch: UInt64, error: SprachmittlerError) { guard eventEpoch == epoch else { return } task = nil continuation.yield(.failed(epoch: eventEpoch, error: error)) } private func cancelEvent(epoch eventEpoch: UInt64) { guard eventEpoch == epoch else { return } task = nil continuation.yield(.cancelled(epoch: eventEpoch)) } }