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.
298 lines
11 KiB
Swift
298 lines
11 KiB
Swift
import Foundation
|
|
import SprachmittlerCore
|
|
import SprachmittlerEngines
|
|
import SprachmittlerOllama
|
|
import SprachmittlerText
|
|
import Testing
|
|
|
|
@Suite("Translation pipeline")
|
|
struct TranslationPipelineTests {
|
|
private let german = HyMT3Languages.german
|
|
private let model = "test-hy-mt3"
|
|
|
|
@Test func usesTheDocumentedPromptAndReportsTheSourceLanguage() async throws {
|
|
let chat = SequencedChat(responses: [[
|
|
.delta("Hallo"), .done(reason: "stop", metrics: ChatMetrics(promptEvalCount: 9, evalCount: 2)),
|
|
]])
|
|
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
|
|
let result = try await pipeline.translate(text: "Hello.", target: german, model: model, keepAlive: "30m")
|
|
|
|
#expect(result.translation == "Hallo")
|
|
#expect(result.sourceLanguage == "en")
|
|
#expect(result.chunkCount == 1)
|
|
#expect(result.warnings.isEmpty)
|
|
|
|
let request = try #require(chat.recorded.first)
|
|
#expect(request.messages.first?.content == HyMT3Prompt.defaultTranslation(target: german, source: "Hello."))
|
|
#expect(request.options.numCtx == 8192)
|
|
}
|
|
|
|
@Test func chunksAreJoinedWithTheOriginalSeparators() async throws {
|
|
let chat = SequencedChat(responses: [
|
|
[.delta("Erster Absatz."), .done(reason: "stop", metrics: .empty)],
|
|
[.delta("Zweiter Absatz."), .done(reason: "stop", metrics: .empty)],
|
|
])
|
|
let pipeline = makePipeline(
|
|
chat: chat,
|
|
chunker: Chunker(latinLimit: 20, denseLimit: 20),
|
|
detector: FixedDetector(code: "en", confidence: 0.9)
|
|
)
|
|
let result = try await pipeline.translate(
|
|
text: "First paragraph.\n\nSecond paragraph.",
|
|
target: german,
|
|
model: model,
|
|
keepAlive: "30m"
|
|
)
|
|
|
|
#expect(result.chunkCount == 2)
|
|
#expect(result.translation == "Erster Absatz.\n\nZweiter Absatz.")
|
|
#expect(chat.recorded.count == 2)
|
|
#expect(chat.recorded[1].messages.first?.content.contains("Second paragraph.") == true)
|
|
}
|
|
|
|
@Test func reportsEachChunkBeforeItStarts() async throws {
|
|
let chat = SequencedChat(responses: [
|
|
[.delta("Erster Absatz."), .done(reason: "stop", metrics: .empty)],
|
|
[.delta("Zweiter Absatz."), .done(reason: "stop", metrics: .empty)],
|
|
])
|
|
let collector = DeltaCollector()
|
|
let pipeline = makePipeline(
|
|
chat: chat,
|
|
chunker: Chunker(latinLimit: 20, denseLimit: 20),
|
|
detector: FixedDetector(code: "en", confidence: 0.9)
|
|
)
|
|
_ = try await pipeline.translate(
|
|
text: "First paragraph.\n\nSecond paragraph.",
|
|
target: german,
|
|
model: model,
|
|
keepAlive: "30m",
|
|
onChunk: { index, total in await collector.append("\(index)/\(total) ") }
|
|
)
|
|
|
|
#expect(await collector.text == "1/2 2/2 ")
|
|
}
|
|
|
|
@Test func streamedTextIncludesChunkSeparators() async throws {
|
|
let chat = SequencedChat(responses: [
|
|
[.delta("Erster Absatz."), .done(reason: "stop", metrics: .empty)],
|
|
[.delta("Zweiter Absatz."), .done(reason: "stop", metrics: .empty)],
|
|
])
|
|
let collector = DeltaCollector()
|
|
let pipeline = makePipeline(
|
|
chat: chat,
|
|
chunker: Chunker(latinLimit: 20, denseLimit: 20),
|
|
detector: FixedDetector(code: "en", confidence: 0.9)
|
|
)
|
|
let result = try await pipeline.translate(
|
|
text: "First paragraph.\n\nSecond paragraph.",
|
|
target: german,
|
|
model: model,
|
|
keepAlive: "30m",
|
|
onDelta: { await collector.append($0) }
|
|
)
|
|
|
|
#expect(await collector.text == result.translation)
|
|
#expect(await collector.text == "Erster Absatz.\n\nZweiter Absatz.")
|
|
}
|
|
|
|
@Test func retryDoesNotStreamBothAttempts() async throws {
|
|
let chat = SequencedChat(responses: [
|
|
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
|
|
[.delta("Öffne https://example.com jetzt."), .done(reason: "stop", metrics: .empty)],
|
|
])
|
|
let collector = DeltaCollector()
|
|
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
|
|
let result = try await pipeline.translate(
|
|
text: "Open https://example.com now.",
|
|
target: german,
|
|
model: model,
|
|
keepAlive: "30m",
|
|
onDelta: { await collector.append($0) }
|
|
)
|
|
|
|
#expect(await collector.text == "Öffne jetzt.")
|
|
#expect(result.translation == "Öffne https://example.com jetzt.")
|
|
}
|
|
|
|
@Test func retriesOnceWithTheDocumentedDelimitersPrompt() async throws {
|
|
let chat = SequencedChat(responses: [
|
|
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
|
|
[.delta("Öffne https://example.com jetzt."), .done(reason: "stop", metrics: .empty)],
|
|
])
|
|
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
|
|
let result = try await pipeline.translate(
|
|
text: "Open https://example.com now.",
|
|
target: german,
|
|
model: model,
|
|
keepAlive: "30m"
|
|
)
|
|
|
|
#expect(chat.recorded.count == 2)
|
|
#expect(chat.recorded[1].messages.first?.content.contains("retain the exact same number of delimiters") == true)
|
|
#expect(result.translation == "Öffne https://example.com jetzt.")
|
|
#expect(!result.warnings.contains {
|
|
if case .missingProtectedToken = $0 {
|
|
true
|
|
} else {
|
|
false
|
|
}
|
|
})
|
|
}
|
|
|
|
@Test func reportsASecondLostTokenWithoutASecondRetry() async throws {
|
|
let chat = SequencedChat(responses: [
|
|
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
|
|
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
|
|
])
|
|
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
|
|
let result = try await pipeline.translate(
|
|
text: "Open https://example.com now.",
|
|
target: german,
|
|
model: model,
|
|
keepAlive: "30m"
|
|
)
|
|
|
|
#expect(chat.recorded.count == 2)
|
|
#expect(result.warnings.contains(.missingProtectedToken("https://example.com")))
|
|
}
|
|
|
|
@Test func emptyTextAndUnknownModelsFailBeforeTheNetwork() async {
|
|
let chat = SequencedChat(responses: [])
|
|
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
|
|
|
|
await #expect(throws: SprachmittlerError.emptyText) {
|
|
_ = try await pipeline.translate(text: " ", target: german, model: model, keepAlive: "30m")
|
|
}
|
|
|
|
let emptyRegistry = TranslationPipeline(
|
|
chat: chat,
|
|
registry: AdapterRegistry(adapters: []),
|
|
detector: FixedDetector(code: "en", confidence: 0.9)
|
|
)
|
|
await #expect(throws: SprachmittlerError.noAdapter(model: "llama3")) {
|
|
_ = try await emptyRegistry.translate(text: "Hello.", target: german, model: "llama3", keepAlive: "30m")
|
|
}
|
|
#expect(chat.recorded.isEmpty)
|
|
}
|
|
|
|
@Test func sameLanguageIsAnAdvisoryWarning() async throws {
|
|
let chat = SequencedChat(responses: [
|
|
[.delta("Hallo."), .done(reason: "stop", metrics: .empty)],
|
|
])
|
|
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "de", confidence: 0.9))
|
|
let result = try await pipeline.translate(text: "Hallo.", target: german, model: model, keepAlive: "30m")
|
|
|
|
#expect(result.warnings.contains(.sameLanguage(source: "de", target: "de")))
|
|
}
|
|
|
|
@Test func truncationAndLoopsAreWarnings() async throws {
|
|
let truncated = SequencedChat(responses: [
|
|
[.delta("Hallo"), .done(reason: "length", metrics: .empty)],
|
|
])
|
|
let truncatedResult = try await makePipeline(
|
|
chat: truncated,
|
|
detector: FixedDetector(code: "en", confidence: 0.9)
|
|
)
|
|
.translate(text: "Hello.", target: german, model: model, keepAlive: "30m")
|
|
#expect(truncatedResult.warnings.contains(.truncated))
|
|
|
|
let repeated = "This line repeats exactly."
|
|
let looping = SequencedChat(responses: [[
|
|
.delta(Array(repeating: repeated, count: 6).joined(separator: "\n")),
|
|
.done(reason: "stop", metrics: .empty),
|
|
]])
|
|
let loopResult = try await makePipeline(chat: looping, detector: FixedDetector(code: "en", confidence: 0.9))
|
|
.translate(text: "Hello.", target: german, model: model, keepAlive: "30m")
|
|
#expect(loopResult.warnings.contains(.repetitionLoop))
|
|
}
|
|
|
|
@Test func transportErrorsAreMappedAtTheCoreBoundary() async throws {
|
|
let url = try #require(URL(string: "http://127.0.0.1:9"))
|
|
let pipeline = TranslationPipeline(
|
|
chat: FailingChat(error: .unreachable(url)),
|
|
registry: AdapterRegistry(adapters: [HyMT3Adapter()]),
|
|
detector: FixedDetector(code: "en", confidence: 0.9)
|
|
)
|
|
await #expect(throws: SprachmittlerError.ollamaUnreachable(url: url)) {
|
|
_ = try await pipeline.translate(
|
|
text: "Hello.",
|
|
target: german,
|
|
model: model,
|
|
keepAlive: "30m"
|
|
)
|
|
}
|
|
}
|
|
|
|
private func makePipeline(
|
|
chat: any OllamaChatting,
|
|
chunker: Chunker = Chunker(),
|
|
detector: any LanguageDetecting
|
|
) -> TranslationPipeline {
|
|
TranslationPipeline(
|
|
chat: chat,
|
|
registry: AdapterRegistry(adapters: [HyMT3Adapter()]),
|
|
detector: detector,
|
|
chunker: chunker
|
|
)
|
|
}
|
|
}
|
|
|
|
private struct FixedDetector: LanguageDetecting {
|
|
let code: String
|
|
let confidence: Double
|
|
|
|
func detect(_ text: String) -> LanguageDetection? {
|
|
LanguageDetection(code: code, confidence: confidence, alternatives: [code])
|
|
}
|
|
}
|
|
|
|
private actor DeltaCollector {
|
|
private(set) var text = ""
|
|
|
|
func append(_ delta: String) {
|
|
text += delta
|
|
}
|
|
}
|
|
|
|
private struct FailingChat: OllamaChatting {
|
|
let error: OllamaError
|
|
|
|
func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error> {
|
|
AsyncThrowingStream { continuation in
|
|
continuation.finish(throwing: error)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A chat fake that returns one response per call. `@unchecked Sendable` is safe because every
|
|
/// mutable field is guarded by `lock`.
|
|
private final class SequencedChat: OllamaChatting, @unchecked Sendable {
|
|
private let lock = NSLock()
|
|
private var responses: [[ChatEvent]]
|
|
private var requests: [ChatRequest] = []
|
|
|
|
init(responses: [[ChatEvent]]) {
|
|
self.responses = responses
|
|
}
|
|
|
|
var recorded: [ChatRequest] {
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
return requests
|
|
}
|
|
|
|
func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error> {
|
|
lock.lock()
|
|
requests.append(request)
|
|
let events = responses.isEmpty ? [] : responses.removeFirst()
|
|
lock.unlock()
|
|
|
|
return AsyncThrowingStream { continuation in
|
|
for event in events {
|
|
continuation.yield(event)
|
|
}
|
|
continuation.finish()
|
|
}
|
|
}
|
|
}
|