Pannello endpoint /endpoint e primo avvio guidato (ripristino da 0.9.2, senza provider predefiniti)

Riportato dalla 0.9.2 solo cio' che serve alla configurazione dei provider:
- /endpoint nella TUI: elenco provider, aggiunta/modifica/rimozione, scelta del
  modello da /v1/models, impostazioni per modello (contesto, temperatura, top_p,
  max output, ragionamento, nome mostrato), nomi abbreviati dei modelli.
- primo avvio guidato quando non c'e' alcun provider: endpoint, chiave, dove
  salvarla (portachiavi o file protetto), elenco modelli dal server, prova della
  connessione, salvataggio in config.toml.
- chiavi per provider nel portachiavi (`api_key = "keyring"`,
  `akode login --provider <id> --with-api-key`, `akode logout --provider <id>`).

Nessun URL, modello o provider predefinito nel codice; nessun provider cloud tra
le scelte (solo endpoint personalizzato e i provider locali Ollama/LM Studio
gia' presenti in upstream). Lasciati fuori: passo tema e passo ricerca web
(SearXNG) del primo avvio, barra di stato, unione messaggi di sistema, header @@,
modello ausiliario, tool function di apply_patch.

Test: test CLI debug_models riportato al comportamento upstream (catalogo
incluso); snapshot doctor aggiornati al nome e alla versione aKode.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 17:41:20 +01:00
parent 565079cb94
commit 2c78ef50e1
106 changed files with 7068 additions and 84 deletions

3
akode-rs/Cargo.lock generated
View File

@@ -718,6 +718,7 @@ dependencies = [
"akode-mcp", "akode-mcp",
"akode-memories-write", "akode-memories-write",
"akode-model-provider", "akode-model-provider",
"akode-model-provider-info",
"akode-models-manager", "akode-models-manager",
"akode-multi-env-copy-file", "akode-multi-env-copy-file",
"akode-plugin", "akode-plugin",
@@ -2239,10 +2240,12 @@ version = "0.10.0-pulito"
dependencies = [ dependencies = [
"akode-client", "akode-client",
"akode-http-client", "akode-http-client",
"akode-keyring-store",
"akode-protocol", "akode-protocol",
"akode-utils-absolute-path", "akode-utils-absolute-path",
"akode-utils-redacted-string", "akode-utils-redacted-string",
"http 1.4.0", "http 1.4.0",
"keyring",
"maplit", "maplit",
"pretty_assertions", "pretty_assertions",
"schemars 0.8.22", "schemars 0.8.22",

View File

@@ -568,6 +568,9 @@ mod thread_processor_behavior_tests {
async fn derive_config_from_params_uses_session_thread_config_model_provider() -> Result<()> { async fn derive_config_from_params_uses_session_thread_config_model_provider() -> Result<()> {
let temp_dir = TempDir::new()?; let temp_dir = TempDir::new()?;
let session_provider = ModelProviderInfo { let session_provider = ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "session".to_string(), name: "session".to_string(),
base_url: Some("http://127.0.0.1:8061/api/codex".to_string()), base_url: Some("http://127.0.0.1:8061/api/codex".to_string()),
model_catalog_url: None, model_catalog_url: None,

View File

@@ -61,6 +61,7 @@ akode-login = { workspace = true }
akode-memories-write = { workspace = true } akode-memories-write = { workspace = true }
akode-mcp = { workspace = true } akode-mcp = { workspace = true }
akode-model-provider = { workspace = true } akode-model-provider = { workspace = true }
akode-model-provider-info = { workspace = true }
akode-models-manager = { workspace = true } akode-models-manager = { workspace = true }
akode-plugin = { workspace = true } akode-plugin = { workspace = true }
akode-protocol = { workspace = true } akode-protocol = { workspace = true }

View File

@@ -15,8 +15,10 @@ pub use debug_sandbox::run_command_under_seatbelt;
pub use debug_sandbox::run_command_under_windows_sandbox; pub use debug_sandbox::run_command_under_windows_sandbox;
pub use login::read_api_key_from_stdin; pub use login::read_api_key_from_stdin;
pub use login::run_login_status; pub use login::run_login_status;
pub use login::run_login_provider_api_key;
pub use login::run_login_with_api_key; pub use login::run_login_with_api_key;
pub use login::run_logout; pub use login::run_logout;
pub use login::run_logout_provider;
#[derive(Debug, Default, Args)] #[derive(Debug, Default, Args)]
pub struct SandboxStateArgs { pub struct SandboxStateArgs {

View File

@@ -184,6 +184,109 @@ fn read_stdin_secret(terminal_message: &str, reading_message: &str, empty_messag
secret secret
} }
/// Stores the API key of one model provider (`api_key = "keyring"`) in the configured
/// provider key store (system keyring, or the private fallback file).
pub async fn run_login_provider_api_key(
cli_config_overrides: CliConfigOverrides,
provider_id: String,
api_key: String,
) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
tracing::info!("storing a provider API key");
if let Some(notice) = provider_key_notice(&provider_id, config.model_providers.get(&provider_id))
{
eprintln!("{notice}");
}
match akode_model_provider_info::save_provider_api_key(&provider_id, &api_key) {
Ok(location) => {
eprintln!(
"API key for `{provider_id}` saved in {location}. {API_KEY_AUTHENTICATION_NOTICE}"
);
std::process::exit(0);
}
Err(error) => {
eprintln!("Error saving the API key: {error}");
std::process::exit(1);
}
}
}
/// Message printed before saving a key: keys under `mcp:<server>` belong to MCP servers, not
/// to model providers, so they never get the model-provider warnings.
fn provider_key_notice(
provider_id: &str,
provider: Option<&akode_model_provider_info::ModelProviderInfo>,
) -> Option<String> {
if let Some(server) = provider_id.strip_prefix("mcp:") {
return Some(format!(
"Key for MCP server `{server}`: sent as Bearer token when the server's bearer_token_env_var is not set."
));
}
match provider {
Some(provider)
if provider.api_key
== Some(akode_model_provider_info::ProviderApiKeySource::Keyring) =>
{
None
}
Some(_) => Some(format!(
"Warning: model_providers.{provider_id} does not set api_key = \"keyring\"; the stored key is used only after you add it."
)),
None => Some(format!(
"Warning: model provider `{provider_id}` is not defined in config.toml yet; add [model_providers.{provider_id}] with api_key = \"keyring\"."
)),
}
}
/// Removes the stored API key of one model provider.
pub async fn run_logout_provider(
cli_config_overrides: CliConfigOverrides,
provider_id: String,
) -> ! {
let _config = load_config_or_exit(cli_config_overrides).await;
match akode_model_provider_info::delete_provider_api_key(&provider_id) {
Ok(true) => eprintln!("Removed the stored API key for `{provider_id}`"),
Ok(false) => eprintln!("No API key is stored for `{provider_id}`"),
Err(error) => {
eprintln!("Error removing the API key: {error}");
std::process::exit(1);
}
}
std::process::exit(0);
}
/// Prints where each `api_key = "keyring"` provider key is stored (never the key itself).
/// Returns whether any provider key is available.
fn print_provider_key_status(config: &Config) -> bool {
let mut any = false;
let mut ids = config.model_providers.keys().collect::<Vec<_>>();
ids.sort();
for id in ids {
let provider = &config.model_providers[id];
if provider.api_key == Some(akode_model_provider_info::ProviderApiKeySource::Keyring) {
match akode_model_provider_info::locate_provider_api_key(id) {
Ok(Some(location)) => {
any = true;
eprintln!("Provider `{id}`: API key stored in {location}");
}
Ok(None) => eprintln!(
"Provider `{id}`: no API key stored (akode login --provider {id} --with-api-key)"
),
Err(error) => eprintln!("Provider `{id}`: cannot read the key store: {error}"),
}
} else if let Some(env_key) = &provider.env_key {
let present = std::env::var(env_key).is_ok_and(|value| !value.trim().is_empty());
any |= present;
eprintln!(
"Provider `{id}`: API key from ${env_key} ({})",
if present { "set" } else { "not set" }
);
}
}
any
}
/// Login using the OAuth device code flow. /// Login using the OAuth device code flow.
pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! { pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
let config = load_config_or_exit(cli_config_overrides).await; let config = load_config_or_exit(cli_config_overrides).await;
@@ -197,6 +300,7 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
AuthMode::ApiKey => match auth.get_token() { AuthMode::ApiKey => match auth.get_token() {
Ok(api_key) => { Ok(api_key) => {
eprintln!("API key configured - {}", safe_format_key(&api_key)); eprintln!("API key configured - {}", safe_format_key(&api_key));
print_provider_key_status(&config);
eprintln!("{API_KEY_AUTHENTICATION_NOTICE}"); eprintln!("{API_KEY_AUTHENTICATION_NOTICE}");
std::process::exit(0); std::process::exit(0);
} }
@@ -210,6 +314,9 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
} }
}, },
Ok(None) => { Ok(None) => {
if print_provider_key_status(&config) {
std::process::exit(0);
}
eprintln!("Not logged in"); eprintln!("Not logged in");
std::process::exit(1); std::process::exit(1);
} }
@@ -297,8 +404,22 @@ mod storage_tests;
mod tests { mod tests {
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use super::provider_key_notice;
use super::safe_format_key; use super::safe_format_key;
#[test]
fn mcp_keys_get_no_model_provider_warning() {
let notice = provider_key_notice("mcp:memoria", None).expect("notice");
assert!(notice.contains("MCP server `memoria`"), "{notice}");
assert!(!notice.contains("model_providers"), "{notice}");
}
#[test]
fn unknown_model_provider_still_warns() {
let notice = provider_key_notice("imeai", None).expect("notice");
assert!(notice.contains("[model_providers.imeai]"), "{notice}");
}
#[test] #[test]
fn formats_long_key() { fn formats_long_key() {
let key = "sk-proj-1234567890ABCDE"; let key = "sk-proj-1234567890ABCDE";

View File

@@ -10,8 +10,10 @@ use akode_arg0::arg0_dispatch_or_else;
use akode_cli::local_config; use akode_cli::local_config;
use akode_cli::read_api_key_from_stdin; use akode_cli::read_api_key_from_stdin;
use akode_cli::run_login_status; use akode_cli::run_login_status;
use akode_cli::run_login_provider_api_key;
use akode_cli::run_login_with_api_key; use akode_cli::run_login_with_api_key;
use akode_cli::run_logout; use akode_cli::run_logout;
use akode_cli::run_logout_provider;
use akode_exec::Cli as ExecCli; use akode_exec::Cli as ExecCli;
use akode_exec::Command as ExecCommand; use akode_exec::Command as ExecCommand;
use akode_exec::ReviewArgs; use akode_exec::ReviewArgs;
@@ -501,6 +503,11 @@ struct LoginCommand {
)] )]
api_key: Option<String>, api_key: Option<String>,
/// Store the key for this model provider (`[model_providers.<id>] api_key = "keyring"`)
/// instead of the shared stored key.
#[arg(long = "provider", value_name = "PROVIDER_ID")]
provider: Option<String>,
#[command(subcommand)] #[command(subcommand)]
action: Option<LoginSubcommand>, action: Option<LoginSubcommand>,
} }
@@ -515,6 +522,10 @@ enum LoginSubcommand {
struct LogoutCommand { struct LogoutCommand {
#[clap(skip)] #[clap(skip)]
config_overrides: CliConfigOverrides, config_overrides: CliConfigOverrides,
/// Remove only the stored API key of this model provider.
#[arg(long = "provider", value_name = "PROVIDER_ID")]
provider: Option<String>,
} }
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
@@ -1435,7 +1446,19 @@ async fn dispatch_cli(
std::process::exit(1); std::process::exit(1);
} else if login_cli.with_api_key { } else if login_cli.with_api_key {
let api_key = read_api_key_from_stdin(); let api_key = read_api_key_from_stdin();
run_login_with_api_key(login_cli.config_overrides, api_key).await; match login_cli.provider {
Some(provider_id) => {
run_login_provider_api_key(
login_cli.config_overrides,
provider_id,
api_key,
)
.await;
}
None => {
run_login_with_api_key(login_cli.config_overrides, api_key).await;
}
}
} else { } else {
eprintln!( eprintln!(
"Only API key login is supported. Pipe the key on stdin, e.g. `printenv MY_KEY | akode login --with-api-key`." "Only API key login is supported. Pipe the key on stdin, e.g. `printenv MY_KEY | akode login --with-api-key`."
@@ -1455,7 +1478,12 @@ async fn dispatch_cli(
&mut logout_cli.config_overrides, &mut logout_cli.config_overrides,
root_config_overrides.clone(), root_config_overrides.clone(),
); );
run_logout(logout_cli.config_overrides).await; match logout_cli.provider {
Some(provider_id) => {
run_logout_provider(logout_cli.config_overrides, provider_id).await;
}
None => run_logout(logout_cli.config_overrides).await,
}
} }
Some(Subcommand::Completion(completion_cli)) => { Some(Subcommand::Completion(completion_cli)) => {
reject_remote_mode_for_subcommand( reject_remote_mode_for_subcommand(

View File

@@ -25,7 +25,7 @@ fn debug_models_bundled_prints_json() -> Result<()> {
} }
#[test] #[test]
fn debug_models_default_prints_empty_json_without_provider() -> Result<()> { fn debug_models_default_prints_json_without_auth() -> Result<()> {
let codex_home = TempDir::new()?; let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?; let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models"]).output()?; let output = cmd.args(["debug", "models"]).output()?;
@@ -34,8 +34,7 @@ fn debug_models_default_prints_empty_json_without_provider() -> Result<()> {
let stdout = String::from_utf8(output.stdout)?; let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?; let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array()); assert!(value["models"].is_array());
// aKode has no default provider and no built-in catalog: nothing to list, no network. assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
assert!(value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(()) Ok(())
} }

View File

@@ -2,7 +2,7 @@
source: cli/tests/doctor_enterprise_network.rs source: cli/tests/doctor_enterprise_network.rs
expression: stdout expression: stdout
--- ---
Codex Doctor v0.0.0 aKode Doctor v0.10.0-pulito
Notes Notes
[XX] config config could not be loaded - Fix the reported config error, then rerun akode doctor. [XX] config config could not be loaded - Fix the reported config error, then rerun akode doctor.

View File

@@ -2,7 +2,7 @@
source: cli/tests/doctor_enterprise_network.rs source: cli/tests/doctor_enterprise_network.rs
expression: stdout expression: stdout
--- ---
Codex Doctor v0.0.0 aKode Doctor v0.10.0-pulito
Configuration Configuration
[ok] config loaded [ok] config loaded

View File

@@ -0,0 +1,17 @@
---
source: cli/tests/doctor_path_safety.rs
expression: "serde_json::to_string_pretty(&check)?"
---
{
"category": "config",
"details": {
"column": "16",
"error": "invalid configuration",
"file": "FIXTURE/home/config.toml",
"line": "9"
},
"id": "config.load",
"remediation": "Fix the reported config error, then rerun akode doctor.",
"status": "fail",
"summary": "config could not be loaded"
}

View File

@@ -478,6 +478,13 @@ pub struct ConfigToml {
pub experimental_thread_store: Option<ThreadStoreToml>, pub experimental_thread_store: Option<ThreadStoreToml>,
pub projects: Option<HashMap<String, ProjectConfig>>, pub projects: Option<HashMap<String, ProjectConfig>>,
/// Where per-provider API keys (`api_key = "keyring"`) are stored.
/// auto (default): the system keyring if available, otherwise
/// `AKODE_HOME/provider_api_keys.json` (owner-only permissions).
/// keyring: the system keyring only. file: the file only. ephemeral: memory only.
#[serde(default)]
pub provider_api_key_store: Option<AuthCredentialsStoreMode>,
/// Controls the web search tool mode: disabled, cached, indexed, or live. /// Controls the web search tool mode: disabled, cached, indexed, or live.
pub web_search: Option<WebSearchMode>, pub web_search: Option<WebSearchMode>,

View File

@@ -304,6 +304,7 @@ mod tests {
experimental_bearer_token: None, experimental_bearer_token: None,
auth: None, auth: None,
gateway_oauth: None, gateway_oauth: None,
api_key: None,
wire_api: WireApi::Responses, wire_api: WireApi::Responses,
query_params: None, query_params: None,
http_headers: None, http_headers: None,
@@ -316,7 +317,9 @@ mod tests {
supports_websockets: true, supports_websockets: true,
supports_standalone_web_search: true, supports_standalone_web_search: true,
capabilities: None, capabilities: None,
keyring_account: None,
include_internal_metadata: false, include_internal_metadata: false,
models: Default::default(),
} }
} }
} }

View File

@@ -183,6 +183,7 @@ fn model_provider_from_proto(
.map(model_provider_auth_from_proto) .map(model_provider_auth_from_proto)
.transpose()?, .transpose()?,
gateway_oauth: None, gateway_oauth: None,
api_key: None,
wire_api, wire_api,
query_params: provider.query_params.map(redacted_string_map), query_params: provider.query_params.map(redacted_string_map),
http_headers: provider.http_headers.map(redacted_string_map), http_headers: provider.http_headers.map(redacted_string_map),
@@ -202,6 +203,8 @@ fn model_provider_from_proto(
}), }),
// Retired Google Cloud fields (project_id, location, credential_file) are ignored. // Retired Google Cloud fields (project_id, location, credential_file) are ignored.
include_internal_metadata: false, include_internal_metadata: false,
keyring_account: None,
models: Default::default(),
}; };
Ok((id, info)) Ok((id, info))
} }
@@ -220,6 +223,8 @@ fn model_provider_to_proto(
experimental_bearer_token, experimental_bearer_token,
auth, auth,
gateway_oauth: _, gateway_oauth: _,
api_key: _,
keyring_account: _,
wire_api, wire_api,
query_params, query_params,
http_headers, http_headers,
@@ -233,6 +238,7 @@ fn model_provider_to_proto(
supports_standalone_web_search, supports_standalone_web_search,
include_internal_metadata: _, include_internal_metadata: _,
capabilities, capabilities,
models: _,
} = provider; } = provider;
proto::ModelProvider { proto::ModelProvider {
@@ -613,10 +619,13 @@ mod tests {
supports_websockets: true, supports_websockets: true,
supports_standalone_web_search: true, supports_standalone_web_search: true,
gateway_oauth: None, gateway_oauth: None,
api_key: None,
capabilities: Some(ModelProviderCapabilities { capabilities: Some(ModelProviderCapabilities {
cyber_access_programs: Some(true), cyber_access_programs: Some(true),
..Default::default() ..Default::default()
}), }),
keyring_account: None,
models: Default::default(),
include_internal_metadata: false, include_internal_metadata: false,
} }
} }

View File

@@ -3048,6 +3048,14 @@
"additionalProperties": false, "additionalProperties": false,
"description": "Serializable representation of a provider definition.", "description": "Serializable representation of a provider definition.",
"properties": { "properties": {
"api_key": {
"allOf": [
{
"$ref": "#/definitions/ProviderApiKeySource"
}
],
"description": "Where to read this provider's API key from. `\"keyring\"` reads the key stored with `akode login --provider <id> --with-api-key`: in the system keyring, or in a private file in AKODE_HOME when `provider_api_key_store` selects (or falls back to) file storage."
},
"auth": { "auth": {
"allOf": [ "allOf": [
{ {
@@ -3106,6 +3114,13 @@
"description": "Optional full URL for a Codex-native model catalog (Codex catalog format, not the public `/v1/models` API). When unset, models are listed from `GET {base_url}/models`.\n\nCatalog requests use the provider's credentials. Only configure an endpoint you trust with those credentials.", "description": "Optional full URL for a Codex-native model catalog (Codex catalog format, not the public `/v1/models` API). When unset, models are listed from `GET {base_url}/models`.\n\nCatalog requests use the provider's credentials. Only configure an endpoint you trust with those credentials.",
"type": "string" "type": "string"
}, },
"models": {
"additionalProperties": {
"$ref": "#/definitions/ProviderModelSettings"
},
"description": "Per-model settings keyed by model id (`[model_providers.<id>.models.\"<model id>\"]`). A value set here wins over the matching global setting (e.g. `model_context_window`).",
"type": "object"
},
"name": { "name": {
"default": "", "default": "",
"description": "Friendly display name.", "description": "Friendly display name.",
@@ -3126,7 +3141,7 @@
}, },
"requires_openai_auth": { "requires_openai_auth": {
"default": false, "default": false,
"description": "Use the API key stored with `akode login --with-api-key` (in `auth.json` or the credentials store selected by `cli_auth_credentials_store`) for this provider. When false (the default), the key comes from `env_key` or `auth`, if any.", "description": "Use the API key stored with `akode login --with-api-key` (in `auth.json` or the credentials store selected by `cli_auth_credentials_store`) for this provider. `use_stored_api_key` is accepted as a clearer alias. When false (the default), the key comes from `api_key`, `env_key`, or `auth`, if any.",
"type": "boolean" "type": "boolean"
}, },
"stream_idle_timeout_ms": { "stream_idle_timeout_ms": {
@@ -3951,6 +3966,58 @@
}, },
"type": "object" "type": "object"
}, },
"ProviderApiKeySource": {
"description": "Source of a provider API key configured through `api_key`.",
"oneOf": [
{
"description": "Read the key from the system keyring (service `aKode`, account `model-provider:<id>`).",
"enum": [
"keyring"
],
"type": "string"
}
]
},
"ProviderModelSettings": {
"additionalProperties": false,
"description": "Settings for one model of a provider. Every value is optional; unset values fall back to the global settings, then to what the server reports, then to the defaults.",
"properties": {
"context_window": {
"description": "Context window in tokens (wins over `model_context_window`).",
"format": "int64",
"type": "integer"
},
"display_name": {
"description": "Name shown in the interface instead of the model id (the API always gets the id).",
"type": "string"
},
"max_output_tokens": {
"description": "Maximum output tokens per response (`max_output_tokens`).",
"format": "uint64",
"minimum": 0.0,
"type": "integer"
},
"reasoning_effort": {
"allOf": [
{
"$ref": "#/definitions/ReasoningEffort"
}
],
"description": "Reasoning effort (wins over `model_reasoning_effort`)."
},
"temperature": {
"description": "Sampling temperature sent with each request.",
"format": "double",
"type": "number"
},
"top_p": {
"description": "Nucleus sampling (`top_p`) sent with each request.",
"format": "double",
"type": "number"
}
},
"type": "object"
},
"ProxySecretSource": { "ProxySecretSource": {
"description": "A credential source in the trusted proxy process, never in the executor environment.", "description": "A credential source in the trusted proxy process, never in the executor environment.",
"oneOf": [ "oneOf": [
@@ -8557,6 +8624,15 @@
}, },
"type": "object" "type": "object"
}, },
"provider_api_key_store": {
"allOf": [
{
"$ref": "#/definitions/AuthCredentialsStoreMode"
}
],
"default": null,
"description": "Where per-provider API keys (`api_key = \"keyring\"`) are stored. auto (default): the system keyring if available, otherwise `AKODE_HOME/provider_api_keys.json` (owner-only permissions). keyring: the system keyring only. file: the file only. ephemeral: memory only."
},
"realtime": { "realtime": {
"allOf": [ "allOf": [
{ {

View File

@@ -1186,6 +1186,9 @@ pub struct Config {
pub web_search_mode: Constrained<WebSearchMode>, pub web_search_mode: Constrained<WebSearchMode>,
/// Additional parameters for the web search tool when it is enabled. /// Additional parameters for the web search tool when it is enabled.
/// Where per-provider API keys are stored (`provider_api_key_store`, default auto).
pub provider_api_key_store_mode: AuthCredentialsStoreMode,
pub web_search_config: Option<WebSearchConfig>, pub web_search_config: Option<WebSearchConfig>,
/// Whether to register the experimental request_user_input tool. /// Whether to register the experimental request_user_input tool.
@@ -4050,6 +4053,11 @@ impl Config {
let agent_roles = let agent_roles =
load_agent_roles(fs, &cfg, &config_layer_stack, &mut startup_warnings).await?; load_agent_roles(fs, &cfg, &config_layer_stack, &mut startup_warnings).await?;
let provider_api_key_store_mode = cfg
.provider_api_key_store
.unwrap_or(AuthCredentialsStoreMode::Auto);
// `api_key = "keyring"` providers read through this process-wide store.
akode_login::install_provider_api_key_store(codex_home.as_path(), provider_api_key_store_mode);
let model_providers = let model_providers =
merge_configured_model_providers(built_in_model_providers(), cfg.model_providers) merge_configured_model_providers(built_in_model_providers(), cfg.model_providers)
.map_err(|message| std::io::Error::new(std::io::ErrorKind::InvalidData, message))?; .map_err(|message| std::io::Error::new(std::io::ErrorKind::InvalidData, message))?;
@@ -4755,6 +4763,7 @@ impl Config {
experimental_thread_store: thread_store_config(cfg.experimental_thread_store), experimental_thread_store: thread_store_config(cfg.experimental_thread_store),
forced_chatgpt_workspace_id, forced_chatgpt_workspace_id,
forced_login_method, forced_login_method,
provider_api_key_store_mode,
web_search_mode: constrained_web_search_mode.value, web_search_mode: constrained_web_search_mode.value,
web_search_config, web_search_config,
experimental_request_user_input_enabled, experimental_request_user_input_enabled,

View File

@@ -72,6 +72,9 @@ async fn responses_stream_includes_subagent_header_on_review() {
.await; .await;
let provider = ModelProviderInfo { let provider = ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "mock".into(), name: "mock".into(),
base_url: Some(format!("{}/v1", server.uri())), base_url: Some(format!("{}/v1", server.uri())),
model_catalog_url: None, model_catalog_url: None,
@@ -214,6 +217,9 @@ async fn responses_stream_includes_subagent_header_on_other() {
.await; .await;
let provider = ModelProviderInfo { let provider = ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "mock".into(), name: "mock".into(),
base_url: Some(format!("{}/v1", server.uri())), base_url: Some(format!("{}/v1", server.uri())),
model_catalog_url: None, model_catalog_url: None,
@@ -337,6 +343,9 @@ async fn responses_respects_model_info_overrides_from_config() {
let request_recorder = responses::mount_sse_once(&server, response_body).await; let request_recorder = responses::mount_sse_once(&server, response_body).await;
let provider = ModelProviderInfo { let provider = ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "mock".into(), name: "mock".into(),
base_url: Some(format!("{}/v1", server.uri())), base_url: Some(format!("{}/v1", server.uri())),
model_catalog_url: None, model_catalog_url: None,

View File

@@ -1669,6 +1669,9 @@ async fn provider_auth_command_recovers_after_initial_resolution_failure() {
/// reaches `Completed` without surfacing an auth or transport error to the client. /// reaches `Completed` without surfacing an auth or transport error to the client.
async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuthInfo) { async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuthInfo) {
let provider = ModelProviderInfo { let provider = ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "corp".into(), name: "corp".into(),
base_url: Some(format!("{}/v1", server.uri())), base_url: Some(format!("{}/v1", server.uri())),
model_catalog_url: None, model_catalog_url: None,
@@ -2899,6 +2902,9 @@ async fn azure_responses_request_does_not_store_and_preserves_prefixed_item_ids(
let resp_mock = mount_sse_once(&server, sse_body.to_string()).await; let resp_mock = mount_sse_once(&server, sse_body.to_string()).await;
let provider = ModelProviderInfo { let provider = ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "azure".into(), name: "azure".into(),
base_url: Some(format!("{}/openai", server.uri())), base_url: Some(format!("{}/openai", server.uri())),
model_catalog_url: None, model_catalog_url: None,
@@ -3736,6 +3742,9 @@ async fn azure_overrides_assign_properties_used_for_responses_url() {
.await; .await;
let provider = ModelProviderInfo { let provider = ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "custom".to_string(), name: "custom".to_string(),
base_url: Some(format!("{}/openai", server.uri())), base_url: Some(format!("{}/openai", server.uri())),
model_catalog_url: None, model_catalog_url: None,
@@ -3823,6 +3832,9 @@ async fn env_var_overrides_loaded_auth() {
.await; .await;
let provider = ModelProviderInfo { let provider = ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: core_test_support::test_codex::test_model_provider_info(/*base_url*/ None).name, name: core_test_support::test_codex::test_model_provider_info(/*base_url*/ None).name,
base_url: Some(format!("{}/openai", server.uri())), base_url: Some(format!("{}/openai", server.uri())),
model_catalog_url: None, model_catalog_url: None,

View File

@@ -2779,6 +2779,9 @@ fn websocket_provider_with_connect_timeout(
websocket_connect_timeout_ms: Option<u64>, websocket_connect_timeout_ms: Option<u64>,
) -> ModelProviderInfo { ) -> ModelProviderInfo {
ModelProviderInfo { ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "mock-ws".into(), name: "mock-ws".into(),
base_url: Some(format!("{}/v1", server.uri())), base_url: Some(format!("{}/v1", server.uri())),
model_catalog_url: None, model_catalog_url: None,

View File

@@ -64,6 +64,9 @@ async fn continue_after_stream_error() {
// server. Use an existing env var (PATH) to satisfy the auth plumbing // server. Use an existing env var (PATH) to satisfy the auth plumbing
// without requiring a real secret. // without requiring a real secret.
let provider = ModelProviderInfo { let provider = ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "mock-openai".into(), name: "mock-openai".into(),
base_url: Some(format!("{}/v1", server.uri())), base_url: Some(format!("{}/v1", server.uri())),
model_catalog_url: None, model_catalog_url: None,

View File

@@ -46,6 +46,9 @@ async fn retries_on_early_close() {
// environment variables. // environment variables.
let model_provider = ModelProviderInfo { let model_provider = ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "openai".into(), name: "openai".into(),
base_url: Some(format!("{}/v1", server.uri())), base_url: Some(format!("{}/v1", server.uri())),
model_catalog_url: None, model_catalog_url: None,

View File

@@ -348,7 +348,7 @@ fn test_macos() {
let user_agent = get_codex_user_agent(); let user_agent = get_codex_user_agent();
let originator = regex_lite::escape(originator().value.as_str()); let originator = regex_lite::escape(originator().value.as_str());
let re = Regex::new(&format!( let re = Regex::new(&format!(
r"^{originator}/\d+\.\d+\.\d+ \(Mac OS \d+\.\d+\.\d+; (x86_64|arm64)\) (\S+)$" r"^{originator}/\d+\.\d+\.\d+(-\S+)? \(Mac OS \d+\.\d+\.\d+; (x86_64|arm64)\) (\S+)$"
)) ))
.unwrap(); .unwrap();
assert!(re.is_match(&user_agent)); assert!(re.is_match(&user_agent));

View File

@@ -8,6 +8,7 @@ mod storage;
mod external_bearer; mod external_bearer;
mod manager; mod manager;
mod provider_api_key;
pub use api_key::is_fedramp_api_key; pub use api_key::is_fedramp_api_key;
pub use auth_headers::AuthHeaders; pub use auth_headers::AuthHeaders;
@@ -17,3 +18,12 @@ pub use change_state::RequestAuthChange;
pub use error::RefreshTokenFailedError; pub use error::RefreshTokenFailedError;
pub use error::RefreshTokenFailedReason; pub use error::RefreshTokenFailedReason;
pub use manager::*; pub use manager::*;
pub use provider_api_key::PROVIDER_API_KEYS_FILE;
pub use provider_api_key::ProviderApiKeyFileStore;
pub use provider_api_key::configured_provider_api_key_store;
pub use provider_api_key::configured_provider_api_key_store_with_keyring;
pub use provider_api_key::install_provider_api_key_store;
pub use provider_api_key::provider_api_key_keyring_available;
pub use provider_api_key::provider_api_key_keyring_available_with;
pub use provider_api_key::save_provider_api_key_to;
pub use provider_api_key::save_provider_api_key_to_with_keyring;

View File

@@ -0,0 +1,332 @@
//! Per-provider API key storage for `api_key = "keyring"` providers.
//!
//! Follows the same policy as CLI auth storage (`AuthCredentialsStoreMode`):
//! - `keyring`: system keyring only (Keychain, Credential Manager, Secret Service/keyutils);
//! - `file`: `AKODE_HOME/provider_api_keys.json`, private like `auth.json`;
//! - `auto` (default): keyring when available, otherwise the file (for example headless
//! Linux without Secret Service/D-Bus);
//! - `ephemeral`: process memory only.
//!
//! Keys never appear in errors, `Debug` output or logs.
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use akode_config::types::AuthCredentialsStoreMode;
use akode_keyring_store::DefaultKeyringStore;
use akode_keyring_store::KeyringStore;
use akode_model_provider_info::KeyringProviderApiKeyStore;
use akode_model_provider_info::ProviderApiKeyLocation;
use akode_model_provider_info::ProviderApiKeyStore;
use tracing::warn;
use super::storage::write_private_credential_file;
/// File name of the fallback store in AKODE_HOME.
pub const PROVIDER_API_KEYS_FILE: &str = "provider_api_keys.json";
/// Private JSON file mapping provider ids to API keys.
#[derive(Clone)]
pub struct ProviderApiKeyFileStore {
path: PathBuf,
}
impl std::fmt::Debug for ProviderApiKeyFileStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProviderApiKeyFileStore")
.field("path", &self.path)
.finish()
}
}
impl ProviderApiKeyFileStore {
pub fn new(codex_home: &Path) -> Self {
Self {
path: codex_home.join(PROVIDER_API_KEYS_FILE),
}
}
pub fn path(&self) -> &Path {
&self.path
}
fn read_all(&self) -> Result<BTreeMap<String, String>, String> {
match std::fs::read(&self.path) {
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| {
// serde_json may quote values; report only the position.
format!(
"{} is not valid (line {} column {})",
self.path.display(),
error.line(),
error.column()
)
}),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()),
Err(error) => Err(format!("cannot read {}: {error}", self.path.display())),
}
}
fn write_all(&self, keys: &BTreeMap<String, String>) -> Result<(), String> {
if keys.is_empty() {
return match std::fs::remove_file(&self.path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(format!("cannot remove {}: {error}", self.path.display())),
};
}
let data = serde_json::to_vec_pretty(keys)
.map_err(|_| "cannot encode provider API keys".to_string())?;
write_private_credential_file(&self.path, &data)
.map_err(|error| format!("cannot write {}: {error}", self.path.display()))
}
fn location(&self) -> ProviderApiKeyLocation {
ProviderApiKeyLocation::File {
path: self.path.display().to_string(),
}
}
}
impl ProviderApiKeyStore for ProviderApiKeyFileStore {
fn load(&self, provider_id: &str) -> Result<Option<String>, String> {
Ok(self
.read_all()?
.remove(provider_id)
.filter(|key| !key.trim().is_empty()))
}
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String> {
let mut keys = self.read_all()?;
keys.insert(provider_id.to_string(), api_key.to_string());
self.write_all(&keys)?;
Ok(self.location())
}
fn delete(&self, provider_id: &str) -> Result<bool, String> {
let mut keys = self.read_all()?;
let removed = keys.remove(provider_id).is_some();
if removed {
self.write_all(&keys)?;
}
Ok(removed)
}
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String> {
Ok(self.load(provider_id)?.map(|_| self.location()))
}
}
/// Keyring first; the file when the keyring is unavailable or has no entry.
#[derive(Debug)]
struct AutoProviderApiKeyStore {
keyring: KeyringProviderApiKeyStore,
file: ProviderApiKeyFileStore,
}
impl ProviderApiKeyStore for AutoProviderApiKeyStore {
fn load(&self, provider_id: &str) -> Result<Option<String>, String> {
match self.keyring.load(provider_id) {
Ok(Some(key)) => Ok(Some(key)),
Ok(None) => self.file.load(provider_id),
Err(error) => {
warn!("provider API key keyring unavailable, using file storage: {error}");
self.file.load(provider_id)
}
}
}
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String> {
match self.keyring.save(provider_id, api_key) {
Ok(location) => {
// Do not leave an older copy behind in the fallback file.
if let Err(error) = self.file.delete(provider_id) {
warn!("could not remove the old file copy of a provider API key: {error}");
}
Ok(location)
}
Err(error) => {
warn!("provider API key keyring unavailable, using file storage: {error}");
self.file.save(provider_id, api_key)
}
}
}
fn delete(&self, provider_id: &str) -> Result<bool, String> {
let keyring = self.keyring.delete(provider_id);
let file = self.file.delete(provider_id)?;
match keyring {
Ok(removed) => Ok(removed || file),
Err(_) if file => Ok(true),
Err(error) => Err(error),
}
}
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String> {
match self.keyring.locate(provider_id) {
Ok(Some(location)) => Ok(Some(location)),
Ok(None) | Err(_) => self.file.locate(provider_id),
}
}
}
/// Process-memory store for `ephemeral` mode.
#[derive(Default)]
struct EphemeralProviderApiKeyStore {
keys: Mutex<HashMap<String, String>>,
}
impl std::fmt::Debug for EphemeralProviderApiKeyStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("EphemeralProviderApiKeyStore")
}
}
impl ProviderApiKeyStore for EphemeralProviderApiKeyStore {
fn load(&self, provider_id: &str) -> Result<Option<String>, String> {
Ok(self
.keys
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(provider_id)
.cloned())
}
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String> {
self.keys
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(provider_id.to_string(), api_key.to_string());
Ok(ProviderApiKeyLocation::Memory)
}
fn delete(&self, provider_id: &str) -> Result<bool, String> {
Ok(self
.keys
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(provider_id)
.is_some())
}
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String> {
Ok(self
.load(provider_id)?
.map(|_| ProviderApiKeyLocation::Memory))
}
}
/// Builds the provider key store for `mode` with an explicit keyring backend.
pub fn configured_provider_api_key_store_with_keyring(
codex_home: &Path,
mode: AuthCredentialsStoreMode,
keyring: Arc<dyn KeyringStore>,
) -> Arc<dyn ProviderApiKeyStore> {
let keyring = KeyringProviderApiKeyStore::new(keyring);
let file = ProviderApiKeyFileStore::new(codex_home);
match mode {
AuthCredentialsStoreMode::Keyring => Arc::new(keyring),
AuthCredentialsStoreMode::File => Arc::new(file),
AuthCredentialsStoreMode::Auto => Arc::new(AutoProviderApiKeyStore { keyring, file }),
AuthCredentialsStoreMode::Ephemeral => Arc::new(EphemeralProviderApiKeyStore::default()),
}
}
/// Builds the provider key store for `mode` using the system keyring.
pub fn configured_provider_api_key_store(
codex_home: &Path,
mode: AuthCredentialsStoreMode,
) -> Arc<dyn ProviderApiKeyStore> {
configured_provider_api_key_store_with_keyring(codex_home, mode, Arc::new(DefaultKeyringStore))
}
/// Installs the process-wide provider key store used by `api_key = "keyring"`.
pub fn install_provider_api_key_store(codex_home: &Path, mode: AuthCredentialsStoreMode) {
akode_model_provider_info::set_provider_api_key_store(configured_provider_api_key_store(
codex_home, mode,
));
}
/// Keyring account used only to check that the system keyring answers (never written).
const KEYRING_PROBE_PROVIDER_ID: &str = "akode-keyring-probe";
/// Whether the system keyring can be used for provider keys (a read-only probe).
pub fn provider_api_key_keyring_available() -> bool {
provider_api_key_keyring_available_with(Arc::new(DefaultKeyringStore))
}
/// [`provider_api_key_keyring_available`] with an explicit keyring backend.
pub fn provider_api_key_keyring_available_with(keyring: Arc<dyn KeyringStore>) -> bool {
KeyringProviderApiKeyStore::new(keyring)
.load(KEYRING_PROBE_PROVIDER_ID)
.is_ok()
}
/// Stores `api_key` for `provider_id` only in the backend chosen by `mode` (`file`, or the
/// system keyring for any other mode) and removes the copy left in the other backend. The
/// keys of `other_providers` found in the other backend move to the chosen one, so a global
/// mode switch keeps them readable.
pub fn save_provider_api_key_to(
codex_home: &Path,
mode: AuthCredentialsStoreMode,
provider_id: &str,
api_key: &str,
other_providers: &[String],
) -> Result<ProviderApiKeyLocation, String> {
save_provider_api_key_to_with_keyring(
codex_home,
mode,
provider_id,
api_key,
other_providers,
Arc::new(DefaultKeyringStore),
)
}
/// [`save_provider_api_key_to`] with an explicit keyring backend.
pub fn save_provider_api_key_to_with_keyring(
codex_home: &Path,
mode: AuthCredentialsStoreMode,
provider_id: &str,
api_key: &str,
other_providers: &[String],
keyring: Arc<dyn KeyringStore>,
) -> Result<ProviderApiKeyLocation, String> {
if api_key.trim().is_empty() {
return Err("API key must not be empty".to_string());
}
let keyring = KeyringProviderApiKeyStore::new(keyring);
let file = ProviderApiKeyFileStore::new(codex_home);
let (target, other): (&dyn ProviderApiKeyStore, &dyn ProviderApiKeyStore) = match mode {
AuthCredentialsStoreMode::File => (&file, &keyring),
_ => (&keyring, &file),
};
for id in other_providers
.iter()
.filter(|id| id.as_str() != provider_id)
{
// An unreadable keyring simply has nothing to move.
let Ok(Some(key)) = other.load(id) else {
continue;
};
if !matches!(target.load(id), Ok(Some(_))) {
target.save(id, &key)?;
}
if let Err(error) = other.delete(id) {
warn!("could not remove the old copy of a provider API key: {error}");
}
}
let location = target.save(provider_id, api_key)?;
if let Err(error) = other.delete(provider_id) {
warn!("could not remove the old copy of a provider API key: {error}");
}
Ok(location)
}
#[cfg(test)]
#[path = "provider_api_key_tests.rs"]
mod tests;

View File

@@ -0,0 +1,252 @@
use std::sync::Arc;
use akode_config::types::AuthCredentialsStoreMode;
use akode_keyring_store::tests::MockKeyringStore;
use akode_model_provider_info::ProviderApiKeyLocation;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::*;
const SECRET: &str = "sk-provider-secret-0123456789";
const ACCOUNT: &str = "model-provider:imeai";
fn failing_keyring() -> MockKeyringStore {
let keyring = MockKeyringStore::default();
keyring.set_error(
ACCOUNT,
keyring::Error::NoStorageAccess(std::io::Error::other("no secret service").into()),
);
keyring
}
#[test]
fn auto_mode_prefers_the_keyring() {
let home = TempDir::new().unwrap();
let keyring = MockKeyringStore::default();
let store = configured_provider_api_key_store_with_keyring(
home.path(),
AuthCredentialsStoreMode::Auto,
Arc::new(keyring.clone()),
);
let location = store.save("imeai", SECRET).unwrap();
assert!(matches!(location, ProviderApiKeyLocation::Keyring { .. }));
assert_eq!(keyring.saved_value(ACCOUNT).as_deref(), Some(SECRET));
assert!(!home.path().join(PROVIDER_API_KEYS_FILE).exists());
assert_eq!(store.load("imeai").unwrap().as_deref(), Some(SECRET));
}
#[test]
fn auto_mode_falls_back_to_a_private_file_without_a_keyring() {
let home = TempDir::new().unwrap();
let store = configured_provider_api_key_store_with_keyring(
home.path(),
AuthCredentialsStoreMode::Auto,
Arc::new(failing_keyring()),
);
let location = store.save("imeai", SECRET).unwrap();
let path = home.path().join(PROVIDER_API_KEYS_FILE);
assert_eq!(
location,
ProviderApiKeyLocation::File {
path: path.display().to_string()
}
);
assert_eq!(store.load("imeai").unwrap().as_deref(), Some(SECRET));
assert_eq!(store.locate("imeai").unwrap(), Some(location.clone()));
// The displayed location never includes the key.
assert!(!location.to_string().contains(SECRET));
assert!(store.delete("imeai").unwrap());
assert_eq!(store.load("imeai").unwrap(), None);
assert!(!path.exists());
}
#[cfg(unix)]
#[test]
fn file_store_is_readable_only_by_the_owner() {
use std::os::unix::fs::PermissionsExt;
let home = TempDir::new().unwrap();
let store = ProviderApiKeyFileStore::new(home.path());
store.save("imeai", SECRET).unwrap();
store.save("other", "second-secret").unwrap();
let mode = std::fs::metadata(store.path())
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(mode, 0o600);
assert_eq!(
store.load("other").unwrap().as_deref(),
Some("second-secret")
);
assert_eq!(store.load("imeai").unwrap().as_deref(), Some(SECRET));
}
#[test]
fn keyring_mode_never_writes_a_file() {
let home = TempDir::new().unwrap();
let store = configured_provider_api_key_store_with_keyring(
home.path(),
AuthCredentialsStoreMode::Keyring,
Arc::new(failing_keyring()),
);
let error = store.save("imeai", SECRET).unwrap_err();
assert!(!error.contains(SECRET), "{error}");
assert!(!home.path().join(PROVIDER_API_KEYS_FILE).exists());
}
#[test]
fn file_mode_ignores_the_keyring() {
let home = TempDir::new().unwrap();
let keyring = MockKeyringStore::default();
let store = configured_provider_api_key_store_with_keyring(
home.path(),
AuthCredentialsStoreMode::File,
Arc::new(keyring.clone()),
);
store.save("imeai", SECRET).unwrap();
assert!(!keyring.contains(ACCOUNT));
assert!(home.path().join(PROVIDER_API_KEYS_FILE).exists());
}
#[test]
fn corrupt_file_errors_and_debug_never_contain_keys() {
let home = TempDir::new().unwrap();
let path = home.path().join(PROVIDER_API_KEYS_FILE);
std::fs::write(&path, format!("{{\"imeai\": \"{SECRET}\", broken")).unwrap();
let store = ProviderApiKeyFileStore::new(home.path());
let error = store.load("imeai").unwrap_err();
assert!(!error.contains(SECRET), "{error}");
let auto = configured_provider_api_key_store_with_keyring(
home.path(),
AuthCredentialsStoreMode::Auto,
Arc::new(MockKeyringStore::default()),
);
assert!(!format!("{auto:?}").contains(SECRET));
}
#[test]
fn ephemeral_mode_keeps_keys_in_memory() {
let home = TempDir::new().unwrap();
let store = configured_provider_api_key_store_with_keyring(
home.path(),
AuthCredentialsStoreMode::Ephemeral,
Arc::new(MockKeyringStore::default()),
);
assert_eq!(
store.save("imeai", SECRET).unwrap(),
ProviderApiKeyLocation::Memory
);
assert_eq!(store.load("imeai").unwrap().as_deref(), Some(SECRET));
assert!(!home.path().join(PROVIDER_API_KEYS_FILE).exists());
assert!(!format!("{store:?}").contains(SECRET));
}
#[test]
fn chosen_file_backend_is_private_and_skips_the_keyring() {
let home = TempDir::new().unwrap();
let keyring = MockKeyringStore::default();
let location = save_provider_api_key_to_with_keyring(
home.path(),
AuthCredentialsStoreMode::File,
"imeai",
SECRET,
&[],
Arc::new(keyring.clone()),
)
.unwrap();
assert!(matches!(location, ProviderApiKeyLocation::File { .. }));
assert!(!location.to_string().contains(SECRET));
assert!(keyring.saved_value(ACCOUNT).is_none());
let path = home.path().join(PROVIDER_API_KEYS_FILE);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600);
}
assert_eq!(
ProviderApiKeyFileStore::new(home.path())
.load("imeai")
.unwrap()
.as_deref(),
Some(SECRET)
);
}
#[test]
fn chosen_keyring_backend_creates_no_file() {
let home = TempDir::new().unwrap();
let keyring = MockKeyringStore::default();
let location = save_provider_api_key_to_with_keyring(
home.path(),
AuthCredentialsStoreMode::Keyring,
"imeai",
SECRET,
&[],
Arc::new(keyring.clone()),
)
.unwrap();
assert!(matches!(location, ProviderApiKeyLocation::Keyring { .. }));
assert_eq!(keyring.saved_value(ACCOUNT).as_deref(), Some(SECRET));
assert!(!home.path().join(PROVIDER_API_KEYS_FILE).exists());
}
#[test]
fn switching_backend_removes_the_old_copy_and_moves_other_keys() {
let home = TempDir::new().unwrap();
let keyring = MockKeyringStore::default();
let other = "model-provider:altro";
for (id, key) in [("imeai", "old-key"), ("altro", "other-key")] {
save_provider_api_key_to_with_keyring(
home.path(),
AuthCredentialsStoreMode::Keyring,
id,
key,
&[],
Arc::new(keyring.clone()),
)
.unwrap();
}
// Keyring -> file: nothing stays in the keyring.
save_provider_api_key_to_with_keyring(
home.path(),
AuthCredentialsStoreMode::File,
"imeai",
SECRET,
&["altro".to_string(), "ollama".to_string()],
Arc::new(keyring.clone()),
)
.unwrap();
assert!(keyring.saved_value(ACCOUNT).is_none());
assert!(keyring.saved_value(other).is_none());
let file = ProviderApiKeyFileStore::new(home.path());
assert_eq!(file.load("imeai").unwrap().as_deref(), Some(SECRET));
assert_eq!(file.load("altro").unwrap().as_deref(), Some("other-key"));
// File -> keyring: the file goes away with its last key.
save_provider_api_key_to_with_keyring(
home.path(),
AuthCredentialsStoreMode::Keyring,
"imeai",
SECRET,
&["altro".to_string()],
Arc::new(keyring.clone()),
)
.unwrap();
assert_eq!(keyring.saved_value(ACCOUNT).as_deref(), Some(SECRET));
assert_eq!(keyring.saved_value(other).as_deref(), Some("other-key"));
assert!(!home.path().join(PROVIDER_API_KEYS_FILE).exists());
}
#[test]
fn keyring_probe_reports_an_unusable_keyring() {
assert!(provider_api_key_keyring_available_with(Arc::new(
MockKeyringStore::default()
)));
let keyring = MockKeyringStore::default();
keyring.set_error(
"model-provider:akode-keyring-probe",
keyring::Error::NoStorageAccess(std::io::Error::other("no secret service").into()),
);
assert!(!provider_api_key_keyring_available_with(Arc::new(keyring)));
}

View File

@@ -88,6 +88,26 @@ impl<'de> Deserialize<'de> for AuthDotJson {
} }
} }
/// Atomically replaces a credential file in AKODE_HOME, like `auth.json`: private (0600 on
/// Unix; on Windows the destination DACL, or AKODE_HOME's inherited one, is kept), never
/// truncated for concurrent readers, symlinks resolved to their target.
pub(crate) fn write_private_credential_file(path: &Path, data: &[u8]) -> std::io::Result<()> {
let path = storage_file::resolve_auth_file(path.to_path_buf())?;
let parent = path
.parent()
.ok_or_else(|| std::io::Error::other("credential file has no parent"))?;
std::fs::create_dir_all(parent)?;
storage_file::check_replaceable(&path)?;
let mut replacement = storage_file::replacement(&path)?;
replacement.write_all(data)?;
replacement.as_file().sync_all()?;
let (_file, temp_path) = replacement.keep().map_err(|error| error.error)?;
let mut temp_path = tempfile::TempPath::try_from_path(temp_path)?;
std::fs::rename(&temp_path, path)?;
temp_path.disable_cleanup(/*disable_cleanup*/ true);
Ok(())
}
pub(super) fn get_auth_file(codex_home: &Path) -> PathBuf { pub(super) fn get_auth_file(codex_home: &Path) -> PathBuf {
codex_home.join("auth.json") codex_home.join("auth.json")
} }

View File

@@ -63,6 +63,7 @@ mod tests {
experimental_bearer_token: None, experimental_bearer_token: None,
auth: None, auth: None,
gateway_oauth: None, gateway_oauth: None,
api_key: None,
wire_api: WireApi::Responses, wire_api: WireApi::Responses,
query_params: None, query_params: None,
http_headers: None, http_headers: None,
@@ -75,7 +76,9 @@ mod tests {
supports_websockets: false, supports_websockets: false,
supports_standalone_web_search: false, supports_standalone_web_search: false,
capabilities: None, capabilities: None,
keyring_account: None,
include_internal_metadata: false, include_internal_metadata: false,
models: Default::default(),
}; };
let telemetry = let telemetry =

View File

@@ -11,6 +11,7 @@ mod outbound_proxy;
pub use akode_config::types::AuthCredentialsStoreMode; pub use akode_config::types::AuthCredentialsStoreMode;
pub use akode_http_client::BuildCustomCaTransportError as BuildLoginHttpClientError; pub use akode_http_client::BuildCustomCaTransportError as BuildLoginHttpClientError;
pub use auth::AKODE_API_KEY_ENV_VAR;
pub use auth::AuthChangeState; pub use auth::AuthChangeState;
pub use auth::AuthConfig; pub use auth::AuthConfig;
pub use auth::AuthDotJson; pub use auth::AuthDotJson;
@@ -21,23 +22,28 @@ pub use auth::AuthManagerConfig;
pub use auth::AuthManagerInitializationError; pub use auth::AuthManagerInitializationError;
pub use auth::AuthOwner; pub use auth::AuthOwner;
pub use auth::AuthRuntimeConfig; pub use auth::AuthRuntimeConfig;
pub use auth::AKODE_API_KEY_ENV_VAR;
pub use auth::CodexAuth; pub use auth::CodexAuth;
pub use auth::ExternalAuth; pub use auth::ExternalAuth;
pub use auth::ExternalAuthFuture; pub use auth::ExternalAuthFuture;
pub use auth::ExternalAuthRefreshContext; pub use auth::ExternalAuthRefreshContext;
pub use auth::ExternalAuthRefreshReason; pub use auth::ExternalAuthRefreshReason;
pub use auth::OPENAI_API_KEY_ENV_VAR; pub use auth::OPENAI_API_KEY_ENV_VAR;
pub use auth::PROVIDER_API_KEYS_FILE;
pub use auth::ProviderApiKeyFileStore;
pub use auth::RefreshTokenError; pub use auth::RefreshTokenError;
pub use auth::RequestAuthChange; pub use auth::RequestAuthChange;
pub use auth::UnauthorizedRecovery; pub use auth::UnauthorizedRecovery;
pub use auth::configured_provider_api_key_store;
pub use auth::default_client; pub use auth::default_client;
pub use auth::enforce_login_restrictions; pub use auth::enforce_login_restrictions;
pub use auth::install_provider_api_key_store;
pub use auth::load_auth_dot_json; pub use auth::load_auth_dot_json;
pub use auth::login_with_api_key; pub use auth::login_with_api_key;
pub use auth::logout; pub use auth::logout;
pub use auth::provider_api_key_keyring_available;
pub use auth::read_openai_api_key_from_env; pub use auth::read_openai_api_key_from_env;
pub use auth::save_auth; pub use auth::save_auth;
pub use auth::save_provider_api_key_to;
pub use auth_env_telemetry::AuthEnvTelemetry; pub use auth_env_telemetry::AuthEnvTelemetry;
pub use auth_env_telemetry::collect_auth_env_telemetry; pub use auth_env_telemetry::collect_auth_env_telemetry;
pub use oauth::OAuthDeviceCodePrompt; pub use oauth::OAuthDeviceCodePrompt;

View File

@@ -15,6 +15,7 @@ workspace = true
[dependencies] [dependencies]
akode-client = { workspace = true } akode-client = { workspace = true }
akode-http-client = { workspace = true } akode-http-client = { workspace = true }
akode-keyring-store = { workspace = true }
akode-protocol = { workspace = true } akode-protocol = { workspace = true }
akode-utils-redacted-string = { workspace = true } akode-utils-redacted-string = { workspace = true }
http = { workspace = true } http = { workspace = true }
@@ -22,6 +23,7 @@ schemars = { workspace = true }
serde = { workspace = true, features = ["derive"] } serde = { workspace = true, features = ["derive"] }
[dev-dependencies] [dev-dependencies]
keyring = { workspace = true }
akode-utils-absolute-path = { workspace = true } akode-utils-absolute-path = { workspace = true }
maplit = { workspace = true } maplit = { workspace = true }
pretty_assertions = { workspace = true } pretty_assertions = { workspace = true }

View File

@@ -195,6 +195,7 @@ impl GatewayOAuthConfig {
} }
let gateway_header = if self.delivery().is_authorization_bearer() { let gateway_header = if self.delivery().is_authorization_bearer() {
if provider.requires_openai_auth if provider.requires_openai_auth
|| provider.api_key.is_some()
|| provider.env_key.is_some() || provider.env_key.is_some()
|| provider.experimental_bearer_token.is_some() || provider.experimental_bearer_token.is_some()
|| provider.has_command_auth() || provider.has_command_auth()

View File

@@ -0,0 +1,243 @@
//! Per-provider API keys stored outside config.toml (`api_key = "keyring"`).
//!
//! The process-wide [`ProviderApiKeyStore`] decides where keys live. By default it is the
//! system keyring (service [`PROVIDER_API_KEY_KEYRING_SERVICE`], account
//! `model-provider:<id>`; Keychain on macOS, Credential Manager on Windows, Secret Service
//! or keyutils on Linux). `akode-login` installs a store that follows
//! `provider_api_key_store = "auto" | "keyring" | "file"` and can fall back to a private
//! file in AKODE_HOME. Loaded keys are cached for the life of the process. Keys are never
//! logged or included in errors.
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::PoisonError;
use std::sync::RwLock;
use akode_keyring_store::DefaultKeyringStore;
use akode_keyring_store::KeyringStore;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use crate::PROVIDER_API_KEY_KEYRING_SERVICE;
use crate::provider_api_key_keyring_account;
/// Where a provider key was found or stored. Never contains the key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProviderApiKeyLocation {
/// System keyring entry (service, account).
Keyring { service: String, account: String },
/// Private file (path shown to the user).
File { path: String },
/// Process memory only.
Memory,
}
impl fmt::Display for ProviderApiKeyLocation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Keyring { service, account } => {
write!(
f,
"system keyring (service `{service}`, account `{account}`)"
)
}
Self::File { path } => write!(f, "file {path}"),
Self::Memory => f.write_str("memory (this process only)"),
}
}
}
/// Backend that stores provider API keys by provider id.
///
/// Implementations must never include key material in errors, `Debug` output or logs.
pub trait ProviderApiKeyStore: fmt::Debug + Send + Sync {
/// Loads the key for `provider_id`; `Ok(None)` when none is stored.
fn load(&self, provider_id: &str) -> Result<Option<String>, String>;
/// Stores `api_key` for `provider_id` and reports where it went.
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String>;
/// Deletes the key for `provider_id`; returns whether one existed.
fn delete(&self, provider_id: &str) -> Result<bool, String>;
/// Where the key for `provider_id` currently is, if stored.
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String>;
}
/// Keyring-only store backed by a [`KeyringStore`].
#[derive(Debug, Clone)]
pub struct KeyringProviderApiKeyStore {
keyring: Arc<dyn KeyringStore>,
}
impl KeyringProviderApiKeyStore {
pub fn new(keyring: Arc<dyn KeyringStore>) -> Self {
Self { keyring }
}
fn location(provider_id: &str) -> ProviderApiKeyLocation {
ProviderApiKeyLocation::Keyring {
service: PROVIDER_API_KEY_KEYRING_SERVICE.to_string(),
account: provider_api_key_keyring_account(provider_id),
}
}
}
impl Default for KeyringProviderApiKeyStore {
fn default() -> Self {
Self::new(Arc::new(DefaultKeyringStore))
}
}
impl ProviderApiKeyStore for KeyringProviderApiKeyStore {
fn load(&self, provider_id: &str) -> Result<Option<String>, String> {
self.keyring
.load(
PROVIDER_API_KEY_KEYRING_SERVICE,
&provider_api_key_keyring_account(provider_id),
)
.map(|key| key.filter(|key| !key.trim().is_empty()))
// The keyring error describes the backend failure, never the secret.
.map_err(|error| format!("system keyring unavailable: {}", error.message()))
}
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String> {
self.keyring
.save(
PROVIDER_API_KEY_KEYRING_SERVICE,
&provider_api_key_keyring_account(provider_id),
api_key,
)
.map_err(|error| format!("system keyring unavailable: {}", error.message()))?;
Ok(Self::location(provider_id))
}
fn delete(&self, provider_id: &str) -> Result<bool, String> {
self.keyring
.delete(
PROVIDER_API_KEY_KEYRING_SERVICE,
&provider_api_key_keyring_account(provider_id),
)
.map_err(|error| format!("system keyring unavailable: {}", error.message()))
}
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String> {
Ok(self.load(provider_id)?.map(|_| Self::location(provider_id)))
}
}
fn store_slot() -> &'static RwLock<Arc<dyn ProviderApiKeyStore>> {
static STORE: OnceLock<RwLock<Arc<dyn ProviderApiKeyStore>>> = OnceLock::new();
STORE.get_or_init(|| RwLock::new(Arc::new(KeyringProviderApiKeyStore::default())))
}
fn cache() -> &'static Mutex<HashMap<String, String>> {
static CACHE: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}
fn clear_cache() {
cache()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
}
/// The process-wide provider key store.
pub fn provider_api_key_store() -> Arc<dyn ProviderApiKeyStore> {
Arc::clone(&store_slot().read().unwrap_or_else(PoisonError::into_inner))
}
/// Installs the process-wide provider key store (done by config loading).
pub fn set_provider_api_key_store(store: Arc<dyn ProviderApiKeyStore>) {
*store_slot().write().unwrap_or_else(PoisonError::into_inner) = store;
clear_cache();
}
/// Replaces the keyring backend with a keyring-only store. Intended for tests.
#[doc(hidden)]
pub fn set_provider_keyring_store_for_testing(keyring: Arc<dyn KeyringStore>) {
set_provider_api_key_store(Arc::new(KeyringProviderApiKeyStore::new(keyring)));
}
fn provider_id_from_account(account: &str) -> &str {
account.strip_prefix("model-provider:").unwrap_or(account)
}
/// Loads the key for a keyring account, failing when no non-empty key is stored.
pub(crate) fn load(account: &str) -> CodexResult<String> {
if let Some(key) = cache()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(account)
{
return Ok(key.clone());
}
let key = load_with(provider_api_key_store().as_ref(), account)?;
cache()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(account.to_string(), key.clone());
Ok(key)
}
pub(crate) fn load_with(store: &dyn ProviderApiKeyStore, account: &str) -> CodexResult<String> {
let provider_id = provider_id_from_account(account);
match store.load(provider_id) {
Ok(Some(key)) if !key.trim().is_empty() => Ok(key),
Ok(_) => Err(CodexErr::UnsupportedOperation(format!(
"No API key is stored for model provider `{provider_id}`. \
Store one with: codex login --provider {provider_id} --with-api-key"
))),
Err(error) => Err(CodexErr::UnsupportedOperation(format!(
"Failed to read the API key for model provider `{provider_id}`: {error}"
))),
}
}
/// Stores `api_key` for `provider_id` in the process-wide store.
pub fn save_provider_api_key(
provider_id: &str,
api_key: &str,
) -> Result<ProviderApiKeyLocation, String> {
if api_key.trim().is_empty() {
return Err("API key must not be empty".to_string());
}
let location = provider_api_key_store()
.save(provider_id, api_key)
.map_err(|error| {
format!("Failed to store the API key for model provider `{provider_id}`: {error}")
})?;
cache()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(
provider_api_key_keyring_account(provider_id),
api_key.to_string(),
);
Ok(location)
}
/// Removes the stored key for `provider_id`. Returns whether a key was present.
pub fn delete_provider_api_key(provider_id: &str) -> Result<bool, String> {
cache()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&provider_api_key_keyring_account(provider_id));
provider_api_key_store()
.delete(provider_id)
.map_err(|error| {
format!("Failed to delete the API key for model provider `{provider_id}`: {error}")
})
}
/// Where the key for `provider_id` is stored, without reading it into any output.
pub fn locate_provider_api_key(
provider_id: &str,
) -> Result<Option<ProviderApiKeyLocation>, String> {
provider_api_key_store().locate(provider_id)
}
#[cfg(test)]
#[path = "keyring_api_key_tests.rs"]
mod tests;

View File

@@ -0,0 +1,113 @@
use std::sync::Arc;
use akode_keyring_store::tests::MockKeyringStore;
use pretty_assertions::assert_eq;
use super::*;
use crate::ModelProviderInfo;
use crate::ProviderApiKeySource;
const SECRET: &str = "sk-test-secret-value-1234567890";
fn keyring_store(mock: &MockKeyringStore) -> KeyringProviderApiKeyStore {
KeyringProviderApiKeyStore::new(Arc::new(mock.clone()))
}
#[test]
fn keyring_store_saves_under_provider_account() {
let mock = MockKeyringStore::default();
let store = keyring_store(&mock);
let location = store.save("imeai", SECRET).expect("save");
assert_eq!(
location,
ProviderApiKeyLocation::Keyring {
service: "aKode".to_string(),
account: "model-provider:imeai".to_string(),
}
);
assert_eq!(
mock.saved_value("model-provider:imeai").as_deref(),
Some(SECRET)
);
assert_eq!(
load_with(&store, "model-provider:imeai").expect("load"),
SECRET
);
assert_eq!(store.locate("imeai").expect("locate"), Some(location));
assert!(!location_string_contains_secret(&store));
}
fn location_string_contains_secret(store: &KeyringProviderApiKeyStore) -> bool {
store
.locate("imeai")
.ok()
.flatten()
.is_some_and(|location| location.to_string().contains(SECRET))
}
#[test]
fn missing_key_error_explains_how_to_store_it() {
let store = keyring_store(&MockKeyringStore::default());
let error = load_with(&store, "model-provider:imeai")
.expect_err("missing key must fail")
.to_string();
assert!(
error.contains("codex login --provider imeai --with-api-key"),
"{error}"
);
}
#[test]
fn keyring_errors_and_debug_output_never_contain_the_key() {
let mock = MockKeyringStore::default();
let store = keyring_store(&mock);
store.save("imeai", SECRET).expect("save");
mock.set_error(
"model-provider:imeai",
keyring::Error::PlatformFailure("locked".into()),
);
let error = load_with(&store, "model-provider:imeai")
.expect_err("keyring failure must surface")
.to_string();
assert!(!error.contains(SECRET), "{error}");
assert!(!format!("{store:?}").contains(SECRET));
let provider = ModelProviderInfo {
name: "imeAI".to_string(),
base_url: Some("http://127.0.0.1:8080/v1".to_string()),
api_key: Some(ProviderApiKeySource::Keyring),
keyring_account: Some("model-provider:imeai".to_string()),
..ModelProviderInfo::default()
};
let debug = format!("{provider:?}");
assert!(!debug.contains(SECRET), "{debug}");
}
#[test]
fn provider_api_key_uses_process_store() {
let mock = MockKeyringStore::default();
set_provider_keyring_store_for_testing(Arc::new(mock));
assert_eq!(
save_provider_api_key("process-store", " ").unwrap_err(),
"API key must not be empty"
);
save_provider_api_key("process-store", SECRET).expect("save");
let provider = ModelProviderInfo {
name: "process-store".to_string(),
base_url: Some("http://127.0.0.1:8080/v1".to_string()),
api_key: Some(ProviderApiKeySource::Keyring),
keyring_account: Some(crate::provider_api_key_keyring_account("process-store")),
..ModelProviderInfo::default()
};
assert_eq!(
provider.api_key().expect("api key").as_deref(),
Some(SECRET)
);
assert!(
locate_provider_api_key("process-store")
.expect("locate")
.is_some()
);
assert_eq!(delete_provider_api_key("process-store"), Ok(true));
assert!(provider.api_key().is_err());
}

View File

@@ -21,6 +21,8 @@ use http::header::HeaderValue;
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize; use serde::Serialize;
use akode_protocol::openai_models::ReasoningEffort;
use std::collections::BTreeMap;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt; use std::fmt;
use std::num::NonZeroU64; use std::num::NonZeroU64;
@@ -32,12 +34,22 @@ use std::time::Duration;
mod capabilities; mod capabilities;
mod gateway_oauth; mod gateway_oauth;
mod keyring_api_key;
mod oauth_session; mod oauth_session;
pub use capabilities::ModelProviderCapabilities; pub use capabilities::ModelProviderCapabilities;
pub use capabilities::RemoteCompactionSupport; pub use capabilities::RemoteCompactionSupport;
pub use gateway_oauth::GatewayOAuthConfig; pub use gateway_oauth::GatewayOAuthConfig;
pub use gateway_oauth::GatewayOAuthDelivery; pub use gateway_oauth::GatewayOAuthDelivery;
pub use gateway_oauth::GatewayOAuthSettings; pub use gateway_oauth::GatewayOAuthSettings;
pub use keyring_api_key::KeyringProviderApiKeyStore;
pub use keyring_api_key::ProviderApiKeyLocation;
pub use keyring_api_key::ProviderApiKeyStore;
pub use keyring_api_key::delete_provider_api_key;
pub use keyring_api_key::locate_provider_api_key;
pub use keyring_api_key::provider_api_key_store;
pub use keyring_api_key::save_provider_api_key;
pub use keyring_api_key::set_provider_api_key_store;
pub use keyring_api_key::set_provider_keyring_store_for_testing;
pub use oauth_session::OAuthCredentialsStore; pub use oauth_session::OAuthCredentialsStore;
pub use oauth_session::OAuthSessionConfig; pub use oauth_session::OAuthSessionConfig;
@@ -80,6 +92,8 @@ const MAX_STREAM_MAX_RETRIES: u64 = 100;
/// Hard cap for user-configured `request_max_retries`. /// Hard cap for user-configured `request_max_retries`.
const MAX_REQUEST_MAX_RETRIES: u64 = 100; const MAX_REQUEST_MAX_RETRIES: u64 = 100;
/// Keyring service under which per-provider API keys are stored.
pub const PROVIDER_API_KEY_KEYRING_SERVICE: &str = "aKode";
/// Error shown when no model provider is configured. /// Error shown when no model provider is configured.
pub const NO_MODEL_PROVIDER_CONFIGURED_ERROR: &str = concat!( pub const NO_MODEL_PROVIDER_CONFIGURED_ERROR: &str = concat!(
"No model provider is configured.\n", "No model provider is configured.\n",
@@ -92,7 +106,8 @@ pub const NO_MODEL_PROVIDER_CONFIGURED_ERROR: &str = concat!(
" [model_providers.local]\n", " [model_providers.local]\n",
" name = \"My server\"\n", " name = \"My server\"\n",
" base_url = \"http://127.0.0.1:8080/v1\" # must implement POST {base_url}/responses\n", " base_url = \"http://127.0.0.1:8080/v1\" # must implement POST {base_url}/responses\n",
" env_key = \"MY_SERVER_API_KEY\" # environment variable that holds the API key\n", " api_key = \"keyring\" # store it with: akode login --provider local --with-api-key\n",
" # or instead: env_key = \"MY_SERVER_API_KEY\"\n",
"\n", "\n",
"Built-in local providers: model_provider = \"ollama\" (http://localhost:11434/v1) ", "Built-in local providers: model_provider = \"ollama\" (http://localhost:11434/v1) ",
"or model_provider = \"lmstudio\" (http://localhost:1234/v1).", "or model_provider = \"lmstudio\" (http://localhost:1234/v1).",
@@ -162,6 +177,10 @@ pub struct ModelProviderInfo {
pub auth: Option<ModelProviderAuthInfo>, pub auth: Option<ModelProviderAuthInfo>,
/// Gateway access token from OAuth or a credential export command. /// Gateway access token from OAuth or a credential export command.
pub gateway_oauth: Option<GatewayOAuthConfig>, pub gateway_oauth: Option<GatewayOAuthConfig>,
/// Where to read this provider's API key from. `"keyring"` reads the key stored with
/// `akode login --provider <id> --with-api-key`: in the system keyring, or in a private
/// file in AKODE_HOME when `provider_api_key_store` selects (or falls back to) file storage.
pub api_key: Option<ProviderApiKeySource>,
/// Which wire protocol this provider expects. /// Which wire protocol this provider expects.
#[serde(default)] #[serde(default)]
pub wire_api: WireApi, pub wire_api: WireApi,
@@ -192,8 +211,9 @@ pub struct ModelProviderInfo {
pub websocket_connect_timeout_ms: Option<u64>, pub websocket_connect_timeout_ms: Option<u64>,
/// Use the API key stored with `akode login --with-api-key` (in `auth.json` or the /// Use the API key stored with `akode login --with-api-key` (in `auth.json` or the
/// credentials store selected by `cli_auth_credentials_store`) for this provider. /// credentials store selected by `cli_auth_credentials_store`) for this provider.
/// When false (the default), the key comes from `env_key` or `auth`, if any. /// `use_stored_api_key` is accepted as a clearer alias. When false (the default),
#[serde(default)] /// the key comes from `api_key`, `env_key`, or `auth`, if any.
#[serde(default, alias = "use_stored_api_key")]
pub requires_openai_auth: bool, pub requires_openai_auth: bool,
/// Whether this provider supports the Responses API WebSocket transport. /// Whether this provider supports the Responses API WebSocket transport.
#[serde(default)] #[serde(default)]
@@ -201,11 +221,45 @@ pub struct ModelProviderInfo {
/// Whether this provider supports the standalone web-search endpoint. /// Whether this provider supports the standalone web-search endpoint.
#[serde(default)] #[serde(default)]
pub supports_standalone_web_search: bool, pub supports_standalone_web_search: bool,
/// Per-model settings keyed by model id (`[model_providers.<id>.models."<model id>"]`).
/// A value set here wins over the matching global setting (e.g. `model_context_window`).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub models: BTreeMap<String, ProviderModelSettings>,
/// Runtime-only opt-in for internal metadata, independent of the destination check. /// Runtime-only opt-in for internal metadata, independent of the destination check.
/// This cannot be loaded from or written to serialized provider configuration. /// This cannot be loaded from or written to serialized provider configuration.
#[serde(skip)] #[serde(skip)]
#[schemars(skip)] #[schemars(skip)]
pub include_internal_metadata: bool, pub include_internal_metadata: bool,
/// Runtime-only keyring account for `api_key = "keyring"`; set from the provider id
/// when configured providers are merged. Never serialized.
#[serde(skip)]
#[schemars(skip)]
pub keyring_account: Option<String>,
}
/// Settings for one model of a provider. Every value is optional; unset values fall back to
/// the global settings, then to what the server reports, then to the defaults.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ProviderModelSettings {
/// Context window in tokens (wins over `model_context_window`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context_window: Option<i64>,
/// Sampling temperature sent with each request.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub temperature: Option<f64>,
/// Nucleus sampling (`top_p`) sent with each request.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub top_p: Option<f64>,
/// Maximum output tokens per response (`max_output_tokens`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<u64>,
/// Reasoning effort (wins over `model_reasoning_effort`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning_effort: Option<ReasoningEffort>,
/// Name shown in the interface instead of the model id (the API always gets the id).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
} }
/// Command used to export credentials for a model provider. /// Command used to export credentials for a model provider.
@@ -251,11 +305,67 @@ fn default_credential_export_timeout_ms() -> NonZeroU64 {
} }
} }
/// Source of a provider API key configured through `api_key`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ProviderApiKeySource {
/// Read the key from the system keyring (service `aKode`, account `model-provider:<id>`).
Keyring,
}
impl<'de> Deserialize<'de> for ProviderApiKeySource {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
match value.as_str() {
"keyring" => Ok(Self::Keyring),
// Never echo the value: it may be a literal API key pasted by mistake.
_ => Err(serde::de::Error::custom(
"provider api_key must be \"keyring\"; literal API keys are not accepted in \
config.toml. Store the key with `akode login --provider <id> --with-api-key`, or use env_key",
)),
}
}
}
/// Keyring account that stores the API key for a provider id.
pub fn provider_api_key_keyring_account(provider_id: &str) -> String {
format!("model-provider:{provider_id}")
}
impl ModelProviderInfo { impl ModelProviderInfo {
/// Settings configured for `model`, if any.
pub fn model_settings(&self, model: &str) -> Option<&ProviderModelSettings> {
self.models.get(model)
}
pub fn validate(&self) -> std::result::Result<(), String> { pub fn validate(&self) -> std::result::Result<(), String> {
if let Some(gateway) = &self.gateway_oauth { if let Some(gateway) = &self.gateway_oauth {
gateway.validate(self)?; gateway.validate(self)?;
} }
if self.api_key.is_some() {
let mut conflicts = Vec::new();
if self.env_key.is_some() {
conflicts.push("env_key");
}
if self.experimental_bearer_token.is_some() {
conflicts.push("experimental_bearer_token");
}
if self.auth.is_some() {
conflicts.push("auth");
}
if self.requires_openai_auth {
conflicts.push("requires_openai_auth");
}
if !conflicts.is_empty() {
return Err(format!(
"provider api_key cannot be combined with {}",
conflicts.join(", ")
));
}
}
let Some(auth) = self.auth.as_ref() else { let Some(auth) = self.auth.as_ref() else {
return Ok(()); return Ok(());
@@ -361,10 +471,21 @@ impl ModelProviderInfo {
}) })
} }
/// If `env_key` is Some, returns the API key for this provider if present /// Returns the API key configured for this provider, if any.
/// (and non-empty) in the environment. If `env_key` is required but ///
/// cannot be found, returns an error. /// `env_key` reads the named environment variable; `api_key = "keyring"` reads the key
/// stored in the system keyring for this provider id. A configured source that yields no
/// key is an error. The key itself is never included in errors or logs.
pub fn api_key(&self) -> CodexResult<Option<String>> { pub fn api_key(&self) -> CodexResult<Option<String>> {
if let Some(ProviderApiKeySource::Keyring) = self.api_key {
let account = self.keyring_account.as_deref().ok_or_else(|| {
CodexErr::UnsupportedOperation(format!(
"model provider `{}` uses api_key = \"keyring\" but its id is unknown",
self.name
))
})?;
return keyring_api_key::load(account).map(Some);
}
match &self.env_key { match &self.env_key {
Some(env_key) => { Some(env_key) => {
let api_key = std::env::var(env_key) let api_key = std::env::var(env_key)
@@ -475,11 +596,13 @@ pub fn built_in_model_providers() -> HashMap<String, ModelProviderInfo> {
/// Merge configured providers into the built-in provider catalog. /// Merge configured providers into the built-in provider catalog.
/// ///
/// Configured providers extend the built-in set; built-in providers are not overridable. /// Configured providers extend the built-in set; built-in providers are not overridable.
/// Each configured provider learns its id as its keyring account.
pub fn merge_configured_model_providers( pub fn merge_configured_model_providers(
mut model_providers: HashMap<String, ModelProviderInfo>, mut model_providers: HashMap<String, ModelProviderInfo>,
configured_model_providers: HashMap<String, ModelProviderInfo>, configured_model_providers: HashMap<String, ModelProviderInfo>,
) -> Result<HashMap<String, ModelProviderInfo>, String> { ) -> Result<HashMap<String, ModelProviderInfo>, String> {
for (key, mut provider) in configured_model_providers { for (key, mut provider) in configured_model_providers {
provider.keyring_account = Some(provider_api_key_keyring_account(&key));
if provider.name.trim().is_empty() { if provider.name.trim().is_empty() {
provider.name = key.clone(); provider.name = key.clone();
} }
@@ -518,6 +641,7 @@ pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> M
experimental_bearer_token: None, experimental_bearer_token: None,
auth: None, auth: None,
gateway_oauth: None, gateway_oauth: None,
api_key: None,
wire_api, wire_api,
query_params: None, query_params: None,
http_headers: None, http_headers: None,
@@ -531,6 +655,8 @@ pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> M
supports_standalone_web_search: false, supports_standalone_web_search: false,
capabilities: None, capabilities: None,
include_internal_metadata: false, include_internal_metadata: false,
keyring_account: None,
models: Default::default(),
} }
} }

View File

@@ -87,6 +87,7 @@ base_url = "http://localhost:11434/v1"
experimental_bearer_token: None, experimental_bearer_token: None,
auth: None, auth: None,
gateway_oauth: None, gateway_oauth: None,
api_key: None,
wire_api: WireApi::Responses, wire_api: WireApi::Responses,
query_params: None, query_params: None,
http_headers: None, http_headers: None,
@@ -99,7 +100,9 @@ base_url = "http://localhost:11434/v1"
supports_websockets: false, supports_websockets: false,
supports_standalone_web_search: false, supports_standalone_web_search: false,
capabilities: None, capabilities: None,
keyring_account: None,
include_internal_metadata: false, include_internal_metadata: false,
models: Default::default(),
}; };
let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap(); let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap();
@@ -123,6 +126,7 @@ query_params = { api-version = "2025-04-01-preview" }
experimental_bearer_token: None, experimental_bearer_token: None,
auth: None, auth: None,
gateway_oauth: None, gateway_oauth: None,
api_key: None,
wire_api: WireApi::Responses, wire_api: WireApi::Responses,
query_params: Some(maplit::hashmap! { query_params: Some(maplit::hashmap! {
"api-version".to_string() => "2025-04-01-preview".into(), "api-version".to_string() => "2025-04-01-preview".into(),
@@ -137,7 +141,9 @@ query_params = { api-version = "2025-04-01-preview" }
supports_websockets: false, supports_websockets: false,
supports_standalone_web_search: false, supports_standalone_web_search: false,
capabilities: None, capabilities: None,
keyring_account: None,
include_internal_metadata: false, include_internal_metadata: false,
models: Default::default(),
}; };
let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap(); let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap();
@@ -163,6 +169,7 @@ supports_standalone_web_search = true
experimental_bearer_token: None, experimental_bearer_token: None,
auth: None, auth: None,
gateway_oauth: None, gateway_oauth: None,
api_key: None,
wire_api: WireApi::Responses, wire_api: WireApi::Responses,
query_params: None, query_params: None,
http_headers: Some(maplit::hashmap! { http_headers: Some(maplit::hashmap! {
@@ -179,7 +186,9 @@ supports_standalone_web_search = true
supports_websockets: false, supports_websockets: false,
supports_standalone_web_search: true, supports_standalone_web_search: true,
capabilities: None, capabilities: None,
keyring_account: None,
include_internal_metadata: false, include_internal_metadata: false,
models: Default::default(),
}; };
let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap(); let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap();
@@ -254,6 +263,7 @@ fn test_merge_configured_model_providers_adds_custom_provider() {
expected.insert( expected.insert(
"custom".to_string(), "custom".to_string(),
ModelProviderInfo { ModelProviderInfo {
keyring_account: Some("model-provider:custom".to_string()),
..custom_provider ..custom_provider
}, },
); );
@@ -367,6 +377,118 @@ fn no_provider_targets_openai_without_explicit_configuration() {
assert!(!error.contains("api.openai.com"), "{error}"); assert!(!error.contains("api.openai.com"), "{error}");
} }
#[test]
fn configured_provider_learns_keyring_account_and_default_name() {
let configured: ModelProviderInfo = toml::from_str(
r#"
base_url = "http://192.0.2.10:8080/v1"
api_key = "keyring"
"#,
)
.unwrap();
assert_eq!(configured.api_key, Some(ProviderApiKeySource::Keyring));
let providers = merge_configured_model_providers(
built_in_model_providers(),
HashMap::from([("imeai".to_string(), configured)]),
)
.unwrap();
let provider = &providers["imeai"];
assert_eq!(provider.name, "imeai");
assert_eq!(
provider.keyring_account.as_deref(),
Some("model-provider:imeai")
);
// The runtime-only keyring account is never serialized.
assert!(
!toml::to_string(provider)
.unwrap()
.contains("model-provider:")
);
}
#[test]
fn literal_api_key_is_rejected_without_echoing_it() {
// The TOML parser quotes the offending source line in its own errors; the
// deserializer message itself must never repeat the value.
let error = toml::from_str::<ModelProviderInfo>(
r#"
base_url = "http://192.0.2.10:8080/v1"
api_key = "sk-literal-secret-do-not-log"
"#,
)
.unwrap_err();
assert!(error.message().contains("must be \"keyring\""), "{error}");
assert!(
!error.message().contains("sk-literal-secret-do-not-log"),
"{error}"
);
let error = ProviderApiKeySource::deserialize(serde::de::value::StrDeserializer::<
serde::de::value::Error,
>::new("sk-literal-secret-do-not-log"))
.unwrap_err()
.to_string();
assert!(!error.contains("sk-literal-secret-do-not-log"), "{error}");
}
#[test]
fn keyring_api_key_conflicts_with_other_credential_sources() {
for extra in [
"env_key = \"KEY\"",
"experimental_bearer_token = \"token\"",
"requires_openai_auth = true",
] {
let provider: ModelProviderInfo = toml::from_str(&format!(
"base_url = \"http://192.0.2.10/v1\"\napi_key = \"keyring\"\n{extra}\n"
))
.unwrap();
let error = provider.validate().unwrap_err();
assert!(error.contains("api_key cannot be combined"), "{error}");
}
}
#[test]
fn use_stored_api_key_is_an_alias_for_requires_openai_auth() {
let provider: ModelProviderInfo =
toml::from_str("base_url = \"http://192.0.2.10/v1\"\nuse_stored_api_key = true\n").unwrap();
assert!(provider.requires_openai_auth);
let legacy: ModelProviderInfo =
toml::from_str("base_url = \"http://192.0.2.10/v1\"\nrequires_openai_auth = true\n")
.unwrap();
assert_eq!(provider, legacy);
}
#[test]
fn deserializes_per_model_settings() {
let provider: ModelProviderInfo = toml::from_str(
r#"
name = "MACOS"
base_url = "http://127.0.0.1:8080/v1"
[models."/models/Flint.gguf"]
context_window = 65536
temperature = 0.7
top_p = 0.95
max_output_tokens = 8192
reasoning_effort = "medium"
display_name = "Flint"
"#,
)
.expect("provider");
let settings = provider
.model_settings("/models/Flint.gguf")
.expect("settings");
assert_eq!(settings.context_window, Some(65536));
assert_eq!(settings.temperature, Some(0.7));
assert_eq!(settings.top_p, Some(0.95));
assert_eq!(settings.max_output_tokens, Some(8192));
assert_eq!(
settings.reasoning_effort,
Some(akode_protocol::openai_models::ReasoningEffort::Medium)
);
assert_eq!(settings.display_name.as_deref(), Some("Flint"));
assert!(provider.model_settings("other").is_none());
}
#[test] #[test]
fn local_providers_get_a_generous_idle_timeout() { fn local_providers_get_a_generous_idle_timeout() {
let provider = |base_url: &str| -> ModelProviderInfo { let provider = |base_url: &str| -> ModelProviderInfo {

View File

@@ -47,6 +47,9 @@ fn test_codex_home() -> std::path::PathBuf {
fn provider_for(base_url: String) -> ModelProviderInfo { fn provider_for(base_url: String) -> ModelProviderInfo {
ModelProviderInfo { ModelProviderInfo {
api_key: None,
keyring_account: None,
models: Default::default(),
name: "mock".into(), name: "mock".into(),
base_url: Some(base_url), base_url: Some(base_url),
model_catalog_url: None, model_catalog_url: None,

View File

@@ -369,6 +369,7 @@ async fn new_config(
experimental_thread_store: ThreadStoreConfig::Local, experimental_thread_store: ThreadStoreConfig::Local,
forced_chatgpt_workspace_id: None, forced_chatgpt_workspace_id: None,
forced_login_method: auth_config.forced_login_method, forced_login_method: auth_config.forced_login_method,
provider_api_key_store_mode: Default::default(),
web_search_mode: Constrained::allow_any(WebSearchMode::Disabled), web_search_mode: Constrained::allow_any(WebSearchMode::Disabled),
web_search_config: None, web_search_config: None,
experimental_request_user_input_enabled: true, experimental_request_user_input_enabled: true,

View File

@@ -194,6 +194,7 @@ mod agents_overview;
mod agents_overview_actions; mod agents_overview_actions;
mod agents_overview_details; mod agents_overview_details;
pub(crate) mod agents_overview_discovery; pub(crate) mod agents_overview_discovery;
mod akode_setup;
mod agents_overview_threads; mod agents_overview_threads;
mod agents_overview_usage; mod agents_overview_usage;
mod agents_overview_view; mod agents_overview_view;

View File

@@ -0,0 +1,173 @@
//! aKode settings flows inside a session: the guided setup
//! (`/setup`) and switching between configured providers from `/model`.
use super::App;
use crate::app_event::AppEvent;
use crate::app_server_session::AppServerSession;
use crate::tui;
impl App {
/// `/setup`: run the guided setup, then start a new chat with the provider it added.
pub(super) async fn run_setup(&mut self, tui: &mut tui::Tui, app_server: &AppServerSession) {
let config = self.chat_widget.config_ref().clone();
let outcome = crate::onboarding::onboarding_screen::run_setup_in_app(
tui,
app_server.request_handle(),
&config,
)
.await;
match outcome {
Ok(Some(setup)) => {
self.chat_widget.add_info_message(
format!(
"Added provider `{}` with model `{}`; starting a new chat with it.",
setup.provider_id, setup.model
),
Some("Use /model to switch between configured providers.".to_string()),
);
self.app_event_tx.send(AppEvent::NewSession { name: None });
}
Ok(None) => {
self.chat_widget
.add_info_message("Setup cancelled.".to_string(), /*hint*/ None);
}
Err(err) => {
self.chat_widget
.add_error_message(format!("Setup failed: {err}"));
}
}
tui.frame_requester().schedule_frame();
}
/// `/endpoint`: endpoints, their models and per-model settings.
pub(super) async fn run_endpoint_panel(
&mut self,
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
) {
self.refresh_in_memory_config_from_disk_best_effort("endpoint panel")
.await;
let config = self.config.clone();
let active_provider = self.chat_widget.config_ref().model_provider_id.clone();
let active_model = self.chat_widget.current_model().to_string();
// Configured endpoints, plus the active one when it is built in.
let configured: std::collections::BTreeSet<String> = config
.config_layer_stack
.effective_config()
.get("model_providers")
.and_then(|providers| providers.as_table())
.map(|providers| providers.keys().cloned().collect())
.unwrap_or_default();
let mut endpoints: Vec<crate::endpoint_panel::EndpointEntry> = config
.model_providers
.iter()
.filter(|(id, _)| configured.contains(*id) || **id == active_provider)
.map(|(id, info)| crate::endpoint_panel::EndpointEntry {
id: id.clone(),
info: info.clone(),
typed_key: None,
})
.collect();
endpoints.sort_by(|a, b| {
(a.id != active_provider, a.info.name.to_lowercase())
.cmp(&(b.id != active_provider, b.info.name.to_lowercase()))
});
let ctx = crate::endpoint_panel::EndpointPanelContext {
endpoints,
active_provider,
active_model,
global_context_window: config.model_context_window,
setup: crate::onboarding::onboarding_screen::setup_context(
&config,
Some(app_server.request_handle()),
),
};
let outcome = match crate::endpoint_panel::run_endpoint_panel(tui, ctx).await {
Ok(outcome) => outcome,
Err(err) => {
self.chat_widget
.add_error_message(format!("Pannello endpoint non disponibile: {err}"));
return;
}
};
if outcome.config_changed {
self.refresh_in_memory_config_from_disk_best_effort("endpoint panel")
.await;
crate::model_display::set_display_names_from_config(&self.config);
self.chat_widget.refresh_model_dependent_surfaces();
}
if let Some(effort) = outcome.active_effort.clone()
&& outcome.activate.is_none()
{
self.app_event_tx
.send(AppEvent::UpdateReasoningEffort(effort));
}
if let Some((provider_id, model)) = outcome.activate {
self.switch_provider(app_server, provider_id, model).await;
}
tui.frame_requester().schedule_frame();
}
/// Fetch another provider's model list directly from its server (`GET {base_url}/models`).
pub(super) fn open_provider_models(&mut self, provider_id: String) {
let config = self.chat_widget.config_ref();
let Some(provider) = config.model_providers.get(&provider_id).cloned() else {
self.chat_widget
.add_error_message(format!("Model provider `{provider_id}` is not configured."));
return;
};
let Some(base_url) = provider.base_url.clone() else {
self.chat_widget
.add_error_message(format!("Model provider `{provider_id}` has no base_url."));
return;
};
let tx = self.app_event_tx.clone();
tokio::spawn(async move {
let api_key = match provider.api_key() {
Ok(key) => key,
Err(err) => {
tx.send(AppEvent::ProviderModelsLoaded {
provider_id,
result: Err(err.to_string()),
});
return;
}
};
let result =
crate::onboarding::setup_wizard::fetch_provider_models(base_url, api_key).await;
tx.send(AppEvent::ProviderModelsLoaded {
provider_id,
result,
});
});
}
/// Make `provider_id`/`model` the default for new chats and start one.
pub(super) async fn switch_provider(
&mut self,
app_server: &mut AppServerSession,
provider_id: String,
model: String,
) {
let edits = vec![
crate::config_update::replace_config_value(
"model_provider",
serde_json::json!(provider_id),
),
crate::config_update::replace_config_value("model", serde_json::json!(model)),
];
match crate::config_update::write_config_batch(app_server.request_handle(), edits).await {
Ok(_) => {
self.chat_widget.add_info_message(
format!("Switched to `{provider_id}` · `{model}`; starting a new chat."),
/*hint*/ None,
);
self.app_event_tx.send(AppEvent::NewSession { name: None });
}
Err(err) => self.chat_widget.add_error_message(format!(
"Could not switch provider: {}",
crate::config_update::format_config_error(&err)
)),
}
}
}

View File

@@ -66,6 +66,8 @@ impl App {
| AppEvent::TerminalTitleSetupCancelled | AppEvent::TerminalTitleSetupCancelled
| AppEvent::OpenConfigEditor(_) | AppEvent::OpenConfigEditor(_)
| AppEvent::Provider(_) | AppEvent::Provider(_)
| AppEvent::OpenSetup
| AppEvent::OpenEndpointPanel
| AppEvent::SyntaxThemeSelected { .. } | AppEvent::SyntaxThemeSelected { .. }
| AppEvent::SyntaxThemePreviewed | AppEvent::SyntaxThemePreviewed
| AppEvent::OpenKeymapActionMenu { .. } | AppEvent::OpenKeymapActionMenu { .. }
@@ -188,6 +190,24 @@ impl App {
event => (event, None), event => (event, None),
}; };
match event { match event {
AppEvent::OpenSetup => {
self.run_setup(tui, app_server).await;
}
AppEvent::OpenEndpointPanel => {
self.run_endpoint_panel(tui, app_server).await;
}
AppEvent::OpenProviderModels { provider_id } => {
self.open_provider_models(provider_id);
}
AppEvent::ProviderModelsLoaded {
provider_id,
result,
} => {
self.chat_widget.show_provider_models(provider_id, result);
}
AppEvent::SwitchProvider { provider_id, model } => {
self.switch_provider(app_server, provider_id, model).await;
}
AppEvent::OpenDaemonMenu => self.open_daemon_menu(), AppEvent::OpenDaemonMenu => self.open_daemon_menu(),
AppEvent::ConfirmDaemonRestart => self.confirm_daemon_restart(), AppEvent::ConfirmDaemonRestart => self.confirm_daemon_restart(),
AppEvent::RunDaemonRestart => { AppEvent::RunDaemonRestart => {

View File

@@ -306,6 +306,29 @@ pub(crate) struct SavedFeedback {
#[allow(clippy::large_enum_variant)] #[allow(clippy::large_enum_variant)]
#[derive(Debug, IntoStaticStr)] #[derive(Debug, IntoStaticStr)]
pub(crate) enum AppEvent { pub(crate) enum AppEvent {
/// Run the guided setup (`/setup`) to add a model provider.
OpenSetup,
/// Open the endpoint, model and per-model settings panel (`/endpoint`).
OpenEndpointPanel,
/// List the models of another configured provider for `/model`.
OpenProviderModels {
provider_id: String,
},
/// Models listed by another provider's server.
ProviderModelsLoaded {
provider_id: String,
result: Result<Vec<String>, String>,
},
/// Make `provider_id`/`model` the default and start a new chat with them.
SwitchProvider {
provider_id: String,
model: String,
},
OpenDaemonMenu, OpenDaemonMenu,
ConfirmDaemonRestart, ConfirmDaemonRestart,
RunDaemonRestart, RunDaemonRestart,

View File

@@ -1,2 +1,5 @@
{"run_id":"1794922138-404543000","line":393,"new":{"module_name":"akode_tui__chatwidget__rendering__tests","snapshot_name":"initial_session_header_starts_at_the_top_of_the_viewport","metadata":{"source":"tui/src/chatwidget/rendering_tests.rs","assertion_line":393,"expression":"header.replace(&cwd, \"/tmp/project\")"},"snapshot":"\n ▄▄████▄▄ aKode v<VERSION>\n██▀▀██▀▀██ loading"},"old":{"module_name":"akode_tui__chatwidget__rendering__tests","metadata":{},"snapshot":">_ aKode (v<VERSION>)\n /tmp/project"}} {"run_id":"1794922138-404543000","line":393,"new":{"module_name":"akode_tui__chatwidget__rendering__tests","snapshot_name":"initial_session_header_starts_at_the_top_of_the_viewport","metadata":{"source":"tui/src/chatwidget/rendering_tests.rs","assertion_line":393,"expression":"header.replace(&cwd, \"/tmp/project\")"},"snapshot":"\n ▄▄████▄▄ aKode v<VERSION>\n██▀▀██▀▀██ loading"},"old":{"module_name":"akode_tui__chatwidget__rendering__tests","metadata":{},"snapshot":">_ aKode (v<VERSION>)\n /tmp/project"}}
{"run_id":"1794922381-669152000","line":393,"new":null,"old":null} {"run_id":"1794922381-669152000","line":393,"new":null,"old":null}
{"run_id":"1794932822-572039000","line":338,"new":null,"old":null}
{"run_id":"1794932822-572039000","line":393,"new":null,"old":null}
{"run_id":"1794932822-572039000","line":147,"new":null,"old":null}

View File

@@ -65,7 +65,7 @@ impl ChatWidget {
let current_label = presets let current_label = presets
.iter() .iter()
.find(|preset| preset.model.as_str() == current_model) .find(|preset| preset.model.as_str() == current_model)
.map(|preset| preset.display_name.clone()) .map(|preset| self.model_catalog.display_name(&preset.model))
.unwrap_or_else(|| self.model_display_name().to_string()); .unwrap_or_else(|| self.model_display_name().to_string());
let (mut auto_presets, other_presets): (Vec<ModelPreset>, Vec<ModelPreset>) = presets let (mut auto_presets, other_presets): (Vec<ModelPreset>, Vec<ModelPreset>) = presets
@@ -115,7 +115,7 @@ impl ChatWidget {
) )
}; };
SelectionItem { SelectionItem {
name: preset.display_name.clone(), name: self.model_catalog.display_name(&preset.model),
description, description,
is_current: model.as_str() == current_model, is_current: model.as_str() == current_model,
secondary_action: if requires_advanced_selection { secondary_action: if requires_advanced_selection {
@@ -231,7 +231,7 @@ impl ChatWidget {
})); }));
})]; })];
items.push(SelectionItem { items.push(SelectionItem {
name: preset.display_name.clone(), name: self.model_catalog.display_name(&preset.model),
description, description,
is_current, is_current,
secondary_action: direct_effort.and_then(|effort| { secondary_action: direct_effort.and_then(|effort| {
@@ -244,6 +244,8 @@ impl ChatWidget {
}); });
} }
// aKode: other configured providers follow the current provider's models.
items.extend(self.provider_switch_items());
let header = self.model_menu_header("Select Model and Effort", ""); let header = self.model_menu_header("Select Model and Effort", "");
self.show_model_selection_view( self.show_model_selection_view(
model_ids, model_ids,
@@ -256,6 +258,100 @@ impl ChatWidget {
); );
} }
/// Rows that switch to another configured provider (its models are listed next).
fn provider_switch_items(&self) -> Vec<SelectionItem> {
let config = self.config_ref();
let built_in = akode_model_provider_info::built_in_model_providers();
let mut ids: Vec<&String> = config
.model_providers
.iter()
// Built-in local servers are offered by /setup, not listed for every user.
.filter(|(id, provider)| {
**id != config.model_provider_id
&& provider.base_url.is_some()
&& !built_in.contains_key(*id)
})
.map(|(id, _)| id)
.collect();
ids.sort();
ids.into_iter()
.map(|id| {
let provider = &config.model_providers[id];
let provider_id = id.clone();
let endpoint = provider
.base_url
.as_deref()
.and_then(|url| url::Url::parse(url).ok())
.and_then(|url| {
url.host_str().map(|host| match url.port() {
Some(port) => format!("{host}:{port}"),
None => host.to_string(),
})
})
.unwrap_or_else(|| id.clone());
SelectionItem {
name: format!("Switch provider: {}", provider.name),
description: Some(format!("{id} · {endpoint}")),
dismiss_on_select: true,
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::OpenProviderModels {
provider_id: provider_id.clone(),
});
})],
..Default::default()
}
})
.collect()
}
/// Models listed by another provider; choosing one switches provider and starts a new chat.
pub(crate) fn show_provider_models(
&mut self,
provider_id: String,
result: Result<Vec<String>, String>,
) {
let models = match result {
Ok(models) => models,
Err(error) => {
self.add_error_message(format!(
"Could not list the models of `{provider_id}`: {error}"
));
return;
}
};
let name = self
.config_ref()
.model_providers
.get(&provider_id)
.map_or_else(|| provider_id.clone(), |provider| provider.name.clone());
let items = models
.into_iter()
.map(|model| {
let provider_id = provider_id.clone();
SelectionItem {
name: crate::model_display::display_name(&model),
dismiss_on_select: true,
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::SwitchProvider {
provider_id: provider_id.clone(),
model: model.clone(),
});
})],
..Default::default()
}
})
.collect();
let header = self.model_menu_header(
&format!("Models on {name}"),
"Choosing a model switches provider and starts a new chat.",
);
self.bottom_pane.show_selection_view(SelectionViewParams {
items,
header,
..SelectionViewParams::picker()
});
}
fn model_selection_actions( fn model_selection_actions(
&self, &self,
model_for_action: String, model_for_action: String,
@@ -504,7 +600,7 @@ impl ChatWidget {
.then(|| default_effort.clone()); .then(|| default_effort.clone());
let model_slug = preset.model.to_string(); let model_slug = preset.model.to_string();
let model_label = preset.display_name.clone(); let model_label = self.model_catalog.display_name(&preset.model);
let is_current_model = self.current_model() == preset.model.as_str(); let is_current_model = self.current_model() == preset.model.as_str();
let highlight_choice = if is_current_model { let highlight_choice = if is_current_model {
if in_plan_mode { if in_plan_mode {

View File

@@ -218,7 +218,7 @@ impl ChatWidget {
&self.config, &self.config,
&self.local_settings, &self.local_settings,
&model_for_header, &model_for_header,
self.model_catalog.display_name(&session.model), &self.model_catalog.display_name(&session.model),
&session, &session,
self.show_welcome_banner, self.show_welcome_banner,
startup_tooltip_override, startup_tooltip_override,

View File

@@ -377,7 +377,7 @@ impl ChatWidget {
/// Consolidating both refreshes here prevents the bug where callers update the /// Consolidating both refreshes here prevents the bug where callers update the
/// header/title (`refresh_model_display`) but forget the footer status line /// header/title (`refresh_model_display`) but forget the footer status line
/// (`refresh_status_line`). /// (`refresh_status_line`).
pub(super) fn refresh_model_dependent_surfaces(&mut self) { pub(crate) fn refresh_model_dependent_surfaces(&mut self) {
self.refresh_model_display(); self.refresh_model_display();
self.refresh_status_line(); self.refresh_status_line();
self.refresh_open_model_picker(); self.refresh_open_model_picker();
@@ -493,10 +493,10 @@ impl ChatWidget {
self.refresh_model_dependent_surfaces(); self.refresh_model_dependent_surfaces();
} }
pub(crate) fn model_display_name(&self) -> &str { pub(crate) fn model_display_name(&self) -> String {
let model = self.current_model(); let model = self.current_model();
if model.is_empty() { if model.is_empty() {
DEFAULT_MODEL_DISPLAY_NAME DEFAULT_MODEL_DISPLAY_NAME.to_string()
} else { } else {
self.model_catalog.display_name(model) self.model_catalog.display_name(model)
} }

View File

@@ -531,6 +531,12 @@ impl ChatWidget {
SlashCommand::Config => { SlashCommand::Config => {
self.open_config_panel(); self.open_config_panel();
} }
SlashCommand::Setup => {
self.app_event_tx.send(AppEvent::OpenSetup);
}
SlashCommand::Endpoint => {
self.app_event_tx.send(AppEvent::OpenEndpointPanel);
}
SlashCommand::Theme => { SlashCommand::Theme => {
self.open_theme_picker(); self.open_theme_picker();
} }
@@ -1279,6 +1285,8 @@ impl ChatWidget {
| SlashCommand::Statusline | SlashCommand::Statusline
| SlashCommand::Config | SlashCommand::Config
| SlashCommand::Theme | SlashCommand::Theme
| SlashCommand::Setup
| SlashCommand::Endpoint
| SlashCommand::Tui | SlashCommand::Tui
| SlashCommand::Pets => QueueDrain::Stop, | SlashCommand::Pets => QueueDrain::Stop,
} }

View File

@@ -252,7 +252,7 @@ impl ChatWidget {
rate_limit_snapshots.as_slice(), rate_limit_snapshots.as_slice(),
self.plan_type, self.plan_type,
Local::now(), Local::now(),
self.model_display_name(), &self.model_display_name(),
collaboration_mode, collaboration_mode,
reasoning_effort_override, reasoning_effort_override,
agents_summary, agents_summary,

View File

@@ -18,6 +18,9 @@ pub(crate) fn is_startup_cell(cell: &dyn HistoryCell) -> bool {
|| cell.as_any().is::<history_cell::SessionInfoCell>() || cell.as_any().is::<history_cell::SessionInfoCell>()
|| cell.as_any().is::<history_cell::StartupWarningsCell>() || cell.as_any().is::<history_cell::StartupWarningsCell>()
|| cell.as_any().is::<history_cell::DeprecationNoticeCell>() || cell.as_any().is::<history_cell::DeprecationNoticeCell>()
|| cell
.as_any()
.is::<history_cell::UpdateAvailableHistoryCell>()
|| cell.as_any().is::<history_cell::SessionNoticeCell>() || cell.as_any().is::<history_cell::SessionNoticeCell>()
|| cell || cell
.as_any() .as_any()

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,168 @@
use super::*;
use pretty_assertions::assert_eq;
const SECRET: &str = "sk-akode-test-secret-0123456789";
const FLINT: &str = "/Users/andrea/models/Flint.APEX-I-NanoPlus-V2.1.gguf";
fn provider(name: &str, url: &str) -> ModelProviderInfo {
ModelProviderInfo {
name: name.to_string(),
base_url: Some(url.to_string()),
..Default::default()
}
}
fn panel() -> EndpointPanel {
let mut macos = provider("MACOS", "http://127.0.0.1:8080/v1");
macos.models.insert(
FLINT.to_string(),
ProviderModelSettings {
context_window: Some(65536),
temperature: Some(0.7),
top_p: Some(0.95),
max_output_tokens: Some(8192),
reasoning_effort: Some(ReasoningEffort::Medium),
display_name: None,
},
);
let ctx = EndpointPanelContext {
endpoints: vec![
EndpointEntry {
id: "macos".to_string(),
info: macos,
typed_key: None,
},
EndpointEntry {
id: "giulio".to_string(),
info: provider("Giulio", "https://mega-link.cloud/v1"),
typed_key: Some(SECRET.to_string()),
},
EndpointEntry {
id: "openrouter".to_string(),
info: provider("OpenRouter", "https://openrouter.ai/api/v1"),
typed_key: None,
},
],
active_provider: "macos".to_string(),
active_model: FLINT.to_string(),
global_context_window: None,
setup: SetupContext::default(),
};
let mut panel = EndpointPanel::new(FrameRequester::test_dummy(), ctx);
panel.set_models_for_test(
"macos",
setup_net::ModelList {
base_url: "http://127.0.0.1:8080/v1".to_string(),
models: vec![FLINT.to_string()],
..Default::default()
},
Some(65536),
);
panel
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn render(panel: &EndpointPanel, width: u16, height: u16) -> String {
let area = Rect::new(0, 0, width, height);
let mut buf = Buffer::empty(area);
panel.render_ref(area, &mut buf);
(0..height)
.map(|y| {
(0..width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn endpoint_panel_snapshots() {
let panel = panel();
for width in [80, 120, 160] {
insta::assert_snapshot!(format!("endpoint_panel_{width}"), render(&panel, width, 14));
}
}
#[test]
fn narrow_panel_shows_one_column_with_breadcrumb() {
let mut panel = panel();
panel.handle_key_event(key(KeyCode::Tab));
panel.handle_key_event(key(KeyCode::Tab));
let text = render(&panel, 80, 14);
assert!(text.contains("Impostazioni · Flint.APEX-I-NanoPlus-V2.1"));
assert!(text.contains("(server 65536)"));
insta::assert_snapshot!("endpoint_panel_settings_80", text);
}
#[test]
fn path_model_ids_show_the_file_stem() {
let text = render(&panel(), 160, 14);
assert!(text.contains("Flint.APEX-I-NanoPlus-V2.1"));
assert!(!text.contains(".gguf"));
}
#[test]
fn keys_never_appear_in_the_panel_or_the_edit_form() {
let mut panel = panel();
panel.handle_key_event(key(KeyCode::Down));
for width in [80, 120, 160] {
assert!(!render(&panel, width, 14).contains(SECRET));
}
panel.handle_key_event(key(KeyCode::Enter));
assert!(panel.wizard.is_some());
let form = render(&panel, 120, 20);
assert!(form.contains("Modifica endpoint"));
assert!(form.contains("lascia vuoto per mantenerla"));
assert!(!form.contains(SECRET));
}
#[test]
fn the_active_endpoint_cannot_be_deleted() {
let mut panel = panel();
panel.handle_key_event(key(KeyCode::Char('d')));
assert!(!panel.confirm_delete);
assert!(render(&panel, 120, 14).contains("Non puoi eliminare l'endpoint attivo"));
panel.handle_key_event(key(KeyCode::Down));
panel.handle_key_event(key(KeyCode::Char('d')));
assert!(panel.confirm_delete);
panel.handle_key_event(key(KeyCode::Esc));
assert!(!panel.confirm_delete);
}
#[test]
fn settings_parse_and_key_paths_quote_the_model_id() {
assert_eq!(
parse_setting(Setting::Temperature, "0,7"),
Ok(Some(serde_json::json!(0.7)))
);
assert_eq!(parse_setting(Setting::Context, ""), Ok(None));
assert!(parse_setting(Setting::TopP, "1.5").is_err());
assert_eq!(
model_setting_path("openrouter", "recursive/flint-v1.0:free", "top_p"),
"model_providers.openrouter.models.\"recursive/flint-v1.0:free\".top_p"
);
}
#[test]
fn per_model_settings_serialize_without_keys() {
let mut info = provider("Giulio", "https://mega-link.cloud/v1");
info.models.insert(
"flint".to_string(),
ProviderModelSettings {
context_window: Some(65536),
temperature: Some(0.7),
..Default::default()
},
);
let toml = toml::to_string(&info).expect("serialize");
assert!(toml.contains("[models.flint]"));
assert!(toml.contains("context_window = 65536"));
assert!(!toml.contains(SECRET));
assert!(!toml.contains("top_p"));
}

View File

@@ -108,6 +108,9 @@ mod async_question_reply;
mod backend_id; mod backend_id;
mod bottom_pane; mod bottom_pane;
mod branding; mod branding;
mod endpoint_panel;
mod model_display;
mod truncate_line;
mod branch_summary; mod branch_summary;
mod chatwidget; mod chatwidget;
mod cli; mod cli;
@@ -1287,18 +1290,14 @@ async fn run_ratatui_app(
), ),
) )
.await; .await;
match provider_check { // aKode: without a provider, startup runs the first-run setup instead of a session.
Ok(false) => {} let provider_missing = match provider_check {
Ok(true) => { Ok(missing) => missing,
let exit_info = onboarding::show_no_model_provider_setup(&mut tui);
shutdown_startup_session(Some(app_server_session), &mut terminal_restore_guard).await;
return Ok(exit_info);
}
Err(err) => { Err(err) => {
shutdown_startup_session(Some(app_server_session), &mut terminal_restore_guard).await; shutdown_startup_session(Some(app_server_session), &mut terminal_restore_guard).await;
return Err(err.into()); return Err(err.into());
} }
} };
let mut app_server = Some(app_server_session); let mut app_server = Some(app_server_session);
// Folder consent runs after the picker resolves the actual destination. // Folder consent runs after the picker resolves the actual destination.
let should_show_trust_screen_flag = false; let should_show_trust_screen_flag = false;
@@ -1325,11 +1324,12 @@ async fn run_ratatui_app(
let requires_openai_auth = startup_account let requires_openai_auth = startup_account
.as_ref() .as_ref()
.is_some_and(|account| account.requires_openai_auth); .is_some_and(|account| account.requires_openai_auth);
let should_show_onboarding = should_show_onboarding( let should_show_onboarding = provider_missing
login_status, || should_show_onboarding(
requires_openai_auth, login_status,
should_show_trust_screen_flag, requires_openai_auth,
); should_show_trust_screen_flag,
);
let mut config = if should_show_onboarding { let mut config = if should_show_onboarding {
if let Err(err) = startup_draft.flush_pending_events(&mut tui).await { if let Err(err) = startup_draft.flush_pending_events(&mut tui).await {
@@ -1365,6 +1365,7 @@ async fn run_ratatui_app(
.as_ref() .as_ref()
.map(AppServerSession::request_handle), .map(AppServerSession::request_handle),
config: initial_config.clone(), config: initial_config.clone(),
show_provider_setup: provider_missing,
}, },
if show_login_screen { if show_login_screen {
app_server.as_mut() app_server.as_mut()
@@ -1398,7 +1399,27 @@ async fn run_ratatui_app(
trust_decision_was_made = trust_decision_was_made =
!uses_remote_workspace && onboarding_result.directory_trust_persisted; !uses_remote_workspace && onboarding_result.directory_trust_persisted;
} }
if let Some(selected_id) = onboarding_result.selected_gateway { // A provider written by the first-run setup is picked up like a selected gateway: reload
// config and restart the embedded server so it serves the new provider.
let selected_provider = onboarding_result.selected_gateway.clone().or_else(|| {
onboarding_result
.provider_setup
.as_ref()
.map(|setup| setup.provider_id.clone())
});
if provider_missing && selected_provider.is_none() {
shutdown_startup_session(app_server.take(), &mut terminal_restore_guard).await;
let _ = tui.terminal.clear();
return Ok(AppExitInfo {
token_usage: crate::token_usage::TokenUsage::default(),
thread_id: None,
resume_hint: None,
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::UserRequested,
});
}
if let Some(selected_id) = selected_provider {
// Account state belongs to the provider captured by the embedded server at startup. // Account state belongs to the provider captured by the embedded server at startup.
let mut selected = startup_draft let mut selected = startup_draft
.run_until( .run_until(
@@ -1452,7 +1473,9 @@ async fn run_ratatui_app(
// Reload config when persisted trust or auth changes alter the current process. // Reload config when persisted trust or auth changes alter the current process.
Ok::<_, std::io::Error>( Ok::<_, std::io::Error>(
if !uses_remote_workspace if !uses_remote_workspace
&& (onboarding_result.directory_trust_persisted || show_login_screen) && (onboarding_result.directory_trust_persisted
|| show_login_screen
|| onboarding_result.provider_setup.is_some())
{ {
load_config_or_exit_with_fallback_cwd( load_config_or_exit_with_fallback_cwd(
cli_kv_overrides.clone(), cli_kv_overrides.clone(),
@@ -2043,6 +2066,7 @@ async fn run_ratatui_app(
} }
let local_settings = crate::local_settings::LocalSettings::for_tui(&config, &tui); let local_settings = crate::local_settings::LocalSettings::for_tui(&config, &tui);
crate::model_display::set_display_names_from_config(&config);
crate::markdown_render::preferences::init(local_settings.tui.rendering); crate::markdown_render::preferences::init(local_settings.tui.rendering);
// Configure syntax highlighting theme from the final config — onboarding // Configure syntax highlighting theme from the final config — onboarding
// and resume/fork can both reload config with a different tui_theme, so // and resume/fork can both reload config with a different tui_theme, so

View File

@@ -66,11 +66,17 @@ impl ModelCatalog {
Ok(self.models.clone()) Ok(self.models.clone())
} }
pub(crate) fn display_name<'a>(&'a self, model: &'a str) -> &'a str { /// Name shown for `model`: a configured display name, a catalog name that differs from
/// the id, else the id (as a file stem when it is a path).
pub(crate) fn display_name(&self, model: &str) -> String {
let shown = crate::model_display::display_name(model);
if shown != model {
return shown;
}
self.models self.models
.iter() .iter()
.find(|preset| preset.model == model) .find(|preset| preset.model == model && preset.display_name != model)
.map(|preset| preset.display_name.as_str()) .map(|preset| preset.display_name.clone())
.unwrap_or_else(|| model_display_name(model)) .unwrap_or_else(|| model_display_name(model).to_string())
} }
} }

View File

@@ -0,0 +1,104 @@
//! Model names as shown in the interface. A `display_name` configured for the model
//! (`[model_providers.<id>.models."<model id>"]`) wins; an id that looks like a file path
//! shows only the file name without its extension. Requests always use the full id.
use std::collections::HashMap;
use std::path::Path;
use std::sync::PoisonError;
use std::sync::RwLock;
use crate::legacy_core::config::Config;
static DISPLAY_NAMES: RwLock<Option<HashMap<String, String>>> = RwLock::new(None);
/// Load the configured display names; the active provider's names win over the others.
pub(crate) fn set_display_names_from_config(config: &Config) {
let mut names = HashMap::new();
let configured = config
.model_providers
.iter()
.filter(|(id, _)| **id != config.model_provider_id)
.map(|(_, provider)| provider)
.chain(std::iter::once(&config.model_provider));
for provider in configured {
for (model, settings) in &provider.models {
if let Some(name) = settings
.display_name
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
{
names.insert(model.clone(), name.to_string());
}
}
}
*DISPLAY_NAMES
.write()
.unwrap_or_else(PoisonError::into_inner) = Some(names);
}
/// Whether `model` is a local file path rather than a plain or `vendor/model` id.
fn looks_like_path(model: &str) -> bool {
const MODEL_FILE_EXTENSIONS: [&str; 6] = ["gguf", "ggml", "bin", "safetensors", "onnx", "mlx"];
model.starts_with('/')
|| model.starts_with("~/")
|| model.starts_with("./")
|| model.starts_with("../")
|| model.contains('\\')
|| Path::new(model)
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| {
MODEL_FILE_EXTENSIONS
.iter()
.any(|known| ext.eq_ignore_ascii_case(known))
})
}
/// `model` without its directory and extension when it looks like a file path.
pub(crate) fn short_model_name(model: &str) -> String {
if !looks_like_path(model) {
return model.to_string();
}
let file = model
.rsplit(['/', '\\'])
.find(|part| !part.is_empty())
.unwrap_or(model);
Path::new(file)
.file_stem()
.and_then(|stem| stem.to_str())
.filter(|stem| !stem.is_empty())
.unwrap_or(file)
.to_string()
}
/// Name shown for `model`: the configured display name, else [`short_model_name`].
pub(crate) fn display_name(model: &str) -> String {
let configured = DISPLAY_NAMES
.read()
.unwrap_or_else(PoisonError::into_inner)
.as_ref()
.and_then(|names| names.get(model).cloned());
configured.unwrap_or_else(|| short_model_name(model))
}
#[cfg(test)]
mod tests {
use super::short_model_name;
use pretty_assertions::assert_eq;
#[test]
fn path_ids_show_the_file_stem() {
assert_eq!(
short_model_name("/Users/me/models/Flint.APEX-I-NanoPlus-V2.1.gguf"),
"Flint.APEX-I-NanoPlus-V2.1"
);
assert_eq!(short_model_name("C:\\models\\qwen3.gguf"), "qwen3");
assert_eq!(short_model_name("flint.gguf"), "flint");
assert_eq!(
short_model_name("qwen/qwen3-coder:free"),
"qwen/qwen3-coder:free"
);
assert_eq!(short_model_name("qwen3.6-35b-a3b"), "qwen3.6-35b-a3b");
}
}

View File

@@ -48,6 +48,7 @@ pub(crate) async fn authenticate_gateway(
app_server_target: AppServerTarget::Embedded, app_server_target: AppServerTarget::Embedded,
app_server_request_handle: Some(handle.clone()), app_server_request_handle: Some(handle.clone()),
config: config.clone(), config: config.clone(),
show_provider_setup: false,
}, },
) )
.await; .await;

View File

@@ -6,8 +6,9 @@ mod keys;
pub(crate) mod onboarding_screen; pub(crate) mod onboarding_screen;
mod provider_required; mod provider_required;
pub(crate) use provider_required::model_provider_missing; pub(crate) use provider_required::model_provider_missing;
pub(crate) use provider_required::show_no_model_provider_setup; pub(crate) mod provider_setup;
mod provider_setup; pub(crate) mod setup_net;
pub(crate) mod setup_wizard;
pub(crate) use provider_setup::FieldDisplay; pub(crate) use provider_setup::FieldDisplay;
pub(crate) use provider_setup::ProviderInput; pub(crate) use provider_setup::ProviderInput;
pub(crate) use provider_setup::move_provider_field; pub(crate) use provider_setup::move_provider_field;

View File

@@ -42,6 +42,9 @@ use crate::onboarding::auth::AuthModeWidget;
use crate::onboarding::auth::SignInOption; use crate::onboarding::auth::SignInOption;
use crate::onboarding::auth::SignInState; use crate::onboarding::auth::SignInState;
use crate::onboarding::keys; use crate::onboarding::keys;
use crate::onboarding::setup_wizard::SetupContext;
use crate::onboarding::setup_wizard::SetupOutcome;
use crate::onboarding::setup_wizard::SetupWizard;
use crate::onboarding::trust_directory::TrustDirectorySelection; use crate::onboarding::trust_directory::TrustDirectorySelection;
use crate::onboarding::trust_directory::TrustDirectoryWidget; use crate::onboarding::trust_directory::TrustDirectoryWidget;
use crate::onboarding::welcome::WelcomeWidget; use crate::onboarding::welcome::WelcomeWidget;
@@ -65,6 +68,7 @@ pub(crate) use directory_trust::check_directory_trust;
enum Step { enum Step {
Welcome(WelcomeWidget), Welcome(WelcomeWidget),
Auth(AuthModeWidget), Auth(AuthModeWidget),
Setup(SetupWizard),
TrustDirectory(TrustDirectoryWidget), TrustDirectory(TrustDirectoryWidget),
} }
@@ -101,12 +105,16 @@ pub(crate) struct OnboardingScreenArgs {
pub app_server_target: crate::AppServerTarget, pub app_server_target: crate::AppServerTarget,
pub app_server_request_handle: Option<AppServerRequestHandle>, pub app_server_request_handle: Option<AppServerRequestHandle>,
pub config: Config, pub config: Config,
/// Run the aKode first-run setup (no model provider is configured).
pub show_provider_setup: bool,
} }
#[derive(Default)] #[derive(Default)]
pub(crate) struct OnboardingResult { pub(crate) struct OnboardingResult {
pub directory_trust_persisted: bool, pub directory_trust_persisted: bool,
pub selected_gateway: Option<String>, pub selected_gateway: Option<String>,
/// Provider and model written by the first-run setup.
pub provider_setup: Option<SetupOutcome>,
pub should_exit: bool, pub should_exit: bool,
} }
@@ -129,6 +137,7 @@ impl OnboardingScreen {
app_server_target, app_server_target,
app_server_request_handle, app_server_request_handle,
config, config,
show_provider_setup,
} = args; } = args;
let local_settings = crate::local_settings::LocalSettings::from(&config); let local_settings = crate::local_settings::LocalSettings::from(&config);
let cwd = config.cwd.to_path_buf(); let cwd = config.cwd.to_path_buf();
@@ -137,10 +146,18 @@ impl OnboardingScreen {
.map(|project| project.trust_target.to_string_lossy().into_owned()); .map(|project| project.trust_target.to_string_lossy().into_owned());
let auth_config = config.auth_config(); let auth_config = config.auth_config();
let mut steps: Vec<Step> = Vec::new(); let mut steps: Vec<Step> = Vec::new();
steps.push(Step::Welcome(WelcomeWidget::new( if show_provider_setup {
!matches!(login_status, LoginStatus::NotAuthenticated), // The setup shows its own welcome page.
local_settings.tui.animations && local_settings.tui.effects.welcome, steps.push(Step::Setup(SetupWizard::new(
))); tui.frame_requester(),
setup_context(&config, app_server_request_handle.clone()),
)));
} else {
steps.push(Step::Welcome(WelcomeWidget::new(
!matches!(login_status, LoginStatus::NotAuthenticated),
local_settings.tui.animations && local_settings.tui.effects.welcome,
)));
}
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
let show_windows_create_sandbox_hint = if show_trust_screen let show_windows_create_sandbox_hint = if show_trust_screen
&& remote_project_trust.is_none() && remote_project_trust.is_none()
@@ -273,7 +290,20 @@ impl OnboardingScreen {
pub(super) fn auth_widget_mut(&mut self) -> Option<&mut AuthModeWidget> { pub(super) fn auth_widget_mut(&mut self) -> Option<&mut AuthModeWidget> {
self.steps.iter_mut().find_map(|step| match step { self.steps.iter_mut().find_map(|step| match step {
Step::Auth(widget) => Some(widget), Step::Auth(widget) => Some(widget),
Step::Welcome(_) | Step::TrustDirectory(_) => None, Step::Welcome(_) | Step::Setup(_) | Step::TrustDirectory(_) => None,
})
}
fn setup_wizard_mut(&mut self) -> Option<&mut SetupWizard> {
self.steps.iter_mut().find_map(|step| match step {
Step::Setup(widget) => Some(widget),
Step::Welcome(_) | Step::Auth(_) | Step::TrustDirectory(_) => None,
})
}
fn is_setup_in_progress(&self) -> bool {
self.steps.iter().any(|step| {
matches!(step, Step::Setup(_)) && matches!(step.get_step_state(), StepState::InProgress)
}) })
} }
@@ -296,15 +326,20 @@ impl OnboardingScreen {
fn text_entry_context(&self) -> TextEntryContext { fn text_entry_context(&self) -> TextEntryContext {
self.steps self.steps
.iter() .iter()
.find_map(|step| { .find_map(|step| match step {
if let Step::Auth(widget) = step { Step::Auth(widget) => Some(TextEntryContext {
active: widget.is_text_entry_active(),
has_text: widget.should_suppress_printable_quit(),
}),
// Setup fields take printable keys (including `q`) from the first character.
Step::Setup(widget) if matches!(widget.get_step_state(), StepState::InProgress) => {
let active = widget.is_text_entry_active();
Some(TextEntryContext { Some(TextEntryContext {
active: widget.is_text_entry_active(), active,
has_text: widget.should_suppress_printable_quit(), has_text: active,
}) })
} else {
None
} }
_ => None,
}) })
.unwrap_or_default() .unwrap_or_default()
} }
@@ -332,6 +367,11 @@ impl KeyboardHandler for OnboardingScreen {
// If the user cancels the auth menu, exit the app rather than // If the user cancels the auth menu, exit the app rather than
// leave the user at a prompt in an unauthed state. // leave the user at a prompt in an unauthed state.
self.should_exit = true; self.should_exit = true;
} else if self.is_setup_in_progress() {
if let Some(widget) = self.setup_wizard_mut() {
widget.cancel();
}
self.should_exit = true;
} else if self.is_trust_step_active() { } else if self.is_trust_step_active() {
self.should_exit = true; self.should_exit = true;
} }
@@ -396,7 +436,7 @@ impl WidgetRef for &OnboardingScreen {
for step in self.current_steps() { for step in self.current_steps() {
match step { match step {
Step::Welcome(widget) => widget.set_presentation(logo_presentation), Step::Welcome(widget) => widget.set_presentation(logo_presentation),
Step::Auth(_) | Step::TrustDirectory(_) => {} Step::Auth(_) | Step::Setup(_) | Step::TrustDirectory(_) => {}
} }
} }
@@ -469,6 +509,7 @@ impl KeyboardHandler for Step {
match self { match self {
Step::Welcome(widget) => widget.handle_key_event(key_event), Step::Welcome(widget) => widget.handle_key_event(key_event),
Step::Auth(widget) => widget.handle_key_event(key_event), Step::Auth(widget) => widget.handle_key_event(key_event),
Step::Setup(widget) => widget.handle_key_event(key_event),
Step::TrustDirectory(widget) => widget.handle_key_event(key_event), Step::TrustDirectory(widget) => widget.handle_key_event(key_event),
} }
} }
@@ -477,6 +518,7 @@ impl KeyboardHandler for Step {
match self { match self {
Step::Welcome(_) => {} Step::Welcome(_) => {}
Step::Auth(widget) => widget.handle_paste(pasted), Step::Auth(widget) => widget.handle_paste(pasted),
Step::Setup(widget) => widget.handle_paste(pasted),
Step::TrustDirectory(widget) => widget.handle_paste(pasted), Step::TrustDirectory(widget) => widget.handle_paste(pasted),
} }
} }
@@ -487,6 +529,7 @@ impl StepStateProvider for Step {
match self { match self {
Step::Welcome(w) => w.get_step_state(), Step::Welcome(w) => w.get_step_state(),
Step::Auth(w) => w.get_step_state(), Step::Auth(w) => w.get_step_state(),
Step::Setup(w) => w.get_step_state(),
Step::TrustDirectory(w) => w.get_step_state(), Step::TrustDirectory(w) => w.get_step_state(),
} }
} }
@@ -501,6 +544,9 @@ impl WidgetRef for Step {
Step::Auth(widget) => { Step::Auth(widget) => {
widget.render_ref(area, buf); widget.render_ref(area, buf);
} }
Step::Setup(widget) => {
widget.render_ref(area, buf);
}
Step::TrustDirectory(widget) => { Step::TrustDirectory(widget) => {
widget.render_ref(area, buf); widget.render_ref(area, buf);
} }
@@ -564,9 +610,16 @@ async fn run_onboarding_screen_inner(
while !onboarding_screen.is_done() { while !onboarding_screen.is_done() {
tokio::select! { tokio::select! {
() = async { () = async {
match onboarding_screen.auth_widget_mut() { // The setup and the sign-in step never run in the same screen.
Some(auth) => auth.advance_gateway_request().await, if onboarding_screen.setup_wizard_mut().is_some() {
None => std::future::pending().await, if let Some(setup) = onboarding_screen.setup_wizard_mut() {
setup.advance().await;
}
} else {
match onboarding_screen.auth_widget_mut() {
Some(auth) => auth.advance_gateway_request().await,
None => std::future::pending().await,
}
} }
} => {} } => {}
event = tui_events.next() => { event = tui_events.next() => {
@@ -655,10 +708,61 @@ async fn run_onboarding_screen_inner(
_ => None, _ => None,
} }
}), }),
provider_setup: onboarding_screen.setup_wizard_mut().and_then(|widget| {
(!widget.is_cancelled())
.then(|| widget.outcome().cloned())
.flatten()
}),
should_exit: onboarding_screen.should_exit(), should_exit: onboarding_screen.should_exit(),
}) })
} }
/// Configuration facts the setup needs (existing provider ids and local server URLs).
pub(crate) fn setup_context(
config: &Config,
request_handle: Option<AppServerRequestHandle>,
) -> SetupContext {
let base_url = |id: &str| {
config
.model_providers
.get(id)
.and_then(|provider| provider.base_url.clone())
};
SetupContext {
existing_provider_ids: config.model_providers.keys().cloned().collect(),
ollama_base_url: base_url(akode_model_provider_info::OLLAMA_OSS_PROVIDER_ID),
lmstudio_base_url: base_url(akode_model_provider_info::LMSTUDIO_OSS_PROVIDER_ID),
request_handle,
codex_home: config.codex_home.as_path().to_path_buf(),
key_store_mode: config.provider_api_key_store_mode,
keyring_available: akode_login::provider_api_key_keyring_available(),
endpoint_mode: None,
}
}
/// Run the setup from inside a session (`/setup`) to add another provider.
pub(crate) async fn run_setup_in_app(
tui: &mut Tui,
request_handle: AppServerRequestHandle,
config: &Config,
) -> Result<Option<SetupOutcome>> {
let screen = OnboardingScreen {
request_frame: tui.frame_requester(),
steps: vec![Step::Setup(SetupWizard::new(
tui.frame_requester(),
setup_context(config, Some(request_handle.clone())),
))],
remote_trust_key: None,
is_done: false,
should_exit: false,
};
let result =
run_onboarding_screen(screen, Some(request_handle), /*app_server*/ None, tui).await?;
tui.terminal.clear()?;
tui.frame_requester().schedule_frame();
Ok(result.provider_setup)
}
/// Render a newly activated trust step before discarding keys from the preceding screen. /// Render a newly activated trust step before discarding keys from the preceding screen.
/// ///
/// Once the step is active, preserve fresh navigation and confirmation input. /// Once the step is active, preserve fresh navigation and confirmation input.

View File

@@ -1,21 +1,16 @@
//! Startup guidance shown when no model provider is configured. //! Detect a fresh installation without a model provider.
//! //!
//! aKode ships no default provider, so a fresh installation cannot start a model session until //! aKode ships no default provider, so a fresh installation cannot start a model session until
//! the user adds one. For now startup prints the setup guidance and exits with an error; a //! the user adds one; startup then runs the first-run setup (`setup_wizard`).
//! first-run onboarding screen can replace [`show_no_model_provider_setup`] later.
use akode_app_server_client::AppServerRequestHandle; use akode_app_server_client::AppServerRequestHandle;
use akode_app_server_protocol::ClientRequest; use akode_app_server_protocol::ClientRequest;
use akode_app_server_protocol::ConfigReadParams; use akode_app_server_protocol::ConfigReadParams;
use akode_app_server_protocol::RequestId; use akode_app_server_protocol::RequestId;
use akode_model_provider_info::NO_MODEL_PROVIDER_CONFIGURED_ERROR;
use uuid::Uuid; use uuid::Uuid;
use crate::AppExitInfo;
use crate::ExitReason;
use crate::config_update::EffectiveConfig; use crate::config_update::EffectiveConfig;
use crate::legacy_core::config::Config; use crate::legacy_core::config::Config;
use crate::tui::Tui;
/// Whether neither the local configuration nor the connected app server selects a provider. /// Whether neither the local configuration nor the connected app server selects a provider.
/// ///
@@ -50,18 +45,3 @@ pub(crate) async fn model_provider_missing(
} }
} }
} }
/// Explain how to configure a model provider instead of starting a model session.
///
/// The returned exit info makes the caller print the guidance and exit with a non-zero status.
pub(crate) fn show_no_model_provider_setup(tui: &mut Tui) -> AppExitInfo {
let _ = tui.terminal.clear();
AppExitInfo {
token_usage: crate::token_usage::TokenUsage::default(),
thread_id: None,
resume_hint: None,
disconnect_info: None,
update_action: None,
exit_reason: ExitReason::Fatal(NO_MODEL_PROVIDER_CONFIGURED_ERROR.to_string()),
}
}

View File

@@ -0,0 +1,414 @@
//! Network checks used by the first-run setup: model list and Responses API probe.
//!
//! Every message returned here is shown to the user, so API keys are redacted from it and
//! requests are sent without request logging.
use std::collections::HashMap;
use std::time::Duration;
use akode_http_client::HttpClient;
use akode_http_client::HttpClientBuilder;
use serde_json::Value;
const MODELS_TIMEOUT: Duration = Duration::from_secs(15);
/// Slow CPU servers can take a while to prefill even a tiny prompt.
const RESPONSES_TIMEOUT: Duration = Duration::from_secs(180);
const MAX_ERROR_BODY: usize = 200;
fn client() -> Result<HttpClient, String> {
HttpClientBuilder::new()
.without_request_logging()
.build_direct()
.map_err(|err| format!("Impossibile preparare il client HTTP: {err}"))
}
/// Remove the API key (and anything that looks like an Authorization header) from `text`.
pub(crate) fn redact(text: &str, api_key: Option<&str>) -> String {
let mut text = text.to_string();
if let Some(key) = api_key.map(str::trim).filter(|key| !key.is_empty()) {
text = text.replace(key, "••••");
}
text
}
fn snippet(body: &str) -> String {
let body = body.split_whitespace().collect::<Vec<_>>().join(" ");
let mut out: String = body.chars().take(MAX_ERROR_BODY).collect();
if body.chars().count() > MAX_ERROR_BODY {
out.push('…');
}
out
}
/// `base` without trailing slashes.
pub(crate) fn normalize_base_url(base: &str) -> String {
base.trim().trim_end_matches('/').to_string()
}
/// Validate a user-entered base URL (http or https, with a host).
pub(crate) fn validate_base_url(base: &str) -> Result<String, String> {
let base = normalize_base_url(base);
match url::Url::parse(&base) {
Ok(url) if matches!(url.scheme(), "http" | "https") && url.host_str().is_some() => Ok(base),
Ok(_) => Err("L'URL deve iniziare con http:// o https://".to_string()),
Err(_) => Err("URL non valido (esempio: http://192.168.1.10:8080/v1)".to_string()),
}
}
/// Model ids from an OpenAI-style `{data: [{id}]}` list (or `{models: [{name|model}]}`).
pub(crate) fn parse_model_ids(body: &Value) -> Vec<String> {
let mut ids: Vec<String> = Vec::new();
let mut push = |id: Option<&str>| {
if let Some(id) = id.map(str::trim).filter(|id| !id.is_empty())
&& !ids.iter().any(|existing| existing == id)
{
ids.push(id.to_string());
}
};
if let Some(data) = body.get("data").and_then(Value::as_array) {
for entry in data {
push(entry.get("id").and_then(Value::as_str));
}
}
if let Some(models) = body.get("models").and_then(Value::as_array) {
for entry in models {
push(
entry
.get("model")
.or_else(|| entry.get("name"))
.and_then(Value::as_str),
);
}
}
ids
}
/// Context window each model runs with, as reported in its list entry (llama.cpp
/// `meta.n_ctx`, vLLM `max_model_len`, OpenRouter `context_length`, LM Studio).
pub(crate) fn parse_model_context_windows(body: &Value) -> HashMap<String, i64> {
let positive = |value: Option<&Value>| value.and_then(Value::as_i64).filter(|n| *n > 0);
let mut windows = HashMap::new();
for entry in body
.get("data")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let Some(id) = entry.get("id").and_then(Value::as_str).map(str::trim) else {
continue;
};
let window = positive(entry.pointer("/meta/n_ctx"))
.or_else(|| positive(entry.get("max_model_len")))
.or_else(|| positive(entry.get("context_length")))
.or_else(|| positive(entry.get("max_context_length")))
.or_else(|| positive(entry.get("loaded_context_length")));
if let Some(window) = window {
windows.insert(id.to_string(), window);
}
}
windows
}
/// Models whose entry lists `supported_parameters` without reasoning (OpenRouter): the
/// reasoning setting is hidden for them. Models without the list may support it.
pub(crate) fn parse_models_without_reasoning(body: &Value) -> Vec<String> {
let mut ids = Vec::new();
for entry in body
.get("data")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let (Some(id), Some(params)) = (
entry.get("id").and_then(Value::as_str),
entry.get("supported_parameters").and_then(Value::as_array),
) else {
continue;
};
if !params
.iter()
.filter_map(Value::as_str)
.any(|param| param == "reasoning")
{
ids.push(id.trim().to_string());
}
}
ids
}
/// Ids of the models a provider offers for free: an OpenRouter-style `:free` suffix, or a
/// `pricing` object whose prompt and completion prices are both zero.
pub(crate) fn parse_free_model_ids(body: &Value) -> Vec<String> {
let is_zero = |value: Option<&Value>| match value {
Some(Value::String(text)) => text.trim().parse::<f64>().is_ok_and(|price| price == 0.0),
Some(Value::Number(number)) => number.as_f64().is_some_and(|price| price == 0.0),
_ => false,
};
let mut free = Vec::new();
for entry in body
.get("data")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let Some(id) = entry.get("id").and_then(Value::as_str).map(str::trim) else {
continue;
};
let pricing = entry.get("pricing");
let zero_priced = pricing.is_some_and(|pricing| {
is_zero(pricing.get("prompt")) && is_zero(pricing.get("completion"))
});
if (id.ends_with(":free") || zero_priced) && !free.iter().any(|known| known == id) {
free.push(id.to_string());
}
}
free
}
fn connection_error(url: &str, err: &impl std::fmt::Display, api_key: Option<&str>) -> String {
redact(&format!("Server non raggiungibile ({url}): {err}"), api_key)
}
/// Result of listing models: the base URL that answered (a `/v1` suffix may have been added).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct ModelList {
pub base_url: String,
pub models: Vec<String>,
/// Models that cost nothing (see [`parse_free_model_ids`]).
pub free: Vec<String>,
/// Server-reported context windows (see [`parse_model_context_windows`]).
pub context_windows: HashMap<String, i64>,
/// Models known not to support reasoning (see [`parse_models_without_reasoning`]).
pub without_reasoning: Vec<String>,
}
/// `GET {base}/models`; when `base` has no path, `{base}/v1/models` is tried too.
pub(crate) async fn fetch_models(
base: String,
api_key: Option<String>,
) -> Result<ModelList, String> {
let base = normalize_base_url(&base);
let client = client()?;
let mut candidates = vec![base.clone()];
if url::Url::parse(&base).is_ok_and(|url| matches!(url.path(), "" | "/")) {
candidates.push(format!("{base}/v1"));
}
let mut last_error = String::new();
for candidate in candidates {
let url = format!("{candidate}/models");
let mut request = client.get(&url).timeout(MODELS_TIMEOUT);
if let Some(key) = api_key.as_deref() {
request = request.bearer_auth(key);
}
let response = match request.send().await {
Ok(response) => response,
Err(err) => return Err(connection_error(&candidate, &err, api_key.as_deref())),
};
let status = response.status();
if status.as_u16() == 401 || status.as_u16() == 403 {
return Err(format!(
"Chiave API rifiutata (HTTP {}): controlla la chiave.",
status.as_u16()
));
}
if !status.is_success() {
let body = response.text().await.unwrap_or_default();
last_error = redact(
&format!(
"GET {url} ha risposto HTTP {}: {}",
status.as_u16(),
snippet(&body)
),
api_key.as_deref(),
);
continue;
}
let body: Value = match response.json().await {
Ok(body) => body,
Err(_) => {
last_error = format!("GET {url} non ha restituito JSON.");
continue;
}
};
let models = parse_model_ids(&body);
if models.is_empty() {
last_error = "Il server non ha elencato nessun modello.".to_string();
continue;
}
let free = parse_free_model_ids(&body);
return Ok(ModelList {
base_url: candidate,
models,
free,
context_windows: parse_model_context_windows(&body),
without_reasoning: parse_models_without_reasoning(&body),
});
}
Err(last_error)
}
/// llama.cpp `GET /props` (at the server root, without `/v1`): the context window the
/// server runs with (`default_generation_settings.n_ctx`, else `n_ctx`). `None` when the
/// server has no such endpoint.
pub(crate) async fn fetch_props_context_window(
base: String,
api_key: Option<String>,
) -> Option<i64> {
let base = normalize_base_url(&base);
let root = base.strip_suffix("/v1").unwrap_or(&base);
let client = client().ok()?;
let mut request = client.get(&format!("{root}/props")).timeout(MODELS_TIMEOUT);
if let Some(key) = api_key.as_deref() {
request = request.bearer_auth(key);
}
let response = request.send().await.ok()?;
if !response.status().is_success() {
return None;
}
let body: Value = response.json().await.ok()?;
let positive = |value: Option<&Value>| value.and_then(Value::as_i64).filter(|n| *n > 0);
positive(body.pointer("/default_generation_settings/n_ctx"))
.or_else(|| positive(body.get("n_ctx")))
}
/// Explain a failed `POST /responses`.
pub(crate) fn classify_responses_failure(status: u16, body: &str, model: &str) -> String {
let lower = body.to_lowercase();
let mentions_model = lower.contains("model");
let not_found = [
"not found",
"does not exist",
"unknown model",
"no such model",
]
.iter()
.any(|needle| lower.contains(needle));
if status == 401 || status == 403 {
format!("Chiave API rifiutata (HTTP {status}): controlla la chiave.")
} else if mentions_model && not_found {
format!("Modello «{model}» non trovato sul server (HTTP {status}).")
} else if matches!(status, 404 | 405 | 501) {
format!(
"Il server non supporta la Responses API: POST /responses ha risposto HTTP {status}."
)
} else {
format!("Il server ha risposto HTTP {status}: {}", snippet(body))
}
}
/// Minimal streaming Responses API request; succeeds once the first event arrives.
pub(crate) async fn test_responses(
base: String,
api_key: Option<String>,
model: String,
) -> Result<(), String> {
let base = normalize_base_url(&base);
let client = client()?;
let url = format!("{base}/responses");
let body = serde_json::json!({
"model": model,
"input": "ok",
"max_output_tokens": 16,
"stream": true,
});
let mut request = client.post(&url).timeout(RESPONSES_TIMEOUT).json(&body);
if let Some(key) = api_key.as_deref() {
request = request.bearer_auth(key);
}
let mut response = match request.send().await {
Ok(response) => response,
Err(err) => return Err(connection_error(&base, &err, api_key.as_deref())),
};
let status = response.status();
if !status.is_success() {
let body = response.text().await.unwrap_or_default();
return Err(redact(
&classify_responses_failure(status.as_u16(), &body, &model),
api_key.as_deref(),
));
}
match response.chunk().await {
Ok(Some(chunk)) => {
let text = String::from_utf8_lossy(&chunk);
if text.contains("data:")
|| text.contains("event:")
|| text.trim_start().starts_with('{')
{
Ok(())
} else {
Err("Risposta inattesa da /responses (non è uno stream di eventi).".to_string())
}
}
Ok(None) => Err("Il server ha chiuso la risposta senza dati.".to_string()),
Err(err) => Err(redact(
&format!("Lettura della risposta non riuscita: {err}"),
api_key.as_deref(),
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn parses_openai_and_llama_cpp_model_lists() {
let body = serde_json::json!({
"models": [{"name": "qwen3.6-35b-a3b", "model": "qwen3.6-35b-a3b"}],
"data": [{"id": "qwen3.6-35b-a3b"}, {"id": "other"}],
});
assert_eq!(parse_model_ids(&body), vec!["qwen3.6-35b-a3b", "other"]);
assert!(parse_model_ids(&serde_json::json!({"data": []})).is_empty());
}
#[test]
fn finds_free_models_by_suffix_or_zero_pricing() {
let body = serde_json::json!({
"data": [
{"id": "meta-llama/llama-3.3-70b-instruct:free", "pricing": {"prompt": "0.0000001", "completion": "0"}},
{"id": "openrouter/zero", "pricing": {"prompt": "0", "completion": "0"}},
{"id": "local-number", "pricing": {"prompt": 0, "completion": 0.0}},
{"id": "anthropic/paid", "pricing": {"prompt": "0.000003", "completion": "0.000015"}},
{"id": "no-pricing"},
],
});
assert_eq!(
parse_free_model_ids(&body),
vec![
"meta-llama/llama-3.3-70b-instruct:free",
"openrouter/zero",
"local-number"
]
);
}
#[test]
fn validates_base_urls() {
assert_eq!(
validate_base_url(" http://192.168.40.25:8080/v1/ "),
Ok("http://192.168.40.25:8080/v1".to_string())
);
assert!(validate_base_url("ftp://host").is_err());
assert!(validate_base_url("not a url").is_err());
}
#[test]
fn classifies_responses_failures() {
assert!(classify_responses_failure(401, "", "m").contains("Chiave API rifiutata"));
assert!(
classify_responses_failure(404, "{\"error\":\"model 'm' not found\"}", "m")
.contains("Modello «m» non trovato")
);
assert!(classify_responses_failure(404, "File Not Found", "m").contains("Responses API"));
assert!(classify_responses_failure(500, "boom", "m").contains("HTTP 500: boom"));
}
#[test]
fn redacts_api_keys_from_messages() {
let key = "sk-secret-123456";
let message = redact(&format!("HTTP 400: invalid key {key}"), Some(key));
assert!(!message.contains(key));
assert!(message.contains("••••"));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,461 @@
use super::*;
use pretty_assertions::assert_eq;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
const SECRET: &str = "sk-akode-test-secret-0123456789";
fn wizard() -> SetupWizard {
let mut ctx = SetupContext {
key_store_mode: AuthCredentialsStoreMode::Auto,
keyring_available: true,
..Default::default()
};
ctx.existing_provider_ids
.extend(["ollama".to_string(), "lmstudio".to_string()]);
SetupWizard::new(FrameRequester::test_dummy(), ctx)
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn type_text(wizard: &mut SetupWizard, text: &str) {
for ch in text.chars() {
wizard.handle_key_event(key(KeyCode::Char(ch)));
}
}
fn render(wizard: &SetupWizard, width: u16, height: u16) -> String {
let area = Rect::new(0, 0, width, height);
let mut buf = Buffer::empty(area);
wizard.render_ref(area, &mut buf);
(0..height)
.map(|y| {
(0..width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.join("\n")
.trim_end()
.to_string()
}
/// Every row fits the terminal width (no wrapping, nothing cut mid-glyph).
fn assert_fits(rendered: &str, width: u16) {
for line in rendered.lines() {
assert!(
display_width(line) <= usize::from(width),
"line wider than {width}: {line:?}"
);
}
}
fn snapshot_all_widths(name: &str, wizard: &SetupWizard, height: u16) {
for width in [80u16, 120, 60] {
let rendered = render(wizard, width, height);
assert_fits(&rendered, width);
insta::assert_snapshot!(format!("{name}_{width}"), rendered);
}
}
fn endpoint_wizard() -> SetupWizard {
let mut wizard = wizard();
wizard.go(Page::Endpoint);
type_text(&mut wizard, "imeAI");
wizard.handle_key_event(key(KeyCode::Tab));
type_text(&mut wizard, "http://192.168.40.25:8080/v1");
wizard.handle_key_event(key(KeyCode::Tab));
type_text(&mut wizard, SECRET);
wizard
}
#[test]
fn welcome_screen() {
snapshot_all_widths("setup_welcome", &wizard(), 18);
}
#[test]
fn provider_screen() {
let mut wizard = wizard();
wizard.go(Page::Provider);
snapshot_all_widths("setup_provider", &wizard, 14);
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Endpoint);
}
#[test]
fn endpoint_form_masks_the_key() {
let mut wizard = endpoint_wizard();
snapshot_all_widths("setup_endpoint", &wizard, 16);
for width in [40u16, 60, 80, 120, 200] {
assert!(!render(&wizard, width, 16).contains(SECRET));
assert!(!render(&wizard, width, 16).contains("sk-akode"));
}
// Moving off the key field keeps it masked.
wizard.handle_key_event(key(KeyCode::Tab));
assert!(!render(&wizard, 80, 16).contains("sk-akode"));
}
#[test]
fn endpoint_form_validates_before_fetching_models() {
let mut wizard = wizard();
wizard.go(Page::Endpoint);
wizard.form_focus = 3;
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Endpoint);
assert_eq!(wizard.form_focus, 0);
type_text(&mut wizard, "x");
wizard.handle_key_event(key(KeyCode::Tab));
type_text(&mut wizard, "ftp://nope");
wizard.form_focus = 3;
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Endpoint);
assert!(
wizard
.form_error
.as_deref()
.is_some_and(|e| e.contains("http"))
);
insta::assert_snapshot!("setup_endpoint_error_80", render(&wizard, 80, 18));
}
#[test]
fn model_list_screen() {
let mut wizard = endpoint_wizard();
wizard.form_focus = 3;
wizard.handle_key_event(key(KeyCode::Enter));
// A key was entered: choose where to store it first.
assert_eq!(wizard.page, Page::KeyStore);
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Model);
assert!(wizard.pending.is_some());
insta::assert_snapshot!("setup_model_loading_80", render(&wizard, 80, 12));
wizard.apply(Outcome::Models(Ok(setup_net::ModelList {
base_url: "http://192.168.40.25:8080/v1".to_string(),
models: vec![
"qwen3.6-35b-a3b".to_string(),
"qwen3-coder-30b-a3b".to_string(),
"gemma-3-4b-it".to_string(),
],
free: Vec::new(),
..Default::default()
})));
snapshot_all_widths("setup_model_list", &wizard, 14);
// The last row switches to manual entry.
for _ in 0..3 {
wizard.handle_key_event(key(KeyCode::Down));
}
wizard.handle_key_event(key(KeyCode::Enter));
assert!(wizard.model_input_active());
type_text(&mut wizard, "my-model");
insta::assert_snapshot!("setup_model_manual_80", render(&wizard, 80, 12));
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Test);
assert_eq!(wizard.model, "my-model");
}
#[test]
fn model_list_failure_offers_manual_entry() {
let mut wizard = endpoint_wizard();
wizard.base_url = "http://192.168.40.25:8080/v1".to_string();
wizard.start_models();
wizard.apply(Outcome::Models(Err(
"Server non raggiungibile (http://192.168.40.25:8080/v1): connection refused".to_string(),
)));
assert!(wizard.is_text_entry_active());
insta::assert_snapshot!("setup_model_failed_80", render(&wizard, 80, 14));
}
#[test]
fn connection_test_screens() {
let mut wizard = endpoint_wizard();
wizard.base_url = "http://192.168.40.25:8080/v1".to_string();
wizard.start_test("qwen3.6-35b-a3b".to_string());
insta::assert_snapshot!("setup_test_running_80", render(&wizard, 80, 12));
wizard.apply(Outcome::Test(Ok(())));
snapshot_all_widths("setup_test_ok", &wizard, 12);
wizard.start_test("qwen3.6-35b-a3b".to_string());
wizard.apply(Outcome::Test(Err(setup_net::classify_responses_failure(
401,
"",
"qwen3.6-35b-a3b",
))));
snapshot_all_widths("setup_test_failed", &wizard, 14);
// "Torna indietro e correggi" returns to the form.
wizard.handle_key_event(key(KeyCode::Down));
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Endpoint);
}
#[test]
fn config_edits_keep_the_key_out_of_config() {
let mut wizard = endpoint_wizard();
wizard.base_url = "http://192.168.40.25:8080/v1".to_string();
wizard.model = "qwen3.6-35b-a3b".to_string();
let id = SetupWizard::provider_id_for("imeAI", &wizard.ctx.existing_provider_ids);
let edits = wizard.config_edits(&id, "imeAI", /*has_key*/ true);
let rendered = serde_json::to_string(
&edits
.iter()
.map(|edit| (edit.key_path.clone(), edit.value.clone()))
.collect::<Vec<_>>(),
)
.expect("json");
assert!(!rendered.contains(SECRET));
assert_eq!(
edits
.iter()
.map(|edit| (edit.key_path.as_str(), edit.value.clone()))
.collect::<Vec<_>>(),
vec![
(
"model_providers.imeai",
serde_json::json!({
"name": "imeAI",
"base_url": "http://192.168.40.25:8080/v1",
"wire_api": "responses",
"api_key": "keyring",
})
),
("model_provider", serde_json::json!("imeai")),
("model", serde_json::json!("qwen3.6-35b-a3b")),
]
);
}
#[test]
fn local_providers_write_no_provider_table() {
let mut wizard = wizard();
wizard.go(Page::Provider);
wizard.handle_key_event(key(KeyCode::Char('2')));
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Model);
assert_eq!(wizard.base_url, "http://localhost:11434/v1");
assert_eq!(wizard.api_key(), None);
wizard.model = "llama3".to_string();
let edits = wizard.config_edits("ollama", "Ollama locale", /*has_key*/ false);
assert!(
edits
.iter()
.all(|edit| !edit.key_path.starts_with("model_providers"))
);
}
#[test]
fn provider_ids_are_unique_slugs() {
let mut existing = BTreeSet::from(["ollama".to_string(), "imeai".to_string()]);
assert_eq!(SetupWizard::provider_id_for("imeAI", &existing), "imeai-2");
existing.insert("imeai-2".to_string());
assert_eq!(SetupWizard::provider_id_for("imeAI", &existing), "imeai-3");
assert_eq!(
SetupWizard::provider_id_for(" Server di Andrea (GPU)! ", &existing),
"server-di-andrea-gpu"
);
assert_eq!(SetupWizard::provider_id_for("Città", &existing), "citta");
assert_eq!(SetupWizard::provider_id_for("***", &existing), "endpoint");
assert_eq!(
SetupWizard::provider_id_for("OpenAI", &existing),
"openai-2"
);
}
#[test]
fn saving_failure_can_retry() {
let mut wizard = endpoint_wizard();
wizard.model = "qwen3.6-35b-a3b".to_string();
wizard.go(Page::Saving);
wizard.save =
CheckState::Failed("Impossibile scrivere config.toml: permesso negato".to_string());
insta::assert_snapshot!("setup_save_failed_80", render(&wizard, 80, 12));
assert!(!render(&wizard, 80, 12).contains(SECRET));
}
#[test]
fn long_model_list_filters_by_text_and_free_toggle() {
let mut wizard = endpoint_wizard();
wizard.base_url = "https://openrouter.ai/api/v1".to_string();
wizard.start_models();
let mut models: Vec<String> = (0..300).map(|i| format!("vendor/model-{i:03}")).collect();
models.push("qwen/qwen3-coder:free".to_string());
models.push("google/gemma-3-27b-it:free".to_string());
models.push("qwen/qwen3-coder".to_string());
wizard.apply(Outcome::Models(Ok(setup_net::ModelList {
base_url: "https://openrouter.ai/api/v1".to_string(),
models,
free: vec![
"qwen/qwen3-coder:free".to_string(),
"google/gemma-3-27b-it:free".to_string(),
],
..Default::default()
})));
assert!(
wizard.is_text_entry_active(),
"typed text goes to the filter"
);
snapshot_all_widths("setup_model_search_empty", &wizard, 20);
// `j`/`k` are text here, not navigation.
type_text(&mut wizard, "qwen");
snapshot_all_widths("setup_model_search_qwen", &wizard, 20);
wizard.handle_key_event(key(KeyCode::Tab));
snapshot_all_widths("setup_model_search_qwen_free", &wizard, 20);
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Test);
assert_eq!(wizard.model, "qwen/qwen3-coder:free");
// Esc clears the filter before leaving the page; Backspace edits it.
wizard.start_models();
wizard.apply(Outcome::Models(Ok(setup_net::ModelList {
base_url: "https://openrouter.ai/api/v1".to_string(),
models: (0..20).map(|i| format!("m-{i}")).collect(),
free: Vec::new(),
..Default::default()
})));
type_text(&mut wizard, "zz");
let rendered = render(&wizard, 80, 16);
assert!(
rendered.contains("Nessun modello corrisponde."),
"{rendered}"
);
assert!(
!rendered.contains("solo gratuiti"),
"no toggle without free models"
);
wizard.handle_key_event(key(KeyCode::Backspace));
wizard.handle_key_event(key(KeyCode::Esc));
assert_eq!(wizard.page, Page::Model);
let ModelsState::Loaded { filter, .. } = &wizard.models else {
panic!("models stay loaded");
};
assert!(filter.is_empty());
wizard.handle_key_event(key(KeyCode::Down));
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.model, "m-1");
}
/// The endpoint form with a key, confirmed: the key storage choice follows.
fn key_store_wizard(configure: impl FnOnce(&mut SetupContext)) -> SetupWizard {
let mut ctx = wizard().ctx.clone();
configure(&mut ctx);
let mut wizard = SetupWizard::new(FrameRequester::test_dummy(), ctx);
wizard.go(Page::Endpoint);
type_text(&mut wizard, "imeAI");
wizard.handle_key_event(key(KeyCode::Tab));
type_text(&mut wizard, "http://192.168.40.25:8080/v1");
wizard.handle_key_event(key(KeyCode::Tab));
type_text(&mut wizard, SECRET);
wizard.handle_key_event(key(KeyCode::Tab));
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::KeyStore);
wizard
}
fn key_store_edit(wizard: &SetupWizard) -> Option<serde_json::Value> {
let edits = wizard.config_edits("imeai", "imeAI", /*has_key*/ true);
let rendered = serde_json::to_string(
&edits
.iter()
.map(|edit| (edit.key_path.clone(), edit.value.clone()))
.collect::<Vec<_>>(),
)
.expect("json");
assert!(!rendered.contains(SECRET));
edits
.into_iter()
.find(|edit| edit.key_path == "provider_api_key_store")
.map(|edit| edit.value)
}
#[test]
fn key_store_choice_defaults_to_the_keyring() {
let mut wizard = key_store_wizard(|_| {});
snapshot_all_widths("setup_key_store", &wizard, 12);
assert!(!wizard.key_in_file);
assert_eq!(key_store_edit(&wizard), None);
wizard.handle_key_event(key(KeyCode::Down));
assert!(wizard.key_in_file);
snapshot_all_widths("setup_key_store_file", &wizard, 14);
assert_eq!(key_store_edit(&wizard), Some(serde_json::json!("file")));
for width in [40u16, 60, 80, 120] {
assert!(!render(&wizard, width, 14).contains("sk-akode"));
}
wizard.handle_key_event(key(KeyCode::Esc));
assert_eq!(wizard.page, Page::Endpoint);
}
#[test]
fn key_store_choice_preselects_the_configured_file() {
let mut wizard = key_store_wizard(|ctx| ctx.key_store_mode = AuthCredentialsStoreMode::File);
assert!(wizard.key_in_file);
assert_eq!(key_store_edit(&wizard), None);
wizard.handle_key_event(key(KeyCode::Char('1')));
assert!(!wizard.key_in_file);
assert_eq!(key_store_edit(&wizard), Some(serde_json::json!("auto")));
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Model);
}
#[test]
fn key_store_choice_offers_only_the_file_without_a_keyring() {
let mut wizard = key_store_wizard(|ctx| ctx.keyring_available = false);
assert!(wizard.key_in_file);
wizard.handle_key_event(key(KeyCode::Up));
assert!(wizard.key_in_file);
snapshot_all_widths("setup_key_store_no_keyring", &wizard, 14);
assert_eq!(key_store_edit(&wizard), Some(serde_json::json!("file")));
}
#[test]
fn endpoint_without_a_key_skips_the_storage_choice() {
let mut wizard = wizard();
wizard.go(Page::Endpoint);
type_text(&mut wizard, "imeAI");
wizard.handle_key_event(key(KeyCode::Tab));
type_text(&mut wizard, "http://192.168.40.25:8080/v1");
wizard.form_focus = 3;
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Model);
}
#[test]
fn endpoint_mode_edits_keep_the_key_out_of_config() {
let mut ctx = SetupContext {
key_store_mode: AuthCredentialsStoreMode::Auto,
keyring_available: true,
endpoint_mode: Some(EndpointMode {
edit: Some(EndpointEdit {
provider_id: "giulio".to_string(),
name: "Giulio".to_string(),
base_url: "https://mega-link.cloud/v1".to_string(),
stored_key: Some(SECRET.to_string()),
}),
}),
..Default::default()
};
ctx.existing_provider_ids.insert("giulio".to_string());
let mut wizard = SetupWizard::new(FrameRequester::test_dummy(), ctx);
assert_eq!(wizard.page, Page::Endpoint);
assert!(!render(&wizard, 80, 14).contains(SECRET));
wizard.handle_key_event(key(KeyCode::Down));
wizard.handle_key_event(key(KeyCode::Down));
type_text(&mut wizard, SECRET);
wizard.base_url = "https://mega-link.cloud/v1".to_string();
let edits = wizard.endpoint_config_edits("giulio", "Giulio", true);
let json = serde_json::to_string(
&edits
.iter()
.map(|e| (&e.key_path, &e.value))
.collect::<Vec<_>>(),
)
.expect("serialize");
assert!(!json.contains(SECRET));
assert!(json.contains("model_providers.giulio.api_key"));
assert!(!json.contains("model_providers.giulio.models"));
assert!(!json.contains("\"model\""));
assert!(!render(&wizard, 80, 14).contains(SECRET));
}

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Endpoint personalizzato passo 2 di 4
Chiave facoltativa: non finisce mai in config.toml.
Nome imeAI
URL http://192.168.40.25:8080/v1
› Chiave API •••••••••••••••••••••••••••••••
[ Avanti ]
tab/↑/↓ campo · invio avanti · esc indietro

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Endpoint personalizzato passo 2 di 4
Chiave facoltativa: non finisce mai in config.toml.
Nome imeAI
URL http://192.168.40.25:8080/v1
› Chiave API •••••••••••••••••••••••••••••••
[ Avanti ]
tab/↑/↓ campo · invio avanti · esc indietro

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Endpoint personalizzato passo 2 di 4
Chiave facoltativa: non finisce mai in config.toml.
Nome imeAI
URL http://192.168.40.25:8080/v1
› Chiave API •••••••••••••••••••••••••••••••
[ Avanti ]
tab/↑/↓ campo · invio avanti · esc indietro

View File

@@ -0,0 +1,18 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: "render(&wizard, 80, 18)"
---
Endpoint personalizzato passo 2 di 4
Chiave facoltativa: non finisce mai in config.toml.
Nome x
› URL ftp://nope
Chiave API facoltativa
[ Avanti ]
L'URL deve iniziare con http:// o https://
tab/↑/↓ campo · invio avanti · esc indietro

View File

@@ -0,0 +1,13 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Dove salvo la chiave? passo 2 di 4
La chiave API non finisce mai in config.toml.
› 1. Portachiavi del sistema (consigliato)
2. File protetto (solo il tuo utente, permessi 600)
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,13 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Dove salvo la chiave? passo 2 di 4
La chiave API non finisce mai in config.toml.
› 1. Portachiavi del sistema (consigliato)
2. File protetto (solo il tuo utente, perm…
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,13 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Dove salvo la chiave? passo 2 di 4
La chiave API non finisce mai in config.toml.
› 1. Portachiavi del sistema (consigliato)
2. File protetto (solo il tuo utente, permessi 600)
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Dove salvo la chiave? passo 2 di 4
La chiave API non finisce mai in config.toml.
1. Portachiavi del sistema (consigliato)
› 2. File protetto (solo il tuo utente, permessi 600)
Vale per tutti i provider: le altre chiavi si spostano.
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Dove salvo la chiave? passo 2 di 4
La chiave API non finisce mai in config.toml.
1. Portachiavi del sistema (consigliato)
› 2. File protetto (solo il tuo utente, perm…
Vale per tutti i provider: le altre chiavi si spostano.
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Dove salvo la chiave? passo 2 di 4
La chiave API non finisce mai in config.toml.
1. Portachiavi del sistema (consigliato)
› 2. File protetto (solo il tuo utente, permessi 600)
Vale per tutti i provider: le altre chiavi si spostano.
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,14 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Dove salvo la chiave? passo 2 di 4
Portachiavi del sistema non disponibile: uso il file.
› 1. File protetto (solo il tuo utente, permessi 600)
Vale per tutti i provider: le altre chiavi si spostano.
invio conferma · esc indietro

View File

@@ -0,0 +1,14 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Dove salvo la chiave? passo 2 di 4
Portachiavi del sistema non disponibile: uso il file.
› 1. File protetto (solo il tuo utente, perm…
Vale per tutti i provider: le altre chiavi si spostano.
invio conferma · esc indietro

View File

@@ -0,0 +1,14 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Dove salvo la chiave? passo 2 di 4
Portachiavi del sistema non disponibile: uso il file.
› 1. File protetto (solo il tuo utente, permessi 600)
Vale per tutti i provider: le altre chiavi si spostano.
invio conferma · esc indietro

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: "render(&wizard, 80, 14)"
---
Modello passo 3 di 4
Server: http://192.168.40.25:8080/v1
Elenco dei modelli non disponibile: Server non raggiungibile
(http://192.168.40.25:8080/v1): connection refused
› Modello nome del modello
invio conferma · esc indietro

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: http://192.168.40.25:8080/v1
› 1. qwen3.6-35b-a3b
2. qwen3-coder-30b-a3b
3. gemma-3-4b-it
4. Inserisci il nome a mano…
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: http://192.168.40.25:8080/v1
› 1. qwen3.6-35b-a3b
2. qwen3-coder-30b-a3b
3. gemma-3-4b-it
4. Inserisci il nome a mano…
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: http://192.168.40.25:8080/v1
› 1. qwen3.6-35b-a3b
2. qwen3-coder-30b-a3b
3. gemma-3-4b-it
4. Inserisci il nome a mano…
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: "render(&wizard, 80, 12)"
---
Modello passo 3 di 4
Server: http://192.168.40.25:8080/v1
Lettura dell'elenco dei modelli…
esc indietro

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: "render(&wizard, 80, 12)"
---
Modello passo 3 di 4
Server: http://192.168.40.25:8080/v1
› Modello my-model
invio conferma · esc indietro

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: https://openrouter.ai/api/v1
Cerca: ▏ [ ] solo gratuiti (tab)
› 1. vendor/model-000
2. vendor/model-001
3. vendor/model-002
4. vendor/model-003
5. vendor/model-004
6. vendor/model-005
7. vendor/model-006
8. vendor/model-007
1 di 304
↑/↓ scegli · tab gratuiti · invio conferma · esc indietro

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: https://openrouter.ai/api/v1
Cerca: ▏ [ ] solo gratuiti (tab)
› 1. vendor/model-000
2. vendor/model-001
3. vendor/model-002
4. vendor/model-003
5. vendor/model-004
6. vendor/model-005
7. vendor/model-006
8. vendor/model-007
1 di 304
↑/↓ scegli · tab gratuiti · invio conferma · esc indiet…

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: https://openrouter.ai/api/v1
Cerca: ▏ [ ] solo gratuiti (tab)
› 1. vendor/model-000
2. vendor/model-001
3. vendor/model-002
4. vendor/model-003
5. vendor/model-004
6. vendor/model-005
7. vendor/model-006
8. vendor/model-007
1 di 304
↑/↓ scegli · tab gratuiti · invio conferma · esc indietro

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: https://openrouter.ai/api/v1
Cerca: qwen▏ [ ] solo gratuiti (tab)
› 1. qwen/qwen3-coder:free
2. qwen/qwen3-coder
3. Inserisci il nome a mano…
1 di 3 · 2 modelli su 303
↑/↓ scegli · tab gratuiti · invio conferma · esc pulisci

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: https://openrouter.ai/api/v1
Cerca: qwen▏ [ ] solo gratuiti (tab)
› 1. qwen/qwen3-coder:free
2. qwen/qwen3-coder
3. Inserisci il nome a mano…
1 di 3 · 2 modelli su 303
↑/↓ scegli · tab gratuiti · invio conferma · esc pulisci

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: https://openrouter.ai/api/v1
Cerca: qwen▏ [ ] solo gratuiti (tab)
› 1. qwen/qwen3-coder:free
2. qwen/qwen3-coder
3. Inserisci il nome a mano…
1 di 3 · 2 modelli su 303
↑/↓ scegli · tab gratuiti · invio conferma · esc pulisci

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: https://openrouter.ai/api/v1
Cerca: qwen▏ [x] solo gratuiti (tab)
› 1. qwen/qwen3-coder:free
2. Inserisci il nome a mano…
1 di 2 · 1 modello su 303
↑/↓ scegli · tab gratuiti · invio conferma · esc pulisci

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: https://openrouter.ai/api/v1
Cerca: qwen▏ [x] solo gratuiti (tab)
› 1. qwen/qwen3-coder:free
2. Inserisci il nome a mano…
1 di 2 · 1 modello su 303
↑/↓ scegli · tab gratuiti · invio conferma · esc pulisci

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Modello passo 3 di 4
Server: https://openrouter.ai/api/v1
Cerca: qwen▏ [x] solo gratuiti (tab)
› 1. qwen/qwen3-coder:free
2. Inserisci il nome a mano…
1 di 2 · 1 modello su 303
↑/↓ scegli · tab gratuiti · invio conferma · esc pulisci

View File

@@ -0,0 +1,14 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Provider del modello passo 1 di 4
Scegli dove gira il modello. Potrai aggiungere altri provider con /setup.
› 1. Endpoint personalizzato server compatibile OpenAI con Responses API
2. Ollama locale localhost:11434
3. LM Studio locale localhost:1234
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Provider del modello passo 1 di 4
Scegli dove gira il modello. Potrai aggiungere altri
provider con /setup.
› 1. Endpoint personalizzato server compatibile OpenAI…
2. Ollama locale localhost:11434
3. LM Studio locale localhost:1234
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,14 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Provider del modello passo 1 di 4
Scegli dove gira il modello. Potrai aggiungere altri provider con /setup.
› 1. Endpoint personalizzato server compatibile OpenAI con Responses API
2. Ollama locale localhost:11434
3. LM Studio locale localhost:1234
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,13 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: "render(&wizard, 80, 12)"
---
Salvataggio
Impossibile scrivere config.toml: permesso negato
› 1. Riprova
2. Indietro
↑/↓ scegli · invio conferma

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Prova della connessione passo 4 di 4
Server: http://192.168.40.25:8080/v1
Modello: qwen3.6-35b-a3b
✗ Chiave API rifiutata (HTTP 401): controlla la chiave.
› 1. Riprova
2. Torna indietro e correggi
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Prova della connessione passo 4 di 4
Server: http://192.168.40.25:8080/v1
Modello: qwen3.6-35b-a3b
✗ Chiave API rifiutata (HTTP 401): controlla la chiave.
› 1. Riprova
2. Torna indietro e correggi
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Prova della connessione passo 4 di 4
Server: http://192.168.40.25:8080/v1
Modello: qwen3.6-35b-a3b
✗ Chiave API rifiutata (HTTP 401): controlla la chiave.
› 1. Riprova
2. Torna indietro e correggi
↑/↓ scegli · invio conferma · esc indietro

View File

@@ -0,0 +1,13 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Prova della connessione passo 4 di 4
Server: http://192.168.40.25:8080/v1
Modello: qwen3.6-35b-a3b
✓ Connessione riuscita (Responses API).
invio continua · esc indietro

View File

@@ -0,0 +1,13 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Prova della connessione passo 4 di 4
Server: http://192.168.40.25:8080/v1
Modello: qwen3.6-35b-a3b
✓ Connessione riuscita (Responses API).
invio continua · esc indietro

View File

@@ -0,0 +1,13 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
Prova della connessione passo 4 di 4
Server: http://192.168.40.25:8080/v1
Modello: qwen3.6-35b-a3b
✓ Connessione riuscita (Responses API).
invio continua · esc indietro

View File

@@ -0,0 +1,13 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: "render(&wizard, 80, 12)"
---
Prova della connessione passo 4 di 4
Server: http://192.168.40.25:8080/v1
Modello: qwen3.6-35b-a3b
Invio di una richiesta minima a /responses…
esc annulla

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
█████╗ ██╗ ██╗ ██████╗ ██████╗ ███████╗
▄▄████▄▄ ██╔══██╗██║ ██╔╝██╔═══██╗██╔══██╗██╔════╝
██▀▀██▀▀██ ███████║█████╔╝ ██║ ██║██║ ██║█████╗
██▄▄██▄▄██ ██╔══██║██╔═██╗ ██║ ██║██║ ██║██╔══╝
██▀████▀██ ██║ ██║██║ ██╗╚██████╔╝██████╔╝███████╗
╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝
Benvenuto in aKode · il tuo agente di coding locale
Configuriamo il server del modello: indirizzo, chiave e modello.
invio inizia · ctrl+c esci

View File

@@ -0,0 +1,18 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
█████╗ ██╗ ██╗ ██████╗ ██████╗ ███████╗
▄▄████▄▄ ██╔══██╗██║ ██╔╝██╔═══██╗██╔══██╗██╔════╝
██▀▀██▀▀██ ███████║█████╔╝ ██║ ██║██║ ██║█████╗
██▄▄██▄▄██ ██╔══██║██╔═██╗ ██║ ██║██║ ██║██╔══╝
██▀████▀██ ██║ ██║██║ ██╗╚██████╔╝██████╔╝███████╗
╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝
Benvenuto in aKode · il tuo agente di coding locale
Configuriamo il server del modello: indirizzo, chiave
e modello.
invio inizia · ctrl+c esci

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/setup_wizard_tests.rs
expression: rendered
---
█████╗ ██╗ ██╗ ██████╗ ██████╗ ███████╗
▄▄████▄▄ ██╔══██╗██║ ██╔╝██╔═══██╗██╔══██╗██╔════╝
██▀▀██▀▀██ ███████║█████╔╝ ██║ ██║██║ ██║█████╗
██▄▄██▄▄██ ██╔══██║██╔═██╗ ██║ ██║██║ ██║██╔══╝
██▀████▀██ ██║ ██║██║ ██╗╚██████╔╝██████╔╝███████╗
╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝
Benvenuto in aKode · il tuo agente di coding locale
Configuriamo il server del modello: indirizzo, chiave e modello.
invio inizia · ctrl+c esci

Some files were not shown because too many files have changed in this diff Show More