feat(m4-m6): session, panel, Replace, settings and onboarding

M4: TranslationSession actor with epochs/one-in-flight streaming, PanelViewModel, non-activating NSPanel, streaming panel UI, searchable/recent target languages, warnings/errors and Copy/Retry/Replace actions.

M5: InsertionCoordinator with target capture, AX direct replacement, secure-field/own-PID refusal, frontmost and selected-text verification, snapshot/⌘V/restore fallback, cancellation-safe restore and blocking-warning gate.

M6: versioned AppSettings/SettingsStore, onboarding for Ollama/model/target/Accessibility, General/Model/Translation/Privacy/Diagnostics settings, launch-at-login via SMAppService, status menu (target, copy/replace last, setup, diagnostics, about), text-free diagnostics and first-run setup.

Docs: PROGRESS M4–M6, ARCHITECTURE §10–§12, ADR-019/020, SELECTION_AND_CLIPBOARD and TESTING. Manual 10-app matrices, real AX/paste delivery, VoiceOver and focus checks remain open.

Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, 217 package tests); app launches and a two-copy clipboard smoke test opens the panel.
This commit is contained in:
schihei committed 2026-11-26 14:03:16 +01:00
1 parent 64078e2f04
commit a78572adc3
47 files changed
+4963 -79

No files matched your search

@@ -0,0 +1,44 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
/// Builds the Ollama clients and pipeline from a settings snapshot. This keeps every concrete
/// client in one composition helper and away from the app target.
public typealias OllamaCatalog = SprachmittlerOllama.OllamaCatalog
public enum AppOllama {
/// A catalog for the configured endpoint.
public static func makeCatalog(settings: AppSettings) throws -> any OllamaCatalog {
let http = try OllamaHTTPClient(
baseURL: settings.endpoint,
allowRemote: settings.allowRemoteEndpoint
)
return OllamaCatalogClient(http: http)
}
/// A translation pipeline for the configured endpoint and chunk limits.
public static func makePipeline(settings: AppSettings) throws -> TranslationPipeline {
let http = try OllamaHTTPClient(
baseURL: settings.endpoint,
allowRemote: settings.allowRemoteEndpoint
)
let chat = OllamaChatClient(http: http)
let registry = AdapterRegistry(adapters: [HyMT3Adapter()])
return TranslationPipeline(chat: chat, registry: registry, chunker: settings.chunker)
}
/// Warms the selected model with fixed synthetic text. Only for a loopback endpoint.
public static func warmUp(settings: AppSettings) async throws {
guard settings.warmUpOnLaunch, EndpointPolicy.isLoopback(settings.endpoint) else { return }
let http = try OllamaHTTPClient(
baseURL: settings.endpoint,
allowRemote: settings.allowRemoteEndpoint
)
let chat = OllamaChatClient(http: http)
let request = HyMT3Adapter().warmUpRequest(
model: settings.model,
keepAlive: settings.keepModelLoaded
)
try await OllamaWarmUpRunner(chat: chat).run(request)
}
}
@@ -0,0 +1,319 @@
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
/// 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
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)
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
}
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
)
)
}
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, launchAtLogin
case keepRecentTranslationInMemory, hasCompletedOnboarding, 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
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
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(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)
}
}
@@ -0,0 +1,55 @@
import Foundation
/// One in-memory diagnostic entry. It never contains selected text or a translation.
public struct DiagnosticEvent: Sendable, Equatable, Codable {
/// When the event happened.
public let timestamp: Date
/// A short kind such as `translation`, `error` or `capture`.
public let kind: String
/// A duration in milliseconds, when relevant.
public let durationMs: Int?
/// A non-text detail such as a warning code or error kind.
public let detail: String?
/// Creates an event.
public init(timestamp: Date, kind: String, durationMs: Int? = nil, detail: String? = nil) {
self.timestamp = timestamp
self.kind = kind
self.durationMs = durationMs
self.detail = detail
}
}
/// A bounded in-memory diagnostics log (`docs/ARCHITECTURE.md` §15).
public actor DiagnosticsStore {
/// The maximum number of retained events.
public static let capacity = 50
private var events: [DiagnosticEvent] = []
private let clock: @Sendable () -> Date
/// Creates a store.
public init(clock: @escaping @Sendable () -> Date = { Date() }) {
self.clock = clock
}
/// Records one non-text event, dropping the oldest beyond the capacity.
public func record(kind: String, durationMs: Int? = nil, detail: String? = nil) {
events.append(
DiagnosticEvent(timestamp: clock(), kind: kind, durationMs: durationMs, detail: detail)
)
if events.count > Self.capacity {
events.removeFirst(events.count - Self.capacity)
}
}
/// The current events, oldest first.
public func snapshot() -> [DiagnosticEvent] {
events
}
/// Clears the in-memory list.
public func clear() {
events.removeAll()
}
}
@@ -0,0 +1,76 @@
import Foundation
import Observation
import SprachmittlerEngines
import SprachmittlerOllama
/// The diagnostics window model. It formats versions, digests, timings and error kinds only.
@MainActor
@Observable
public final class DiagnosticsViewModel {
/// The last events, oldest first.
public private(set) var events: [DiagnosticEvent] = []
/// The Ollama version.
public private(set) var serverVersion: String?
/// The installed Hy-MT3 models.
public private(set) var models: [InstalledModel] = []
/// A short error when the refresh failed.
public private(set) var error: String?
/// True while refreshing.
public private(set) var isRefreshing = false
private let store: DiagnosticsStore
private let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog
private let settingsProvider: @Sendable () -> AppSettings
/// Creates the diagnostics model.
public init(
store: DiagnosticsStore,
catalogProvider: @escaping @Sendable (AppSettings) throws -> any OllamaCatalog,
settingsProvider: @escaping @Sendable () -> AppSettings
) {
self.store = store
self.catalogProvider = catalogProvider
self.settingsProvider = settingsProvider
}
/// Reloads events and, when possible, server/model details.
public func refresh() async {
isRefreshing = true
defer { isRefreshing = false }
events = await store.snapshot()
do {
let catalog = try catalogProvider(settingsProvider())
serverVersion = try await catalog.serverVersion()
models = try await catalog.installedModels()
.filter { HyMT3ModelPreset.isHyMT3($0.name) }
error = nil
} catch let rejection as EndpointRejection {
self.error = SprachmittlerError.endpointRejected(reason: rejection).userMessage
} catch {
self.error = "Ollama details are unavailable."
}
}
/// Clears the in-memory event list.
public func clear() async {
await store.clear()
events = []
}
/// A text-only report for the clipboard; no source text or translation is included.
public func report() -> String {
var lines = [
"Sprachmittler diagnostics",
"Ollama: \(serverVersion ?? "unknown")",
"Endpoint: \(settingsProvider().endpoint.absoluteString)",
"Models: \(models.map { "\($0.name) [\($0.digest.prefix(12))]" }.joined(separator: ", "))",
]
for event in events {
let duration = event.durationMs.map { " \($0) ms" } ?? ""
let detail = event.detail.map { " [\($0)]" } ?? ""
lines.append("\(event.kind)\(duration)\(detail)")
}
return lines.joined(separator: "\n")
}
}
@@ -6,3 +6,6 @@ public typealias LanguageCode = String
/// The UI-facing name for a target language. The value type lives in `SprachmittlerEngines` because
/// it carries the exact model-card name used by prompts (ADR-014, ADR-017).
public typealias TargetLanguage = SprachmittlerEngines.ModelLanguage
/// The language value type, re-exported for app views.
public typealias ModelLanguage = SprachmittlerEngines.ModelLanguage
@@ -0,0 +1,19 @@
import SprachmittlerEngines
/// The app-facing language catalogue. It re-exports the model-name data owned by Engines.
public enum LanguageCatalogue {
/// All 102 supported languages.
public static var all: [ModelLanguage] {
HyMT3Languages.all
}
/// The common first-run list.
public static var common: [ModelLanguage] {
HyMT3Languages.common
}
/// Resolves a BCP-47 code.
public static func resolve(_ code: String) -> ModelLanguage? {
HyMT3Languages.resolve(code)
}
}
@@ -0,0 +1,135 @@
import Foundation
import Observation
import SprachmittlerEngines
import SprachmittlerOllama
/// One onboarding check.
public enum OnboardingCheck: Sendable, Equatable {
/// Not checked yet.
case idle
/// A check is running.
case checking
/// The check passed; the value is a short detail.
case ok(String)
/// The check failed; the value is a user-facing message.
case failed(String)
}
/// First-run onboarding state and actions (`docs/IMPLEMENTATION_PLAN.md` T6.2).
@MainActor
@Observable
public final class OnboardingViewModel {
/// Ollama reachability and version.
public private(set) var ollama: OnboardingCheck = .idle
/// Hy-MT3 installation.
public private(set) var model: OnboardingCheck = .idle
/// Accessibility trust (optional, for Replace).
public private(set) var accessibilityTrusted = false
/// The selected target.
public private(set) var target: ModelLanguage
/// The installed Hy-MT3 tags.
public private(set) var installedModels: [String] = []
/// True while any check is running.
public private(set) var isChecking = false
private let settingsStore: SettingsStore
private let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog
private let accessibility: any AccessibilityPermissionChecking
/// Creates the onboarding model.
public init(
settingsStore: SettingsStore,
catalogProvider: @escaping @Sendable (AppSettings) throws -> any OllamaCatalog,
accessibility: any AccessibilityPermissionChecking
) {
self.settingsStore = settingsStore
self.catalogProvider = catalogProvider
self.accessibility = accessibility
let settings = settingsStore.current()
target = settings.targetLanguageModel
accessibilityTrusted = accessibility.isTrusted
}
/// The command shown when the model is missing.
public var pullCommand: String {
"ollama pull \(settingsStore.current().model)"
}
/// True when the essential checks passed; the app can be used.
public var canFinish: Bool {
if case .ok = ollama, case .ok = model {
return true
}
return false
}
/// Runs all checks.
public func refresh() async {
isChecking = true
ollama = .checking
model = .checking
accessibilityTrusted = accessibility.isTrusted
do {
let settings = settingsStore.current()
let catalog = try catalogProvider(settings)
let version = try await catalog.serverVersion()
ollama = .ok(version)
let models = try await catalog.installedModels()
let tags = models.map(\.name).filter { HyMT3ModelPreset.isHyMT3($0) }
installedModels = tags
if tags.isEmpty {
model = .failed(SprachmittlerError.modelNotInstalled(model: settings.model).userMessage)
} else {
if !tags.contains(settings.model), let first = tags.first {
try? settingsStore.update { $0.model = first }
}
model = .ok(tags.joined(separator: ", "))
}
} catch let error as OllamaError {
let domain = SprachmittlerError(ollama: error)
ollama = .failed(domain.userMessage)
model = .failed(domain.userMessage)
} catch let error as SprachmittlerError {
ollama = .failed(error.userMessage)
model = .failed(error.userMessage)
} catch let rejection as EndpointRejection {
let message = SprachmittlerError.endpointRejected(reason: rejection).userMessage
ollama = .failed(message)
model = .failed(message)
} catch {
let message = "Ollama could not be reached."
ollama = .failed(message)
model = .failed(message)
}
isChecking = false
}
/// Saves the chosen target.
public func saveTarget() throws {
try settingsStore.update { $0.noteTarget(target) }
}
/// Sets the target; the caller saves.
public func setTarget(_ language: ModelLanguage) {
target = language
}
/// Requests Accessibility trust. Only call from onboarding.
public func requestAccessibility() {
accessibility.requestTrust()
accessibilityTrusted = accessibility.isTrusted
}
/// Opens the Accessibility settings page.
public func openAccessibilitySettings() {
accessibility.openSettings()
}
/// Marks onboarding complete after a successful setup.
public func complete() throws {
try saveTarget()
try settingsStore.update { $0.hasCompletedOnboarding = true }
}
}
@@ -0,0 +1,331 @@
import Foundation
import Observation
import SprachmittlerEngines
/// The panel phase from `docs/ARCHITECTURE.md` §10.
public enum PanelPhase: Sendable, Equatable {
/// Nothing captured.
case idle
/// A request is queued or running.
case translating
/// Deltas are arriving.
case streaming
/// A validated translation is ready.
case ready
/// The request failed.
case failed
}
/// The settings snapshot used by the panel for one translation.
public struct PanelConfiguration: Sendable, Equatable {
/// The selected target language.
public var target: ModelLanguage
/// The selected model tag.
public var model: String
/// The Ollama keep-alive value.
public var keepAlive: String
/// The sampling values.
public var sampling: SamplingOptions
/// Whether to show the source preview.
public var showSourcePreview: Bool
/// Recent targets, most recent first.
public var recentTargets: [ModelLanguage]
/// Creates a configuration.
public init(
target: ModelLanguage,
model: String,
keepAlive: String,
sampling: SamplingOptions = .publisherDefault,
showSourcePreview: Bool = true,
recentTargets: [ModelLanguage] = []
) {
self.target = target
self.model = model
self.keepAlive = keepAlive
self.sampling = sampling
self.showSourcePreview = showSourcePreview
self.recentTargets = recentTargets
}
}
/// The panel presentation model. It mirrors `TranslationSession` and owns no disk state.
@MainActor
@Observable
public final class PanelViewModel {
/// The current phase.
public private(set) var phase: PanelPhase = .idle
/// The captured source.
public private(set) var source: CapturedText?
/// The streamed and final translation.
public private(set) var translation = ""
/// Validation warnings for the current result.
public private(set) var warnings: [TranslationWarning] = []
/// The current error, if any.
public private(set) var error: SprachmittlerError?
/// The last timing.
public private(set) var timing: TranslationTiming?
/// The advisory source language code.
public private(set) var sourceLanguage: String?
/// True after a successful Copy.
public private(set) var didCopy = false
/// True while a Replace action is running.
public private(set) var isReplacing = false
/// The current target, model and prompt settings.
public private(set) var configuration: PanelConfiguration
/// True after the user dismisses the same-language advisory.
public private(set) var sameLanguageDismissed = false
/// The copy action. The composition root writes with own-write markers.
public let copy: @MainActor (String) -> Void
/// The optional Replace action; nil until the insertion module is available.
public let replace: (@MainActor () async -> InsertionOutcome)?
/// Called when a successful Replace should close the panel.
public let onCloseRequest: @MainActor () -> Void
/// Called with every session event for diagnostics.
public let eventObserver: (@MainActor (TranslationSessionEvent) -> Void)?
/// Called when the user changes the target from the panel.
public let onTargetChanged: @MainActor (ModelLanguage) -> Void
private let session: TranslationSession
private var eventTask: Task<Void, Never>?
private var currentEpoch: UInt64 = 0
private var lastCaptured: CapturedText?
/// Creates a panel model.
public init(
session: TranslationSession,
configuration: PanelConfiguration,
copy: @escaping @MainActor (String) -> Void,
replace: (@MainActor () async -> InsertionOutcome)? = nil,
onCloseRequest: @escaping @MainActor () -> Void = {},
eventObserver: (@MainActor (TranslationSessionEvent) -> Void)? = nil,
onTargetChanged: @escaping @MainActor (ModelLanguage) -> Void = { _ in }
) {
self.session = session
self.configuration = configuration
self.copy = copy
self.replace = replace
self.onCloseRequest = onCloseRequest
self.eventObserver = eventObserver
self.onTargetChanged = onTargetChanged
}
/// Starts consuming session events. Call once after init.
public func startObserving() {
guard eventTask == nil else { return }
let session = session
eventTask = Task { [weak self] in
for await event in await session.events() {
guard let self else { return }
handle(event)
}
}
}
/// True when Copy can write the current translation.
public var canCopy: Bool {
!translation.isEmpty && (phase == .ready || phase == .failed)
}
/// True when Replace is safe and the insertion module is available.
public var canReplace: Bool {
phase == .ready
&& !isReplacing
&& !warnings.contains(where: \.blocksReplacement)
&& replace != nil
}
/// The replacement is unavailable until M5 in this build.
public var replaceUnavailableReason: String? {
replace == nil ? "Replace is not available." : nil
}
/// Warnings that disable Replace.
public var blockingWarnings: [TranslationWarning] {
warnings.filter(\.blocksReplacement)
}
/// The same-language advisory, if present and not dismissed.
public var sameLanguageWarning: TranslationWarning? {
guard !sameLanguageDismissed else { return nil }
return warnings.first { warning in
if case .sameLanguage = warning {
true
} else {
false
}
}
}
/// The user-facing error message.
public var errorMessage: String? {
error?.userMessage
}
/// The error's recovery action.
public var recoveryAction: RecoveryAction? {
error?.recoveryAction
}
/// Synchronously resets the visible state before the panel is shown.
public func prepare(_ captured: CapturedText) {
currentEpoch = 0
lastCaptured = captured
source = captured
translation = ""
warnings = []
error = nil
timing = nil
sourceLanguage = nil
didCopy = false
isReplacing = false
sameLanguageDismissed = false
phase = .translating
}
/// Starts a translation for a captured text.
public func begin(_ captured: CapturedText) async {
prepare(captured)
_ = await session.start(request(for: captured))
}
/// Retries the last captured text.
public func retry() async {
guard let lastCaptured else { return }
await begin(lastCaptured)
}
/// Retranslates after an external target change.
public func retranslate() async {
guard let lastCaptured else { return }
await begin(lastCaptured)
}
/// Shows a capture-time error such as a too-long selection.
public func showError(_ error: SprachmittlerError, source: CapturedText? = nil) {
currentEpoch = 0
Task { await session.reset() }
phase = .failed
self.error = error
self.source = source
translation = ""
warnings = []
timing = nil
sourceLanguage = nil
}
/// Changes the target and retranslates the current selection.
public func setTarget(_ language: ModelLanguage) async {
guard language.code != configuration.target.code else { return }
configuration.target = language
onTargetChanged(language)
if let lastCaptured {
await begin(lastCaptured)
}
}
/// Copies the translation and keeps the panel open (R023).
public func copyTranslation() {
guard canCopy else { return }
copy(translation)
didCopy = true
}
/// Runs the optional Replace action.
public func replaceSelection() async {
guard canReplace, let replace else { return }
isReplacing = true
let outcome = await replace()
isReplacing = false
switch outcome {
case .replaced:
onCloseRequest()
case .copiedOnly:
break
case let .failed(insertionError):
error = insertionError
phase = .failed
}
}
/// Dismisses the same-language advisory; translation stays available.
public func dismissSameLanguageWarning() {
sameLanguageDismissed = true
}
/// Updates the settings snapshot without restarting the current request.
public func updateConfiguration(_ configuration: PanelConfiguration) {
self.configuration = configuration
}
/// Resets the panel and cancels the active request. The event stream stays open.
public func close() async {
await session.reset()
phase = .idle
source = nil
translation = ""
warnings = []
error = nil
timing = nil
sourceLanguage = nil
didCopy = false
isReplacing = false
sameLanguageDismissed = false
lastCaptured = nil
}
/// Stops the event consumer for app termination.
public func shutdown() {
eventTask?.cancel()
eventTask = nil
}
private func request(for captured: CapturedText) -> TranslationSessionRequest {
TranslationSessionRequest(
captured: captured,
target: configuration.target,
model: configuration.model,
keepAlive: configuration.keepAlive,
sampling: configuration.sampling
)
}
private func handle(_ event: TranslationSessionEvent) {
switch event {
case let .started(epoch, request):
currentEpoch = epoch
source = request.captured
configuration.target = request.target
translation = ""
warnings = []
error = nil
phase = .translating
case let .delta(epoch, text):
guard epoch == currentEpoch else { return }
translation += text
phase = .streaming
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
case let .cancelled(epoch):
guard epoch == currentEpoch else { return }
phase = .idle
error = nil
}
eventObserver?(event)
}
}
@@ -0,0 +1,49 @@
import Foundation
/// UI-facing warning helpers re-exported by Core.
public extension TranslationWarning {
/// A short panel message. It never rewrites the translation.
var panelMessage: String {
switch self {
case let .preambleDetected(line):
String(localized: "The model added an explanation: “\(line)”")
case .truncated:
String(localized: "The translation was cut off.")
case .repetitionLoop:
String(localized: "The translation started repeating.")
case let .missingProtectedToken(token):
String(localized: "A protected token was lost: \(token)")
case .emptyOutput:
String(localized: "The model returned an empty translation.")
case let .sameLanguage(source, target):
String(localized: "This text already appears to be in \(target) (detected \(source)).")
case .numericMismatch:
String(localized: "A number may have changed.")
case let .chunkFailed(index):
String(localized: "Chunk \(index + 1) failed; the translation is incomplete.")
}
}
/// True when the warning should disable Replace by default.
/// The domain error that blocks Replace for this warning.
var insertionError: SprachmittlerError {
switch self {
case .truncated: .truncated
case .repetitionLoop: .repetitionLoop
case .preambleDetected: .preambleDetected
case let .missingProtectedToken(token): .protectedTokenLost(token: token)
case .emptyOutput: .emptyOutput
case .chunkFailed: .server(status: 0, message: "Chunk failed")
case .sameLanguage, .numericMismatch: .cancelled
}
}
var isBlocking: Bool {
switch self {
case .preambleDetected, .truncated, .repetitionLoop, .missingProtectedToken, .emptyOutput, .chunkFailed:
true
case .sameLanguage, .numericMismatch:
false
}
}
}
@@ -0,0 +1,19 @@
/// Accessibility is optional and used only for Replace (SEE: docs/SELECTION_AND_CLIPBOARD.md).
@MainActor
public protocol AccessibilityPermissionChecking: AnyObject {
/// Whether the app is currently trusted for Accessibility.
var isTrusted: Bool { get }
/// Shows the system prompt. Call only from onboarding or an explicit Replace click.
func requestTrust()
/// Opens System Settings ▸ Privacy & Security ▸ Accessibility.
func openSettings()
}
/// The login-item seam; production uses `SMAppService.mainApp`.
@MainActor
public protocol LaunchAtLoginControlling: AnyObject {
/// The current system state.
var isEnabled: Bool { get }
/// Registers or unregisters the app.
func setEnabled(_ enabled: Bool) throws
}
@@ -0,0 +1,100 @@
import Foundation
/// The minimal persistence seam for settings. Production uses `UserDefaults`; tests use memory.
public protocol SettingsDataStoring: Sendable {
/// Returns the stored data, if any.
func data(forKey key: String) -> Data?
/// Stores or removes data.
func set(_ data: Data?, forKey key: String)
}
/// The production `UserDefaults` adapter. `UserDefaults` is thread-safe; the unchecked
/// conformance records that no additional mutable state lives here.
public final class UserDefaultsSettingsDataStore: SettingsDataStoring, @unchecked Sendable {
private let defaults: UserDefaults
/// Creates an adapter.
public init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
public func data(forKey key: String) -> Data? {
defaults.data(forKey: key)
}
public func set(_ data: Data?, forKey key: String) {
if let data {
defaults.set(data, forKey: key)
} else {
defaults.removeObject(forKey: key)
}
}
}
/// Loads, caches, migrates and saves `AppSettings` as one JSON blob.
///
/// `@unchecked Sendable` is safe: every cached value is guarded by `lock`, and the storage seam is
/// itself Sendable.
public final class SettingsStore: @unchecked Sendable {
/// The single defaults key; only configuration is stored here.
public static let storageKey = "com.schihei.sprachmittler.settings"
private let storage: any SettingsDataStoring
private let lock = NSLock()
private var cached: AppSettings?
/// Creates a store.
public init(storage: any SettingsDataStoring = UserDefaultsSettingsDataStore()) {
self.storage = storage
}
/// The current settings, loading and migrating once.
public func current() -> AppSettings {
lock.lock()
defer { lock.unlock() }
if let cached {
return cached
}
let settings = loadLocked()
cached = settings
return settings
}
/// Saves settings and updates the cache.
public func save(_ settings: AppSettings) throws {
let data = try JSONEncoder().encode(settings)
lock.lock()
storage.set(data, forKey: Self.storageKey)
cached = settings
lock.unlock()
}
/// Mutates and saves atomically.
public func update(_ transform: (inout AppSettings) -> Void) throws {
lock.lock()
defer { lock.unlock() }
var settings = cached ?? loadLocked()
transform(&settings)
let data = try JSONEncoder().encode(settings)
storage.set(data, forKey: Self.storageKey)
cached = settings
}
/// Deletes the stored blob and returns defaults.
@discardableResult
public func reset() -> AppSettings {
lock.lock()
storage.set(nil, forKey: Self.storageKey)
let settings = AppSettings()
cached = settings
lock.unlock()
return settings
}
private func loadLocked() -> AppSettings {
guard let data = storage.data(forKey: Self.storageKey) else {
return AppSettings()
}
return (try? JSONDecoder().decode(AppSettings.self, from: data)) ?? AppSettings()
}
}
@@ -0,0 +1,119 @@
import Foundation
import Observation
import SprachmittlerEngines
import SprachmittlerOllama
/// Settings presentation model. It never stores source text or translations.
@MainActor
@Observable
public final class SettingsViewModel {
/// The editable draft.
public var draft: AppSettings
/// A settings validation or save error.
public private(set) var saveError: String?
/// A launch-at-login error; the other settings still saved.
public private(set) var launchError: String?
/// Installed Hy-MT3 tags, loaded on demand.
public private(set) var installedModels: [InstalledModel] = []
/// True while refreshing the model list.
public private(set) var isRefreshingModels = false
private let store: SettingsStore
private let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog
private let launchAtLogin: any LaunchAtLoginControlling
/// Creates the settings model.
public init(
store: SettingsStore,
catalogProvider: @escaping @Sendable (AppSettings) throws -> any OllamaCatalog,
launchAtLogin: any LaunchAtLoginControlling
) {
self.store = store
self.catalogProvider = catalogProvider
self.launchAtLogin = launchAtLogin
draft = store.current()
draft.launchAtLogin = launchAtLogin.isEnabled
}
/// Reloads the draft from storage.
public func reload() {
draft = store.current()
draft.launchAtLogin = launchAtLogin.isEnabled
saveError = nil
}
/// Validates and saves the draft. The remote endpoint policy is enforced here.
public func save() {
draft.sanitize()
saveError = nil
launchError = nil
do {
_ = try draft.validatedEndpoint()
try store.save(draft)
} catch let rejection as EndpointRejection {
saveError = SprachmittlerError.endpointRejected(reason: rejection).userMessage
return
} catch {
saveError = "Settings could not be saved."
return
}
do {
try launchAtLogin.setEnabled(draft.launchAtLogin)
} catch {
launchError = "Launch at login could not be changed."
}
}
/// Resets stored settings and the login item.
public func reset() {
draft = store.reset()
try? launchAtLogin.setEnabled(false)
saveError = nil
launchError = nil
}
/// Refreshes the installed model list using the draft endpoint.
public func refreshModels() async {
isRefreshingModels = true
defer { isRefreshingModels = false }
do {
let catalog = try catalogProvider(draft)
installedModels = try await catalog.installedModels()
.filter { HyMT3ModelPreset.isHyMT3($0.name) }
saveError = nil
} catch let rejection as EndpointRejection {
saveError = SprachmittlerError.endpointRejected(reason: rejection).userMessage
} catch let error as OllamaError {
saveError = SprachmittlerError(ollama: error).userMessage
} catch let error as SprachmittlerError {
saveError = error.userMessage
} catch {
saveError = "Models could not be loaded."
}
}
/// The model tags offered to the picker, including the current values.
public var modelChoices: [String] {
var tags = Set(installedModels.map(\.name))
tags.insert(draft.model)
if let fast = draft.fastModel {
tags.insert(fast)
}
return tags.sorted()
}
/// The licence text from the model card, not the Ollama field.
public var licenceNote: String {
"Hy-MT3 is Apache-2.0 per the model card. Sprachmittler bundles no weights."
}
/// The selected model digest, when installed.
public var selectedDigest: String? {
installedModels.first { $0.name == draft.model }?.digest
}
/// The installed Fast model candidate, if any.
public var detectedFastModel: String? {
installedModels.first { HyMT3ModelPreset.isFastModel($0.name) }?.name
}
}
@@ -0,0 +1,139 @@
import Foundation
import SprachmittlerOllama
/// A user-facing recovery action. The UI never shows a raw `localizedDescription`.
public enum RecoveryAction: Sendable, Equatable {
/// Start Ollama.
case startOllama
/// Copy and run `ollama pull <model>`.
case pullModel(String)
/// Open the relevant System Settings page.
case openSettings
/// Copy the translation instead.
case copyInstead
/// Shorten the selection.
case shortenText
/// Retry the translation.
case retry
/// Nothing to do.
case none
}
public extension SprachmittlerError {
/// A short, non-technical message for the panel and onboarding.
var userMessage: String {
switch self {
case .noSelection:
"No text was selected."
case .emptyText:
"No text was copied."
case let .textTooLong(_, limit):
"This selection is too long (limit \(limit) characters)."
case .pasteboardUnavailable:
"The clipboard is unavailable."
case .ollamaUnreachable:
"Ollama is not running."
case let .ollamaTooOld(_, required):
"Ollama is too old. Version \(required) or newer is required."
case let .endpointRejected(reason):
"The endpoint is not allowed: \(reason.userMessage)"
case .modelNotInstalled:
"The Hy-MT3 model is not installed."
case .noAdapter:
"This model is not supported."
case .badRequest:
"Ollama rejected the request."
case .server:
"Ollama returned an error."
case .timeout:
"Ollama took too long to answer."
case .emptyOutput:
"The model returned an empty translation."
case .truncated:
"The translation was cut off."
case .repetitionLoop:
"The translation started repeating."
case .preambleDetected:
"The model added an explanation."
case .protectedTokenLost:
"A URL, placeholder or code token was lost."
case .accessibilityNotTrusted:
"Replace needs the Accessibility permission."
case .accessibilityUnsupported:
"This app did not accept the replacement."
case .insertionTargetChanged:
"The selection changed before Replace."
case .pasteboardRestoreFailed:
"The previous clipboard could not be restored."
case .cancelled:
"Translation cancelled."
}
}
/// A stable non-text code for diagnostics.
var diagnosticCode: String {
switch self {
case .noSelection: "noSelection"
case .emptyText: "emptyText"
case .textTooLong: "textTooLong"
case .pasteboardUnavailable: "pasteboardUnavailable"
case .ollamaUnreachable: "ollamaUnreachable"
case .ollamaTooOld: "ollamaTooOld"
case .endpointRejected: "endpointRejected"
case .modelNotInstalled: "modelNotInstalled"
case .noAdapter: "noAdapter"
case .badRequest: "badRequest"
case .server: "server"
case .timeout: "timeout"
case .emptyOutput: "emptyOutput"
case .truncated: "truncated"
case .repetitionLoop: "repetitionLoop"
case .preambleDetected: "preambleDetected"
case .protectedTokenLost: "protectedTokenLost"
case .accessibilityNotTrusted: "accessibilityNotTrusted"
case .accessibilityUnsupported: "accessibilityUnsupported"
case .insertionTargetChanged: "insertionTargetChanged"
case .pasteboardRestoreFailed: "pasteboardRestoreFailed"
case .cancelled: "cancelled"
}
}
/// The primary recovery action, if any.
var recoveryAction: RecoveryAction {
switch self {
case .ollamaUnreachable:
.startOllama
case let .modelNotInstalled(model):
.pullModel(model)
case .ollamaTooOld, .endpointRejected:
.openSettings
case .textTooLong:
.shortenText
case .accessibilityNotTrusted:
.openSettings
case .accessibilityUnsupported, .insertionTargetChanged, .pasteboardRestoreFailed:
.copyInstead
case .timeout, .server, .emptyOutput, .truncated, .repetitionLoop, .preambleDetected:
.retry
default:
.none
}
}
}
private extension EndpointRejection {
var userMessage: String {
switch self {
case .scheme:
"only http and https are supported"
case .form:
"it must not contain credentials, a query or a fragment"
case .remoteNotAllowed:
"remote endpoints are disabled"
case .remoteRequiresHTTPS:
"remote endpoints require HTTPS"
case .redirect:
"redirects are refused"
}
}
}
@@ -0,0 +1,52 @@
import Foundation
/// A text replacement implementation. Accessibility direct replacement is preferred; the paste
/// fallback is the second strategy (`docs/SELECTION_AND_CLIPBOARD.md` §4).
public protocol TextInserting: Sendable {
/// Replaces the captured selection with `translation`.
func replace(
selection: CapturedText,
with translation: String,
target: InsertionTarget
) async throws -> InsertionOutcome
}
/// Captures the source app and, when Accessibility is trusted, the focused selection at trigger
/// time. Never reads a full document value.
@MainActor
public protocol InsertionTargetProviding {
/// Returns the target, or nil when no app is frontmost.
func captureTarget() -> InsertionTarget?
}
/// The safety checks shared by AX and paste insertion.
public enum InsertionPolicy {
/// Verifies the frontmost app and, when available, the selected text.
public static func verify(
frontmostPID: pid_t,
target: InsertionTarget,
selectedText: String?,
source: String
) throws {
guard frontmostPID == target.pid else {
throw SprachmittlerError.insertionTargetChanged
}
guard let selectedText else { return }
let expected = selectedText
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
.trimmingCharacters(in: .whitespacesAndNewlines)
let actual = source
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
.trimmingCharacters(in: .whitespacesAndNewlines)
guard expected == actual else {
throw SprachmittlerError.insertionTargetChanged
}
}
/// True when the text should not be replaced because a blocking warning exists.
public static func isBlocked(by warnings: [TranslationWarning]) -> Bool {
warnings.contains(where: \.blocksReplacement)
}
}
@@ -92,7 +92,9 @@ public struct TranslationPipeline: Sendable {
text: String,
target: ModelLanguage,
model: String,
keepAlive: String
keepAlive: String,
sampling: SamplingOptions = .publisherDefault,
onDelta: (@Sendable (String) async -> Void)? = nil
) async throws -> PipelineResult {
let normalized = TextNormalization.normalizeInput(text)
guard !normalized.isEmpty else {
@@ -112,7 +114,9 @@ public struct TranslationPipeline: Sendable {
target: target,
model: model,
keepAlive: keepAlive,
tokens: tokens
sampling: sampling,
tokens: tokens,
onDelta: onDelta
)
let accumulator = try await translateAll(chunks, context: context)
@@ -150,7 +154,9 @@ public struct TranslationPipeline: Sendable {
let target: ModelLanguage
let model: String
let keepAlive: String
let sampling: SamplingOptions
let tokens: [ProtectedToken]
let onDelta: (@Sendable (String) async -> Void)?
}
private struct Accumulator {
@@ -180,6 +186,9 @@ public struct TranslationPipeline: Sendable {
accumulator.sawLength = true
}
accumulator.joined += result.text + chunk.separatorAfter
if !chunk.separatorAfter.isEmpty {
await context.onDelta?(chunk.separatorAfter)
}
}
} catch is CancellationError {
throw SprachmittlerError.cancelled
@@ -214,16 +223,10 @@ public struct TranslationPipeline: Sendable {
var outputTokens: Int?
while true {
let request = try registry.makeRequest(
AdapterRequest(
text: chunk.text,
target: context.target,
model: context.model,
keepAlive: context.keepAlive,
prompt: prompt
)
)
let attempt = try await stream(request)
let request = try makeRequest(chunk: chunk, prompt: prompt, context: context)
// A retry replaces the first attempt; do not stream both into the panel.
let deltaHandler = retried ? nil : context.onDelta
let attempt = try await stream(request, onDelta: deltaHandler)
response = attempt
promptTokens = sum(promptTokens, attempt.metrics.promptEvalCount)
outputTokens = sum(outputTokens, attempt.metrics.evalCount)
@@ -255,6 +258,23 @@ public struct TranslationPipeline: Sendable {
)
}
private func makeRequest(
chunk: TextChunk,
prompt: PromptVariant,
context: TranslationContext
) throws -> ChatRequest {
try registry.makeRequest(
AdapterRequest(
text: chunk.text,
target: context.target,
model: context.model,
keepAlive: context.keepAlive,
prompt: prompt,
sampling: context.sampling
)
)
}
private struct StreamResult {
let text: String
let doneReason: String?
@@ -263,7 +283,10 @@ public struct TranslationPipeline: Sendable {
let looped: Bool
}
private func stream(_ request: ChatRequest) async throws -> StreamResult {
private func stream(
_ request: ChatRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> StreamResult {
var text = ""
var doneReason: String?
var metrics = ChatMetrics.empty
@@ -280,6 +303,7 @@ public struct TranslationPipeline: Sendable {
firstTokenAt = clock()
}
text += delta
await onDelta?(delta)
if repetition.append(delta) {
looped = true
}
@@ -0,0 +1,191 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
/// The streaming translation seam used by `TranslationSession`. The production implementation is
/// `TranslationPipeline`; tests provide a controlled fake.
public protocol TranslationStreaming: Sendable {
/// Translates one captured selection, optionally forwarding deltas.
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult
}
extension TranslationPipeline: TranslationStreaming {}
public extension TranslationPipeline {
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) 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
)
}
}
/// One translation request, including the settings snapshot it was built from.
public struct TranslationSessionRequest: Sendable, Equatable {
/// The captured text.
public let captured: CapturedText
/// The target language.
public let target: ModelLanguage
/// The installed model tag.
public let model: String
/// The Ollama keep-alive value.
public let keepAlive: String
/// The sampling values.
public let sampling: SamplingOptions
/// Creates a request.
public init(
captured: CapturedText,
target: ModelLanguage,
model: String,
keepAlive: String,
sampling: SamplingOptions = .publisherDefault
) {
self.captured = captured
self.target = target
self.model = model
self.keepAlive = keepAlive
self.sampling = sampling
}
}
/// An event from the translation session. The epoch lets the panel drop stale events.
public enum TranslationSessionEvent: Sendable, Equatable {
/// A request started.
case started(epoch: UInt64, request: TranslationSessionRequest)
/// One streamed delta.
case delta(epoch: UInt64, text: String)
/// The final validated result.
case finished(epoch: UInt64, result: PipelineResult)
/// A domain error.
case failed(epoch: UInt64, error: SprachmittlerError)
/// The request was cancelled or replaced.
case cancelled(epoch: UInt64)
}
/// The only translation actor: one request in flight, epochs discard stale events (ADR-015).
public actor TranslationSession {
private let pipelineFactory: @Sendable () throws -> any TranslationStreaming
private let eventsStream: AsyncStream<TranslationSessionEvent>
private let continuation: AsyncStream<TranslationSessionEvent>.Continuation
private var epoch: UInt64 = 0
private var task: Task<Void, Never>?
/// Creates a session. The factory reads a settings snapshot and builds a pipeline.
public init(pipelineFactory: @escaping @Sendable () throws -> any TranslationStreaming) {
self.pipelineFactory = pipelineFactory
let pair = AsyncStream<TranslationSessionEvent>.makeStream()
eventsStream = pair.stream
continuation = pair.continuation
}
/// The event stream. It has one consumer, normally `PanelViewModel`.
public func events() -> AsyncStream<TranslationSessionEvent> {
eventsStream
}
/// Starts a request, cancelling any active one, and returns its epoch.
@discardableResult
public func start(_ request: TranslationSessionRequest) -> UInt64 {
task?.cancel()
epoch &+= 1
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))
)
return currentEpoch
}
task = Task { [pipelineFactory] in
do {
let pipeline = try pipelineFactory()
let result = try await pipeline.translate(
request,
onDelta: { delta in
await self.forwardDelta(epoch: currentEpoch, text: delta)
}
)
self.finish(epoch: currentEpoch, result: result)
} catch let error as SprachmittlerError {
if error == .cancelled {
self.cancelEvent(epoch: currentEpoch)
} else {
self.fail(epoch: currentEpoch, error: error)
}
} catch let error as OllamaError {
self.fail(epoch: currentEpoch, error: SprachmittlerError(ollama: error))
} catch let rejection as EndpointRejection {
self.fail(
epoch: currentEpoch,
error: .endpointRejected(reason: rejection)
)
} catch is CancellationError {
self.cancelEvent(epoch: currentEpoch)
} catch {
self.fail(
epoch: currentEpoch,
error: .server(status: 0, message: "Translation failed")
)
}
}
return currentEpoch
}
/// Cancels the active request and emits a cancellation for its epoch.
public func cancel() {
let previous = epoch
epoch &+= 1
task?.cancel()
task = nil
continuation.yield(.cancelled(epoch: previous))
}
/// Cancels without emitting. Use when the panel closes.
public func reset() {
epoch &+= 1
task?.cancel()
task = nil
}
private func forwardDelta(epoch eventEpoch: UInt64, text: String) {
guard eventEpoch == epoch else { return }
continuation.yield(.delta(epoch: eventEpoch, text: text))
}
private func finish(epoch eventEpoch: UInt64, result: PipelineResult) {
guard eventEpoch == epoch else { return }
task = nil
continuation.yield(.finished(epoch: eventEpoch, result: result))
}
private func fail(epoch eventEpoch: UInt64, error: SprachmittlerError) {
guard eventEpoch == epoch else { return }
task = nil
continuation.yield(.failed(epoch: eventEpoch, error: error))
}
private func cancelEvent(epoch eventEpoch: UInt64) {
guard eventEpoch == epoch else { return }
task = nil
continuation.yield(.cancelled(epoch: eventEpoch))
}
}