Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/hop/blob/main/Sources/Dictation.swift # hop Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key. Brought by drakestapleton Sign in to star 1 stars 1 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `hop / Sources / Dictation.swift` 414 lines · 21559 bytes Raw Blame History 1 import AppKit 2 import AVFoundation 3 import Combine 4 import SwiftUI 5 6 /// Hold a key, talk, let go: the words land where the cursor is. The recognition runs on this Mac; the text then 7 /// goes where it is pointed, which for Ask, Agent and rewrites means the service configured for them. 8 @MainActor 9 final class Dictation: ObservableObject { 10 enum Mode { case hold, handsFree, command } 11 enum Phase: Equatable { case idle, listening, finishing, working(String), notice(String) } 12 struct Entry: Identifiable { let id = UUID(); let date: Date; let text: String; let heard: String; let app: String?; let seconds: Double } 13 14 static let wisprBundleID = "com.electron.wispr-flow" 15 16 @Published private(set) var phase: Phase = .idle 17 @Published private(set) var mode: Mode = .hold 18 @Published private(set) var partial = "" 19 @Published private(set) var level: Float = 0 20 @Published private(set) var recent: [Entry] = [] 21 @Published private(set) var modelReady = false 22 @Published private(set) var setupProblem = "" 23 @Published var settings = DictationSettings.load() { 24 didSet { 25 if !testMode { settings.save() } 26 engine.hints = hints; applyTakeover() 27 if settings.enabled, !oldValue.enabled, !modelReady { Task { await warmUp() } } // just turned on: get the speech model ready 28 } 29 } 30 31 let engine = SpeechEngine() 32 weak var model: AppModel? 33 var isHopFront: () -> Bool = { false } 34 var showHop: () -> Void = {} 35 var keysChanged: () -> Void = {} 36 37 private var startTask: Task? 38 private var startedAt = Date() 39 private var mutedByUs = false 40 private var targetApp: NSRunningApplication? 41 private(set) var speakNextReply = false 42 private let voice = AVSpeechSynthesizer() 43 private var watchers = Set() 44 45 var lastText: String { recent.first?.text ?? "" } 46 var listening: Bool { phase == .listening } 47 private var hints: [String] { Array(Set(settings.words + settings.fixes.map(\.write))) } 48 var otherDictationAppRunning: Bool { !NSRunningApplication.runningApplications(withBundleIdentifier: Self.wisprBundleID).isEmpty } 49 /// Hop listens on the dictation key only when no other dictation app would answer the same press. 50 var armed: Bool { settings.enabled && (settings.takeOverFromWispr || !otherDictationAppRunning) } 51 52 init() { 53 engine.hints = hints 54 engine.onPartial = { [weak self] t in self?.partial = t } 55 engine.onLevel = { [weak self] l in self?.level = l } 56 let nc = NSWorkspace.shared.notificationCenter 57 nc.addObserver(forName: NSWorkspace.didLaunchApplicationNotification, object: nil, queue: .main) { [weak self] _ in 58 MainActor.assumeIsolated { self?.applyTakeover(); self?.keysChanged() } 59 } 60 nc.addObserver(forName: NSWorkspace.didTerminateApplicationNotification, object: nil, queue: .main) { [weak self] _ in 61 MainActor.assumeIsolated { self?.keysChanged() } 62 } 63 } 64 65 func attach(_ m: AppModel) { 66 model = m 67 // Read the answer aloud when the question was spoken. 68 m.$agentRunning.removeDuplicates().dropFirst().sink { [weak self, weak m] running in 69 guard let self, !running, self.speakNextReply else { return } 70 self.speakNextReply = false 71 // @Published tells before it changes: the answer and its last piece are in the conversation a moment later. 72 DispatchQueue.main.async { 73 if let reply = m.map({ AppModel.history($0.agentLog) })?.last, reply.role == "assistant" { self.say(reply.text) } 74 } 75 }.store(in: &watchers) 76 applyTakeover() 77 if settings.enabled { Task { await warmUp() } } // nothing is fetched or loaded while dictation is off 78 } 79 80 func warmUp() async { 81 do { try await engine.prepare(); modelReady = true; setupProblem = "" } 82 catch { modelReady = false; setupProblem = error.localizedDescription } 83 } 84 85 /// Gets dictation working with as little from the user as macOS allows: asks for the microphone once and proves it 86 /// works. Only when `autoTakeOverFromWispr` is set does it then also take the Fn key over from Wispr Flow. 87 /// Runs again every few seconds until it is done. 88 private var askedMic = false, checkingMic = false 89 var testMode = false // UI self-test: no sounds, nothing saved 90 func autoSetup() { 91 guard settings.enabled, !testMode, modelReady, !settings.autoSwitched, !checkingMic else { return } 92 if SpeechEngine.microphoneUndecided { 93 if !askedMic { askedMic = true; Task { _ = await SpeechEngine.askForMicrophone() } } 94 return 95 } 96 guard SpeechEngine.microphoneAllowed, AXIsProcessTrusted(), phase == .idle else { return } 97 checkingMic = true 98 Task { [weak self] in 99 guard let self else { return } 100 let problem = await self.engine.microphoneCheck() 101 self.checkingMic = false 102 if let problem { self.setupProblem = problem; AppDelegate.log("dictation: microphone check failed: \(problem)"); return } 103 self.setupProblem = "" 104 self.settings.autoSwitched = true 105 if self.settings.autoTakeOverFromWispr { self.settings.takeOverFromWispr = true } // closes Wispr Flow; Hop now answers Fn 106 self.keysChanged() 107 if self.armed { 108 AppDelegate.log("dictation: microphone check passed; Hop now handles dictation") 109 self.flash("Hop is your dictation now. Hold Fn and talk.") 110 } else { 111 AppDelegate.log("dictation: microphone check passed; standing by while another dictation app has the key") 112 } 113 } 114 } 115 116 private func applyTakeover() { 117 guard settings.enabled, settings.takeOverFromWispr else { return } 118 for app in NSRunningApplication.runningApplications(withBundleIdentifier: Self.wisprBundleID) { app.terminate() } 119 } 120 121 // MARK: Listening 122 func begin(_ m: Mode, source: SpeechEngine.Source = .microphone) { 123 guard settings.enabled, !unwinding else { return } 124 switch phase { case .idle, .notice: break; default: return } 125 if case .microphone = source, !SpeechEngine.microphoneAllowed { 126 if SpeechEngine.microphoneUndecided { 127 Task { _ = await SpeechEngine.askForMicrophone() } 128 flash("Allow the microphone, then hold the key again") 129 } else { flash("Microphone is off for Hop. Turn it on in System Settings, Privacy & Security.") } 130 return 131 } 132 checkFixes() // the previous dictation's field, before new text lands in it 133 mode = m; partial = ""; level = 0; phase = .listening; startedAt = Date() 134 if !testMode { AppDelegate.log("dictation: listening (\(m))") } 135 targetApp = NSWorkspace.shared.frontmostApplication 136 voice.stopSpeaking(at: .immediate) 137 if settings.sounds && !testMode { // a beat later, so using Fn as an ordinary modifier stays silent 138 DispatchQueue.main.asyncAfter(deadline: .now() + 0.12) { [weak self] in if self?.phase == .listening { NSSound(named: "Tink")?.play() } } 139 } 140 let useMic: Bool = { if case .microphone = source { return true }; return false }() 141 startTask = Task { [weak self] in 142 guard let self else { return false } 143 do { try await self.engine.start(source) } 144 catch { self.phase = .idle; self.flash(error.localizedDescription); return false } 145 if self.settings.muteAudioWhileDictating, useMic { 146 try? await Task.sleep(nanoseconds: 180_000_000) // let the start sound finish 147 if self.phase == .listening, SystemAudio.muted == false { self.mutedByUs = SystemAudio.setMuted(true) } 148 } 149 return true 150 } 151 } 152 153 /// Stop listening and use what was said. 154 func end() { 155 guard phase == .listening else { return } 156 phase = .finishing 157 let m = mode, began = startedAt, start = startTask 158 Task { [weak self] in 159 guard let self else { return } 160 guard await start?.value == true else { self.restoreAudio(); return } 161 let heard = await self.engine.finish() 162 self.restoreAudio() 163 if !self.testMode { // counts and timing only, never the words 164 AppDelegate.log("dictation: \(heard.split(separator: " ").count) words after \(String(format: "%.1f", Date().timeIntervalSince(began))) s of listening (\(m))") 165 } 166 guard !heard.isEmpty else { self.phase = .idle; self.flash("Didn't catch anything"); return } 167 if self.settings.sounds && !self.testMode { NSSound(named: "Pop")?.play() } 168 let text = Cleanup.apply(heard, self.settings) 169 self.recent.insert(Entry(date: Date(), text: text, heard: heard, app: self.targetApp?.localizedName, 170 seconds: Date().timeIntervalSince(began)), at: 0) 171 if self.recent.count > 100 { self.recent.removeLast() } 172 if !self.testMode { self.model?.clipboard.record(text, from: "Dictation") } 173 if m == .command { await self.runCommand(text) } else { self.deliver(text) } 174 } 175 } 176 177 func cancel() { 178 guard phase == .listening else { return } 179 phase = .idle; unwinding = true 180 if !testMode { AppDelegate.log("dictation: cancelled") } 181 let start = startTask 182 Task { [weak self] in 183 _ = await start?.value 184 await self?.engine.cancel() 185 self?.restoreAudio() 186 self?.unwinding = false 187 } 188 } 189 private var unwinding = false 190 191 /// Hands-free: the same key starts and stops. 192 func toggleHandsFree() { if phase == .listening { end() } else { begin(.handsFree) } } 193 /// Turns a held dictation into a hands-free one (Space while holding, or a double tap). 194 func lock() { if phase == .listening { mode = .handsFree } else { begin(.handsFree) } } 195 /// Turns a held dictation into a spoken instruction (Control while holding). 196 func makeCommand() { if phase == .listening { mode = .command } } 197 198 private func restoreAudio() { if mutedByUs { SystemAudio.setMuted(false); mutedByUs = false } } 199 200 // MARK: Using the words 201 func deliver(_ text: String) { 202 phase = .idle 203 if isHopFront(), let model { // talking to Hop itself 204 model.query = model.query.isEmpty ? text : model.query + " " + text 205 if model.tab == .agent { 206 model.submit(alt: false) 207 } 208 return 209 } 210 let field = settings.learnFromFixes && (!testMode || learnInTest) ? FixLearner.focusedField() : nil 211 if !Paster.type(text + " ") { flash("Copied. Press ⌘V to paste (Hop needs the paste permission).") } 212 else if let field { watchForFixes(field, text) } 213 } 214 215 // MARK: Learning from the user's corrections (Sources/Learn.swift) 216 private struct FixWatch { let field: AXUIElement; let text: String; let before: String } 217 private var fixWatch: FixWatch? 218 private var fixTask: Task? 219 /// Reads the field once the paste has landed, then looks again after `fixWindow` seconds (or at the next dictation). 220 var fixWindow: Double = 45 221 var learnInTest = false // `--uitest-learn`: the learning path runs although the UI test mode is on 222 /// `--uitest-learn` only: the words a dictation ends with, typed the same way (paste into the app in front). 223 func deliverForTest(_ text: String) { deliver(text) } 224 private func watchForFixes(_ field: AXUIElement, _ text: String) { 225 fixTask?.cancel() 226 fixTask = Task { [weak self] in 227 try? await Task.sleep(nanoseconds: 1_200_000_000) // Paster restores the clipboard at 0.9 s 228 guard let self, !Task.isCancelled, let before = FixLearner.value(field), 229 !FixLearner.words(text).isEmpty, before.contains(text.trimmingCharacters(in: .whitespacesAndNewlines)) else { return } 230 self.fixWatch = FixWatch(field: field, text: text, before: before) 231 try? await Task.sleep(nanoseconds: UInt64(self.fixWindow * 1_000_000_000)) 232 guard !Task.isCancelled else { return } 233 self.checkFixes() 234 } 235 } 236 /// Compares the watched field with what it held right after the paste, and learns from the difference. 237 /// Only the field read happens here; the comparison runs in the background, so the next dictation starts at once. 238 func checkFixes() { 239 guard let w = fixWatch else { return } 240 fixWatch = nil; fixTask?.cancel(); fixTask = nil 241 guard settings.learnFromFixes, let after = FixLearner.value(w.field), after != w.before else { return } 242 learnFrom(w.text, before: w.before, after: after) 243 } 244 /// The comparison of one dictation's field, before and after; returns at once. The task ends when it has learned. 245 @discardableResult 246 func learnFrom(_ text: String, before: String, after: String) -> Task { 247 let compare = FixLearner.correctionsInBackground(dictated: text, before: before, after: after) 248 return Task { [weak self] in 249 let pairs = await compare.value 250 guard let self, !pairs.isEmpty, self.settings.learnFromFixes else { return } 251 var s = self.settings 252 let got = s.learn(pairs, isNewName: FixLearner.isNewName, isKnownWords: FixLearner.isKnownWords) 253 self.settings = s 254 if !self.testMode { AppDelegate.log("dictation: \(pairs.count) correction(s) seen, \(got.count) learned") } // counts only, never the words 255 // Never over a dictation in progress: the notice would end it. 256 if let l = got.first, self.phase == .idle { self.flash("Learned: “\(l.heard)” → “\(l.write)”. Undo on the Voice screen.") } 257 } 258 } 259 func undoLearned(_ l: FixLearner.Learned) { 260 var s = settings; s.undoLearned(l); settings = s 261 } 262 263 /// A spoken instruction. With text selected it rewrites that text in place; with nothing selected Hop's agent does it. 264 private func runCommand(_ instruction: String) async { 265 let selected = Paster.selectedText() 266 guard !selected.isEmpty else { 267 phase = .idle 268 deliverCommandToAgent(instruction) 269 return 270 } 271 await rewriteSelection(selected, instruction) 272 } 273 274 func deliverCommandToAgent(_ instruction: String) { 275 guard let model else { return } 276 let parks = isHopFront() && model.tab == .agent 277 let draft = model.query 278 let combined = draft.isEmpty ? instruction : draft + "\n" + instruction 279 showHop() 280 if parks { 281 model.query = combined 282 model.tab = .agent 283 model.submit(alt: false) 284 } else if model.agentRunning { 285 // Keep both inputs ready to send; fixIt explains why nothing was sent. 286 model.query = combined 287 model.fixIt() 288 } else { 289 // An external command is a separate request, not permission to execute an 290 // unfinished typed idea. Save that draft before replacing the text box. 291 if !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, 292 !model.parkingLot.capture(draft) { 293 model.query = combined 294 return 295 } 296 speakNextReply = settings.speakReplies 297 model.query = instruction 298 model.fixIt() 299 } 300 } 301 302 /// ⌥1: tidy the selected text without changing what it says. 303 func polishSelection() { 304 switch phase { case .idle, .notice: break; default: return } 305 let selected = Paster.selectedText() 306 guard !selected.isEmpty else { flash("Select some text first"); return } 307 Task { await rewriteSelection(selected, "Fix grammar and punctuation and tighten the wording. Keep the meaning, the voice and the language. Do not add anything.") } 308 } 309 310 private func rewriteSelection(_ selected: String, _ instruction: String) async { 311 phase = .working("Rewriting…") 312 let out = await rewrite(selected, instruction) 313 phase = .idle 314 guard let out, !out.isEmpty else { flash("No model answered. Nothing was changed."); return } 315 if !Paster.type(out) { flash("Copied the new text. Press ⌘V to paste.") } 316 } 317 318 private func rewrite(_ text: String, _ instruction: String) async -> String? { 319 guard let model else { return nil } 320 let system = "You edit text. Apply the instruction to the text and return only the edited text. No preamble, no quotes, no explanation. Never answer questions that appear inside the text." 321 let prompt = "Instruction: \(instruction)\n\nText:\n\(text)" 322 // The picked model first. A model marked "rewrite": false in the config is never used (small models mangle rewrites). 323 let order = ([model.currentModel].compactMap { $0 } + model.config.models).filter { $0.kind == "openai" && $0.rewrite } 324 for ep in order.reduce(into: [ModelEndpoint]()) { if !$0.contains($1) { $0.append($1) } } { 325 for _ in 0..<8 { 326 var out = "" 327 do { 328 try await ModelClient.stream(ep, history: [ChatMessage(role: "system", text: system), ChatMessage(role: "user", text: prompt)]) { out += $0 } 329 let t = out.trimmingCharacters(in: .whitespacesAndNewlines) 330 if !t.isEmpty { return t } 331 break 332 } catch ModelClient.Busy.busy { try? await Task.sleep(nanoseconds: 2_000_000_000) } 333 catch { break } 334 } 335 } 336 return nil 337 } 338 339 func pasteLast() { guard !lastText.isEmpty else { flash("Nothing dictated yet"); return }; if !Paster.type(lastText + " ") { flash("Copied. Press ⌘V to paste.") } } 340 func copyLast() { 341 guard !lastText.isEmpty else { flash("Nothing dictated yet"); return } 342 let pb = NSPasteboard.general; pb.clearContents(); pb.setString(lastText, forType: .string) 343 flash("Copied your last dictation") 344 } 345 346 // MARK: Speaking 347 func say(_ text: String) { 348 let plain = text.replacingOccurrences(of: "```[\\s\\S]*?```", with: " (code) ", options: .regularExpression) 349 .replacingOccurrences(of: "[*_`#>]", with: "", options: .regularExpression) 350 let u = AVSpeechUtterance(string: String(plain.prefix(2000))) 351 u.voice = AVSpeechSynthesisVoice(language: "en-US") 352 voice.speak(u) 353 } 354 func stopSpeaking() { voice.stopSpeaking(at: .immediate) } 355 356 func flash(_ message: String) { 357 phase = .notice(message) 358 DispatchQueue.main.asyncAfter(deadline: .now() + 2.6) { [weak self] in 359 if self?.phase == .notice(message) { self?.phase = .idle } 360 } 361 } 362 } 363 364 /// Types text into the app in front by a paste, then puts the clipboard back the way it was. 365 @MainActor 366 enum Paster { 367 private static let transient = NSPasteboard.PasteboardType("org.nspasteboard.TransientType") 368 369 /// False when macOS has not allowed Hop to paste; the text is then left on the clipboard. 370 @discardableResult 371 static func type(_ text: String) -> Bool { 372 let pb = NSPasteboard.general 373 guard AXIsProcessTrusted() else { 374 pb.clearContents(); pb.setString(text, forType: .string) 375 return false 376 } 377 let saved: [NSPasteboardItem] = (pb.pasteboardItems ?? []).map { old in 378 let copy = NSPasteboardItem() 379 for t in old.types { if let d = old.data(forType: t) { copy.setData(d, forType: t) } } 380 return copy 381 } 382 pb.clearContents() 383 pb.declareTypes([.string, transient], owner: nil) // transient: clipboard history skips it 384 pb.setString(text, forType: .string) 385 pb.setString("", forType: transient) 386 let mine = pb.changeCount 387 commandV() 388 DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) { 389 guard pb.changeCount == mine else { return } // the user copied something new meanwhile: leave it 390 pb.clearContents() 391 if !saved.isEmpty { pb.writeObjects(saved) } 392 } 393 return true 394 } 395 396 static func commandV() { 397 let src = CGEventSource(stateID: .combinedSessionState) 398 let down = CGEvent(keyboardEventSource: src, virtualKey: 9, keyDown: true) 399 let up = CGEvent(keyboardEventSource: src, virtualKey: 9, keyDown: false) 400 down?.flags = .maskCommand; up?.flags = .maskCommand 401 down?.post(tap: .cghidEventTap); up?.post(tap: .cghidEventTap) 402 } 403 404 /// The text selected in the app in front, when that app shares it. Empty otherwise. 405 static func selectedText() -> String { 406 guard AXIsProcessTrusted() else { return "" } 407 let system = AXUIElementCreateSystemWide() 408 var focused: CFTypeRef? 409 guard AXUIElementCopyAttributeValue(system, kAXFocusedUIElementAttribute as CFString, &focused) == .success, let el = focused else { return "" } 410 var value: CFTypeRef? 411 guard AXUIElementCopyAttributeValue(el as! AXUIElement, kAXSelectedTextAttribute as CFString, &value) == .success else { return "" } 412 return (value as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines) 413 } 414 }