Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

feat(dictionary): train corrections inline

altic-dev9988f2c07c56
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 4291f5ee..48c016f2 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -240,7 +240,6 @@ struct ContentView: View {
@State private var selectedSidebarItem: SidebarItem?
@State private var previousSidebarItem: SidebarItem? = nil // Track previous for mode transitions
- @State private var pendingDictionaryTrainingPrefill: DictionaryTrainingPrefill?
@State private var playgroundUsed: Bool = SettingsStore.shared.playgroundUsed
@State private var recordingAppInfo: (name: String, bundleId: String, windowTitle: String)? = nil
@State private var recordingPrecedingText: String = ""
@@ -1013,9 +1012,6 @@ struct ContentView: View {
self.selectedSidebarItem = .aiEnhancements
case .history:
self.selectedSidebarItem = .history
- case let .customDictionaryTraining(prefill):
- self.pendingDictionaryTrainingPrefill = prefill
- self.selectedSidebarItem = .customDictionary
}
}
@@ -1312,12 +1308,7 @@ struct ContentView: View {
case .meetingTools:
return AnyView(self.meetingToolsView)
case .customDictionary:
- return AnyView(CustomDictionaryView(
- trainingPrefill: self.pendingDictionaryTrainingPrefill,
- onTrainingPrefillConsumed: {
- self.pendingDictionaryTrainingPrefill = nil
- }
- ))
+ return AnyView(CustomDictionaryView())
case .stats:
return AnyView(self.statsView)
case .feedback:
@@ -3535,6 +3526,12 @@ struct ContentView: View {
private func handleCancelShortcut() -> Bool {
var handled = false
+ if DictionaryCorrectionOverlayController.shared.isPresented {
+ DebugLogger.shared.debug("Cancel shortcut: closing dictionary suggestion", source: "ContentView")
+ DictionaryCorrectionOverlayController.shared.hide()
+ return true
+ }
+
if NotchOverlayManager.shared.isCommandOutputExpanded {
DebugLogger.shared.debug("Cancel shortcut: closing expanded command notch", source: "ContentView")
NotchOverlayManager.shared.hideExpandedCommandOutput()
diff --git a/Sources/Fluid/Services/AppNavigationRouter.swift b/Sources/Fluid/Services/AppNavigationRouter.swift
index c3d65c94..bd131303 100644
--- a/Sources/Fluid/Services/AppNavigationRouter.swift
+++ b/Sources/Fluid/Services/AppNavigationRouter.swift
@@ -1,15 +1,8 @@
import Foundation
-struct DictionaryTrainingPrefill: Equatable, Identifiable {
- let id = UUID()
- let intendedText: String
- let capturedVariants: [String]
-}
-
enum AppNavigationDestination {
case aiEnhancements
case history
- case customDictionaryTraining(DictionaryTrainingPrefill)
}
@MainActor
@@ -17,19 +10,11 @@ final class AppNavigationRouter {
static let shared = AppNavigationRouter()
private var pendingDestination: AppNavigationDestination?
- private var presentMainWindow: (() -> Void)?
private init() {}
- func configureWindowPresenter(_ presenter: @escaping () -> Void) {
- self.presentMainWindow = presenter
- }
-
- func request(_ destination: AppNavigationDestination, presentsMainWindow: Bool = false) {
+ func request(_ destination: AppNavigationDestination) {
self.pendingDestination = destination
- if presentsMainWindow {
- self.presentMainWindow?()
- }
NotificationCenter.default.post(name: .appNavigationRequested, object: nil)
}
diff --git a/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift b/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
index 4c8a7e5e..8f33d5d8 100644
--- a/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
+++ b/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
@@ -491,16 +491,7 @@ final class AutomaticDictionaryCorrectionTracker {
self.stopObservation()
guard let candidate, !self.isAlreadySaved(candidate) else { return }
- DictionaryCorrectionOverlayController.shared.show(candidate: candidate) {
- let prefill = DictionaryTrainingPrefill(
- intendedText: candidate.correctedText,
- capturedVariants: [candidate.heardText]
- )
- AppNavigationRouter.shared.request(
- .customDictionaryTraining(prefill),
- presentsMainWindow: true
- )
- }
+ DictionaryCorrectionOverlayController.shared.show(candidate: candidate)
}
private func isAlreadySaved(_ candidate: AutomaticDictionaryCorrectionCandidate) -> Bool {
diff --git a/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift b/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
new file mode 100644
index 00000000..bb5b409c
--- /dev/null
+++ b/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
@@ -0,0 +1,340 @@
+import AppKit
+import Combine
+import Foundation
+
+@MainActor
+final class AutomaticDictionaryTrainingSession: ObservableObject {
+ enum Screen: Equatable {
+ case choice
+ case training
+ case success
+ }
+
+ enum CapturePhase: Equatable {
+ case idle
+ case starting
+ case recording
+ case processing
+ }
+
+ let candidate: AutomaticDictionaryCorrectionCandidate
+
+ @Published private(set) var screen: Screen = .choice
+ @Published private(set) var capturePhase: CapturePhase = .idle
+ @Published private(set) var variants: [String]
+ @Published private(set) var sampleCount = 0
+ @Published private(set) var lastOutput = ""
+ @Published private(set) var lastOutputIsCovered = false
+ @Published private(set) var consecutiveCoveredCaptures = 0
+ @Published private(set) var statusMessage = ""
+ @Published private(set) var hasError = false
+ @Published private(set) var successTitle = "Added to Dictionary"
+
+ var onInteraction: (() -> Void)?
+ var onSuccess: (() -> Void)?
+
+ private let asr: ASRService
+ private var stopRequestedDuringStart = false
+ private var didStartAudioCapture = false
+ private var discardCurrentCapture = false
+ private var isCancelled = false
+ private var stopTask: Task<Void, Never>?
+
+ init(candidate: AutomaticDictionaryCorrectionCandidate, asr: ASRService) {
+ self.candidate = candidate
+ self.asr = asr
+
+ let replacement = CustomDictionaryTrainingMerge.normalizedReplacement(candidate.correctedText)
+ let savedVariants = SettingsStore.shared.customDictionaryEntries
+ .filter { $0.replacement.caseInsensitiveCompare(replacement) == .orderedSame }
+ .flatMap(\.triggers)
+ self.variants = CustomDictionaryTrainingMerge.normalizedTriggers(
+ from: savedVariants + [candidate.heardText],
+ intendedReplacement: replacement
+ )
+ }
+
+ var intendedText: String {
+ CustomDictionaryTrainingMerge.normalizedReplacement(self.candidate.correctedText)
+ }
+
+ var readinessProgress: Int {
+ guard self.lastOutputIsCovered else { return 0 }
+ return min(self.consecutiveCoveredCaptures, CustomDictionaryTrainingMerge.readyCoveredCount)
+ }
+
+ var readinessFraction: Double {
+ Double(self.readinessProgress) / Double(CustomDictionaryTrainingMerge.readyCoveredCount)
+ }
+
+ var isReady: Bool {
+ self.readinessProgress >= CustomDictionaryTrainingMerge.readyCoveredCount
+ }
+
+ var finalOutputText: String {
+ guard !self.lastOutput.isEmpty else { return "Record to check" }
+ return self.lastOutputIsCovered ? self.intendedText : self.lastOutput
+ }
+
+ var canSave: Bool {
+ !self.variants.isEmpty && self.capturePhase == .idle
+ }
+
+ var canUseRecordButton: Bool {
+ switch self.capturePhase {
+ case .starting:
+ return !self.stopRequestedDuringStart
+ case .recording:
+ return true
+ case .processing:
+ return false
+ case .idle:
+ return !self.asr.isRunning && self.sampleCount < CustomDictionaryTrainingMerge.maxSamples
+ }
+ }
+
+ var recordButtonIsStop: Bool {
+ self.capturePhase == .starting || self.capturePhase == .recording
+ }
+
+ var recordButtonTitle: String {
+ switch self.capturePhase {
+ case .starting:
+ return self.stopRequestedDuringStart ? "Stopping..." : "Stop"
+ case .recording:
+ return "Stop"
+ case .processing:
+ return "Checking..."
+ case .idle:
+ return "Record"
+ }
+ }
+
+ var trainingHeadline: String {
+ if self.isReady {
+ return "FluidVoice understands you"
+ }
+ return self.sampleCount == 0 ? "Say it naturally" : "Say it again"
+ }
+
+ var trainingDetail: String {
+ if self.isReady {
+ return "You can add it now, or keep trying."
+ }
+ if self.sampleCount >= CustomDictionaryTrainingMerge.maxSamples {
+ return "Maximum samples reached. Add the replacement when ready."
+ }
+ return "Keep going until FluidVoice understands you 3 times in a row."
+ }
+
+ func beginTraining() {
+ guard self.screen == .choice else { return }
+ self.onInteraction?()
+ self.screen = .training
+ self.statusMessage = ""
+ self.hasError = false
+ }
+
+ func returnToChoice() {
+ guard self.screen == .training, self.capturePhase == .idle else { return }
+ self.onInteraction?()
+ self.screen = .choice
+ }
+
+ func toggleCapture() {
+ self.onInteraction?()
+ switch self.capturePhase {
+ case .idle:
+ Task { await self.startCapture() }
+ case .starting, .recording:
+ Task { await self.stopCapture() }
+ case .processing:
+ break
+ }
+ }
+
+ func addOnlyCorrection() {
+ self.persist(triggers: [self.candidate.heardText])
+ }
+
+ func addTrainedReplacement() {
+ guard self.canSave else { return }
+ self.persist(triggers: self.variants)
+ }
+
+ func removeVariant(_ variant: String) {
+ guard self.capturePhase == .idle else { return }
+ self.onInteraction?()
+ self.variants.removeAll { $0.caseInsensitiveCompare(variant) == .orderedSame }
+ self.refreshCoverageAfterVariantRemoval()
+ }
+
+ func cancel() {
+ self.isCancelled = true
+ self.discardCurrentCapture = true
+ switch self.capturePhase {
+ case .starting:
+ self.stopRequestedDuringStart = true
+ case .recording:
+ self.stopTask?.cancel()
+ self.stopTask = Task { await self.finishCapture() }
+ case .idle, .processing:
+ break
+ }
+ }
+
+ private func startCapture() async {
+ guard self.capturePhase == .idle,
+ !self.asr.isRunning,
+ self.sampleCount < CustomDictionaryTrainingMerge.maxSamples
+ else {
+ return
+ }
+
+ self.stopRequestedDuringStart = false
+ self.didStartAudioCapture = false
+ self.discardCurrentCapture = false
+ self.capturePhase = .starting
+ self.hasError = false
+ self.statusMessage = "Starting..."
+
+ await self.asr.start(forDictionaryTraining: true) { [weak self] in
+ guard let self else { return }
+ self.didStartAudioCapture = true
+ self.capturePhase = .recording
+ if self.stopRequestedDuringStart || self.isCancelled {
+ self.statusMessage = "Stopping..."
+ self.stopTask?.cancel()
+ self.stopTask = Task { await self.finishCapture() }
+ } else {
+ self.statusMessage = "Listening..."
+ }
+ }
+ guard self.asr.isRunning else {
+ self.capturePhase = .idle
+ self.stopRequestedDuringStart = false
+ guard !self.didStartAudioCapture else { return }
+ guard !self.isCancelled else { return }
+ self.hasError = true
+ self.statusMessage = "Couldn't start recording. Check microphone access and try again."
+ return
+ }
+
+ if self.stopRequestedDuringStart || self.isCancelled {
+ await self.finishCapture()
+ return
+ }
+
+ if self.capturePhase == .starting {
+ self.capturePhase = .recording
+ self.statusMessage = "Listening..."
+ }
+ }
+
+ private func stopCapture() async {
+ switch self.capturePhase {
+ case .starting:
+ self.stopRequestedDuringStart = true
+ self.statusMessage = "Stopping..."
+ case .recording:
+ await self.finishCapture()
+ case .idle, .processing:
+ break
+ }
+ }
+
+ private func finishCapture() async {
+ guard self.capturePhase == .recording || self.capturePhase == .starting else { return }
+ self.capturePhase = .processing
+ self.stopRequestedDuringStart = false
+ self.hasError = false
+ self.statusMessage = "Checking..."
+
+ let transcript = await self.asr.stop(forDictionaryTraining: true)
+ let shouldDiscard = self.discardCurrentCapture || self.isCancelled
+ self.capturePhase = .idle
+ self.discardCurrentCapture = false
+ guard !shouldDiscard else { return }
+ self.addTrainingVariant(from: transcript)
+ }
+
+ private func addTrainingVariant(from transcript: String) {
+ guard let detected = CustomDictionaryTrainingMerge.normalizedTrigger(transcript) else {
+ self.lastOutput = ""
+ self.lastOutputIsCovered = false
+ self.consecutiveCoveredCaptures = 0
+ self.hasError = true
+ self.statusMessage = "Nothing heard. Try again."
+ return
+ }
+
+ self.lastOutput = detected
+ self.sampleCount = min(self.sampleCount + 1, CustomDictionaryTrainingMerge.maxSamples)
+
+ let matchesReplacement = detected.caseInsensitiveCompare(self.intendedText) == .orderedSame
+ let isCaptured = self.variants.contains { $0.caseInsensitiveCompare(detected) == .orderedSame }
+ if matchesReplacement || isCaptured {
+ self.lastOutputIsCovered = true
+ self.consecutiveCoveredCaptures += 1
+ self.hasError = false
+ self.statusMessage = self.isReady ? "Ready to add." : "Understood. Try again."
+ return
+ }
+
+ guard self.variants.count < CustomDictionaryTrainingMerge.maxSamples else {
+ self.lastOutputIsCovered = false
+ self.consecutiveCoveredCaptures = 0
+ self.hasError = false
+ self.statusMessage = "Maximum samples reached."
+ return
+ }
+
+ self.variants.append(detected)
+ self.lastOutputIsCovered = false
+ self.consecutiveCoveredCaptures = 0
+ self.hasError = false
+ self.statusMessage = "New pronunciation captured."
+ }
+
+ private func refreshCoverageAfterVariantRemoval() {
+ guard !self.lastOutput.isEmpty else { return }
+ let matchesReplacement = self.lastOutput.caseInsensitiveCompare(self.intendedText) == .orderedSame
+ let isCaptured = self.variants.contains { $0.caseInsensitiveCompare(self.lastOutput) == .orderedSame }
+ self.lastOutputIsCovered = matchesReplacement || isCaptured
+ if !self.lastOutputIsCovered {
+ self.consecutiveCoveredCaptures = 0
+ }
+ }
+
+ private func persist(triggers: [String]) {
+ guard !self.isCancelled else { return }
+ self.onInteraction?()
+ let currentEntries = SettingsStore.shared.customDictionaryEntries
+ let updatedExisting = currentEntries.contains {
+ $0.replacement.caseInsensitiveCompare(self.intendedText) == .orderedSame
+ }
+ let mergedEntries = CustomDictionaryTrainingMerge.mergedEntries(
+ current: currentEntries,
+ replacement: self.intendedText,
+ triggers: triggers
+ )
+ guard mergedEntries != currentEntries else {
+ self.completeSave(title: "Already in Dictionary")
+ return
+ }
+
+ SettingsStore.shared.customDictionaryEntries = mergedEntries
+ ASRService.invalidateDictionaryCache()
+ NotificationCenter.default.post(name: .parakeetVocabularyDidChange, object: nil)
+ self.completeSave(title: updatedExisting ? "Dictionary Updated" : "Added to Dictionary")
+ }
+
+ private func completeSave(title: String) {
+ NSHapticFeedbackManager.defaultPerformer.perform(.levelChange, performanceTime: .now)
+ self.successTitle = title
+ self.screen = .success
+ self.hasError = false
+ self.statusMessage = ""
+ self.onSuccess?()
+ }
+}
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index 63dea037..6621b54e 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -56,14 +56,6 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
/// Subscription for forwarding audio levels to expanded command notch
private var expandedModeAudioSubscription: AnyCancellable?
- override init() {
- super.init()
- AppNavigationRouter.shared.configureWindowPresenter { [weak self] in
- self?.openMainWindow()
- }
- // Don't setup menu bar immediately - defer until app is ready
- }
-
func initializeMenuBar() {
guard !self.isSetup else { return }
@@ -108,6 +100,18 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
private func handleOverlayState(isRunning: Bool, asrService: ASRService) {
self.overlayBench("handle_state isRunning=\(isRunning) overlayVisible=\(self.overlayVisible) processing=\(self.isProcessingActive) mode=\(self.currentOverlayMode.rawValue)")
+ // Dictionary training owns its recording controls, so showing the
+ // regular dictation notch here would create two competing overlays.
+ if asrService.isDictionaryTrainingCaptureActive {
+ self.pendingShowOperation?.cancel()
+ self.pendingShowOperation = nil
+ if self.overlayVisible {
+ self.overlayVisible = false
+ NotchOverlayManager.shared.hide()
+ }
+ return
+ }
+
// Don't hide the overlay while AI processing is active.
// Without this, the notch can disappear during the short "Refining..." phase because
// `isRunning` becomes false before post-processing completes.
diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swift
index c3b69dc1..719f3388 100644
--- a/Sources/Fluid/UI/CustomDictionaryView.swift
+++ b/Sources/Fluid/UI/CustomDictionaryView.swift
@@ -15,9 +15,6 @@ struct CustomDictionaryView: View {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@EnvironmentObject private var appServices: AppServices
- private let trainingPrefill: DictionaryTrainingPrefill?
- private let onTrainingPrefillConsumed: () -> Void
-
private var asr: ASRService { self.appServices.asr }
@State private var entries: [SettingsStore.CustomDictionaryEntry] = SettingsStore.shared.customDictionaryEntries
@@ -62,17 +59,6 @@ struct CustomDictionaryView: View {
@State private var editingPunctuationRuleID: UUID?
@State private var punctuationAliasesText = ""
@State private var punctuationSymbolText = ""
- @State private var appliedTrainingPrefillID: UUID?
- @State private var programmaticTrainingReplacementKey: String?
-
- init(
- trainingPrefill: DictionaryTrainingPrefill? = nil,
- onTrainingPrefillConsumed: @escaping () -> Void = {}
- ) {
- self.trainingPrefill = trainingPrefill
- self.onTrainingPrefillConsumed = onTrainingPrefillConsumed
- }
-
private var normalizedTrainingReplacement: String {
self.trainingReplacement.trimmingCharacters(in: .whitespacesAndNewlines)
}
@@ -305,13 +291,13 @@ struct CustomDictionaryView: View {
}
}
.onAppear {
+ self.entries = SettingsStore.shared.customDictionaryEntries
self.loadBoostTerms()
self.automaticDictionaryLearningEnabled = SettingsStore.shared.automaticDictionaryLearningEnabled
self.punctuationAutoConvertEnabled = SettingsStore.shared.autoConvertPunctuationEnabled
- self.applyTrainingPrefillIfNeeded()
}
- .onChange(of: self.trainingPrefill?.id) { _, _ in
- self.applyTrainingPrefillIfNeeded()
+ .onReceive(NotificationCenter.default.publisher(for: .parakeetVocabularyDidChange)) { _ in
+ self.entries = SettingsStore.shared.customDictionaryEntries
}
.onDisappear {
guard self.isTrainingRecording else { return }
@@ -1607,40 +1593,6 @@ struct CustomDictionaryView: View {
self.composerMode = mode
}
- private func applyTrainingPrefillIfNeeded() {
- guard let trainingPrefill,
- self.appliedTrainingPrefillID != trainingPrefill.id
- else {
- return
- }
-
- let intendedText = CustomDictionaryTrainingMerge.normalizedReplacement(trainingPrefill.intendedText)
- let savedVariants = SettingsStore.shared.customDictionaryEntries
- .filter { $0.replacement.caseInsensitiveCompare(intendedText) == .orderedSame }
- .flatMap(\.triggers)
- let variants = CustomDictionaryTrainingMerge.normalizedTriggers(
- from: savedVariants + trainingPrefill.capturedVariants,
- intendedReplacement: intendedText
- )
-
- self.appliedTrainingPrefillID = trainingPrefill.id
- self.composerMode = .train
- self.programmaticTrainingReplacementKey = intendedText.lowercased()
- self.trainingReplacement = intendedText
- self.trainingVariants = variants
- self.trainingSampleCount = 0
- self.lastTrainingOutput = ""
- self.lastTrainingOutputIsCovered = false
- self.consecutiveCoveredCaptures = 0
- self.trainingStatusMessage = variants.isEmpty ? "" : "Correction loaded."
- self.trainingHasError = false
- self.isTrainingActive = !intendedText.isEmpty
-
- DispatchQueue.main.async {
- self.onTrainingPrefillConsumed()
- }
- }
-
private func addManualReplacementIfValid() {
guard self.canAddManualReplacement else { return }
let entry = SettingsStore.CustomDictionaryEntry(
@@ -2003,12 +1955,6 @@ struct CustomDictionaryView: View {
private func handleTrainingReplacementChange(oldValue: String, newValue: String) {
let oldKey = CustomDictionaryTrainingMerge.normalizedReplacement(oldValue).lowercased()
let newKey = CustomDictionaryTrainingMerge.normalizedReplacement(newValue).lowercased()
- if let programmaticKey = self.programmaticTrainingReplacementKey {
- self.programmaticTrainingReplacementKey = nil
- if newKey == programmaticKey {
- return
- }
- }
guard oldKey != newKey else { return }
self.trainingVariants = self.existingTrainingVariants(for: newValue)
diff --git a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
index b8caee29..02281178 100644
--- a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
+++ b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
@@ -1,4 +1,6 @@
import AppKit
+import Combine
+import QuartzCore
import SwiftUI
@MainActor
@@ -6,31 +8,44 @@ final class DictionaryCorrectionOverlayController {
static let shared = DictionaryCorrectionOverlayController()
private static let displayDurationNanoseconds: UInt64 = 5_000_000_000
+ private static let successDurationNanoseconds: UInt64 = 1_400_000_000
private static let presentationDuration: TimeInterval = 0.05
private static let dismissalDuration: TimeInterval = 0.05
private var panel: NSPanel?
private var hostingView: NSHostingView<AutomaticDictionaryCorrectionOverlayView>?
+ private var session: AutomaticDictionaryTrainingSession?
+ private var sessionCancellable: AnyCancellable?
private var dismissTask: Task<Void, Never>?
private var generation: UInt64 = 0
private init() {}
- func show(
- candidate: AutomaticDictionaryCorrectionCandidate,
- onTrain: @escaping () -> Void
- ) {
+ var isPresented: Bool {
+ self.panel?.isVisible == true
+ }
+
+ func show(candidate: AutomaticDictionaryCorrectionCandidate) {
self.generation &+= 1
let currentGeneration = self.generation
self.dismissTask?.cancel()
+ self.session?.cancel()
- let rootView = AutomaticDictionaryCorrectionOverlayView(
+ let session = AutomaticDictionaryTrainingSession(
candidate: candidate,
+ asr: AppServices.shared.asr
+ )
+ session.onInteraction = { [weak self] in
+ self?.keepVisible()
+ }
+ session.onSuccess = { [weak self] in
+ self?.scheduleSuccessDismissal()
+ }
+ self.session = session
+
+ let rootView = AutomaticDictionaryCorrectionOverlayView(
+ session: session,
displayDuration: Double(Self.displayDurationNanoseconds) / 1_000_000_000,
- onTrain: { [weak self] in
- self?.hide()
- onTrain()
- },
onDismiss: { [weak self] in
self?.hide()
}
@@ -42,12 +57,16 @@ final class DictionaryCorrectionOverlayController {
self.createPanel(rootView: rootView)
}
- guard let panel = self.panel, let hostingView = self.hostingView else { return }
- let fittingSize = hostingView.fittingSize
- hostingView.frame = NSRect(origin: .zero, size: fittingSize)
- panel.setContentSize(fittingSize)
- self.position(panel)
+ self.sessionCancellable = session.objectWillChange
+ .receive(on: RunLoop.main)
+ .sink { [weak self] _ in
+ DispatchQueue.main.async {
+ self?.resizeAndPositionPanel(animated: true)
+ }
+ }
+ guard let panel = self.panel else { return }
+ self.resizeAndPositionPanel(animated: false)
panel.alphaValue = 0
panel.orderFrontRegardless()
NSAnimationContext.runAnimationGroup { context in
@@ -60,7 +79,8 @@ final class DictionaryCorrectionOverlayController {
try? await Task.sleep(nanoseconds: Self.displayDurationNanoseconds)
guard !Task.isCancelled,
let self,
- self.generation == currentGeneration
+ self.generation == currentGeneration,
+ self.session?.screen == .choice
else {
return
}
@@ -70,20 +90,55 @@ final class DictionaryCorrectionOverlayController {
func hide() {
self.generation &+= 1
+ let hideGeneration = self.generation
self.dismissTask?.cancel()
self.dismissTask = nil
- guard let panel, panel.isVisible else { return }
+ self.session?.cancel()
+ guard let panel, panel.isVisible else {
+ self.clearSession()
+ return
+ }
NSAnimationContext.runAnimationGroup { context in
context.duration = Self.dismissalDuration
context.allowsImplicitAnimation = true
panel.animator().alphaValue = 0
- } completionHandler: { [weak panel] in
- panel?.orderOut(nil)
- panel?.alphaValue = 1
+ } completionHandler: { [weak self] in
+ MainActor.assumeIsolated {
+ guard let self, self.generation == hideGeneration else { return }
+ self.panel?.orderOut(nil)
+ self.panel?.alphaValue = 1
+ self.clearSession()
+ }
}
}
+ private func keepVisible() {
+ self.dismissTask?.cancel()
+ self.dismissTask = nil
+ }
+
+ private func scheduleSuccessDismissal() {
+ self.keepVisible()
+ let successGeneration = self.generation
+ self.dismissTask = Task { @MainActor [weak self] in
+ try? await Task.sleep(nanoseconds: Self.successDurationNanoseconds)
+ guard !Task.isCancelled,
+ let self,
+ self.generation == successGeneration
+ else {
+ return
+ }
+ self.hide()
+ }
+ }
+
+ private func clearSession() {
+ self.sessionCancellable?.cancel()
+ self.sessionCancellable = nil
+ self.session = nil
+ }
+
private func createPanel(rootView: AutomaticDictionaryCorrectionOverlayView) {
let panel = NSPanel(
contentRect: .zero,
@@ -110,118 +165,339 @@ final class DictionaryCorrectionOverlayController {
self.hostingView = hostingView
}
- private func position(_ panel: NSPanel) {
- guard let screen = OverlayScreenResolver.screenForCurrentPointer() ?? NSScreen.main else { return }
+ private func resizeAndPositionPanel(animated: Bool) {
+ guard let panel, let hostingView,
+ let screen = OverlayScreenResolver.screenForCurrentPointer() ?? NSScreen.main
+ else {
+ return
+ }
+
+ hostingView.layoutSubtreeIfNeeded()
+ let fittingSize = hostingView.fittingSize
+ let size = NSSize(width: ceil(fittingSize.width), height: ceil(fittingSize.height))
+ guard size.width > 0, size.height > 0 else { return }
+ hostingView.frame = NSRect(origin: .zero, size: size)
+
let visibleFrame = screen.visibleFrame
- let size = panel.frame.size
- let x = screen.frame.midX - size.width / 2
let requestedY = visibleFrame.minY + CGFloat(SettingsStore.shared.overlayBottomOffset)
let y = max(visibleFrame.minY + 10, min(requestedY, visibleFrame.maxY - size.height - 40))
- panel.setFrameOrigin(NSPoint(x: x, y: y))
+ let frame = NSRect(
+ x: screen.frame.midX - size.width / 2,
+ y: y,
+ width: size.width,
+ height: size.height
+ )
+
+ guard animated, panel.isVisible else {
+ panel.setFrame(frame, display: true)
+ return
+ }
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.16
+ context.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ panel.animator().setFrame(frame, display: true)
+ }
}
}
private struct AutomaticDictionaryCorrectionOverlayView: View {
- let candidate: AutomaticDictionaryCorrectionCandidate
+ @ObservedObject var session: AutomaticDictionaryTrainingSession
+
let displayDuration: TimeInterval
- let onTrain: () -> Void
let onDismiss: () -> Void
@Environment(\.accessibilityReduceMotion) private var reduceMotion
- @State private var isTrainHovered = false
@State private var isDismissHovered = false
@State private var progress: CGFloat = 1
+ private var accent: Color { SettingsStore.shared.accentColor }
+
var body: some View {
- VStack(alignment: .leading, spacing: 8) {
- HStack(spacing: 7) {
- Image(systemName: "mic.fill")
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(.white.opacity(0.78))
+ Group {
+ switch self.session.screen {
+ case .choice:
+ self.choiceContent
+ case .training:
+ self.trainingContent
+ case .success:
+ self.successContent
+ }
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 12)
+ .frame(width: 460)
+ .background(self.overlayBackground)
+ .overlay(alignment: .bottomLeading) {
+ if self.session.screen == .choice {
+ GeometryReader { proxy in
+ Capsule()
+ .fill(Color.white.opacity(0.72))
+ .frame(width: proxy.size.width * self.progress, height: 2)
+ .frame(maxHeight: .infinity, alignment: .bottom)
+ }
+ .padding(.horizontal, 14)
+ .padding(.bottom, 3)
+ .allowsHitTesting(false)
+ }
+ }
+ .preferredColorScheme(.dark)
+ .animation(self.reduceMotion ? nil : .easeOut(duration: 0.16), value: self.session.screen)
+ .onAppear {
+ self.startProgressAnimation()
+ }
+ }
- Text("Correction noticed")
- .font(.system(size: 12, weight: .medium))
- .foregroundStyle(.white.opacity(0.72))
+ private var choiceContent: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ self.header(title: "Correction noticed", allowsBack: false)
- Spacer(minLength: 8)
+ self.correctionPair
- Button(action: self.onDismiss) {
- Image(systemName: "xmark")
- .font(.system(size: 10, weight: .semibold))
- .foregroundStyle(.white.opacity(self.isDismissHovered ? 0.95 : 0.68))
- .frame(width: 24, height: 24)
- .background(
- Circle()
- .fill(Color.white.opacity(self.isDismissHovered ? 0.13 : 0.06))
- )
- }
- .buttonStyle(.plain)
- .contentShape(Circle())
- .onHover { self.isDismissHovered = $0 }
- .help("Dismiss")
+ Text("Save only this correction, or teach FluidVoice other pronunciations.")
+ .font(.system(size: 11))
+ .foregroundStyle(.white.opacity(0.58))
+ .lineLimit(1)
+
+ HStack(spacing: 8) {
+ CorrectionOverlayActionButton(
+ title: "Train by Voice",
+ systemImage: "mic.fill",
+ style: .secondary,
+ accent: self.accent,
+ action: self.session.beginTraining
+ )
+
+ CorrectionOverlayActionButton(
+ title: "Add This Correction",
+ systemImage: "plus",
+ style: .accent,
+ accent: self.accent,
+ action: self.session.addOnlyCorrection
+ )
}
+ }
+ .transition(.opacity)
+ }
- HStack(alignment: .center, spacing: 12) {
- VStack(alignment: .leading, spacing: 5) {
- HStack(spacing: 8) {
- Text(self.candidate.heardText)
- .foregroundStyle(.white.opacity(0.9))
+ private var trainingContent: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ self.header(title: "Train by Voice", allowsBack: true)
- Image(systemName: "arrow.right")
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(.white.opacity(0.48))
+ self.correctionPair
- Text(self.candidate.correctedText)
- .foregroundStyle(.white)
- }
- .font(.system(size: 16, weight: .semibold))
- .lineLimit(1)
- .minimumScaleFactor(0.78)
+ HStack(alignment: .center, spacing: 12) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(self.session.trainingHeadline)
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(.white.opacity(0.94))
+
+ Text(self.session.trainingDetail)
+ .font(.system(size: 10.5))
+ .foregroundStyle(.white.opacity(0.56))
+ .lineLimit(2)
- Text("Train FluidVoice to remember this?")
- .font(.system(size: 11, weight: .regular))
- .foregroundStyle(.white.opacity(0.58))
- .lineLimit(1)
+ self.readinessRow
}
.frame(maxWidth: .infinity, alignment: .leading)
- Button(action: self.onTrain) {
- Label("Train by Voice", systemImage: "mic.fill")
- .font(.system(size: 12, weight: .semibold))
- .foregroundStyle(.white.opacity(0.92))
- .padding(.horizontal, 12)
- .frame(height: 34)
- .background(self.trainButtonBackground)
+ CorrectionOverlayRecordButton(
+ title: self.session.recordButtonTitle,
+ isStop: self.session.recordButtonIsStop,
+ isEnabled: self.session.canUseRecordButton,
+ accent: self.accent,
+ action: self.session.toggleCapture
+ )
+ }
+ .padding(10)
+ .background(self.panelSurface)
+
+ self.finalOutputRow
+
+ if !self.session.variants.isEmpty {
+ self.capturedVariantsRow
+ }
+
+ if self.session.capturePhase == .idle, !self.session.statusMessage.isEmpty {
+ Label(
+ self.session.statusMessage,
+ systemImage: self.session.hasError ? "exclamationmark.triangle.fill" : "checkmark.circle"
+ )
+ .font(.system(size: 10.5, weight: .medium))
+ .foregroundStyle(self.session.hasError ? Color.red.opacity(0.9) : .white.opacity(0.58))
+ .lineLimit(1)
+ }
+
+ CorrectionOverlayActionButton(
+ title: "Add Replacement",
+ systemImage: "plus",
+ style: .accent,
+ accent: self.accent,
+ isEnabled: self.session.canSave,
+ isReady: self.session.isReady,
+ action: self.session.addTrainedReplacement
+ )
+ }
+ .transition(.opacity.combined(with: .move(edge: .bottom)))
+ }
+
+ private var successContent: some View {
+ HStack(spacing: 12) {
+ ZStack {
+ Circle()
+ .fill(self.accent.opacity(0.18))
+ .frame(width: 38, height: 38)
+ Image(systemName: "checkmark")
+ .font(.system(size: 15, weight: .bold))
+ .foregroundStyle(self.accent)
+ }
+
+ VStack(alignment: .leading, spacing: 3) {
+ Text(self.session.successTitle)
+ .font(.system(size: 14, weight: .semibold))
+ .foregroundStyle(.white)
+ Text("“\(self.session.candidate.heardText)” will become “\(self.session.candidate.correctedText)”.")
+ .font(.system(size: 11))
+ .foregroundStyle(.white.opacity(0.6))
+ .lineLimit(1)
+ }
+
+ Spacer(minLength: 8)
+ }
+ .padding(.vertical, 4)
+ .transition(.scale(scale: 0.96).combined(with: .opacity))
+ }
+
+ private func header(title: String, allowsBack: Bool) -> some View {
+ HStack(spacing: 7) {
+ if allowsBack {
+ Button(action: self.session.returnToChoice) {
+ Image(systemName: "chevron.left")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundStyle(.white.opacity(0.72))
+ .frame(width: 24, height: 24)
+ .background(Circle().fill(Color.white.opacity(0.06)))
}
.buttonStyle(.plain)
- .contentShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
- .onHover { self.isTrainHovered = $0 }
- .help("Open Train by Voice")
+ .disabled(self.session.capturePhase != .idle)
+ .opacity(self.session.capturePhase == .idle ? 1 : 0.35)
+ .help("Back")
+ } else {
+ Image(systemName: "mic.fill")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(.white.opacity(0.78))
+ .frame(width: 24, height: 24)
+ }
+
+ Text(title)
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(.white.opacity(0.72))
+
+ Spacer(minLength: 8)
+
+ Button(action: self.onDismiss) {
+ Image(systemName: "xmark")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundStyle(.white.opacity(self.isDismissHovered ? 0.95 : 0.68))
+ .frame(width: 24, height: 24)
+ .background(
+ Circle()
+ .fill(Color.white.opacity(self.isDismissHovered ? 0.13 : 0.06))
+ )
}
+ .buttonStyle(.plain)
+ .contentShape(Circle())
+ .onHover { self.isDismissHovered = $0 }
+ .help("Dismiss")
}
- .padding(.horizontal, 14)
- .padding(.top, 10)
- .padding(.bottom, 12)
- .frame(width: 440)
- .background(self.overlayBackground)
- .overlay(alignment: .bottomLeading) {
+ }
+
+ private var correctionPair: some View {
+ HStack(spacing: 8) {
+ Text(self.session.candidate.heardText)
+ .foregroundStyle(.white.opacity(0.78))
+
+ Image(systemName: "arrow.right")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(.white.opacity(0.42))
+
+ Text(self.session.candidate.correctedText)
+ .foregroundStyle(.white)
+ }
+ .font(.system(size: 16, weight: .semibold))
+ .lineLimit(1)
+ .minimumScaleFactor(0.72)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ private var readinessRow: some View {
+ HStack(spacing: 8) {
GeometryReader { proxy in
- Capsule()
- .fill(Color.white.opacity(0.75))
- .frame(width: proxy.size.width * self.progress, height: 2)
- .frame(maxHeight: .infinity, alignment: .bottom)
+ ZStack(alignment: .leading) {
+ Capsule().fill(Color.white.opacity(0.1))
+ Capsule()
+ .fill(self.session.isReady ? Color.green.opacity(0.9) : self.accent)
+ .frame(width: proxy.size.width * CGFloat(self.session.readinessFraction))
+ }
}
- .padding(.horizontal, 14)
- .padding(.bottom, 3)
- .allowsHitTesting(false)
+ .frame(height: 4)
+
+ Text("\(self.session.readinessProgress)/\(CustomDictionaryTrainingMerge.readyCoveredCount)")
+ .font(.system(size: 10, weight: .semibold, design: .rounded))
+ .foregroundStyle(.white.opacity(0.58))
+ .monospacedDigit()
+ .frame(width: 24, alignment: .trailing)
+
+ Text("\(self.session.sampleCount)/\(CustomDictionaryTrainingMerge.maxSamples)")
+ .font(.system(size: 10, weight: .medium, design: .rounded))
+ .foregroundStyle(.white.opacity(0.38))
+ .monospacedDigit()
+ .frame(width: 30, alignment: .trailing)
}
- .preferredColorScheme(.dark)
- .onAppear {
- self.startProgressAnimation()
+ }
+
+ private var finalOutputRow: some View {
+ HStack(spacing: 8) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Final output")
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(.white.opacity(0.46))
+ Text(self.session.finalOutputText)
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(.white.opacity(self.session.lastOutput.isEmpty ? 0.48 : 0.9))
+ .lineLimit(1)
+ }
+
+ Spacer(minLength: 8)
+
+ if self.session.isReady {
+ Label("Ready", systemImage: "checkmark.circle.fill")
+ .font(.system(size: 10.5, weight: .semibold))
+ .foregroundStyle(Color.green.opacity(0.9))
+ }
}
- .onChange(of: self.candidate.id) { _, _ in
- self.startProgressAnimation()
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ .background(self.panelSurface)
+ }
+
+ private var capturedVariantsRow: some View {
+ HStack(spacing: 6) {
+ Text("Captured")
+ .font(.system(size: 10.5, weight: .medium))
+ .foregroundStyle(.white.opacity(0.46))
+
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 6) {
+ ForEach(self.session.variants, id: \.self) { variant in
+ CorrectionOverlayVariantChip(variant: variant) {
+ self.session.removeVariant(variant)
+ }
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
}
+ .frame(minHeight: 24)
}
private func startProgressAnimation() {
@@ -234,22 +510,12 @@ private struct AutomaticDictionaryCorrectionOverlayView: View {
}
}
- private var trainButtonBackground: some View {
+ private var panelSurface: some View {
RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(self.isTrainHovered ? Color(red: 0.13, green: 0.13, blue: 0.16) : .black)
+ .fill(Color.white.opacity(0.045))
.overlay(
RoundedRectangle(cornerRadius: 8, style: .continuous)
- .strokeBorder(
- LinearGradient(
- colors: [
- .white.opacity(self.isTrainHovered ? 0.38 : 0.24),
- .white.opacity(self.isTrainHovered ? 0.22 : 0.12),
- ],
- startPoint: .top,
- endPoint: .bottom
- ),
- lineWidth: 1
- )
+ .strokeBorder(Color.white.opacity(0.09), lineWidth: 1)
)
}
@@ -269,3 +535,132 @@ private struct AutomaticDictionaryCorrectionOverlayView: View {
)
}
}
+
+private struct CorrectionOverlayActionButton: View {
+ enum Style {
+ case accent
+ case secondary
+ }
+
+ let title: String
+ let systemImage: String
+ let style: Style
+ let accent: Color
+ var isEnabled = true
+ var isReady = false
+ let action: () -> Void
+
+ @State private var isHovered = false
+
+ var body: some View {
+ Button(action: self.action) {
+ Label(self.title, systemImage: self.systemImage)
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(.white.opacity(self.isEnabled ? 0.94 : 0.42))
+ .frame(maxWidth: .infinity)
+ .frame(height: 36)
+ .background(self.background)
+ }
+ .buttonStyle(.plain)
+ .disabled(!self.isEnabled)
+ .onHover { self.isHovered = $0 }
+ }
+
+ private var background: some View {
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.fillColor)
+ .overlay(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .strokeBorder(self.borderColor, lineWidth: self.isReady ? 1.5 : 1)
+ )
+ .shadow(color: self.isReady ? Color.green.opacity(0.2) : .clear, radius: 10, y: 3)
+ }
+
+ private var fillColor: Color {
+ switch self.style {
+ case .accent:
+ return self.accent.opacity(self.isEnabled ? (self.isHovered ? 1 : 0.9) : 0.25)
+ case .secondary:
+ return Color.white.opacity(self.isHovered ? 0.1 : 0.045)
+ }
+ }
+
+ private var borderColor: Color {
+ if self.isReady {
+ return Color.green.opacity(0.75)
+ }
+ switch self.style {
+ case .accent:
+ return Color.white.opacity(self.isEnabled ? 0.18 : 0.06)
+ case .secondary:
+ return Color.white.opacity(self.isHovered ? 0.28 : 0.16)
+ }
+ }
+}
+
+private struct CorrectionOverlayRecordButton: View {
+ let title: String
+ let isStop: Bool
+ let isEnabled: Bool
+ let accent: Color
+ let action: () -> Void
+
+ @State private var isHovered = false
+
+ var body: some View {
+ Button(action: self.action) {
+ Label(self.title, systemImage: self.isStop ? "stop.fill" : "mic.fill")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(.white.opacity(self.isEnabled ? 0.95 : 0.4))
+ .padding(.horizontal, 13)
+ .frame(height: 36)
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.buttonColor.opacity(self.isEnabled ? (self.isHovered ? 1 : 0.9) : 0.25))
+ )
+ }
+ .buttonStyle(.plain)
+ .disabled(!self.isEnabled)
+ .onHover { self.isHovered = $0 }
+ }
+
+ private var buttonColor: Color {
+ self.isStop ? Color(red: 0.82, green: 0.18, blue: 0.2) : self.accent
+ }
+}
+
+private struct CorrectionOverlayVariantChip: View {
+ let variant: String
+ let onRemove: () -> Void
+
+ @State private var isHovered = false
+
+ var body: some View {
+ Button(action: self.onRemove) {
+ HStack(spacing: 4) {
+ Text(self.variant)
+ .lineLimit(1)
+ .minimumScaleFactor(0.75)
+ Image(systemName: "xmark.circle.fill")
+ .font(.system(size: 9))
+ .foregroundStyle(.white.opacity(self.isHovered ? 0.72 : 0.42))
+ }
+ .font(.system(size: 10.5, weight: .medium))
+ .foregroundStyle(.white.opacity(0.72))
+ .padding(.horizontal, 7)
+ .frame(height: 23)
+ .background(
+ RoundedRectangle(cornerRadius: 6, style: .continuous)
+ .fill(Color.white.opacity(self.isHovered ? 0.1 : 0.06))
+ .overlay(
+ RoundedRectangle(cornerRadius: 6, style: .continuous)
+ .strokeBorder(Color.white.opacity(0.1), lineWidth: 1)
+ )
+ )
+ }
+ .buttonStyle(.plain)
+ .frame(maxWidth: 112)
+ .onHover { self.isHovered = $0 }
+ .help("Remove \(self.variant)")
+ }
+}