opentoken-cli 0.0.1

Configure Claude Code, Claude Desktop, Codex, OpenCode, OpenClaw, Hermes, pi and Atomcode for the OpenToken gateway in one command. OpenToken 一键接入 AI 模型。
//! 终端交互:Logo、提示、菜单选择、加载动画和结果行。

use std::future::Future;
use std::time::Duration;

use console::{style, Term};
use dialoguer::theme::ColorfulTheme;
use dialoguer::{Input, Password, Select};
use indicatif::{ProgressBar, ProgressStyle};
use opentoken_core::models::{API_NODES, CUSTOM_NODE, DEFAULT_BASE_URL};
use opentoken_core::test_connection::TestResult;
use opentoken_core::{mask_api_key, Context};
use unicode_width::UnicodeWidthStr;

pub type AnyResult<T> = Result<T, Box<dyn std::error::Error>>;

const LOGO_LINES: &[&str] = &[
    " ██████╗ ██████╗ ███████╗███╗   ██╗████████╗ ██████╗ ██╗  ██╗███████╗███╗   ██╗",
    "██╔═══██╗██╔══██╗██╔════╝████╗  ██║╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗  ██║",
    "██║   ██║██████╔╝█████╗  ██╔██╗ ██║   ██║   ██║   ██║█████╔╝ █████╗  ██╔██╗ ██║",
    "██║   ██║██╔═══╝ ██╔══╝  ██║╚██╗██║   ██║   ██║   ██║██╔═██╗ ██╔══╝  ██║╚██╗██║",
    "╚██████╔╝██║     ███████╗██║ ╚████║   ██║   ╚██████╔╝██║  ██╗███████╗██║ ╚████║",
    " ╚═════╝ ╚═╝     ╚══════╝╚═╝  ╚═══╝   ╚═╝    ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═══╝",
];

const SPINNER_FRAMES: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏", ""];

pub fn clear_screen() {
    let term = Term::stdout();
    if term.is_term() {
        let _ = term.clear_screen();
    }
}

pub fn print_logo() {
    let width = LOGO_LINES.iter().map(|l| l.width()).max().unwrap_or(0);
    let border = "═".repeat(width);
    println!();
    println!("{}", style(format!("╔{border}╗")).cyan());
    for line in LOGO_LINES {
        let padded = format!("{line}{}", " ".repeat(width - line.width()));
        println!("{}{}{}", style("║").cyan(), style(padded).white().bold(), style("║").cyan());
    }
    println!("{}", style(format!("╚{border}╝")).cyan());
    println!();
}

pub fn paint() {
    clear_screen();
    print_logo();
}

pub fn title(text: &str) {
    println!("{}", style(text).cyan().bold());
}

pub fn ok_line(text: &str) {
    println!("{}", style(format!("  ✓ {text}")).green());
}

/// `  ✓ <label> : <value>`
pub fn field(label: &str, value: &str) {
    println!("{}{value}", style(format!("  ✓ {label} : ")).green());
}

pub fn warn(text: &str) {
    println!("{}", style(format!("  ! {text}")).yellow());
}

pub fn yellow(text: &str) {
    println!("{}", style(text).yellow());
}

pub fn error(text: &str) {
    println!("{}", style(format!("  ✗ {text}")).red());
}

pub fn gray(text: &str) {
    println!("{}", style(text).dim());
}

pub fn gray_paren(text: &str) -> String {
    style(format!("({text})")).dim().to_string()
}

pub fn or_unset(value: &str) -> &str {
    if value.is_empty() {
        "未配置"
    } else {
        value
    }
}

pub fn masked_or_unset(key: &str) -> String {
    if key.is_empty() {
        "未配置".into()
    } else {
        mask_api_key(key)
    }
}

fn theme() -> ColorfulTheme {
    ColorfulTheme::default()
}

pub fn select(prompt: &str, items: &[String], default: usize) -> AnyResult<usize> {
    Ok(Select::with_theme(&theme()).with_prompt(prompt).items(items).default(default).max_length(15).interact()?)
}

pub fn input_text(prompt: &str, default: &str) -> AnyResult<String> {
    let theme = theme();
    let mut input = Input::<String>::with_theme(&theme).with_prompt(prompt).allow_empty(true);
    if !default.is_empty() {
        input = input.default(default.to_string());
    }
    Ok(input.interact_text()?.trim().to_string())
}

fn input_validated(prompt: &str, default: &str, check: fn(&str) -> Result<(), &'static str>) -> AnyResult<String> {
    let theme = theme();
    let mut input = Input::<String>::with_theme(&theme)
        .with_prompt(prompt)
        .validate_with(move |s: &String| check(s.trim()));
    if !default.is_empty() {
        input = input.default(default.to_string());
    }
    Ok(input.interact_text()?.trim().to_string())
}

pub fn input_model(prompt: &str, default: &str) -> AnyResult<String> {
    input_validated(prompt, default, |s| if s.is_empty() { Err("请输入模型 ID") } else { Ok(()) })
}

pub fn input_claude_model(prompt: &str, default: &str) -> AnyResult<String> {
    input_validated(prompt, default, |s| {
        if opentoken_core::clients::desktop::is_claude_id(s) {
            Ok(())
        } else {
            Err("模型 ID 必须以 claude- 开头")
        }
    })
}

pub fn input_url(prompt: &str, default: &str) -> AnyResult<String> {
    input_validated(prompt, default, |s| if s.starts_with("http") { Ok(()) } else { Err("请输入合法的 URL(以 http 开头)") })
}

/// 读取 API Key;留空返回 None。
pub fn read_api_key(prompt: &str) -> AnyResult<Option<String>> {
    let key = Password::with_theme(&theme()).with_prompt(prompt).allow_empty_password(true).interact()?;
    let key = key.trim().to_string();
    if key.is_empty() {
        gray("  (留空,保持不变)");
        Ok(None)
    } else {
        ok_line("API Key 已更新");
        Ok(Some(key))
    }
}

pub fn mode_item(ctx: &Context) -> String {
    format!("保存方式({})", ctx.mode_label())
}

pub fn choose_config_mode(ctx: &mut Context) -> AnyResult<()> {
    let items = vec!["新增 opentoken 配置(默认)".to_string(), "覆盖本地配置".to_string()];
    ctx.overwrite = select("请选择保存方式:", &items, usize::from(ctx.overwrite))? == 1;
    Ok(())
}

pub fn choose_base_url(current: &str) -> AnyResult<String> {
    let items: Vec<String> = API_NODES
        .iter()
        .map(|n| if n.value == current { style(format!("► {}", n.name)).green().to_string() } else { format!("  {}", n.name) })
        .collect();
    let default = API_NODES.iter().position(|n| n.value == current).unwrap_or(0);
    let selected = API_NODES[select("请选择 Base URL:", &items, default)?].value;
    let url = if selected == CUSTOM_NODE {
        let initial = if current.is_empty() || current == CUSTOM_NODE { DEFAULT_BASE_URL } else { current };
        input_url("请输入自定义 Base URL:", initial)?
    } else {
        selected.to_string()
    };
    ok_line(&format!("Base URL 已更新:{url}"));
    Ok(url)
}

/// 从模型列表中选择;当前模型不在列表中时放到最前。返回 (选择结果, 展示的列表),选择“手动输入”时结果为 None。
pub fn pick_from_list(
    models: &[String],
    current: &str,
    preferred: Option<&str>,
    prompt: &str,
) -> AnyResult<(Option<String>, Vec<String>)> {
    let mut ids = models.to_vec();
    if !current.is_empty() && !ids.iter().any(|id| id == current) {
        ids.insert(0, current.to_string());
    }
    let mut items: Vec<String> = ids
        .iter()
        .map(|id| if id == current { style(format!("► {id}")).green().to_string() } else { format!("  {id}") })
        .collect();
    items.push("  手动输入其他模型 ID…".into());
    let wanted = if current.is_empty() { preferred.unwrap_or("") } else { current };
    let default = ids.iter().position(|id| id == wanted).unwrap_or(0);
    let index = select(prompt, &items, default)?;
    Ok((ids.get(index).cloned(), ids))
}

pub async fn with_spinner<F: Future<Output = TestResult>>(label: &str, fut: F) -> TestResult {
    let pb = ProgressBar::new_spinner();
    if let Ok(s) = ProgressStyle::with_template("  {spinner:.cyan} {msg:.cyan}") {
        pb.set_style(s.tick_strings(SPINNER_FRAMES));
    }
    pb.set_message(format!("{label}  测试中..."));
    pb.enable_steady_tick(Duration::from_millis(80));
    let result = fut.await;
    pb.finish_and_clear();
    result
}

pub fn print_test(label: &str, result: &TestResult) {
    if result.ok {
        ok_line(&format!("{label}  连接成功  {}ms", result.latency_ms.unwrap_or(0)));
    } else {
        error(&format!("{label}  {}", result.error.as_deref().unwrap_or("未知错误")));
    }
}