hex/src/dictation/modes.rs
Dax 74e8914261
labs: voice prompt, speak an instruction to rewrite one dictation (#1716)
* labs: add a spoken voice prompt for one-off OpenCode instructions

A new Output lab, off by default, splits a dictation at a spoken trigger phrase and replaces the mode's rewrite with one request applying the instruction after it to the text before it. The phrase is validated, saved as labs.voice_prompt_phrase, and shown on its card while the lab is on.

* labs: refine voice prompt matching and quiet empty output

Hyphens and apostrophes inside a word are ignored instead of breaking it, the pieces keep their own punctuation, and Windows/Linux finish a deliberately empty voice prompt quietly through a Processed flag. Also keeps the phrase field's caret through unrelated saves, resyncs it when the lab toggles elsewhere, maps it to the OpenCode lock, reads the browser host on every OS, and extends courtesy phrases.

* labs: read the quiet voice prompt signal on macOS

macOS skips the output through CompletedTranscript.nothing, and its Processing stage now uses the same prepared text and replacements the request does, so it shows only when a request would actually run.

* labs: trim the marks around a spoken voice prompt

Quotes, brackets, and spaced dashes that only set the phrase off leave the split, while punctuation inside the text survives. Windows and Linux treat a deliberately empty prompt as a discard rather than an empty paste, macOS reads the browser host for the request, and the OpenCode lock covers the phrase setting too.

* labs: keep quotes that don't touch the spoken phrase

A quote or bracket pair leaves the split only when its opening mark touches the phrase, and terminal punctuation inside the pair is allowed. The empty outcome closes the oldest Linux HUD job directly and records a discard reason Activity names, with translations.

* labs: keep the voice prompt discard helper out of macOS builds
2026-11-12 07:18:02 -05:00

491 lines
18 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Dictation modes for the Windows and Linux listeners. The focused
//! application or website selects a mode, and its replacements,
//! post-processing, and transformations run in the shared
//! `dictation_processor` order. macOS selects modes through `config`.
use std::sync::atomic::AtomicBool;
use url::Url;
use crate::app_settings::{AppSettings, DictationMode, DictationProcessingSettings};
use crate::dictation::processor::{PostProcessingSettings, Processed, Profile, Profiles};
use crate::dictation::text_replacements::ReplacementSet;
/// Live mode-processing snapshot. The output worker clones it before any
/// deadline-bounded OpenCode call, so settings writes never wait on
/// inference.
#[derive(Clone)]
pub struct ModeRuntime {
replacements: ReplacementSet,
default: PostProcessingSettings,
default_transformations: Vec<String>,
default_vocabulary: Vec<crate::dictation::vocabulary::VocabularyEntry>,
modes: Vec<DictationMode>,
reads_page: bool,
}
impl ModeRuntime {
pub fn from_settings(settings: &AppSettings) -> Self {
let processing = &settings.dictation_processing;
Self {
replacements: ReplacementSet::new(&processing.default_mode.replacements),
default: processing.default_mode.post_processing.clone(),
default_transformations: processing.default_mode.transformations.clone(),
default_vocabulary: processing.default_mode.vocabulary.clone(),
modes: processing.modes.clone(),
// Labs › Voice prompt carries the browser host in its request,
// so its mode runtime reads the page too.
reads_page: uses_page(processing) || settings.labs.voice_prompt,
}
}
/// Whether processing looks at the focused page: a mode chosen by
/// website, an OpenCode rewrite, or a script transformation. Otherwise
/// the listener never asks the browser for its address, as on macOS.
pub fn reads_page(&self) -> bool {
self.reads_page
}
/// Global replacements, then the matching mode's corrections,
/// post-processing, and transformations.
pub fn process(
&self,
raw_text: &str,
language: &str,
context: &crate::dictation::context::ContextSnapshot,
transformations: &crate::personal_commands::TransformationClient,
source: crate::dictation::processor::Source,
) -> Processed {
self.process_cancellable(
raw_text,
language,
context,
transformations,
&AtomicBool::new(false),
source,
)
}
/// [`Self::process`] with a cancellation flag the stages check, for work
/// that ends early when Hex quits.
pub fn process_cancellable(
&self,
raw_text: &str,
language: &str,
context: &crate::dictation::context::ContextSnapshot,
transformations: &crate::personal_commands::TransformationClient,
cancelled: &AtomicBool,
source: crate::dictation::processor::Source,
) -> Processed {
let text = self.replacements.replace(raw_text);
let profile = self.profile(context);
let mut processed =
Profiles::new(profile).process_cancellable(&text, language, context, cancelled, source);
processed.apply_transformations(transformations, context, cancelled, source);
processed
}
/// The matching mode's profile, or Global's.
fn profile(&self, context: &crate::dictation::context::ContextSnapshot) -> Profile {
let mode = mode_for_context(
&self.modes,
context.application.as_deref(),
context.browser_host(),
);
mode.map_or_else(
|| {
Profile::configured(
"Global",
ReplacementSet::default(),
self.default_transformations.clone(),
&self.default,
)
.vocabulary(self.default_vocabulary.clone())
},
Profile::from_mode,
)
}
}
/// The live mode runtime and transformation client a listener shares with
/// the local API's `process=global` processor, so saved settings and the
/// personal-commands host apply to both.
#[cfg(any(target_os = "linux", target_os = "windows"))]
#[derive(Clone)]
pub struct ProcessingState {
pub modes: std::sync::Arc<std::sync::RwLock<ModeRuntime>>,
pub transformations: std::sync::Arc<crate::personal_commands::TransformationClient>,
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
impl ProcessingState {
/// Reads `settings` once; a listener replaces `modes` as settings change.
pub fn from_settings(settings: &AppSettings) -> Self {
Self {
modes: std::sync::Arc::new(std::sync::RwLock::new(ModeRuntime::from_settings(
settings,
))),
transformations: std::sync::Arc::new(
crate::personal_commands::TransformationClient::default(),
),
}
}
}
/// Whether anything set up in `settings` looks at the focused page: a mode
/// chosen by website, an OpenCode rewrite (its prompt names the site), or a
/// script transformation (it receives the page address). Every OS asks the
/// browser for its page only for one of these or Labs › Voice prompt (macOS
/// through `config::reads_browser`).
pub(crate) fn uses_page(settings: &DictationProcessingSettings) -> bool {
settings
.modes
.iter()
.any(|mode| !mode.browser_hosts.is_empty())
|| std::iter::once(&settings.default_mode)
.chain(&settings.modes)
.any(|mode| {
mode.post_processing.enabled
|| mode
.transformations
.iter()
.any(|id| !crate::personal_commands::is_builtin_transformation(id))
})
}
/// The history entry for one pasted dictation.
pub fn history_draft(
raw_text: String,
processed: &Processed,
application: Option<String>,
audio_ms: u64,
inference_ms: u64,
total_ms: u64,
recording: Option<crate::history::Recording>,
) -> crate::history::HistoryDraft {
crate::history::HistoryDraft {
kind: crate::history::HistoryKind::Dictation,
raw_text,
final_text: processed.text.clone(),
application,
processing: processed.observation.as_ref().map(|processing| {
crate::history::HistoryProcessing {
profile: processing.profile.clone(),
latency_ms: processing.latency_ms,
fallback: processing.fallback.clone(),
}
}),
audio_ms,
inference_ms,
total_ms,
recording,
model: crate::history::dictation_model(),
}
}
/// Whether a mode's applications match the focused application. Windows
/// and Linux name applications by executable, and a rule matches any
/// case-insensitive substring of that name ("code" matches "vscode").
fn matches_application(mode: &DictationMode, application: &str) -> bool {
let application = application.to_lowercase();
mode.applications.iter().any(|candidate| {
let candidate = candidate.trim().to_lowercase();
!candidate.is_empty() && application.contains(&candidate)
})
}
/// Whether a mode's websites match the focused page's exact host.
fn matches_website(mode: &DictationMode, host: &str) -> bool {
let host = normalize_host(host);
mode.browser_hosts.iter().any(|candidate| {
// Entries are stored as typed; pasted URLs, ports, and IDN text
// reduce to their host here.
canonical_host(candidate).is_some_and(|candidate| candidate == host)
})
}
/// The first mode matching the focused context. A website rule is more
/// specific than an application rule, so browser-host matches win, like
/// the macOS selector ordering.
fn mode_for_context<'a>(
modes: &'a [DictationMode],
application: Option<&str>,
browser_host: Option<&str>,
) -> Option<&'a DictationMode> {
if let Some(host) = browser_host
&& let Some(mode) = modes.iter().find(|mode| matches_website(mode, host))
{
return Some(mode);
}
let application = application?;
modes
.iter()
.find(|mode| matches_application(mode, application))
}
/// The speech model and language the mode matching the focused context
/// carries, else Global's. `None` means the mode never switches.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) fn speech_for<'a>(
settings: &'a DictationProcessingSettings,
application: Option<&str>,
browser_host: Option<&str>,
) -> Option<&'a crate::app_settings::KeyboardModelChoice> {
mode_for_context(&settings.modes, application, browser_host)
.unwrap_or(&settings.default_mode)
.speech
.as_ref()
}
/// Hosts compare case-insensitively with any trailing dot removed,
/// matching the macOS browser-host semantics.
pub fn normalize_host(host: &str) -> String {
host.trim_end_matches('.').to_lowercase()
}
/// A website rule entry reduced to its comparable host: bare hosts,
/// pasted URLs, host:port forms, and IDN text all work, matching the
/// macOS Websites field.
pub fn canonical_host(entry: &str) -> Option<String> {
let entry = entry.trim();
if entry.is_empty() {
return None;
}
let parsed = Url::parse(entry)
.ok()
.filter(|url| url.host_str().is_some())
.or_else(|| Url::parse(&format!("https://{entry}")).ok())?;
parsed.host_str().map(normalize_host)
}
#[cfg(test)]
mod tests {
use super::*;
fn mode(name: &str, applications: &[&str], browser_hosts: &[&str]) -> DictationMode {
DictationMode {
name: name.into(),
applications: applications.iter().map(|value| value.to_string()).collect(),
browser_hosts: browser_hosts
.iter()
.map(|value| value.to_string())
.collect(),
..DictationMode::default()
}
}
fn matched<'a>(
modes: &'a [DictationMode],
application: Option<&str>,
host: Option<&str>,
) -> Option<&'a str> {
mode_for_context(modes, application, host).map(|mode| mode.name.as_str())
}
fn runtime(settings: impl FnOnce(&mut AppSettings)) -> ModeRuntime {
let mut value = AppSettings::default();
settings(&mut value);
ModeRuntime::from_settings(&value)
}
#[test]
fn modes_match_case_insensitive_application_substrings() {
let modes = [
mode("Code", &["Code", "rustrover"], &[]),
mode("Chat", &["slack"], &[]),
];
assert_eq!(matched(&modes, Some("code"), None), Some("Code"));
assert_eq!(matched(&modes, Some("slack"), None), Some("Chat"));
assert_eq!(matched(&modes, Some("vscode"), None), Some("Code"));
assert_eq!(matched(&modes, Some("notepad"), None), None);
assert_eq!(matched(&modes, None, None), None);
}
#[test]
fn website_rules_match_exact_hosts_and_beat_application_rules() {
let modes = [
mode("Browser", &["chrome"], &[]),
mode("X", &[], &["X.com"]),
];
assert_eq!(matched(&modes, Some("chrome"), Some("x.com.")), Some("X"));
assert_eq!(
matched(&modes, Some("chrome"), Some("news.x.com")),
Some("Browser")
);
assert_eq!(matched(&modes, Some("chrome"), None), Some("Browser"));
}
#[test]
fn the_page_is_read_only_when_processing_uses_it() {
assert!(!runtime(|_| {}).reads_page());
assert!(
!runtime(|settings| {
settings.dictation_processing.modes = vec![DictationMode {
transformations: vec!["lowercase".into()],
..mode("Code", &["code"], &[])
}];
})
.reads_page()
);
assert!(
runtime(|settings| {
settings.dictation_processing.modes = vec![mode("X", &[], &["x.com"])];
})
.reads_page()
);
assert!(
runtime(|settings| {
settings
.dictation_processing
.default_mode
.post_processing
.enabled = true;
})
.reads_page()
);
// A voice prompt's request carries the browser host, so its lab
// reads the page even with no rewrite or website rule.
assert!(
runtime(|settings| {
settings.labs.voice_prompt = true;
})
.reads_page()
);
}
#[test]
fn blank_rules_never_match() {
let modes = [mode("Broken", &[" ", ""], &[" "])];
assert_eq!(matched(&modes, Some("anything"), Some("x.com")), None);
}
#[test]
fn global_replacements_run_before_mode_corrections() {
let runtime = runtime(|settings| {
let processing = &mut settings.dictation_processing;
processing.default_mode.replacements =
vec![crate::dictation::text_replacements::TextReplacement {
matched_phrase: "hex".into(),
output: "Hex".into(),
}];
processing.modes = vec![DictationMode {
replacements: vec![crate::dictation::text_replacements::TextReplacement {
matched_phrase: "open code".into(),
output: "OpenCode".into(),
}],
..mode("Code", &["code"], &[])
}];
});
let context = crate::dictation::context::ContextSnapshot {
application: Some("Visual Studio Code".into()),
..crate::dictation::context::ContextSnapshot::default()
};
let transformations = crate::personal_commands::TransformationClient::default();
let processed = runtime.process(
"Use open code in hex.",
"en",
&context,
&transformations,
crate::dictation::processor::Source::Dictation,
);
assert_eq!(processed.text, "Use OpenCode in Hex.");
assert!(processed.observation.is_none());
}
#[test]
fn modes_execute_selected_transformations_after_corrections() {
let runtime = runtime(|settings| {
settings.dictation_processing.default_mode.transformations = vec!["lowercase".into()];
});
let transformations = crate::personal_commands::TransformationClient::default();
let processed = runtime.process(
"Keep OpenCode Exact.",
"en",
&crate::dictation::context::ContextSnapshot::default(),
&transformations,
crate::dictation::processor::Source::Dictation,
);
assert_eq!(processed.text, "keep opencode exact.");
let observation = processed.observation.as_ref().expect("transformation ran");
assert_eq!(observation.profile, "Custom transformations");
assert_eq!(observation.fallback, None);
}
#[test]
fn saved_post_processing_enables_the_global_rewrite() {
let path = std::env::temp_dir().join(format!("hex-970-{}.json", std::process::id()));
std::fs::write(
&path,
br#"{"dictation_processing":{"default_mode":{"post_processing":{"enabled":true,"prompt":"Fix it.","model":"opencode/big-pickle","deadline_seconds":30}}}}"#,
)
.unwrap();
let (settings, _) = AppSettings::read_from(&path).unwrap();
let _ = std::fs::remove_file(&path);
let runtime = ModeRuntime::from_settings(&settings);
let context = crate::dictation::context::ContextSnapshot {
application: Some("kitty".into()),
..crate::dictation::context::ContextSnapshot::default()
};
assert!(runtime.profile(&context).rewrites());
}
#[test]
fn a_modes_speech_choice_matches_its_application_or_website_else_global() {
use crate::app_settings::KeyboardModelChoice;
use crate::transcription::models::TranscriptionModelId;
let choice = |language: &str| KeyboardModelChoice {
model: TranscriptionModelId::ParakeetV3,
language: language.into(),
};
let settings = DictationProcessingSettings {
default_mode: DictationMode {
speech: Some(choice("en")),
..DictationMode::default()
},
modes: vec![
DictationMode {
applications: vec!["code".into()],
speech: Some(choice("de")),
..DictationMode::default()
},
DictationMode {
browser_hosts: vec!["x.com".into()],
speech: Some(choice("es")),
..DictationMode::default()
},
],
};
let matched = |application: Option<&str>, host: Option<&str>| {
speech_for(&settings, application, host).map(|choice| choice.language.as_str())
};
assert_eq!(matched(Some("vscode"), None), Some("de"));
// A website is more specific than an application.
assert_eq!(matched(Some("chrome"), Some("x.com")), Some("es"));
// Nothing matches, so Global's own choice applies.
assert_eq!(matched(Some("notepad"), None), Some("en"));
assert_eq!(matched(None, None), Some("en"));
}
#[test]
fn website_entries_reduce_to_their_host() {
assert_eq!(normalize_host("X.com."), "x.com");
assert_eq!(
canonical_host("https://x.com/home").as_deref(),
Some("x.com")
);
assert_eq!(
canonical_host("github.com/hex/pull/1").as_deref(),
Some("github.com")
);
assert_eq!(
canonical_host("localhost:3000").as_deref(),
Some("localhost")
);
assert_eq!(canonical_host(" "), None);
}
}