Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift
T
schihei 2a601058f4 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.
2026-11-27 20:21:30 +01:00

288 lines
11 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
import SprachmittlerText
/// The documented prompt policy. `contentAware` is reserved for M7.
public enum PromptVariantPolicy: String, Codable, Sendable, Equatable {
/// Default Translation only (v1).
case defaultOnly
/// Content-aware prompt selection (reserved for M7).
case contentAware
}
/// The versioned, text-free application settings from `docs/ARCHITECTURE.md` §12.
public struct AppSettings: Codable, Sendable, Equatable {
/// The loopback default endpoint; a compile-time constant.
public static let defaultEndpoint = URL(string: "http://127.0.0.1:11434")!
/// The current settings schema version.
public static let currentVersion = 1
/// Ollama base URL.
public var endpoint: URL
/// Whether a non-loopback endpoint is allowed (HTTPS only).
public var allowRemoteEndpoint: Bool
/// The selected Hy-MT3 model tag.
public var model: String
/// The optional Fast model tag.
public var fastModel: String?
/// The mother tongue BCP-47 code; the default target when no rule matches.
public var targetLanguage: String
/// Source-language to target-language rules. Empty means everything goes to the mother tongue.
public var languageRoutes: [LanguageRoute]
/// Up to three recent target codes, most recent first.
public var recentTargetLanguages: [String]
/// The double-copy window in milliseconds (300–1000).
public var doubleCopyWindowMs: Int
/// The Latin/Cyrillic/Greek chunk limit.
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`.
public var numPredict: Int
/// `temperature`.
public var temperature: Double
/// `top_p`.
public var topP: Double
/// `top_k`.
public var topK: Int
/// `repeat_penalty`.
public var repeatPenalty: Double
/// `keep_alive` value: `5m`, `30m`, `1h` or `0`.
public var keepModelLoaded: String
/// Warm the model after launch (loopback only).
public var warmUpOnLaunch: Bool
/// Prompt policy; `defaultOnly` in v1.
public var promptVariantPolicy: PromptVariantPolicy
/// Always false; never copy automatically.
public var autoCopy: Bool
/// Show the source preview in the panel.
public var showSourcePreview: Bool
/// Translation text size in points (12–28).
public var translationFontSize: Int
/// Render Markdown formatting in the translation panel.
public var renderMarkdown: Bool
/// Make the panel key when shown so Esc and the shortcuts work without a click.
public var closeWithEscape: Bool
/// Reflect the login-item setting.
public var launchAtLogin: Bool
/// Keep the last translation in memory for the panel.
public var keepRecentTranslationInMemory: Bool
/// Whether first-run onboarding has been completed.
public var hasCompletedOnboarding: Bool
/// The settings schema version.
public var settingsVersion: Int
/// Creates the defaults. The system language becomes the target when supported.
public init() {
let systemCode = Locale.preferredLanguages.first.flatMap { HyMT3Languages.resolve($0)?.code }
endpoint = Self.defaultEndpoint
allowRemoteEndpoint = false
model = HyMT3ModelPreset.defaultModel
fastModel = HyMT3ModelPreset.fastModel
targetLanguage = systemCode ?? HyMT3Languages.english.code
languageRoutes = []
recentTargetLanguages = []
doubleCopyWindowMs = 500
maxCharactersLatin = 4000
maxCharactersCJK = 2000
maximumPartsPerSelection = 1
numCtx = 8192
numPredict = 4096
temperature = 0.7
topP = 0.6
topK = 20
repeatPenalty = 1.05
keepModelLoaded = HyMT3ModelPreset.defaultKeepAlive
warmUpOnLaunch = true
promptVariantPolicy = .defaultOnly
autoCopy = false
showSourcePreview = true
translationFontSize = 17
renderMarkdown = true
closeWithEscape = true
launchAtLogin = false
keepRecentTranslationInMemory = true
hasCompletedOnboarding = false
settingsVersion = Self.currentVersion
}
/// The target language value, always a catalogue entry.
public var targetLanguageModel: ModelLanguage {
HyMT3Languages.resolve(targetLanguage) ?? HyMT3Languages.english
}
/// The recent targets that still exist in the catalogue.
public var recentTargets: [ModelLanguage] {
recentTargetLanguages.compactMap(HyMT3Languages.resolve)
}
/// Validates the configured endpoint against the remote policy.
public func validatedEndpoint() throws -> URL {
try EndpointPolicy.validate(endpoint, allowRemote: allowRemoteEndpoint)
}
/// Records a target as recent, keeping at most three unique codes.
public mutating func noteTarget(_ language: ModelLanguage) {
targetLanguage = language.code
recentTargetLanguages.removeAll { $0 == language.code }
recentTargetLanguages.insert(language.code, at: 0)
recentTargetLanguages = Array(recentTargetLanguages.prefix(3))
}
/// Clamps values edited outside the decoder (Settings UI) to the safe ranges.
public mutating func sanitize() {
targetLanguage = HyMT3Languages.resolve(targetLanguage)?.code ?? HyMT3Languages.english.code
languageRoutes = Self.normalizedRoutes(languageRoutes)
doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000)
maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000)
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)
topP = min(max(topP, 0), 1)
topK = Self.clamp(topK, to: 1 ... 100)
repeatPenalty = min(max(repeatPenalty, 0.5), 2)
translationFontSize = Self.clamp(translationFontSize, to: 12 ... 28)
if !["5m", "30m", "1h", "0"].contains(keepModelLoaded) {
keepModelLoaded = HyMT3ModelPreset.defaultKeepAlive
}
autoCopy = false
}
/// The documented sampling values as an options value.
public var samplingOptions: SamplingOptions {
SamplingOptions(
temperature: temperature,
topP: topP,
topK: topK,
repeatPenalty: repeatPenalty,
numPredict: numPredict,
numCtx: numCtx
)
}
/// The chunker limits.
public var chunker: Chunker {
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
}
struct DecodedSampling {
let temperature: Double
let topP: Double
let topK: Int
let repeatPenalty: Double
}
static func decodeLimits(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings
) throws -> DecodedLimits {
try DecodedLimits(
window: clamp(
container.decodeIfPresent(Int.self, forKey: .doubleCopyWindowMs)
?? defaults.doubleCopyWindowMs,
to: 300 ... 1000
),
latin: clamp(
container.decodeIfPresent(Int.self, forKey: .maxCharactersLatin)
?? defaults.maxCharactersLatin,
to: 500 ... 10000
),
cjk: clamp(
container.decodeIfPresent(Int.self, forKey: .maxCharactersCJK)
?? defaults.maxCharactersCJK,
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,
to: 1024 ... 32768
),
numPredict: clamp(
container.decodeIfPresent(Int.self, forKey: .numPredict) ?? defaults.numPredict,
to: 1 ... 8192
),
fontSize: clamp(
container.decodeIfPresent(Int.self, forKey: .translationFontSize)
?? defaults.translationFontSize,
to: 12 ... 28
)
)
}
static func decodeSampling(
from container: KeyedDecodingContainer<CodingKeys>,
defaults: AppSettings
) throws -> DecodedSampling {
let temperature = try container.decodeIfPresent(Double.self, forKey: .temperature)
?? defaults.temperature
let topP = try container.decodeIfPresent(Double.self, forKey: .topP) ?? defaults.topP
let repeatPenalty = try container.decodeIfPresent(Double.self, forKey: .repeatPenalty)
?? defaults.repeatPenalty
return try DecodedSampling(
temperature: min(max(temperature, 0), 2),
topP: min(max(topP, 0), 1),
topK: clamp(
container.decodeIfPresent(Int.self, forKey: .topK) ?? defaults.topK,
to: 1 ... 100
),
repeatPenalty: min(max(repeatPenalty, 0.5), 2)
)
}
enum CodingKeys: String, CodingKey {
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, languageRoutes
case recentTargetLanguages
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
case settingsVersion
}
static func normalizedRoutes(_ routes: [LanguageRoute]) -> [LanguageRoute] {
var seen = Set<String>()
return routes.compactMap { route in
guard let source = HyMT3Languages.resolve(route.source)?.code,
let target = HyMT3Languages.resolve(route.target)?.code,
source.caseInsensitiveCompare(target) != .orderedSame,
seen.insert(source.lowercased()).inserted
else {
return nil
}
return LanguageRoute(source: source, target: target)
}
}
static func clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
min(max(value, range.lowerBound), range.upperBound)
}
}