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:
1 parent
64078e2f04
commit
a78572adc3
47 files changed
+4963
-79
No files matched your search
+355
-14
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user