use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use std::sync::Mutex; use std::sync::Once; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError}; use std::thread; use std::time::Instant; use color_eyre::eyre::{Result, WrapErr, eyre}; use transcribe_cpp::{Backend, Model, ModelOptions, RunOptions, TimestampKind, Transcript}; use crate::continuation::InputActivity; use crate::dictation::context::ContextSnapshot; use crate::dictation::processor::ProcessingObservation; use crate::dictation::{DictationClip, pad_for_parakeet}; use crate::history::{History, HistoryDraft, HistoryKind}; use crate::meeting; use crate::paste::{PasteMode, Paster}; use crate::transcription::WarmTranscriber; use crate::transcription::engine::{PendingTranscript, TranscriptionEngine}; use crate::transcription::gguf_session::{OfflineGgufSession, output_truncated}; use crate::transcription::models::{ TranscriptionModelId, TranscriptionSelection, model_path, validate, }; pub struct Parakeet { session: OfflineGgufSession, options: RunOptions, name: String, selection: Option, max_audio_samples: Option, _weights: procwatch::Lease, } /// Loaded model weights, estimated from the model file size (they live in Metal buffers). static MODEL_WEIGHTS: procwatch::Gauge = procwatch::Gauge::new("speech.model_weights"); static TRANSCRIBE_LOGGING: Once = Once::new(); #[cfg(hex_capture)] const TRANSCRIPTION_SAMPLES_PER_MS: usize = 16; const MAX_PENDING_OUTPUTS: usize = 16; pub enum WorkerEvent { ModelFailed(String), Completed { job_id: DictationJobId, target: TranscriptionTarget, result: Result, processing: Option, }, Stage { job_id: DictationJobId, stage: DictationJobStage, }, Pasted { kind: PasteKind, result: Result, }, } #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct DictationJobId(u64); impl DictationJobId { pub const fn value(self) -> u64 { self.0 } #[cfg(test)] pub(crate) const fn for_test(value: u64) -> Self { Self(value) } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DictationJobStage { Transcribing, Processing, } #[derive(Clone, Copy, Debug)] pub enum PasteKind { LastTranscript, MeetingDelta, } #[derive(Clone, Copy, Debug)] pub enum TranscriptionTarget { Paste, /// A recording microphone interrupted a shortcut dictation: processed /// like a paste, but copied to the clipboard instead of pasted, still /// available to Paste Last Dictation and kept in History. CopyOnlyPaste, /// The same interrupted recording from Dictate without processing: copied /// as heard, skipping the Output pane's steps. RawCopyOnlyPaste, /// Dictate without processing: pasted as heard, skipping the Output /// pane's steps. RawPaste, Service, /// `hex dictation stop --print`: processed as a paste, then handed to /// the waiting command instead of pasted. Print, /// A printing stop of a raw dictation: the transcript as heard. RawPrint, } struct InferenceJob { job_id: DictationJobId, control: Arc, submitted_at: Instant, transcript: PendingTranscript, audio_ms: u64, prepare_ms: u128, target: TranscriptionTarget, context: ContextSnapshot, /// Labs › Return to app: the app the capture started in, which the /// paste returns to (macOS). return_to: Option, /// The language the model was asked for at submission. language: String, /// The clip, kept for History while Labs › Keep recordings is on. recording: Option, /// See [`JobTimings::send_gate`]. send_gate: Option, /// Labs › Stop phrase: the words its capture ended with, read when the /// phrase was heard, removed from the transcript before processing. stop_phrase: Option, } struct ProcessorJob { job_id: DictationJobId, control: Arc, target: TranscriptionTarget, text: String, context: ContextSnapshot, return_to: Option, language: String, timings: JobTimings, recording: Option, } /// Pipeline timings carried from inference through output for the final log. #[derive(Clone, Copy)] struct JobTimings { total_started: Instant, queue_ms: u128, audio_ms: u64, prepare_ms: u128, inference_ms: u128, /// Only a shortcut's processed paste can send. An Escape after /// submission lets the text paste but skips Return. send_gate: Option, } struct CompletedTranscript { text: String, /// Labs › Rewrite by voice asked for nothing: finish without output even if /// some later stage left text behind. nothing: bool, /// Corrected local transcript before mode processing. raw: String, application: Option, /// [`crate::dictation::context::ContextSnapshot::bundle_name`]. bundle_name: Option, /// Labs › Return to app: the app the capture started in, which the /// paste returns to (macOS). return_to: Option, timings: JobTimings, processing: Option, recording: Option, } enum OutputJob { PreparePaste, #[cfg(hex_capture)] Recent { sequence: u64, request: crate::paste::recent::Request, }, Completed { job_id: DictationJobId, control: Arc, target: TranscriptionTarget, result: Box>, }, Paste { sequence: u64, kind: PasteKind, }, } impl OutputJob { fn sequence(&self) -> u64 { match self { Self::PreparePaste => u64::MAX, #[cfg(hex_capture)] Self::Recent { sequence, .. } => *sequence, Self::Completed { job_id, .. } => job_id.0, Self::Paste { sequence, .. } => *sequence, } } } #[derive(Default)] struct JobControl { /// A printing stop's reply; dropping the job unanswered tells it the /// dictation was cancelled or failed. print: Mutex>, } impl JobControl { fn answer_print(&self, transcript: crate::control::PrintedTranscript) { if let Some(reply) = self .print .lock() .unwrap_or_else(|error| error.into_inner()) .take() { reply.send(transcript); } } } #[derive(Default)] struct OrderedOutputs { waiting: BTreeMap, next_sequence: u64, } impl OrderedOutputs { fn push(&mut self, job: OutputJob) -> Vec { if job.sequence() < self.next_sequence { return Vec::new(); } self.waiting.insert(job.sequence(), job); let mut ready = Vec::new(); while let Some(job) = self.waiting.remove(&self.next_sequence) { ready.push(job); self.next_sequence += 1; } ready } } pub struct DictationWorker { engine: Option>, inference_jobs: Option>, output_jobs: Option>, events: Receiver, event_sender: mpsc::Sender, state: Arc>, inference_worker: Option>, processor_workers: Vec>, output_worker: Option>, } struct WorkerState { next_sequence: u64, jobs: BTreeSet, pending_pastes: usize, /// Labs › Return to app: the app in front when the capture started, /// which its output returns to (macOS). return_to: Option, /// Whether the dictation shortcut, rather than `hex dictation`, started /// the capture now recording (Labs › YOLO mode). started_by_shortcut: bool, } impl WorkerState { fn next_output_sequence(&self) -> Result { // Count accepted work even after it leaves a channel for ordered buffering. if self.jobs.len() + self.pending_pastes >= MAX_PENDING_OUTPUTS { return Err("dictation queue is full"); } Ok(self.next_sequence) } } impl DictationWorker { pub fn start( activity: InputActivity, transformations: Arc, history: Option, ) -> Self { const PROCESSOR_WORKERS: usize = 2; // Admission caps accepted jobs, so a submitted job always has a slot. let (inference_jobs, inference_receiver) = mpsc::sync_channel::(MAX_PENDING_OUTPUTS); let (processor_jobs, processor_receiver) = mpsc::sync_channel::(4); let (output_jobs, output_receiver) = mpsc::sync_channel::(8); let (event_sender, events) = mpsc::channel(); let state = Arc::new(Mutex::new(WorkerState { next_sequence: 0, jobs: BTreeSet::new(), pending_pastes: 0, return_to: None, started_by_shortcut: false, })); let (_, selection) = crate::app_settings::transcription_selection(); // Labs › Free memory when idle parks a GGUF model at launch too: // the first dictation reloads it, so memory stays free until then. // Apple Speech holds no model of Hex's and stays loaded. let parked = crate::labs::unload_idle().is_some() && matches!( validate(&selection).map(|definition| definition.runtime), Ok(crate::transcription::models::ModelRuntime::Gguf(_)) ); let engine = if parked { TranscriptionEngine::start_parked(selection) } else { TranscriptionEngine::start(WarmTranscriber::default()) }; let engine = match engine { Ok(engine) => { if !parked { let events = event_sender.clone(); let _ = engine.run(move |model| { prioritize_inference_thread(); match WarmTranscriber::load() { Ok(loaded) => { tracing::info!("transcription model loaded"); *model = loaded; } Err(error) => { let _ = events.send(WorkerEvent::ModelFailed(error.to_string())); } } }); } let engine = Arc::new(engine); engine.share(); Some(engine) } Err(error) => { let _ = event_sender.send(WorkerEvent::ModelFailed(error.to_string())); None } }; let output_worker = thread::spawn({ let state = state.clone(); let events = event_sender.clone(); move || run_output_worker(output_receiver, activity, history, &state, &events) }); let processor_receiver = Arc::new(Mutex::new(processor_receiver)); let processor_workers = (0..PROCESSOR_WORKERS) .map(|_| { let jobs = processor_receiver.clone(); let output = output_jobs.clone(); let events = event_sender.clone(); let transformations = transformations.clone(); thread::spawn(move || { run_processor_worker(&jobs, &output, &events, &transformations) }) }) .collect(); let inference_worker = thread::spawn({ let output = output_jobs.clone(); let events = event_sender.clone(); move || run_inference_worker(inference_receiver, &processor_jobs, &output, &events) }); Self { engine, inference_jobs: Some(inference_jobs), output_jobs: Some(output_jobs), events, event_sender, state, inference_worker: Some(inference_worker), processor_workers, output_worker: Some(output_worker), } } /// Labs › Return to app (macOS): remembers the app in front as this /// capture starts, so its paste can bring it back. Read only while the /// lab is on, and never Hex itself. pub fn remember_return_to_app(&self) { let return_to = crate::paste::return_to_app::capture_start(); let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); state.return_to = return_to; } /// Records who started the capture now recording: a dictation shortcut, /// or a `hex dictation` command. Only a shortcut's paste may send /// (Labs › YOLO mode). pub fn set_started_by_shortcut(&self, by_shortcut: bool) { let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); state.started_by_shortcut = by_shortcut; } #[cfg(hex_capture)] pub(crate) fn started_by_shortcut(&self) -> bool { self.state .lock() .unwrap_or_else(|e| e.into_inner()) .started_by_shortcut } /// Hands the clip to the engine at once, so its live stream finishes /// before any later capture begins one; the job then waits in order. pub fn transcribe( &self, clip: DictationClip, target: TranscriptionTarget, context: ContextSnapshot, stop_phrase: Option, ) -> Result { self.submit(clip, target, context, None, stop_phrase) } /// Like a paste, but the transcript (processed unless `raw`) goes to /// `print`. pub fn transcribe_printed( &self, clip: DictationClip, print: crate::control::PrintReply, raw: bool, context: ContextSnapshot, stop_phrase: Option, ) -> Result { let target = if raw { TranscriptionTarget::RawPrint } else { TranscriptionTarget::Print }; self.submit(clip, target, context, Some(print), stop_phrase) } fn submit( &self, mut clip: DictationClip, target: TranscriptionTarget, context: ContextSnapshot, print: Option, stop_phrase: Option, ) -> Result { let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); let job_id = DictationJobId(state.next_output_sequence()?); // Labs › Return to app: only a paste returns to an app; a printing // stop and the service never paste. let return_to = matches!( target, TranscriptionTarget::Paste | TranscriptionTarget::RawPaste ) .then(|| state.return_to.take()) .flatten(); let (Some(engine), Some(jobs)) = (&self.engine, &self.inference_jobs) else { return Err("dictation worker is unavailable"); }; let control = Arc::new(JobControl { print: Mutex::new(print), }); let (_, selection) = crate::app_settings::transcription_selection(); let language = selection.language.clone(); let submitted_at = Instant::now(); let audio_ms = clip.duration_ms(); let send_gate = (matches!(target, TranscriptionTarget::Paste) && state.started_by_shortcut) .then(crate::dictation::yolo_mode::SendGate::open); // Labs › Words on screen: this capture's terms belong to its // whole-clip run and no other job. Only a model that reads the terms // gives up its live stream, whose vocabulary is fixed when it starts // (before the window was read); a model that ignores them keeps it. let screen_terms = context.screen_terms.clone(); let keeps_stream = screen_terms.is_empty() || !crate::dictation::vocabulary::uses_terms(); let stream = clip.take_stream().filter(|_| keeps_stream); let _capture = clip.take_capture_marker(); let samples = clip.into_transcription_samples(); crate::dictation::diagnostics::persist(&samples); let recording = match target { TranscriptionTarget::Service => None, _ => crate::history::Recording::keep(&samples), }; let prepare_ms = submitted_at.elapsed().as_millis(); let offline = Box::new(move |model: &mut WarmTranscriber, samples: Vec| { let _busy = DictationInference::begin(); let transcriber = model .activate(&selection) .map_err(|error| error.to_string())?; crate::dictation::vocabulary::for_capture(&screen_terms, || { transcriber.transcribe(samples) }) .map_err(|error| error.to_string()) }); let transcript = engine .finish_with(stream, samples, offline) .map_err(|_| "dictation worker is unavailable")?; jobs.try_send(InferenceJob { job_id, control, submitted_at, transcript, audio_ms, prepare_ms, target, context, return_to, language, recording, send_gate, stop_phrase, }) .map(|()| { state.next_sequence += 1; state.jobs.insert(job_id); job_id }) .map_err(queue_error) } /// The engine that streams hotkey captures while they are recorded. pub fn engine(&self) -> Option> { self.engine.clone() } pub fn prepare_paste(&self) { let state = self.state.lock().unwrap_or_else(|error| error.into_inner()); if !state.jobs.is_empty() || state.pending_pastes > 0 { return; } drop(state); let Some(output_jobs) = &self.output_jobs else { return; }; let _ = output_jobs.try_send(OutputJob::PreparePaste); } /// Switches the warm model after the work already handed to the engine. pub fn reload(&self, selection: TranscriptionSelection) -> Result<(), &'static str> { let events = self.event_sender.clone(); self.engine .as_ref() .ok_or("dictation worker is unavailable")? .run(move |model| { let _busy = DictationInference::begin(); if let Err(error) = model.activate(&selection) { let _ = events.send(WorkerEvent::ModelFailed(error.to_string())); } }) .map_err(|_| "dictation worker is unavailable") } pub fn paste_last(&self) -> Result<(), &'static str> { #[cfg(hex_capture)] if crate::paste::recent::enabled() { return self.paste_recent(crate::paste::recent::Request { id: None, target: crate::paste::recent::Target::capture() .ok_or("could not confirm the paste target")?, }); } self.submit_paste(PasteKind::LastTranscript) } pub fn paste_meeting(&self) -> Result<(), &'static str> { self.submit_paste(PasteKind::MeetingDelta) } fn submit_paste(&self, kind: PasteKind) -> Result<(), &'static str> { self.enqueue_paste(|sequence| OutputJob::Paste { sequence, kind }) } #[cfg(hex_capture)] pub(crate) fn paste_recent( &self, request: crate::paste::recent::Request, ) -> Result<(), &'static str> { self.enqueue_paste(|sequence| OutputJob::Recent { sequence, request }) } fn enqueue_paste(&self, job: impl FnOnce(u64) -> OutputJob) -> Result<(), &'static str> { let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); let sequence = state.next_output_sequence()?; self.output_jobs .as_ref() .ok_or("dictation worker is unavailable")? .try_send(job(sequence)) .map(|()| { state.next_sequence += 1; state.pending_pastes += 1; }) .map_err(queue_error) } pub fn try_recv(&self) -> Option { self.events.try_recv().ok() } pub fn is_busy(&self) -> bool { let state = self.state.lock().unwrap_or_else(|error| error.into_inner()); !state.jobs.is_empty() || state.pending_pastes > 0 } pub fn pending_count(&self) -> usize { self.state .lock() .unwrap_or_else(|error| error.into_inner()) .jobs .len() } fn shutdown(&mut self) { // Accepted jobs still finish: the inference worker drains its queue. self.inference_jobs.take(); join_worker(self.inference_worker.take(), "dictation inference"); for worker in self.processor_workers.drain(..) { join_worker(Some(worker), "dictation processing"); } self.output_jobs.take(); join_worker(self.output_worker.take(), "dictation output"); } } impl Drop for DictationWorker { fn drop(&mut self) { self.shutdown(); } } fn run_output_worker( jobs: Receiver, activity: InputActivity, history: Option, state: &Mutex, events: &mpsc::Sender, ) { let mut paster = Paster::new(activity); let mut last_transcript = None; let mut ordered = OrderedOutputs::default(); while let Ok(job) = jobs.recv() { if matches!(job, OutputJob::PreparePaste) { paster.prepare(); continue; } for job in ordered.push(job) { let event = match job { #[cfg(hex_capture)] OutputJob::Recent { request, .. } => WorkerEvent::Pasted { kind: PasteKind::LastTranscript, result: request .insert(&mut paster, history.as_ref()) .map_err(|e| e.to_string()), }, job => finish_output( job, &mut |text, mode| paster.paste(text, mode), &mut last_transcript, history.as_ref(), ), }; let mut state = state.lock().unwrap_or_else(|error| error.into_inner()); match &event { WorkerEvent::Completed { job_id, .. } => { state.jobs.remove(job_id); } WorkerEvent::Pasted { .. } => { state.pending_pastes = state.pending_pastes.saturating_sub(1); } WorkerEvent::ModelFailed(_) | WorkerEvent::Stage { .. } => {} } drop(state); if events.send(event).is_err() { return; } } } } fn run_processor_worker( jobs: &Mutex>, output: &SyncSender, events: &mpsc::Sender, transformations: &crate::personal_commands::TransformationClient, ) { loop { let job = jobs .lock() .unwrap_or_else(|error| error.into_inner()) .recv(); let Ok(job) = job else { break }; let mut processed = process_job_text(&job, crate::dictation::config::dictation_profiles, || { let _ = events.send(WorkerEvent::Stage { job_id: job.job_id, stage: DictationJobStage::Processing, }); }); processed.apply_transformations( transformations, &job.context, &AtomicBool::new(false), crate::dictation::processor::Source::Dictation, ); if let Some(observation) = &processed.observation && let Some(error) = &observation.fallback { tracing::warn!( profile = observation.profile, %error, "dictation processing fell back to the previous pipeline output" ); } if output .send(OutputJob::Completed { job_id: job.job_id, control: job.control, target: job.target, result: Box::new(Ok(CompletedTranscript { text: processed.text, nothing: processed.nothing, raw: job.text, application: job.context.application, bundle_name: job.context.bundle_name, return_to: job.return_to, timings: job.timings, processing: processed.observation, recording: job.recording, })), }) .is_err() { break; } } } /// Select processing when the worker reaches the job; the stage precedes processing. fn process_job_text( job: &ProcessorJob, profiles: impl FnOnce() -> crate::dictation::processor::Profiles, processing: impl FnOnce(), ) -> crate::dictation::processor::Processed { let profiles = profiles(); // A voice prompt can run a request even when the mode's own rewrite and // transformations are off, so the HUD shows its stage too. if profiles.processes(&job.context) || profiles.voice_prompts( &job.text, &job.language, &job.context, crate::dictation::processor::Source::Dictation, ) { processing(); } profiles.process_cancellable( &job.text, &job.language, &job.context, &AtomicBool::new(false), crate::dictation::processor::Source::Dictation, ) } /// The longest audio the capture path hands the model at once; longer /// captures are transcribed in consecutive chunks with their times offset. #[cfg(hex_capture)] const WORD_CHUNK_SAMPLES: usize = 30 * 16_000; /// How long a capture chunk waits for dictation to go idle before it is /// queued anyway; the engine still never runs it inside a live stream. #[cfg(hex_capture)] const WORD_DICTATION_WAIT: std::time::Duration = std::time::Duration::from_secs(20); /// Transcribes a capture's 16 kHz audio with word timestamps on the engine's /// warm model (the `capture` experiment). Before each chunk it waits while /// dictation is busy (from the shortcut press through inference); each chunk /// is then a foreground request: after the dictation already sent, before /// meeting chunks, and never inside a dictation live stream, which finishes /// first. No second copy of the model is loaded, and only a weak reference /// to the engine is kept between chunks. Quitting stops it between chunks. /// Every chunk runs on `selection`. #[cfg(hex_capture)] pub fn transcribe_with_words( engine: &std::sync::Weak, selection: &crate::transcription::models::TranscriptionSelection, samples: Vec, ) -> Result { if samples.is_empty() { return Ok(crate::transcription::Transcript::default()); } transcribe_in_chunks(samples, WORD_CHUNK_SAMPLES, |chunk| { wait_for_dictation_idle()?; let selection = selection.clone(); let (send, transcript) = mpsc::sync_channel(1); let offline: crate::transcription::engine::Offline = Box::new(move |model, samples| { let _busy = DictationInference::begin(); let transcriber = model .activate(&selection) .map_err(|error| format!("{error:#}"))?; let result = transcriber .transcribe_segments(samples) .map_err(|error| format!("{error:#}"))?; let text = result.text.clone(); let _ = send.send(result); Ok(text) }); let pending = engine .upgrade() .ok_or_else(|| eyre!("the transcription engine stopped"))? .foreground(chunk, offline)?; pending.wait().map_err(|error| eyre!(error))?; transcript .try_recv() .map_err(|_| eyre!("the transcription returned no words")) }) } #[cfg(hex_capture)] fn wait_for_dictation_idle() -> Result<()> { let started = Instant::now(); while dictation_busy() && !crate::desktop::process_exit::quitting() && started.elapsed() < WORD_DICTATION_WAIT { thread::sleep(std::time::Duration::from_millis(50)); } if crate::desktop::process_exit::quitting() { return Err(eyre!("Hex is quitting")); } Ok(()) } /// Transcribes `samples` in chunks of at most `chunk_samples`, offsetting /// each chunk's segment and word times by where it starts. #[cfg(hex_capture)] fn transcribe_in_chunks( samples: Vec, chunk_samples: usize, mut transcribe: impl FnMut(Vec) -> Result, ) -> Result { use crate::transcription::{Transcript, TranscriptSegment}; let shift = |spans: Vec, offset_ms: i64| { spans.into_iter().filter_map(move |span| { let text = span.text.trim(); let start_ms = span.start_ms.max(0); (!text.is_empty()).then(|| TranscriptSegment { start_ms: start_ms + offset_ms, end_ms: span.end_ms.max(start_ms) + offset_ms, text: text.to_string(), }) }) }; let mut merged = Transcript::default(); let mut texts = Vec::new(); for (index, chunk) in samples.chunks(chunk_samples.max(1)).enumerate() { let offset_ms = (index * chunk_samples / TRANSCRIPTION_SAMPLES_PER_MS) as i64; let result = transcribe(chunk.to_vec())?; let text = result.text.trim(); if !text.is_empty() { texts.push(text.to_string()); } merged.segments.extend(shift(result.segments, offset_ms)); merged.words.extend(shift(result.words, offset_ms)); } merged.text = texts.join(" "); Ok(merged) } /// Waits for each accepted job's transcript in submission order, then hands /// it to processing. The engine thread runs the inference itself. fn run_inference_worker( jobs: Receiver, processor_jobs: &SyncSender, output: &SyncSender, events: &mpsc::Sender, ) { while let Ok(job) = jobs.recv() { let _busy = DictationInference::begin(); let _ = events.send(WorkerEvent::Stage { job_id: job.job_id, stage: DictationJobStage::Transcribing, }); let total_started = job.submitted_at; let queue_ms = total_started.elapsed().as_millis(); let inference_started = Instant::now(); let audio_ms = job.audio_ms; let result = job.transcript.wait().map(|transcribed| { tracing::info!( source = transcribed.source.label(), finish_ms = transcribed.finish_ms, audio_ms, "transcribed dictation" ); let text = transcribed.text; // Labs › Stop phrase: the words that finished this capture never // reach the text, and a capture that was only the phrase reads as // empty. let text = crate::dictation::stop_phrase::strip_finished(text, job.stop_phrase.as_deref()); let corrected = if matches!(job.target, TranscriptionTarget::Service) { text.clone() } else { text.trim().to_string() }; tracing::debug!( raw_transcript = text, corrected_transcript = corrected, "prepared local transcript" ); corrected }); let timings = JobTimings { total_started, queue_ms, audio_ms, prepare_ms: job.prepare_ms, inference_ms: inference_started.elapsed().as_millis(), send_gate: job.send_gate, }; let target = job.target; match result { Ok(text) if matches!( target, TranscriptionTarget::Paste | TranscriptionTarget::CopyOnlyPaste | TranscriptionTarget::Print ) && !text.trim().is_empty() => { if processor_jobs .send(ProcessorJob { job_id: job.job_id, control: job.control, target, text, context: job.context, return_to: job.return_to, language: job.language, timings, recording: job.recording, }) .is_err() { break; } } result => { let application = job.context.application; let bundle_name = job.context.bundle_name; let recording = job.recording; let result = result.map(|text| CompletedTranscript { raw: text.clone(), text, nothing: false, application, bundle_name, return_to: job.return_to, timings, processing: None, recording, }); if output .send(OutputJob::Completed { job_id: job.job_id, control: job.control, target, result: Box::new(result), }) .is_err() { break; } } } } } fn join_worker(worker: Option>, name: &str) { if let Some(worker) = worker && worker.join().is_err() { tracing::error!(worker = name, "worker panicked during shutdown"); } } #[cfg(target_os = "macos")] pub(crate) fn prioritize_inference_thread() { // ggml worker pthreads start at default QoS instead of inheriting this // class; GGUF sessions use one decoder thread so decoding stays here. const QOS_CLASS_USER_INTERACTIVE: u32 = 0x21; unsafe extern "C" { fn pthread_set_qos_class_self_np(qos_class: u32, relative_priority: i32) -> i32; } // SAFETY: This configures only the calling worker thread using the public // macOS pthread QoS API. Relative priority zero is valid for this class. let status = unsafe { pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0) }; if status == 0 { tracing::info!("dictation inference worker uses user-interactive QoS"); } else { tracing::warn!(status, "could not raise dictation inference worker QoS"); } } #[cfg(not(target_os = "macos"))] pub(crate) fn prioritize_inference_thread() {} static DICTATION_INFERENCE: AtomicUsize = AtomicUsize::new(0); struct DictationInference; impl DictationInference { fn begin() -> Self { DICTATION_INFERENCE.fetch_add(1, Ordering::AcqRel); Self } } impl Drop for DictationInference { fn drop(&mut self) { DICTATION_INFERENCE.fetch_sub(1, Ordering::AcqRel); } } /// Makes [`dictation_busy`] hold until dropped, as a dictation would. #[cfg(test)] pub(crate) struct DictationBusyForTest { _busy: DictationInference, } #[cfg(test)] pub(crate) fn dictation_busy_for_test() -> DictationBusyForTest { DictationBusyForTest { _busy: DictationInference::begin(), } } /// Whether dictation is capturing or running inference. Meeting /// transcription starts no chunk while this holds. A capture counts from its /// press: a chunk already running then finishes during the hold threshold /// and release tail, before the clip needs the model. pub(crate) fn dictation_busy() -> bool { DICTATION_INFERENCE.load(Ordering::Acquire) > 0 || crate::audio::recording_environment::capture_active() || crate::audio::recording_environment::intentional_recording_active() } /// Runs `work` at utility QoS on the dictation inference thread, then /// restores its user-interactive class. pub(crate) fn at_background_priority(work: impl FnOnce() -> R) -> R { const QOS_CLASS_USER_INTERACTIVE: u32 = 0x21; const QOS_CLASS_UTILITY: u32 = 0x11; unsafe extern "C" { fn pthread_set_qos_class_self_np(qos_class: u32, relative_priority: i32) -> i32; } // SAFETY: These configure only the calling thread using the public macOS // pthread QoS API. Relative priority zero is valid for both classes. unsafe { pthread_set_qos_class_self_np(QOS_CLASS_UTILITY, 0) }; let result = work(); unsafe { pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0) }; result } /// Runs the calling thread at utility QoS for background transcription. pub(crate) fn deprioritize_background_thread() { const QOS_CLASS_UTILITY: u32 = 0x11; unsafe extern "C" { fn pthread_set_qos_class_self_np(qos_class: u32, relative_priority: i32) -> i32; } // SAFETY: This configures only the calling thread using the public macOS // pthread QoS API. Relative priority zero is valid for this class. let status = unsafe { pthread_set_qos_class_self_np(QOS_CLASS_UTILITY, 0) }; if status != 0 { tracing::warn!(status, "could not lower background transcription QoS"); } } fn queue_error(error: TrySendError) -> &'static str { match error { TrySendError::Full(_) => "dictation queue is full", TrySendError::Disconnected(_) => "dictation worker is unavailable", } } fn finish_output( job: OutputJob, paste: &mut impl FnMut(&str, PasteMode) -> Result<()>, last_transcript: &mut Option, history: Option<&History>, ) -> WorkerEvent { match job { OutputJob::PreparePaste => unreachable!("paste preparation bypasses ordered output"), #[cfg(hex_capture)] OutputJob::Recent { .. } => unreachable!("a recent paste uses its own insertion adapter"), OutputJob::Completed { job_id, control, target, result, } => { let result = *result; let processing = result .as_ref() .ok() .and_then(|result| result.processing.clone()); let result = result.and_then(|mut completed| { let paste_started = Instant::now(); let mut sent = false; if !completed.nothing && !completed.text.trim().is_empty() { match target { TranscriptionTarget::Paste | TranscriptionTarget::CopyOnlyPaste | TranscriptionTarget::RawCopyOnlyPaste | TranscriptionTarget::RawPaste => { // A rescued microphone-loss dictation is always // copied: the disruption may have taken focus. let rescued = matches!( target, TranscriptionTarget::CopyOnlyPaste | TranscriptionTarget::RawCopyOnlyPaste ); let send_gate = completed.timings.send_gate.filter(|_| { !rescued && crate::dictation::yolo_mode::sends( completed.application.as_deref(), completed.bundle_name.as_deref(), ) }); // Labs › Copy dictation only, read as the output // commits: dictations go to the clipboard // unpasted; Paste last dictation still pastes. // A dictation YOLO mode sends is pasted anyway. let copy_only = rescued || (crate::labs::copy_only() && send_gate.is_none()); let mode = if copy_only { PasteMode::CopyOnly } else if send_gate.is_some() { PasteMode::Send } else { PasteMode::Continue }; // Labs › Return to app: the app the capture // started in comes back first. When it can't, // nothing is pasted; the text stays for Paste // last dictation, and History keeps only pasted // output, as on any failed paste. if matches!(mode, PasteMode::Continue | PasteMode::Send) && let Err(error) = crate::paste::return_to_app::bring_to_front(completed.return_to) { recover_output(history, last_transcript, completed.text); tracing::warn!( %error, "a dictation found another app in front and couldn't return to its own" ); return Err(error.to_string()); } // A paste that fails (another app changed the // clipboard while Hex saved it) keeps the text // for Paste last dictation, as above, so the // dictation isn't lost. if let Err(error) = paste(&completed.text, mode) { recover_output(history, last_transcript, completed.text); return Err(error.to_string()); } if let Some(gate) = send_gate { sent = send_unless_escaped(gate, Instant::now(), paste); } } TranscriptionTarget::Service | TranscriptionTarget::Print | TranscriptionTarget::RawPrint => {} } let reusable = matches!( target, TranscriptionTarget::Paste | TranscriptionTarget::CopyOnlyPaste | TranscriptionTarget::RawCopyOnlyPaste | TranscriptionTarget::RawPaste ); let recorded = history.and_then(|h| record_history(h, target, sent, &mut completed)); if reusable { if recorded.is_some() { *last_transcript = Some(completed.text.clone()); } else { recover_output(history, last_transcript, completed.text.clone()); } } } tracing::info!( audio_ms = completed.timings.audio_ms, queue_ms = completed.timings.queue_ms, prepare_ms = completed.timings.prepare_ms, inference_ms = completed.timings.inference_ms, paste_ms = paste_started.elapsed().as_millis(), total_ms = completed.timings.total_started.elapsed().as_millis(), "dictation pipeline completed" ); Ok(completed.text) }); if matches!( target, TranscriptionTarget::Print | TranscriptionTarget::RawPrint ) { control.answer_print(match &result { Ok(text) if text.trim().is_empty() => { crate::control::PrintedTranscript::NoSpeech } Ok(text) => crate::control::PrintedTranscript::Text(text.clone()), Err(error) => crate::control::PrintedTranscript::Failed(error.clone()), }); } WorkerEvent::Completed { job_id, target, result, processing, } } OutputJob::Paste { kind, .. } => { let result = match kind { PasteKind::LastTranscript => last_transcript .clone() .or_else(|| history.and_then(History::recovered_output)) .ok_or_else(|| "no previous transcript is available".to_string()) .and_then(|text| { paste(&text, PasteMode::Continue).map_err(|error| error.to_string())?; Ok(text) }), PasteKind::MeetingDelta => { paste_meeting_delta(paste).map_err(|error| error.to_string()) } }; WorkerEvent::Pasted { kind, result } } } } /// Labs › YOLO mode, after a `Send` paste landed at `pasted_at`: presses /// Return unless Escape came after the release. Returns whether it sent; the /// text stays pasted either way. fn send_unless_escaped( gate: crate::dictation::yolo_mode::SendGate, pasted_at: Instant, paste: &mut impl FnMut(&str, PasteMode) -> Result<()>, ) -> bool { if !gate.wait(pasted_at) { tracing::info!("YOLO mode pasted without Return: Escape after the release"); return false; } match paste("", PasteMode::Return) { Ok(()) => { tracing::info!( after_submit_ms = gate.submitted_at().elapsed().as_millis(), "YOLO mode pressed Return" ); true } Err(error) => { tracing::warn!(%error, "YOLO mode could not press Return"); false } } } mod output_history; use output_history::{record_history, recover_output}; fn paste_meeting_delta(paste: &mut impl FnMut(&str, PasteMode) -> Result<()>) -> Result { meeting::consume_active_or_latest_delta(|text| paste(text, PasteMode::Standalone)) } pub(crate) fn default_model_path() -> Result { model_path(crate::transcription::models::definition( crate::transcription::models::TranscriptionModelId::default(), )) } impl Parakeet { #[cfg(test)] pub fn load() -> Result { let (_, selection) = crate::app_settings::transcription_selection(); Self::load_selection(&selection) } pub fn load_selection(selection: &TranscriptionSelection) -> Result { let definition = validate(selection)?; if !crate::transcription::models::is_installed(definition, &selection.language) { return Err(eyre!("{} is not installed", definition.name)); } let path = model_path(definition)?; let mut parakeet = Self::load_from(&path, true, Some(selection))?; parakeet.prewarm()?; let stream_run = parakeet.stream_run_options(); parakeet.session.probe_stream(&stream_run, &path); Ok(parakeet) } /// Streams decode like offline runs, at segment timestamps: only the text /// of a stream is used. fn stream_run_options(&self) -> RunOptions { RunOptions { timestamps: match self.options.timestamps { TimestampKind::Word | TimestampKind::Token => TimestampKind::Segment, timestamps => timestamps, }, ..self.options.clone() } } pub(crate) fn stream_options(&self) -> Option<&transcribe_cpp::StreamOptions> { self.session.stream_options() } /// Re-probes the live stream when Labs › Faster live text or an env /// override changed, so a later capture streams with it. Streams decode /// with [`Self::stream_run_options`], as the load-time probe does. pub(crate) fn refresh_stream(&mut self) { let options = self.stream_run_options(); self.session.refresh_stream(&options); } pub(crate) fn with_stream( &mut self, stream_options: &transcribe_cpp::StreamOptions, cancel: &transcribe_cpp::CancelToken, drive: impl FnOnce(&mut transcribe_cpp::Stream<'_>) -> R, ) -> transcribe_cpp::Result { let options = self.stream_run_options(); self.session .with_stream(&options, stream_options, cancel, drive) } pub(crate) fn load_for_benchmark(model_path: &std::path::Path) -> Result { Self::load_from(model_path, false, None) } fn load_from( model_path: &std::path::Path, diagnostics: bool, selection: Option<&TranscriptionSelection>, ) -> Result { if diagnostics { TRANSCRIBE_LOGGING.call_once(transcribe_cpp::init_logging); } else { transcribe_cpp::disable_logging(); } let model = Model::load_with( model_path, &ModelOptions { backend: Backend::Metal, ..Default::default() }, ) .wrap_err_with(|| { format!( "could not load transcription model from {}", model_path.display() ) })?; let device = model.device()?; if device.kind != "metal" { return Err(eyre!( "transcription model selected {} ({}) instead of Metal", device.kind, device.name )); } let variant = model.variant(); let architecture = model.arch(); let name = format!("transcribe-cpp-{}-{variant}", device.kind); let definition = selection.map(validate).transpose()?; tracing::info!( backend = device.kind, device = device.description, variant, "loaded transcription model" ); let capabilities = model.capabilities()?; let mut options = RunOptions { timestamps: match capabilities.max_timestamp_kind { TimestampKind::Word | TimestampKind::Token => TimestampKind::Word, TimestampKind::Auto | TimestampKind::Segment => TimestampKind::Segment, TimestampKind::None => TimestampKind::None, }, ..Default::default() }; if let (Some(selection), Some(definition)) = (selection, definition) { let runtime_language = crate::transcription::gguf_session::validate_gguf_artifact( model_path, definition, &architecture, &variant, selection, capabilities.supports_language_detect, )?; if let Some(runtime_language) = &runtime_language && !capabilities.languages.is_empty() && !capabilities .languages .iter() .any(|language| language == runtime_language) { return Err(eyre!( "{} does not advertise support for {}", definition.name, crate::transcription::models::language_name(&selection.language) )); } options.language = runtime_language; } let session = OfflineGgufSession::new(model)?; let weights_bytes = std::fs::metadata(model_path).map_or(0, |meta| meta.len() as usize); Ok(Self { session, options, name, selection: selection.cloned(), max_audio_samples: crate::transcription::models::max_audio_chunk_samples( &architecture, capabilities.max_audio_ms, ), _weights: MODEL_WEIGHTS.track(weights_bytes), }) } /// Runs a short silent inference. ggml keeps the Metal weights resident /// for only three minutes after a run; then macOS may compress or swap /// them out, and the next run pays to bring them back. A prewarm pays that /// before the audio arrives, and is skipped right after another run. pub(crate) fn prewarm(&mut self) -> Result<()> { if self.session.ran_recently() { return Ok(()); } let started = Instant::now(); let mut silence = Vec::new(); pad_for_parakeet(&mut silence); // No vocabulary: with it, a decoder such as Qwen3-ASR 1.7B reads a // long term list back to its output cap on every warm-up (#1568). let result = self .session .warm(&silence, &self.options) .map(drop) .wrap_err("could not prewarm transcription model"); match result { // Backstop: a decode that still runs to its generation cap on // silence (Qwen3-ASR 1.7B, #968) ran the whole graph on the // device, so that is a warm model, not a failed selection; Linux // and Windows accept it the same way. Err(error) if output_truncated(&error) => { tracing::info!( error = format!("{error:#}"), "the warm-up run on silence hit the output limit; the model is warm" ); } result => result?, } tracing::info!( prewarm_ms = started.elapsed().as_millis(), "prewarmed transcription model" ); Ok(()) } pub(crate) fn name(&self) -> &str { &self.name } pub(crate) fn matches_selection(&self, selection: &TranscriptionSelection) -> bool { self.selection.as_ref() == Some(selection) } pub(crate) fn selection(&self) -> Option<&TranscriptionSelection> { self.selection.as_ref() } pub(crate) fn model_id(&self) -> Option { self.selection.as_ref().map(|selection| selection.model) } /// Low-level GGUF entry point over prepared audio. `Transcriber` owns the /// whole-clip padding; chunks only apply the minimum duration, never /// another model-specific trailing context. pub fn transcribe(&mut self, samples: &[f32]) -> Result { self.session .transcribe_chunked(samples, &self.options, self.max_audio_samples) } /// [`Self::transcribe`] with the model's own segment and word times, /// chunked and offset exactly as the untimed run chunks it. pub(crate) fn transcribe_timed( &mut self, samples: &[f32], ) -> Result { self.session .transcribe_chunked_timed(samples, &self.options, self.max_audio_samples) } /// The finest native timings this model gives, as a timed request needs /// them. Never the level a caller asked for. pub(crate) fn timestamps(&self) -> crate::transcription::transcript::TimestampLevel { crate::transcription::gguf_session::timestamp_level(self.options.timestamps) } pub fn transcribe_segments(&mut self, samples: &[f32]) -> Result { self.session .run(samples, &self.options) .wrap_err("transcription failed") } } #[cfg(test)] mod tests { use std::path::PathBuf; use hound::WavReader; use super::*; use crate::dictation::resample_for_parakeet; use crate::meeting::{MeetingSource, TranscriptEntry, format_meeting_delta}; fn processing_job(target: TranscriptionTarget) -> ProcessorJob { ProcessorJob { job_id: DictationJobId(0), control: Arc::new(JobControl::default()), target, text: "raw instruction".into(), context: ContextSnapshot::default(), return_to: None, language: "en".into(), timings: JobTimings { total_started: Instant::now(), queue_ms: 0, audio_ms: 1000, prepare_ms: 0, inference_ms: 0, send_gate: None, }, recording: None, } } #[test] fn ordinary_processing_snapshots_modes_before_stage_and_keeps_transformations() { use crate::dictation::processor::{Profile, Profiles}; use std::cell::Cell; for transformations in [vec![], vec!["fixture-transform".to_string()]] { let loaded = Cell::new(false); let stage_sent = Cell::new(false); let processed = process_job_text( &processing_job(TranscriptionTarget::Paste), || { assert!(!stage_sent.get()); loaded.set(true); Profiles::new( Profile::new("Global", "").transformations(transformations.clone()), ) }, || { assert!(loaded.get()); stage_sent.set(true); }, ); assert!(loaded.get()); assert_eq!(stage_sent.get(), !transformations.is_empty()); assert_eq!(processed.text, "raw instruction"); assert_eq!(processed.transformations, transformations); } } #[test] #[ignore = "requires HEX_COHERE_MODEL and HEX_COHERE_FIXTURES synthetic audio"] fn cohere_long_form_keeps_all_sections_with_and_without_pauses() { let model_path = PathBuf::from(std::env::var_os("HEX_COHERE_MODEL").expect("model path")); let fixtures = PathBuf::from(std::env::var_os("HEX_COHERE_FIXTURES").expect("fixture path")); let selection = TranscriptionSelection { model: TranscriptionModelId::CohereTranscribe, language: "en".into(), }; let mut model = Parakeet::load_from(&model_path, false, Some(&selection)).unwrap(); eprintln!( "Cohere maximum chunk: {:?} samples", model.max_audio_samples ); for (name, repeats) in [ ("long-continuous", 1), ("long-pauses", 1), ("long-repeated", 3), ] { let mut reader = WavReader::open(fixtures.join(format!("{name}.wav"))).unwrap(); assert_eq!(reader.spec().sample_rate, 16_000); assert_eq!(reader.spec().channels, 1); let samples = reader .samples::() .map(|sample| f32::from(sample.unwrap()) / 32768.0) .collect::>(); assert!(samples.len() > 35 * 16_000); let text = model.transcribe(&samples).unwrap().to_lowercase(); for phrase in [ "small community garden", "bright green door", "purple submarine", ] { assert_eq!( text.matches(phrase).count(), repeats, "{name} lost {phrase:?}: {text}" ); } assert!( text.split_whitespace().count() >= 160 * repeats, "{name}: {text}" ); } } #[test] fn meeting_delta_coalesces_turns_in_time_order() { let entry = |source, start_ms, end_ms, text: &str| TranscriptEntry { source, start_ms, end_ms, text: text.into(), }; let entries = [ entry(MeetingSource::Microphone, 0, 1_000, "First."), entry(MeetingSource::Microphone, 1_100, 1_400, "Still me."), entry(MeetingSource::System, 1_500, 2_500, "Reply."), entry(MeetingSource::Microphone, 2_600, 3_000, "Second."), ]; assert_eq!( format_meeting_delta(&entries).unwrap(), "You: First. Still me.\n\nThem: Reply.\n\nYou: Second." ); assert!(format_meeting_delta(&[]).is_err()); } #[test] fn yolo_sends_yep_only_after_a_successful_paste() { use crate::app_settings::LabsSettings; use crate::dictation::yolo_mode::{ESCAPE_WINDOW, SendGate}; use std::sync::atomic::AtomicU64; static ESCAPES: AtomicU64 = AtomicU64::new(0); let mut labs = LabsSettings { yolo_mode: true, yolo_mode_apps: vec!["Messages".into()], ..Default::default() }; crate::labs::apply(&labs); let deliver = |text: Result<&str, &str>, app: &str, paste_succeeds: bool| { let mut calls = Vec::new(); let result = text .map(|text| CompletedTranscript { raw: "yep".into(), text: text.into(), nothing: false, application: Some(app.into()), bundle_name: None, return_to: None, timings: JobTimings { audio_ms: 1_000, send_gate: Some(SendGate::on(&ESCAPES, Instant::now() - ESCAPE_WINDOW)), ..processing_job(TranscriptionTarget::Paste).timings }, processing: None, recording: None, }) .map_err(str::to_owned); finish_output( OutputJob::Completed { job_id: DictationJobId(1), control: Arc::new(JobControl::default()), target: TranscriptionTarget::Paste, result: Box::new(result), }, &mut |text, mode| { calls.push(match mode { PasteMode::Return => "Return".into(), PasteMode::CopyOnly => format!("copy {text}"), _ => format!("paste {text}"), }); if !paste_succeeds { return Err(eyre!("failed insertion")); } Ok(()) }, &mut Some("older dictation".into()), None, ); calls }; assert_eq!( deliver(Ok("yep"), "Messages", true), ["paste yep", "Return"] ); assert_eq!(deliver(Ok("yep"), "Messages", false), ["paste yep"]); assert_eq!(deliver(Ok("yep"), "Notes", true), ["paste yep"]); for no_text in [Ok(""), Ok(" \t\n"), Err("failed transcription")] { assert!(deliver(no_text, "Messages", true).is_empty()); } labs.copy_only = true; crate::labs::apply(&labs); assert_eq!( deliver(Ok("yep"), "Messages", true), ["paste yep", "Return"], "YOLO mode's apps paste and send through Copy dictation only" ); assert_eq!(deliver(Ok("yep"), "Notes", true), ["copy yep"]); crate::labs::apply(&LabsSettings::default()); assert_eq!(deliver(Ok("yep"), "Messages", true), ["paste yep"]); } #[test] fn a_failed_paste_keeps_the_dictation_for_paste_last() { let text = "the dictation whose paste failed"; let mut last_transcript = Some("an older dictation".to_string()); let event = finish_output( OutputJob::Completed { job_id: DictationJobId(1), control: Arc::new(JobControl::default()), target: TranscriptionTarget::Paste, result: Box::new(Ok(CompletedTranscript { text: text.into(), nothing: false, raw: text.into(), application: None, bundle_name: None, return_to: None, timings: JobTimings { total_started: Instant::now(), queue_ms: 0, audio_ms: 2_000, prepare_ms: 0, inference_ms: 0, send_gate: None, }, processing: None, recording: None, })), }, &mut |_, _| Err(eyre!("clipboard changed while Hex was preserving it")), &mut last_transcript, None, ); assert!(matches!( event, WorkerEvent::Completed { result: Err(_), .. } )); assert_eq!(last_transcript.as_deref(), Some(text)); } #[test] fn a_salvaged_dictation_is_copied_and_kept_for_paste_last_and_history() { // A normal salvage is processed before it is copied; a raw one is // copied as heard and recorded as raw history. Neither is pasted. for (target, kind) in [ (TranscriptionTarget::CopyOnlyPaste, HistoryKind::Dictation), (TranscriptionTarget::RawCopyOnlyPaste, HistoryKind::Raw), ] { let directory = std::env::temp_dir().join(format!( "hex-parakeet-salvage-{}-{target:?}", std::process::id() )); let _ = std::fs::remove_dir_all(&directory); std::fs::create_dir_all(&directory).unwrap(); let history = History::new(crate::history::HistoryStore::open( directory.join("history.json"), crate::history::HistoryRetention::Week, crate::history::now_ms(), )); let text = "the part of the dictation the microphone heard"; let mut pasted = None; let mut last_transcript = None; let event = finish_output( OutputJob::Completed { job_id: DictationJobId(1), control: Arc::new(JobControl::default()), target, result: Box::new(Ok(CompletedTranscript { text: text.into(), nothing: false, raw: text.into(), application: Some("Call".into()), bundle_name: None, return_to: None, timings: JobTimings { total_started: Instant::now(), queue_ms: 0, audio_ms: 4_000, prepare_ms: 0, inference_ms: 0, send_gate: None, }, processing: None, recording: None, })), }, &mut |pasted_text, mode| { pasted = Some((pasted_text.to_string(), mode)); Ok(()) }, &mut last_transcript, Some(&history), ); assert!(matches!( event, WorkerEvent::Completed { result: Ok(ref completed), .. } if completed.as_str() == text )); let (pasted_text, mode) = pasted.expect("the transcript reaches the clipboard"); assert_eq!(pasted_text, text); assert!( matches!(mode, PasteMode::CopyOnly), "{target:?}: an interrupted dictation is copied, never pasted" ); assert_eq!(last_transcript.as_deref(), Some(text)); let entries = history.recent(1); assert_eq!(entries.len(), 1); assert_eq!(entries[0].kind, kind, "{target:?}"); assert_eq!(entries[0].final_text, text); assert_eq!(entries[0].application.as_deref(), Some("Call")); let _ = std::fs::remove_dir_all(&directory); } } /// Labs › YOLO mode: Escape after the release keeps the paste and skips /// the Return, so History records a dictation rather than a send. #[test] fn escape_after_release_pastes_a_yolo_dictation_without_return() { use crate::dictation::yolo_mode::{ESCAPE_WINDOW, SendGate}; use std::sync::atomic::{AtomicU64, Ordering}; static ESCAPES: AtomicU64 = AtomicU64::new(0); let submitted = Instant::now() - ESCAPE_WINDOW; let presses = std::cell::RefCell::new(Vec::new()); let mut paste = |text: &str, mode| { presses .borrow_mut() .push((text.to_owned(), matches!(mode, PasteMode::Return))); Ok(()) }; let gate = SendGate::on(&ESCAPES, submitted); ESCAPES.fetch_add(1, Ordering::AcqRel); assert!(!send_unless_escaped(gate, submitted, &mut paste)); assert!(presses.borrow().is_empty(), "no Return after an Escape"); let gate = SendGate::on(&ESCAPES, submitted); assert!(send_unless_escaped(gate, submitted, &mut paste)); assert_eq!(*presses.borrow(), [(String::new(), true)]); let failing = SendGate::on(&ESCAPES, submitted); assert!(!send_unless_escaped(failing, submitted, &mut |_, _| Err( eyre!("Return failed") ))); let directory = std::env::temp_dir().join(format!("hex-parakeet-yolo-{}", std::process::id())); let _ = std::fs::remove_dir_all(&directory); std::fs::create_dir_all(&directory).unwrap(); let history = History::new(crate::history::HistoryStore::open( directory.join("history.json"), crate::history::HistoryRetention::Week, crate::history::now_ms(), )); for sent in [false, true] { let mut completed = CompletedTranscript { text: "a long message".into(), nothing: false, raw: "a long message".into(), application: None, bundle_name: None, return_to: None, timings: JobTimings { total_started: Instant::now(), queue_ms: 0, audio_ms: 3_000, prepare_ms: 0, inference_ms: 0, send_gate: Some(SendGate::open()), }, processing: None, recording: None, }; record_history(&history, TranscriptionTarget::Paste, sent, &mut completed); } let kinds: Vec<_> = history .recent(2) .into_iter() .map(|entry| entry.kind) .collect(); assert!(kinds.contains(&HistoryKind::Dictation) && kinds.contains(&HistoryKind::Send)); let _ = std::fs::remove_dir_all(&directory); } #[test] fn parallel_processing_results_are_released_in_submission_order() { let mut outputs = OrderedOutputs::default(); let job = |sequence| OutputJob::Paste { sequence, kind: PasteKind::LastTranscript, }; assert!(outputs.push(job(1)).is_empty()); assert_eq!( outputs .push(job(0)) .into_iter() .map(|job| job.sequence()) .collect::>(), [0, 1] ); assert_eq!( outputs .push(job(2)) .into_iter() .map(|job| job.sequence()) .collect::>(), [2] ); } #[test] fn ordered_waiting_outputs_remain_bounded_after_channel_drain() { let (output_sender, output_receiver) = mpsc::sync_channel(1); let (event_sender, events) = mpsc::channel(); let worker = DictationWorker { engine: None, inference_jobs: None, output_jobs: Some(output_sender), events, event_sender, state: Arc::new(Mutex::new(WorkerState { next_sequence: 1, jobs: BTreeSet::from([DictationJobId(0)]), pending_pastes: 0, return_to: None, started_by_shortcut: false, })), inference_worker: None, processor_workers: Vec::new(), output_worker: None, }; let mut ordered = OrderedOutputs::default(); for _ in 1..MAX_PENDING_OUTPUTS { worker.paste_last().unwrap(); assert!(ordered.push(output_receiver.try_recv().unwrap()).is_empty()); } assert_eq!(worker.paste_last(), Err("dictation queue is full")); assert_eq!(worker.paste_meeting(), Err("dictation queue is full")); assert_eq!(ordered.waiting.len(), MAX_PENDING_OUTPUTS - 1); assert_eq!( worker.state.lock().unwrap().next_sequence, MAX_PENDING_OUTPUTS as u64 ); worker.state.lock().unwrap().jobs.remove(&DictationJobId(0)); worker.paste_last().unwrap(); assert_eq!( output_receiver.try_recv().unwrap().sequence(), MAX_PENDING_OUTPUTS as u64 ); } /// Replays recordings into the production engine as capture would (160 ms /// blocks, the last 200 ms held back as the release tail) and compares /// the stream's release latency and text with whole-clip transcription. #[test] #[ignore = "requires HEX_STREAM_MODEL (Unified English GGUF) and HEX_STREAM_WAVS (comma-separated)"] fn metal_stream_tracks_offline_transcription() { use crate::transcription::engine::{Offline, Source, TranscriptionEngine}; use crate::transcription::{Transcriber, WarmTranscriber}; let selection = TranscriptionSelection::default(); let path = PathBuf::from(std::env::var("HEX_STREAM_MODEL").unwrap()); let mut model = Parakeet::load_from(&path, false, Some(&selection)).unwrap(); model .session .probe_stream(&model.stream_run_options(), &path); assert!(model.stream_options().is_some(), "Metal must stream"); let engine = TranscriptionEngine::start(WarmTranscriber::serving(Transcriber::Gguf( Box::new(model), ))) .unwrap(); // `HEX_STREAM_LIVE_TEXT=0` replays without reading live text. let engine = if std::env::var("HEX_STREAM_LIVE_TEXT").is_ok_and(|value| value == "0") { engine } else { engine.with_live_text() }; let speed = std::env::var("HEX_STREAM_SPEED") .ok() .and_then(|speed| speed.parse::().ok()) .unwrap_or(4.0); let offline = || -> Offline { let selection = selection.clone(); Box::new(move |model, samples| { model .activate(&selection) .and_then(|model| model.transcribe(samples)) .map_err(|error| error.to_string()) }) }; let words = |text: &str| { text.split_whitespace() .map(|word| { word.chars() .filter(|c| c.is_alphanumeric()) .flat_map(char::to_lowercase) .collect::() }) .filter(|word| !word.is_empty()) .collect::>() }; for path in std::env::var("HEX_STREAM_WAVS").unwrap().split(',') { let mut reader = WavReader::open(path).unwrap(); let rate = reader.spec().sample_rate; let channels = usize::from(reader.spec().channels); let raw = match reader.spec().sample_format { hound::SampleFormat::Float => reader .samples::() .map(Result::unwrap) .collect::>(), hound::SampleFormat::Int => reader .samples::() .map(|sample| f32::from(sample.unwrap()) / 32_768.0) .collect(), }; let mono = raw .chunks(channels) .map(|frame| frame.iter().sum::() / channels as f32) .collect::>(); let samples = resample_for_parakeet(&mono, rate); // A warm app has already run inputs of this size. let run = |samples: Vec| { engine .finish_with(None, samples, offline()) .unwrap() .wait() .unwrap() }; run(samples.clone()); let whole = run(samples.clone()); let mut stream = engine.begin().expect("the model streams"); let held = samples.len().saturating_sub(3_200); let feeding = Instant::now(); // Live text as a HUD would read it: (audio fed in ms, stable // words, tentative words), and how often the stable text was // rewritten instead of extended. let mut timeline = Vec::new(); let mut stable = String::new(); let mut rewrites = 0; for (index, block) in samples[..held].chunks(2_560).enumerate() { let due = std::time::Duration::from_secs_f64(index as f64 * 0.16 / speed); thread::sleep(due.saturating_sub(feeding.elapsed())); stream.feed(block); if let Some(partial) = stream.take_partial() { if !partial.stable.starts_with(stable.as_str()) { rewrites += 1; } stable = partial.stable.clone(); timeline.push(( stream.fed() / 16, words(&partial.stable).len(), words(&partial.tentative).len(), )); } } thread::sleep(std::time::Duration::from_secs_f64(0.2 / speed)); let streamed = engine .finish_with(Some(stream), samples.clone(), offline()) .unwrap() .wait() .unwrap(); let (reference, hypothesis) = (words(&whole.text), words(&streamed.text)); let mut previous = (0..=hypothesis.len()).collect::>(); for (row, expected) in reference.iter().enumerate() { let mut current = vec![row + 1; hypothesis.len() + 1]; for (column, actual) in hypothesis.iter().enumerate() { current[column + 1] = (previous[column + 1] + 1) .min(current[column] + 1) .min(previous[column] + usize::from(expected != actual)); } previous = current; } let differences = previous[hypothesis.len()]; println!( "{path}: audio_ms={} offline_ms={} release_ms={} ({}) word_differences={differences}/{}", samples.len() / 16, whole.finish_ms, streamed.finish_ms, streamed.source.label(), reference.len() ); println!(" offline {}", whole.text); println!(" stream {}", streamed.text); let first_text_ms = timeline .iter() .find(|(_, stable, tentative)| stable + tentative > 0) .map(|(fed_ms, ..)| *fed_ms); println!( " live text: updates={} first_text_at_audio_ms={first_text_ms:?} stable_rewrites={rewrites} last_stable_words={}/{}", timeline.len(), timeline.last().map_or(0, |(_, stable, _)| *stable), reference.len() ); for (fed_ms, stable, tentative) in &timeline { println!(" audio_ms={fed_ms} stable_words={stable} tentative_words={tentative}"); } let closing_mark = |text: &str| { const CLOSERS: [char; 8] = ['"', '\'', '”', '’', ')', ']', '}', '»']; text.trim_end() .trim_end_matches(CLOSERS) .chars() .last() .is_some_and(|last| matches!(last, '.' | '?' | '!' | '…')) }; // A stream that dropped its closing mark takes the whole-clip // fallback for that reason only (#1933). assert!( streamed.source == Source::Stream || matches!( &streamed.source, Source::Fallback(reason) if reason.as_str() == "the stream ended without closing sentence punctuation" ), "unexpected source {}", streamed.source.label() ); if closing_mark(&whole.text) { assert!( closing_mark(&streamed.text), "the stream dropped the offline text's closing mark: {}", streamed.text ); } assert!(differences * 20 <= reference.len().max(20)); } } #[cfg(hex_capture)] #[test] fn chunked_word_transcription_keeps_word_times_across_chunks() { use crate::transcription::{Transcript, TranscriptSegment}; let span = |start_ms, end_ms, text: &str| TranscriptSegment { start_ms, end_ms, text: text.into(), }; let mut calls = Vec::new(); let merged = transcribe_in_chunks(vec![0.0; 16_000 * 25], 16_000 * 10, |chunk| { calls.push(chunk.len()); let chunk_index = calls.len(); Ok(Transcript { text: format!(" part {chunk_index} "), segments: vec![span(0, 900, " part ")], words: vec![ span(-5, 400, " part"), span(450, 300, "two"), span(500, 600, " "), ], }) }) .unwrap(); assert_eq!(calls, [160_000, 160_000, 80_000]); assert_eq!(merged.text, "part 1 part 2 part 3"); let words = merged .words .iter() .map(|word| (word.start_ms, word.end_ms, word.text.as_str())) .collect::>(); assert_eq!( words, [ (0, 400, "part"), (450, 450, "two"), (10_000, 10_400, "part"), (10_450, 10_450, "two"), (20_000, 20_400, "part"), (20_450, 20_450, "two"), ] ); assert_eq!(merged.segments[2].start_ms, 20_000); } #[cfg(hex_capture)] #[test] fn word_transcription_is_a_foreground_request_on_the_shared_engine() { use crate::transcription::engine::Command as EngineCommand; let (engine, commands) = TranscriptionEngine::for_test(); let engine = Arc::new(engine); let weak = Arc::downgrade(&engine); assert!( transcribe_with_words(&weak, &Default::default(), Vec::new()) .unwrap() .words .is_empty() ); assert!( commands.try_recv().is_err(), "silence never reaches the model" ); // A busy dictation holds the chunk back until it is idle. let busy = DictationInference::begin(); let request = { let weak = weak.clone(); thread::spawn(move || { transcribe_with_words( &weak, &Default::default(), vec![0.1; WORD_CHUNK_SAMPLES + 1_600], ) }) }; assert!( commands .recv_timeout(std::time::Duration::from_millis(200)) .is_err() ); drop(busy); let command = commands .recv_timeout(std::time::Duration::from_secs(5)) .unwrap(); // A foreground request: after dictation already sent, counted as a // request so meeting chunks yield to it, and never inside a stream. assert!(matches!( command, EngineCommand::Foreground { ref clip, .. } if clip.len() == WORD_CHUNK_SAMPLES )); // The next chunk waits for this one, so a dictation sent meanwhile // runs first. assert!( commands .recv_timeout(std::time::Duration::from_millis(100)) .is_err() ); drop(command); assert!(request.join().unwrap().is_err()); // Only a weak reference is held: once the engine is gone, a capture // fails instead of keeping it alive. drop(engine); assert!(transcribe_with_words(&weak, &Default::default(), vec![0.1; 16]).is_err()); } #[test] #[ignore = "requires HEX_STUTTER_FIXTURE and the installed Parakeet model"] fn tdt_decoder_does_not_repeat_single_letter_tokens() { let path = PathBuf::from(std::env::var("HEX_STUTTER_FIXTURE").unwrap()); let mut reader = WavReader::open(path).unwrap(); let sample_rate = reader.spec().sample_rate; let samples = reader .samples::() .skip(sample_rate as usize * 20) .take(sample_rate as usize * 25) .collect::, _>>() .unwrap(); let samples = resample_for_parakeet(&samples, sample_rate); let text = Parakeet::load().unwrap().transcribe(&samples).unwrap(); assert!(text.contains("sweatshirt"), "unexpected transcript: {text}"); assert!( !text.contains("p p p p") && !text.contains("p-p-p-p"), "pathological token repetition: {text}" ); } } #[cfg(test)] #[path = "dictation/tail_tests.rs"] mod dictation_tail_tests; #[cfg(test)] #[path = "dictation/corpus_tests.rs"] mod dictation_corpus_tests; /// Loads a GGUF model file directly, for opt-in harnesses that replay /// recordings without the installed model catalog. #[cfg(test)] pub(crate) fn load_test_model(path: &std::path::Path) -> Result { Parakeet::load_from(path, false, Some(&TranscriptionSelection::default())) }