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
thinhlpg541ecffd06b8
diff --cc src-tauri/src/core/agent/loop.rsindex 558e25061,0845da597..94ebd0fbe--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@@ -4,27 -4,27 +4,26 @@@//! events, and one terminal `Done`/`Error`) while still returning the final//! completion JSON, so the API server's original contract is unchanged.++use async_trait::async_trait;use std::collections::HashMap;use std::sync::atomic::{AtomicUsize, Ordering};--use std::sync::Arc;----use async_trait::async_trait;- use reqwest::Client;++use std::sync::{Arc, LazyLock};+ // Agent upstream traffic runs on `genai`, which is built against reqwest 0.13;+ // the rest of the app is still on 0.12, so the two `Client` types differ.+ use reqwest13::Client;#[cfg(not(feature = "cli"))]use tauri_plugin_llamacpp::state::LlamacppState;use tokio::sync::{mpsc, Mutex};use crate::core::agent::events::{StreamEvent, Usage};use crate::core::agent::session::SessionBudget;--use tauri_plugin_agent_tools::tools::gate::{DenyReason, PermissionDecision};use crate::core::agent::upstream::{collect_mcp_openai_tools, copy_optional_chat_params, drop_malformed_tool_calls,execute_mcp_tool_calls, extract_choice_message, extract_tool_calls, load_assistant_config,- parse_openai_messages, repair_dangling_tool_calls, resolve_upstream_for_model,- set_system_prompt, stream_openai_chat_completions,+ parse_openai_messages, repair_dangling_tool_calls, resolve_api_type_for_model,- resolve_upstream_for_model,- set_system_prompt, stream_openai_chat_completions,++ resolve_upstream_for_model, set_system_prompt, stream_openai_chat_completions,};+use crate::core::server::converters::{converter_for, UpstreamConverter};#[cfg(not(feature = "cli"))]use crate::core::server::proxy::router_first_model;#[cfg(not(feature = "cli"))]@@@ -33,6 -33,6 +32,7 @@@ use crate::core::mcp::models::McpSettings,state::{ProviderConfig, SharedMcpServers},};++use tauri_plugin_agent_tools::tools::gate::{DenyReason, PermissionDecision};/// In-flight permission prompts keyed by `request_id`, shared between the loop/// (which inserts a one-shot sender before awaiting) and the respond command@@@ -143,22 -143,14 +143,29 @@@ impl ToolOutcome#[async_trait]pub(crate) trait ToolInvoker: Send + Sync {-- async fn invoke(&self, tool_calls: &[serde_json::Value])-- -> Result<Vec<ToolOutcome>, String>;++ async fn invoke(&self, tool_calls: &[serde_json::Value]) -> Result<Vec<ToolOutcome>, String>;}struct HttpModelInvoker {client: Client,upstream_url: String,api_keys: Vec<String>,+ /// Provider registry, used to strip a `<provider>/` qualifier from the+ /// request's `model` field (the upstream must receive the bare model id).+ provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,+ /// When the provider fronts a native (non-chat/completions) wire API+ /// (Anthropic `/messages`, OpenAI `/responses`, Google `generateContent`),+ /// this converter translates the request and decodes the upstream stream+ /// back into chat shape. `None` keeps the verbatim chat/completions path.+ converter: Option<Box<dyn UpstreamConverter>>,++ /// Native provider converters still use reqwest 0.12 while the default++ /// agent path uses genai's reqwest 0.13 client.++ converter_client: reqwest::Client,++}++++fn converter_http_client() -> reqwest::Client {++ static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new);++ CLIENT.clone()}#[async_trait]@@@ -168,38 -160,17 +175,40 @@@ impl ModelInvoker for HttpModelInvokerrequest: &serde_json::Value,events: &mpsc::UnboundedSender<StreamEvent>,) -> Result<serde_json::Value, String> {- stream_openai_chat_completions(- &self.client,- &self.upstream_url,- &self.api_keys,- // The agent speaks OpenAI chat/completions to every provider; see- // the note on `stream_openai_chat_completions`.- None,- request,- events,- )- .await+ // `provider/model` is the CLI's explicit selection syntax. The upstream+ // URL + credential have already been resolved from that qualifier, so+ // the body must carry the bare model id - providers like OpenCode GO+ // reject a provider-qualified id with "model not supported".+ let mut normalized = request.clone();+ if let Some(model) = normalized.get("model").and_then(|m| m.as_str()) {+ let pc = self.provider_configs.lock().await;+ let bare = crate::core::agent::upstream::strip_provider_prefix(model, &pc);+ if bare != model {+ normalized["model"] = serde_json::json!(bare);+ }+ }+ if let Some(converter) = &self.converter {+ crate::core::agent::upstream::stream_converted_chat_completions(- &self.client,++ &self.converter_client,+ &self.upstream_url,+ &self.api_keys,+ converter.as_ref(),+ &normalized,+ events,+ )+ .await+ } else {+ stream_openai_chat_completions(+ &self.client,+ &self.upstream_url,+ &self.api_keys,++ // The agent speaks OpenAI chat/completions to default providers.++ None,+ &normalized,+ events,+ )+ .await+ }}}@@@ -212,10 -182,10 +220,7 @@@ struct McpToolInvoker#[async_trait]impl ToolInvoker for McpToolInvoker {-- async fn invoke(-- &self,-- tool_calls: &[serde_json::Value],-- ) -> Result<Vec<ToolOutcome>, String> {++ async fn invoke(&self, tool_calls: &[serde_json::Value]) -> Result<Vec<ToolOutcome>, String> {let results = execute_mcp_tool_calls(tool_calls,&self.tool_to_server,@@@ -360,7 -344,7 +379,10 @@@ fn ask_timeout_setting() -> Option<std:/// Whether `bash` would be confined in `project_root` with no `--sandbox` flag/// passed: the answer `jan cli agent status` reports and the TUI notices on.pub fn effective_sandbox(project_root: &std::path::Path) -> bool {-- resolve_sandbox(None, crate::core::agent::project::run_settings(project_root).sandbox)++ resolve_sandbox(++ None,++ crate::core::agent::project::run_settings(project_root).sandbox,++ )}/// agent.toml resolved for one run: the skill whitelist, plus the network@@@ -528,7 -550,7 +588,8 @@@ impl CompositeToolInvokerlet mut registry = SubagentRegistry::load(&self.project_root);match registry.create_in(&dir, def.clone(), scope, overwrite) {Ok(shadows) => {-- let mut msg = format!("Created {scope_label}-scope subagent '{}'.", def.name);++ let mut msg =++ format!("Created {scope_label}-scope subagent '{}'.", def.name);if shadows {msg.push_str(" Note: it shadows a user-scope subagent of the same name.",@@@ -587,8 -642,8 +681,7 @@@async fn handle_todo_tool(&self, args: &serde_json::Value) -> String {use crate::core::agent::todo::{parse_target, render_result, TodoPhase};let Some(registry) = &self.todo_registry else {-- return "ERROR [todo_unavailable]: todo tool requires an attached session"-- .to_string();++ return "ERROR [todo_unavailable]: todo tool requires an attached session".to_string();};let op = args.get("op").and_then(|v| v.as_str()).unwrap_or("");let mut list = registry.lock().await;@@@ -598,7 -653,7 +691,11 @@@list_val.iter().map(|p| {-- let name = p.get("phase").and_then(|v| v.as_str()).unwrap_or("").to_string();++ let name = p++ .get("phase")++ .and_then(|v| v.as_str())++ .unwrap_or("")++ .to_string();let items = p.get("items").and_then(|v| v.as_array())@@@ -653,7 -708,7 +750,12 @@@let items: Vec<String> = args.get("items").and_then(|v| v.as_array())-- .map(|arr| arr.iter().filter_map(|v| v.as_str()).map(String::from).collect())++ .map(|arr| {++ arr.iter()++ .filter_map(|v| v.as_str())++ .map(String::from)++ .collect()++ }).unwrap_or_default();if phase.is_empty() || items.is_empty() {return "ERROR: append requires 'phase' and non-empty 'items'".to_string();@@@ -667,7 -722,7 +769,9 @@@Ok(()) => {let snapshot = list.clone();drop(list);-- let _ = self.events.send(StreamEvent::TodoUpdate { list: snapshot.clone() });++ let _ = self.events.send(StreamEvent::TodoUpdate {++ list: snapshot.clone(),++ });render_result(&snapshot)}Err(error) => format!("ERROR: {error}"),@@@ -711,10 -766,10 +815,7 @@@ fn plan_mode_read_only_msg(name: &str)#[async_trait]impl ToolInvoker for CompositeToolInvoker {-- async fn invoke(-- &self,-- tool_calls: &[serde_json::Value],-- ) -> Result<Vec<ToolOutcome>, String> {++ async fn invoke(&self, tool_calls: &[serde_json::Value]) -> Result<Vec<ToolOutcome>, String> {use tauri_plugin_agent_tools::tools::{gate::{resolve_decision, Decision, PromptKind},handlers::{execute_builtin_with_diff, preview_diff},@@@ -768,7 -823,7 +869,11 @@@// Subagent tools are handled ahead of the fs/exec gate and the MCP// fallback: they orchestrate nested runs, not filesystem access.if crate::core::agent::subagent::is_subagent_tool(name) {-- let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();++ let id = tc++ .get("id")++ .and_then(|v| v.as_str())++ .unwrap_or("")++ .to_string();// Plan mode blocks subagent dispatch (a subagent could mutate).// They are not advertised in Plan; this is defense in depth// against a stale tool schema. Auto-approval cannot override.@@@ -787,7 -842,7 +892,11 @@@continue;}if !is_builtin(name) {-- let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();++ let id = tc++ .get("id")++ .and_then(|v| v.as_str())++ .unwrap_or("")++ .to_string();// Plan mode blocks all MCP tools: their capability is arbitrary// and unknowable, so they are never advertised in Plan and are// hard-denied here as defense in depth. Auto-approval cannot override.@@@ -879,8 -934,8 +988,7 @@@.with_home_readonly(allow_home_read).with_sandbox(sandbox).with_scratch_root(&scratch);-- let (text, diff, images) =-- execute_builtin_with_diff(tool, &args, &ctx).await;++ let (text, diff, images) = execute_builtin_with_diff(tool, &args, &ctx).await;ToolOutcome {id,content: text,@@@ -1324,7 -1389,7 +1442,9 @@@ async fn orchestrate_inner// names the scratch, and whether there *is* one is the sandbox decision, so// both have to read the same answer or the model is told about a directory// nothing binds.-- let settings = project_root.as_deref().map(|root| resolve_run_settings(root, *sandbox));++ let settings = project_root++ .as_deref()++ .map(|root| resolve_run_settings(root, *sandbox));let mut system_prompt = build_run_system_prompt(assistant_instructions.as_deref(),@@@ -1349,7 -1414,7 +1469,10 @@@}}// Always tell the model today's date, including isolated child runs.-- let date_line = format!("Today's date is {}.", chrono::Local::now().format("%Y-%m-%d"));++ let date_line = format!(++ "Today's date is {}.",++ chrono::Local::now().format("%Y-%m-%d")++ );let system_prompt = match system_prompt {Some(sys) => format!("{date_line}\n\n{sys}"),None => date_line,@@@ -1487,9 -1557,9 +1615,10 @@@if args.subagents_enabled && run_mode != crate::core::agent::plan::RunMode::Plan {if let Some(root) = project_root {let registry = crate::core::agent::subagent::SubagentRegistry::load(root);-- for schema in-- crate::core::agent::subagent::subagent_tool_schemas(®istry, *max_parallel_subagents)-- {++ for schema in crate::core::agent::subagent::subagent_tool_schemas(++ ®istry,++ *max_parallel_subagents,++ ) {let name = schema["function"]["name"].as_str().unwrap_or_default();if permissions.is_denied(name) {continue;@@@ -1540,10 -1610,6 +1669,11 @@@client: client.clone(),upstream_url,api_keys: session_api_keys,+ provider_configs: provider_configs.clone(),+ converter: resolve_api_type_for_model(&model_id, provider_configs.clone())+ .await+ .and_then(|(api_type, oauth)| converter_for(Some(&api_type), oauth)),++ converter_client: converter_http_client(),};let mcp_tools = McpToolInvoker {tool_to_server,@@@ -1602,7 -1668,7 +1732,9 @@@permission_requests: permission_requests.clone(),ask_requests: ask_requests.clone(),todo_registry: todo_registry.clone(),-- grants: std::sync::Mutex::new(tauri_plugin_agent_tools::tools::gate::SessionGrants::default()),++ grants: std::sync::Mutex::new(++ tauri_plugin_agent_tools::tools::gate::SessionGrants::default(),++ ),subagents,auto_approve: *auto_approve,run_mode,@@@ -1630,9 -1696,9 +1762,11 @@@}if index_memory {if let Ok(completion) = &result {-- if let Some(answer) = extract_choice_message(completion)-- .and_then(|m| m.get("content").and_then(|c| c.as_str()).map(str::to_string))-- {++ if let Some(answer) = extract_choice_message(completion).and_then(|m| {++ m.get("content")++ .and_then(|c| c.as_str())++ .map(str::to_string)++ }) {crate::core::agent::memory::index_message(root, "assistant", &answer);}}@@@ -1705,10 -1771,10 +1839,7 @@@ fn build_completion_request};let mut completion_map = serde_json::Map::new();completion_map.insert("model".to_string(), serde_json::json!(model_id));-- completion_map.insert(-- "messages".to_string(),-- serde_json::Value::Array(messages),-- );++ completion_map.insert("messages".to_string(), serde_json::Value::Array(messages));let tool_choice = forced_tool_choice.filter(|name| {openai_tools@@@ -1754,18 -1820,14 +1885,14 @@@ pub(crate) async fn compact_historyclient: args.client.clone(),upstream_url,api_keys,+ provider_configs: args.provider_configs.clone(),+ converter: resolve_api_type_for_model(model_id, args.provider_configs.clone())+ .await+ .and_then(|(api_type, oauth)| converter_for(Some(&api_type), oauth)),++ converter_client: converter_http_client(),};- crate::core::agent::compaction::compact_conversation(- Ok(crate::core::agent::compaction::compact_conversation(-- messages,-- model_id,-- &model,-- keep_recent,-- )- .await- .await)++ crate::core::agent::compaction::compact_conversation(messages, model_id, &model, keep_recent)++ .await}/// Run one stateless `/goal` evaluation against `smol_model_id` (the session's@@@ -1792,10 -1854,6 +1919,11 @@@ pub(crate) async fn evaluate_goalclient: args.client.clone(),upstream_url,api_keys,+ provider_configs: args.provider_configs.clone(),+ converter: resolve_api_type_for_model(smol_model_id, args.provider_configs.clone())+ .await+ .and_then(|(api_type, oauth)| converter_for(Some(&api_type), oauth)),++ converter_client: converter_http_client(),};crate::core::agent::goal::evaluate(smol_model_id, condition, messages, &model).await}@@@ -2010,6 -2072,34 +2142,40 @@@ async fn run_turn_cyclecontinue;}}+ // Every turn is finished and the run passed its token ceiling, so+ // the conversation is both complete and oversized. Compact it here,+ // while nothing is waiting on the result: the ceiling no longer+ // stops a run, so without this the thread only grows, and the next+ // run resumes it by sending the whole oversized history upstream.+ // The reactive path above cannot help with that -- it only fires+ // once an upstream has already rejected a request.+ //+ // Only when it actually shrinks: `compact_conversation` returns the+ // input untouched when there is too little to drop, and publishing+ // an unchanged history would spend a summarizer call for nothing.+ if budget.exhausted() {- let compacted = crate::core::agent::compaction::compact_conversation(++ match crate::core::agent::compaction::compact_conversation(+ &conversation_messages,+ model_id,+ model,+ crate::core::agent::compaction::DEFAULT_KEEP_RECENT,+ )- .await;- if compacted.len() < conversation_messages.len() {- log::info!(- "agent: budget exhausted at end of run, compacted {} -> {} messages",- conversation_messages.len(),- compacted.len()- );- conversation_messages = compacted;++ .await++ {++ Ok(compacted) if compacted.len() < conversation_messages.len() => {++ log::info!(++ "agent: budget exhausted at end of run, compacted {} -> {} messages",++ conversation_messages.len(),++ compacted.len()++ );++ conversation_messages = compacted;++ }++ Ok(_) => {}++ Err(error) => {++ log::warn!("agent: budget exhausted but compaction failed: {error}");++ }+ }+ }let _ = events.send(StreamEvent::MessagesUpdated {messages: conversation_messages.clone(),});@@@ -2116,7 -2199,7 +2275,11 @@@// sees the error and retries with a shorter response next turn.if stop_reason_of(&completion) == "length" {for tc in &tool_calls {-- let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();++ let id = tc++ .get("id")++ .and_then(|v| v.as_str())++ .unwrap_or("")++ .to_string();let content ="ERROR: response truncated (finish_reason=length); tool-call arguments are \incomplete and were not executed. Retry with a shorter response."@@@ -2328,7 -2411,7 +2491,10 @@@ mod testsstd::sync::Arc::new(tokio::sync::Mutex::new(TodoList {phases: vec![TodoPhase {name: "P".into(),-- tasks: vec![TodoItem { content: "t1".into(), status: TodoStatus::Pending }],++ tasks: vec![TodoItem {++ content: "t1".into(),++ status: TodoStatus::Pending,++ }],}],}))}@@@ -2830,7 -2913,7 +2996,10 @@@std::sync::Arc::new(tokio::sync::Mutex::new(TodoList {phases: vec![TodoPhase {name: "P".into(),-- tasks: vec![TodoItem { content: "t1".into(), status: TodoStatus::InProgress }],++ tasks: vec![TodoItem {++ content: "t1".into(),++ status: TodoStatus::InProgress,++ }],}],}))}@@@ -2864,10 -2947,10 +3033,14 @@@let mut responses: Vec<serde_json::Value> = (0..13).map(|i| mutating_tool_call_completion(&format!("call_{i}"), "bash")).collect();-- responses.push(json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }));++ responses.push(++ json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }),++ );// The task is still open at that first stop, so the close-out nudge// spends one more turn before the loop hands back; answer it too.-- responses.push(json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }));++ responses.push(++ json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }),++ );let model = MockModel::new(responses);let tool = MockTool::default();let mut budget = SessionBudget::new(None);@@@ -2893,9 -2976,9 +3066,15 @@@let requests = model.requests.lock().unwrap();let nudges = nudge_message_count(requests.last().expect("at least one request"));-- assert!(nudges >= 1, "expected a mid-run nudge after 12+ mutating calls");++ assert!(++ nudges >= 1,++ "expected a mid-run nudge after 12+ mutating calls"++ );// MID_RUN_NUDGE_MAX_PER_CYCLE is local to run_turn_cycle; mirror it here.-- assert!(nudges <= 2, "must not exceed the per-cycle nudge cap, saw {nudges}");++ assert!(++ nudges <= 2,++ "must not exceed the per-cycle nudge cap, saw {nudges}"++ );}/// A resumed/multi-turn session still needs the upkeep instruction: the@@@ -2907,7 -2990,7 +3086,10 @@@let registry = Some(todo_registry_with_open_task());// Not a first-message candidate (eager_todo_plan == false), list exists.let addendum = todo_prompt_addendum(false, ®istry).await;-- assert_eq!(addendum, Some(crate::core::agent::context::TODO_UPKEEP_PROMPT_ADDENDUM));++ assert_eq!(++ addendum,++ Some(crate::core::agent::context::TODO_UPKEEP_PROMPT_ADDENDUM)++ );// A first substantive message gets the init guidance instead.assert_eq!(@@@ -2960,9 -3043,9 +3142,7 @@@let requests = model.requests.lock().unwrap();assert_eq!(requests.len(), 2, "one extra turn for the close-out ask");-- let closeouts = requests-- .last()-- .expect("second request")["messages"]++ let closeouts = requests.last().expect("second request")["messages"].as_array().expect("messages").iter()@@@ -3013,7 -3096,7 +3193,9 @@@let mut responses: Vec<serde_json::Value> = (0..13).map(|i| mutating_tool_call_completion(&format!("call_{i}"), "bash")).collect();-- responses.push(json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }));++ responses.push(++ json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }),++ );let model = MockModel::new(responses);let tool = MockTool::default();let mut budget = SessionBudget::new(None);@@@ -3037,7 -3120,7 +3219,12 @@@.await.unwrap();assert!(-- model.requests.lock().unwrap().iter().all(|r| !request_has_nudge(r)),++ model++ .requests++ .lock()++ .unwrap()++ .iter()++ .all(|r| !request_has_nudge(r)),"plan mode must never get a mid-run nudge");}@@@ -3052,10 -3135,10 +3239,14 @@@.collect();responses.push(mutating_tool_call_completion("mid", "todo"));responses.extend((0..6).map(|i| mutating_tool_call_completion(&format!("b{i}"), "edit")));-- responses.push(json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }));++ responses.push(++ json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }),++ );// The task is still open at that first stop, so the close-out nudge// spends one more turn before the loop hands back; answer it too.-- responses.push(json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }));++ responses.push(++ json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }),++ );let model = MockModel::new(responses);let tool = MockTool::default();let mut budget = SessionBudget::new(None);@@@ -3079,7 -3162,7 +3270,12 @@@.await.unwrap();assert!(-- model.requests.lock().unwrap().iter().all(|r| !request_has_nudge(r)),++ model++ .requests++ .lock()++ .unwrap()++ .iter()++ .all(|r| !request_has_nudge(r)),"a todo touch partway through must reset the mutation counter");}@@@ -3096,7 -3179,7 +3292,11 @@@Ok(tool_calls.iter().map(|tc| {-- let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();++ let id = tc++ .get("id")++ .and_then(|v| v.as_str())++ .unwrap_or("")++ .to_string();ToolOutcome::plain(id, self.content.clone())}).collect())@@@ -3125,7 -3208,7 +3325,9 @@@bash_call_completion(),json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }),]);-- let tool = FixedTool { content: content.to_string() };++ let tool = FixedTool {++ content: content.to_string(),++ };let mut budget = SessionBudget::new(None);run_turn_cycle(&tx,@@@ -3188,28 -3280,56 +3399,60 @@@None,).await- .expect("budget exhaustion is a soft stop, not an error");+ .expect("passing the ceiling is not an error");- let final_text = extract_choice_message(&result)- .and_then(|m| m.get("content").and_then(|c| c.as_str()))- .unwrap_or_default();- let spent = budget.spent();assert!(- final_text.contains("budget")- && final_text.contains(&spent.to_string()),- "soft stop should describe the exhausted budget ({spent} tokens): {final_text}",+ budget.exhausted(),+ "precondition: the run really did cross the ceiling");assert!(- tool.calls.lock().unwrap().is_empty(),- "tool must not run once budget is exhausted"+ !tool.calls.lock().unwrap().is_empty(),+ "tool calls still run once the ceiling is passed"+ );+ assert_eq!(+ extract_choice_message(&result)+ .and_then(|m| m.get("content").and_then(|c| c.as_str()))+ .unwrap_or_default(),+ "all done",+ "the run finishes on the model's own answer, not a stop notice"+ );++ // Announced exactly once, in the system voice -- never as an assistant+ // turn the model could later imitate.+ let requests = model.requests.lock().unwrap();+ assert_eq!(requests.len(), 3, "the run kept taking turns");+ // The last request is two turns past the ceiling: if the latch were+ // missing, the note would appear once per turn here.+ let messages = requests[2]["messages"].as_array().unwrap();+ let notes: Vec<&serde_json::Value> = messages+ .iter()+ .filter(|m| {+ m.get("content")+ .and_then(|c| c.as_str())+ .is_some_and(|c| c.contains("budget exhausted"))+ })+ .collect();- assert_eq!(notes.len(), 1, "announced once, not per turn: {messages:#?}");++ assert_eq!(++ notes.len(),++ 1,++ "announced once, not per turn: {messages:#?}"+ );- // A MessagesUpdated is published so live surfaces (and the replay- // session) see the partial conversation before the soft stop.+ assert_eq!(notes[0]["role"], "system", "system voice, not assistant");assert!(- std::iter::from_fn(|| rx.try_recv().ok()).any(- |ev| matches!(ev, StreamEvent::MessagesUpdated { .. })- messages- .iter()- .all(|m| m.get("role").and_then(|v| v.as_str()) != Some("assistant")++ messages.iter().all(++ |m| m.get("role").and_then(|v| v.as_str()) != Some("assistant")+ || !m["content"]+ .as_str()+ .unwrap_or_default()- .contains("budget exhausted")),++ .contains("budget exhausted")+ ),- "expected a MessagesUpdated event on soft stop"+ "no assistant turn carries the marker"+ );++ assert!(+ std::iter::from_fn(|| rx.try_recv().ok())+ .any(|ev| matches!(ev, StreamEvent::MessagesUpdated { .. })),+ "live surfaces see the annotated conversation");}@@@ -3258,9 -3508,9 +3631,22 @@@convo.push(json!({ "role": r, "content": format!("m{i}") }));}-- let result = run_turn_cycle(&tx, &json!({}), "m", &[], convo, 8, &mut budget, &model, &tool, crate::core::agent::plan::RunMode::Normal, None, None)-- .await-- .unwrap();++ let result = run_turn_cycle(++ &tx,++ &json!({}),++ "m",++ &[],++ convo,++ 8,++ &mut budget,++ &model,++ &tool,++ crate::core::agent::plan::RunMode::Normal,++ None,++ None,++ )++ .await++ .unwrap();assert_eq!(result["choices"][0]["message"]["content"], "final");assert!(tool.calls.lock().unwrap().is_empty());@@@ -3292,9 -3542,9 +3678,22 @@@json!({ "role": "user", "content": "again" }),];-- let result = run_turn_cycle(&tx, &json!({}), "m", &[], convo, 8, &mut budget, &model, &tool, crate::core::agent::plan::RunMode::Normal, None, None)-- .await-- .unwrap();++ let result = run_turn_cycle(++ &tx,++ &json!({}),++ "m",++ &[],++ convo,++ 8,++ &mut budget,++ &model,++ &tool,++ crate::core::agent::plan::RunMode::Normal,++ None,++ None,++ )++ .await++ .unwrap();assert_eq!(result["choices"][0]["message"]["content"], "final");let published: Vec<serde_json::Value> = std::iter::from_fn(|| rx.try_recv().ok())@@@ -3331,8 -3581,8 +3730,21 @@@json!({ "role": "assistant", "content": "hey", "reasoning_content": "thinking" }),];-- let result = run_turn_cycle(&tx, &json!({}), "m", &[], convo, 8, &mut budget, &model, &tool, crate::core::agent::plan::RunMode::Normal, None, None)-- .await;++ let result = run_turn_cycle(++ &tx,++ &json!({}),++ "m",++ &[],++ convo,++ 8,++ &mut budget,++ &model,++ &tool,++ crate::core::agent::plan::RunMode::Normal,++ None,++ None,++ )++ .await;assert!(result.is_err(), "a persistent rejection must fail the turn");assert_eq!(@@@ -3412,70 -3662,6 +3824,68 @@@);}+ /// When the *target-model summarizer* itself overflows, compaction must not+ /// fabricate a fallback-note history (which could still overflow and would+ /// silently drop the whole span). The turn exits with the summarizer error+ /// and no `MessagesUpdated` is published for a made-up history.+ #[tokio::test]+ async fn turn_cycle_surfaces_summarizer_overflow_without_fabricating_history() {+ let (tx, mut rx) = mpsc::unbounded_channel();+ let overflow = || {+ Err(format!(+ "[{}] Upstream returned HTTP 400: prompt is too long",+ crate::core::agent::upstream::CONTEXT_OVERFLOW_MARKER+ ))+ };+ // 1) the main request overflows, 2) the summarizer it spawned overflows too.+ let model = ResultQueueModel {+ results: StdMutex::new(vec![overflow(), overflow()].into_iter().collect()),+ };+ let tool = MockTool::default();+ let mut budget = SessionBudget::new(None);+ let mut convo = vec![json!({ "role": "system", "content": "sys" })];+ for i in 0..60 {+ let r = if i % 2 == 0 { "user" } else { "assistant" };+ convo.push(json!({ "role": r, "content": format!("m{i}") }));+ }++ let result = run_turn_cycle(+ &tx,+ &json!({}),+ "m",+ &[],+ convo,+ 8,+ &mut budget,+ &model,+ &tool,+ crate::core::agent::plan::RunMode::Normal,+ None,+ None,+ )+ .await;++ assert!(+ result.is_err(),+ "a summarizer context overflow must fail the turn"+ );+ assert!(- crate::core::agent::upstream::is_context_overflow_error(- result.as_ref().unwrap_err()- ),++ crate::core::agent::upstream::is_context_overflow_error(result.as_ref().unwrap_err()),+ "the summarizer overflow must propagate, not be rewritten"+ );+ drop(tx);+ let mut published = false;+ while let Ok(ev) = rx.try_recv() {+ if let StreamEvent::MessagesUpdated { .. } = ev {+ published = true;+ }+ }+ assert!(+ !published,+ "no fabricated compacted history may be published"+ );+ }+#[tokio::test]async fn turn_cycle_skips_execution_on_truncated_tool_calls() {let (tx, _rx) = mpsc::unbounded_channel();@@@ -3489,9 -3675,9 +3899,22 @@@let mut budget = SessionBudget::new(None);let convo = vec![json!({ "role": "user", "content": "hi" })];-- let result = run_turn_cycle(&tx, &json!({}), "m", &[], convo, 8, &mut budget, &model, &tool, crate::core::agent::plan::RunMode::Normal, None, None)-- .await-- .unwrap();++ let result = run_turn_cycle(++ &tx,++ &json!({}),++ "m",++ &[],++ convo,++ 8,++ &mut budget,++ &model,++ &tool,++ crate::core::agent::plan::RunMode::Normal,++ None,++ None,++ )++ .await++ .unwrap();assert_eq!(result["choices"][0]["message"]["content"], "recovered");assert!(@@@ -3513,9 -3699,9 +3936,22 @@@// max_turns = 0 means unbounded: it must not error out and must keep// going past the tool-call turn to return the final answer.-- let result = run_turn_cycle(&tx, &json!({}), "m", &[], convo, 0, &mut budget, &model, &tool, crate::core::agent::plan::RunMode::Normal, None, None)-- .await-- .unwrap();++ let result = run_turn_cycle(++ &tx,++ &json!({}),++ "m",++ &[],++ convo,++ 0,++ &mut budget,++ &model,++ &tool,++ crate::core::agent::plan::RunMode::Normal,++ None,++ None,++ )++ .await++ .unwrap();assert_eq!(result["choices"][0]["message"]["content"], "done");}@@@ -3530,7 -3716,7 +3966,10 @@@#[test]fn session_budget_treats_zero_and_absent_as_no_ceiling() {assert_eq!(body_session_budget(&json!({})), None);-- assert_eq!(body_session_budget(&json!({ "max_session_tokens": 0 })), None);++ assert_eq!(++ body_session_budget(&json!({ "max_session_tokens": 0 })),++ None++ );assert_eq!(body_session_budget(&json!({ "max_session_tokens": 128_000 })),Some(128_000)@@@ -3740,13 -3926,13 +4179,25 @@@#[test]fn unsandboxed_prompt_does_not_advertise_a_scratch() {let root = unique_project_root();-- let confined =-- build_run_system_prompt(None, Some("do things"), Some(&root), Some("s1"), false, true)-- .expect("prompt");++ let confined = build_run_system_prompt(++ None,++ Some("do things"),++ Some(&root),++ Some("s1"),++ false,++ true,++ )++ .expect("prompt");assert!(confined.contains("Scratch:"), "{confined}");-- let bare =-- build_run_system_prompt(None, Some("do things"), Some(&root), Some("s1"), false, false)-- .expect("prompt");++ let bare = build_run_system_prompt(++ None,++ Some("do things"),++ Some(&root),++ Some("s1"),++ false,++ false,++ )++ .expect("prompt");assert!(!bare.contains("Scratch:"), "{bare}");}@@@ -3759,11 -3945,11 +4210,8 @@@fn cli_tool_context_allows_network() {let root = std::path::PathBuf::from("/tmp/jan-net-check");let (tx, _rx) = mpsc::unbounded_channel();-- let invoker = build_prompting_invoker(-- root,-- tx,-- Arc::new(tokio::sync::Mutex::new(HashMap::new())),-- );++ let invoker =++ build_prompting_invoker(root, tx, Arc::new(tokio::sync::Mutex::new(HashMap::new())));assert!(invoker.tool_context().allow_network,"CLI shell must keep its network namespace"@@@ -3777,11 -3963,11 +4225,8 @@@fn cli_tool_context_reads_home() {let root = std::path::PathBuf::from("/tmp/jan-home-check");let (tx, _rx) = mpsc::unbounded_channel();-- let invoker = build_prompting_invoker(-- root,-- tx,-- Arc::new(tokio::sync::Mutex::new(HashMap::new())),-- );++ let invoker =++ build_prompting_invoker(root, tx, Arc::new(tokio::sync::Mutex::new(HashMap::new())));assert!(invoker.tool_context().home_readonly,"CLI shell must read $HOME"@@@ -3796,11 -3982,11 +4241,8 @@@fn desktop_tool_context_withholds_home() {let root = std::path::PathBuf::from("/tmp/jan-home-check");let (tx, _rx) = mpsc::unbounded_channel();-- let invoker = build_prompting_invoker(-- root,-- tx,-- Arc::new(tokio::sync::Mutex::new(HashMap::new())),-- );++ let invoker =++ build_prompting_invoker(root, tx, Arc::new(tokio::sync::Mutex::new(HashMap::new())));assert!(!invoker.tool_context().home_readonly);}@@@ -3811,11 -3997,11 +4253,8 @@@fn desktop_tool_context_withholds_network() {let root = std::path::PathBuf::from("/tmp/jan-net-check");let (tx, _rx) = mpsc::unbounded_channel();-- let invoker = build_prompting_invoker(-- root,-- tx,-- Arc::new(tokio::sync::Mutex::new(HashMap::new())),-- );++ let invoker =++ build_prompting_invoker(root, tx, Arc::new(tokio::sync::Mutex::new(HashMap::new())));assert!(!invoker.tool_context().allow_network);}@@@ -3899,10 -4113,10 +4366,17 @@@// An unknown (non-builtin) name stands in for an MCP tool a stale schema// could still surface; it must be denied before any dispatch.-- let out = invoker.invoke(&[tool_call("m1", "some_mcp_tool")]).await.unwrap();++ let out = invoker++ .invoke(&[tool_call("m1", "some_mcp_tool")])++ .await++ .unwrap();assert_eq!(out.len(), 1);-- assert!(out[0].content.contains("plan_mode_read_only"), "{}", out[0].content);++ assert!(++ out[0].content.contains("plan_mode_read_only"),++ "{}",++ out[0].content++ );let _ = std::fs::remove_dir_all(&root);}@@@ -3920,7 -4134,7 +4394,11 @@@.unwrap();assert_eq!(out.len(), 1);-- assert!(out[0].content.contains("plan_mode_read_only"), "{}", out[0].content);++ assert!(++ out[0].content.contains("plan_mode_read_only"),++ "{}",++ out[0].content++ );let _ = std::fs::remove_dir_all(&root);}@@@ -3960,7 -4174,7 +4438,10 @@@.and_then(|x| serde_json::from_value::<RunMode>(x.clone()).ok())};assert_eq!(from_body(json!({"run_mode": "plan"})), Some(RunMode::Plan));-- assert_eq!(from_body(json!({"run_mode": "normal"})), Some(RunMode::Normal));++ assert_eq!(++ from_body(json!({"run_mode": "normal"})),++ Some(RunMode::Normal)++ );assert_eq!(from_body(json!({})), None);}@@@ -4080,6 -4295,106 +4562,105 @@@let _ = std::fs::remove_dir_all(&root);}+ // An unanswered ask with `ask_timeout_secs` set resolves to the+ // auto-selected recommended option (here the first, since `ask_call` sets+ // no recommended index), NOT to `ask_cancelled`. `with_temp_home` points+ // HOME at the config it writes; a nested current-thread runtime runs the+ // invoke because that helper is synchronous.+ // `global_config` (the timeout source) is CLI-only, so this test is too.+ #[cfg(feature = "cli")]+ #[test]+ fn ask_auto_selects_on_timeout_instead_of_cancelling() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let path = crate::core::agent::global_config::ensure_global_config().unwrap();+ std::fs::write(&path, "ask_timeout_secs = 1\n").unwrap();++ let rt = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap();+ rt.block_on(async {+ let root = unique_project_root();+ let (tx, _rx) = mpsc::unbounded_channel();+ let permissions: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let asks = crate::core::agent::interaction::new_registry();+ let mut invoker = build_prompting_invoker(root.clone(), tx, permissions);+ invoker.ask_requests = Some(asks.clone());++ // No one answers: handle_ask_tool self-resolves after the timeout.+ let out = invoker.invoke(&[ask_call()]).await.unwrap();+ assert_eq!(out.len(), 1);+ assert!(+ !out[0].content.contains("ask_cancelled"),+ "timeout is not a cancel: {}",+ out[0].content+ );+ assert!(- out[0].content.contains("User response for \"scope\": Small"),++ out[0]++ .content++ .contains("User response for \"scope\": Small"),+ "auto-selected the first option: {}",+ out[0].content+ );+ assert!(+ asks.lock().await.is_empty(),+ "the timed-out ask must be deregistered"+ );+ let _ = std::fs::remove_dir_all(&root);+ });+ });+ }++ // A timeout with a non-zero `recommended` index must select that option,+ // never silently fall back to the first (index 0). `ask_call_recommended`+ // asks for `scope` with options [Small, Large, Huge] and `recommended: 2`,+ // so a correct result says "Huge" and an index-0 fallback says "Small".+ #[cfg(feature = "cli")]+ #[test]+ fn ask_timeout_auto_selects_the_recommended_option_not_the_first() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let path = crate::core::agent::global_config::ensure_global_config().unwrap();+ std::fs::write(&path, "ask_timeout_secs = 1\n").unwrap();++ let rt = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap();+ rt.block_on(async {+ let root = unique_project_root();+ let (tx, _rx) = mpsc::unbounded_channel();+ let permissions: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let asks = crate::core::agent::interaction::new_registry();+ let mut invoker = build_prompting_invoker(root.clone(), tx, permissions);+ invoker.ask_requests = Some(asks.clone());++ // No one answers: handle_ask_tool self-resolves after the timeout.- let out = invoker- .invoke(&[ask_call_recommended()])- .await- .unwrap();++ let out = invoker.invoke(&[ask_call_recommended()]).await.unwrap();+ assert_eq!(out.len(), 1);+ assert!(+ !out[0].content.contains("ask_cancelled"),+ "timeout is not a cancel: {}",+ out[0].content+ );+ assert!(+ out[0].content.contains("User response for \"scope\": Huge"),+ "must select the recommended option (Huge): {}",+ out[0].content+ );+ assert!(+ !out[0].content.contains("Small"),+ "must not fall back to the first option: {}",+ out[0].content+ );+ assert!(+ asks.lock().await.is_empty(),+ "the timed-out ask must be deregistered"+ );+ let _ = std::fs::remove_dir_all(&root);+ });+ });+ }+fn todo_call(id: &str, args: serde_json::Value) -> serde_json::Value {json!({"id": id,@@@ -4232,7 -4547,7 +4813,11 @@@.unwrap();assert_eq!(out.len(), 1);-- assert!(!out[0].content.starts_with("ERROR"), "got: {}", out[0].content);++ assert!(++ !out[0].content.starts_with("ERROR"),++ "got: {}",++ out[0].content++ );let result: crate::core::agent::todo::TodoList =serde_json::from_str(&out[0].content).unwrap();assert_eq!(result.active().unwrap().1.content, "a");@@@ -4254,10 -4569,10 +4839,7 @@@invoker.todo_registry = Some(todos.clone());invoker-- .invoke(&[todo_call(-- "t1",-- json!({"op": "init", "items": ["a", "b"]}),-- )])++ .invoke(&[todo_call("t1", json!({"op": "init", "items": ["a", "b"]}))]).await.unwrap();let _ = rx.recv().await; // drain init's TodoUpdate@@@ -4266,7 -4581,7 +4848,11 @@@.invoke(&[todo_call("t2", json!({"op": "done", "task": "a"}))]).await.unwrap();-- assert!(!out[0].content.starts_with("ERROR"), "got: {}", out[0].content);++ assert!(++ !out[0].content.starts_with("ERROR"),++ "got: {}",++ out[0].content++ );let result: crate::core::agent::todo::TodoList =serde_json::from_str(&out[0].content).unwrap();assert_eq!(result.active().unwrap().1.content, "b");@@@ -4293,7 -4608,7 +4879,11 @@@.invoke(&[todo_call("t2", json!({"op": "rm", "task": "missing"}))]).await.unwrap();-- assert!(out[0].content.starts_with("ERROR"), "got: {}", out[0].content);++ assert!(++ out[0].content.starts_with("ERROR"),++ "got: {}",++ out[0].content++ );let _ = std::fs::remove_dir_all(&root);}@@@ -4315,7 -4630,7 +4905,11 @@@"function": { "name": "read", "arguments": format!("{{\"path\":\"{path}\"}}") }})};-- let calls = vec![read("r1", "a.txt"), read("r2", "b.txt"), read("r3", "c.txt")];++ let calls = vec![++ read("r1", "a.txt"),++ read("r2", "b.txt"),++ read("r3", "c.txt"),++ ];let out = invoker.invoke(&calls).await.unwrap();assert_eq!(out.len(), 3);@@@ -4348,7 -4663,7 +4942,11 @@@responder.await.unwrap();assert_eq!(out.len(), 1);-- assert!(!out[0].content.starts_with("ERROR"), "unexpected: {}", out[0].content);++ assert!(++ !out[0].content.starts_with("ERROR"),++ "unexpected: {}",++ out[0].content++ );assert_eq!(std::fs::read_to_string(root.join("out.txt")).unwrap(), "hi");let _ = std::fs::remove_dir_all(&root);}@@@ -4364,7 -4679,7 +4962,11 @@@let out = invoker.invoke(&[write_call()]).await.unwrap();assert_eq!(out.len(), 1);-- assert!(!out[0].content.starts_with("ERROR"), "unexpected: {}", out[0].content);++ assert!(++ !out[0].content.starts_with("ERROR"),++ "unexpected: {}",++ out[0].content++ );assert_eq!(std::fs::read_to_string(root.join("out.txt")).unwrap(), "hi");// No permission prompt should have been emitted.assert!(@@@ -4393,7 -4708,7 +4995,11 @@@responder.await.unwrap();assert_eq!(out.len(), 1);-- assert!(out[0].content.contains("denied by user"), "got: {}", out[0].content);++ assert!(++ out[0].content.contains("denied by user"),++ "got: {}",++ out[0].content++ );assert!(!root.join("out.txt").exists());let _ = std::fs::remove_dir_all(&root);}@@@ -4422,7 -4737,7 +5028,11 @@@};let out1 = invoker.invoke(&[write_call()]).await.unwrap();-- assert!(!out1[0].content.starts_with("ERROR"), "first: {}", out1[0].content);++ assert!(++ !out1[0].content.starts_with("ERROR"),++ "first: {}",++ out1[0].content++ );let second = json!({"id": "c2",@@@ -4433,7 -4748,7 +5043,11 @@@}});let out2 = invoker.invoke(&[second]).await.unwrap();-- assert!(!out2[0].content.starts_with("ERROR"), "second: {}", out2[0].content);++ assert!(++ !out2[0].content.starts_with("ERROR"),++ "second: {}",++ out2[0].content++ );drop(invoker); // close events channel so responder loop endsresponder.await.unwrap();@@@ -4468,11 -4783,11 +5082,18 @@@})};-- let out = invoker.invoke(&[mcp_call("m1", "web_search_exa")]).await.unwrap();++ let out = invoker++ .invoke(&[mcp_call("m1", "web_search_exa")])++ .await++ .unwrap();responder.await.unwrap();assert_eq!(out.len(), 1);-- assert!(out[0].content.contains("denied by user"), "got: {}", out[0].content);++ assert!(++ out[0].content.contains("denied by user"),++ "got: {}",++ out[0].content++ );let _ = std::fs::remove_dir_all(&root);}@@@ -4534,14 -4849,14 +5155,19 @@@#[test]fn read_only_project_still_advertises_mcp_tools() {use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};-- let mut tools = vec![json!({ "type": "function", "function": { "name": "web_search_exa" } })];++ let mut tools =++ vec![json!({ "type": "function", "function": { "name": "web_search_exa" } })];let mut map = HashMap::from([("web_search_exa".to_string(), "exa".to_string())]);// The scaffolded CLI project default: read-only, no allow-list.let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);retain_advertisable_mcp_tools(&mut tools, &mut map, &perms);-- assert_eq!(tools.len(), 1, "read-only must not suppress MCP advertisement");++ assert_eq!(++ tools.len(),++ 1,++ "read-only must not suppress MCP advertisement"++ );assert!(map.contains_key("web_search_exa"));}@@@ -4567,19 -4882,57 +5193,67 @@@assert_eq!(tools.len(), 1);assert!(map.contains_key("web_search_exa"));-- assert!(!map.contains_key("dangerous_write"), "deny-list must still prune");++ assert!(++ !map.contains_key("dangerous_write"),++ "deny-list must still prune"++ );}#[test]fn deny_default_advertises_no_mcp_tools() {use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};-- let mut tools = vec![json!({ "type": "function", "function": { "name": "web_search_exa" } })];++ let mut tools =++ vec![json!({ "type": "function", "function": { "name": "web_search_exa" } })];let mut map = HashMap::from([("web_search_exa".to_string(), "exa".to_string())]);let perms = ToolPermissions::new(PermissionDefault::Deny, &[], &[], &[]);retain_advertisable_mcp_tools(&mut tools, &mut map, &perms);-- assert!(tools.is_empty(), "default=deny must lock down MCP advertisement");++ assert!(++ tools.is_empty(),++ "default=deny must lock down MCP advertisement"++ );assert!(map.is_empty());}++ /// `bash` hands its child to a detached task that keeps the output sink+ /// alive after the call has returned its `job_id`. The sink must not keep+ /// the run's event channel open with it: every consumer of that channel --+ /// the desktop forwarder, the headless printer, a subagent's forwarder --+ /// finishes only when the channel closes.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_backgrounded_job_does_not_hold_the_event_channel_open() {+ use tauri_plugin_agent_tools::tools::{handlers::execute_builtin, lookup, ToolContext};+ let dir = tempfile::tempdir().unwrap();+ let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();+ let skills: Vec<String> = Vec::new();+ let ctx = ToolContext::new(dir.path(), dir.path(), &skills)+ .with_sandbox(false)+ .with_output_sink(output_sink(&tx, "call-1"));+ let out = execute_builtin(+ lookup("bash").unwrap(),+ &json!({"command": "sleep 3; printf 'late\\n'", "timeout": 0}),+ &ctx,+ )+ .await+ .0;- assert!(out.contains("job_id=bash-"), "expected a backgrounded job, got: {out}");++ assert!(++ out.contains("job_id=bash-"),++ "expected a backgrounded job, got: {out}"++ );++ // The run is over: the orchestration future has returned and dropped its+ // sender, so the receiver must observe closure without waiting for the+ // straggling command (which outlives this assertion by seconds).+ drop(tx);+ let closed = tokio::time::timeout(std::time::Duration::from_millis(1500), async {+ while rx.recv().await.is_some() {}+ })+ .await;+ assert!(+ closed.is_ok(),+ "the event channel never closed while a backgrounded bash job was still running"+ );+ }}diff --cc src-tauri/src/core/agent/upstream.rsindex ab7c91d3a,bc6e499a1..51f0bae19--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@@ -4,14 -4,12 +4,14 @@@//! `core/server/proxy.rs` (no behavior change) so both the server path and//! `core/agent/loop.rs` consume one implementation.++use futures_util::StreamExt;+#[cfg(feature = "cli")]+use std::cmp::Reverse;use std::collections::HashMap;use std::fs;use std::path::PathBuf;use std::sync::Arc;- use futures_util::StreamExt;-#[cfg(not(feature = "cli"))]use reqwest::Client;use rmcp::model::{CallToolRequestParam, CallToolResult};#[cfg(not(feature = "cli"))]@@@ -19,10 -17,9 +19,8 @@@ use tauri_plugin_llamacpp::state::Llamause tokio::sync::{mpsc, Mutex};use crate::core::agent::events::StreamEvent;- use crate::core::openai_schema::{- http_status_indicates_api_key_retry, normalize_openai_tool_parameters_schema,- };+ use crate::core::openai_schema::normalize_openai_tool_parameters_schema;-#[cfg(not(feature = "cli"))]-use crate::core::openai_schema::http_status_indicates_api_key_retry;+use crate::core::server::converters::UpstreamConverter;#[cfg(not(feature = "cli"))]use crate::core::server::proxy::router_upstream;#[cfg(not(feature = "cli"))]@@@ -167,15 -165,15 +166,17 @@@ pub(crate) fn repair_dangling_tool_call// isn't a tool reply.let mut answered: std::collections::HashSet<&str> = std::collections::HashSet::new();let mut j = i + 1;-- while j < messages.len()-- && messages[j].get("role").and_then(|v| v.as_str()) == Some("tool")++ while j < messages.len() && messages[j].get("role").and_then(|v| v.as_str()) == Some("tool"){if let Some(id) = messages[j].get("tool_call_id").and_then(|v| v.as_str()) {answered.insert(id);}j += 1;}-- let missing: Vec<&String> = ids.iter().filter(|id| !answered.contains(id.as_str())).collect();++ let missing: Vec<&String> = ids++ .iter()++ .filter(|id| !answered.contains(id.as_str()))++ .collect();for id in &missing {messages.insert(j,@@@ -376,12 -362,7 +377,7 @@@ pub(crate) async fn resolve_upstream_fo.filter(|(_, config)| {config.base_url.as_deref().is_some_and(|u| !u.is_empty()) && offers(config)})- .min_by_key(|(name, config)| {- (- Reverse(credentialed(config)),- name.to_string(),- )- })- .min_by_key(|(name, _)| name.to_string())++ .min_by_key(|(name, config)| (Reverse(credentialed(config)), name.to_string())).or_else(|| pc.iter().find(|(_, config)| offers(config)));#[cfg(not(feature = "cli"))]let first_match = pc.iter().find(|(_, config)| offers(config));@@@ -400,40 -381,24 +396,53 @@@drop(pc);if let Some(provider) = provider_name {- let provider_cfg = provider_configs.lock().await.get(provider.as_str()).cloned();- let pc2 = provider_configs.lock().await;- if let Some(provider_cfg) = pc2.get(provider.as_str()).cloned() {++ let provider_cfg = provider_configs++ .lock()++ .await++ .get(provider.as_str())++ .cloned();+ if let Some(provider_cfg) = provider_cfg {// A populated base_url means an HTTP upstream (cloud, or a local// engine whose live endpoint was registered at runtime). A local// engine loaded from persisted settings has none -- fall through to// the MLX session / llama-server router resolution below.if let Some(api_url) = provider_cfg.base_url.clone().filter(|u| !u.is_empty()) {- let url = format!("{}{}", api_url, destination_path);- // Desktop-inherited providers arrive keyless in this build; the- // OS secret store is read here, for the one provider the run- // resolved to, rather than for every provider at load time.+ // A registered account takes its OAuth access token (refreshed if+ // needed) ahead of any stored API key. Account auth is a `cli`+ // concern; the desktop resolves credentials through its own+ // proxy path and falls back to the bearer key chain here.#[cfg(feature = "cli")]- let provider_cfg = {- let mut cfg = provider_cfg;- crate::core::cli::providers::hydrate_provider_keys(&mut cfg);- cfg+ let (api_url, api_keys) = {- let account_token = crate::core::cli::auth::account::access_token(- &provider_cfg.provider,- )- .await?;++ let account_token =++ crate::core::cli::auth::account::access_token(&provider_cfg.provider)++ .await?;+ let api_url = if provider_cfg.provider == "openai"+ && account_token.is_some()+ && api_url.trim_end_matches('/') == "https://api.openai.com/v1"+ {+ "https://chatgpt.com/backend-api".to_string()+ } else {+ api_url+ };+ let api_keys = account_token+ .map(|token| vec![token])+ .unwrap_or_else(|| provider_cfg.bearer_key_chain());+ (api_url, api_keys)};- return Ok((url, provider_cfg.bearer_key_chain()));+ #[cfg(not(feature = "cli"))]+ let api_keys = provider_cfg.bearer_key_chain();+ let url = format!("{}{}", api_url, destination_path);++ #[cfg(feature = "cli")]++ {++ if api_keys.is_empty() {++ let mut provider_cfg = provider_cfg;++ crate::core::cli::providers::hydrate_provider_keys(&mut provider_cfg);++ return Ok((url, provider_cfg.bearer_key_chain()));++ }++ return Ok((url, api_keys));++ }++ #[cfg(not(feature = "cli"))]+ return Ok((url, api_keys));}}}@@@ -457,86 -422,6 +466,80 @@@Err(format!("No upstream session found for model '{model_id}'"))}+/// Strip a leading `<provider>/` qualifier from `model_id` when that prefix+/// names a configured provider, mirroring the disambiguation in+/// [`resolve_upstream_for_model`]. `provider/model` is the CLI's explicit+/// selection syntax; once the upstream URL and credential are resolved the+/// request body must carry the bare model id, or providers that reject a+/// provider-qualified id (e.g. OpenCode GO) fail with "model not supported".+/// A slash inside a real model id (e.g. an org-scoped name) is left alone+/// unless the leading segment is literally a provider key.+pub(crate) fn strip_provider_prefix(+ model_id: &str,+ provider_configs: &HashMap<String, ProviderConfig>,+) -> String {+ if let Some(sep_pos) = model_id.find('/') {+ let potential_provider: &str = &model_id[..sep_pos];+ if provider_configs.contains_key(potential_provider) {+ return model_id[sep_pos + 1..].to_string();+ }+ }+ model_id.to_string()+}+-+/// Resolve the wire API for `model_id`'s provider, mirroring the+/// model-to-provider lookup in [`resolve_upstream_for_model`]. Returns the+/// provider's `api_type` and whether its credential is an OAuth account token+/// rather than an API key, when the model maps to a reachable HTTP provider+/// that declares a non-default wire API. `None` otherwise (OpenAI+/// chat/completions or a model with no provider entry).+pub(crate) async fn resolve_api_type_for_model(+ model_id: &str,+ provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,+) -> Option<(String, bool)> {+ let pc = provider_configs.lock().await;+ let offers = |config: &ProviderConfig| config.models.iter().any(|m| m == model_id);++ // A converter is only meaningful for an HTTP provider (it needs a base_url+ // to append the native path to), so prefer a reachable entry and otherwise+ // fall back to the first model-claiming entry, exactly as resolution does.+ #[cfg(feature = "cli")]+ let first_match = pc+ .iter()+ .filter(|(_, config)| {+ config.base_url.as_deref().is_some_and(|u| !u.is_empty()) && offers(config)+ })- .min_by_key(|(name, config)| {- (- Reverse(credentialed(config)),- name.to_string(),- )- })++ .min_by_key(|(name, config)| (Reverse(credentialed(config)), name.to_string()))+ .or_else(|| pc.iter().find(|(_, config)| offers(config)));+ #[cfg(not(feature = "cli"))]+ let first_match = pc.iter().find(|(_, config)| offers(config));++ let provider_name = first_match+ .map(|(_, config)| config.provider.clone())+ .or_else(|| {+ if let Some(sep_pos) = model_id.find('/') {+ let potential_provider: &str = &model_id[..sep_pos];+ if pc.contains_key(potential_provider) {+ return Some(potential_provider.to_string());+ }+ }+ pc.get(model_id).map(|c| c.provider.clone())+ });+ let cfg = provider_name.and_then(|p| pc.get(&p).cloned());+ drop(pc);++ let api_type = cfg.as_ref().and_then(|c| c.api_type.clone())?;+ // OAuth account login is a `cli` feature; resolve the auth scheme from+ // the stored credential so a plain API key stays on its key scheme.+ #[cfg(feature = "cli")]+ let oauth = cfg+ .as_ref()+ .map(|c| crate::core::cli::auth::account::has_oauth_credential(&c.provider))+ .unwrap_or(false);+ #[cfg(not(feature = "cli"))]+ let oauth = false;+ Some((api_type, oauth))+}pub(crate) fn copy_optional_chat_params(from: &serde_json::Value,@@@ -572,28 -457,28 +575,27 @@@ pub(crate) async fn collect_mcp_openai_// Probe every server concurrently so one slow/hanging server can't serialize// the whole collection behind its timeout (previously each server waited out// the full timeout before the next was contacted).-- let listings = futures_util::future::join_all(servers.iter().map(|(server_name, service)| {-- async move {-- let result = match tokio::time::timeout(timeout_duration, service.list_all_tools()).await-- {-- Ok(Ok(tools)) => Some(tools),-- Ok(Err(e)) => {-- log::warn!("MCP server {} failed to list tools: {}", server_name, e);-- None-- }-- Err(_) => {-- log::warn!(-- "Listing MCP tools timed out after {} seconds on server {}",-- timeout_duration.as_secs(),-- server_name-- );-- None-- }-- };++ let listings =++ futures_util::future::join_all(servers.iter().map(|(server_name, service)| async move {++ let result =++ match tokio::time::timeout(timeout_duration, service.list_all_tools()).await {++ Ok(Ok(tools)) => Some(tools),++ Ok(Err(e)) => {++ log::warn!("MCP server {} failed to list tools: {}", server_name, e);++ None++ }++ Err(_) => {++ log::warn!(++ "Listing MCP tools timed out after {} seconds on server {}",++ timeout_duration.as_secs(),++ server_name++ );++ None++ }++ };(server_name.clone(), result)-- }-- }))-- .await;++ }))++ .await;for (server_name, tools) in listings {let Some(tools) = tools else { continue };@@@ -745,7 -638,7 +755,7 @@@ pub(crate) async fn call_openai_chat_co}last_err = format!("Upstream returned HTTP {status}: {text}");-- if http_status_indicates_api_key_retry(status) && i + 1 < attempts.len() {++ if should_try_next_api_key(status) && i + 1 < attempts.len() {log::warn!("OpenAI completion: HTTP {status} with API key index {i}, trying next key");continue;}@@@ -823,6 -717,6 +833,7 @@@ pub(crate) fn is_reasoning_field_error(/// connection, TLS mismatch, dropped socket) is one or more sources down and is/// otherwise lost to the user. Consecutive duplicates are collapsed: hyper and/// its io error often stringify identically.++#[cfg(any(not(feature = "cli"), test))]fn error_source_chain(err: &dyn std::error::Error) -> Vec<String> {let mut chain = Vec::new();let mut cur = err.source();@@@ -843,6 -738,6 +854,7 @@@/// already closed as `connection closed before message completed`, or as an/// `ECONNRESET`/`EPIPE` io error if the RST lands while the request is going/// out. A timeout is deliberately excluded: retrying one doubles the wait.++#[cfg(not(feature = "cli"))]fn is_retryable_send_error(err: &reqwest::Error) -> bool {if err.is_timeout() || err.is_body() || err.is_decode() || err.is_builder() {return false;@@@ -854,6 -750,6 +866,7 @@@/// on text because the io error is several opaque layers down (hyper's/// `SendRequest` -> `connection error` -> `std::io::Error`) and its `ErrorKind`/// is not exposed through `reqwest`.++#[cfg(not(feature = "cli"))]fn chain_indicates_dropped_connection(chain: &[String]) -> bool {const MARKERS: &[&str] = &["connection closed before message completed",@@@ -862,25 -758,27 +875,25 @@@"connection aborted","unexpected eof",];-- chain-- .iter()-- .any(|msg| {-- let msg = msg.to_lowercase();-- MARKERS.iter().any(|m| msg.contains(m))-- })++ chain.iter().any(|msg| {++ let msg = msg.to_lowercase();++ MARKERS.iter().any(|m| msg.contains(m))++ })}-#[cfg(not(feature = "cli"))]/// How long to wait before the one retry of a dropped connection. Long enough/// for a load balancer that just recycled a backend to finish, short enough that/// the user does not read it as a hang.++#[cfg(not(feature = "cli"))]const SEND_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(250);-#[cfg(not(feature = "cli"))]/// Send a request, retrying it once when the connection dropped before any/// response arrived. This is the failure a long turn invites: while tools run/// locally no bytes flow, an idle keep-alive connection is reclaimed by the peer/// or its load balancer, and the next turn's request is written into a socket/// that is already gone. Retrying is safe precisely because nothing was received/// -- see [`is_retryable_send_error`].++#[cfg(not(feature = "cli"))]async fn send_with_one_retry(req: reqwest::RequestBuilder) -> Result<reqwest::Response, String> {// `try_clone` returns `None` only for a streaming body; every caller here// sends a `String`, so the retry path is always available in practice.@@@ -909,26 -807,19 +922,30 @@@})}- /// The HTTP client every agent turn goes through. `Client::new()`'s defaults are- /// wrong for this traffic in one specific way: connections idle for up to 90s- /// stay in the pool, but a turn spends far longer than that running tools, and- /// the peer (or its load balancer) closes an idle connection well before then.- /// Reusing one is the `Connection reset by peer` a long session eventually hits,- /// so the pool is kept shorter-lived than any plausible upstream idle timeout.- /// No overall request timeout: a streamed answer legitimately runs for minutes.- pub(crate) fn agent_http_client() -> Client {- Client::builder()- .pool_idle_timeout(std::time::Duration::from_secs(15))- .tcp_keepalive(std::time::Duration::from_secs(30))- .connect_timeout(std::time::Duration::from_secs(30))- .build()- .unwrap_or_else(|_| Client::new())+ /// The HTTP client every agent turn goes through. Agent traffic now runs on+ /// `genai`, which is built against reqwest 0.13, so this is the aliased crate+ /// rather than the 0.12 `Client` the rest of the app (and the API server below)+ /// uses. Pool tuning lives with the builder in [`super::genai_bridge`].+ pub(crate) fn agent_http_client() -> reqwest13::Client {+ super::genai_bridge::shared_http_client()+ }+-#[cfg(not(feature = "cli"))]++/// The converted native-wire path can rotate through configured credentials on++/// the same auth failures as the desktop proxy.++fn should_try_next_api_key(status: reqwest::StatusCode) -> bool {++ matches!(++ status,++ reqwest::StatusCode::UNAUTHORIZED++ | reqwest::StatusCode::FORBIDDEN++ | reqwest::StatusCode::TOO_MANY_REQUESTS++ )+}+/// Names the proxy environment variables in force, without their values (they/// routinely carry credentials). A proxy set in the environment is a common/// reason a request fails for Jan and for nothing else, and it is invisible in/// the error itself.++#[cfg(any(not(feature = "cli"), test))]fn proxy_env_hint() -> Option<String> {const VARS: &[&str] = &["HTTPS_PROXY",@@@ -954,6 -846,6 +971,7 @@@/// `reqwest` message, its whole cause chain, and -- for a connect or timeout/// failure, where the environment is usually the culprit -- which proxy/// variables are set.++#[cfg(not(feature = "cli"))]pub(crate) fn describe_request_error(err: &reqwest::Error) -> String {let stage = if err.is_timeout() {"timed out"@@@ -991,593 -897,23 +1023,522 @@@ pub(crate) async fn stream_openai_chat_body: &serde_json::Value,events: &mpsc::UnboundedSender<StreamEvent>,) -> Result<serde_json::Value, String> {- let mut req_body = body.clone();- if let Some(obj) = req_body.as_object_mut() {- obj.insert("stream".to_string(), serde_json::json!(true));- obj.insert(- "stream_options".to_string(),- serde_json::json!({ "include_usage": true }),- );- }-- let attempts: Vec<Option<&str>> = if api_keys.is_empty() {- vec![None]- } else {- api_keys.iter().map(|s| Some(s.as_str())).collect()- };-- let mut last_err = String::new();- for (i, key_ref) in attempts.iter().enumerate() {- let mut req = client- .post(upstream_url)- .header("Content-Type", "application/json")- .header("Accept", "text/event-stream")- .header("Accept-Encoding", "identity");-- if let Some(key) = key_ref {- req = req.header("Authorization", format!("Bearer {key}"));- }-- let resp = send_with_one_retry(req.body(req_body.to_string())).await?;-- let status = resp.status();- if status.is_success() {- return consume_openai_sse(resp, events).await;- }-- let text = resp.text().await.unwrap_or_default();- last_err = format!("Upstream returned HTTP {status}: {text}");- if is_context_overflow_body(&text) {- last_err = format!("[{CONTEXT_OVERFLOW_MARKER}] {last_err}");- }- if http_status_indicates_api_key_retry(status) && i + 1 < attempts.len() {- log::warn!("OpenAI stream: HTTP {status} with API key index {i}, trying next key");- continue;- }-- return Err(last_err);- }-- Err(last_err)+ super::genai_bridge::stream_chat_completions(+ client,+ upstream_url,+ api_keys,+ api_type,+ body,+ events,+ )+ .await}+/// Streaming counterpart of [`stream_openai_chat_completions`] for providers+/// that speak a native (non-chat/completions) wire API. Uses the provider's+/// [`UpstreamConverter`] to rewrite the request body, point at the native path,+/// and translate the upstream stream back into chat/completions SSE chunks,+/// which are then fed through the same [`SseAccumulator::ingest_line`] decode+/// as the OpenAI path so `StreamEvent`s (Token / ToolCallStarted /+/// ToolCallArgsDelta) are emitted identically.+///+/// `upstream_url` is the resolved base + "/chat/completions" (see+/// [`resolve_upstream_for_model`]); the base is recovered by stripping that+/// suffix and the native path appended in its place.+pub(crate) async fn stream_converted_chat_completions(+ client: &Client,+ upstream_url: &str,+ api_keys: &[String],+ converter: &dyn UpstreamConverter,+ body: &serde_json::Value,+ events: &mpsc::UnboundedSender<StreamEvent>,+) -> Result<serde_json::Value, String> {+ // Base is upstream_url minus the trailing "/chat/completions". Recover it+ // the same way the proxy does when it swaps the destination path.+ let base = upstream_url+ .strip_suffix("/chat/completions")+ .unwrap_or(upstream_url)+ .trim_end_matches('/');+ let native_path = converter.upstream_path(body);+ let native_url = format!("{base}{native_path}");++ // Force streaming so the converter emits the SSE form and `upstream_path`+ // (Google) selects the `?alt=sse` variant, matching the OpenAI path.+ let mut native_body = body.clone();+ if let Some(obj) = native_body.as_object_mut() {+ obj.insert("stream".to_string(), serde_json::json!(true));+ }+ let native_body = converter.convert_request(&native_body);++ let attempts: Vec<Option<&str>> = if api_keys.is_empty() {+ vec![None]+ } else {+ api_keys.iter().map(|s| Some(s.as_str())).collect()+ };++ let mut last_err = String::new();+ for (i, key_ref) in attempts.iter().enumerate() {+ let mut req = client+ .post(&native_url)+ .header("Content-Type", "application/json")+ .header("Accept", "text/event-stream")+ .header("Accept-Encoding", "identity");++ // The converter decides the auth scheme (Bearer default, but Google+ // uses x-goog-api-key and Anthropic x-api-key).+ if let Some(key) = key_ref {+ let (auth_name, auth_value) = converter.auth_header(key);+ req = req.header(auth_name, auth_value);+ for (name, value) in converter.credential_headers(key) {+ req = req.header(name, value);+ }+ }+ // Fixed headers the native API requires (Anthropic: anthropic-version).+ for (name, value) in converter.extra_headers() {+ req = req.header(name, value);+ }++ let resp = req+ .body(native_body.to_string())+ .send()+ .await+ .map_err(|e| format!("Upstream request failed: {e}"))?;++ let status = resp.status();+ if !status.is_success() {+ let text = resp.text().await.unwrap_or_default();+ last_err = format!("Upstream returned HTTP {status}: {text}");+ if is_context_overflow_body(&text) {+ last_err = format!("[{CONTEXT_OVERFLOW_MARKER}] {last_err}");+ }- if http_status_indicates_api_key_retry(status) && i + 1 < attempts.len() {++ if should_try_next_api_key(status) && i + 1 < attempts.len() {+ log::warn!(+ "converted stream: HTTP {status} with API key index {i}, trying next key"+ );+ continue;+ }+ return Err(last_err);+ }++ // Every converted call above requests a stream. Some native backends+ // (notably ChatGPT Codex) omit Content-Type on a valid SSE response, so+ // absence means SSE; an explicit non-SSE type remains the JSON fallback.+ let is_sse = resp+ .headers()+ .get(reqwest::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .map(|ct| ct.contains("event-stream"))+ .unwrap_or(true);++ if is_sse {+ return consume_converted_sse(resp, converter, events).await;+ }++ let bytes = resp+ .bytes()+ .await+ .map_err(|e| format!("Upstream body read failed: {e}"))?;+ return decode_converted_response(&bytes, converter);+ }++ Err(last_err)+}++/// Read a native SSE stream, translating each event through `converter` and+/// feeding the produced chat-shaped chunks into the OpenAI [`SseAccumulator`]+/// so `StreamEvent`s match the chat/completions path exactly.+async fn consume_converted_sse(+ resp: reqwest::Response,+ converter: &dyn UpstreamConverter,+ events: &mpsc::UnboundedSender<StreamEvent>,+) -> Result<serde_json::Value, String> {+ let mut stream = resp.bytes_stream();+ let mut frame = crate::core::server::converters::SseAccumulator::new();+ let mut state = crate::core::server::converters::StreamState::default();+ // Reassembles the translated chat/completions SSE into one completion.+ let mut acc = SseAccumulator::default();++ while let Some(chunk) = stream.next().await {+ let chunk = chunk.map_err(|e| format!("Upstream stream error: {e}"))?;+ let text = String::from_utf8_lossy(&chunk);+ for event in frame.push(&text) {+ for payload in converter.convert_stream_event(&event, &mut state) {+ // Each payload is one chat-shaped JSON chunk or `[DONE]`.+ acc.ingest(&payload, events);+ }+ }+ }+ if let Some(event) = frame.finish() {+ for payload in converter.convert_stream_event(&event, &mut state) {+ acc.ingest(&payload, events);+ }+ }++ if let Some(err) = acc.error.take() {+ let msg = format!("Upstream stream error: {err}");+ return Err(if is_context_overflow_body(&err) {+ format!("[{CONTEXT_OVERFLOW_MARKER}] {msg}")+ } else {+ msg+ });+ }++ Ok(acc.into_completion())+}++/// Translate a non-streaming native response into a chat.completion object.+fn decode_converted_response(+ bytes: &[u8],+ converter: &dyn UpstreamConverter,+) -> Result<serde_json::Value, String> {+ let upstream: serde_json::Value = serde_json::from_slice(bytes)+ .map_err(|e| format!("Upstream returned invalid JSON: {e}"))?;+ let completion = converter.convert_response(&upstream);+ if let Some(err) = completion.get("error") {+ let message = err+ .get("message")+ .and_then(|v| v.as_str())+ .map(|s| s.to_string())+ .unwrap_or_else(|| err.to_string());+ let msg = format!("Upstream stream error: {message}");+ return Err(if is_context_overflow_body(&message) {+ format!("[{CONTEXT_OVERFLOW_MARKER}] {msg}")+ } else {+ msg+ });+ }+ Ok(completion)+}++#[derive(Default)]+struct ToolCallAccum {+ id: String,+ name: String,+ arguments: String,+ /// A `ToolCallStarted` was already emitted for this call; guards the+ /// once-per-call in-progress signal against later argument deltas.+ started_emitted: bool,+ /// Bytes of `arguments` already forwarded as `ToolCallArgsDelta`. Zero+ /// until the first forward, which replays whatever arrived before the call+ /// could be announced.+ args_forwarded: usize,+}++/// Accumulates OpenAI SSE deltas into a single reconstructed completion. Kept+/// separate from the byte-stream reader so it is unit-testable without a live+/// HTTP response.+#[derive(Default)]+struct SseAccumulator {+ content: String,+ /// Natively streamed reasoning (`reasoning_content` deltas), accumulated so+ /// the reconstructed completion carries it back on the assistant message.+ /// Kept apart from `content`: reasoning is never part of the answer prose,+ /// but a caller resending assistant turns may forward it to the model.+ reasoning: String,+ tool_calls: Vec<ToolCallAccum>,+ finish_reason: Option<String>,+ usage: Option<serde_json::Value>,+ /// An error object delivered inside the stream (`data: {"error": {...}}`).+ /// OpenAI-compatible upstreams can fail mid-stream after a `200 OK`; without+ /// capturing it the run would end as a silent "no answer" instead of- /// surfacing the failure. Propagated as an `Err` by `consume_openai_sse`.++ /// surfacing the failure. The converted-stream reader turns it into an error.+ error: Option<String>,+}++impl SseAccumulator {+ /// Parse one raw SSE line (`data: {...}`); non-`data:`/blank lines are ignored.++ #[cfg(test)]+ fn ingest_line(&mut self, line: &str, events: &mpsc::UnboundedSender<StreamEvent>) {+ if let Some(rest) = line.trim_end_matches('\r').strip_prefix("data:") {+ let data = rest.trim();+ if !data.is_empty() {+ self.ingest(data, events);+ }+ }+ }++ fn ingest(&mut self, data: &str, events: &mpsc::UnboundedSender<StreamEvent>) {+ if data == "[DONE]" {+ return;+ }+ let json: serde_json::Value = match serde_json::from_str(data) {+ Ok(v) => v,+ Err(_) => return,+ };++ if let Some(err) = json.get("error").filter(|e| !e.is_null()) {+ let message = err+ .get("message")+ .and_then(|v| v.as_str())+ .map(|s| s.to_string())+ .unwrap_or_else(|| err.to_string());+ let kind = err.get("type").and_then(|v| v.as_str());+ self.error = Some(match kind {+ Some(t) if !t.is_empty() => format!("{t}: {message}"),+ _ => message,+ });+ return;+ }++ if let Some(u) = json.get("usage") {+ if !u.is_null() {+ self.usage = Some(u.clone());+ }+ }++ let Some(choice) = json+ .get("choices")+ .and_then(|c| c.as_array())+ .and_then(|a| a.first())+ else {+ return;+ };++ if let Some(fr) = choice.get("finish_reason").and_then(|v| v.as_str()) {+ self.finish_reason = Some(fr.to_string());+ }++ let Some(delta) = choice.get("delta") else {+ return;+ };++ // Native reasoning: providers exposing a dedicated `reasoning_content`+ // field stream it as `Reasoning` events, never as content tokens, so+ // consumers get the boundary for free instead of re-parsing synthetic+ // `<think>` tags. Providers that inline tags in `content` still flow+ // through `Token`; consumers keep the tag-stripping fallback for them.+ if let Some(text) = delta.get("reasoning_content").and_then(|v| v.as_str()) {+ if !text.is_empty() {+ self.reasoning.push_str(text);+ let _ = events.send(StreamEvent::Reasoning {+ text: text.to_string(),+ });+ }+ }++ if let Some(text) = delta.get("content").and_then(|v| v.as_str()) {+ if !text.is_empty() {+ self.content.push_str(text);+ let _ = events.send(StreamEvent::Token {+ text: text.to_string(),+ });+ }+ }++ if let Some(tcs) = delta.get("tool_calls").and_then(|v| v.as_array()) {+ for tc in tcs {+ let idx = tc.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as usize;+ while self.tool_calls.len() <= idx {+ self.tool_calls.push(ToolCallAccum::default());+ }+ let slot = &mut self.tool_calls[idx];+ if let Some(id) = tc.get("id").and_then(|v| v.as_str()) {+ if !id.is_empty() {+ slot.id = id.to_string();+ }+ }+ let func = tc.get("function");+ if let Some(name) = func+ .and_then(|f| f.get("name"))+ .and_then(|v| v.as_str())+ .filter(|n| !n.is_empty())+ {+ slot.name = name.to_string();+ }+ let arg_delta = func+ .and_then(|f| f.get("arguments"))+ .and_then(|v| v.as_str())+ .filter(|s| !s.is_empty());+ if let Some(arg) = arg_delta {+ slot.arguments.push_str(arg);+ }++ // Signal the in-progress tool call the instant both id and name+ // are known, so consumers can show activity while arguments are+ // still streaming (a long window for large write/edit calls).+ if !slot.started_emitted && !slot.id.is_empty() && !slot.name.is_empty() {+ slot.started_emitted = true;+ let _ = events.send(StreamEvent::ToolCallStarted {+ id: slot.id.clone(),+ name: slot.name.clone(),+ });+ }++ // Forward the argument text itself, but only once the call has+ // been announced -- a delta with no preceding `ToolCallStarted`+ // has no call for the consumer to attach it to. Providers that+ // send arguments before the id/name are covered by the replay+ // below, which flushes what was buffered before the announce.+ if slot.started_emitted {+ if let Some(arg) = arg_delta {+ let delta = if slot.args_forwarded == 0 {+ // First forward after the announce: ship everything+ // accumulated so far, including any chunks that+ // arrived before id/name were known.+ slot.arguments.clone()+ } else {+ arg.to_string()+ };+ slot.args_forwarded = slot.arguments.len();+ let _ = events.send(StreamEvent::ToolCallArgsDelta {+ id: slot.id.clone(),+ delta,+ });+ }+ }+ }+ }+ }++ fn into_completion(self) -> serde_json::Value {+ let tool_calls: Vec<serde_json::Value> = self+ .tool_calls+ .into_iter()+ .filter(|t| !t.id.is_empty() || !t.name.is_empty() || !t.arguments.is_empty())+ .map(|t| {+ serde_json::json!({+ "id": t.id,+ "type": "function",+ "function": { "name": t.name, "arguments": t.arguments }+ })+ })+ .collect();++ let mut message = serde_json::Map::new();+ message.insert("role".to_string(), serde_json::json!("assistant"));+ message.insert(+ "content".to_string(),+ if self.content.is_empty() {+ serde_json::Value::Null+ } else {+ serde_json::json!(self.content)+ },+ );+ // Reasoning stays out of `content` but is carried on the message so a+ // caller that resends assistant turns to the model can forward it (and+ // so a turn that only reasoned still surfaces its reasoning). Empty is+ // omitted so non-reasoning providers produce an unchanged shape.+ if !self.reasoning.is_empty() {- message.insert("reasoning_content".to_string(), serde_json::json!(self.reasoning));++ message.insert(++ "reasoning_content".to_string(),++ serde_json::json!(self.reasoning),++ );+ }+ if !tool_calls.is_empty() {+ message.insert(+ "tool_calls".to_string(),+ serde_json::Value::Array(tool_calls),+ );+ }++ let mut choice = serde_json::Map::new();+ choice.insert("index".to_string(), serde_json::json!(0));+ choice.insert("message".to_string(), serde_json::Value::Object(message));+ choice.insert(+ "finish_reason".to_string(),+ self.finish_reason+ .map(|s| serde_json::json!(s))+ .unwrap_or(serde_json::Value::Null),+ );++ let mut completion = serde_json::Map::new();+ completion.insert(+ "choices".to_string(),+ serde_json::Value::Array(vec![serde_json::Value::Object(choice)]),+ );+ if let Some(u) = self.usage {+ completion.insert("usage".to_string(), u);+ }++ serde_json::Value::Object(completion)+ }+}++/// Drain every complete (newline-terminated) line from `buf` into `acc`,+/// leaving any trailing partial line buffered for the next chunk.++#[cfg(test)]+fn drain_complete_lines(+ buf: &mut String,+ acc: &mut SseAccumulator,+ events: &mpsc::UnboundedSender<StreamEvent>,+) {+ while let Some(nl) = buf.find('\n') {+ let line = buf[..nl].to_string();+ buf.drain(..=nl);+ acc.ingest_line(&line, events);+ }+}++/// Ingest a final, non-newline-terminated line left after the stream closes.+/// Providers may end with `data: {...}` and no trailing blank line / `[DONE]`;+/// without this the last chunk's finish_reason and tool-call args are dropped.++#[cfg(test)]+fn flush_trailing_line(+ buf: &str,+ acc: &mut SseAccumulator,+ events: &mpsc::UnboundedSender<StreamEvent>,+) {+ if !buf.trim().is_empty() {+ acc.ingest_line(buf, events);+ }+}+- async fn consume_openai_sse(- resp: reqwest::Response,- events: &mpsc::UnboundedSender<StreamEvent>,- ) -> Result<serde_json::Value, String> {- let url = resp.url().to_string();- let mut stream = resp.bytes_stream();- let mut buf = String::new();- let mut acc = SseAccumulator::default();- let mut bytes = 0usize;-- while let Some(chunk) = stream.next().await {- // A stream that dies mid-response is the hardest case to tell apart from- // an empty answer, so the byte count so far goes in the message.- let chunk = chunk.map_err(|e| {- format!(- "Upstream stream error ({url}) after {bytes} bytes: {}",- describe_request_error(&e)- )- })?;- bytes += chunk.len();- buf.push_str(&String::from_utf8_lossy(&chunk));- drain_complete_lines(&mut buf, &mut acc, events);- }- flush_trailing_line(&buf, &mut acc, events);-- if let Some(err) = acc.error.take() {- let msg = format!("Upstream stream error: {err}");- return Err(if is_context_overflow_body(&err) {- format!("[{CONTEXT_OVERFLOW_MARKER}] {msg}")- } else {- msg- });- }-- Ok(acc.into_completion())- }-#[cfg(test)]mod tests {use super::*;use serde_json::json;- #[cfg(not(feature = "cli"))]+ fn sink() -> (+ mpsc::UnboundedSender<StreamEvent>,+ mpsc::UnboundedReceiver<StreamEvent>,+ ) {+ mpsc::unbounded_channel()+ }+ fn provider_configs(map: &[(&str, &str)]) -> HashMap<String, ProviderConfig> {+ map.iter()+ .map(|(name, url)| {+ (+ name.to_string(),+ ProviderConfig {+ provider: name.to_string(),+ base_url: Some(url.to_string()),+ models: vec![],+ ..Default::default()+ },+ )+ })+ .collect()+ }++ /// A `<provider>/<model>` id resolves to the bare model once the prefix+ /// names a configured provider - the body the upstream receives must not+ /// carry the selection qualifier.+ #[test]+ fn provider_prefix_is_stripped_when_it_names_a_provider() {+ let pc = provider_configs(&[("opencode", "https://opencode.ai/zen/go/v1")]);+ assert_eq!(+ strip_provider_prefix("opencode/gpt-5.6-luna", &pc),+ "gpt-5.6-luna"+ );+ }++ /// A slash inside a real model id is preserved when the leading segment is+ /// not a provider key, so org-scoped ids survive untouched.+ #[test]+ fn unknown_slash_prefix_is_left_alone() {+ let pc = provider_configs(&[("opencode", "https://opencode.ai/zen/go/v1")]);+ assert_eq!(+ strip_provider_prefix("mistral-technologies/mixtral", &pc),+ "mistral-technologies/mixtral"+ );+ }++ /// A bare model id (no slash) is returned unchanged.+ #[test]+ fn bare_model_id_is_unchanged() {+ let pc = provider_configs(&[("opencode", "https://opencode.ai/zen/go/v1")]);+ assert_eq!(strip_provider_prefix("gpt-5.6-luna", &pc), "gpt-5.6-luna");+ }-/// `reqwest` prints only its own layer, so the cause chain is where the/// actual failure lives -- the whole point of `describe_request_error`.#[test]@@@ -1591,7 -927,7 +1552,9 @@@}impl std::error::Error for Err2 {fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {-- self.1.as_ref().map(|e| e.as_ref() as &(dyn std::error::Error + 'static))++ self.1++ .as_ref()++ .map(|e| e.as_ref() as &(dyn std::error::Error + 'static))}}@@@ -1682,125 -1021,7 +1648,124 @@@}}- #[cfg(not(feature = "cli"))]+ /// The failure a long turn invites: the peer reclaims a keep-alive+ /// connection while tools run, and the next request is written into a socket+ /// that is already gone. One retry must carry the turn through, transparently+ /// -- the caller sees a normal completion, not an error.+ #[tokio::test]+ async fn a_dropped_first_connection_is_retried_and_the_turn_succeeds() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind");+ let addr = listener.local_addr().expect("addr");+ let server = tokio::spawn(async move {+ // First connection: read the request, then hang up without a byte of+ // response -- exactly what a reclaimed pooled connection looks like.+ let (mut first, _) = listener.accept().await.expect("first accept");+ let mut scratch = [0u8; 1024];+ let _ = first.read(&mut scratch).await;+ drop(first);++ // Second connection: a normal one-token SSE answer.+ let (mut second, _) = listener.accept().await.expect("second accept");+ let _ = second.read(&mut scratch).await;+ let sse = "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n\+ data: [DONE]\n\n";+ let resp = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\n\r\n{sse}",+ sse.len()+ );+ let _ = second.write_all(resp.as_bytes()).await;+ let _ = second.flush().await;+ });++ let (tx, mut rx) = sink();+ let url = format!("http://{addr}/v1/chat/completions");+ let completion = stream_openai_chat_completions(- &Client::new(),++ &reqwest13::Client::new(),+ &url,+ &[],++ None,+ &json!({ "model": "m", "messages": [] }),+ &tx,+ )+ .await+ .expect("the retry carries the turn");++ assert_eq!(+ completion["choices"][0]["message"]["content"], "hi",+ "answer from the second connection: {completion}"+ );+ let mut tokens = Vec::new();+ while let Ok(ev) = rx.try_recv() {+ if let StreamEvent::Token { text } = ev {+ tokens.push(text);+ }+ }+ assert_eq!(tokens, vec!["hi".to_string()], "streamed once, not twice");+ server.await.expect("server task");+ }+ #[tokio::test]+ async fn codex_oauth_request_matches_chatgpt_backend_contract() {+ use base64::Engine as _;+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind");+ let addr = listener.local_addr().expect("addr");+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.expect("accept");+ let mut bytes = vec![0u8; 16 * 1024];+ let read = socket.read(&mut bytes).await.expect("read");+ bytes.truncate(read);+ let response = "event: response.completed\n\+ data: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n";+ let wire = format!(+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{response}",+ response.len()+ );+ socket.write_all(wire.as_bytes()).await.expect("response");+ String::from_utf8(bytes).expect("request is utf-8")+ });+- let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(- br#"{"https://api.openai.com/auth":{"chatgpt_account_id":"account-123"}}"#,- );++ let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD++ .encode(br#"{"https://api.openai.com/auth":{"chatgpt_account_id":"account-123"}}"#);+ let token = format!("header.{payload}.signature");+ let converter =+ crate::core::server::converters::converter_for(Some("openai-responses"), true)+ .expect("converter");+ let (tx, _rx) = sink();+ stream_converted_chat_completions(+ &Client::new(),+ &format!("http://{addr}/chat/completions"),+ &[token],+ converter.as_ref(),+ &json!({+ "model": "gpt-5.6-terra",+ "messages": [{"role": "user", "content": "hi"}],+ "max_tokens": 128,+ }),+ &tx,+ )+ .await+ .expect("request");++ let request = server.await.expect("server task");+ let lower = request.to_ascii_lowercase();+ assert!(request.starts_with("POST /codex/responses HTTP/1.1\r\n"));+ assert!(lower.contains("\r\nchatgpt-account-id: account-123\r\n"));+ assert!(lower.contains("\r\nopenai-beta: responses=experimental\r\n"));+ assert!(lower.contains("\r\noriginator: jan\r\n"));+ let body: serde_json::Value =+ serde_json::from_str(request.split_once("\r\n\r\n").unwrap().1).unwrap();+ assert_eq!(body["store"], false);+ assert_eq!(body["include"], json!(["reasoning.encrypted_content"]));+ assert!(body.get("max_output_tokens").is_none());+ }+-/// A proxy in the environment breaks Jan and nothing else, and never shows up/// in the error. Names only: the values carry credentials.#[test]@@@ -1854,133 -1075,15 +1819,126 @@@},);-- let (url, _keys) = resolve_upstream_for_model(-- "sentence-transformer-mini",-- Arc::new(Mutex::new(configs)),-- )-- .await-- .expect("the API server provider is reachable");++ let (url, _keys) =++ resolve_upstream_for_model("sentence-transformer-mini", Arc::new(Mutex::new(configs)))++ .await++ .expect("the API server provider is reachable");assert_eq!(url, "http://127.0.0.1:1337/v1/chat/completions");}+ /// When two reachable HTTP providers offer the same model id - one+ /// credentialed, one keyless - resolution must pick the credentialed one.+ /// Alphabetical order alone would route e.g. `gpt-5.6-luna` (carried by+ /// both `openai` and a signed-in `opencode`) to the keyless `openai` entry+ /// and fail with a 401 on the first request.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn shared_model_id_prefers_the_credentialed_provider() {+ let mut configs = HashMap::new();+ // Alphabetically first, but keyless - the old code would pick this.+ configs.insert(+ "openai".to_string(),+ ProviderConfig {+ provider: "openai".into(),+ base_url: Some("https://api.openai.com/v1".into()),+ models: vec!["gpt-5.6-luna".into()],+ ..Default::default()+ },+ );+ // Signed in, so it carries a key.+ configs.insert(+ "opencode".to_string(),+ ProviderConfig {+ provider: "opencode".into(),+ base_url: Some("https://opencode.ai/zen/v1".into()),+ api_key: Some("sk-opencode".into()),+ models: vec!["gpt-5.6-luna".into()],+ ..Default::default()+ },+ );+- let (url, keys) = resolve_upstream_for_model(- "gpt-5.6-luna",- Arc::new(Mutex::new(configs)),- )- .await- .expect("the credentialed provider is selected");++ let (url, keys) = resolve_upstream_for_model("gpt-5.6-luna", Arc::new(Mutex::new(configs)))++ .await++ .expect("the credentialed provider is selected");+ assert_eq!(url, "https://opencode.ai/zen/v1/chat/completions");+ assert_eq!(keys, vec!["sk-opencode"]);+ }++ /// Holds the secret-store serialization guard, the temp data folder and the+ /// `JAN_DATA_FOLDER` restore together, so an async test can keep all three+ /// alive across `.await` without holding a bare lock guard over it.+ #[cfg(feature = "cli")]+ struct TempSecretStore {+ _guard: std::sync::MutexGuard<'static, ()>,+ previous: Option<String>,+ _dir: tempfile::TempDir,+ }++ #[cfg(feature = "cli")]+ impl TempSecretStore {+ fn new() -> Self {+ 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 previous = std::env::var("JAN_DATA_FOLDER").ok();+ std::env::set_var("JAN_DATA_FOLDER", dir.path());+ crate::core::server::provider_secrets::force_file_secrets();+ Self {+ _guard: guard,+ previous,+ _dir: dir,+ }+ }+ }++ #[cfg(feature = "cli")]+ impl Drop for TempSecretStore {+ fn drop(&mut self) {+ match &self.previous {+ Some(value) => std::env::set_var("JAN_DATA_FOLDER", value),+ None => std::env::remove_var("JAN_DATA_FOLDER"),+ }+ }+ }++ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn account_credentials_override_the_api_key_chain() {+ use crate::core::cli::auth::{Credential, CredentialStore, OAuthToken};++ let _secrets = TempSecretStore::new();+ CredentialStore::store(+ "openai",+ &Credential::OAuthToken(OAuthToken {+ access_token: "account-access".into(),+ refresh_token: Some("refresh".into()),+ expires_at: Some(1_800_000_000),+ token_type: "Bearer".into(),+ scopes: vec![],+ }),+ )+ .unwrap();+ let mut configs = HashMap::new();+ configs.insert(+ "openai".to_string(),+ ProviderConfig {+ provider: "openai".into(),+ base_url: Some("https://api.openai.com/v1".into()),+ api_key: Some("api-key".into()),+ models: vec!["account-model".into()],+ ..Default::default()+ },+ );+- let (url, keys) = resolve_upstream_for_model(- "account-model",- Arc::new(Mutex::new(configs)),- )- .await- .unwrap();++ let (url, keys) =++ resolve_upstream_for_model("account-model", Arc::new(Mutex::new(configs)))++ .await++ .unwrap();+ assert_eq!(url, "https://chatgpt.com/backend-api/chat/completions");+ assert_eq!(keys, vec!["account-access"]);+ }+#[test]fn parse_messages_passes_multimodal_content_array_through() {let messages = json!([{@@@ -2083,8 -1186,8 +2041,14 @@@assert_eq!(messages.len(), 4);assert_eq!(messages[2]["role"], "tool");assert_eq!(messages[2]["tool_call_id"], "toolu_ask");-- assert!(messages[2]["content"].as_str().unwrap().starts_with("ERROR"));-- assert_eq!(messages[3]["content"], "next message, no reply ever recorded");++ assert!(messages[2]["content"]++ .as_str()++ .unwrap()++ .starts_with("ERROR"));++ assert_eq!(++ messages[3]["content"],++ "next message, no reply ever recorded"++ );}#[test]@@@ -2249,8 -1352,8 +2213,12 @@@assert!(is_context_overflow_body("{\"error\":{\"code\":\"context_length_exceeded\"}}"));-- assert!(is_context_overflow_body("This model's maximum context length is 8192 tokens"));-- assert!(is_context_overflow_body("prompt is too long: 210000 tokens > 200000"));++ assert!(is_context_overflow_body(++ "This model's maximum context length is 8192 tokens"++ ));++ assert!(is_context_overflow_body(++ "prompt is too long: 210000 tokens > 200000"++ ));assert!(is_context_overflow_body("the request exceeds the available context size"));@@@ -2267,7 -1370,7 +2235,9 @@@fn overflow_marker_round_trips() {let err = format!("[{CONTEXT_OVERFLOW_MARKER}] Upstream returned HTTP 400: ...");assert!(is_context_overflow_error(&err));-- assert!(!is_context_overflow_error("Upstream returned HTTP 500: boom"));++ assert!(!is_context_overflow_error(++ "Upstream returned HTTP 500: boom"++ ));}/// The shapes strict endpoints actually return, plus the two ways a false@@@ -2479,265 -1425,4 +2292,263 @@@"an assistant turn with no reasoning stays unchanged");}++ /// Providers that inline `<think>` tags in `content` (no reasoning_content+ /// field) keep streaming through Token untouched: the tag-stripping+ /// fallback lives in the consumers.+ #[test]+ fn inline_think_tags_in_content_pass_through_as_tokens() {+ let (tx, mut rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest(+ &json!({ "choices": [{ "delta": { "content": "<think>hmm</think>answer" } }] })+ .to_string(),+ &tx,+ );+ drop(tx);+ let mut tokens = Vec::new();+ while let Ok(ev) = rx.try_recv() {+ match ev {+ StreamEvent::Token { text } => tokens.push(text),+ StreamEvent::Reasoning { .. } => panic!("no native reasoning here"),+ _ => {}+ }+ }+ assert_eq!(tokens, vec!["<think>hmm</think>answer"]);+ }++ #[test]+ fn reassembles_tool_call_arguments_split_across_deltas() {+ let (tx, _rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest(+ &json!({ "choices": [{ "delta": { "tool_calls": [+ { "index": 0, "id": "call_1", "function": { "name": "search", "arguments": "{\"q\":" } }+ ] } }] })+ .to_string(),+ &tx,+ );+ acc.ingest(+ &json!({ "choices": [{ "delta": { "tool_calls": [+ { "index": 0, "function": { "arguments": "\"rust\"}" } }+ ] } }] })+ .to_string(),+ &tx,+ );+ acc.ingest(+ &json!({ "choices": [{ "delta": {}, "finish_reason": "tool_calls" }],+ "usage": { "total_tokens": 12 } })+ .to_string(),+ &tx,+ );++ let completion = acc.into_completion();+ let tc = &completion["choices"][0]["message"]["tool_calls"][0];+ assert_eq!(tc["id"], "call_1");+ assert_eq!(tc["function"]["name"], "search");+ assert_eq!(tc["function"]["arguments"], "{\"q\":\"rust\"}");+ assert_eq!(completion["choices"][0]["finish_reason"], "tool_calls");+ assert_eq!(completion["usage"]["total_tokens"], 12);+ }++ #[test]+ fn emits_tool_call_started_once_when_id_and_name_first_known() {+ let (tx, mut rx) = sink();+ let mut acc = SseAccumulator::default();+ // First delta carries id + name; arguments arrive later, split across+ // deltas -- the in-progress signal must fire on this first delta only.+ acc.ingest(+ &json!({ "choices": [{ "delta": { "tool_calls": [+ { "index": 0, "id": "call_1", "function": { "name": "write", "arguments": "{\"path\":" } }+ ] } }] })+ .to_string(),+ &tx,+ );+ acc.ingest(+ &json!({ "choices": [{ "delta": { "tool_calls": [+ { "index": 0, "function": { "arguments": "\"a.txt\"}" } }+ ] } }] })+ .to_string(),+ &tx,+ );++ drop(tx);+ let started: Vec<(String, String)> = std::iter::from_fn(|| rx.try_recv().ok())+ .filter_map(|ev| match ev {+ StreamEvent::ToolCallStarted { id, name } => Some((id, name)),+ _ => None,+ })+ .collect();+ assert_eq!(started, vec![("call_1".to_string(), "write".to_string())]);+ }++ #[test]+ fn emits_tool_call_started_per_parallel_call() {+ let (tx, mut rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest(+ &json!({ "choices": [{ "delta": { "tool_calls": [+ { "index": 0, "id": "call_a", "function": { "name": "read", "arguments": "" } },+ { "index": 1, "id": "call_b", "function": { "name": "grep", "arguments": "" } }+ ] } }] })+ .to_string(),+ &tx,+ );++ drop(tx);+ let mut names: Vec<String> = std::iter::from_fn(|| rx.try_recv().ok())+ .filter_map(|ev| match ev {+ StreamEvent::ToolCallStarted { name, .. } => Some(name),+ _ => None,+ })+ .collect();+ names.sort();+ assert_eq!(names, vec!["grep".to_string(), "read".to_string()]);+ }++ #[test]+ fn captures_mid_stream_error_object_with_type_prefix() {+ let (tx, _rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest(+ &json!({ "choices": [{ "delta": { "content": "partial" } }] }).to_string(),+ &tx,+ );+ acc.ingest(+ &json!({ "error": { "message": "upstream exploded", "type": "server_error" } })+ .to_string(),+ &tx,+ );+ assert_eq!(+ acc.error.as_deref(),+ Some("server_error: upstream exploded")+ );+ }++ #[test]+ fn mid_stream_error_falls_back_to_message_without_type() {+ let (tx, _rx) = sink();+ let mut acc = SseAccumulator::default();- acc.ingest(- &json!({ "error": { "message": "boom" } }).to_string(),- &tx,- );++ acc.ingest(&json!({ "error": { "message": "boom" } }).to_string(), &tx);+ assert_eq!(acc.error.as_deref(), Some("boom"));+ }++ #[test]+ fn ignores_done_sentinel_and_malformed_lines() {+ let (tx, _rx) = sink();+ let mut acc = SseAccumulator::default();+ acc.ingest("[DONE]", &tx);+ acc.ingest("not json", &tx);+ let completion = acc.into_completion();+ assert!(completion["choices"][0]["message"]["content"].is_null());+ }++ /// Feed arbitrary byte chunks through the real buffering path, then close.+ fn feed_and_close(+ chunks: &[&str],+ events: &mpsc::UnboundedSender<StreamEvent>,+ ) -> serde_json::Value {+ let mut buf = String::new();+ let mut acc = SseAccumulator::default();+ for c in chunks {+ buf.push_str(c);+ drain_complete_lines(&mut buf, &mut acc, events);+ }+ flush_trailing_line(&buf, &mut acc, events);+ acc.into_completion()+ }++ #[test]+ fn flushes_final_line_without_trailing_newline() {+ let (tx, _rx) = sink();+ // Provider closes right after the final data line: no `\n`, no `[DONE]`.+ let final_chunk = json!({ "choices": [{ "delta": {}, "finish_reason": "tool_calls" }] });+ let completion = feed_and_close(+ &[+ "data: ",+ &json!({ "choices": [{ "delta": { "content": "hi" } }] }).to_string(),+ "\n\ndata: ",+ &final_chunk.to_string(),+ ],+ &tx,+ );++ assert_eq!(completion["choices"][0]["message"]["content"], "hi");+ assert_eq!(completion["choices"][0]["finish_reason"], "tool_calls");+ }++ #[test]+ fn newline_terminated_stream_still_parses() {+ let (tx, _rx) = sink();+ let completion = feed_and_close(+ &[+ &format!(+ "data: {}\n\n",+ json!({ "choices": [{ "delta": { "content": "ok" }, "finish_reason": "stop" }] })+ ),+ "data: [DONE]\n\n",+ ],+ &tx,+ );+ assert_eq!(completion["choices"][0]["message"]["content"], "ok");+ assert_eq!(completion["choices"][0]["finish_reason"], "stop");+ }++ /// The converted-stream decode path: a native (non-chat/completions) SSE+ /// event is run through its [`UpstreamConverter::convert_stream_event`],+ /// and each produced chat-shaped payload is fed into the same+ /// [`SseAccumulator`] the OpenAI path uses, so `StreamEvent`s come out+ /// identical. This mirrors `consume_converted_sse` (minus the live HTTP).+ #[test]+ fn converted_stream_emits_chat_shaped_events() {- use crate::core::server::converters::{- AnthropicMessagesConverter, SseEvent, StreamState,- };++ use crate::core::server::converters::{AnthropicMessagesConverter, SseEvent, StreamState};++ let (tx, mut rx) = sink();+ let converter = AnthropicMessagesConverter::new();+ let mut state = StreamState::default();+ let mut acc = SseAccumulator::default();++ // A single Anthropic `message_start` event -> role header chunk, then a+ // `content_block_delta` with text -> token chunk, then `message_stop`.+ let events = [+ SseEvent {+ event: "message_start".into(),+ data: json!({+ "type": "message_start",+ "message": { "id": "msg_1", "model": "claude-sonnet-4" }+ })+ .to_string(),+ },+ SseEvent {+ event: "content_block_delta".into(),+ data: json!({+ "type": "content_block_delta",+ "delta": { "type": "text_delta", "text": "hi" }+ })+ .to_string(),+ },+ SseEvent {+ event: "message_stop".into(),+ data: json!({ "type": "message_stop" }).to_string(),+ },+ ];+ for event in &events {+ for payload in converter.convert_stream_event(event, &mut state) {+ acc.ingest(&payload, &tx);+ }+ }++ // Exactly one Token event with the translated text.+ let mut tokens = Vec::new();+ while let Ok(StreamEvent::Token { text }) = rx.try_recv() {+ tokens.push(text);+ }- assert!(tokens.contains(&"hi".to_string()), "token delta decoded: {tokens:?}");++ assert!(++ tokens.contains(&"hi".to_string()),++ "token delta decoded: {tokens:?}"++ );++ let completion = acc.into_completion();+ assert_eq!(completion["choices"][0]["message"]["content"], "hi");+ }}diff --cc src-tauri/src/core/app/commands.rsindex aef1a3e5f,0bb40e8c0..7b95bfbd6--- a/src-tauri/src/core/app/commands.rs+++ b/src-tauri/src/core/app/commands.rs@@@ -58,7 -58,7 +58,7 @@@ fn migrate_from_candidates(canonical: &Ok(())}--fn legacy_app_config_candidate_paths(app_data_dir: &Path) -> Vec<PathBuf> {++fn legacy_app_config_candidate_paths(_app_data_dir: &Path) -> Vec<PathBuf> {let mut paths = Vec::new();if let Some(bundle_dir) = resolve_bundle_app_data_dir() {@@@ -70,7 -70,7 +70,7 @@@let package_name = env!("CARGO_PKG_NAME");if let Some(config_dir) = dirs::config_dir() {let legacy = config_dir.join(package_name).join(CONFIGURATION_FILE_NAME);-- if legacy != app_data_dir.join(CONFIGURATION_FILE_NAME) {++ if legacy != _app_data_dir.join(CONFIGURATION_FILE_NAME) {paths.push(legacy);}}diff --cc src-tauri/src/core/cli/auth/account.rsindex fba296830,000000000..7755ddbc7mode 100644,000000..100644--- a/src-tauri/src/core/cli/auth/account.rs+++ b/src-tauri/src/core/cli/auth/account.rs@@@ -1,2097 -1,0 +1,2098 @@@+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};+use rand::RngCore;+use sha2::{Digest, Sha256};++use super::{Credential, CredentialStore, OAuthToken};++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AccountProvider {+ Codex,+ Claude,+}++impl AccountProvider {+ pub const fn credential_provider(self) -> &'static str {+ match self {+ Self::Codex => "openai",+ Self::Claude => "anthropic",+ }+ }++ pub(crate) fn from_credential_provider(provider: &str) -> Option<Self> {+ match provider {+ "openai" => Some(Self::Codex),+ "anthropic" => Some(Self::Claude),+ _ => None,+ }+ }+}++#[derive(Clone)]+pub struct AccountLogin {+ pub authorization_url: String,+ pub redirect_uri: String,+ pub state: String,+ pub verifier: String,+ provider: AccountProvider,+ client_id: &'static str,+ token_endpoint: String,+ #[cfg(test)]+ model_base_url: Option<String>,+}++impl AccountLogin {+ pub const fn provider(&self) -> AccountProvider {+ self.provider+ }++ pub fn parse_manual_input(&self, raw: &str) -> Result<String, String> {+ parse_manual_callback(raw, &self.state)+ }++ fn set_redirect_uri(&mut self, redirect_uri: String) -> Result<(), String> {+ let mut authorization = url::Url::parse(&self.authorization_url)+ .map_err(|_| "the authorization URL was invalid".to_string())?;+ let query: Vec<(String, String)> = authorization+ .query_pairs()+ .filter(|(key, _)| key != "redirect_uri")+ .map(|(key, value)| (key.into_owned(), value.into_owned()))+ .collect();+ authorization+ .query_pairs_mut()+ .clear()+ .extend_pairs(query)+ .append_pair("redirect_uri", &redirect_uri);+ self.authorization_url = authorization.into();+ self.redirect_uri = redirect_uri;+ Ok(())+ }+}++pub fn begin(provider: AccountProvider) -> Result<AccountLogin, String> {+ let (client_id, authorization_endpoint, token_endpoint, redirect_uri, scopes) = match provider {+ AccountProvider::Codex => (+ "app_EMoamEEZ73f0CkXaXp7hrann",+ "https://auth.openai.com/oauth/authorize",+ "https://auth.openai.com/oauth/token",+ "http://localhost:1455/auth/callback",+ "openid profile email offline_access",+ ),+ AccountProvider::Claude => (+ "9d1c250a-e61b-44d9-88ed-5944d1962f5e",+ "https://claude.ai/oauth/authorize",+ "https://platform.claude.com/v1/oauth/token",+ "http://localhost:54545/callback",+ "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",+ ),+ };+ // PKCE generates a single random verifier; the `state` CSRF nonce is+ // usually a second random value. Anthropic's `claude.ai/oauth/authorize`+ // endpoint empirically rejects a random `state` with "Invalid request+ // format" -- it accepts only `state == code_verifier`, which is what the+ // Claude Code CLI, pi, and motosan-ai-oauth all send. OpenAI's Codex+ // endpoint accepts an independent random state, so only Claude reuses the+ // verifier as its state.+ let verifier = random_url_safe(96);+ let codex_state = random_hex(16);+ let state = if provider == AccountProvider::Claude {+ verifier.clone()+ } else {+ codex_state+ };+ let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));+ let mut url = url::Url::parse(authorization_endpoint).map_err(|e| e.to_string())?;+ {+ let mut query = url.query_pairs_mut();+ query.append_pair("response_type", "code");+ query.append_pair("client_id", client_id);+ query.append_pair("redirect_uri", redirect_uri);+ query.append_pair("scope", scopes);+ query.append_pair("code_challenge", &challenge);+ query.append_pair("code_challenge_method", "S256");+ query.append_pair("state", &state);+ if provider == AccountProvider::Codex {+ query.append_pair("id_token_add_organizations", "true");+ query.append_pair("codex_cli_simplified_flow", "true");+ query.append_pair("originator", "jan");+ } else {+ query.append_pair("code", "true");+ }+ }+ Ok(AccountLogin {+ authorization_url: url.into(),+ redirect_uri: redirect_uri.to_string(),+ state,+ verifier,+ provider,+ client_id,+ token_endpoint: token_endpoint.to_string(),+ #[cfg(test)]+ model_base_url: None,+ })+}++/// Append one line to the account-oauth debug log (under the Jan data+/// folder's `logs/` directory). Best-effort: a failing login must never be+/// blocked by a failing log write. The on-screen message stays sanitized;+/// this file carries the real stage/status/body detail for diagnostics.+pub fn debug_log(message: &str) {+ use std::io::Write;++ let data_folder = crate::core::app::commands::resolve_jan_data_folder();+ let path = data_folder.join("logs").join("account-oauth.log");+ let _ = std::fs::create_dir_all(path.parent().expect("log path has a parent"));+ let timestamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|duration| duration.as_secs())+ .unwrap_or_default();+ if let Ok(mut file) = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(&path)+ {+ let _ = writeln!(file, "[{timestamp}] {message}");+ }+}++fn random_url_safe(bytes: usize) -> String {+ let mut value = vec![0; bytes];+ rand::thread_rng().fill_bytes(&mut value);+ URL_SAFE_NO_PAD.encode(value)+}++/// CSRF state token. Lower-entropy hex (not base64url) to match what both+/// providers' authorization servers were validated against by the reference+/// implementations; the format is opaque to us either way; only the+/// authorize/callback round trip cares that it matches.+fn random_hex(bytes: usize) -> String {+ let mut value = vec![0; bytes];+ rand::thread_rng().fill_bytes(&mut value);+ hex::encode(value)+}++/// Extract the ChatGPT account id a Codex OAuth token was issued to. OpenAI's+/// Codex login returns an account-scoped token whose JWT claims carry the+/// ChatGPT account under `https://api.openai.com/auth` -> `chatgpt_account_id`;+/// both pi and opencode use this claim (never a `/v1/models` call) to identify+/// and validate the account. Returns the account id, or an error when the token+/// is not a decodable JWT carrying the claim.+fn codex_chatgpt_account_id(token: &str) -> Result<String, String> {+ let mut segments = token.split('.');+ let _header = segments.next();+ let payload = segments.next().ok_or_else(|| "token is not a JWT".to_string())?;+ let decoded = URL_SAFE_NO_PAD+ .decode(payload)+ .map_err(|_| "token payload is not base64url".to_string())?;+ let claims: serde_json::Value = serde_json::from_slice(&decoded)+ .map_err(|_| "token payload is not JSON".to_string())?;+ claims+ .get("https://api.openai.com/auth")+ .and_then(|auth| auth.get("chatgpt_account_id"))+ .and_then(|id| id.as_str())+ .map(str::to_string)+ .filter(|id| !id.is_empty())+ .ok_or_else(|| "token carries no chatgpt_account_id claim".to_string())+}++pub fn parse_callback(raw: &str, expected_state: &str) -> Result<String, String> {+ let url =+ url::Url::parse(raw.trim()).map_err(|_| "paste the complete redirect URL".to_string())?;+ let state = url+ .query_pairs()+ .find_map(|(key, value)| (key == "state").then_some(value.into_owned()))+ .ok_or_else(|| "the redirect URL is missing its state".to_string())?;+ if state != expected_state {+ return Err("the redirect state did not match".to_string());+ }++ url.query_pairs()+ .find_map(|(key, value)| (key == "code").then_some(value.into_owned()))+ .filter(|code| !code.is_empty())+ .ok_or_else(|| "the redirect URL is missing its authorization code".to_string())+}++pub fn parse_manual_callback(raw: &str, expected_state: &str) -> Result<String, String> {+ fn code_from_pairs<'a>(+ pairs: impl Iterator<Item = (std::borrow::Cow<'a, str>, std::borrow::Cow<'a, str>)>,+ expected_state: &str,+ ) -> Result<String, String> {+ let mut code = None;+ let mut state = None;+ for (key, value) in pairs {+ match key.as_ref() {+ "code" => code = Some(value.into_owned()),+ "state" => state = Some(value.into_owned()),+ _ => {}+ }+ }+ if state.is_some_and(|state| state != expected_state) {+ return Err("the redirect state did not match".to_string());+ }+ code.filter(|code| !code.is_empty())+ .ok_or_else(|| "the authorization code was empty".to_string())+ }++ let input = raw.trim();+ if input.is_empty() {+ return Err("enter the redirect URL or authorization code".to_string());+ }++ if let Ok(url) = url::Url::parse(input) {+ return code_from_pairs(url.query_pairs(), expected_state);+ }++ if input.starts_with("code=") || input.starts_with("?code=") {+ return code_from_pairs(+ url::form_urlencoded::parse(input.trim_start_matches('?').as_bytes()),+ expected_state,+ );+ }++ let (code, state) = input+ .split_once('#')+ .map_or((input, None), |(code, state)| (code, Some(state)));+ if state.is_some_and(|state| state.trim() != expected_state) {+ return Err("the redirect state did not match".to_string());+ }+ let code = code.trim();+ if code.is_empty() {+ return Err("the authorization code was empty".to_string());+ }+ Ok(code.to_string())+}++async fn accept_callback(+ listener: &CallbackListener,+ login: &AccountLogin,+) -> Result<String, String> {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ let mut stream = listener+ .accept()+ .await+ .map_err(|_| "could not receive the account callback".to_string())?;+ let mut request = [0; 8192];+ let read = stream+ .read(&mut request)+ .await+ .map_err(|_| "could not read the account callback".to_string())?;+ let target = std::str::from_utf8(&request[..read])+ .ok()+ .and_then(|request| request.lines().next())+ .and_then(|line| line.split_whitespace().nth(1))+ .ok_or_else(|| "the account callback was malformed".to_string())?;+ let callback = format!(+ "{}/{}",+ login.redirect_uri.trim_end_matches('/'),+ target.trim_start_matches('/')+ );+ let result = parse_callback(&callback, &login.state);+ let response = if result.is_ok() {+ "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 71\r\nConnection: close\r\n\r\n<html><body>Sign-in completed. You can close this window.</body></html>"+ } else {+ "HTTP/1.1 400 Bad Request\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 56\r\nConnection: close\r\n\r\n<html><body>Sign-in could not be verified.</body></html>"+ };+ let _ = stream.write_all(response.as_bytes()).await;+ result+}++/// A loopback listener for the OAuth redirect.+///+/// `localhost` resolves to both `::1` and `127.0.0.1`, and the browser opens a+/// single connection to whichever the resolver returns first (IPv6 on macOS and+/// most Linux distributions). One socket per family means the callback is+/// caught either way, and - because a bind to a *specific* address always+/// conflicts with another socket on that same address - it also lets us notice+/// that a port we were about to advertise is already someone else's.+pub struct CallbackListener {+ primary: tokio::net::TcpListener,+ secondary: Option<tokio::net::TcpListener>,+}++impl From<tokio::net::TcpListener> for CallbackListener {+ fn from(primary: tokio::net::TcpListener) -> Self {+ Self {+ primary,+ secondary: None,+ }+ }+}++impl CallbackListener {+ pub fn local_addr(&self) -> std::io::Result<std::net::SocketAddr> {+ self.primary.local_addr()+ }++ /// Accept the redirect from whichever loopback family the browser used.+ async fn accept(&self) -> std::io::Result<tokio::net::TcpStream> {+ match &self.secondary {+ None => self.primary.accept().await.map(|(stream, _)| stream),+ Some(secondary) => tokio::select! {+ accepted = self.primary.accept() => accepted.map(|(stream, _)| stream),+ accepted = secondary.accept() => accepted.map(|(stream, _)| stream),+ },+ }+ }+}++/// Bind the loopback listener that receives the OAuth redirect.+///+/// Prefer the provider's registered port, since some providers only whitelist+/// that exact redirect URI, and fall back to a fresh port when any loopback+/// family of the preferred port is taken - a port that is only half ours would+/// silently hand the callback to the process holding the other family.+pub async fn bind_callback(login: &mut AccountLogin) -> Result<CallbackListener, String> {+ let mut redirect = url::Url::parse(&login.redirect_uri)+ .map_err(|_| "the callback URL was invalid".to_string())?;+ let port = redirect+ .port_or_known_default()+ .ok_or_else(|| "the callback URL did not include a port".to_string())?;+ if let Some(listener) = bind_loopback(port).await {+ return Ok(listener);+ }++ let listener = bind_fresh_loopback()+ .await+ .ok_or_else(|| "could not start the local sign-in callback".to_string())?;+ let port = listener+ .local_addr()+ .map_err(|_| "could not read the local sign-in callback".to_string())?+ .port();+ redirect+ .set_port(Some(port))+ .map_err(|_| "the callback URL could not use the fallback port".to_string())?;+ login.set_redirect_uri(redirect.into())?;+ Ok(listener)+}++/// Claim `port` on every loopback family, or nothing at all.+async fn bind_loopback(port: u16) -> Option<CallbackListener> {+ let primary = match tokio::net::TcpListener::bind((std::net::Ipv6Addr::LOCALHOST, port)).await {+ Ok(primary) => primary,+ // Occupied means the browser could reach that other process: refuse the+ // port. Any other error means this host has no IPv6 loopback at all, so+ // `localhost` can only resolve to IPv4 and a v4 socket is sufficient.+ Err(error) if error.kind() == std::io::ErrorKind::AddrInUse => return None,+ Err(_) => {+ return tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port))+ .await+ .ok()+ .map(CallbackListener::from);+ }+ };+ let secondary = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port))+ .await+ .ok()?;+ Some(CallbackListener {+ primary,+ secondary: Some(secondary),+ })+}++/// Find an ephemeral port that is free on every loopback family.+///+/// The kernel only hands out an unused port for the family we ask about, so a+/// port free on IPv6 can still be taken on IPv4. Retry a few times rather than+/// advertising a half-owned port.+async fn bind_fresh_loopback() -> Option<CallbackListener> {+ for _ in 0..8 {+ let probe = match tokio::net::TcpListener::bind((std::net::Ipv6Addr::LOCALHOST, 0)).await {+ Ok(probe) => probe,+ // No IPv6 loopback: an IPv4 socket is all `localhost` can reach.+ Err(_) => {+ return tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))+ .await+ .ok()+ .map(CallbackListener::from);+ }+ };+ let candidate = probe.local_addr().ok()?.port();+ drop(probe);+ if let Some(listener) = bind_loopback(candidate).await {+ return Some(listener);+ }+ }+ None+}+++fn token_request_body(+ login: &AccountLogin,+ code: &str,+) -> std::collections::BTreeMap<String, String> {+ let mut fields = vec![+ ("grant_type", "authorization_code".to_string()),+ ("client_id", login.client_id.to_string()),+ ("code", code.to_string()),+ ("code_verifier", login.verifier.clone()),+ ("redirect_uri", login.redirect_uri.to_string()),+ ];+ // Anthropic's token endpoint expects `state` echoed back in the exchange+ // body (pi's `AnthropicOAuthFlow.exchangeToken` sends it); OpenAI's does+ // not accept it on this grant.+ if login.provider == AccountProvider::Claude {+ fields.push(("state", login.state.clone()));+ }+ fields+ .into_iter()+ .map(|(key, value)| (key.to_string(), value))+ .collect()+}+fn refresh_request_body(+ client_id: &str,+ token: &OAuthToken,+) -> Result<std::collections::BTreeMap<String, String>, String> {+ let refresh_token = token+ .refresh_token+ .as_deref()+ .filter(|token| !token.is_empty())+ .ok_or_else(|| "account sign-in must be completed again".to_string())?;+ Ok([+ ("grant_type", "refresh_token".to_string()),+ ("client_id", client_id.to_string()),+ ("refresh_token", refresh_token.to_string()),+ ]+ .into_iter()+ .map(|(key, value)| (key.to_string(), value))+ .collect())+}++async fn exchange(login: &AccountLogin, code: &str) -> Result<OAuthToken, String> {+ #[derive(serde::Deserialize)]+ struct TokenResponse {+ access_token: String,+ #[serde(default)]+ refresh_token: Option<String>,+ #[serde(default)]+ expires_in: Option<i64>,+ #[serde(default = "default_token_type")]+ token_type: String,+ #[serde(default)]+ scope: String,+ }++ fn default_token_type() -> String {+ "Bearer".to_string()+ }++ let request = reqwest::Client::new().post(&login.token_endpoint);+ let request = match login.provider {+ // Anthropic's /v1/oauth/token expects a JSON body (pi posts+ // application/json); OpenAI's accepts only form-encoded.+ AccountProvider::Claude => request.json(&token_request_body(login, code)),+ AccountProvider::Codex => request.form(&token_request_body(login, code)),+ };+ let response = request+ .send()+ .await+ .map_err(|error| {+ debug_log(&format!(+ "exchange: could not reach {}: {error}",+ login.token_endpoint+ ));+ "could not exchange the authorization code".to_string()+ })?;+ if !response.status().is_success() {+ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ debug_log(&format!(+ "exchange: rejected by {} with HTTP {status} body={body}",+ login.token_endpoint+ ));+ return Err(format!("account sign-in was rejected (HTTP {status})"));+ }+ let token = response+ .json::<TokenResponse>()+ .await+ .map_err(|_| "the account token response was unreadable".to_string())?;+ if token.access_token.is_empty() {+ return Err("the account token response did not contain an access token".to_string());+ }+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_err(|_| "could not read the system clock".to_string())?+ .as_secs() as i64;+ Ok(OAuthToken {+ access_token: token.access_token,+ refresh_token: token.refresh_token,+ expires_at: token+ .expires_in+ .map(|seconds| now.saturating_add(seconds.saturating_sub(300))),+ token_type: token.token_type,+ scopes: token.scope.split_whitespace().map(str::to_string).collect(),+ })+}++/// Client id and token endpoint for the refresh grant. Kept in sync with+/// `begin()` so a refresh always hits the same endpoint the user consented+/// to. Both providers' OAuth servers are served from the platform host, not+/// the inference API host (`api.anthropic.com` has no `/v1/oauth/token`).+fn refresh_endpoint(provider: AccountProvider) -> (&'static str, &'static str) {+ match provider {+ AccountProvider::Codex => (+ "app_EMoamEEZ73f0CkXaXp7hrann",+ "https://auth.openai.com/oauth/token",+ ),+ AccountProvider::Claude => (+ "9d1c250a-e61b-44d9-88ed-5944d1962f5e",+ "https://platform.claude.com/v1/oauth/token",+ ),+ }+}++pub async fn refresh(provider: AccountProvider, token: &OAuthToken) -> Result<OAuthToken, String> {+ #[derive(serde::Deserialize)]+ struct TokenResponse {+ access_token: String,+ #[serde(default)]+ refresh_token: Option<String>,+ #[serde(default)]+ expires_in: Option<i64>,+ #[serde(default = "default_token_type")]+ token_type: String,+ #[serde(default)]+ scope: String,+ }++ fn default_token_type() -> String {+ "Bearer".to_string()+ }++ let (client_id, token_endpoint) = refresh_endpoint(provider);+ let body = refresh_request_body(client_id, token)?;+ let request = reqwest::Client::new().post(token_endpoint);+ let request = match provider {+ // Anthropic refresh expects JSON plus the versioned beta header and a+ // recognizable user agent (pi's refreshAnthropicToken sends both);+ // OpenAI's endpoint accepts only form-encoded.+ AccountProvider::Claude => request+ .header("anthropic-beta", "oauth-2025-04-20")+ .header(+ "user-agent",+ "anthropic-sdk-typescript/0.94.0 userOAuthProvider",+ )+ .json(&body),+ AccountProvider::Codex => request.form(&body),+ };+ let response = request+ .send()+ .await+ .map_err(|error| {+ debug_log(&format!("refresh: could not reach {token_endpoint}: {error}"));+ "could not refresh the account token".to_string()+ })?;+ if !response.status().is_success() {+ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ debug_log(&format!(+ "refresh: rejected by {token_endpoint} with HTTP {status} body={body}"+ ));+ return Err(format!(+ "account token refresh was rejected (HTTP {status})"+ ));+ }+ let refreshed = response+ .json::<TokenResponse>()+ .await+ .map_err(|_| "the refreshed account token was unreadable".to_string())?;+ if refreshed.access_token.is_empty() {+ return Err("the refreshed account token did not contain an access token".to_string());+ }+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_err(|_| "could not read the system clock".to_string())?+ .as_secs() as i64;+ Ok(OAuthToken {+ access_token: refreshed.access_token,+ refresh_token: refreshed+ .refresh_token+ .or_else(|| token.refresh_token.clone()),+ expires_at: refreshed+ .expires_in+ .map(|seconds| now.saturating_add(seconds.saturating_sub(300))),+ token_type: refreshed.token_type,+ scopes: if refreshed.scope.is_empty() {+ token.scopes.clone()+ } else {+ refreshed+ .scope+ .split_whitespace()+ .map(str::to_string)+ .collect()+ },+ })+}++/// Test convenience: the Claude Code subscription access token from its stored+/// JSON secret. [`claude_code_oauth`] feeds it the raw keychain payload.+/// Returns `None` when the shape is absent or unparsable.+#[cfg(test)]+fn parse_claude_code_secret(raw: &str) -> Option<String> {+ claude_code_oauth(raw).map(|oauth| oauth.access_token)+}++/// Parse the full `claudeAiOauth` block Claude Code stores in its keychain+/// JSON into a Jan [`OAuthToken`] (access + refresh + expiry). Pure and+/// unit-testable. Returns `None` when the block is absent or unparsable.+fn claude_code_oauth(raw: &str) -> Option<OAuthToken> {+ // Claude Code stores a JSON object with a `claudeAiOauth` block carrying+ // accessToken/refreshToken/expiresAt. `expiresAt` is in epoch milliseconds;+ // Jan's OAuthToken expires_at is in seconds.+ let parsed: serde_json::Value = serde_json::from_str(raw).ok()?;+ let oauth = parsed.get("claudeAiOauth")?;+ let access = oauth.get("accessToken")?.as_str()?;+ if access.is_empty() {+ return None;+ }+ let expires_at = oauth+ .get("expiresAt")+ .and_then(|value| value.as_i64())+ .map(|millis| millis / 1000);+ Some(OAuthToken {+ access_token: access.to_string(),+ refresh_token: oauth+ .get("refreshToken")+ .and_then(|value| value.as_str())+ .map(str::to_string),+ expires_at,+ token_type: "Bearer".to_string(),+ scopes: Vec::new(),+ })+}++/// The clean generic macOS keychain descriptor type returned by the keyring+/// crate for a `Claude Code-credentials` entry.+fn claude_code_keychain_entry() -> Option<keyring::Entry> {+ // The account name is the macOS login user, which the OS keychain keys the+ // entry under. Claude Code names its service with the stable literal+ // "Claude Code-credentials" (a second, machine-hashed service has the+ // "Claude Code-credentials-<uuid>" shape and is not the live one).+ let user = std::env::var("USER")+ .or_else(|_| std::env::var("LOGNAME"))+ .ok()?;+ keyring::Entry::new("Claude Code-credentials", &user).ok()+}++/// The `subscriptionType` Claude Code stamps on a resolved account (e.g.+/// `team`, `pro`, `enterprise`, `free`). Authoritative for which plan the token+/// actually resolved to, so a team/enterprise account whose heavy-model quota is+/// momentarily exhausted is not misreported as a free personal plan. Best-effort:+/// returns `None` when the keychain entry is absent or the field is missing.+fn claude_code_subscription_type() -> Option<String> {+ if !claude_alias_enabled() {+ return None;+ }+ claude_code_keychain_entry()?+ .get_password()+ .ok()+ .and_then(|raw| {+ let doc: serde_json::Value = serde_json::from_str(&raw).ok()?;+ doc.get("claudeAiOauth")?+ .get("subscriptionType")?+ .as_str()+ .map(str::to_string)+ })+}++pub(crate) const CLAUDE_ALIAS_NOTICE: &str =+ "Claude Code keychain login is active: Jan may use and refresh that credential for Claude requests. Disable with `claude_code_alias = false` in ~/.jan/config.toml or `/settings`. Jan is a third-party client; review Anthropic's Terms of Service.";++static CLAUDE_ALIAS_ENGAGED: std::sync::atomic::AtomicBool =+ std::sync::atomic::AtomicBool::new(false);++#[cfg(test)]+static CLAUDE_ALIAS_ENABLED: std::sync::atomic::AtomicBool =+ std::sync::atomic::AtomicBool::new(false);++#[cfg(test)]+fn claude_alias_enabled() -> bool {+ CLAUDE_ALIAS_ENABLED.load(std::sync::atomic::Ordering::Relaxed)+}++#[cfg(not(test))]+fn claude_alias_enabled() -> bool {+ crate::core::agent::global_config::claude_code_alias_enabled()+}++/// Test-only: flip whether the Claude Code alias is consulted in production+/// code paths from unit tests. Off by default so tests never touch the+/// developer's keychain or a real omp install; on in production.+#[cfg(test)]+pub(crate) fn set_claude_alias(enabled: bool) {+ CLAUDE_ALIAS_ENABLED.store(enabled, std::sync::atomic::Ordering::Relaxed);+}++pub(crate) fn take_claude_alias_engaged() -> bool {+ CLAUDE_ALIAS_ENGAGED.swap(false, std::sync::atomic::Ordering::Relaxed)+}++#[cfg(test)]+pub(crate) fn mark_claude_alias_engaged_for_test() {+ CLAUDE_ALIAS_ENGAGED.store(true, std::sync::atomic::Ordering::Relaxed);+}++/// Resolve a working access token from Claude Code's keychain entry, refreshing+/// it and writing the rotated token back into the same keychain entry (the+/// single source of truth omp also reads) when it has expired. This keeps Jan+/// usable unattended with the enterprise workspace's OAuth login without a+/// browser re-consent, and omp re-reads its own keychain each launch so it+/// stays current.+async fn claude_code_access_token() -> Option<String> {+ if !claude_alias_enabled() {+ return None;+ }+ let entry = claude_code_keychain_entry()?;+ let raw = entry.get_password().ok()?;+ let oauth = claude_code_oauth(&raw)?;+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .ok()?+ .as_secs() as i64;+ if oauth.expires_at.is_some_and(|expires_at| expires_at <= now) {+ match refresh(AccountProvider::Claude, &oauth).await {+ Ok(fresh) => {+ // Write the rotated token back into omp's keychain entry so the+ // shared credential stays fresh even if Jan is the only client+ // running. On writeback failure we still return the refreshed+ // token so Jan keeps working for this session.+ if write_claude_code_keychain(&entry, &raw, &fresh).is_err() {+ debug_log("claude alias: refreshed but could not write back to the Claude Code keychain");+ }+ #[cfg(not(test))]+ CLAUDE_ALIAS_ENGAGED.store(true, std::sync::atomic::Ordering::Relaxed);+ return Some(fresh.access_token);+ }+ Err(error) => {+ debug_log(&format!(+ "claude alias: could not refresh Claude Code token: {error}"+ ));+ return None;+ }+ }+ }+ #[cfg(not(test))]+ CLAUDE_ALIAS_ENGAGED.store(true, std::sync::atomic::Ordering::Relaxed);+ Some(oauth.access_token)+}++/// Refresh-rotate the `claudeAiOauth` block inside a Claude Code keychain JSON+/// document in place, preserving all other top-level fields (e.g. `mcpOAuth`,+/// `claudeOauth`), so omp's entry is updated rather than replaced. Pure and+/// unit-testable; [`write_claude_code_keychain`] persists the result.+fn rotate_claude_code_secret(raw: &str, fresh: &OAuthToken) -> Result<String, String> {+ let mut doc: serde_json::Value =+ serde_json::from_str(raw).map_err(|_| "unparsable Claude Code secret".to_string())?;+ let oauth = doc+ .get_mut("claudeAiOauth")+ .ok_or_else(|| "no claudeAiOauth block in Claude Code secret".to_string())?;+ oauth["accessToken"] = serde_json::Value::String(fresh.access_token.clone());+ if let Some(refresh_token) = &fresh.refresh_token {+ oauth["refreshToken"] = serde_json::Value::String(refresh_token.clone());+ }+ if let Some(expires_at_secs) = fresh.expires_at {+ // Claude Code stores expiresAt in epoch milliseconds.+ oauth["expiresAt"] =+ serde_json::Value::Number((expires_at_secs.saturating_mul(1000)).into());+ }+ Ok(doc.to_string())+}++/// Refresh-rotate the `claudeAiOauth` block inside a Claude Code keychain JSON+/// document in place, preserving all other top-level fields (e.g. `mcpOAuth`,+/// `claudeOauth`), so omp's entry is updated rather than replaced.+fn write_claude_code_keychain(+ entry: &keyring::Entry,+ raw: &str,+ fresh: &OAuthToken,+) -> Result<(), String> {+ let updated = rotate_claude_code_secret(raw, fresh)?;+ entry+ .set_password(&updated)+ .map_err(|error| format!("could not update the Claude Code keychain: {error}"))+}++/// Resolve a working access token for `provider`, preferring Jan's own stored+/// credential. For the Claude provider, when Jan has no account credential of+/// its own, this falls back to Claude Code's keychain token (see+/// [`claude_code_access_token`]) so the enterprise subscription quota is the+/// same one omp uses.+pub async fn access_token(provider: &str) -> Result<Option<String>, String> {+ let Some(provider_kind) = AccountProvider::from_credential_provider(provider) else {+ return Ok(None);+ };+ let stored = CredentialStore::load(provider)?;+ let Some(stored) = stored else {+ // No Jan-owned credential at all: alias Claude Code's token (Claude+ // only). A stored API key is a deliberate user choice and must not be+ // overridden by the Claude Code keychain token.+ if provider_kind == AccountProvider::Claude {+ if let Some(access) = claude_code_access_token().await {+ return Ok(Some(access));+ }+ }+ return Ok(None);+ };+ let Credential::OAuthToken(token) = stored else {+ // A stored API key is a deliberate choice; never substitute a token.+ return Ok(None);+ };+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_err(|_| "could not read the system clock".to_string())?+ .as_secs() as i64;+ if token.expires_at.is_some_and(|expires_at| expires_at <= now) {+ let refreshed = refresh(provider_kind, &token).await?;+ store(provider_kind, &refreshed)?;+ return Ok(Some(refreshed.access_token));+ }+ Ok(Some(token.access_token))+}+/// Whether `provider` is authenticated with an OAuth account token rather+/// than a plain API key. This is the discriminator for selecting the OAuth+/// upstream wire scheme (Bearer + Code `?beta=true` headers): it must reflect+/// the stored credential, not merely that the provider supports account+/// login. `openai`/`anthropic` are also first-class API-key providers, so a+/// provider name alone is not enough to pick the OAuth scheme (a plain+/// `sk-ant-…` key must stay on `x-api-key` + `/messages`).+pub fn has_oauth_credential(provider: &str) -> bool {+ let Ok(Some(Credential::OAuthToken(_))) = CredentialStore::load(provider) else {+ return false;+ };+ true+}+++pub fn store(provider: AccountProvider, token: &OAuthToken) -> Result<(), String> {+ CredentialStore::store(+ provider.credential_provider(),+ &Credential::OAuthToken(token.clone()),+ )+}+// A Claude account token resolves to whichever Anthropic org/workspace was+// active on claude.ai at consent time. That org's plan decides which models+// the token may run: on the free personal plan only lightweight models (e.g.+// claude-haiku) respond, while heavy models (sonnet/opus) return 429 even+// with plentiful overall quota. This reports the resolved entitlement so a+// sign-in that landed on the wrong org is diagnosed immediately instead of+// surfacing later as mysterious rate-limit errors. Best-effort: never fails+// a login; on any error it returns the given `fallback` message.+pub async fn claude_plan_summary(fallback: &str) -> String {+ // Resolve through access_token so the probe sees the same token the+ // request path uses: Jan's own credential when present, otherwise the+ // Claude Code alias (see claude_code_access_token).+ let Some(token) = access_token(AccountProvider::Claude.credential_provider())+ .await+ .ok()+ .flatten()+ else {+ return fallback.to_string();+ };+ let client = match reqwest::Client::builder()+ .timeout(std::time::Duration::from_secs(15))+ .build()+ {+ Ok(client) => client,+ Err(_) => return fallback.to_string(),+ };+ // Distinguish a model-family entitlement boundary from a transient quota+ // window. Probe one heavy model (sonnet) and one lightweight model (haiku).+ // When only haiku answers, the heavy answer may be a genuine entitlement+ // boundary OR a momentarily exhausted 5-hour quota window; the account's+ // stamped `subscriptionType` disambiguates the two (a paid tier that 429s is+ // quota exhaustion, not a free plan).+ let mut heavy_ok = false;+ for model in ["claude-haiku-4-5", "claude-sonnet-5"] {+ let body = serde_json::json!({+ "model": model,+ "max_tokens": 1,+ "messages": [{"role": "user", "content": "hi"}],+ // Anthropic gates heavy-model quota (sonnet) behind this billing+ // marker on the /v1/messages system block for an OAuth token;+ // without it sonnet 429s regardless of the account's real plan+ // (see AnthropicMessagesConverter). Probe with it so the report+ // matches the plan Jan's request path actually resolves.+ "system": [{"type": "text", "text": "x-anthropic-billing-header: cc_version=2.1.92; cc_entrypoint=sdk-cli;"}],+ });+ let probe = client+ .post("https://api.anthropic.com/v1/messages")+ .header("Authorization", format!("Bearer {token}"))+ .header("anthropic-beta", "oauth-2025-04-20,claude-code-20250219")+ .header("anthropic-version", "2023-06-01")+ .json(&body)+ .send()+ .await;+ if model == "claude-sonnet-5"+ && matches!(&probe, Ok(response) if response.status().is_success())+ {+ heavy_ok = true;+ }+ }+ let tier = claude_code_subscription_type();+ claude_plan_message(heavy_ok, tier.as_deref())+}++/// True when a stamped `subscriptionType` is a paid/enterprise plan whose heavy+/// models carry quota, as opposed to the free personal plan.+fn is_paid_claude_tier(tier: Option<&str>) -> bool {+ matches!(+ tier,+ Some("team")+ | Some("pro")+ | Some("enterprise")+ | Some("max")+ | Some("premium")+ )+}++/// Human-readable verdict on which Claude entitlement a token resolved to.+/// `heavy_ok` is whether the heavy-model probe (sonnet) succeeded; `tier` is+/// the `subscriptionType` stamped by Claude Code, when reachable.+fn claude_plan_message(heavy_ok: bool, tier: Option<&str>) -> String {+ if heavy_ok {+ "Claude account resolved with heavy-model access (enterprise/premium quota in effect). Models check out: claude-sonnet-5 and claude-haiku-4-5 both respond.".to_string()+ } else if is_paid_claude_tier(tier) {+ format!(+ "Claude account resolves to a {} account, not a free plan: heavy models are momentarily rate-limited (429) while claude-haiku-4-5 works. This is a transient 5-hour quota window, not a plan or sign-in problem - retry shortly or use a lightweight model to continue.",+ tier.unwrap_or("paid")+ )+ } else {+ "Claude account resolves to a plan without heavy-model access (likely the free personal plan): claude-sonnet-5 is rate-limited (429) while claude-haiku-4-5 works. This is a quota/entitlement boundary, not a sign-in problem, so reusing Claude Code's saved login (sign out with x on the picker) inherits whatever quota that workspace carries - heavy-model access only improves if your Claude Code workspace has a premium allowance.".to_string()+ }+}+++pub async fn complete_callback_login_with_manual(+ listener: CallbackListener,+ login: AccountLogin,+ mut manual: tokio::sync::mpsc::UnboundedReceiver<String>,+) -> Result<AccountProvider, String> {+ let code = {+ let callback = accept_callback(&listener, &login);+ tokio::pin!(callback);+ loop {+ match manual.try_recv() {+ Ok(input) => {+ if let Ok(code) = login.parse_manual_input(&input) {+ break code;+ }+ }+ Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {}+ Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {+ break callback.await?;+ }+ }+ tokio::select! {+ result = &mut callback => break result?,+ input = manual.recv() => match input {+ Some(input) => {+ if let Ok(code) = login.parse_manual_input(&input) {+ break code;+ }+ }+ None => break callback.await?,+ },+ }+ }+ };+ complete_code_login(login, code).await+}++async fn complete_code_login(+ login: AccountLogin,+ code: String,+) -> Result<AccountProvider, String> {+ let provider = login.provider;+ let token = exchange(&login, &code).await?;+ let definition =+ crate::core::cli::auth::provider_by_id(provider.credential_provider())+ .ok_or_else(|| "selected account is unavailable".to_string())?;+ #[cfg(test)]+ let definition = {+ let mut definition = definition;+ if let Some(base_url) = login.model_base_url {+ definition.default_base_url = base_url;+ }+ definition+ };+ // Codex and Claude account tokens authenticate against different surfaces.+ // A Claude account token is valid against `/v1/models` (Anthropic accepts+ // it with the OAuth beta header). A Codex account token is a ChatGPT+ // account token that `api.openai.com/v1/models` rejects (401) because that+ // endpoint only accepts an API key - so discovery is skipped for Codex and+ // the account is instead verified from the JWT `chatgpt_account_id` claim,+ // exactly as opencode and pi do. Codex is served through the Responses API.+ let (models, api_type) = if provider == AccountProvider::Codex {+ match codex_chatgpt_account_id(&token.access_token) {+ Ok(account_id) => {+ debug_log(&format!("codex: verified chatgpt_account_id {account_id}"));+ // Fetch the account's real Codex roster from the ChatGPT+ // backend's `/codex/models` endpoint (a Codex account token is+ // a ChatGPT credential, not an OpenAI API key, so+ // `api.openai.com/v1/models` rejects it). `/codex/models`+ // returns the stable Codex slugs, whereas+ // `chatgpt.com/backend-api/models` would return rolling+ // user-scoped ChatGPT codenames that cannot run. Fall back to+ // a single default model so a transient roster failure never+ // hard-fails an otherwise valid login.+ let models = crate::core::cli::auth::providers::discover_codex_models(+ &token.access_token,+ Some(&account_id),+ &definition.default_base_url,+ )+ .await+ .map(|m| {+ if m.is_empty() {+ vec!["gpt-5-chat-latest".to_string()]+ } else {+ m+ }+ })+ .unwrap_or_else(|error| {+ debug_log(&format!("codex: model discovery failed: {error:?}"));+ vec!["gpt-5-chat-latest".to_string()]+ });+ (models, Some("openai-responses".to_string()))+ }+ Err(error) => {+ debug_log(&format!("codex: account validation failed: {error}"));+ return Err("could not verify the Codex account".to_string());+ }+ }+ } else {+ let models =+ crate::core::cli::auth::providers::discover_models(&definition, &token.access_token, true)+ .await+ .map_err(|error| {+ debug_log(&format!(+ "model discovery: {} rejected the token: {error:?}",+ definition.id+ ));+ "could not discover account models".to_string()+ })?;+ (+ models,+ matches!(+ definition.transport,+ crate::core::cli::auth::Transport::Anthropic+ )+ .then_some("anthropic".to_string()),+ )+ };+ store(provider, &token)?;+ if let Err(error) = crate::core::agent::global_config::set_provider(+ definition.id,+ crate::core::agent::global_config::ProviderUpdate {+ api_key: None,+ clear_api_key: true,+ base_url: Some(definition.default_base_url),+ models: Some(models),+ api_type,++ ..Default::default()+ },+ ) {+ let _ = CredentialStore::delete(provider.credential_provider());+ return Err(format!(+ "could not save the provider configuration: {error}"+ ));+ }+ Ok(provider)+}+#[cfg(test)]+mod tests {++ use super::*;+ use crate::core::agent::global_config::{load_global_config, with_temp_home};+ use crate::core::server::provider_secrets::SECRET_STORE_TEST_LOCK;+ use std::io::{Read, Write};+ use std::net::TcpListener;+ use std::sync::{mpsc, MutexGuard};++ /// Serializes the tests that mutate the process-global Claude alias latch,+ /// which cargo runs in parallel threads. A tokio mutex, not a std one:+ /// these tests hold the guard across `.await`.+ static ALIAS_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());++ async fn alias_test_lock() -> tokio::sync::MutexGuard<'static, ()> {+ ALIAS_TEST_LOCK.lock().await+ }++ struct TempSecrets {+ _guard: MutexGuard<'static, ()>,+ prev_data_folder: Option<String>,+ _dir: tempfile::TempDir,+ }++ impl TempSecrets {+ fn new() -> Self {+ let guard = SECRET_STORE_TEST_LOCK+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ let dir = tempfile::tempdir().unwrap();+ let prev_data_folder = std::env::var("JAN_DATA_FOLDER").ok();+ std::env::set_var("JAN_DATA_FOLDER", dir.path());+ crate::core::server::provider_secrets::force_file_secrets();+ Self {+ _guard: guard,+ prev_data_folder,+ _dir: dir,+ }+ }+ }++ impl Drop for TempSecrets {+ fn drop(&mut self) {+ match &self.prev_data_folder {+ Some(value) => std::env::set_var("JAN_DATA_FOLDER", value),+ None => std::env::remove_var("JAN_DATA_FOLDER"),+ }+ }+ }++ fn account_models_server(+ status_line: &'static str,+ body: &'static str,+ ) -> (String, mpsc::Receiver<String>) {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ let (tx, rx) = mpsc::channel();+ std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut request = [0; 4096];+ let read = stream.read(&mut request).unwrap_or(0);+ let _ = tx.send(String::from_utf8_lossy(&request[..read]).into_owned());+ let response = format!(+ "HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ body.len(),+ body+ );+ let _ = stream.write_all(response.as_bytes());+ });+ (format!("http://{addr}/v1"), rx)+ }++ fn unavailable_base_url() -> String {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ drop(listener);+ format!("http://{addr}/v1")+ }++ /// Build a signed-shape Codex OAuth access token (a JWT) carrying the+ /// `https://api.openai.com/auth` -> `chatgpt_account_id` claim that jan+ /// uses to verify a Codex account. The signature is a dummy; `codex_chatgpt_account_id`+ /// decodes only the payload segment.+ fn codex_jwt(account_id: &str) -> String {+ use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};+ let header = URL_SAFE_NO_PAD.encode(r#"{"alg":"RS256"}"#);+ let payload = serde_json::json!({+ "https://api.openai.com/auth": { "chatgpt_account_id": account_id },+ "sub": account_id,+ });+ let payload = URL_SAFE_NO_PAD.encode(payload.to_string());+ format!("{header}.{payload}.signature")+ }++ /// Build a fake OpenAI token exchange response whose access token is a+ /// Codex JWT. Used by the live accounts tests to exercise the Codex+ /// verify-then-persist path.+ fn codex_token_server(account_id: &str) -> String {+ let jwt = codex_jwt(account_id);+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let endpoint = format!("http://{}/token", listener.local_addr().unwrap());+ std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut request = [0; 4096];+ let _ = stream.read(&mut request).unwrap();+ let body = format!(+ r#"{{"access_token":"{}","refresh_token":"refresh","expires_in":3600,"token_type":"Bearer","scope":"profile offline_access"}}"#,+ jwt+ );+ write!(+ stream,+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ body.len(),+ body+ )+ .unwrap();+ });+ endpoint+ }++ fn complete_account_for_test(models_base_url: String) -> Result<AccountProvider, String> {+ std::thread::spawn(move || {+ tokio::runtime::Runtime::new().unwrap().block_on(async move {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let mut login = begin(AccountProvider::Codex).unwrap();+ login.token_endpoint = codex_token_server("account-321");+ login.model_base_url = Some(models_base_url);+ let callback = format!(+ "GET /auth/callback?code=authorization-code&state={} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n",+ login.state+ );+ let client = tokio::spawn(async move {+ let mut stream = tokio::net::TcpStream::connect(address).await.unwrap();+ tokio::io::AsyncWriteExt::write_all(&mut stream, callback.as_bytes())+ .await+ .unwrap();+ });+ let code = accept_callback(&listener.into(), &login).await?;+ let result = complete_code_login(login, code).await;+ client.await.unwrap();+ result+ })+ })+ .join()+ .expect("account completion thread must not panic")+ }+++ /// A Claude-specific completion helper. Claude OAuth keeps the real+ /// `/v1/models` discovery path, so these tests exercise discovery failure+ /// semantics against a plain account token (Claude's token is not a JWT).+ fn complete_claude_account_for_test(+ models_base_url: String,+ ) -> Result<AccountProvider, String> {+ std::thread::spawn(move || {+ tokio::runtime::Runtime::new().unwrap().block_on(async move {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let mut login = begin(AccountProvider::Claude).unwrap();+ login.model_base_url = Some(models_base_url);+ let callback = format!(+ "GET /callback?code=authorization-code&state={} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n",+ login.state+ );+ let client = tokio::spawn(async move {+ let mut stream = tokio::net::TcpStream::connect(address).await.unwrap();+ tokio::io::AsyncWriteExt::write_all(&mut stream, callback.as_bytes())+ .await+ .unwrap();+ });+ let code = accept_callback(&listener.into(), &login).await?;+ let result = complete_code_login(login, code).await;+ client.await.unwrap();+ result+ })+ })+ .join()+ .expect("claude account completion thread must not panic")+ }+ fn complete_account_manually_for_test(+ models_base_url: String,+ ) -> Result<AccountProvider, String> {+ std::thread::spawn(move || {+ tokio::runtime::Runtime::new().unwrap().block_on(async move {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let mut login = begin(AccountProvider::Codex).unwrap();+ login.token_endpoint = codex_token_server("account-321");+ login.model_base_url = Some(models_base_url);+ let manual_input = format!("authorization-code#{}", login.state);+ let (manual, receiver) = tokio::sync::mpsc::unbounded_channel();+ manual.send(manual_input).unwrap();+ complete_callback_login_with_manual(listener.into(), login, receiver).await+ })+ })+ .join()+ .expect("manual account completion thread must not panic")+ }++ #[test]+ fn codex_browser_login_uses_pkce_and_loopback_callback() {+ let login = begin(AccountProvider::Codex).unwrap();+ let url = url::Url::parse(&login.authorization_url).unwrap();++ assert_eq!(+ url.origin().ascii_serialization(),+ "https://auth.openai.com"+ );+ assert_eq!(url.path(), "/oauth/authorize");+ assert_eq!(+ url.query_pairs()+ .find(|(key, _)| key == "response_type")+ .unwrap()+ .1,+ "code"+ );+ assert_eq!(+ url.query_pairs()+ .find(|(key, _)| key == "code_challenge_method")+ .unwrap()+ .1,+ "S256"+ );+ assert_eq!(login.redirect_uri, "http://localhost:1455/auth/callback");+ assert!(!login.state.is_empty());+ assert!(!login.verifier.is_empty());+ }++ #[test]+ fn claude_browser_login_uses_pkce_and_loopback_callback() {+ let login = begin(AccountProvider::Claude).unwrap();+ let url = url::Url::parse(&login.authorization_url).unwrap();++ assert_eq!(url.origin().ascii_serialization(), "https://claude.ai");+ assert_eq!(url.path(), "/oauth/authorize");+ assert_eq!(+ url.query_pairs()+ .find(|(key, _)| key == "response_type")+ .unwrap()+ .1,+ "code"+ );+ assert_eq!(+ url.query_pairs()+ .find(|(key, _)| key == "code_challenge_method")+ .unwrap()+ .1,+ "S256"+ );+ assert_eq!(login.redirect_uri, "http://localhost:54545/callback");+ assert!(!login.state.is_empty());+ assert!(!login.verifier.is_empty());+ }++ #[tokio::test]+ async fn callback_falls_back_when_the_preferred_port_is_busy() {+ let occupied = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let occupied_port = occupied.local_addr().unwrap().port();+ let mut login = begin(AccountProvider::Claude).unwrap();+ login.redirect_uri = format!("http://localhost:{occupied_port}/callback");++ let listener = bind_callback(&mut login)+ .await+ .expect("a random callback port is used");+ let actual_port = listener.local_addr().unwrap().port();+ assert_ne!(actual_port, occupied_port);+ let expected = format!("http://localhost:{actual_port}/callback");+ assert_eq!(login.redirect_uri, expected);+ let authorization = url::Url::parse(&login.authorization_url).unwrap();+ assert_eq!(+ authorization+ .query_pairs()+ .find(|(key, _)| key == "redirect_uri")+ .unwrap()+ .1,+ expected+ );+ assert_eq!(+ token_request_body(&login, "code").get("redirect_uri"),+ Some(&expected)+ );+ }++ /// The user-visible bug: another process (Cursor, another Claude Code+ /// install) holds the IPv6 loopback for the preferred port while IPv4 is+ /// still free. `localhost` resolves IPv6-first on macOS, so the browser+ /// delivers the callback to that other process and the sign-in hangs+ /// forever. Binding IPv4 must not be treated as "the port is ours".+ #[tokio::test]+ async fn callback_avoids_a_port_whose_ipv6_loopback_is_busy() {+ let Ok(occupied) = tokio::net::TcpListener::bind("[::1]:0").await else {+ return; // No IPv6 loopback on this machine; nothing to prove.+ };+ let occupied_port = occupied.local_addr().unwrap().port();+ let mut login = begin(AccountProvider::Claude).unwrap();+ login+ .set_redirect_uri(format!("http://localhost:{occupied_port}/callback"))+ .unwrap();++ let listener = bind_callback(&mut login)+ .await+ .expect("a usable callback port is chosen");++ // The browser opens ONE connection to the first address `localhost`+ // resolves to, so the advertised port must be ours on every loopback+ // family - not merely on IPv4.+ let redirect = url::Url::parse(&login.redirect_uri).unwrap();+ let port = redirect.port().unwrap();+ assert_eq!(listener.local_addr().unwrap().port(), port);+ assert_ne!(+ port, occupied_port,+ "advertised a port whose IPv6 loopback belongs to another process"+ );+ assert!(+ tokio::net::TcpListener::bind((std::net::Ipv6Addr::LOCALHOST, port))+ .await+ .is_err(),+ "the callback listener must own the IPv6 loopback the browser will use"+ );+ }++ #[test]+ fn claude_browser_login_uses_registered_client_id() {+ let login = begin(AccountProvider::Claude).unwrap();+ let url = url::Url::parse(&login.authorization_url).unwrap();++ assert_eq!(+ url.query_pairs()+ .find(|(key, _)| key == "client_id")+ .unwrap()+ .1,+ "9d1c250a-e61b-44d9-88ed-5944d1962f5e"+ );+ assert_eq!(login.client_id, "9d1c250a-e61b-44d9-88ed-5944d1962f5e");+ assert_eq!(+ login.token_endpoint,+ "https://platform.claude.com/v1/oauth/token"+ );+ }++ #[test]+ fn claude_browser_login_matches_reference_state_and_scopes() {+ let login = begin(AccountProvider::Claude).unwrap();+ let url = url::Url::parse(&login.authorization_url).unwrap();++ assert_eq!(+ url.query_pairs()+ .find(|(key, _)| key == "scope")+ .unwrap()+ .1,+ "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload"+ );+ // Anthropic accepts only `state == code_verifier`, so Claude's state+ // must equal its verifier (not be an independent random value).+ assert_eq!(login.state, login.verifier, "Claude state must equal verifier");+ assert!(+ url.query_pairs()+ .find(|(key, _)| key == "state")+ .unwrap()+ .1+ == login.verifier,+ "authorize URL state must be the verifier"+ );+ }++ #[test]+ fn codex_browser_login_matches_reference_flow() {+ let login = begin(AccountProvider::Codex).unwrap();+ let url = url::Url::parse(&login.authorization_url).unwrap();++ assert_eq!(+ url.query_pairs()+ .find(|(key, _)| key == "scope")+ .unwrap()+ .1,+ "openid profile email offline_access"+ );+ assert_eq!(+ url.query_pairs()+ .find(|(key, _)| key == "originator")+ .unwrap()+ .1,+ "jan"+ );+ assert_eq!(url.query_pairs().find(|(key, _)| key == "client_id").unwrap().1, "app_EMoamEEZ73f0CkXaXp7hrann");+ assert_eq!(login.token_endpoint, "https://auth.openai.com/oauth/token");+ }++ #[test]+ fn callback_requires_the_matching_state() {+ let login = begin(AccountProvider::Codex).unwrap();+ let accepted = format!(+ "{}?code=authorization-code&state={}",+ login.redirect_uri, login.state+ );+ assert_eq!(+ parse_callback(&accepted, &login.state).unwrap(),+ "authorization-code"+ );+ assert!(parse_callback(+ "http://localhost:1455/auth/callback?code=authorization-code&state=wrong",+ &login.state+ )+ .is_err());+ }++ #[test]+ fn manual_callback_accepts_a_complete_redirect_url() {+ let login = begin(AccountProvider::Codex).unwrap();+ let raw = format!(+ "{}?code=authorization-code&state={}",+ login.redirect_uri, login.state+ );+ assert_eq!(+ parse_manual_callback(&raw, &login.state).unwrap(),+ "authorization-code"+ );+ }++ #[test]+ fn manual_callback_accepts_a_raw_code_and_optional_state_suffix() {+ assert_eq!(+ parse_manual_callback("authorization-code", "expected-state").unwrap(),+ "authorization-code"+ );+ assert_eq!(+ parse_manual_callback("authorization-code#expected-state", "expected-state").unwrap(),+ "authorization-code"+ );+ }++ #[test]+ fn manual_callback_rejects_empty_code_and_mismatched_state() {+ assert!(parse_manual_callback("", "expected-state").is_err());+ assert!(parse_manual_callback("authorization-code#wrong-state", "expected-state").is_err());+ assert!(parse_manual_callback(+ "http://localhost:1455/auth/callback?code=authorization-code&state=wrong-state",+ "expected-state"+ )+ .is_err());+ }++ #[test]+ fn token_exchange_binds_code_to_the_original_pkce_request() {+ let login = begin(AccountProvider::Claude).unwrap();+ let fields = token_request_body(&login, "authorization-code");++ assert_eq!(+ fields.get("grant_type"),+ Some(&"authorization_code".to_string())+ );+ assert_eq!(fields.get("code"), Some(&"authorization-code".to_string()));+ assert_eq!(fields.get("code_verifier"), Some(&login.verifier));+ assert_eq!(+ fields.get("redirect_uri"),+ Some(&login.redirect_uri.to_string())+ );+ assert!(fields.contains_key("client_id"));+ // Anthropic's token endpoint expects `state` echoed back on exchange;+ // OpenAI's rejects the extra field, so it must stay Claude-only.+ assert_eq!(fields.get("state"), Some(&login.state));++ let codex_login = begin(AccountProvider::Codex).unwrap();+ let codex_fields = token_request_body(&codex_login, "authorization-code");+ assert!(!codex_fields.contains_key("state"));+ }++ #[tokio::test]+ async fn token_exchange_stores_refreshable_credentials() {+ use std::io::{Read, Write};+ use std::net::TcpListener;++ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let endpoint = format!("http://{}/token", listener.local_addr().unwrap());+ std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut request = [0; 4096];+ let _ = stream.read(&mut request).unwrap();+ let body = r#"{"access_token":"access","refresh_token":"refresh","expires_in":3600,"token_type":"Bearer","scope":"profile offline_access"}"#;+ write!(+ stream,+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ body.len(),+ body+ )+ .unwrap();+ });++ let mut login = begin(AccountProvider::Codex).unwrap();+ login.token_endpoint = endpoint;+ let token = exchange(&login, "authorization-code").await.unwrap();++ assert_eq!(token.access_token, "access");+ assert_eq!(token.refresh_token.as_deref(), Some("refresh"));+ assert_eq!(token.token_type, "Bearer");+ assert_eq!(token.scopes, vec!["profile", "offline_access"]);+ assert!(token.expires_at.is_some());+ }++ /// Each provider's token endpoint expects a specific request encoding:+ /// Anthropic posts JSON, OpenAI posts form-encoded. Sending the wrong one+ /// gets the exchange rejected even when every other parameter is right.+ #[tokio::test]+ async fn exchange_posts_json_for_claude_and_form_for_codex() {+ use std::io::{Read, Write};+ use std::net::TcpListener;++ async fn run_case(provider: AccountProvider, expected: &str) {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let endpoint = format!("http://{}/token", listener.local_addr().unwrap());+ let body = r#"{"access_token":"access","expires_in":3600,"token_type":"Bearer"}"#;+ let expected = expected.to_string();+ let handle = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut request = Vec::new();+ let mut chunk = [0; 8192];+ // Read until the full body has arrived: a single read can+ // return headers only while the body is still in flight, and+ // answering early makes reqwest's send() fail mid-write.+ loop {+ match stream.read(&mut chunk).unwrap() {+ 0 => break,+ n => {+ request.extend_from_slice(&chunk[..n]);+ if let Some(header_end) =+ request.windows(4).position(|w| w == b"\r\n\r\n")+ {+ let head = String::from_utf8_lossy(&request[..header_end]);+ let content_length = head+ .lines()+ .find_map(|line| {+ line.to_ascii_lowercase()+ .strip_prefix("content-length:")+ .map(|v| v.trim().parse::<usize>().unwrap_or(0))+ })+ .unwrap_or(0);+ if request.len() >= header_end + 4 + content_length {+ break;+ }+ }+ }+ }+ }+ let request = String::from_utf8_lossy(&request);+ assert!(+ request.starts_with("POST /token HTTP/1.1\r\n"),+ "{request}"+ );+ let lower = request.to_ascii_lowercase();+ assert!(+ lower.contains(&expected.to_ascii_lowercase()),+ "missing {expected} in: {request}"+ );+ write!(+ stream,+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ body.len(),+ body+ )+ .unwrap();+ });++ let mut login = begin(provider).unwrap();+ login.token_endpoint = endpoint;+ exchange(&login, "authorization-code").await.unwrap();+ handle.join().unwrap();+ }++ run_case(AccountProvider::Claude, "Content-Type: application/json").await;+ run_case(+ AccountProvider::Codex,+ "Content-Type: application/x-www-form-urlencoded",+ )+ .await;+ }++ #[tokio::test]+ async fn loopback_listener_accepts_matching_callback() {+ use tokio::io::AsyncWriteExt;++ let login = begin(AccountProvider::Codex).unwrap();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let callback = format!(+ "GET /auth/callback?code=authorization-code&state={} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n",+ login.state+ );+ let client = tokio::spawn(async move {+ let mut stream = tokio::net::TcpStream::connect(address).await.unwrap();+ stream.write_all(callback.as_bytes()).await.unwrap();+ });++ assert_eq!(+ accept_callback(&listener.into(), &login).await.unwrap(),+ "authorization-code"+ );+ client.await.unwrap();+ }++ #[test]+ fn codex_login_persists_token_and_responses_config() {+ let _tmp = TempSecrets::new();+ with_temp_home(|_| {+ // Codex verifies the account via the JWT chatgpt_account_id claim+ // and fetches its real model roster from the ChatGPT backend's+ // `/codex/models` endpoint (not the rolling `/models` roster),+ // then configures the Responses API with that roster.+ let roster = r#"{"models":[{"slug":"gpt-5.5","display_name":"GPT-5.5"},{"slug":"gpt-5.4","display_name":"GPT-5.4"}]}"#;+ let (models_base_url, request) = account_models_server("200 OK", roster);++ assert_eq!(+ complete_account_for_test(models_base_url.clone()).unwrap(),+ AccountProvider::Codex+ );++ // Codex performs model discovery against the Codex roster route,+ // carrying the Codex client identifiers. The mock channel records+ // the raw HTTP request, so assert the path and headers directly.+ let request = request.try_recv().expect("Codex must hit /codex/models");+ assert!(+ request.contains("/codex/models"),+ "must target /codex/models, got: {request}"+ );+ assert!(+ request.contains("client_version=0.144.1"),+ "missing client_version in: {request}"+ );+ assert!(+ request.contains("chatgpt-account-id: account-321"),+ "missing chatgpt-account-id in: {request}"+ );+ assert!(+ request.to_ascii_lowercase()+ .contains("openai-beta: responses=experimental"),+ "missing OpenAI-Beta in: {request}"+ );++ let token = OAuthToken {+ access_token: codex_jwt("account-321"),+ refresh_token: Some("refresh".into()),+ expires_at: CredentialStore::load("openai")+ .unwrap()+ .and_then(|credential| {+ credential.as_oauth().and_then(|token| token.expires_at)+ }),+ token_type: "Bearer".into(),+ scopes: vec!["profile".into(), "offline_access".into()],+ };+ assert_eq!(+ CredentialStore::load("openai").unwrap(),+ Some(Credential::OAuthToken(token))+ );++ let cfg = load_global_config().unwrap().get("openai").unwrap().clone();+ assert!(cfg.api_key.is_none());+ assert!(cfg.api_keys.is_empty());+ assert_eq!(cfg.base_url.as_deref(), Some(models_base_url.as_str()));+ assert_eq!(+ cfg.models,+ vec!["gpt-5.4".to_string(), "gpt-5.5".to_string()]+ );+ assert_eq!(cfg.api_type.as_deref(), Some("openai-responses"));+ });+ }++ #[test]+ fn codex_login_falls_back_to_default_when_roster_unavailable() {+ let _tmp = TempSecrets::new();+ with_temp_home(|_| {+ // A failed/empty roster must not hard-fail an otherwise valid+ // login; the account persists with a single usable default model.+ let (models_base_url, _request) = account_models_server("200 OK", "{}");++ assert_eq!(+ complete_account_for_test(models_base_url.clone()).unwrap(),+ AccountProvider::Codex+ );++ let cfg = load_global_config().unwrap().get("openai").unwrap().clone();+ assert_eq!(cfg.models, vec!["gpt-5-chat-latest".to_string()]);+ assert_eq!(cfg.api_type.as_deref(), Some("openai-responses"));+ });+ }++ #[test]+ fn manual_codex_login_persists_token_and_responses_config() {+ let _tmp = TempSecrets::new();+ with_temp_home(|_| {+ let roster = r#"{"models":[{"slug":"gpt-5.5","display_name":"GPT-5.5"},{"slug":"gpt-5.4","display_name":"GPT-5.4"}]}"#;+ let (models_base_url, request) = account_models_server("200 OK", roster);++ assert_eq!(+ complete_account_manually_for_test(models_base_url.clone()).unwrap(),+ AccountProvider::Codex+ );++ // Codex performs model discovery against the Codex roster route.+ let request = request.try_recv().expect("Codex must hit /codex/models");+ assert!(+ request.contains("/codex/models"),+ "must target /codex/models, got: {request}"+ );+ assert!(+ request.contains("chatgpt-account-id: account-321"),+ "missing chatgpt-account-id in: {request}"+ );++ let token = OAuthToken {+ access_token: codex_jwt("account-321"),+ refresh_token: Some("refresh".into()),+ expires_at: CredentialStore::load("openai")+ .unwrap()+ .and_then(|credential| {+ credential.as_oauth().and_then(|token| token.expires_at)+ }),+ token_type: "Bearer".into(),+ scopes: vec!["profile".into(), "offline_access".into()],+ };+ assert_eq!(+ CredentialStore::load("openai").unwrap(),+ Some(Credential::OAuthToken(token))+ );++ let cfg = load_global_config().unwrap().get("openai").unwrap().clone();+ assert!(cfg.api_key.is_none());+ assert!(cfg.api_keys.is_empty());+ assert_eq!(cfg.base_url.as_deref(), Some(models_base_url.as_str()));+ assert_eq!(+ cfg.models,+ vec!["gpt-5.4".to_string(), "gpt-5.5".to_string()]+ );+ assert_eq!(cfg.api_type.as_deref(), Some("openai-responses"));+ });+ }+++ #[test]+ fn account_model_discovery_unauthorized_leaves_no_account_state() {+ let _tmp = TempSecrets::new();+ with_temp_home(|_| {+ let (models_base_url, _request) = account_models_server("401 Unauthorized", "{}");+ let error = complete_claude_account_for_test(models_base_url).unwrap_err();++ assert!(!error.contains("exchanged-account-token"), "{error}");+ assert!(!error.contains("authorization-code"), "{error}");+ assert!(CredentialStore::load(AccountProvider::Claude.credential_provider())+ .unwrap()+ .is_none());+ assert!(!load_global_config().unwrap().contains_key("anthropic"));+ });+ }++ #[test]+ fn account_model_discovery_unreadable_response_leaves_no_account_state() {+ let _tmp = TempSecrets::new();+ with_temp_home(|_| {+ let (models_base_url, _request) =+ account_models_server("200 OK", "not-json-without-secret");+ let error = complete_claude_account_for_test(models_base_url).unwrap_err();++ assert!(!error.contains("not-json-without-secret"), "{error}");+ assert!(!error.contains("exchanged-account-token"), "{error}");+ assert!(!error.contains("authorization-code"), "{error}");+ assert!(CredentialStore::load(AccountProvider::Claude.credential_provider())+ .unwrap()+ .is_none());+ assert!(!load_global_config().unwrap().contains_key("anthropic"));+ });+ }++ #[test]+ fn account_model_discovery_unavailable_server_leaves_no_account_state() {+ let _tmp = TempSecrets::new();+ with_temp_home(|_| {+ let error = complete_claude_account_for_test(unavailable_base_url()).unwrap_err();++ assert!(!error.contains("exchanged-account-token"), "{error}");+ assert!(!error.contains("authorization-code"), "{error}");+ assert!(CredentialStore::load(AccountProvider::Claude.credential_provider())+ .unwrap()+ .is_none());+ assert!(!load_global_config().unwrap().contains_key("anthropic"));+ });+ }++ #[test]+ fn exchanged_token_is_scoped_to_its_account_provider() {+ use crate::core::server::provider_secrets::SECRET_STORE_TEST_LOCK;++ let _guard = SECRET_STORE_TEST_LOCK+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ let directory = tempfile::tempdir().unwrap();+ let previous = std::env::var("JAN_DATA_FOLDER").ok();+ std::env::set_var("JAN_DATA_FOLDER", directory.path());+ crate::core::server::provider_secrets::force_file_secrets();++ let token = OAuthToken {+ access_token: "access".into(),+ refresh_token: Some("refresh".into()),+ expires_at: Some(1_800_000_000),+ token_type: "Bearer".into(),+ scopes: vec!["profile".into()],+ };+ store(AccountProvider::Claude, &token).unwrap();+ assert_eq!(+ crate::core::cli::auth::CredentialStore::load("anthropic").unwrap(),+ Some(crate::core::cli::auth::Credential::OAuthToken(token))+ );++ match previous {+ Some(value) => std::env::set_var("JAN_DATA_FOLDER", value),+ None => std::env::remove_var("JAN_DATA_FOLDER"),+ }+ }++ #[test]+ fn refresh_request_uses_the_refresh_grant_without_the_expired_access_token() {+ let token = OAuthToken {+ access_token: "expired-access".into(),+ refresh_token: Some("refresh-token".into()),+ expires_at: Some(1),+ token_type: "Bearer".into(),+ scopes: vec!["profile".into()],+ };++ let fields = refresh_request_body("client", &token).unwrap();++ assert_eq!(fields.get("grant_type"), Some(&"refresh_token".to_string()));+ assert_eq!(+ fields.get("refresh_token"),+ Some(&"refresh-token".to_string())+ );+ assert_eq!(fields.get("client_id"), Some(&"client".to_string()));+ assert!(!fields.contains_key("access_token"));+ }+++ #[test]+ fn claude_plan_message_heavy_access_names_premium() {+ let text = claude_plan_message(true, None);+ assert!(text.contains("heavy-model access"), "{text}");+ assert!(text.contains("enterprise/premium"), "{text}");+ }++ #[test]+ fn claude_plan_message_paid_tier_is_not_reported_as_free() {+ // A team/enterprise account whose heavy-model quota is momentarily+ // exhausted must be reported as a paid tier with a transient 429, never+ // as a "free personal plan".+ let text = claude_plan_message(false, Some("team"));+ assert!(text.contains("team account"), "{text}");+ assert!(text.contains("not a free plan"), "{text}");+ assert!(text.contains("429"), "{text}");+ assert!(!text.contains("free personal plan"), "{text}");+ let pro = claude_plan_message(false, Some("pro"));+ assert!(pro.contains("pro account"), "{pro}");+ // An unknown / missing tier falls back to the free-plan framing.+ let unknown = claude_plan_message(false, None);+ assert!(unknown.contains("free personal plan"), "{unknown}");+ }++ #[test]+ fn claude_plan_message_personal_plan_names_the_discriminator() {+ let text = claude_plan_message(false, None);+ assert!(text.contains("free personal plan"), "{text}");+ assert!(text.contains("claude-sonnet-5"), "{text}");+ assert!(text.contains("429"), "{text}");+ assert!(text.contains("claude-haiku-4-5"), "{text}");+ // The guidance must be honest that 429 is a quota boundary, not a+ // sign-in problem, so it never promises a sign-out unlocks heavy models.+ assert!(text.contains("quota"), "{text}");+ assert!(!text.contains("it will reuse Claude Code's existing login, which carries the workspace you approved there"), "{text}");+ }++ #[tokio::test(flavor = "current_thread")]+ async fn claude_plan_summary_falls_back_when_no_credential() {+ let _alias = alias_test_lock().await;+ set_claude_alias(false);+ let _temp = TempSecrets::new();+ // No Claude credential is stored in the fresh temp home, and the alias+ // is pinned off, so the function must produce the fallback line.+ let summary = claude_plan_summary("fallback-line").await;+ assert_eq!(summary, "fallback-line");+ }+ #[test]+ fn claude_code_secret_extracts_the_access_token() {+ let secret = r#"{"mcpOAuth":{},"claudeAiOauth":{"accessToken":"sk-ant-oat01-abc","refreshToken":"sk-ant-ort01-def","expiresAt":1786970599091,"scopes":["user:inference"]}}"#;+ assert_eq!(+ parse_claude_code_secret(secret).as_deref(),+ Some("sk-ant-oat01-abc")+ );+ // A missing/empty access token must not come through as Some("").+ assert_eq!(parse_claude_code_secret(r#"{"claudeAiOauth":{"accessToken":""}}"#), None);+ assert_eq!(+ parse_claude_code_secret(r#"{"claudeAiOauth":{"refreshToken":"sk-ant-ort01-x"}}"#),+ None+ );+ assert_eq!(parse_claude_code_secret("not json"), None);+ }+ #[test]+ fn claude_code_oauth_converts_expiry_to_seconds_and_carries_refresh() {+ // expiresAt is stored in epoch milliseconds; OAuthToken.expires_at is+ // in seconds. 1786970599091 ms -> 1786970599 s.+ let oauth = claude_code_oauth(+ r#"{"claudeAiOauth":{"accessToken":"sk-ant-oat01-abc","refreshToken":"sk-ant-ort01-def","expiresAt":1786970599091}}"#,+ )+ .expect("parseable");+ assert_eq!(oauth.access_token, "sk-ant-oat01-abc");+ assert_eq!(oauth.refresh_token.as_deref(), Some("sk-ant-ort01-def"));+ assert_eq!(oauth.expires_at, Some(1786970599));+ }++ #[test]+ fn rotate_claude_code_secret_preserves_unrelated_fields_and_rotates_ms() {+ let fresh = OAuthToken {+ access_token: "sk-ant-oat01-new".to_string(),+ refresh_token: Some("sk-ant-ort01-new".to_string()),+ expires_at: Some(1_800_000_000),+ token_type: "Bearer".to_string(),+ scopes: vec!["user:inference".to_string()],+ };+ let updated = rotate_claude_code_secret(+ r#"{"mcpOAuth":{"some":"kept"},"claudeAiOauth":{"accessToken":"old","refreshToken":"oldrt","expiresAt":1000},"claudeOauth":{"x":1}}"#,+ &fresh,+ )+ .expect("rotates");+ let doc: serde_json::Value = serde_json::from_str(&updated).unwrap();+ // Unrelated top-level blocks are preserved.+ assert_eq!(doc["mcpOAuth"]["some"], "kept");+ assert_eq!(doc["claudeOauth"]["x"], 1);+ // The oauth block is rotated; expiresAt written back in milliseconds.+ assert_eq!(doc["claudeAiOauth"]["accessToken"], "sk-ant-oat01-new");+ assert_eq!(doc["claudeAiOauth"]["refreshToken"], "sk-ant-ort01-new");+ assert_eq!(doc["claudeAiOauth"]["expiresAt"], 1_800_000_000_000_i64);+ }++ #[test]+ fn rotate_claude_code_secret_rejects_missing_oauth_block() {+ assert!(rotate_claude_code_secret(+ r#"{"mcpOAuth":{}}"#,+ &OAuthToken {+ access_token: "x".to_string(),+ refresh_token: None,+ expires_at: None,+ token_type: "Bearer".to_string(),+ scopes: Vec::new(),+ }+ )+ .is_err());+ }++ #[tokio::test(flavor = "current_thread")]+ async fn claude_alias_is_off_by_default_in_tests() {+ let _guard = alias_test_lock().await;+ set_claude_alias(false);+ assert!(!claude_alias_enabled());+ assert_eq!(claude_code_access_token().await, None);+ }++ #[test]+ fn claude_alias_engagement_latch_is_one_shot() {+ CLAUDE_ALIAS_ENGAGED.store(true, std::sync::atomic::Ordering::Relaxed);+ assert!(take_claude_alias_engaged());+ assert!(!take_claude_alias_engaged());+ }++ #[tokio::test(flavor = "current_thread")]+ async fn claude_alias_toggle_controls_the_lookup_gate() {+ let _guard = alias_test_lock().await;+ set_claude_alias(false);+ // Off: the keychain is never touched, so this is deterministic None+ // even on a machine with Claude Code / omp installed.+ assert_eq!(claude_code_access_token().await, None);+ set_claude_alias(true);+ assert!(claude_alias_enabled());+ // On: it may surface a real token (on a machine with omp signed in) or+ // None (sandboxed/CI); either is a valid gate result, so only assert+ // the gate flips without panicking.+ let _ = claude_code_access_token().await;+ set_claude_alias(false);+ assert!(!claude_alias_enabled());+ }++ #[test]+ fn refresh_endpoint_matches_the_endpoint_begin_authorized_against() {+ // A refresh grant against a different endpoint than the one the user+ // consented to at `begin()` can silently swap token scope (Claude's+ // console endpoint grants org:create_api_key only, not+ // user:inference) even though the request itself succeeds.+ for provider in [AccountProvider::Codex, AccountProvider::Claude] {+ let login = begin(provider).unwrap();+ let (client_id, token_endpoint) = refresh_endpoint(provider);+ assert_eq!(client_id, login.client_id);+ assert_eq!(token_endpoint, login.token_endpoint);+ }+ }+}diff --cc src-tauri/src/core/cli/auth/providers.rsindex 93245ae08,000000000..3a05b85d2mode 100644,000000..100644--- a/src-tauri/src/core/cli/auth/providers.rs+++ b/src-tauri/src/core/cli/auth/providers.rs@@@ -1,606 -1,0 +1,608 @@@+//! API-key validation and the login/logout transaction.+//!+//! Ordering is the security contract: sanitize, then validate over HTTP,+//! then persist the secret, then write only non-secret provider+//! configuration. A failure at any point leaves nothing behind - a rejected+//! key never creates a credential record or a config entry, and a failed+//! write rolls back the secret it already stored.++use std::time::Duration;++use crate::core::agent::global_config::{+ remove_provider, set_default_model_if_unset, set_provider, ProviderUpdate,+};++use super::{Credential, CredentialStore, LoginError, LoginResult, ProviderDefinition, Transport};++const VERIFY_TIMEOUT: Duration = Duration::from_secs(20);++/// Trim and reject a key before any I/O. 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())+}++/// Validate `raw_key` against the provider's model endpoint, then persist+/// the credential (secret store) and non-secret provider configuration.+/// Nothing is written when validation fails.+pub async fn login_with_api_key(+ definition: &ProviderDefinition,+ raw_key: &str,+) -> Result<LoginResult, LoginError> {+ let key = sanitize_key(raw_key).map_err(LoginError::InvalidKey)?;+ let models = discover_models(definition, &key, false).await?;+ persist(definition, &key, &models)+}++/// Remove the stored credential and the provider's non-secret+/// configuration entry. Missing entries are not an error.+pub fn logout(provider: &str) -> Result<(), LoginError> {+ CredentialStore::delete(provider).map_err(|e| {+ LoginError::Persist(format!("could not clear the stored credential: {e}"))+ })?;+ remove_provider(provider).map_err(|e| {+ LoginError::Persist(format!("could not clear the provider configuration: {e}"))+ })?;+ Ok(())+}++pub(crate) async fn discover_models(+ definition: &ProviderDefinition,+ credential: &str,+ oauth: bool,+) -> Result<Vec<String>, LoginError> {+ let client = reqwest::Client::builder()+ .timeout(VERIFY_TIMEOUT)+ .build()+ .map_err(|e| LoginError::Unavailable(format!("could not build an HTTP client: {e}")))?;+ let url = format!(+ "{}/models",+ definition.default_base_url.trim_end_matches('/')+ );+ let mut request = client.get(&url);+ request = match definition.transport {+ // An API-key credential identifies itself with `x-api-key`; an OAuth+ // access token must go as `Authorization: Bearer` (with the oauth beta+ // header), or Anthropic rejects the discovery with 401.+ Transport::Anthropic if oauth => request+ .header("Authorization", format!("Bearer {credential}"))+ .header("anthropic-beta", "oauth-2025-04-20")+ .header("anthropic-version", "2023-06-01")+ .header("Accept", "application/json"),+ Transport::Anthropic => request+ .header("x-api-key", credential)+ .header("anthropic-version", "2023-06-01")+ .header("Accept", "application/json"),+ Transport::OpenAi => request.header("Authorization", format!("Bearer {credential}")),+ };+ let response = request.send().await.map_err(|e| {+ LoginError::Unavailable(format!(+ "could not reach {}: {e}",+ definition.default_base_url+ ))+ })?;++ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ if !status.is_success() {+ return Err(failure_for(definition, status.as_u16(), &body));+ }+ let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {+ LoginError::Unavailable(format!(+ "{} returned a response we could not read: {e}",+ definition.name+ ))+ })?;+ Ok(parse_models(&parsed))+}++/// Discover the models available to a Codex (ChatGPT account) OAuth token.+///+/// A Codex account token is a ChatGPT account credential, not an OpenAI API+/// key, so `api.openai.com/v1/models` rejects it with 401. The models are+/// instead served by ChatGPT's own backend, which the Codex CLI (and pi)+/// targets at `chatgpt.com/backend-api/codex/models`. That endpoint is distinct+/// from `chatgpt.com/backend-api/models`: the latter returns the internal+/// rolling/user-scoped ChatGPT roster (e.g. `gpt-5.6-luna-wm`) that has no real+/// upstream session, whereas `/codex/models` returns the stable Codex slugs+/// (`gpt-5.5`, `gpt-5.4`, ...) that the Responses API actually serves. The+/// Codex client identifiers (`client_version`, `chatgpt-account-id`,+/// `OpenAI-Beta`, `originator`, `version`) are mirrored from the pi coding+/// agent so the backend returns the Codex roster instead of the ChatGPT one.+///+/// `base_url` is the persisted Codex provider base (the OpenAI API-key surface+/// `api.openai.com/v1`); it is rewritten to the ChatGPT backend origin, or used+/// verbatim in tests. Falls back to `/models` when `/codex/models` is not+/// served.+pub(crate) async fn discover_codex_models(+ credential: &str,+ account_id: Option<&str>,+ base_url: &str,+) -> Result<Vec<String>, LoginError> {+ // The persisted Codex default_base_url points at the OpenAI API-key+ // surface (`api.openai.com/v1`), which rejects an account token. Discovery+ // must target the ChatGPT backend instead; a test override (the mock+ // model server) is used verbatim.+ let backend = if base_url.trim_end_matches('/').ends_with("api.openai.com/v1") {+ "https://chatgpt.com/backend-api"+ } else {+ base_url+ };+ let client = reqwest::Client::builder()+ .timeout(VERIFY_TIMEOUT)+ .build()+ .map_err(|e| LoginError::Unavailable(format!("could not build an HTTP client: {e}")))?;++ // `/codex/models` is the Codex roster; `/models` is the plain ChatGPT+ // roster and is kept only as a fallback for backends that omit the Codex+ // route (matching pi's `DEFAULT_MODEL_LIST_PATHS`).+ let paths = ["/codex/models", "/models"];+ let mut last_error: Option<LoginError> = None;+ for path in paths {+ let url = format!("{}{}", backend.trim_end_matches('/'), path);+ let mut request = client+ .get(&url)+ .header("Authorization", format!("Bearer {credential}"))+ .header("Accept", "application/json");+ // Only the Codex route is marked with the Codex client identifiers.+ if path == "/codex/models" {+ request = request+ .query(&[("client_version", "0.144.1")])+ .header("OpenAI-Beta", "responses=experimental")+ .header("originator", "jan")+ .header("version", "0.144.1");+ if let Some(account_id) = account_id {+ request = request.header("chatgpt-account-id", account_id);+ }+ }+ match request.send().await {+ Ok(response) => {+ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ if !status.is_success() {+ last_error = Some(match status.as_u16() {+ 401 | 403 => LoginError::Unauthorized,+ 429 => LoginError::RateLimited,+ 500..=599 => LoginError::Unavailable(format!(+ "the ChatGPT backend is unavailable right now (HTTP {status})."+ )),+ _ => LoginError::Unavailable(format!(+ "the ChatGPT backend returned HTTP {status}."+ )),+ });+ continue;+ }+ let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {+ LoginError::Unavailable(format!(+ "the ChatGPT backend returned a response we could not read: {e}"+ ))+ })?;+ return Ok(parse_codex_models(&parsed));+ }+ Err(e) => {+ last_error = Some(LoginError::Unavailable(format!(+ "could not reach the ChatGPT backend: {e}"+ )));+ continue;+ }+ }+ }+ Err(last_error.unwrap_or(LoginError::Unavailable(+ "the ChatGPT backend returned no usable model roster".to_string(),+ )))+}++/// Stable Codex model slugs from a `/codex/models` payload, sorted, deduped,+/// and with hidden/rolling entries filtered out. Accepts both the ChatGPT+/// backend shape (`{"models":[{slug,display_name,visibility}]}`) and the+/// OpenAI shape (`{"data":[{"id"}]}`) for backends that serve either.+fn parse_codex_models(value: &serde_json::Value) -> Vec<String> {+ let entries = value+ .get("models")+ .and_then(|m| m.as_array())+ .or_else(|| value.get("data").and_then(|d| d.as_array()))+ .into_iter()+ .flatten();+ let mut ids: Vec<String> = entries+ .filter_map(|entry| {+ // A `visibility` of `hide` shadows internal/rolling roster entries.+ let visibility = entry+ .get("visibility")+ .and_then(|v| v.as_str())+ .map(str::to_ascii_lowercase)+ .unwrap_or_default();+ if visibility == "hide" || visibility == "hidden" {+ return None;+ }+ // Stable slug/id, or a bare string slug for minimal gateways.+ let id = entry+ .get("slug")+ .and_then(|s| s.as_str())+ .or_else(|| entry.get("id").and_then(|s| s.as_str()))+ .or_else(|| entry.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(String::from);+ id+ })+ .collect();+ // Rolling ChatGPT codenames carry a user-scoped suffix (e.g.+ // `gpt-5.6-luna-wm`); they are not stable Codex models, so drop them.+ ids.retain(|id| !id.ends_with("-wm"));+ ids.sort();+ ids.dedup();+ ids+}++/// Human-readable reason a verification request was rejected. Never includes+/// the key.+fn failure_for(definition: &ProviderDefinition, status: u16, _body: &str) -> LoginError {+ match status {+ 401 | 403 => LoginError::Unauthorized,+ 429 => LoginError::RateLimited,+ 500..=599 => LoginError::Unavailable(format!(+ "{} is unavailable right now (HTTP {status}).",+ definition.name+ )),+ _ => LoginError::Unavailable(format!("{} returned HTTP {status}.", definition.name)),+ }+}++/// 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. Anthropic's `/models` uses the same `data` shape.+pub(crate) 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+}++/// Write the verified key + model list. Secret first, then non-secret+/// configuration; a failed config write rolls back the secret.+fn persist(+ definition: &ProviderDefinition,+ key: &str,+ models: &[String],+) -> Result<LoginResult, LoginError> {+ CredentialStore::store(definition.id, &Credential::ApiKey(key.to_string()))+ .map_err(|e| LoginError::Persist(format!("could not save the credential securely: {e}")))?;++ let config_path = match set_provider(+ definition.id,+ ProviderUpdate {+ // Keys never enter provider configuration; the credential store is+ // the only home for secrets.+ api_key: None,+ // Migrate away any legacy plaintext key the entry still holds.+ clear_api_key: true,+ base_url: Some(definition.default_base_url.clone()),+ models: Some(models.to_vec()),+ api_type: match definition.transport {+ Transport::Anthropic => Some("anthropic".to_string()),+ Transport::OpenAi => None,+ },++ ..Default::default()+ },+ ) {+ Ok(path) => path,+ Err(e) => {+ let _ = CredentialStore::delete(definition.id);+ return Err(LoginError::Persist(format!(+ "could not save the provider configuration: {e}"+ )));+ }+ };++ // Adopt the first discovered model as the default only when the user has+ // none; an explicit choice is never overwritten. A failure here is not+ // fatal: the sign-in itself is complete and the config is valid.+ let default_model = match models.first() {+ Some(first) => match set_default_model_if_unset(first) {+ Ok(true) => Some(first.clone()),+ _ => None,+ },+ None => None,+ };++ Ok(LoginResult {+ provider: definition.id.to_string(),+ models: models.to_vec(),+ config_path,+ default_model,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::core::agent::global_config::{load_global_config, with_temp_home};+ use crate::core::cli::auth::provider_by_id;+ use crate::core::server::provider_secrets::SECRET_STORE_TEST_LOCK;+ use serde_json::json;+ use std::io::{Read, Write};+ use std::net::TcpListener;+ use std::sync::MutexGuard;++ struct TempSecrets {+ _guard: MutexGuard<'static, ()>,+ prev_data_folder: Option<String>,+ _dir: tempfile::TempDir,+ }++ impl TempSecrets {+ fn new() -> Self {+ let guard = SECRET_STORE_TEST_LOCK+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ let dir = tempfile::tempdir().unwrap();+ let prev_data_folder = std::env::var("JAN_DATA_FOLDER").ok();+ std::env::set_var("JAN_DATA_FOLDER", dir.path());+ crate::core::server::provider_secrets::force_file_secrets();+ Self {+ _guard: guard,+ prev_data_folder,+ _dir: dir,+ }+ }+ }++ impl Drop for TempSecrets {+ fn drop(&mut self) {+ match &self.prev_data_folder {+ Some(v) => std::env::set_var("JAN_DATA_FOLDER", v),+ None => std::env::remove_var("JAN_DATA_FOLDER"),+ }+ }+ }++ /// A one-shot HTTP server answering with `status` and `body`, returning its+ /// base URL. The thread detaches; it serves exactly one request.+ fn mock_server(status_line: &'static str, body: &'static str) -> String {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ std::thread::spawn(move || {+ for stream in listener.incoming().take(1) {+ let Ok(mut stream) = stream else { continue };+ let _ = Read::read(&mut stream, &mut [0u8; 4096]);+ let response = format!(+ "HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ body.len(),+ body+ );+ let _ = Write::write_all(&mut stream, response.as_bytes());+ }+ });+ format!("http://{addr}/v1")+ }++ fn deepseek_at(endpoint: String) -> ProviderDefinition {+ let mut def = provider_by_id("deepseek").unwrap();+ def.default_base_url = endpoint;+ def+ }++ fn login_for_test(+ definition: &ProviderDefinition,+ key: &str,+ ) -> Result<LoginResult, LoginError> {+ let definition = definition.clone();+ let key = key.to_string();+ std::thread::spawn(move || {+ tokio::runtime::Runtime::new()+ .unwrap()+ .block_on(login_with_api_key(&definition, &key))+ })+ .join()+ .expect("verification thread must not panic")+ }++ #[test]+ fn sanitize_trims_and_rejects_unusable_input() {+ assert_eq!(sanitize_key(" sk-abc\n").unwrap(), "sk-abc");+ assert!(sanitize_key(" ").is_err());+ assert!(sanitize_key("").is_err());+ assert!(sanitize_key("sk-abc def").is_err());+ assert!(sanitize_key("sk-abc\ndef").is_err());+ }++ #[test]+ fn parses_openai_and_bare_model_lists_sorted_and_deduped() {+ let body = json!({"data": [{"id": "deepseek-chat"}, {"id": "b"}, {"id": "b"}]});+ assert_eq!(+ parse_models(&body),+ vec!["b".to_string(), "deepseek-chat".to_string()]+ );+ assert_eq!(+ parse_models(&json!(["x", {"id": "y"}])),+ vec!["x".to_string(), "y".to_string()]+ );+ assert!(parse_models(&json!({"data": []})).is_empty());+ assert!(parse_models(&json!({"unexpected": 1})).is_empty());+ }+ #[test]+ fn codex_models_filters_rolling_codenames_and_hidden_entries() {+ // Stable Codex slugs are kept; rolling user-scoped ChatGPT codenames+ // (the `-wm` suffix that has no upstream session) and `visibility: hide`+ // entries are dropped, exactly so the picker never offers a model that+ // later fails "No upstream session found for model ...".+ let body = json!({+ "models": [+ {"slug": "gpt-5.5", "display_name": "GPT-5.5"},+ {"slug": "gpt-5.6-luna-wm", "display_name": "GPT-5.6 Luna"},+ {"slug": "gpt-5.4", "display_name": "GPT-5.4", "visibility": "hide"},+ {"slug": "gpt-5.3", "display_name": "GPT-5.3", "visibility": "hidden"}+ ]+ });+ assert_eq!(+ parse_codex_models(&body),+ vec!["gpt-5.5".to_string()]+ );+ // Accepts the OpenAI `data` shape for backends that serve either.+ assert_eq!(+ parse_codex_models(&json!({"data": [{"id": "gpt-5.4"}, {"id": "gpt-5.5"}]})),+ vec!["gpt-5.4".to_string(), "gpt-5.5".to_string()]+ );+ assert!(parse_codex_models(&json!({"models": []})).is_empty());+ }++ #[test]+ fn provider_error_never_echoes_the_submitted_key() {+ let definition = provider_by_id("deepseek").unwrap();+ let error = failure_for(+ &definition,+ 400,+ r#"{"error":{"message":"invalid key sk-secret"}}"#,+ );+ let LoginError::Unavailable(message) = error else {+ panic!("HTTP 400 must be an unavailable error");+ };+ assert!(!message.contains("sk-secret"), "{message}");+ }++ #[test]+ fn rejected_key_never_writes_a_secret_or_provider_config() {+ let _tmp = TempSecrets::new();+ with_temp_home(|_| {+ let endpoint = mock_server("401 Unauthorized", "{}");+ let result = login_for_test(&deepseek_at(endpoint), "bad");+ assert!(matches!(result, Err(LoginError::Unauthorized)));+ assert!(CredentialStore::load("deepseek").unwrap().is_none());+ assert!(!load_global_config().unwrap().contains_key("deepseek"));+ });+ }++ #[tokio::test]+ async fn rate_limited_key_maps_to_rate_limited_error() {+ let _tmp = TempSecrets::new();+ let endpoint = mock_server("429 Too Many Requests", "{}");+ let result = login_with_api_key(&deepseek_at(endpoint), "sk-busy").await;+ assert!(matches!(result, Err(LoginError::RateLimited)));+ }++ #[tokio::test]+ async fn unreachable_provider_maps_to_unavailable() {+ let _tmp = TempSecrets::new();+ // Nothing listens on this port: connection refused.+ let def = deepseek_at("http://127.0.0.1:9/v1".to_string());+ let result = login_with_api_key(&def, "sk-x").await;+ assert!(matches!(result, Err(LoginError::Unavailable(_))));+ }++ #[tokio::test]+ async fn valid_key_persists_secret_and_non_secret_config() {+ let _tmp = TempSecrets::new();+ with_temp_home(|_| {+ let body = r#"{"data":[{"id":"deepseek-chat"},{"id":"deepseek-reasoner"}]}"#;+ let endpoint = mock_server("200 OK", body);+ let result = login_for_test(&deepseek_at(endpoint.clone()), "sk-ok").unwrap();+ assert_eq!(result.provider, "deepseek");+ assert_eq!(+ result.models,+ vec!["deepseek-chat".to_string(), "deepseek-reasoner".to_string()]+ );+ assert_eq!(result.default_model.as_deref(), Some("deepseek-chat"));++ // The credential lives only in the secret store.+ assert_eq!(+ CredentialStore::load("deepseek").unwrap(),+ Some(Credential::ApiKey("sk-ok".into()))+ );+ // The config entry carries no secret, only id/endpoint/models.+ let cfg = load_global_config()+ .unwrap()+ .get("deepseek")+ .unwrap()+ .clone();+ assert!(cfg.api_key.is_none());+ assert!(cfg.api_keys.is_empty());+ assert_eq!(cfg.base_url.as_deref(), Some(endpoint.as_str()));+ assert_eq!(+ cfg.models,+ vec!["deepseek-chat".to_string(), "deepseek-reasoner".to_string()]+ );+ });+ }++ #[tokio::test]+ async fn logout_removes_credential_and_config() {+ let _tmp = TempSecrets::new();+ with_temp_home(|_| {+ let body = r#"{"data":[{"id":"deepseek-chat"}]}"#;+ let endpoint = mock_server("200 OK", body);+ login_for_test(&deepseek_at(endpoint), "sk-ok").unwrap();+ assert!(CredentialStore::load("deepseek").unwrap().is_some());+ assert!(load_global_config().unwrap().contains_key("deepseek"));++ logout("deepseek").unwrap();+ assert!(CredentialStore::load("deepseek").unwrap().is_none());+ assert!(!load_global_config().unwrap().contains_key("deepseek"));+ // Logging out again is a no-op, not an error.+ logout("deepseek").unwrap();+ });+ }++ #[tokio::test]+ async fn legacy_plaintext_key_is_cleared_by_login() {+ let _tmp = TempSecrets::new();+ with_temp_home(|_| {+ // Simulate a pre-existing legacy entry with a plaintext key.+ set_provider(+ "deepseek",+ ProviderUpdate {+ api_key: Some("sk-legacy".into()),+ clear_api_key: false,+ base_url: Some("https://api.deepseek.com/v1".into()),+ models: Some(vec!["deepseek-chat".into()]),+ api_type: None,++ ..Default::default()+ },+ )+ .unwrap();++ let body = r#"{"data":[{"id":"deepseek-chat"}]}"#;+ let endpoint = mock_server("200 OK", body);+ login_for_test(&deepseek_at(endpoint), "sk-new").unwrap();++ let cfg = load_global_config()+ .unwrap()+ .get("deepseek")+ .unwrap()+ .clone();+ assert!(+ cfg.api_key.is_none(),+ "legacy plaintext key must be migrated away"+ );+ assert_eq!(+ CredentialStore::load("deepseek").unwrap(),+ Some(Credential::ApiKey("sk-new".into()))+ );+ });+ }+}diff --cc src-tauri/src/core/cli/mod.rsindex 02f9fe950,1950895a3..303cf17cd--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@@ -2,9 -2,9 +2,10 @@@//!//! This module is only compiled when the `cli` feature is enabled.+pub mod auth;pub mod brand;pub mod browser;+ pub mod device_auth;pub mod journal;pub mod login;pub mod mcp;diff --cc src-tauri/src/core/cli/providers.rsindex b89a5cd76,4c688dee8..05e14aa99--- a/src-tauri/src/core/cli/providers.rs+++ b/src-tauri/src/core/cli/providers.rs@@@ -313,9 -320,9 +340,10 @@@ pub async fn fetch_missing_modelscrate::core::agent::global_config::ProviderUpdate {api_key: None,base_url: None,+ clear_api_key: false,models: Some(models),api_type: None,+ ..Default::default()},)?;populated = true;@@@ -400,36 -406,19 +428,42 @@@ pub fn load_provider_configsOk(configs)}+/// Fill a login-created provider's key chain from the auth credential store+/// when neither persisted configuration nor CLI/env overrides supplied a key.+/// The login flow writes only non-secret metadata to config, so without this+/// seeding a signed-in provider would resolve keyless at runtime and every+/// request would 401. OAuth credentials are resolved by the transport layer+/// and deliberately not seeded here.+fn seed_from_credential_store(configs: &mut HashMap<String, ProviderConfig>) {+ use crate::core::cli::auth::CredentialStore;+ for (name, cfg) in configs.iter_mut() {+ if !cfg.bearer_key_chain().is_empty() {+ continue;+ }+ let Ok(Some(credential)) = CredentialStore::load(name) else {+ continue;+ };+ let Some(key) = credential.as_api_key() else {+ continue;+ };+ cfg.api_key = Some(key.to_string());+ cfg.api_keys = vec![key.to_string()];+ }+}+/// Layer in providers from Desktop's `settings.json` that Global doesn't/// already define. Read-only inherit: never overwrites a Global entry, never- /// writes back to `settings.json`. Secrets are seeded from the OS keyring /- /// encrypted fallback file (#8388) since they no longer live in the JSON blob.+ /// writes back to `settings.json`.+ ///+ /// Their secrets live in the OS keyring (#8388) and are deliberately *not*+ /// read here: this runs on startup, on every `/model` open and on every status+ /// call, and reading N keychain items costs N macOS authorization prompts for+ /// providers a run will never select. Keys are fetched by+ /// [`hydrate_provider_keys`] for the one provider that is actually used;+ /// [`has_stored_key`] answers presence without touching the secret.fn inherit_desktop_providers(configs: &mut HashMap<String, ProviderConfig>) {let path = resolve_jan_data_folder().join("settings.json");- let mut desktop_configs = match std::fs::read_to_string(&path) {+ let desktop_configs = match std::fs::read_to_string(&path) {Ok(raw) => parse_provider_store(&raw),Err(_) => return,};@@@ -965,9 -1074,9 +1119,10 @@@ mod testscrate::core::agent::global_config::ProviderUpdate {api_key: Some("k".into()),base_url: Some(format!("http://{addr}/v1")),+ clear_api_key: false,models: Some(vec![]),api_type: None,+ ..Default::default()},).unwrap();@@@ -993,9 -1102,9 +1148,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("k".into()),base_url: Some("http://127.0.0.1:9/v1".into()), // would refuse+ clear_api_key: false,models: Some(vec!["my-model".into()]),api_type: None,+ ..Default::default()},).unwrap();@@@ -1022,9 -1131,9 +1178,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: None,base_url: Some(format!("http://{addr}/v1")),+ clear_api_key: false,models: Some(vec![]),api_type: None,+ ..Default::default()},).unwrap();@@@ -1072,9 -1181,9 +1229,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("k".into()),base_url: Some(format!("http://{addr}/v1")),+ clear_api_key: false,models: Some(vec![]),api_type: None,+ ..Default::default()},).unwrap();@@@ -1100,9 -1209,9 +1258,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("k".into()),base_url: Some("http://127.0.0.1:9/v1".into()), // refuses instantly+ clear_api_key: false,models: Some(vec![]),api_type: None,+ ..Default::default()},).unwrap();@@@ -1124,160 -1233,4 +1283,163 @@@assert!(!again, "already-probed provider is not re-fetched");});}++ /// Redirects the secret store (data folder + forced file fallback) for the+ /// duration of `f`. `JAN_DATA_FOLDER` is process-wide, so tests touching it+ /// must not run concurrently.+ fn with_temp_secrets<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 = std::env::var("JAN_DATA_FOLDER").ok();+ std::env::set_var("JAN_DATA_FOLDER", dir.path());+ crate::core::server::provider_secrets::force_file_secrets();+ let result = f();+ match &prev {+ Some(v) => std::env::set_var("JAN_DATA_FOLDER", v),+ None => std::env::remove_var("JAN_DATA_FOLDER"),+ }+ result+ }++ #[test]+ fn provider_is_signed_in_when_api_key_credential_exists() {+ use crate::core::agent::global_config::with_temp_home;+ use crate::core::cli::auth::{Credential, CredentialStore};++ with_temp_secrets(|| {+ with_temp_home(|_| {+ CredentialStore::store("deepseek", &Credential::ApiKey("sk-live".into())).unwrap();++ assert!(provider_is_signed_in(None, "deepseek"));+ });+ });+ }++ #[test]+ fn provider_is_signed_in_when_oauth_credential_exists() {+ use crate::core::agent::global_config::with_temp_home;+ use crate::core::cli::auth::{Credential, CredentialStore, OAuthToken};++ with_temp_secrets(|| {+ with_temp_home(|_| {+ CredentialStore::store(+ "anthropic",+ &Credential::OAuthToken(OAuthToken {+ access_token: "access".into(),+ refresh_token: Some("refresh".into()),+ expires_at: Some(1_800_000_000),+ token_type: "Bearer".into(),+ scopes: vec!["model.read".into()],+ }),+ )+ .unwrap();++ assert!(provider_is_signed_in(None, "anthropic"));+ });+ });+ }++ #[test]+ fn provider_is_not_signed_in_without_credential_or_usable_config() {+ use crate::core::agent::global_config::with_temp_home;++ with_temp_secrets(|| {+ with_temp_home(|_| {+ assert!(!provider_is_signed_in(None, "deepseek"));+ });+ });+ }++ #[test]+ fn provider_is_signed_in_when_resolved_config_is_usable() {+ use crate::core::agent::global_config::{set_provider, with_temp_home, ProviderUpdate};++ with_temp_secrets(|| {+ with_temp_home(|_| {+ set_provider(+ "jan",+ ProviderUpdate {+ api_key: None,+ clear_api_key: true,+ base_url: Some("http://localhost:1337/v1".into()),+ models: Some(vec!["jan-local".into()]),+ api_type: None,++ ..Default::default()+ },+ )+ .unwrap();++ assert!(provider_is_signed_in(None, "jan"));+ });+ });+ }++ #[test]+ fn runtime_uses_secret_store_when_non_secret_config_has_no_key() {+ use crate::core::agent::global_config::{set_provider, with_temp_home, ProviderUpdate};+ use crate::core::cli::auth::{Credential, CredentialStore};++ with_temp_secrets(|| {+ with_temp_home(|_| {+ // The login flow writes only non-secret metadata to config.+ set_provider(+ "deepseek",+ ProviderUpdate {+ api_key: None,+ clear_api_key: true,+ base_url: Some("https://mock/v1".into()),+ models: Some(vec!["deepseek-chat".into()]),+ api_type: None,++ ..Default::default()+ },+ )+ .unwrap();+ CredentialStore::store("deepseek", &Credential::ApiKey("sk-live".into())).unwrap();++ let configs = load_provider_configs(None, &ProviderOverrides::default()).unwrap();+ assert_eq!(+ configs.get("deepseek").unwrap().bearer_key_chain(),+ vec!["sk-live".to_string()]+ );+ });+ });+ }++ #[test]+ fn secret_store_never_overrides_an_explicit_override_key() {+ use crate::core::agent::global_config::{set_provider, with_temp_home, ProviderUpdate};+ use crate::core::cli::auth::{Credential, CredentialStore};++ with_temp_secrets(|| {+ with_temp_home(|_| {+ set_provider(+ "deepseek",+ ProviderUpdate {+ api_key: None,+ clear_api_key: true,+ base_url: Some("https://mock/v1".into()),+ models: Some(vec!["deepseek-chat".into()]),+ api_type: None,++ ..Default::default()+ },+ )+ .unwrap();+ CredentialStore::store("deepseek", &Credential::ApiKey("sk-stored".into())).unwrap();++ // A CLI/env override is the most explicit, most ephemeral signal+ // and must win over the persisted secret.+ let overrides = ProviderOverrides {+ provider: Some("deepseek".into()),+ api_key: Some("sk-flag".into()),+ };+ let configs = load_provider_configs(None, &overrides).unwrap();+ assert_eq!(+ configs.get("deepseek").unwrap().bearer_key_chain(),+ vec!["sk-flag".to_string()]+ );+ });+ });+ }}diff --cc src-tauri/src/core/cli/tokamak.rsindex 5a19dc691,c9b03479e..7eb304fac--- a/src-tauri/src/core/cli/tokamak.rs+++ b/src-tauri/src/core/cli/tokamak.rs@@@ -84,10 -125,14 +118,15 @@@ fn persist(api_key: &str, models: Vec<SPROVIDER,ProviderUpdate {api_key: Some(api_key.to_string()),+ clear_api_key: false,- base_url: Some(BASE_URL.to_string()),+ base_url: Some(base_url()),models: Some(models.clone()),api_type: None,+ // A pasted key carries no metadata, and any left over from a+ // previous browser login belongs to a key this one replaces.+ key_id: Some(None),+ key_expires_at: Some(None),+ account: Some(None),},)?;let default_model = match models.first() {@@@ -98,6 -143,98 +137,99 @@@models,config_path,default_model,+ // The paste flow verifies a key against `/v1/models`; it never learns+ // who the key belongs to.+ account: None,+ })+ }++ /// Run the device (browser-approval) login to completion and persist the+ /// minted key. `pending` comes from [`super::device_auth::begin`].+ ///+ /// The claim reply carries the key and its metadata but no model list, so the+ /// models are resolved the same way the paste flow resolves them -- a+ /// `GET /v1/models` with the fresh key. That doubles as a check that the minted+ /// key actually works before anything is written.+ pub(crate) async fn device_login(+ pending: super::device_auth::PendingAuth,+ ) -> Result<Login, String> {+ let minted = pending.claim().await?;+ let models = verify_key(&minted.api_key).await?;+ persist_minted(&minted, models)+ }++ /// Persist a verified key plus the server-assigned key metadata (`key_id`/+ /// `key_expires_at`, so `auth status` can show the expiry and logout can revoke+ /// this exact key), adopting the first model as `default_model` when the user+ /// has none.+ fn persist_minted(+ minted: &super::device_auth::Minted,+ models: Vec<String>,+ ) -> Result<Login, String> {+ let config_path = set_provider(+ PROVIDER,+ ProviderUpdate {+ api_key: Some(minted.api_key.clone()),++ clear_api_key: false,+ base_url: Some(base_url()),+ models: Some(models.clone()),+ api_type: None,+ // Written even when the server sent nothing, so a re-login cannot+ // leave the previous key's id behind to be revoked by mistake.+ key_id: Some(minted.key_id.clone()),+ key_expires_at: Some(minted.key_expires_at),+ account: Some(minted.account.clone()),+ },+ )?;+ 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,+ account: minted.account.clone(),+ })+ }++ /// What a sign-out actually did, so the caller does not claim a revocation that+ /// never happened.+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]+ pub enum Logout {+ /// Nothing was configured.+ NothingToDo,+ /// The local entry is gone and the server confirmed the key is revoked.+ ClearedAndRevoked,+ /// The local entry is gone, but the key was not revoked upstream -- no+ /// `key_id` was recorded (a legacy paste login) or the call did not land.+ ClearedOnly,+ }++ /// Sign out: revoke the stored key server-side (best-effort) and clear the+ /// `tokamak` provider entry. Local sign-out always happens even if the+ /// revocation call fails, so a network problem cannot strand the user signed in+ /// locally -- but the result says which of the two happened.+ pub async fn logout() -> Result<Logout, String> {+ use crate::core::agent::global_config::{provider_key_meta, remove_provider};++ let meta = provider_key_meta(PROVIDER).unwrap_or_default();+ let key = stored_api_key();+ if meta.key_id.is_none() && key.is_none() {+ return Ok(Logout::NothingToDo);+ }++ // Revoking needs both the server-side id and the key itself to authenticate+ // the call; a legacy paste login recorded no id, so it can only clear local.+ let revoked = match (&meta.key_id, &key) {+ (Some(key_id), Some(key)) => revoke_key(key_id, key).await,+ _ => false,+ };++ remove_provider(PROVIDER)?;+ Ok(match revoked {+ true => Logout::ClearedAndRevoked,+ false => Logout::ClearedOnly,})}diff --cc src-tauri/src/core/cli/tui.rsindex d1c9efcc6,2a3cac134..5a17e00ba--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@@ -45,12 -44,10 +45,12 @@@ use super::branduse super::journal::{self, DisplayEntry, ReasoningSeg};use super::mcp::McpServerEntry;use super::{sort_threads_recent, AgentSession, ResumeTarget, SessionLimits};--use serde_json::Value;use crate::core::agent::events::{describe_tool_call, StreamEvent, Usage};use crate::core::agent::git;-use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs, PermissionRegistry};+use crate::core::agent::r#loop::{+ run_orchestration_streamed, OrchestrationArgs, PermissionRegistry,+};++use serde_json::Value;use tauri_plugin_agent_tools::tools::gate::PermissionDecision;use tauri_plugin_agent_tools::workspace;@@@ -120,6 -116,21 +120,20 @@@ fn startup_modes(mouse: bool) -> Strin}modes}++ /// Whether to wrap each repaint in synchronized output (`\x1b[?2026h/l`).+ /// kitty honors DEC 2026 but can drop the resize-triggered full clear + repaint+ /// while a synchronized frame is held, leaving a persistent black screen on+ /// resize (konsole ignores 2026, so it never shows this). Skipping the wrapper+ /// under kitty trades tearing for a reliable resize; every other terminal that+ /// supports 2026 keeps the anti-tearing frame.+ fn sync_output_for(kind: super::terminal_setup::Kind) -> bool {+ !matches!(kind, super::terminal_setup::Kind::Kitty)+ }++ fn use_synchronized_output() -> bool {+ sync_output_for(super::terminal_setup::identify(|k| std::env::var(k).ok()))+ }-/// How long the dock advertises a finished copy.const COPY_NOTICE: Duration = Duration::from_millis(1500);/// Terminals cap the OSC 52 payload they will accept; past this the sequence is@@@ -456,11 -463,11 +470,11 @@@ impl PickerPickerKind::RewindScope => " ↑/↓ select Enter restore Esc cancel",PickerKind::ViewConfig => " set via: jan config set --provider <id> ... Esc close",PickerKind::AgentSettings => " ↑/↓ select Enter edit x unset Esc close",- PickerKind::ProviderSettings => " ↑/↓ select Enter edit a add dd delete x logout Esc close",- PickerKind::ProviderSettings => " ↑/↓ select Enter edit a add dd delete Esc close",-- PickerKind::Todo => " ↑/↓ select d done x abandon r remove Esc close",-- PickerKind::PluginSelect => {-- " ↑/↓ select Space toggle Enter install Esc cancel"++ PickerKind::ProviderSettings => {++ " ↑/↓ select Enter edit a add dd delete x logout Esc close"}++ PickerKind::Todo => " ↑/↓ select d done x abandon r remove Esc close",++ PickerKind::PluginSelect => " ↑/↓ select Space toggle Enter install Esc cancel",PickerKind::McpServer => " ↑/↓ select Enter run Esc back",}}@@@ -670,12 -543,69 +684,70 @@@ enum McpJobDone},}- /// `/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.+ /// A browser launch held back for confirmation, for flows with no dock of their+ /// own to ask in (currently `/mcp` authorization).+ struct BrowserConfirm {+ url: String,+ /// What the page is for, e.g. `authorize 'github'`.+ purpose: String,+ }++ /// Which sign-in the `/login` dock is running. The browser flow is the default;+ /// the paste field is what a server predating it (or a failure) falls back to.+ enum LoginStage {+ /// Creating the session -- one round trip before there is a code to show.+ Connecting,+ /// Waiting on the browser. The code is displayed so the user can check it+ /// against the approve page before clicking Approve.+ ///+ /// While `confirm_open` is set the user has not yet said whether to launch a+ /// browser here. The poll runs regardless, so approving from a phone still+ /// completes the sign-in without ever answering.+ Approving {+ user_code: String,+ authorize_url: String,+ confirm_open: bool,+ },+ /// Legacy paste-a-key entry. `confirm_open` gates sending the user to the+ /// API-keys page; the field only accepts a key once that is answered.+ Paste { confirm_open: bool },+ }++ impl LoginStage {+ /// The page this stage would send the user to, while that is still unasked.+ fn unconfirmed_url(&self) -> Option<&str> {+ match self {+ Self::Approving {+ authorize_url,+ confirm_open: true,+ ..+ } => Some(authorize_url),+ Self::Paste { confirm_open: true } => Some(super::tokamak::API_KEYS_URL),+ _ => None,+ }+ }++ /// Mark the browser question answered, whichever stage asked it.+ fn mark_confirmed(&mut self) {+ match self {+ Self::Approving { confirm_open, .. } | Self::Paste { confirm_open } => {+ *confirm_open = false+ }+ Self::Connecting => {}+ }+ }+ }++ /// `/login`: a docked prompt that runs the browser-approval sign-in and, when+ /// that is unavailable, collects a Tokamak API key without echoing it. The+ /// network work runs off the render loop (see `login_*_task` in `chat_loop`), so+ /// `verifying` marks the window where the paste field is read-only.+ ///+ /// The dock stays open for the whole flow, which is also what makes Esc a+ /// reliable cancel: `chat_loop` drops every in-flight sign-in task the moment+ /// `app.login` goes to `None`.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.@@@ -690,9 -620,24 +763,40 @@@ impl LoginPromptinput: String::new(),error: None,verifying: false,+ stage: LoginStage::Paste { confirm_open: true },+ }+ }++ /// The dock as `/login` opens it, before the session exists.++ /// The dock for Tokamak's browser-approval flow, before the session exists.+ fn connecting() -> Self {+ Self {+ stage: LoginStage::Connecting,- ..Self::new()++ ..Self::new("tokamak")+ }+ }+++ fn unconfirmed_url(&self) -> Option<String> {++ match &self.stage {++ LoginStage::Paste { confirm_open: true } => {++ crate::core::cli::auth::provider_by_id(&self.provider)++ .map(|provider| provider.api_key.keys_url.to_string())++ }++ _ => self.stage.unconfirmed_url().map(str::to_string),+ }+ }++ /// Only the paste field accepts input, and only once the browser question is+ /// answered; the approval stages are display-only throughout.+ fn editable(&self) -> bool {- matches!(self.stage, LoginStage::Paste { confirm_open: false }) && !self.verifying++ matches!(++ self.stage,++ LoginStage::Paste {++ confirm_open: false++ }++ ) && !self.verifying+ }+fn masked(&self) -> String {super::secret_input::mask(self.input.chars().count())}@@@ -1115,7 -1025,7 +1218,12 @@@ impl Row}fn fill(&self, width: u16) {-- if self.cache.borrow().as_ref().is_some_and(|r| r.width == width) {++ if self++ .cache++ .borrow()++ .as_ref()++ .is_some_and(|r| r.width == width)++ {return;}let lines = self.render(width);@@@ -1666,16 -1610,13 +1817,22 @@@ struct App/// request timeout -- so only unprobed providers are fetched once.probed_models: std::collections::HashSet<String>,/// Key handed off to the loop to verify off the render loop. Taken once.- login_submit: Option<String>,+ login_submit: Option<(String, String)>,+ /// Active OAuth account prompt; owns the keyboard while open.+ account_login: Option<AccountLoginPrompt>,+ /// Account sign-in handed off to the loop after its local callback is ready.+ account_login_submit: Option<crate::core::cli::auth::account::AccountLogin>,+ /// Manual OAuth redirect/code sender for the active account task.+ account_login_manual_tx: Option<tokio::sync::mpsc::UnboundedSender<String>>,+ /// Manual OAuth input submitted while no task sender is active; delivered to+ /// the fresh task channel on retry spawn.+ account_login_pending_manual_input: Option<String>,+ /// `/login` asked for the browser flow: `chat_loop` creates the session.+ login_device_request: bool,+ /// A `/mcp` authorization waiting on the user's yes/no before a browser is- /// launched. Holds only the URL and what it is for -- never the bound++ /// launched. Holds only the URL and what it is for - never the bound+ /// loopback listener, which stays on the task awaiting the redirect.+ browser_confirm: Option<BrowserConfirm>,/// `/update` handed off to the loop, which spawns the install. Taken once.update_requested: bool,/// `/plugin install` handed off to the loop, which runs the git clone off@@@ -2136,10 -2080,8 +2301,12 @@@ impl Appprovider_prompt: None,probed_models: std::collections::HashSet::new(),login_submit: None,+ account_login: None,+ account_login_submit: None,+ account_login_manual_tx: None,+ account_login_pending_manual_input: None,+ login_device_request: false,+ browser_confirm: None,update_requested: false,plugin_install_request: None,plugin_select_request: None,@@@ -2711,12 -2720,12 +2944,10 @@@// block closed, so a long tool call or answer prose falls back to the// plain [working] instead of pinning [thought for Ns] till turn end.match (self.thought_for, self.thought_for_since) {-- (Some(d), Some(since)) if since.elapsed() < THOUGHT_FOR_TTL => {-- Some((-- format!("thought for {}", format_elapsed(d.as_secs())),-- Style::new().yellow(),-- ))-- }++ (Some(d), Some(since)) if since.elapsed() < THOUGHT_FOR_TTL => Some((++ format!("thought for {}", format_elapsed(d.as_secs())),++ Style::new().yellow(),++ )),_ => None,}}@@@ -6165,41 -6239,8 +6515,50 @@@ async fn await_mcp_job/// 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<crate::core::cli::auth::LoginResult, crate::core::cli::auth::LoginError>,+ >,+ >,+) -> Result<crate::core::cli::auth::LoginResult, crate::core::cli::auth::LoginError> {+ let joined = match task.as_mut() {+ Some(h) => h.await,+ None => return pending().await,+ };+ *task = None;+ match joined {+ Ok(inner) => inner,+ Err(e) => Err(crate::core::cli::auth::LoginError::Unavailable(format!(+ "sign-in task failed: {e}"+ ))),+ }+}+++async fn await_tokamak_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;++ joined.map_err(|e| format!("Tokamak sign-in task failed: {e}"))?++}+++async fn await_account_login(+ task: &mut Option<tokio::task::JoinHandle<Result<String, String>>>,+) -> Result<String, String> {+ let joined = match task.as_mut() {+ Some(h) => h.await,+ None => return pending().await,+ };+ *task = None;+ joined.map_err(|e| format!("account sign-in task failed: {e}"))?+}++/// Await the post-Claude-login plan-report task, parking forever when none is+/// running so this can sit in the loop's `select!` unconditionally.- async fn await_account_usage(- task: &mut Option<tokio::task::JoinHandle<String>>,- ) -> String {++async fn await_account_usage(task: &mut Option<tokio::task::JoinHandle<String>>) -> String {let joined = match task.as_mut() {Some(h) => h.await,None => return pending().await,@@@ -6351,7 -6413,7 +6731,10 @@@ fn finish_plugin_installapp.note("nothing installed");}for p in plugins {-- app.note(&format!("installed plugin '{}' ({} skills)", p.name, p.skills));++ app.note(&format!(++ "installed plugin '{}' ({} skills)",++ p.name, p.skills++ ));}}Ok(GitInstall::Collection(candidates)) => {@@@ -6471,7 -6533,11 +6854,11 @@@ pub async fn run};app.push_session_banner(!seeded);if app.model.is_empty() {- app.note("not signed in — run /login to choose a provider");- app.note("not signed in — run /login to sign in to Tokamak, or `jan config set` to configure a provider manually");++ app.note("not signed in - run /login to choose a provider");+ } else if let Some(warning) = super::tokamak::expiry_warning() {+ // Say it at launch rather than letting the key expire into a 401 in the+ // middle of a run.+ app.note(&warning);}// Only when there is nothing to load: a project that already has JAN.md needs// no invitation, and the splash hint covers re-running /init deliberately.@@@ -6551,14 -6625,6 +6946,13 @@@res}- const CLAUDE_ALIAS_NOTICE: &str =- crate::core::cli::auth::account::CLAUDE_ALIAS_NOTICE;++const CLAUDE_ALIAS_NOTICE: &str = crate::core::cli::auth::account::CLAUDE_ALIAS_NOTICE;++fn note_claude_alias_if_engaged(app: &mut App) {+ if crate::core::cli::auth::account::take_claude_alias_engaged() {+ app.system(Level::Warn, CLAUDE_ALIAS_NOTICE);+ }+}/// Apply one event from the active run's stream, clearing `current` on a/// terminal one. `None` is a stream that closed without a terminal event (an/// aborted task).@@@ -6664,17 -6729,21 +7058,28 @@@ 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;+ // The browser-approval sign-in, in two off-loop halves: `begin` creates the+ // session (one round trip), then the claim polls until the user approves --+ // which can take minutes, so it must never touch the render loop.+ let mut login_begin_task: Option<+ tokio::task::JoinHandle<+ Result<super::device_auth::PendingAuth, super::device_auth::BeginError>,+ >,+ > = None;+ let mut login_claim_task: Option<+ tokio::task::JoinHandle<Result<super::tokamak::Login, 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.@@@ -6684,11 -6753,7 +7089,6 @@@// and notes itself whenever it lands rather than delaying the first frame.let mut update_task = Some(tokio::spawn(super::updater::available_update()));- // Anonymous usage ping (see `telemetry::ping_if_due`), same reasoning:- // detached so it never delays the first frame. Nothing is noted for it --- // it has no user-visible outcome.- tokio::spawn(super::telemetry::ping_if_due());--// `/update` downloads tens of megabytes and rewrites the binary; off the// render loop for the same reason, and one at a time.let mut update_install_task: Option<@@@ -6736,53 -6805,24 +7140,61 @@@}}- // 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.+ // Esc closed the dock while sign-in work was in flight: drop all of it,+ // so a late reply can't report a sign-in the user walked away from. The+ // dock stays open for the whole flow, so this is the one cancel path.if app.login.is_none() {- for task in [- login_task.take(),- login_claim_task.take(),- ]- .into_iter()- .flatten()- {+ if let Some(task) = login_task.take() {+ task.abort();+ }++ if let Some(task) = login_claim_task.take() {+ task.abort();+ }+ if let Some(task) = login_begin_task.take() {+ task.abort();+ }+ app.login_device_request = false;}+ 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@@@ -6800,19 -6840,12 +7212,18 @@@}// 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++ crate::core::cli::auth::providers::login_with_api_key(&definition, &key).await+ }));}}@@@ -6987,24 -7040,35 +7418,51 @@@reload_provider_configs(app).await;}}+ account_login = await_account_login(&mut account_login_task) => {+ let anthropic = matches!(account_login.as_deref(), Ok("anthropic"));+ finish_account_login(app, account_login);+ if anthropic {+ // Fallback text is only shown if the stored token or the+ // probe itself errors (no credential, network failure), so+ // a straightforward down/rate-limit state stays visible.+ account_usage_task = Some(tokio::spawn(async move {+ crate::core::cli::auth::account::claude_plan_summary(+ "could not check which Claude plan this account resolves to.",+ )+ .await+ }));+ }+ }+ usage = await_account_usage(&mut account_usage_task) => {+ app.note(&usage);+ }+ begun = await_login_begin(&mut login_begin_task) => {+ match begun {+ Ok(pending) => {+ show_login_approval(app, pending.session());+ login_claim_task =+ Some(tokio::spawn(super::tokamak::device_login(pending)));+ }+ // Not a failure, but say it: an unexplained paste field+ // reads as the browser sign-in having silently broken.+ Err(super::device_auth::BeginError::Unsupported) => {+ app.note("this Tokamak deployment does not support browser sign-in yet");- open_login_prompt(app);++ open_login_prompt(app, "tokamak");+ }+ Err(e) => {+ app.note(&format!(+ "browser sign-in unavailable: {}",+ e.message(&super::tokamak::base_url())+ ));- open_login_prompt(app);++ open_login_prompt(app, "tokamak");+ }+ }+ }- claimed = await_login(&mut login_claim_task) => {- let login_ok = claimed.is_ok();- finish_login(app, claimed);- if login_ok {++ claimed = await_tokamak_login(&mut login_claim_task) => {++ if finish_tokamak_login(app, claimed) {+ reload_provider_configs(app).await;+ }+ }update = await_update_check(&mut update_task) => {note_update(app, update);}@@@ -7489,8 -7463,29 +7954,28 @@@ fn handle_login_key(app: &mut App, keyif cancel {app.login = None;app.login_submit = None;- app.note("sign-in cancelled (run /login again any time)");return;}+ // The browser question owns the keyboard until it is answered, so a+ // keystroke meant for it can never fall through into the key field.+ if app+ .login+ .as_ref()- .is_some_and(|p| p.stage.unconfirmed_url().is_some())++ .is_some_and(|p| p.unconfirmed_url().is_some())+ {+ if ctrl {+ return;+ }+ match key.code {+ KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {+ resolve_login_browser(app, true)+ }+ KeyCode::Char('n') | KeyCode::Char('N') => resolve_login_browser(app, false),+ _ => {}+ }+ 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') {@@@ -7516,19 -7516,17 +8006,17 @@@return;}match key.code {- KeyCode::Enter => {- match crate::core::cli::auth::providers::sanitize_key(&prompt.input) {- Ok(key) => {- prompt.verifying = true;- prompt.error = None;- app.login_submit = Some((prompt.provider.clone(), key));- }- Err(e) => {- prompt.input.clear();- prompt.error = Some(e);- }- KeyCode::Enter => match super::tokamak::sanitize_key(&prompt.input) {++ KeyCode::Enter => match crate::core::cli::auth::providers::sanitize_key(&prompt.input) {+ Ok(key) => {+ prompt.verifying = true;+ prompt.error = None;- app.login_submit = Some(key);++ app.login_submit = Some((prompt.provider.clone(), key));}- }+ Err(e) => {+ prompt.input.clear();+ prompt.error = Some(e);+ }+ },KeyCode::Backspace => {prompt.input.pop();}@@@ -7537,66 -7535,15 +8025,81 @@@}}-/// The copyable continuation command shown when a session closes, mirroring-/// the non-interactive resume line in `cli`/`mod.rs`. The id is the same-/// short thread id `--resume` accepts, taken from the thread the session-/// persists to rather than a separately minted one.-fn resume_hint(thread_id: &str) -> String {- let id: String = thread_id.chars().take(8).collect();- format!("\x1b[2m[session {id} - resume with `jan --resume={id}`]\x1b[0m")+/// 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> {+ super::secret_input::clipboard_text()}+fn handle_model_picker_key(app: &mut App, key: KeyEvent, ctrl: bool) {- if key.code == KeyCode::Esc || (ctrl && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d'))) {++ if key.code == KeyCode::Esc++ || (ctrl && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d')))++ {+ app.model_picker = None;+ return;+ }++ let mut chosen = None;+ if let Some(picker) = app.model_picker.as_mut() {+ match key.code {+ KeyCode::Left => picker.focus = ModelPickerFocus::Scopes,+ KeyCode::Right => {+ picker.focus = ModelPickerFocus::Models;+ picker.move_selection(0);+ }+ KeyCode::Up => match picker.focus {- ModelPickerFocus::Scopes => picker.select_scope(picker.active_scope.saturating_sub(1)),++ ModelPickerFocus::Scopes => {++ picker.select_scope(picker.active_scope.saturating_sub(1))++ }+ ModelPickerFocus::Models => picker.move_selection(-1),+ },+ KeyCode::Down => match picker.focus {+ ModelPickerFocus::Scopes => {+ let max = picker.scopes.len().saturating_sub(1);+ picker.select_scope((picker.active_scope + 1).min(max));+ }+ ModelPickerFocus::Models => picker.move_selection(1),+ },+ KeyCode::Char('k') if picker.focus == ModelPickerFocus::Models && !ctrl => {+ picker.move_selection(-1);+ }+ KeyCode::Char('j') if picker.focus == ModelPickerFocus::Models && !ctrl => {+ picker.move_selection(1);+ }+ KeyCode::Backspace if picker.focus == ModelPickerFocus::Models => {+ picker.query.pop();+ picker.refresh_items();+ }+ KeyCode::Char(ch) if picker.focus == ModelPickerFocus::Models && !ctrl => {+ picker.query.push(ch);+ picker.refresh_items();+ }+ KeyCode::Enter if picker.focus == ModelPickerFocus::Scopes => {+ picker.select_scope(picker.active_scope);+ picker.focus = ModelPickerFocus::Models;+ }+ KeyCode::Enter if picker.focus == ModelPickerFocus::Models => {- chosen = picker.items.get(picker.selected).map(|item| item.value.clone());++ chosen = picker++ .items++ .get(picker.selected)++ .map(|item| item.value.clone());+ }+ _ => {}+ }+ }+ if let Some(value) = chosen {+ app.set_model(value);+ app.model_picker = None;+ }+}++/// The copyable continuation command shown when a session closes, mirroring++/// the non-interactive resume line in `cli`/`mod.rs`. The id is the same++/// short thread id `--resume` accepts, taken from the thread the session++/// persists to rather than a separately minted one.++fn resume_hint(thread_id: &str) -> String {++ let id: String = thread_id.chars().take(8).collect();++ format!("\x1b[2m[session {id} - resume with `jan --resume={id}`]\x1b[0m")++}async fn handle_key(app: &mut App,key: KeyEvent,@@@ -7613,7 -7560,7 +8116,8 @@@let sup = key.modifiers.contains(KeyModifiers::SUPER);// A modified Enter is a newline, never a submit or a completion, so the// hint popups below have to let it through to the editing keys.-- let newline = key.code == KeyCode::Enter && (alt || key.modifiers.contains(KeyModifiers::SHIFT));++ let newline =++ key.code == KeyCode::Enter && (alt || key.modifiers.contains(KeyModifiers::SHIFT));let ctrl_c = ctrl && key.code == KeyCode::Char('c');let ctrl_d = ctrl && key.code == KeyCode::Char('d');@@@ -7710,12 -7661,8 +8231,13 @@@return;}+ if app.model_picker.is_some() {+ handle_model_picker_key(app, key, ctrl);+ return;+ }+- // Ctrl-D quits from anywhere not owned by a prompt or picker; Ctrl-C cancels a run or quits when idle.+ // Ctrl-D quits from anywhere; Ctrl-C cancels a run, clears a draft, or (on+ // a blank idle composer, and only on a second press) quits.if ctrl_d {abort_run(current);app.should_quit = true;@@@ -7821,9 -7768,9 +8343,7 @@@if picker.armed_delete == Some(sel) {// Second `d` on the same row confirms the delete.app.picker = None;-- if crate::core::agent::global_config::remove_provider(&name)-- .unwrap_or(false)-- {++ if crate::core::agent::global_config::remove_provider(&name).unwrap_or(false) {app.note(&format!("removed provider '{name}'"));} else {app.note(&format!("provider '{name}' was not configured"));@@@ -7906,31 -7842,8 +8426,32 @@@picker.selected.min(picker.items.len().saturating_sub(1));}}-- Err(e) => {-- app.note(&format!("failed to write {}: {e}", setting_path(def, &toml_path)))- }++ Err(e) => app.note(&format!(++ "failed to write {}: {e}",++ setting_path(def, &toml_path)++ )),+ }+ }+ // `/login`: `x` signs out the selected provider without leaving+ // the picker, so it doubles as a sign-out list. Only meaningful+ // for a provider that is currently signed in.+ KeyCode::Char('x') if picker.kind == PickerKind::LoginProvider => {+ let name = picker.items[picker.selected].value.clone();+ if !crate::core::cli::providers::provider_is_signed_in(+ Some(&app.project_root),+ &name,+ ) {+ app.note(&format!("{name} is not signed in"));+ return;+ }+ sign_out_provider(app, &name);+ // Refresh the status labels so the row flips to+ // "not signed in" without reopening the picker.+ if let Some(p) = app.picker.as_mut() {+ for item in &mut p.items {+ if item.value == name {+ item.hint = Some("not signed in".to_string());+ }}}}@@@ -7971,15 -7884,7 +8492,17 @@@app.picker = None;match kind {PickerKind::ResumeThread => resume_thread(app, &value).await,- PickerKind::SelectModel => app.set_model(value),+ PickerKind::LoginProvider => {+ if crate::core::cli::auth::account::AccountProvider::from_credential_provider(&value)+ .is_some()+ {+ open_account_login(app, &value);++ } else if value == "tokamak" {++ open_login(app);+ } else {+ open_login_prompt(app, &value);+ }+ }PickerKind::ToggleMcp => {}PickerKind::RewindMessage => {if let Ok(idx) = value.parse::<usize>() {@@@ -8026,9 -7931,9 +8549,7 @@@// Esc on the detail screen steps back to the server list rather// than closing outright: the detail is one level *inside* `/mcp`,// and dropping the user to the prompt loses the place they were at.-- KeyCode::Esc | KeyCode::Char('q')-- if !ctrl && picker.kind == PickerKind::McpServer =>-- {++ KeyCode::Esc | KeyCode::Char('q') if !ctrl && picker.kind == PickerKind::McpServer => {open_mcp_picker(app, mcp_servers).await;}KeyCode::Esc | KeyCode::Char('q') if !ctrl => {@@@ -8591,13 -8543,9 +9159,15 @@@ const SLASH_COMMANDS: &[SlashCommand]},SlashCommand {name: "/login",- hint: "",+ hint: "[--paste-token]",- description: "Sign in to Tokamak in a browser, or --paste-token to paste an API key",+ description: "Sign in to a provider",++ alias_of: None,+ },+ SlashCommand {+ name: "/logout",+ hint: "<provider>",+ description: "Remove a saved provider credential and configuration",+ alias_of: None,},SlashCommand {name: "/config",@@@ -8689,23 -8641,20 +9263,32 @@@ fn line_bounds(s: &str, at: usize) -> (const KEY_BINDINGS: &[(&str, &str)] = &[("Enter", "Send the message"),-- ("Alt+Enter / Ctrl-J", "Insert a newline (Shift+Enter where reported)"),++ (++ "Alt+Enter / Ctrl-J",++ "Insert a newline (Shift+Enter where reported)",++ ),("Ctrl-A/E, Alt+B/F", "Start/end of line, word left/right"),("Ctrl-W, Alt+Backspace", "Delete the word before the caret"),("Ctrl-U / Ctrl-K", "Delete to the start / end of the line"),- ("Esc / Ctrl-C", "Cancel the running turn"),- ("Esc / Ctrl-C", "Cancel the running turn, or clear the input"),++ (++ "Esc / Ctrl-C",++ "Cancel the running turn, or clear the input",++ ),("Esc Esc", "Rewind to an earlier message"),- ("↑/↓", "Recall sent messages and drafts (scrolls while typing)"),+ (+ "↑/↓",- "Recall sent messages (scrolls while the input has text)",++ "Recall sent messages and drafts (scrolls while typing)",+ ),("PgUp/PgDn", "Scroll the transcript"),("Ctrl-O", "Expand or collapse all tool calls"),("Ctrl-V", "Paste an image from the clipboard"),("Shift+Tab", "Cycle reasoning effort (low/medium/high)"),("Alt+T", "Toggle reasoning effort (low / last)"),-- ("Drag", "Select text, copied on release (Alt+drag for a block)"),- ("Ctrl-D", "Quit"),++ (++ "Drag",++ "Select text, copied on release (Alt+drag for a block)",++ ),+ ("Ctrl-D, or Ctrl-C twice", "Quit"),];/// Split a command line into `(name, arg)`, UTF-8 safe (no byte slicing).@@@ -8790,8 -8745,7 +9379,8 @@@ async fn run_command}"mcp" => open_mcp_picker(app, mcp_servers).await,"plugin" => plugin_command(app, arg).await,- "login" => open_login_picker(app),+ "login" => login_command(app, arg),+ "logout" => logout_command(app, arg),"update" => update_command(app),"config" => open_config_screen(app),"terminal-setup" => terminal_setup_command(app),@@@ -9048,13 -8990,13 +9637,21 @@@ enum SettingScope}enum AgentSettingKind {-- Int { default: Option<u64>, min: u64 },++ Int {++ default: Option<u64>,++ min: u64,++ },/// Short display glyph with a grapheme cap, and the one kind where an/// empty field is a *value* rather than an unset: `""` is the deliberate/// "off", distinct from the key being absent, which takes the default./// `x` on the row still removes the key.-- Glyph { default: &'static str, max: usize },-- Text { default: &'static str },++ Glyph {++ default: &'static str,++ max: usize,++ },++ Text {++ default: &'static str,++ },/// Exact-match choice: Enter writes one of `options`, cleared field/// unsets. Covers the `read-only | deny | allow` and `always | relevance`/// toggles that hand-editing agent.toml previously required.@@@ -9294,10 -9219,10 +9898,7 @@@ impl McpPromptfn prev_field(&mut self) {let fields = self.visible_fields();-- let pos = fields-- .iter()-- .position(|f| *f == self.field)-- .unwrap_or(0);++ let pos = fields.iter().position(|f| *f == self.field).unwrap_or(0);self.field = fields[if pos == 0 { fields.len() - 1 } else { pos - 1 }];}@@@ -9491,9 -9411,9 +10092,8 @@@ impl ProviderPrompt.iter().position(|f| *f == self.field).unwrap_or(0);-- self.field = Self::FIELD_ORDER[-- (pos + Self::FIELD_ORDER.len() - 1) % Self::FIELD_ORDER.len()-- ];++ self.field =++ Self::FIELD_ORDER[(pos + Self::FIELD_ORDER.len() - 1) % Self::FIELD_ORDER.len()];}}@@@ -9574,26 -9489,10 +10173,23 @@@if url.starts_with("http://") && is_loopback_url(url) {return None;}-- Some(-- "base URL must be https:// (or http:// for a localhost/loopback host)"-- .to_string(),-- )++ Some("base URL must be https:// (or http:// for a localhost/loopback host)".to_string())+ }+ /// `None` renders as the OpenAI-compatible default; `Some("anthropic")`+ /// selects the Anthropic messages API.+ fn toggle_api_type(&mut self) {+ self.api_type = match self.api_type.as_deref() {+ Some("anthropic") => None,+ _ => Some("anthropic".to_string()),+ };+ }++ /// Human label for the active api-type selection.+ fn api_type_label(&self) -> String {+ match self.api_type.as_deref() {+ Some("anthropic") => "anthropic-compatible".to_string(),+ _ => "openai-compatible".to_string(),+ }}/// Persist the provider to `~/.jan/config.toml` via the headless config@@@ -9613,21 -9512,14 +10209,17 @@@return Err(err);}let base_url = self.base_url.trim().to_string();-- let api_key = (self.key_touched || self.editing.is_none())-- .then(|| self.api_key.trim().to_string());-- let models: Vec<String> = self-- .models-- .split_whitespace()-- .map(str::to_string)-- .collect();- super::cli_agent_config_set(name, api_key, Some(base_url), Some(models), None).map(|_| ())++ let api_key =++ (self.key_touched || self.editing.is_none()).then(|| self.api_key.trim().to_string());++ let models: Vec<String> = self.models.split_whitespace().map(str::to_string).collect();+ super::cli_agent_config_set(+ name,+ api_key,+ Some(base_url),+ Some(models),+ self.api_type.clone(),+ )+ .map(|_| ())}}@@@ -9814,8 -9706,8 +10406,7 @@@ fn open_provider_settings(app: &mut Applet items: Vec<PickerItem> = if providers.is_empty() {vec![PickerItem {-- label: "no providers configured - press a to add an OpenAI-compatible one"-- .to_string(),++ label: "no providers configured - press a to add an OpenAI-compatible one".to_string(),value: String::new(),hint: None,checkbox: None,@@@ -9824,7 -9716,7 +10415,11 @@@providers.into_iter().map(|c| {-- let key = if c.api_key.is_some() { "key set" } else { "no key" };++ let key = if c.api_key.is_some() {++ "key set"++ } else {++ "no key"++ };let base = c.base_url.as_deref().unwrap_or("default url");PickerItem {label: format!("{key} {base} {} model(s)", c.models.len()),@@@ -9902,10 -9791,10 +10497,8 @@@ fn handle_settings_key(app: &mut App, k}Some(toml_edit::value(input.to_string()))}-- AgentSettingKind::Text { .. } => {-- (!prompt.input.trim().is_empty())-- .then(|| toml_edit::value(prompt.input.trim().to_string()))-- }++ AgentSettingKind::Text { .. } => (!prompt.input.trim().is_empty())++ .then(|| toml_edit::value(prompt.input.trim().to_string())),AgentSettingKind::Enum { options, default } => {let input = prompt.input.trim();if input.is_empty() {@@@ -9962,8 -9853,8 +10555,8 @@@// leaves `👁`, so the row looks unchanged and the key reads as// broken. Other kinds keep the plain char pop.if matches!(prompt.def().kind, AgentSettingKind::Glyph { .. }) {-- let keep = crate::core::agent::global_config::wave_len(&prompt.input)-- .saturating_sub(1);++ let keep =++ crate::core::agent::global_config::wave_len(&prompt.input).saturating_sub(1);prompt.input = grapheme_prefix(&prompt.input, keep);} else {prompt.input.pop();@@@ -10040,25 -9931,25 +10633,35 @@@ async fn handle_mcp_prompt_key}}KeyCode::Backspace => match prompt.field {-- McpField::Name => { prompt.name.pop(); }-- McpField::Command => { prompt.command.pop(); }-- McpField::Args => { prompt.args.pop(); }-- McpField::Env => { prompt.env.pop(); }-- McpField::Url => { prompt.url.pop(); }-- McpField::Headers => { prompt.headers.pop(); }++ McpField::Name => {++ prompt.name.pop();++ }++ McpField::Command => {++ prompt.command.pop();++ }++ McpField::Args => {++ prompt.args.pop();++ }++ McpField::Env => {++ prompt.env.pop();++ }++ McpField::Url => {++ prompt.url.pop();++ }++ McpField::Headers => {++ prompt.headers.pop();++ }++ _ => {}++ },++ KeyCode::Char(ch) if !ctrl => match prompt.field {++ McpField::Name => prompt.name.push(ch),++ McpField::Command => prompt.command.push(ch),++ McpField::Args => prompt.args.push(ch),++ McpField::Env => prompt.env.push(ch),++ McpField::Url => prompt.url.push(ch),++ McpField::Headers => prompt.headers.push(ch),_ => {}},-- KeyCode::Char(ch) if !ctrl => {-- match prompt.field {-- McpField::Name => prompt.name.push(ch),-- McpField::Command => prompt.command.push(ch),-- McpField::Args => prompt.args.push(ch),-- McpField::Env => prompt.env.push(ch),-- McpField::Url => prompt.url.push(ch),-- McpField::Headers => prompt.headers.push(ch),-- _ => {}-- }-- }_ => {}}}@@@ -10705,15 -10593,18 +11308,11 @@@ fn open_thread_picker(app: &mut App)}}-/// Open the `/model` selector listing the `provider / model` pairs this build-/// can actually run, with the current model pre-highlighted. A reachable-/// provider with no configured model list (e.g. just added via the settings-/// wizard) is queried for its `GET /models` on the spot and the discovered ids-/// persisted, so a bare provider becomes selectable immediately.+/// Open the `/model` hub listing the `provider / model` pairs this build can+/// actually run, with the current raw model pre-highlighted.async fn open_model_picker(app: &mut App) {let project_root = app.project_root.clone();-- match super::providers::fetch_missing_models(-- Some(&project_root),-- &mut app.probed_models,-- )-- .await++ match super::providers::fetch_missing_models(Some(&project_root), &mut app.probed_models).await{Ok(true) => {// The discovered ids now live on disk; refresh the session's@@@ -10726,16 -10617,27 +11325,15 @@@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,- });}/// Action ids for the `McpServer` detail screen. String values rather than an@@@ -10949,10 -10847,10 +11547,7 @@@ fn mcp_detail_lines(detail: &McpDetail));rows.push(("Config location",-- vec![Span::styled(-- tilde_path(&server.config_path),-- dim,-- )],++ vec![Span::styled(tilde_path(&server.config_path), dim)],));if let Some(implementation) = &server.implementation {rows.push(("Server", vec![Span::styled(implementation.clone(), dim)]));@@@ -10992,9 -10890,9 +11587,7 @@@ fn tools_span(tools: &ToolsState) -> Spmatch 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) 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()),}@@@ -11064,290 -10962,196 +11657,419 @@@ fn clamp_line(line: Line<'static>, widtLine::from(spans)}-/// `/login [--paste-token]`: the browser flow, or the legacy paste field when-/// the user asks for it explicitly (the same escape hatch `jan login` has).+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,+ });+}+++/// `/login [--paste-token]`: choose a provider, or skip directly to Tokamak's++/// legacy API-key field.+ fn login_command(app: &mut App, arg: &str) {- // One sign-in at a time: the dock is open for the whole flow, and switching- // it under an in-flight session would either drop the new request (the- // browser flow) or have the arriving session clobber the paste field.- if app.login.is_some() {++ if app.login.is_some()++ || app.account_login.is_some()++ || app++ .picker++ .as_ref()++ .is_some_and(|picker| picker.kind == PickerKind::LoginProvider)++ {+ app.note("a sign-in is already in progress - press Esc to cancel it first");+ return;+ }+ match arg.split_whitespace().next() {- Some("--paste-token" | "--paste") => open_login_prompt(app),- Some(other) => app.note(&format!("/login: unknown option {other} (try --paste-token)")),- None => open_login(app),++ Some("--paste-token" | "--paste") => open_login_prompt(app, "tokamak"),++ Some(other) => app.note(&format!(++ "/login: unknown option {other} (try --paste-token)"++ )),++ None => open_login_picker(app),+ }+ }++ /// Start `/login`: the browser-approval flow. The dock opens immediately, so+ /// there is something to Esc out of while the session is being created, and+ /// `chat_loop` picks the request up off the render loop.+ fn open_login(app: &mut App) {+ app.login = Some(LoginPrompt::connecting());+ app.login_device_request = true;+ }++ /// The session exists: show the code to check and the page to approve on, and+ /// open the browser. The URL goes to the transcript as well as the dock, so a+ /// remote or headless session can still be finished by hand -- or from a phone.+ fn show_login_approval(app: &mut App, session: &super::device_auth::Session) {+ app.note("sign in to Tokamak in your browser - confirm this code matches:");+ app.system_detail(vec![Span::styled(+ session.user_code.clone(),+ Style::new().cyan().bold(),+ )]);+ app.system_detail(vec![Span::styled(+ session.authorize_url.clone(),+ Style::new().cyan(),+ )]);+ app.login = Some(LoginPrompt {+ stage: LoginStage::Approving {+ user_code: session.user_code.clone(),+ authorize_url: session.authorize_url.clone(),+ confirm_open: true,+ },- ..LoginPrompt::new()++ ..LoginPrompt::new("tokamak")+ });+ }++ /// Act on an answered "open a browser?" question: launch it, or say we didn't.+ /// Either way the URL is already in the transcript, so declining is a valid way+ /// to finish the flow on another device rather than a way to abandon it. Shared+ /// by `/login` and `/mcp`, which ask the same question in different docks.+ fn open_browser_reporting(app: &mut App, url: &str, open: bool) {+ if !open {+ app.system_detail_text("not opening a browser - use the URL above on any device");+ return;+ }+ match super::browser::open(url) {+ Ok(()) => app.system_detail_text("opening that page in your browser"),+ Err(e) => app.system_detail_text(&format!("could not open a browser ({e})")),+ }+ }++ /// Answer the question the `/login` dock is holding. The dock moves on either+ /// way, so the sign-in is never blocked on a browser.+ fn resolve_login_browser(app: &mut App, open: bool) {- let Some(url) = app- .login- .as_ref()- .and_then(|p| p.stage.unconfirmed_url())- .map(str::to_string)- else {++ let Some(url) = app.login.as_ref().and_then(LoginPrompt::unconfirmed_url) else {+ return;+ };+ open_browser_reporting(app, &url, open);+ if let Some(prompt) = app.login.as_mut() {+ prompt.stage.mark_confirmed();+ }+ }++ /// Answer the standalone `/mcp` question. The authorization is already waiting on+ /// its loopback listener, so declining just means the user opens the URL+ /// themselves -- the redirect still completes the sign-in.+ fn resolve_mcp_browser(app: &mut App, open: bool) {+ let Some(confirm) = app.browser_confirm.take() else {+ return;+ };+ open_browser_reporting(app, &confirm.url, open);+ }-/// Fall back to the paste field: 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_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 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);- app.login = Some(LoginPrompt::new());++ app.login = Some(LoginPrompt::new(provider));}-/// 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;- let who = match &login.account {- Some(account) => format!(" as {account}"),- None => String::new(),- };- app.note(&format!(- "signed in to Tokamak{who} - {} model(s) available, key saved to {}",- login.models.len(),- login.config_path.display()- ));- if let Some(warning) = super::tokamak::expiry_warning() {- app.note(&warning);- }+ app.note(&login_success_message(&login.provider));adopt_login_model(app, &login);}- Err(e) => {- // Keep the paste field open with the reason: a rejected key is- // usually a partial paste, and reopening from scratch loses that- // context. A browser approval that was denied or expired has no- // field to correct, so the dock closes and the reason is noted.- match app.login.as_mut() {- Some(prompt) if prompt.editable() || prompt.verifying => {+ Err(error) => {- if let Some(prompt) = app.login.as_mut() {- let provider = prompt.provider.clone();- prompt.verifying = false;- prompt.input.clear();- prompt.error = Some(login_error_message(&provider, error));++ let Some((provider, retryable)) = app.login.as_ref().map(|prompt| {++ (++ prompt.provider.clone(),++ prompt.editable() || prompt.verifying,++ )++ }) else {++ return;++ };++ let message = login_error_message(&provider, error);++ if retryable {++ if let Some(prompt) = app.login.as_mut() {+ prompt.verifying = false;+ prompt.input.clear();- prompt.error = Some(e);- }- _ => {- app.login = None;- app.note(&format!("sign-in failed: {e}"));++ prompt.error = Some(message);+ }++ } else {++ app.login = None;++ app.note(&format!("sign-in failed: {message}"));+ }+ }+ }+ }+-/// 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. "Runnable" is the-/// CLI's own reachability (`is_cli_reachable`), so a local-engine model -- which-/// this build can never resolve an upstream for -- is adopted away from rather-/// than left as a session that cannot answer.-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());- }-}--/// Re-read `~/.jan/config.toml` (plus desktop and project layers) into the-/// session's in-memory `args.provider_configs` map. Must be called after any-/// mid-session credential write (`/login`, `jan config set`) because-/// `prepare_agent_session` snapshots the provider map once at startup and-/// never re-reads it. Without this, the first turn after sign-in fails-/// upstream resolution (`"No upstream session found for model ..."`) and-/// requires a restart.-async fn reload_provider_configs(app: &mut App) {- let Some(args) = app.args.clone() else {- return;- };- let project_root = app.project_root.clone();- match super::providers::load_provider_configs(- Some(&project_root),- &super::providers::ProviderOverrides::default().with_env(),- ) {- Ok(configs) => {- *args.provider_configs.lock().await = configs;++fn finish_tokamak_login(app: &mut App, result: Result<super::tokamak::Login, String>) -> bool {++ match result {++ Ok(login) => {++ let super::tokamak::Login {++ models,++ config_path,++ default_model,++ account,++ } = login;++ finish_login(++ app,++ Ok(crate::core::cli::auth::LoginResult {++ provider: "tokamak".to_string(),++ models,++ config_path,++ default_model,++ }),++ );++ if let Some(account) = account {++ app.note(&format!("signed in to Tokamak as {account}"));+ }++ if let Some(warning) = super::tokamak::expiry_warning() {++ app.note(&warning);++ }++ true+ }- Err(e) => {- app.note(&format!(- "could not reload provider config after sign-in: {e}"- ));++ Err(error) => {++ finish_login(app, Err(crate::core::cli::auth::LoginError::OAuth(error)));++ false}}}-/// `/terminal-setup`: teach the host terminal to send `Shift+Enter`. See-/// `terminal_setup` for why a terminal-side binding is the only reliable route.-fn terminal_setup_command(app: &mut App) {+fn finish_account_login(app: &mut App, result: Result<String, String>) {+ app.account_login_manual_tx = None;+ if app.account_login.is_none() {+ clear_account_login_pending(app);+ return;+ }+ match result {+ Ok(provider) => {+ clear_account_login_pending(app);+ app.account_login = None;+ app.account_login_submit = None;+ app.note(&login_success_message(&provider));+ warn_on_claude_login(app, &provider);+ adopt_account_login_model(app, &provider);+ }+ Err(error) => {+ if let Some(prompt) = app.account_login.as_mut() {+ let provider = prompt.provider_id();+ crate::core::cli::auth::account::debug_log(&format!(+ "account login failed for {provider}: {error}"+ ));+ prompt.submitting = false;+ prompt.input.clear();+ prompt.error = Some(if error == "could not open the browser" {+ "could not open the browser; use the URL below".to_string()+ } else {+ account_login_error_message(provider)+ });+ }+ }+ }+}++fn login_success_message(provider: &str) -> String {+ format!("signed in to {provider}. Use /model to select a model.")+}+/// Warn after a Claude account sign-in that Jan reaches Anthropic directly+/// with the user's OAuth token. Since Jan is a third-party client (not the+/// official Claude Code CLI), usage proceeds against Anthropic's Claude Code+/// Terms of Service at the user's own risk; there is no guarantee that+/// Anthropic permits third-party access to the same quota.+fn warn_on_claude_login(app: &mut App, provider: &str) {+ if provider == "anthropic" {+ app.system(+ Level::Warn,+ "Claude sign-in: Jan is a third-party client. Using the Claude Code \+ quota through Jan may not be sanctioned by Anthropic; proceed at \+ your own risk and review Anthropic's Terms of Service.",+ );+ }+}+-+fn account_login_error_message(provider: &str) -> String {+ format!("{provider} sign-in failed: could not complete browser sign-in")+}++fn login_error_message(provider: &str, error: crate::core::cli::auth::LoginError) -> String {+ let message = match error {+ crate::core::cli::auth::LoginError::InvalidKey(message)+ | crate::core::cli::auth::LoginError::Unavailable(message) => message,+ crate::core::cli::auth::LoginError::Persist(_) => {+ "could not save sign-in securely".to_string()+ }+ crate::core::cli::auth::LoginError::OAuth(_) => {+ "could not complete browser sign-in".to_string()+ }+ crate::core::cli::auth::LoginError::Unauthorized => {+ "that API key was not accepted".to_string()+ }+ crate::core::cli::auth::LoginError::RateLimited => {+ "that API key is rate limited - wait and try again".to_string()+ }+ };+ format!("{provider} sign-in failed: {message}")+}+-+fn adopt_account_login_model(app: &mut App, provider: &str) {+ let models = crate::core::agent::global_config::load_global_config()+ .ok()+ .and_then(|configs| configs.get(provider).map(|config| config.models.clone()))+ .unwrap_or_default();+ let login = crate::core::cli::auth::LoginResult {+ provider: provider.to_string(),+ models,+ config_path: std::path::PathBuf::new(),+ default_model: None,+ };+ adopt_login_model(app, &login);+}+fn adopt_login_model(app: &mut App, login: &crate::core::cli::auth::LoginResult) {+ let runnable = super::providers::list_provider_models(Some(&app.project_root));+ if runnable.iter().any(|(_, model)| *model == app.model) {+ return;+ }+ if let Some(model) = login.models.first() {+ app.model = model.clone();+ let _ = super::cli_set_project_model(&app.agent_dir, &app.model);+ }+}++/// Re-read `~/.jan/config.toml` (plus desktop and project layers) into the+/// session's in-memory `args.provider_configs` map. Must be called after any+/// mid-session credential write (`/login`, `jan config set`) because+/// `prepare_agent_session` snapshots the provider map once at startup and+/// never re-reads it. Without this, the first turn after sign-in fails+/// upstream resolution (`"No upstream session found for model ..."`) and+/// requires a restart.+async fn reload_provider_configs(app: &mut App) {+ let Some(args) = app.args.clone() else {+ return;+ };+ let project_root = app.project_root.clone();+ match super::providers::load_provider_configs(+ Some(&project_root),+ &super::providers::ProviderOverrides::default().with_env(),+ ) {+ Ok(configs) => {+ *args.provider_configs.lock().await = configs;+ }+ Err(e) => {+ app.note(&format!(+ "could not reload provider config after sign-in: {e}"+ ));+ }+ }+}++/// `/terminal-setup`: teach the host terminal to send `Shift+Enter`. See+/// `terminal_setup` for why a terminal-side binding is the only reliable route.+fn terminal_setup_command(app: &mut App) {use super::terminal_setup::{apply, Outcome};let Some(home) = dirs::home_dir() else {app.system(Level::Error, "no home directory for terminal config");@@@ -11513,7 -11320,7 +12242,11 @@@ async fn finish_mcp_jobOk(()) => app.note(&format!("'{server}' connected")),Err(e) => app.note(&format!("MCP: {e}")),}-- if app.mcp_detail.as_ref().is_some_and(|d| d.server.name == server) {++ if app++ .mcp_detail++ .as_ref()++ .is_some_and(|d| d.server.name == server)++ {open_mcp_detail(app, &server, mcp_servers).await;}}@@@ -12665,16 -12465,19 +13402,17 @@@ fn draw(f: &mut Frame, app: &mut App)app.row_index = row_index;// Keep the cursor row visible when the input outgrows the box.- let input_scroll = if app.status == Status::Idle && app.picker.is_none() {- let input_scroll = if app.status == Status::Idle- && app.picker.is_none()- && app.blocking_dock().is_none()- {-- let visible = chunks[2].height.saturating_sub(1);-- let total = Paragraph::new(input_content_lines(&app.input, app.cursor))-- .wrap(Wrap { trim: false })-- .line_count(chunks[2].width.saturating_sub(2).max(1))-- .min(u16::MAX as usize) as u16;-- total.saturating_sub(visible)-- } else {-- 0-- };++ let input_scroll =++ if app.status == Status::Idle && app.picker.is_none() && app.blocking_dock().is_none() {++ let visible = chunks[2].height.saturating_sub(1);++ let total = Paragraph::new(input_content_lines(&app.input, app.cursor))++ .wrap(Wrap { trim: false })++ .line_count(chunks[2].width.saturating_sub(2).max(1))++ .min(u16::MAX as usize) as u16;++ total.saturating_sub(visible)++ } else {++ 0++ };if let Some(lines) = panel_lines {f.render_widget(Paragraph::new(lines), panel_area);}@@@ -12705,6 -12498,18 +13443,18 @@@height,};draw_login(f, rect, prompt);+ } else if let Some(confirm) = &app.browser_confirm {- let height = (browser_confirm_lines(confirm, chunks[2].width.saturating_sub(2)).len() as u16- + 2)- .min(chunks[1].height);++ let height =++ (browser_confirm_lines(confirm, chunks[2].width.saturating_sub(2)).len() as u16 + 2)++ .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_browser_confirm(f, rect, confirm);} else if let Some(prompt) = &app.settings_prompt {let toml_path = app.agent_dir.join("agent.toml");let height = (settings_prompt_lines(prompt, &toml_path, chunks[2].width.saturating_sub(2))@@@ -12896,79 -12704,6 +13649,78 @@@ fn draw_ask(f: &mut Frame, area: Rect,f.render_widget(Paragraph::new(help), rows[2]);}+/// Rows the account OAuth box needs: two borders plus status, authorization+/// destination, callback URI, masked field, and help. An error adds one more.+const ACCOUNT_LOGIN_PROMPT_ROWS: u16 = 7;++fn safe_url_origin_path(raw: &str) -> String {+ url::Url::parse(raw).map_or_else(+ |_| "unknown URL".to_string(),+ |mut url| {+ url.set_query(None);+ url.set_fragment(None);+ format!("{}{}", url.origin().ascii_serialization(), url.path())+ },+ )+}+- fn draw_account_login(- f: &mut Frame,- area: ratatui::layout::Rect,- prompt: &AccountLoginPrompt,- ) {++fn draw_account_login(f: &mut Frame, area: ratatui::layout::Rect, prompt: &AccountLoginPrompt) {+ use ratatui::widgets::Clear;++ let dim = Style::new().dark_gray();+ let provider = prompt.provider_id();+ let name = crate::core::cli::auth::provider_by_id(provider)+ .map_or("provider", |definition| definition.name);+ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(Style::new().cyan())+ .title(Span::styled(+ format!(" {name} sign-in "),+ Style::new().on_cyan().black().bold(),+ ));+ let mut lines = vec![+ Line::styled("open the browser to continue", dim),+ Line::from(vec![+ Span::styled("authorization: ", dim),+ Span::styled(+ safe_url_origin_path(&prompt.login.authorization_url),+ Style::new().cyan(),+ ),+ ]),+ Line::from(vec![+ Span::styled("callback: ", dim),- Span::styled(safe_url_origin_path(&prompt.login.redirect_uri), Style::new().cyan()),++ Span::styled(++ safe_url_origin_path(&prompt.login.redirect_uri),++ Style::new().cyan(),++ ),+ ]),+ ];+ if let Some(error) = &prompt.error {+ lines.push(Line::styled(error.clone(), Style::new().red()));+ }+ lines.push(Line::from(vec![+ Span::styled("authorization code or redirect URL: ", Style::new().bold()),+ Span::raw(prompt.masked()),+ Span::styled("█", Style::new().cyan()),+ ]));+ lines.push(Line::styled(+ if prompt.submitting {+ "waiting for browser sign-in · Esc cancel"+ } else {+ "Enter submit · Esc cancel"+ },+ dim,+ ));++ f.render_widget(Clear, area);+ let inner = block.inner(area);+ f.render_widget(block, area);+ f.render_widget(Paragraph::new(lines), inner);+}++/// 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.@@@ -12979,15 -12714,29 +13731,33 @@@fn login_prompt_lines(prompt: &LoginPrompt, width: u16) -> Vec<Line<'static>> {let dim = Style::new().dark_gray();let max = width.max(1) as usize;- let definition = crate::core::cli::auth::provider_by_id(&prompt.provider);- let keys_url = definition- .as_ref()- .map_or("", |provider| provider.api_key.keys_url);-- let mut lines = vec![Line::from(vec![- Span::styled("get a key at ", dim),- Span::styled(keys_url.to_string(), Style::new().cyan()),- ])];+ let lead = match &prompt.stage {+ LoginStage::Connecting => vec![Span::styled("starting browser sign-in...", dim)],+ LoginStage::Approving { authorize_url, .. } => vec![+ Span::styled("approve at ", dim),+ Span::styled(authorize_url.clone(), Style::new().cyan()),+ ],- LoginStage::Paste { .. } => vec![- Span::styled("get a key at ", dim),- Span::styled(super::tokamak::API_KEYS_URL, Style::new().cyan()),- ],++ LoginStage::Paste { .. } => {++ let keys_url = crate::core::cli::auth::provider_by_id(&prompt.provider)++ .map_or("", |provider| provider.api_key.keys_url);++ vec![++ Span::styled("get a key at ", dim),++ Span::styled(keys_url.to_string(), Style::new().cyan()),++ ]++ }+ };+ let mut lines: Vec<Line<'static>> = wrap_spans_hard(lead, max)+ .into_iter()+ .map(Line::from)+ .collect();+ // The code is the one thing the user must compare against the browser, so+ // it gets its own bright line rather than riding the URL's wrap.+ if let LoginStage::Approving { user_code, .. } = &prompt.stage {+ lines.push(Line::from(vec![+ Span::styled("code: ", dim),+ Span::styled(user_code.clone(), Style::new().cyan().bold()),+ ]));+ }if let Some(error) = &prompt.error {lines.extend(wrap_text(error, Style::new().red(), max)@@@ -12995,23 -12744,49 +13765,49 @@@.map(Line::from),);}- if prompt.verifying {+ // The browser question, whichever stage is asking it, reads the same.- if prompt.stage.unconfirmed_url().is_some() {++ if prompt.unconfirmed_url().is_some() {lines.push(Line::styled(- "verifying...".to_string(),+ "open this page in your browser?".to_string(),Style::new().yellow(),));- lines.push(Line::styled("Esc cancel".to_string(), dim));- } else {- lines.extend(field_lines(- vec![Span::styled("API key: ", Style::new().bold())],- &prompt.masked(),- Style::new(),- max,- ));lines.push(Line::styled(- "paste the key · Enter verify · Esc cancel".to_string(),+ "Enter open · n skip · Esc cancel".to_string(),dim,));+ return lines;+ }+ match &prompt.stage {+ LoginStage::Connecting => lines.push(Line::styled("Esc cancel".to_string(), dim)),+ LoginStage::Approving { .. } => {+ lines.push(Line::styled(+ "waiting for approval...".to_string(),+ Style::new().yellow(),+ ));+ lines.push(Line::styled(+ "approve from any device · Esc cancel".to_string(),+ dim,+ ));+ }+ LoginStage::Paste { .. } if prompt.verifying => {+ lines.push(Line::styled(+ "verifying...".to_string(),+ Style::new().yellow(),+ ));+ lines.push(Line::styled("Esc cancel".to_string(), dim));+ }+ LoginStage::Paste { .. } => {+ lines.extend(field_lines(+ vec![Span::styled("API key: ", Style::new().bold())],+ &prompt.masked(),+ Style::new(),+ max,+ ));+ lines.push(Line::styled(+ "paste the key · Enter verify · Esc cancel".to_string(),+ dim,+ ));+ }}lines}@@@ -13035,6 -12810,57 +13831,53 @@@ fn field_linesgutter_lines(rows, lead, vec![Span::raw(" ".repeat(lead_w))])}+ /// The pending-browser box's contents at `width`, sized by the caller the same+ /// way as `login_prompt_lines` -- the URL is the long line that has to be+ /// readable, since declining means opening it by hand.+ fn browser_confirm_lines(confirm: &BrowserConfirm, width: u16) -> Vec<Line<'static>> {+ let dim = Style::new().dark_gray();+ let max = width.max(1) as usize;+ let mut lines: Vec<Line<'static>> = wrap_spans_hard(+ vec![+ Span::styled(format!("{} at ", confirm.purpose), dim),+ Span::styled(confirm.url.clone(), Style::new().cyan()),+ ],+ max,+ )+ .into_iter()+ .map(Line::from)+ .collect();+ lines.push(Line::styled(+ "open this page in your browser?".to_string(),+ Style::new().yellow(),+ ));+ lines.push(Line::styled(+ "Enter open · n skip · Esc skip".to_string(),+ dim,+ ));+ lines+ }+-fn draw_browser_confirm(- f: &mut Frame,- area: ratatui::layout::Rect,- confirm: &BrowserConfirm,-) {++fn draw_browser_confirm(f: &mut Frame, area: ratatui::layout::Rect, confirm: &BrowserConfirm) {+ use ratatui::widgets::Clear;++ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(Style::new().cyan())+ .title(Span::styled(+ " open a browser? ",+ Style::new().on_cyan().black().bold(),+ ));++ f.render_widget(Clear, area);+ let inner = block.inner(area);+ f.render_widget(block, area);+ f.render_widget(+ Paragraph::new(browser_confirm_lines(confirm, inner.width)),+ inner,+ );+ }+fn draw_login(f: &mut Frame, area: ratatui::layout::Rect, prompt: &LoginPrompt) {use ratatui::widgets::Clear;@@@ -13470,175 -13290,6 +14317,191 @@@ fn draw_permissionf.render_stateful_widget(list, rows[2], &mut state);}+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)+}++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]);++ 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()+ .enumerate()+ .map(|(idx, scope)| {+ let style = if idx == picker.active_scope {+ if picker.focus == ModelPickerFocus::Scopes {+ Style::new().reversed().bold()+ } else {+ Style::new().reversed()+ }+ } else {+ Style::new()+ };+ ListItem::new(Line::styled(+ count_label(&scope.label, scope.count, scope_width),+ style,+ ))+ })+ .collect();- let scopes = List::new(scope_items).highlight_symbol(if picker.focus == ModelPickerFocus::Scopes {- "▶ "- } else {- " "- });++ 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);++ 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()),- ])),++ 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" };++ 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,@@@ -13733,9 -13384,9 +14596,7 @@@} else if let (PickerKind::McpServer, Some(detail)) = (picker.kind, mcp_detail) {// The info block and the actions share one border: they are one screen,// and two stacked frames would read as two unrelated panels.-- let block = Block::default()-- .borders(Borders::ALL)-- .title(picker.title());++ let block = Block::default().borders(Borders::ALL).title(picker.title());let inner = block.inner(area);f.render_widget(block, area);@@@ -13745,7 -13396,7 +14606,10 @@@// it would displace.let info_h = (info.len() as u16).min(inner.height.saturating_sub(1));let (info_area, list_area) = (-- Rect { height: info_h, ..inner },++ Rect {++ height: info_h,++ ..inner++ },Rect {y: inner.y + info_h,height: inner.height - info_h,@@@ -13753,11 -13404,11 +14617,7 @@@},);f.render_widget(Paragraph::new(info), info_area);-- f.render_stateful_widget(-- list.block(Block::default()),-- list_area,-- &mut state,-- );++ f.render_stateful_widget(list.block(Block::default()), list_area, &mut state);} else {f.render_stateful_widget(list, area, &mut state);}@@@ -13993,39 -13645,6 +14860,37 @@@ fn shimmer_spans(text: &str, palette: [.collect()}-+/// Resolve the display label for `model`: the `provider/model` pair when the+/// bare id maps to a configured provider (mirroring upstream resolution:+/// an exact hit in a provider's `models` list, or a `<provider>/<model>`+/// prefix). A bare id stays bare when no provider claims it, so a fresh or+/// custom id is not mislabeled.+fn provider_label_for_model(+ model: &str,+ pc: &HashMap<String, crate::core::state::ProviderConfig>,+) -> String {+ use crate::core::cli::providers::is_cli_reachable;+ // Explicit `<provider>/<model>` form: verify the prefix names a provider.+ if let Some(sep) = model.find('/') {+ if pc.contains_key(&model[..sep]) {+ return model.to_string();+ }+ }+ // Bare id: find the (preferentially reachable, credentialed) provider that+ // offers it, matching `resolve_upstream_for_model`'s deterministic pick.+ let offers = |c: &&crate::core::state::ProviderConfig| c.models.iter().any(|m| m == model);+ let reachable = pc+ .iter()+ .filter(|(_, c)| is_cli_reachable(c) && offers(c))+ .min_by_key(|(name, c)| (std::cmp::Reverse(c.api_key.is_some()), (*name).clone()))+ .or_else(|| pc.iter().find(|(_, c)| offers(c)));+ match reachable {+ Some((name, _)) if name != model => format!("{name}/{model}"),+ Some(_) => model.to_string(),+ None => model.to_string(),+ }+}+-fn header(app: &App) -> Paragraph<'static> {Paragraph::new(Line::from(header_spans(app)))}@@@ -14065,7 -13684,7 +14930,10 @@@ fn header_spans(app: &App) -> Vec<Span<if app.model.is_empty() {Span::styled(" no model", Style::new().red().bold())} else {- Span::styled(format!(" {}", app.header_model_label()), Style::new().bold())- Span::styled(format!(" {}", app.model), Style::new().bold())++ Span::styled(++ format!(" {}", app.header_model_label()),++ Style::new().bold(),++ )},];// Reasoning-effort badge: `effort high` after the model, so the configured@@@ -14477,9 -14103,9 +15347,9 @@@ fn input_box(app: &App) -> Paragraph<'slet message = format!("{word}…");let mut spans = Vec::with_capacity(6);match wave_glyph() {-- Some(glyph) => spans.extend(-- wave_sweep_line(&message, &glyph, app.spinner_frame, style).spans,-- ),++ Some(glyph) => {++ spans.extend(wave_sweep_line(&message, &glyph, app.spinner_frame, style).spans)++ }None => {spans.push(Span::styled(format!("{} ", app.spinner()),@@@ -14686,50 -14314,44 +15564,37 @@@ mod testsfn no_mcp() -> crate::core::state::SharedMcpServers {std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()))}++ use super::journal::{self, DisplayEntry};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,-- diff_lines, Row, group_detail_lines, group_summary, handle_ask_key,-- handle_ask_mouse, handle_key, handle_mouse, image_mime, input_content_lines,- route_paste_event,- compact_tokens, finish_account_login, finish_compaction, finish_login, finish_update_install,- route_paste_event, resume_hint,- compact_tokens, finish_compaction, finish_login, finish_update_install,-- image_mime_of, load_first_file_image, load_image_file, MAX_IMAGE_BYTES,-- message_text, CompactKind, MAX_OVERFLOW_RETRIES,- estimate_token_count, header_spans,- provider_label_for_model,- estimate_token_count, header_spans, status_panel, SubagentPanel,-- note_update, open_config_screen, spawn_branch_poll, await_branch_poll,-- parse_command, partial_json_field, restore_goal, restore_run_mode, restore_todos,-- McpPrompt, McpField, pairs_to_str,-- ProviderField,-- autoscroll_selection, selection_text, Selection, SelectionMode, COPY_NOTICE,- startup_modes, KITTY_KEYS_OFF, KITTY_KEYS_ON,- backgrounded_job_id,- apply_stream_event,- drain_stream_events,- run_command,- starting_call_lines,- startup_modes, sync_output_for, KITTY_KEYS_OFF, KITTY_KEYS_ON,- backgrounded_job_id, drain_stream_events, run_command, starting_call_lines,-- unescape_partial_json_string,-- running_group_rows, split_reasoning, strip_system_xml_tags, subagent_activity,-- answer_without_reasoning, assistant_runs, replay_display_log, thinking_open,-- without_think_tags, ReasoningSeg,-- subagent_name_from_run_id, summarize_result, tilde_path, tokens_per_second,-- tool_activity, tool_finished,-- transcript_top_padding, rewind_to, open_rewind_picker, rebuild_recall,-- row_width, user_content_parts, App, CurrentRun, Pending, PendingImage, PickerKind,-- ResumeTarget, RowKind, finish_plugin_install,-- SnapshotJob, Status, AGENT_SETTINGS, ALT_SCROLL_RESTORE, ALT_SCROLL_SAVE_OFF,-- DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS, DIFF_PREVIEW_MAX_ROWS,-- KEY_BINDINGS, MOUSE_TRACK_ON, SLASH_COMMANDS, SPINNER, PROVIDERS_SETTINGS_ROW,++ age_closed_todos, alt_scroll_restore, alt_scroll_save_off, answer_without_reasoning,++ apply_resume, apply_stream_event, assistant_is_awaiting_user_answer, assistant_runs,++ autoscroll_selection, await_branch_poll, backgrounded_job_id, brand, build_user_message,++ clipboard_path, compact_tokens, diff_lines, drain_stream_events, estimate_token_count,++ finish_account_login, finish_compaction, finish_login, finish_plugin_install,++ finish_tokamak_login, finish_update_install, group_detail_lines, group_summary,++ handle_ask_key, handle_ask_mouse, handle_key, handle_mouse, header_spans, image_mime,++ image_mime_of, input_content_lines, load_first_file_image, load_image_file, message_text,++ note_update, open_config_screen, open_rewind_picker, pairs_to_str, parse_command,++ partial_json_field, provider_label_for_model, rebuild_recall, replay_display_log,++ restore_goal, restore_run_mode, restore_todos, resume_hint, rewind_to, route_paste_event,++ row_width, run_command, running_group_rows, selection_text, spans_width, spawn_branch_poll,++ split_reasoning, starting_call_lines, startup_modes, strip_system_xml_tags,++ subagent_activity, subagent_name_from_run_id, summarize_result, sync_output_for,++ thinking_open, tilde_path, tokens_per_second, tool_activity, tool_finished,++ transcript_top_padding, unescape_partial_json_string, user_content_parts, wave_sweep_line,++ with_wave_glyph, without_think_tags, App, CompactKind, CurrentRun, McpField, McpPrompt,++ Pending, PendingImage, PickerKind, ProviderField, ReasoningSeg, ResumeTarget, Row, RowKind,++ Selection, SelectionMode, SnapshotJob, Status, AGENT_SETTINGS, ALT_SCROLL_RESTORE,++ ALT_SCROLL_SAVE_OFF, COPY_NOTICE, DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS,++ DIFF_PREVIEW_MAX_ROWS, KEY_BINDINGS, KITTY_KEYS_OFF, KITTY_KEYS_ON, MAX_IMAGE_BYTES,++ MAX_OVERFLOW_RETRIES, MOUSE_TRACK_ON, PROVIDERS_SETTINGS_ROW, SLASH_COMMANDS, SPINNER,SPINNER_ADVANCE_MS, THINKING_WORDS, WORKING_WORDS,-- alt_scroll_restore, alt_scroll_save_off, spans_width, wave_sweep_line, with_wave_glyph,};-- use unicode_width::UnicodeWidthStr;use crate::core::agent::events::{StreamEvent, Usage};use crate::core::agent::r#loop::PermissionRegistry;use crate::core::cli::updater::{AvailableUpdate, UpdateOutcome};- use super::journal::{self, DisplayEntry};+ use ratatui::buffer::Buffer;use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,MouseEventKind,@@@ -14739,12 -14362,11 +15604,12 @@@style::{Color, Modifier, Style},text::Line,};-- use tauri_plugin_agent_tools::tools::gate::PermissionDecision;use serde_json::json;use std::collections::HashMap;use std::sync::Arc;use std::time::{Duration, Instant};-++ use tauri_plugin_agent_tools::tools::gate::PermissionDecision;++ use unicode_width::UnicodeWidthStr;/// A bare key press with no modifiers.fn key(code: KeyCode) -> KeyEvent {@@@ -14801,7 -14423,6 +15666,8 @@@let dir = tempfile::tempdir().unwrap();let limits = SessionLimits {context_window: 128_000,- context_window_source: crate::core::cli::model_capabilities::ContextWindowSource::Fallback,++ context_window_source:++ crate::core::cli::model_capabilities::ContextWindowSource::Fallback,reserve_tokens: 16_384,max_tokens: None,max_session_tokens: 128_000,@@@ -15331,8 -14908,8 +16197,7 @@@app.push_user_line("first line\nsecond line", &[]);let rows = render_rows(&mut app, 60, 12);assert!(-- rows.iter()-- .any(|r| r.trim_end().ends_with("> first line")),++ rows.iter().any(|r| r.trim_end().ends_with("> first line")),"first line not on its own row: {rows:?}");assert!(@@@ -15482,10 -15060,8 +16348,10 @@@let error = "verification failed: the upstream returned 502 Bad Gateway \from https://api.tokamak.sh/v1/models after three attempts";app.login = Some(super::LoginPrompt {+ provider: "tokamak".to_string(),+ input: String::new(),error: Some(error.to_string()),- verifying: false,- ..super::LoginPrompt::new()++ ..super::LoginPrompt::new("tokamak")});let rows = render_rows(&mut app, 56, 24);let joined = rows.join(" ");@@@ -15532,13 -15108,13 +16398,15 @@@}}--/// Degenerate frames (a sliver of a terminal mid-drag) must render, not panic.#[test]fn tiny_frames_render_without_panicking() {let mut app = test_app();app.push_user_line("hello", &[]);-- app.push_assistant_blocks("| a | b |\n|---|---|\n| 1 | 2 |\n\n```rs\nlet x = 1;\n```", &[]);++ app.push_assistant_blocks(++ "| a | b |\n|---|---|\n| 1 | 2 |\n\n```rs\nlet x = 1;\n```",++ &[],++ );app.apply(StreamEvent::ToolResult {id: "x".into(),content: "done".into(),@@@ -15708,6 -15284,28 +16577,32 @@@assert!(app.ask_queue.is_empty());}+ #[test]+ fn ask_resolved_dismisses_only_the_matching_prompt() {+ let mut app = test_app();+ app.apply(StreamEvent::AskRequest {+ request_id: "keep".into(),+ request: ask_request(false, false),+ timeout_secs: None,+ });+ app.apply(StreamEvent::AskRequest {+ request_id: "gone".into(),+ request: ask_request(false, false),+ timeout_secs: None,+ });+ assert_eq!(app.ask_queue.len(), 2);++ app.apply(StreamEvent::AskResolved {+ request_id: "gone".into(),+ });- assert_eq!(app.ask_queue.len(), 1, "only the timed-out prompt is dropped");++ assert_eq!(++ app.ask_queue.len(),++ 1,++ "only the timed-out prompt is dropped"++ );+ assert_eq!(app.ask_queue.front().unwrap().request_id, "keep");+ }+#[tokio::test]async fn ask_keyboard_accepts_repeated_key_events() {let mut app = test_app();@@@ -15882,18 -15490,92 +16784,94 @@@assert!(app.input.is_empty(), "paste leaked into chat composer");}+ /// A `PendingAsk` built from a `timeout_secs: Some(n)` event carries a+ /// deadline roughly `n` seconds out, and one with `None` carries none.#[test]- fn paste_event_routes_to_chat_composer_without_login_or_ask() {- let mut app = test_app();-- route_paste_event(&mut app, Event::Paste("chat text".into()));+ fn pending_ask_deadline_tracks_configured_timeout() {+ let req = ask_request(false, false);+ let none = super::PendingAsk::new("r1".into(), req.clone(), None);+ assert_eq!(none.deadline, None, "no timeout should mean no deadline");- assert_eq!(app.input, "chat text");+ let short = super::PendingAsk::new(+ "r2".into(),+ req.clone(),+ Some(std::time::Duration::from_secs(30)),+ );+ let deadline = short.deadline.expect("a deadline should be set");+ let now = std::time::Instant::now();+ let slack = deadline.duration_since(now).as_secs_f64();+ assert!(+ (slack - 30.0).abs() < 1.0,+ "deadline should be ~30s out, got {slack:.1}s"+ );+ }++ /// `remaining_secs` rounds the leftover time UP (ceil): a sub-second+ /// remainder still reads `1s`, never `0s`, so a still-live prompt never+ /// claims it is out of time.+ #[test]+ fn pending_ask_remaining_seconds_rounds_up_and_stops_at_deadline() {+ let req = ask_request(false, false);- let ask = super::PendingAsk::new(- "r1".into(),- req,- Some(std::time::Duration::from_secs(30)),- );++ let ask =++ super::PendingAsk::new("r1".into(), req, Some(std::time::Duration::from_secs(30)));+ let deadline = ask.deadline.unwrap();+ // 500ms before the deadline: ceil -> 1s.+ let early = deadline - std::time::Duration::from_millis(500);+ assert_eq!(ask.remaining_secs(early), Some(1), "ceil, not floor");+ // Well before: whole seconds.+ let far = deadline - std::time::Duration::from_secs(27);+ assert_eq!(ask.remaining_secs(far), Some(27));+ // At/after the deadline: no remaining time.+ assert_eq!(ask.remaining_secs(deadline), None);- assert_eq!(ask.remaining_secs(deadline + std::time::Duration::from_secs(1)), None);++ assert_eq!(++ ask.remaining_secs(deadline + std::time::Duration::from_secs(1)),++ None++ );}+ /// The ask box title carries the live countdown when a timeout is set, and+ /// omits it when none is.#[test]- fn split_reasoning_separates_think_blocks() {- let segs = split_reasoning("before<think>hidden</think>after");+ fn ask_title_counts_down_the_configured_deadline() {+ let mut app = test_app();+ let req = ask_request(false, false);- app.ask_queue- .push_back(super::PendingAsk::new(- "r1".into(),- req,- Some(std::time::Duration::from_secs(120)),- ));++ app.ask_queue.push_back(super::PendingAsk::new(++ "r1".into(),++ req,++ Some(std::time::Duration::from_secs(120)),++ ));+ let join = render_rows(&mut app, 60, 24).join("\n");+ assert!(+ join.contains("question 1/1") && join.contains("120s"),+ "title should show the countdown, got {join:?}"+ );++ // No timeout: no countdown segment at all.+ let mut app = test_app();- app.ask_queue- .push_back(super::PendingAsk::new("r2".into(), ask_request(false, false), None));++ app.ask_queue.push_back(super::PendingAsk::new(++ "r2".into(),++ ask_request(false, false),++ None,++ ));+ let join = render_rows(&mut app, 60, 24).join("\n");+ assert!(+ join.contains("question 1/1") && !join.contains("120s") && !join.contains("s\u{b7}"),+ "no-timeout title should omit the countdown, got {join:?}"+ );+ }++ #[test]+ fn paste_event_routes_to_chat_composer_without_login_or_ask() {+ let mut app = test_app();++ route_paste_event(&mut app, Event::Paste("chat text".into()));++ assert_eq!(app.input, "chat text");+ }++ #[test]+ fn split_reasoning_separates_think_blocks() {+ let segs = split_reasoning("before<think>hidden</think>after");assert_eq!(segs,vec![@@@ -15974,7 -15656,7 +16952,10 @@@fn a_split_journal_entry_replays_prose_and_reasoning_apart() {let entry = DisplayEntry::Assistant {text: "Answer.".into(),-- reasoning: vec![ReasoningSeg { at: 0, text: "a thought".into() }],++ reasoning: vec![ReasoningSeg {++ at: 0,++ text: "a thought".into(),++ }],};let round_tripped: DisplayEntry =serde_json::from_str(&serde_json::to_string(&entry).unwrap()).unwrap();@@@ -16009,8 -15691,8 +16990,14 @@@#[test]fn assistant_runs_interleaves_native_reasoning_by_offset() {let segs = vec![-- ReasoningSeg { at: 0, text: "first".into() },-- ReasoningSeg { at: 6, text: "second".into() },++ ReasoningSeg {++ at: 0,++ text: "first".into(),++ },++ ReasoningSeg {++ at: 6,++ text: "second".into(),++ },];assert_eq!(assistant_runs("prose tail", &segs),@@@ -16109,7 -15798,7 +17096,10 @@@// With show_reasoning on, folding is off entirely and it renders whole.app.show_reasoning = true;let shown = render_rows(&mut app, 60, 30).join("\n");-- assert!(shown.contains("pondering"), "revealed live tail must contain it");++ assert!(++ shown.contains("pondering"),++ "revealed live tail must contain it"++ );}/// A long chain of thought must not push the answer, or the conversation@@@ -16117,13 -15806,13 +17107,7 @@@#[test]fn live_tail_bounds_streaming_reasoning_to_its_last_lines() {let body: String = (1..=20).map(|n| format!("step {n}\n")).collect();-- let lines = super::live_assistant_lines(-- &format!("<think>{body}"),-- &[],-- 60,-- true,-- true,-- );++ let lines = super::live_assistant_lines(&format!("<think>{body}"), &[], 60, true, true);let text: Vec<String> = lines.iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())@@@ -16153,7 -15842,7 +17137,10 @@@"a pre-wrapped tail must not re-wrap ({n} words)");assert!(rows <= 6, "tail grew to {rows} rows ({n} words)");-- assert!(rows >= seen, "tail shrank from {seen} to {rows} rows ({n} words)");++ assert!(++ rows >= seen,++ "tail shrank from {seen} to {rows} rows ({n} words)"++ );seen = rows;}assert_eq!(seen, 6, "tail never filled to its cap");@@@ -16578,6 -16250,184 +17565,192 @@@);}+ /// Backdate a call's first-output stamp past [`LIVE_OUTPUT_GRACE`], so a test+ /// renders the panel a long-running command would have without sleeping.+ fn age_live_output(app: &mut App, id: &str) {+ let since = app.live_since.get_mut(id).expect("call has streamed");+ *since -= super::LIVE_OUTPUT_GRACE;+ }++ /// A running command is a terminal, not a spinner: its output appears under+ /// the activity row as it is produced, framed and prefixed by the command.+ #[test]+ fn a_running_command_shows_its_output_live() {+ let mut app = test_app();+ app.apply(StreamEvent::ToolCall {+ id: "t1".into(),+ name: "bash".into(),+ args: json!({ "command": "make" }),+ });+ // Nothing printed yet: the activity row stands alone rather than opening+ // an empty box.+ let quiet = render_rows(&mut app, 70, 16).join("\n");+ assert!(!quiet.contains("$ make"), "no box before output: {quiet}");++ app.apply(StreamEvent::ToolOutputDelta {+ id: "t1".into(),+ delta: "compiling foo\n".into(),+ });+ app.apply(StreamEvent::ToolOutputDelta {+ id: "t1".into(),+ delta: "compiling bar\n".into(),+ });+ // Still inside the grace window: a command this brief would only flash.+ let brief = render_rows(&mut app, 70, 16).join("\n");+ assert!(!brief.contains("$ make"), "no box while brief: {brief}");++ age_live_output(&mut app, "t1");+ let live = render_rows(&mut app, 70, 16).join("\n");+ assert!(+ live.contains("$ make"),+ "command on the prompt line: {live}"+ );+ assert!(live.contains("compiling foo"), "first chunk: {live}");+ assert!(live.contains("compiling bar"), "and the next: {live}");+ assert!(live.contains('\u{250c}'), "framed: {live}");+ }++ /// The result is the authoritative output, so the live buffer is released+ /// with it -- a long session must not accumulate every command it ran.+ #[test]+ fn a_finished_command_releases_its_live_buffer() {+ let mut app = test_app();+ app.apply(StreamEvent::ToolCall {+ id: "t1".into(),+ name: "bash".into(),+ args: json!({ "command": "make" }),+ });+ app.apply(StreamEvent::ToolOutputDelta {+ id: "t1".into(),+ delta: "compiling foo\n".into(),+ });+ app.apply(StreamEvent::ToolResult {+ id: "t1".into(),+ content: "compiling foo\n[exit 0]".into(),+ is_error: false,+ diff: None,+ });+ assert!(+ !app.live_output.contains_key("t1"),+ "the finished call still holds its buffer"+ );+ }++ /// A group runs its calls in parallel, so the panel follows the call that is+ /// actually printing. Keying it to the newest unresolved call instead made a+ /// `read` issued after a long `bash` blank the box until the read landed.+ #[test]+ fn a_later_call_does_not_blank_the_live_panel() {+ let mut app = test_app();+ app.apply(StreamEvent::ToolCall {+ id: "t1".into(),+ name: "bash".into(),+ args: json!({ "command": "make" }),+ });+ app.apply(StreamEvent::ToolOutputDelta {+ id: "t1".into(),+ delta: "compiling foo\n".into(),+ });+ age_live_output(&mut app, "t1");+ app.apply(StreamEvent::ToolCall {+ id: "t2".into(),+ name: "read".into(),+ args: json!({ "path": "src/main.rs" }),+ });+ let live = render_rows(&mut app, 70, 18).join("\n");+ assert!(+ live.contains("compiling foo"),+ "the streaming call keeps the panel: {live}"+ );+ }++ /// The wait on a backgrounded job is the case the live view matters most for.+ /// The job streams under the id of the call that *started* it while the user+ /// watches the later call that *collects* it, so the two are aliased.+ #[test]+ fn waiting_on_a_backgrounded_job_shows_its_live_output() {+ let mut app = test_app();+ app.apply(StreamEvent::ToolCall {+ id: "t1".into(),+ name: "bash".into(),+ args: json!({ "command": "cargo test" }),+ });+ app.apply(StreamEvent::ToolResult {+ id: "t1".into(),+ content: "Command exceeded 30s and is continuing in the background \+ (job_id=bash-7)."+ .into(),+ is_error: false,+ diff: None,+ });+ // Backgrounded, so the buffer survives its own result.+ app.apply(StreamEvent::ToolOutputDelta {+ id: "t1".into(),+ delta: "test tui::rolls ... ok\n".into(),+ });+ app.apply(StreamEvent::ToolCall {+ id: "t2".into(),+ name: "bash".into(),+ args: json!({ "job_id": "bash-7" }),+ });+ assert_eq!(+ app.live_alias.get("t2").map(String::as_str),+ Some("t1"),+ "the collecting call is aliased to the job's origin"+ );+ app.apply(StreamEvent::ToolOutputDelta {+ id: "t1".into(),+ delta: "test tui::folds ... ok\n".into(),+ });+ age_live_output(&mut app, "t1");+ let live = render_rows(&mut app, 74, 20).join("\n");+ assert!(+ live.contains("test tui::folds ... ok"),+ "the waiting row reports the job's progress: {live}"+ );+ }++ /// A runaway command must not grow the TUI's memory without bound.+ #[test]+ fn live_output_is_bounded() {+ let mut app = test_app();+ app.apply(StreamEvent::ToolOutputDelta {+ id: "t1".into(),+ delta: "x".repeat(super::LIVE_OUTPUT_MAX_BYTES * 2),+ });+ let held = app.live_output.get("t1").expect("buffered").len();+ assert!(held <= super::LIVE_OUTPUT_MAX_BYTES, "kept {held} bytes");+ }++ /// Only a bounded tail is rendered, so a chatty command cannot push the+ /// conversation off the screen.+ #[test]+ fn the_live_panel_renders_only_a_bounded_tail() {+ let many: String = (0..60).map(|i| format!("line {i}\n")).collect();+ let rows = super::shell_panel_lines("make", &many, 70, "\u{2502} ");+ assert!(+ rows.len() <= super::LIVE_OUTPUT_TAIL_LINES + 4,+ "unbounded panel: {} rows",+ rows.len()+ );+ let text = rows+ .iter()- .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>())++ .map(|l| {++ l.spans++ .iter()++ .map(|s| s.content.as_ref())++ .collect::<String>()++ })+ .collect::<Vec<_>>()+ .join("\n");+ assert!(text.contains("line 59"), "the newest line shows: {text}");+ assert!(!text.contains("line 0\n"), "the oldest is elided: {text}");- assert!(text.contains("earlier lines"), "elision is reported: {text}");++ assert!(++ text.contains("earlier lines"),++ "elision is reported: {text}"++ );+ }+#[test]fn tool_activity_is_concise_present_tense() {assert_eq!(@@@ -17660,617 -17497,556 +18896,1134 @@@}#[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();- open_paste_field(&mut app).await;- assert!(app.login.is_some(), "the paste prompt must be open");-- 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("sign in to Jan"), "{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();- open_paste_field(&mut app).await;- app.login.as_mut().unwrap().paste(" tk-abc\n");- press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ run_command(&mut app, "help", &no_mcp()).await;- assert_eq!(app.login_submit.as_deref(), Some("tk-abc"));- assert!(app.login.as_ref().unwrap().verifying);+ 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_rejects_a_mispasted_key_before_any_request() {+ #[test]+ fn login_empty_state_points_to_provider_picker_without_stale_tokamak_copy() {let mut app = test_app();- open_paste_field(&mut app).await;- type_key_chars(&mut app, "tk-abc def").await;- press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ app.model.clear();- 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());+ app.submit_user("hello".to_string());- // Empty input is likewise not worth a round trip.- press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;- assert!(app.login_submit.is_none());+ 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_backspace_edits_and_esc_cancels() {- let mut app = test_app();- open_paste_field(&mut app).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());- }+ 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();- #[tokio::test]- async fn login_stays_cancellable_while_verifying() {- let mut app = test_app();- open_paste_field(&mut app).await;- app.login.as_mut().unwrap().paste("tk-abc");- press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;- app.login_submit.take();+ 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();- // 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:?}");+ let result = crate::core::agent::global_config::with_temp_home(|_| f());- press(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL).await;- assert!(app.login.is_none(), "Ctrl-C must not wedge the prompt");+ 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 failed_verification_keeps_the_prompt_open_with_the_reason() {- let mut app = test_app();- open_paste_field(&mut app).await;- app.login.as_mut().unwrap().paste("tk-abc");- press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;- app.login_submit.take();+ #[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,++ ..Default::default()+ },+ )+ .unwrap();- 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."));+ 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<_>>()++ 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_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_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"- );++ open_paste_field(&mut app).await;++ assert!(app.login.is_some(), "the paste prompt must be open");++ 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");++ open_paste_field(&mut app).await;+ 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");++ open_paste_field(&mut app).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();- super::open_login_prompt(&mut app, "tokamak");++ open_paste_field(&mut app).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_prompt_esc_cancels_without_outcome_message() {+ let mut app = test_app();+ super::open_login_prompt(&mut app, "tokamak");+ let before = app.transcript.len();++ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;++ assert!(app.login.is_none(), "Esc must close the prompt");+ assert!(app.login_submit.is_none());+ assert_eq!(+ app.transcript.len(),+ before,+ "cancellation must stay silent"+ );+ }++ #[tokio::test]+ async fn login_stays_cancellable_while_verifying() {+ let mut app = test_app();- super::open_login_prompt(&mut app, "tokamak");++ open_paste_field(&mut app).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");+ assert!(app.login_submit.is_none());+ }++ #[tokio::test]+ async fn failed_verification_keeps_the_prompt_open_with_the_reason() {+ let mut app = test_app();- super::open_login_prompt(&mut app, "tokamak");++ open_paste_field(&mut app).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(crate::core::cli::auth::LoginError::Unavailable(+ "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 sign-in failed: Tokamak rejected that API key.")+ );+ }++ #[tokio::test]+ async fn esc_cancels_a_pending_account_sign_in() {+ let mut app = test_app();+ super::open_account_login(&mut app, "openai");+ assert!(app.account_login.is_some());+ assert!(app.account_login_submit.is_some());++ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;++ assert!(app.account_login.is_none());+ assert!(app.account_login_submit.is_none());+ assert!(app.account_login_manual_tx.is_none());+ assert!(!transcript_text(&app).contains("cancelled"));+ assert!(!transcript_text(&app).contains("failed"));+ assert!(!transcript_text(&app).contains("signed in"));+ }++ #[tokio::test]+ async fn account_prompt_captures_manual_input_and_never_renders_secrets() {+ let mut app = test_app();+ super::open_account_login(&mut app, "openai");+ let state = app.account_login.as_ref().unwrap().login.state.clone();+ let verifier = app.account_login.as_ref().unwrap().login.verifier.clone();+ let authorization_url = app+ .account_login+ .as_ref()+ .unwrap()+ .login+ .authorization_url+ .clone();+ let manual = format!("authorization-code#{state}");++ for ch in manual.chars() {+ press(&mut app, KeyCode::Char(ch), KeyModifiers::NONE).await;+ }++ let prompt = app.account_login.as_ref().unwrap();+ assert_eq!(prompt.input, manual);+ assert_eq!(prompt.masked().chars().count(), 32);+ let screen = render_rows(&mut app, 100, 24).join("\n");+ assert!(screen.contains("Codex sign-in"), "{screen}");- assert!(screen.contains("authorization: https://auth.openai.com/oauth/authorize"), "{screen}");- assert!(screen.contains("callback: http://localhost:1455/auth/callback"), "{screen}");++ assert!(++ screen.contains("authorization: https://auth.openai.com/oauth/authorize"),++ "{screen}"++ );++ assert!(++ screen.contains("callback: http://localhost:1455/auth/callback"),++ "{screen}"++ );+ assert!(!screen.contains("authorization-code"), "{screen}");+ assert!(!screen.contains(&state), "{screen}");+ assert!(!screen.contains(&verifier), "{screen}");+ assert!(!screen.contains(&authorization_url), "{screen}");+ assert!(!screen.contains("code_challenge"), "{screen}");+ }++ #[tokio::test]+ async fn account_enter_rejects_bad_manual_input_before_sending() {+ let mut app = test_app();+ super::open_account_login(&mut app, "openai");- app.account_login.as_mut().unwrap().paste("authorization-code#wrong-state");++ app.account_login++ .as_mut()++ .unwrap()++ .paste("authorization-code#wrong-state");++ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;++ let prompt = app.account_login.as_ref().unwrap();+ assert!(!prompt.submitting);+ assert!(prompt.input.is_empty());- assert_eq!(prompt.error.as_deref(), Some("the redirect state did not match"));++ assert_eq!(++ prompt.error.as_deref(),++ Some("the redirect state did not match")++ );+ }++ #[tokio::test]+ async fn account_enter_sends_manual_input_to_active_task_sender() {+ let mut app = test_app();+ super::open_account_login(&mut app, "openai");+ let state = app.account_login.as_ref().unwrap().login.state.clone();+ let manual = format!("authorization-code#{state}");+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ app.account_login_manual_tx = Some(tx);+ app.account_login.as_mut().unwrap().paste(&manual);++ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;++ assert_eq!(rx.recv().await.as_deref(), Some(manual.as_str()));+ assert!(app.account_login.as_ref().unwrap().submitting);+ }++ #[tokio::test]+ async fn account_enter_retries_after_task_failure() {+ let mut app = test_app();+ super::open_account_login(&mut app, "openai");- finish_account_login(&mut app, Err("could not discover account models".to_string()));++ finish_account_login(++ &mut app,++ Err("could not discover account models".to_string()),++ );+ let state = app.account_login.as_ref().unwrap().login.state.clone();+ app.account_login_submit = None;+ let manual = format!("authorization-code#{state}");+ app.account_login.as_mut().unwrap().paste(&manual);++ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;++ let (mut rx, has_pending) = super::account_login_manual_channel(&mut app);+ assert!(has_pending);+ assert_eq!(rx.recv().await.as_deref(), Some(manual.as_str()));+ assert!(app.account_login.as_ref().unwrap().submitting);+ assert!(app.account_login_submit.is_some());+ assert!(app.account_login_pending_manual_input.is_none());+ }++ #[tokio::test]+ async fn account_retry_keeps_pending_manual_input_after_failure_result() {+ let mut app = test_app();+ super::open_account_login(&mut app, "openai");+ let (rx, _) = super::account_login_manual_channel(&mut app);+ drop(rx);+ let state = app.account_login.as_ref().unwrap().login.state.clone();+ let manual = format!("authorization-code#{state}");+ app.account_login.as_mut().unwrap().paste(&manual);++ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(+ app.account_login_pending_manual_input.as_deref(),+ Some(manual.as_str())+ );+- finish_account_login(&mut app, Err("could not discover account models".to_string()));++ finish_account_login(++ &mut app,++ Err("could not discover account models".to_string()),++ );++ assert_eq!(+ app.account_login_pending_manual_input.as_deref(),+ Some(manual.as_str()),+ "failed old task result must not clear input queued for retry"+ );+ let (mut rx, has_pending) = super::account_login_manual_channel(&mut app);+ assert!(has_pending);+ assert_eq!(rx.recv().await.as_deref(), Some(manual.as_str()));+ assert!(app.account_login_pending_manual_input.is_none());+ }++ #[test]+ fn account_login_completion_handles_success_failure_and_stale_results() {+ crate::core::agent::global_config::with_temp_home(|_| {+ crate::core::agent::global_config::set_provider(+ "openai",+ crate::core::agent::global_config::ProviderUpdate {+ api_key: None,+ clear_api_key: true,+ base_url: Some("https://api.openai.com/v1".into()),+ models: Some(vec!["gpt-4o-mini".into()]),+ api_type: None,++ ..Default::default()+ },+ )+ .unwrap();+ let mut app = test_app();+ super::open_account_login(&mut app, "openai");++ finish_account_login(&mut app, Ok("openai".to_string()));+ let text = transcript_text(&app);+ assert!(+ text.contains("signed in to openai. Use /model to select a model."),+ "{text}"+ );+ assert!(app.account_login.is_none());+ assert_eq!(app.model, "gpt-4o-mini");+ });++ let mut app = test_app();+ finish_account_login(&mut app, Ok("openai".to_string()));+ assert!(+ !transcript_text(&app).contains("signed in"),+ "stale result must stay silent"+ );++ let mut app = test_app();+ super::open_account_login(&mut app, "anthropic");+ finish_account_login(+ &mut app,+ Err("the redirect state did not match".to_string()),+ );+ let prompt = app.account_login.as_ref().expect("prompt stays open");+ assert_eq!(+ prompt.error.as_deref(),+ Some("anthropic sign-in failed: could not complete browser sign-in")+ );+ assert!(!prompt.submitting);+ assert!(!transcript_text(&app).contains("signed in to anthropic"));+ }++ #[test]+ fn account_login_failure_sanitizes_callback_and_secret_details() {+ let mut app = test_app();+ super::open_account_login(&mut app, "anthropic");++ finish_account_login(+ &mut app,+ Err("could not save provider configuration to /Users/alice/.jan/config.toml after callback code=callback-code-do-not-render with client_secret=sk-secret-do-not-render access_token=tok-secret-do-not-render scope=openid profile model.write model=claude-3 provider_payload={\"error\":\"invalid_grant\"}".to_string()),+ );++ let screen = render_rows(&mut app, 100, 24).join("\n");+ assert!(+ screen.contains("anthropic sign-in failed: could not complete browser sign-in"),+ "{screen}"+ );- assert!(!screen.contains("/Users/alice/.jan/config.toml"), "{screen}");++ assert!(++ !screen.contains("/Users/alice/.jan/config.toml"),++ "{screen}"++ );+ assert!(!screen.contains("callback-code-do-not-render"), "{screen}");+ assert!(!screen.contains("sk-secret-do-not-render"), "{screen}");+ assert!(!screen.contains("tok-secret-do-not-render"), "{screen}");+ assert!(!screen.contains("model.write"), "{screen}");+ assert!(!screen.contains("claude-3"), "{screen}");+ assert!(!screen.contains("invalid_grant"), "{screen}");+ }++ #[test]+ fn claude_account_login_warns_about_third_party_use() {+ crate::core::agent::global_config::with_temp_home(|_| {+ crate::core::agent::global_config::set_provider(+ "anthropic",+ crate::core::agent::global_config::ProviderUpdate {+ api_key: None,+ clear_api_key: true,+ base_url: Some("https://api.anthropic.com/v1".into()),+ models: Some(vec!["claude-sonnet-5".into()]),+ api_type: Some("anthropic".into()),++ ..Default::default()+ },+ )+ .unwrap();+ let mut app = test_app();+ super::open_account_login(&mut app, "anthropic");+ super::finish_account_login(&mut app, Ok("anthropic".to_string()));+ let text = transcript_text(&app);+ assert!(+ text.contains("signed in to anthropic. Use /model to select a model."),+ "{text}"+ );+ assert!(+ text.contains("third-party client"),+ "Claude success must warn about third-party use: {text}"+ );+ assert!(+ text.contains("Terms of Service"),+ "Claude warning must mention the ToS: {text}"+ );+ assert!(+ text.contains("own risk"),+ "Claude warning must flag user risk: {text}"+ );+ });+ }++ #[test]+ fn account_login_begin_failure_uses_safe_provider_message() {+ let mut app = test_app();++ super::open_account_login_with_begin(&mut app, "anthropic", |_| {+ Err("could not create callback from /Users/alice/.jan/config.toml with client_secret=sk-secret-do-not-render".to_string())+ });++ let text = transcript_text(&app);+ assert!(+ text.contains("anthropic sign-in failed: could not complete browser sign-in"),+ "{text}"+ );+ assert!(!text.contains("/Users/alice/.jan/config.toml"), "{text}");+ assert!(!text.contains("sk-secret-do-not-render"), "{text}");+ assert!(app.account_login.is_none());+ assert!(app.account_login_submit.is_none());}+ /// `/login --paste-token` skips straight to the legacy field, the same+ /// escape hatch `jan login --paste-token` gives, and never asks the loop for+ /// a browser session.+ #[tokio::test]+ async fn login_paste_token_forces_the_legacy_field() {+ let mut app = test_app();+ run_command(&mut app, "login --paste-token", &no_mcp()).await;+ let prompt = app.login.as_ref().expect("dock open");+ assert!(matches!(+ prompt.stage,+ super::LoginStage::Paste { confirm_open: true }+ ));- assert!(!app.login_device_request, "no browser session may be started");++ assert!(++ !app.login_device_request,++ "no browser session may be started"++ );++ // The field opens only once the browser question is answered.- assert!(!prompt.editable(), "no key entry before the browser question");++ assert!(++ !prompt.editable(),++ "no key entry before the browser question"++ );+ press(&mut app, KeyCode::Char('n'), KeyModifiers::NONE).await;+ assert!(app.login.as_ref().unwrap().editable());+ }++ /// Nothing may reach a browser until the user says so -- in either flow.+ #[tokio::test]+ async fn the_browser_is_never_opened_without_an_answer() {+ // Paste fallback.+ let mut app = test_app();- super::open_login_prompt(&mut app);++ super::open_login_prompt(&mut app, "tokamak");+ let prompt = app.login.as_ref().unwrap();+ assert_eq!(+ prompt.stage.unconfirmed_url(),+ Some(crate::core::cli::tokamak::API_KEYS_URL)+ );+ let screen = render_rows(&mut app, 80, 24).join("\n");- assert!(screen.contains("open this page in your browser?"), "{screen}");++ assert!(++ screen.contains("open this page in your browser?"),++ "{screen}"++ );++ // Browser approval.+ let mut app = test_app();+ super::show_login_approval(&mut app, &test_session());+ assert_eq!(+ app.login.as_ref().unwrap().stage.unconfirmed_url(),+ Some("https://tokamak.sh/cli/authorize?code=ABCD-2345")+ );+ let screen = render_rows(&mut app, 80, 24).join("\n");- assert!(screen.contains("open this page in your browser?"), "{screen}");++ assert!(++ screen.contains("open this page in your browser?"),++ "{screen}"++ );+ // The code is still shown while the question is up: the user may prefer+ // to approve on a phone and never open a browser here at all.+ assert!(screen.contains("ABCD-2345"), "{screen}");+ }++ /// Declining does not abandon the sign-in: the poll is already running, so+ /// the dock moves on to waiting and a phone can still approve it.+ #[tokio::test]+ async fn declining_the_browser_still_waits_for_approval() {+ let mut app = test_app();+ super::show_login_approval(&mut app, &test_session());+ press(&mut app, KeyCode::Char('n'), KeyModifiers::NONE).await;++ let prompt = app.login.as_ref().expect("dock stays open");- assert!(prompt.stage.unconfirmed_url().is_none(), "question answered");++ assert!(++ prompt.stage.unconfirmed_url().is_none(),++ "question answered"++ );+ assert!(matches!(+ prompt.stage,+ super::LoginStage::Approving {+ confirm_open: false,+ ..+ }+ ));+ let screen = render_rows(&mut app, 80, 24).join("\n");+ assert!(screen.contains("waiting for approval"), "{screen}");+ }++ /// Esc at the browser question cancels the whole sign-in rather than+ /// answering it, so the question can never wedge the dock.+ #[tokio::test]+ async fn esc_at_the_browser_question_cancels() {+ for open_paste in [true, false] {+ let mut app = test_app();+ if open_paste {- super::open_login_prompt(&mut app);++ super::open_login_prompt(&mut app, "tokamak");+ } else {+ super::show_login_approval(&mut app, &test_session());+ }+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;+ assert!(app.login.is_none(), "Esc must close the dock");+ }+ }++ fn pending_browser(app: &mut App) {+ app.browser_confirm = Some(super::BrowserConfirm {+ url: "https://github.com/login/oauth/authorize?client_id=x".into(),+ purpose: "authorize 'github'".into(),+ });+ }++ /// The `/mcp` question shows what it is for and the URL to open, so+ /// declining still leaves a way to finish.+ #[tokio::test]+ async fn the_mcp_browser_question_shows_the_purpose_and_url() {+ let mut app = test_app();+ pending_browser(&mut app);+ let screen = render_rows(&mut app, 90, 24).join("\n");+ assert!(screen.contains("open a browser?"), "{screen}");+ assert!(screen.contains("authorize 'github'"), "{screen}");- assert!(screen.contains("open this page in your browser?"), "{screen}");- assert!(screen.contains("github.com/login/oauth/authorize"), "{screen}");++ assert!(++ screen.contains("open this page in your browser?"),++ "{screen}"++ );++ assert!(++ screen.contains("github.com/login/oauth/authorize"),++ "{screen}"++ );+ }++ /// Every answer dismisses the question. `browser::open` is disabled under+ /// `cfg(test)`, so the accept path is exercised without a real browser.+ #[tokio::test]+ async fn every_answer_dismisses_the_mcp_browser_question() {+ for key in [+ KeyCode::Enter,+ KeyCode::Char('y'),+ KeyCode::Char('n'),+ KeyCode::Esc,+ ] {+ let mut app = test_app();+ pending_browser(&mut app);+ press(&mut app, key, KeyModifiers::NONE).await;+ assert!(+ app.browser_confirm.is_none(),+ "{key:?} must dismiss the question"+ );+ }+ }++ /// The question owns the keyboard while it is up: a keystroke meant for it+ /// must not land in the chat input.+ #[tokio::test]+ async fn the_mcp_browser_question_owns_the_keyboard() {+ let mut app = test_app();+ pending_browser(&mut app);+ type_key_chars(&mut app, "hello").await;+ assert!(app.browser_confirm.is_some(), "stray keys are not answers");+ assert!(app.input.is_empty(), "nothing may reach the chat input");+ }++ /// An authorization that settles before the user answers takes the stale+ /// question away with it, rather than leaving a dock pointing at a spent URL.+ #[tokio::test]+ async fn a_settled_authorization_clears_a_pending_question() {+ for result in [Ok(()), Err("nope".to_string())] {+ let mut app = test_app();+ pending_browser(&mut app);+ let mut job = None;+ super::finish_mcp_job(+ &mut app,+ super::McpJobDone::Authorized {+ server: "github".into(),+ result,+ },+ &no_mcp(),+ &mut job,+ )+ .await;+ assert!(app.browser_confirm.is_none(), "stale question must go");+ }+ }++ /// The paste field with the browser question already answered -- what most+ /// key-entry tests are actually about.+ /// Accepting launches the opener and moves on. `browser::open` is disabled+ /// under `cfg(test)`, so this exercises the accept path (and its "could not+ /// open" reporting) without hijacking a real browser.+ #[tokio::test]+ async fn accepting_the_browser_question_moves_on_either_way() {+ for accept in [KeyCode::Enter, KeyCode::Char('y')] {+ let mut app = test_app();+ super::show_login_approval(&mut app, &test_session());+ press(&mut app, accept, KeyModifiers::NONE).await;++ let prompt = app.login.as_ref().expect("dock stays open");+ assert!(+ prompt.stage.unconfirmed_url().is_none(),+ "{accept:?} must answer the question"+ );+ let screen = render_rows(&mut app, 80, 24).join("\n");+ assert!(screen.contains("waiting for approval"), "{screen}");+ }++ // Same for the paste fallback: accepting opens the field.+ let mut app = test_app();- super::open_login_prompt(&mut app);++ super::open_login_prompt(&mut app, "tokamak");+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert!(app.login.as_ref().unwrap().editable());+ }++ /// A keystroke that is neither an answer nor a cancel is swallowed, so it+ /// cannot leak into the key field or the chat input.+ #[tokio::test]+ async fn stray_keys_at_the_browser_question_do_nothing() {+ let mut app = test_app();- super::open_login_prompt(&mut app);++ super::open_login_prompt(&mut app, "tokamak");+ type_key_chars(&mut app, "tk-secret").await;++ let prompt = app.login.as_ref().expect("dock stays open");+ assert!(prompt.stage.unconfirmed_url().is_some(), "still unanswered");+ assert!(prompt.input.is_empty(), "no key may be collected yet");+ assert!(app.input.is_empty(), "and nothing may reach the chat input");+ }++ fn confirmed_paste_prompt() -> super::LoginPrompt {+ super::LoginPrompt {- stage: super::LoginStage::Paste { confirm_open: false },- ..super::LoginPrompt::new()++ stage: super::LoginStage::Paste {++ confirm_open: false,++ },++ ..super::LoginPrompt::new("tokamak")+ }+ }++ /// Open the paste fallback and decline the browser, leaving an editable field.+ async fn open_paste_field(app: &mut App) {- super::open_login_prompt(app);++ super::open_login_prompt(app, "tokamak");+ press(app, KeyCode::Char('n'), KeyModifiers::NONE).await;+ }++ fn test_session() -> crate::core::cli::device_auth::Session {+ crate::core::cli::device_auth::Session {+ session_id: "sess-1".into(),+ user_code: "ABCD-2345".into(),+ authorize_url: "https://tokamak.sh/cli/authorize?code=ABCD-2345".into(),+ expires_in: 300,+ interval: 5,+ }+ }++ #[tokio::test]+ async fn login_rejects_an_unknown_option_without_opening_a_dock() {+ let mut app = test_app();+ run_command(&mut app, "login --nope", &no_mcp()).await;+ assert!(app.login.is_none());+ assert!(!app.login_device_request);+ }+- /// `/login` starts the browser flow: the dock opens straight away (so Esc- /// has something to cancel) and the loop is asked for a session.++ /// `/login` opens the provider picker. Selecting Tokamak starts its browser++ /// flow; other providers open their own credential path.+ #[tokio::test]- async fn login_starts_the_browser_flow_and_opens_the_dock() {++ async fn login_opens_the_provider_picker() {+ let mut app = test_app();+ run_command(&mut app, "login", &no_mcp()).await;- let prompt = app.login.as_ref().expect("/login must open the dock");- assert!(matches!(prompt.stage, super::LoginStage::Connecting));- assert!(app.login_device_request, "the loop must be asked to begin");- // No field yet, so nothing may be typed into one.- assert!(!prompt.editable());++ assert_eq!(++ app.picker.as_ref().map(|picker| picker.kind),++ Some(PickerKind::LoginProvider)++ );++ assert!(app.login.is_none());++ assert!(!app.login_device_request);+ }+- /// A second `/login` while a session is being created must not switch the- /// dock: the browser session would land on top of the new one.++ /// A second `/login` while the provider picker is open must not replace it++ /// with a different sign-in flow.+ #[tokio::test]- async fn login_refuses_while_a_sign_in_is_already_in_progress() {++ async fn login_refuses_while_provider_selection_is_in_progress() {+ let mut app = test_app();+ run_command(&mut app, "login", &no_mcp()).await;- app.login_device_request = false;++ run_command(&mut app, "login --paste-token", &no_mcp()).await;- let prompt = app.login.as_ref().expect("the first dock stays open");- assert!(matches!(prompt.stage, super::LoginStage::Connecting));++ assert_eq!(++ app.picker.as_ref().map(|picker| picker.kind),++ Some(PickerKind::LoginProvider)++ );++ assert!(app.login.is_none());+ assert!(!app.login_device_request);+ let transcript = transcript_text(&app);+ assert!(transcript.contains("already in progress"), "{transcript}");+ }++ /// The ask layer is consulted before `handle_key`, so an ask queued by the+ /// running agent must not swallow the secret being typed into `/login` --+ /// a custom answer is submitted to the model.+ #[tokio::test]+ async fn a_queued_ask_never_captures_login_keystrokes() {+ let mut app = test_app();+ let registry = crate::core::agent::interaction::new_registry();+ let (request_id, _receiver) = crate::core::agent::interaction::register(®istry).await;+ open_paste_field(&mut app).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });+ app.ask_queue.front_mut().unwrap().editing_custom = true;++ for ch in "tk-secret".chars() {+ let key = KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE);+ assert!(+ !handle_ask_key(&mut app, key, ®istry).await,+ "the login dock owns the keyboard"+ );+ press(&mut app, KeyCode::Char(ch), KeyModifiers::NONE).await;+ }++ assert_eq!(app.login.as_ref().unwrap().input, "tk-secret");+ assert_eq!(app.ask_queue.front().unwrap().custom_input, "");+ assert!(app.input.is_empty(), "the composer must not see the key");+ }++ fn blank_mcp_prompt() -> super::McpPrompt {+ super::McpPrompt {+ editing: None,+ field: super::McpField::Name,+ name: String::new(),+ transport: "stdio".to_string(),+ command: String::new(),+ args: String::new(),+ env: String::new(),+ url: String::new(),+ headers: String::new(),+ active: false,+ error: None,+ }+ }++ /// A named way to open one keyboard-owning dock, for the table below.+ type DockSetup = (&'static str, fn(&mut App));++ /// Every dock that takes the keyboard in `handle_key` must also blank the+ /// input row: a live cursor under a dock that swallows every keystroke+ /// promises a field that is not there. One case per guard in that list, so+ /// the next dock added cannot quietly regress only the rendering half.+ #[test]+ fn every_blocking_dock_marks_the_input_row_inactive() {+ let setups: [DockSetup; 6] = [+ ("login/connecting", |app| {+ app.login = Some(super::LoginPrompt::connecting())+ }),+ ("login/paste", |app| {+ app.login = Some(confirmed_paste_prompt())+ }),+ ("browser_confirm", |app| {+ app.browser_confirm = Some(super::BrowserConfirm {+ url: "https://example.com/authorize".into(),+ purpose: "authorize 'github'".into(),+ })+ }),+ ("settings_prompt", |app| {+ let def = AGENT_SETTINGS+ .iter()+ .find(|d| d.key == "max_parallel_subagents")+ .unwrap();+ app.settings_prompt = Some(super::SettingsPrompt::new(def, None));+ }),+ ("mcp_prompt", |app| {+ app.mcp_prompt = Some(blank_mcp_prompt())+ }),+ ("provider_prompt", |app| {+ app.provider_prompt = Some(super::ProviderPrompt::new())+ }),+ ];+ for (name, open) in setups {+ let mut app = test_app();+ open(&mut app);+ assert!(app.blocking_dock().is_some(), "{name} must block the field");+ let screen = render_rows(&mut app, 80, 24).join("\n");- assert!(- screen.contains("the field is inactive"),- "{name}: {screen}"- );++ assert!(screen.contains("the field is inactive"), "{name}: {screen}");+ assert!(+ !screen.contains("Type here to chat with agent"),+ "{name}: a live field must not show while the dock is open: {screen}"+ );+ }+ }++ /// The composer is only dead while a dock is up -- an idle app with no dock+ /// must still offer a field, or the guard above has over-reached.+ #[test]+ fn no_dock_leaves_the_input_row_live() {+ let mut app = test_app();+ assert!(app.blocking_dock().is_none());+ let screen = render_rows(&mut app, 80, 24).join("\n");+ assert!(screen.contains("Type here to chat with agent"), "{screen}");+ assert!(!screen.contains("the field is inactive"), "{screen}");+ }++ /// The approval stage shows the code and the URL, and takes no input -- the+ /// code is the one thing the user has to compare against the browser.+ #[tokio::test]+ async fn login_approval_stage_shows_the_code_and_ignores_typing() {+ let mut app = test_app();+ super::show_login_approval(+ &mut app,+ &crate::core::cli::device_auth::Session {+ session_id: "sess-1".into(),+ user_code: "ABCD-2345".into(),+ authorize_url: "https://tokamak.sh/cli/authorize?code=ABCD-2345".into(),+ expires_in: 300,+ interval: 5,+ },+ );+ let prompt = app.login.as_ref().expect("dock open");+ assert!(matches!(prompt.stage, super::LoginStage::Approving { .. }));+ assert!(!prompt.editable());++ type_key_chars(&mut app, "xyz").await;- assert!(app.login.as_ref().unwrap().input.is_empty(), "no field to type into");++ assert!(++ app.login.as_ref().unwrap().input.is_empty(),++ "no field to type into"++ );+ assert!(app.login_submit.is_none());++ let screen = render_rows(&mut app, 80, 24).join("\n");+ assert!(screen.contains("ABCD-2345"), "{screen}");+ assert!(screen.contains("waiting for approval"), "{screen}");+ }++ /// Esc during a browser approval closes the dock, which is what makes+ /// `chat_loop` drop the in-flight poll.+ #[tokio::test]+ async fn esc_cancels_a_browser_approval() {+ let mut app = test_app();+ run_command(&mut app, "login", &no_mcp()).await;+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;+ assert!(app.login.is_none(), "Esc must close the dock");+ }++ /// A denied or expired approval has no field to correct, so the dock closes+ /// with the reason rather than sitting there uneditable.+ #[tokio::test]+ async fn a_failed_approval_closes_the_dock_with_the_reason() {+ let mut app = test_app();+ super::show_login_approval(+ &mut app,+ &crate::core::cli::device_auth::Session {+ session_id: "s".into(),+ user_code: "A-1".into(),+ authorize_url: "https://tokamak.sh/cli/authorize?code=A-1".into(),+ expires_in: 300,+ interval: 5,+ },+ );- finish_login(&mut app, Err("the sign-in was denied in the browser.".to_string()));++ finish_login(++ &mut app,++ Err(crate::core::cli::auth::LoginError::OAuth(++ "the sign-in was denied in the browser.".to_string(),++ )),++ );+ assert!(app.login.is_none(), "an uneditable dock must not stay open");+ let text: String = row_lines(&app.transcript)+ .iter()+ .flat_map(|l| l.spans.clone())+ .map(|s| s.content.to_string())+ .collect();- assert!(text.contains("denied in the browser"), "{text}");++ assert!(++ text.contains("could not complete browser sign-in"),++ "{text}"++ );+ }++ /// A successful browser sign-in names the account it signed in as.+ #[test]+ fn a_browser_login_reports_the_account() {+ let mut app = test_app();- finish_login(++ assert!(finish_tokamak_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,+ account: Some("[email protected]".into()),+ }),- );++ ));+ let text: String = row_lines(&app.transcript)+ .iter()+ .flat_map(|l| l.spans.clone())+ .map(|s| s.content.to_string())+ .collect();+ assert!(text.contains("as [email protected]"), "{text}");+ }+#[test]fn submit_user_with_no_model_notes_instead_of_starting_a_turn() {let mut app = test_app();@@@ -18341,92 -18110,26 +20094,93 @@@}#[test]- fn successful_login_closes_the_prompt_and_adopts_a_runnable_model() {+ fn login_successful_api_key_login_reports_only_model_guidance() {crate::core::agent::global_config::with_temp_home(|_| {let mut app = test_app();- app.login = Some(super::LoginPrompt::new("tokamak"));+ app.login = Some(confirmed_paste_prompt());finish_login(&mut app,- Ok(crate::core::cli::tokamak::Login {+ Ok(crate::core::cli::auth::LoginResult {+ provider: "tokamak".into(),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());+ assert!(- transcript_text(&app).contains("signed in to tokamak. Use /model to select a model."),++ transcript_text(&app)++ .contains("signed in to tokamak. Use /model to select a model."),+ "{}",+ transcript_text(&app)+ );// 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 failed_api_key_login_reports_provider_safe_error_without_key() {+ let mut app = test_app();- super::open_login_prompt(&mut app, "tokamak");++ app.login = Some(confirmed_paste_prompt());+ app.login.as_mut().unwrap().paste("tk-secret-do-not-render");++ finish_login(+ &mut app,+ Err(crate::core::cli::auth::LoginError::Unauthorized),+ );++ let prompt = app.login.as_ref().expect("prompt stays open to retry");+ assert_eq!(+ prompt.error.as_deref(),+ Some("tokamak sign-in failed: that API key was not accepted")+ );+ let screen = render_rows(&mut app, 80, 24).join("\n");+ assert!(screen.contains("tokamak sign-in failed"), "{screen}");+ assert!(!screen.contains("tk-secret-do-not-render"), "{screen}");+ }++ #[test]+ fn login_error_message_sanitizes_persistence_failure_details() {+ let message = super::login_error_message(+ "tokamak",+ crate::core::cli::auth::LoginError::Persist(+ "could not save provider configuration to /Users/alice/.jan/config.toml with key tk-secret-do-not-render".to_string(),+ ),+ );++ assert_eq!(+ message,+ "tokamak sign-in failed: could not save sign-in securely"+ );+ assert!(+ !message.contains("/Users/alice/.jan/config.toml"),+ "{message}"+ );+ assert!(!message.contains("tk-secret-do-not-render"), "{message}");+ }++ #[test]+ fn login_error_message_sanitizes_oauth_failure_details() {+ let message = super::login_error_message(+ "anthropic",+ crate::core::cli::auth::LoginError::OAuth(+ "callback contained code=sk-secret-do-not-render from /Users/alice/.jan/config.toml".to_string(),+ ),+ );++ assert_eq!(+ message,+ "anthropic sign-in failed: could not complete browser sign-in"+ );+ assert!(+ !message.contains("/Users/alice/.jan/config.toml"),+ "{message}"+ );+ assert!(!message.contains("sk-secret-do-not-render"), "{message}");+ }+#[test]fn login_keeps_a_still_runnable_model_on_a_key_refresh() {crate::core::agent::global_config::with_temp_home(|_| {@@@ -18438,16 -18140,16 +20192,17 @@@base_url: Some(crate::core::cli::tokamak::BASE_URL.into()),models: Some(vec!["m".into()]),api_type: None,- ..Default::default()++ ..Default::default()},).expect("seed provider");let mut app = test_app();- app.login = Some(super::LoginPrompt::new("tokamak"));+ app.login = Some(confirmed_paste_prompt());finish_login(&mut app,- Ok(crate::core::cli::tokamak::Login {+ Ok(crate::core::cli::auth::LoginResult {+ provider: "tokamak".into(),models: vec!["tokamak-1-preview".into()],config_path: std::path::PathBuf::from("/tmp/config.toml"),default_model: None,@@@ -18473,6 -18175,7 +20228,7 @@@base_url: Some(crate::core::cli::tokamak::BASE_URL.into()),models: Some(vec!["tokamak-1-preview".into()]),api_type: None,- ..Default::default()++ ..Default::default()},).expect("seed provider");@@@ -18480,14 -18183,14 +20236,16 @@@let mut app = test_app();// Give the app a provider_configs map that is stale (empty, as it// would be on a fresh launch before login).-- let provider_configs: std::collections::HashMap<String, crate::core::state::ProviderConfig> =-- std::collections::HashMap::new();++ let provider_configs: std::collections::HashMap<++ String,++ crate::core::state::ProviderConfig,++ > = std::collections::HashMap::new();let args = std::sync::Arc::new(super::OrchestrationArgs {client: crate::core::agent::upstream::agent_http_client(),-- provider_configs: std::sync::Arc::new(tokio::sync::Mutex::new(-- provider_configs,++ provider_configs: std::sync::Arc::new(tokio::sync::Mutex::new(provider_configs)),++ mcp_servers: std::sync::Arc::new(tokio::sync::Mutex::new(++ std::collections::HashMap::new(),)),-- mcp_servers: std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new())),mcp_settings: std::sync::Arc::new(tokio::sync::Mutex::new(crate::core::mcp::models::McpSettings::default(),)),@@@ -18969,7 -18647,7 +20727,10 @@@assert!(app.settings_prompt.is_none(), "Enter closes the dock");let global = std::fs::read_to_string(home.join(".jan").join("config.toml")).unwrap();-- assert!(global.contains("wave = \"~\""), "written globally: {global}");++ assert!(++ global.contains("wave = \"~\""),++ "written globally: {global}"++ );let project = std::fs::read_to_string(&toml_path).unwrap();assert!(!project.contains("wave"),@@@ -18978,7 -18656,7 +20739,10 @@@assert_eq!(super::wave_glyph().as_deref(), Some("~"), "applied live");let note = transcript_text(&app);assert!(note.contains("wave = ~ written"), "{note}");-- assert!(note.contains("in effect now"), "no restart is needed: {note}");++ assert!(++ note.contains("in effect now"),++ "no restart is needed: {note}"++ );// Clearing the field writes the off value, live. It does *not*// remove the key: absent means the default 👋 comes back, which is@@@ -18996,7 -18674,7 +20760,10 @@@"cleared field persists as the off value");let note = transcript_text(&app);-- assert!(note.contains("wave off (throbber)"), "off, not unset: {note}");++ assert!(++ note.contains("wave off (throbber)"),++ "off, not unset: {note}"++ );// Removing the key is the other path, and it restores the default// rather than leaving the sweep off.@@@ -19104,7 -18779,7 +20871,11 @@@fn input(app: &App) -> String {app.settings_prompt.as_ref().unwrap().input.clone()}-- assert_eq!(input(&app), "👁️👄👁️", "three clusters of five chars all fit");++ assert_eq!(++ input(&app),++ "👁️👄👁️",++ "three clusters of five chars all fit"++ );// One past the cap is dropped, and the field is left exactly as it was// rather than half-appended.@@@ -19276,20 -18951,20 +21047,12 @@@let rt = tokio::runtime::Runtime::new().unwrap();rt.block_on(async {// Skip to the Url field: Name -> Transport -> Url.-- super::handle_mcp_prompt_key(-- &mut app, key(KeyCode::Down), false, &servers,-- )-- .await;-- super::handle_mcp_prompt_key(-- &mut app, key(KeyCode::Down), false, &servers,-- )-- .await;++ super::handle_mcp_prompt_key(&mut app, key(KeyCode::Down), false, &servers).await;++ super::handle_mcp_prompt_key(&mut app, key(KeyCode::Down), false, &servers).await;assert_eq!(app.mcp_prompt.as_ref().unwrap().field, McpField::Url);for ch in "https://jk.example/".chars() {-- super::handle_mcp_prompt_key(-- &mut app, key(KeyCode::Char(ch)), false, &servers,-- )-- .await;++ super::handle_mcp_prompt_key(&mut app, key(KeyCode::Char(ch)), false, &servers)++ .await;}});@@@ -19406,83 -19074,12 +21169,89 @@@let configs = crate::core::agent::global_config::load_global_config().unwrap();let cfg = configs.get("myprovider").expect("provider written");-- assert_eq!(cfg.base_url.as_deref(), Some("https://my-provider.example/v1"));++ assert_eq!(++ cfg.base_url.as_deref(),++ Some("https://my-provider.example/v1")++ );assert_eq!(cfg.api_key.as_deref(), Some("sk-test-123"));assert_eq!(cfg.models, vec!["gpt-4o", "gpt-4o-mini"]);});}+ #[test]+ fn provider_prompt_saves_anthropic_api_type() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let mut p = super::ProviderPrompt::new();+ p.name = "myanthropic".to_string();+ p.base_url = "https://api.my-anthropic.example/v1".to_string();+ p.api_key = "sk-test-123".to_string();+ p.toggle_api_type();+ assert_eq!(p.api_type_label(), "anthropic-compatible");+ assert!(p.save().is_ok());++ let configs = crate::core::agent::global_config::load_global_config().unwrap();- let cfg = configs.get("myanthropic").expect("anthropic provider written");++ let cfg = configs++ .get("myanthropic")++ .expect("anthropic provider written");+ assert_eq!(cfg.api_type.as_deref(), Some("anthropic"));+ });+ }++ #[test]+ fn provider_prompt_api_type_toggle_cycles_openai_anthropic() {+ let mut p = super::ProviderPrompt::new();+ assert_eq!(p.api_type_label(), "openai-compatible");+ p.toggle_api_type();+ assert_eq!(p.api_type_label(), "anthropic-compatible");+ p.toggle_api_type();+ assert_eq!(p.api_type_label(), "openai-compatible");+ }++ #[test]+ fn provider_prompt_left_right_toggles_api_type_field() {+ let mut app = test_app();+ let mut p = super::ProviderPrompt::new();+ p.field = ProviderField::ApiType;+ app.provider_prompt = Some(p);+ super::handle_provider_prompt_key(&mut app, key(KeyCode::Right), false);+ assert_eq!(+ app.provider_prompt.as_ref().unwrap().api_type_label(),+ "anthropic-compatible",+ "Right on the api type field selects anthropic"+ );+ }++ #[test]+ fn provider_prompt_keeps_existing_anthropic_type_when_editing() {+ crate::core::agent::global_config::with_temp_home(|_| {+ use crate::core::agent::global_config::{set_provider, ProviderUpdate};+ set_provider(+ "p",+ ProviderUpdate {+ api_key: Some("sk-1".into()),+ clear_api_key: false,+ base_url: Some("https://example.com/v1".into()),+ models: Some(vec!["claude-sonnet-5".into()]),+ api_type: Some("anthropic".into()),++ ..Default::default()+ },+ )+ .unwrap();+ let entry = crate::core::agent::global_config::load_global_config()+ .unwrap()+ .get("p")+ .unwrap()+ .clone();+ let prompt = super::ProviderPrompt::from_entry(&entry);+ assert_eq!(prompt.api_type.as_deref(), Some("anthropic"));+ assert_eq!(+ prompt.api_type_label(),+ "anthropic-compatible",+ "editing an anthropic provider keeps its wire type"+ );+ });+ }+#[test]fn provider_prompt_save_and_cancel_via_keys() {crate::core::agent::global_config::with_temp_home(|_| {@@@ -19535,14 -19131,13 +21304,21 @@@}super::handle_provider_prompt_key(&mut app, key(KeyCode::Down), false);super::handle_provider_prompt_key(&mut app, key(KeyCode::Down), false);- assert_eq!(app.provider_prompt.as_ref().unwrap().field, ProviderField::ApiKey);+ super::handle_provider_prompt_key(&mut app, key(KeyCode::Down), false);- assert_eq!(app.provider_prompt.as_ref().unwrap().field, ProviderField::ApiKey);++ assert_eq!(++ app.provider_prompt.as_ref().unwrap().field,++ ProviderField::ApiKey++ );for ch in "sk-ant-k3y-j".chars() {super::handle_provider_prompt_key(&mut app, key(KeyCode::Char(ch)), false);}let prompt = app.provider_prompt.as_ref().expect("still open");-- assert_eq!(prompt.field, ProviderField::ApiKey, "typing k must not move up");++ assert_eq!(++ prompt.field,++ ProviderField::ApiKey,++ "typing k must not move up"++ );assert_eq!(prompt.name, "kitty-jet");assert_eq!(prompt.api_key, "sk-ant-k3y-j");}@@@ -19558,9 -19153,9 +21334,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("sk-old".into()),base_url: Some("https://api.example/v1".into()),+ clear_api_key: false,models: Some(vec!["m1".into()]),api_type: None,- ..Default::default()++ ..Default::default()},).unwrap();@@@ -19598,9 -19193,9 +21375,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("sk-old".into()),base_url: Some("https://api.example/v1".into()),+ clear_api_key: false,models: Some(vec!["m1".into()]),api_type: None,- ..Default::default()++ ..Default::default()},).unwrap();@@@ -19627,7 -19222,7 +21405,11 @@@}super::handle_provider_prompt_key(&mut app, key(KeyCode::Enter), false);assert!(app.provider_prompt.is_none());-- assert_eq!(stored_key().as_deref(), Some("sk-new-key"), "typed key replaces");++ assert_eq!(++ stored_key().as_deref(),++ Some("sk-new-key"),++ "typed key replaces"++ );// Empty the key field: the stored key is cleared.app.provider_prompt = fresh();@@@ -19655,7 -19249,7 +21437,11 @@@models: String::new(),error: None,};-- assert_eq!(p.masked_key(), "(unchanged)", "untouched edit shows unchanged");++ assert_eq!(++ p.masked_key(),++ "(unchanged)",++ "untouched edit shows unchanged"++ );p.key_touched = true;p.api_key = "sk-abc".to_string();assert_eq!(p.masked_key(), "******", "touched key masks its length");@@@ -19679,8 -19273,7 +21465,11 @@@// Advance to the API key field and paste a key shaped like a real one.super::handle_provider_prompt_key(&mut app, key(KeyCode::Down), false);super::handle_provider_prompt_key(&mut app, key(KeyCode::Down), false);- assert_eq!(app.provider_prompt.as_ref().unwrap().field, ProviderField::ApiKey);+ super::handle_provider_prompt_key(&mut app, key(KeyCode::Down), false);- assert_eq!(app.provider_prompt.as_ref().unwrap().field, ProviderField::ApiKey);++ assert_eq!(++ app.provider_prompt.as_ref().unwrap().field,++ ProviderField::ApiKey++ );route_paste_event(&mut app, Event::Paste("sk-ant-pasted-key".into()));assert_eq!(app.provider_prompt.as_ref().unwrap().api_key,@@@ -19758,9 -19351,9 +21547,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("k".into()),base_url: Some("https://my.example/v1".into()),+ clear_api_key: false,models: Some(vec!["m1".into()]),api_type: None,- ..Default::default()++ ..Default::default()},).unwrap();@@@ -19787,21 -19380,21 +21577,20 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("k".into()),base_url: Some("https://my.example/v1".into()),+ clear_api_key: false,models: Some(vec![]),api_type: None,- ..Default::default()++ ..Default::default()},).unwrap();let mut app = test_app();super::open_provider_settings(&mut app);- let rt = tokio::runtime::Runtime::new().unwrap();- assert!(- crate::core::agent::global_config::load_global_config()- .unwrap()- .contains_key("myprovider")- );+ let rt = tokio::runtime::Runtime::new().unwrap();- assert!(- crate::core::agent::global_config::load_global_config()- .unwrap()- .contains_key("myprovider")- );++ assert!(crate::core::agent::global_config::load_global_config()++ .unwrap()++ .contains_key("myprovider"));// First `d` arms but must not delete.rt.block_on(async {@@@ -19845,9 -19438,9 +21634,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("k".into()),base_url: Some("https://my.example/v1".into()),+ clear_api_key: false,models: Some(vec![]),api_type: None,- ..Default::default()++ ..Default::default()},).unwrap();@@@ -19875,7 -19468,7 +21665,10 @@@press(&mut app, KeyCode::Char('d'), KeyModifiers::NONE).await;});let configs = crate::core::agent::global_config::load_global_config().unwrap();-- assert!(configs.contains_key("a"), "a must still exist, only armed on b");++ assert!(++ configs.contains_key("a"),++ "a must still exist, only armed on b"++ );assert!(configs.contains_key("b"));assert!(app.picker.as_ref().unwrap().armed_delete == Some(idx_b));});@@@ -19891,7 -19484,7 +21684,10 @@@super::open_provider_settings(&mut app);let picker = app.picker.as_ref().expect("picker opened");assert_eq!(picker.items.len(), 1);-- assert!(picker.items[0].value.is_empty(), "watermark row has no value");++ assert!(++ picker.items[0].value.is_empty(),++ "watermark row has no value"++ );let rt = tokio::runtime::Runtime::new().unwrap();rt.block_on(async {@@@ -19902,102 -19495,14 +21698,115 @@@"no arm on watermark");assert!(-- !crate::core::agent::global_config::load_global_config().unwrap().contains_key(""),++ !crate::core::agent::global_config::load_global_config()++ .unwrap()++ .contains_key(""),"d on the watermark must not delete an empty-named entry");rt.block_on(async {press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;});-- assert!(app.provider_prompt.is_none(), "Enter on the watermark opens no wizard");++ assert!(++ app.provider_prompt.is_none(),++ "Enter on the watermark opens no wizard"++ );+ });+ }+ /// `x` on the provider-settings picker signs out (clears the credential)+ /// but keeps the provider entry and its config, distinct from `d` delete.+ #[test]+ fn provider_settings_x_logout_clears_credential_and_keeps_config() {+ // Seeds the process-global secret store, so it has to hold the same+ // lock (and get its own data folder) as every other credential test.+ with_isolated_login_state(|| {+ use crate::core::cli::auth::{Credential, CredentialStore};+ crate::core::agent::global_config::set_provider(+ "myprovider",+ crate::core::agent::global_config::ProviderUpdate {+ api_key: Some("k".into()),+ base_url: Some("https://my.example/v1".into()),+ clear_api_key: false,+ models: Some(vec!["m1".into()]),+ api_type: None,++ ..Default::default()+ },+ )+ .unwrap();+ CredentialStore::store("myprovider", &Credential::ApiKey("k".into()))+ .expect("seed a stored credential");++ let mut app = test_app();+ super::open_provider_settings(&mut app);+ let rt = tokio::runtime::Runtime::new().unwrap();+ rt.block_on(async {+ press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE).await;+ });++ // The provider entry (and its models) survive; the credential is gone.+ let configs = crate::core::agent::global_config::load_global_config().unwrap();- assert!(configs.contains_key("myprovider"), "config kept after logout");++ assert!(++ configs.contains_key("myprovider"),++ "config kept after logout"++ );+ assert_eq!(configs.get("myprovider").unwrap().models, vec!["m1"]);+ assert!(+ CredentialStore::load("myprovider").unwrap().is_none(),+ "credential cleared on logout"+ );+ assert!(transcript_text(&app).contains("signed out of myprovider"));+ assert!(app.picker.is_some(), "logout keeps the picker open");+ });+ }++ /// `x` on the `/login` picker signs out a signed-in provider and flips its+ /// row hint to "not signed in" without closing the picker.+ #[test]+ fn login_picker_x_signs_out_signed_in_provider() {+ with_isolated_login_state(|| {+ use crate::core::cli::auth::{Credential, CredentialStore};+ // A catalog provider (tokamak) that we can sign out of.+ CredentialStore::store("tokamak", &Credential::ApiKey("k".into()))+ .expect("seed a stored credential");+ crate::core::agent::global_config::set_provider(+ "tokamak",+ crate::core::agent::global_config::ProviderUpdate {+ api_key: Some("k".into()),+ base_url: Some("https://api.tokamak.sh/v1".into()),+ clear_api_key: false,+ models: Some(vec!["tokamak-1-preview".into()]),+ api_type: None,++ ..Default::default()+ },+ )+ .unwrap();++ let mut app = test_app();+ super::open_login_picker(&mut app);+ // Tokamak is pinned to the top of the login picker.+ let rt = tokio::runtime::Runtime::new().unwrap();+ rt.block_on(async {+ press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE).await;+ });++ assert!(+ crate::core::cli::auth::CredentialStore::load("tokamak")+ .unwrap()+ .is_none(),+ "x on the login picker signs out"+ );- assert!(app.picker.is_some(), "login picker stays open after sign-out");++ assert!(++ app.picker.is_some(),++ "login picker stays open after sign-out"++ );+ let picker = app.picker.as_ref().unwrap();+ assert_eq!(picker.items[0].value, "tokamak");+ assert_eq!(+ picker.items[0].hint.as_deref(),+ Some("not signed in"),+ "row hint flips to not signed in"+ );+ assert!(transcript_text(&app).contains("signed out of tokamak"));});}@@@ -20012,9 -19517,9 +21821,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("sk-secret".into()),base_url: Some("https://my.example/v1".into()),+ clear_api_key: false,models: Some(vec!["m1".into(), "m2".into()]),api_type: None,- ..Default::default()++ ..Default::default()},).unwrap();@@@ -20031,7 -19536,7 +21841,11 @@@assert!(prompt.editing.is_some());// The name field is read-only while editing; typing must not change it.-- assert_eq!(prompt.field, ProviderField::BaseUrl, "edit starts on base url");++ assert_eq!(++ prompt.field,++ ProviderField::BaseUrl,++ "edit starts on base url"++ );app.provider_prompt.as_mut().unwrap().field = ProviderField::Name;for ch in "RENAMED".chars() {super::handle_provider_prompt_key(&mut app, key(KeyCode::Char(ch)), false);@@@ -20133,9 -19635,9 +21947,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("k".into()),base_url: Some(format!("http://{addr}/v1")),+ clear_api_key: false,models: Some(vec![]), // no models configuredapi_type: None,- ..Default::default()++ ..Default::default()},).expect("seed provider");@@@ -20145,14 -19647,12 +21960,18 @@@let rt = tokio::runtime::Runtime::new().unwrap();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.all_items.iter().map(|i| &i.model).collect::<Vec<_>>()- picker.items.iter().map(|i| &i.label).collect::<Vec<_>>()++ picker++ .all_items++ .iter()++ .map(|i| &i.model)++ .collect::<Vec<_>>());});}@@@ -20170,9 -19670,9 +21989,10 @@@crate::core::agent::global_config::ProviderUpdate {api_key: Some("k".into()),base_url: Some("http://127.0.0.1:9/v1".into()),+ clear_api_key: false,models: Some(vec![]),api_type: None,- ..Default::default()++ ..Default::default()},).unwrap();@@@ -20184,7 -19684,7 +22004,10 @@@// The picker opened (no reachable pairs => the note path fires,// but there is no panic, no hang, and the provider stays put).let configs = crate::core::agent::global_config::load_global_config().unwrap();-- assert!(configs.contains_key("dead"), "provider not removed by a failed probe");++ assert!(++ configs.contains_key("dead"),++ "provider not removed by a failed probe"++ );// Opening once more must not re-contact the dead endpoint: the// session short-circuit means the second open is near-instant.@@@ -22599,6 -21995,31 +24422,34 @@@}}+ /// kitty's `?2026` handling can drop the resize repaint, so synchronized+ /// output is skipped there; every other identity keeps it. (Konsole, the+ /// whole reason kitty looks broken by contrast, is not the one gated.)+ #[test]+ fn synchronized_output_is_off_only_for_kitty() {+ use super::super::terminal_setup::Kind;+ for kind in [+ Kind::Ghostty,+ Kind::WezTerm,+ Kind::Foot,+ Kind::Rio,+ Kind::Konsole,+ Kind::ITerm2,+ Kind::AppleTerminal,+ Kind::VsCode,+ Kind::WindowsTerminal,+ Kind::Alacritty,+ Kind::Vte,+ Kind::Unknown,+ ] {- assert!(sync_output_for(kind), "{kind:?} must keep synchronized output");++ assert!(++ sync_output_for(kind),++ "{kind:?} must keep synchronized output"++ );+ }+ assert!(!sync_output_for(Kind::Kitty), "kitty must skip it");+ }+#[test]fn alt_scroll_is_disabled_only_where_the_terminal_reports_wheel() {// The app keeps native alternate scroll (i.e. sends nothing) on Windows,@@@ -22606,8 -22027,8 +24457,16 @@@// so the wheel arrives as SGR mouse reports. The save/off and restore// pair must always agree so the mode is left balanced on exit.if cfg!(windows) {-- assert_eq!(alt_scroll_save_off(), "", "Windows must not disable alt scroll");-- assert_eq!(alt_scroll_restore(), "", "Windows must not restore alt scroll");++ assert_eq!(++ alt_scroll_save_off(),++ "",++ "Windows must not disable alt scroll"++ );++ assert_eq!(++ alt_scroll_restore(),++ "",++ "Windows must not restore alt scroll"++ );} else {assert_eq!(alt_scroll_save_off(), ALT_SCROLL_SAVE_OFF);assert_eq!(alt_scroll_restore(), ALT_SCROLL_RESTORE);@@@ -23260,13 -22638,10 +25119,16 @@@app.spinner_frame = 3;let later = frame_of(&mut app);- assert!(later.contains(SPINNER[3]), "expected frame 3 glyph: {later:?}");+ assert!(+ later.contains(SPINNER[3]),+ "expected frame 3 glyph: {later:?}"+ );assert_ne!(first, later, "row must change as the frame advances");-- assert!(later.contains("(Esc to cancel, type to queue next message)"), "{later:?}");++ assert!(++ later.contains("(Esc to cancel, type to queue next message)"),++ "{later:?}"++ );}/// When the model is reasoning (a ` think>` block is streaming), the input@@@ -23320,8 -22695,8 +25182,7 @@@if !THINKING_WORDS.iter().any(|w| row.contains(w)) {return false;}-- (0..buf.area.width)-- .any(|x| buf[(x, y)].style().fg == Some(super::THINKING_ORANGE))++ (0..buf.area.width).any(|x| buf[(x, y)].style().fg == Some(super::THINKING_ORANGE))});assert!(orange, "thinking synonym not orange");}@@@ -23395,7 -22770,7 +25256,11 @@@text: "Here is the answer".into(),});app.on_done("stop".into(), None);-- assert_eq!(app.reasoning_blocks.len(), 1, "reasoning folded into one block");++ assert_eq!(++ app.reasoning_blocks.len(),++ 1,++ "reasoning folded into one block"++ );// The wire history carries the answer, with the reasoning preserved on// the message's `reasoning_content` rather than inlined into `content`.let last = app.history.last().expect("assistant turn in history");@@@ -23476,13 -22851,13 +25341,17 @@@fn native_reasoning_badge_closes_once_prose_starts() {let mut app = test_app();app.submit_user("go".into());-- app.apply(StreamEvent::Reasoning { text: "ponder".into() });++ app.apply(StreamEvent::Reasoning {++ text: "ponder".into(),++ });assert_eq!(app.reasoning_status().map(|(w, _)| w),Some("thinking".to_string()));assert!(app.reasoning_open(), "reasoning is live");-- app.apply(StreamEvent::Token { text: "Answer".into() });++ app.apply(StreamEvent::Token {++ text: "Answer".into(),++ });assert!(!app.reasoning_open(), "prose has started");assert_eq!(app.reasoning_status().map(|(w, _)| w),@@@ -23536,10 -22911,10 +25405,18 @@@fn interleaved_native_reasoning_keeps_emission_order() {let mut app = test_app();app.submit_user("go".into());-- app.apply(StreamEvent::Reasoning { text: "first thought".into() });-- app.apply(StreamEvent::Token { text: "Part one.".into() });-- app.apply(StreamEvent::Reasoning { text: "second thought".into() });-- app.apply(StreamEvent::Token { text: " Part two.".into() });++ app.apply(StreamEvent::Reasoning {++ text: "first thought".into(),++ });++ app.apply(StreamEvent::Token {++ text: "Part one.".into(),++ });++ app.apply(StreamEvent::Reasoning {++ text: "second thought".into(),++ });++ app.apply(StreamEvent::Token {++ text: " Part two.".into(),++ });app.on_done("stop".into(), None);assert_eq!(app.reasoning_blocks.len(), 2, "two separate stretches");// Journaled apart: prose verbatim, each stretch at the offset it@@@ -23557,8 -22932,8 +25434,14 @@@assert_eq!(reasoning,&vec![-- ReasoningSeg { at: 0, text: "first thought".into() },-- ReasoningSeg { at: 9, text: "second thought".into() },++ ReasoningSeg {++ at: 0,++ text: "first thought".into()++ },++ ReasoningSeg {++ at: 9,++ text: "second thought".into()++ },]);// The wire answer is prose only; both thoughts ride along on@@@ -23733,6 -23099,45 +25616,48 @@@fn compact_is_a_registered_command() {assert!(SLASH_COMMANDS.iter().any(|c| c.name == "/compact"));}+ #[test]+ fn effort_aliases_are_registered_as_aliases_of_effort() {+ let effort = SLASH_COMMANDS+ .iter()+ .find(|c| c.name == "/effort")+ .expect("/effort is canonical");+ assert_eq!(effort.alias_of, None, "/effort is not an alias");+ for alias in ["/think", "/reasoning"] {+ let row = SLASH_COMMANDS+ .iter()+ .find(|c| c.name == alias)+ .unwrap_or_else(|| panic!("{alias} must be registered"));+ assert_eq!(row.alias_of, Some("/effort"), "{alias} alias target");+ }+ }++ #[tokio::test]+ async fn help_lists_effort_aliases_and_marks_effort_canonical() {+ let mut app = test_app();+ run_command(&mut app, "help", &no_mcp()).await;+ let text: String = app.transcript.iter().map(row_text).collect();+ // `/effort` desc has no alias prefix; each alias row derives from+ // `alias_of` and must read as an alias of `/effort`. Signatures are+ // wider than the 18-char pad, so assert on the embedded parts rather+ // than exact column alignment.- assert!(text.contains("alias of /effort"), "alias annotation missing: {text}");++ assert!(++ text.contains("alias of /effort"),++ "alias annotation missing: {text}"++ );+ assert!(+ text.contains("/think [low|medium|high] alias of /effort"),+ "think row: {text}"+ );+ assert!(+ text.contains("/reasoning [low|medium|high] alias of /effort"),+ "reasoning row: {text}"+ );+ assert!(+ text.contains("/effort [low|medium|high] Set reasoning effort"),+ "canonical effort row must not be an alias: {text}"+ );+ }#[test]fn partial_json_field_reads_a_truncated_value() {@@@ -23922,19 -23281,19 +25847,30 @@@fn a_clamped_line_keeps_its_head_unless_it_is_the_open_one() {let mut call = super::StartingCall::new("c1".into(), "write".into());let filler = "-".repeat(super::STREAM_MAX_LINE_CHARS * 2);-- call.args = format!(-- r#"{{"path":"a.txt","content":"HEAD1{filler}TAIL1\nHEAD2{filler}TAIL2"#-- );++ call.args =++ format!(r#"{{"path":"a.txt","content":"HEAD1{filler}TAIL1\nHEAD2{filler}TAIL2"#);let text: Vec<String> = starting_call_lines(&mut call, "\u{280b}").iter().map(line_text).collect();let joined = text.join("\n");-- assert!(joined.contains("HEAD1"), "finished line lost its head: {joined}");-- assert!(!joined.contains("TAIL1"), "finished line kept its tail: {joined}");-- assert!(joined.contains("TAIL2"), "open line lost its tail: {joined}");-- assert!(!joined.contains("HEAD2"), "open line kept its head: {joined}");++ assert!(++ joined.contains("HEAD1"),++ "finished line lost its head: {joined}"++ );++ assert!(++ !joined.contains("TAIL1"),++ "finished line kept its tail: {joined}"++ );++ assert!(++ joined.contains("TAIL2"),++ "open line lost its tail: {joined}"++ );++ assert!(++ !joined.contains("HEAD2"),++ "open line kept its head: {joined}"++ );}/// A file-sized `write` streams its arguments in thousands of deltas. One@@@ -23983,7 -23342,7 +25919,8 @@@handle: tokio::spawn(async {}),});for _ in 0..(super::EVENT_DRAIN_MAX + 50) {-- tx.send(StreamEvent::Token { text: "x".into() }).expect("send");++ tx.send(StreamEvent::Token { text: "x".into() })++ .expect("send");}assert_eq!(drain_stream_events(&mut app, &mut current).await,@@@ -24001,13 -23360,13 +25938,17 @@@rx,handle: tokio::spawn(async {}),});-- tx.send(StreamEvent::Token { text: "hi".into() }).expect("send");++ tx.send(StreamEvent::Token { text: "hi".into() })++ .expect("send");tx.send(StreamEvent::Done {stop_reason: "stop".into(),usage: None,}).expect("send");-- tx.send(StreamEvent::Token { text: "late".into() }).expect("send");++ tx.send(StreamEvent::Token {++ text: "late".into(),++ })++ .expect("send");let drained = drain_stream_events(&mut app, &mut current).await;assert_eq!(drained, 2, "drain must stop on the terminal event");@@@ -24316,7 -23672,7 +26257,10 @@@let mut app = test_app();run_command(&mut app, "effort", &no_mcp()).await;let text: String = app.transcript.iter().map(row_text).collect();-- assert!(text.contains("medium"), "default level not reported: {text}");++ assert!(++ text.contains("medium"),++ "default level not reported: {text}"++ );}#[tokio::test]@@@ -24333,9 -23689,63 +26277,87 @@@async fn effort_command_rejects_unknown_level() {let mut app = test_app();run_command(&mut app, "effort turbo", &no_mcp()).await;-- assert_eq!(app.reasoning_effort, "medium", "invalid level must not apply");++ assert_eq!(++ app.reasoning_effort, "medium",++ "invalid level must not apply"++ );+ let text: String = app.transcript.iter().map(row_text).collect();- assert!(text.contains("unknown effort level"), "missing note: {text}");++ assert!(++ text.contains("unknown effort level"),++ "missing note: {text}"++ );+ }++ #[tokio::test]+ async fn think_alias_reports_current_level() {+ let mut app = test_app();+ run_command(&mut app, "think", &no_mcp()).await;+ let text: String = app.transcript.iter().map(row_text).collect();- assert!(text.contains("medium"), "default level not reported: {text}");++ assert!(++ text.contains("medium"),++ "default level not reported: {text}"++ );+ }++ #[tokio::test]+ async fn think_alias_sets_valid_level() {+ let mut app = test_app();+ run_command(&mut app, "think high", &no_mcp()).await;+ assert_eq!(app.reasoning_effort, "high");+ assert_eq!(app.last_non_low_effort, "high");+ let text: String = app.transcript.iter().map(row_text).collect();+ assert!(text.contains("set to high"), "missing note: {text}");+ }++ #[tokio::test]+ async fn think_alias_rejects_unknown_level() {+ let mut app = test_app();+ run_command(&mut app, "think turbo", &no_mcp()).await;- assert_eq!(app.reasoning_effort, "medium", "invalid level must not apply");++ assert_eq!(++ app.reasoning_effort, "medium",++ "invalid level must not apply"++ );+ let text: String = app.transcript.iter().map(row_text).collect();- assert!(text.contains("unknown effort level"), "missing note: {text}");++ assert!(++ text.contains("unknown effort level"),++ "missing note: {text}"++ );+ }++ #[tokio::test]+ async fn reasoning_alias_reports_current_level() {+ let mut app = test_app();+ run_command(&mut app, "reasoning", &no_mcp()).await;+ let text: String = app.transcript.iter().map(row_text).collect();- assert!(text.contains("medium"), "default level not reported: {text}");++ assert!(++ text.contains("medium"),++ "default level not reported: {text}"++ );+ }++ #[tokio::test]+ async fn reasoning_alias_sets_valid_level() {+ let mut app = test_app();+ run_command(&mut app, "reasoning high", &no_mcp()).await;+ assert_eq!(app.reasoning_effort, "high");+ assert_eq!(app.last_non_low_effort, "high");+ let text: String = app.transcript.iter().map(row_text).collect();+ assert!(text.contains("set to high"), "missing note: {text}");+ }++ #[tokio::test]+ async fn reasoning_alias_rejects_unknown_level() {+ let mut app = test_app();+ run_command(&mut app, "reasoning turbo", &no_mcp()).await;- assert_eq!(app.reasoning_effort, "medium", "invalid level must not apply");++ assert_eq!(++ app.reasoning_effort, "medium",++ "invalid level must not apply"++ );let text: String = app.transcript.iter().map(row_text).collect();-- assert!(text.contains("unknown effort level"), "missing note: {text}");++ assert!(++ text.contains("unknown effort level"),++ "missing note: {text}"++ );}#[test]@@@ -24346,7 -23756,7 +26368,10 @@@assert_eq!(app.reasoning_effort, "low");assert_eq!(app.last_non_low_effort, "medium");app.toggle_reasoning_effort();-- assert_eq!(app.reasoning_effort, "medium", "toggle back restores last non-low");++ assert_eq!(++ app.reasoning_effort, "medium",++ "toggle back restores last non-low"++ );}#[test]@@@ -24357,7 -23767,7 +26382,10 @@@app.toggle_reasoning_effort();assert_eq!(app.reasoning_effort, "low");app.toggle_reasoning_effort();-- assert_eq!(app.reasoning_effort, "high", "restores the latest non-low, not a hardcoded default");++ assert_eq!(++ app.reasoning_effort, "high",++ "restores the latest non-low, not a hardcoded default"++ );}#[test]@@@ -24370,7 -23780,7 +26398,10 @@@assert_eq!(app.reasoning_effort, "high");app.cycle_reasoning_effort();assert_eq!(app.reasoning_effort, "low", "cycles back to low");-- assert_eq!(app.last_non_low_effort, "high", "tracks the most recent non-low");++ assert_eq!(++ app.last_non_low_effort, "high",++ "tracks the most recent non-low"++ );}#[test]@@@ -24607,7 -23993,7 +26638,10 @@@assert!(injected.contains("t1") && injected.contains("t2"));// The reminder is hidden: no user-authored `> ` row in the transcript.let rows: String = app.transcript.iter().map(row_text).collect();-- assert!(!rows.contains("> "), "reminder must not render as a user row");++ assert!(++ !rows.contains("> "),++ "reminder must not render as a user row"++ );}#[test]@@@ -24653,12 -24036,10 +26687,13 @@@app.apply(StreamEvent::AskRequest {request_id,request: ask_request(false, false),+ timeout_secs: None,});finish_clean_turn(&mut app);- assert!(!app.want_start, "a pending ask blocks the reminder boundary");+ assert!(+ !app.want_start,+ "a pending ask blocks the reminder boundary"+ );}#[test]@@@ -25023,10 -24360,10 +27058,16 @@@app.apply(StreamEvent::Token {text: "<think>more".into(),});-- assert!(!app.is_thinking(), "streamed reasoning needs no badge motion");++ assert!(++ !app.is_thinking(),++ "streamed reasoning needs no badge motion"++ );app.stream_reasoning = false;app.show_reasoning = true;-- assert!(!app.is_thinking(), "unfolded reasoning needs no badge motion");++ assert!(++ !app.is_thinking(),++ "unfolded reasoning needs no badge motion"++ );}/// Folded reasoning summaries and tool rows are one run of activity: a turn@@@ -25991,7 -25389,7 +28129,12 @@@transcript_text(&app));// Explicit qualified form.-- run_command(&mut app, "command:feature-dev:feature-dev fix tests", &no_mcp()).await;++ run_command(++ &mut app,++ "command:feature-dev:feature-dev fix tests",++ &no_mcp(),++ )++ .await;let user = app.history.iter().last().unwrap();assert!(user.get("content")@@@ -26113,12 -25511,12 +28256,21 @@@// the TUI); it hands the spec to the loop, which runs the install off// the render loop. Drive the handoff: the request is recorded, a second// is refused while one is in flight, and the loop clears it on pick-up.-- run_command(&mut app, &format!("plugin install file://{}", repo.display()), &no_mcp()).await;++ run_command(++ &mut app,++ &format!("plugin install file://{}", repo.display()),++ &no_mcp(),++ )++ .await;assert!(app.plugin_install_request.is_some(),"install spec should be handed to the loop");-- assert!(transcript_text(&app).contains("installing plugin..."), "{}", transcript_text(&app));++ assert!(++ transcript_text(&app).contains("installing plugin..."),++ "{}",++ transcript_text(&app)++ );app.plugin_installing = true;run_command(&mut app, "plugin install file://nowhere", &no_mcp()).await;assert!(@@@ -26131,12 -25529,12 +28283,9 @@@// Actually install so the list/dispatch/remove checks below have a// plugin present (the install itself is covered by plugins::tests).-- let p = crate::core::agent::plugins::install(-- &root,-- &format!("file://{}", repo.display()),-- )-- .await-- .unwrap();++ let p = crate::core::agent::plugins::install(&root, &format!("file://{}", repo.display()))++ .await++ .unwrap();assert_eq!(p.name, "release-tools");app.refresh_slash_catalog();@@@ -26214,9 -25612,9 +28363,14 @@@finish_plugin_install(&mut app,Some("file:///tmp/collection".to_string()),-- Ok(crate::core::agent::plugins::GitInstall::Collection(candidates)),++ Ok(crate::core::agent::plugins::GitInstall::Collection(++ candidates,++ )),);-- let picker = app.picker.as_ref().expect("collection listing opens the picker");++ let picker = app++ .picker++ .as_ref()++ .expect("collection listing opens the picker");assert_eq!(picker.kind, PickerKind::PluginSelect);assert_eq!(picker.items.len(), 2);@@@ -26255,11 -25653,11 +28409,17 @@@assert!(app.plugin_collection_url.is_some());press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE).await;press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;-- let (url, paths) = app.plugin_select_request.expect("Enter submits the pick").clone();++ let (url, paths) = app++ .plugin_select_request++ .expect("Enter submits the pick")++ .clone();assert_eq!(url, "file:///tmp/collection");assert_eq!(paths, vec!["alpha".to_string()]);assert!(app.picker.is_none());-- assert!(app.plugin_collection_url.is_none(), "URL consumed on submit");++ assert!(++ app.plugin_collection_url.is_none(),++ "URL consumed on submit"++ );let _ = std::fs::remove_dir_all(&root);}@@@ -26746,77 -26080,11 +28906,80 @@@}#[test]- fn header_drops_the_denominator_once_the_window_is_untrusted() {+ fn unknown_model_resolves_to_the_fallback_window() {let mut app = test_app();- app.apply(StreamEvent::TurnUsage {- usage: usage_of(200_000, 100),- });+ app.set_model("private-gateway-model".to_string());+ assert_eq!(app.context_window, 128_000);+ assert_eq!(+ app.context_window_source,+ crate::core::cli::model_capabilities::ContextWindowSource::Fallback+ );+ }++ #[test]+ fn a_target_compaction_that_overflows_blocks_the_gated_run() {+ let mut app = test_app();+ app.compacting = Some(CompactKind::Auto);+ app.history = vec![serde_json::json!({ "role": "user", "content": "hi" })];+ app.want_start = true;+ let overflow = format!(+ "[{}] Upstream returned HTTP 400: prompt is too long",+ crate::core::agent::upstream::CONTEXT_OVERFLOW_MARKER+ );+ finish_compaction(&mut app, Err(overflow), 1);+- assert!(app.compacting.is_none(), "a failure must clear the throbber");++ assert!(++ app.compacting.is_none(),++ "a failure must clear the throbber"++ );+ assert_eq!(app.history.len(), 1, "history must be left untouched");+ let text: String = app.transcript.iter().map(row_text).collect();+ assert!(+ text.contains("auto-compacting failed"),+ "an actionable error must be shown: {text}"+ );+ assert!(+ !app.want_start,+ "the oversized regular request must not be auto-resubmitted"+ );+ }++ #[test]+ fn model_switch_during_compaction_requeues_for_a_smaller_target() {+ let mut app = test_app();+ app.context_window = 1_000_000;+ app.tokens = 500_000;+ app.history = (0..10)+ .map(|i| serde_json::json!({ "role": "user", "content": format!("before-{i}") }))+ .collect();+ app.compacting = Some(CompactKind::Auto);++ app.set_model("claude-sonnet-4-5".to_string());+ assert_eq!(+ app.compact_request,+ Some(CompactKind::Auto),+ "a smaller selected model queues a follow-up compaction"+ );++ finish_compaction(+ &mut app,+ Ok(vec![+ serde_json::json!({ "role": "system", "content": "summary" }),+ serde_json::json!({ "role": "user", "content": "x".repeat(2_000_000) }),+ ]),+ 10,+ );++ assert_eq!(+ app.compact_request,+ Some(CompactKind::Auto),+ "the smaller selected model must compact again before a normal request"+ );+ }++ #[test]+ fn header_labels_the_context_source() {+ let app = test_app();let text: String = header_spans(&app).iter().map(|s| s.content.as_ref())@@@ -26884,7 -26110,35 +29047,10 @@@.iter().map(|s| s.content.as_ref()).collect::<String>();-- assert!(text.contains("effort low"), "badge must track the level: {text}");- }-- #[test]- fn subagent_share_is_suppressed_when_the_window_is_untrusted() {- let mut app = test_app();- app.subagents.push(SubagentPanel {- run_id: "r".into(),- name: "alpha".into(),- task: "t".into(),- calls: Vec::new(),- requests: 1,- prompt_tokens: 200_000,- active: None,- queued: false,- waiting: 0,- });- app.apply(StreamEvent::TurnUsage {- usage: usage_of(200_000, 100),- });- let rows = status_panel(&mut app, 120, 8);- let text: String = rows- .iter()- .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))- .collect::<String>();+ assert!(- !text.contains('%'),- "no share against a wrong window: {text}"++ text.contains("effort low"),++ "badge must track the level: {text}"+ );}#[test]@@@ -26907,9 -26161,9 +29073,15 @@@#[test]fn body_includes_reasoning_effort() {let mut app = test_app();-- assert_eq!(app.body().get("reasoning_effort").and_then(|v| v.as_str()), Some("medium"));++ assert_eq!(++ app.body().get("reasoning_effort").and_then(|v| v.as_str()),++ Some("medium")++ );app.reasoning_effort = "high".into();-- assert_eq!(app.body().get("reasoning_effort").and_then(|v| v.as_str()), Some("high"));++ assert_eq!(++ app.body().get("reasoning_effort").and_then(|v| v.as_str()),++ Some("high")++ );}/// The session token budget is the only cap: it is always forwarded, and no@@@ -27272,8 -26503,8 +29442,6 @@@assert!(narrow.len() > 1, "{narrow:?}");}----/// The transcript is laid out on every 50ms tick, so any per-frame work/// proportional to history (rather than to the viewport) compounds into an/// unusable session. `draw` must materialize only the rows on screen.@@@ -27324,133 -26555,7 +29492,135 @@@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,++ ..Default::default()+ },+ )+ .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,++ ..Default::default()+ },+ )+ .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 -------------------------------------------@@@ -27513,7 -26618,7 +29683,11 @@@// 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!(++ 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);@@@ -27601,7 -26706,7 +29775,10 @@@.map(|i| i.value.as_str()).collect();assert!(!values.contains(&super::MCP_ACTION_AUTH), "{values:?}");-- assert!(!values.contains(&super::MCP_ACTION_CLEAR_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:?}");@@@ -27619,7 -26724,7 +29796,10 @@@.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."));++ assert_eq!(++ app.picker.as_ref().unwrap().items[0].hint.as_deref(),++ Some("1.")++ );});}@@@ -27641,7 -26746,7 +29821,9 @@@.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));++ 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!(@@@ -27675,7 -26780,7 +29857,9 @@@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));++ assert!(!items++ .iter()++ .any(|i| i.value == super::MCP_ACTION_CLEAR_AUTH));});}@@@ -27782,10 -26887,10 +29966,12 @@@).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);++ 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()));@@@ -27821,10 -26926,10 +30007,7 @@@#[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 line = Line::from(vec![Span::raw("URL: "), Span::raw("x".repeat(400))]);let clamped = super::clamp_line(line, 40);let width: usize = clamped.spans@@@ -27832,12 -26937,12 +30015,7 @@@.map(|s| s.content.chars().count()).sum();assert!(width <= 38, "clamped to {width}");-- assert!(clamped-- .spans-- .last()-- .unwrap()-- .content-- .ends_with('\u{2026}'));++ assert!(clamped.spans.last().unwrap().content.ends_with('\u{2026}'));}/// The bug #8726 was reverted for: a 2-cell emoji stood in for a 1-cell@@@ -27952,5 -27057,5 +30130,4 @@@"throbber still present in {row:?}");}--}diff --cc src-tauri/src/core/server/provider_secrets.rsindex 2cb9944b6,5d44bdb64..df89031f6--- a/src-tauri/src/core/server/provider_secrets.rs+++ b/src-tauri/src/core/server/provider_secrets.rs@@@ -35,8 -36,9 +36,11 @@@ const NONCE_LEN: usize = 12/// Serializes read-modify-write on the fallback file.static FILE_LOCK: Mutex<()> = Mutex::new(());+#[cfg(test)]+pub(crate) static SECRET_STORE_TEST_LOCK: Mutex<()> = Mutex::new(());+ /// Serializes read-modify-write on the presence index. Separate from+ /// `FILE_LOCK` because the index is updated around calls that take it.+ static INDEX_LOCK: Mutex<()> = Mutex::new(());/// Latched on the first infrastructure-level keyring failure (D-Bus timeout,/// platform/storage-access failure). Once set, every secret op skips the@@@ -107,7 -109,7 +111,10 @@@ fn read_file_map(path: &PathBuf) -> BTrserde_json::from_slice(&plaintext).unwrap_or_default()}--fn write_file_map_atomic(path: &PathBuf, map: &BTreeMap<String, Vec<String>>) -> Result<(), String> {++fn write_file_map_atomic(++ path: &PathBuf,++ map: &BTreeMap<String, Vec<String>>,++) -> Result<(), String> {if let Some(parent) = path.parent() {fs::create_dir_all(parent).map_err(|e| e.to_string())?;}@@@ -132,7 -134,7 +139,10 @@@fn restrict_permissions(path: &PathBuf) {use std::os::unix::fs::PermissionsExt;if let Err(err) = fs::set_permissions(path, fs::Permissions::from_mode(0o600)) {-- log::warn!("Failed to restrict permissions on {}: {err}", path.display());++ log::warn!(++ "Failed to restrict permissions on {}: {err}",++ path.display()++ );}}@@@ -235,33 -300,6 +308,35 @@@ pub async fn set_secret(key: String, va.map_err(|e| e.to_string())?}+/// Store (or replace) one opaque secret record under `key` (namespaced+/// `auth:<key>` so it can never collide with a provider key chain). Used for+/// versioned login credential bundles; empty values delete the entry.+pub fn store_secret_record(key: &str, value: &str) -> Result<(), String> {+ store_provider_keys(&format!("auth:{key}"), &[value.to_string()])+}++/// Read a secret record stored via [`store_secret_record`]. `None` when absent.+pub fn load_secret_record(key: &str) -> Option<String> {- load_provider_keys(&format!("auth:{key}")).into_iter().next()++ load_provider_keys(&format!("auth:{key}"))++ .into_iter()++ .next()+}++/// Remove a secret record stored via [`store_secret_record`]. Missing entries+/// are not an error.+pub fn delete_secret_record(key: &str) -> Result<(), String> {+ delete_provider_keys(&format!("auth:{key}"))+}++/// Force the encrypted-file fallback for the rest of the process. Test-only:+/// lets unit tests exercise the file path without touching the developer's+/// keychain. Every caller is a `cli`-feature test, so the desktop build would+/// otherwise carry it unused.+#[cfg(all(test, feature = "cli"))]+pub(crate) fn force_file_secrets() {+ KEYRING_DOWN.store(true, Ordering::Relaxed);+}+/// Read a single generic secret stored via `set_secret`. None when absent.#[cfg(not(feature = "cli"))]#[tauri::command]@@@ -277,18 -315,19 +352,19 @@@ mod testsuse super::*;use std::sync::MutexGuard;- /// `resolve_jan_data_folder` reads process-wide env, so tests that redirect- /// it must not run concurrently.- static ENV_LOCK: Mutex<()> = Mutex::new(());--+ // Field order is drop order: `_dir` must be removed and the env restored+ // while the lock is still held, so `_guard` has to be the last field.struct TempDataFolder {- _guard: MutexGuard<'static, ()>,prev_data_folder: Option<String>,_dir: tempfile::TempDir,+ _guard: MutexGuard<'static, ()>,}impl TempDataFolder {fn new() -> Self {- let guard = SECRET_STORE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());- let guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());++ let guard = SECRET_STORE_TEST_LOCK++ .lock()++ .unwrap_or_else(|e| e.into_inner());let dir = tempfile::tempdir().unwrap();let prev_data_folder = std::env::var("JAN_DATA_FOLDER").ok();// Portable override: XDG_DATA_HOME only redirects on Linux, so@@@ -334,12 -373,45 +410,45 @@@// A missing key is normal churn -> must not disable the keyring.assert!(!is_infra_failure(&keyring::Error::NoEntry));// Backend-unusable errors (D-Bus timeout surfaces as PlatformFailure) latch.-- assert!(is_infra_failure(&keyring::Error::PlatformFailure(Box::new(-- std::io::Error::other("dbus timeout")-- ))));-- assert!(is_infra_failure(&keyring::Error::NoStorageAccess(Box::new(-- std::io::Error::other("locked")-- ))));++ assert!(is_infra_failure(&keyring::Error::PlatformFailure(++ Box::new(std::io::Error::other("dbus timeout"))++ )));++ assert!(is_infra_failure(&keyring::Error::NoStorageAccess(++ Box::new(std::io::Error::other("locked"))++ )));+ }++ /// Presence must be answerable from the index alone: `has_stored_key` is+ /// what replaced probing the real store, and probing is exactly the thing+ /// that costs a keychain prompt per provider on macOS.+ #[test]+ fn the_index_answers_presence_without_the_secret() {+ let _tmp = TempDataFolder::new();+ assert!(!has_stored_key("openai"));++ index_set("openai", true);+ assert!(has_stored_key("openai"));+ assert!(!has_stored_key("anthropic"), "presence is per provider");++ // The index carries names, never key material.+ let raw = fs::read_to_string(secrets_index_path()).unwrap();+ assert!(raw.contains("openai"));++ index_set("openai", false);+ assert!(!has_stored_key("openai"));+ }++ /// An install whose keys predate the index still has the encrypted fallback+ /// file, which is free to read, so presence is not silently lost there.+ #[test]+ fn the_fallback_file_backstops_a_missing_index() {+ let _tmp = TempDataFolder::new();+ file_store("openai", &["sk-x".to_string()]).unwrap();+ assert!(+ !secrets_index_path().exists(),+ "no index written by file_store"+ );+ assert!(has_stored_key("openai"));}#[test]@@@ -387,8 -459,8 +496,14 @@@file_store("openai", &[secret.to_string()]).unwrap();let bytes = fs::read(secrets_file_path()).unwrap();let haystack = String::from_utf8_lossy(&bytes);-- assert!(!haystack.contains(secret), "secret must not appear in plaintext on disk");-- assert!(!haystack.contains("openai"), "provider name must not appear in plaintext");++ assert!(++ !haystack.contains(secret),++ "secret must not appear in plaintext on disk"++ );++ assert!(++ !haystack.contains("openai"),++ "provider name must not appear in plaintext"++ );}#[cfg(unix)]@@@ -397,7 -469,7 +512,10 @@@use std::os::unix::fs::PermissionsExt;let _tmp = TempDataFolder::new();file_store("openai", &["sk-x".to_string()]).unwrap();-- let mode = fs::metadata(secrets_file_path()).unwrap().permissions().mode();++ let mode = fs::metadata(secrets_file_path())++ .unwrap()++ .permissions()++ .mode();assert_eq!(mode & 0o777, 0o600);}}diff --cc src-tauri/src/core/setup.rsindex 19f13cdee,19f13cdee..14b846799--- a/src-tauri/src/core/setup.rs+++ b/src-tauri/src/core/setup.rs@@@ -1,4 -1,4 +1,6 @@@--use std::{fs, path::PathBuf, sync::Arc, time::Duration};++use std::{fs, sync::Arc, time::Duration};++#[cfg(target_os = "linux")]++use std::path::PathBuf;use tauri::{App, AppHandle, Emitter, Listener, Manager, Runtime, WindowEvent, Wry};#[cfg(feature = "desktop")]diff --cc src-tauri/src/core/system/commands.rsindex 73b39914e,f66baa170..755aa0e78--- a/src-tauri/src/core/system/commands.rs+++ b/src-tauri/src/core/system/commands.rs@@@ -1167,4 -1194,61 +1194,60 @@@ mod tests"/home/user/.local/share/jan")));}+ #[test]+ fn claude_code_env_uses_real_token_when_set() {+ let env = build_claude_code_env_vars(+ "http://127.0.0.1:1337".to_string(),+ Some("sk-real-secret".to_string()),+ None,+ None,+ None,+ vec![],+ )+ .unwrap();+ let token = env+ .iter()+ .find(|(k, _)| k == "ANTHROPIC_AUTH_TOKEN")+ .map(|(_, v)| v.as_str())+ .unwrap();+ assert_eq!(token, "sk-real-secret");+ assert!(env+ .iter()+ .all(|(_, v)| v != "jan"),+ "placeholder must never be shipped as a token");+ }++ #[test]+ fn claude_code_env_rejects_missing_key() {+ let err = build_claude_code_env_vars(+ "http://127.0.0.1:1337".to_string(),+ None,+ None,+ None,+ None,+ vec![],+ )+ .unwrap_err();+ assert!(+ err.contains("API key"),+ "should tell the user a local API key is required: {err}"+ );+ }++ #[test]+ fn claude_code_env_rejects_blank_key() {+ let err = build_claude_code_env_vars(+ "http://127.0.0.1:1337".to_string(),+ Some(" ".to_string()),+ None,+ None,+ None,+ vec![],+ )+ .unwrap_err();+ assert!(+ err.contains("API key"),+ "a whitespace-only key is not a real credential: {err}"+ );+ }}-