Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.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

246 lines
8.8 KiB
Swift

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<TranslationSessionEvent>
private let continuation: AsyncStream<TranslationSessionEvent>.Continuation
private var epoch: UInt64 = 0
private var task: Task<Void, Never>?
/// 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<TranslationSessionEvent>.makeStream()
eventsStream = pair.stream
continuation = pair.continuation
}
/// The event stream. It has one consumer, normally `PanelViewModel`.
public func events() -> AsyncStream<TranslationSessionEvent> {
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))
}
}