use crate::source::{Origin, Stop, open_recipe};
use serde_json::{Value, json};
use std::fmt::Write as _;
use tessera_frontend::recipe::{Host, Recipe, Resolved, Selection};
use tessera_frontend::tasks::Error;
use tessera_frontend::tasks::task::{Run, Sink, Task};
const GIB: f64 = (1u64 << 30) as f64;
#[derive(Task)]
#[task(name = "recipe")]
pub(crate) struct RecipeCmd {
pub json: bool,
pub list: bool,
#[arg(value = "<name>")]
pub backend: Option<String>,
#[arg(value = "<arch>")]
pub arch: Option<String>,
#[arg(value = "<name>")]
pub device: Option<String>,
#[arg(value = "<n>")]
pub gpus: Option<u32>,
#[arg(value = "<gb>")]
pub vram_gib: Option<f64>,
#[arg(value = "<gb>")]
pub host_gib: Option<f64>,
#[arg(value = "<bool>")]
pub integrated: Option<bool>,
}
fn build_host(args: &RecipeCmd) -> Host {
let settings = tessera_frontend::frontend_settings::read();
let specs = crate::size::specs(&settings);
let mut host = crate::size::host(&specs, args.gpus);
if let Some(b) = &args.backend {
host.backend = b.clone();
}
if let Some(a) = &args.arch {
host.arch = a.clone();
}
if let Some(d) = &args.device {
host.device = d.clone();
}
if let Some(g) = args.gpus {
host.gpus = g;
}
if let Some(v) = args.vram_gib {
host.vram_bytes = (v.max(0.0) * GIB).round() as u64;
}
if let Some(h) = args.host_gib {
host.host_bytes = (h.max(0.0) * GIB).round() as u64;
}
if let Some(i) = args.integrated {
host.integrated = i;
}
host
}
impl Run<Option<Origin>> for RecipeCmd {
fn run(self, origin: Option<Origin>, sink: &mut dyn Sink) -> Result<(), Error> {
let origin = origin.ok_or_else(|| Stop::Failed("recipe requires --recipe <src>".into()))?;
let (raw, explicit) = open_recipe(&origin)?;
let raw = raw.ok_or_else(|| Stop::Failed("recipe requires --recipe <src>".into()))?;
let host = build_host(&self);
let text = render(&raw, explicit.as_deref(), &host, self.list, self.json)?;
sink.text(&text);
Ok(())
}
}
crate::task::register!(RecipeCmd, crate::task::OnOrigin<false>, "", false);
pub(crate) fn render(
raw: &Recipe,
explicit: Option<&str>,
host: &Host,
list: bool,
as_json: bool,
) -> Result<String, Stop> {
if list {
return Ok(render_list(raw, explicit, host, as_json));
}
let resolved = raw.resolve_profile(explicit, Some(host))?;
if as_json {
let out = effective_json(raw, &resolved, host)?;
return Ok(format!(
"{}\n",
serde_json::to_string_pretty(&out).map_err(|e| Stop::Failed(e.to_string()))?
));
}
render_toml(&resolved)
}
fn render_toml(resolved: &Resolved) -> Result<String, Stop> {
let mut out = String::new();
let sel = match resolved.selection {
Selection::Base => "base",
Selection::Explicit => "explicit",
Selection::Auto => "auto",
Selection::Default => "default",
};
match &resolved.profile {
Some(name) => {
let _ = writeln!(out, "# profile: {name} ({sel})");
}
None => {
let _ = writeln!(out, "# profile: none ({sel})");
}
}
if resolved.filter.is_some() {
if resolved.mismatches.is_empty() {
let _ = writeln!(out, "# filter: matched");
} else {
let _ = writeln!(
out,
"# filter: MISMATCH ({})",
resolved.mismatches.join("; ")
);
}
}
out.push_str(&resolved.recipe.effective_toml()?);
Ok(out)
}
fn effective_json(raw: &Recipe, resolved: &Resolved, host: &Host) -> Result<Value, Stop> {
let r = &resolved.recipe;
let flags: Vec<String> = r
.flags()
.into_iter()
.flat_map(|(k, v)| match v {
Some(val) => vec![k, val],
None => vec![k],
})
.collect();
let lower = match &r.lower {
Some(l) => serde_json::to_value(l).map_err(|e| Stop::Failed(e.to_string()))?,
None => Value::Null,
};
let serve = serde_json::to_value(&r.serve).map_err(|e| Stop::Failed(e.to_string()))?;
let config = serde_json::to_value(&r.config).map_err(|e| Stop::Failed(e.to_string()))?;
let profiles = profile_entries(raw, resolved.profile.as_deref(), host);
Ok(json!({
"name": r.name,
"about": r.about,
"profile": resolved.profile,
"selection": resolved.selection,
"filter": resolved.filter,
"filter_matches": resolved.mismatches.is_empty(),
"filter_mismatches": resolved.mismatches,
"host": {
"backend": host.backend,
"arch": host.arch,
"device": host.device,
"gpus": host.gpus,
"vram_gib": (host.vram_gib() * 10.0).round() / 10.0,
"host_gib": (host.host_gib() * 10.0).round() / 10.0,
"integrated": host.integrated,
},
"weights": {
"path": r.weights.path,
"hf": r.weights.hf,
"extra": r.weights.extra,
"width": r.weights.width,
},
"names": r.names,
"module": r.module,
"script": r.script,
"lower": lower,
"serve": serve,
"flags": flags,
"config": config,
"profiles": profiles,
}))
}
fn profile_entries(raw: &Recipe, selected: Option<&str>, host: &Host) -> Vec<Value> {
raw.profile
.iter()
.map(|(name, prof)| {
let mismatches = prof
.filter
.as_ref()
.map(|f| f.mismatches(host))
.unwrap_or_default();
json!({
"name": name,
"about": prof.about,
"filter": prof.filter,
"matches": mismatches.is_empty(),
"mismatches": mismatches,
"selected": selected == Some(name.as_str()),
})
})
.collect()
}
fn render_list(raw: &Recipe, explicit: Option<&str>, host: &Host, as_json: bool) -> String {
let selected = raw
.resolve_profile(explicit, Some(host))
.ok()
.and_then(|r| r.profile);
if as_json {
let out = json!({
"name": raw.name,
"about": raw.about,
"default_profile": raw.default_profile,
"selected": selected,
"profiles": profile_entries(raw, selected.as_deref(), host),
});
return format!(
"{}\n",
serde_json::to_string_pretty(&out).unwrap_or_default()
);
}
let mut out = String::new();
let _ = writeln!(out, "recipe: {}", raw.name);
if let Some(def) = &raw.default_profile {
let _ = writeln!(out, "default_profile: {def}");
}
if raw.profile.is_empty() {
let _ = writeln!(out, "profiles: (none)");
return out;
}
for (name, prof) in &raw.profile {
let mark = if selected.as_deref() == Some(name.as_str()) {
"*"
} else {
" "
};
let status = match &prof.filter {
None => "no filter".to_string(),
Some(f) => {
let miss = f.mismatches(host);
if miss.is_empty() {
"match".to_string()
} else {
format!("no match: {}", miss.join("; "))
}
}
};
let about = prof.about.as_deref().unwrap_or("");
if about.is_empty() {
let _ = writeln!(out, "{mark} {name} [{status}]");
} else {
let _ = writeln!(out, "{mark} {name} [{status}] — {about}");
}
}
out
}