use std::collections::HashMap;
use std::time::Instant;
use abstracttui::prelude::*;
use serde_json::Value;
use crate::cli::{CliError, CliInfo};
use crate::config::{ConfigPath, FileState};
#[derive(Clone, Debug, Default)]
pub enum Loadable<T> {
#[default]
NotAsked,
Loading,
Ready(T),
Failed(CliError),
}
impl<T> Loadable<T> {
pub fn ready(&self) -> Option<&T> {
match self {
Loadable::Ready(t) => Some(t),
_ => None,
}
}
}
fn s(v: &Value, key: &str) -> Option<String> {
v.get(key).and_then(Value::as_str).map(str::to_string)
}
fn b(v: &Value, key: &str) -> Option<bool> {
v.get(key).and_then(Value::as_bool)
}
#[derive(Clone, Debug)]
pub struct ConfigMirror {
pub path: ConfigPath,
pub state: FileState,
pub loaded_at: String,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct RouteRow {
pub key: String,
pub kind: String,
pub modality: String,
pub label: String,
pub configured: bool,
pub source: String,
pub provider: Option<String>,
pub model: Option<String>,
pub base_url: Option<String>,
pub options: Option<Value>,
pub covered_by: Option<String>,
pub read_only: bool,
pub overrideable: bool,
pub package_hint: Option<String>,
pub option_examples: Option<Value>,
pub reasoning: Option<String>,
pub derived_from: Option<String>,
pub broad_key: Option<String>,
pub task_keys: Vec<String>,
pub covered_by_tasks: bool,
pub inherits_broad: bool,
pub recommendation_unavailable: Option<RouteUnavailable>,
pub route_unavailable: Option<RouteUnavailable>,
pub engine_missing: Option<EngineMissing>,
}
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct EngineMissing {
pub engine: String,
pub name: String,
pub reason: String,
pub install: Option<String>,
pub engine_row: Option<String>,
}
impl EngineMissing {
pub fn is_unknown_engine(&self) -> bool {
self.install.is_none()
}
pub fn from_value(v: Option<&Value>) -> Option<EngineMissing> {
let v = v.filter(|v| v.is_object())?;
let engine = s(v, "engine").unwrap_or_default();
Some(EngineMissing {
name: s(v, "name").unwrap_or_else(|| engine.clone()),
reason: s(v, "reason").unwrap_or_else(|| "its engine is not installed".into()),
install: s(v, "install").filter(|c| !c.is_empty()),
engine_row: s(v, "engine_row").filter(|r| !r.is_empty()),
engine,
})
}
}
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct RouteUnavailable {
pub provider: Option<String>,
pub model: Option<String>,
pub reason: String,
}
impl RouteUnavailable {
fn from_value(v: Option<&Value>) -> Option<RouteUnavailable> {
let v = v.filter(|v| v.is_object())?;
Some(RouteUnavailable {
provider: s(v, "provider").filter(|p| !p.is_empty()),
model: s(v, "model").filter(|m| !m.is_empty()),
reason: s(v, "reason").unwrap_or_else(|| "no reason given".into()),
})
}
pub fn pair_text(&self) -> String {
match (&self.provider, &self.model) {
(None, None) => String::new(),
(p, m) => format!(
"{} · {}",
p.as_deref().unwrap_or("?"),
m.as_deref().unwrap_or("?")
),
}
}
}
impl RouteRow {
pub fn from_value(v: &Value) -> Option<RouteRow> {
let key = s(v, "key")?;
Some(RouteRow {
kind: s(v, "kind").unwrap_or_default(),
modality: s(v, "modality").unwrap_or_default(),
label: s(v, "label").unwrap_or_else(|| key.clone()),
configured: b(v, "configured").unwrap_or(false),
source: s(v, "source").unwrap_or_default(),
provider: s(v, "provider").filter(|p| !p.is_empty()),
model: s(v, "model").filter(|m| !m.is_empty()),
base_url: s(v, "base_url").filter(|u| !u.is_empty()),
options: v.get("options").filter(|o| !o.is_null()).cloned(),
covered_by: s(v, "covered_by"),
read_only: b(v, "read_only").unwrap_or(false),
overrideable: b(v, "overrideable").unwrap_or(false),
package_hint: s(v, "package_hint"),
option_examples: v.get("option_examples").filter(|o| !o.is_null()).cloned(),
reasoning: s(v, "reasoning").filter(|r| !r.is_empty()),
derived_from: s(v, "derived_from").filter(|d| !d.is_empty()),
broad_key: s(v, "broad_key").filter(|k| !k.is_empty()),
task_keys: v
.get("task_keys")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(|k| k.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default(),
covered_by_tasks: b(v, "covered_by_tasks").unwrap_or(false),
inherits_broad: b(v, "inherits_broad").unwrap_or(false),
recommendation_unavailable: RouteUnavailable::from_value(
v.get("recommendation_unavailable"),
),
route_unavailable: RouteUnavailable::from_value(v.get("route_unavailable")),
engine_missing: EngineMissing::from_value(v.get("engine_missing")),
key,
})
}
pub fn is_task_parent(&self) -> bool {
!self.task_keys.is_empty()
}
pub fn display_key(&self) -> String {
match self.broad_key.as_deref() {
Some(parent) if self.key.len() > parent.len() + 1 => {
format!(" └ {}", &self.key[parent.len() + 1..])
}
_ => self.key.clone(),
}
}
pub fn editable(&self) -> bool {
if self.derived_from.is_some() {
return false;
}
if self.covered_by.is_some() {
return self.overrideable && !self.read_only;
}
!self.read_only
}
pub fn state_label(&self) -> String {
if let Some(from) = self.derived_from.as_deref() {
return format!("derived ← {from}");
}
if let Some(by) = self.covered_by.as_deref() {
return format!("covered by {by}");
}
if self.configured {
if self.route_unavailable.is_some() {
return "cannot run here".to_string();
}
if let Some(m) = &self.engine_missing {
return if m.is_unknown_engine() {
"unknown engine".to_string()
} else {
"engine not installed".to_string()
};
}
return "configured".to_string();
}
if self.covered_by_tasks {
return "not needed".to_string();
}
if self.inherits_broad {
return "inherited".to_string();
}
"not configured".to_string()
}
pub fn is_text_generation(&self) -> bool {
self.key == "output.text" || self.key == "input.text"
}
pub fn pair_text(&self) -> String {
match (self.provider.as_deref(), self.model.as_deref()) {
(None, None) => "—".to_string(),
(p, m) => format!("{} / {}", p.unwrap_or("—"), m.unwrap_or("—")),
}
}
}
pub const REASONING_LEVELS: [&str; 4] = ["minimal", "low", "medium", "high"];
pub fn reasoning_index(stored: Option<&str>) -> usize {
stored
.map(str::trim)
.filter(|r| !r.is_empty())
.and_then(|r| {
REASONING_LEVELS
.iter()
.position(|l| l.eq_ignore_ascii_case(r))
})
.map(|i| i + 1)
.unwrap_or(0)
}
#[derive(Clone, Debug, Default)]
pub struct RoutesData {
pub ok: bool,
pub writable: bool,
pub config_file: Option<String>,
pub rows: Vec<RouteRow>,
pub errors: Vec<String>,
}
impl RoutesData {
pub fn from_value(v: &Value) -> RoutesData {
RoutesData {
ok: b(v, "ok").unwrap_or(false),
writable: b(v, "writable").unwrap_or(false),
config_file: s(v, "config_file"),
rows: v
.get("routes")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(RouteRow::from_value).collect())
.unwrap_or_default(),
errors: v
.get("errors")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.map(|e| {
e.as_str()
.map(str::to_string)
.unwrap_or_else(|| e.to_string())
})
.collect()
})
.unwrap_or_default(),
}
}
pub fn configured_count(&self) -> usize {
self.rows.iter().filter(|r| r.configured).count()
}
}
#[derive(Clone, Debug, Default)]
pub struct WeightsRow {
pub status: String,
pub provider: String,
pub route_provider: Option<String>,
pub artifact: String,
pub detail: String,
pub instruction: String,
pub downloadable: bool,
}
impl WeightsRow {
pub fn label(&self) -> &str {
match self.status.as_str() {
"installed" => "installed",
"absent" => "not downloaded",
"not_applicable" => "remote",
"unknown" => "unknown",
_ => "",
}
}
}
#[derive(Clone, Debug, Default)]
pub struct AvailabilityData {
pub by_route: HashMap<String, WeightsRow>,
pub total: usize,
pub installed: usize,
pub absent: usize,
pub unknown: usize,
pub missing: Vec<(String, String, String)>,
}
impl AvailabilityData {
pub fn from_value(v: &Value) -> AvailabilityData {
let mut by_route = HashMap::new();
for row in v
.get("routes")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let Some(key) = s(row, "key").filter(|k| !k.is_empty()) else {
continue;
};
let a = row.get("availability").cloned().unwrap_or(Value::Null);
let status = s(&a, "status").unwrap_or_default();
if s(&a, "evidence").as_deref() == Some("route not configured") {
continue;
}
by_route.insert(
key,
WeightsRow {
status,
provider: s(row, "download_provider")
.filter(|p| !p.is_empty())
.or_else(|| s(row, "provider"))
.unwrap_or_default(),
route_provider: s(row, "download_provider")
.filter(|p| !p.is_empty())
.and_then(|_| s(row, "provider")),
artifact: s(row, "download_artifact")
.or_else(|| s(&a, "artifact"))
.or_else(|| s(row, "model"))
.unwrap_or_default(),
detail: s(&a, "detail").unwrap_or_default(),
instruction: s(&a, "instruction").unwrap_or_default(),
downloadable: b(&a, "downloadable").unwrap_or(false),
},
);
}
let plan = v.get("recommended").cloned().unwrap_or(Value::Null);
let n = |key: &str| plan.get(key).and_then(Value::as_u64).unwrap_or(0) as usize;
let missing = plan
.get("gaps")
.or_else(|| plan.get("would_download"))
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(|item| {
Some((
s(item, "route").unwrap_or_default(),
s(item, "provider")?,
s(item, "artifact")?,
))
})
.collect()
})
.unwrap_or_default();
AvailabilityData {
by_route,
total: n("total"),
installed: n("installed"),
absent: n("absent"),
unknown: n("unknown"),
missing,
}
}
}
#[derive(Clone, Debug)]
pub struct ProfileRow {
pub id: String,
pub display_name: String,
pub description: String,
pub family: String,
pub base_url: String,
pub api_key_set: bool,
pub api_key_fingerprint: Option<String>,
pub api_key_env_var: Option<String>,
pub allowed_models: Vec<String>,
pub enabled: bool,
}
impl ProfileRow {
pub fn from_value(v: &Value) -> Option<ProfileRow> {
let id = s(v, "id")?;
Some(ProfileRow {
display_name: s(v, "display_name").unwrap_or_else(|| id.clone()),
description: s(v, "description").unwrap_or_default(),
family: s(v, "provider_family").unwrap_or_default(),
base_url: s(v, "base_url").unwrap_or_default(),
api_key_set: b(v, "api_key_set").unwrap_or(false),
api_key_fingerprint: s(v, "api_key_fingerprint").filter(|f| !f.is_empty()),
api_key_env_var: s(v, "api_key_env_var").filter(|e| !e.is_empty()),
allowed_models: v
.get("allowed_models")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(Value::as_str)
.map(str::to_string)
.collect()
})
.unwrap_or_default(),
enabled: b(v, "enabled").unwrap_or(true),
id,
})
}
pub fn virtual_provider(&self) -> String {
format!("endpoint:{}", self.id)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Origin {
Config,
Env,
Auto,
Registry,
}
impl Origin {
pub fn label(self) -> &'static str {
match self {
Origin::Config => "config",
Origin::Env => "env",
Origin::Auto => "auto",
Origin::Registry => "registry",
}
}
}
#[derive(Clone, Debug)]
pub struct ConnectionRow {
pub provider: String,
pub family: String,
pub base_url: String,
pub api_key: String,
pub models: String,
pub enabled: Option<bool>,
pub origin: Origin,
pub origin_env: String,
pub profile: Option<ProfileRow>,
pub api_key_field: String,
pub detail: String,
}
impl ConnectionRow {
fn compose(inv: &ProviderRow, profile: Option<&ProfileRow>) -> ConnectionRow {
let origin = if profile.is_some() {
Origin::Config
} else if inv.api_key_source.starts_with("env:") || inv.base_url_source.starts_with("env:")
{
Origin::Env
} else if inv.api_key_source == "config" {
Origin::Config
} else if inv.reachable == Some(true) {
Origin::Auto
} else {
Origin::Registry
};
let origin_env = match origin {
Origin::Env => inv
.api_key_source
.strip_prefix("env:")
.or_else(|| inv.base_url_source.strip_prefix("env:"))
.unwrap_or_default()
.to_string(),
_ => String::new(),
};
let mut detail = Vec::new();
if inv.reachable == Some(false) && !inv.reachability.is_empty() {
detail.push(inv.reachability.clone());
}
if !inv.note.is_empty() {
detail.push(inv.note.clone());
}
ConnectionRow {
provider: inv.provider.clone(),
family: match profile {
Some(p) if !p.family.is_empty() => p.family.clone(),
Some(_) => "—".into(),
None => inv.provider.clone(),
},
base_url: inv.base_url.clone(),
api_key: key_cell(
inv.api_key_set,
&inv.api_key_source,
&inv.api_key_env_var,
&inv.api_key_fingerprint,
),
models: models_cell(
profile.map(|p| p.allowed_models.len()).unwrap_or(0),
&inv.reachability,
),
enabled: profile.map(|p| p.enabled),
origin,
origin_env,
profile: profile.cloned(),
api_key_field: inv.api_key_field.clone(),
detail: detail.join(" · "),
}
}
fn from_profile(p: &ProfileRow) -> ConnectionRow {
ConnectionRow {
provider: p.virtual_provider(),
family: if p.family.is_empty() {
"—".into()
} else {
p.family.clone()
},
base_url: p.base_url.clone(),
api_key: key_cell(
p.api_key_set,
&match &p.api_key_env_var {
Some(v) => format!("env:{v}"),
None => "profile".to_string(),
},
p.api_key_env_var.as_deref().unwrap_or_default(),
p.api_key_fingerprint.as_deref().unwrap_or_default(),
),
models: models_cell(p.allowed_models.len(), ""),
enabled: Some(p.enabled),
origin: Origin::Config,
origin_env: String::new(),
profile: Some(p.clone()),
api_key_field: String::new(),
detail: String::new(),
}
}
pub fn is_profile(&self) -> bool {
self.profile.is_some()
}
pub fn takes_key(&self) -> bool {
!self.api_key_field.is_empty()
}
pub fn base_url_text(&self) -> String {
if self.base_url.is_empty() {
"—".into()
} else {
self.base_url.clone()
}
}
pub fn enabled_text(&self) -> String {
match self.enabled {
Some(true) => "yes".into(),
Some(false) => "NO".into(),
None => "—".into(),
}
}
pub fn origin_detail(&self) -> String {
let mut parts = vec![match self.origin {
Origin::Config if self.is_profile() => {
"endpoint profile stored in this config".to_string()
}
Origin::Config if self.takes_key() => {
format!(
"key stored in this config (api_keys.{})",
self.api_key_field
)
}
Origin::Config => "stored in this config".to_string(),
Origin::Env => format!("resolved from the environment (${})", self.origin_env),
Origin::Auto if self.base_url.is_empty() => "answering locally".to_string(),
Origin::Auto => format!("a local server answering at {}", self.base_url),
Origin::Registry => "known to the registry — nothing configured yet".to_string(),
}];
if !self.detail.is_empty() {
parts.push(self.detail.clone());
}
parts.join(" · ")
}
}
fn key_cell(set: bool, source: &str, env_var: &str, fingerprint: &str) -> String {
let from_env = source.strip_prefix("env:").filter(|v| !v.is_empty());
if set {
if let Some(var) = from_env {
return format!("stored (${var})");
}
return match fingerprint {
"" => "stored".to_string(),
fp => format!("stored ({fp})"),
};
}
if env_var.is_empty() {
"none".to_string()
} else {
format!("none (${env_var})")
}
}
fn models_cell(allowed: usize, reachability: &str) -> String {
if allowed > 0 {
return format!("{allowed} restr");
}
match models_reported(reachability) {
Some(n) => format!("{n} live"),
None => "live".to_string(),
}
}
pub fn models_reported(reachability: &str) -> Option<u64> {
let open = reachability.find('(')? + 1;
let rest = reachability.get(open..)?;
let end = rest.find(" models)")?;
rest.get(..end)?.trim().parse().ok()
}
#[derive(Clone, Debug, Default)]
pub struct ProviderRow {
pub provider: String,
pub kind: String,
pub auth: String,
pub api_key_field: String,
pub api_key_env_var: String,
pub api_key_set: bool,
pub api_key_source: String,
pub api_key_fingerprint: String,
pub base_url: String,
pub base_url_source: String,
pub reachable: Option<bool>,
pub reachability: String,
pub note: String,
}
impl ProviderRow {
pub fn from_value(v: &Value) -> Option<ProviderRow> {
let provider = s(v, "provider").filter(|p| !p.is_empty())?;
Some(ProviderRow {
provider,
kind: s(v, "kind").unwrap_or_default(),
auth: s(v, "auth").unwrap_or_default(),
api_key_field: s(v, "api_key_field").unwrap_or_default(),
api_key_env_var: s(v, "api_key_env_var").unwrap_or_default(),
api_key_set: b(v, "api_key_set").unwrap_or(false),
api_key_source: s(v, "api_key_source").unwrap_or_default(),
api_key_fingerprint: s(v, "api_key_fingerprint").unwrap_or_default(),
base_url: s(v, "base_url").unwrap_or_default(),
base_url_source: s(v, "base_url_source").unwrap_or_default(),
reachable: v.get("reachable").and_then(Value::as_bool),
reachability: s(v, "reachability").unwrap_or_default(),
note: s(v, "note").unwrap_or_default(),
})
}
pub fn editable_key(&self) -> bool {
!self.api_key_field.is_empty()
}
}
#[derive(Clone, Debug, Default)]
pub struct ProfilesData {
pub ok: bool,
pub writable: bool,
pub config_file: Option<String>,
pub providers: Vec<ProviderRow>,
pub probed: bool,
pub profiles: Vec<ProfileRow>,
}
impl ProfilesData {
pub fn from_value(v: &Value) -> ProfilesData {
ProfilesData {
ok: b(v, "ok").unwrap_or(false),
writable: b(v, "writable").unwrap_or(false),
config_file: s(v, "config_file"),
providers: v
.get("providers")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(ProviderRow::from_value).collect())
.unwrap_or_default(),
probed: b(v, "probed").unwrap_or(false),
profiles: v
.get("profiles")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(ProfileRow::from_value).collect())
.unwrap_or_default(),
}
}
pub fn connections(&self) -> Vec<ConnectionRow> {
let mut rows: Vec<ConnectionRow> = self
.providers
.iter()
.map(|inv| {
let profile = inv
.provider
.strip_prefix("endpoint:")
.and_then(|id| self.profiles.iter().find(|p| p.id == id));
ConnectionRow::compose(inv, profile)
})
.collect();
for p in &self.profiles {
let name = p.virtual_provider();
if !rows.iter().any(|r| r.provider == name) {
rows.push(ConnectionRow::from_profile(p));
}
}
rows
}
}
pub fn models_from_payload(v: &Value) -> Vec<String> {
v.get("models")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(Value::as_str)
.map(str::to_string)
.collect()
})
.unwrap_or_default()
}
#[derive(Clone, Debug)]
pub struct JournalEntry {
pub when: String,
pub action: String,
pub outcome: Result<String, String>,
}
#[derive(Clone, Debug)]
pub struct BusyOp {
pub id: u64,
pub label: String,
pub started: Instant,
}
#[derive(Clone, Copy)]
pub struct Store {
pub cfg: Signal<Loadable<ConfigMirror>>,
pub routes: Signal<Loadable<RoutesData>>,
pub profiles: Signal<Loadable<ProfilesData>>,
pub availability: Signal<Loadable<AvailabilityData>>,
pub cli: Signal<Option<CliInfo>>,
pub models: Signal<HashMap<String, Loadable<Vec<String>>>>,
pub journal: Signal<Vec<JournalEntry>>,
pub busy: Signal<Vec<BusyOp>>,
pub tick: Signal<u64>,
pub notice: Signal<Option<String>>,
pub python_fallback: Signal<Option<String>>,
pub tests: Signal<Vec<crate::probes::TestResult>>,
pub probe_busy: Signal<bool>,
pub email: Signal<Loadable<Value>>,
pub email_oauth_prompt: Signal<Option<Value>>,
pub email_discovery: Signal<Option<Value>>,
pub email_error_code: Signal<Option<String>>,
}
impl Store {
pub fn create(cx: Scope) -> Store {
Store {
cfg: cx.signal(Loadable::default()),
routes: cx.signal(Loadable::default()),
profiles: cx.signal(Loadable::default()),
availability: cx.signal(Loadable::default()),
cli: cx.signal(None),
models: cx.signal(HashMap::new()),
journal: cx.signal(Vec::new()),
busy: cx.signal(Vec::new()),
tick: cx.signal(0),
notice: cx.signal(None),
python_fallback: cx.signal(None),
tests: cx.signal(Vec::new()),
probe_busy: cx.signal(false),
email: cx.signal(Loadable::default()),
email_oauth_prompt: cx.signal(None),
email_discovery: cx.signal(None),
email_error_code: cx.signal(None),
}
}
pub fn reset_domains(&self) {
let Store {
cli: _, journal: _, busy: _, tick: _, notice: _, tests: _, probe_busy: _, email_oauth_prompt: _, email_discovery: _, email_error_code: _, cfg,
routes,
profiles,
availability,
models,
python_fallback,
email,
} = *self;
cfg.set(Loadable::NotAsked);
routes.set(Loadable::NotAsked);
profiles.set(Loadable::NotAsked);
availability.set(Loadable::NotAsked);
models.update(|m| m.clear());
python_fallback.set(None);
email.set(Loadable::NotAsked);
}
pub fn record_test(&self, result: crate::probes::TestResult) {
self.tests.update(|v| {
v.retain(|r| r.label != result.label);
v.insert(0, result);
});
}
pub fn push_journal(&self, entry: JournalEntry) {
self.journal.update(|j| j.push(entry));
}
pub fn begin_busy(&self, id: u64, label: &str) {
let label = label.to_string();
self.busy.update(move |ops| {
ops.push(BusyOp {
id,
label,
started: Instant::now(),
})
});
}
pub fn end_busy(&self, id: u64) {
self.busy.update(move |ops| ops.retain(|o| o.id != id));
}
}
pub fn now_hms() -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let (h, m, s) = ((secs / 3600) % 24, (secs / 60) % 60, secs % 60);
format!("{h:02}:{m:02}:{s:02}Z")
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_route_whose_engine_is_not_installed_reads_so() {
let row = RouteRow::from_value(&json!({
"key": "input.text", "configured": true, "provider": "mlx", "model": "m",
"engine_missing": {"engine": "mlx", "name": "MLX (mlx-lm)", "reason": "MLX is not installed",
"install": "pip install mlx-lm", "engine_row": "mlx"}
}))
.unwrap();
let m = row.engine_missing.clone().unwrap();
assert_eq!(
(
m.engine.as_str(),
m.install.as_deref(),
m.engine_row.as_deref()
),
("mlx", Some("pip install mlx-lm"), Some("mlx"))
);
assert_eq!(row.state_label(), "engine not installed");
let broken = RouteRow::from_value(&json!({
"key": "input.text", "configured": true,
"route_unavailable": {"reason": "MLX needs Apple silicon"},
"engine_missing": {"engine": "mlx", "reason": "x"}
}))
.unwrap();
assert_eq!(broken.state_label(), "cannot run here");
let old = RouteRow::from_value(&json!({"key": "input.text", "configured": true})).unwrap();
assert!(old.engine_missing.is_none() && old.state_label() == "configured");
}
#[test]
fn route_rows_render_the_broad_task_hierarchy() {
let parent = |covered: bool| {
RouteRow::from_value(&json!({
"key": "output.image", "kind": "output", "modality": "image",
"label": "Image Output", "configured": false,
"source": "not_configured",
"task_keys": ["output.image.text_to_image", "output.image.image_to_image",
"output.image.image_upscale"],
"covered_by_tasks": covered
}))
.unwrap()
};
let child = RouteRow::from_value(&json!({
"key": "output.image.text_to_image", "kind": "output", "modality": "image",
"label": "Image Generation", "configured": true, "provider": "mlx-gen",
"model": "AbstractFramework/flux.2-klein-9b-8bit",
"source": "abstractcore.capability_defaults",
"broad_key": "output.image"
}))
.unwrap();
let covered = parent(true);
assert!(covered.is_task_parent());
assert_eq!(covered.task_keys.len(), 3);
assert_eq!(
covered.display_key(),
"output.image",
"the parent is not indented"
);
assert_eq!(
covered.state_label(),
"not needed",
"an unset parent every task row already covers is benign, not a red flag"
);
assert!(
covered.editable(),
"the parent stays settable — one image model for every task is the simple path"
);
assert_eq!(
parent(false).state_label(),
"not configured",
"a parent with an uncovered task under it IS the missing setting"
);
assert!(!child.is_task_parent());
assert_eq!(child.broad_key.as_deref(), Some("output.image"));
assert_eq!(
child.display_key(),
" └ text_to_image",
"task rows indent under the parent and drop its repeated prefix"
);
assert_eq!(child.state_label(), "configured");
}
#[test]
fn task_rows_answered_by_a_configured_parent_read_as_inherited() {
let inherited = RouteRow::from_value(&json!({
"key": "output.image.image_upscale", "kind": "output", "modality": "image",
"label": "Image Restore / Upscale", "configured": false,
"source": "not_configured", "broad_key": "output.image",
"inherits_broad": true
}))
.unwrap();
assert_eq!(inherited.state_label(), "inherited");
assert_eq!(inherited.display_key(), " └ image_upscale");
assert!(inherited.editable(), "an inherited row is still settable");
let orphan = RouteRow::from_value(&json!({
"key": "output.video.text_to_video", "kind": "output", "modality": "video",
"label": "Video Generation", "configured": false,
"source": "not_configured", "broad_key": "output.video"
}))
.unwrap();
assert_eq!(orphan.state_label(), "not configured");
}
#[test]
fn broad_only_modalities_carry_no_hierarchy() {
let voice = RouteRow::from_value(&json!({
"key": "output.voice", "kind": "output", "modality": "voice",
"label": "Voice Output", "configured": true, "provider": "supertonic",
"model": "supertonic-3", "source": "abstractcore.capability_defaults"
}))
.unwrap();
assert!(!voice.is_task_parent());
assert!(voice.broad_key.is_none());
assert!(!voice.covered_by_tasks);
assert_eq!(voice.display_key(), "output.voice");
assert_eq!(voice.state_label(), "configured");
}
#[test]
fn routes_fold_reads_the_live_shape() {
let v = json!({
"ok": true, "authority": "abstractcore.local",
"config_file": "/home/u/.abstractcore/config/abstractcore.json",
"writable": true, "errors": [],
"routes": [
{"key": "input.text", "kind": "input", "modality": "text",
"label": "Text Input", "task": "text_understanding",
"provider": "lmstudio", "model": "qwen3-0.6b",
"base_url": "http://localhost:1234/v1",
"source": "abstractcore.capability_defaults", "configured": true},
{"key": "input.image", "kind": "input", "modality": "image",
"label": "Image Input", "provider": "lmstudio",
"model": "m", "configured": true,
"covered_by": "input.text", "read_only": true,
"source": "abstractcore.capability_defaults"},
{"key": "output.text", "kind": "output", "modality": "text",
"label": "Text Output", "provider": "lmstudio", "model": "m",
"reasoning": "high", "configured": true, "read_only": true,
"derived_from": "input.text",
"source": "abstractcore.capability_defaults"},
{"key": "input.video", "kind": "input", "modality": "video",
"label": "Video Input", "configured": false,
"source": "not_configured",
"package_hint": "abstractvideo or a video-capable LLM"},
{"no_key": true}
]
});
let d = RoutesData::from_value(&v);
assert!(d.ok && d.writable);
assert_eq!(d.rows.len(), 4, "the keyless row is dropped");
assert_eq!(d.configured_count(), 3);
assert_eq!(
d.config_file.as_deref(),
Some("/home/u/.abstractcore/config/abstractcore.json")
);
let by_key = |k: &str| d.rows.iter().find(|r| r.key == k).unwrap();
assert!(by_key("input.text").editable());
assert!(
!by_key("input.image").editable(),
"covered + read_only is locked"
);
assert!(
!by_key("output.text").editable(),
"the input.text alias is never independently editable"
);
assert_eq!(
by_key("input.video").package_hint.as_deref(),
Some("abstractvideo or a video-capable LLM")
);
assert_eq!(by_key("input.text").state_label(), "configured");
assert_eq!(by_key("input.image").state_label(), "covered by input.text");
assert_eq!(by_key("output.text").state_label(), "derived ← input.text");
assert_eq!(by_key("input.video").state_label(), "not configured");
assert_eq!(
by_key("output.text").derived_from.as_deref(),
Some("input.text")
);
assert_eq!(by_key("output.text").reasoning.as_deref(), Some("high"));
assert!(by_key("output.text").is_text_generation());
assert!(by_key("input.text").is_text_generation());
assert!(!by_key("input.image").is_text_generation());
assert_eq!(reasoning_index(Some("HIGH")), 4, "case-insensitive");
assert_eq!(reasoning_index(Some(" ")), 0, "blank = not set");
assert_eq!(
reasoning_index(Some("ludicrous")),
0,
"a level the list does not offer never fabricates a selection"
);
assert_eq!(reasoning_index(None), 0);
assert_eq!(by_key("input.text").pair_text(), "lmstudio / qwen3-0.6b");
assert_eq!(by_key("input.video").pair_text(), "—");
}
#[test]
fn profiles_fold_reads_the_live_shape() {
let v = json!({
"ok": true, "writable": true, "config_file": "/x.json",
"profiles": [
{"id": "ovh-provider", "display_name": "OVH Provider",
"description": "hosted endpoint", "provider_family": "openai-compatible",
"base_url": "https://oai.example/v1",
"api_key_set": true, "api_key_fingerprint": "35982521",
"api_key_env_var": "", "allowed_models": [], "enabled": true,
"virtual_provider": "endpoint:ovh-provider"},
{"id": "local", "provider_family": "lmstudio",
"base_url": "http://localhost:1234/v1",
"api_key_set": false, "api_key_fingerprint": null,
"allowed_models": ["a", "b"], "enabled": false}
]
});
let d = ProfilesData::from_value(&v);
assert_eq!(d.profiles.len(), 2);
let ovh = &d.profiles[0];
assert_eq!(ovh.virtual_provider(), "endpoint:ovh-provider");
assert!(ovh.api_key_set);
assert_eq!(ovh.api_key_fingerprint.as_deref(), Some("35982521"));
assert_eq!(ovh.api_key_env_var, None, "blank env var reads as none");
let local = &d.profiles[1];
assert!(!local.enabled);
assert_eq!(local.allowed_models, vec!["a", "b"]);
}
fn unified_fixture() -> ProfilesData {
ProfilesData::from_value(&json!({
"ok": true, "writable": true, "probed": true,
"providers": [
{"provider": "openai", "kind": "cloud_api", "auth": "required",
"api_key_field": "openai", "api_key_env_var": "OPENAI_API_KEY",
"api_key_set": true, "api_key_source": "config",
"api_key_fingerprint": "9f1c33aa", "base_url": "", "base_url_source": "",
"reachable": null, "reachability": "", "note": ""},
{"provider": "anthropic", "kind": "cloud_api", "auth": "required",
"api_key_field": "anthropic", "api_key_env_var": "ANTHROPIC_API_KEY",
"api_key_set": true, "api_key_source": "env:ANTHROPIC_API_KEY",
"api_key_fingerprint": "aa11bb22", "base_url": "", "base_url_source": "",
"reachable": null, "reachability": "", "note": ""},
{"provider": "lmstudio", "kind": "local_server", "auth": "none",
"api_key_field": "", "api_key_env_var": "", "api_key_set": false,
"api_key_source": "", "api_key_fingerprint": "",
"base_url": "http://localhost:1234/v1", "base_url_source": "default",
"reachable": true, "reachability": "reachable (43 models)", "note": ""},
{"provider": "ollama", "kind": "local_server", "auth": "none",
"api_key_field": "", "api_key_env_var": "", "api_key_set": false,
"api_key_source": "", "api_key_fingerprint": "",
"base_url": "http://localhost:11434", "base_url_source": "default",
"reachable": false, "reachability": "GET .../api/tags unreachable",
"note": ""},
{"provider": "mlx", "kind": "local_engine", "auth": "none",
"api_key_field": "", "api_key_env_var": "", "api_key_set": false,
"api_key_source": "", "api_key_fingerprint": "",
"base_url": "", "base_url_source": "",
"reachable": null, "reachability": "",
"note": "Apple Silicon text/vision inference"},
{"provider": "endpoint:ovh-provider", "kind": "endpoint_profile",
"auth": "optional", "api_key_field": "", "api_key_env_var": "",
"api_key_set": true, "api_key_source": "profile",
"api_key_fingerprint": "35982521",
"base_url": "https://oai.example.net/v1",
"base_url_source": "endpoint profile",
"reachable": true, "reachability": "reachable (22 models)",
"note": "endpoint profile (openai-compatible)"},
{"provider": "endpoint:team-proxy", "kind": "endpoint_profile",
"auth": "optional", "api_key_field": "", "api_key_env_var": "TEAM_KEY",
"api_key_set": false, "api_key_source": "",
"api_key_fingerprint": "",
"base_url": "https://proxy.example/v1",
"base_url_source": "endpoint profile",
"reachable": null, "reachability": "", "note": ""}
],
"profiles": [
{"id": "ovh-provider", "display_name": "OVH Provider",
"provider_family": "openai-compatible",
"base_url": "https://oai.example.net/v1",
"api_key_set": true, "api_key_fingerprint": "35982521",
"api_key_env_var": "", "allowed_models": [], "enabled": true},
{"id": "team-proxy", "display_name": "Team proxy",
"provider_family": "openai", "base_url": "https://proxy.example/v1",
"api_key_set": false, "api_key_fingerprint": null,
"api_key_env_var": "TEAM_KEY", "allowed_models": ["gpt-x"],
"enabled": false}
]
}))
}
#[test]
fn connections_compose_one_row_per_provider_in_payload_order() {
let rows = unified_fixture().connections();
assert_eq!(
rows.iter().map(|r| r.provider.as_str()).collect::<Vec<_>>(),
vec![
"openai",
"anthropic",
"lmstudio",
"ollama",
"mlx",
"endpoint:ovh-provider",
"endpoint:team-proxy"
],
"payload order is preserved and each profile appears ONCE, inline"
);
let row = |name: &str| {
rows.iter()
.find(|r| r.provider == name)
.unwrap_or_else(|| panic!("{name} row"))
.clone()
};
assert_eq!(row("endpoint:ovh-provider").family, "openai-compatible");
assert_eq!(row("endpoint:team-proxy").family, "openai");
assert_eq!(row("lmstudio").family, "lmstudio");
assert_eq!(row("endpoint:ovh-provider").enabled_text(), "yes");
assert_eq!(row("endpoint:team-proxy").enabled_text(), "NO");
assert_eq!(row("lmstudio").enabled_text(), "—");
assert_eq!(row("lmstudio").enabled, None);
assert_eq!(row("endpoint:team-proxy").models, "1 restr");
assert_eq!(row("lmstudio").models, "43 live");
assert_eq!(row("endpoint:ovh-provider").models, "22 live");
assert_eq!(row("openai").models, "live");
assert_eq!(row("openai").base_url_text(), "—");
assert_eq!(row("ollama").base_url_text(), "http://localhost:11434");
assert!(row("endpoint:ovh-provider").is_profile());
assert!(!row("endpoint:ovh-provider").takes_key());
assert!(!row("lmstudio").is_profile());
assert!(!row("lmstudio").takes_key());
assert!(row("openai").takes_key());
assert_eq!(row("openai").api_key_field, "openai");
}
#[test]
fn origin_labels_say_where_each_row_comes_from() {
let rows = unified_fixture().connections();
let origin = |name: &str| {
rows.iter()
.find(|r| r.provider == name)
.map(|r| r.origin)
.unwrap_or_else(|| panic!("{name} row"))
};
assert_eq!(origin("openai"), Origin::Config, "key stored in this file");
assert_eq!(origin("anthropic"), Origin::Env, "key from the environment");
assert_eq!(
origin("lmstudio"),
Origin::Auto,
"a local server that ANSWERED at its default address"
);
assert_eq!(
origin("ollama"),
Origin::Registry,
"a default address with nothing behind it is not configured"
);
assert_eq!(origin("mlx"), Origin::Registry);
assert_eq!(
origin("endpoint:ovh-provider"),
Origin::Config,
"an endpoint profile lives in provider_profiles — always this file"
);
assert_eq!(origin("endpoint:team-proxy"), Origin::Config);
assert_eq!(
["config", "env", "auto", "registry"],
[
Origin::Config.label(),
Origin::Env.label(),
Origin::Auto.label(),
Origin::Registry.label()
]
);
let detail = |name: &str| {
rows.iter()
.find(|r| r.provider == name)
.map(ConnectionRow::origin_detail)
.unwrap_or_default()
};
assert_eq!(
detail("endpoint:ovh-provider"),
"endpoint profile stored in this config · endpoint profile (openai-compatible)"
);
assert_eq!(
detail("openai"),
"key stored in this config (api_keys.openai)"
);
assert_eq!(
detail("anthropic"),
"resolved from the environment ($ANTHROPIC_API_KEY)"
);
assert_eq!(
detail("lmstudio"),
"a local server answering at http://localhost:1234/v1"
);
assert!(
detail("ollama").starts_with("known to the registry — nothing configured yet · GET"),
"an unreachable row keeps the probe's own words: {}",
detail("ollama")
);
}
#[test]
fn api_key_cells_speak_one_vocabulary() {
let rows = unified_fixture().connections();
let key = |name: &str| {
rows.iter()
.find(|r| r.provider == name)
.map(|r| r.api_key.clone())
.unwrap_or_else(|| panic!("{name} row"))
};
assert_eq!(key("openai"), "stored (9f1c33aa)");
assert_eq!(key("anthropic"), "stored ($ANTHROPIC_API_KEY)");
assert_eq!(key("endpoint:ovh-provider"), "stored (35982521)");
assert_eq!(key("endpoint:team-proxy"), "none ($TEAM_KEY)");
assert_eq!(key("lmstudio"), "none");
assert_eq!(key_cell(true, "profile", "", ""), "stored");
}
#[test]
fn a_profile_missing_from_the_inventory_still_gets_a_row() {
let d = ProfilesData::from_value(&json!({
"providers": [
{"provider": "openai", "kind": "cloud_api", "api_key_field": "openai",
"api_key_env_var": "OPENAI_API_KEY"}
],
"profiles": [
{"id": "paritytest", "provider_family": "openai-compatible",
"base_url": "http://127.0.0.1:1234/v1", "api_key_set": false,
"allowed_models": [], "enabled": true}
]
}));
let rows = d.connections();
assert_eq!(rows.len(), 2);
let orphan = rows.last().unwrap();
assert_eq!(orphan.provider, "endpoint:paritytest");
assert_eq!(orphan.family, "openai-compatible");
assert_eq!(orphan.origin, Origin::Config);
assert_eq!(orphan.enabled_text(), "yes");
assert_eq!(orphan.api_key, "none");
assert!(orphan.is_profile(), "e/d still act on the stored profile");
}
#[test]
fn model_counts_are_read_not_guessed() {
assert_eq!(models_reported("reachable (43 models)"), Some(43));
assert_eq!(models_reported("reachable (0 models)"), Some(0));
assert_eq!(models_reported(""), None);
assert_eq!(models_reported("GET http://x/v1/models unreachable"), None);
assert_eq!(models_reported("reachable (many models)"), None);
}
}