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.
This commit is contained in:
1 parent
9f89000b0d
commit
2a601058f4
29 files changed
+607
-122
No files matched your search
@@ -16,6 +16,7 @@ struct AppSettingsTests {
|
||||
#expect(settings.doubleCopyWindowMs == 500)
|
||||
#expect(settings.maxCharactersLatin == 4000)
|
||||
#expect(settings.maxCharactersCJK == 2000)
|
||||
#expect(settings.maximumPartsPerSelection == 1)
|
||||
#expect(settings.numCtx == 8192)
|
||||
#expect(settings.translationFontSize == 17)
|
||||
#expect(settings.languageRoutes.isEmpty)
|
||||
@@ -25,6 +26,18 @@ struct AppSettingsTests {
|
||||
#expect(!settings.hasCompletedOnboarding)
|
||||
}
|
||||
|
||||
@Test func captureLimitsFollowPartsAndScript() {
|
||||
var settings = AppSettings()
|
||||
#expect(settings.captureLimits.chunkLimit(for: "a") == 4000)
|
||||
#expect(settings.captureLimits.captureLimit(for: "a") == 4000)
|
||||
#expect(settings.captureLimits.captureLimit(for: "你") == 2000)
|
||||
|
||||
settings.maximumPartsPerSelection = 4
|
||||
#expect(settings.captureLimits.captureLimit(for: "a") == 16000)
|
||||
#expect(settings.captureLimits.captureLimit(for: "你") == 8000)
|
||||
#expect(settings.captureLimits.maximumParts == 4)
|
||||
}
|
||||
|
||||
@Test func codableRoundTripPreservesValues() throws {
|
||||
var settings = AppSettings()
|
||||
settings.endpoint = try #require(URL(string: "https://example.com:11434"))
|
||||
@@ -38,6 +51,7 @@ struct AppSettingsTests {
|
||||
settings.closeWithEscape = false
|
||||
settings.launchAtLogin = true
|
||||
settings.hasCompletedOnboarding = true
|
||||
settings.maximumPartsPerSelection = 4
|
||||
|
||||
let data = try JSONEncoder().encode(settings)
|
||||
let decoded = try JSONDecoder().decode(AppSettings.self, from: data)
|
||||
@@ -65,6 +79,7 @@ struct AppSettingsTests {
|
||||
#expect(decoded.renderMarkdown)
|
||||
#expect(decoded.closeWithEscape)
|
||||
#expect(!decoded.autoCopy)
|
||||
#expect(decoded.maximumPartsPerSelection == 1)
|
||||
}
|
||||
|
||||
@Test func fastModelCanBeClearedExplicitly() throws {
|
||||
@@ -102,7 +117,8 @@ struct AppSettingsTests {
|
||||
let decoded = try JSONDecoder().decode(AppSettings.self, from: Data(json.utf8))
|
||||
#expect(decoded.doubleCopyWindowMs == 300)
|
||||
#expect(decoded.maxCharactersLatin == 500)
|
||||
#expect(decoded.maxCharactersCJK == 5000)
|
||||
#expect(decoded.maxCharactersCJK == 4000)
|
||||
#expect(decoded.maximumPartsPerSelection == 1)
|
||||
#expect(decoded.numCtx == 1024)
|
||||
#expect(decoded.numPredict == 8192)
|
||||
#expect(decoded.temperature == 2)
|
||||
@@ -131,6 +147,8 @@ struct AppSettingsTests {
|
||||
]
|
||||
settings.autoCopy = true
|
||||
settings.targetLanguage = "de"
|
||||
settings.maxCharactersCJK = 9999
|
||||
settings.maximumPartsPerSelection = 99
|
||||
settings.sanitize()
|
||||
|
||||
#expect(settings.doubleCopyWindowMs == 300)
|
||||
@@ -139,6 +157,8 @@ struct AppSettingsTests {
|
||||
#expect(settings.topK == 1)
|
||||
#expect(settings.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
|
||||
#expect(settings.translationFontSize == 28)
|
||||
#expect(settings.maxCharactersCJK == 4000)
|
||||
#expect(settings.maximumPartsPerSelection == 8)
|
||||
#expect(settings.languageRoutes == [
|
||||
LanguageRoute(source: "de", target: "en"),
|
||||
LanguageRoute(source: "zh", target: "en"),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerText
|
||||
import Testing
|
||||
|
||||
@Suite("Capture policy")
|
||||
@@ -25,4 +26,29 @@ struct CapturePolicyTests {
|
||||
== .textTooLong(characters: 2001, limit: 2000)
|
||||
)
|
||||
}
|
||||
|
||||
@Test func partsRaiseTheCaptureLimit() {
|
||||
let limits = CaptureLimits(maximumParts: 3)
|
||||
#expect(CapturePolicy.validate(String(repeating: "a", count: 12000), limits: limits) == .valid)
|
||||
#expect(
|
||||
CapturePolicy.validate(String(repeating: "a", count: 12001), limits: limits)
|
||||
== .textTooLong(characters: 12001, limit: 12000)
|
||||
)
|
||||
#expect(CapturePolicy.validate(String(repeating: "你", count: 6000), limits: limits) == .valid)
|
||||
#expect(
|
||||
CapturePolicy.validate(String(repeating: "你", count: 6001), limits: limits)
|
||||
== .textTooLong(characters: 6001, limit: 6000)
|
||||
)
|
||||
}
|
||||
|
||||
@Test func maximumPartsIsAtLeastOne() {
|
||||
#expect(CaptureLimits(maximumParts: 0).maximumParts == 1)
|
||||
#expect(CaptureLimits(maximumParts: 0).captureLimit(for: "a") == 4000)
|
||||
}
|
||||
|
||||
@Test func chunkerStillSplitsTheAcceptedText() {
|
||||
let limits = CaptureLimits(maximumParts: 3)
|
||||
let text = String(repeating: "a", count: 12000)
|
||||
#expect(limits.chunker.chunks(for: text).count == 3)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerText
|
||||
import Testing
|
||||
@testable import SprachmittlerCore
|
||||
|
||||
@Suite("Panel chunk progress")
|
||||
@MainActor
|
||||
struct PanelChunkingTests {
|
||||
private let longCaptured = CapturedText(
|
||||
text: String(repeating: "a", count: 9000),
|
||||
capturedAt: Date(timeIntervalSince1970: 0),
|
||||
source: .doubleCopy
|
||||
)
|
||||
|
||||
@Test func reportsPartsAndProgress() async {
|
||||
let limits = CaptureLimits(maximumParts: 3)
|
||||
let streaming = GatedMultiPartStreaming()
|
||||
let (panel, _, _) = makePanel(streaming: streaming, captureLimits: limits)
|
||||
|
||||
await panel.begin(longCaptured)
|
||||
await waitFor { panel.currentChunk == 1 && panel.totalChunks == 3 && !panel.translation.isEmpty }
|
||||
|
||||
#expect(panel.phase == .streaming)
|
||||
#expect(panel.chunkCount == 1)
|
||||
|
||||
await streaming.release()
|
||||
await waitFor { panel.phase == .ready }
|
||||
|
||||
#expect(panel.translation == "part1 part2 part3")
|
||||
#expect(panel.chunkCount == 3)
|
||||
#expect(panel.currentChunk == nil)
|
||||
#expect(panel.totalChunks == nil)
|
||||
#expect(await streaming.requests.first?.captureLimits == limits)
|
||||
}
|
||||
|
||||
@Test func aSinglePartHasNoProgress() async {
|
||||
let captured = CapturedText(
|
||||
text: "Hallo.",
|
||||
capturedAt: Date(timeIntervalSince1970: 0),
|
||||
source: .doubleCopy
|
||||
)
|
||||
let (panel, _, _) = makePanel(streaming: EchoStreaming())
|
||||
await panel.begin(captured)
|
||||
await waitFor { panel.phase == .ready }
|
||||
|
||||
#expect(panel.chunkCount == 1)
|
||||
#expect(panel.currentChunk == nil)
|
||||
#expect(panel.totalChunks == nil)
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,8 @@ func makePanel(
|
||||
onClose: @escaping @MainActor () -> Void = {},
|
||||
detector: any LanguageDetecting = FixedLanguageDetector(detection: nil),
|
||||
target: ModelLanguage = HyMT3Languages.german,
|
||||
routes: [LanguageRoute] = []
|
||||
routes: [LanguageRoute] = [],
|
||||
captureLimits: CaptureLimits = CaptureLimits()
|
||||
) -> (PanelViewModel, CopiedTextBox, TargetBox) {
|
||||
let session = TranslationSession(pipelineFactory: { streaming })
|
||||
let copies = CopiedTextBox()
|
||||
@@ -26,7 +27,8 @@ func makePanel(
|
||||
target: target,
|
||||
model: "test-hy-mt3",
|
||||
keepAlive: "30m",
|
||||
languageRoutes: routes
|
||||
languageRoutes: routes,
|
||||
captureLimits: captureLimits
|
||||
),
|
||||
copy: { copies.text = $0 },
|
||||
replace: replacement,
|
||||
@@ -151,3 +153,46 @@ struct FixedLanguageDetector: LanguageDetecting {
|
||||
detection
|
||||
}
|
||||
}
|
||||
|
||||
/// A fake that reports three parts and waits after the first until the test releases it.
|
||||
actor GatedMultiPartStreaming: TranslationStreaming {
|
||||
private(set) var requests: [TranslationSessionRequest] = []
|
||||
private var releaseContinuation: CheckedContinuation<Void, Never>?
|
||||
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?
|
||||
) async throws -> PipelineResult {
|
||||
try await translate(request, onDelta: onDelta, onChunk: nil)
|
||||
}
|
||||
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?,
|
||||
onChunk: (@Sendable (Int, Int) async -> Void)?
|
||||
) async throws -> PipelineResult {
|
||||
requests.append(request)
|
||||
await onChunk?(1, 3)
|
||||
await onDelta?("part1 ")
|
||||
await withCheckedContinuation { releaseContinuation = $0 }
|
||||
await onChunk?(2, 3)
|
||||
await onDelta?("part2 ")
|
||||
await onChunk?(3, 3)
|
||||
await onDelta?("part3")
|
||||
return PipelineResult(
|
||||
translation: "part1 part2 part3",
|
||||
warnings: [],
|
||||
sourceLanguage: "en",
|
||||
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
|
||||
chunkCount: 3
|
||||
)
|
||||
}
|
||||
|
||||
func release() async {
|
||||
while releaseContinuation == nil {
|
||||
await Task.yield()
|
||||
}
|
||||
releaseContinuation?.resume()
|
||||
releaseContinuation = nil
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,28 @@ struct TranslationPipelineTests {
|
||||
#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)],
|
||||
|
||||
@@ -165,6 +165,67 @@ struct TranslationSessionTests {
|
||||
#expect(event == .failed(epoch: epoch, error: .ollamaUnreachable(url: url)))
|
||||
}
|
||||
|
||||
@Test func chunkProgressAndRequestLimitsAreForwarded() async {
|
||||
let streaming = ChunkReportingStreaming()
|
||||
let session = TranslationSession(pipelineFactory: { streaming })
|
||||
var iterator = await session.events().makeAsyncIterator()
|
||||
let longRequest = TranslationSessionRequest(
|
||||
captured: CapturedText(
|
||||
text: String(repeating: "a", count: 9000),
|
||||
capturedAt: Date(),
|
||||
source: .doubleCopy
|
||||
),
|
||||
target: HyMT3Languages.german,
|
||||
model: "test-hy-mt3",
|
||||
keepAlive: "30m",
|
||||
captureLimits: CaptureLimits(maximumParts: 3)
|
||||
)
|
||||
|
||||
let epoch = await session.start(longRequest)
|
||||
var chunks: [String] = []
|
||||
var finished = false
|
||||
while let event = await iterator.next() {
|
||||
switch event {
|
||||
case let .chunkStarted(eventEpoch, index, total) where eventEpoch == epoch:
|
||||
chunks.append("\(index)/\(total)")
|
||||
case let .finished(eventEpoch, result) where eventEpoch == epoch:
|
||||
#expect(result.chunkCount == 3)
|
||||
finished = true
|
||||
default:
|
||||
break
|
||||
}
|
||||
if finished {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
#expect(chunks == ["1/3", "2/3", "3/3"])
|
||||
#expect(finished)
|
||||
}
|
||||
|
||||
@Test func textAboveTheRequestCaptureLimitFailsBeforeTheFactory() async {
|
||||
let streaming = ScriptedStreaming()
|
||||
let session = TranslationSession(pipelineFactory: { streaming })
|
||||
var iterator = await session.events().makeAsyncIterator()
|
||||
let tooLong = TranslationSessionRequest(
|
||||
captured: CapturedText(
|
||||
text: String(repeating: "a", count: 8001),
|
||||
capturedAt: Date(),
|
||||
source: .doubleCopy
|
||||
),
|
||||
target: HyMT3Languages.german,
|
||||
model: "test-hy-mt3",
|
||||
keepAlive: "30m",
|
||||
captureLimits: CaptureLimits(maximumParts: 2)
|
||||
)
|
||||
|
||||
let epoch = await session.start(tooLong)
|
||||
_ = await iterator.next()
|
||||
let event = await iterator.next()
|
||||
#expect(event == .failed(epoch: epoch, error: .textTooLong(characters: 8001, limit: 8000)))
|
||||
#expect(await streaming.callCount == 0)
|
||||
}
|
||||
|
||||
private func result(_ translation: String, warnings: [TranslationWarning] = []) -> PipelineResult {
|
||||
PipelineResult(
|
||||
translation: translation,
|
||||
@@ -176,6 +237,34 @@ struct TranslationSessionTests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A fake that reports three chunks and a matching result.
|
||||
private actor ChunkReportingStreaming: TranslationStreaming {
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?
|
||||
) async throws -> PipelineResult {
|
||||
try await translate(request, onDelta: onDelta, onChunk: nil)
|
||||
}
|
||||
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?,
|
||||
onChunk: (@Sendable (Int, Int) async -> Void)?
|
||||
) async throws -> PipelineResult {
|
||||
for index in 1 ... 3 {
|
||||
await onChunk?(index, 3)
|
||||
await onDelta?("part\(index)")
|
||||
}
|
||||
return PipelineResult(
|
||||
translation: "done",
|
||||
warnings: [],
|
||||
sourceLanguage: "en",
|
||||
timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4),
|
||||
chunkCount: 3
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A controlled streaming fake. Each call waits until the test releases its outcome.
|
||||
private actor ScriptedStreaming: TranslationStreaming {
|
||||
enum Outcome: Sendable {
|
||||
|
||||
Reference in new issue
Block a user