bctx 0.1.38

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) -> Result<()> {
    if cloud {
        open_cloud(open_browser)
    } else {
        crate::local_dashboard::serve(port, 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 = rt.block_on(cloud::client::auth::request_web_code(
            base,
            &token.access_token,
        ))?;
        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(())
}