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:
schihei committed 2026-11-27 20:21:30 +01:00
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
}
}
@@ -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.