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
@@ -0,0 +1,331 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import SprachmittlerEngines
|
||||
|
||||
/// The panel phase from `docs/ARCHITECTURE.md` §10.
|
||||
public enum PanelPhase: Sendable, Equatable {
|
||||
/// Nothing captured.
|
||||
case idle
|
||||
/// A request is queued or running.
|
||||
case translating
|
||||
/// Deltas are arriving.
|
||||
case streaming
|
||||
/// A validated translation is ready.
|
||||
case ready
|
||||
/// The request failed.
|
||||
case failed
|
||||
}
|
||||
|
||||
/// The settings snapshot used by the panel for one translation.
|
||||
public struct PanelConfiguration: Sendable, Equatable {
|
||||
/// The selected target language.
|
||||
public var target: ModelLanguage
|
||||
/// The selected model tag.
|
||||
public var model: String
|
||||
/// The Ollama keep-alive value.
|
||||
public var keepAlive: String
|
||||
/// The sampling values.
|
||||
public var sampling: SamplingOptions
|
||||
/// Whether to show the source preview.
|
||||
public var showSourcePreview: Bool
|
||||
/// Recent targets, most recent first.
|
||||
public var recentTargets: [ModelLanguage]
|
||||
|
||||
/// Creates a configuration.
|
||||
public init(
|
||||
target: ModelLanguage,
|
||||
model: String,
|
||||
keepAlive: String,
|
||||
sampling: SamplingOptions = .publisherDefault,
|
||||
showSourcePreview: Bool = true,
|
||||
recentTargets: [ModelLanguage] = []
|
||||
) {
|
||||
self.target = target
|
||||
self.model = model
|
||||
self.keepAlive = keepAlive
|
||||
self.sampling = sampling
|
||||
self.showSourcePreview = showSourcePreview
|
||||
self.recentTargets = recentTargets
|
||||
}
|
||||
}
|
||||
|
||||
/// The panel presentation model. It mirrors `TranslationSession` and owns no disk state.
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class PanelViewModel {
|
||||
/// The current phase.
|
||||
public private(set) var phase: PanelPhase = .idle
|
||||
/// The captured source.
|
||||
public private(set) var source: CapturedText?
|
||||
/// The streamed and final translation.
|
||||
public private(set) var translation = ""
|
||||
/// Validation warnings for the current result.
|
||||
public private(set) var warnings: [TranslationWarning] = []
|
||||
/// The current error, if any.
|
||||
public private(set) var error: SprachmittlerError?
|
||||
/// The last timing.
|
||||
public private(set) var timing: TranslationTiming?
|
||||
/// The advisory source language code.
|
||||
public private(set) var sourceLanguage: String?
|
||||
/// True after a successful Copy.
|
||||
public private(set) var didCopy = false
|
||||
/// True while a Replace action is running.
|
||||
public private(set) var isReplacing = false
|
||||
/// The current target, model and prompt settings.
|
||||
public private(set) var configuration: PanelConfiguration
|
||||
/// True after the user dismisses the same-language advisory.
|
||||
public private(set) var sameLanguageDismissed = false
|
||||
|
||||
/// The copy action. The composition root writes with own-write markers.
|
||||
public let copy: @MainActor (String) -> Void
|
||||
/// The optional Replace action; nil until the insertion module is available.
|
||||
public let replace: (@MainActor () async -> InsertionOutcome)?
|
||||
/// Called when a successful Replace should close the panel.
|
||||
public let onCloseRequest: @MainActor () -> Void
|
||||
/// Called with every session event for diagnostics.
|
||||
public let eventObserver: (@MainActor (TranslationSessionEvent) -> Void)?
|
||||
/// Called when the user changes the target from the panel.
|
||||
public let onTargetChanged: @MainActor (ModelLanguage) -> Void
|
||||
|
||||
private let session: TranslationSession
|
||||
private var eventTask: Task<Void, Never>?
|
||||
private var currentEpoch: UInt64 = 0
|
||||
private var lastCaptured: CapturedText?
|
||||
|
||||
/// Creates a panel model.
|
||||
public init(
|
||||
session: TranslationSession,
|
||||
configuration: PanelConfiguration,
|
||||
copy: @escaping @MainActor (String) -> Void,
|
||||
replace: (@MainActor () async -> InsertionOutcome)? = nil,
|
||||
onCloseRequest: @escaping @MainActor () -> Void = {},
|
||||
eventObserver: (@MainActor (TranslationSessionEvent) -> Void)? = nil,
|
||||
onTargetChanged: @escaping @MainActor (ModelLanguage) -> Void = { _ in }
|
||||
) {
|
||||
self.session = session
|
||||
self.configuration = configuration
|
||||
self.copy = copy
|
||||
self.replace = replace
|
||||
self.onCloseRequest = onCloseRequest
|
||||
self.eventObserver = eventObserver
|
||||
self.onTargetChanged = onTargetChanged
|
||||
}
|
||||
|
||||
/// Starts consuming session events. Call once after init.
|
||||
public func startObserving() {
|
||||
guard eventTask == nil else { return }
|
||||
let session = session
|
||||
eventTask = Task { [weak self] in
|
||||
for await event in await session.events() {
|
||||
guard let self else { return }
|
||||
handle(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True when Copy can write the current translation.
|
||||
public var canCopy: Bool {
|
||||
!translation.isEmpty && (phase == .ready || phase == .failed)
|
||||
}
|
||||
|
||||
/// True when Replace is safe and the insertion module is available.
|
||||
public var canReplace: Bool {
|
||||
phase == .ready
|
||||
&& !isReplacing
|
||||
&& !warnings.contains(where: \.blocksReplacement)
|
||||
&& replace != nil
|
||||
}
|
||||
|
||||
/// The replacement is unavailable until M5 in this build.
|
||||
public var replaceUnavailableReason: String? {
|
||||
replace == nil ? "Replace is not available." : nil
|
||||
}
|
||||
|
||||
/// Warnings that disable Replace.
|
||||
public var blockingWarnings: [TranslationWarning] {
|
||||
warnings.filter(\.blocksReplacement)
|
||||
}
|
||||
|
||||
/// The same-language advisory, if present and not dismissed.
|
||||
public var sameLanguageWarning: TranslationWarning? {
|
||||
guard !sameLanguageDismissed else { return nil }
|
||||
return warnings.first { warning in
|
||||
if case .sameLanguage = warning {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The user-facing error message.
|
||||
public var errorMessage: String? {
|
||||
error?.userMessage
|
||||
}
|
||||
|
||||
/// The error's recovery action.
|
||||
public var recoveryAction: RecoveryAction? {
|
||||
error?.recoveryAction
|
||||
}
|
||||
|
||||
/// Synchronously resets the visible state before the panel is shown.
|
||||
public func prepare(_ captured: CapturedText) {
|
||||
currentEpoch = 0
|
||||
lastCaptured = captured
|
||||
source = captured
|
||||
translation = ""
|
||||
warnings = []
|
||||
error = nil
|
||||
timing = nil
|
||||
sourceLanguage = nil
|
||||
didCopy = false
|
||||
isReplacing = false
|
||||
sameLanguageDismissed = false
|
||||
phase = .translating
|
||||
}
|
||||
|
||||
/// Starts a translation for a captured text.
|
||||
public func begin(_ captured: CapturedText) async {
|
||||
prepare(captured)
|
||||
_ = await session.start(request(for: captured))
|
||||
}
|
||||
|
||||
/// Retries the last captured text.
|
||||
public func retry() async {
|
||||
guard let lastCaptured else { return }
|
||||
await begin(lastCaptured)
|
||||
}
|
||||
|
||||
/// Retranslates after an external target change.
|
||||
public func retranslate() async {
|
||||
guard let lastCaptured else { return }
|
||||
await begin(lastCaptured)
|
||||
}
|
||||
|
||||
/// Shows a capture-time error such as a too-long selection.
|
||||
public func showError(_ error: SprachmittlerError, source: CapturedText? = nil) {
|
||||
currentEpoch = 0
|
||||
Task { await session.reset() }
|
||||
phase = .failed
|
||||
self.error = error
|
||||
self.source = source
|
||||
translation = ""
|
||||
warnings = []
|
||||
timing = nil
|
||||
sourceLanguage = nil
|
||||
}
|
||||
|
||||
/// Changes the target and retranslates the current selection.
|
||||
public func setTarget(_ language: ModelLanguage) async {
|
||||
guard language.code != configuration.target.code else { return }
|
||||
configuration.target = language
|
||||
onTargetChanged(language)
|
||||
if let lastCaptured {
|
||||
await begin(lastCaptured)
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies the translation and keeps the panel open (R023).
|
||||
public func copyTranslation() {
|
||||
guard canCopy else { return }
|
||||
copy(translation)
|
||||
didCopy = true
|
||||
}
|
||||
|
||||
/// Runs the optional Replace action.
|
||||
public func replaceSelection() async {
|
||||
guard canReplace, let replace else { return }
|
||||
isReplacing = true
|
||||
let outcome = await replace()
|
||||
isReplacing = false
|
||||
switch outcome {
|
||||
case .replaced:
|
||||
onCloseRequest()
|
||||
case .copiedOnly:
|
||||
break
|
||||
case let .failed(insertionError):
|
||||
error = insertionError
|
||||
phase = .failed
|
||||
}
|
||||
}
|
||||
|
||||
/// Dismisses the same-language advisory; translation stays available.
|
||||
public func dismissSameLanguageWarning() {
|
||||
sameLanguageDismissed = true
|
||||
}
|
||||
|
||||
/// Updates the settings snapshot without restarting the current request.
|
||||
public func updateConfiguration(_ configuration: PanelConfiguration) {
|
||||
self.configuration = configuration
|
||||
}
|
||||
|
||||
/// Resets the panel and cancels the active request. The event stream stays open.
|
||||
public func close() async {
|
||||
await session.reset()
|
||||
phase = .idle
|
||||
source = nil
|
||||
translation = ""
|
||||
warnings = []
|
||||
error = nil
|
||||
timing = nil
|
||||
sourceLanguage = nil
|
||||
didCopy = false
|
||||
isReplacing = false
|
||||
sameLanguageDismissed = false
|
||||
lastCaptured = nil
|
||||
}
|
||||
|
||||
/// Stops the event consumer for app termination.
|
||||
public func shutdown() {
|
||||
eventTask?.cancel()
|
||||
eventTask = nil
|
||||
}
|
||||
|
||||
private func request(for captured: CapturedText) -> TranslationSessionRequest {
|
||||
TranslationSessionRequest(
|
||||
captured: captured,
|
||||
target: configuration.target,
|
||||
model: configuration.model,
|
||||
keepAlive: configuration.keepAlive,
|
||||
sampling: configuration.sampling
|
||||
)
|
||||
}
|
||||
|
||||
private func handle(_ event: TranslationSessionEvent) {
|
||||
switch event {
|
||||
case let .started(epoch, request):
|
||||
currentEpoch = epoch
|
||||
source = request.captured
|
||||
configuration.target = request.target
|
||||
translation = ""
|
||||
warnings = []
|
||||
error = nil
|
||||
phase = .translating
|
||||
case let .delta(epoch, text):
|
||||
guard epoch == currentEpoch else { return }
|
||||
translation += text
|
||||
phase = .streaming
|
||||
case let .finished(epoch, result):
|
||||
guard epoch == currentEpoch else { return }
|
||||
translation = result.translation
|
||||
warnings = result.warnings
|
||||
timing = result.timing
|
||||
sourceLanguage = result.sourceLanguage
|
||||
if result.warnings.contains(.emptyOutput) {
|
||||
error = .emptyOutput
|
||||
phase = .failed
|
||||
} else {
|
||||
phase = .ready
|
||||
}
|
||||
case let .failed(epoch, failure):
|
||||
guard epoch == currentEpoch else { return }
|
||||
error = failure
|
||||
phase = .failed
|
||||
case let .cancelled(epoch):
|
||||
guard epoch == currentEpoch else { return }
|
||||
phase = .idle
|
||||
error = nil
|
||||
}
|
||||
eventObserver?(event)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user