hex/src/dictation/processor.rs
Dax b820ea712e
labs: dictation style (polished, casual, notes, verbatim) for desktop dictation (#2326)
* labs: dictation style for every dictation

* labs: fix dictation style edge cases
2026-11-22 01:55:42 -05:00

2994 lines
104 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.

use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use color_eyre::eyre::{Result, WrapErr, eyre};
use serde::{Deserialize, Serialize};
use crate::app_settings::DictationStyle;
use crate::desktop::opencode_service::Service;
use crate::dictation::context::{ContextSelector, ContextSnapshot};
use crate::dictation::numbers::numbers_only;
use crate::dictation::text_replacements::ReplacementSet;
use crate::dictation::vocabulary::VocabularyEntry;
mod generation;
mod processed;
pub use self::processed::{Processed, ProcessingObservation};
use self::generation::{
Request, Response, generate_single_model, post_generation, remaining_generation_deadline,
};
const PROTOCOL_PROMPT: &str = "You transform dictated speech into replacement text. Return only the text that should be pasted. Do not add an explanation, label, alternative, or Markdown fence.\n\nNumbers: keep every number the speaker said. Never drop, merge, reorder, round, or reinterpret a number, and never add thousands separators or other formatting to a number that the transcript already writes in digits.\n\nLists: unless the profile instructions say otherwise, when the speaker enumerates items (for example \"point one ... point two ...\", \"first ... second ...\", or \"number one ... number two ...\"), keep every item and write them as a numbered list, one item per line (\"1. ...\", \"2. ...\"), without the spoken cue words.";
const CATALOG_DEADLINE: Duration = Duration::from_secs(10);
pub use crate::app_settings::DictationPostProcessing as PostProcessingSettings;
/// The processing profile a run records when only the person's
/// transformations ran, with no mode or voice-prompt rewrite. It is not a
/// mode, so Output time leaves these runs out.
pub const CUSTOM_TRANSFORMATIONS: &str = "Custom transformations";
/// Where the text a mode processes came from.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Source {
/// A hotkey, API, or meeting dictation: heard speech.
Dictation,
/// Labs › Transform typed text: the selection already written in the
/// focused field.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
TypedText,
}
impl Source {
/// The `source` field transformations receive.
pub fn as_str(self) -> &'static str {
match self {
Self::Dictation => "dictation",
Self::TypedText => "typed-text",
}
}
}
/// The speech-only Labs steps, read once per processing run.
#[derive(Clone, Copy, Debug, Default)]
struct DictationLabs {
spoken_formatting: bool,
spoken_symbols: bool,
filler_words: bool,
/// Labs › Dictation style's choice while on; None leaves the text as
/// the corrections and rewrite wrote it.
dictation_style: Option<DictationStyle>,
}
impl DictationLabs {
/// The Labs switches as this process holds them now.
fn current() -> Self {
Self {
spoken_formatting: crate::labs::spoken_formatting(),
spoken_symbols: crate::labs::spoken_symbols(),
filler_words: crate::labs::filler_words(),
dictation_style: crate::labs::dictation_style(),
}
}
}
#[derive(Clone)]
pub struct Profile {
name: String,
ai_enabled: bool,
prompt: String,
model: Option<Model>,
deadline: Duration,
replacements: ReplacementSet,
transformations: Vec<String>,
/// The mode's own vocabulary, heard and spelled ahead of the shared list.
vocabulary: Vec<VocabularyEntry>,
/// The mode's speech model and language while it matches the foreground
/// app (Labs › Switch model with app).
speech: Option<crate::app_settings::KeyboardModelChoice>,
/// Rewrite this mode's dictations into plain, neutral wording on this Mac
/// (Labs › Neutral voice, macOS).
neutral_voice: bool,
}
impl Profile {
pub fn new(name: impl Into<String>, prompt: impl Into<String>) -> Self {
Self {
name: name.into(),
ai_enabled: false,
prompt: prompt.into(),
model: None,
deadline: Duration::from_secs(30),
replacements: ReplacementSet::default(),
transformations: Vec::new(),
vocabulary: Vec::new(),
speech: None,
neutral_voice: false,
}
}
pub(crate) fn speech(
mut self,
speech: Option<crate::app_settings::KeyboardModelChoice>,
) -> Self {
self.speech = speech;
self
}
pub(crate) fn vocabulary(mut self, vocabulary: Vec<VocabularyEntry>) -> Self {
self.vocabulary = vocabulary;
self
}
pub fn ai_enabled(mut self, enabled: bool) -> Self {
self.ai_enabled = enabled;
self
}
/// Whether this profile runs the OpenCode rewrite.
#[cfg(test)]
pub(crate) fn rewrites(&self) -> bool {
self.ai_enabled
}
pub(crate) fn replacements(mut self, replacements: ReplacementSet) -> Self {
self.replacements = replacements;
self
}
pub fn transformations(mut self, transformations: Vec<String>) -> Self {
self.transformations = transformations;
self
}
pub fn model(mut self, provider: impl Into<String>, id: impl Into<String>) -> Self {
self.model = Some(Model {
provider: provider.into(),
id: id.into(),
variant: None,
});
self
}
pub fn variant(mut self, variant: impl Into<String>) -> Self {
let Some(model) = &mut self.model else {
panic!("a processor profile variant requires a model");
};
model.variant = Some(variant.into());
self
}
pub fn deadline(mut self, deadline: Duration) -> Self {
self.deadline = deadline;
self
}
pub(crate) fn from_mode(mode: &crate::app_settings::DictationMode) -> Self {
let name = if mode.name.trim().is_empty() {
"Untitled mode"
} else {
&mode.name
};
let mut profile = Self::configured(
name,
ReplacementSet::new(&mode.replacements),
mode.transformations.clone(),
&mode.post_processing,
)
.vocabulary(mode.vocabulary.clone())
.speech(mode.speech.clone());
profile.neutral_voice = mode.neutral_voice;
profile
}
/// Builds a runtime profile from persisted settings. A malformed model key
/// falls back to the default model rather than disabling the mode.
pub(crate) fn configured(
name: impl Into<String>,
replacements: ReplacementSet,
transformations: Vec<String>,
settings: &PostProcessingSettings,
) -> Self {
Self::configured_under(
name,
replacements,
transformations,
settings,
crate::policy::Policy::current(),
)
}
/// [`Self::configured`] under `policy`: a managed lock drops the
/// OpenCode rewrite or every transformation, leaving the mode saved as is.
fn configured_under(
name: impl Into<String>,
replacements: ReplacementSet,
transformations: Vec<String>,
settings: &PostProcessingSettings,
policy: crate::policy::Policy,
) -> Self {
use crate::policy::Lock;
let transformations = if policy.locks(Lock::Transforms) {
Vec::new()
} else {
transformations
};
let mut profile = Self::new(name, &settings.prompt)
.ai_enabled(settings.enabled && !policy.locks(Lock::OpenCodeProcessing))
.replacements(replacements)
.transformations(transformations);
if let Some((provider, model)) = settings
.model
.as_deref()
.and_then(|key| key.split_once('/'))
{
profile = profile.model(provider, model);
if let Some(variant) = settings
.variant
.as_deref()
.filter(|variant| !variant.is_empty())
{
profile = profile.variant(variant);
}
}
profile.deadline(Duration::from_secs(settings.deadline_seconds.max(1)))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Model {
#[serde(rename = "providerID")]
pub provider: String,
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub variant: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RecommendedModel {
pub id: &'static str,
pub preferred_variants: &'static [&'static str],
}
/// Ranked fast, 100%-protocol-compliant OpenCode models for dictation
/// rewriting, ordered by latency, cost, and strict paste-ready output
/// compliance.
pub const RECOMMENDED_OPENCODE_MODELS: &[RecommendedModel] = &[
RecommendedModel {
id: "gemini-3.1-flash-lite",
preferred_variants: &["minimal", "none", "low"],
},
RecommendedModel {
id: "claude-haiku-4-5",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "gpt-5.4-nano",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "gpt-4.1-mini",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "gpt-4.1-nano",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "gpt-5.4-mini",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "gemini-3-flash",
preferred_variants: &["minimal", "none", "low"],
},
RecommendedModel {
id: "gpt-4o-mini",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "gpt-4.1",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "gpt-5.4",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "claude-sonnet-4-6",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "claude-sonnet-4-5",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "gemini-2.5-flash-lite",
preferred_variants: &["none", "minimal", "low"],
},
RecommendedModel {
id: "gemini-2.5-flash",
preferred_variants: &["none", "minimal", "low"],
},
];
#[derive(Clone)]
struct ContextualProfile {
selector: ContextSelector,
profile: Profile,
}
#[derive(Clone)]
pub struct Profiles {
default: Profile,
contextual: Vec<ContextualProfile>,
/// Global's corrections, run after speech preparation and before the mode's.
global: ReplacementSet,
}
impl Profiles {
pub(crate) fn from_settings(
settings: &crate::app_settings::DictationProcessingSettings,
) -> Self {
let mut global = Profile::from_mode(&settings.default_mode);
global.name = "Global".into();
let replacements = std::mem::take(&mut global.replacements);
let mut profiles = Self::new(global).global_replacements(replacements);
for mode in &settings.modes {
let profile = Profile::from_mode(mode);
for application in &mode.applications {
let selector = if cfg!(target_os = "macos") {
ContextSelector::application(application.clone())
} else {
ContextSelector::ApplicationSubstring(application.trim().to_lowercase())
};
profiles = profiles.push(selector, profile.clone());
}
for host in &mode.browser_hosts {
profiles = profiles.browser_host(host.clone(), profile.clone());
}
}
profiles
}
pub fn new(default: Profile) -> Self {
Self {
default,
contextual: Vec::new(),
global: ReplacementSet::default(),
}
}
pub(crate) fn global_replacements(mut self, replacements: ReplacementSet) -> Self {
self.global = replacements;
self
}
#[cfg(test)]
pub fn application(self, application: impl Into<String>, profile: Profile) -> Self {
self.push(ContextSelector::application(application.into()), profile)
}
pub fn browser_host(self, host: impl Into<String>, profile: Profile) -> Self {
self.push(ContextSelector::browser_host(host.into()), profile)
}
fn push(mut self, selector: ContextSelector, profile: Profile) -> Self {
if self
.contextual
.iter()
.any(|existing| existing.selector == selector)
{
tracing::warn!(?selector, "ignored duplicate dictation processor selector");
return self;
}
self.contextual
.push(ContextualProfile { selector, profile });
self
}
fn select<'a>(&'a self, context: &ContextSnapshot) -> &'a Profile {
let selected = self
.contextual
.iter()
.find(|candidate| {
candidate.selector.is_browser() && candidate.selector.matches(context)
})
.or_else(|| {
self.contextual.iter().find(|candidate| {
!candidate.selector.is_browser() && candidate.selector.matches(context)
})
});
selected.map_or(&self.default, |selected| &selected.profile)
}
/// The selected mode's own vocabulary.
pub(crate) fn vocabulary_for(&self, context: &ContextSnapshot) -> Vec<VocabularyEntry> {
self.select(context).vocabulary.clone()
}
/// The speech model and language the selected mode carries, if any.
pub(crate) fn speech_for(
&self,
context: &ContextSnapshot,
) -> Option<crate::app_settings::KeyboardModelChoice> {
self.select(context).speech.clone()
}
pub fn processes(&self, context: &ContextSnapshot) -> bool {
let profile = self.select(context);
// A cleanup-only or neutral-only dictation still shows the HUD's
// processing stage.
profile.ai_enabled
|| !profile.transformations.is_empty()
|| crate::dictation::apple_cleanup::runs_here()
|| (profile.neutral_voice && crate::dictation::neutral_voice::runs_here())
}
fn corrected(
&self,
profile: &Profile,
transcript: &str,
language: &str,
source: Source,
labs: DictationLabs,
) -> String {
let prepared = prepare_transcript(transcript, language, source, labs);
profile
.replacements
.replace(&self.global.replace(&prepared))
}
/// Whether processing `transcript` would run a voice prompt request: the
/// lab is on, this is heard speech, and the phrase is there after
/// preparation and replacements. The `Nothing` outcome asks nothing, so
/// it shows no stage either.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn voice_prompts(
&self,
transcript: &str,
language: &str,
context: &ContextSnapshot,
source: Source,
) -> bool {
use crate::dictation::voice_prompt::Instruction;
if source != Source::Dictation {
return false;
}
let Some(phrase) = crate::labs::voice_prompt().then(crate::labs::voice_prompt_phrase)
else {
return false;
};
let profile = self.select(context);
let corrected = self.corrected(
profile,
transcript,
language,
source,
DictationLabs::current(),
);
matches!(
crate::dictation::voice_prompt::instruction(&corrected, &phrase),
Some(instruction) if !matches!(instruction, Instruction::Nothing)
)
}
pub fn process_cancellable(
&self,
transcript: &str,
language: &str,
context: &ContextSnapshot,
cancelled: &AtomicBool,
source: Source,
) -> Processed {
let voice_prompt = crate::labs::voice_prompt().then(crate::labs::voice_prompt_phrase);
self.process_cancellable_with(
transcript,
language,
context,
cancelled,
source,
voice_prompt.as_deref(),
)
}
/// [`Self::process_cancellable`] with the voice prompt phrase already
/// resolved: `None` is Labs › Rewrite by voice off, or locked.
fn process_cancellable_with(
&self,
transcript: &str,
language: &str,
context: &ContextSnapshot,
cancelled: &AtomicBool,
source: Source,
voice_prompt: Option<&str>,
) -> Processed {
self.process_cancellable_inner(
transcript,
language,
context,
cancelled,
source,
voice_prompt,
true,
DictationLabs::current(),
)
}
/// The local API's `process=global`: Global mode's replacements,
/// corrections, rewrite, and transformations, without the dictation
/// style, which belongs to a dictation's own paste.
pub fn process_api_cancellable(
&self,
transcript: &str,
language: &str,
context: &ContextSnapshot,
cancelled: &AtomicBool,
source: Source,
) -> Processed {
let voice_prompt = crate::labs::voice_prompt().then(crate::labs::voice_prompt_phrase);
self.process_cancellable_inner(
transcript,
language,
context,
cancelled,
source,
voice_prompt.as_deref(),
false,
DictationLabs::current(),
)
}
#[allow(clippy::too_many_arguments)]
fn process_cancellable_inner(
&self,
transcript: &str,
language: &str,
context: &ContextSnapshot,
cancelled: &AtomicBool,
source: Source,
voice_prompt: Option<&str>,
style_dictation: bool,
labs: DictationLabs,
) -> Processed {
let profile = self.select(context);
// Labs › Spoken formatting, spoken symbols, and filler words only
// make sense for speech: typed text starts from what is already
// written and skips them.
let corrected = self.corrected(profile, transcript, language, source, labs);
// Labs › Dictation style writes a dictation's final text, after the
// corrections and any rewrite and before the transformations.
let style = labs
.dictation_style
.filter(|_| style_dictation && source == Source::Dictation);
// A transcript of numbers alone has nothing to rewrite; a model only
// turns it into digits and re-punctuates it (#949). The neutral pass
// and Labs › Clean up with Apple Intelligence skip those too.
let numbers_only = numbers_only(&corrected);
// Labs › Neutral voice replaces both the rewrite and the cleanup for
// an opted-in mode, and outranks the voice prompt too, so a privacy
// dictation never reaches OpenCode.
if let Some(processed) = crate::dictation::neutral_voice::processed(
&corrected,
numbers_only,
cancelled,
profile.neutral_voice,
source,
&profile.transformations,
) {
return with_style(processed, style, language);
}
// Labs › Rewrite by voice: heard speech may carry a spoken instruction
// that replaces the mode's rewrite with one request of its own.
if source == Source::Dictation
&& let Some(phrase) = voice_prompt
&& let Some(instruction) =
crate::dictation::voice_prompt::instruction(&corrected, phrase)
{
return with_style(
voice_prompt_processed(profile, &instruction, &corrected, context, cancelled),
style,
language,
);
}
if profile.ai_enabled && numbers_only {
tracing::info!(
profile = profile.name,
"dictation post-processing skipped for a numbers-only transcript"
);
}
if !profile.ai_enabled {
tracing::info!(
profile = profile.name,
"dictation post-processing skipped: the OpenCode rewrite is off for this mode"
);
}
if !profile.ai_enabled || numbers_only {
// A mode with no OpenCode rewrite leaves the corrections alone
// for one on-device pass; a mode that rewrites keeps its model.
let (text, observation) = if profile.ai_enabled || source != Source::Dictation {
(corrected, None)
} else {
crate::dictation::apple_cleanup::stage(&corrected, numbers_only, cancelled)
};
return with_style(
Processed {
text,
nothing: false,
observation,
transformations: profile.transformations.clone(),
},
style,
language,
);
}
let prompt = prompt(
profile,
&corrected,
context,
&crate::dictation::vocabulary::merged(
&profile.vocabulary,
&crate::dictation::vocabulary::entries(),
),
source,
);
let (text, observation) = generate_observed(
&prompt,
profile.model.as_ref(),
profile.deadline,
cancelled,
&profile.name,
Instant::now(),
);
let model = model_label(&observation);
match &observation.fallback {
None => tracing::info!(
profile = profile.name,
latency_ms = observation.latency_ms,
model = %model,
"dictation post-processing completed"
),
Some(reason) => tracing::warn!(
profile = profile.name,
latency_ms = observation.latency_ms,
model = %model,
%reason,
"dictation post-processing failed; pasting the corrected transcript"
),
}
with_style(
Processed {
text: text.unwrap_or(corrected),
nothing: false,
observation: Some(observation),
transformations: profile.transformations.clone(),
},
style,
language,
)
}
}
/// `processed` after Labs › Dictation style: the text is written in `style`
/// when the lab is on, and stays exactly as it was otherwise.
fn with_style(
mut processed: Processed,
style: Option<DictationStyle>,
language: &str,
) -> Processed {
if let Some(style) = style {
processed.text = crate::dictation::style::format(&processed.text, style, language);
}
processed
}
/// One voice-prompt request instead of the mode's rewrite: the spoken
/// instruction over the text before it, or what is there when one side is
/// empty. A phrase with nothing around it asks nothing and pastes nothing.
fn voice_prompt_processed(
profile: &Profile,
instruction: &crate::dictation::voice_prompt::Instruction,
corrected: &str,
context: &ContextSnapshot,
cancelled: &AtomicBool,
) -> Processed {
use crate::dictation::voice_prompt::Instruction;
if matches!(instruction, Instruction::Nothing) {
tracing::info!(
profile = profile.name,
"voice prompt had nothing to ask; nothing is pasted"
);
// No request ran, and no transformation gets a chance to turn an
// empty result into something that would paste.
return Processed {
text: String::new(),
nothing: true,
observation: None,
transformations: Vec::new(),
};
}
let request = voice_prompt_request(
profile,
instruction,
context,
&crate::dictation::vocabulary::merged(
&profile.vocabulary,
&crate::dictation::vocabulary::entries(),
),
);
// A voice prompt is one request: the mode's own rewrite never runs, even
// while its switch is off, with its model and deadline when it names one.
let (text, observation) = generate_observed(
&request,
profile.model.as_ref(),
profile.deadline,
cancelled,
&profile.name,
Instant::now(),
);
let model = model_label(&observation);
match &observation.fallback {
None => tracing::info!(
profile = profile.name,
latency_ms = observation.latency_ms,
model = %model,
"voice prompt completed"
),
Some(reason) => tracing::warn!(
profile = profile.name,
latency_ms = observation.latency_ms,
model = %model,
%reason,
"voice prompt failed; pasting what the speaker dictated"
),
}
voice_prompt_answer(
instruction,
text,
corrected,
&profile.transformations,
Some(observation),
)
}
/// The result a voice prompt pastes: the model's answer when it has one, else
/// [`voice_prompt_fallback`], then the mode's transformations as usual.
fn voice_prompt_answer(
instruction: &crate::dictation::voice_prompt::Instruction,
generated: Option<String>,
corrected: &str,
transformations: &[String],
observation: Option<ProcessingObservation>,
) -> Processed {
Processed {
text: generated.unwrap_or_else(|| voice_prompt_fallback(instruction, corrected)),
nothing: false,
observation,
transformations: transformations.to_vec(),
}
}
/// The request one voice prompt makes: the protocol, the mode's instructions
/// as background while its rewrite is on, the vocabulary and foreground
/// context a rewrite carries, and the spoken task.
fn voice_prompt_request(
profile: &Profile,
instruction: &crate::dictation::voice_prompt::Instruction,
context: &ContextSnapshot,
vocabulary: &[VocabularyEntry],
) -> String {
use crate::dictation::voice_prompt::Instruction;
let application = context.application.as_deref().unwrap_or("unknown");
let host = context.browser_host().unwrap_or("none");
let background = if profile.ai_enabled && !profile.prompt.trim().is_empty() {
format!(
"Background instructions for this mode (the spoken instruction overrides them when they conflict):\n{}\n\n",
profile.prompt
)
} else {
String::new()
};
let task = match instruction {
Instruction::Rewrite { text, prompt } => format!(
"The speaker dictated some text, then gave an instruction about it. Apply the spoken instruction to the dictated text and return only the result.\n\nSpoken instruction:\n<instruction>\n{prompt}\n</instruction>\n\nDictated text:\n<text>\n{text}\n</text>"
),
Instruction::RewriteText { text } => format!(
"Rewrite the dictated text below so it is clear and concise. Keep its meaning, facts, numbers, and names. Return only the rewritten text.\n\nDictated text:\n<text>\n{text}\n</text>"
),
Instruction::Write { prompt } => format!(
"The speaker asked you to write something. Write exactly what the spoken instruction asks for and return only that text.\n\nSpoken instruction:\n<instruction>\n{prompt}\n</instruction>"
),
Instruction::Nothing => unreachable!("nothing is never asked"),
};
format!(
"{PROTOCOL_PROMPT}\n\n{background}{}Foreground application: {application}\nBrowser host: {host}\n\n{task}",
vocabulary_lines(vocabulary)
)
}
/// What a failed, empty, or timed-out voice prompt pastes: the text before
/// the phrase, or the whole corrected transcript when there is none.
fn voice_prompt_fallback(
instruction: &crate::dictation::voice_prompt::Instruction,
corrected: &str,
) -> String {
use crate::dictation::voice_prompt::Instruction;
match instruction {
Instruction::Rewrite { text, .. } | Instruction::RewriteText { text } => text.clone(),
Instruction::Write { .. } => corrected.to_owned(),
Instruction::Nothing => String::new(),
}
}
/// One generation's text and the model that wrote it, when Hex named one
/// (`None` when OpenCode's own default model answered).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Generated {
pub text: String,
pub model: Option<Model>,
}
/// One generation from OpenCode's own default model, for work outside
/// dictation such as meeting notes: a request that names no model, so it
/// never walks the ranked models into another provider.
pub(crate) fn generate_text(
prompt: &str,
deadline: Duration,
cancelled: &AtomicBool,
) -> Result<Generated> {
let started = Instant::now();
let service = generation_service(started, deadline, cancelled)?;
generate_default_model(prompt, &service, started, deadline, cancelled)
}
/// [`generate_text`]'s one request, through the running service.
fn generate_default_model(
prompt: &str,
service: &Service,
started: Instant,
deadline: Duration,
cancelled: &AtomicBool,
) -> Result<Generated> {
let text = generate_single_model(
prompt,
None,
started,
deadline,
cancelled,
|data, remaining, cancelled| post_generation(service, data, remaining, cancelled),
)?;
Ok(Generated { text, model: None })
}
/// One generation from exactly `model`, never another provider's: a failure
/// is OpenCode's answer for that model (the meeting summary model).
pub(crate) fn generate_text_with(
prompt: &str,
model: &Model,
deadline: Duration,
cancelled: &AtomicBool,
) -> Result<Generated> {
generate_cancellable(prompt, Some(model), deadline, cancelled)
}
/// Runs one generation and reports it as a processing observation. The text is
/// `None` whenever the caller must fall back, with the reason recorded in the
/// observation.
fn generate_observed(
prompt: &str,
model: Option<&Model>,
deadline: Duration,
cancelled: &AtomicBool,
profile_name: &str,
started: Instant,
) -> (Option<String>, ProcessingObservation) {
observed(
generate_cancellable(prompt, model, deadline, cancelled),
model,
profile_name,
started.elapsed(),
)
}
/// The text and observation for one generation. The observation names the
/// model that answered, or the one the request asked for when nothing did, so
/// logs and retained events say which model rewrote the text.
fn observed(
result: Result<Generated>,
requested: Option<&Model>,
profile_name: &str,
elapsed: Duration,
) -> (Option<String>, ProcessingObservation) {
let (text, model, fallback) = match result {
Ok(generated) => {
let trimmed = generated.text.trim();
let text = (!trimmed.is_empty()).then(|| trimmed.to_owned());
let fallback = text
.is_none()
.then(|| "processor returned empty text".to_owned());
(text, generated.model, fallback)
}
Err(error) => (None, requested.cloned(), Some(error.to_string())),
};
let observation = ProcessingObservation {
profile: profile_name.into(),
latency_ms: elapsed.as_millis() as u64,
model: model
.as_ref()
.map(|model| format!("{}/{}", model.provider, model.id)),
fallback,
};
(text, observation)
}
/// What a processing log line names for the model that ran: the named model
/// that answered, or on failure the one the request asked for; OpenCode's own
/// default when no model was named and it answered; and Hex's automatic
/// choice when no named model answered at all.
fn model_label(observation: &ProcessingObservation) -> &str {
match observation.model.as_deref() {
Some(model) => model,
None if observation.fallback.is_some() => AUTOMATIC_MODEL,
None => OPENCODE_DEFAULT_MODEL,
}
}
/// What a processing log line names when the request named no model and
/// Hex's automatic ranked choice had no model answer.
const AUTOMATIC_MODEL: &str = "automatic";
/// What a processing log line names when the request asked for no model:
/// OpenCode picked its own default.
const OPENCODE_DEFAULT_MODEL: &str = "opencode default";
#[derive(Clone, Debug)]
pub struct ModelChoice {
pub key: String,
pub name: String,
pub provider: String,
pub variants: Vec<String>,
}
#[derive(Clone, Debug)]
pub struct ModelCatalog {
pub models: Vec<ModelChoice>,
pub default_key: Option<String>,
pub default_name: Option<String>,
pub default_variant: Option<String>,
}
impl ModelCatalog {
/// Whether an unset model key gets Hex's own ranked pick instead of
/// OpenCode's default model. [`build_model_catalog`] sets the default
/// from the ranked list exactly when this is true.
pub fn automatic_default(&self) -> bool {
!self.ranked_candidates(None).is_empty()
}
pub fn recommended_variant_for(&self, key: &str) -> Option<&str> {
let choice = self.models.iter().find(|choice| choice.key == key)?;
recommended_variant_for_choice(choice)
}
pub fn ranked_candidates(&self, variant_override: Option<&str>) -> Vec<Model> {
ranked_choice_indices(&self.models)
.into_iter()
.filter_map(|index| {
let choice = &self.models[index];
let (provider, id) = choice.key.split_once('/')?;
let variant = variant_override
.filter(|v| choice.variants.iter().any(|candidate| candidate == *v))
.or_else(|| recommended_variant_for_choice(choice))
.map(str::to_owned);
Some(Model {
provider: provider.into(),
id: id.into(),
variant,
})
})
.collect()
}
}
fn leaf_model_id(key: &str) -> &str {
key.rsplit_once('/').map_or(key, |(_, id)| id)
}
fn matches_recommended_model_id(leaf: &str, recommended_id: &str) -> bool {
if leaf == recommended_id {
return true;
}
let Some(suffix) = leaf.strip_prefix(recommended_id) else {
return false;
};
suffix == "-preview"
|| suffix == "-latest"
|| (suffix.starts_with("-20") && suffix[1..].bytes().all(|byte| byte.is_ascii_digit()))
}
fn recommendation_entry_for_key(key: &str) -> Option<(usize, &'static RecommendedModel)> {
let leaf = leaf_model_id(key);
RECOMMENDED_OPENCODE_MODELS
.iter()
.enumerate()
.find(|(_, rec)| matches_recommended_model_id(leaf, rec.id))
}
fn recommended_variant_for_choice(choice: &ModelChoice) -> Option<&str> {
let (_, rec) = recommendation_entry_for_key(&choice.key)?;
rec.preferred_variants
.iter()
.copied()
.find(|preferred| choice.variants.iter().any(|v| v == *preferred))
}
/// Providers that wrap a model in a local agent harness instead of calling
/// its API directly. Each request pays that harness's startup, so they stay
/// selectable but are never picked automatically (#1954).
const AGENT_HARNESS_PROVIDERS: &[&str] = &["claude-agent"];
fn is_agent_harness_provider(provider: &str) -> bool {
AGENT_HARNESS_PROVIDERS.contains(&provider)
}
fn provider_priority(provider: &str) -> usize {
match provider {
"google" | "anthropic" | "openai" => 0,
"opencode" => 1,
"github-copilot" => 2,
p if p.starts_with("console-") => 3,
_ => 4,
}
}
fn ranked_choice_indices(choices: &[ModelChoice]) -> Vec<usize> {
let mut ranked = Vec::new();
for rec in RECOMMENDED_OPENCODE_MODELS {
if let Some((best_idx, _)) = choices
.iter()
.enumerate()
.filter(|(_, choice)| !is_agent_harness_provider(&choice.provider))
.filter(|(_, choice)| matches_recommended_model_id(leaf_model_id(&choice.key), rec.id))
.min_by_key(|(idx, choice)| (provider_priority(&choice.provider), *idx))
&& !ranked.contains(&best_idx)
{
ranked.push(best_idx);
}
}
ranked
}
#[derive(Deserialize)]
struct ModelsResponse {
data: Vec<ModelInfo>,
}
#[derive(Deserialize)]
struct DefaultModelResponse {
data: Option<ModelInfo>,
}
#[derive(Clone, Deserialize)]
struct ModelInfo {
id: String,
#[serde(rename = "providerID")]
provider_id: String,
name: String,
enabled: bool,
capabilities: ModelCapabilities,
variants: Vec<ModelVariant>,
}
#[derive(Clone, Deserialize)]
struct ModelCapabilities {
output: Vec<String>,
}
#[derive(Clone, Deserialize)]
struct ModelVariant {
id: String,
}
fn model_is_available(model: &ModelInfo) -> bool {
model.enabled
&& model
.capabilities
.output
.iter()
.any(|output| output == "text")
}
/// The ranked default candidates for the service at `address`, cached with
/// the last catalog so a rewrite doesn't fetch it every time.
static CACHED_RANKED_CANDIDATES: std::sync::Mutex<Option<(Service, Vec<Model>)>> =
std::sync::Mutex::new(None);
fn cache_ranked_candidates(service: &Service, catalog: &ModelCatalog) {
if let Ok(mut guard) = CACHED_RANKED_CANDIDATES.lock() {
*guard = Some((service.clone(), catalog.ranked_candidates(None)));
}
}
/// Drops the cached ranked candidates once one of them failed: the catalog
/// may have been read while OpenCode was still loading, listing models that
/// left it since (#1123). The next generation reads the catalog again.
fn forget_ranked_candidates() {
if let Ok(mut guard) = CACHED_RANKED_CANDIDATES.lock() {
*guard = None;
}
}
fn ranked_candidates_for(
service: &Service,
deadline: Duration,
cancelled: &AtomicBool,
) -> Vec<Model> {
if let Ok(guard) = CACHED_RANKED_CANDIDATES.lock()
&& let Some((cached, candidates)) = guard.as_ref()
&& cached == service
{
return candidates.clone();
}
let Ok(models) = opencode_api_within::<ModelsResponse>(
service,
"/api/model",
deadline.min(CATALOG_DEADLINE),
cancelled,
) else {
// A cancelled or timed-out lookup caches nothing, like any other
// catalog failure: the next generation reads it again.
return Vec::new();
};
let catalog = build_model_catalog(models.data, None);
cache_ranked_candidates(service, &catalog);
catalog.ranked_candidates(None)
}
/// The running service's model catalog. Reads OpenCode's registration and
/// talks loopback HTTP; never starts anything. Call off the UI thread.
/// `None` when OpenCode isn't running; an obsolete OpenCode is an error that
/// says to update it.
pub fn load_model_catalog() -> Result<Option<ModelCatalog>> {
use crate::desktop::opencode_service::Missing;
let service = match crate::desktop::opencode_service::find() {
Ok(service) => service,
Err(Missing::NotRunning) => return Ok(None),
Err(missing) => return Err(eyre!(missing.message())),
};
let models: ModelsResponse = opencode_api(&service, "/api/model")?;
let default: DefaultModelResponse = opencode_api(&service, "/api/model/default")?;
let catalog = build_model_catalog(models.data, default.data);
cache_ranked_candidates(&service, &catalog);
Ok(Some(catalog))
}
fn build_model_catalog(models: Vec<ModelInfo>, default: Option<ModelInfo>) -> ModelCatalog {
let fallback_default_key = default
.as_ref()
.map(|model| format!("{}/{}", model.provider_id, model.id));
let fallback_default_name = default.as_ref().map(|model| model.name.clone());
let mut seen = HashSet::new();
let raw_choices: Vec<ModelChoice> = models
.into_iter()
.chain(default)
.filter(model_is_available)
.filter_map(|model| {
let key = format!("{}/{}", model.provider_id, model.id);
seen.insert(key.clone()).then_some(ModelChoice {
key,
name: model.name,
provider: model.provider_id,
variants: model
.variants
.into_iter()
.map(|variant| variant.id)
.collect(),
})
})
.collect();
let ranked_indices = ranked_choice_indices(&raw_choices);
let mut choices = Vec::with_capacity(raw_choices.len());
for &idx in &ranked_indices {
choices.push(raw_choices[idx].clone());
}
for (idx, choice) in raw_choices.into_iter().enumerate() {
if !ranked_indices.contains(&idx) {
choices.push(choice);
}
}
let (default_key, default_name, default_variant) = if !ranked_indices.is_empty()
&& let Some(top) = choices.first()
{
(
Some(top.key.clone()),
Some(top.name.clone()),
recommended_variant_for_choice(top).map(str::to_owned),
)
} else {
(fallback_default_key, fallback_default_name, None)
};
ModelCatalog {
default_key,
default_name,
default_variant,
models: choices,
}
}
fn decode_api_response<T: for<'de> Deserialize<'de>>(path: &str, body: &[u8]) -> Result<T> {
let value: serde_json::Value = serde_json::from_slice(body)
.wrap_err_with(|| format!("OpenCode {path} returned invalid JSON"))?;
if let Some(message) = value.get("message").and_then(|message| message.as_str())
&& value.get("_tag").is_some()
{
return Err(eyre!("OpenCode {path} failed: {message}"));
}
serde_json::from_value(value)
.wrap_err_with(|| format!("OpenCode {path} returned an invalid response"))
}
fn opencode_api<T: for<'de> Deserialize<'de>>(service: &Service, path: &str) -> Result<T> {
opencode_api_within(service, path, CATALOG_DEADLINE, &AtomicBool::new(false))
}
fn opencode_api_within<T: for<'de> Deserialize<'de>>(
service: &Service,
path: &str,
deadline: Duration,
cancelled: &AtomicBool,
) -> Result<T> {
let workspace = crate::app_paths::opencode_workspace()?;
let response = service.request("GET", path, None, Some(&workspace), deadline, cancelled)?;
if !(200..300).contains(&response.status) {
return Err(eyre!("OpenCode {path} answered HTTP {}", response.status));
}
decode_api_response(path, &response.body)
}
/// The transcript ahead of mode corrections. Spoken formatting, spoken
/// symbols, and filler words only apply to heard speech, so typed text skips
/// every one of them.
fn prepare_transcript(
transcript: &str,
language: &str,
source: Source,
labs: DictationLabs,
) -> String {
if source != Source::Dictation {
return transcript.to_owned();
}
let formatted;
let transcript = if labs.spoken_formatting {
formatted = crate::dictation::spoken_formatting::apply(transcript);
formatted.as_str()
} else {
transcript
};
let symbolized;
let transcript = if labs.spoken_symbols {
symbolized = crate::dictation::spoken_symbols::apply(transcript);
symbolized.as_str()
} else {
transcript
};
// Only English dictations drop fillers: "er" and "um" are ordinary words
// in other languages, and "auto" says nothing about the language.
crate::dictation::filler_words::strip_if(transcript, language, labs.filler_words)
.unwrap_or_else(|| transcript.to_owned())
}
fn prompt(
profile: &Profile,
transcript: &str,
context: &ContextSnapshot,
vocabulary: &[VocabularyEntry],
source: Source,
) -> String {
let application = context.application.as_deref().unwrap_or("unknown");
let host = context.browser_host().unwrap_or("none");
let caret = crate::dictation::caret_prompt::for_source(context, source)
.map(crate::dictation::caret_prompt::section)
.unwrap_or_default();
format!(
"{PROTOCOL_PROMPT}\n\nProfile instructions:\n{}\n\n{}Foreground application: {application}\nBrowser host: {host}\n\n{caret}Raw transcript:\n<transcript>\n{transcript}\n</transcript>",
profile.prompt,
vocabulary_lines(vocabulary)
)
}
/// The vocabulary as prompt lines, so a rewrite spells its terms right;
/// nothing when it is empty (or its experiment is off).
fn vocabulary_lines(vocabulary: &[VocabularyEntry]) -> String {
if vocabulary.is_empty() {
return String::new();
}
let terms = vocabulary
.iter()
.map(|entry| match entry.sounds_like.as_slice() {
[] => entry.term.clone(),
spellings => format!(
"{} (may be transcribed as {})",
entry.term,
spellings.join(", ")
),
})
.collect::<Vec<_>>()
.join("; ");
format!("Vocabulary (spell these exactly when the speaker means them): {terms}\n\n")
}
#[cfg(test)]
fn generate(prompt: &str, model: Option<&Model>, deadline: Duration) -> Result<String> {
generate_cancellable(prompt, model, deadline, &AtomicBool::new(false))
.map(|generated| generated.text)
}
fn generate_cancellable(
prompt: &str,
model: Option<&Model>,
deadline: Duration,
cancelled: &AtomicBool,
) -> Result<Generated> {
let started = Instant::now();
let service = generation_service(started, deadline, cancelled)?;
generate_with_candidates(
prompt,
model,
|| {
ranked_candidates_for(
&service,
deadline.saturating_sub(started.elapsed()),
cancelled,
)
},
forget_ranked_candidates,
started,
deadline,
cancelled,
|data, remaining, cancelled| post_generation(&service, data, remaining, cancelled),
)
}
/// Finds the running OpenCode service, or why it can't answer. Service
/// discovery spends the generation's own remaining budget, so a stalled
/// OpenCode falls back by the deadline instead of adding its fixed lookup
/// timeouts on top.
fn generation_service(
started: Instant,
deadline: Duration,
cancelled: &AtomicBool,
) -> Result<Service> {
let lock = crate::policy::Lock::OpenCodeProcessing;
if crate::policy::Policy::current().locks(lock) {
return Err(eyre!(lock.refusal()));
}
let service = crate::desktop::opencode_service::find_cancellable(
remaining_generation_deadline(started, deadline)?,
cancelled,
);
if cancelled.load(Ordering::Acquire) {
return Err(eyre!("OpenCode generation was cancelled"));
}
remaining_generation_deadline(started, deadline)?;
service.map_err(|missing| eyre!(missing.message()))
}
#[allow(clippy::too_many_arguments)]
fn generate_with_candidates(
prompt: &str,
model: Option<&Model>,
candidates: impl FnOnce() -> Vec<Model>,
forget_candidates: impl FnMut(),
started: Instant,
deadline: Duration,
cancelled: &AtomicBool,
post: impl FnMut(&str, Duration, &AtomicBool) -> Result<Response>,
) -> Result<Generated> {
if model.is_none() {
let candidates = candidates();
if !candidates.is_empty() {
return generate_with_ranked_candidates(
prompt,
&candidates,
forget_candidates,
started,
deadline,
cancelled,
post,
);
}
}
let text = generate_single_model(prompt, model, started, deadline, cancelled, post)?;
Ok(Generated {
text,
model: model.cloned(),
})
}
/// Walks the ranked models in order. Any failure forgets the cached list so
/// the next generation reads OpenCode's catalog again, and when every ranked
/// model fails, OpenCode's own default model answers instead (#1123).
fn generate_with_ranked_candidates(
prompt: &str,
candidates: &[Model],
mut forget_candidates: impl FnMut(),
started: Instant,
deadline: Duration,
cancelled: &AtomicBool,
mut post: impl FnMut(&str, Duration, &AtomicBool) -> Result<Response>,
) -> Result<Generated> {
let mut last_error = None;
for candidate in candidates {
let remaining = remaining_generation_deadline(started, deadline)?;
let data = serde_json::to_string(&Request {
prompt,
model: Some(candidate),
})?;
let response = match post(&data, remaining, cancelled) {
Ok(response) => response,
Err(error) => {
forget_candidates();
return Err(error);
}
};
match response {
Response::Success { data } => {
return Ok(Generated {
text: data.text,
model: Some(candidate.clone()),
});
}
Response::Error { message } => {
forget_candidates();
tracing::warn!(
provider = %candidate.provider,
model = %candidate.id,
%message,
"ranked OpenCode model failed; trying the next one"
);
last_error = Some(message);
}
}
}
tracing::warn!("every ranked OpenCode model failed; asking OpenCode's default model");
match generate_single_model(prompt, None, started, deadline, cancelled, &mut post) {
Ok(text) => Ok(Generated { text, model: None }),
Err(error) => Err(match last_error {
Some(message) => eyre!(
"OpenCode generation failed: {message}; OpenCode's default model also failed: {error:#}"
),
None => error,
}),
}
}
#[cfg(test)]
mod tests {
use super::generation::{ResponseData, retryable_generation_error, wait_for_generation_retry};
use super::*;
use crate::dictation::caret_text::CaretText;
use std::net::TcpListener;
use std::thread;
use url::Url;
#[test]
fn managed_locks_drop_the_rewrite_and_transformations() {
use crate::policy::{Lock, Policy};
let settings = PostProcessingSettings {
enabled: true,
..PostProcessingSettings::default()
};
let build = |policy| {
Profile::configured_under(
"Mode",
ReplacementSet::default(),
vec!["lowercase".into()],
&settings,
policy,
)
};
let open = build(Policy::default());
assert!(open.rewrites());
assert_eq!(open.transformations, ["lowercase"]);
let rewrite = build(Policy::default().with(Lock::OpenCodeProcessing));
assert!(!rewrite.rewrites());
assert_eq!(rewrite.transformations, ["lowercase"]);
let transforms = build(Policy::default().with(Lock::Transforms));
assert!(transforms.rewrites());
assert!(transforms.transformations.is_empty());
}
fn context(application: &str, url: Option<&str>) -> ContextSnapshot {
ContextSnapshot {
application: Some(application.into()),
browser_url: url.map(|url| Url::parse(url).unwrap()),
window_title: None,
input_revision: None,
screen_terms: Vec::new(),
caret_text: None,
bundle_name: None,
}
}
fn profiles() -> Profiles {
Profiles::new(Profile::new("default", "default prompt").ai_enabled(true))
.application("Slack", Profile::new("slack", "slack prompt"))
.browser_host("x.com", Profile::new("x", "x prompt"))
}
#[test]
fn model_catalog_uses_wire_catalog_ids_and_preserves_aliases() {
let wire_models = ["rewrite-fast", "rewrite-careful", "rewrite-fast"].map(|id| {
serde_json::json!({
"id": id,
"modelID": "shared-deployment",
"providerID": "example",
"name": id,
"enabled": true,
"status": "active",
"capabilities": { "tools": false, "input": ["text"], "output": ["text"] },
"variants": [{ "id": "high" }],
"time": { "released": 0 },
"cost": [],
"limit": { "context": 10000, "output": 1000 }
})
});
let models: ModelsResponse =
serde_json::from_value(serde_json::json!({ "data": wire_models })).unwrap();
let mut default: DefaultModelResponse =
serde_json::from_value(serde_json::json!({ "data": wire_models[1] })).unwrap();
let default_model = default.data.as_mut().unwrap();
default_model.name = "Default display name".into();
default_model.variants.clear();
let catalog = build_model_catalog(models.data, default.data);
assert_eq!(catalog.models.len(), 2);
assert_eq!(
catalog.default_name.as_deref(),
Some("Default display name")
);
assert_eq!(
catalog.default_key.as_deref(),
Some("example/rewrite-careful")
);
assert!(!catalog.automatic_default());
for (choice, expected_id) in catalog
.models
.iter()
.zip(["rewrite-fast", "rewrite-careful"])
{
assert_eq!(choice.key, format!("example/{expected_id}"));
assert_eq!(choice.name, expected_id);
assert_eq!(choice.variants, ["high"]);
let (provider, id) = choice.key.split_once('/').unwrap();
let model = Model {
provider: provider.into(),
id: id.into(),
variant: Some("high".into()),
};
let request = serde_json::to_value(Request {
prompt: "Rewrite this.",
model: Some(&model),
})
.unwrap();
assert_eq!(
request["model"],
serde_json::json!({
"providerID": "example", "id": expected_id, "variant": "high"
})
);
}
let mut missing_catalog_id = wire_models[0].clone();
missing_catalog_id.as_object_mut().unwrap().remove("id");
assert!(serde_json::from_value::<ModelInfo>(missing_catalog_id).is_err());
}
#[test]
fn model_catalog_keeps_an_available_default_missing_from_the_model_list() {
let default: DefaultModelResponse = serde_json::from_value(serde_json::json!({
"data": {
"id": "rewrite-default",
"modelID": "shared-deployment",
"providerID": "example",
"name": "Example Rewrite",
"enabled": true,
"status": "beta",
"capabilities": { "tools": false, "input": ["text"], "output": ["text"] },
"variants": [{ "id": "high" }],
"time": { "released": 0 },
"cost": [],
"limit": { "context": 10000, "output": 1000 }
}
}))
.unwrap();
let model = default.data.unwrap();
let catalog = build_model_catalog(Vec::new(), Some(model.clone()));
assert_eq!(catalog.models.len(), 1);
assert_eq!(catalog.models[0].key, "example/rewrite-default");
assert_eq!(catalog.models[0].variants, ["high"]);
assert_eq!(
catalog.default_key.as_deref(),
Some("example/rewrite-default")
);
assert_eq!(catalog.default_name.as_deref(), Some("Example Rewrite"));
for unavailable in [
ModelInfo {
enabled: false,
..model.clone()
},
ModelInfo {
capabilities: ModelCapabilities {
output: vec!["image".into()],
},
..model
},
] {
let catalog = build_model_catalog(Vec::new(), Some(unavailable));
assert!(catalog.models.is_empty());
assert_eq!(
catalog.default_key.as_deref(),
Some("example/rewrite-default")
);
assert_eq!(catalog.default_name.as_deref(), Some("Example Rewrite"));
}
}
#[test]
fn model_catalog_keeps_available_text_models_regardless_of_release_status() {
let wire_models: Vec<_> = [
("active", "active", true, "text"),
("alpha", "alpha", true, "text"),
("beta", "beta", true, "text"),
("deprecated", "deprecated", true, "text"),
("disabled", "active", false, "text"),
("image", "active", true, "image"),
]
.into_iter()
.map(|(id, status, enabled, output)| {
serde_json::json!({
"id": id,
"modelID": id,
"providerID": "example",
"name": id,
"enabled": enabled,
"status": status,
"capabilities": { "tools": false, "input": ["text"], "output": [output] },
"variants": [],
"time": { "released": 0 },
"cost": [],
"limit": { "context": 10000, "output": 1000 }
})
})
.collect();
let models: ModelsResponse =
serde_json::from_value(serde_json::json!({ "data": wire_models })).unwrap();
let catalog = build_model_catalog(models.data, None);
assert_eq!(
catalog
.models
.iter()
.map(|choice| choice.key.as_str())
.collect::<Vec<_>>(),
[
"example/active",
"example/alpha",
"example/beta",
"example/deprecated"
]
);
}
#[test]
fn browser_host_beats_application_and_application_beats_default() {
let profiles = profiles();
assert_eq!(
profiles
.select(&context("Brave Browser", Some("https://x.com/home")))
.name,
"x"
);
assert_eq!(profiles.select(&context("Slack", None)).name, "slack");
assert_eq!(profiles.select(&context("Zed", None)).name, "default");
}
#[test]
fn prompt_contains_only_current_transcript_and_selected_context() {
let profile = Profile::new("default", "Rewrite freely.");
let prompt = prompt(
&profile,
"This is the current transcript.",
&context("Slack", None),
&[],
Source::Dictation,
);
assert!(prompt.contains("Rewrite freely."));
assert!(prompt.contains("Foreground application: Slack"));
assert!(prompt.contains("This is the current transcript."));
assert!(!prompt.contains("Vocabulary"));
}
#[test]
fn a_prompt_without_caret_text_is_byte_for_byte_todays_prompt() {
let expected = [
PROTOCOL_PROMPT,
"\n\nProfile instructions:\nRewrite freely.\n\nForeground application: Slack\n\
Browser host: none\n\nRaw transcript:\n<transcript>\n\
This is the current transcript.\n</transcript>",
]
.concat();
let prompt = prompt(
&Profile::new("default", "Rewrite freely."),
"This is the current transcript.",
&context("Slack", None),
&[],
Source::Dictation,
);
assert_eq!(prompt, expected);
}
#[test]
fn caret_text_joins_the_prompt_ahead_of_the_transcript() {
let mut with_caret = context("Slack", None);
with_caret.caret_text = Some(CaretText {
before: "We ship on ".into(),
selected: "Friday".into(),
after: " morning.".into(),
});
let prompt = prompt(
&Profile::new("default", "Rewrite freely."),
"we ship on friday morning.",
&with_caret,
&[],
Source::Dictation,
);
assert!(
prompt.contains("<before_cursor>\nWe ship on \n</before_cursor>"),
"{prompt}"
);
assert!(
prompt.contains("<selected_text>\nFriday\n</selected_text>"),
"{prompt}"
);
assert!(
prompt.contains("The selected text will be replaced and will not remain."),
"{prompt}"
);
assert!(
prompt.contains("<after_cursor>\n morning.\n</after_cursor>"),
"{prompt}"
);
let caret = prompt.find("<before_cursor>").unwrap();
let raw = prompt.find("Raw transcript:").unwrap();
assert!(caret < raw, "the context sits before the transcript");
}
#[test]
fn empty_caret_parts_leave_no_tags_and_typed_text_reads_none() {
let mut with_caret = context("Slack", None);
with_caret.caret_text = Some(CaretText {
before: "Only before".into(),
..CaretText::default()
});
let dictation = prompt(
&Profile::new("default", "Rewrite freely."),
"Ship it.",
&with_caret,
&[],
Source::Dictation,
);
assert!(dictation.contains("<before_cursor>\nOnly before\n</before_cursor>"));
assert!(!dictation.contains("<selected_text>"));
assert!(!dictation.contains("<after_cursor>"));
assert!(!dictation.contains("will be replaced"));
let typed = prompt(
&Profile::new("default", "Rewrite freely."),
"Ship it.",
&with_caret,
&[],
Source::TypedText,
);
assert!(!typed.contains("<before_cursor>"), "{typed}");
assert_eq!(
typed,
prompt(
&Profile::new("default", "Rewrite freely."),
"Ship it.",
&context("Slack", None),
&[],
Source::TypedText,
)
);
}
#[test]
fn prompt_names_vocabulary_terms_and_their_mistranscriptions() {
let vocabulary = [
VocabularyEntry {
term: "cappuccino".into(),
sounds_like: vec!["capuchin".into(), "cap a chino".into()],
},
VocabularyEntry {
term: "Rune".into(),
sounds_like: vec![],
},
];
let prompt = prompt(
&Profile::new("default", "Rewrite freely."),
"Ship the avatar change.",
&context("Slack", None),
&vocabulary,
Source::Dictation,
);
assert!(prompt.contains(
"Vocabulary (spell these exactly when the speaker means them): cappuccino (may be \
transcribed as capuchin, cap a chino); Rune\n\nForeground application: Slack"
));
}
#[test]
fn a_contextual_raw_mode_overrides_processed_default() {
let profiles = Profiles::new(Profile::new("default", "default prompt").ai_enabled(true))
.application("Slack", Profile::new("raw", "").ai_enabled(false));
assert!(!profiles.select(&context("Slack", None)).ai_enabled);
assert_eq!(profiles.select(&context("Zed", None)).name, "default");
}
fn voice_prompt(text: &str) -> crate::dictation::voice_prompt::Instruction {
crate::dictation::voice_prompt::instruction(text, "rewrite this")
.expect("the phrase is in the transcript")
}
#[test]
fn a_spoken_instruction_replaces_the_rewrite_and_carries_context() {
let instruction = voice_prompt("We ship Friday. rewrite this make it formal");
let vocabulary = [VocabularyEntry {
term: "Rune".into(),
sounds_like: vec!["roon".into()],
}];
let rewrite = Profile::new("Mode", "Keep it short.").ai_enabled(true);
let request = voice_prompt_request(
&rewrite,
&instruction,
&context("Slack", Some("https://x.com/home")),
&vocabulary,
);
assert!(request.contains("Keep it short."), "{request}");
assert!(request.contains("make it formal"), "{request}");
assert!(request.contains("We ship Friday"), "{request}");
assert!(
request.contains("Foreground application: Slack"),
"{request}"
);
assert!(request.contains("Browser host: x.com"), "{request}");
assert!(
request.contains("Rune (may be transcribed as roon)"),
"{request}"
);
assert!(request.contains(PROTOCOL_PROMPT), "{request}");
// A mode with its rewrite off uses the same request without its
// prompt as background.
let plain = voice_prompt_request(
&Profile::new("Mode", "Keep it short."),
&instruction,
&context("Slack", None),
&[],
);
assert!(!plain.contains("Keep it short."), "{plain}");
assert!(plain.contains("make it formal"), "{plain}");
}
#[test]
fn a_failed_voice_prompt_pastes_its_text_or_the_whole_transcript() {
let both = voice_prompt("Ship it. rewrite this make it formal");
assert_eq!(
voice_prompt_fallback(&both, "Ship it. rewrite this make it formal"),
"Ship it."
);
let text_only = voice_prompt("Ship it. rewrite this");
assert_eq!(
voice_prompt_fallback(&text_only, "Ship it. rewrite this"),
"Ship it."
);
// Nothing before the phrase: the whole corrected transcript falls back.
let prompt_only = voice_prompt("rewrite this an email to Bob");
assert_eq!(
voice_prompt_fallback(&prompt_only, "rewrite this an email to Bob"),
"rewrite this an email to Bob"
);
}
#[test]
fn text_only_and_prompt_only_requests_ask_for_the_right_thing() {
let profile = Profile::new("Mode", "");
let text_only = voice_prompt("We ship Friday. rewrite this");
let request = voice_prompt_request(&profile, &text_only, &context("Zed", None), &[]);
assert!(
request.contains("Rewrite the dictated text below so it is clear and concise"),
"{request}"
);
assert!(request.contains("We ship Friday."), "{request}");
assert!(!request.contains("<instruction>"), "{request}");
let prompt_only = voice_prompt("rewrite this an email to Bob");
let request = voice_prompt_request(&profile, &prompt_only, &context("Zed", None), &[]);
assert!(
request.contains("Write exactly what the spoken instruction asks for"),
"{request}"
);
assert!(request.contains("an email to Bob"), "{request}");
assert!(!request.contains("<text>"), "{request}");
// A mode whose rewrite is on but has no prompt adds no empty header.
let request = voice_prompt_request(
&Profile::new("Mode", " ").ai_enabled(true),
&text_only,
&context("Zed", None),
&[],
);
assert!(!request.contains("Background instructions"), "{request}");
}
#[test]
fn a_closed_or_locked_voice_prompt_gate_leaves_processing_alone() {
use crate::policy::{Lock, Policy};
let profiles = Profiles::new(Profile::new("default", "").ai_enabled(false));
let context = context("Zed", None);
let transcript = "We ship Friday. rewrite this make it formal";
let cancelled = AtomicBool::new(false);
// Labs › Rewrite by voice off: no phrase is even resolved.
let processed = profiles.process_cancellable_with(
transcript,
"en",
&context,
&cancelled,
Source::Dictation,
None,
);
assert_eq!(processed.text, transcript);
assert!(!processed.nothing);
// An organization's DisableOpenCodeProcessing lock closes the gate,
// even with the lab's saved switch on.
let locked =
crate::labs::voice_prompt_under(Policy::default().with(Lock::OpenCodeProcessing));
assert!(!locked);
let locked_phrase = locked.then(crate::labs::voice_prompt_phrase);
let processed = profiles.process_cancellable_with(
transcript,
"en",
&context,
&cancelled,
Source::Dictation,
locked_phrase.as_deref(),
);
assert_eq!(processed.text, transcript);
// Typed text never splits on the phrase.
let processed = profiles.process_cancellable_with(
transcript,
"en",
&context,
&cancelled,
Source::TypedText,
Some("rewrite this"),
);
assert_eq!(processed.text, transcript);
assert!(!processed.nothing);
}
#[test]
fn a_voice_prompt_that_asks_nothing_ends_through_process_cancellable() {
let profiles = Profiles::new(Profile::new("default", ""));
let processed = profiles.process_cancellable_with(
"rewrite this thanks a lot",
"en",
&context("Zed", None),
&AtomicBool::new(false),
Source::Dictation,
Some("rewrite this"),
);
assert_eq!(processed.text, "");
assert!(processed.nothing, "the listeners finish quietly");
assert!(processed.transformations.is_empty());
}
#[test]
fn a_voice_prompt_answer_or_its_fallback_keeps_the_modes_transformations() {
let both = voice_prompt("Ship it. rewrite this make it formal");
let transformations = vec!["lowercase".to_string()];
let answered = voice_prompt_answer(
&both,
Some("Make it formal.".into()),
"Ship it. rewrite this make it formal",
&transformations,
None,
);
assert_eq!(answered.text, "Make it formal.");
assert_eq!(answered.transformations, transformations);
let failed = voice_prompt_answer(
&both,
None,
"Ship it. rewrite this make it formal",
&transformations,
None,
);
assert_eq!(failed.text, "Ship it.");
assert_eq!(failed.transformations, transformations);
}
#[test]
fn a_voice_prompt_with_nothing_to_ask_pastes_nothing_and_runs_no_transformations() {
let processed = voice_prompt_processed(
&Profile::new("Mode", "").transformations(vec!["lowercase".into()]),
&voice_prompt("rewrite this thanks"),
"rewrite this thanks",
&context("Zed", None),
&AtomicBool::new(false),
);
assert_eq!(processed.text, "");
assert!(processed.transformations.is_empty());
assert!(processed.observation.is_none());
}
#[test]
fn typed_text_skips_the_dictation_only_labs() {
let labs = DictationLabs {
spoken_formatting: true,
spoken_symbols: true,
filler_words: true,
dictation_style: None,
};
let speech = "um first new line done comma thanks";
let dictated = prepare_transcript(speech, "en", Source::Dictation, labs);
assert!(dictated.contains('\n'), "{dictated}");
assert!(dictated.contains(", "), "{dictated}");
assert!(!dictated.to_lowercase().contains("um "), "{dictated}");
assert!(!dictated.contains("new line"), "{dictated}");
assert!(
!dictated.contains("comma"),
"spoken symbols should have replaced it: {dictated}"
);
// Typed text runs the same profile but none of the speech Labs.
assert_eq!(
prepare_transcript(speech, "en", Source::TypedText, labs),
speech
);
assert_eq!(
prepare_transcript(speech, "en", Source::Dictation, DictationLabs::default()),
speech
);
}
/// Labs › Dictation style writes a dictation's final text after its
/// corrections and before the transformations; typed text and the local
/// API's process=global keep their text exactly.
#[test]
fn the_dictation_style_writes_a_dictation_and_leaves_typed_text_and_the_api_alone() {
use crate::app_settings::DictationStyle;
let profiles =
Profiles::new(Profile::new("Global", "").transformations(vec!["lowercase".into()]));
let context = context("Zed", None);
let cancelled = AtomicBool::new(false);
let casual = DictationLabs {
dictation_style: Some(DictationStyle::Casual),
..DictationLabs::default()
};
let dictated = profiles.process_cancellable_inner(
"Um, I'll call Ravi.",
"en",
&context,
&cancelled,
Source::Dictation,
None,
true,
casual,
);
assert_eq!(dictated.text, "i'll call Ravi");
// The transformation runs after the style, so its lowercase output
// proves the style wrote "i'll call Ravi" first.
let mut dictated = dictated;
dictated.apply_transformations(
&crate::personal_commands::TransformationClient::default(),
&context,
&cancelled,
Source::Dictation,
);
assert_eq!(dictated.text, "i'll call ravi");
let typed = profiles.process_cancellable_inner(
"Um, I'll call Ravi.",
"en",
&context,
&cancelled,
Source::TypedText,
None,
true,
casual,
);
assert_eq!(typed.text, "Um, I'll call Ravi.");
let api = profiles.process_cancellable_inner(
"Um, I'll call Ravi.",
"en",
&context,
&cancelled,
Source::Dictation,
None,
false,
casual,
);
assert_eq!(api.text, "Um, I'll call Ravi.");
assert_eq!(dictated.transformations, ["lowercase"]);
}
/// Labs › Transform typed text runs the same profile but never the
/// dictation cleanup, so its text and observation are untouched.
#[test]
fn typed_text_never_reaches_the_dictation_cleanup() {
let profiles = Profiles::new(Profile::new("Global", ""));
let processed = profiles.process_cancellable(
"ship it",
"en",
&context("Zed", None),
&AtomicBool::new(false),
Source::TypedText,
);
assert_eq!(processed.text, "ship it");
assert!(processed.observation.is_none());
assert!(processed.transformations.is_empty());
}
/// A transcript of nothing but numbers gets no cleanup pass either: the
/// guard's digit rule would refuse anything a model could add.
#[test]
fn a_numbers_only_dictation_skips_the_cleanup() {
let profiles = Profiles::new(Profile::new("Global", ""));
let processed = profiles.process_cancellable(
"one two three four five",
"en",
&context("Zed", None),
&AtomicBool::new(false),
Source::Dictation,
);
assert_eq!(processed.text, "one two three four five");
assert!(processed.observation.is_none());
}
/// Only a mode that opts in carries Labs › Neutral voice into its
/// profile; every other mode behaves as before.
#[test]
fn only_a_mode_that_asks_for_neutral_voice_carries_it() {
use crate::app_settings::{DictationMode, DictationProcessingSettings};
let profiles = Profiles::from_settings(&DictationProcessingSettings {
modes: vec![
DictationMode {
applications: vec!["Notes".into()],
..Default::default()
},
DictationMode {
applications: vec!["Slack".into()],
neutral_voice: true,
..Default::default()
},
],
..Default::default()
});
assert!(!profiles.select(&context("Notes", None)).neutral_voice);
assert!(profiles.select(&context("Slack", None)).neutral_voice);
assert!(!profiles.select(&context("Zed", None)).neutral_voice);
}
#[test]
fn speech_preparation_precedes_global_and_mode_corrections() {
use crate::app_settings::{DictationMode, DictationProcessingSettings};
use crate::dictation::text_replacements::TextReplacement;
let pair = |from: &str, to: &str| TextReplacement {
matched_phrase: from.into(),
output: to.into(),
};
let profiles = Profiles::from_settings(&DictationProcessingSettings {
default_mode: DictationMode {
replacements: vec![pair("comma", "WRONG"), pair("thanks", "thank you")],
..Default::default()
},
modes: vec![DictationMode {
applications: vec!["Notes".into()],
replacements: vec![pair("thank you", "cheers")],
..Default::default()
}],
});
let profile = profiles.select(&context("Notes", None));
let labs = DictationLabs {
spoken_symbols: true,
..Default::default()
};
assert_eq!(
profiles.corrected(profile, "done comma thanks", "en", Source::Dictation, labs),
"done, cheers"
);
assert_eq!(
profiles.corrected(profile, "done comma thanks", "en", Source::TypedText, labs),
"done WRONG cheers"
);
}
#[test]
fn shared_pipeline_preserves_the_macos_corpus_output() {
use crate::app_settings::{AppSettings, DictationMode};
use crate::dictation::text_replacements::TextReplacement;
let mut settings = AppSettings::default();
settings.dictation_processing.default_mode.replacements = vec![TextReplacement {
matched_phrase: "notes".into(),
output: "documents".into(),
}];
settings.dictation_processing.default_mode.transformations = vec!["lowercase".into()];
settings.dictation_processing.modes = vec![DictationMode {
name: "Writing".into(),
applications: vec!["Notes".into()],
browser_hosts: vec!["example.com".into()],
replacements: vec![TextReplacement {
matched_phrase: "documents".into(),
output: "drafts".into(),
}],
transformations: vec!["no-trailing-punctuation".into()],
..Default::default()
}];
// The former macOS compiler, independent of the shared settings entry point.
let global = &settings.dictation_processing.default_mode;
let mode = &settings.dictation_processing.modes[0];
let reference = Profiles::new(Profile::configured(
"Global",
ReplacementSet::default(),
global.transformations.clone(),
&global.post_processing,
))
.global_replacements(ReplacementSet::new(&global.replacements))
.application("Notes", Profile::from_mode(mode))
.browser_host("example.com", Profile::from_mode(mode));
let runtime = crate::dictation::modes::ModeRuntime::from_settings(&settings);
let transformations = crate::personal_commands::TransformationClient::default();
let corpus: serde_json::Value = serde_json::from_str(include_str!(
"../../tests/fixtures/vocabulary/manifest.json"
))
.unwrap();
for clip in corpus["clips"].as_array().unwrap() {
let text = clip["expected"].as_str().unwrap();
for context in [
context("Other", None),
context("Notes", None),
context("Browser", Some("https://example.com/page")),
] {
let mut expected = reference.process_cancellable(
text,
"en",
&context,
&AtomicBool::new(false),
Source::Dictation,
);
expected.apply_transformations(
&transformations,
&context,
&AtomicBool::new(false),
Source::Dictation,
);
let actual =
runtime.process(text, "en", &context, &transformations, Source::Dictation);
assert_eq!(actual.text, expected.text, "{}", clip["id"]);
assert_eq!(actual.nothing, expected.nothing);
assert_eq!(
actual
.observation
.as_ref()
.and_then(|value| value.fallback.as_ref()),
None
);
}
}
}
#[test]
fn mode_corrections_run_before_registered_transformations() {
let profile = Profile::new("Global", "")
.replacements(ReplacementSet::new(&[
crate::dictation::text_replacements::TextReplacement {
matched_phrase: "open code".into(),
output: "OpenCode".into(),
},
]))
.transformations(vec!["lowercase".into()]);
let profiles = Profiles::new(profile);
let processed = profiles.process_cancellable(
"Use open code.",
"en",
&context("Zed", None),
&AtomicBool::new(false),
Source::Dictation,
);
assert_eq!(processed.text, "Use OpenCode.");
assert_eq!(processed.transformations, ["lowercase"]);
assert!(processed.observation.is_none());
}
#[test]
fn numbers_only_transcripts_skip_the_rewrite() {
for numbers in [
"One, two, three, four, five, six, seven, eight, nine, ten.",
"1355",
"Twenty-one point five.",
"one hundred and forty two",
] {
assert!(numbers_only(numbers), "{numbers}");
}
for speech in [
"",
"And.",
"Point one, the dataset has 1355 evaluation windows.",
"Call me at five.",
] {
assert!(!numbers_only(speech), "{speech}");
}
let profiles = Profiles::new(Profile::new("default", "Rewrite freely.").ai_enabled(true));
let processed = profiles.process_cancellable(
"one two three four five",
"en",
&context("Zed", None),
&AtomicBool::new(false),
Source::Dictation,
);
assert_eq!(processed.text, "one two three four five");
assert!(processed.observation.is_none());
}
#[test]
fn only_model_unavailability_is_retried() {
assert!(retryable_generation_error(
"Model unavailable: example/rewrite-model"
));
assert!(!retryable_generation_error("Provider request failed"));
assert!(!retryable_generation_error("processor returned empty text"));
}
/// The meeting summary model: a chosen model is the only one
/// asked, and its failure is reported rather than another provider tried.
#[test]
fn a_chosen_model_is_asked_alone_and_never_falls_back() {
let chosen = Model {
provider: "openai".into(),
id: "gpt-5".into(),
variant: None,
};
let mut posted = Vec::new();
let error = generate_with_candidates(
"Summarize.",
Some(&chosen),
|| -> Vec<Model> { panic!("a chosen model never reads the ranked candidates") },
|| panic!("a chosen model never forgets the ranked candidates"),
Instant::now(),
Duration::from_secs(5),
&AtomicBool::new(false),
|data, _, _| {
posted.push(data.to_owned());
Ok(Response::Error {
message: "Provider request failed".into(),
})
},
)
.unwrap_err();
assert!(
error.to_string().contains("Provider request failed"),
"{error}"
);
assert_eq!(posted.len(), 1);
assert!(
posted[0].contains(r#""providerID":"openai""#),
"{}",
posted[0]
);
}
#[test]
fn generation_retry_wait_observes_cancellation() {
let cancelled = AtomicBool::new(true);
let started = Instant::now();
let error = wait_for_generation_retry(started, Duration::from_secs(30), &cancelled)
.expect_err("cancelled retry unexpectedly waited");
assert!(error.to_string().contains("was cancelled"));
assert!(started.elapsed() < Duration::from_secs(1));
}
/// A rewrite with no time left, or one already cancelled, stops before
/// asking for a service; nothing may add a fixed lookup timeout on top.
#[test]
fn a_generation_without_time_or_after_cancellation_fails_promptly() {
let started = Instant::now();
let error = generate_cancellable(
"Rewrite this.",
None,
Duration::ZERO,
&AtomicBool::new(false),
)
.unwrap_err();
assert!(error.to_string().contains("exceeded"), "{error}");
let error = generate_cancellable(
"Rewrite this.",
None,
Duration::from_secs(1),
&AtomicBool::new(true),
)
.unwrap_err();
assert!(error.to_string().contains("cancelled"), "{error}");
assert!(
started.elapsed() < Duration::from_secs(1),
"{:?}",
started.elapsed()
);
}
#[test]
fn a_cancelled_catalog_lookup_returns_nothing_and_caches_nothing() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/", listener.local_addr().unwrap());
let service = crate::desktop::opencode_service::tests::fixture(&url);
let started = Instant::now();
assert!(
ranked_candidates_for(&service, Duration::from_secs(30), &AtomicBool::new(true))
.is_empty()
);
assert!(
started.elapsed() < Duration::from_secs(1),
"{:?}",
started.elapsed()
);
let cached = CACHED_RANKED_CANDIDATES.lock().unwrap();
assert!(
!cached
.as_ref()
.is_some_and(|(cached, _)| *cached == service),
"a cancelled catalog lookup must not cache its result"
);
}
/// The service fixture answering each `(path, status, body)` POST in order.
fn generation_server(
routes: Vec<(&'static str, u16, &'static str)>,
) -> (Service, thread::JoinHandle<Vec<Vec<u8>>>) {
let (url, server) = crate::desktop::opencode_service::tests::serve(
routes
.into_iter()
.map(|(path, status, body)| (format!("POST {path}"), status, body.to_owned()))
.collect(),
);
let server = thread::spawn(move || {
server
.join()
.unwrap()
.into_iter()
.map(|(_, body)| body)
.collect()
});
(
crate::desktop::opencode_service::tests::fixture(&url),
server,
)
}
#[test]
fn generation_falls_back_to_the_legacy_route_only_when_the_new_one_is_missing() {
let success = r#"{"data":{"text":"fixture result"}}"#;
let unavailable = r#"{"_tag":"InvalidRequestError","message":"Model unavailable: x"}"#;
for (routes, expected) in [
(
vec![
("/api/experimental/generate", 404, ""),
("/api/generate", 200, success),
],
Ok("fixture result"),
),
(
vec![("/api/experimental/generate", 400, unavailable)],
Err("Model unavailable: x"),
),
(
vec![(
"/api/experimental/generate",
404,
r#"{"_tag":"NotFoundError","message":"Model not found: github-copilot/gpt-5.4-nano"}"#,
)],
Err("Model not found: github-copilot/gpt-5.4-nano"),
),
(
vec![
(
"/api/experimental/generate",
404,
r#"{"error":"Not Found"}"#,
),
("/api/generate", 404, ""),
],
Err("does not serve a generation route"),
),
] {
let requests = routes.len();
let (service, server) = generation_server(routes);
let result = post_generation(
&service,
"{}",
Duration::from_secs(5),
&AtomicBool::new(false),
);
match (result, expected) {
(Ok(Response::Success { data }), Ok(text)) => assert_eq!(data.text, text),
(Ok(Response::Error { message }), Err(text)) => assert_eq!(message, text),
(Err(error), Err(text)) => assert!(error.to_string().contains(text), "{error}"),
(result, expected) => {
panic!(
"unexpected outcome for {expected:?}: {:?}",
result.map(|_| ())
)
}
}
assert_eq!(server.join().unwrap().len(), requests);
}
}
#[test]
fn model_catalog_ranks_recommended_models_and_selects_top_available_default_with_variant() {
let model_info = |provider: &str, id: &str, name: &str, variants: &[&str]| ModelInfo {
id: id.into(),
provider_id: provider.into(),
name: name.into(),
enabled: true,
capabilities: ModelCapabilities {
output: vec!["text".into()],
},
variants: variants
.iter()
.map(|v| ModelVariant { id: (*v).into() })
.collect(),
};
let heavy_default = model_info("example", "heavy-agent", "Heavy Agent", &["high"]);
let models = vec![
model_info("example", "unranked-a", "Unranked A", &[]),
model_info(
"openai",
"gpt-5.4-nano",
"GPT-5.4 Nano",
&["none", "low", "medium"],
),
model_info(
"anthropic",
"claude-haiku-4-5-20251001",
"Claude Haiku 4.5",
&[],
),
model_info(
"google",
"gemini-3.1-flash-lite",
"Gemini 3.1 Flash Lite",
&["minimal", "low", "high"],
),
];
let catalog = build_model_catalog(models.clone(), Some(heavy_default.clone()));
assert_eq!(
catalog.default_key.as_deref(),
Some("google/gemini-3.1-flash-lite")
);
assert_eq!(
catalog.default_name.as_deref(),
Some("Gemini 3.1 Flash Lite")
);
assert!(catalog.automatic_default());
assert_eq!(catalog.default_variant.as_deref(), Some("minimal"));
assert_eq!(
catalog
.models
.iter()
.map(|choice| choice.key.as_str())
.collect::<Vec<_>>(),
[
"google/gemini-3.1-flash-lite",
"anthropic/claude-haiku-4-5-20251001",
"openai/gpt-5.4-nano",
"example/unranked-a",
"example/heavy-agent",
]
);
// Removing the #1 recommendation falls back to #2 (`claude-haiku-4-5`), then #3 (`gpt-5.4-nano` with `none`).
let without_gemini: Vec<_> = models
.iter()
.filter(|m| m.id != "gemini-3.1-flash-lite")
.cloned()
.collect();
let catalog2 = build_model_catalog(without_gemini.clone(), Some(heavy_default.clone()));
assert_eq!(
catalog2.default_key.as_deref(),
Some("anthropic/claude-haiku-4-5-20251001")
);
assert_eq!(catalog2.default_variant, None);
let only_nano: Vec<_> = without_gemini
.into_iter()
.filter(|m| !m.id.starts_with("claude-haiku-4-5"))
.collect();
let catalog3 = build_model_catalog(only_nano, Some(heavy_default));
assert_eq!(catalog3.default_key.as_deref(), Some("openai/gpt-5.4-nano"));
assert_eq!(catalog3.default_variant.as_deref(), Some("none"));
}
fn model_choice(provider: &str, id: &str, name: &str, variants: &[&str]) -> ModelInfo {
ModelInfo {
id: id.into(),
provider_id: provider.into(),
name: name.into(),
enabled: true,
capabilities: ModelCapabilities {
output: vec!["text".into()],
},
variants: variants
.iter()
.map(|v| ModelVariant { id: (*v).into() })
.collect(),
}
}
#[test]
fn model_catalog_ranks_a_direct_provider_over_its_agent_harness() {
let models = vec![
model_choice(
"claude-agent",
"claude-haiku-4-5-20251001",
"Claude Haiku 4.5",
&[],
),
model_choice(
"anthropic",
"claude-haiku-4-5-20251001",
"Claude Haiku 4.5",
&[],
),
];
let catalog = build_model_catalog(models, None);
assert_eq!(
catalog.default_key.as_deref(),
Some("anthropic/claude-haiku-4-5-20251001")
);
assert_eq!(
catalog
.ranked_candidates(None)
.iter()
.map(|model| (model.provider.as_str(), model.id.as_str()))
.collect::<Vec<_>>(),
[("anthropic", "claude-haiku-4-5-20251001")]
);
assert!(
catalog
.models
.iter()
.any(|choice| choice.key == "claude-agent/claude-haiku-4-5-20251001"),
"the agent harness stays explicitly selectable: {:?}",
catalog
.models
.iter()
.map(|choice| choice.key.as_str())
.collect::<Vec<_>>()
);
}
#[test]
fn agent_harness_models_never_rank_and_fall_back_to_the_default_model() {
let harness = model_choice(
"claude-agent",
"claude-haiku-4-5-20251001",
"Claude Haiku 4.5",
&[],
);
let direct = model_choice("openai", "gpt-5.4-nano", "GPT-5.4 Nano", &[]);
let opencode_default = model_choice("example", "default-model", "Default Model", &[]);
let catalog = build_model_catalog(
vec![harness.clone(), direct],
Some(opencode_default.clone()),
);
assert_eq!(catalog.default_key.as_deref(), Some("openai/gpt-5.4-nano"));
assert_eq!(
catalog
.ranked_candidates(None)
.iter()
.map(|model| model.provider.as_str())
.collect::<Vec<_>>(),
["openai"]
);
let only_harness = build_model_catalog(vec![harness], Some(opencode_default));
assert!(only_harness.ranked_candidates(None).is_empty());
assert_eq!(
only_harness.default_key.as_deref(),
Some("example/default-model")
);
assert!(
only_harness
.models
.iter()
.any(|choice| choice.key == "claude-agent/claude-haiku-4-5-20251001")
);
}
#[test]
fn ranked_generation_walks_candidates_until_one_succeeds() {
let candidates = vec![
Model {
provider: "google".into(),
id: "gemini-3.1-flash-lite".into(),
variant: Some("minimal".into()),
},
Model {
provider: "anthropic".into(),
id: "claude-haiku-4-5".into(),
variant: None,
},
Model {
provider: "openai".into(),
id: "gpt-5.4-nano".into(),
variant: Some("none".into()),
},
];
let (service, server) = generation_server(vec![
(
"/api/experimental/generate",
400,
r#"{"message":"Model unavailable: google/gemini-3.1-flash-lite"}"#,
),
(
"/api/experimental/generate",
200,
r#"{"data":{"text":"resolved from second ranked model"}}"#,
),
]);
let mut forgotten = 0;
let output = generate_with_ranked_candidates(
"Make this concise.",
&candidates,
|| forgotten += 1,
Instant::now(),
Duration::from_secs(5),
&AtomicBool::new(false),
|data, remaining, cancelled| post_generation(&service, data, remaining, cancelled),
)
.unwrap();
assert_eq!(output.text, "resolved from second ranked model");
assert_eq!(output.model.as_ref(), Some(&candidates[1]));
assert_eq!(forgotten, 1, "a failed candidate drops the cached list");
let requests = server.join().unwrap();
assert_eq!(requests.len(), 2);
let first: serde_json::Value = serde_json::from_slice(&requests[0]).unwrap();
let second: serde_json::Value = serde_json::from_slice(&requests[1]).unwrap();
assert_eq!(
first["model"],
serde_json::json!({
"providerID": "google",
"id": "gemini-3.1-flash-lite",
"variant": "minimal"
})
);
assert_eq!(
second["model"],
serde_json::json!({
"providerID": "anthropic",
"id": "claude-haiku-4-5"
})
);
}
/// A processing observation names the model that answered, so the log
/// line and the retained event say which one rewrote the text.
#[test]
fn a_processing_observation_names_the_model_that_answered() {
let model = Model {
provider: "anthropic".into(),
id: "claude-haiku-4-5".into(),
variant: None,
};
let (text, observation) = observed(
Ok(Generated {
text: " rewritten ".into(),
model: Some(model.clone()),
}),
None,
"Chat",
Duration::from_millis(120),
);
assert_eq!(text.as_deref(), Some("rewritten"));
assert_eq!(
observation.model.as_deref(),
Some("anthropic/claude-haiku-4-5")
);
assert_eq!(observation.fallback, None);
assert_eq!(observation.latency_ms, 120);
// OpenCode's own default answered: there is no model to name.
let (_, observation) = observed(
Ok(Generated {
text: "rewritten".into(),
model: None,
}),
None,
"Chat",
Duration::ZERO,
);
assert_eq!(observation.model, None);
// Nothing answered: the observation still names the model asked for.
let (text, observation) =
observed(Err(eyre!("boom")), Some(&model), "Chat", Duration::ZERO);
assert_eq!(text, None);
assert_eq!(
observation.model.as_deref(),
Some("anthropic/claude-haiku-4-5")
);
assert_eq!(observation.fallback.as_deref(), Some("boom"));
// An empty answer still names the model that made it.
let (text, observation) = observed(
Ok(Generated {
text: " ".into(),
model: Some(model),
}),
None,
"Chat",
Duration::ZERO,
);
assert_eq!(text, None);
assert_eq!(
observation.model.as_deref(),
Some("anthropic/claude-haiku-4-5")
);
assert_eq!(
observation.fallback.as_deref(),
Some("processor returned empty text")
);
}
/// A failure with no named model leaves the observation without one, so
/// the log line must not claim OpenCode's default model ran.
#[test]
fn a_processing_log_line_names_the_model_or_its_automatic_choice() {
let model = Model {
provider: "anthropic".into(),
id: "claude-haiku-4-5".into(),
variant: None,
};
let answered = |model| {
observed(
Ok(Generated {
text: "rewritten".into(),
model,
}),
None,
"Chat",
Duration::ZERO,
)
.1
};
assert_eq!(
model_label(&answered(Some(model.clone()))),
"anthropic/claude-haiku-4-5"
);
let failed = observed(Err(eyre!("boom")), Some(&model), "Chat", Duration::ZERO).1;
assert_eq!(model_label(&failed), "anthropic/claude-haiku-4-5");
assert_eq!(model_label(&answered(None)), "opencode default");
let automatic = observed(
Err(eyre!("OpenCode isn't running")),
None,
"Chat",
Duration::ZERO,
)
.1;
assert_eq!(model_label(&automatic), "automatic");
}
/// A ranked list read while OpenCode was still loading can name models
/// that left its catalog (#1123): every one failing forgets the list and
/// asks OpenCode's own default model instead.
#[test]
fn stale_ranked_models_fall_back_to_the_default_model() {
let candidates = vec![Model {
provider: "github-copilot".into(),
id: "gpt-5.4-nano".into(),
variant: None,
}];
let mut forgotten = 0;
let mut posted = Vec::new();
let output = generate_with_ranked_candidates(
"Summarize.",
&candidates,
|| forgotten += 1,
Instant::now(),
Duration::from_secs(5),
&AtomicBool::new(false),
|data, _, _| {
posted.push(serde_json::from_str::<serde_json::Value>(data).unwrap());
Ok(if posted.len() == 1 {
Response::Error {
message: "Model not found: github-copilot/gpt-5.4-nano".into(),
}
} else {
Response::Success {
data: ResponseData {
text: "from the default".into(),
},
}
})
},
)
.unwrap();
assert_eq!(output.text, "from the default");
assert_eq!(output.model, None);
assert_eq!(forgotten, 1);
assert_eq!(posted.len(), 2);
assert!(posted[1].get("model").is_none(), "{}", posted[1]);
}
/// Meeting notes with no chosen model ask only OpenCode's own default:
/// one request with no `model`, never a ranked candidate's catalog read
/// or provider.
#[test]
fn a_meeting_generation_posts_one_request_naming_no_model() {
let (service, server) = generation_server(vec![(
"/api/experimental/generate",
200,
r#"{"data":{"text":"from OpenCode's default"}}"#,
)]);
let generated = generate_default_model(
"Summarize.",
&service,
Instant::now(),
Duration::from_secs(5),
&AtomicBool::new(false),
)
.unwrap();
assert_eq!(generated.text, "from OpenCode's default");
assert_eq!(generated.model, None);
let requests = server.join().unwrap();
assert_eq!(requests.len(), 1, "one request, with no catalog read");
let posted: serde_json::Value = serde_json::from_slice(&requests[0]).unwrap();
assert!(posted.get("model").is_none(), "{posted}");
}
#[test]
#[ignore = "requires a running OpenCode service"]
fn live_catalog() {
let catalog = load_model_catalog()
.unwrap()
.expect("OpenCode should be running");
println!("{}", catalog.models.len());
}
#[test]
#[ignore = "requires a running OpenCode service and a configured model"]
fn live_generation_returns_text_without_creating_a_session() {
assert_eq!(
generate("Reply with exactly: test", None, Duration::from_secs(30)).unwrap(),
"test"
);
}
}