Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift
T
schihei a3e544fbe4 feat(panel): close with Esc without a click and render Markdown
Esc: make the panel key when shown (closeWithEscape, default on) without activating the app; the source app stays frontmost and Replace still targets it. Handle Esc with SwiftUI's exit command, which also works from the popover and after clicking controls. Add TranslationPanel.canBecomeKey and amend ADR-009.\n\nMarkdown: add MarkdownPresentation in SprachmittlerText (Foundation inline parser plus a conservative block parser for headings, lists, quotes, fenced code and rules), a SwiftUI MarkdownTranslationView, and a renderMarkdown setting (default on). JSON, HTML and code sources are never rendered; only http/https links open; images become alt text; Copy and Replace keep the raw Markdown (ADR-021).\n\nVerified: make verify green; synthetic Esc closes the panel and closes an open language popover first; a live Markdown translation rendered heading, bold/italic, inline code, list, quote, code block and link; Copy returned the raw Markdown; Replace still changed the TextEdit selection with the panel key.
2026-11-26 15:26:30 +01:00

341 lines
15 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 selected target BCP-47 code.
public var targetLanguage: String
/// 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
/// `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
recentTargetLanguages = []
doubleCopyWindowMs = 500
maxCharactersLatin = 4000
maxCharactersCJK = 2000
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
doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000)
maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000)
maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 5000)
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)
}
private struct DecodedLimits {
let window: Int
let latin: Int
let cjk: Int
let numCtx: Int
let numPredict: Int
let fontSize: Int
}
private struct DecodedSampling {
let temperature: Double
let topP: Double
let topK: Int
let repeatPenalty: Double
}
private 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 ... 5000
),
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
)
)
}
private 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)
)
}
private enum CodingKeys: String, CodingKey {
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, recentTargetLanguages
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict
case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown
case closeWithEscape, launchAtLogin, keepRecentTranslationInMemory, hasCompletedOnboarding
case settingsVersion
}
/// Decodes with v0 migration: missing or unknown fields fall back to defaults, and an old
/// `settingsVersion` is upgraded to the current one. Unknown keys are ignored by Codable.
public init(from decoder: any Decoder) throws {
let defaults = AppSettings()
let container = try decoder.container(keyedBy: CodingKeys.self)
endpoint = try container.decodeIfPresent(URL.self, forKey: .endpoint) ?? defaults.endpoint
allowRemoteEndpoint = try container.decodeIfPresent(Bool.self, forKey: .allowRemoteEndpoint)
?? defaults.allowRemoteEndpoint
model = try container.decodeIfPresent(String.self, forKey: .model) ?? defaults.model
fastModel = container.contains(.fastModel)
? try container.decodeIfPresent(String.self, forKey: .fastModel)
: defaults.fastModel
let decodedTarget = try container.decodeIfPresent(String.self, forKey: .targetLanguage)
?? defaults.targetLanguage
targetLanguage = HyMT3Languages.resolve(decodedTarget)?.code ?? defaults.targetLanguage
let recents = try container.decodeIfPresent([String].self, forKey: .recentTargetLanguages) ?? []
var seen = Set<String>()
recentTargetLanguages = recents.compactMap { HyMT3Languages.resolve($0)?.code }
.filter { seen.insert($0).inserted }
.prefix(3)
.map(\.self)
let limits = try Self.decodeLimits(from: container, defaults: defaults)
doubleCopyWindowMs = limits.window
maxCharactersLatin = limits.latin
maxCharactersCJK = limits.cjk
numCtx = limits.numCtx
numPredict = limits.numPredict
translationFontSize = limits.fontSize
let sampling = try Self.decodeSampling(from: container, defaults: defaults)
temperature = sampling.temperature
topP = sampling.topP
topK = sampling.topK
repeatPenalty = sampling.repeatPenalty
let keep = try container.decodeIfPresent(String.self, forKey: .keepModelLoaded)
?? defaults.keepModelLoaded
keepModelLoaded = ["5m", "30m", "1h", "0"].contains(keep) ? keep : defaults.keepModelLoaded
warmUpOnLaunch = try container.decodeIfPresent(Bool.self, forKey: .warmUpOnLaunch) ?? defaults.warmUpOnLaunch
let policy = try container.decodeIfPresent(PromptVariantPolicy.self, forKey: .promptVariantPolicy)
?? defaults.promptVariantPolicy
promptVariantPolicy = policy
// Auto-copy is a hard invariant: decoding cannot turn it on.
autoCopy = false
showSourcePreview = try container.decodeIfPresent(Bool.self, forKey: .showSourcePreview)
?? defaults.showSourcePreview
renderMarkdown = try container.decodeIfPresent(Bool.self, forKey: .renderMarkdown) ?? defaults.renderMarkdown
closeWithEscape = try container.decodeIfPresent(Bool.self, forKey: .closeWithEscape) ?? defaults.closeWithEscape
launchAtLogin = try container.decodeIfPresent(Bool.self, forKey: .launchAtLogin) ?? defaults.launchAtLogin
keepRecentTranslationInMemory = try container.decodeIfPresent(
Bool.self,
forKey: .keepRecentTranslationInMemory
) ?? defaults.keepRecentTranslationInMemory
hasCompletedOnboarding = try container.decodeIfPresent(Bool.self, forKey: .hasCompletedOnboarding)
?? defaults.hasCompletedOnboarding
settingsVersion = Self.currentVersion
}
public func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(endpoint, forKey: .endpoint)
try container.encode(allowRemoteEndpoint, forKey: .allowRemoteEndpoint)
try container.encode(model, forKey: .model)
try container.encode(fastModel, forKey: .fastModel)
try container.encode(targetLanguage, forKey: .targetLanguage)
try container.encode(recentTargetLanguages, forKey: .recentTargetLanguages)
try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs)
try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin)
try container.encode(maxCharactersCJK, forKey: .maxCharactersCJK)
try container.encode(numCtx, forKey: .numCtx)
try container.encode(numPredict, forKey: .numPredict)
try container.encode(temperature, forKey: .temperature)
try container.encode(topP, forKey: .topP)
try container.encode(topK, forKey: .topK)
try container.encode(repeatPenalty, forKey: .repeatPenalty)
try container.encode(keepModelLoaded, forKey: .keepModelLoaded)
try container.encode(warmUpOnLaunch, forKey: .warmUpOnLaunch)
try container.encode(promptVariantPolicy, forKey: .promptVariantPolicy)
try container.encode(autoCopy, forKey: .autoCopy)
try container.encode(showSourcePreview, forKey: .showSourcePreview)
try container.encode(translationFontSize, forKey: .translationFontSize)
try container.encode(renderMarkdown, forKey: .renderMarkdown)
try container.encode(closeWithEscape, forKey: .closeWithEscape)
try container.encode(launchAtLogin, forKey: .launchAtLogin)
try container.encode(keepRecentTranslationInMemory, forKey: .keepRecentTranslationInMemory)
try container.encode(hasCompletedOnboarding, forKey: .hasCompletedOnboarding)
try container.encode(settingsVersion, forKey: .settingsVersion)
}
private static func clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
min(max(value, range.lowerBound), range.upperBound)
}
}