use crate::ChannelMessage;
use crate::config::{
CONFIG_KEY_PROVIDER_ENDPOINT, CONFIG_KEY_PROVIDER_ENDPOINT_KEY, CONFIG_KEY_PROVIDER_KEY,
};
use std::sync::atomic::{AtomicBool, Ordering};
static KICKOFF_FIRED: AtomicBool = AtomicBool::new(false);
static GREETING_GUIDE_PENDING: AtomicBool = AtomicBool::new(false);
pub fn mark_greeting_guide_pending() {
GREETING_GUIDE_PENDING.store(true, Ordering::SeqCst);
}
pub fn take_greeting_guide_pending() -> bool {
GREETING_GUIDE_PENDING.swap(false, Ordering::SeqCst)
}
#[derive(Debug)]
pub enum ProviderInput {
OpenRouterKey(String),
CustomEndpoint { url: String, key: Option<String> },
Invalid,
}
#[must_use]
pub fn parse_provider_input(raw: &str) -> ProviderInput {
let trimmed = raw.trim();
let lines: Vec<&str> = trimmed
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.collect();
if lines.len() >= 2 && is_http_url(lines[0]) {
let key = lines[1].to_string();
if crate::config::is_default_endpoint(lines[0]) && key.contains("sk-or-v1-") {
return ProviderInput::OpenRouterKey(key);
}
return custom_endpoint(lines[0], Some(key));
}
if lines.len() == 1 && is_http_url(lines[0]) {
return custom_endpoint(lines[0], None);
}
if let Some(key_line) = lines.iter().find(|l| l.contains("sk-or-v1-")) {
return ProviderInput::OpenRouterKey(key_line.to_string());
}
ProviderInput::Invalid
}
fn custom_endpoint(url_line: &str, key: Option<String>) -> ProviderInput {
if crate::config::is_default_endpoint(url_line) {
return ProviderInput::Invalid;
}
if !is_clean_url_line(url_line) {
return ProviderInput::Invalid;
}
ProviderInput::CustomEndpoint {
url: url_line.to_string(),
key,
}
}
fn is_http_url(s: &str) -> bool {
let lower = s.to_ascii_lowercase();
lower.starts_with("http://") || lower.starts_with("https://")
}
fn is_clean_url_line(s: &str) -> bool {
s.split_whitespace().count() == 1
}
pub async fn persist_provider_input(input: &ProviderInput) -> anyhow::Result<()> {
match input {
ProviderInput::OpenRouterKey(key) => {
crate::config::persist_settled_string_field(CONFIG_KEY_PROVIDER_KEY, key).await?;
}
ProviderInput::CustomEndpoint { url, key } => {
if let Some(k) = key {
crate::config::persist_settled_string_field(CONFIG_KEY_PROVIDER_ENDPOINT_KEY, k)
.await?;
}
crate::config::persist_settled_string_field(CONFIG_KEY_PROVIDER_ENDPOINT, url).await?;
}
ProviderInput::Invalid => anyhow::bail!("invalid provider input"),
}
Ok(())
}
#[must_use]
pub fn intro_messages() -> [&'static str; 2] {
[
"Welcome to MahBot! Before we start, I need an LLM provider to power your agents.",
"Enter your OpenRouter API key (it starts with `sk-or-v1-`), or paste a custom endpoint. For a custom endpoint, put the URL on the FIRST line and your API key on the SECOND line (the key is optional).",
]
}
#[must_use]
pub fn success_message() -> &'static str {
"Provider configured! Setting up your admin Assistant — one moment."
}
#[must_use]
pub fn invalid_message() -> &'static str {
"That doesn't look right. Enter an OpenRouter key (starts with `sk-or-v1-`) or a custom endpoint URL (first line) + optional API key (second line)."
}
pub async fn kickoff_onboarding(user_name: &str) -> anyhow::Result<()> {
use crate::config::OnboardingState;
if crate::config::CONFIG.onboarding_stage() != OnboardingState::Init {
return Ok(());
}
if !crate::config::provider_configured() {
return Ok(());
}
if !crate::users::is_admin(user_name).await {
return Ok(());
}
if KICKOFF_FIRED.swap(true, Ordering::SeqCst) {
return Ok(());
}
if let Err(e) = crate::config::persist_settled_string_field(
crate::config::CONFIG_KEY_ONBOARDING_STATE,
OnboardingState::Finished.as_str(),
)
.await
{
KICKOFF_FIRED.store(false, Ordering::SeqCst);
return Err(e);
}
mark_greeting_guide_pending();
let msg = ChannelMessage {
user_name: user_name.to_string(),
reply_target: user_name.to_string(),
content: "hi mah bot".to_string(),
channel: "gui".to_string(),
workspace: crate::users::personal_workspace_name(user_name),
..Default::default()
};
if let Some(tx) = crate::GUI_MESSAGE_TX.get()
&& let Err(e) = tx.send(msg)
{
tracing::error!("kickoff: failed to send 'hi mah bot' via GUI_MESSAGE_TX: {e}");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn provider_input_is_read_as_the_one_form_it_is() {
#[derive(Debug, PartialEq, Eq)]
enum Read {
Key(String),
Endpoint { url: String, key: Option<String> },
Invalid,
}
let key = |key: &str| Read::Key(key.to_string());
let endpoint = |url: &str, name: Option<&str>| Read::Endpoint {
url: url.to_string(),
key: name.map(str::to_string),
};
let read = |raw: &str| match parse_provider_input(raw) {
ProviderInput::OpenRouterKey(key) => Read::Key(key),
ProviderInput::CustomEndpoint { url, key } => Read::Endpoint { url, key },
ProviderInput::Invalid => Read::Invalid,
};
for (raw, expected) in [
(" sk-or-v1-abc123def456 ", key("sk-or-v1-abc123def456")),
(
"https://openrouter.ai/api/v1\nsk-or-v1-abc123def456",
key("sk-or-v1-abc123def456"),
),
(
"sk-or-v1-abc123def456\nhttps://custom.example/v1",
key("sk-or-v1-abc123def456"),
),
(
"https://ollama.local:11434/v1",
endpoint("https://ollama.local:11434/v1", None),
),
(
"http://localhost:8080/v1\nsk-local-123",
endpoint("http://localhost:8080/v1", Some("sk-local-123")),
),
("https://openrouter.ai/api/v1", Read::Invalid),
("https://openrouter.ai/api/v1\nmy-random-key", Read::Invalid),
("https://custom.example/v1 sk-local-123", Read::Invalid),
("https://custom.example/v1 extra", Read::Invalid),
("just some chat text", Read::Invalid),
] {
assert_eq!(read(raw), expected, "entry {raw:?}");
}
}
}