use crate::config::{
CONFIG, CONFIG_KEY_PROVIDER_ENDPOINT, CONFIG_KEY_PROVIDER_ENDPOINT_KEY,
CONFIG_KEY_PROVIDER_KEY, OnboardingState,
};
use crate::users::{ADMIN_USER_NAME, describe_telegram_binding};
use crate::util::json::{get_bool, get_opt_str_strict};
use anyhow::Context as _;
use std::fmt::Write as _;
use std::time::Duration;
pub(crate) const ACTION: &str = "setup";
const OPENROUTER_KEY_CHECK: &str = "https://openrouter.ai/api/v1/key";
const KEY_CHECK_TIMEOUT: Duration = Duration::from_secs(10);
const ENDPOINT_MENTIONS: usize = 5;
const REPORT_PROSE_BYTES: usize = 1800;
pub(crate) const MAX_ENDPOINT_BYTES: usize =
(crate::settings::MAX_READ_BACK_BYTES - REPORT_PROSE_BYTES) / ENDPOINT_MENTIONS;
#[derive(Debug, Default, PartialEq, Eq)]
struct SetupArgs {
provider_key: Option<String>,
provider_endpoint: Option<String>,
provider_endpoint_key: Option<String>,
clear_provider_endpoint: bool,
telegram_token: Option<String>,
owner: Option<String>,
unbind_owner: bool,
}
fn text_arg(args: &serde_json::Value, key: &str) -> anyhow::Result<Option<String>> {
match get_opt_str_strict(args, key)? {
Some(value) if value.trim().is_empty() => anyhow::bail!(
"usage: argument \"{key}\" is blank — give it a value, or leave the argument out"
),
Some(value) => Ok(Some(value.trim().to_string())),
None => Ok(None),
}
}
impl SetupArgs {
fn parse(args: &serde_json::Value) -> anyhow::Result<Self> {
let parsed = Self {
provider_key: text_arg(args, "provider_key")?,
provider_endpoint: text_arg(args, "provider_endpoint")?,
provider_endpoint_key: text_arg(args, "provider_endpoint_key")?,
clear_provider_endpoint: get_bool(args, "clear_provider_endpoint", false)?,
telegram_token: text_arg(args, "telegram_token")?,
owner: text_arg(args, "owner")?,
unbind_owner: get_bool(args, "unbind_owner", false)?,
};
anyhow::ensure!(
parsed.provider_endpoint.is_some() || parsed.provider_endpoint_key.is_none(),
"usage: \"provider_endpoint_key\" needs \"provider_endpoint\" — a custom endpoint's key \
is saved with the endpoint it belongs to"
);
if let Some(endpoint) = &parsed.provider_endpoint {
anyhow::ensure!(
endpoint.len() <= MAX_ENDPOINT_BYTES,
"usage: \"provider_endpoint\" takes at most {MAX_ENDPOINT_BYTES} bytes — got {} \
(see the `reference` action)",
endpoint.len()
);
}
anyhow::ensure!(
parsed.provider_endpoint_key.is_none()
|| parsed
.provider_endpoint
.as_deref()
.is_some_and(crate::config::is_custom_endpoint),
"usage: \"provider_endpoint_key\" is a custom endpoint's own key — give it with a \
\"provider_endpoint\" that is not OpenRouter's (an OpenRouter key goes in \
\"provider_key\")"
);
anyhow::ensure!(
!parsed.clear_provider_endpoint
|| (parsed.provider_endpoint.is_none() && parsed.provider_endpoint_key.is_none()),
"usage: \"clear_provider_endpoint\" is the move back to OpenRouter's own — give it \
alone, with no \"provider_endpoint\" or \"provider_endpoint_key\""
);
anyhow::ensure!(
!(parsed.owner.is_some() && parsed.unbind_owner),
"usage: \"owner\" and \"unbind_owner\" are one decision — give one or the other"
);
if let Some(owner) = &parsed.owner {
crate::users::normalize_telegram_binding(owner)
.map_err(|e| anyhow::anyhow!("usage: \"owner\": {e:#}"))?;
}
Ok(parsed)
}
}
#[derive(Debug)]
enum ProviderState {
NotConfigured,
OpenRouter,
Custom { key: bool, openrouter_key: bool },
}
impl ProviderState {
fn openrouter_key(&self) -> bool {
match self {
Self::NotConfigured => false,
Self::OpenRouter => true,
Self::Custom { openrouter_key, .. } => *openrouter_key,
}
}
}
#[derive(Debug)]
enum OwnerBinding {
None,
Bound(String),
Unreadable(String),
}
#[derive(Debug)]
struct Report {
changed: Vec<String>,
warnings: Vec<String>,
stopped: Option<String>,
provider: ProviderState,
endpoint: String,
bot_token_saved: bool,
bot: Option<String>,
owner: OwnerBinding,
onboarding: OnboardingState,
}
impl Report {
fn provider_line(&self) -> String {
let detail = match &self.provider {
ProviderState::NotConfigured => return " provider: not configured".to_string(),
ProviderState::OpenRouter => "OpenRouter, key saved",
ProviderState::Custom {
key,
openrouter_key,
} => match (key, openrouter_key) {
(true, true) => {
"custom endpoint, its own key saved, plus an OpenRouter key for media"
}
(false, true) => "custom endpoint, keyless, plus an OpenRouter key for media",
(true, false) => "custom endpoint, its own key saved",
(false, false) => "custom endpoint, keyless",
},
};
format!(" provider: configured — {} ({detail})", self.endpoint)
}
fn bot_line(&self) -> String {
match (&self.bot, self.bot_token_saved) {
(Some(identity), _) => format!(" telegram bot: {identity}"),
(None, true) => " telegram bot: a token is saved; its identity is checked only by a \
run that saves it"
.to_string(),
(None, false) => " telegram bot: no token saved".to_string(),
}
}
fn owner_line(&self) -> String {
match &self.owner {
OwnerBinding::None => " owner: no Telegram binding".to_string(),
OwnerBinding::Bound(binding) => format!(" owner: {binding}"),
OwnerBinding::Unreadable(e) => format!(" owner: could not be read back ({e})"),
}
}
fn onboarding_line(&self) -> String {
let state = match self.onboarding {
OnboardingState::Finished => "finished",
OnboardingState::Init => "still open — a provider credential finishes it",
};
format!(" onboarding: {state}")
}
fn notes(&self) -> Vec<String> {
let mut notes = self.warnings.clone();
if crate::config::is_custom_endpoint(&self.endpoint) && !self.provider.openrouter_key() {
notes.push(
"This instance uses a custom endpoint and no OpenRouter key is saved: media \
generation and editing need an OpenRouter key."
.to_string(),
);
}
notes
}
fn next_steps(&self) -> Vec<String> {
let mut steps = Vec::new();
if matches!(self.provider, ProviderState::NotConfigured) {
steps.push(
"Set the model provider: mahbot config setup --provider-key @key.txt for an \
OpenRouter key, or --provider-endpoint URL [--provider-endpoint-key @key.txt] for \
a custom OpenAI-compatible endpoint."
.to_string(),
);
}
if !self.bot_token_saved {
steps.push(
"Save the Telegram bot token from BotFather: mahbot config setup --telegram-token \
@token.txt."
.to_string(),
);
}
if matches!(self.owner, OwnerBinding::None) {
steps.push(
"Bind your own Telegram account as the owner: mahbot config setup --owner \
./@yourname (or --owner <numeric id>)."
.to_string(),
);
}
if matches!(self.owner, OwnerBinding::Unreadable(_)) {
steps.push(
"Read the owner binding back with `mahbot config setup` (no arguments) — this run \
could not read it after its writes."
.to_string(),
);
}
steps.push(format!(
"Send /start to {} from the owner's Telegram account — a bot cannot start the \
conversation itself, so nothing reaches you until that first message.",
self.bot.as_deref().unwrap_or("the bot")
));
steps
}
fn render(&self) -> String {
let mut out = String::from("Changed:\n");
if self.changed.is_empty() {
out.push_str(" (nothing — this run changed nothing)\n");
} else {
for change in &self.changed {
let _ = writeln!(out, " - {change}");
}
}
if let Some(stopped) = &self.stopped {
out.push_str("\nStopped:\n");
let _ = writeln!(out, " - {stopped}");
if self.changed.is_empty() {
out.push_str(" Nothing was written before this step.\n");
} else {
out.push_str(
" The changes listed above were applied; the run ended at this step.\n",
);
}
}
out.push_str("\nCurrent state:\n");
let _ = writeln!(out, "{}", self.provider_line());
let _ = writeln!(out, "{}", self.bot_line());
let _ = writeln!(out, "{}", self.owner_line());
let _ = writeln!(out, "{}", self.onboarding_line());
let notes = self.notes();
if !notes.is_empty() {
out.push_str("\nWarnings:\n");
for note in ¬es {
let _ = writeln!(out, " - {note}");
}
}
out.push_str("\nNext:\n");
for step in self.next_steps() {
let _ = writeln!(out, " - {step}");
}
out
}
}
fn owner_binding_line(identifier: &str) -> String {
let described = describe_telegram_binding(identifier);
if crate::users::telegram_identifier_is_number(identifier) {
format!("owner bound to {described}")
} else {
format!(
"owner bound to {described} — accepted; the binding is confirmed at the first message \
from that account, and the bot's reply there says so"
)
}
}
async fn openrouter_key_answers(key: &str) -> anyhow::Result<bool> {
let client = crate::util::http::build_http_client(KEY_CHECK_TIMEOUT);
let response = client
.get(OPENROUTER_KEY_CHECK)
.bearer_auth(key)
.send()
.await
.context("OpenRouter could not be reached")?;
let status = response.status();
Ok(!(status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN))
}
async fn save_openrouter_key(
key: &str,
changed: &mut Vec<String>,
warnings: &mut Vec<String>,
) -> anyhow::Result<()> {
if CONFIG.provider_key().as_deref() == Some(key) {
return Ok(());
}
crate::config::persist_settled_string_field(CONFIG_KEY_PROVIDER_KEY, key).await?;
changed.push("OpenRouter key saved".to_string());
match openrouter_key_answers(key).await {
Ok(true) => {}
Ok(false) => warnings.push(
"The key was saved, but OpenRouter does not accept it: the Assistant cannot answer \
until a working key is saved."
.to_string(),
),
Err(e) => warnings.push(format!(
"The key was saved, but OpenRouter could not be reached to check it ({e:#}): the \
Assistant cannot answer until a working key is saved."
)),
}
Ok(())
}
fn is_key_row_set() -> bool {
CONFIG
.provider_endpoint_key()
.is_some_and(|key| !key.trim().is_empty())
}
#[derive(PartialEq, Eq, Debug)]
enum KeyRowFate {
Dropped,
LeftBehind,
}
impl KeyRowFate {
const fn with_endpoint(self) -> &'static str {
match self {
Self::Dropped => ", and its key was dropped with it",
Self::LeftBehind => ", but its key row could not be removed and is left behind",
}
}
}
fn key_row_fate(dropped: bool, had_key: bool, still_set: bool) -> Option<KeyRowFate> {
match (dropped, had_key, still_set) {
(true, true, false) => Some(KeyRowFate::Dropped),
(true, true, true) => Some(KeyRowFate::LeftBehind),
_ => None,
}
}
async fn apply_provider(
args: &SetupArgs,
changed: &mut Vec<String>,
warnings: &mut Vec<String>,
) -> anyhow::Result<()> {
if args.clear_provider_endpoint {
let before = crate::config::effective_chat_endpoint(&CONFIG.snapshot());
let custom = crate::config::is_custom_endpoint(&before);
let had_key = is_key_row_set();
if custom {
crate::config::persist_settled_string_field(CONFIG_KEY_PROVIDER_ENDPOINT, "").await?;
let fate = key_row_fate(true, had_key, is_key_row_set());
changed.push(match fate {
Some(fate) => format!(
"custom endpoint cleared — back to OpenRouter's own{}",
fate.with_endpoint()
),
None => "custom endpoint cleared — back to OpenRouter's own".to_string(),
});
} else if had_key {
crate::config::persist_settled_string_field(CONFIG_KEY_PROVIDER_ENDPOINT_KEY, "")
.await?;
changed.push("nothing changed about the endpoint; its key row was removed".to_string());
}
}
if let Some(endpoint) = &args.provider_endpoint {
let before = crate::config::effective_chat_endpoint(&CONFIG.snapshot());
if before != endpoint.trim() {
let had_key = is_key_row_set();
let outcome =
crate::config::persist_settled_string_field(CONFIG_KEY_PROVIDER_ENDPOINT, endpoint)
.await?;
let after = crate::config::effective_chat_endpoint(&CONFIG.snapshot());
if after != before {
let dropped = !crate::config::is_custom_endpoint(&after);
changed.push(format!(
"provider endpoint set to {after}{}",
key_row_fate(dropped, had_key, is_key_row_set())
.map_or("", KeyRowFate::with_endpoint)
));
}
warnings.extend(outcome.warning);
}
if let Some(key) = &args.provider_endpoint_key
&& CONFIG.provider_endpoint_key().as_deref() != Some(key.as_str())
{
crate::config::persist_settled_string_field(CONFIG_KEY_PROVIDER_ENDPOINT_KEY, key)
.await?;
changed.push("custom endpoint key saved".to_string());
}
}
if let Some(key) = &args.provider_key {
save_openrouter_key(key, changed, warnings).await?;
}
Ok(())
}
async fn apply_telegram_token(
token: &str,
changed: &mut Vec<String>,
warnings: &mut Vec<String>,
bot: &mut Option<String>,
) -> anyhow::Result<()> {
if CONFIG.telegram_bot_token().as_deref() == Some(token) {
return Ok(());
}
*bot = crate::config::persist_telegram_bot_token(token).await?;
changed.push("Telegram bot token saved".to_string());
if bot.is_none() {
warnings.push(
"The Telegram bot token was saved, but its identity could not be checked now: the \
local Bot API server has no endpoint yet, so the bot cannot be named."
.to_string(),
);
}
Ok(())
}
async fn apply(
args: &SetupArgs,
changed: &mut Vec<String>,
warnings: &mut Vec<String>,
bot: &mut Option<String>,
) -> anyhow::Result<()> {
apply_provider(args, changed, warnings).await?;
if let Some(token) = &args.telegram_token {
apply_telegram_token(token, changed, warnings, bot).await?;
}
if args.unbind_owner
&& crate::users::store()
.unbind_telegram(crate::users::ADMIN_USER_NAME)
.await?
{
changed.push("owner Telegram binding removed".to_string());
}
if let Some(value) = &args.owner {
let rebound = crate::users::store()
.rebind_telegram_for_admin(value)
.await?;
if rebound.changed {
changed.push(owner_binding_line(&rebound.identifier));
}
}
if crate::config::provider_configured() && CONFIG.onboarding_stage() == OnboardingState::Init {
crate::onboarding::finish_onboarding().await?;
changed.push("onboarding finished".to_string());
}
Ok(())
}
pub(crate) async fn run(args: &serde_json::Value) -> anyhow::Result<String> {
let args = SetupArgs::parse(args)?;
let mut changed: Vec<String> = Vec::new();
let mut warnings: Vec<String> = Vec::new();
let mut bot = None;
let stopped = apply(&args, &mut changed, &mut warnings, &mut bot)
.await
.err()
.map(|e| format!("{e:#}"));
let config = CONFIG.snapshot();
let endpoint = crate::config::effective_chat_endpoint(&config);
let openrouter_key = config.provider_key.is_some();
let provider = if !crate::config::provider_configured() {
ProviderState::NotConfigured
} else if crate::config::is_custom_endpoint(&endpoint) {
ProviderState::Custom {
key: config.provider_endpoint_key.is_some(),
openrouter_key,
}
} else {
ProviderState::OpenRouter
};
let report = Report {
changed,
warnings,
stopped,
provider,
endpoint,
bot_token_saved: config.telegram_bot_token.is_some(),
bot,
owner: match crate::users::store()
.telegram_binding(ADMIN_USER_NAME)
.await
{
Ok(Some(identifier)) => OwnerBinding::Bound(describe_telegram_binding(&identifier)),
Ok(None) => OwnerBinding::None,
Err(e) => OwnerBinding::Unreadable(format!("{e:#}")),
},
onboarding: CONFIG.onboarding_stage(),
};
if report.stopped.is_some() {
anyhow::bail!("{}", report.render());
}
Ok(report.render())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn stand_in_provider() -> String {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind a stand-in host");
let addr = listener.local_addr().expect("its address");
listener
.set_nonblocking(true)
.expect("a stand-in host that never blocks its thread");
std::thread::spawn(move || {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
match listener.accept() {
Ok((mut stream, _)) => {
let _ = stream.set_nonblocking(false);
let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
let mut buf = [0u8; 2048];
let _ = std::io::Read::read(&mut stream, &mut buf);
let _ = std::io::Write::write_all(
&mut stream,
b"HTTP/1.1 405 Method Not Allowed\r\ncontent-length: 0\r\nconnection: \
close\r\n\r\n",
);
return;
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
if std::time::Instant::now() > deadline {
return;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
Err(_) => return,
}
}
});
format!("http://{addr}/v1")
}
fn report() -> Report {
Report {
changed: Vec::new(),
warnings: Vec::new(),
stopped: None,
provider: ProviderState::OpenRouter,
endpoint: "https://openrouter.ai/api/v1".to_string(),
bot_token_saved: true,
bot: None,
owner: OwnerBinding::Bound("@owner".to_string()),
onboarding: OnboardingState::Finished,
}
}
#[test]
fn the_settings_bridge_names_the_arguments_this_module_reads() {
use crate::settings::Setting;
for setting in [Setting::ProviderKey, Setting::ProviderEndpoint] {
let args = json!({ setting.name(): "acme" });
let expected = match setting {
Setting::ProviderKey => SetupArgs {
provider_key: Some("acme".to_string()),
..SetupArgs::default()
},
Setting::ProviderEndpoint => SetupArgs {
provider_endpoint: Some("acme".to_string()),
..SetupArgs::default()
},
_ => unreachable!(),
};
assert_eq!(
SetupArgs::parse(&args).unwrap(),
expected,
"the bridge's argument for `{}` is not the field this module reads",
setting.name()
);
}
}
#[test]
fn the_key_row_fate_is_said_only_where_a_removal_was_attempted() {
assert_eq!(
key_row_fate(false, true, true),
None,
"a custom-to-custom write drops nothing and keeps its key"
);
assert_eq!(key_row_fate(false, false, false), None);
assert_eq!(
key_row_fate(true, false, false),
None,
"there was nothing to drop"
);
assert_eq!(
key_row_fate(true, true, false).map(KeyRowFate::with_endpoint),
Some(", and its key was dropped with it")
);
assert_eq!(
key_row_fate(true, true, true).map(KeyRowFate::with_endpoint),
Some(", but its key row could not be removed and is left behind")
);
}
#[tokio::test]
#[serial_test::serial(config_persist, provider)]
async fn a_custom_endpoint_rewritten_to_another_one_keeps_its_key() {
let _guard = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_test_stores().await;
let _provider = crate::util::test::ProviderSnapshot::take();
let mut changed = Vec::new();
let mut warnings = Vec::new();
let first = stand_in_provider();
let second = stand_in_provider();
apply_provider(
&SetupArgs {
provider_endpoint: Some(first),
provider_endpoint_key: Some("k1".to_string()),
..SetupArgs::default()
},
&mut changed,
&mut warnings,
)
.await
.expect("the first custom endpoint");
assert_eq!(CONFIG.provider_endpoint_key().as_deref(), Some("k1"));
changed.clear();
apply_provider(
&SetupArgs {
provider_endpoint: Some(second),
..SetupArgs::default()
},
&mut changed,
&mut warnings,
)
.await
.expect("the second custom endpoint");
assert!(
!changed.iter().any(|line| line.contains("key row")),
"nothing tried to remove the key, and it is the live one: {changed:?}"
);
assert_eq!(
CONFIG.provider_endpoint_key().as_deref(),
Some("k1"),
"the key belongs to the custom endpoint that replaced the old one"
);
changed.clear();
apply_provider(
&SetupArgs {
clear_provider_endpoint: true,
..SetupArgs::default()
},
&mut changed,
&mut warnings,
)
.await
.expect("the clear");
assert!(
changed
.iter()
.any(|line| line.contains("its key was dropped with it")),
"got: {changed:?}"
);
assert_eq!(CONFIG.provider_endpoint_key().as_deref(), None);
crate::config_db::store()
.set_kv(CONFIG_KEY_PROVIDER_ENDPOINT_KEY, "leftover")
.await
.expect("a leftover key row");
let _ = CONFIG.set_string_field(CONFIG_KEY_PROVIDER_ENDPOINT_KEY, "leftover");
changed.clear();
apply_provider(
&SetupArgs {
clear_provider_endpoint: true,
..SetupArgs::default()
},
&mut changed,
&mut warnings,
)
.await
.expect("the clear of a leftover key row");
assert!(
changed
.iter()
.any(|line| line.contains("nothing changed about the endpoint")
&& line.contains("key row was removed")),
"got: {changed:?}"
);
assert_eq!(CONFIG.provider_endpoint_key().as_deref(), None);
}
#[test]
fn an_endpoint_too_long_for_one_read_back_is_refused() {
let prefix = "https://acme.invalid/";
let long = format!("{prefix}{}", "p".repeat(MAX_ENDPOINT_BYTES));
let refused = SetupArgs::parse(&json!({ "provider_endpoint": long }))
.unwrap_err()
.to_string();
assert!(
refused.contains(&format!("at most {MAX_ENDPOINT_BYTES} bytes"))
&& refused.contains("`reference` action"),
"the refusal says the limit and where it is written down: {refused}"
);
let longest = format!("{prefix}{}", "p".repeat(MAX_ENDPOINT_BYTES - prefix.len()));
assert_eq!(longest.len(), MAX_ENDPOINT_BYTES);
assert!(SetupArgs::parse(&json!({ "provider_endpoint": longest })).is_ok());
assert!(
crate::settings::reference().contains(&format!("capped at {MAX_ENDPOINT_BYTES} bytes")),
"the reference never states the custom endpoint's {MAX_ENDPOINT_BYTES} bytes"
);
}
#[test]
fn the_longest_endpoint_answer_fits_one_read_back() {
let prefix = "https://acme.invalid/";
let endpoint = format!("{prefix}{}", "p".repeat(MAX_ENDPOINT_BYTES - prefix.len()));
let report = Report {
changed: vec![format!("provider endpoint set to {endpoint}")],
warnings: vec![crate::config::warmup_warning(
&endpoint,
&anyhow::anyhow!(
"error sending request for url ({endpoint}/chat/completions): client error \
(Connect): dns error: failed to lookup address information: nodename nor \
servname provided, or not known"
),
)],
stopped: None,
provider: ProviderState::Custom {
key: false,
openrouter_key: false,
},
endpoint: endpoint.clone(),
bot_token_saved: false,
bot: None,
owner: OwnerBinding::None,
onboarding: OnboardingState::Init,
};
let answer =
crate::settings::answer_with_report("provider_endpoint", &endpoint, &report.render());
assert_eq!(
report.render().matches(&endpoint).count(),
ENDPOINT_MENTIONS - 1,
"the report's endpoint mentions are what the cap's derivation counts"
);
assert!(
answer.len() <= crate::settings::MAX_READ_BACK_BYTES,
"a provider write's answer must fit one read-back, got {} bytes",
answer.len()
);
let prose = answer.len() - ENDPOINT_MENTIONS * endpoint.len();
assert!(
prose <= REPORT_PROSE_BYTES,
"the report's prose is {prose} bytes against the {REPORT_PROSE_BYTES} its cap allows"
);
}
#[test]
fn argument_parsing_reads_the_terminal_flags() {
assert_eq!(SetupArgs::parse(&json!({})).unwrap(), SetupArgs::default());
let parsed = SetupArgs::parse(&json!({
"provider_key": " sk-or-v1-abc ",
"telegram_token": "123:abc",
"owner": "@someone",
}))
.unwrap();
assert_eq!(parsed.provider_key.as_deref(), Some("sk-or-v1-abc"));
assert_eq!(parsed.telegram_token.as_deref(), Some("123:abc"));
assert_eq!(parsed.owner.as_deref(), Some("@someone"));
assert!(!parsed.unbind_owner);
assert!(
SetupArgs::parse(&json!({
"provider_endpoint": "https://llm.example/v1",
"provider_endpoint_key": "local-key",
"unbind_owner": true,
}))
.unwrap()
.unbind_owner
);
let err = SetupArgs::parse(&json!({ "provider_key": " " }))
.unwrap_err()
.to_string();
assert!(
err.starts_with("usage:") && err.contains("provider_key"),
"{err}"
);
let err = SetupArgs::parse(&json!({ "provider_endpoint": " " }))
.unwrap_err()
.to_string();
assert!(err.contains("provider_endpoint"), "{err}");
assert!(
SetupArgs::parse(&json!({ "clear_provider_endpoint": true }))
.unwrap()
.clear_provider_endpoint
);
for args in [
json!({ "clear_provider_endpoint": true, "provider_endpoint": "https://llm.example/v1" }),
json!({ "clear_provider_endpoint": true, "provider_endpoint_key": "local-key" }),
] {
assert!(
SetupArgs::parse(&args).is_err(),
"a clear cannot be meant beside an endpoint or a key: {args}"
);
}
let err = SetupArgs::parse(&json!({ "provider_endpoint_key": "k" }))
.unwrap_err()
.to_string();
assert!(
err.starts_with("usage:") && err.contains("provider_endpoint_key"),
"{err}"
);
let err = SetupArgs::parse(&json!({
"provider_endpoint": "https://openrouter.ai/api/v1",
"provider_endpoint_key": "k",
}))
.unwrap_err()
.to_string();
assert!(
err.starts_with("usage:") && err.contains("provider_endpoint_key"),
"{err}"
);
let err = SetupArgs::parse(&json!({ "owner": "@a", "unbind_owner": true }))
.unwrap_err()
.to_string();
assert!(
err.starts_with("usage:") && err.contains("unbind_owner"),
"{err}"
);
let err = SetupArgs::parse(&json!({ "owner": "unknown" }))
.unwrap_err()
.to_string();
assert!(
err.starts_with("usage:") && err.contains("owner"),
"the owner's shape must be read with the other usage rules: {err}"
);
}
#[test]
fn a_stopped_run_reports_what_landed_before_it() {
let stopped = Report {
changed: vec!["provider endpoint set to https://llm.example/v1".to_string()],
stopped: Some("Telegram rejected the bot token — Unauthorized".to_string()),
..report()
};
let rendered = stopped.render();
assert!(rendered.contains("Stopped:"), "{rendered}");
assert!(
rendered.contains("Telegram rejected the bot token"),
"{rendered}"
);
assert!(
rendered.contains("provider endpoint set to"),
"the change that landed must still be reported: {rendered}"
);
assert!(
rendered.contains("The changes listed above were applied"),
"{rendered}"
);
let empty = Report {
stopped: Some("Telegram rejected the bot token — Unauthorized".to_string()),
..report()
}
.render();
assert!(
!empty.contains("changes listed above were applied"),
"{empty}"
);
assert!(
empty.contains("Nothing was written before this step"),
"{empty}"
);
}
#[test]
fn the_terminal_flags_are_exactly_what_the_parser_reads() {
let operation = crate::cli::FAMILIES
.iter()
.find(|family| family.tool == "mahbot_config")
.and_then(|family| match family.surface {
crate::cli::Surface::Operations(operations) => operations
.iter()
.find(|operation| operation.action == Some(ACTION)),
crate::cli::Surface::Standalone(_) => None,
})
.expect("the command line exposes 'mahbot config setup'");
let empty = SetupArgs::parse(&json!({})).unwrap();
let probes = [
("provider_key", json!("sk-or-v1-x"), json!({})),
(
"provider_endpoint",
json!("https://llm.example/v1"),
json!({}),
),
(
"provider_endpoint_key",
json!("local-key"),
json!({ "provider_endpoint": "https://llm.example/v1" }),
),
("clear_provider_endpoint", json!(true), json!({})),
("telegram_token", json!("1:A"), json!({})),
("owner", json!("12345"), json!({})),
("unbind_owner", json!(true), json!({})),
];
for (name, value, beside) in &probes {
let mut args = beside.clone();
args[*name] = value.clone();
let parsed = SetupArgs::parse(&args)
.unwrap_or_else(|e| panic!("the parser must read '{name}': {e}"));
assert_ne!(parsed, empty, "the parser ignores '{name}'");
}
let mut declared: Vec<&str> = operation.flags.iter().map(|flag| flag.arg).collect();
let mut read: Vec<&str> = probes.iter().map(|(name, _, _)| *name).collect();
declared.sort_unstable();
read.sort_unstable();
assert_eq!(
declared, read,
"the command line's flags must be exactly the arguments the parser reads"
);
}
#[test]
fn a_run_that_names_nothing_changes_nothing_and_still_advises() {
let rendered = report().render();
assert!(
rendered.contains("(nothing — this run changed nothing)"),
"{rendered}"
);
assert!(rendered.contains("provider: configured"), "{rendered}");
assert!(rendered.contains("owner: @owner"), "{rendered}");
assert!(
rendered.contains("a bot cannot start the conversation itself"),
"{rendered}"
);
assert!(!rendered.contains("Warnings:"), "{rendered}");
}
#[test]
fn the_report_names_the_media_gap_only_for_a_keyless_custom_endpoint() {
let keyless = Report {
endpoint: "https://llm.example/v1".to_string(),
provider: ProviderState::Custom {
key: false,
openrouter_key: false,
},
..report()
};
let rendered = keyless.render();
assert!(
rendered.contains("media generation and editing need an OpenRouter key"),
"{rendered}"
);
assert!(
rendered.contains("custom endpoint, keyless"),
"the state must say the endpoint is keyless: {rendered}"
);
let keyed = Report {
endpoint: "https://llm.example/v1".to_string(),
provider: ProviderState::Custom {
key: true,
openrouter_key: true,
},
..report()
};
assert!(
!keyed
.render()
.contains("media generation and editing need an OpenRouter key")
);
assert!(
!report()
.render()
.contains("media generation and editing need an OpenRouter key"),
"the default endpoint IS OpenRouter"
);
}
#[test]
fn an_unreadable_owner_is_not_reported_as_absent() {
let unreadable = Report {
owner: OwnerBinding::Unreadable("disk i/o error".to_string()),
..report()
}
.render();
assert!(
unreadable.contains("owner: could not be read back (disk i/o error)"),
"{unreadable}"
);
assert!(
!unreadable.contains("owner: no Telegram binding"),
"{unreadable}"
);
assert!(
!unreadable.contains("Bind your own Telegram account"),
"a failed read is not a missing binding: {unreadable}"
);
assert!(
unreadable.contains("Read the owner binding back"),
"{unreadable}"
);
}
#[test]
fn missing_pieces_each_name_their_own_command() {
let bare = Report {
provider: ProviderState::NotConfigured,
bot_token_saved: false,
owner: OwnerBinding::None,
..report()
};
let rendered = bare.render();
assert!(rendered.contains("provider: not configured"), "{rendered}");
assert!(
rendered.contains("mahbot config setup --provider-key @key.txt"),
"{rendered}"
);
assert!(
rendered.contains("mahbot config setup --telegram-token @token.txt"),
"{rendered}"
);
assert!(
rendered.contains("mahbot config setup --owner ./@yourname"),
"{rendered}"
);
let unchecked = Report {
bot: None,
..report()
};
assert!(
unchecked
.render()
.contains("a token is saved; its identity is checked only by a run that saves it"),
"{}",
unchecked.render()
);
}
#[test]
fn an_owner_binding_says_whether_it_still_needs_the_first_message() {
assert_eq!(owner_binding_line("123456"), "owner bound to id 123456");
let nickname = owner_binding_line("alice");
assert!(nickname.starts_with("owner bound to @alice"), "{nickname}");
assert!(
nickname.contains("confirmed at the first message"),
"{nickname}"
);
}
}