From 2a601058f4047fbc416077ca459386acd2f085d4 Mon Sep 17 00:00:00 2001 From: Heiko Joerg Schick Date: Fri, 27 Nov 2026 20:21:30 +0100 Subject: [PATCH] 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. --- App/AppEnvironment.swift | 14 ++- App/Panel/PanelView+Content.swift | 12 ++ App/Settings/LongSelectionsSettings.swift | 39 ++++++ App/Settings/SettingsView.swift | 15 +-- MANIFEST.sha256 | 54 ++++---- .../PasteboardWatcher.swift | 7 +- .../AppSettings+Codable.swift | 2 + .../SprachmittlerCore/AppSettings.swift | 22 +++- .../SprachmittlerCore/CaptureLimits.swift | 29 ++++- .../SprachmittlerCore/CapturePolicy.swift | 6 +- .../SprachmittlerCore/PanelViewModel.swift | 117 +++++++++++++----- .../SprachmittlerErrorMessages.swift | 4 +- .../TranslationPipeline.swift | 14 ++- .../TranslationSession.swift | 76 ++++++++++-- .../Sources/SprachmittlerText/Chunker.swift | 2 +- .../PasteboardWatcherTests.swift | 25 ++++ .../AppSettingsTests.swift | 22 +++- .../CapturePolicyTests.swift | 26 ++++ .../PanelChunkingTests.swift | 51 ++++++++ .../PanelTestSupport.swift | 49 +++++++- .../TranslationPipelineTests.swift | 22 ++++ .../TranslationSessionTests.swift | 89 +++++++++++++ README.md | 2 +- docs/ARCHITECTURE.md | 9 +- docs/DECISIONS.md | 6 +- docs/LANGUAGES.md | 2 +- docs/PROGRESS.md | 1 + docs/SELECTION_AND_CLIPBOARD.md | 4 +- docs/TRANSLATION_OUTPUT.md | 8 +- 29 files changed, 607 insertions(+), 122 deletions(-) create mode 100644 App/Settings/LongSelectionsSettings.swift create mode 100644 Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelChunkingTests.swift diff --git a/App/AppEnvironment.swift b/App/AppEnvironment.swift index bc9449a..9134da4 100644 --- a/App/AppEnvironment.swift +++ b/App/AppEnvironment.swift @@ -88,7 +88,8 @@ final class AppEnvironment { pasteboard: pasteboard, configuration: DoubleCopyDetector.Configuration( window: Double(windowMs) / 1000 - ) + ), + limits: store.current().captureLimits ) let factoryStore = store @@ -218,7 +219,8 @@ final class AppEnvironment { renderMarkdown: settings.renderMarkdown, closeWithEscape: settings.closeWithEscape, languageRoutes: settings.languageRoutes, - recentTargets: settings.recentTargets + recentTargets: settings.recentTargets, + captureLimits: settings.captureLimits ) } @@ -227,6 +229,7 @@ final class AppEnvironment { let previousTarget = panelViewModel.configuration.target.code let previousRoutes = panelViewModel.configuration.languageRoutes panelViewModel.updateConfiguration(configuration(for: settings)) + watcher.limits = settings.captureLimits if settings.doubleCopyWindowMs != watcherWindowMs { watcherWindowMs = settings.doubleCopyWindowMs restartWatcher() @@ -250,7 +253,8 @@ final class AppEnvironment { pasteboard: pasteboard, configuration: DoubleCopyDetector.Configuration( window: Double(watcherWindowMs) / 1000 - ) + ), + limits: settingsStore.current().captureLimits ) if let sink = watcherEventSink { watcher.start(onEvent: sink) @@ -279,7 +283,7 @@ final class AppEnvironment { lastWarnings = [] onStateChange?() - switch CapturePolicy.validate(captured.text) { + switch CapturePolicy.validate(captured.text, limits: settingsStore.current().captureLimits) { case .valid: lastCaptureFailure = nil case .empty: @@ -404,7 +408,7 @@ extension AppEnvironment { await diagnostics.record(kind: "error", detail: error.diagnosticCode) } onStateChange?() - case .started, .delta, .cancelled: + case .started, .chunkStarted, .delta, .cancelled: break } } diff --git a/App/Panel/PanelView+Content.swift b/App/Panel/PanelView+Content.swift index ef47b78..e26b219 100644 --- a/App/Panel/PanelView+Content.swift +++ b/App/Panel/PanelView+Content.swift @@ -220,6 +220,18 @@ extension PanelView { .disabled(model.source == nil) .accessibilityLabel(String(localized: "Retry translation")) + if let current = model.currentChunk, let total = model.totalChunks, total > 1 { + Text(String(localized: "Part \(current) of \(total)")) + .font(.caption) + .foregroundStyle(.secondary) + .accessibilityLabel(String(localized: "Part \(current) of \(total)")) + } else if model.chunkCount > 1 { + Text(String(localized: "\(model.chunkCount) parts")) + .font(.caption) + .foregroundStyle(.secondary) + .accessibilityLabel(String(localized: "Translated in \(model.chunkCount) parts")) + } + Spacer() Button { diff --git a/App/Settings/LongSelectionsSettings.swift b/App/Settings/LongSelectionsSettings.swift new file mode 100644 index 0000000..7b59a77 --- /dev/null +++ b/App/Settings/LongSelectionsSettings.swift @@ -0,0 +1,39 @@ +import SprachmittlerCore +import SwiftUI + +/// The long-selection settings: part size and the number of parts one capture may use. +struct LongSelectionsSettings: View { + @Binding var draft: AppSettings + + var body: some View { + Section(String(localized: "Long selections")) { + Stepper( + String(localized: "Latin part size: \(draft.maxCharactersLatin)"), + value: $draft.maxCharactersLatin, + in: 1000 ... 10000, + step: 500 + ) + Stepper( + String(localized: "Dense-script part size: \(draft.maxCharactersCJK)"), + value: $draft.maxCharactersCJK, + in: 500 ... 4000, + step: 250 + ) + Stepper( + String(localized: "Maximum parts per selection: \(draft.maximumPartsPerSelection)"), + value: $draft.maximumPartsPerSelection, + in: 1 ... 8 + ) + Text( + String( + localized: """ + One part rejects text longer than a single part. Higher values translate \ + long selections one part at a time, which takes longer. + """ + ) + ) + .font(.caption) + .foregroundStyle(.secondary) + } + } +} diff --git a/App/Settings/SettingsView.swift b/App/Settings/SettingsView.swift index e5de061..c5fc87c 100644 --- a/App/Settings/SettingsView.swift +++ b/App/Settings/SettingsView.swift @@ -239,20 +239,7 @@ struct SettingsView: View { } } - Section(String(localized: "Chunking")) { - Stepper( - String(localized: "Latin limit: \(draft.maxCharactersLatin)"), - value: $draft.maxCharactersLatin, - in: 1000 ... 10000, - step: 500 - ) - Stepper( - String(localized: "Dense-script limit: \(draft.maxCharactersCJK)"), - value: $draft.maxCharactersCJK, - in: 500 ... 5000, - step: 250 - ) - } + LongSelectionsSettings(draft: $draft) Section(String(localized: "Prompt policy")) { Text(String(localized: "Default translation is fixed for v1.")) diff --git a/MANIFEST.sha256 b/MANIFEST.sha256 index cd888a5..85933e8 100644 --- a/MANIFEST.sha256 +++ b/MANIFEST.sha256 @@ -18,7 +18,7 @@ c989a2513d0b926f3a202b0616426c7443594ce72896ee91c29c4e83451d433c ./.opencode/sk 2c0c375f3f6704a43e1042b250e0b633ba740aa7bc2fbf5518891a7b5464507e ./.swiftlint.yml 3222c8553505401c967cc302e2d46a99db95f98d92650f6b245e2a1dc901bea9 ./AGENTS.md 593745fab27436e91148de34b7e0e530cef5137e2c566cb479caed033602b949 ./App/AppDelegate.swift -ffecf629fcbe9b5d3f85e9834f5a9c3eb794304a7cc20a45691d1943eb57d18a ./App/AppEnvironment.swift +1461fb881c44cee037051e78a4ea1e36ad459abbab1fc7d530ad993687520d11 ./App/AppEnvironment.swift dc41f554a88b5b499840f72ef676b31530e6ebfcc5da636155001c52ca48d8a1 ./App/Diagnostics/DiagnosticsView.swift 69f0c24937507ed7a9137abfa95fdcd2798cd909dd74642d4b5e6a859da94253 ./App/Info.plist 36aec6e936e6ffff104908b370a7231b9283e178df8d0a453639dca9c573460d ./App/LaunchAtLoginController.swift @@ -30,7 +30,7 @@ ba9467153908c81fbb2497d5679642ae15c7b9fa23a10ca9b9ab678042aab222 ./App/Onboardi 382661bb55524acd7a686f215f8dd1cfdd4127dc19629dd637204c5b1e0734e9 ./App/Panel/LanguagePickerView.swift 76dcf59e01ae8319d4f0aabc5e600c549adaf56b6db802794804c3215be9377c ./App/Panel/MarkdownTranslationView.swift 0d8e9dd5c361987e717e5425cb3a4bef2849a3ba5f40d302a4074f4847abf45b ./App/Panel/PanelController.swift -e8ac837a35076814985d3320e5996c8cee00074bb9e1c8073804e20ed0c76f33 ./App/Panel/PanelView+Content.swift +6b84571bda2bd12e4990430d098d081871c6e239782f5c2e07650e3f7cde6dbc ./App/Panel/PanelView+Content.swift 5a76a652c8f5b03421f475211a4beff98037092004dfbfb54fcaab18fab67b36 ./App/Panel/PanelView.swift bd37b327672595d55c263f109005b816406cce5928ac58c66286cee0f5d16531 ./App/Panel/README.md 9e09591204b9ca4518a031fc856b0cd01245fe8c4e14aa7238e75a83ab05d4c3 ./App/Panel/TranslationPanel.swift @@ -50,8 +50,9 @@ f23266b9672263c92ced1d26fe4dafa75a14d530eb9bc5fc1f599034d597ab48 ./App/Resource ce0c088300a0a739ecc0a73892aad6b9538397d637760962a810dbf65692f62b ./App/Resources/de.lproj/Localizable.strings ac67edd346d0828cd0e86cae4e3da719a9e574d22217f0f15a6d30558bd76e14 ./App/Resources/en.lproj/Localizable.strings 5c2e5222430e1822c3e13cdfed202f54cabc32beefb7651af78475b29494dcf2 ./App/Settings/LanguageRulesSettings.swift +0be6586ef0653cd8e5dd12a1b195c236d54fd1aeaf09bbef48da43195e78b6c7 ./App/Settings/LongSelectionsSettings.swift dcdaf8761f3b195e8c8d8889b2b792aa3dabbaa47b0c641fb4db4cdc09436026 ./App/Settings/README.md -b686d5d282bf569af3985099546195815c2bb5be1db74a2895d9c1b7eda12df1 ./App/Settings/SettingsView.swift +3066bb45d7b90e3ad07931f56dc234b4b3481c40459842e00430b6a66ef28308 ./App/Settings/SettingsView.swift d3dcb4365c3d9ec39fa379b8e5cc0813745acc68dc851a85b4ab277896a2a5b1 ./App/Sprachmittler.entitlements ddda3377a2e130e25195da349dd0964cfca8a401464b7b0cd8fcec6bfb575fa3 ./App/SprachmittlerApp.swift c3d0de679f6d151f46cfdd11577eba65e1cff1f82be669be32e42a99fba302ba ./Makefile @@ -65,15 +66,15 @@ ec2f66d1a2d8ebb308427802f54cc70c6bdead8c31a57ed87648446d6bda9ce1 ./Packages/Spr 85abecf8ca1b15fe1a9d5dbaa0caee16a38a4408e932f6115975d9823a2ac47c ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/InsertionCoordinator.swift 0b8a8223e67d0c94551c1dd68609858602069d0ecd4eda736f988880d1e04464 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardAccessing.swift 4ca88b4f08515057738a45c9ae475260e3a840c1d5bb3d4622a57ce04f5b8cb1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardTicking.swift -543efb54825e2851528efd0c2a4b068929b79c3e0276c1314e6b5414480f893a ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.swift +dc5f5b08ec537ac917c96b7ba4c1881bfdfb7c21e166a4f9ee1f6d9e1289b351 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.swift 26aeb81883b8216f364215602b804a2d6e6994a221f9c910c0ed52cc70d4c3aa ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/ServicesProvider.swift dada1b00037d12da0df03a24d1140e428beb9488fde7e0a9d99d0cca58d1a4ca ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/SprachmittlerCapture.swift 728ab857854f1f2bb46f032a13f6d47edd491ee0d6ca0aa8bf2b98f91ccb3c23 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/SystemPasteboard.swift 7c580669d76ca3154889a2f3045a1e2689c8984398163496e0ce4cdcad9ae880 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppOllama.swift -f916e53b45650e03f3ff112cb35b67d52de48164f22aa0656a51d4a3353fb9b4 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift -9be13be1a6fdeb0c0dccfd86fc57036a8d9decdcb36e8e61360c269f3824309a ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift -7921d56341b4b6fe4392989b30de91bb2aeb91a8d52d840dc9602a3d5a6134dd ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift -5159e03a08507c4d6f61479cd4ce389e9541a8df4540ef6540cedaba6e8133a1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift +9030a1f039515cd92b2178f90649cb028d248a941f16e2d1fc9d52663d7239d9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift +e2ced0cedfdbea4621ba9d01907a56e80001770af0e7e41b31712a042d0c451e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift +a150f68cc08fddc17c09dea5bdb4d85b1b4c3035fa4a9f8a24c48efd1fc0f313 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift +d711719fa15d25c28c7e29c1a8773da9da61ff0372917ecf684fe27538e1decf ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift 02421321864ecf0540a96b55a692e91eacb9364d579735d20b9ca94ebcf99a80 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureText.swift 3ce80227fe4f6cfb9efc00d83cb4bff28e870fd72aa29d8cc03a723e8694a34e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturedText.swift 2a8c7b261b3c955547fd88520a9582c5c31a1e86a4c13d8bebfbe1d4b8f752bc ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsStore.swift @@ -86,7 +87,7 @@ cc89553a898735a1288bdd1c67a04fbcd282f99ee812a83c8b18eff9627ab65d ./Packages/Spr 39cec81db2748fd5e01c5d6ade00bae5babf4a68d7d472a69e98b20884585c5f ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Loggers.swift 83b6c93fc950df1fa8e4942521187a0ee3ecb319b5ffec6deef6047ef8d2b171 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OllamaErrorMapping.swift b7dfab9b2c613071b97bc329378eae47b97305cae758221fba787c8be4eb52f5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OnboardingViewModel.swift -2e7a0d02cd9341471e8b58c5df16aa75706dd1350d82fb496e3ad54d3a9cb14d ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift +0e08aac528b2a8da63f2b2cccbc2a4a134c1dbc49927f3d78115b3faaa2944ef ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift c52e182fdc6806a06f7b516806140ef26aad8c44e72f9e5beb9135acbe28b878 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelWarningMessages.swift 563d79ceae06a20e8a5b78e155bfe8489bac8f5267a8c3d064fd5c50ecc66cf5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PermissionProtocols.swift 761c20b4a1c063ac39648c3d24d8864a0329ff348eaf45db4fb27c573f15e44a ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsStore.swift @@ -96,10 +97,10 @@ e33ebfeeeb27b88029c20f212769852c5c0a697abaeb1bc249d350e7ad649273 ./Packages/Spr 20e3977534de6e1c1af8bcc3049318007213a034aa2e8d2d24032b22e1bacba0 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Signposts.swift b6580ae5a0f5e18b6b527766cb5acd5de4d828df3badac44ae294dd72acfc436 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerCore.swift 2864b92feb24a0616fa546ea2683fbdc9f73352ca64ab84da110e19fd7c6a926 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerError.swift -c54f853a63db2f71fb5e574976e0f6b3ed39ae768adb644a0e245c5844fa2b5c ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift +359faa0524007bb58a504b073c854c04736482b893e9509e56843a6850d9e7ac ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift f75ae67b262e18b53721d070acc0e8d7bdfca94698f10c1a5780ef948ef72912 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TextInserting.swift -b7d4bf8d2a1ab24b26dfa3e091e9fa7e92f8460f8850f9f086af4814537b1f4a ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift -d01aaf98c054bd3d14ce4d6055f576738d83b63037f246b0ec3cc302b130c12b ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift +98de162fc7be182a5832e81f12b2bf72c336abf1a65a6a2c94821b4bf51b39d9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift +d3511504a464cb986ffad56ef31f5723cf6451fdef04b1e2bf6c58d2be21a6be ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift 480503eea4bc64f3125560c91d47e56cd9905e957af189a54cdf8b816a380ec2 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationWarning.swift 5a721207611b9aa6228bc288f5f5e0c57dd26c593ab3aec9bd38c91f9a9e0fd2 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Adapter.swift 06bf6da9127b3a010cb33b3db091e4301b32aca44f8cc7181ed1c34b00ece7b5 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Languages.swift @@ -162,7 +163,7 @@ c32d05b70ba04d525064a2ed71f5ea67d1655d72c56f9d185aefe4250840321b ./Packages/Spr 03d570bc4022f205abb52da509bd68444879308b14f46bad497cadf9f80f3845 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeSettingsAndPermissions.swift 16e6ae7d693df1ee6532affec1fa687aeed1e709595b929f2a4e1f00e1b9d88a ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/ManualPasteboardTicker.swift c0f87a5320fe715f5dbc7c9bbc7c0fb19a5b64d1c145c45b26f060c151eccada ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/ManualSleeper.swift -3443a4e2a7d3d493b9d604875f0abec2f3a515fd162f6af41e25f48c78185b57 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift +0ea5a0c60c2185262e52f71c78538f9b1bb308c9835dc2362f70929da9bc42cd ./Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift b639d452d78dcda9e9f3b5ac3298e8499a7837a955839ae5203b508944df2c63 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClass.swift b768d43f50bd4fcede0f3c654787771a605b6ea2648cac722d0e78dd913b4fa5 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClassifier.swift 9eebbc1339104d8a0b0f9f579d0c9f0bf69b05b5ad1a4550cf645ca3197686dd ./Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.swift @@ -194,23 +195,24 @@ e7ec098ecc2e0c3f62ba53cd44afc0659b77b7baf2d5ab307cb4238c1f6efa5c ./Packages/Spr d4e110c510cac46c1acecc68f28ef8b30daaf1f9b623f0533ad359a6a13680aa ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/ClipboardSnapshotTests.swift 23e0c52e3f5f9b5848ff9118bfe3baf474a21c830560be382b978328e794218e ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/DoubleCopyDetectorTests.swift efac77b258ef29cca1cc61311ef8d167e45ad5680a73396a1b4bc6d99d9a3f45 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/InsertionCoordinatorTests.swift -6ff42653fd8b3bf33407249c9a482397bd6fbf953b149ad51136ea2a16f29c45 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PasteboardWatcherTests.swift +c23c58fa553049241f4c40193d41aba4fed8261f1ece4f32bcdf65af25abf099 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PasteboardWatcherTests.swift 87e92d608b14675873a6554a3bcce951fb62b45b95ce32972df978cada697a43 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PlaceholderTests.swift d2d3507f437c7126bf15ebcba7be6d03794a73a637089c511c99096bc564cc5a ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/ServicesProviderTests.swift f7375e2cd08709d7b590ae4f6d70be3edb88f122f9fb3aeaac37c826ff637d12 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/SystemPasteboardTests.swift -f6929d7db0379c53a7e32ec16b3f0e8e56b6aa48cdc570b68fa06f6541da0b1f ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift -4ca70a674a35b723f7608bfe9b250b8572586ce4923e9965245626588935bb6e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.swift +8eb9ab1b8b15568295aff0b90640afad7f1a38ceaf3dfa2145a0a338f7071d57 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift +2ea18f23e2328110fa6d61e51ecf4607eea7bb82d1c8eeac5dfd844f07c3a6e0 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.swift 2d5742a1fbbb65044455cea92b9f95b9d39f5236e92e4f152b141bcf964c639e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMappingTests.swift c584df764e9fa0a029ed9f17c1a3b27cb4e3b91005f27171d5553aaf51edb48a ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMessageTests.swift 95ca20f1c4cf0fd68f29a488770a1d6d7911c534913a0f88515ea1fe4f4cdb9e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/LogRedactionTests.swift 6610797e6dd77401d1bce624d65e84db9bdda95820b1f56add1d24cea1f5df91 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/LoggingContractTests.swift 8c0462d50ff3796aba6024349083d8b1ede654b495790d7610f95aecc8870001 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/OnboardingAndSettingsTests.swift +fa5572b8825c7cff4c21f45e5381cb746606c270a45dee75e304be684b64ce1d ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelChunkingTests.swift f8f1ecfe58f003a0713ee2948c06a7b0ea18272319336025a31f87618bd56f0d ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelRoutingTests.swift -199d3bd2f5f3a0aecf2f654279c80d2e78a79a51e4317de980d7e8bfe33381ae ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelTestSupport.swift +f2071269097a49ddd38a23a213920d09a7786201ef7eb68199a8eb90a4bee303 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelTestSupport.swift 667624e7bc610bbecf323d4401787082bec3e3a2397bd1de86d1dca897e1082b ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift e9fe1b63792e610bac81153c6bc79d4c836c36c4c9538b26887daf62e9684d80 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PlaceholderTests.swift -9a1a9671fdde945d3dd8356ea4dab8b6c30120d868970507883a77657701c500 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift -304cc5262dd6713041bb12cfa5502e5971c1c7e486c33be79818985bc0545232 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift +5671265556115fe93adb7ee3ccd39a9f31786c7da2e022fe9914db06e5555e24 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift +641482d5c4e8540861775d67d007d6820e1849f6e7b3d2b0456ef462434ada79 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift 988eb93a5d1483a6db061c1a11d5b06d7632157c076352c435418152f47910a5 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/README.md 86bae20b590f03748a5b498a0ae402d7bb10fb0b7ba7bbccc821fcbbcba8ab37 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/default-prompt.txt 615de4459d2d77dac87809bb33af42d32ab624cb5367d1b3b9de6841d4935bc3 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/delimiters-prompt.txt @@ -258,25 +260,25 @@ b0a7d3451d8830654fe79476b8d32d95709d956817a4436f58c0f73bbd8d3194 ./Packages/Spr 8c5c21634d749ad05da8b6a0fc1d8e132a494177a697ba0a1338a7a6b5dba50c ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/PlaceholderTests.swift 67c0f9ba9e818267e99c1756b82643f7e59effa6783325675386aba0a1002cb3 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ProtectedTokenScannerTests.swift c3294d486cfe44a6f0a69a1ec05cff33a8eccf090fce04fadffa96b6b2563d6f ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/TextNormalizationTests.swift -615bd4d905b4f5c3330749444475ae601d542c6225cae28ad103928107c66fc0 ./README.md +2d902ce53c14b6d64a578bdcc99845b6375a69ced37f503423c9df6cbf3c15f0 ./README.md f1dbc2fb876d909b8486239e9b75b09ed68516c341d586e96d8626715c86a88c ./dist/Sprachmittler-0.1.0-local.dmg -7e3d7e96941603d6838739080abc64d6c77d09efac28a4eda1591da57e6a6336 ./docs/ARCHITECTURE.md +b100978fe55c5afbf6b3c987b34e17f3413329d3fd580a2cfcd616f71a564aa9 ./docs/ARCHITECTURE.md 018c5faf1a5d2e8d851ab209d45e64993cbd6b7976c4aa90c571359c83e83264 ./docs/CODING_STANDARDS.md -3678c5d63ed05f279fb7a4923e677dff08353c898b65679107819b7c03228ff7 ./docs/DECISIONS.md +0eddd31ac7f4ad295720b9081896200d622f28ed3a17bdab30f57f557d980bdd ./docs/DECISIONS.md 5b80ea8994519f2be34aa10abb345ac3029d3d3a29705dcfa0a1cb344f4b95d2 ./docs/HYMT3_MODEL.md d87fc9df926f6ba77ce67b2731b83f48f2b49848c637f12d0fdfb5f27f3c6775 ./docs/IMPLEMENTATION_PLAN.md c3a1838fb0a06acf6b7826f6ff278e15065af198dab22ffb1435dacdc064ad69 ./docs/KICKOFF.md -20a87dc7cf8cb593445c89d334e123f6275232524598ac71a21ca32766cedfb7 ./docs/LANGUAGES.md +b1d9fcfffd9d0e6b3a9792633ad71acdef29a344eea0dea778e132a7c0330322 ./docs/LANGUAGES.md a28161210fbabe27d1348f3552851fe7b30c9dccc658272f2cc79af5e085ec40 ./docs/MODEL_EVALUATION.md 6f94dfe4f2146ce0b9e066198c9e05ce659faf4318513ce586c966989fd3d1c0 ./docs/OLLAMA_TRANSLATION_API.md e6dbccc3cb4c7a169a6daaa563066a6764a76b6b7649738b839dcbd9b2400ee5 ./docs/OPENCODE_V2.md e2b785807ecb56eb1e7c02aaa6a487ce7c1be421865685bed4be2e973269bdce ./docs/PERFORMANCE.md 4a37cf1815071b3afdd10443ec9e05a5a78411d615c42f51117c5873922531c4 ./docs/PRD.md -ca7650131b2dd399f02fbbc85bc231bdeb0c421affd6c2a44447ec60223e1b20 ./docs/PROGRESS.md +6ea3e3881a9f6a7de968128e660a897c648d8e01af77b3e831228b809d0d94e2 ./docs/PROGRESS.md c72f39e7e5e1fb9c45c32f0741a379564debca4b408e702615d162f360d47ecf ./docs/SECURITY_PRIVACY.md -2e6c7ba67d857db7cddf1e31b5a6516f70b8094e9115094b58156f9e6626452c ./docs/SELECTION_AND_CLIPBOARD.md +f140344de55d11eb450961639ba85a1ff479cf2e0cfb3c8bd3c4cdb2220a11ea ./docs/SELECTION_AND_CLIPBOARD.md 8720e8bf79ba7ab051bb8bd09f55b7766f98941904f354cbe3ab7b88c941e860 ./docs/TESTING.md -555a42e170353fff25e349f61b7aef40e5b2a7ea7493d47e8c77ce15f3a70d14 ./docs/TRANSLATION_OUTPUT.md +14677683317de607406997825d4ee239ec042c9872f0b44c29ebdf00f6540aa5 ./docs/TRANSLATION_OUTPUT.md 5c4d63f01581cdbc21d7ff9da8604adf8230e280b42512e3375cd0a72a225f5a ./docs/USER_GUIDE.md 373b20746a6ed145ee598786458a97cead5cacd97a339db14b3e2341645c6c8d ./evaluation/README.md a60f1917c64ac8c3df0d01dd55818652ae100a6d750c34be24675b33226cad45 ./evaluation/corpus.example.json diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.swift index eb7dd1d..bd1db95 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.swift @@ -30,6 +30,9 @@ public final class PasteboardWatcher { private var suppressUntil = Date.distantPast private var task: Task? + /// 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) diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift index d68d8e1..13cb162 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift @@ -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) diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift index 83faa64..44ba215 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift @@ -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 diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift index b744247..156bf7e 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift @@ -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 } } diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift index c9619f3..98c20be 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift @@ -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) diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift index 9bf719c..22f4ca8 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift @@ -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 + } } diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift index 0483778..401712d 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift @@ -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: diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift index ea42356..3460a63 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift @@ -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 diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift index 88140ad..fa67b4e 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift @@ -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 diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift index 0ce50ca..8319e05 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift @@ -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. diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PasteboardWatcherTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PasteboardWatcherTests.swift index 9e00784..fd7516b 100644 --- a/Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PasteboardWatcherTests.swift +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PasteboardWatcherTests.swift @@ -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) diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift index d1dc637..da1f185 100644 --- a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift @@ -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"), diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.swift index 7bf474b..3d3a44f 100644 --- a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.swift +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.swift @@ -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) + } } diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelChunkingTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelChunkingTests.swift new file mode 100644 index 0000000..2708fad --- /dev/null +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelChunkingTests.swift @@ -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) + } +} diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelTestSupport.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelTestSupport.swift index 9cbcf09..8eac5f5 100644 --- a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelTestSupport.swift +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelTestSupport.swift @@ -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? + + 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 + } +} diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift index 8185153..2e6eb66 100644 --- a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift @@ -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)], diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift index e27f5b3..a45c556 100644 --- a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift @@ -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 { diff --git a/README.md b/README.md index ebb8ade..adc7fdf 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ Replace verifies the source app and, when available, the selected text before to - **General** — mother tongue, language rules, source preview, Markdown rendering, translation text size, Esc behaviour, double-copy window and startup. - **Model** — model and Fast preset, Ollama endpoint, sampling and context settings. -- **Translation** — chunking and prompt policy. +- **Translation** — part size, maximum parts per selection and prompt policy. One part (the default) rejects longer text; higher values translate long selections sequentially and the panel shows the part progress. - **Privacy** — local/remote endpoint policy and permissions. - **Diagnostics** — server version, model digests, the last 50 timings and error kinds. No text or translations. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3342834..3e9fadd 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -359,7 +359,7 @@ public struct DoubleCopyDetector { /* pure state machine */ } - Poll `NSPasteboard.general.changeCount` every **120 ms** on the main actor through `PasteboardTicking`. - A candidate trigger is two changes within **500 ms** (range 300–1000 ms, setting) whose `.string` values are identical and non-empty after trimming. -- Require at least one non-whitespace character and at most `maxCharacters` (4000 Latin / 2000 CJK by default). +- Require at least one non-whitespace character and at most the capture limit (`maxCharacters` per part × `maximumPartsPerSelection`: 4000/2000 Latin/dense by default, one part). - Ignore changes whose pasteboard contains the app's own marker (`com.schihei.sprachmittler.own`) or `org.nspasteboard.TransientType`, and ignore all changes for 750 ms after our own write. - Keep only the last two strings and their hashes in memory; clear them after the window or after the session starts. - Do not log the text. Log only `changeCount` deltas and a short hash at `privacy: .private`. @@ -483,7 +483,7 @@ Full detail: `docs/TRANSLATION_OUTPUT.md`. 2. Detect the source language with `NLLanguageRecognizer` for display only. The prompt does not need it. 3. Classify content: `.plain`, `.markdown`, `.json`, `.html`, `.code`, `.delimited` (many URLs/placeholders). 4. Scan protected tokens: URLs, e-mail addresses, `{{var}}`, `${var}`, `%s`, `%d`, `%1$@`, Markdown code spans, fenced code blocks, HTML tags, JSON keys. -5. Plan chunks: paragraph boundaries first, then sentence, then word; script-aware limits (4000 characters for Latin/Cyrillic/Greek, 2000 for CJK/Arabic/Hebrew/Devanagari etc.). Never split a grapheme cluster. +5. Plan parts: paragraph boundaries first, then sentence, then word; script-aware part sizes (4000 characters for Latin/Cyrillic/Greek, 2000 for CJK/Arabic/Hebrew/Devanagari etc.). Never split a grapheme cluster. The capture gate accepts up to `maximumPartsPerSelection` parts. ### 9.2 Prompt selection (`SprachmittlerEngines`) @@ -575,8 +575,9 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour | `targetLanguage` | LanguageCode | system language if supported, else `en` | | `recentTargetLanguages` | [String] | last three targets, most recent first | | `doubleCopyWindowMs` | Int | 500 (300–1000) | -| `maxCharactersLatin` | Int | 4000 | -| `maxCharactersCJK` | Int | 2000 | +| `maxCharactersLatin` | Int | 4000 (500–10000) | +| `maxCharactersCJK` | Int | 2000 (500–4000) | +| `maximumPartsPerSelection` | Int | 1 (1–8); 1 rejects text longer than one part | | `numCtx` | Int | 8192 | | `numPredict` | Int | 4096 | | `temperature` | Double | 0.7 | diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 88e2782..238b68e 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -77,9 +77,9 @@ Consequences: No mixed V1/V2 files. Sampling settings for agents, if wanted, go ## ADR-011 — Chunk at paragraph boundaries with script-aware limits Status: Accepted -Context: Hy-MT3's documented translation context is 8192 tokens. A long selection can exceed it; splitting mid-sentence harms quality; splitting mid-grapheme corrupts text. -Decision: Chunk at blank-line paragraph boundaries first, then sentence, then word. Use 4000 characters for Latin/Cyrillic/Greek and 2000 for CJK and other dense scripts. Never split a grapheme cluster. Reassemble with the original separators. Translate chunks sequentially with one request in flight. -Consequences: Most selections are one chunk. Very long selections lose some cross-paragraph context; the panel shows a chunk count and any failed chunk. `done_reason: "length"` is always a warning. +Context: Hy-MT3's documented translation context is 8192 tokens. A long selection can exceed it; splitting mid-sentence harms quality; splitting mid-grapheme corrupts text. The capture gate and the chunk size were the same number, so selections over one chunk were rejected before the pipeline could split them. +Decision: Chunk at blank-line paragraph boundaries first, then sentence, then word. Use 4000 characters per part for Latin/Cyrillic/Greek and 2000 for CJK and other dense scripts. Never split a grapheme cluster. Reassemble with the original separators. Translate parts sequentially with one request in flight. The capture limit is the part size multiplied by `maximumPartsPerSelection` (1–8, default 1); `1` rejects anything over one part, and higher values accept the selection and translate it in parts. The dense-script part size is capped at 4000 because 5000 dense characters plus a 4096-token output can overflow the context. +Consequences: Default behaviour is unchanged (one part). Users who opt into parts trade latency for reach: every extra part is another sequential request, and the panel shows “Part 2 of 4” while streaming and “3 parts” when finished. Very long selections lose some cross-paragraph context; the panel keeps the streamed partial text and disables Replace when a part fails. `done_reason: "length"` is always a warning. ## ADR-012 — Only documented prompt variants; no free-form prompts Status: Accepted diff --git a/docs/LANGUAGES.md b/docs/LANGUAGES.md index 70f7bfd..f4619a5 100644 --- a/docs/LANGUAGES.md +++ b/docs/LANGUAGES.md @@ -138,7 +138,7 @@ Hy-MT3 supports **102 languages**. The exact English name matters: it is inserte 4. **Unknown codes are not silently mapped.** The UI shows only the 102 supported languages; an incoming detection result outside the list is displayed as "Unknown" and translation still proceeds (the prompt only needs the target). 5. **Source detection is advisory.** `NLLanguageRecognizer` supports fewer languages than Hy-MT3. A low-confidence or unsupported detection never blocks translation. 6. **RTL languages:** `ar`, `he`, `fa`, `ur`, `ps`, `sd`, `ug`, `ckb`, `yi`, and `kk` (Arabic Kazakh). The panel must render them right-to-left; the source and translation directions can differ. -7. **Dense-script chunk limit:** CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts use the 2000-character chunk limit; Latin/Cyrillic/Greek use 4000. The chunker uses Unicode script ranges, not the language code. +7. **Dense-script part size:** CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts use the 2000-character part size; Latin/Cyrillic/Greek use 4000. The chunker uses Unicode script ranges, not the language code. ## 5. UI ordering diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 50f7c68..3e5eb23 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -159,3 +159,4 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain) 2026-11-26 · Panel · Added an optional reverse direction: with the saved target German and fallback English, confidently German text is translated to English automatically, and vice versa. The saved target and effective target are separate; a banner offers a one-capture override, and the language picker still changes the saved target. `autoSwitchTarget` defaults on and `fallbackTargetLanguage` defaults to English/the opposite language. Filtered near-zero detector hypotheses so the high-confidence same-language rule works. Added resolver, settings, view-model and detector tests. (Superseded by the routing entry below.) 2026-11-26 · Settings · Replaced the single reverse-direction pair with language routing: the saved target is the mother tongue and the default for every source; an empty `languageRoutes` table means everything goes to the mother tongue. Optional source→target rules (for example Chinese → English) apply only to confidently detected sources. The panel shows the effective direction, offers a one-capture override, and keeps the picker session-only; persistent rules live in Settings. Removed the old fallback settings. 2026-11-27 · Panel · Fixed the header language picker: an override now carries the chosen language instead of only disabling routing. `TranslationDirectionPolicy.resolve` takes `override: ModelLanguage?`, and `PanelViewModel` stores the override target, so picking a language other than the mother tongue retranslates into it; a new capture still returns to the rule/mother tongue. Added picker and rule-override tests. +2026-11-27 · T3.2/T4.1/Settings · Long selections can now be translated in parts. The capture gate and the chunk size were the same number, so text over one chunk was rejected before the pipeline could split it. Added `maximumPartsPerSelection` (1–8, default 1, so existing behaviour is unchanged); the capture limit is now part size × parts, carried on `TranslationSessionRequest` and applied by the watcher, `CapturePolicy` and the session. `TranslationStreaming` can report each part, the session emits `chunkStarted`, and the panel shows “Part 2 of 4” while streaming and “3 parts” when finished. `textTooLong` now points at Settings and offers the Settings button. Lowered the dense-script part size maximum to 4000 (5000 dense characters plus a 4096-token output can overflow the 8192 context). Tests: capture limits, watcher limits, pipeline part callbacks, session events, panel progress and settings clamping. Docs: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES, README. diff --git a/docs/SELECTION_AND_CLIPBOARD.md b/docs/SELECTION_AND_CLIPBOARD.md index f76a28a..75216b5 100644 --- a/docs/SELECTION_AND_CLIPBOARD.md +++ b/docs/SELECTION_AND_CLIPBOARD.md @@ -33,7 +33,7 @@ Rules: - Window: **500 ms** default, configurable 300–1000 ms. - Identical text: compare normalized line endings and trimming only; do not collapse internal whitespace. - Non-empty: at least one non-whitespace character. -- Length: 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts; above the limit, show `textTooLong` with the limit and no request. +- Length: part size 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts, multiplied by `maximumPartsPerSelection` (1–8, default 1); above that capture limit, show `textTooLong` with the limit, offer Settings and make no request. - A new trigger during an active translation cancels the old one (ADR-015). - Copying two different things quickly does not trigger; this is deliberate. - Copying the same text twice slowly does not trigger; increase the window if needed. @@ -160,7 +160,7 @@ Info.plist: **This table is filled in by a person, on a real Mac.** Double copy, Accessibility replacement and clipboard restoration differ in every app and cannot be tested headlessly. Until a row is tested its cells stay ☐; an untested cell is not a claim. -Implementation status (2026-11-26): T3.1–T3.4 and T5.1–T5.4 are implemented and covered by component tests (`DoubleCopyDetector`, `PasteboardWatcher`, `ClipboardSnapshot`, `ServicesProvider`, `InsertionCoordinator`). The 4000/2000 limit and own-marker check apply to double copy, the menu item and Services (`CapturePolicy`). Replace captures the target at trigger time, re-verifies it, prefers AX and falls back to a snapshot/⌘V/restore path. The 10-app double-copy and insertion matrices remain untested; they are the T3.5/T5.5 manual tasks. +Implementation status (2026-11-26): T3.1–T3.4 and T5.1–T5.4 are implemented and covered by component tests (`DoubleCopyDetector`, `PasteboardWatcher`, `ClipboardSnapshot`, `ServicesProvider`, `InsertionCoordinator`). The script-aware part size × `maximumPartsPerSelection` capture limit and own-marker check apply to double copy, the menu item and Services (`CapturePolicy`). Replace captures the target at trigger time, re-verifies it, prefers AX and falls back to a snapshot/⌘V/restore path. The 10-app double-copy and insertion matrices remain untested; they are the T3.5/T5.5 manual tasks. For each app test: diff --git a/docs/TRANSLATION_OUTPUT.md b/docs/TRANSLATION_OUTPUT.md index 8500494..af0178e 100644 --- a/docs/TRANSLATION_OUTPUT.md +++ b/docs/TRANSLATION_OUTPUT.md @@ -24,10 +24,12 @@ The prompt prefix depends only on the target language. Append the source last. D - Paragraph boundaries (blank lines) first. - Then sentence boundaries (`.`, `!`, `?`, `。`, `!`, `?`, `…` followed by whitespace/end). - Then word boundaries; never split a grapheme cluster. -- Limits: **4000 characters** for Latin/Cyrillic/Greek; **2000** for CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts. The limit is script-based, not language-based. +- Part size: **4000 characters** for Latin/Cyrillic/Greek; **2000** for CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts. The limit is script-based, not language-based. +- Capture limit: part size × `maximumPartsPerSelection` (1–8, default **1**). `1` rejects a selection longer than one part; higher values accept it and translate it part by part. The dense part size is configurable up to 4000. - Reassemble with the original separators (usually `\n\n`). Do not collapse or invent paragraph breaks. -- Translate chunks sequentially; one request in flight. -- A chunk failure stops the sequence and is shown as `chunkFailed(index:)`; the panel keeps the partial translation and disables Replace. +- Translate parts sequentially; one request in flight. +- Show “Part i of n” while a multi-part request streams and “n parts” when it finishes. +- A part failure stops the sequence and is shown as `chunkFailed(index:)`; the panel keeps the partial translation and disables Replace. ## 4. Protected tokens