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.

Merge remote-tracking branch 'origin/dev' into feature/8661-improve-login-ux

thinhlpg2061bb1da96d
diff --cc src-tauri/src/core/cli/mod.rs
index 4a0eddf14,9c61a8add..f7af36a8d
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@@ -2,8 -2,8 +2,9 @@@
//!
//! This module is only compiled when the `cli` feature is enabled.
+pub mod auth;
pub mod brand;
+ pub mod browser;
pub mod journal;
pub mod login;
pub mod mcp;
diff --cc src-tauri/src/core/cli/tui.rs
index 4b8084540,cd9b4fe63..71dbdfcbe
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@@ -411,10 -404,13 +411,13 @@@ enum PickerKind
/// `/plugin install <collection>`: choose which plugins inside a collection
/// repo to install. Space toggles a row, Enter installs everything checked.
PluginSelect,
+ /// One MCP server's detail screen: the info block plus the actions that
+ /// apply to it (see `open_mcp_detail`). Reached with Enter from `ToggleMcp`.
+ McpServer,
}
-/// Interactive list overlay (`/resume` threads, `/model` models, `/mcp`
-/// servers): rows with a highlighted cursor, acted on by `PickerKind` on Enter.
+/// Interactive list overlay (`/resume`, `/login`, `/mcp`, etc.): rows with a
+/// highlighted cursor, acted on by `PickerKind` on Enter.
struct Picker {
kind: PickerKind,
items: Vec<PickerItem>,
@@@ -426,26 -422,29 +429,29 @@@
}
impl Picker {
- fn title(&self) -> String {
+ fn title(&self) -> &'static str {
match self.kind {
- PickerKind::ResumeThread => " resume thread ".to_string(),
- PickerKind::LoginProvider => " sign in ".to_string(),
- PickerKind::ToggleMcp => " mcp servers ".to_string(),
- PickerKind::RewindMessage => " rewind to message ".to_string(),
- PickerKind::RewindScope => " restore ".to_string(),
- PickerKind::ViewConfig => " provider config ".to_string(),
- PickerKind::AgentSettings => " agent settings ".to_string(),
- PickerKind::ProviderSettings => " providers ".to_string(),
- PickerKind::Todo => " todo ".to_string(),
- PickerKind::PluginSelect => " install plugins ".to_string(),
+ PickerKind::ResumeThread => " resume thread ",
- PickerKind::SelectModel => " select model ",
++ PickerKind::LoginProvider => " sign in ",
+ PickerKind::ToggleMcp => " mcp servers ",
+ PickerKind::RewindMessage => " rewind to message ",
+ PickerKind::RewindScope => " restore ",
+ PickerKind::ViewConfig => " provider config ",
+ PickerKind::AgentSettings => " agent settings ",
+ PickerKind::ProviderSettings => " providers ",
+ PickerKind::Todo => " todo ",
+ PickerKind::PluginSelect => " install plugins ",
+ PickerKind::McpServer => " mcp server ",
}
}
fn action_hint(&self) -> &'static str {
match self.kind {
PickerKind::ResumeThread => " ↑/↓ select Enter resume Esc cancel",
- PickerKind::SelectModel => " ↑/↓ select Enter choose Esc cancel",
+ PickerKind::LoginProvider => " ↑/↓ select Enter sign in x sign out Esc cancel",
- PickerKind::ToggleMcp => " ↑/↓ select Enter toggle a add e edit d delete Esc close",
+ PickerKind::ToggleMcp => {
+ " ↑/↓ select Enter open Space toggle a add e edit d delete Esc close"
+ }
PickerKind::RewindMessage => " ↑/↓ select Enter choose Esc cancel",
PickerKind::RewindScope => " ↑/↓ select Enter restore Esc cancel",
PickerKind::ViewConfig => " set via: jan config set --provider <id> ... Esc close",
@@@ -604,12 -470,69 +611,71 @@@ struct PickerItem
checkbox: Option<bool>,
}
+ /// The `/mcp` detail screen's data: a local snapshot (config plus the cached
+ /// `initialize` response) and the one field that needs a round trip.
+ struct McpDetail {
+ server: super::mcp::ServerDetail,
+ tools: ToolsState,
+ }
+
+ /// Where the detail screen's tool list is. Split from `Option<Vec<_>>` so the
+ /// screen can say *why* there is no list -- "not connected" and "the listing
+ /// failed" are different problems.
+ enum ToolsState {
+ /// Not connected, so there is nothing to ask for.
+ Unavailable,
+ Loading,
+ Ready(Vec<String>),
+ Failed(String),
+ }
+
+ /// Off-loop MCP work the detail screen hands to the loop. Everything here
+ /// either talks to a peer or waits on a browser, so none of it may run inside
+ /// `handle_key`.
+ enum McpJob {
+ /// List a connected server's tools for the `Tools:` line.
+ Tools(String),
+ /// Discover the provider and mint a consent url. Deliberately separate from
+ /// `Authorize`: the url must reach the transcript *before* anything waits on
+ /// the redirect, or a user with no browser has nothing to act on.
+ BeginAuth(String),
+ /// Wait for the redirect and persist the tokens.
+ Authorize {
+ server: String,
+ pending: Box<crate::core::mcp::oauth::PendingAuth>,
+ },
+ /// Bring a server up. Run as a job rather than detached whenever the detail
+ /// screen is open, so the screen refreshes when the connect lands instead of
+ /// sitting on `not connected` until the user navigates away and back.
+ Connect(String),
+ }
+
+ /// What an `McpJob` came back with.
+ enum McpJobDone {
+ Tools {
+ server: String,
+ result: Result<Vec<String>, String>,
+ },
+ AuthStarted {
+ server: String,
+ result: Result<Box<crate::core::mcp::oauth::PendingAuth>, String>,
+ },
+ Authorized {
+ server: String,
+ result: Result<(), String>,
+ },
+ Connected {
+ server: String,
+ result: Result<(), String>,
+ },
+ }
+
-/// `/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.
+/// `/login` key entry: a docked prompt opened after provider/method selection
+/// that collects a masked API key for the chosen provider 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 {
+ provider: String,
/// The key as typed/pasted. Never rendered verbatim -- see `masked`.
input: String,
/// Why the previous attempt failed, shown above the field.
@@@ -6428,17 -6225,13 +6517,21 @@@ async fn chat_loop<B: Backend>
// `/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>>,
+ tokio::task::JoinHandle<
+ Result<crate::core::cli::auth::LoginResult, crate::core::cli::auth::LoginError>,
+ >,
> = None;
+ let mut account_login_task: Option<tokio::task::JoinHandle<Result<String, String>>> = None;
+ // Claude sign-in reports which org/plan the token resolved to (personal
+ // free vs enterprise premium) so a wrong-org consent is caught immediately
+ // instead of surfacing later as sonnet/opus 429s. Detached like the update
+ // check: the probe is a network round trip and must not block sign-in.
+ let mut account_usage_task: Option<tokio::task::JoinHandle<String>> = None;
+ // `/mcp` work that must not run on the render loop: a tool listing is a
+ // round trip to the peer, and an authorization waits on a browser for up to
+ // five minutes. One at a time -- the detail screen only ever asks for one.
+ let mut mcp_job: Option<tokio::task::JoinHandle<McpJobDone>> = None;
// The update check is a network round trip, so it runs off the render loop
// and notes itself whenever it lands rather than delaying the first frame.
@@@ -6503,61 -6296,29 +6596,76 @@@
task.abort();
}
}
+ if app.account_login.is_none() {
+ app.account_login_pending_manual_input = None;
+ app.account_login_manual_tx = None;
+ if let Some(task) = account_login_task.take() {
+ task.abort();
+ }
+ }
+
+ if account_login_task.is_none() {
+ if let Some(mut login) = app.account_login_submit.take() {
+ let (manual_rx, has_pending_manual_input) = account_login_manual_channel(app);
+ match crate::core::cli::auth::account::bind_callback(&mut login).await {
+ Err(error) => finish_account_login(app, Err(error)),
+ Ok(listener) => {
+ if let Some(prompt) = app.account_login.as_mut() {
+ prompt.login = login.clone();
+ }
+ account_login_task = Some(tokio::spawn(async move {
+ if let Err(error) = open_browser(&login.authorization_url) {
+ if !has_pending_manual_input {
+ return Err(error);
+ }
+ }
+ let provider = tokio::time::timeout(
+ ACCOUNT_CALLBACK_TIMEOUT,
+ crate::core::cli::auth::account::
+ complete_callback_login_with_manual(
+ listener,
+ login,
+ manual_rx,
+ ),
+ )
+ .await
+ .map_err(|_| "account sign-in timed out".to_string())??;
+ Ok(provider.credential_provider().to_string())
+ }));
+ }
+ }
+ }
+ }
+ // The detail screen asked for something off-loop. One job at a time, and
+ // a request arriving while one is in flight *waits* rather than being
+ // dropped: an authorization owns the slot for up to `CALLBACK_TIMEOUT`
+ // while the browser is out, and a tool listing dropped in that window
+ // would leave the screen on `listing...` with nothing to retrigger it.
+ // The slot holds the latest request only -- a newer one replaces it, and
+ // a request whose server the screen has since left is discarded on
+ // arrival by `finish_mcp_job`.
+ if mcp_job.is_none() {
+ if let Some(job) = app.mcp_job_request.take() {
+ let servers = mcp_servers.clone();
+ mcp_job = Some(tokio::spawn(run_mcp_job(job, servers)));
+ }
+ }
+
// A key was submitted at the `/login` prompt: verify it off-loop. One at
- // a time -- the prompt is read-only while `verifying`.
+ // 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 },
- ));
+ if let Some((provider, key)) = app.login_submit.take() {
+ login_task = Some(tokio::spawn(async move {
+ let definition =
+ crate::core::cli::auth::provider_by_id(&provider).ok_or_else(|| {
+ crate::core::cli::auth::LoginError::InvalidKey(
+ "selected provider is unavailable".to_string(),
+ )
+ })?;
+ crate::core::cli::auth::providers::login_with_api_key(&definition, &key)
+ .await
+ }));
}
}
@@@ -8475,10 -8036,9 +8629,10 @@@ async fn run_command
app.set_model(arg.to_string());
}
}
- "mcp" => open_mcp_picker(app),
+ "mcp" => open_mcp_picker(app, mcp_servers).await,
"plugin" => plugin_command(app, arg).await,
- "login" => open_login_prompt(app),
+ "login" => open_login_picker(app),
+ "logout" => logout_command(app, arg),
"update" => update_command(app),
"config" => open_config_screen(app),
"terminal-setup" => terminal_setup_command(app),
@@@ -10252,35 -9748,88 +10405,77 @@@ async fn open_model_picker(app: &mut Ap
Err(e) => app.note(&format!("could not fetch models: {e}")),
}
let pairs = super::providers::list_provider_models(Some(&project_root));
- if pairs.is_empty() {
- return app.note(
+ match ModelPicker::from_pairs(pairs, &app.model) {
+ Some(picker) => {
+ app.picker = None;
+ app.model_picker = Some(picker);
+ }
+ None => app.note(
"no models available (add a provider with `jan config set`, or configure one in the desktop app)",
- );
+ ),
}
- let selected = pairs.iter().position(|(_, m)| *m == app.model).unwrap_or(0);
- let items = pairs
- .into_iter()
- .map(|(provider, model)| PickerItem {
- label: format!("{provider} / {model}"),
- value: model,
- hint: None,
- checkbox: None,
- })
- .collect();
- app.picker = Some(Picker {
- kind: PickerKind::SelectModel,
- items,
- selected,
- armed_delete: None,
- });
+
}
- /// Open the `/mcp` picker listing configured MCP servers with their enabled
- /// state. Enter toggles a row in place (see `toggle_mcp_server`); `a` adds, `e`
- /// edits, and `d` removes (see the picker key handler).
- fn open_mcp_picker(app: &mut App) {
+ /// Action ids for the `McpServer` detail screen. String values rather than an
+ /// enum because `PickerItem::value` is the picker's one payload; keeping them
+ /// as constants is what stops the key handler and the row builder from drifting.
+ const MCP_ACTION_TOOLS: &str = "tools";
+ const MCP_ACTION_AUTH: &str = "auth";
+ const MCP_ACTION_CLEAR_AUTH: &str = "clear-auth";
+ const MCP_ACTION_RECONNECT: &str = "reconnect";
+ const MCP_ACTION_TOGGLE: &str = "toggle";
+ const MCP_ACTION_EDIT: &str = "edit";
+ const MCP_ACTION_REMOVE: &str = "remove";
+
+ /// Open the `/mcp` screen: one row per configured server, with its live state.
+ ///
+ /// An empty config opens the screen anyway, on a watermark row (the same shape
+ /// `open_provider_settings` uses). Returning a note instead left a fresh install
+ /// with no way *in* to the thing `/mcp` manages -- `a` to add is only reachable
+ /// once the picker exists, so the one state that most needs the add wizard was
+ /// the one state that could not reach it.
+ async fn open_mcp_picker(app: &mut App, mcp_servers: &crate::core::state::SharedMcpServers) {
let servers = super::mcp::list_servers();
- if servers.is_empty() {
- return app.note("no MCP servers configured (press a to add one, or use `jan cli mcp add ...`)");
- }
- let items = servers
- .into_iter()
- .map(|s| PickerItem {
- label: s.name.clone(),
- value: s.name,
+ let items: Vec<PickerItem> = if servers.is_empty() {
+ vec![PickerItem {
+ label: "no MCP servers configured - press a to add one".to_string(),
+ value: String::new(),
hint: None,
- checkbox: Some(s.active),
- })
- .collect();
+ checkbox: None,
+ }]
+ } else {
+ // One lock for the whole list: `describe` per row would take and drop it
+ // N times, and nothing here goes to the network.
+ let connected: std::collections::HashSet<String> =
+ mcp_servers.lock().await.keys().cloned().collect();
+ servers
+ .into_iter()
+ .map(|s| {
+ let state = if !s.active {
+ "disabled".to_string()
+ } else if connected.contains(&s.name) {
+ "connected".to_string()
+ } else {
+ match super::mcp::auth_status(&s.name, &s.config) {
+ crate::core::mcp::oauth::AuthStatus::Unauthenticated
+ | crate::core::mcp::oauth::AuthStatus::Expired { .. }
+ | crate::core::mcp::oauth::AuthStatus::StaleResource => {
+ "needs auth".to_string()
+ }
+ _ => "not connected".to_string(),
+ }
+ };
+ PickerItem {
+ label: format!("{} {state}", s.name),
+ value: s.name,
+ hint: None,
+ checkbox: Some(s.active),
+ }
+ })
+ .collect()
+ };
+ app.mcp_detail = None;
app.picker = Some(Picker {
kind: PickerKind::ToggleMcp,
items,
@@@ -10289,145 -9838,283 +10484,400 @@@
});
}
+fn open_login_picker(app: &mut App) {
+ open_login_picker_at(app, None);
+}
+
+ /// Open the detail screen for one server: the info block plus the actions that
+ /// apply to it. Everything shown is local, so this opens in one frame; the tool
+ /// list is requested as a job and fills in when it lands.
+ async fn open_mcp_detail(
+ app: &mut App,
+ name: &str,
+ mcp_servers: &crate::core::state::SharedMcpServers,
+ ) {
+ let Some(server) = super::mcp::describe(name, mcp_servers).await else {
+ app.mcp_detail = None;
+ return app.note(&format!("server '{name}' no longer exists"));
+ };
+ let tools = if server.connected {
+ app.mcp_job_request = Some(McpJob::Tools(name.to_string()));
+ ToolsState::Loading
+ } else {
+ ToolsState::Unavailable
+ };
+ app.picker = Some(Picker {
+ kind: PickerKind::McpServer,
+ items: mcp_action_items(&server),
+ selected: 0,
+ armed_delete: None,
+ });
+ app.mcp_detail = Some(McpDetail { server, tools });
+ }
+
+ /// The actions offered for one server, filtered to what its state can actually
+ /// do: a stdio server has nothing to authenticate, and a disconnected one has no
+ /// tools to list.
+ fn mcp_action_items(server: &super::mcp::ServerDetail) -> Vec<PickerItem> {
+ use crate::core::mcp::oauth::AuthStatus;
+ let mut actions: Vec<(&str, String)> = Vec::new();
+ if server.connected {
+ actions.push((MCP_ACTION_TOOLS, "View tools".to_string()));
+ }
+ match server.auth {
+ // A pipe has nothing to authorize, and a hand-written header is the
+ // user's own credential -- offering to overwrite it with OAuth would be
+ // offering to break it.
+ AuthStatus::NotApplicable | AuthStatus::StaticHeader => {}
+ // Anything with tokens on disk can be renewed *and* forgotten, whether
+ // they still work or not.
+ AuthStatus::Authenticated { .. }
+ | AuthStatus::Expired { .. }
+ | AuthStatus::StaleResource => {
+ actions.push((MCP_ACTION_AUTH, "Re-authenticate".to_string()));
+ actions.push((MCP_ACTION_CLEAR_AUTH, "Clear authentication".to_string()));
+ }
+ AuthStatus::Unauthenticated => {
+ actions.push((MCP_ACTION_AUTH, "Authenticate".to_string()));
+ }
+ }
+ if server.active {
+ actions.push((MCP_ACTION_RECONNECT, "Reconnect".to_string()));
+ actions.push((MCP_ACTION_TOGGLE, "Disable".to_string()));
+ } else {
+ actions.push((MCP_ACTION_TOGGLE, "Enable".to_string()));
+ }
+ actions.push((MCP_ACTION_EDIT, "Edit configuration".to_string()));
+ actions.push((MCP_ACTION_REMOVE, "Remove server".to_string()));
+
+ actions
+ .into_iter()
+ .enumerate()
+ .map(|(i, (value, label))| PickerItem {
+ // Numbered like the rest of the screen reads: the hint column is
+ // already the dim prefix slot, so this costs no extra layout.
+ hint: Some(format!("{}.", i + 1)),
+ label,
+ value: value.to_string(),
+ checkbox: None,
+ })
+ .collect()
+ }
+
+ /// The info block above the detail screen's actions: aligned labels, the state
+ /// in colour, and the config path so "where do I edit this" is answerable
+ /// without leaving the screen.
+ fn mcp_detail_lines(detail: &McpDetail, width: u16) -> Vec<Line<'static>> {
+ use crate::core::mcp::oauth::AuthStatus;
+ let server = &detail.server;
+ let dim = Style::new().dark_gray();
+ let good = Style::new().green();
+ let bad = Style::new().red();
+ let warn = Style::new().yellow();
+
+ let mut rows: Vec<(&str, Vec<Span<'static>>)> = Vec::new();
+
+ let status = if !server.active {
+ vec![Span::styled("- disabled", dim)]
+ } else if server.connected {
+ vec![Span::styled("✓ connected", good)]
+ } else {
+ vec![Span::styled("✗ not connected", bad)]
+ };
+ rows.push(("Status", status));
+
+ let auth = match &server.auth {
+ AuthStatus::NotApplicable => vec![Span::styled("- not required (stdio)", dim)],
+ AuthStatus::StaticHeader => {
+ vec![Span::styled("✓ Authorization header (configured)", good)]
+ }
+ AuthStatus::Authenticated { expires_at } => {
+ let mut spans = vec![Span::styled("✓ authenticated", good)];
+ if let Some(at) = expires_at {
+ spans.push(Span::styled(
+ format!(" (expires in {})", until_label(*at)),
+ dim,
+ ));
+ }
+ spans
+ }
+ AuthStatus::Expired { renewable, .. } => vec![Span::styled(
+ if *renewable {
+ "! expired (renewable)"
+ } else {
+ "! expired - re-authenticate"
+ },
+ warn,
+ )],
+ AuthStatus::StaleResource => vec![Span::styled(
+ "! tokens were issued for a different url",
+ warn,
+ )],
+ AuthStatus::Unauthenticated => vec![Span::styled("✗ not authenticated", bad)],
+ };
+ rows.push(("Auth", auth));
+
+ let endpoint_label = if server.transport == "stdio" {
+ "Command"
+ } else {
+ "URL"
+ };
+ rows.push((
+ endpoint_label,
+ vec![Span::styled(server.endpoint.clone(), dim)],
+ ));
+ rows.push((
+ "Config location",
+ vec![Span::styled(
+ tilde_path(&server.config_path),
+ dim,
+ )],
+ ));
+ if let Some(implementation) = &server.implementation {
+ rows.push(("Server", vec![Span::styled(implementation.clone(), dim)]));
+ }
+ if !server.capabilities.is_empty() {
+ rows.push((
+ "Capabilities",
+ vec![Span::styled(server.capabilities.join(" · "), dim)],
+ ));
+ }
+ rows.push(("Tools", vec![tools_span(&detail.tools)]));
+
+ // One label column for every row, so the values line up the way the screen
+ // is meant to read.
+ let pad = rows.iter().map(|(k, _)| k.len()).max().unwrap_or(0) + 2;
+ let mut out = vec![
+ Line::from(Span::styled(
+ server.name.clone(),
+ Style::new().cyan().bold(),
+ )),
+ Line::raw(""),
+ ];
+ for (key, value) in rows {
+ let mut spans = vec![Span::styled(
+ format!("{key}:{}", " ".repeat(pad - key.len())),
+ Style::new().bold(),
+ )];
+ spans.extend(value);
+ out.push(clamp_line(Line::from(spans), width));
+ }
+ out.push(Line::raw(""));
+ out
+ }
+
+ fn tools_span(tools: &ToolsState) -> Span<'static> {
+ let dim = Style::new().dark_gray();
+ match tools {
+ ToolsState::Unavailable => Span::styled("- connect to list", dim),
+ ToolsState::Loading => Span::styled("listing...", dim),
+ ToolsState::Ready(names) if names.is_empty() => {
+ Span::styled("none exposed", dim)
+ }
+ ToolsState::Ready(names) => Span::styled(format!("{} tools", names.len()), dim),
+ ToolsState::Failed(e) => Span::styled(e.clone(), Style::new().red()),
+ }
+ }
+
+ /// A coarse "in 42m" / "in 3h" for a unix-second deadline. Coarse on purpose:
+ /// the exact second a token dies is never what the reader wants to know.
+ fn until_label(expires_at: u64) -> String {
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ match expires_at.saturating_sub(now) {
+ s if s < 60 => format!("{s}s"),
+ s if s < 3600 => format!("{}m", s / 60),
+ s if s < 86400 => format!("{}h", s / 3600),
+ s => format!("{}d", s / 86400),
+ }
+ }
+
+ /// Truncate a composed line to `width`, so a long url or path cannot push the
+ /// panel's border off the frame. Spans are kept whole where they fit and the
+ /// overflowing one is cut with an ellipsis.
+ ///
+ /// Two cells short of `width` on purpose: callers pass the *inner* width of a
+ /// bordered panel, and a line that exactly fills it wraps into a second row,
+ /// which pushes the action list down by one for as long as the value is long.
+ ///
+ /// Measured in display cells, not chars: a CJK server name or an emoji in a tool
+ /// name is two cells wide, so a char count would let it overrun the border.
+ fn clamp_line(line: Line<'static>, width: u16) -> Line<'static> {
+ use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
+
+ let max = width.saturating_sub(2) as usize;
+ if max == 0 {
+ return Line::raw("");
+ }
+ let total: usize = line.spans.iter().map(|s| s.content.width()).sum();
+ if total <= max {
+ return line;
+ }
+ let mut used = 0usize;
+ let mut spans: Vec<Span<'static>> = Vec::new();
+ for span in line.spans {
+ let len = span.content.width();
+ if used + len <= max.saturating_sub(1) {
+ used += len;
+ spans.push(span);
+ continue;
+ }
+ // The ellipsis takes the last cell; a wide glyph that would straddle the
+ // boundary is dropped rather than half-drawn.
+ let room = max.saturating_sub(used + 1);
+ let mut cut = String::new();
+ let mut cut_width = 0usize;
+ for c in span.content.chars() {
+ let w = c.width().unwrap_or(0);
+ if cut_width + w > room {
+ break;
+ }
+ cut_width += w;
+ cut.push(c);
+ }
+ spans.push(Span::styled(format!("{cut}…"), span.style));
+ break;
+ }
+ Line::from(spans)
+ }
+
-/// 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.note("sign in to Tokamak and create an API key:");
+fn open_login_picker_at(app: &mut App, selected_provider: Option<&str>) {
+ let mut providers = crate::core::cli::auth::provider_catalog();
+ // Pin Tokamak to the top (the default provider), then list the rest in
+ // name order so the picker is stable and predictable.
+ providers.sort_by(|a, b| match (a.id == "tokamak", b.id == "tokamak") {
+ (true, false) => std::cmp::Ordering::Less,
+ (false, true) => std::cmp::Ordering::Greater,
+ _ => a.name.cmp(b.name),
+ });
+ let items = providers
+ .into_iter()
+ .map(|provider| {
+ let status =
+ if super::providers::provider_is_signed_in(Some(&app.project_root), provider.id) {
+ "signed in"
+ } else {
+ "not signed in"
+ };
+ PickerItem {
+ value: provider.id.to_string(),
+ label: format!("{} ({})", provider.name, provider.id),
+ hint: Some(status.to_string()),
+ checkbox: None,
+ }
+ })
+ .collect::<Vec<_>>();
+ let selected = selected_provider
+ .and_then(|provider| items.iter().position(|item| item.value == provider))
+ .unwrap_or(0);
+ app.picker = Some(Picker {
+ kind: PickerKind::LoginProvider,
+ items,
+ selected,
+ armed_delete: None,
+ });
+}
+
+
+fn open_account_login(app: &mut App, provider: &str) {
+ open_account_login_with_begin(app, provider, crate::core::cli::auth::account::begin);
+}
+
+fn open_account_login_with_begin(
+ app: &mut App,
+ provider: &str,
+ begin: impl FnOnce(
+ crate::core::cli::auth::account::AccountProvider,
+ ) -> Result<crate::core::cli::auth::account::AccountLogin, String>,
+) {
+ let Some(provider) =
+ crate::core::cli::auth::account::AccountProvider::from_credential_provider(provider)
+ else {
+ return app.note(&format!(
+ "{provider} sign-in failed: selected account is unavailable"
+ ));
+ };
+ let provider_id = provider.credential_provider();
+ match begin(provider) {
+ Ok(login) => {
+ app.account_login = Some(AccountLoginPrompt::new(login.clone()));
+ app.account_login_submit = Some(login);
+ app.account_login_manual_tx = None;
+ }
+ Err(_) => app.note(&account_login_error_message(provider_id)),
+ }
+}
+
+fn open_browser(url: &str) -> Result<(), String> {
+ #[cfg(target_os = "macos")]
+ let mut command = Command::new("open");
+ #[cfg(target_os = "linux")]
+ let mut command = Command::new("xdg-open");
+ #[cfg(target_os = "windows")]
+ let mut command = {
+ let mut command = Command::new("cmd");
+ command.args(["/C", "start"]);
+ command
+ };
+ command
+ .arg(url)
+ .spawn()
+ .map(|_| ())
+ .map_err(|_| "could not open the browser".to_string())
+}
+
+fn logout_command(app: &mut App, provider: &str) {
+ if provider.trim().is_empty() {
+ return app.note("usage: /logout <provider>");
+ }
+ let owned_model = crate::core::agent::global_config::load_global_config()
+ .ok()
+ .and_then(|configs| configs.get(provider).cloned())
+ .is_some_and(|config| config.models.iter().any(|model| model == &app.model));
+ match crate::core::cli::auth::providers::logout(provider) {
+ Ok(()) => {
+ if owned_model {
+ app.set_model(String::new());
+ }
+ app.note(&format!("signed out of {provider}"));
+ }
+ Err(error) => app.note(&format!("could not sign out: {error:?}")),
+ }
+}
+/// Sign out of a provider from the pickers: clear the stored credential (API
+/// key or OAuth token) but keep the provider entry and its model list in
+/// `~/.jan/config.toml`, so a re-login is one Enter away. Distinct from
+/// [`logout_command`] (which also removes the config entry) and from the
+/// provider-settings `d` delete.
+fn sign_out_provider(app: &mut App, provider: &str) {
+ match crate::core::cli::auth::CredentialStore::delete(provider) {
+ Ok(()) => app.note(&format!("signed out of {provider} (provider config kept)")),
+ Err(error) => app.note(&format!("could not sign out: {error}")),
+ }
+}
+
+fn open_login_prompt(app: &mut App, provider: &str) {
+ let Some(definition) = crate::core::cli::auth::provider_by_id(provider) else {
+ return app.note("selected provider is unavailable");
+ };
+ app.note(&format!("sign in to {} with an API key:", definition.name));
app.system_detail(vec![Span::styled(
- super::tokamak::API_KEYS_URL,
+ definition.api_key.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.system_detail_text(&browser);
- app.login = Some(LoginPrompt::new());
+ let mut prompt = LoginPrompt::new(provider);
+ if definition.api_key.open_in_browser && open_browser(definition.api_key.keys_url).is_err() {
+ prompt.error = Some("could not open the browser; use the URL below".to_string());
+ }
+ app.login = Some(prompt);
}
-/// 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>) {
+fn finish_login(
+ app: &mut App,
+ result: Result<crate::core::cli::auth::LoginResult, crate::core::cli::auth::LoginError>,
+) {
match result {
Ok(login) => {
app.login = None;
@@@ -12470,208 -12194,40 +13146,209 @@@ fn draw_permission
f.render_stateful_widget(list, rows[2], &mut state);
}
-fn draw_picker(
- f: &mut Frame,
- area: ratatui::layout::Rect,
- picker: &Picker,
- toml_path: &std::path::Path,
- mcp_detail: Option<&McpDetail>,
-) {
- use ratatui::widgets::{List, ListItem, ListState};
+fn count_label(label: &str, count: usize, width: u16) -> String {
+ let width = width as usize;
+ if width == 0 {
+ return String::new();
+ }
+ let count = count.to_string();
+ let label_width = width.saturating_sub(count.chars().count() + 1).max(1);
+ let label = truncate(label, label_width);
+ let used = label.chars().count() + count.chars().count();
+ if used >= width {
+ return truncate(&format!("{label} {count}"), width);
+ }
+ format!("{label}{}{}", " ".repeat(width - used), count)
+}
- let items: Vec<ListItem> = picker
- .items
+fn draw_model_picker(f: &mut Frame, area: Rect, picker: &ModelPicker, current_model: &str) {
+ use ratatui::widgets::{Clear, List, ListItem, ListState};
+
+ let block = Block::default()
+ .borders(Borders::ALL)
+ .border_style(Style::new().cyan())
+ .title(Span::styled(
+ " Models ",
+ Style::new().on_cyan().black().bold(),
+ ));
+ f.render_widget(Clear, area);
+ let inner = block.inner(area);
+ f.render_widget(block, area);
+ if inner.width == 0 || inner.height == 0 {
+ return;
+ }
+
+ let rows = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(inner);
+ let body = rows[0];
+ let help = truncate(
+ "Enter choose · Left/Right panes · Up/Down move · type to search · Esc close",
+ rows[1].width as usize,
+ );
+ f.render_widget(Paragraph::new(Line::styled(help, Style::new().dark_gray())), rows[1]);
+ if body.width == 0 || body.height == 0 {
+ return;
+ }
+
+ let scope_w = body
+ .width
+ .saturating_sub(1)
+ .min(28)
+ .max(body.width.saturating_sub(1).min(14));
+ let panes = Layout::horizontal([
+ Constraint::Length(scope_w),
+ Constraint::Length(1),
+ Constraint::Min(0),
+ ])
+ .split(body);
+
+ let scope_width = panes[0].width.saturating_sub(2);
+ let scope_items: Vec<ListItem> = picker
+ .scopes
.iter()
- .map(|it| {
- let mut spans = Vec::new();
- if let Some(on) = it.checkbox {
- let (mark, style) = if on {
- ("[x] ", Style::new().green())
+ .enumerate()
+ .map(|(idx, scope)| {
+ let style = if idx == picker.active_scope {
+ if picker.focus == ModelPickerFocus::Scopes {
+ Style::new().reversed().bold()
} else {
- ("[ ] ", Style::new().dark_gray())
- };
- spans.push(Span::styled(mark, style));
- }
- if let Some(hint) = &it.hint {
- spans.push(Span::styled(format!("{hint} "), Style::new().dark_gray()));
- }
- spans.push(Span::raw(it.label.clone()));
- ListItem::new(Line::from(spans))
+ Style::new().reversed()
+ }
+ } else {
+ Style::new()
+ };
+ ListItem::new(Line::styled(
+ count_label(&scope.label, scope.count, scope_width),
+ style,
+ ))
})
.collect();
- let list = List::new(items)
- .block(Block::default().borders(Borders::ALL).title(picker.title()))
- .highlight_style(select_style())
- .highlight_symbol(SELECT_MARK);
- let mut state = ListState::default();
+ let scopes = List::new(scope_items).highlight_symbol(if picker.focus == ModelPickerFocus::Scopes {
+ "▶ "
+ } else {
+ " "
+ });
+ let mut scope_state = ListState::default();
+ if !picker.scopes.is_empty() {
+ scope_state.select(Some(picker.active_scope.min(picker.scopes.len() - 1)));
+ }
+ f.render_stateful_widget(scopes, panes[0], &mut scope_state);
+
+ let divider = (0..panes[1].height)
+ .map(|_| Line::styled("│", Style::new().dark_gray()))
+ .collect::<Vec<_>>();
+ f.render_widget(Paragraph::new(divider), panes[1]);
+
+ if panes[2].width == 0 || panes[2].height == 0 {
+ return;
+ }
+ let right_rows = Layout::vertical([
+ Constraint::Length(1),
+ Constraint::Length(1),
+ Constraint::Min(0),
+ Constraint::Length(1),
+ ])
+ .split(panes[2]);
+ let title = picker
+ .scopes
+ .get(picker.active_scope)
+ .and_then(|scope| scope.provider.as_deref())
+ .map(|provider| format!("{provider} models"))
+ .unwrap_or_else(|| "All available models".to_string());
+ f.render_widget(
+ Paragraph::new(Line::styled(
+ truncate(&title, right_rows[0].width as usize),
+ Style::new().bold(),
+ )),
+ right_rows[0],
+ );
+ let caret = if picker.focus == ModelPickerFocus::Models { "█" } else { "" };
+ let search = truncate(&format!("⌕ {}{caret}", picker.query), right_rows[1].width as usize);
+ f.render_widget(
+ Paragraph::new(Line::from(vec![
+ Span::styled(search, Style::new().dark_gray()),
+ ])),
+ right_rows[1],
+ );
+
+ let model_width = right_rows[2].width.saturating_sub(2) as usize;
+ let model_items: Vec<ListItem> = picker
+ .items
+ .iter()
+ .map(|item| {
+ ListItem::new(Line::raw(truncate(
+ &format!("{} / {}", item.provider, item.model),
+ model_width,
+ )))
+ })
+ .collect();
+ let models = List::new(model_items)
+ .highlight_style(if picker.focus == ModelPickerFocus::Models {
+ Style::new().reversed().bold()
+ } else {
+ Style::new().reversed()
+ })
+ .highlight_symbol(if picker.focus == ModelPickerFocus::Models {
+ "▶ "
+ } else {
+ " "
+ });
+ let mut model_state = ListState::default();
+ if !picker.items.is_empty() {
+ model_state.select(Some(picker.selected.min(picker.items.len() - 1)));
+ }
+ f.render_stateful_widget(models, right_rows[2], &mut model_state);
+
+ let detail = picker
+ .items
+ .get(picker.selected)
+ .map(|item| {
+ let state = if item.value == current_model { "current" } else { "default" };
+ format!("{}/{} · {state}", item.provider, item.model)
+ })
+ .unwrap_or_else(|| "no models match".to_string());
+ f.render_widget(
+ Paragraph::new(Line::styled(
+ truncate(&detail, right_rows[3].width as usize),
+ Style::new().dark_gray(),
+ )),
+ right_rows[3],
+ );
+}
+
+fn draw_picker(
+ f: &mut Frame,
+ area: ratatui::layout::Rect,
+ picker: &Picker,
+ toml_path: &std::path::Path,
++ mcp_detail: Option<&McpDetail>,
+) {
+ use ratatui::widgets::{List, ListItem, ListState};
+
+ let items: Vec<ListItem> = picker
+ .items
+ .iter()
+ .map(|it| {
+ let mut spans = Vec::new();
+ if let Some(on) = it.checkbox {
+ let (mark, style) = if on {
+ ("[x] ", Style::new().green())
+ } else {
+ ("[ ] ", Style::new().dark_gray())
+ };
+ spans.push(Span::styled(mark, style));
+ }
+ if let Some(hint) = &it.hint {
+ spans.push(Span::styled(format!("{hint} "), Style::new().dark_gray()));
+ }
+ spans.push(Span::raw(it.label.clone()));
+ ListItem::new(Line::from(spans))
+ })
+ .collect();
+ let list = List::new(items)
+ .block(Block::default().borders(Borders::ALL).title(picker.title()))
+ .highlight_style(select_style())
+ .highlight_symbol(SELECT_MARK);
+ let mut state = ListState::default();
state.select(Some(picker.selected));
// The settings menu keeps two rows under the list for the selected
@@@ -13634,7 -13177,14 +14339,13 @@@ fn footer_spans(app: &App) -> Vec<Span<
#[cfg(test)]
mod tests {
+
+ /// An empty MCP map, for the `run_command`/`handle_key` paths that take one
+ /// but whose behaviour under test has nothing to do with MCP.
+ fn no_mcp() -> crate::core::state::SharedMcpServers {
+ std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()))
+ }
use super::SessionLimits;
- use super::{journal, DisplayEntry};
use super::{
age_closed_todos, apply_resume, assistant_is_awaiting_user_answer, brand, build_user_message,
clipboard_path,
@@@ -13891,12 -13435,9 +14602,12 @@@
#[tokio::test]
async fn update_command_requests_an_install_once() {
let mut app = test_app();
- run_command(&mut app, "update").await;
+ run_command(&mut app, "update", &no_mcp()).await;
assert!(app.update_requested, "the loop should pick up the request");
- assert!(transcript_text(&app).contains("downloading"), "no progress note");
+ assert!(
+ transcript_text(&app).contains("downloading"),
+ "no progress note"
+ );
// A second /update while the first is still downloading must not queue a
// concurrent install (two processes rewriting the same binary).
@@@ -16579,292 -16020,63 +17290,292 @@@
}
#[tokio::test]
- async fn login_prompt_captures_keys_and_never_renders_the_key() {
+ async fn help_login_copy_describes_provider_sign_in_without_stale_tokamak_key_copy() {
let mut app = test_app();
- run_command(&mut app, "login", &no_mcp()).await;
- assert!(app.login.is_some(), "/login must open the prompt");
- run_command(&mut app, "help").await;
- 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(), "*********");
++ run_command(&mut app, "help", &no_mcp()).await;
- 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}"
- );
+ let text: String = app.transcript.iter().map(row_text).collect();
+ assert!(text.contains("/login"), "{text}");
+ assert!(text.contains("Sign in to a provider"), "{text}");
+ assert!(!text.contains("Sign in to Tokamak"), "{text}");
+ assert!(!text.contains("save the API key"), "{text}");
}
- #[tokio::test]
- async fn login_enter_hands_a_trimmed_key_to_the_loop() {
+ #[test]
+ fn login_empty_state_points_to_provider_picker_without_stale_tokamak_copy() {
let mut app = test_app();
- run_command(&mut app, "login", &no_mcp()).await;
- app.login.as_mut().unwrap().paste(" tk-abc\n");
- press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+ app.model.clear();
- assert_eq!(app.login_submit.as_deref(), Some("tk-abc"));
- assert!(app.login.as_ref().unwrap().verifying);
+ app.submit_user("hello".to_string());
+
+ let text = transcript_text(&app);
+ assert!(
+ text.contains("not signed in — run /login to choose a provider"),
+ "{text}"
+ );
+ assert!(!text.contains("Tokamak"), "{text}");
}
- #[tokio::test]
- async fn login_rejects_a_mispasted_key_before_any_request() {
- let mut app = test_app();
- run_command(&mut app, "login", &no_mcp()).await;
- type_key_chars(&mut app, "tk-abc def").await;
- press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+ fn with_isolated_login_state<T>(f: impl FnOnce() -> T) -> T {
+ let _guard = crate::core::server::provider_secrets::SECRET_STORE_TEST_LOCK
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ let dir = tempfile::tempdir().unwrap();
+ let prev_data_folder = std::env::var_os("JAN_DATA_FOLDER");
+ std::env::set_var("JAN_DATA_FOLDER", dir.path());
+ crate::core::server::provider_secrets::force_file_secrets();
- 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());
+ let mut env_vars = vec!["JAN_API_KEY".to_string()];
+ env_vars.extend(
+ crate::core::cli::auth::provider_catalog()
+ .into_iter()
+ .map(|provider| format!("{}_API_KEY", provider.id.to_ascii_uppercase())),
+ );
+ let prev_env: Vec<(String, Option<std::ffi::OsString>)> = env_vars
+ .into_iter()
+ .map(|var| {
+ let prev = std::env::var_os(&var);
+ std::env::remove_var(&var);
+ (var, prev)
+ })
+ .collect();
- // Empty input is likewise not worth a round trip.
- press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
- assert!(app.login_submit.is_none());
+ let result = crate::core::agent::global_config::with_temp_home(|_| f());
+
+ match prev_data_folder {
+ Some(value) => std::env::set_var("JAN_DATA_FOLDER", value),
+ None => std::env::remove_var("JAN_DATA_FOLDER"),
+ }
+ for (var, value) in prev_env {
+ match value {
+ Some(value) => std::env::set_var(var, value),
+ None => std::env::remove_var(var),
+ }
+ }
+ result
}
- #[tokio::test]
- async fn login_backspace_edits_and_esc_cancels() {
- let mut app = test_app();
- run_command(&mut app, "login", &no_mcp()).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");
+ #[test]
+ fn login_opens_catalog_provider_status_picker_without_secret_hints() {
+ with_isolated_login_state(|| {
+ crate::core::agent::global_config::set_provider(
+ "deepseek",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("sk-status-secret".into()),
+ clear_api_key: false,
+ base_url: Some("https://api.deepseek.com/v1".into()),
+ models: Some(vec!["secret-model".into()]),
+ api_type: None,
+ },
+ )
+ .unwrap();
+
+ let mut app = test_app();
+ super::open_login_picker(&mut app);
+
+ let picker = app
+ .picker
+ .as_ref()
+ .expect("/login must open a provider picker");
+ assert_eq!(picker.kind, PickerKind::LoginProvider);
+
+ let catalog = crate::core::cli::auth::provider_catalog();
+ // Expected picker order: Tokamak pinned to the top (the default
+ // provider), then the remaining providers in name order:
+ // Claude, Codex, DeepSeek, OpenCode. (catalog keeps its own order.)
+ let ordered = |catalog: &Vec<crate::core::cli::auth::ProviderDefinition>| {
+ let mut providers = catalog.clone();
+ providers.sort_by(|a, b| match (a.id == "tokamak", b.id == "tokamak") {
+ (true, false) => std::cmp::Ordering::Less,
+ (false, true) => std::cmp::Ordering::Greater,
+ _ => a.name.cmp(b.name),
+ });
+ providers
+ };
+ let ordered = ordered(&catalog);
+ assert_eq!(
+ picker
+ .items
+ .iter()
+ .map(|item| item.value.as_str())
+ .collect::<Vec<_>>(),
+ ordered.iter().map(|provider| provider.id).collect::<Vec<_>>()
+ );
+ assert_eq!(
+ picker
+ .items
+ .iter()
+ .map(|item| item.label.as_str())
+ .collect::<Vec<_>>(),
+ ordered
+ .iter()
+ .map(|provider| format!("{} ({})", provider.name, provider.id))
+ .collect::<Vec<_>>()
+ );
+ assert_eq!(
+ picker
+ .items
+ .iter()
+ .map(|item| item.hint.as_deref())
+ .collect::<Vec<_>>(),
+ ordered
+ .iter()
+ .map(|provider| {
+ if provider.id == "deepseek" {
+ Some("signed in")
+ } else {
+ Some("not signed in")
+ }
+ })
+ .collect::<Vec<_>>()
+ );
+ // Tokamak is the first row.
+ assert_eq!(picker.items.first().map(|i| i.value.as_str()), Some("tokamak"));
+ assert!(picker
+ .items
+ .iter()
+ .all(|item| matches!(item.hint.as_deref(), Some("signed in" | "not signed in"))));
+
+ let rendered = picker
+ .items
+ .iter()
+ .flat_map(|item| {
+ [
+ item.value.as_str(),
+ item.label.as_str(),
+ item.hint.as_deref().unwrap_or_default(),
+ ]
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(!rendered.contains("sk-status-secret"), "{rendered}");
+ assert!(!rendered.contains("secret-model"), "{rendered}");
+ assert!(!rendered.contains("api-keys"), "{rendered}");
+ });
+ }
+
+ #[tokio::test]
+ async fn login_provider_selection_starts_account_login_directly() {
+ let mut app = test_app();
+ super::open_login_picker(&mut app);
+ let openai = app
+ .picker
+ .as_ref()
+ .unwrap()
+ .items
+ .iter()
+ .position(|item| item.value == "openai")
+ .unwrap();
+ app.picker.as_mut().unwrap().selected = openai;
+
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+
+ assert!(app.picker.is_none());
+ assert!(app.account_login.is_some());
+ assert!(app.account_login_submit.is_some());
+ assert!(app.login.is_none());
+ }
+
+ #[tokio::test]
+ async fn login_api_key_provider_selection_starts_masked_prompt_directly() {
+ let mut app = test_app();
+ super::open_login_picker(&mut app);
+ let tokamak = app
+ .picker
+ .as_ref()
+ .unwrap()
+ .items
+ .iter()
+ .position(|item| item.value == "tokamak")
+ .unwrap();
+ app.picker.as_mut().unwrap().selected = tokamak;
+
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+
+ assert!(app.picker.is_none());
+ assert_eq!(app.login.as_ref().map(|p| p.provider.as_str()), Some("tokamak"));
+ assert!(app.account_login.is_none());
+ }
+
+ #[tokio::test]
+ async fn login_provider_picker_esc_cancels_without_mutation() {
+ let mut app = test_app();
+ super::open_login_picker(&mut app);
+
+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;
+
+ assert!(app.picker.is_none());
+ assert!(app.login.is_none());
+ assert!(app.login_submit.is_none());
+ assert!(app.account_login_submit.is_none());
+ assert!(app.account_login.is_none());
+ }
+
+ #[tokio::test]
+ async fn login_prompt_captures_keys_and_never_renders_the_key() {
+ let mut app = test_app();
+ super::open_login_prompt(&mut app, "tokamak");
+ assert!(
+ app.login.is_some(),
+ "provider selection 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();
+ super::open_login_prompt(&mut app, "tokamak");
+ app.login.as_mut().unwrap().paste(" tk-abc\n");
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+
+ assert_eq!(
+ app.login_submit.as_ref(),
+ Some(&("tokamak".to_string(), "tk-abc".to_string()))
+ );
+ assert!(app.login.as_ref().unwrap().verifying);
+ }
+
+ #[tokio::test]
+ async fn login_rejects_a_mispasted_key_before_any_request() {
+ let mut app = test_app();
+ super::open_login_prompt(&mut app, "tokamak");
+ 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();
+ super::open_login_prompt(&mut app, "tokamak");
+ 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");
@@@ -18890,16 -17534,14 +19601,16 @@@
let mut app = test_app();
// `with_temp_home` is sync; drive the async command on a dedicated runtime.
let rt = tokio::runtime::Runtime::new().unwrap();
- rt.block_on(super::run_command(&mut app, "model"));
+ rt.block_on(super::run_command(&mut app, "model", &no_mcp()));
- let picker = app.picker.as_ref().expect("model picker opened");
- assert_eq!(picker.kind, PickerKind::SelectModel);
+ let picker = app.model_picker.as_ref().expect("model picker opened");
assert!(
- picker.items.iter().any(|i| i.label.contains("discovered-model")),
+ picker
+ .all_items
+ .iter()
+ .any(|i| i.model.contains("discovered-model")),
"discovered model must be offered: {:?}",
- picker.items.iter().map(|i| &i.label).collect::<Vec<_>>()
+ picker.all_items.iter().map(|i| &i.model).collect::<Vec<_>>()
);
});
}
@@@ -23222,16 -21648,8 +23933,17 @@@
async fn plan_command_with_text_enters_plan_and_submits_it() {
use crate::core::agent::plan::RunMode;
let mut app = test_app();
- run_command(&mut app, "plan make a html cat slide. use 3 subagents to research", &no_mcp()).await;
- assert_eq!(app.run_mode, RunMode::Plan, "text arg must also enter plan mode");
+ run_command(
+ &mut app,
+ "plan make a html cat slide. use 3 subagents to research",
++ &no_mcp(),
+ )
+ .await;
+ assert_eq!(
+ app.run_mode,
+ RunMode::Plan,
+ "text arg must also enter plan mode"
+ );
assert_eq!(app.status, Status::Running, "seeded text must start a turn");
let text: String = app.transcript.iter().map(row_text).collect();
assert!(
@@@ -25925,10 -24092,8 +26637,10 @@@
async fn probe_blocks() {
let mut app = test_app();
app.note("conversation cleared");
- run_command(&mut app, "help").await;
+ run_command(&mut app, "help", &no_mcp()).await;
- for l in render_rows(&mut app, 84, 40) { println!("|{}", l.trim_end()); }
+ for l in render_rows(&mut app, 84, 40) {
+ println!("|{}", l.trim_end());
+ }
}
/// Every rendered line of the last row, as plain text.
@@@ -26047,131 -24206,394 +26759,520 @@@
Some(&Some(last)),
"the last body row must map to the last transcript row"
);
+}
+ #[test]
+ fn model_picker_pins_tokamak_scope_and_models_first() {
+ let picker = super::ModelPicker::from_pairs(
+ vec![
+ ("anthropic".into(), "claude-sonnet".into()),
+ ("openai".into(), "gpt-5-codex".into()),
+ ("tokamak".into(), "tokamak-1-preview".into()),
+ ],
+ "tokamak-1-preview",
+ )
+ .unwrap();
+
+ assert_eq!(picker.scopes[1].label, "tokamak");
+ assert_eq!(picker.items[0].provider, "tokamak");
+ assert_eq!(picker.items[0].model, "tokamak-1-preview");
+ }
+
+ #[test]
+ fn model_picker_builds_all_and_provider_scopes_with_counts() {
+ let picker = super::ModelPicker::from_pairs(
+ vec![
+ ("anthropic".into(), "claude-sonnet".into()),
+ ("openai".into(), "gpt-5-codex".into()),
+ ("openai".into(), "gpt-5-mini".into()),
+ ],
+ "gpt-5-codex",
+ )
+ .unwrap();
+
+ assert_eq!(picker.scopes[0].label, "All models");
+ assert_eq!(picker.scopes[0].count, 3);
+ assert_eq!(picker.scopes[1].label, "anthropic");
+ assert_eq!(picker.scopes[1].count, 1);
+ assert_eq!(picker.scopes[2].label, "openai");
+ assert_eq!(picker.scopes[2].count, 2);
+ assert_eq!(picker.items[picker.selected].value, "gpt-5-codex");
+ }
+
+ #[test]
+ fn model_picker_filters_all_terms_and_changes_scope() {
+ let mut picker = super::ModelPicker::from_pairs(
+ vec![
+ ("openai".into(), "gpt-5.6-luna".into()),
+ ("openai".into(), "gpt-5.6-terra".into()),
+ ("anthropic".into(), "claude-sonnet".into()),
+ ],
+ "gpt-5.6-luna",
+ )
+ .unwrap();
+
+ picker.query = "openai luna".into();
+ picker.refresh_items();
+ assert_eq!(picker.items.len(), 1);
+ assert_eq!(picker.items[0].value, "gpt-5.6-luna");
+
+ picker.select_scope(1);
+ assert_eq!(picker.scopes[picker.active_scope].label, "anthropic");
+ assert!(picker.items.iter().all(|item| item.provider == "anthropic"));
+ }
+
+ #[tokio::test]
+ async fn model_picker_enter_uses_raw_value_while_label_is_provider_scoped() {
+ let mut app = test_app();
+ app.model_picker = super::ModelPicker::from_pairs(
+ vec![("openai".into(), "gpt-5-codex".into())],
+ "missing-current",
+ );
+
+ let picker = app.model_picker.as_ref().unwrap();
+ assert_eq!(picker.items[picker.selected].provider, "openai");
+ assert_eq!(picker.items[picker.selected].model, "gpt-5-codex");
+ assert_eq!(picker.items[picker.selected].value, "gpt-5-codex");
+
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+
+ assert_eq!(app.model, "gpt-5-codex");
+ assert!(app.model_picker.is_none());
+ }
+
+ #[test]
+ fn model_picker_reopens_with_newly_written_provider_models() {
+ with_isolated_login_state(|| {
+ crate::core::agent::global_config::set_provider(
+ "tokamak",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("tk".into()),
+ clear_api_key: false,
+ base_url: Some(crate::core::cli::tokamak::BASE_URL.into()),
+ models: Some(vec!["tokamak-old".into()]),
+ api_type: None,
+ },
+ )
+ .unwrap();
+
+ let mut app = test_app();
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ rt.block_on(super::open_model_picker(&mut app));
+ assert!(app
+ .model_picker
+ .as_ref()
+ .unwrap()
+ .all_items
+ .iter()
+ .any(|item| item.value == "tokamak-old"));
+
+ crate::core::agent::global_config::set_provider(
+ "tokamak",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("tk".into()),
+ clear_api_key: false,
+ base_url: Some(crate::core::cli::tokamak::BASE_URL.into()),
+ models: Some(vec!["tokamak-old".into(), "tokamak-new".into()]),
+ api_type: None,
+ },
+ )
+ .unwrap();
+
+ rt.block_on(super::open_model_picker(&mut app));
+ let picker = app.model_picker.as_ref().unwrap();
+ assert!(picker
+ .all_items
+ .iter()
+ .any(|item| item.value == "tokamak-new"));
+ assert!(app.picker.is_none());
+ });
}
+
+ // --- `/mcp` management screen -------------------------------------------
+
+ /// Write an `mcp_config.json` with the given servers into the redirected
+ /// data folder, so the `/mcp` screen reads a real config.
+ fn write_mcp_config(folder: &std::path::Path, servers: serde_json::Value) {
+ std::fs::write(
+ folder.join("mcp_config.json"),
+ serde_json::to_string(&serde_json::json!({
+ "mcpServers": servers,
+ "mcpSettings": {},
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ }
+
+ fn rt() -> tokio::runtime::Runtime {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ }
+
+ /// The regression this whole screen exists for: a fresh install used to get
+ /// a note and no screen, so `a` (add) -- the only thing that could fix the
+ /// empty state -- was unreachable.
+ #[test]
+ fn the_mcp_screen_opens_on_a_watermark_row_when_nothing_is_configured() {
+ crate::core::app::commands::with_temp_data_folder(|_| {
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_picker(&mut app, &no_mcp()));
+
+ let picker = app.picker.as_ref().expect("the screen opens even so");
+ assert_eq!(picker.kind, PickerKind::ToggleMcp);
+ assert_eq!(picker.items.len(), 1);
+ assert!(picker.items[0].label.contains("press a to add"));
+ // An empty value marks the row inert, the way the provider screen's
+ // watermark does.
+ assert!(picker.items[0].value.is_empty());
+ assert!(picker.action_hint().contains("a add"));
+ });
+ }
+
+ #[test]
+ fn the_mcp_screen_lists_configured_servers_with_their_state() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "files": { "command": "npx", "args": ["-y", "files"], "active": true },
+ "remote": { "type": "http", "url": "https://x/mcp", "active": false },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_picker(&mut app, &no_mcp()));
+
+ let items = &app.picker.as_ref().unwrap().items;
+ assert_eq!(items.len(), 2);
+ // Sorted by name, so the order is stable across runs.
+ assert_eq!(items[0].value, "files");
+ assert_eq!(items[0].checkbox, Some(true));
+ assert!(items[0].label.contains("not connected"), "{}", items[0].label);
+ assert_eq!(items[1].value, "remote");
+ assert_eq!(items[1].checkbox, Some(false));
+ assert!(items[1].label.contains("disabled"), "{}", items[1].label);
+ });
+ }
+
+ /// An http server with no stored tokens reads as `needs auth` rather than
+ /// the bare `not connected` a stdio server gets: the two have different
+ /// fixes.
+ #[test]
+ fn an_unauthenticated_remote_server_is_labelled_needs_auth() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "remote": { "type": "http", "url": "https://x/mcp", "active": true },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_picker(&mut app, &no_mcp()));
+ assert!(app.picker.as_ref().unwrap().items[0]
+ .label
+ .contains("needs auth"));
+ });
+ }
+
+ #[test]
+ fn the_detail_screen_shows_status_auth_and_where_the_config_lives() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "remote": { "type": "http", "url": "https://x/mcp", "active": true },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_detail(&mut app, "remote", &no_mcp()));
+
+ assert_eq!(app.picker.as_ref().unwrap().kind, PickerKind::McpServer);
+ let detail = app.mcp_detail.as_ref().expect("detail is held on App");
+ let text: String = super::mcp_detail_lines(detail, 120)
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.as_ref())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ assert!(text.contains("remote"), "{text}");
+ assert!(text.contains("Status:"), "{text}");
+ assert!(text.contains("not connected"), "{text}");
+ assert!(text.contains("Auth:"), "{text}");
+ assert!(text.contains("not authenticated"), "{text}");
+ assert!(text.contains("URL:"), "{text}");
+ assert!(text.contains("https://x/mcp"), "{text}");
+ assert!(text.contains("Config location:"), "{text}");
+ assert!(text.contains("mcp_config.json"), "{text}");
+ assert!(text.contains("Tools:"), "{text}");
+ });
+ }
+
+ /// A stdio server has no HTTP transport, so the auth rows are absent rather
+ /// than present-and-inert; and a disconnected server has no tools to view.
+ #[test]
+ fn detail_actions_are_filtered_to_what_the_server_can_actually_do() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "files": { "command": "npx", "args": [], "active": true },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_detail(&mut app, "files", &no_mcp()));
+
+ let values: Vec<&str> = app
+ .picker
+ .as_ref()
+ .unwrap()
+ .items
+ .iter()
+ .map(|i| i.value.as_str())
+ .collect();
+ assert!(!values.contains(&super::MCP_ACTION_AUTH), "{values:?}");
+ assert!(!values.contains(&super::MCP_ACTION_CLEAR_AUTH), "{values:?}");
+ // Not connected, so there is nothing to list.
+ assert!(!values.contains(&super::MCP_ACTION_TOOLS), "{values:?}");
+ assert!(values.contains(&super::MCP_ACTION_TOGGLE), "{values:?}");
+ assert!(values.contains(&super::MCP_ACTION_EDIT), "{values:?}");
+ assert!(values.contains(&super::MCP_ACTION_REMOVE), "{values:?}");
+ // An active server can be reconnected; the label reads Disable.
+ assert!(values.contains(&super::MCP_ACTION_RECONNECT), "{values:?}");
+ let toggle = app
+ .picker
+ .as_ref()
+ .unwrap()
+ .items
+ .iter()
+ .find(|i| i.value == super::MCP_ACTION_TOGGLE)
+ .unwrap();
+ assert_eq!(toggle.label, "Disable");
+ // Rows are numbered, as the screen is meant to read.
+ assert_eq!(app.picker.as_ref().unwrap().items[0].hint.as_deref(), Some("1."));
+ });
+ }
+
+ #[test]
+ fn a_remote_server_offers_authenticate_and_no_clear_until_there_is_something_to_clear() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "remote": { "type": "http", "url": "https://x/mcp", "active": false },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_detail(&mut app, "remote", &no_mcp()));
+
+ let items = &app.picker.as_ref().unwrap().items;
+ let auth = items
+ .iter()
+ .find(|i| i.value == super::MCP_ACTION_AUTH)
+ .expect("an unauthenticated remote can sign in");
+ assert_eq!(auth.label, "Authenticate");
+ assert!(!items.iter().any(|i| i.value == super::MCP_ACTION_CLEAR_AUTH));
+ // Inactive, so Reconnect is not offered and the toggle reads Enable.
+ assert!(!items.iter().any(|i| i.value == super::MCP_ACTION_RECONNECT));
+ assert_eq!(
+ items
+ .iter()
+ .find(|i| i.value == super::MCP_ACTION_TOGGLE)
+ .unwrap()
+ .label,
+ "Enable"
+ );
+ });
+ }
+
+ /// A hand-written `Authorization` header is the user's own credential: OAuth
+ /// must not offer to replace it, because doing so would break it.
+ #[test]
+ fn a_hand_written_authorization_header_suppresses_the_oauth_actions() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "remote": {
+ "type": "http",
+ "url": "https://x/mcp",
+ "headers": { "Authorization": "Bearer mine" },
+ "active": true,
+ },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_detail(&mut app, "remote", &no_mcp()));
+ let items = &app.picker.as_ref().unwrap().items;
+ assert!(!items.iter().any(|i| i.value == super::MCP_ACTION_AUTH));
+ assert!(!items.iter().any(|i| i.value == super::MCP_ACTION_CLEAR_AUTH));
+ });
+ }
+
+ /// The watermark row is inert: Enter must not open a detail screen for the
+ /// empty string, and Space must not try to toggle it.
+ #[test]
+ fn the_watermark_row_does_nothing_on_enter_or_space() {
+ crate::core::app::commands::with_temp_data_folder(|_| {
+ let registry: PermissionRegistry =
+ std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()));
+ let mut current: Option<CurrentRun> = None;
+ let mut app = test_app();
+ let servers = no_mcp();
+ rt().block_on(async {
+ super::open_mcp_picker(&mut app, &servers).await;
+ for code in [KeyCode::Enter, KeyCode::Char(' ')] {
+ handle_key(
+ &mut app,
+ KeyEvent::new(code, KeyModifiers::NONE),
+ &registry,
+ &mut current,
+ &servers,
+ )
+ .await;
+ assert!(app.mcp_detail.is_none(), "{code:?} opened a detail screen");
+ assert_eq!(
+ app.picker.as_ref().map(|p| p.kind),
+ Some(PickerKind::ToggleMcp),
+ "{code:?} left the list"
+ );
+ }
+ });
+ });
+ }
+
+ /// Esc on the detail screen steps back up to the list rather than closing
+ /// `/mcp` outright.
+ #[test]
+ fn esc_on_the_detail_screen_returns_to_the_server_list() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "files": { "command": "npx", "args": [], "active": true },
+ }),
+ );
+ let registry: PermissionRegistry =
+ std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()));
+ let mut current: Option<CurrentRun> = None;
+ let mut app = test_app();
+ let servers = no_mcp();
+ rt().block_on(async {
+ super::open_mcp_detail(&mut app, "files", &servers).await;
+ assert_eq!(app.picker.as_ref().unwrap().kind, PickerKind::McpServer);
+
+ handle_key(
+ &mut app,
+ KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
+ &registry,
+ &mut current,
+ &servers,
+ )
+ .await;
+ assert_eq!(
+ app.picker.as_ref().map(|p| p.kind),
+ Some(PickerKind::ToggleMcp),
+ "Esc should step back, not close"
+ );
+ assert!(app.mcp_detail.is_none());
+ });
+ });
+ }
+
+ /// Removing a server takes its tokens with it: a later server reusing the
+ /// name must not silently inherit someone else's authorization.
+ #[test]
+ fn removing_a_server_also_forgets_its_stored_credentials() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "remote": { "type": "http", "url": "https://x/mcp", "active": false },
+ }),
+ );
+ // A credential file the removal must clean up. Spelled out rather
+ // than stubbed: an unparseable record would read as an empty store
+ // and the assertion would pass without the removal doing anything.
+ let store = folder.join("mcp_oauth.json");
+ std::fs::write(
+ &store,
+ serde_json::to_string(&serde_json::json!({
+ "remote": {
+ "client_id": "c1",
+ "tokens": {
+ "access_token": "at",
+ "token_type": "bearer",
+ "expires_in": 3600
+ },
+ "expires_at": 9_999_999_999u64,
+ "resource": "https://x/mcp"
+ }
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ // The fixture must actually load, or this test proves nothing.
+ assert!(super::super::mcp::auth_status(
+ "remote",
+ &serde_json::json!({ "type": "http", "url": "https://x/mcp" })
+ ) != crate::core::mcp::oauth::AuthStatus::Unauthenticated);
+
+ let mut app = test_app();
+ rt().block_on(super::remove_mcp_server(&mut app, "remote", &no_mcp()));
+
+ assert!(super::super::mcp::get_server("remote").is_none());
+ let left = std::fs::read_to_string(&store).unwrap_or_default();
+ assert!(!left.contains("remote"), "credentials survived: {left}");
+ });
+ }
+
+ /// The detail screen must open in one frame, so the tool list is requested
+ /// as a job rather than awaited inline.
+ #[test]
+ fn a_connected_servers_tool_list_is_requested_as_a_job_not_awaited() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "files": { "command": "npx", "args": [], "active": true },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_detail(&mut app, "files", &no_mcp()));
+ // Not connected here, so nothing is requested and the state says why.
+ assert!(app.mcp_job_request.is_none());
+ assert!(matches!(
+ app.mcp_detail.as_ref().unwrap().tools,
+ super::ToolsState::Unavailable
+ ));
+ });
+ }
+
+ #[test]
+ fn a_long_value_is_clamped_instead_of_pushing_the_border_off_the_frame() {
+ use ratatui::text::Span;
+ let line = Line::from(vec![
+ Span::raw("URL: "),
+ Span::raw("x".repeat(400)),
+ ]);
+ let clamped = super::clamp_line(line, 40);
+ let width: usize = clamped
+ .spans
+ .iter()
+ .map(|s| s.content.chars().count())
+ .sum();
+ assert!(width <= 38, "clamped to {width}");
+ assert!(clamped
+ .spans
+ .last()
+ .unwrap()
+ .content
+ .ends_with('\u{2026}'));
+ }
+
}