bctx 0.1.40

bctx CLI — intercept CLI commands and compress output for LLM coding agents
use anyhow::Result;
use cloud::client::auth::load_token;

pub fn handle(
    cloud: bool,
    open_browser: bool,
    port: u16,
    idle_secs: u64,
    serve: bool,
) -> Result<()> {
    if cloud {
        open_cloud(open_browser)
    } else if serve {
        crate::local_dashboard::serve(port, idle_secs)
    } else {
        crate::local_dashboard::start(port, idle_secs, open_browser)
    }
}

fn open_cloud(open_browser: bool) -> Result<()> {
    // If authenticated, open the web dashboard pre-logged in
    if let Some(token) = load_token() {
        let base = token.endpoint.trim_end_matches('/');
        // A one-time code, not the token: the URL ends up in history and access logs.
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;
        let code = match rt.block_on(cloud::client::auth::request_web_code(
            base,
            &token.access_token,
        )) {
            Ok(code) => code,
            Err(e) if e.is::<cloud::client::auth::LoginExpired>() => {
                println!("Your bctx login has expired. Run `bctx login`, then `bctx dashboard --cloud` again.");
                println!("Or sign in on the web:");
                println!("  {base}/");
                if open_browser {
                    let _ = open::that(format!("{base}/"));
                }
                return Ok(());
            }
            Err(e) => return Err(e),
        };
        let url = format!("{base}/?code={code}");
        println!("Opening dashboard at {base}/");
        if !open_browser || open::that(&url).is_err() {
            println!("Visit:");
            println!("  {url}");
        }
        return Ok(());
    }

    // Not logged in — open dashboard login page
    let url = "https://api.betterctx.com/";
    println!("Not logged in. Run `bctx login` first, or open the dashboard manually:");
    println!("  {url}");
    if open_browser {
        let _ = open::that(url);
    }
    Ok(())
}