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

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

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

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

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

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

No files matched your search

+84 -12
View File
@@ -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
)
}
}
+355 -14
View File
@@ -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")
}
}
}
}
+95
View File
@@ -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)
}
}
+21
View File
@@ -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()
}
}
}
+8
View File
@@ -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
}
+68
View File
@@ -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")
}
}
+231
View File
@@ -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)
}
}
+55
View File
@@ -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)
}
}
}
+75
View File
@@ -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)
}
}
+300
View File
@@ -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"))
}
}
}
+291
View File
@@ -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()
}
}
+10 -20
View File
@@ -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() }
)
}
}
}