diff --git a/Sources/NotebookApp/ContentView.swift b/Sources/NotebookApp/ContentView.swift index 6a1c5bb..7879ac8 100644 --- a/Sources/NotebookApp/ContentView.swift +++ b/Sources/NotebookApp/ContentView.swift @@ -1252,6 +1252,15 @@ struct AskBar: View { var cancel: (() -> Void)? /// Focus lives here so ⌘K can put the cursor in the field from anywhere. @FocusState private var writing: Bool + /// What dictation is doing, when it is doing anything. + @State private var voiceStatus: String? + /// Whether the words in the field were spoken, and whether the question + /// now being answered was. The second decides whether the answer is read + /// back under "When asked by voice". + @State private var dictated = false + @State private var askedByVoice = false + @State private var clears = 0 + private var readAloud: ReadAloud { .shared } /// Asking needs both a notebook with chunks and a loaded model. private var canAsk: Bool { @@ -1264,9 +1273,45 @@ struct AskBar: View { let embedder = embedding.ready(for: manifest.embeddingModel) else { return } let asked = question question = "" + askedByVoice = dictated + dictated = false + // A new question makes the last answer old news. + readAloud.stop() model.ask(asked, using: embedder, gateway: Self.gateway()) } + private func readBack(_ answered: NotebookModel.Answered?) { + guard let answered, answered.generated else { return } + switch VoiceSettings.readAloud { + case .never: return + case .whenSpoken: guard askedByVoice else { return } + case .always: break + } + readAloud.speak(answered.turn) + } + + /// Words the recogniser should expect: the notebook's own source names, as + /// words rather than filenames. "vcf-9-1.pdf" is spoken as "VCF 9 1", never + /// as "vcf dash nine dash one dot pdf". + private var vocabulary: [String] { + model.activeSources.prefix(100).map { + ($0 as NSString).deletingPathExtension + .replacingOccurrences(of: "-", with: " ") + .replacingOccurrences(of: "_", with: " ") + } + } + + @available(macOS 26, *) + private var talkerHost: Talker.Host { + Talker.Host( + text: $question, + fieldFocused: { writing }, + focusField: { writing = true }, + enabled: { canAsk }, + vocabulary: { vocabulary }, + dictated: { dictated = true }) + } + /// The fleet, when one has been configured. /// /// nil is a working state, not a failure: retrieval alone is useful and is @@ -1323,12 +1368,43 @@ struct AskBar: View { question = recalled return .handled } + // Inside the field, where every search box keeps it. A four line + // question - or a dictation that heard the radio - was cleared + // by selecting all and deleting, which is two shortcuts for the + // commonest correction there is. + if !question.isEmpty && !model.asking { + Button { + question = "" + dictated = false + clears += 1 + writing = true + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(Palette.inkSecondary) + } + .buttonStyle(.plain) + .help("Clear the question") + } + if readAloud.speaking { + Button { readAloud.stop() } label: { + Image(systemName: "speaker.slash.fill").font(.title2) + .foregroundStyle(Palette.inkSecondary) + } + .buttonStyle(.plain) + .help("Stop reading the answer") + } + // Present while a question is out, only disabled: taking it away + // would drop the keyboard monitor with it and build a new one, + // microphone state and all, every time a question was asked. + if #available(macOS 26, *) { + DictateButton(host: talkerHost, status: $voiceStatus, clears: clears) + } if model.asking { // The same control, doing the opposite thing. A spinner // here said "wait" and offered nothing; the only place // somebody looks to take a question back is where they sent // it from. - Button { cancel?() } label: { + Button { readAloud.stop(); cancel?() } label: { Image(systemName: "stop.circle.fill") .font(.title2) .foregroundStyle(Palette.warning) @@ -1359,7 +1435,10 @@ struct AskBar: View { if case .warming = embedding.state { ProgressView().controlSize(.small) } - if let summary = embedding.summary { + if let voiceStatus { + Text(voiceStatus).font(.caption).foregroundStyle(Palette.inkSecondary) + .lineLimit(2) + } else if let summary = embedding.summary { Text(summary).font(Type.provenance).foregroundStyle(Palette.inkSecondary) } if let detail = embedding.detail { @@ -1384,6 +1463,10 @@ struct AskBar: View { .opacity(0) .accessibilityHidden(true) } + .onChange(of: model.justAnswered) { _, answered in readBack(answered) } + // A field cleared by hand holds nothing spoken any more, so whatever is + // typed next is a typed question. + .onChange(of: question) { _, now in if now.isEmpty { dictated = false } } .padding(.horizontal, Measure.pagePadding / 2) .padding(.vertical, 12) // The same column as the record above it, left aligned to the same diff --git a/Sources/NotebookApp/Dictation.swift b/Sources/NotebookApp/Dictation.swift new file mode 100644 index 0000000..748bd16 --- /dev/null +++ b/Sources/NotebookApp/Dictation.swift @@ -0,0 +1,471 @@ +import AVFoundation +import NotebookKit +import Observation +import os +import Speech + +/// Speech in, text out, without the audio leaving this Mac. +/// +/// SpeechAnalyzer with SpeechTranscriber, which runs on-device and reports a +/// volatile guess while somebody is still talking, so the field fills as they +/// speak rather than after they stop. The older recogniser was the alternative +/// and it is noticeably worse at exactly what a notebook question is made of: +/// product names, filenames and long sentences. +/// +/// **The model is installed once, from Apple.** SpeechTranscriber's language +/// model is a system asset, not part of this app, and the first dictation on a +/// Mac that has never used it downloads it. That is said on screen when it +/// happens. The audio itself is never sent anywhere. +/// +/// **The next session is always ready before it is asked for.** Building one - +/// finding the locale, checking the model is installed, loading the analyzer - +/// was done on the key press, and the first words of every question were spoken +/// into a microphone that was not open yet. Now it is built ahead of time, when +/// the Ask bar appears and again as each dictation ends, so a press only has to +/// open the microphone. Nothing is recorded ahead of time: the microphone opens +/// on the press and closes on the release. +@available(macOS 26, *) +@Observable @MainActor +final class Dictation { + + enum State: Equatable { + case idle + /// Getting ready, with the reason said: the first run can take a while + /// and a silent pause reads as the button not working. + case preparing(String) + case listening + case finishing + case failed(String) + } + + private(set) var state: State = .idle + private(set) var transcript = LiveTranscript() + + var isActive: Bool { + switch state { + case .preparing, .listening, .finishing: true + case .idle, .failed: false + } + } + + /// An analyzer loaded and waiting for audio, and a microphone ready to + /// start - built, tapped and prepared, but not running, so nothing is heard + /// until a press starts it. + /// + /// Unchecked because AVAudioEngine is not Sendable. It is made, stored and + /// taken only on the main actor; the Task that carries it never leaves. + private struct Ready: @unchecked Sendable { + let transcriber: SpeechTranscriber + let analyzer: SpeechAnalyzer + let format: AVAudioFormat + var vocabulary: [String] + let engine: AVAudioEngine + let stream: AsyncStream + let continuation: AsyncStream.Continuation + } + + @ObservationIgnored private var ready: Ready? + @ObservationIgnored private var readying: Task? + @ObservationIgnored private var engine: AVAudioEngine? + @ObservationIgnored private var analyzer: SpeechAnalyzer? + @ObservationIgnored private var input: AsyncStream.Continuation? + @ObservationIgnored private var reading: Task? + @ObservationIgnored private var starting: Task? + /// Bumped by every start and cancel, so a start that finishes preparing + /// after it was called off does not open the microphone anyway. + @ObservationIgnored private var session = 0 + @ObservationIgnored private var clock = Timing() + + /// Get the next session ready without opening the microphone. + /// + /// Only when that needs nobody's permission: the microphone already + /// allowed, and dictation already used on this Mac. A permission prompt or + /// a model download that nobody asked for, triggered by opening a window, + /// would be a strange thing for a notebook to do; the first real press does + /// those. + /// + /// **The installation request is not a download once dictation has + /// worked.** The framework asks for one on every launch, even with the + /// model already on the Mac, and completes it in a fraction of a second. + /// Treating every request as a download stopped the warm-up every time, + /// silently, and each press paid 1.7 seconds building an analyzer while its + /// first words went unheard. + func warm(vocabulary: [String]) { + guard ready == nil, readying == nil, !isActive, VoiceSettings.dictationWorked, + AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else { return } + let task = Task { try await Self.makeReady(vocabulary: vocabulary, download: {}) } + readying = task + Task { [weak self] in + let made: Ready? + do { + made = try await task.value + } catch { + made = nil + Self.log.error("warm-up failed: \(String(describing: error), privacy: .public)") + } + // Only if nothing took the task in the meantime. A start that + // awaited it is already using what it made. + guard let self, self.readying == task else { + if let made { Self.discard(made) } + return + } + self.readying = nil + self.ready = made + } + } + + /// Begin listening. + /// + /// `vocabulary` is words the recogniser should expect - the open notebook's + /// source titles - offered as context. It biases recognition toward them; + /// it does not force them. + func start(vocabulary: [String]) { + guard !isActive else { return } + session += 1 + let mine = session + clock = Timing() + transcript = LiveTranscript() + state = .preparing("Starting the microphone…") + starting = Task { [weak self] in + await self?.begin(vocabulary: vocabulary, session: mine) + } + } + + /// Stop listening and return everything heard. + /// + /// Waits for the recogniser to finalise what it already has, because the + /// last words of a question are usually still volatile at the moment the + /// key comes up, and dropping them loses the end of the sentence. + func stop() async -> String { + clock.mark("released") + await starting?.value + guard state == .listening else { + if case .preparing = state { cancel() } + return transcript.text + } + state = .finishing + closeMicrophone() + do { + try await analyzer?.finalizeAndFinishThroughEndOfInput() + } catch { + // What was heard before the failure is still what was said. + } + await reading?.value + clock.mark("final text") + clock.report() + let vocabulary = currentVocabulary + teardown() + state = .idle + warm(vocabulary: vocabulary) + return transcript.text + } + + /// Stop and throw away what was heard. + func cancel() { + session += 1 + starting?.cancel() + closeMicrophone() + reading?.cancel() + let analyzer = self.analyzer + Task { await analyzer?.cancelAndFinishNow() } + let vocabulary = currentVocabulary + teardown() + transcript = LiveTranscript() + state = .idle + warm(vocabulary: vocabulary) + } + + func clearFailure() { + if case .failed = state { state = .idle } + } + + @ObservationIgnored private var currentVocabulary: [String] = [] + + // ------------------------------------------------------------ starting + + private func begin(vocabulary: [String], session mine: Int) async { + currentVocabulary = vocabulary + do { + try await requireMicrophone() + guard session == mine else { return } + let ready = try await take(vocabulary: vocabulary) + guard session == mine else { Self.discard(ready); return } + + self.engine = ready.engine + self.analyzer = ready.analyzer + self.input = ready.continuation + try ready.engine.start() + clock.mark("microphone open") + let transcriber = ready.transcriber + reading = Task { [weak self] in + do { + for try await result in transcriber.results { + guard let self else { return } + if self.transcript.text.isEmpty { self.clock.mark("first words") } + self.transcript.apply(String(result.text.characters), + isFinal: result.isFinal) + } + } catch { + // The sequence ends with an error when cancelled, which is + // the normal way out of a discarded dictation. + } + } + try await ready.analyzer.start(inputSequence: ready.stream) + state = .listening + VoiceSettings.dictationWorked = true + clock.mark("listening") + } catch { + guard session == mine else { return } + closeMicrophone() + teardown() + state = .failed((error as? Failure)?.message ?? error.localizedDescription) + } + } + + /// The analyzer made ahead of time if there is one, otherwise one made now. + private func take(vocabulary: [String]) async throws -> Ready { + var made: Ready? + if let ready { + self.ready = nil + made = ready + clock.mark("ready (made earlier)") + } else if let readying { + self.readying = nil + do { + made = try await readying.value + clock.mark("ready (was being made)") + } catch { + Self.log.error("warm-up failed: \(String(describing: error), privacy: .public)") + } + } + if var made { + // The notebook's sources may have changed since it was made. + if made.vocabulary != vocabulary { + try? await made.analyzer.setContext(Self.context(vocabulary)) + made.vocabulary = vocabulary + } + return made + } + let fresh = try await Self.makeReady(vocabulary: vocabulary) { [weak self] in + self?.state = .preparing("Downloading the speech model from Apple (once)…") + } + clock.mark("ready (made now)") + return fresh + } + + /// Build an analyzer and load its model. + /// + /// `download` is called before the model is fetched; nil means a missing + /// model is a reason to stop rather than to fetch it. + private static func makeReady(vocabulary: [String], + download: (@MainActor () -> Void)?) async throws -> Ready { + guard SpeechTranscriber.isAvailable, + let locale = await SpeechTranscriber.supportedLocale(equivalentTo: .current) + else { + throw Failure("Dictation is not available for \(Locale.current.identifier) on this Mac.") + } + let transcriber = SpeechTranscriber( + locale: locale, transcriptionOptions: [], + // Fast results trade a little accuracy in the first guess for + // words on screen sooner. The final reading that replaces the guess + // is unaffected, and that is what gets asked. + reportingOptions: [.volatileResults, .fastResults], attributeOptions: []) + + if let request = try await AssetInventory.assetInstallationRequest( + supporting: [transcriber]) { + guard let download else { throw Failure("The speech model is not installed yet.") } + download() + try await request.downloadAndInstall() + } + + let analyzer = SpeechAnalyzer( + modules: [transcriber], + // Kept loaded after use, so the second question in a conversation + // does not pay the model load the first one did. + options: .init(priority: .userInitiated, modelRetention: .lingering)) + guard let format = await SpeechAnalyzer.bestAvailableAudioFormat( + compatibleWith: [transcriber]) else { + throw Failure("The speech model accepts no audio format this Mac can record.") + } + try await analyzer.prepareToAnalyze(in: format) + if !vocabulary.isEmpty { + // Best effort: a context the model declines is a small loss in + // accuracy, not a reason to refuse to listen. + try? await analyzer.setContext(context(vocabulary)) + } + // The audio side too, short of starting it. Starting an engine that is + // already built and tapped is the only part left for the key press. + let (stream, continuation) = AsyncStream.makeStream(of: AnalyzerInput.self) + let engine = AVAudioEngine() + try Microphone.tap(engine, into: continuation, as: format) + engine.prepare() + return Ready(transcriber: transcriber, analyzer: analyzer, format: format, + vocabulary: vocabulary, engine: engine, stream: stream, + continuation: continuation) + } + + /// Let go of a session that was made and never used. + private static func discard(_ ready: Ready) { + ready.engine.inputNode.removeTap(onBus: 0) + ready.continuation.finish() + let analyzer = ready.analyzer + Task { await analyzer.cancelAndFinishNow() } + } + + private static let log = Logger(subsystem: "com.dai.notebookmlx", category: "dictation") + + private static func context(_ vocabulary: [String]) -> AnalysisContext { + let context = AnalysisContext() + context.contextualStrings[.general] = vocabulary + return context + } + + /// Ask for the microphone the first time, and explain a refusal after. + private func requireMicrophone() async throws { + switch AVCaptureDevice.authorizationStatus(for: .audio) { + case .authorized: + return + case .notDetermined: + if await AVCaptureDevice.requestAccess(for: .audio) { return } + fallthrough + default: + throw Failure("notebookMLX is not allowed to use the microphone. " + + "Turn it on in System Settings › Privacy & Security › Microphone.") + } + } + + // ------------------------------------------------------------- stopping + + private func closeMicrophone() { + if let engine { + engine.inputNode.removeTap(onBus: 0) + engine.stop() + } + input?.finish() + } + + private func teardown() { + engine = nil + input = nil + analyzer = nil + reading = nil + starting = nil + } + + struct Failure: Error { + let message: String + init(_ message: String) { self.message = message } + } + + /// Where the time goes in one dictation, written to the unified log. + /// + /// "Slow" has at least four places to live - opening the microphone, + /// loading the model, the first words, and finalising after the release - + /// and each wants a different fix. Read it with: + /// + /// log show --last 5m --predicate 'subsystem == "com.dai.notebookmlx"' + struct Timing { + private let started = ContinuousClock.now + private var marks: [(String, Duration)] = [] + private static let log = Logger(subsystem: "com.dai.notebookmlx", category: "dictation") + + mutating func mark(_ what: String) { + marks.append((what, ContinuousClock.now - started)) + } + + func report() { + let line = marks.map { "\($0.0) +\($0.1.milliseconds)ms" }.joined(separator: ", ") + Self.log.notice("dictation: \(line, privacy: .public)") + } + } +} + +private extension Duration { + var milliseconds: Int64 { + let (seconds, attoseconds) = components + return seconds * 1000 + attoseconds / 1_000_000_000_000_000 + } +} + +/// The audio tap, kept off the main actor. +/// +/// The tap block runs on a real-time audio thread. Formed inside a main-actor +/// type it would inherit that isolation, and Swift 6 checks isolation at run +/// time - the first buffer would stop the app. Built here, in a nonisolated +/// context, it is an ordinary closure. +@available(macOS 26, *) +enum Microphone { + nonisolated static func tap(_ engine: AVAudioEngine, + into continuation: AsyncStream.Continuation, + as format: AVAudioFormat) throws { + let node = engine.inputNode + let natural = node.outputFormat(forBus: 0) + guard natural.sampleRate > 0, natural.channelCount > 0 else { + throw Dictation.Failure("No microphone is connected.") + } + let converter = natural == format ? nil : AVAudioConverter(from: natural, to: format) + if natural != format && converter == nil { + throw Dictation.Failure("The microphone's audio cannot be converted for the speech model.") + } + let feed = Feed(converter: converter, format: format, continuation: continuation) + // Small buffers, so audio reaches the recogniser every ~20 ms rather + // than every ~85 ms. The first words are what a slow start is felt as. + node.installTap(onBus: 0, bufferSize: 1024, format: natural) { buffer, _ in + feed.push(buffer) + } + } + + /// Converts each buffer to the model's format and hands it on. + /// + /// Unchecked because AVAudioConverter is not Sendable; it is only ever used + /// from the one audio thread that calls the tap. + final class Feed: @unchecked Sendable { + let converter: AVAudioConverter? + let format: AVAudioFormat + let continuation: AsyncStream.Continuation + + init(converter: AVAudioConverter?, format: AVAudioFormat, + continuation: AsyncStream.Continuation) { + self.converter = converter + self.format = format + self.continuation = continuation + } + + func push(_ buffer: AVAudioPCMBuffer) { + guard let converter else { + continuation.yield(AnalyzerInput(buffer: buffer)) + return + } + let ratio = format.sampleRate / buffer.format.sampleRate + let capacity = AVAudioFrameCount((Double(buffer.frameLength) * ratio).rounded(.up)) + 16 + guard let out = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: capacity) else { return } + let once = Once(buffer) + var error: NSError? + converter.convert(to: out, error: &error) { _, status in + guard let buffer = once.take() else { + status.pointee = .noDataNow + return nil + } + status.pointee = .haveData + return buffer + } + if error == nil, out.frameLength > 0 { + continuation.yield(AnalyzerInput(buffer: out)) + } + } + } + + /// One buffer, handed to the converter once. + /// + /// The converter's input block is declared @Sendable but is called + /// synchronously, inside `convert`, on the thread that called it. This is + /// the state that call needs, in a form the compiler can accept. + final class Once: @unchecked Sendable { + private var buffer: AVAudioPCMBuffer? + init(_ buffer: AVAudioPCMBuffer) { self.buffer = buffer } + func take() -> AVAudioPCMBuffer? { + defer { buffer = nil } + return buffer + } + } +} diff --git a/Sources/NotebookApp/NotebookModel.swift b/Sources/NotebookApp/NotebookModel.swift index 2624732..6a4ac35 100644 --- a/Sources/NotebookApp/NotebookModel.swift +++ b/Sources/NotebookApp/NotebookModel.swift @@ -307,6 +307,20 @@ final class NotebookModel { } private(set) var pending: Pending? + /// The answer that has just arrived, for whoever wants to act on arrival. + /// + /// Reading answers aloud needs the moment a question is answered, and + /// watching `turns` does not give it: opening a notebook fills `turns` with + /// yesterday's answers, and all of them would be read out. A fresh id per + /// answer is the event; `generated` is false for a retrieval-only turn, + /// whose "answer" is a count of passages and not worth saying. + struct Answered: Equatable { + let id = UUID() + let turn: NotebookPackage.Turn + let generated: Bool + } + private(set) var justAnswered: Answered? + /// The question in flight, so it can be stopped. /// /// Held rather than fired and forgotten. A question takes seconds to answer @@ -431,11 +445,13 @@ final class NotebookModel { // asker cancelled is a record of something that did not happen. try Task.checkCancellation() try package.append(turn) + let generated = gateway != nil await MainActor.run { self?.turns.append(turn) self?.pending = nil self?.asking = false self?.asked = nil + self?.justAnswered = Answered(turn: turn, generated: generated) } } catch is CancellationError { // Already cleared by cancelAsk, and deliberately silent. diff --git a/Sources/NotebookApp/ReadAloud.swift b/Sources/NotebookApp/ReadAloud.swift new file mode 100644 index 0000000..1a09a16 --- /dev/null +++ b/Sources/NotebookApp/ReadAloud.swift @@ -0,0 +1,92 @@ +import AVFoundation +import NotebookKit +import Observation + +/// Answers, spoken. +/// +/// One for the whole app rather than one per window: two windows answering at +/// once should not talk over each other, and a new answer anywhere is the one +/// somebody is waiting to hear. +/// +/// On-device. AVSpeechSynthesizer uses the voices installed on this Mac, so an +/// answer that never left the building is not sent anywhere to be read out. +@Observable @MainActor +final class ReadAloud { + static let shared = ReadAloud() + + private(set) var speaking = false + + @ObservationIgnored private let synthesizer = AVSpeechSynthesizer() + @ObservationIgnored private let watcher = Watcher() + + private init() { + synthesizer.delegate = watcher + watcher.changed = { [weak self] speaking in + Task { @MainActor in self?.speaking = speaking } + } + } + + /// Read a turn's answer, citations and markdown removed. + func speak(_ turn: NotebookPackage.Turn) { + let text = SpeakableText.from(answer: turn.answer, + citations: turn.citations.map(\.citation)) + guard !text.isEmpty else { return } + stop() + let utterance = AVSpeechUtterance(string: text) + if let voice = Self.chosenVoice() { utterance.voice = voice } + synthesizer.speak(utterance) + } + + func stop() { + guard synthesizer.isSpeaking || synthesizer.isPaused else { return } + synthesizer.stopSpeaking(at: .immediate) + } + + /// The voice from Settings, or nil for the system default. + /// + /// A voice that has since been removed from the Mac falls back rather than + /// failing: an answer read in the default voice is better than one not read. + static func chosenVoice() -> AVSpeechSynthesisVoice? { + let id = VoiceSettings.voiceIdentifier + guard !id.isEmpty else { return nil } + return AVSpeechSynthesisVoice(identifier: id) + } + + /// Voices for the current language, best first. + /// + /// The language filter is what makes the list usable: a Mac carries dozens + /// of voices, and an English answer read in a Korean voice is not a choice + /// anybody means to make. + static func voices() -> [AVSpeechSynthesisVoice] { + let language = Locale.current.language.languageCode?.identifier ?? "en" + return AVSpeechSynthesisVoice.speechVoices() + .filter { $0.language.hasPrefix(language) } + .sorted { + if $0.quality != $1.quality { return $0.quality.rawValue > $1.quality.rawValue } + return $0.name < $1.name + } + } + + static func label(for voice: AVSpeechSynthesisVoice) -> String { + let quality = switch voice.quality { + case .premium: " · Premium" + case .enhanced: " · Enhanced" + default: "" + } + return "\(voice.name) (\(voice.language))\(quality)" + } + + /// The delegate, kept apart because its callbacks arrive off the main actor. + private final class Watcher: NSObject, AVSpeechSynthesizerDelegate, @unchecked Sendable { + var changed: (@Sendable (Bool) -> Void)? + func speechSynthesizer(_ s: AVSpeechSynthesizer, didStart u: AVSpeechUtterance) { + changed?(true) + } + func speechSynthesizer(_ s: AVSpeechSynthesizer, didFinish u: AVSpeechUtterance) { + changed?(false) + } + func speechSynthesizer(_ s: AVSpeechSynthesizer, didCancel u: AVSpeechUtterance) { + changed?(false) + } + } +} diff --git a/Sources/NotebookApp/SettingsView.swift b/Sources/NotebookApp/SettingsView.swift index 294f5fe..f55d2b1 100644 --- a/Sources/NotebookApp/SettingsView.swift +++ b/Sources/NotebookApp/SettingsView.swift @@ -17,6 +17,9 @@ struct SettingsView: View { @State private var isDaiFleet: Bool? @State private var maxTokens = GatewaySettings.maxTokens @State private var appearance = Appearance.current + @State private var readAloud = VoiceSettings.readAloud + @State private var holdSpace = VoiceSettings.holdSpace + @State private var voiceID = VoiceSettings.voiceIdentifier @State private var available: [Gateway.Model] = [] @State private var loadingModels = false @State private var modelsProblem: String? @@ -190,6 +193,34 @@ struct SettingsView: View { + "finishes early costs nothing extra.") .font(.caption).foregroundStyle(.secondary) } + Section("Voice") { + // Written as they change, like the theme: these are felt on the + // next question, and a setting that only takes effect when the + // window closes is a setting that seems not to work. + Picker("Read answers aloud", selection: $readAloud) { + ForEach(VoiceSettings.ReadAloud.allCases) { Text($0.label).tag($0) } + } + .onChange(of: readAloud) { _, new in VoiceSettings.readAloud = new } + Picker("Voice", selection: $voiceID) { + Text("System default").tag("") + ForEach(ReadAloud.voices(), id: \.identifier) { v in + Text(ReadAloud.label(for: v)).tag(v.identifier) + } + } + .onChange(of: voiceID) { _, new in VoiceSettings.voiceIdentifier = new } + if #available(macOS 26, *) { + Toggle("Hold space in an empty Ask field to dictate", isOn: $holdSpace) + .onChange(of: holdSpace) { _, new in VoiceSettings.holdSpace = new } + Text("Speech is recognised on this Mac. The first dictation " + + "downloads Apple's speech model once; your audio is " + + "never sent anywhere. Better voices can be added in " + + "System Settings › Accessibility › Spoken Content.") + .font(.caption).foregroundStyle(.secondary) + } else { + Text("Dictation needs macOS 26. Answers can still be read aloud.") + .font(.caption).foregroundStyle(.secondary) + } + } Section("Credential") { // Secure, and stored in the Keychain rather than in defaults: a // key in a plist is readable by anything running as this user diff --git a/Sources/NotebookApp/VoiceInput.swift b/Sources/NotebookApp/VoiceInput.swift new file mode 100644 index 0000000..2f3a8df --- /dev/null +++ b/Sources/NotebookApp/VoiceInput.swift @@ -0,0 +1,288 @@ +import AppKit +import NotebookKit +import Observation +import SwiftUI + +/// Hold space, or click the mic, to put a spoken question in the Ask field. +/// +/// Dictate-then-review: speech fills the field and Return sends it, so a +/// misheard product name is fixed before it reaches the fleet rather than +/// answered. `HoldToTalk` decides what each press of space means; this is the +/// part that listens to the keyboard, owns the microphone and writes the field. +@available(macOS 26, *) +@Observable @MainActor +final class Talker { + + /// What the Ask bar lends this: its field, its focus and whether asking is + /// possible right now. + struct Host { + var text: Binding + var fieldFocused: () -> Bool + var focusField: () -> Void + var enabled: () -> Bool + var vocabulary: () -> [String] + /// Told when a dictation put words in the field, so the answer to that + /// question can be read back. + var dictated: () -> Void + } + + let dictation = Dictation() + /// Whether the current dictation is a held space, which changes what the + /// status line tells somebody to do to stop it. + private(set) var byHold = false + /// What was in the field when dictation started, kept so speech is added + /// to it and so Escape can put it back. + private(set) var typed = "" + + @ObservationIgnored var host: Host? + @ObservationIgnored weak var window: NSWindow? + @ObservationIgnored private var machine = HoldToTalk() + @ObservationIgnored private var monitor: Any? + @ObservationIgnored private var resigned: NSObjectProtocol? + @ObservationIgnored private var heldDown: NSEvent? + @ObservationIgnored private var timer = 0 + @ObservationIgnored private var replaying = false + + // ------------------------------------------------------------ keyboard + + func install() { + guard monitor == nil else { return } + // AppKit calls this on the main thread without saying so in its type. + // Only a Bool crosses back out, because NSEvent is not Sendable. + monitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .keyUp]) { [weak self] event in + nonisolated(unsafe) let seen = event + let keep = MainActor.assumeIsolated { self?.keeps(seen) ?? true } + return keep ? event : nil + } + // A release that lands in another app never arrives here. Without this, + // switching away mid-hold left the microphone open. + resigned = NotificationCenter.default.addObserver( + forName: NSWindow.didResignKeyNotification, object: nil, queue: .main + ) { [weak self] note in + let window = note.object as? NSWindow + MainActor.assumeIsolated { + guard let self, window === self.window else { return } + self.perform(self.machine.handle(.interrupted).effects) + } + } + } + + func uninstall() { + if let monitor { NSEvent.removeMonitor(monitor) } + if let resigned { NotificationCenter.default.removeObserver(resigned) } + monitor = nil + resigned = nil + if dictation.isActive { discard() } + } + + /// Whether the event goes on to the app; false means it was used here. + private func keeps(_ event: NSEvent) -> Bool { + // Only this window's keys, and never the press being replayed. + guard !replaying, let window, event.window === window, host != nil else { return true } + let hold: HoldToTalk.Event + switch (event.type, event.keyCode) { + case (.keyDown, Keys.space): + hold = .spaceDown(isRepeat: event.isARepeat, eligible: eligible(event)) + case (.keyUp, Keys.space): + hold = .spaceUp + case (.keyDown, Keys.escape): + hold = .escape + case (.keyDown, _): + hold = .otherKey + default: + return true + } + if case .spaceDown(isRepeat: false, eligible: true) = hold { heldDown = event } + let outcome = machine.handle(hold) + perform(outcome.effects) + return !outcome.consume + } + + /// Whether a hold may start: only where a space would be wasted. + /// + /// The Ask field when it is empty, or the window when no text is being + /// edited at all. Anywhere else - half a question typed, a rename field, a + /// search box - space is a character and passes straight through. + private func eligible(_ event: NSEvent) -> Bool { + guard VoiceSettings.holdSpace, let host, host.enabled(), !dictation.isActive, + event.modifierFlags.intersection([.command, .control, .option, .shift]).isEmpty + else { return false } + if host.fieldFocused() { return host.text.wrappedValue.isEmpty } + return !(window?.firstResponder is NSText) + } + + private func perform(_ effects: [HoldToTalk.Effect]) { + for effect in effects { + switch effect { + case .replaySpace: + // Sent straight to the app rather than posted to the queue, so + // it is delivered now - ahead of any key that overlapped it - + // and does not come back through this monitor. + if let heldDown { + replaying = true + NSApp.sendEvent(heldDown) + replaying = false + } + heldDown = nil + case .startTimer: + timer += 1 + let mine = timer + Task { [weak self] in + try? await Task.sleep(for: HoldToTalk.threshold) + // A timer from an earlier tap must not decide a later press. + guard let self, mine == self.timer else { return } + self.perform(self.machine.handle(.held).effects) + } + case .startRecording: + // Only the microphone. The field is not focused and nothing is + // silenced until the hold is certain, so a tap that turns out + // to be a tap leaves everything as it was. + begin(byHold: true, confirmed: false) + case .confirmRecording: + heldDown = nil + confirm() + case .stopRecording: + finish() + case .discardRecording: + discard() + } + } + } + + // ---------------------------------------------------------- dictating + + /// The mic button: start, or stop and keep what was said. + func toggle() { + dictation.isActive ? finish() : begin(byHold: false, confirmed: true) + } + + private func begin(byHold: Bool, confirmed: Bool) { + guard let host, !dictation.isActive else { return } + self.byHold = byHold + typed = host.text.wrappedValue + dictation.clearFailure() + dictation.start(vocabulary: host.vocabulary()) + if confirmed { confirm() } + } + + private func confirm() { + // Talking over the last answer is how somebody says they have heard + // enough of it. + ReadAloud.shared.stop() + host?.focusField() + } + + private func finish() { + guard let host else { return } + Task { + let spoken = await dictation.stop() + host.text.wrappedValue = LiveTranscript.compose(typed: typed, spoken: spoken) + if !spoken.isEmpty { host.dictated() } + host.focusField() + } + } + + private func discard() { + dictation.cancel() + host?.text.wrappedValue = typed + } + + /// The field was cleared. A dictation still running would write straight + /// back into it, so it is stopped, and what was typed before it is gone too. + func cleared() { + guard dictation.isActive else { return } + typed = "" + discard() + } + + /// Live text for the field while dictation is running. + func show(_ transcript: LiveTranscript) { + guard dictation.isActive, let host else { return } + host.text.wrappedValue = LiveTranscript.compose(typed: typed, spoken: transcript.text) + } + + /// What the Ask bar's status line says, if anything. + var status: String? { + switch dictation.state { + case .idle: nil + case .preparing(let why): why + case .listening: byHold ? "Listening… let go of space to stop, Esc to discard." + : "Listening… click the microphone to stop." + case .finishing: "Finishing…" + case .failed(let why): why + } + } + + private enum Keys { + static let space: UInt16 = 49 + static let escape: UInt16 = 53 + } +} + +/// The mic button in the Ask bar, and the owner of the keyboard monitor. +@available(macOS 26, *) +struct DictateButton: View { + let host: Talker.Host + @Binding var status: String? + /// Bumped by the Ask bar's clear button. + var clears: Int = 0 + @State private var talker = Talker() + + var body: some View { + Button { talker.toggle() } label: { + Image(systemName: symbol) + .font(.title2) + .foregroundStyle(listening ? Palette.danger : Palette.inkSecondary) + .symbolEffect(.pulse, isActive: listening) + } + .buttonStyle(.plain) + .disabled(!host.enabled() && !talker.dictation.isActive) + .help(talker.dictation.isActive + ? "Stop listening" + : (VoiceSettings.holdSpace ? "Dictate a question (or hold space in the empty field)" + : "Dictate a question")) + .background(WindowReader { talker.window = $0 }) + .onAppear { + talker.host = host + talker.install() + // Loaded now, so the first hold only has to open the microphone. + talker.dictation.warm(vocabulary: host.vocabulary()) + } + .onDisappear { talker.uninstall() } + .onChange(of: clears) { talker.cleared() } + .onChange(of: talker.dictation.transcript) { _, transcript in talker.show(transcript) } + .onChange(of: talker.status, initial: true) { _, now in status = now } + } + + private var listening: Bool { talker.dictation.state == .listening } + + private var symbol: String { + switch talker.dictation.state { + case .listening, .finishing: "mic.fill" + case .failed: "mic.slash" + default: "mic" + } + } +} + +/// The window a SwiftUI view is in, which the key monitor needs so one window's +/// space bar does not start dictation in another. +struct WindowReader: NSViewRepresentable { + let found: (NSWindow?) -> Void + + func makeNSView(context: Context) -> NSView { + let probe = Probe() + probe.found = found + return probe + } + + func updateNSView(_ view: NSView, context: Context) {} + + final class Probe: NSView { + var found: ((NSWindow?) -> Void)? + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + found?(window) + } + } +} diff --git a/Sources/NotebookApp/VoiceSettings.swift b/Sources/NotebookApp/VoiceSettings.swift new file mode 100644 index 0000000..376dd5a --- /dev/null +++ b/Sources/NotebookApp/VoiceSettings.swift @@ -0,0 +1,54 @@ +import Foundation + +/// How the app listens and speaks. Not secret, so defaults, like +/// `GatewaySettings`. +enum VoiceSettings { + + /// When an answer is read aloud. + /// + /// Three states rather than a switch, because the useful default is neither + /// on nor off. Somebody who spoke a question is usually not looking at the + /// screen and wants the answer spoken back; somebody who typed one is + /// reading already, and a voice starting up unasked is an interruption. + enum ReadAloud: String, CaseIterable, Identifiable { + case never, whenSpoken, always + var id: String { rawValue } + var label: String { + switch self { + case .never: "Never" + case .whenSpoken: "When asked by voice" + case .always: "Always" + } + } + } + + static var readAloud: ReadAloud { + get { + UserDefaults.standard.string(forKey: "voice.readAloud") + .flatMap(ReadAloud.init(rawValue:)) ?? .whenSpoken + } + set { UserDefaults.standard.set(newValue.rawValue, forKey: "voice.readAloud") } + } + + /// Whether holding space in an empty Ask field dictates. On by default: it + /// only ever acts where a space would have done nothing useful. + static var holdSpace: Bool { + get { UserDefaults.standard.object(forKey: "voice.holdSpace") as? Bool ?? true } + set { UserDefaults.standard.set(newValue, forKey: "voice.holdSpace") } + } + + /// Whether dictation has worked on this Mac, which is what allows getting + /// it ready in advance: by then the microphone has been allowed and the + /// speech model is installed, so preparing asks nothing of anybody. + static var dictationWorked: Bool { + get { UserDefaults.standard.bool(forKey: "voice.dictationWorked") } + set { UserDefaults.standard.set(newValue, forKey: "voice.dictationWorked") } + } + + /// The voice answers are read in. Empty means the system's default for + /// the current language. + static var voiceIdentifier: String { + get { UserDefaults.standard.string(forKey: "voice.identifier") ?? "" } + set { UserDefaults.standard.set(newValue, forKey: "voice.identifier") } + } +} diff --git a/Sources/NotebookKit/HoldToTalk.swift b/Sources/NotebookKit/HoldToTalk.swift new file mode 100644 index 0000000..f5801c8 --- /dev/null +++ b/Sources/NotebookKit/HoldToTalk.swift @@ -0,0 +1,146 @@ +import Foundation + +/// Holding space to talk, without taking space away from typing. +/// +/// Space is the one key everybody already has under a thumb, and it is also a +/// character. So the first press is held back rather than acted on: released +/// quickly it was a tap, and the held-back press is replayed so the space +/// arrives as if nothing had intervened; still down after `threshold`, it was a +/// hold. Letting go stops it. +/// +/// **Recording starts on the press, not on the decision.** It started once the +/// hold was certain, and a fast talker's first words went into the quarter +/// second spent deciding - measured, together with a cold start, as almost two +/// seconds of speech that never reached the recogniser. So the microphone opens +/// the moment space goes down, and a press that turns out to be a tap throws +/// away the fraction of a second it heard. +/// +/// **Only where a space would be wasted.** The caller decides eligibility - in +/// this app, the Ask field focused and empty, or no text field focused at all - +/// and anywhere else space passes straight through. A hold in the middle of a +/// sentence is somebody holding the key to type spaces, however unlikely. +/// +/// A pure type, events in and effects out, so the rule can be tested without a +/// keyboard, a window or a clock. +public struct HoldToTalk: Equatable, Sendable { + + /// How long space must be held before it counts as a hold. Long enough that + /// a tap from a fast typist is never mistaken for one, short enough that a + /// deliberate hold does not feel like waiting. + public static let threshold: Duration = .milliseconds(250) + + public enum Event: Equatable, Sendable { + /// Space went down. `isRepeat` is the key's autorepeat; `eligible` is + /// whether a hold may start here at all. + case spaceDown(isRepeat: Bool, eligible: Bool) + case spaceUp + /// `threshold` passed since the press being decided. + case held + case escape + /// Any other key while space is down. + case otherKey + /// The window lost focus, or anything else that means the key-up may + /// never arrive. A dictation left running because its release went to + /// another app is a microphone left open. + case interrupted + } + + public enum Effect: Equatable, Sendable { + /// Deliver the space press that was held back. + case replaySpace + /// Start the timer that will send `.held`. + case startTimer + /// Open the microphone. Sent on the press, before it is known whether + /// this is a hold. + case startRecording + /// It is a hold: what is being recorded is meant. + case confirmRecording + case stopRecording + case discardRecording + } + + public struct Outcome: Equatable, Sendable { + /// Whether the event is consumed here rather than passed on. + public var consume: Bool + public var effects: [Effect] + + public static let pass = Outcome(consume: false, effects: []) + public static func swallow(_ effects: Effect...) -> Outcome { + Outcome(consume: true, effects: effects) + } + } + + public enum State: Equatable, Sendable { + case idle + /// Space is down and it is not yet known whether it is a tap or a hold. + case deciding + case recording + /// Escape threw the recording away; waiting for space to come up so its + /// release does not type anything. + case discarded + } + + public private(set) var state: State = .idle + + public init() {} + + public mutating func handle(_ event: Event) -> Outcome { + switch (state, event) { + + case (.idle, .spaceDown(isRepeat: false, eligible: true)): + state = .deciding + return .swallow(.startRecording, .startTimer) + case (.idle, _): + return .pass + + case (.deciding, .held): + state = .recording + return .swallow(.confirmRecording) + case (.deciding, .spaceDown): + // Autorepeat while deciding. Letting it through would type the + // spaces the hold is about to make pointless. + return .swallow() + case (.deciding, .spaceUp): + state = .idle + return .swallow(.discardRecording, .replaySpace) + case (.deciding, .otherKey): + // Typing fast enough that keys overlap: "a b" pressed as space-down, + // b-down, space-up. The space was a space, it goes in first, and + // the other key follows it through untouched. + state = .idle + return Outcome(consume: false, effects: [.discardRecording, .replaySpace]) + case (.deciding, .escape), (.deciding, .interrupted): + state = .idle + return .swallow(.discardRecording) + + case (.recording, .spaceDown): + return .swallow() + case (.recording, .spaceUp): + state = .idle + return .swallow(.stopRecording) + case (.recording, .escape): + state = .discarded + return .swallow(.discardRecording) + case (.recording, .interrupted): + // Kept rather than discarded: what was said before the window lost + // focus was said on purpose. + state = .idle + return .swallow(.stopRecording) + case (.recording, _): + // Other keys still work. Somebody holding space and pressing a + // shortcut meant the shortcut. + return .pass + + case (.discarded, .spaceDown): + return .swallow() + case (.discarded, .spaceUp): + state = .idle + return .swallow() + case (.discarded, .interrupted): + state = .idle + return .swallow() + case (.discarded, _): + return .pass + } + } +} diff --git a/Sources/NotebookKit/LiveTranscript.swift b/Sources/NotebookKit/LiveTranscript.swift new file mode 100644 index 0000000..57bd7e6 --- /dev/null +++ b/Sources/NotebookKit/LiveTranscript.swift @@ -0,0 +1,46 @@ +import Foundation + +/// What has been said so far, while it is still being said. +/// +/// A recogniser answers twice for the same stretch of speech: a *volatile* +/// guess straight away, so the field fills while somebody is talking, and a +/// *final* reading a moment later that replaces it. Appending both produced +/// every phrase twice; keeping only finals left the field empty until a pause. +/// So finals accumulate and the one volatile guess sits on the end, replaced +/// each time a newer guess or its final arrives. +public struct LiveTranscript: Equatable, Sendable { + public private(set) var finalized = "" + public private(set) var volatile = "" + + public init() {} + + public mutating func apply(_ text: String, isFinal: Bool) { + if isFinal { + finalized = Self.join(finalized, text) + volatile = "" + } else { + volatile = text.trimmingCharacters(in: .whitespacesAndNewlines) + } + } + + /// Everything heard, finals first and the current guess after them. + public var text: String { Self.join(finalized, volatile) } + + /// What goes in the field: anything typed before dictation started, then + /// what was said. + /// + /// The typed part is kept as it was. Dictation started from the mic button + /// with half a question already written is adding to that question, and + /// replacing it would throw away the half somebody took the trouble to type. + public static func compose(typed: String, spoken: String) -> String { + join(typed, spoken) + } + + static func join(_ a: String, _ b: String) -> String { + let left = a.trimmingCharacters(in: .whitespacesAndNewlines) + let right = b.trimmingCharacters(in: .whitespacesAndNewlines) + if left.isEmpty { return right } + if right.isEmpty { return left } + return left + " " + right + } +} diff --git a/Sources/NotebookKit/SpeakableText.swift b/Sources/NotebookKit/SpeakableText.swift new file mode 100644 index 0000000..711bd95 --- /dev/null +++ b/Sources/NotebookKit/SpeakableText.swift @@ -0,0 +1,95 @@ +import Foundation + +/// An answer as something worth listening to. +/// +/// An answer is written to be read, and read aloud it is mostly punctuation. +/// "as described in (vcf-9-1.pdf p2518 (2/6))" is a link on screen and eight +/// seconds of a voice spelling out a filename, a page number and a fraction; +/// markdown is worse, because a synthesiser reads "asterisk asterisk" as +/// faithfully as it reads the words between them. +/// +/// **Citations are removed only where the answer is known to name one.** The +/// same conservative match `AnswerLinks` uses to make them clickable decides +/// what is dropped here, so a sentence that happens to contain something shaped +/// like a filename is read as written rather than quietly shortened. The page +/// still carries every citation; what is lost is only the noise of hearing them. +public enum SpeakableText { + + public static func from(answer: String, citations: [String]) -> String { + var text = withoutCitations(answer, citations: citations) + text = withoutMarkdown(text) + return tidied(text) + } + + // ------------------------------------------------------------ citations + + static func withoutCitations(_ answer: String, citations: [String]) -> String { + var text = answer + // Back to front, so the ranges found in the original are still valid + // while later text is removed. + for hit in AnswerLinks.find(in: answer, citations: citations).reversed() { + text.removeSubrange(hit.range) + } + // Whatever held the citation is now empty - "()", "[ ]", or "(, )" + // where two were listed together - and is removed until none are left, + // because emptying the inner pair can empty the outer one. + var previous = "" + while previous != text { + previous = text + text = text.replacing(#/[\(\[][\s,;]*[\)\]]/#, with: "") + } + return text + } + + // ------------------------------------------------------------- markdown + + static func withoutMarkdown(_ text: String) -> String { + var lines: [String] = [] + for raw in text.components(separatedBy: .newlines) { + var line = raw + // A fence is layout, not content. The code inside it is kept: an + // answer that quotes a command is answering with that command. + if line.trimmingCharacters(in: .whitespaces).hasPrefix("```") { continue } + line = line.replacing(#/^\s*#{1,6}\s+/#, with: "") + line = line.replacing(#/^\s*[-*+]\s+/#, with: "") + line = line.replacing(#/^\s*>\s?/#, with: "") + lines.append(line) + } + var out = lines.joined(separator: "\n") + // [words](address) is read as its words; a bare address is not read at + // all, because nobody listening can follow it and it takes longer to + // say than the sentence around it. + out = out.replacing(#/\[([^\]]+)\]\([^)]*\)/#) { String($0.output.1) } + out = out.replacing(#/https?:\/\/\S+/#, with: "") + out = out.replacing("**", with: "") + out = out.replacing("__", with: "") + out = out.replacing("`", with: "") + out = out.replacing("*", with: "") + // A table row read cell by cell, with a pause between cells. + out = out.replacing(#/^\s*\|?[\s:|-]+\|?\s*$/#.anchorsMatchLineEndings(), with: "") + out = out.replacing("|", with: ", ") + return out + } + + // ---------------------------------------------------------------- tidy + + static func tidied(_ text: String) -> String { + var lines: [String] = [] + for raw in text.components(separatedBy: .newlines) { + var line = raw.replacing(#/[ \t]+/#, with: " ") + // What a removal left behind: " ." and " ," read as a pause before + // nothing, and a leading comma as a cough. + line = line.replacing(#/\s+([.,;:!?])/#) { String($0.output.1) } + line = line.replacing(#/^[\s,;]+/#, with: "") + line = line.replacing(#/[\s,;]+$/#, with: "") + line = line.trimmingCharacters(in: .whitespaces) + guard !line.isEmpty else { continue } + // A list item with no full stop runs straight into the next one + // when spoken. The full stop is the pause a reader's eye takes at + // the line break. + if let last = line.last, !".!?:;".contains(last) { line += "." } + lines.append(line) + } + return lines.joined(separator: "\n") + } +} diff --git a/Tests/NotebookKitTests/VoiceTests.swift b/Tests/NotebookKitTests/VoiceTests.swift new file mode 100644 index 0000000..f4bd523 --- /dev/null +++ b/Tests/NotebookKitTests/VoiceTests.swift @@ -0,0 +1,201 @@ +import Testing +@testable import NotebookKit + +/// An answer read aloud should be the answer, not its typesetting. +@Suite("Speakable text") +struct SpeakableTextTests { + + @Test("drops a citation the answer names, and the brackets around it") + func citationDropped() { + let spoken = SpeakableText.from( + answer: "Add the host first (vcf-9-1.pdf p2518 (2/6)), then commission it.", + citations: ["vcf-9-1.pdf p2518 (2/6)"]) + #expect(spoken == "Add the host first, then commission it.") + } + + @Test("drops two citations listed together without leaving their comma") + func twoCitations() { + let spoken = SpeakableText.from( + answer: "Both apply (a-guide.pdf p12, b-manual.pdf p40).", + citations: ["a-guide.pdf p12", "b-manual.pdf p40"]) + #expect(spoken == "Both apply.") + } + + /// The same rule as linking: only names the turn actually cited. Something + /// shaped like a filename that was not retrieved is part of the sentence. + @Test("keeps text that only looks like a citation") + func conservative() { + let spoken = SpeakableText.from( + answer: "Edit settings.json p1 to change it.", + citations: ["other-document.pdf p9"]) + #expect(spoken == "Edit settings.json p1 to change it.") + } + + @Test("reads markdown as its words") + func markdown() { + let answer = """ + ## Steps + - **Stop** the `dai-agent` service + - Read [the manual](https://example.com/manual) first + """ + let spoken = SpeakableText.from(answer: answer, citations: []) + #expect(spoken == "Steps.\nStop the dai-agent service.\nRead the manual first.") + } + + @Test("does not read an address aloud") + func bareURL() { + let spoken = SpeakableText.from( + answer: "The console is at https://control.example.com:8452/ui/ for admins.", + citations: []) + #expect(spoken == "The console is at for admins.") + } + + @Test("keeps the code inside a fence and drops the fence") + func fence() { + let spoken = SpeakableText.from( + answer: "Run:\n```sh\nsudo launchctl kickstart\n```", + citations: []) + #expect(spoken == "Run:\nsudo launchctl kickstart.") + } + + @Test("reads a table row by row") + func table() { + let spoken = SpeakableText.from( + answer: "| Port | Use |\n|---|---|\n| 8452 | admin |", + citations: []) + #expect(spoken == "Port, Use.\n8452, admin.") + } + + @Test("leaves plain prose alone") + func prose() { + let answer = "The group serves one model. It listens on port 8463." + #expect(SpeakableText.from(answer: answer, citations: []) == answer) + } +} + +/// Volatile guesses replace each other; finals accumulate. +@Suite("Live transcript") +struct LiveTranscriptTests { + + @Test("a newer guess replaces the last one rather than adding to it") + func volatileReplaces() { + var t = LiveTranscript() + t.apply("how do", isFinal: false) + t.apply("how do I add", isFinal: false) + #expect(t.text == "how do I add") + } + + @Test("a final replaces its guess and later speech follows it") + func finalThenMore() { + var t = LiveTranscript() + t.apply("how do I add", isFinal: false) + t.apply("How do I add a host?", isFinal: true) + t.apply("to the", isFinal: false) + #expect(t.text == "How do I add a host? to the") + t.apply(" To the cluster.", isFinal: true) + #expect(t.text == "How do I add a host? To the cluster.") + #expect(t.volatile.isEmpty) + } + + @Test("dictation adds to what was typed rather than replacing it") + func compose() { + #expect(LiveTranscript.compose(typed: "In the manual, ", spoken: "how do I add a host?") + == "In the manual, how do I add a host?") + #expect(LiveTranscript.compose(typed: "", spoken: "hello") == "hello") + #expect(LiveTranscript.compose(typed: "typed", spoken: "") == "typed") + } +} + +/// Space is both a character and the talk key; these are the ways it can go. +@Suite("Hold to talk") +struct HoldToTalkTests { + + /// The microphone opens on the press. Waiting for the hold to be certain + /// lost a fast talker's first words. + @Test("recording starts on the press, before the hold is certain") + func recordsOnPress() { + var h = HoldToTalk() + #expect(h.handle(.spaceDown(isRepeat: false, eligible: true)) + == .swallow(.startRecording, .startTimer)) + } + + @Test("a tap throws away what it heard and is replayed as a space") + func tap() { + var h = HoldToTalk() + _ = h.handle(.spaceDown(isRepeat: false, eligible: true)) + #expect(h.handle(.spaceUp) == .swallow(.discardRecording, .replaySpace)) + #expect(h.state == .idle) + } + + @Test("a hold records until space comes up") + func hold() { + var h = HoldToTalk() + _ = h.handle(.spaceDown(isRepeat: false, eligible: true)) + #expect(h.handle(.held) == .swallow(.confirmRecording)) + #expect(h.handle(.spaceDown(isRepeat: true, eligible: true)) == .swallow()) + #expect(h.handle(.spaceUp) == .swallow(.stopRecording)) + #expect(h.state == .idle) + } + + @Test("autorepeat while deciding types nothing") + func repeatWhileDeciding() { + var h = HoldToTalk() + _ = h.handle(.spaceDown(isRepeat: false, eligible: true)) + #expect(h.handle(.spaceDown(isRepeat: true, eligible: true)) == .swallow()) + } + + @Test("space passes straight through where a hold may not start") + func ineligible() { + var h = HoldToTalk() + #expect(h.handle(.spaceDown(isRepeat: false, eligible: false)) == .pass) + #expect(h.handle(.spaceUp) == .pass) + #expect(h.state == .idle) + } + + @Test("a timer that fires after a tap does nothing") + func staleTimer() { + var h = HoldToTalk() + _ = h.handle(.spaceDown(isRepeat: false, eligible: true)) + _ = h.handle(.spaceUp) + #expect(h.handle(.held) == .pass) + #expect(h.state == .idle) + } + + @Test("overlapping keys from fast typing keep their order") + func rollover() { + var h = HoldToTalk() + _ = h.handle(.spaceDown(isRepeat: false, eligible: true)) + let outcome = h.handle(.otherKey) + #expect(outcome == HoldToTalk.Outcome(consume: false, + effects: [.discardRecording, .replaySpace])) + #expect(h.state == .idle) + } + + @Test("escape throws the recording away and the release types nothing") + func escape() { + var h = HoldToTalk() + _ = h.handle(.spaceDown(isRepeat: false, eligible: true)) + _ = h.handle(.held) + #expect(h.handle(.escape) == .swallow(.discardRecording)) + #expect(h.handle(.spaceUp) == .swallow()) + #expect(h.state == .idle) + } + + @Test("losing focus while recording stops rather than leaving the mic open") + func interrupted() { + var h = HoldToTalk() + _ = h.handle(.spaceDown(isRepeat: false, eligible: true)) + _ = h.handle(.held) + #expect(h.handle(.interrupted) == .swallow(.stopRecording)) + #expect(h.state == .idle) + } + + @Test("other keys still work while recording") + func shortcutsWhileRecording() { + var h = HoldToTalk() + _ = h.handle(.spaceDown(isRepeat: false, eligible: true)) + _ = h.handle(.held) + #expect(h.handle(.otherKey) == .pass) + #expect(h.state == .recording) + } +} diff --git a/packaging/NotebookMLX.entitlements b/packaging/NotebookMLX.entitlements new file mode 100644 index 0000000..d0c59a0 --- /dev/null +++ b/packaging/NotebookMLX.entitlements @@ -0,0 +1,10 @@ + + + + + + com.apple.security.device.audio-input + + diff --git a/packaging/make-app.sh b/packaging/make-app.sh index 9a85661..016ddb3 100755 --- a/packaging/make-app.sh +++ b/packaging/make-app.sh @@ -90,6 +90,13 @@ cat > "$APP/Contents/Info.plist" <<'PLIST' LSUIElement NSHighResolutionCapable + + NSMicrophoneUsageDescription + notebookMLX listens only while you hold space or click the microphone, to turn a spoken question into text. Recognition happens on this Mac. + NSSpeechRecognitionUsageDescription + Your spoken question is recognised on this Mac and never sent anywhere.