From a78572adc3caa14b5c5a4c63ecc3b687d593493e Mon Sep 17 00:00:00 2001 From: Heiko Joerg Schick Date: Thu, 26 Nov 2026 14:03:05 +0100 Subject: [PATCH] feat(m4-m6): session, panel, Replace, settings and onboarding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- App/AppDelegate.swift | 96 ++++- App/AppEnvironment.swift | 369 +++++++++++++++++- App/Diagnostics/DiagnosticsView.swift | 95 +++++ App/LaunchAtLoginController.swift | 21 + App/MenuBar/StatusMenuState.swift | 8 + App/MenuBar/StatusMenuView.swift | 68 ++++ App/Onboarding/OnboardingView.swift | 231 +++++++++++ App/Panel/LanguagePickerView.swift | 55 +++ App/Panel/PanelController.swift | 75 ++++ App/Panel/PanelView.swift | 300 ++++++++++++++ App/Settings/SettingsView.swift | 291 ++++++++++++++ App/SprachmittlerApp.swift | 30 +- .../SprachmittlerCapture/AXTextEditor.swift | 99 +++++ .../AccessibilityPermission.swift | 27 ++ .../FrontmostTargetProvider.swift | 20 + .../InsertionCoordinator.swift | 110 ++++++ .../PasteboardAccessing.swift | 2 +- .../Sources/SprachmittlerCore/AppOllama.swift | 44 +++ .../SprachmittlerCore/AppSettings.swift | 319 +++++++++++++++ .../SprachmittlerCore/DiagnosticsStore.swift | 55 +++ .../DiagnosticsViewModel.swift | 76 ++++ .../SprachmittlerCore/LanguageAliases.swift | 3 + .../SprachmittlerCore/LanguageCatalogue.swift | 19 + .../OnboardingViewModel.swift | 135 +++++++ .../SprachmittlerCore/PanelViewModel.swift | 331 ++++++++++++++++ .../PanelWarningMessages.swift | 49 +++ .../PermissionProtocols.swift | 19 + .../SprachmittlerCore/SettingsStore.swift | 100 +++++ .../SprachmittlerCore/SettingsViewModel.swift | 119 ++++++ .../SprachmittlerErrorMessages.swift | 139 +++++++ .../SprachmittlerCore/TextInserting.swift | 52 +++ .../TranslationPipeline.swift | 50 ++- .../TranslationSession.swift | 191 +++++++++ .../HyMT3ModelPreset.swift | 5 + .../FakeSettingsAndPermissions.swift | 65 +++ .../InsertionCoordinatorTests.swift | 297 ++++++++++++++ .../AppSettingsTests.swift | 200 ++++++++++ .../ErrorMessageTests.swift | 62 +++ .../OnboardingAndSettingsTests.swift | 169 ++++++++ .../PanelViewModelTests.swift | 273 +++++++++++++ .../TranslationPipelineTests.swift | 50 +++ .../TranslationSessionTests.swift | 248 ++++++++++++ docs/ARCHITECTURE.md | 6 +- docs/DECISIONS.md | 14 + docs/PROGRESS.md | 50 ++- docs/SELECTION_AND_CLIPBOARD.md | 2 +- docs/TESTING.md | 3 + 47 files changed, 4963 insertions(+), 79 deletions(-) create mode 100644 App/Diagnostics/DiagnosticsView.swift create mode 100644 App/LaunchAtLoginController.swift create mode 100644 App/MenuBar/StatusMenuState.swift create mode 100644 App/MenuBar/StatusMenuView.swift create mode 100644 App/Onboarding/OnboardingView.swift create mode 100644 App/Panel/LanguagePickerView.swift create mode 100644 App/Panel/PanelController.swift create mode 100644 App/Panel/PanelView.swift create mode 100644 App/Settings/SettingsView.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AXTextEditor.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AccessibilityPermission.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCapture/FrontmostTargetProvider.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCapture/InsertionCoordinator.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppOllama.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsStore.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsViewModel.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageCatalogue.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/OnboardingViewModel.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelWarningMessages.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/PermissionProtocols.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsStore.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsViewModel.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/TextInserting.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift create mode 100644 Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeSettingsAndPermissions.swift create mode 100644 Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/InsertionCoordinatorTests.swift create mode 100644 Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift create mode 100644 Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMessageTests.swift create mode 100644 Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/OnboardingAndSettingsTests.swift create mode 100644 Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift create mode 100644 Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift diff --git a/App/AppDelegate.swift b/App/AppDelegate.swift index 26e8488..266d3ce 100644 --- a/App/AppDelegate.swift +++ b/App/AppDelegate.swift @@ -1,40 +1,112 @@ import AppKit +import Combine import os import SprachmittlerCore -/// Lifecycle glue: composition root, Services provider, double-copy watcher, termination. +/// Lifecycle glue: composition root, Services provider, watcher, panel and windows. @MainActor -final class AppDelegate: NSObject, NSApplicationDelegate { +final class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject { + let environment: AppEnvironment private let loggers = Loggers(subsystem: Bundle.main.bundleIdentifier ?? "Sprachmittler") - private var environment: AppEnvironment? + @Published private(set) var menuState = StatusMenuState( + targetCode: "", + hasTranslation: false, + canReplace: false + ) + + private lazy var onboardingWindow = OnboardingWindowController( + model: environment.onboarding, + onCopyCommand: { [weak self] text in self?.environment.copyText(text) }, + onFinished: { [weak self] in + self?.environment.settingsDidChange() + self?.refreshMenuState() + } + ) + + private lazy var diagnosticsWindow = DiagnosticsWindowController( + model: environment.diagnosticsModel, + onCopy: { [weak self] text in self?.environment.copyText(text) } + ) + + override init() { + environment = AppEnvironment() + super.init() + refreshMenuState() + } func applicationDidFinishLaunching(_ notification: Notification) { loggers.logger(.session).notice("Sprachmittler launched") - - let environment = AppEnvironment() - self.environment = environment + environment.onStateChange = { [weak self] in self?.refreshMenuState() } environment.start { [weak self] captured in self?.handle(captured) } - NSApp.servicesProvider = environment.servicesProvider NSUpdateDynamicServices() + + if !environment.settingsStore.current().hasCompletedOnboarding { + showOnboarding() + } } func applicationWillTerminate(_ notification: Notification) { - environment?.stop() - environment = nil + environment.stop() } - /// Menu-bar action: translate the current clipboard text. + /// Menu action: translate the current clipboard text. func captureClipboardText() { - environment?.captureClipboardText() + environment.captureClipboardText() + } + + /// Menu action: change the target language. + func selectTarget(_ language: TargetLanguage) { + environment.selectTarget(language) + refreshMenuState() + } + + /// Menu action: copy the last translation. + func copyLastTranslation() { + environment.copyLastTranslation() + } + + /// Menu action: replace the last selection with the last translation. + func replaceLastTranslation() { + environment.replaceLastTranslation() + } + + /// Menu action: open setup. + func showOnboarding() { + onboardingWindow.show() + } + + /// Menu action: open diagnostics. + func showDiagnostics() { + diagnosticsWindow.show() + } + + /// Menu action: About and licence notice. + func showAbout() { + NSApp.activate(ignoringOtherApps: true) + NSApp.orderFrontStandardAboutPanel(options: [ + .applicationName: "Sprachmittler", + .credits: NSAttributedString( + string: "Local translation with Hy-MT3. No text leaves this Mac.\n" + + "Hy-MT3 is Apache-2.0 per the model card; Sprachmittler bundles no weights." + ), + ]) } private func handle(_ captured: CapturedText) { - // The M4 session will replace this log-only sink. Log counts and source only. loggers.logger(.capture).notice( "Captured \(captured.text.count) characters from \(captured.source.rawValue, privacy: .public)" ) + refreshMenuState() + } + + private func refreshMenuState() { + menuState = StatusMenuState( + targetCode: environment.currentTarget.code, + hasTranslation: environment.lastTranslation != nil, + canReplace: environment.canReplaceLast + ) } } diff --git a/App/AppEnvironment.swift b/App/AppEnvironment.swift index 3048b26..13bce26 100644 --- a/App/AppEnvironment.swift +++ b/App/AppEnvironment.swift @@ -1,19 +1,34 @@ +import AppKit import Foundation import SprachmittlerCapture import SprachmittlerCore -/// The app composition root for capture. It owns the watcher, pasteboard and Services provider. +/// The app composition root: settings, Ollama clients, session, panel, capture and diagnostics. @MainActor final class AppEnvironment { + let settingsStore: SettingsStore let pasteboard: SystemPasteboard - let watcher: PasteboardWatcher + var watcher: PasteboardWatcher + let accessibility: AccessibilityPermission + let launchAtLogin: LaunchAtLoginController + let diagnostics: DiagnosticsStore + let targetProvider: FrontmostTargetProvider + let session: TranslationSession + let settingsModel: SettingsViewModel + let onboarding: OnboardingViewModel + let diagnosticsModel: DiagnosticsViewModel - private var onCapture: ((CapturedText) -> Void)? - - /// The most recent capture, kept in memory only for the M4 panel. private(set) var lastCaptured: CapturedText? - /// The most recent capture rejection, for the M4 panel and diagnostics. + private(set) var lastTranslation: String? + private(set) var lastWarnings: [TranslationWarning] = [] + private(set) var insertionTarget: InsertionTarget? + private var insertionTargetGeneration = 0 private(set) var lastCaptureFailure: CaptureValidation? + var onCapture: ((CapturedText) -> Void)? + var onStateChange: (() -> Void)? + + private var watcherEventSink: (@MainActor (PasteboardWatcherEvent) -> Void)? + private var watcherWindowMs: Int /// The Services provider, created lazily so it can capture `self` weakly. lazy var servicesProvider = ServicesProvider { [weak self] captured in @@ -22,25 +37,104 @@ final class AppEnvironment { } } - /// Creates the capture stack. + /// The insertion coordinator, created on first use. + lazy var insertionCoordinator = InsertionCoordinator( + pasteboard: pasteboard, + accessibility: AXTextEditor(), + ownWrite: { [weak self] in self?.watcher.noteOwnWrite(at: Date()) }, + frontmostPID: { NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0 } + ) + + /// The panel model, created on first use. + lazy var panelViewModel: PanelViewModel = { + let model = PanelViewModel( + session: session, + configuration: configuration(for: settingsStore.current()), + copy: { [weak self] text in + self?.copyToPasteboard(text, remember: self?.panelViewModel.translation == text) + }, + replace: { [weak self] in + guard let self else { return .failed(.cancelled) } + return await performReplace() + }, + onCloseRequest: { [weak self] in self?.panelController.close() }, + eventObserver: { [weak self] event in self?.observe(event) }, + onTargetChanged: { [weak self] language in self?.applyTarget(language) } + ) + model.startObserving() + return model + }() + + /// The panel window controller, created on first use. + lazy var panelController = PanelController(viewModel: panelViewModel) + + /// Creates the environment. init() { + let store = SettingsStore() let pasteboard = SystemPasteboard() + let access = AccessibilityPermission() + let launch = LaunchAtLoginController() + let diagnostics = DiagnosticsStore() + let windowMs = store.current().doubleCopyWindowMs + + settingsStore = store self.pasteboard = pasteboard - watcher = PasteboardWatcher(pasteboard: pasteboard) + accessibility = access + targetProvider = FrontmostTargetProvider() + launchAtLogin = launch + self.diagnostics = diagnostics + watcherWindowMs = windowMs + watcher = PasteboardWatcher( + pasteboard: pasteboard, + configuration: DoubleCopyDetector.Configuration( + window: Double(windowMs) / 1000 + ) + ) + + let factoryStore = store + session = TranslationSession(pipelineFactory: { + try AppOllama.makePipeline(settings: factoryStore.current()) + }) + + let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog = { settings in + try AppOllama.makeCatalog(settings: settings) + } + settingsModel = SettingsViewModel( + store: store, + catalogProvider: catalogProvider, + launchAtLogin: launch + ) + onboarding = OnboardingViewModel( + settingsStore: store, + catalogProvider: catalogProvider, + accessibility: access + ) + diagnosticsModel = DiagnosticsViewModel( + store: diagnostics, + catalogProvider: catalogProvider, + settingsProvider: { factoryStore.current() } + ) } - /// Starts the watcher and delivers every capture to `onCapture`. + /// Starts the watcher and optional warm-up. func start(onCapture: @escaping (CapturedText) -> Void) { self.onCapture = onCapture - watcher.start { [weak self] event in + let sink: @MainActor (PasteboardWatcherEvent) -> Void = { [weak self] event in self?.handle(event) } + watcherEventSink = sink + watcher.start(onEvent: sink) + warmUpIfNeeded() } - /// Stops the watcher and releases the in-memory text. + /// Stops the watcher, panel and event stream. func stop() { watcher.stop() + panelViewModel.shutdown() + Task { await panelViewModel.close() } lastCaptured = nil + lastTranslation = nil + lastWarnings = [] } /// Reads the clipboard once for the menu-bar item. @@ -54,24 +148,271 @@ final class AppEnvironment { deliver(CapturedText(text: text, capturedAt: Date(), source: .menu)) } + /// Copies arbitrary text with the app's own-write markers. + func copyText(_ text: String) { + copyToPasteboard(text, remember: false) + } + + /// Copies the last translation for the status menu. + func copyLastTranslation() { + guard let lastTranslation else { return } + copyToPasteboard(lastTranslation, remember: false) + } + + /// True when the last translation can safely be inserted. + var canReplaceLast: Bool { + lastTranslation != nil + && lastCaptured != nil + && insertionTarget != nil + && !InsertionPolicy.isBlocked(by: lastWarnings) + } + + /// Replaces the last selection from the status menu. + func replaceLastTranslation() { + guard let captured = lastCaptured, + let translation = lastTranslation, + let target = insertionTarget + else { + return + } + Task { + do { + _ = try await insertionCoordinator.replace( + selection: captured, + with: translation, + target: target + ) + } catch let error as SprachmittlerError { + showPanelError(error, source: captured) + } catch { + showPanelError(.server(status: 0, message: "Insertion failed"), source: captured) + } + } + } + + /// The current target code, for the status menu. + var currentTarget: ModelLanguage { + settingsStore.current().targetLanguageModel + } + + /// Changes the target from the status menu and retranslates the open panel. + func selectTarget(_ language: ModelLanguage) { + try? settingsStore.update { $0.noteTarget(language) } + applySettings() + } + + /// Called after Settings or Onboarding saves. Updates the panel and watcher. + func settingsDidChange() { + applySettings() + settingsModel.reload() + } + + private func configuration(for settings: AppSettings) -> PanelConfiguration { + PanelConfiguration( + target: settings.targetLanguageModel, + model: settings.model, + keepAlive: settings.keepModelLoaded, + sampling: settings.samplingOptions, + showSourcePreview: settings.showSourcePreview, + recentTargets: settings.recentTargets + ) + } + + private func applySettings() { + let settings = settingsStore.current() + let previousTarget = panelViewModel.configuration.target.code + panelViewModel.updateConfiguration(configuration(for: settings)) + if settings.doubleCopyWindowMs != watcherWindowMs { + watcherWindowMs = settings.doubleCopyWindowMs + restartWatcher() + } + let targetChanged = previousTarget != settings.targetLanguage && panelViewModel.source != nil + if targetChanged { + Task { await panelViewModel.retranslate() } + } + onStateChange?() + } + + private func applyTarget(_ language: ModelLanguage) { + try? settingsStore.update { $0.noteTarget(language) } + applySettings() + } + + private func restartWatcher() { + watcher.stop() + watcher = PasteboardWatcher( + pasteboard: pasteboard, + configuration: DoubleCopyDetector.Configuration( + window: Double(watcherWindowMs) / 1000 + ) + ) + if let sink = watcherEventSink { + watcher.start(onEvent: sink) + } + } + private func handle(_ event: PasteboardWatcherEvent) { switch event { case let .captured(captured): deliver(captured) - case .textTooLong, .noText, .ignoredOwnWrite: + case let .textTooLong(characters, limit): + let error = SprachmittlerError.textTooLong(characters: characters, limit: limit) + lastTranslation = nil + lastWarnings = [] + onStateChange?() + lastCaptureFailure = .textTooLong(characters: characters, limit: limit) + showPanelError(error) + case .noText, .ignoredOwnWrite: break } } private func deliver(_ captured: CapturedText) { + // A new capture invalidates the previous result for the status-menu actions. + lastTranslation = nil + lastWarnings = [] + onStateChange?() + switch CapturePolicy.validate(captured.text) { case .valid: lastCaptureFailure = nil - case let failure: - lastCaptureFailure = failure + case .empty: + lastCaptureFailure = .empty + return + case let .textTooLong(characters, limit): + lastCaptureFailure = .textTooLong(characters: characters, limit: limit) + showPanelError( + .textTooLong(characters: characters, limit: limit), + source: captured + ) return } + lastCaptured = captured + captureInsertionTarget() onCapture?(captured) + panelViewModel.updateConfiguration(configuration(for: settingsStore.current())) + panelViewModel.prepare(captured) + panelController.show() + Task { await panelViewModel.begin(captured) } + } +} + +extension AppEnvironment { + private func performReplace() async -> InsertionOutcome { + guard let captured = lastCaptured, + let target = insertionTarget, + !panelViewModel.translation.isEmpty + else { + return .failed(.insertionTargetChanged) + } + if let warning = panelViewModel.blockingWarnings.first { + return .failed(warning.insertionError) + } + do { + if let selected = target.selectedText { + let frontmost = NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0 + try InsertionPolicy.verify( + frontmostPID: frontmost, + target: target, + selectedText: selected, + source: captured.text + ) + } + return try await insertionCoordinator.replace( + selection: captured, + with: panelViewModel.translation, + target: target + ) + } catch let error as SprachmittlerError { + return .failed(error) + } catch is CancellationError { + return .failed(.cancelled) + } catch { + return .failed(.server(status: 0, message: "Insertion failed")) + } + } + + private func captureInsertionTarget() { + guard let base = targetProvider.captureTarget() else { + insertionTarget = nil + return + } + insertionTarget = base + Task { + let editor = AXTextEditor() + guard await editor.isTrusted(), + let selected = await editor.selectedText(pid: base.pid), + insertionTarget?.pid == base.pid + else { + return + } + insertionTarget = InsertionTarget( + pid: base.pid, + bundleID: base.bundleID, + selectedText: selected, + capturedAt: base.capturedAt + ) + } + } + + private func showPanelError(_ error: SprachmittlerError, source: CapturedText? = nil) { + panelViewModel.updateConfiguration(configuration(for: settingsStore.current())) + panelViewModel.showError(error, source: source) + panelController.show() + } + + private func copyToPasteboard(_ text: String, remember: Bool) { + pasteboard.write(text) + watcher.noteOwnWrite(at: Date()) + let shouldRemember = remember + && panelViewModel.phase == .ready + && settingsStore.current().keepRecentTranslationInMemory + if shouldRemember { + lastTranslation = text + } + onStateChange?() + } + + private func observe(_ event: TranslationSessionEvent) { + switch event { + case let .finished(_, result): + lastWarnings = result.warnings + if settingsStore.current().keepRecentTranslationInMemory { + lastTranslation = result.translation + } else { + lastTranslation = nil + } + let detail = result.warnings.map(\.code).joined(separator: ",") + let duration = result.timing.totalMs + Task { + await diagnostics.record( + kind: "translation", + durationMs: duration, + detail: detail.isEmpty ? nil : detail + ) + } + onStateChange?() + case let .failed(_, error): + Task { + await diagnostics.record(kind: "error", detail: error.diagnosticCode) + } + onStateChange?() + case .started, .delta, .cancelled: + break + } + } + + private func warmUpIfNeeded() { + let settings = settingsStore.current() + guard settings.warmUpOnLaunch else { return } + Task { + do { + try await AppOllama.warmUp(settings: settings) + await diagnostics.record(kind: "warmup") + } catch { + await diagnostics.record(kind: "warmupFailed", detail: "unavailable") + } + } } } diff --git a/App/Diagnostics/DiagnosticsView.swift b/App/Diagnostics/DiagnosticsView.swift new file mode 100644 index 0000000..b305740 --- /dev/null +++ b/App/Diagnostics/DiagnosticsView.swift @@ -0,0 +1,95 @@ +import AppKit +import SprachmittlerCore +import SwiftUI + +/// The diagnostics window. It shows no text, only versions, digests, timings and error kinds. +struct DiagnosticsView: View { + @Bindable var model: DiagnosticsViewModel + let onCopy: @MainActor (String) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + HStack { + Text(String(localized: "Diagnostics")) + .font(.title2.bold()) + Spacer() + Button(String(localized: "Refresh")) { + Task { await model.refresh() } + } + .disabled(model.isRefreshing) + Button(String(localized: "Copy report")) { + onCopy(model.report()) + } + Button(String(localized: "Clear")) { + Task { await model.clear() } + } + } + + GroupBox(String(localized: "Ollama")) { + VStack(alignment: .leading, spacing: 4) { + Text("Version: \(model.serverVersion ?? String(localized: "unknown"))") + Text( + "Models: " + + model.models.map { "\($0.name) [\($0.digest.prefix(12))]" } + .joined(separator: ", ") + ) + if let error = model.error { + Text(error).foregroundStyle(.red) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } + + Text(String(localized: "Last 50 events")) + .font(.headline) + List { + ForEach(Array(model.events.enumerated()), id: \.offset) { _, event in + HStack { + Text(event.kind) + Spacer() + if let duration = event.durationMs { + Text("\(duration) ms").foregroundStyle(.secondary) + } + if let detail = event.detail { + Text(detail).foregroundStyle(.secondary) + } + } + .font(.callout) + } + } + .frame(minHeight: 220) + } + .padding(20) + .frame(width: 620, height: 520) + .task { + await model.refresh() + } + } +} + +/// The diagnostics window controller. +@MainActor +final class DiagnosticsWindowController { + private let window: NSWindow + + init(model: DiagnosticsViewModel, onCopy: @escaping @MainActor (String) -> Void) { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 620, height: 520), + styleMask: [.titled, .closable, .resizable], + backing: .buffered, + defer: false + ) + self.window = window + window.title = String(localized: "Sprachmittler Diagnostics") + window.isReleasedWhenClosed = false + window.contentViewController = NSHostingController( + rootView: DiagnosticsView(model: model, onCopy: onCopy) + ) + window.center() + } + + func show() { + NSApp.activate(ignoringOtherApps: true) + window.makeKeyAndOrderFront(nil) + } +} diff --git a/App/LaunchAtLoginController.swift b/App/LaunchAtLoginController.swift new file mode 100644 index 0000000..b6a7112 --- /dev/null +++ b/App/LaunchAtLoginController.swift @@ -0,0 +1,21 @@ +import Foundation +import ServiceManagement +import SprachmittlerCore + +/// The production launch-at-login controller backed by `SMAppService.mainApp`. +@MainActor +final class LaunchAtLoginController: LaunchAtLoginControlling { + var isEnabled: Bool { + SMAppService.mainApp.status == .enabled + } + + func setEnabled(_ enabled: Bool) throws { + if enabled { + if SMAppService.mainApp.status != .enabled { + try SMAppService.mainApp.register() + } + } else if SMAppService.mainApp.status == .enabled { + try SMAppService.mainApp.unregister() + } + } +} diff --git a/App/MenuBar/StatusMenuState.swift b/App/MenuBar/StatusMenuState.swift new file mode 100644 index 0000000..469c0e5 --- /dev/null +++ b/App/MenuBar/StatusMenuState.swift @@ -0,0 +1,8 @@ +import Foundation + +/// The small observable state the status menu needs. +struct StatusMenuState: Equatable { + var targetCode: String + var hasTranslation: Bool + var canReplace: Bool +} diff --git a/App/MenuBar/StatusMenuView.swift b/App/MenuBar/StatusMenuView.swift new file mode 100644 index 0000000..c7386da --- /dev/null +++ b/App/MenuBar/StatusMenuView.swift @@ -0,0 +1,68 @@ +import AppKit +import SprachmittlerCore +import SwiftUI + +/// The menu-bar status menu. +struct StatusMenuView: View { + @ObservedObject var delegate: AppDelegate + + var body: some View { + Button(String(localized: "Translate Clipboard Text")) { + delegate.captureClipboardText() + } + + Menu(String(localized: "Target Language")) { + ForEach(LanguageCatalogue.common) { language in + Button { + delegate.selectTarget(language) + } label: { + HStack { + Text(language.localizedDisplayName) + if language.code == delegate.menuState.targetCode { + Image(systemName: "checkmark") + } + } + } + } + Divider() + SettingsLink { + Text(String(localized: "More languages…")) + } + } + + Divider() + + Button(String(localized: "Copy Last Translation")) { + delegate.copyLastTranslation() + } + .disabled(!delegate.menuState.hasTranslation) + + Button(String(localized: "Replace Last Translation")) { + delegate.replaceLastTranslation() + } + .disabled(!delegate.menuState.canReplace) + + Divider() + + Button(String(localized: "Set up Sprachmittler…")) { + delegate.showOnboarding() + } + Button(String(localized: "Diagnostics…")) { + delegate.showDiagnostics() + } + Button(String(localized: "About Sprachmittler")) { + delegate.showAbout() + } + + SettingsLink { + Text(String(localized: "Settings…")) + } + + Divider() + + Button(String(localized: "Quit Sprachmittler")) { + NSApplication.shared.terminate(nil) + } + .keyboardShortcut("q") + } +} diff --git a/App/Onboarding/OnboardingView.swift b/App/Onboarding/OnboardingView.swift new file mode 100644 index 0000000..d9c556a --- /dev/null +++ b/App/Onboarding/OnboardingView.swift @@ -0,0 +1,231 @@ +import AppKit +import SprachmittlerCore +import SwiftUI + +/// The first-run setup window. +struct OnboardingView: View { + @Bindable var model: OnboardingViewModel + let onCopyCommand: @MainActor (String) -> Void + let onFinished: @MainActor () -> Void + + @State private var showLanguagePicker = false + @State private var errorMessage: String? + + var body: some View { + VStack(alignment: .leading, spacing: 16) { + VStack(alignment: .leading, spacing: 4) { + Text(String(localized: "Set up Sprachmittler")) + .font(.title2.bold()) + Text(String(localized: "Local translation with Ollama. Nothing leaves this Mac.")) + .foregroundStyle(.secondary) + } + + checkRow( + title: String(localized: "Ollama"), + state: model.ollama, + detail: ollamaDetail + ) { + Button(String(localized: "Check again")) { + Task { await model.refresh() } + } + .controlSize(.small) + if case .failed = model.ollama, let url = URL(string: "https://ollama.com/download") { + Link(String(localized: "Download Ollama"), destination: url) + .controlSize(.small) + } + } + + checkRow( + title: String(localized: "Hy-MT3 model"), + state: model.model, + detail: modelDetail + ) { + Button(String(localized: "Refresh")) { + Task { await model.refresh() } + } + .controlSize(.small) + if case .failed = model.model { + Button(String(localized: "Copy pull command")) { + onCopyCommand(model.pullCommand) + } + .controlSize(.small) + } + } + + VStack(alignment: .leading, spacing: 6) { + Text(String(localized: "Target language")) + .font(.headline) + Button { + showLanguagePicker.toggle() + } label: { + HStack { + Text(model.target.localizedDisplayName) + Image(systemName: "chevron.up.chevron.down") + .font(.caption) + } + } + .popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) { + LanguagePickerView( + selection: Binding( + get: { model.target }, + set: { model.setTarget($0) } + ) + ) + } + .accessibilityLabel(String(localized: "Target language")) + } + + VStack(alignment: .leading, spacing: 6) { + Text(String(localized: "Accessibility (optional)")) + .font(.headline) + Text(String(localized: "Only Replace needs it. Double copy, translation and Copy work without it.")) + .font(.caption) + .foregroundStyle(.secondary) + HStack { + if model.accessibilityTrusted { + Label(String(localized: "Granted"), systemImage: "checkmark.circle.fill") + .foregroundStyle(.green) + } else { + Button(String(localized: "Enable Accessibility")) { + model.requestAccessibility() + } + Button(String(localized: "Open System Settings")) { + model.openAccessibilitySettings() + } + } + } + } + + if let errorMessage { + Text(errorMessage) + .font(.callout) + .foregroundStyle(.red) + } + + Spacer() + HStack { + Button(String(localized: "Check again")) { + Task { await model.refresh() } + } + Spacer() + Button(String(localized: "Done")) { + do { + try model.complete() + onFinished() + } catch { + errorMessage = String(localized: "Setup could not be saved.") + } + } + .keyboardShortcut(.defaultAction) + .buttonStyle(.borderedProminent) + .disabled(!model.canFinish) + } + } + .padding(24) + .frame(width: 540, height: 560) + .task { + await model.refresh() + } + } + + private var ollamaDetail: String? { + switch model.ollama { + case let .ok(version): String(localized: "Running, version \(version)") + case let .failed(message): message + case .checking: String(localized: "Checking…") + case .idle: nil + } + } + + private var modelDetail: String? { + switch model.model { + case let .ok(tags): tags + case let .failed(message): message + case .checking: String(localized: "Checking…") + case .idle: nil + } + } + + private func checkRow( + title: String, + state: OnboardingCheck, + detail: String?, + @ViewBuilder actions: () -> some View + ) -> some View { + HStack(alignment: .top, spacing: 10) { + Image(systemName: icon(for: state)) + .foregroundStyle(color(for: state)) + .font(.title3) + VStack(alignment: .leading, spacing: 2) { + Text(title).font(.headline) + if let detail { + Text(detail) + .font(.callout) + .foregroundStyle(.secondary) + } + } + Spacer() + HStack(spacing: 8) { + actions() + } + } + .padding(10) + .background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 10)) + } + + private func icon(for state: OnboardingCheck) -> String { + switch state { + case .ok: "checkmark.circle.fill" + case .failed: "xmark.octagon.fill" + case .checking: "clock" + case .idle: "circle" + } + } + + private func color(for state: OnboardingCheck) -> Color { + switch state { + case .ok: .green + case .failed: .red + case .checking: .secondary + case .idle: .secondary + } + } +} + +/// The onboarding window controller. +@MainActor +final class OnboardingWindowController { + private let window: NSWindow + + init( + model: OnboardingViewModel, + onCopyCommand: @escaping @MainActor (String) -> Void, + onFinished: @escaping @MainActor () -> Void + ) { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 540, height: 560), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + self.window = window + window.title = String(localized: "Set up Sprachmittler") + window.isReleasedWhenClosed = false + window.contentViewController = NSHostingController( + rootView: OnboardingView( + model: model, + onCopyCommand: onCopyCommand, + onFinished: { [weak window] in + window?.close() + onFinished() + } + ) + ) + window.center() + } + + func show() { + NSApp.activate(ignoringOtherApps: true) + window.makeKeyAndOrderFront(nil) + } +} diff --git a/App/Panel/LanguagePickerView.swift b/App/Panel/LanguagePickerView.swift new file mode 100644 index 0000000..857d6b7 --- /dev/null +++ b/App/Panel/LanguagePickerView.swift @@ -0,0 +1,55 @@ +import SprachmittlerCore +import SwiftUI + +/// A searchable language list used by the panel and Settings. +struct LanguagePickerView: View { + @Binding var selection: ModelLanguage + var recent: [ModelLanguage] = [] + @Environment(\.dismiss) private var dismiss + @State private var query = "" + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + TextField(String(localized: "Search languages"), text: $query) + .textFieldStyle(.roundedBorder) + .accessibilityLabel(String(localized: "Search languages")) + + ScrollView { + LazyVStack(alignment: .leading, spacing: 2) { + ForEach(filtered) { language in + Button { + selection = language + dismiss() + } label: { + HStack { + Text(language.localizedDisplayName) + Spacer() + if language.code == selection.code { + Image(systemName: "checkmark") + } + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .padding(.vertical, 4) + .padding(.horizontal, 6) + } + } + } + } + .padding(12) + .frame(width: 320, height: 380) + } + + private var filtered: [ModelLanguage] { + let all = LanguageCatalogue.all.sorted { + $0.localizedDisplayName.localizedCaseInsensitiveCompare($1.localizedDisplayName) == .orderedAscending + } + guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return all } + return all.filter { + $0.localizedDisplayName.localizedCaseInsensitiveContains(query) + || $0.modelName.localizedCaseInsensitiveContains(query) + || $0.code.localizedCaseInsensitiveContains(query) + } + } +} diff --git a/App/Panel/PanelController.swift b/App/Panel/PanelController.swift new file mode 100644 index 0000000..073181a --- /dev/null +++ b/App/Panel/PanelController.swift @@ -0,0 +1,75 @@ +import AppKit +import SprachmittlerCore +import SwiftUI + +/// The non-activating floating panel. It never activates the app or steals focus. +@MainActor +final class PanelController: NSObject, NSWindowDelegate { + private let panel: NSPanel + private let viewModel: PanelViewModel + + /// Creates the panel and its SwiftUI content. + init(viewModel: PanelViewModel) { + self.viewModel = viewModel + panel = NSPanel( + contentRect: NSRect(x: 0, y: 0, width: 540, height: 520), + styleMask: [.titled, .fullSizeContentView, .nonactivatingPanel], + backing: .buffered, + defer: false + ) + super.init() + panel.delegate = self + panel.isFloatingPanel = true + panel.becomesKeyOnlyIfNeeded = true + panel.level = .floating + panel.hidesOnDeactivate = false + panel.isMovableByWindowBackground = true + panel.isReleasedWhenClosed = false + panel.titleVisibility = .hidden + panel.titlebarAppearsTransparent = true + panel.backgroundColor = .clear + panel.isOpaque = false + panel.hasShadow = true + panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary] + panel.standardWindowButton(.closeButton)?.isHidden = true + panel.standardWindowButton(.miniaturizeButton)?.isHidden = true + panel.standardWindowButton(.zoomButton)?.isHidden = true + panel.contentView = NSHostingView( + rootView: PanelView( + model: viewModel, + onClose: { [weak self] in self?.close() } + ) + ) + panel.setContentSize(NSSize(width: 540, height: 520)) + } + + /// Shows the panel near the mouse without activating the app. + func show() { + positionNearMouse() + panel.orderFrontRegardless() + } + + /// Hides the panel and cancels/releases its content. + func close() { + panel.orderOut(nil) + Task { await viewModel.close() } + } + + func windowWillClose(_ notification: Notification) { + Task { await viewModel.close() } + } + + private func positionNearMouse() { + let mouse = NSEvent.mouseLocation + let screen = NSScreen.screens.first { $0.frame.contains(mouse) } ?? NSScreen.main + guard let visible = screen?.visibleFrame else { + panel.setFrameOrigin(mouse) + return + } + let size = panel.frame.size + var origin = NSPoint(x: mouse.x - size.width / 2, y: mouse.y + 16) + origin.x = max(visible.minX + 12, min(origin.x, visible.maxX - size.width - 12)) + origin.y = max(visible.minY + 12, min(origin.y, visible.maxY - size.height - 12)) + panel.setFrameOrigin(origin) + } +} diff --git a/App/Panel/PanelView.swift b/App/Panel/PanelView.swift new file mode 100644 index 0000000..8aec5c8 --- /dev/null +++ b/App/Panel/PanelView.swift @@ -0,0 +1,300 @@ +import AppKit +import SprachmittlerCore +import SwiftUI + +/// The translation panel view. It never activates the app. +struct PanelView: View { + @Bindable var model: PanelViewModel + let onClose: @MainActor () -> Void + + @Environment(\.openSettings) private var openSettings + @State private var showLanguagePicker = false + @State private var showSource = true + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + header + if showSource, let source = model.source { + sourcePreview(source) + } + translationArea + warningArea + errorArea + footer + } + .padding(16) + .frame(width: 540) + .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 14, style: .continuous) + .strokeBorder(.separator, lineWidth: 1) + ) + .onAppear { showSource = model.configuration.showSourcePreview } + .onChange(of: model.configuration.showSourcePreview) { _, newValue in + showSource = newValue + } + .onExitCommand(perform: onClose) + .accessibilityElement(children: .contain) + .accessibilityLabel(String(localized: "Translation panel")) + } + + private var header: some View { + HStack(spacing: 10) { + Image(systemName: "character.bubble") + .font(.title2) + .foregroundStyle(.tint) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 1) { + Text(String(localized: "Translate")) + .font(.headline) + Text("\(sourceLanguageLabel) → \(model.configuration.target.localizedDisplayName)") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Button { + showLanguagePicker.toggle() + } label: { + Label(model.configuration.target.localizedDisplayName, systemImage: "globe") + .labelStyle(.titleAndIcon) + } + .accessibilityLabel(String(localized: "Target language")) + .popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) { + LanguagePickerView( + selection: Binding( + get: { model.configuration.target }, + set: { language in + Task { await model.setTarget(language) } + } + ), + recent: model.configuration.recentTargets + ) + } + Button { + openSettings() + } label: { + Image(systemName: "gearshape") + } + .accessibilityLabel(String(localized: "Settings")) + } + } + + private var sourceLanguageLabel: String { + guard let code = model.sourceLanguage, let language = LanguageCatalogue.resolve(code) else { + return String(localized: "Detected language") + } + return language.localizedDisplayName + } + + private func sourcePreview(_ source: CapturedText) -> some View { + DisclosureGroup(isExpanded: $showSource) { + ScrollView { + Text(source.text) + .font(.callout) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + } + .frame(maxHeight: 100) + } label: { + Text(String(localized: "Source")) + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + } + .accessibilityLabel(String(localized: "Source text")) + } + + private var translationArea: some View { + ScrollView { + Text(translationText) + .font(.body) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + .foregroundStyle(model.translation.isEmpty ? .secondary : .primary) + .environment( + \.layoutDirection, + model.configuration.target.isRTL ? .rightToLeft : .leftToRight + ) + .accessibilityLabel(String(localized: "Translation")) + } + .frame(minHeight: 120, maxHeight: 260) + .padding(10) + .background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8)) + .overlay(alignment: .topTrailing) { + if model.phase == .translating || model.phase == .streaming { + ProgressView() + .controlSize(.small) + .padding(8) + .accessibilityLabel(String(localized: "Translating")) + } + } + } + + private var translationText: String { + if !model.translation.isEmpty { + return model.translation + } + switch model.phase { + case .translating, .streaming: + return String(localized: "Translating…") + case .failed: + return String(localized: "No translation.") + case .idle, .ready: + return String(localized: "No translation yet.") + } + } + + @ViewBuilder private var warningArea: some View { + if model.sameLanguageWarning != nil { + HStack(alignment: .top, spacing: 8) { + Image(systemName: "info.circle.fill").foregroundStyle(.blue) + Text("This text already appears to be in \(model.configuration.target.localizedDisplayName).") + .font(.callout) + Spacer() + Button(String(localized: "Translate anyway")) { + model.dismissSameLanguageWarning() + } + .controlSize(.small) + } + .padding(8) + .background(.blue.opacity(0.08), in: RoundedRectangle(cornerRadius: 8)) + } + + ForEach(Array(visibleWarnings.enumerated()), id: \.offset) { _, warning in + HStack(alignment: .top, spacing: 8) { + Image(systemName: warning.isBlocking ? "exclamationmark.triangle.fill" : "exclamationmark.circle") + .foregroundStyle(warning.isBlocking ? .orange : .secondary) + Text(warning.panelMessage) + .font(.callout) + Spacer() + } + .padding(8) + .background( + (warning.isBlocking ? Color.orange : Color.secondary) + .opacity(0.08), + in: RoundedRectangle(cornerRadius: 8) + ) + .accessibilityLabel(warning.panelMessage) + } + } + + private var visibleWarnings: [TranslationWarning] { + model.warnings.filter { warning in + if case .sameLanguage = warning { + return false + } + return true + } + } + + @ViewBuilder private var errorArea: some View { + if let message = model.errorMessage, model.phase == .failed { + HStack(alignment: .top, spacing: 8) { + Image(systemName: "exclamationmark.octagon.fill") + .foregroundStyle(.red) + VStack(alignment: .leading, spacing: 6) { + Text(message) + .font(.callout) + if let action = model.recoveryAction { + recoveryButton(action) + } + } + Spacer() + } + .padding(8) + .background(.red.opacity(0.08), in: RoundedRectangle(cornerRadius: 8)) + .accessibilityLabel(message) + } + } + + @ViewBuilder private func recoveryButton(_ action: RecoveryAction) -> some View { + switch action { + case .startOllama: + if let url = URL(string: "https://ollama.com/download") { + Link(String(localized: "Download Ollama"), destination: url) + .controlSize(.small) + } + case let .pullModel(modelName): + Button(String(localized: "Copy pull command")) { + model.copy("ollama pull \(modelName)") + } + .controlSize(.small) + case .openSettings: + if model.error == .accessibilityNotTrusted, let url = accessibilitySettingsURL { + Button(String(localized: "Open Accessibility Settings")) { + NSWorkspace.shared.open(url) + } + .controlSize(.small) + } else { + Button(String(localized: "Open Settings")) { + openSettings() + } + .controlSize(.small) + } + case .copyInstead: + Button(String(localized: "Copy instead")) { + model.copyTranslation() + } + .controlSize(.small) + case .shortenText: + EmptyView() + case .retry: + Button(String(localized: "Retry")) { + Task { await model.retry() } + } + .controlSize(.small) + case .none: + EmptyView() + } + } + + private var accessibilitySettingsURL: URL? { + URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility") + } + + private var footer: some View { + HStack(spacing: 10) { + Button { + model.copyTranslation() + } label: { + Label( + model.didCopy ? String(localized: "Copied") : String(localized: "Copy"), + systemImage: "doc.on.doc" + ) + } + .keyboardShortcut("c", modifiers: .command) + .disabled(!model.canCopy) + .accessibilityLabel(String(localized: "Copy translation")) + + Button { + Task { await model.retry() } + } label: { + Label(String(localized: "Retry"), systemImage: "arrow.clockwise") + } + .keyboardShortcut("r", modifiers: .command) + .disabled(model.source == nil) + .accessibilityLabel(String(localized: "Retry translation")) + + Spacer() + + Button { + onClose() + } label: { + Text(String(localized: "Close")) + } + .keyboardShortcut(.cancelAction) + .accessibilityLabel(String(localized: "Close panel")) + + Button { + Task { await model.replaceSelection() } + } label: { + Text(String(localized: "Replace")) + } + .keyboardShortcut(.return, modifiers: .command) + .buttonStyle(.borderedProminent) + .disabled(!model.canReplace) + .help(model.replaceUnavailableReason ?? String(localized: "Replace the selection")) + .accessibilityLabel(String(localized: "Replace selection")) + } + } +} diff --git a/App/Settings/SettingsView.swift b/App/Settings/SettingsView.swift new file mode 100644 index 0000000..81b1672 --- /dev/null +++ b/App/Settings/SettingsView.swift @@ -0,0 +1,291 @@ +import SprachmittlerCore +import SwiftUI + +/// The Settings window: General, Model, Translation, Privacy and Diagnostics. +@MainActor +struct SettingsView: View { + @Bindable var model: SettingsViewModel + let onOpenDiagnostics: @MainActor () -> Void + let onSaved: @MainActor () -> Void + + @State private var draft: AppSettings + @State private var endpointText: String + @State private var saveMessage: String? + @State private var showLanguagePicker = false + + init( + model: SettingsViewModel, + onOpenDiagnostics: @escaping @MainActor () -> Void, + onSaved: @escaping @MainActor () -> Void = {} + ) { + self.model = model + self.onOpenDiagnostics = onOpenDiagnostics + self.onSaved = onSaved + _draft = State(initialValue: model.draft) + _endpointText = State(initialValue: model.draft.endpoint.absoluteString) + } + + var body: some View { + VStack(spacing: 0) { + TabView { + generalTab + .tabItem { Label(String(localized: "General"), systemImage: "gearshape") } + modelTab + .tabItem { Label(String(localized: "Model"), systemImage: "cpu") } + translationTab + .tabItem { Label(String(localized: "Translation"), systemImage: "text.bubble") } + privacyTab + .tabItem { Label(String(localized: "Privacy"), systemImage: "lock") } + diagnosticsTab + .tabItem { Label(String(localized: "Diagnostics"), systemImage: "stethoscope") } + } + .padding(16) + + Divider() + HStack { + if let saveMessage { + Text(saveMessage) + .font(.callout) + .foregroundStyle(.red) + } else if let launchError = model.launchError { + Text(launchError) + .font(.callout) + .foregroundStyle(.orange) + } + Spacer() + Button(String(localized: "Reset")) { + model.reset() + draft = model.draft + endpointText = model.draft.endpoint.absoluteString + saveMessage = nil + onSaved() + } + Button(String(localized: "Save")) { + save() + } + .keyboardShortcut("s", modifiers: .command) + .buttonStyle(.borderedProminent) + } + .padding(12) + } + .frame(width: 660, height: 520) + } + + private var generalTab: some View { + Form { + Section(String(localized: "Translation")) { + LabeledContent(String(localized: "Target language")) { + Button { + showLanguagePicker.toggle() + } label: { + HStack { + Text(draft.targetLanguageModel.localizedDisplayName) + Image(systemName: "chevron.up.chevron.down") + .font(.caption) + } + } + .popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) { + LanguagePickerView( + selection: Binding( + get: { draft.targetLanguageModel }, + set: { draft.targetLanguage = $0.code } + ), + recent: draft.recentTargets + ) + } + .accessibilityLabel(String(localized: "Target language")) + } + Toggle(String(localized: "Show source preview"), isOn: $draft.showSourcePreview) + } + + Section(String(localized: "Double copy")) { + LabeledContent(String(localized: "Window: \(draft.doubleCopyWindowMs) ms")) { + Slider( + value: Binding( + get: { Double(draft.doubleCopyWindowMs) }, + set: { draft.doubleCopyWindowMs = Int($0) } + ), + in: 300 ... 1000, + step: 50 + ) + } + Text(String(localized: "Two identical copies inside this window trigger a translation.")) + .font(.caption) + .foregroundStyle(.secondary) + } + + Section(String(localized: "Startup")) { + Toggle(String(localized: "Launch at login"), isOn: $draft.launchAtLogin) + Toggle(String(localized: "Warm up the model on launch"), isOn: $draft.warmUpOnLaunch) + } + } + .formStyle(.grouped) + } + + private var modelTab: some View { + Form { + Section(String(localized: "Ollama")) { + TextField(String(localized: "Endpoint"), text: $endpointText) + .accessibilityLabel(String(localized: "Ollama endpoint")) + Toggle(String(localized: "Allow a remote HTTPS endpoint"), isOn: $draft.allowRemoteEndpoint) + Button(String(localized: "Refresh installed models")) { + guard let endpoint = URL(string: endpointText) else { + saveMessage = String(localized: "Enter a valid endpoint URL.") + return + } + draft.endpoint = endpoint + model.draft = draft + Task { + await model.refreshModels() + draft.fastModel = model.detectedFastModel ?? draft.fastModel + } + } + } + + Section(String(localized: "Model")) { + Picker(String(localized: "Translation model"), selection: $draft.model) { + ForEach(model.modelChoices, id: \.self) { tag in + Text(tag).tag(tag) + } + } + TextField( + String(localized: "Fast model tag (optional)"), + text: Binding( + get: { draft.fastModel ?? "" }, + set: { draft.fastModel = $0.isEmpty ? nil : $0 } + ) + ) + Picker(String(localized: "Keep model loaded"), selection: $draft.keepModelLoaded) { + Text("5 minutes").tag("5m") + Text("30 minutes").tag("30m") + Text("1 hour").tag("1h") + Text("Unload after each request").tag("0") + } + if let digest = model.selectedDigest { + LabeledContent(String(localized: "Digest"), value: String(digest.prefix(12))) + } + Text(model.licenceNote) + .font(.caption) + .foregroundStyle(.secondary) + } + + Section(String(localized: "Context and output")) { + Stepper( + String(localized: "Context: \(draft.numCtx)"), + value: $draft.numCtx, + in: 1024 ... 32768, + step: 1024 + ) + Stepper( + String(localized: "Maximum output: \(draft.numPredict)"), + value: $draft.numPredict, + in: 256 ... 8192, + step: 256 + ) + } + } + .formStyle(.grouped) + } + + private var translationTab: some View { + Form { + Section(String(localized: "Sampling")) { + LabeledContent(String(localized: "Temperature")) { + TextField("", value: $draft.temperature, format: .number.precision(.fractionLength(0 ... 2))) + .frame(width: 80) + .accessibilityLabel(String(localized: "Temperature")) + } + LabeledContent(String(localized: "Top P")) { + TextField("", value: $draft.topP, format: .number.precision(.fractionLength(0 ... 2))) + .frame(width: 80) + .accessibilityLabel(String(localized: "Top P")) + } + Stepper(String(localized: "Top K: \(draft.topK)"), value: $draft.topK, in: 1 ... 100) + LabeledContent(String(localized: "Repetition penalty")) { + TextField("", value: $draft.repeatPenalty, format: .number.precision(.fractionLength(0 ... 2))) + .frame(width: 80) + .accessibilityLabel(String(localized: "Repetition penalty")) + } + } + + 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 + ) + } + + Section(String(localized: "Prompt policy")) { + Text(String(localized: "Default translation is fixed for v1.")) + Text(String(localized: "Content-aware prompt selection is decided in M7.")) + .font(.caption) + .foregroundStyle(.secondary) + } + } + .formStyle(.grouped) + } + + private var privacyTab: some View { + Form { + Section(String(localized: "Local and private")) { + Text( + String( + localized: "Selected text, translations, the clipboard and app names are never written to disk." + ) + ) + Text(String(localized: "No telemetry, no analytics and no accounts.")) + Text( + String( + localized: "The clipboard is read only after a change; the last translation stays in memory." + ) + ) + } + Section(String(localized: "Permissions")) { + Text(String(localized: "Accessibility is optional and used only for Replace.")) + Text(String(localized: "Input Monitoring, Screen Recording, Camera, Microphone and Apple Events")) + Text(String(localized: "are never requested.")) + } + } + .formStyle(.grouped) + } + + private var diagnosticsTab: some View { + Form { + Section { + Button(String(localized: "Open Diagnostics…")) { + onOpenDiagnostics() + } + Text(String(localized: "Versions, model digests, timings and error kinds only. No text.")) + .font(.caption) + .foregroundStyle(.secondary) + } + } + .formStyle(.grouped) + } + + private func save() { + guard let endpoint = URL(string: endpointText) else { + saveMessage = String(localized: "Enter a valid endpoint URL.") + return + } + draft.endpoint = endpoint + model.draft = draft + model.save() + if let error = model.saveError { + saveMessage = error + return + } + draft = model.draft + endpointText = draft.endpoint.absoluteString + saveMessage = nil + onSaved() + } +} diff --git a/App/SprachmittlerApp.swift b/App/SprachmittlerApp.swift index 4d7d0f2..778444a 100644 --- a/App/SprachmittlerApp.swift +++ b/App/SprachmittlerApp.swift @@ -1,35 +1,25 @@ import AppKit import SwiftUI -/// Entry point. Keep this file thin: scenes only, no business logic (ARCHITECTURE §3). +/// Entry point. Scenes and glue only; business logic lives in the package. @main struct SprachmittlerApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate var body: some Scene { - MenuBarExtra("Sprachmittler", systemImage: "translate") { - Button(String(localized: "Translate Clipboard Text")) { - (NSApp.delegate as? AppDelegate)?.captureClipboardText() - } - Divider() - Button(String(localized: "Set up Sprachmittler…")) {} - .disabled(true) - SettingsLink { - Text(String(localized: "Settings…")) - } - Divider() - Button(String(localized: "Quit Sprachmittler")) { - NSApplication.shared.terminate(nil) - } - .keyboardShortcut("q") + MenuBarExtra { + StatusMenuView(delegate: appDelegate) + } label: { + Label("Sprachmittler", systemImage: "translate") } .menuBarExtraStyle(.menu) Settings { - // Replaced by Settings/SettingsView.swift. - Text("Settings") - .padding() - .frame(width: 480, height: 320) + SettingsView( + model: appDelegate.environment.settingsModel, + onOpenDiagnostics: { appDelegate.showDiagnostics() }, + onSaved: { appDelegate.environment.settingsDidChange() } + ) } } } diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AXTextEditor.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AXTextEditor.swift new file mode 100644 index 0000000..f930df7 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AXTextEditor.swift @@ -0,0 +1,99 @@ +import ApplicationServices +import CoreGraphics +import Foundation + +/// The Accessibility operations Replace needs, behind a seam for tests. +public protocol AccessibilityTextEditing: Sendable { + /// Whether the app is trusted for Accessibility. + func isTrusted() async -> Bool + /// The focused element's selected text, or nil when unsupported. + func selectedText(pid: pid_t) async -> String? + /// True for a secure/password field. + func isSecureField(pid: pid_t) async -> Bool + /// Sets the focused selection. Returns false when the app does not accept it. + func setSelectedText(pid: pid_t, to text: String) async -> Bool +} + +/// Posts the synthetic paste. Tests replace it with a fake. +public protocol EventPosting: Sendable { + /// Posts ⌘V to a PID. Returns false when events cannot be created. + func postPaste(to pid: pid_t) -> Bool +} + +/// The production Accessibility editor. AX calls run on this actor, never on the main actor. +public actor AXTextEditor: AccessibilityTextEditing { + /// Creates the editor. + public init() {} + + public func isTrusted() -> Bool { + AXIsProcessTrusted() + } + + public func selectedText(pid: pid_t) -> String? { + guard let focused = focusedElement(pid: pid) else { return nil } + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue( + focused, + kAXSelectedTextAttribute as CFString, + &value + ) == .success else { + return nil + } + return value as? String + } + + public func isSecureField(pid: pid_t) -> Bool { + guard let focused = focusedElement(pid: pid) else { return false } + if attribute(focused, kAXSubroleAttribute) == "AXSecureTextField" { + return true + } + return attribute(focused, kAXRoleAttribute) == "AXSecureTextField" + } + + private func attribute(_ element: AXUIElement, _ name: String) -> String? { + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success else { + return nil + } + return value as? String + } + + public func setSelectedText(pid: pid_t, to text: String) async -> Bool { + guard let focused = focusedElement(pid: pid) else { return false } + return AXUIElementSetAttributeValue( + focused, + kAXSelectedTextAttribute as CFString, + text as CFTypeRef + ) == .success + } + + private func focusedElement(pid: pid_t) -> AXUIElement? { + let application = AXUIElementCreateApplication(pid) + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue( + application, + kAXFocusedUIElementAttribute as CFString, + &value + ) == .success, let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil } + return unsafeDowncast(value, to: AXUIElement.self) + } +} + +/// The production ⌘V poster. +public struct CGEventPoster: EventPosting { + /// Creates a poster. + public init() {} + + public func postPaste(to pid: pid_t) -> Bool { + guard let keyDown = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: true), + let keyUp = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: false) + else { + return false + } + keyDown.flags = .maskCommand + keyUp.flags = .maskCommand + keyDown.postToPid(pid) + keyUp.postToPid(pid) + return true + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AccessibilityPermission.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AccessibilityPermission.swift new file mode 100644 index 0000000..e6b3ecb --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AccessibilityPermission.swift @@ -0,0 +1,27 @@ +import AppKit +import ApplicationServices +import SprachmittlerCore + +/// The production Accessibility permission gate. It is never called on the capture path. +@MainActor +public final class AccessibilityPermission: AccessibilityPermissionChecking { + /// Creates the gate. + public init() {} + + public var isTrusted: Bool { + AXIsProcessTrusted() + } + + public func requestTrust() { + // Use the public option key literal: the ApplicationServices global is not + // concurrency-safe under Swift 6, and this is the same documented key. + let options = ["AXTrustedCheckOptionPrompt": true] as CFDictionary + _ = AXIsProcessTrustedWithOptions(options) + } + + public func openSettings() { + let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility") + ?? URL(fileURLWithPath: "/System/Applications/System Settings.app") + NSWorkspace.shared.open(url) + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/FrontmostTargetProvider.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/FrontmostTargetProvider.swift new file mode 100644 index 0000000..041f496 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/FrontmostTargetProvider.swift @@ -0,0 +1,20 @@ +import AppKit +import Foundation +import SprachmittlerCore + +/// Captures the frontmost app at trigger time. It never reads a full document value. +@MainActor +public final class FrontmostTargetProvider: InsertionTargetProviding { + /// Creates a provider. + public init() {} + + public func captureTarget() -> InsertionTarget? { + guard let application = NSWorkspace.shared.frontmostApplication else { return nil } + return InsertionTarget( + pid: application.processIdentifier, + bundleID: application.bundleIdentifier, + selectedText: nil, + capturedAt: Date() + ) + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/InsertionCoordinator.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/InsertionCoordinator.swift new file mode 100644 index 0000000..5767ba3 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/InsertionCoordinator.swift @@ -0,0 +1,110 @@ +import Darwin +import Foundation +import SprachmittlerCore + +/// Replaces the selection with Accessibility first and a clipboard paste as fallback. +public actor InsertionCoordinator: TextInserting { + private let pasteboard: any PasteboardAccessing + private let accessibility: any AccessibilityTextEditing + private let poster: any EventPosting + private let delay: @Sendable (Duration) async throws -> Void + private let ownWrite: @MainActor @Sendable () -> Void + private let frontmostPID: @MainActor @Sendable () -> pid_t + + /// Creates the coordinator. + public init( + pasteboard: any PasteboardAccessing, + accessibility: any AccessibilityTextEditing, + poster: any EventPosting = CGEventPoster(), + delay: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, + ownWrite: @escaping @MainActor @Sendable () -> Void, + frontmostPID: @escaping @MainActor @Sendable () -> pid_t + ) { + self.pasteboard = pasteboard + self.accessibility = accessibility + self.poster = poster + self.delay = delay + self.ownWrite = ownWrite + self.frontmostPID = frontmostPID + } + + public func replace( + selection: CapturedText, + with translation: String, + target: InsertionTarget + ) async throws -> InsertionOutcome { + guard target.pid != getpid() else { + throw SprachmittlerError.insertionTargetChanged + } + let pid = await frontmostPID() + try InsertionPolicy.verify( + frontmostPID: pid, + target: target, + selectedText: nil, + source: selection.text + ) + + guard await accessibility.isTrusted() else { + throw SprachmittlerError.accessibilityNotTrusted + } + if await accessibility.isSecureField(pid: target.pid) { + throw SprachmittlerError.accessibilityUnsupported(app: target.bundleID) + } + + if let selected = await accessibility.selectedText(pid: target.pid) { + try InsertionPolicy.verify( + frontmostPID: pid, + target: target, + selectedText: selected, + source: selection.text + ) + if await accessibility.setSelectedText(pid: target.pid, to: translation) { + return .replaced(using: .accessibility) + } + } + + return try await pasteFallback(selection: selection, translation: translation, target: target, pid: pid) + } + + private func pasteFallback( + selection: CapturedText, + translation: String, + target: InsertionTarget, + pid: pid_t + ) async throws -> InsertionOutcome { + // Re-check the selection after a failed AX set before mutating the clipboard. + if let selected = await accessibility.selectedText(pid: target.pid) { + try InsertionPolicy.verify( + frontmostPID: pid, + target: target, + selectedText: selected, + source: selection.text + ) + } + + guard let snapshot = await pasteboard.snapshot() else { + throw SprachmittlerError.pasteboardUnavailable + } + let written = await pasteboard.write(translation) + await ownWrite() + do { + guard poster.postPaste(to: target.pid) else { + throw SprachmittlerError.accessibilityUnsupported(app: target.bundleID) + } + try await delay(.milliseconds(300)) + guard await pasteboard.restore(snapshot, onlyIfChangeCountMatches: written) else { + throw SprachmittlerError.pasteboardRestoreFailed + } + } catch { + // SP-9: restore even when the paste or the settle delay is cancelled/fails. + _ = await pasteboard.restore(snapshot, onlyIfChangeCountMatches: written) + throw error + } + return .replaced(using: .paste) + } + + /// Whether Accessibility is currently available; the panel uses this for hints. + public func isAccessibilityTrusted() async -> Bool { + await accessibility.isTrusted() + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardAccessing.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardAccessing.swift index 2ea67db..1150414 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardAccessing.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardAccessing.swift @@ -3,7 +3,7 @@ import Foundation /// The pasteboard operations `SprachmittlerCapture` needs. Tests use a fake; the app uses /// `SystemPasteboard`. Every member is main-actor isolated because `NSPasteboard` is. @MainActor -public protocol PasteboardAccessing: AnyObject { +public protocol PasteboardAccessing: AnyObject, Sendable { /// The current pasteboard change count. var changeCount: Int { get } diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppOllama.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppOllama.swift new file mode 100644 index 0000000..a581475 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppOllama.swift @@ -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) + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift new file mode 100644 index 0000000..6d2be14 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift @@ -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, + 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, + 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() + 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 { + min(max(value, range.lowerBound), range.upperBound) + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsStore.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsStore.swift new file mode 100644 index 0000000..82b436b --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsStore.swift @@ -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() + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsViewModel.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsViewModel.swift new file mode 100644 index 0000000..83c7432 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsViewModel.swift @@ -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") + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageAliases.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageAliases.swift index a408356..a0fd79c 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageAliases.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageAliases.swift @@ -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 diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageCatalogue.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageCatalogue.swift new file mode 100644 index 0000000..cd37de9 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageCatalogue.swift @@ -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) + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/OnboardingViewModel.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/OnboardingViewModel.swift new file mode 100644 index 0000000..0873119 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/OnboardingViewModel.swift @@ -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 } + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift new file mode 100644 index 0000000..e7b0b8c --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift @@ -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? + 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) + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelWarningMessages.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelWarningMessages.swift new file mode 100644 index 0000000..78db695 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelWarningMessages.swift @@ -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 + } + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PermissionProtocols.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PermissionProtocols.swift new file mode 100644 index 0000000..8be816a --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/PermissionProtocols.swift @@ -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 +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsStore.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsStore.swift new file mode 100644 index 0000000..6a42014 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsStore.swift @@ -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() + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsViewModel.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsViewModel.swift new file mode 100644 index 0000000..77c7d0a --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsViewModel.swift @@ -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 + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift new file mode 100644 index 0000000..0483778 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift @@ -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 `. + 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" + } + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TextInserting.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TextInserting.swift new file mode 100644 index 0000000..a718678 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TextInserting.swift @@ -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) + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift index 9f2adc6..ea42356 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift @@ -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 } diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift new file mode 100644 index 0000000..88140ad --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift @@ -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 + private let continuation: AsyncStream.Continuation + private var epoch: UInt64 = 0 + private var task: Task? + + /// 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.makeStream() + eventsStream = pair.stream + continuation = pair.continuation + } + + /// The event stream. It has one consumer, normally `PanelViewModel`. + public func events() -> AsyncStream { + 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)) + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3ModelPreset.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3ModelPreset.swift index c9db26f..2f1a1dd 100644 --- a/Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3ModelPreset.swift +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3ModelPreset.swift @@ -14,4 +14,9 @@ public enum HyMT3ModelPreset { public static func isHyMT3(_ model: String) -> Bool { model.lowercased().contains("hy-mt3") } + + /// True for the 1.8B Fast tag, without hard-coding the full tag in UI code. + public static func isFastModel(_ model: String) -> Bool { + model.lowercased().contains("hy-mt3-1.8b") + } } diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeSettingsAndPermissions.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeSettingsAndPermissions.swift new file mode 100644 index 0000000..7cabc69 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeSettingsAndPermissions.swift @@ -0,0 +1,65 @@ +import Foundation +import SprachmittlerCore + +/// An in-memory settings backend for tests. +public final class InMemorySettingsDataStore: SettingsDataStoring, @unchecked Sendable { + private let lock = NSLock() + private var values: [String: Data] = [:] + + /// Creates an empty store. + public init() {} + + public func data(forKey key: String) -> Data? { + lock.lock() + defer { lock.unlock() } + return values[key] + } + + public func set(_ data: Data?, forKey key: String) { + lock.lock() + values[key] = data + lock.unlock() + } +} + +/// An Accessibility fake for onboarding and insertion tests. +@MainActor +public final class FakeAccessibilityPermission: AccessibilityPermissionChecking { + public var isTrusted: Bool + public private(set) var requestCount = 0 + public private(set) var openSettingsCount = 0 + + /// Creates a fake. + public init(isTrusted: Bool = false) { + self.isTrusted = isTrusted + } + + public func requestTrust() { + requestCount += 1 + } + + public func openSettings() { + openSettingsCount += 1 + } +} + +/// A launch-at-login fake. +@MainActor +public final class FakeLaunchAtLogin: LaunchAtLoginControlling { + public var isEnabled: Bool + public private(set) var requestedValues: [Bool] = [] + public var error: (any Error)? + + /// Creates a fake. + public init(isEnabled: Bool = false) { + self.isEnabled = isEnabled + } + + public func setEnabled(_ enabled: Bool) throws { + requestedValues.append(enabled) + if let error { + throw error + } + isEnabled = enabled + } +} diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/InsertionCoordinatorTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/InsertionCoordinatorTests.swift new file mode 100644 index 0000000..51ad3ad --- /dev/null +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/InsertionCoordinatorTests.swift @@ -0,0 +1,297 @@ +import Darwin +import Foundation +import SprachmittlerCore +import SprachmittlerTestSupport +import Testing +@testable import SprachmittlerCapture + +@Suite("Insertion coordinator") +@MainActor +struct InsertionCoordinatorTests { + private let source = CapturedText( + text: "Hello.", + capturedAt: Date(timeIntervalSince1970: 0), + source: .doubleCopy + ) + private let target = InsertionTarget( + pid: 1234, + bundleID: "com.example.app", + selectedText: nil, + capturedAt: Date(timeIntervalSince1970: 0) + ) + + @Test func accessibilityDirectReplacementDoesNotTouchTheClipboard() async throws { + let pasteboard = makePasteboard() + let accessibility = FakeAccessibilityEditor( + trusted: true, + selected: "Hello.", + secure: false, + setResult: true + ) + let poster = FakeEventPoster(result: true) + let coordinator = makeCoordinator(pasteboard: pasteboard, accessibility: accessibility, poster: poster) + + let outcome = try await coordinator.replace(selection: source, with: "Hallo", target: target) + + #expect(outcome == .replaced(using: .accessibility)) + #expect(await accessibility.setCalls == ["Hallo"]) + #expect(pasteboard.writtenTexts.isEmpty) + #expect(poster.pids.isEmpty) + } + + @Test func unsupportedAccessibilityFallsBackToPasteAndRestoresTheClipboard() async throws { + let pasteboard = makePasteboard() + let accessibility = FakeAccessibilityEditor( + trusted: true, + selected: nil, + secure: false, + setResult: false + ) + let poster = FakeEventPoster(result: true) + let coordinator = makeCoordinator(pasteboard: pasteboard, accessibility: accessibility, poster: poster) + + let outcome = try await coordinator.replace(selection: source, with: "Hallo", target: target) + + #expect(outcome == .replaced(using: .paste)) + #expect(pasteboard.writtenTexts == ["Hallo"]) + #expect(pasteboard.text == "Original") + #expect(!pasteboard.hasOwnWriteMarkers) + #expect(poster.pids == [1234]) + } + + @Test func wrongFrontmostAppAbortsBeforeTouchingAnything() async { + let pasteboard = makePasteboard() + let accessibility = FakeAccessibilityEditor( + trusted: true, + selected: "Hello.", + secure: false, + setResult: true + ) + let coordinator = makeCoordinator( + pasteboard: pasteboard, + accessibility: accessibility, + poster: FakeEventPoster(result: true), + frontmost: 999 + ) + + await #expect(throws: SprachmittlerError.insertionTargetChanged) { + _ = try await coordinator.replace(selection: source, with: "Hallo", target: target) + } + #expect(pasteboard.writtenTexts.isEmpty) + } + + @Test func changedSelectionAborts() async { + let accessibility = FakeAccessibilityEditor( + trusted: true, + selected: "Different.", + secure: false, + setResult: true + ) + let coordinator = makeCoordinator( + pasteboard: makePasteboard(), + accessibility: accessibility, + poster: FakeEventPoster(result: true) + ) + + await #expect(throws: SprachmittlerError.insertionTargetChanged) { + _ = try await coordinator.replace(selection: source, with: "Hallo", target: target) + } + } + + @Test func deniedAccessibilityAborts() async { + let accessibility = FakeAccessibilityEditor( + trusted: false, + selected: nil, + secure: false, + setResult: false + ) + let coordinator = makeCoordinator( + pasteboard: makePasteboard(), + accessibility: accessibility, + poster: FakeEventPoster(result: true) + ) + + await #expect(throws: SprachmittlerError.accessibilityNotTrusted) { + _ = try await coordinator.replace(selection: source, with: "Hallo", target: target) + } + } + + @Test func secureFieldIsRefused() async { + let accessibility = FakeAccessibilityEditor( + trusted: true, + selected: nil, + secure: true, + setResult: false + ) + let coordinator = makeCoordinator( + pasteboard: makePasteboard(), + accessibility: accessibility, + poster: FakeEventPoster(result: true) + ) + + await #expect(throws: SprachmittlerError.accessibilityUnsupported(app: "com.example.app")) { + _ = try await coordinator.replace(selection: source, with: "Hallo", target: target) + } + } + + @Test func restoreFailureIsReported() async { + let pasteboard = makePasteboard() + pasteboard.restoreSucceeds = false + let accessibility = FakeAccessibilityEditor( + trusted: true, + selected: nil, + secure: false, + setResult: false + ) + let coordinator = makeCoordinator( + pasteboard: pasteboard, + accessibility: accessibility, + poster: FakeEventPoster(result: true) + ) + + await #expect(throws: SprachmittlerError.pasteboardRestoreFailed) { + _ = try await coordinator.replace(selection: source, with: "Hallo", target: target) + } + #expect(pasteboard.text == "Hallo") + } + + @Test func cancelledSettleDelayStillRestoresTheClipboard() async { + let pasteboard = makePasteboard() + let accessibility = FakeAccessibilityEditor( + trusted: true, + selected: nil, + secure: false, + setResult: false + ) + let coordinator = makeCoordinator( + pasteboard: pasteboard, + accessibility: accessibility, + poster: FakeEventPoster(result: true), + delay: { _ in throw CancellationError() } + ) + + await #expect(throws: CancellationError.self) { + _ = try await coordinator.replace(selection: source, with: "Hallo", target: target) + } + #expect(pasteboard.text == "Original") + #expect(!pasteboard.hasOwnWriteMarkers) + } + + @Test func eventPostingFailureRestoresAndReportsUnsupported() async { + let pasteboard = makePasteboard() + let accessibility = FakeAccessibilityEditor( + trusted: true, + selected: nil, + secure: false, + setResult: false + ) + let coordinator = makeCoordinator( + pasteboard: pasteboard, + accessibility: accessibility, + poster: FakeEventPoster(result: false) + ) + + await #expect(throws: SprachmittlerError.accessibilityUnsupported(app: "com.example.app")) { + _ = try await coordinator.replace(selection: source, with: "Hallo", target: target) + } + #expect(pasteboard.text == "Original") + } + + @Test func refusesToInsertIntoItsOwnApp() async { + let own = InsertionTarget( + pid: getpid(), + bundleID: "de.schihei.sprachmittler", + selectedText: nil, + capturedAt: Date() + ) + let coordinator = makeCoordinator( + pasteboard: makePasteboard(), + accessibility: FakeAccessibilityEditor( + trusted: true, + selected: nil, + secure: false, + setResult: false + ), + poster: FakeEventPoster(result: true) + ) + + await #expect(throws: SprachmittlerError.insertionTargetChanged) { + _ = try await coordinator.replace(selection: source, with: "Hallo", target: own) + } + } + + private func makePasteboard() -> FakePasteboard { + let original = Data("Original".utf8) + return FakePasteboard( + changeCount: 1, + text: "Original", + items: [ClipboardItemData(data: ["public.utf8-plain-text": original])] + ) + } + + private func makeCoordinator( + pasteboard: FakePasteboard, + accessibility: FakeAccessibilityEditor, + poster: FakeEventPoster, + frontmost: pid_t = 1234, + delay: @escaping @Sendable (Duration) async throws -> Void = { _ in } + ) -> InsertionCoordinator { + InsertionCoordinator( + pasteboard: pasteboard, + accessibility: accessibility, + poster: poster, + delay: delay, + ownWrite: {}, + frontmostPID: { frontmost } + ) + } +} + +private actor FakeAccessibilityEditor: AccessibilityTextEditing { + let trusted: Bool + let selected: String? + let secure: Bool + let setResult: Bool + private(set) var setCalls: [String] = [] + + init(trusted: Bool, selected: String?, secure: Bool, setResult: Bool) { + self.trusted = trusted + self.selected = selected + self.secure = secure + self.setResult = setResult + } + + func isTrusted() async -> Bool { + trusted + } + + func selectedText(pid: pid_t) async -> String? { + selected + } + + func isSecureField(pid: pid_t) async -> Bool { + secure + } + + func setSelectedText(pid: pid_t, to text: String) async -> Bool { + setCalls.append(text) + return setResult + } +} + +private final class FakeEventPoster: EventPosting, @unchecked Sendable { + private let lock = NSLock() + private(set) var pids: [pid_t] = [] + let result: Bool + + init(result: Bool) { + self.result = result + } + + func postPaste(to pid: pid_t) -> Bool { + lock.lock() + pids.append(pid) + lock.unlock() + return result + } +} diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift new file mode 100644 index 0000000..a4e1f46 --- /dev/null +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift @@ -0,0 +1,200 @@ +import Foundation +import SprachmittlerEngines +import SprachmittlerOllama +import SprachmittlerTestSupport +import Testing +@testable import SprachmittlerCore + +@Suite("App settings") +struct AppSettingsTests { + @Test func defaultsAreValidAndTextFree() { + let settings = AppSettings() + #expect(settings.endpoint == AppSettings.defaultEndpoint) + #expect(!settings.allowRemoteEndpoint) + #expect(settings.model == HyMT3ModelPreset.defaultModel) + #expect(settings.targetLanguageModel.code == HyMT3Languages.resolve(settings.targetLanguage)?.code) + #expect(settings.doubleCopyWindowMs == 500) + #expect(settings.maxCharactersLatin == 4000) + #expect(settings.maxCharactersCJK == 2000) + #expect(settings.numCtx == 8192) + #expect(!settings.autoCopy) + #expect(!settings.hasCompletedOnboarding) + } + + @Test func codableRoundTripPreservesValues() throws { + var settings = AppSettings() + settings.endpoint = try #require(URL(string: "https://example.com:11434")) + settings.allowRemoteEndpoint = true + settings.targetLanguage = "de" + settings.noteTarget(HyMT3Languages.german) + settings.temperature = 0.2 + settings.launchAtLogin = true + settings.hasCompletedOnboarding = true + + let data = try JSONEncoder().encode(settings) + let decoded = try JSONDecoder().decode(AppSettings.self, from: data) + #expect(decoded == settings) + #expect(decoded.settingsVersion == AppSettings.currentVersion) + } + + @Test func v0MigrationFillsDefaultsAndIgnoresUnknownKeys() throws { + let json = """ + { + "settingsVersion": 0, + "endpoint": "http://127.0.0.1:11434", + "targetLanguage": "de", + "autoCopy": true, + "unknownFutureKey": "ignored" + } + """ + let decoded = try JSONDecoder().decode(AppSettings.self, from: Data(json.utf8)) + #expect(decoded.settingsVersion == AppSettings.currentVersion) + #expect(decoded.targetLanguage == "de") + #expect(decoded.model == HyMT3ModelPreset.defaultModel) + #expect(!decoded.autoCopy) + } + + @Test func fastModelCanBeClearedExplicitly() throws { + var settings = AppSettings() + settings.fastModel = nil + let encoded = try JSONEncoder().encode(settings) + let decoded = try JSONDecoder().decode(AppSettings.self, from: encoded) + #expect(decoded.fastModel == nil) + + let nullJSON = try JSONDecoder().decode( + AppSettings.self, + from: Data(#"{"settingsVersion":1,"fastModel":null}"#.utf8) + ) + #expect(nullJSON.fastModel == nil) + } + + @Test func invalidValuesAreClampedOrReset() throws { + let json = """ + { + "settingsVersion": 0, + "doubleCopyWindowMs": 10, + "maxCharactersLatin": 1, + "maxCharactersCJK": 99999, + "numCtx": 1, + "numPredict": 99999, + "temperature": 9, + "topP": -1, + "topK": 0, + "repeatPenalty": 9, + "keepModelLoaded": "forever", + "targetLanguage": "xx" + } + """ + 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.numCtx == 1024) + #expect(decoded.numPredict == 8192) + #expect(decoded.temperature == 2) + #expect(decoded.topP == 0) + #expect(decoded.topK == 1) + #expect(decoded.repeatPenalty == 2) + #expect(decoded.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive) + #expect(HyMT3Languages.resolve(decoded.targetLanguage) != nil) + } + + @Test func sanitizeClampsValuesEditedInTheUI() { + var settings = AppSettings() + settings.doubleCopyWindowMs = 10 + settings.temperature = 9 + settings.topP = -1 + settings.topK = 0 + settings.keepModelLoaded = "forever" + settings.autoCopy = true + settings.targetLanguage = "xx" + settings.sanitize() + + #expect(settings.doubleCopyWindowMs == 300) + #expect(settings.temperature == 2) + #expect(settings.topP == 0) + #expect(settings.topK == 1) + #expect(settings.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive) + #expect(!settings.autoCopy) + #expect(HyMT3Languages.resolve(settings.targetLanguage) != nil) + } + + @Test func endpointPolicyIsEnforced() throws { + var settings = AppSettings() + settings.endpoint = try #require(URL(string: "http://192.168.1.10:11434")) + #expect(throws: EndpointRejection.remoteNotAllowed) { + try settings.validatedEndpoint() + } + + settings.allowRemoteEndpoint = true + #expect(throws: EndpointRejection.remoteRequiresHTTPS) { + try settings.validatedEndpoint() + } + + settings.endpoint = try #require(URL(string: "https://ollama.example.com")) + #expect(try settings.validatedEndpoint() == settings.endpoint) + } + + @Test func recentTargetsAreUniqueAndCappedAtThree() throws { + var settings = AppSettings() + settings.noteTarget(HyMT3Languages.german) + settings.noteTarget(HyMT3Languages.english) + settings.noteTarget(HyMT3Languages.german) + try settings.noteTarget(#require(HyMT3Languages.resolve("fr"))) + try settings.noteTarget(#require(HyMT3Languages.resolve("es"))) + + #expect(settings.recentTargetLanguages.count == 3) + #expect(settings.recentTargetLanguages == ["es", "fr", "de"]) + #expect(settings.targetLanguage == "es") + } +} + +@Suite("Settings store") +struct SettingsStoreTests { + private func makeStore() -> (SettingsStore, InMemorySettingsDataStore) { + let data = InMemorySettingsDataStore() + return (SettingsStore(storage: data), data) + } + + @Test func saveUpdatesTheCache() throws { + let (store, _) = makeStore() + var settings = AppSettings() + settings.targetLanguage = "de" + try store.save(settings) + #expect(store.current() == settings) + } + + @Test func valuesSurviveANewStoreOverTheSameBackend() throws { + let data = InMemorySettingsDataStore() + var settings = AppSettings() + settings.targetLanguage = "fr" + settings.hasCompletedOnboarding = true + try SettingsStore(storage: data).save(settings) + + let reloaded = SettingsStore(storage: data).current() + #expect(reloaded.targetLanguage == "fr") + #expect(reloaded.hasCompletedOnboarding) + } + + @Test func corruptOrUnknownDataFallsBackSafely() { + let data = InMemorySettingsDataStore() + data.set(Data("not json".utf8), forKey: SettingsStore.storageKey) + let store = SettingsStore(storage: data) + #expect(store.current() == AppSettings()) + + let unknown = Data(#"{"settingsVersion":1,"unknown":"x"}"#.utf8) + data.set(unknown, forKey: SettingsStore.storageKey) + let migrated = SettingsStore(storage: data).current() + #expect(migrated.settingsVersion == AppSettings.currentVersion) + } + + @Test func updateAndReset() throws { + let (store, data) = makeStore() + try store.update { $0.targetLanguage = "de" } + #expect(store.current().targetLanguage == "de") + + _ = store.reset() + #expect(store.current().targetLanguage == AppSettings().targetLanguage) + #expect(data.data(forKey: SettingsStore.storageKey) == nil) + } +} diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMessageTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMessageTests.swift new file mode 100644 index 0000000..6270e5a --- /dev/null +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMessageTests.swift @@ -0,0 +1,62 @@ +import Foundation +import SprachmittlerOllama +import Testing +@testable import SprachmittlerCore + +@Suite("User-facing errors") +struct ErrorMessageTests { + @Test func everyErrorHasAMessageAndARecoveryAction() throws { + let url = try #require(URL(string: "http://127.0.0.1:11434")) + let errors: [SprachmittlerError] = [ + .noSelection, + .emptyText, + .textTooLong(characters: 5000, limit: 4000), + .pasteboardUnavailable, + .ollamaUnreachable(url: url), + .ollamaTooOld(found: "0.1", required: "0.40"), + .endpointRejected(reason: .remoteNotAllowed), + .modelNotInstalled(model: "m"), + .noAdapter(model: "m"), + .badRequest(message: "raw body"), + .server(status: 500, message: "raw body"), + .timeout(phase: .firstToken), + .emptyOutput, + .truncated, + .repetitionLoop, + .preambleDetected, + .protectedTokenLost(token: "https://example.com"), + .accessibilityNotTrusted, + .accessibilityUnsupported(app: "App"), + .insertionTargetChanged, + .pasteboardRestoreFailed, + .cancelled, + ] + + for error in errors { + #expect(!error.userMessage.isEmpty) + #expect(!error.userMessage.contains("raw body")) + _ = error.recoveryAction + } + #expect(SprachmittlerError.ollamaUnreachable(url: url).recoveryAction == .startOllama) + #expect(SprachmittlerError.accessibilityNotTrusted.recoveryAction == .openSettings) + } +} + +@Suite("Diagnostics store") +struct DiagnosticsStoreTests { + @Test func keepsTheLastFiftyEventsAndClears() async { + let store = DiagnosticsStore(clock: { Date(timeIntervalSince1970: 0) }) + for index in 0 ..< 60 { + await store.record(kind: "event-\(index)", durationMs: index, detail: "code") + } + let events = await store.snapshot() + #expect(events.count == DiagnosticsStore.capacity) + #expect(events.first?.kind == "event-10") + #expect(events.last?.kind == "event-59") + #expect(events.allSatisfy { $0.detail == "code" }) + + await store.clear() + let cleared = await store.snapshot() + #expect(cleared.isEmpty) + } +} diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/OnboardingAndSettingsTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/OnboardingAndSettingsTests.swift new file mode 100644 index 0000000..e6d6502 --- /dev/null +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/OnboardingAndSettingsTests.swift @@ -0,0 +1,169 @@ +import Foundation +import SprachmittlerEngines +import SprachmittlerOllama +import SprachmittlerTestSupport +import Testing +@testable import SprachmittlerCore + +@Suite("Onboarding") +@MainActor +struct OnboardingViewModelTests { + private let hyModel = InstalledModel(name: "hy-mt3", model: "hy-mt3", digest: "abc") + + @Test func refreshReportsOllamaAndModel() async { + let store = SettingsStore(storage: InMemorySettingsDataStore()) + let catalog = FakeOllamaCatalog(version: "0.40.18", models: [hyModel]) + let access = FakeAccessibilityPermission(isTrusted: false) + let model = OnboardingViewModel( + settingsStore: store, + catalogProvider: { _ in catalog }, + accessibility: access + ) + + await model.refresh() + #expect(model.ollama == .ok("0.40.18")) + #expect(model.model == .ok("hy-mt3")) + #expect(!model.accessibilityTrusted) + #expect(!model.isChecking) + } + + @Test func missingModelIsAFailedCheck() async { + let store = SettingsStore(storage: InMemorySettingsDataStore()) + let other = InstalledModel(name: "llama3", model: "llama3", digest: "x") + let model = OnboardingViewModel( + settingsStore: store, + catalogProvider: { _ in FakeOllamaCatalog(models: [other]) }, + accessibility: FakeAccessibilityPermission() + ) + + await model.refresh() + guard case let .failed(message) = model.model else { + Issue.record("expected a failed model check") + return + } + #expect(message.contains("not installed")) + } + + @Test func unreachableOllamaIsAFailedCheck() async { + let store = SettingsStore(storage: InMemorySettingsDataStore()) + let model = OnboardingViewModel( + settingsStore: store, + catalogProvider: { _ in throw FailingCatalog() }, + accessibility: FakeAccessibilityPermission() + ) + + await model.refresh() + guard case let .failed(message) = model.ollama else { + Issue.record("expected a failed Ollama check") + return + } + #expect(!message.isEmpty) + } + + @Test func targetAndCompletionArePersisted() throws { + let store = SettingsStore(storage: InMemorySettingsDataStore()) + let model = OnboardingViewModel( + settingsStore: store, + catalogProvider: { _ in FakeOllamaCatalog() }, + accessibility: FakeAccessibilityPermission() + ) + model.setTarget(HyMT3Languages.german) + try model.complete() + + #expect(store.current().targetLanguage == "de") + #expect(store.current().hasCompletedOnboarding) + } +} + +@Suite("Settings view model") +@MainActor +struct SettingsViewModelTests { + private let hyModel = InstalledModel(name: "hy-mt3", model: "hy-mt3", digest: "abc") + + @Test func saveValidatesEndpointPersistsAndUpdatesLoginItem() { + let store = SettingsStore(storage: InMemorySettingsDataStore()) + let launch = FakeLaunchAtLogin() + let model = SettingsViewModel( + store: store, + catalogProvider: { _ in FakeOllamaCatalog() }, + launchAtLogin: launch + ) + model.draft.targetLanguage = "de" + model.draft.launchAtLogin = true + model.save() + + #expect(model.saveError == nil) + #expect(store.current().targetLanguage == "de") + #expect(launch.requestedValues == [true]) + } + + @Test func invalidRemoteEndpointIsBlocked() throws { + let store = SettingsStore(storage: InMemorySettingsDataStore()) + let model = SettingsViewModel( + store: store, + catalogProvider: { _ in FakeOllamaCatalog() }, + launchAtLogin: FakeLaunchAtLogin() + ) + model.draft.endpoint = try #require(URL(string: "http://192.168.1.10:11434")) + model.draft.allowRemoteEndpoint = false + model.save() + + #expect(model.saveError?.contains("remote") == true) + #expect(store.current().endpoint == AppSettings.defaultEndpoint) + } + + @Test func resetRestoresDefaultsAndDisablesLoginItem() { + let store = SettingsStore(storage: InMemorySettingsDataStore()) + let launch = FakeLaunchAtLogin(isEnabled: true) + let model = SettingsViewModel( + store: store, + catalogProvider: { _ in FakeOllamaCatalog() }, + launchAtLogin: launch + ) + model.draft.targetLanguage = "de" + model.save() + model.reset() + + #expect(store.current() == AppSettings()) + #expect(launch.requestedValues.last == false) + } + + @Test func refreshModelsFiltersToHyMT3() async { + let other = InstalledModel(name: "llama3", model: "llama3", digest: "x") + let model = SettingsViewModel( + store: SettingsStore(storage: InMemorySettingsDataStore()), + catalogProvider: { _ in FakeOllamaCatalog(models: [hyModel, other]) }, + launchAtLogin: FakeLaunchAtLogin() + ) + await model.refreshModels() + #expect(model.installedModels.map(\.name) == ["hy-mt3"]) + #expect(model.modelChoices.contains("hy-mt3")) + } +} + +private struct FailingCatalog: OllamaCatalog, Error { + private var unreachable: OllamaError { + let url = URLComponents(string: "http://127.0.0.1:11434")?.url ?? URL(fileURLWithPath: "/") + return .unreachable(url) + } + + func serverVersion() async throws -> String { + throw unreachable + } + + func installedModels() async throws -> [InstalledModel] { + throw unreachable + } + + func show(model: String) async throws -> ModelDetails { + throw OllamaError.modelNotInstalled(model) + } + + func loadedModels() async throws -> [LoadedModel] { + [] + } + + func refresh() async {} + + func checkMinimumVersion() async throws {} +} diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift new file mode 100644 index 0000000..c1100c6 --- /dev/null +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift @@ -0,0 +1,273 @@ +import Foundation +import SprachmittlerEngines +import Testing +@testable import SprachmittlerCore + +@Suite("Panel view model") +@MainActor +struct PanelViewModelTests { + private let captured = CapturedText( + text: "Hello.", + capturedAt: Date(timeIntervalSince1970: 0), + source: .doubleCopy + ) + + @Test func streamsIntoThePanelAndCopyKeepsItOpen() async { + let (panel, copies, _) = makePanel( + streaming: ImmediateStreaming(deltas: ["Hal", "lo"], result: makeResult("Hallo")) + ) + await panel.begin(captured) + await waitFor { panel.phase == .ready } + + #expect(panel.translation == "Hallo") + #expect(panel.canCopy) + #expect(!panel.didCopy) + + panel.copyTranslation() + #expect(panel.didCopy) + #expect(copies.text == "Hallo") + #expect(panel.phase == .ready) + } + + @Test func blockingWarningsDisableReplace() async { + let replaceBox = ReplaceBox() + let (panel, _, _) = makePanel( + streaming: ImmediateStreaming( + deltas: ["Hallo"], + result: makeResult("Hallo", warnings: [.truncated]) + ), + replacement: { + replaceBox.called = true + return .replaced(using: .accessibility) + } + ) + await panel.begin(captured) + await waitFor { panel.phase == .ready } + + #expect(panel.blockingWarnings.contains(.truncated)) + #expect(!panel.canReplace) + await panel.replaceSelection() + #expect(!replaceBox.called) + } + + @Test func cleanResultEnablesReplaceAndClosesOnSuccess() async { + let closeBox = CloseBox() + let (panel, _, _) = makePanel( + streaming: ImmediateStreaming(deltas: ["Hallo"], result: makeResult("Hallo")), + replacement: { .replaced(using: .accessibility) }, + onClose: { closeBox.closed = true } + ) + await panel.begin(captured) + await waitFor { panel.phase == .ready } + + #expect(panel.canReplace) + await panel.replaceSelection() + #expect(closeBox.closed) + } + + @Test func sameLanguageWarningCanBeDismissed() async { + let warning = TranslationWarning.sameLanguage(source: "de", target: "de") + let (panel, _, _) = makePanel( + streaming: ImmediateStreaming( + deltas: ["Hallo"], + result: makeResult("Hallo", warnings: [warning]) + ) + ) + await panel.begin(captured) + await waitFor { panel.phase == .ready } + + #expect(panel.sameLanguageWarning == warning) + panel.dismissSameLanguageWarning() + #expect(panel.sameLanguageWarning == nil) + } + + @Test func changingTargetRetranslatesAndNotifies() async { + let streaming = EchoStreaming() + let (panel, _, targets) = makePanel(streaming: streaming) + await panel.begin(captured) + await waitFor { panel.phase == .ready } + #expect(panel.translation == "de") + + await panel.setTarget(HyMT3Languages.english) + await waitFor { panel.phase == .ready && panel.translation == "en" } + + #expect(panel.configuration.target == HyMT3Languages.english) + #expect(targets.codes == ["en"]) + #expect(await streaming.callCount == 2) + } + + @Test func retryUsesTheLastCapture() async { + let streaming = CountingStreaming(result: makeResult("Hallo")) + let (panel, _, _) = makePanel(streaming: streaming) + await panel.begin(captured) + await waitFor { panel.phase == .ready } + + await panel.retry() + for _ in 0 ..< 1000 { + if await streaming.callCount == 2 { + break + } + await Task.yield() + } + await waitFor { panel.phase == .ready } + + #expect(panel.translation == "Hallo") + #expect(await streaming.callCount == 2) + } + + @Test func failureShowsAUserMessage() async { + let error = SprachmittlerError.modelNotInstalled(model: "m") + let (panel, _, _) = makePanel(streaming: FailingStreaming(error: error)) + await panel.begin(captured) + await waitFor { panel.phase == .failed } + + #expect(panel.error == error) + #expect(panel.errorMessage == error.userMessage) + #expect(panel.recoveryAction == .pullModel("m")) + } + + @Test func closeClearsStateAndCancels() async { + let (panel, _, _) = makePanel( + streaming: ImmediateStreaming(deltas: ["Hallo"], result: makeResult("Hallo")) + ) + await panel.begin(captured) + await waitFor { panel.phase == .ready } + + await panel.close() + #expect(panel.phase == .idle) + #expect(panel.source == nil) + #expect(panel.translation.isEmpty) + #expect(panel.warnings.isEmpty) + } + + // The helper returns the panel and two small test captures; a struct would add noise here. + // swiftlint:disable large_tuple + private func makePanel( + streaming: any TranslationStreaming, + replacement: (@MainActor () async -> InsertionOutcome)? = nil, + onClose: @escaping @MainActor () -> Void = {} + ) -> (PanelViewModel, CopiedTextBox, TargetBox) { + let session = TranslationSession(pipelineFactory: { streaming }) + let copies = CopiedTextBox() + let targets = TargetBox() + let panel = PanelViewModel( + session: session, + configuration: PanelConfiguration( + target: HyMT3Languages.german, + model: "test-hy-mt3", + keepAlive: "30m" + ), + copy: { copies.text = $0 }, + replace: replacement, + onCloseRequest: onClose, + onTargetChanged: { targets.codes.append($0.code) } + ) + panel.startObserving() + return (panel, copies, targets) + } + + // swiftlint:enable large_tuple + + private func waitFor(_ condition: @MainActor () -> Bool) async { + for _ in 0 ..< 10000 { + if condition() { + return + } + await Task.yield() + } + Issue.record("panel condition was not reached") + } + + private func makeResult( + _ translation: String, + warnings: [TranslationWarning] = [] + ) -> PipelineResult { + PipelineResult( + translation: translation, + warnings: warnings, + sourceLanguage: "en", + timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4), + chunkCount: 1 + ) + } +} + +private struct ImmediateStreaming: TranslationStreaming { + let deltas: [String] + let result: PipelineResult + + func translate( + _ request: TranslationSessionRequest, + onDelta: (@Sendable (String) async -> Void)? + ) async throws -> PipelineResult { + for delta in deltas { + await onDelta?(delta) + } + return result + } +} + +private struct FailingStreaming: TranslationStreaming { + let error: SprachmittlerError + + func translate( + _ request: TranslationSessionRequest, + onDelta: (@Sendable (String) async -> Void)? + ) async throws -> PipelineResult { + throw error + } +} + +private actor EchoStreaming: TranslationStreaming { + private(set) var callCount = 0 + + func translate( + _ request: TranslationSessionRequest, + onDelta: (@Sendable (String) async -> Void)? + ) async throws -> PipelineResult { + callCount += 1 + let result = PipelineResult( + translation: request.target.code, + warnings: [], + sourceLanguage: "en", + timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4), + chunkCount: 1 + ) + await onDelta?(result.translation) + return result + } +} + +private actor CountingStreaming: TranslationStreaming { + private(set) var callCount = 0 + let result: PipelineResult + + init(result: PipelineResult) { + self.result = result + } + + func translate( + _ request: TranslationSessionRequest, + onDelta: (@Sendable (String) async -> Void)? + ) async throws -> PipelineResult { + callCount += 1 + await onDelta?(result.translation) + return result + } +} + +private final class CopiedTextBox: @unchecked Sendable { + var text: String? +} + +private final class TargetBox: @unchecked Sendable { + var codes: [String] = [] +} + +private final class ReplaceBox: @unchecked Sendable { + var called = false +} + +private final class CloseBox: @unchecked Sendable { + var closed = false +} diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift index 40aab2e..8185153 100644 --- a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift @@ -50,6 +50,48 @@ struct TranslationPipelineTests { #expect(chat.recorded[1].messages.first?.content.contains("Second paragraph.") == true) } + @Test func streamedTextIncludesChunkSeparators() 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) + ) + let result = try await pipeline.translate( + text: "First paragraph.\n\nSecond paragraph.", + target: german, + model: model, + keepAlive: "30m", + onDelta: { await collector.append($0) } + ) + + #expect(await collector.text == result.translation) + #expect(await collector.text == "Erster Absatz.\n\nZweiter Absatz.") + } + + @Test func retryDoesNotStreamBothAttempts() async throws { + let chat = SequencedChat(responses: [ + [.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)], + [.delta("Öffne https://example.com jetzt."), .done(reason: "stop", metrics: .empty)], + ]) + let collector = DeltaCollector() + let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9)) + let result = try await pipeline.translate( + text: "Open https://example.com now.", + target: german, + model: model, + keepAlive: "30m", + onDelta: { await collector.append($0) } + ) + + #expect(await collector.text == "Öffne jetzt.") + #expect(result.translation == "Öffne https://example.com jetzt.") + } + @Test func retriesOnceWithTheDocumentedDelimitersPrompt() async throws { let chat = SequencedChat(responses: [ [.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)], @@ -182,6 +224,14 @@ private struct FixedDetector: LanguageDetecting { } } +private actor DeltaCollector { + private(set) var text = "" + + func append(_ delta: String) { + text += delta + } +} + private struct FailingChat: OllamaChatting { let error: OllamaError diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift new file mode 100644 index 0000000..e27f5b3 --- /dev/null +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift @@ -0,0 +1,248 @@ +import Foundation +import SprachmittlerEngines +import SprachmittlerOllama +import SprachmittlerText +import Testing +@testable import SprachmittlerCore + +@Suite("Translation session") +struct TranslationSessionTests { + private let request = TranslationSessionRequest( + captured: CapturedText(text: "Hello.", capturedAt: Date(timeIntervalSince1970: 0), source: .doubleCopy), + target: HyMT3Languages.german, + model: "test-hy-mt3", + keepAlive: "30m" + ) + + @Test func streamsThenFinishes() async { + let streaming = ScriptedStreaming() + let session = TranslationSession(pipelineFactory: { streaming }) + var iterator = await session.events().makeAsyncIterator() + + await session.start(request) + let started = await iterator.next() + guard case let .started(epoch, _) = started else { + Issue.record("expected started") + return + } + #expect(await streaming.waitForCalls(1)) + await streaming.release( + call: 0, + outcome: .success(deltas: ["Hal", "lo"], result: result("Hallo")) + ) + + var deltas: [String] = [] + var finished = false + while let event = await iterator.next() { + switch event { + case let .delta(eventEpoch, text) where eventEpoch == epoch: + deltas.append(text) + case let .finished(eventEpoch, pipelineResult) where eventEpoch == epoch: + #expect(pipelineResult.translation == "Hallo") + finished = true + default: + break + } + if finished { + break + } + } + #expect(deltas == ["Hal", "lo"]) + #expect(finished) + } + + @Test func newTriggerDropsLateEventsFromTheOldEpoch() async { + let streaming = ScriptedStreaming() + let session = TranslationSession(pipelineFactory: { streaming }) + var iterator = await session.events().makeAsyncIterator() + + await session.start(request) + _ = await iterator.next() // started A + #expect(await streaming.waitForCalls(1)) + + let second = TranslationSessionRequest( + captured: CapturedText(text: "Second.", capturedAt: Date(), source: .menu), + target: HyMT3Languages.german, + model: "test-hy-mt3", + keepAlive: "30m" + ) + await session.start(second) + _ = await iterator.next() // started B + + await streaming.release(call: 0, outcome: .success(deltas: ["old"], result: result("Old"))) + #expect(await streaming.waitForCalls(2)) + await streaming.release(call: 1, outcome: .success(deltas: ["new"], result: result("New"))) + + var sawOnlyNew = true + var finished = false + while let event = await iterator.next() { + switch event { + case let .delta(_, text): + if text == "old" { + sawOnlyNew = false + } + case let .finished(_, pipelineResult): + if pipelineResult.translation == "New" { + finished = true + } + default: + break + } + if finished { + break + } + } + #expect(sawOnlyNew) + #expect(finished) + } + + @Test func explicitCancelEmitsCancelledForTheOldEpoch() async { + let streaming = ScriptedStreaming() + let session = TranslationSession(pipelineFactory: { streaming }) + var iterator = await session.events().makeAsyncIterator() + + let epoch = await session.start(request) + _ = await iterator.next() // started + await session.cancel() + let event = await iterator.next() + #expect(event == .cancelled(epoch: epoch)) + } + + @Test func failuresAreScopedToTheCurrentEpoch() async { + let streaming = ScriptedStreaming() + let session = TranslationSession(pipelineFactory: { streaming }) + var iterator = await session.events().makeAsyncIterator() + + let epoch = await session.start(request) + _ = await iterator.next() + #expect(await streaming.waitForCalls(1)) + await streaming.release(call: 0, outcome: .failure(.modelNotInstalled(model: "m"))) + + let event = await iterator.next() + #expect(event == .failed(epoch: epoch, error: .modelNotInstalled(model: "m"))) + } + + @Test func emptyCaptureFailsBeforeTheFactory() async { + let streaming = ScriptedStreaming() + let session = TranslationSession(pipelineFactory: { streaming }) + var iterator = await session.events().makeAsyncIterator() + let empty = TranslationSessionRequest( + captured: CapturedText(text: " ", capturedAt: Date(), source: .doubleCopy), + target: HyMT3Languages.german, + model: "test-hy-mt3", + keepAlive: "30m" + ) + + let epoch = await session.start(empty) + _ = await iterator.next() + let event = await iterator.next() + #expect(event == .failed(epoch: epoch, error: .emptyText)) + #expect(await streaming.callCount == 0) + } + + @Test func pipelineFactoryErrorsBecomeDomainFailures() async { + let session = TranslationSession(pipelineFactory: { + throw SprachmittlerError.endpointRejected(reason: .remoteNotAllowed) + }) + var iterator = await session.events().makeAsyncIterator() + + let epoch = await session.start(request) + _ = await iterator.next() + let event = await iterator.next() + #expect(event == .failed(epoch: epoch, error: .endpointRejected(reason: .remoteNotAllowed))) + } + + @Test func factoryTransportErrorsAreMapped() async throws { + let url = try #require(URL(string: "http://127.0.0.1:9")) + let session = TranslationSession(pipelineFactory: { + throw OllamaError.unreachable(url) + }) + var iterator = await session.events().makeAsyncIterator() + + let epoch = await session.start(request) + _ = await iterator.next() + let event = await iterator.next() + #expect(event == .failed(epoch: epoch, error: .ollamaUnreachable(url: url))) + } + + private func result(_ translation: String, warnings: [TranslationWarning] = []) -> PipelineResult { + PipelineResult( + translation: translation, + warnings: warnings, + sourceLanguage: "en", + timing: TranslationTiming(firstTokenMs: 1, totalMs: 2, promptTokens: 3, outputTokens: 4), + chunkCount: 1 + ) + } +} + +/// A controlled streaming fake. Each call waits until the test releases its outcome. +private actor ScriptedStreaming: TranslationStreaming { + enum Outcome: Sendable { + case success(deltas: [String], result: PipelineResult) + case failure(SprachmittlerError) + } + + private var requests: [TranslationSessionRequest] = [] + private var waiters: [Int: CheckedContinuation] = [:] + private var outcomes: [Int: Outcome] = [:] + + var callCount: Int { + requests.count + } + + func translate( + _ request: TranslationSessionRequest, + onDelta: (@Sendable (String) async -> Void)? + ) async throws -> PipelineResult { + let index = requests.count + requests.append(request) + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + if outcomes[index] != nil { + continuation.resume() + } else { + waiters[index] = continuation + } + } + } onCancel: { + Task { await self.cancel(index) } + } + + guard let outcome = outcomes.removeValue(forKey: index) else { + throw CancellationError() + } + switch outcome { + case let .success(deltas, result): + for delta in deltas { + await onDelta?(delta) + } + return result + case let .failure(error): + throw error + } + } + + func release(call index: Int, outcome: Outcome) { + outcomes[index] = outcome + if let waiter = waiters.removeValue(forKey: index) { + waiter.resume() + } + } + + func waitForCalls(_ count: Int) async -> Bool { + for _ in 0 ..< 10000 { + if requests.count >= count { + return true + } + await Task.yield() + } + return false + } + + private func cancel(_ index: Int) { + if let waiter = waiters.removeValue(forKey: index) { + waiter.resume(throwing: CancellationError()) + } + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f82ca11..5c1176e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -516,7 +516,7 @@ If the detected source language equals the target with reasonable confidence, th ## 10. Translation session and state machine -`TranslationSession` is an actor in `SprachmittlerCore`; `PanelViewModel` is `@MainActor @Observable` and mirrors it. +`TranslationSession` is an actor in `SprachmittlerCore`; `PanelViewModel` is `@MainActor @Observable` in Core and mirrors it. The App target owns the non-activating `NSPanel` controller. ```mermaid stateDiagram-v2 @@ -540,7 +540,7 @@ stateDiagram-v2 - Every session has an epoch (`UInt64`). A new trigger increments it; events from an older epoch are ignored. - `Copy` never changes the session state; it writes the clipboard and keeps the panel open. - `Replace` is disabled while `.translating` or `.failed`, and when validation found a blocking warning. -- The session owns no disk state. It releases source and translation when the panel closes. +- The session owns no disk state. Its working copy is released when the panel closes; `AppEnvironment` may keep the last source, translation and insertion target in memory until quit, solely for the status menu's Copy/Replace Last actions (ADR-007). Nothing is written to disk. --- @@ -571,6 +571,7 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour | `model` | String | `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` (provisional until T7.4) | | `fastModel` | String? | `hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M` (if installed) | | `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 | @@ -587,6 +588,7 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour | `showSourcePreview` | Bool | true | | `launchAtLogin` | Bool | false | | `keepRecentTranslationInMemory` | Bool | true (cleared on quit; no disk) | +| `hasCompletedOnboarding` | Bool | false | | `settingsVersion` | Int | 1 | Never store source text, translations, pasteboard contents or app names in settings. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 7918b19..c38ed66 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -129,3 +129,17 @@ Status: Accepted Context: Double copy, clipboard snapshot/restore and Services all touch `NSPasteboard`, but the state machine and watcher need deterministic tests without real time or the user's clipboard. The Services path must work with no Accessibility permission. Decision: `SprachmittlerCapture` defines `PasteboardAccessing` and `PasteboardTicking`. `SystemPasteboard` is the only production `NSPasteboard` user; `FakePasteboard` and `ManualPasteboardTicker` live in `SprachmittlerTestSupport`. `DoubleCopyDetector` is a pure state machine over change events and an injected date. `PasteboardWatcher` polls every 120 ms, reads the string only after `changeCount` changes, suppresses own/transient changes for 750 ms, and enforces the 4000/2000 limit. `ServicesProvider` receives the system pasteboard and needs no polling or Accessibility. `AppDelegate` installs it and calls `NSUpdateDynamicServices`. Consequences: Capture logic is unit-testable and no global key tap is needed. The Services and double-copy paths both produce `CapturedText`. The 10-app compatibility matrix remains a manual task. + +## ADR-019 — AX first, paste fallback, target re-verified at Replace +Status: Accepted + +Context: Replace must be safe and reversible, but Accessibility support differs by app. AX calls can block, so they must stay off the main actor. Tests need deterministic insertion without a real app or clipboard. +Decision: `InsertionCoordinator` lives in `SprachmittlerCapture` and uses `AccessibilityTextEditing` and `EventPosting` seams. At trigger time the app captures the frontmost PID/bundle and, when trusted, reads only the focused selection; at Replace it re-verifies the frontmost app and the selected text (`InsertionPolicy`). It refuses secure fields and its own PID. AX direct replacement is tried first; if unsupported, it snapshots the clipboard, writes the translation with own/transient markers, posts ⌘V to the target PID, waits up to 300 ms and restores only when `changeCount` still matches the write. Blocking warnings disable Replace; failures keep the panel open and offer Copy. +Consequences: Most apps use the no-clipboard AX path; the fallback preserves the previous clipboard in the common case. Manual testing is still required because AX support and paste delivery are app-specific. + +## ADR-020 — UI state models in Core, AppKit controllers in App +Status: Accepted + +Context: Panel, Settings, Onboarding and Diagnostics contain branching worth testing, but their windows are AppKit/SwiftUI. The app target must stay thin. +Decision: `PanelViewModel`, `SettingsViewModel`, `OnboardingViewModel` and `DiagnosticsViewModel` are `@MainActor @Observable` types in `SprachmittlerCore`; `SettingsStore` uses a `SettingsDataStoring` seam. `App` owns only `NSPanel`/`NSWindow` controllers, SwiftUI views, the composition root (`AppEnvironment`) and lifecycle glue. `TranslationSession` uses an injected pipeline factory so endpoint/settings changes apply on the next request without rebuilding the UI. +Consequences: Logic is covered by package tests; AppKit remains untested by `make verify` and requires the manual checklist. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 0e09b3d..4677115 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -37,26 +37,26 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain) - [~] T3.5 Manual double-copy matrix — 2026-11-26 · code complete; 10-app matrix needs a person ## M4 — Translation session and panel -- [ ] T4.1 TranslationSession actor and epochs -- [ ] T4.2 Panel controller and view model -- [ ] T4.3 Panel view with Copy and Replace -- [ ] T4.4 Target language, persistence, same-language -- [ ] T4.5 Error messages and recovery actions -- [ ] T4.6 Panel keyboard and accessibility +- [x] T4.1 TranslationSession actor and epochs — 2026-11-26 +- [~] T4.2 Panel controller and view model — 2026-11-26 · code/test complete; manual focus/position pending +- [~] T4.3 Panel view with Copy and Replace — 2026-11-26 · code complete; manual streaming/Copy/Replace pending +- [x] T4.4 Target language, persistence, same-language — 2026-11-26 +- [x] T4.5 Error messages and recovery actions — 2026-11-26 +- [~] T4.6 Panel keyboard and accessibility — 2026-11-26 · shortcuts/labels in code; VoiceOver manual pending ## M5 — Replace -- [ ] T5.1 InsertionCoordinator and target capture -- [ ] T5.2 Accessibility direct replacement -- [ ] T5.3 Paste fallback and clipboard restore -- [ ] T5.4 Safety checks and Copy fallback -- [ ] T5.5 Manual insertion matrix and permission onboarding +- [x] T5.1 InsertionCoordinator and target capture — 2026-11-26 +- [x] T5.2 Accessibility direct replacement — 2026-11-26 +- [x] T5.3 Paste fallback and clipboard restore — 2026-11-26 +- [x] T5.4 Safety checks and Copy fallback — 2026-11-26 +- [~] T5.5 Manual insertion matrix and permission onboarding — 2026-11-26 · 10-app matrix needs a person ## M6 — Settings, onboarding, menu bar -- [ ] T6.1 AppSettings and persistence -- [ ] T6.2 Onboarding checks and window -- [ ] T6.3 Settings UI -- [ ] T6.4 Status menu, launch at login, diagnostics -- [ ] T6.5 End-to-end integration checkpoint (gate) +- [x] T6.1 AppSettings and persistence — 2026-11-26 +- [~] T6.2 Onboarding checks and window — 2026-11-26 · code complete; manual checks pending +- [~] T6.3 Settings UI — 2026-11-26 · code complete; manual endpoint/licence checks pending +- [~] T6.4 Status menu, launch at login, diagnostics — 2026-11-26 · code complete; manual login/diagnostics checks pending +- [~] T6.5 End-to-end integration checkpoint (gate) — 2026-11-26 · needs the user's manual 10-app pass ## M7 — Evaluation and the default-model gate - [ ] T7.1 Corpus manifest and eval CLI @@ -120,3 +120,21 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain) 2026-11-26 · T3.4 · Added `ServicesProvider` and wired `NSApp.servicesProvider` + `NSUpdateDynamicServices`; the menu-bar “Translate Clipboard Text” item now delivers a `.menu` capture. The app has a log-only sink until the M4 panel. 2026-11-26 · M3 · The capture matrix (T3.5) is intentionally still unchecked; it needs a person in 10 real apps. No Accessibility is requested on the double-copy or Services path. 2026-11-26 · M2/M3 · Review fixes: `OllamaError` is mapped to `SprachmittlerError` at the Core boundary and the CLI maps domain errors to exit 2/3/4; the chunker preserves leading empty separators; `LanguageMatching` moved to Engines and `keepAlive` is supplied by the composition root; `CapturePolicy` enforces the 4000/2000 limit and own markers for menu/Services; golden prompt tests remove exactly one fixture terminator; docs aligned (TestSupport deps, warning enum, 15 common targets, Fixtures path). +2026-11-26 · T4.1 · Added `TranslationSession` actor with epochs, one in-flight task, delta forwarding, cancellation and stale-event dropping; tests cover streaming, replacement, cancel and factory failures. +2026-11-26 · T4.2 · Added `PanelViewModel` in Core and a non-activating `NSPanel` controller in the app; the panel positions near the mouse and never calls `NSApp.activate`. +2026-11-26 · T4.3 · Added the SwiftUI panel: source preview, streaming translation, warning/error banners, Copy, Retry, Replace, close; Replace is disabled while translating and for blocking warnings. +2026-11-26 · T4.4 · Added searchable language picker, recent targets, target persistence and retranslation on change; same-language advisory with “Translate anyway”. +2026-11-26 · T4.5 · Added `SprachmittlerError.userMessage`, `RecoveryAction` and an exhaustive test; raw server/model text is never shown. +2026-11-26 · T4.6 · Added Esc, ⌘C, ⌘↩, ⌘R, ⌘, paths and accessibility labels; VoiceOver verification remains manual. +2026-11-26 · T5.1 · Target provider captures the frontmost PID/bundle at trigger and reads only the focused selection when Accessibility is trusted; the coordinator verifies the target again at Replace. +2026-11-26 · T5.2 · Added `AXTextEditor` (focused element, selected text, secure-field check, direct set) behind a testable protocol; AX work runs on an actor, never the main actor. +2026-11-26 · T5.3 · Added `CGEventPoster` ⌘V to the target PID, full snapshot/write/restore and a 300 ms settle; own writes suppress the watcher. +2026-11-26 · T5.4 · Added `InsertionPolicy` frontmost/selection checks, secure-field refusal, self-insertion refusal, blocking-warning gate and Copy fallback. +2026-11-26 · T5.5 · The insertion matrix and real-app permission flow remain manual; unit/component tests cover the strategies and failure paths. +2026-11-26 · T6.1 · Added versioned `AppSettings` with v0 migration, clamping, unknown-key tolerance, recent targets, `SettingsStore` over a UserDefaults seam and reset. +2026-11-26 · T6.2 · Added onboarding for Ollama/version, Hy-MT3 install, target and optional Accessibility, with fix actions; first-run and menu reopen wired. +2026-11-26 · T6.3 · Added General/Model/Translation/Privacy/Diagnostics tabs, endpoint validation, model/digest/licence display and reset. +2026-11-26 · T6.4 · Added the status menu (translate, target, copy/replace last, setup, diagnostics, about, settings, quit), launch-at-login via `SMAppService`, and a text-free diagnostics window. +2026-11-26 · T6.5 · The end-to-end gate is ready to run but not marked complete: it needs the user's manual double-copy → panel → Copy/Replace pass. +2026-11-26 · M4/M5/M6 smoke · Launched the Debug app and sent two identical clipboard copies; the non-activating panel appeared on screen without a crash. Full focus, Copy/Replace, VoiceOver, onboarding and 10-app matrices remain manual. +2026-11-26 · M4/M5/M6 review · Cleared the previous translation when a new capture arrives (menu Replace cannot pair old text with a new selection); restored the clipboard on cancelled/failed paste; reset the panel before showing a new capture; mapped blocked Replace to the real warning; mapped endpoint/transport errors in onboarding and settings; surfaced launch-item errors; moved Fast-model detection to Engines; suppressed retry deltas and streamed chunk separators; made settings updates atomic and fastModel nullable; fixed refresh endpoint validation; localized warning strings; used the captured selection for an early safety check; the event observer now sees only current-epoch events and only a validated `.ready` result can become the status-menu last translation; insertion-target enrichment is generation-guarded. `make verify` green. diff --git a/docs/SELECTION_AND_CLIPBOARD.md b/docs/SELECTION_AND_CLIPBOARD.md index fcd6cb6..f76a28a 100644 --- a/docs/SELECTION_AND_CLIPBOARD.md +++ b/docs/SELECTION_AND_CLIPBOARD.md @@ -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 are implemented and covered by component tests (`DoubleCopyDetector`, `PasteboardWatcher`, `ClipboardSnapshot`, `ServicesProvider`). The 4000/2000 limit and own-marker check apply to double copy, the menu item and Services (`CapturePolicy`). The matrix below is still untested; it is the T3.5 manual task. +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. For each app test: diff --git a/docs/TESTING.md b/docs/TESTING.md index f4af82c..724df19 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -68,6 +68,9 @@ Evaluation: - [ ] Translate Markdown and JSON: keys/formatting survive. - [ ] Change the target language while streaming: the old request is cancelled and the new one starts. - [ ] Services ▸ Translate with Sprachmittler works without Accessibility. +- [ ] Settings: an invalid remote `http://` endpoint is blocked; reset restores defaults; model/digest/licence are shown. +- [ ] Onboarding reopens from the menu; Ollama stopped, model missing and Accessibility denied each show a fix action. +- [ ] Launch at login follows `SMAppService`; Diagnostics shows versions, digests, timings and error kinds but no text. - [ ] VoiceOver can operate the panel and Settings; every action has a keyboard path. - [ ] Console.app shows no selected text, translation, pasteboard content, app name or path. - [ ] Quit during a translation: no orphaned request; `ollama ps` shows no hanging request.