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
@@ -30,6 +30,9 @@ public final class PasteboardWatcher {
|
||||
private var suppressUntil = Date.distantPast
|
||||
private var task: Task<Void, Never>?
|
||||
|
||||
/// The capture limits used by the next poll.
|
||||
public var limits: CaptureLimits
|
||||
|
||||
/// True while the poll task is running.
|
||||
public private(set) var isRunning = false
|
||||
|
||||
@@ -38,11 +41,13 @@ public final class PasteboardWatcher {
|
||||
pasteboard: any PasteboardAccessing,
|
||||
configuration: DoubleCopyDetector.Configuration = DoubleCopyDetector.Configuration(),
|
||||
ticker: any PasteboardTicking = TimerPasteboardTicker(),
|
||||
limits: CaptureLimits = CaptureLimits(),
|
||||
now: @escaping @MainActor () -> Date = { Date() }
|
||||
) {
|
||||
self.pasteboard = pasteboard
|
||||
detector = DoubleCopyDetector(configuration: configuration)
|
||||
self.ticker = ticker
|
||||
self.limits = limits
|
||||
self.now = now
|
||||
lastChangeCount = pasteboard.changeCount
|
||||
}
|
||||
@@ -102,7 +107,7 @@ public final class PasteboardWatcher {
|
||||
case .empty:
|
||||
return .noText
|
||||
case let .captured(text):
|
||||
let limit = CaptureLimits.characters(for: text)
|
||||
let limit = limits.captureLimit(for: text)
|
||||
guard text.count <= limit else {
|
||||
detector.reset()
|
||||
return .textTooLong(characters: text.count, limit: limit)
|
||||
|
||||
@@ -24,6 +24,7 @@ public extension AppSettings {
|
||||
doubleCopyWindowMs = limits.window
|
||||
maxCharactersLatin = limits.latin
|
||||
maxCharactersCJK = limits.cjk
|
||||
maximumPartsPerSelection = limits.parts
|
||||
numCtx = limits.numCtx
|
||||
numPredict = limits.numPredict
|
||||
translationFontSize = limits.fontSize
|
||||
@@ -67,6 +68,7 @@ public extension AppSettings {
|
||||
try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs)
|
||||
try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin)
|
||||
try container.encode(maxCharactersCJK, forKey: .maxCharactersCJK)
|
||||
try container.encode(maximumPartsPerSelection, forKey: .maximumPartsPerSelection)
|
||||
try container.encode(numCtx, forKey: .numCtx)
|
||||
try container.encode(numPredict, forKey: .numPredict)
|
||||
try container.encode(temperature, forKey: .temperature)
|
||||
|
||||
@@ -39,6 +39,8 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
public var maxCharactersLatin: Int
|
||||
/// The dense-script chunk limit.
|
||||
public var maxCharactersCJK: Int
|
||||
/// How many chunks one capture may contain (1–8). `1` rejects text longer than one chunk.
|
||||
public var maximumPartsPerSelection: Int
|
||||
/// `num_ctx`.
|
||||
public var numCtx: Int
|
||||
/// `num_predict`.
|
||||
@@ -89,6 +91,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
doubleCopyWindowMs = 500
|
||||
maxCharactersLatin = 4000
|
||||
maxCharactersCJK = 2000
|
||||
maximumPartsPerSelection = 1
|
||||
numCtx = 8192
|
||||
numPredict = 4096
|
||||
temperature = 0.7
|
||||
@@ -138,7 +141,8 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
languageRoutes = Self.normalizedRoutes(languageRoutes)
|
||||
doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000)
|
||||
maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000)
|
||||
maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 5000)
|
||||
maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 4000)
|
||||
maximumPartsPerSelection = Self.clamp(maximumPartsPerSelection, to: 1 ... 8)
|
||||
numCtx = Self.clamp(numCtx, to: 1024 ... 32768)
|
||||
numPredict = Self.clamp(numPredict, to: 1 ... 8192)
|
||||
temperature = min(max(temperature, 0), 2)
|
||||
@@ -169,10 +173,16 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
Chunker(latinLimit: maxCharactersLatin, denseLimit: maxCharactersCJK)
|
||||
}
|
||||
|
||||
/// The chunk and capture limits derived from the settings.
|
||||
public var captureLimits: CaptureLimits {
|
||||
CaptureLimits(chunker: chunker, maximumParts: maximumPartsPerSelection)
|
||||
}
|
||||
|
||||
struct DecodedLimits {
|
||||
let window: Int
|
||||
let latin: Int
|
||||
let cjk: Int
|
||||
let parts: Int
|
||||
let numCtx: Int
|
||||
let numPredict: Int
|
||||
let fontSize: Int
|
||||
@@ -203,7 +213,12 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
cjk: clamp(
|
||||
container.decodeIfPresent(Int.self, forKey: .maxCharactersCJK)
|
||||
?? defaults.maxCharactersCJK,
|
||||
to: 500 ... 5000
|
||||
to: 500 ... 4000
|
||||
),
|
||||
parts: clamp(
|
||||
container.decodeIfPresent(Int.self, forKey: .maximumPartsPerSelection)
|
||||
?? defaults.maximumPartsPerSelection,
|
||||
to: 1 ... 8
|
||||
),
|
||||
numCtx: clamp(
|
||||
container.decodeIfPresent(Int.self, forKey: .numCtx) ?? defaults.numCtx,
|
||||
@@ -244,7 +259,8 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, languageRoutes
|
||||
case recentTargetLanguages
|
||||
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict
|
||||
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, maximumPartsPerSelection
|
||||
case numCtx, numPredict
|
||||
case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch
|
||||
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown
|
||||
case closeWithEscape, launchAtLogin, keepRecentTranslationInMemory, hasCompletedOnboarding
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
import SprachmittlerText
|
||||
|
||||
/// The capture character limit for a text, based on its script (`docs/TRANSLATION_OUTPUT.md` §3).
|
||||
public enum CaptureLimits {
|
||||
/// 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts.
|
||||
public static func characters(for text: String) -> Int {
|
||||
Chunker().limit(for: text)
|
||||
/// The per-request chunk size and the total size one capture may have.
|
||||
///
|
||||
/// `maximumParts == 1` rejects anything longer than one chunk. Higher values accept up to
|
||||
/// `maximumParts` chunks and translate them sequentially (`docs/TRANSLATION_OUTPUT.md` §3).
|
||||
public struct CaptureLimits: Sendable, Equatable {
|
||||
/// The per-request chunk size.
|
||||
public let chunker: Chunker
|
||||
/// How many chunks one capture may contain (at least 1).
|
||||
public let maximumParts: Int
|
||||
|
||||
/// Creates limits.
|
||||
public init(chunker: Chunker = Chunker(), maximumParts: Int = 1) {
|
||||
self.chunker = chunker
|
||||
self.maximumParts = max(1, maximumParts)
|
||||
}
|
||||
|
||||
/// The per-chunk character limit for `text`.
|
||||
public func chunkLimit(for text: String) -> Int {
|
||||
chunker.limit(for: text)
|
||||
}
|
||||
|
||||
/// The total character limit for one capture.
|
||||
public func captureLimit(for text: String) -> Int {
|
||||
chunkLimit(for: text) * maximumParts
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,10 @@ public enum CaptureValidation: Sendable, Equatable {
|
||||
|
||||
/// Applies the capture rules shared by double copy, the menu and Services.
|
||||
public enum CapturePolicy {
|
||||
/// Validates non-emptiness and the 4000/2000 script-aware limit.
|
||||
public static func validate(_ text: String) -> CaptureValidation {
|
||||
/// Validates non-emptiness and the capture limit (`chunk size × maximum parts`).
|
||||
public static func validate(_ text: String, limits: CaptureLimits = CaptureLimits()) -> CaptureValidation {
|
||||
guard text.contains(where: { !$0.isWhitespace }) else { return .empty }
|
||||
let limit = CaptureLimits.characters(for: text)
|
||||
let limit = limits.captureLimit(for: text)
|
||||
let characters = text.count
|
||||
guard characters <= limit else {
|
||||
return .textTooLong(characters: characters, limit: limit)
|
||||
|
||||
@@ -39,6 +39,8 @@ public struct PanelConfiguration: Sendable, Equatable {
|
||||
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(
|
||||
@@ -51,7 +53,8 @@ public struct PanelConfiguration: Sendable, Equatable {
|
||||
renderMarkdown: Bool = true,
|
||||
closeWithEscape: Bool = true,
|
||||
languageRoutes: [LanguageRoute] = [],
|
||||
recentTargets: [ModelLanguage] = []
|
||||
recentTargets: [ModelLanguage] = [],
|
||||
captureLimits: CaptureLimits = CaptureLimits()
|
||||
) {
|
||||
self.target = target
|
||||
self.model = model
|
||||
@@ -63,6 +66,7 @@ public struct PanelConfiguration: Sendable, Equatable {
|
||||
self.closeWithEscape = closeWithEscape
|
||||
self.languageRoutes = languageRoutes
|
||||
self.recentTargets = recentTargets
|
||||
self.captureLimits = captureLimits
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,6 +100,12 @@ public final class PanelViewModel {
|
||||
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
|
||||
@@ -205,6 +215,9 @@ public final class PanelViewModel {
|
||||
timing = nil
|
||||
didCopy = false
|
||||
isReplacing = false
|
||||
chunkCount = 1
|
||||
currentChunk = nil
|
||||
totalChunks = nil
|
||||
if resetDirectionOverride {
|
||||
targetOverride = nil
|
||||
}
|
||||
@@ -256,6 +269,9 @@ public final class PanelViewModel {
|
||||
warnings = []
|
||||
timing = nil
|
||||
sourceLanguage = nil
|
||||
chunkCount = 1
|
||||
currentChunk = nil
|
||||
totalChunks = nil
|
||||
effectiveTarget = configuration.target
|
||||
routedSource = nil
|
||||
targetOverride = nil
|
||||
@@ -339,6 +355,9 @@ public final class PanelViewModel {
|
||||
didCopy = false
|
||||
isReplacing = false
|
||||
sameLanguageDismissed = false
|
||||
chunkCount = 1
|
||||
currentChunk = nil
|
||||
totalChunks = nil
|
||||
effectiveTarget = configuration.target
|
||||
routedSource = nil
|
||||
targetOverride = nil
|
||||
@@ -357,45 +376,83 @@ public final class PanelViewModel {
|
||||
target: effectiveTarget,
|
||||
model: configuration.model,
|
||||
keepAlive: configuration.keepAlive,
|
||||
sampling: configuration.sampling
|
||||
sampling: configuration.sampling,
|
||||
captureLimits: configuration.captureLimits
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension PanelViewModel {
|
||||
private func handle(_ event: TranslationSessionEvent) {
|
||||
switch event {
|
||||
case let .started(epoch, request):
|
||||
currentEpoch = epoch
|
||||
source = request.captured
|
||||
effectiveTarget = request.target
|
||||
translation = ""
|
||||
warnings = []
|
||||
error = nil
|
||||
phase = .translating
|
||||
handleStarted(epoch: epoch, request: request)
|
||||
case let .chunkStarted(epoch, index, total):
|
||||
handleChunkStarted(epoch: epoch, index: index, total: total)
|
||||
case let .delta(epoch, text):
|
||||
guard epoch == currentEpoch else { return }
|
||||
translation += text
|
||||
phase = .streaming
|
||||
handleDelta(epoch: epoch, text: text)
|
||||
case let .finished(epoch, result):
|
||||
guard epoch == currentEpoch else { return }
|
||||
translation = result.translation
|
||||
warnings = result.warnings
|
||||
timing = result.timing
|
||||
sourceLanguage = result.sourceLanguage
|
||||
if result.warnings.contains(.emptyOutput) {
|
||||
error = .emptyOutput
|
||||
phase = .failed
|
||||
} else {
|
||||
phase = .ready
|
||||
}
|
||||
case let .failed(epoch, failure):
|
||||
guard epoch == currentEpoch else { return }
|
||||
error = failure
|
||||
phase = .failed
|
||||
handleFinished(epoch: epoch, result: result)
|
||||
case let .failed(epoch, error):
|
||||
handleFailed(epoch: epoch, error: error)
|
||||
case let .cancelled(epoch):
|
||||
guard epoch == currentEpoch else { return }
|
||||
phase = .idle
|
||||
error = nil
|
||||
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
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -28,7 +28,7 @@ public extension SprachmittlerError {
|
||||
case .emptyText:
|
||||
"No text was copied."
|
||||
case let .textTooLong(_, limit):
|
||||
"This selection is too long (limit \(limit) characters)."
|
||||
"This selection is too long (limit \(limit) characters). You can raise the limit in Settings."
|
||||
case .pasteboardUnavailable:
|
||||
"The clipboard is unavailable."
|
||||
case .ollamaUnreachable:
|
||||
@@ -108,7 +108,7 @@ public extension SprachmittlerError {
|
||||
case .ollamaTooOld, .endpointRejected:
|
||||
.openSettings
|
||||
case .textTooLong:
|
||||
.shortenText
|
||||
.openSettings
|
||||
case .accessibilityNotTrusted:
|
||||
.openSettings
|
||||
case .accessibilityUnsupported, .insertionTargetChanged, .pasteboardRestoreFailed:
|
||||
|
||||
@@ -94,7 +94,8 @@ public struct TranslationPipeline: Sendable {
|
||||
model: String,
|
||||
keepAlive: String,
|
||||
sampling: SamplingOptions = .publisherDefault,
|
||||
onDelta: (@Sendable (String) async -> Void)? = nil
|
||||
onDelta: (@Sendable (String) async -> Void)? = nil,
|
||||
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)? = nil
|
||||
) async throws -> PipelineResult {
|
||||
let normalized = TextNormalization.normalizeInput(text)
|
||||
guard !normalized.isEmpty else {
|
||||
@@ -118,7 +119,7 @@ public struct TranslationPipeline: Sendable {
|
||||
tokens: tokens,
|
||||
onDelta: onDelta
|
||||
)
|
||||
let accumulator = try await translateAll(chunks, context: context)
|
||||
let accumulator = try await translateAll(chunks, context: context, onChunk: onChunk)
|
||||
|
||||
let final = TextNormalization.normalizeOutput(accumulator.joined)
|
||||
let validation = validator.validate(
|
||||
@@ -168,11 +169,16 @@ public struct TranslationPipeline: Sendable {
|
||||
var sawLength = false
|
||||
}
|
||||
|
||||
private func translateAll(_ chunks: [TextChunk], context: TranslationContext) async throws -> Accumulator {
|
||||
private func translateAll(
|
||||
_ chunks: [TextChunk],
|
||||
context: TranslationContext,
|
||||
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)?
|
||||
) async throws -> Accumulator {
|
||||
var accumulator = Accumulator()
|
||||
do {
|
||||
for chunk in chunks {
|
||||
for (offset, chunk) in chunks.enumerated() {
|
||||
try Task.checkCancellation()
|
||||
await onChunk?(offset + 1, chunks.count)
|
||||
let result = try await translateChunk(chunk, context: context)
|
||||
if accumulator.firstTokenAt == nil {
|
||||
accumulator.firstTokenAt = result.firstTokenAt
|
||||
|
||||
@@ -10,6 +10,24 @@ public protocol TranslationStreaming: Sendable {
|
||||
_ 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 {}
|
||||
@@ -28,6 +46,22 @@ public extension TranslationPipeline {
|
||||
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.
|
||||
@@ -42,6 +76,8 @@ public struct TranslationSessionRequest: Sendable, Equatable {
|
||||
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(
|
||||
@@ -49,13 +85,15 @@ public struct TranslationSessionRequest: Sendable, Equatable {
|
||||
target: ModelLanguage,
|
||||
model: String,
|
||||
keepAlive: String,
|
||||
sampling: SamplingOptions = .publisherDefault
|
||||
sampling: SamplingOptions = .publisherDefault,
|
||||
captureLimits: CaptureLimits = CaptureLimits()
|
||||
) {
|
||||
self.captured = captured
|
||||
self.target = target
|
||||
self.model = model
|
||||
self.keepAlive = keepAlive
|
||||
self.sampling = sampling
|
||||
self.captureLimits = captureLimits
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +101,8 @@ public struct TranslationSessionRequest: Sendable, Equatable {
|
||||
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.
|
||||
@@ -102,16 +142,7 @@ public actor TranslationSession {
|
||||
let currentEpoch = epoch
|
||||
continuation.yield(.started(epoch: currentEpoch, request: request))
|
||||
|
||||
switch CapturePolicy.validate(request.captured.text) {
|
||||
case .valid:
|
||||
break
|
||||
case .empty:
|
||||
continuation.yield(.failed(epoch: currentEpoch, error: .emptyText))
|
||||
return currentEpoch
|
||||
case let .textTooLong(characters, limit):
|
||||
continuation.yield(
|
||||
.failed(epoch: currentEpoch, error: .textTooLong(characters: characters, limit: limit))
|
||||
)
|
||||
guard validate(request, epoch: currentEpoch) else {
|
||||
return currentEpoch
|
||||
}
|
||||
|
||||
@@ -122,6 +153,9 @@ public actor TranslationSession {
|
||||
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)
|
||||
@@ -166,11 +200,31 @@ public actor TranslationSession {
|
||||
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
|
||||
|
||||
@@ -4,7 +4,7 @@ import Foundation
|
||||
///
|
||||
/// Joining `chunks(for:)` with `reassemble(_:)` always returns the input exactly. The chunker does
|
||||
/// not trim, normalise or invent separators; call `TextNormalization.normalizeInput` first.
|
||||
public struct Chunker: Sendable {
|
||||
public struct Chunker: Sendable, Equatable {
|
||||
/// The limit for Latin, Cyrillic and Greek text.
|
||||
public let latinLimit: Int
|
||||
/// The limit for CJK, Arabic, Thai, Indic and other dense scripts.
|
||||
|
||||
+25
@@ -67,6 +67,31 @@ struct PasteboardWatcherTests {
|
||||
)
|
||||
}
|
||||
|
||||
@Test func configuredPartsAcceptLongerText() {
|
||||
let pasteboard = FakePasteboard()
|
||||
let watcher = PasteboardWatcher(pasteboard: pasteboard, limits: CaptureLimits(maximumParts: 3))
|
||||
|
||||
let accepted = String(repeating: "a", count: 12000)
|
||||
pasteboard.simulateCopy(accepted)
|
||||
_ = watcher.poll(at: start)
|
||||
pasteboard.simulateCopy(accepted)
|
||||
guard case let .captured(captured) = watcher.poll(at: start.addingTimeInterval(0.1)) else {
|
||||
Issue.record("expected a capture")
|
||||
return
|
||||
}
|
||||
#expect(captured.text.count == 12000)
|
||||
|
||||
let tooLong = String(repeating: "a", count: 12001)
|
||||
watcher.clear()
|
||||
pasteboard.simulateCopy(tooLong)
|
||||
_ = watcher.poll(at: start.addingTimeInterval(0.2))
|
||||
pasteboard.simulateCopy(tooLong)
|
||||
#expect(
|
||||
watcher.poll(at: start.addingTimeInterval(0.3))
|
||||
== .textTooLong(characters: 12001, limit: 12000)
|
||||
)
|
||||
}
|
||||
|
||||
@Test func ownWritesAreSuppressedFor750Milliseconds() {
|
||||
let pasteboard = FakePasteboard()
|
||||
let watcher = PasteboardWatcher(pasteboard: pasteboard)
|
||||
|
||||
@@ -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