Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(cli): Tokamak sign-in for the agent CLI

Akarshan Biswas4787ead75e36
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rs
index 0acccb4b1..5d6331b77 100644
--- a/src-tauri/src/bin/jan.rs
+++ b/src-tauri/src/bin/jan.rs
@@ -120,14 +120,17 @@ enum Commands {
#[command(subcommand)]
cmd: CliCommands,
},
- /// Manage provider credentials in ~/.jan/config.toml (used by the TUI and CLI)
+ /// Sign in to Tokamak and save the API key to ~/.jan/config.toml
#[command(display_order = 2)]
+ Login,
+ /// Manage provider credentials in ~/.jan/config.toml (used by the TUI and CLI)
+ #[command(display_order = 3)]
Config {
#[command(subcommand)]
cmd: AgentConfigCommands,
},
/// Update this binary to the latest build of the channel it was built for
- #[command(display_order = 3)]
+ #[command(display_order = 4)]
Update {
/// Report whether an update exists without installing it
#[arg(long)]
@@ -395,6 +398,12 @@ async fn main() {
match command {
Commands::Cli { cmd } => handle_cli(cmd).await,
+ Commands::Login => {
+ if let Err(e) = app_lib::core::cli::login::run_login().await {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ }
Commands::Config { cmd } => {
if let Err(e) = handle_agent_config(cmd) {
eprintln!("Error: {e}");
@@ -647,4 +656,11 @@ mod tests {
));
assert!(Cli::try_parse_from(["jan", "update", "--check", "--force"]).is_err());
}
+
+ #[test]
+ fn login_command_parses_and_takes_no_args() {
+ let cli = Cli::parse_from(["jan", "login"]);
+ assert!(matches!(cli.command, Some(Commands::Login)));
+ assert!(Cli::try_parse_from(["jan", "login", "sk-key"]).is_err());
+ }
}
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index c04e060c7..72e3a4232 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -191,6 +191,27 @@ pub(crate) fn set_provider(name: &str, update: ProviderUpdate) -> Result<PathBuf
write_raw(&config)
}
+/// Point `default_model` at `model` unless the user already chose one. Returns
+/// `true` when it was written. Used by sign-in flows: the first provider a user
+/// connects should become runnable without a second config step, but an explicit
+/// choice must never be overwritten.
+pub(crate) fn set_default_model_if_unset(model: &str) -> Result<bool, String> {
+ if model.trim().is_empty() {
+ return Ok(false);
+ }
+ let mut config = load_raw()?;
+ if config
+ .default_model
+ .as_deref()
+ .is_some_and(|m| !m.trim().is_empty())
+ {
+ return Ok(false);
+ }
+ config.default_model = Some(model.to_string());
+ write_raw(&config)?;
+ Ok(true)
+}
+
/// Remove a provider entry from `~/.jan/config.toml`. Returns `true` if the
/// provider existed and was removed, `false` if it was already absent.
pub(crate) fn remove_provider(name: &str) -> Result<bool, String> {
@@ -215,31 +236,35 @@ pub(crate) fn ensure_global_config() -> Result<PathBuf, String> {
Ok(path)
}
+/// Redirect `HOME` to a scratch dir for the duration of `f`. Every test that
+/// touches `~/.jan` must go through this one helper: `HOME` is process-wide, so
+/// a second lock elsewhere would let those tests race each other.
#[cfg(test)]
-mod tests {
- use super::*;
+pub(crate) fn with_temp_home<T>(f: impl FnOnce(&std::path::Path) -> T) -> T {
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Mutex;
- // HOME is process-wide; serialize tests that mutate it.
static ENV_LOCK: Mutex<()> = Mutex::new(());
static COUNTER: AtomicU32 = AtomicU32::new(0);
- fn with_temp_home<T>(f: impl FnOnce(&std::path::Path) -> T) -> T {
- let _guard = ENV_LOCK.lock().unwrap();
- let n = COUNTER.fetch_add(1, Ordering::SeqCst);
- let home = std::env::temp_dir().join(format!("jan_global_cfg_test_{n}"));
- std::fs::create_dir_all(&home).unwrap();
- let prev = std::env::var_os("HOME");
- std::env::set_var("HOME", &home);
- let result = f(&home);
- match prev {
- Some(p) => std::env::set_var("HOME", p),
- None => std::env::remove_var("HOME"),
- }
- let _ = std::fs::remove_dir_all(&home);
- result
+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);
+ let home = std::env::temp_dir().join(format!("jan_global_cfg_test_{n}"));
+ std::fs::create_dir_all(&home).unwrap();
+ let prev = std::env::var_os("HOME");
+ std::env::set_var("HOME", &home);
+ let result = f(&home);
+ match prev {
+ Some(p) => std::env::set_var("HOME", p),
+ None => std::env::remove_var("HOME"),
}
+ let _ = std::fs::remove_dir_all(&home);
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
#[test]
fn missing_file_yields_empty_map() {
@@ -398,6 +423,31 @@ models = ["gpt-4o"]
});
}
+ #[test]
+ fn default_model_is_set_once_and_never_overwritten() {
+ with_temp_home(|_| {
+ assert!(set_default_model_if_unset("m1").expect("set"));
+ assert_eq!(default_model().expect("read").as_deref(), Some("m1"));
+ assert!(!set_default_model_if_unset("m2").expect("set again"));
+ assert_eq!(default_model().expect("read").as_deref(), Some("m1"));
+ });
+ }
+
+ #[test]
+ fn default_model_set_keeps_existing_providers_and_rejects_blank() {
+ with_temp_home(|_| {
+ set_provider(
+ "tokamak",
+ ProviderUpdate { api_key: Some("tk".into()), ..Default::default() },
+ )
+ .unwrap();
+ assert!(!set_default_model_if_unset(" ").expect("blank"));
+ assert!(set_default_model_if_unset("m1").expect("set"));
+ let configs = load_global_config().expect("load");
+ assert_eq!(configs.get("tokamak").unwrap().api_key.as_deref(), Some("tk"));
+ });
+ }
+
#[test]
fn remove_provider_reports_presence() {
with_temp_home(|_| {
diff --git a/src-tauri/src/core/cli/login.rs b/src-tauri/src/core/cli/login.rs
new file mode 100644
index 000000000..012381546
--- /dev/null
+++ b/src-tauri/src/core/cli/login.rs
@@ -0,0 +1,199 @@
+//! Terminal sign-in UX for Tokamak: the plain-stdout counterpart to the TUI's
+//! `/login` overlay. Both drive [`super::tokamak`]; only presentation differs.
+//!
+//! This runs *before* the TUI starts, which is what makes a fresh install work
+//! at all: with no provider configured, session setup fails on "no model
+//! specified" before a single frame is drawn, so the key has to be collected
+//! here.
+
+use std::io::IsTerminal;
+
+use super::tokamak;
+
+/// Max key prompts before giving up, so a wrong paste is retryable but a script
+/// piping garbage at us can't loop forever.
+const MAX_ATTEMPTS: usize = 3;
+
+/// Guarantee a runnable provider before the agent starts, signing the user in if
+/// there is none. No-op when anything usable is already configured, so the
+/// startup cost on an existing install is one config read.
+///
+/// Non-interactive (piped stdin) fails with instructions instead of prompting:
+/// there is no one there to paste a key.
+pub async fn ensure_provider_configured(
+ project_root: Option<&std::path::Path>,
+) -> Result<(), String> {
+ if super::providers::has_usable_provider(project_root) {
+ return Ok(());
+ }
+ if !std::io::stdin().is_terminal() {
+ return Err(headless_message());
+ }
+ println!("No AI provider is configured yet.");
+ run_login().await
+}
+
+/// Sign in to Tokamak from a plain terminal: point the user at the API-keys
+/// page, read the key they paste (hidden), verify it, and persist it.
+///
+/// A piped stdin (`echo $KEY | jan login`) is verified directly instead: there
+/// is no browser to open and no prompt to answer, so scripting it is the only
+/// sensible reading.
+pub async fn run_login() -> Result<(), String> {
+ if !std::io::stdin().is_terminal() {
+ return login_from_stdin().await;
+ }
+ println!();
+ println!("Sign in to Tokamak and create an API key:");
+ println!(" {}", tokamak::API_KEYS_URL);
+ match tokamak::open_api_keys_page() {
+ Ok(()) => println!(" (opening that page in your browser)"),
+ Err(e) => println!(" (open that URL yourself: {e})"),
+ }
+ println!();
+
+ let mut last_error = None;
+ for attempt in 1..=MAX_ATTEMPTS {
+ let entered = match prompt_for_key().await? {
+ Some(key) => key,
+ // Ctrl-C / Ctrl-D at the prompt: the user chose not to sign in.
+ None => return Err(cancelled_message()),
+ };
+ // Validate before announcing a request, so an empty line (Ctrl-D) or a
+ // mis-paste doesn't read as a rejection by Tokamak.
+ let result = match tokamak::sanitize_key(&entered) {
+ Ok(key) => {
+ println!("Verifying...");
+ tokamak::login(&key).await
+ }
+ Err(e) => Err(e),
+ };
+ match result {
+ Ok(login) => {
+ report(&login);
+ return Ok(());
+ }
+ Err(e) => {
+ if attempt < MAX_ATTEMPTS {
+ eprintln!("{e}");
+ println!();
+ }
+ last_error = Some(e);
+ }
+ }
+ }
+ Err(last_error.unwrap_or_else(|| "sign-in failed".to_string()))
+}
+
+/// Verify a key piped in on stdin. Reports to stdout exactly like the
+/// interactive path so a script's log shows what changed.
+async fn login_from_stdin() -> Result<(), String> {
+ let mut piped = String::new();
+ std::io::Read::read_to_string(&mut std::io::stdin(), &mut piped)
+ .map_err(|e| format!("could not read the API key from stdin: {e}"))?;
+ if piped.trim().is_empty() {
+ return Err(piped_empty_message());
+ }
+ let login = tokamak::login(&piped).await?;
+ report(&login);
+ Ok(())
+}
+
+/// Read the key with echo disabled. `None` means the user interrupted the
+/// prompt. Runs on a blocking thread: `dialoguer` owns the terminal while it
+/// waits, which must not stall the async runtime.
+async fn prompt_for_key() -> Result<Option<String>, String> {
+ tokio::task::spawn_blocking(|| {
+ match dialoguer::Password::new()
+ .with_prompt("Paste your Tokamak API key")
+ .allow_empty_password(true)
+ .interact()
+ {
+ Ok(key) => Ok(Some(key)),
+ Err(e) if is_interrupted(&e) => Ok(None),
+ Err(e) => Err(format!("could not read the API key: {e}")),
+ }
+ })
+ .await
+ .map_err(|e| format!("key prompt failed: {e}"))?
+}
+
+fn is_interrupted(e: &dialoguer::Error) -> bool {
+ let dialoguer::Error::IO(io) = e;
+ io.kind() == std::io::ErrorKind::Interrupted
+}
+
+/// Why we stopped when there is nobody at the keyboard to paste a key.
+fn headless_message() -> String {
+ "no AI provider is configured. Run `jan login` to sign in to Tokamak, or set one manually:\n \
+ jan config set --provider <id> --api-key <key> --base-url <url>\nA key can also be passed \
+ per run with --api-key or $JAN_API_KEY."
+ .to_string()
+}
+
+/// `jan login` with nothing on a piped stdin: say how to feed it one, rather
+/// than repeating "run `jan login`" at someone who just did.
+fn piped_empty_message() -> String {
+ format!(
+ "no API key on stdin. Either run `jan login` from a terminal, pipe the key in:\n echo \
+ $TOKAMAK_API_KEY | jan login\nor set it directly:\n jan config set --provider {} \
+ --api-key <key> --base-url {}",
+ tokamak::PROVIDER,
+ tokamak::BASE_URL
+ )
+}
+
+fn cancelled_message() -> String {
+ "sign-in cancelled. Run `jan login` when you have a key, or configure a provider manually \
+ with `jan config set`.\nAlready running a model locally? Point Jan at the desktop app's API \
+ server:\n jan config set --provider jan --base-url http://localhost:1337/v1 --model <model>"
+ .to_string()
+}
+
+fn report(login: &tokamak::Login) {
+ println!();
+ match login.models.len() {
+ 0 => println!(
+ "Signed in to Tokamak, but the account exposes no models yet. Pick one with /model \
+ once it does."
+ ),
+ 1 => println!("Signed in to Tokamak - 1 model available."),
+ n => println!("Signed in to Tokamak - {n} models available."),
+ }
+ println!(" key saved to {}", login.config_path.display());
+ if let Some(model) = &login.default_model {
+ println!(" default model: {model}");
+ }
+ println!();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_dead_end_points_at_a_way_forward() {
+ for message in [
+ cancelled_message(),
+ headless_message(),
+ piped_empty_message(),
+ ] {
+ assert!(message.contains("jan login"), "{message}");
+ assert!(message.contains("jan config set"), "{message}");
+ }
+ // The piped variant must not tell the user to re-run what just failed as
+ // if nothing else were possible.
+ assert!(piped_empty_message().contains("| jan login"));
+ }
+
+ #[test]
+ fn report_survives_every_model_count() {
+ for models in [Vec::new(), vec!["m".to_string()], vec!["a".into(), "b".into()]] {
+ report(&tokamak::Login {
+ models,
+ config_path: std::path::PathBuf::from("/tmp/config.toml"),
+ default_model: Some("a".to_string()),
+ });
+ }
+ }
+}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index dc74895e0..98017865d 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -2,9 +2,11 @@
//!
//! This module is only compiled when the `cli` feature is enabled.
+pub mod login;
pub mod mcp;
pub mod providers;
mod path_refs;
+pub mod tokamak;
mod tui;
pub mod updater;
@@ -644,7 +646,7 @@ fn prepare_agent_session(
.or_else(|| crate::core::agent::global_config::default_model().ok().flatten())
.or_else(|| crate::core::cli::providers::desktop_selection().model)
.ok_or_else(|| {
- "no model specified: pass --model, set [agent].model in agent.toml, set default_model in ~/.jan/config.toml, or select a model in the desktop app"
+ "no model specified: run `jan login` to sign in to Tokamak, or pass --model, set [agent].model in agent.toml, set default_model in ~/.jan/config.toml, or select a model in the desktop app"
.to_string()
})?;
let max_turns = max_turns_override
@@ -909,10 +911,16 @@ pub async fn cli_agent_ui(
plan: bool,
resume: Option<ResumeTarget>,
) -> Result<(), String> {
+ let project_root = resolve_project_root(project);
+ // Fresh install: sign in before session setup, which would otherwise fail on
+ // "no model specified" with nothing configured. Skipped the moment any
+ // provider is usable, and bypassed entirely by an explicit --api-key/env key.
+ if overrides.api_key.is_none() {
+ login::ensure_provider_configured(Some(&project_root)).await?;
+ }
let session = prepare_agent_session(project, model, max_turns, overrides, yolo, plan)?;
// TUI threads persist under the project's .jan/agent dir, separate from the
// desktop store, so continuing here never mutates desktop threads.
- let project_root = resolve_project_root(project);
let agent_dir = agent_dir_for(&project_root);
tui::run(session, agent_dir, project_root, task, images, resume).await
}
diff --git a/src-tauri/src/core/cli/providers.rs b/src-tauri/src/core/cli/providers.rs
index 154e5c722..d6b4efa58 100644
--- a/src-tauri/src/core/cli/providers.rs
+++ b/src-tauri/src/core/cli/providers.rs
@@ -114,6 +114,49 @@ pub fn is_cli_reachable(config: &ProviderConfig) -> bool {
config.base_url.as_deref().is_some_and(|u| !u.is_empty())
}
+/// Whether this install can run a turn at all: some provider is reachable and
+/// either credentialed or local (a self-hosted endpoint - typically the desktop
+/// app's API server - needs no key). `false` is the fresh-install state that
+/// triggers the sign-in flow. A remote entry with no key does not count: the
+/// request would only fail later with a 401.
+pub fn has_usable_provider(project_root: Option<&std::path::Path>) -> bool {
+ let overrides = ProviderOverrides::default().with_env();
+ match load_provider_configs(project_root, &overrides) {
+ Ok(configs) => configs.values().any(is_usable),
+ Err(e) => {
+ log::warn!("could not load provider configs: {e}");
+ false
+ }
+ }
+}
+
+fn is_usable(config: &ProviderConfig) -> bool {
+ if !is_cli_reachable(config) {
+ return false;
+ }
+ config.api_key.is_some()
+ || !config.api_keys.is_empty()
+ || config.base_url.as_deref().is_some_and(is_loopback_url)
+}
+
+/// Whether a base URL points at this machine, where an API key is usually not
+/// required. Host-only match (no DNS): anything else is treated as remote.
+fn is_loopback_url(url: &str) -> bool {
+ let authority = url
+ .split_once("://")
+ .map(|(_, rest)| rest)
+ .unwrap_or(url)
+ .split('/')
+ .next()
+ .unwrap_or("");
+ // Bracketed IPv6 keeps its colons; everything else splits off the port.
+ let host = match authority.strip_prefix('[') {
+ Some(rest) => rest.split(']').next().unwrap_or(""),
+ None => authority.split(':').next().unwrap_or(""),
+ };
+ matches!(host, "localhost" | "127.0.0.1" | "0.0.0.0" | "::1")
+}
+
/// `(provider, model_id)` pairs the CLI can actually run, sorted by provider
/// then model.
pub fn reachable_models(configs: &HashMap<String, ProviderConfig>) -> Vec<(String, String)> {
@@ -550,6 +593,47 @@ mod tests {
assert!(!is_cli_reachable(&blank));
}
+ #[test]
+ fn usable_requires_a_key_only_for_remote_upstreams() {
+ let keyed_remote = ProviderConfig {
+ provider: "tokamak".into(),
+ base_url: Some("https://api.tokamak.sh/v1".into()),
+ api_key: Some("tk".into()),
+ ..Default::default()
+ };
+ let keyless_remote = ProviderConfig {
+ provider: "openai".into(),
+ base_url: Some("https://api.openai.com/v1".into()),
+ ..Default::default()
+ };
+ let keyless_local = ProviderConfig {
+ provider: "jan".into(),
+ base_url: Some("http://localhost:1337/v1".into()),
+ ..Default::default()
+ };
+ let engine = ProviderConfig {
+ provider: "llamacpp".into(),
+ base_url: None,
+ api_key: Some("k".into()),
+ ..Default::default()
+ };
+ assert!(is_usable(&keyed_remote));
+ assert!(!is_usable(&keyless_remote));
+ assert!(is_usable(&keyless_local));
+ assert!(!is_usable(&engine));
+ }
+
+ #[test]
+ fn loopback_detection_ignores_ports_paths_and_lookalike_hosts() {
+ assert!(is_loopback_url("http://127.0.0.1:1337/v1"));
+ assert!(is_loopback_url("http://localhost/v1"));
+ assert!(is_loopback_url("http://[::1]:1337/v1"));
+ assert!(is_loopback_url("localhost:1337"));
+ assert!(!is_loopback_url("https://localhost.evil.com/v1"));
+ assert!(!is_loopback_url("https://api.tokamak.sh/v1"));
+ assert!(!is_loopback_url(""));
+ }
+
#[test]
fn reachable_models_skips_local_engine_providers() {
let mut configs = HashMap::new();
diff --git a/src-tauri/src/core/cli/tokamak.rs b/src-tauri/src/core/cli/tokamak.rs
new file mode 100644
index 000000000..7b304ece8
--- /dev/null
+++ b/src-tauri/src/core/cli/tokamak.rs
@@ -0,0 +1,324 @@
+//! Tokamak sign-in for the headless CLI.
+//!
+//! Tokamak is an ordinary OpenAI-compatible upstream as far as the agent is
+//! concerned (Bearer key + `{base_url}/chat/completions`), so "login" is just:
+//! send the user to the web UI to mint an API key, verify what they paste
+//! against `GET /v1/models`, and persist it as a provider entry in
+//! `~/.jan/config.toml`. No OAuth, no callback server, no browser required --
+//! the key can always be pasted from another machine.
+//!
+//! Presentation lives in the callers ([`super::mod`] for the fresh-install
+//! prompt, [`super::tui`] for `/login`); this module is UI-free so both share
+//! one implementation.
+
+use std::path::PathBuf;
+use std::time::Duration;
+
+use crate::core::agent::global_config::{set_default_model_if_unset, set_provider, ProviderUpdate};
+
+/// Provider id this login writes to in `~/.jan/config.toml`.
+pub const PROVIDER: &str = "tokamak";
+/// OpenAI-compatible API root. Persisted (not hardcoded at call sites) so a user
+/// can retarget it by editing the config afterwards.
+pub const BASE_URL: &str = "https://api.tokamak.sh/v1";
+/// Where the user signs in and mints a key.
+pub const API_KEYS_URL: &str = "https://tokamak.sh/settings/api-keys";
+
+const VERIFY_TIMEOUT: Duration = Duration::from_secs(20);
+
+/// What a successful sign-in changed, for the caller to report.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Login {
+ pub models: Vec<String>,
+ pub config_path: PathBuf,
+ /// The model written to `default_model`, or `None` when the user already had one.
+ pub default_model: Option<String>,
+}
+
+/// Trim a pasted key and reject anything that isn't plausibly one. Terminals and
+/// clipboards routinely add surrounding whitespace or a trailing newline; a key
+/// with interior whitespace is a mis-paste (partial selection, wrapped line)
+/// that would otherwise fail as a confusing 401.
+pub fn sanitize_key(raw: &str) -> Result<String, String> {
+ let key = raw.trim();
+ if key.is_empty() {
+ return Err("no API key entered".to_string());
+ }
+ if key.chars().any(char::is_whitespace) {
+ return Err("that key contains spaces or line breaks - copy it again".to_string());
+ }
+ Ok(key.to_string())
+}
+
+/// Verify `api_key` against Tokamak and return the model ids it grants access
+/// to. An empty list is a valid answer (the account has no models yet), so the
+/// caller decides whether that is usable.
+pub async fn verify_key(api_key: &str) -> Result<Vec<String>, String> {
+ let client = reqwest::Client::builder()
+ .timeout(VERIFY_TIMEOUT)
+ .build()
+ .map_err(|e| e.to_string())?;
+ let response = client
+ .get(format!("{BASE_URL}/models"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .map_err(|e| format!("could not reach {BASE_URL}: {e}"))?;
+
+ let status = response.status();
+ let body = response.text().await.unwrap_or_default();
+ if !status.is_success() {
+ return Err(describe_failure(status.as_u16(), &body));
+ }
+ let parsed: serde_json::Value = serde_json::from_str(&body)
+ .map_err(|e| format!("Tokamak returned a response we could not read: {e}"))?;
+ Ok(parse_models(&parsed))
+}
+
+/// Verify the key, then persist it as the `tokamak` provider. Nothing is written
+/// when verification fails, so a typo never leaves a broken entry behind.
+pub async fn login(api_key: &str) -> Result<Login, String> {
+ let api_key = sanitize_key(api_key)?;
+ let models = verify_key(&api_key).await?;
+ persist(&api_key, models)
+}
+
+/// Write the verified key + model list to `~/.jan/config.toml`, adopting the
+/// first model as `default_model` when the user has none (otherwise the agent
+/// would still start with "no model specified" right after signing in).
+fn persist(api_key: &str, models: Vec<String>) -> Result<Login, String> {
+ let config_path = set_provider(
+ PROVIDER,
+ ProviderUpdate {
+ api_key: Some(api_key.to_string()),
+ base_url: Some(BASE_URL.to_string()),
+ models: Some(models.clone()),
+ api_type: None,
+ },
+ )?;
+ let default_model = match models.first() {
+ Some(first) if set_default_model_if_unset(first)? => Some(first.clone()),
+ _ => None,
+ };
+ Ok(Login {
+ models,
+ config_path,
+ default_model,
+ })
+}
+
+/// Human-readable reason a verification request was rejected.
+fn describe_failure(status: u16, body: &str) -> String {
+ match status {
+ 401 | 403 => "Tokamak rejected that API key. Mint a fresh one and try again.".to_string(),
+ 429 => "Tokamak is rate limiting this key - wait a moment and try again.".to_string(),
+ 500..=599 => format!("Tokamak is unavailable right now (HTTP {status})."),
+ _ => {
+ let detail = api_error_message(body).unwrap_or_else(|| snippet(body));
+ if detail.is_empty() {
+ format!("Tokamak returned HTTP {status}.")
+ } else {
+ format!("Tokamak returned HTTP {status}: {detail}")
+ }
+ }
+ }
+}
+
+/// `error` as a string, or `error.message`, from an error body.
+fn api_error_message(body: &str) -> Option<String> {
+ let value: serde_json::Value = serde_json::from_str(body).ok()?;
+ let error = value.get("error")?;
+ let text = error
+ .as_str()
+ .or_else(|| error.get("message").and_then(|m| m.as_str()))?;
+ Some(text.to_string())
+}
+
+fn snippet(body: &str) -> String {
+ let one_line = body.split_whitespace().collect::<Vec<_>>().join(" ");
+ if one_line.chars().count() > 120 {
+ format!("{}...", one_line.chars().take(117).collect::<String>())
+ } else {
+ one_line
+ }
+}
+
+/// Model ids from a `/models` payload, sorted and deduped so a config write and
+/// the "N models" report are stable across calls. Accepts the OpenAI shape
+/// (`{"data":[{"id":...}]}`) plus the bare-array and array-of-strings variants
+/// smaller gateways serve.
+fn parse_models(value: &serde_json::Value) -> Vec<String> {
+ let entries = value
+ .get("data")
+ .and_then(|d| d.as_array())
+ .or_else(|| value.as_array());
+ let Some(entries) = entries else {
+ return Vec::new();
+ };
+ let mut ids: Vec<String> = entries
+ .iter()
+ .filter_map(|entry| {
+ entry
+ .as_str()
+ .or_else(|| entry.get("id").and_then(|id| id.as_str()))
+ })
+ .map(str::trim)
+ .filter(|id| !id.is_empty())
+ .map(String::from)
+ .collect();
+ ids.sort();
+ ids.dedup();
+ ids
+}
+
+/// Open the API-keys page in the user's browser. `Err` means the caller must
+/// print the URL for the user to open themselves -- which callers do
+/// unconditionally anyway, since a spawned launcher reports nothing about
+/// whether a page actually appeared.
+pub fn open_api_keys_page() -> Result<(), String> {
+ open_url(API_KEYS_URL)
+}
+
+fn open_url(url: &str) -> Result<(), String> {
+ if cfg!(test) {
+ // A test run must never take over the developer's browser.
+ return Err("browser launch is disabled under test".to_string());
+ }
+ launch(url)
+}
+
+fn launch(url: &str) -> Result<(), String> {
+ #[cfg(target_os = "macos")]
+ let (program, args): (&str, &[&str]) = ("open", &[]);
+ #[cfg(target_os = "windows")]
+ let (program, args): (&str, &[&str]) = ("cmd", &["/C", "start", ""]);
+ #[cfg(all(unix, not(target_os = "macos")))]
+ let (program, args): (&str, &[&str]) = ("xdg-open", &[]);
+
+ #[cfg(all(unix, not(target_os = "macos")))]
+ if !has_display() {
+ return Err("no graphical session detected".to_string());
+ }
+
+ std::process::Command::new(program)
+ .args(args)
+ .arg(url)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| format!("could not launch {program}: {e}"))
+}
+
+/// Whether a Linux/BSD session has a display server to open a browser on. Over
+/// SSH or in a container `xdg-open` would either fail noisily or block, so the
+/// caller falls back to printing the URL.
+#[cfg(all(unix, not(target_os = "macos")))]
+fn has_display() -> bool {
+ ["WAYLAND_DISPLAY", "DISPLAY"]
+ .iter()
+ .any(|var| std::env::var_os(var).is_some_and(|v| !v.is_empty()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::core::agent::global_config::{load_global_config, with_temp_home};
+ use serde_json::json;
+
+ #[test]
+ fn sanitize_trims_and_rejects_unusable_input() {
+ assert_eq!(sanitize_key(" tk-abc\n").unwrap(), "tk-abc");
+ assert!(sanitize_key(" ").is_err());
+ assert!(sanitize_key("").is_err());
+ assert!(sanitize_key("tk-abc def").is_err());
+ assert!(sanitize_key("tk-abc\ndef").is_err());
+ }
+
+ #[test]
+ fn parses_openai_model_list_sorted_and_deduped() {
+ let body = json!({"object": "list", "data": [
+ {"id": "tokamak-1-preview"},
+ {"id": "alpha"},
+ {"id": "alpha"},
+ {"id": " "},
+ {"name": "no-id-field"},
+ ]});
+ assert_eq!(
+ parse_models(&body),
+ vec!["alpha".to_string(), "tokamak-1-preview".to_string()]
+ );
+ }
+
+ #[test]
+ fn parses_bare_array_and_string_variants() {
+ assert_eq!(
+ parse_models(&json!(["b", {"id": "a"}])),
+ vec!["a".to_string(), "b".to_string()]
+ );
+ assert!(parse_models(&json!({"data": []})).is_empty());
+ assert!(parse_models(&json!({"unexpected": 1})).is_empty());
+ }
+
+ #[test]
+ fn failure_messages_name_the_actual_problem() {
+ assert!(describe_failure(401, r#"{"error":"unauthorized"}"#).contains("rejected"));
+ assert!(describe_failure(403, "").contains("rejected"));
+ assert!(describe_failure(429, "").contains("rate limiting"));
+ assert!(describe_failure(503, "").contains("unavailable"));
+ let other = describe_failure(400, r#"{"error":{"message":"bad request"}}"#);
+ assert!(other.contains("400") && other.contains("bad request"));
+ assert!(describe_failure(418, "").contains("418"));
+ }
+
+ #[test]
+ fn persist_writes_provider_entry_and_default_model() {
+ with_temp_home(|_| {
+ let login = persist("tk-1", vec!["m-a".into(), "m-b".into()]).expect("persist");
+ assert_eq!(login.default_model.as_deref(), Some("m-a"));
+
+ let configs = load_global_config().expect("load");
+ let cfg = configs.get(PROVIDER).expect("tokamak present");
+ assert_eq!(cfg.api_key.as_deref(), Some("tk-1"));
+ assert_eq!(cfg.base_url.as_deref(), Some(BASE_URL));
+ assert_eq!(cfg.models, vec!["m-a".to_string(), "m-b".to_string()]);
+ assert!(super::super::providers::is_cli_reachable(cfg));
+ });
+ }
+
+ #[test]
+ fn persist_respects_an_existing_default_model() {
+ with_temp_home(|_| {
+ crate::core::agent::global_config::set_default_model_if_unset("chosen").unwrap();
+ let login = persist("tk-1", vec!["m-a".into()]).expect("persist");
+ assert_eq!(login.default_model, None);
+ });
+ }
+
+ #[test]
+ fn persist_with_no_models_still_saves_the_key() {
+ with_temp_home(|_| {
+ let login = persist("tk-1", Vec::new()).expect("persist");
+ assert!(login.models.is_empty());
+ assert_eq!(login.default_model, None);
+ let configs = load_global_config().expect("load");
+ assert_eq!(
+ configs.get(PROVIDER).unwrap().api_key.as_deref(),
+ Some("tk-1")
+ );
+ });
+ }
+
+ #[test]
+ fn relogin_replaces_the_key_and_model_list() {
+ with_temp_home(|_| {
+ persist("tk-old", vec!["m-a".into(), "m-b".into()]).expect("first");
+ persist("tk-new", vec!["m-c".into()]).expect("second");
+ let configs = load_global_config().expect("load");
+ let cfg = configs.get(PROVIDER).unwrap();
+ assert_eq!(cfg.api_key.as_deref(), Some("tk-new"));
+ assert_eq!(cfg.models, vec!["m-c".to_string()]);
+ });
+ }
+}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index d891caa2e..e19974f0c 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -197,6 +197,42 @@ struct PickerItem {
checkbox: Option<bool>,
}
+/// `/login` key entry: a docked prompt that collects a Tokamak API key without
+/// echoing it. Verification runs off the render loop (see `login_task` in
+/// `chat_loop`), so `verifying` marks the window where the prompt is read-only.
+struct LoginPrompt {
+ /// The key as typed/pasted. Never rendered verbatim -- see `masked`.
+ input: String,
+ /// Why the previous attempt failed, shown above the field.
+ error: Option<String>,
+ verifying: bool,
+}
+
+impl LoginPrompt {
+ fn new() -> Self {
+ Self {
+ input: String::new(),
+ error: None,
+ verifying: false,
+ }
+ }
+
+ /// Bounded stand-in for the key so a long paste can't overflow the box and a
+ /// shoulder-surfer learns nothing beyond "something was entered".
+ fn masked(&self) -> String {
+ "*".repeat(self.input.chars().count().min(32))
+ }
+
+ /// Append pasted text, dropping the whitespace terminals add around a paste.
+ /// Interior whitespace is kept so `sanitize_key` can reject a mis-paste with
+ /// a clear reason rather than silently mangling the key.
+ fn paste(&mut self, text: &str) {
+ if !self.verifying {
+ self.input.push_str(text.trim());
+ }
+ }
+}
+
/// A spawned agent run: the event stream and its abort handle.
struct CurrentRun {
rx: mpsc::UnboundedReceiver<StreamEvent>,
@@ -516,6 +552,10 @@ struct App {
/// Structured questions waiting for this TUI, oldest first.
ask_queue: std::collections::VecDeque<PendingAsk>,
picker: Option<Picker>,
+ /// Active `/login` prompt; owns the keyboard while open.
+ login: Option<LoginPrompt>,
+ /// Key handed off to the loop to verify off the render loop. Taken once.
+ login_submit: Option<String>,
/// Lines scrolled back from the tail; 0 pins the view to the bottom so new
/// content follows. Non-zero survives streaming so scroll-back stays usable.
scrollback: u16,
@@ -706,6 +746,8 @@ impl App {
pending_queue: std::collections::VecDeque::new(),
ask_queue: std::collections::VecDeque::new(),
picker: None,
+ login: None,
+ login_submit: None,
scrollback: 0,
want_start: false,
view_width: 0,
@@ -2826,6 +2868,22 @@ async fn await_snapshot(
}
}
+/// Await an in-flight `/login` verification, parking forever when none is
+/// running so this can sit in the loop's `select!` unconditionally.
+async fn await_login(
+ task: &mut Option<tokio::task::JoinHandle<Result<super::tokamak::Login, String>>>,
+) -> Result<super::tokamak::Login, String> {
+ let joined = match task.as_mut() {
+ Some(h) => h.await,
+ None => return pending().await,
+ };
+ *task = None;
+ match joined {
+ Ok(inner) => inner,
+ Err(e) => Err(format!("sign-in task failed: {e}")),
+ }
+}
+
pub async fn run(
session: AgentSession,
agent_dir: std::path::PathBuf,
@@ -2938,6 +2996,12 @@ async fn chat_loop<B: Backend>(
let mut snap_task: Option<tokio::task::JoinHandle<Result<String, String>>> = None;
let mut snap_inflight: Option<SnapshotJob> = None;
+ // `/login` key verification: an HTTP round trip, so it runs off the render
+ // loop and the prompt keeps repainting ("verifying...") while it's in flight.
+ let mut login_task: Option<
+ tokio::task::JoinHandle<Result<super::tokamak::Login, String>>,
+ > = None;
+
match initial_task {
Some(task) if !task.trim().is_empty() => app.submit_user(task.trim().to_string()),
_ => app.note("type a message to start, or /help for commands"),
@@ -2956,6 +3020,24 @@ async fn chat_loop<B: Backend>(
}
}
+ // Esc closed the prompt while a verification was in flight: drop it, so a
+ // late reply can't report a sign-in the user walked away from.
+ if app.login.is_none() {
+ if let Some(task) = login_task.take() {
+ task.abort();
+ }
+ }
+
+ // A key was submitted at the `/login` prompt: verify it off-loop. One at
+ // a time -- the prompt is read-only while `verifying`.
+ if login_task.is_none() {
+ if let Some(key) = app.login_submit.take() {
+ login_task = Some(tokio::spawn(
+ async move { super::tokamak::login(&key).await },
+ ));
+ }
+ }
+
// A turn finished under an active goal: run the (stateless) evaluator
// before anything else. It either auto-submits the next turn (setting
// want_start) or hands control back. Gated on an idle, run-free state so
@@ -3015,11 +3097,16 @@ async fn chat_loop<B: Backend>(
};
}
}
- Ok(Event::Paste(text)) => {
- for c in text.chars() {
- app.input_insert(c);
+ Ok(Event::Paste(text)) => match app.login.as_mut() {
+ // A pasted API key belongs to the login field, not
+ // the input box (where it would be echoed).
+ Some(prompt) => prompt.paste(&text),
+ None => {
+ for c in text.chars() {
+ app.input_insert(c);
+ }
}
- }
+ },
Ok(Event::Mouse(mouse)) => {
if !handle_ask_mouse(app, mouse, ask_requests).await {
handle_mouse(app, mouse);
@@ -3036,6 +3123,9 @@ async fn chat_loop<B: Backend>(
names => app.note(&format!("MCP ready: {}", names.join(", "))),
}
}
+ login_res = await_login(&mut login_task) => {
+ finish_login(app, login_res);
+ }
snap_res = await_snapshot(&mut snap_task) => {
match (snap_inflight.take(), snap_res) {
(Some(SnapshotJob::Base), Ok(sha)) => {
@@ -3323,6 +3413,72 @@ async fn handle_ask_mouse(
true
}
+/// Keys for the `/login` prompt. Enter hands the key to the loop for
+/// verification (`login_submit`); Esc or Ctrl-C abandons sign-in. While a
+/// verification is in flight the field is read-only, so a stray keystroke cannot
+/// edit the key being checked -- but Esc still cancels, so the prompt can never
+/// wedge the TUI.
+fn handle_login_key(app: &mut App, key: KeyEvent, ctrl: bool) {
+ let cancel = key.code == KeyCode::Esc
+ || (ctrl && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d')));
+ if cancel {
+ app.login = None;
+ app.login_submit = None;
+ app.note("sign-in cancelled (run /login again any time)");
+ return;
+ }
+ // Ctrl-V: terminals deliver a normal paste as `Event::Paste`, but some send
+ // Ctrl-V through as a key, so read the clipboard directly for those.
+ if ctrl && key.code == KeyCode::Char('v') {
+ match clipboard_text() {
+ Ok(text) => {
+ if let Some(prompt) = app.login.as_mut() {
+ prompt.paste(&text);
+ }
+ }
+ Err(e) => {
+ if let Some(prompt) = app.login.as_mut() {
+ prompt.error = Some(format!("could not read the clipboard: {e}"));
+ }
+ }
+ }
+ return;
+ }
+
+ let Some(prompt) = app.login.as_mut() else {
+ return;
+ };
+ if prompt.verifying {
+ return;
+ }
+ match key.code {
+ KeyCode::Enter => match super::tokamak::sanitize_key(&prompt.input) {
+ Ok(key) => {
+ prompt.verifying = true;
+ prompt.error = None;
+ app.login_submit = Some(key);
+ }
+ Err(e) => {
+ prompt.input.clear();
+ prompt.error = Some(e);
+ }
+ },
+ KeyCode::Backspace => {
+ prompt.input.pop();
+ }
+ KeyCode::Char(ch) if !ctrl => prompt.input.push(ch),
+ _ => {}
+ }
+}
+
+/// Plain text from the OS clipboard, for Ctrl-V in the `/login` prompt (the
+/// image path is `clipboard_image`).
+fn clipboard_text() -> Result<String, String> {
+ arboard::Clipboard::new()
+ .and_then(|mut clip| clip.get_text())
+ .map_err(|e| e.to_string())
+}
+
async fn handle_key(
app: &mut App,
key: KeyEvent,
@@ -3350,6 +3506,14 @@ async fn handle_key(
return;
}
+ // The `/login` prompt owns the keyboard while open: every keystroke is part
+ // of a secret being typed, so none of it may reach the input box or the
+ // transcript shortcuts.
+ if app.login.is_some() {
+ handle_login_key(app, key, ctrl);
+ return;
+ }
+
// A pending permission prompt captures y/a/n; Ctrl-C cancels the run and
// Ctrl-D quits, so it can't be wedged waiting on an unanswered prompt.
// Several subagents can have requests queued at once (see `pending_queue`),
@@ -3736,6 +3900,11 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
hint: "[N]",
description: "Cancel queued messages (bare: all, or index)",
},
+ SlashCommand {
+ name: "/login",
+ hint: "",
+ description: "Sign in to Tokamak and save the API key",
+ },
SlashCommand {
name: "/config",
hint: "",
@@ -3832,6 +4001,7 @@ async fn run_command(app: &mut App, line: &str) {
}
}
"mcp" => open_mcp_picker(app),
+ "login" => open_login_prompt(app),
"config" => open_config_screen(app),
"goal" => goal_command(app, arg),
"plan" => plan_command(app, arg),
@@ -4264,6 +4434,69 @@ fn open_mcp_picker(app: &mut App) {
});
}
+/// Open the `/login` prompt: send the user to Tokamak's API-keys page and wait
+/// for the key they paste back. The URL is always written to the transcript, not
+/// just handed to the browser, so a headless or remote session can still be
+/// completed by hand.
+fn open_login_prompt(app: &mut App) {
+ app.gap(Kind::Meta);
+ app.push(Line::styled(
+ "sign in to Tokamak and create an API key:".to_string(),
+ Style::new().dim(),
+ ));
+ app.push(Line::styled(
+ format!(" {}", super::tokamak::API_KEYS_URL),
+ Style::new().cyan(),
+ ));
+ let browser = match super::tokamak::open_api_keys_page() {
+ Ok(()) => " opening that page in your browser".to_string(),
+ Err(e) => format!(" open that URL yourself ({e})"),
+ };
+ app.push(Line::styled(browser, Style::new().dim()));
+ app.login = Some(LoginPrompt::new());
+}
+
+/// Apply a finished verification. Success persists the key and, when the session
+/// is pointed at a model this account cannot serve, moves it onto one that works
+/// -- otherwise signing in would appear to do nothing on the next message.
+fn finish_login(app: &mut App, result: Result<super::tokamak::Login, String>) {
+ match result {
+ Ok(login) => {
+ app.login = None;
+ app.note(&format!(
+ "signed in to Tokamak - {} model(s) available, key saved to {}",
+ login.models.len(),
+ login.config_path.display()
+ ));
+ adopt_login_model(app, &login);
+ }
+ Err(e) => {
+ // Keep the prompt open with the reason: a rejected key is usually a
+ // partial paste, and reopening from scratch loses that context.
+ if let Some(prompt) = app.login.as_mut() {
+ prompt.verifying = false;
+ prompt.input.clear();
+ prompt.error = Some(e);
+ } else {
+ app.note(&format!("sign-in failed: {e}"));
+ }
+ }
+ }
+}
+
+/// Point the session at a Tokamak model when the current one is not runnable.
+/// A model that already resolves is left alone: `/login` is also used to refresh
+/// an expired key, which must not silently switch models.
+fn adopt_login_model(app: &mut App, login: &super::tokamak::Login) {
+ let runnable = super::providers::list_provider_models(Some(&app.project_root));
+ if runnable.iter().any(|(_, m)| *m == app.model) {
+ return;
+ }
+ if let Some(model) = login.models.first() {
+ app.set_model(model.clone());
+ }
+}
+
/// Open the `/config` screen: a read-only view of the providers configured in
/// `~/.jan/config.toml` (the standalone-agent credential store), with API keys
/// redacted. Editing is headless via `jan config set/unset` (shown in the
@@ -5060,9 +5293,19 @@ fn draw(f: &mut Frame, app: &mut App) {
f.render_widget(path_line(app), chunks[3]);
f.render_widget(footer(app), chunks[4]);
- // An interactive question owns the dock while active. Permission prompts
- // remain queued behind it and surface as soon as the question resolves.
- if !app.ask_queue.is_empty() {
+ // `/login` is modal and user-initiated (only reachable while idle), so it
+ // outranks the queues below: nothing else may take keystrokes meant for a key.
+ if let Some(prompt) = &app.login {
+ let height = (LOGIN_PROMPT_ROWS + u16::from(prompt.error.is_some())).min(chunks[1].height);
+ let y = chunks[2].y.saturating_sub(height).max(chunks[1].y);
+ let rect = ratatui::layout::Rect {
+ x: chunks[2].x,
+ y,
+ width: chunks[2].width,
+ height,
+ };
+ draw_login(f, rect, prompt);
+ } else if !app.ask_queue.is_empty() {
let queue_len = app.ask_queue.len();
let ask = app.ask_queue.front_mut().expect("checked non-empty above");
let height = (ask.row_count() as u16 + 4).min(chunks[1].height);
@@ -5235,6 +5478,56 @@ fn draw_ask(f: &mut Frame, area: Rect, ask: &mut PendingAsk, queue_len: usize) {
f.render_widget(Paragraph::new(help), rows[2]);
}
+/// Rows the `/login` box needs: two borders, the URL, the field, and the help
+/// line. An error adds one more (see the `draw` call site).
+const LOGIN_PROMPT_ROWS: u16 = 5;
+
+/// The `/login` prompt: the API-keys URL, a masked key field, and a help line.
+/// The key is never rendered, so a shared screen or scrollback capture cannot
+/// leak it.
+fn draw_login(f: &mut Frame, area: ratatui::layout::Rect, prompt: &LoginPrompt) {
+ use ratatui::widgets::Clear;
+
+ let dim = Style::new().dark_gray();
+ let block = Block::default()
+ .borders(Borders::ALL)
+ .border_style(Style::new().cyan())
+ .title(Span::styled(
+ " tokamak sign-in ",
+ Style::new().on_cyan().black().bold(),
+ ));
+
+ let mut lines = vec![Line::from(vec![
+ Span::styled("get a key at ", dim),
+ Span::styled(super::tokamak::API_KEYS_URL, Style::new().cyan()),
+ ])];
+ if let Some(error) = &prompt.error {
+ lines.push(Line::styled(error.clone(), Style::new().red()));
+ }
+ if prompt.verifying {
+ lines.push(Line::styled(
+ "verifying...".to_string(),
+ Style::new().yellow(),
+ ));
+ lines.push(Line::styled("Esc cancel".to_string(), dim));
+ } else {
+ lines.push(Line::from(vec![
+ Span::styled("API key: ", Style::new().bold()),
+ Span::raw(prompt.masked()),
+ Span::styled("█", Style::new().cyan()),
+ ]));
+ lines.push(Line::styled(
+ "paste the key · Enter verify · Esc cancel".to_string(),
+ dim,
+ ));
+ }
+
+ f.render_widget(Clear, area);
+ let inner = block.inner(area);
+ f.render_widget(block, area);
+ f.render_widget(Paragraph::new(lines), inner);
+}
+
/// Slash-command hint popup: one row per match (`/name [hint] description`),
/// the highlighted row reversed. Docked above the input box.
fn draw_slash_hints(
@@ -5866,7 +6159,8 @@ mod tests {
apply_resume, assistant_is_awaiting_user_answer, build_user_message, clipboard_path,
diff_lines, group_activity, group_detail_lines, group_summary, handle_ask_key,
handle_ask_mouse, handle_key, handle_mouse, image_mime, input_content_lines,
- is_table_separator, load_image_file, message_text, open_config_screen, parse_command,
+ finish_login, is_table_separator, load_image_file, message_text, open_config_screen,
+ parse_command,
render_table, restore_goal, restore_run_mode, restore_todos, run_command,
running_group_row, split_reasoning, subagent_activity, subagent_name_from_run_id,
summarize_result, tokens_per_second, tool_activity, tool_finished, transcript_top_padding,
@@ -6914,6 +7208,181 @@ mod tests {
);
}
+ async fn press(app: &mut App, code: KeyCode, mods: KeyModifiers) {
+ let registry: PermissionRegistry = Arc::new(tokio::sync::Mutex::new(HashMap::new()));
+ let mcp_servers: crate::core::state::SharedMcpServers =
+ Arc::new(tokio::sync::Mutex::new(HashMap::new()));
+ let mut current: Option<CurrentRun> = None;
+ handle_key(app, KeyEvent::new(code, mods), &registry, &mut current, &mcp_servers).await;
+ }
+
+ async fn type_key_chars(app: &mut App, text: &str) {
+ for ch in text.chars() {
+ press(app, KeyCode::Char(ch), KeyModifiers::NONE).await;
+ }
+ }
+
+ #[test]
+ fn slash_commands_include_login() {
+ assert!(SLASH_COMMANDS.iter().any(|c| c.name == "/login"));
+ }
+
+ #[tokio::test]
+ async fn login_prompt_captures_keys_and_never_renders_the_key() {
+ let mut app = test_app();
+ run_command(&mut app, "login").await;
+ assert!(app.login.is_some(), "/login must open the prompt");
+
+ type_key_chars(&mut app, "tk-secret").await;
+ // Keystrokes are the key, not chat input.
+ assert!(app.input.is_empty(), "the input box must not see the key");
+ let prompt = app.login.as_ref().unwrap();
+ assert_eq!(prompt.input, "tk-secret");
+ assert_eq!(prompt.masked(), "*********");
+
+ let rows = render_rows(&mut app, 80, 24);
+ let screen = rows.join("\n");
+ assert!(screen.contains("tokamak sign-in"), "{screen}");
+ assert!(
+ !screen.contains("tk-secret"),
+ "the key must never be rendered:\n{screen}"
+ );
+ }
+
+ #[tokio::test]
+ async fn login_enter_hands_a_trimmed_key_to_the_loop() {
+ let mut app = test_app();
+ run_command(&mut app, "login").await;
+ app.login.as_mut().unwrap().paste(" tk-abc\n");
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+
+ assert_eq!(app.login_submit.as_deref(), Some("tk-abc"));
+ assert!(app.login.as_ref().unwrap().verifying);
+ }
+
+ #[tokio::test]
+ async fn login_rejects_a_mispasted_key_before_any_request() {
+ let mut app = test_app();
+ run_command(&mut app, "login").await;
+ type_key_chars(&mut app, "tk-abc def").await;
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+
+ assert!(app.login_submit.is_none(), "no request for a bad paste");
+ let prompt = app.login.as_ref().unwrap();
+ assert!(!prompt.verifying);
+ assert!(prompt.input.is_empty(), "a rejected key is cleared");
+ assert!(prompt.error.is_some());
+
+ // Empty input is likewise not worth a round trip.
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+ assert!(app.login_submit.is_none());
+ }
+
+ #[tokio::test]
+ async fn login_backspace_edits_and_esc_cancels() {
+ let mut app = test_app();
+ run_command(&mut app, "login").await;
+ type_key_chars(&mut app, "tk-ab").await;
+ press(&mut app, KeyCode::Backspace, KeyModifiers::NONE).await;
+ assert_eq!(app.login.as_ref().unwrap().input, "tk-a");
+
+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;
+ assert!(app.login.is_none(), "Esc must close the prompt");
+ assert!(app.login_submit.is_none());
+ }
+
+ #[tokio::test]
+ async fn login_stays_cancellable_while_verifying() {
+ let mut app = test_app();
+ run_command(&mut app, "login").await;
+ app.login.as_mut().unwrap().paste("tk-abc");
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+ app.login_submit.take();
+
+ // Read-only while in flight: no edit may change the key being checked.
+ type_key_chars(&mut app, "xyz").await;
+ press(&mut app, KeyCode::Backspace, KeyModifiers::NONE).await;
+ assert_eq!(app.login.as_ref().unwrap().input, "tk-abc");
+ let rows = render_rows(&mut app, 80, 24);
+ assert!(rows.iter().any(|r| r.contains("verifying")), "{rows:?}");
+
+ press(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL).await;
+ assert!(app.login.is_none(), "Ctrl-C must not wedge the prompt");
+ }
+
+ #[tokio::test]
+ async fn failed_verification_keeps_the_prompt_open_with_the_reason() {
+ let mut app = test_app();
+ run_command(&mut app, "login").await;
+ app.login.as_mut().unwrap().paste("tk-abc");
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+ app.login_submit.take();
+
+ finish_login(&mut app, Err("Tokamak rejected that API key.".to_string()));
+ let prompt = app.login.as_ref().expect("prompt stays open to retry");
+ assert!(!prompt.verifying);
+ assert!(prompt.input.is_empty());
+ assert_eq!(prompt.error.as_deref(), Some("Tokamak rejected that API key."));
+ }
+
+ #[test]
+ fn successful_login_closes_the_prompt_and_adopts_a_runnable_model() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let mut app = test_app();
+ app.login = Some(super::LoginPrompt::new());
+ finish_login(
+ &mut app,
+ Ok(crate::core::cli::tokamak::Login {
+ models: vec!["tokamak-1-preview".into(), "tokamak-1-mini".into()],
+ config_path: std::path::PathBuf::from("/tmp/config.toml"),
+ default_model: Some("tokamak-1-preview".into()),
+ }),
+ );
+ assert!(app.login.is_none());
+ // The session's old model ("m") is offered by nobody, so sign-in must
+ // move it onto one the new account can serve.
+ assert_eq!(app.model, "tokamak-1-preview");
+ });
+ }
+
+ #[test]
+ fn login_keeps_a_still_runnable_model_on_a_key_refresh() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ crate::core::agent::global_config::set_provider(
+ "tokamak",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("tk".into()),
+ base_url: Some(crate::core::cli::tokamak::BASE_URL.into()),
+ models: Some(vec!["m".into()]),
+ api_type: None,
+ },
+ )
+ .expect("seed provider");
+
+ let mut app = test_app();
+ app.login = Some(super::LoginPrompt::new());
+ finish_login(
+ &mut app,
+ Ok(crate::core::cli::tokamak::Login {
+ models: vec!["tokamak-1-preview".into()],
+ config_path: std::path::PathBuf::from("/tmp/config.toml"),
+ default_model: None,
+ }),
+ );
+ assert_eq!(app.model, "m", "a working model must survive a re-login");
+ });
+ }
+
+ #[test]
+ fn masked_key_is_bounded() {
+ let mut prompt = super::LoginPrompt::new();
+ prompt.paste(&"k".repeat(200));
+ assert_eq!(prompt.masked().chars().count(), 32);
+ prompt.verifying = true;
+ prompt.paste("ignored");
+ assert_eq!(prompt.input.chars().count(), 200);
+ }
+
#[test]
fn reasoning_folds_before_await_subagent() {
// A reasoning model that thinks and then awaits a subagent must fold