use serde_json::Value;
use crate::config::fingerprint;
#[derive(Clone)]
pub enum Arg {
Plain(String),
Secret(String),
}
impl Arg {
pub fn value(&self) -> &str {
match self {
Arg::Plain(s) | Arg::Secret(s) => s,
}
}
pub fn p(s: impl Into<String>) -> Arg {
Arg::Plain(s.into())
}
}
impl std::fmt::Debug for Arg {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Arg::Plain(s) => write!(f, "{s:?}"),
Arg::Secret(_) => write!(f, "«redacted»"),
}
}
}
#[derive(Clone)]
pub struct StdinSecret(String);
impl StdinSecret {
pub fn new(value: impl Into<String>) -> Result<StdinSecret, String> {
let value = value.into();
if value.contains('\n') || value.contains('\r') {
return Err("the secret contains a line break; it must be one line".into());
}
Ok(StdinSecret(value))
}
pub fn line(&self) -> String {
format!("{}\n", self.0)
}
}
impl std::fmt::Debug for StdinSecret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "«redacted»")
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum RmwOp {
SetField {
section: String,
key: String,
value: Value,
},
ClearField { section: String, key: String },
RemoveFallbackEntry { section: String, index: usize },
ClearGlobalDefaultFields,
ResetAudioStrategy,
}
impl RmwOp {
pub fn apply(&self, raw: &mut Value) -> Result<(), String> {
let obj = raw.as_object_mut().ok_or("config root is not an object")?;
match self {
RmwOp::SetField {
section,
key,
value,
} => {
let sec = obj
.entry(section.clone())
.or_insert_with(|| Value::Object(Default::default()));
let sec = sec.as_object_mut().ok_or_else(|| {
format!("section {section} is not an object — fix it by hand first")
})?;
sec.insert(key.clone(), value.clone());
Ok(())
}
RmwOp::ClearField { section, key } => {
if let Some(sec) = obj.get_mut(section).and_then(Value::as_object_mut) {
sec.remove(key);
}
Ok(())
}
RmwOp::RemoveFallbackEntry { section, index } => {
let chain = obj
.get_mut(section)
.and_then(Value::as_object_mut)
.and_then(|s| s.get_mut("fallback_chain"))
.and_then(Value::as_array_mut)
.ok_or_else(|| format!("{section}.fallback_chain is not a list"))?;
if *index >= chain.len() {
return Err(format!(
"entry {index} no longer exists (the chain has {})",
chain.len()
));
}
chain.remove(*index);
Ok(())
}
RmwOp::ClearGlobalDefaultFields => {
if let Some(dm) = obj.get_mut("default_models").and_then(Value::as_object_mut) {
dm.insert("global_provider".into(), Value::Null);
dm.insert("global_model".into(), Value::Null);
}
Ok(())
}
RmwOp::ResetAudioStrategy => {
obj.remove(crate::schema::META_FLAG);
if let Some(audio) = obj.get_mut("audio").and_then(Value::as_object_mut) {
audio.remove("strategy");
audio.remove("strategy_explicit");
}
Ok(())
}
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum WriteVerb {
Cli(Vec<Arg>),
ApplyRecommended(Vec<Arg>),
Rmw(RmwOp),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Expect {
Eq {
path: Vec<String>,
value: Value,
},
Cleared {
path: Vec<String>,
},
SecretFp {
path: Vec<String>,
fp: String,
},
RouteEq {
key: String,
provider: Option<String>,
model: Option<String>,
reasoning: Option<String>,
},
RouteCleared {
key: String,
},
ProfileExists {
id: String,
},
ProfileAbsent {
id: String,
},
}
impl Expect {
pub fn needs_routes(&self) -> bool {
matches!(self, Expect::RouteEq { .. } | Expect::RouteCleared { .. })
}
pub fn needs_profiles(&self) -> bool {
matches!(
self,
Expect::ProfileExists { .. } | Expect::ProfileAbsent { .. }
)
}
}
#[derive(Clone, Debug)]
pub struct WriteSpec {
pub label: String,
pub verbs: Vec<WriteVerb>,
pub expects: Vec<Expect>,
pub base_stamp: Option<crate::config::FileStamp>,
pub form_id: Option<u64>,
}
impl WriteSpec {
pub fn needs_routes(&self) -> bool {
self.expects.iter().any(Expect::needs_routes)
}
pub fn needs_profiles(&self) -> bool {
self.expects.iter().any(Expect::needs_profiles)
}
}
fn walk<'v>(raw: &'v Value, path: &[String]) -> Option<&'v Value> {
let mut cur = raw;
for seg in path {
cur = match cur {
Value::Array(items) => items.get(seg.parse::<usize>().ok()?)?,
other => other.get(seg)?,
};
}
Some(cur)
}
pub fn eval_file_expect(raw: &Value, expect: &Expect) -> Result<String, String> {
let get = |path: &[String]| -> Option<&Value> { walk(raw, path) };
let dotted = |path: &[String]| path.join(".");
match expect {
Expect::Eq { path, value } => {
let got = get(path);
if got == Some(value) {
Ok(format!("{} = {}", dotted(path), value))
} else {
Err(format!(
"{} is {} (expected {})",
dotted(path),
got.map(Value::to_string).unwrap_or_else(|| "absent".into()),
value
))
}
}
Expect::Cleared { path } => match get(path) {
None | Some(Value::Null) => Ok(format!("{} cleared", dotted(path))),
Some(Value::String(s)) if s.trim().is_empty() => {
Ok(format!("{} cleared", dotted(path)))
}
Some(v) => Err(format!("{} still holds {}", dotted(path), redact_scalar(v))),
},
Expect::SecretFp { path, fp } => match get(path).and_then(Value::as_str) {
Some(s) if fingerprint(s) == *fp => Ok(format!("{} stored (fp {fp})", dotted(path))),
Some(_) => Err(format!(
"{} holds a DIFFERENT value (fingerprint mismatch)",
dotted(path)
)),
None => Err(format!("{} is not set", dotted(path))),
},
other => Err(format!("not a file expectation: {other:?}")),
}
}
fn redact_scalar(v: &Value) -> String {
match v {
Value::String(_) => "a value («redacted»)".into(),
other => other.to_string(),
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FieldRoute {
Set(&'static str),
SetBlankClears(&'static str),
Toggle { on: &'static str, off: &'static str },
Rmw,
Pair,
Secret,
VisionStrategy,
}
pub fn field_route(section: &str, key: &str) -> FieldRoute {
use FieldRoute as R;
match (section, key) {
("vision", "strategy") => R::VisionStrategy,
("vision", "caption_provider" | "caption_model") => R::Pair,
("vision", "fallback_chain") => R::Rmw, ("vision", "local_models_path") => R::Rmw,
("audio", "strategy") => R::Set("--set-audio-strategy"),
("audio", "stt_backend_id") => R::SetBlankClears("--set-stt-backend-id"),
("audio", "stt_language") => R::SetBlankClears("--set-stt-language"),
("audio", _) => R::Rmw,
("video", "strategy") => R::Set("--set-video-strategy"),
("video", "max_frames") => R::Set("--set-video-max-frames"),
("video", "max_frames_native") => R::Set("--set-video-max-frames-native"),
("video", "frame_format") => R::Set("--set-video-frame-format"),
("video", "sampling_strategy") => R::Set("--set-video-sampling-strategy"),
("video", "max_frame_side") => R::Set("--set-video-max-frame-side"),
("video", "max_video_size_bytes") => R::Set("--set-video-max-size-bytes"),
("embeddings", "provider" | "model") => R::Pair,
("embeddings", "base_url") => R::SetBlankClears("--set-embeddings-base-url"),
("app_defaults", _) => R::Pair,
("default_models", "global_provider" | "global_model") => R::Pair,
("default_models", "chat_model") => R::Set("--set-chat-model"),
("default_models", "code_model") => R::Set("--set-code-model"),
("api_keys", _) => R::Secret,
("server", "auth_token") => R::Secret,
("server", "allow_unauthenticated") => R::Toggle {
on: "--allow-unauthenticated-server",
off: "--disallow-unauthenticated-server",
},
("server", "base_url_allowlist") => R::SetBlankClears("--set-server-base-url-allowlist"),
("server", "url_fetch_allowlist") => R::SetBlankClears("--set-server-url-fetch-allowlist"),
("server", "media_root") => R::SetBlankClears("--set-server-media-root"),
("server", "allow_local_files") => R::Toggle {
on: "--allow-server-local-files",
off: "--disallow-server-local-files",
},
("server", "host") => R::Set("--set-server-host"),
("server", "port") => R::Set("--set-server-port"),
("cache", "default_cache_dir") => R::Set("--set-default-cache-dir"),
("cache", "huggingface_cache_dir") => R::Set("--set-huggingface-cache-dir"),
("cache", "local_models_cache_dir") => R::Set("--set-local-models-cache-dir"),
("cache", "glyph_cache_dir") => R::Rmw,
("logging", "console_level") => R::Set("--set-console-log-level"),
("logging", "file_level") => R::Set("--set-file-log-level"),
("logging", "file_logging_enabled") => R::Toggle {
on: "--enable-file-logging",
off: "--disable-file-logging",
},
("logging", "log_base_dir") => R::Set("--set-log-base-dir"),
("logging", _) => R::Rmw,
("streaming", "cli_stream_default") => R::Toggle {
on: "--enable-streaming",
off: "--disable-streaming",
},
("timeouts", "default_timeout") => R::Set("--set-default-timeout"),
("timeouts", "tool_timeout") => R::Set("--set-tool-timeout"),
_ => R::Rmw,
}
}
fn path2(section: &str, key: &str) -> Vec<String> {
vec![section.to_string(), key.to_string()]
}
pub fn set_scalar(
section: &str,
key: &str,
value: Value,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> Result<WriteSpec, String> {
let label = format!("set {section}.{key} = {value}");
let cli_value = match &value {
Value::String(s) => s.clone(),
other => other.to_string(),
};
let (verbs, expects) = match field_route(section, key) {
FieldRoute::Set(flag) | FieldRoute::SetBlankClears(flag) => (
vec![WriteVerb::Cli(vec![Arg::p(flag), Arg::p(cli_value)])],
vec![Expect::Eq {
path: path2(section, key),
value,
}],
),
FieldRoute::Toggle { on, off } => {
let is_on = value.as_bool().ok_or("toggle needs a bool")?;
(
vec![WriteVerb::Cli(vec![Arg::p(if is_on { on } else { off })])],
vec![Expect::Eq {
path: path2(section, key),
value,
}],
)
}
FieldRoute::Rmw => (
vec![WriteVerb::Rmw(RmwOp::SetField {
section: section.into(),
key: key.into(),
value: value.clone(),
})],
vec![Expect::Eq {
path: path2(section, key),
value,
}],
),
other => {
return Err(format!(
"{section}.{key} routes to {other:?} — use its editor"
))
}
};
Ok(WriteSpec {
label,
verbs,
expects,
base_stamp: base,
form_id,
})
}
pub fn clear_scalar(
section: &str,
key: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> Result<WriteSpec, String> {
let label = format!("clear {section}.{key}");
let verbs = match field_route(section, key) {
FieldRoute::SetBlankClears(flag) => {
vec![WriteVerb::Cli(vec![Arg::p(flag), Arg::p("")])]
}
FieldRoute::Set(_) | FieldRoute::Rmw => vec![WriteVerb::Rmw(RmwOp::ClearField {
section: section.into(),
key: key.into(),
})],
other => {
return Err(format!(
"{section}.{key} routes to {other:?} — use its editor"
))
}
};
Ok(WriteSpec {
label,
verbs,
expects: vec![Expect::Cleared {
path: path2(section, key),
}],
base_stamp: base,
form_id,
})
}
pub fn set_global_default(
provider: &str,
model: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("set global default = {provider}/{model} (+ route input.text)"),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("--set-global-default"),
Arg::p(format!("{provider}/{model}")),
])],
expects: vec![
Expect::Eq {
path: path2("default_models", "global_provider"),
value: Value::String(provider.into()),
},
Expect::Eq {
path: path2("default_models", "global_model"),
value: Value::String(model.into()),
},
Expect::RouteEq {
key: "input.text".into(),
provider: Some(provider.into()),
model: Some(model.into()),
reasoning: None,
},
],
base_stamp: base,
form_id,
}
}
pub fn clear_global_default(
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: "clear global default (+ route input.text)".into(),
verbs: vec![
WriteVerb::Cli(vec![
Arg::p("config"),
Arg::p("clear-default"),
Arg::p("input.text"),
]),
WriteVerb::Rmw(RmwOp::ClearGlobalDefaultFields),
],
expects: vec![
Expect::Cleared {
path: path2("default_models", "global_provider"),
},
Expect::Cleared {
path: path2("default_models", "global_model"),
},
Expect::RouteCleared {
key: "input.text".into(),
},
],
base_stamp: base,
form_id,
}
}
pub fn set_app_default(
app: &str,
provider: &str,
model: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("set app default {app} = {provider}/{model}"),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("--set-app-default"),
Arg::p(app),
Arg::p(provider),
Arg::p(model),
])],
expects: vec![
Expect::Eq {
path: path2("app_defaults", &format!("{app}_provider")),
value: Value::String(provider.into()),
},
Expect::Eq {
path: path2("app_defaults", &format!("{app}_model")),
value: Value::String(model.into()),
},
],
base_stamp: base,
form_id,
}
}
pub fn set_embeddings(
provider: &str,
model: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("set embeddings = {provider}/{model} (+ route embedding.text)"),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("--set-embeddings-model"),
Arg::p(format!("{provider}/{model}")),
])],
expects: vec![
Expect::Eq {
path: path2("embeddings", "provider"),
value: Value::String(provider.into()),
},
Expect::Eq {
path: path2("embeddings", "model"),
value: Value::String(model.into()),
},
Expect::RouteEq {
key: "embedding.text".into(),
provider: Some(provider.into()),
model: Some(model.into()),
reasoning: None,
},
],
base_stamp: base,
form_id,
}
}
pub fn set_vision_pair(
provider: &str,
model: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("set vision fallback = {provider}/{model} (strategy two_stage)"),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("--set-vision-provider"),
Arg::p(provider),
Arg::p(model),
])],
expects: vec![
Expect::Eq {
path: path2("vision", "strategy"),
value: Value::String("two_stage".into()),
},
Expect::Eq {
path: path2("vision", "caption_provider"),
value: Value::String(provider.into()),
},
Expect::Eq {
path: path2("vision", "caption_model"),
value: Value::String(model.into()),
},
],
base_stamp: base,
form_id,
}
}
pub fn set_vision_strategy(
strategy: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> Result<WriteSpec, String> {
let (label, verbs, expects) = match strategy {
"disabled" => (
"set vision.strategy = disabled (clears caption pair + fallback chain)".to_string(),
vec![WriteVerb::Cli(vec![Arg::p("--disable-vision")])],
vec![
Expect::Eq {
path: path2("vision", "strategy"),
value: Value::String("disabled".into()),
},
Expect::Cleared {
path: path2("vision", "caption_provider"),
},
Expect::Cleared {
path: path2("vision", "caption_model"),
},
Expect::Eq {
path: path2("vision", "fallback_chain"),
value: Value::Array(Vec::new()),
},
],
),
"basic_metadata" => (
"set vision.strategy = basic_metadata".to_string(),
vec![WriteVerb::Rmw(RmwOp::SetField {
section: "vision".into(),
key: "strategy".into(),
value: Value::String("basic_metadata".into()),
})],
vec![Expect::Eq {
path: path2("vision", "strategy"),
value: Value::String("basic_metadata".into()),
}],
),
"two_stage" => {
return Err(
"two_stage needs a caption provider/model — use the vision pair editor".into(),
)
}
other => return Err(format!("unknown vision strategy {other:?}")),
};
Ok(WriteSpec {
label,
verbs,
expects,
base_stamp: base,
form_id,
})
}
pub fn reset_audio_strategy(
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: "reset audio.strategy (clears the explicit flag — smart default applies again)"
.into(),
verbs: vec![WriteVerb::Rmw(RmwOp::ResetAudioStrategy)],
expects: vec![
Expect::Cleared {
path: path2("audio", "strategy"),
},
Expect::Cleared {
path: vec![crate::schema::META_FLAG.to_string()],
},
],
base_stamp: base,
form_id,
}
}
pub fn add_vision_fallback(
provider: &str,
model: &str,
new_len: usize,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("add vision fallback {provider}/{model}"),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("--add-vision-fallback"),
Arg::p(provider),
Arg::p(model),
])],
expects: vec![Expect::Eq {
path: vec![
"vision".into(),
"fallback_chain".into(),
(new_len - 1).to_string(),
"provider".into(),
],
value: Value::String(provider.into()),
}],
base_stamp: base,
form_id,
}
}
pub fn remove_vision_fallback(
index: usize,
old_len: usize,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("remove vision fallback entry {index}"),
verbs: vec![WriteVerb::Rmw(RmwOp::RemoveFallbackEntry {
section: "vision".into(),
index,
})],
expects: vec![if old_len <= 1 {
Expect::Cleared {
path: vec![
"vision".into(),
"fallback_chain".into(),
"0".into(),
"provider".into(),
],
}
} else {
Expect::Cleared {
path: vec![
"vision".into(),
"fallback_chain".into(),
(old_len - 1).to_string(),
"provider".into(),
],
}
}],
base_stamp: base,
form_id,
}
}
pub fn set_api_key(
name: &str,
key: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("set API key {name}"),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("--set-api-key"),
Arg::p(name),
Arg::Secret(key.to_string()),
])],
expects: vec![Expect::SecretFp {
path: path2("api_keys", name),
fp: fingerprint(key),
}],
base_stamp: base,
form_id,
}
}
pub fn clear_api_key(
name: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("clear API key {name}"),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("--set-api-key"),
Arg::p(name),
Arg::p(""),
])],
expects: vec![Expect::Cleared {
path: path2("api_keys", name),
}],
base_stamp: base,
form_id,
}
}
pub fn set_server_auth_token(
token: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: "set server auth token".into(),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("--set-server-auth-token"),
Arg::Secret(token.to_string()),
])],
expects: vec![Expect::SecretFp {
path: path2("server", "auth_token"),
fp: fingerprint(token),
}],
base_stamp: base,
form_id,
}
}
pub fn clear_server_auth_token(
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: "clear server auth token".into(),
verbs: vec![WriteVerb::Cli(vec![Arg::p("--clear-server-auth-token")])],
expects: vec![Expect::Cleared {
path: path2("server", "auth_token"),
}],
base_stamp: base,
form_id,
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RouteEdit {
pub provider: Option<String>,
pub model: Option<String>,
pub base_url: Option<String>,
pub reasoning: Option<String>,
pub options: Option<Vec<(String, String)>>,
}
impl RouteEdit {
pub fn is_empty(&self) -> bool {
self.provider.is_none()
&& self.model.is_none()
&& self.base_url.is_none()
&& self.reasoning.is_none()
&& self.options.is_none()
}
}
pub fn set_route(
key: &str,
edit: &RouteEdit,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
let mut args = vec![Arg::p("config"), Arg::p("set-default"), Arg::p(key)];
for (flag, value) in [
("--provider", edit.provider.as_deref()),
("--model", edit.model.as_deref()),
("--base-url", edit.base_url.as_deref()),
("--reasoning", edit.reasoning.as_deref()),
] {
if let Some(v) = value {
args.push(Arg::p(flag));
args.push(Arg::p(v));
}
}
match edit.options.as_deref() {
None => {}
Some([]) => {
args.push(Arg::p("--option"));
args.push(Arg::p(""));
}
Some(pairs) => {
for (k, v) in pairs {
args.push(Arg::p("--option"));
args.push(Arg::p(format!("{k}={v}")));
}
}
}
let mut changed: Vec<&str> = Vec::new();
for (name, set) in [
("provider", edit.provider.is_some()),
("model", edit.model.is_some()),
("base URL", edit.base_url.is_some()),
("reasoning", edit.reasoning.is_some()),
("options", edit.options.is_some()),
] {
if set {
changed.push(name);
}
}
WriteSpec {
label: format!("set route {key} ({})", changed.join(", ")),
verbs: vec![WriteVerb::Cli(args)],
expects: vec![Expect::RouteEq {
key: key.to_string(),
provider: edit.provider.clone(),
model: edit.model.clone(),
reasoning: edit.reasoning.clone(),
}],
base_stamp: base,
form_id,
}
}
pub fn apply_recommended(
force: bool,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
let mut args = vec![Arg::p("config"), Arg::p("apply-recommended")];
if force {
args.push(Arg::p("--force"));
}
args.push(Arg::p("--json"));
WriteSpec {
label: if force {
"apply recommended routes (replacing yours)".into()
} else {
"apply recommended routes (keeping yours)".into()
},
verbs: vec![WriteVerb::ApplyRecommended(args)],
expects: vec![],
base_stamp: base,
form_id,
}
}
pub fn apply_report_lines(doc: &Value) -> Result<Vec<String>, String> {
if doc.get("ok").and_then(Value::as_bool) != Some(true) {
return Err(format!(
"apply-recommended did not report success: {}",
doc.get("error")
.and_then(Value::as_str)
.unwrap_or("no `ok: true` in its report")
));
}
let rows = doc
.get("routes")
.and_then(Value::as_array)
.ok_or("apply-recommended answered without its `routes` report")?;
let pair = |v: Option<&Value>| -> String {
let f = |k: &str| {
v.and_then(|v| v.get(k))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
};
match (f("provider"), f("model")) {
(None, None) => "unset".to_string(),
(p, m) => format!("{} · {}", p.unwrap_or("?"), m.unwrap_or("?")),
}
};
let mut out = Vec::new();
let totals: Vec<String> = ["changed", "cleared", "kept", "already", "unavailable"]
.iter()
.filter_map(|k| {
doc.get(*k)
.and_then(Value::as_u64)
.filter(|n| *n > 0)
.map(|n| format!("{n} {k}"))
})
.collect();
if !totals.is_empty() {
out.push(totals.join(" · "));
}
for r in rows {
let key = r.get("key").and_then(Value::as_str).unwrap_or("?");
let action = r.get("action").and_then(Value::as_str).unwrap_or("?");
let reason = r
.get("reason")
.and_then(Value::as_str)
.unwrap_or("no reason given");
let cannot_run = r
.get("route_unavailable")
.and_then(|u| u.get("reason"))
.and_then(Value::as_str)
.map(|why| format!(" — yours cannot run on this computer: {why}"))
.unwrap_or_default();
let engine = crate::store::EngineMissing::from_value(r.get("engine_missing"))
.map(|m| match m.install {
Some(cmd) => format!(" — {} is not installed here: {cmd}", m.name),
None => format!(" — {}", m.reason),
})
.unwrap_or_default();
let cannot_run = format!("{cannot_run}{engine}");
let line = match action {
"apply" => format!("{key}: applied {}{cannot_run}", pair(r.get("after"))),
"overwrite" => format!(
"{key}: replaced {} with {}{cannot_run}",
pair(r.get("before")),
pair(r.get("after"))
),
"already" => format!("{key}: already {}{cannot_run}", pair(r.get("after"))),
"kept" => format!(
"{key}: kept yours {} (recommended {}){cannot_run}",
pair(r.get("before")),
pair(r.get("recommended"))
),
"cleared" => format!(
"{key}: removed {}{cannot_run}; nothing recommended runs here either — {reason}",
pair(r.get("before"))
),
"unavailable" => {
let before = pair(r.get("before"));
let left = if before == "unset" {
"left unset".to_string()
} else {
format!("left as {before}")
};
format!(
"{key}: nothing recommended runs on this computer — {reason}; {left}{cannot_run}"
)
}
other => format!("{key}: {other} {}", pair(r.get("after"))),
};
out.push(line);
}
Ok(out)
}
pub fn clear_route(
key: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("clear route {key}"),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("config"),
Arg::p("clear-default"),
Arg::p(key),
])],
expects: vec![Expect::RouteCleared {
key: key.to_string(),
}],
base_stamp: base,
form_id,
}
}
#[allow(clippy::too_many_arguments)]
pub fn save_profile(
id: &str,
family: &str,
base_url: &str,
api_key: Option<&str>,
clear_key: bool,
display_name: &str,
description: &str,
enabled: bool,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
let mut args = vec![
Arg::p("config"),
Arg::p("set-provider"),
Arg::p(id),
Arg::p("--family"),
Arg::p(family),
];
if !base_url.is_empty() {
args.push(Arg::p("--base-url"));
args.push(Arg::p(base_url));
}
if let Some(k) = api_key {
args.push(Arg::p("--api-key"));
args.push(Arg::Secret(k.to_string()));
} else if clear_key {
args.push(Arg::p("--clear-api-key"));
}
if !display_name.is_empty() {
args.push(Arg::p("--name"));
args.push(Arg::p(display_name));
}
if !description.is_empty() {
args.push(Arg::p("--description"));
args.push(Arg::p(description));
}
args.push(Arg::p(if enabled { "--enabled" } else { "--disabled" }));
WriteSpec {
label: format!("save provider profile {id}"),
verbs: vec![WriteVerb::Cli(args)],
expects: vec![Expect::ProfileExists { id: id.to_string() }],
base_stamp: base,
form_id,
}
}
pub fn delete_profile(
id: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("delete provider profile {id}"),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("config"),
Arg::p("delete-provider"),
Arg::p(id),
])],
expects: vec![Expect::ProfileAbsent { id: id.to_string() }],
base_stamp: base,
form_id,
}
}
pub fn set_audio_strategy(
strategy: &str,
base: Option<crate::config::FileStamp>,
form_id: Option<u64>,
) -> WriteSpec {
WriteSpec {
label: format!("set audio.strategy = {strategy} (marks it explicit)"),
verbs: vec![WriteVerb::Cli(vec![
Arg::p("--set-audio-strategy"),
Arg::p(strategy),
])],
expects: vec![
Expect::Eq {
path: path2("audio", "strategy"),
value: Value::String(strategy.into()),
},
Expect::Eq {
path: vec!["audio_strategy_explicit".into()],
value: Value::Bool(true),
},
],
base_stamp: base,
form_id,
}
}
#[cfg(test)]
mod apply_report_tests {
use super::*;
use serde_json::json;
#[test]
fn apply_report_says_which_engine_still_needs_installing() {
let doc = json!({"ok": true, "routes": [
{"key": "output.voice", "action": "apply", "before": {},
"after": {"provider": "supertonic", "model": "supertonic-3"},
"engine_missing": {"engine": "supertonic", "name": "Supertonic",
"reason": "Supertonic is not installed.",
"install": "pip install \"abstractvoice[supertonic]\""}},
{"key": "output.image", "action": "already", "before": {},
"after": {"provider": "mlx-gen", "model": "flux"},
"engine_missing": {"engine": "voxtral", "name": "voxtral",
"reason": "unknown AbstractVoice engine 'voxtral'", "install": null}},
]});
assert_eq!(
apply_report_lines(&doc).unwrap(),
vec![
"output.voice: applied supertonic · supertonic-3 — Supertonic is not installed here: pip install \"abstractvoice[supertonic]\"",
"output.image: already mlx-gen · flux — unknown AbstractVoice engine 'voxtral'",
]
);
}
#[test]
fn apply_report_names_every_route_including_what_cannot_run_here() {
let doc = json!({"ok": true, "routes": [
{"key": "input.text", "action": "apply",
"before": {}, "after": {"provider": "lmstudio", "model": "qwen/qwen3.5-9b"}},
{"key": "output.voice", "action": "kept",
"before": {"provider": "openai", "model": "tts-1"},
"recommended": {"provider": "supertonic", "model": "supertonic-3"}},
{"key": "output.image", "action": "unavailable",
"before": {}, "reason": "MLX-Gen needs Apple silicon"},
{"key": "output.video", "action": "unavailable",
"before": {"provider": "mlx-gen", "model": "wan"}, "reason": "needs 58 GiB"},
]});
let lines = apply_report_lines(&doc).unwrap();
assert_eq!(
lines,
vec![
"input.text: applied lmstudio · qwen/qwen3.5-9b",
"output.voice: kept yours openai · tts-1 (recommended supertonic · supertonic-3)",
"output.image: nothing recommended runs on this computer — MLX-Gen needs Apple silicon; left unset",
"output.video: nothing recommended runs on this computer — needs 58 GiB; left as mlx-gen · wan",
]
);
let doc = json!({"ok": true, "changed": 1, "cleared": 1, "kept": 1, "already": 0,
"routes": [
{"key": "output.image", "action": "cleared",
"before": {"provider": "mlx-gen", "model": "flux"}, "after": {},
"reason": "MLX-Gen needs Apple silicon",
"route_unavailable": {"provider": "mlx-gen", "model": "flux", "reason": "needs Apple silicon"}},
{"key": "output.voice", "action": "kept",
"before": {"provider": "supertonic", "model": "s3"},
"recommended": {"provider": "piper", "model": "p"},
"route_unavailable": {"provider": "supertonic", "model": "s3", "reason": "no arm64 wheel"}},
]});
assert_eq!(
apply_report_lines(&doc).unwrap(),
vec![
"1 changed · 1 cleared · 1 kept",
"output.image: removed mlx-gen · flux — yours cannot run on this computer: needs \
Apple silicon; nothing recommended runs here either — MLX-Gen needs Apple silicon",
"output.voice: kept yours supertonic · s3 (recommended piper · p) — yours cannot run \
on this computer: no arm64 wheel",
]
);
assert!(apply_report_lines(&json!({"ok": false, "error": "boom"}))
.unwrap_err()
.contains("boom"));
assert!(apply_report_lines(&json!({"ok": true})).is_err());
}
#[test]
fn apply_recommended_asks_for_the_json_report() {
for force in [false, true] {
let spec = apply_recommended(force, None, None);
let [WriteVerb::ApplyRecommended(args)] = spec.verbs.as_slice() else {
panic!("{:?}", spec.verbs)
};
let argv: Vec<&str> = args.iter().map(Arg::value).collect();
assert_eq!(argv.last(), Some(&"--json"), "{argv:?}");
assert_eq!(argv.contains(&"--force"), force, "{argv:?}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn secrets_redact_in_debug_everywhere() {
let spec = set_api_key("openai", "sk-very-secret", None, Some(1));
let dbg = format!("{spec:?}");
assert!(!dbg.contains("sk-very-secret"), "{dbg}");
assert!(dbg.contains("«redacted»"));
let spec = save_profile(
"x",
"openai",
"https://x/v1",
Some("sk-other-secret"),
false,
"",
"",
true,
None,
None,
);
let dbg = format!("{spec:?}");
assert!(!dbg.contains("sk-other-secret"), "{dbg}");
}
#[test]
fn rmw_ops_mutate_and_preserve() {
let mut raw = json!({
"future_section": {"keep": true},
"logging": {"verbatim_enabled": true, "unknown_knob": 7},
"vision": {"fallback_chain": [
{"provider": "a", "model": "m1"},
{"provider": "b", "model": "m2"}
]},
"default_models": {"global_provider": "x", "global_model": "y"}
});
RmwOp::SetField {
section: "logging".into(),
key: "verbatim_enabled".into(),
value: json!(false),
}
.apply(&mut raw)
.unwrap();
RmwOp::RemoveFallbackEntry {
section: "vision".into(),
index: 0,
}
.apply(&mut raw)
.unwrap();
RmwOp::ClearGlobalDefaultFields.apply(&mut raw).unwrap();
RmwOp::SetField {
section: "offline".into(),
key: "allow_network".into(),
value: json!(true),
}
.apply(&mut raw)
.unwrap();
assert_eq!(raw["logging"]["verbatim_enabled"], json!(false));
assert_eq!(raw["logging"]["unknown_knob"], json!(7), "unknown key kept");
assert_eq!(
raw["future_section"]["keep"],
json!(true),
"unknown section kept"
);
assert_eq!(raw["vision"]["fallback_chain"].as_array().unwrap().len(), 1);
assert_eq!(raw["vision"]["fallback_chain"][0]["provider"], json!("b"));
assert_eq!(raw["default_models"]["global_provider"], Value::Null);
assert_eq!(
raw["offline"]["allow_network"],
json!(true),
"absent section created"
);
let err = RmwOp::RemoveFallbackEntry {
section: "vision".into(),
index: 9,
}
.apply(&mut raw)
.unwrap_err();
assert!(err.contains("no longer exists"), "{err}");
}
#[test]
fn file_expects_evaluate_and_redact() {
let raw = json!({
"video": {"max_frames": 5},
"api_keys": {"openai": "sk-live-secret"},
"audio": {"stt_language": null}
});
assert!(eval_file_expect(
&raw,
&Expect::Eq {
path: vec!["video".into(), "max_frames".into()],
value: json!(5)
}
)
.is_ok());
let err = eval_file_expect(
&raw,
&Expect::Eq {
path: vec!["video".into(), "max_frames".into()],
value: json!(9),
},
)
.unwrap_err();
assert!(err.contains("is 5"), "{err}");
assert!(eval_file_expect(
&raw,
&Expect::Cleared {
path: vec!["audio".into(), "stt_language".into()]
}
)
.is_ok());
assert!(eval_file_expect(
&raw,
&Expect::Cleared {
path: vec!["audio".into(), "never_there".into()]
}
)
.is_ok());
let err = eval_file_expect(
&raw,
&Expect::Cleared {
path: vec!["api_keys".into(), "openai".into()],
},
)
.unwrap_err();
assert!(!err.contains("sk-live-secret"), "{err}");
assert!(err.contains("«redacted»"), "{err}");
let ok = eval_file_expect(
&raw,
&Expect::SecretFp {
path: vec!["api_keys".into(), "openai".into()],
fp: fingerprint("sk-live-secret"),
},
)
.unwrap();
assert!(!ok.contains("sk-live-secret"), "{ok}");
}
#[test]
fn every_schema_field_has_a_route() {
for section in crate::schema::SECTIONS {
for fs in section.fields {
let route = field_route(section.name, fs.key);
match fs.kind {
crate::schema::FieldKind::Secret => {
assert_eq!(
route,
FieldRoute::Secret,
"{}.{} must route to the masked editor",
section.name,
fs.key
);
}
_ => {
}
}
}
}
assert_eq!(
field_route("default_models", "chat_model"),
FieldRoute::Set("--set-chat-model")
);
assert_eq!(field_route("offline", "allow_network"), FieldRoute::Rmw);
assert_eq!(field_route("email", "smtp_host"), FieldRoute::Rmw);
}
#[test]
fn expect_paths_walk_arrays() {
let raw = json!({"vision": {"fallback_chain": [
{"provider": "a", "model": "m1"},
{"provider": "b", "model": "m2"}
]}});
let ok = eval_file_expect(
&raw,
&Expect::Eq {
path: vec![
"vision".into(),
"fallback_chain".into(),
"1".into(),
"provider".into(),
],
value: json!("b"),
},
)
.unwrap();
assert!(ok.contains("fallback_chain.1.provider"), "{ok}");
assert!(eval_file_expect(
&raw,
&Expect::Eq {
path: vec![
"vision".into(),
"fallback_chain".into(),
"9".into(),
"provider".into()
],
value: json!("x"),
},
)
.is_err());
assert!(eval_file_expect(
&raw,
&Expect::Cleared {
path: vec![
"vision".into(),
"fallback_chain".into(),
"0".into(),
"provider".into()
],
},
)
.is_err());
}
#[test]
fn reset_audio_strategy_clears_value_and_both_flag_spellings() {
let mut raw = json!({
"audio_strategy_explicit": true,
"audio": {"strategy": "speech_to_text", "strategy_explicit": true,
"stt_language": "fr"},
});
RmwOp::ResetAudioStrategy.apply(&mut raw).unwrap();
assert!(raw.get("audio_strategy_explicit").is_none());
assert!(raw["audio"].get("strategy").is_none());
assert!(raw["audio"].get("strategy_explicit").is_none());
assert_eq!(raw["audio"]["stt_language"], json!("fr"), "siblings kept");
let spec = reset_audio_strategy(None, None);
assert!(matches!(
spec.verbs[0],
WriteVerb::Rmw(RmwOp::ResetAudioStrategy)
));
assert!(spec
.expects
.iter()
.any(|e| matches!(e, Expect::Cleared { path } if path == &vec!["audio_strategy_explicit".to_string()])));
}
#[test]
fn disable_vision_spec_verifies_the_wipe() {
let spec = set_vision_strategy("disabled", None, None).unwrap();
assert!(spec.label.contains("clears caption pair + fallback chain"));
let has = |p: &[&str]| {
spec.expects.iter().any(|e| match e {
Expect::Cleared { path } => path.iter().map(String::as_str).eq(p.iter().copied()),
_ => false,
})
};
assert!(has(&["vision", "caption_provider"]));
assert!(has(&["vision", "caption_model"]));
assert!(spec.expects.iter().any(|e| matches!(
e,
Expect::Eq { path, value } if path[1] == "fallback_chain" && value == &json!([])
)));
}
#[test]
fn coupled_specs_carry_their_couplings() {
let g = set_global_default("lmstudio", "m", None, None);
assert!(g.needs_routes(), "global default verifies route input.text");
let e = set_embeddings("ollama", "nomic", None, None);
assert!(e.needs_routes());
let a = set_audio_strategy("speech_to_text", None, None);
assert!(a
.expects
.iter()
.any(|x| matches!(x, Expect::Eq { path, .. } if path == &vec!["audio_strategy_explicit".to_string()])));
let c = clear_global_default(None, None);
assert_eq!(c.verbs.len(), 2, "RMW fields + CLI route clear");
}
#[test]
fn set_route_sends_only_the_edited_fields() {
let args = |spec: &WriteSpec| -> Vec<String> {
match &spec.verbs[0] {
WriteVerb::Cli(a) => a.iter().map(|x| x.value().to_string()).collect(),
other => panic!("expected a CLI verb, got {other:?}"),
}
};
let only_reasoning = set_route(
"input.text",
&RouteEdit {
reasoning: Some("high".into()),
..RouteEdit::default()
},
None,
None,
);
assert_eq!(
args(&only_reasoning),
vec!["config", "set-default", "input.text", "--reasoning", "high"]
);
assert!(
only_reasoning.label.contains("reasoning"),
"{}",
only_reasoning.label
);
assert_eq!(
only_reasoning.expects,
vec![Expect::RouteEq {
key: "input.text".into(),
provider: None,
model: None,
reasoning: Some("high".into()),
}],
"a partial write verifies exactly what it named"
);
let cleared = set_route(
"output.voice",
&RouteEdit {
base_url: Some(String::new()),
reasoning: Some(String::new()),
..RouteEdit::default()
},
None,
None,
);
assert_eq!(
args(&cleared),
vec![
"config",
"set-default",
"output.voice",
"--base-url",
"",
"--reasoning",
""
]
);
let untouched = set_route("output.voice", &RouteEdit::default(), None, None);
assert!(
!args(&untouched).contains(&"--option".to_string()),
"no --option when the operator never touched the options"
);
let cleared_opts = set_route(
"output.voice",
&RouteEdit {
options: Some(Vec::new()),
..RouteEdit::default()
},
None,
None,
);
assert_eq!(
args(&cleared_opts),
vec!["config", "set-default", "output.voice", "--option", ""]
);
let replaced = set_route(
"output.voice",
&RouteEdit {
provider: Some("supertonic".into()),
options: Some(vec![
("voice".into(), "M2".into()),
("speed".into(), "1.2".into()),
]),
..RouteEdit::default()
},
None,
None,
);
assert_eq!(
args(&replaced),
vec![
"config",
"set-default",
"output.voice",
"--provider",
"supertonic",
"--option",
"voice=M2",
"--option",
"speed=1.2"
]
);
assert!(RouteEdit::default().is_empty());
assert!(!RouteEdit {
model: Some(String::new()),
..RouteEdit::default()
}
.is_empty());
}
}