WIP v0.2.0: pannello /endpoint e nomi abbreviati dei modelli (in pausa, non compilato)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3394,6 +3394,9 @@ impl App {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -1641,6 +1641,9 @@ 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,
|
||||
|
||||
@@ -553,6 +553,7 @@ fn parent_owned_command_is_allowed(command: SlashCommand, args: &str) -> bool {
|
||||
| SlashCommand::DebugConfig
|
||||
| SlashCommand::Theme
|
||||
| SlashCommand::Setup
|
||||
| SlashCommand::Endpoint
|
||||
| SlashCommand::Pets
|
||||
| SlashCommand::Ps
|
||||
| SlashCommand::Stop
|
||||
|
||||
@@ -35,7 +35,8 @@ impl ChatWidget {
|
||||
| SlashCommand::Title
|
||||
| SlashCommand::Statusline
|
||||
| SlashCommand::Theme
|
||||
| SlashCommand::Setup,
|
||||
| SlashCommand::Setup
|
||||
| SlashCommand::Endpoint,
|
||||
) => false,
|
||||
InputResult::Command(_)
|
||||
| InputResult::ServiceTierCommand(_)
|
||||
|
||||
@@ -65,7 +65,7 @@ impl ChatWidget {
|
||||
let current_label = presets
|
||||
.iter()
|
||||
.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());
|
||||
|
||||
let (mut auto_presets, other_presets): (Vec<ModelPreset>, Vec<ModelPreset>) = presets
|
||||
@@ -115,7 +115,7 @@ impl ChatWidget {
|
||||
)
|
||||
};
|
||||
SelectionItem {
|
||||
name: preset.display_name.clone(),
|
||||
name: self.model_catalog.display_name(&preset.model),
|
||||
description,
|
||||
is_current: model.as_str() == current_model,
|
||||
secondary_action: if requires_advanced_selection {
|
||||
@@ -231,7 +231,7 @@ impl ChatWidget {
|
||||
}));
|
||||
})];
|
||||
items.push(SelectionItem {
|
||||
name: preset.display_name.clone(),
|
||||
name: self.model_catalog.display_name(&preset.model),
|
||||
description,
|
||||
is_current,
|
||||
secondary_action: direct_effort.and_then(|effort| {
|
||||
@@ -329,7 +329,7 @@ impl ChatWidget {
|
||||
.map(|model| {
|
||||
let provider_id = provider_id.clone();
|
||||
SelectionItem {
|
||||
name: model.clone(),
|
||||
name: crate::model_display::display_name(&model),
|
||||
dismiss_on_select: true,
|
||||
actions: vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::SwitchProvider {
|
||||
@@ -600,7 +600,7 @@ impl ChatWidget {
|
||||
.then(|| default_effort.clone());
|
||||
|
||||
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 highlight_choice = if is_current_model {
|
||||
if in_plan_mode {
|
||||
|
||||
@@ -377,7 +377,7 @@ impl ChatWidget {
|
||||
/// Consolidating both refreshes here prevents the bug where callers update the
|
||||
/// header/title (`refresh_model_display`) but forget the footer 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_status_line();
|
||||
self.refresh_open_model_picker();
|
||||
@@ -493,10 +493,10 @@ impl ChatWidget {
|
||||
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();
|
||||
if model.is_empty() {
|
||||
DEFAULT_MODEL_DISPLAY_NAME
|
||||
DEFAULT_MODEL_DISPLAY_NAME.to_string()
|
||||
} else {
|
||||
self.model_catalog.display_name(model)
|
||||
}
|
||||
|
||||
@@ -547,6 +547,9 @@ impl ChatWidget {
|
||||
SlashCommand::Setup => {
|
||||
self.app_event_tx.send(AppEvent::OpenSetup);
|
||||
}
|
||||
SlashCommand::Endpoint => {
|
||||
self.app_event_tx.send(AppEvent::OpenEndpointPanel);
|
||||
}
|
||||
SlashCommand::Pets => {
|
||||
self.open_pets_picker();
|
||||
}
|
||||
@@ -1293,6 +1296,7 @@ impl ChatWidget {
|
||||
| SlashCommand::Config
|
||||
| SlashCommand::Theme
|
||||
| SlashCommand::Setup
|
||||
| SlashCommand::Endpoint
|
||||
| SlashCommand::Tui
|
||||
| SlashCommand::Pets => QueueDrain::Stop,
|
||||
}
|
||||
|
||||
@@ -373,7 +373,8 @@ impl HistoryCell for SessionHeaderHistoryCell {
|
||||
if !show_avatar {
|
||||
title.insert(0, ">_ ".fg(accent_color()));
|
||||
}
|
||||
let mut model: Vec<Span<'static>> = vec![self.model.clone().into()];
|
||||
let mut model: Vec<Span<'static>> =
|
||||
vec![crate::model_display::display_name(&self.model).into()];
|
||||
if let Some(provider) = &self.provider_name {
|
||||
model.push(" · ".dim());
|
||||
model.push(provider.clone().dim());
|
||||
@@ -418,7 +419,7 @@ impl HistoryCell for SessionHeaderHistoryCell {
|
||||
Line::from(format!("{} v{}", branding::PRODUCT_NAME, self.version)),
|
||||
Line::from(format!(
|
||||
"model: {}{}",
|
||||
self.model,
|
||||
crate::model_display::display_name(&self.model),
|
||||
self.reasoning_label()
|
||||
.map(|reasoning| format!(" {reasoning}"))
|
||||
.unwrap_or_default()
|
||||
|
||||
@@ -171,6 +171,8 @@ mod markdown_stream;
|
||||
mod markdown_text_merge;
|
||||
mod mention_codec;
|
||||
mod model_catalog;
|
||||
mod model_display;
|
||||
mod endpoint_panel;
|
||||
mod model_migration;
|
||||
mod motion;
|
||||
mod multi_agents;
|
||||
@@ -2056,6 +2058,7 @@ async fn run_ratatui_app(
|
||||
let local_settings = crate::local_settings::LocalSettings::for_tui(&config, &tui);
|
||||
crate::markdown_render::preferences::init(local_settings.tui.rendering);
|
||||
ui_theme::apply_configured_palette(local_settings.tui.ui_theme.as_deref());
|
||||
crate::model_display::set_display_names_from_config(&config);
|
||||
// Configure syntax highlighting theme from the final config — onboarding
|
||||
// and resume/fork can both reload config with a different tui_theme, so
|
||||
// this must happen after the last possible reload.
|
||||
|
||||
@@ -66,11 +66,17 @@ impl ModelCatalog {
|
||||
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
|
||||
.iter()
|
||||
.find(|preset| preset.model == model)
|
||||
.map(|preset| preset.display_name.as_str())
|
||||
.unwrap_or_else(|| model_display_name(model))
|
||||
.find(|preset| preset.model == model && preset.display_name != model)
|
||||
.map(|preset| preset.display_name.clone())
|
||||
.unwrap_or_else(|| model_display_name(model).to_string())
|
||||
}
|
||||
}
|
||||
|
||||
99
akode-rs/tui/src/model_display.rs
Normal file
99
akode-rs/tui/src/model_display.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
//! 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");
|
||||
}
|
||||
}
|
||||
@@ -742,6 +742,12 @@ pub(crate) fn setup_context(
|
||||
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(),
|
||||
searx_url: config
|
||||
.web_search_backend
|
||||
.as_ref()
|
||||
.map(|backend| backend.url.clone())
|
||||
.filter(|url| !url.trim().is_empty()),
|
||||
endpoint_mode: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! 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;
|
||||
@@ -83,6 +84,59 @@ pub(crate) fn parse_model_ids(body: &Value) -> Vec<String> {
|
||||
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> {
|
||||
@@ -117,12 +171,16 @@ fn connection_error(url: &str, err: &impl std::fmt::Display, api_key: Option<&st
|
||||
}
|
||||
|
||||
/// Result of listing models: the base URL that answered (a `/v1` suffix may have been added).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[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.
|
||||
@@ -183,11 +241,37 @@ pub(crate) async fn fetch_models(
|
||||
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();
|
||||
|
||||
@@ -57,7 +57,7 @@ const MANUAL_MODEL_LABEL: &str = "Inserisci il nome a mano…";
|
||||
|
||||
/// Models shown for the current filter: case-insensitive substring match on the id, and
|
||||
/// only the free ones when `free_only` is set.
|
||||
fn visible_models<'a>(
|
||||
pub(crate) fn visible_models<'a>(
|
||||
models: &'a [String],
|
||||
free: &[String],
|
||||
filter: &str,
|
||||
@@ -187,6 +187,26 @@ enum Outcome {
|
||||
Test(Result<(), String>),
|
||||
Searx(Result<String, String>),
|
||||
Saved(Result<(), String>),
|
||||
/// Endpoint-only mode: connection check through the model list.
|
||||
Check(Result<setup_net::ModelList, String>),
|
||||
}
|
||||
|
||||
/// The endpoint form alone (from `/endpoint`): add a provider or edit one, without
|
||||
/// touching the active provider, the model, the theme or web search.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct EndpointMode {
|
||||
/// Endpoint being edited; `None` adds a new one.
|
||||
pub edit: Option<EndpointEdit>,
|
||||
}
|
||||
|
||||
/// An endpoint opened for editing. `stored_key` is only used for the connection check
|
||||
/// and is never shown: an empty key field keeps it.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct EndpointEdit {
|
||||
pub provider_id: String,
|
||||
pub name: String,
|
||||
pub base_url: String,
|
||||
pub stored_key: Option<String>,
|
||||
}
|
||||
|
||||
/// What the setup wrote, for the caller to switch to the new provider.
|
||||
@@ -213,6 +233,10 @@ pub(crate) struct SetupContext {
|
||||
pub key_store_mode: AuthCredentialsStoreMode,
|
||||
/// Whether the system keyring answers; without it only the file is offered.
|
||||
pub keyring_available: bool,
|
||||
/// SearXNG URL already configured in `[web_search]`, offered as «Mantieni».
|
||||
pub searx_url: Option<String>,
|
||||
/// Run only the endpoint form (see [`EndpointMode`]).
|
||||
pub endpoint_mode: Option<EndpointMode>,
|
||||
}
|
||||
|
||||
pub(crate) struct SetupWizard {
|
||||
@@ -243,6 +267,8 @@ pub(crate) struct SetupWizard {
|
||||
searx_verified: Option<String>,
|
||||
save: CheckState,
|
||||
save_choice: usize,
|
||||
/// Models listed by the endpoint-only connection check.
|
||||
checked_models: usize,
|
||||
pending: Option<LocalBoxFuture<'static, Outcome>>,
|
||||
finished: bool,
|
||||
cancelled: bool,
|
||||
@@ -260,15 +286,32 @@ impl SetupWizard {
|
||||
.unwrap_or(0);
|
||||
let key_in_file =
|
||||
ctx.key_store_mode == AuthCredentialsStoreMode::File || !ctx.keyring_available;
|
||||
let edit = ctx
|
||||
.endpoint_mode
|
||||
.as_ref()
|
||||
.and_then(|mode| mode.edit.clone());
|
||||
let page = if ctx.endpoint_mode.is_some() {
|
||||
Page::Endpoint
|
||||
} else {
|
||||
Page::Welcome
|
||||
};
|
||||
let searx_url = ctx.searx_url.as_deref().map(ProviderInput::from).unwrap_or_default();
|
||||
let searx_focus = usize::from(ctx.searx_url.is_some());
|
||||
Self {
|
||||
request_frame,
|
||||
ctx,
|
||||
page: Page::Welcome,
|
||||
page,
|
||||
original_palette,
|
||||
palette_idx,
|
||||
provider_idx: 0,
|
||||
name: ProviderInput::default(),
|
||||
url: ProviderInput::default(),
|
||||
name: edit
|
||||
.as_ref()
|
||||
.map(|edit| ProviderInput::from(edit.name.as_str()))
|
||||
.unwrap_or_default(),
|
||||
url: edit
|
||||
.as_ref()
|
||||
.map(|edit| ProviderInput::from(edit.base_url.as_str()))
|
||||
.unwrap_or_default(),
|
||||
key: ProviderInput::default(),
|
||||
key_in_file,
|
||||
form_focus: 0,
|
||||
@@ -280,12 +323,13 @@ impl SetupWizard {
|
||||
model: String::new(),
|
||||
test: CheckState::Idle,
|
||||
test_choice: 0,
|
||||
searx_url: ProviderInput::default(),
|
||||
searx_focus: 0,
|
||||
searx_url,
|
||||
searx_focus,
|
||||
searx: CheckState::Idle,
|
||||
searx_verified: None,
|
||||
save: CheckState::Idle,
|
||||
save_choice: 0,
|
||||
checked_models: 0,
|
||||
pending: None,
|
||||
finished: false,
|
||||
cancelled: false,
|
||||
@@ -297,6 +341,21 @@ impl SetupWizard {
|
||||
self.outcome.as_ref()
|
||||
}
|
||||
|
||||
/// After an endpoint-only save: provider id, name, base URL and the key typed (if any).
|
||||
/// The key is only handed back for the panel's own requests and is never shown.
|
||||
pub(crate) fn endpoint_saved(&self) -> Option<(String, String, String, Option<String>)> {
|
||||
if !self.finished || !self.endpoint_mode() {
|
||||
return None;
|
||||
}
|
||||
let outcome = self.outcome.as_ref()?;
|
||||
Some((
|
||||
outcome.provider_id.clone(),
|
||||
self.name.value().unwrap_or_default(),
|
||||
self.base_url.clone(),
|
||||
self.api_key(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn is_cancelled(&self) -> bool {
|
||||
self.cancelled
|
||||
}
|
||||
@@ -308,6 +367,27 @@ impl SetupWizard {
|
||||
self.cancelled = true;
|
||||
}
|
||||
|
||||
fn endpoint_mode(&self) -> bool {
|
||||
self.ctx.endpoint_mode.is_some()
|
||||
}
|
||||
|
||||
fn endpoint_edit(&self) -> Option<&EndpointEdit> {
|
||||
self.ctx
|
||||
.endpoint_mode
|
||||
.as_ref()
|
||||
.and_then(|mode| mode.edit.as_ref())
|
||||
}
|
||||
|
||||
/// The configured SearXNG URL is still in the field: «Mantieni» keeps it as is.
|
||||
fn searx_keep_available(&self) -> bool {
|
||||
self.searx_verified.is_none()
|
||||
&& self
|
||||
.ctx
|
||||
.searx_url
|
||||
.as_deref()
|
||||
.is_some_and(|url| self.searx_url.value().as_deref() == Some(url))
|
||||
}
|
||||
|
||||
fn palette(&self) -> UiPalette {
|
||||
ALL_PALETTES[self.palette_idx]
|
||||
}
|
||||
@@ -382,6 +462,17 @@ impl SetupWizard {
|
||||
}
|
||||
Err(error) => self.searx = CheckState::Failed(error),
|
||||
},
|
||||
Outcome::Check(result) if self.page == Page::Test => {
|
||||
self.test = match result {
|
||||
Ok(list) => {
|
||||
self.base_url = list.base_url;
|
||||
self.checked_models = list.models.len();
|
||||
CheckState::Ok
|
||||
}
|
||||
Err(error) => CheckState::Failed(error),
|
||||
};
|
||||
self.test_choice = 0;
|
||||
}
|
||||
Outcome::Saved(result) if self.page == Page::Saving => match result {
|
||||
Ok(()) => self.finished = true,
|
||||
Err(error) => {
|
||||
@@ -417,6 +508,54 @@ impl SetupWizard {
|
||||
}));
|
||||
}
|
||||
|
||||
/// Endpoint-only mode: check the connection by listing the models.
|
||||
fn start_endpoint_check(&mut self) {
|
||||
self.go(Page::Test);
|
||||
self.test = CheckState::Running;
|
||||
let base = self.base_url.clone();
|
||||
let key = self
|
||||
.api_key()
|
||||
.or_else(|| self.endpoint_edit().and_then(|edit| edit.stored_key.clone()));
|
||||
self.pending = Some(Box::pin(async move {
|
||||
Outcome::Check(setup_net::fetch_models(base, key).await)
|
||||
}));
|
||||
}
|
||||
|
||||
/// Config edits for an endpoint added or edited from `/endpoint`: only the provider's
|
||||
/// own keys, so its per-model settings and the active provider stay untouched.
|
||||
pub(crate) fn endpoint_config_edits(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
name: &str,
|
||||
new_key: bool,
|
||||
) -> Vec<ConfigEdit> {
|
||||
let prefix = format!("model_providers.{provider_id}");
|
||||
let mut edits = vec![
|
||||
replace_config_value(format!("{prefix}.name"), serde_json::json!(name)),
|
||||
replace_config_value(format!("{prefix}.base_url"), serde_json::json!(self.base_url)),
|
||||
];
|
||||
if self.endpoint_edit().is_none() {
|
||||
edits.push(replace_config_value(
|
||||
format!("{prefix}.wire_api"),
|
||||
serde_json::json!("responses"),
|
||||
));
|
||||
}
|
||||
if new_key {
|
||||
edits.push(replace_config_value(
|
||||
format!("{prefix}.api_key"),
|
||||
serde_json::json!("keyring"),
|
||||
));
|
||||
let key_store_mode = self.key_store_mode();
|
||||
if key_store_mode != self.ctx.key_store_mode {
|
||||
edits.push(replace_config_value(
|
||||
"provider_api_key_store",
|
||||
serde_json::json!(key_store_mode),
|
||||
));
|
||||
}
|
||||
}
|
||||
edits
|
||||
}
|
||||
|
||||
fn start_test(&mut self, model: String) {
|
||||
self.model = model;
|
||||
self.go(Page::Test);
|
||||
@@ -535,6 +674,17 @@ impl SetupWizard {
|
||||
fn start_save(&mut self) {
|
||||
self.go(Page::Saving);
|
||||
self.save = CheckState::Running;
|
||||
if self.endpoint_mode() {
|
||||
let name = self.name.value().unwrap_or_default();
|
||||
let provider_id = match self.endpoint_edit() {
|
||||
Some(edit) => edit.provider_id.clone(),
|
||||
None => Self::provider_id_for(&name, &self.ctx.existing_provider_ids),
|
||||
};
|
||||
let key = self.api_key();
|
||||
let edits = self.endpoint_config_edits(&provider_id, &name, key.is_some());
|
||||
self.queue_save(provider_id, String::new(), key, edits);
|
||||
return;
|
||||
}
|
||||
let (provider_id, name) = match self.provider().builtin_id() {
|
||||
Some(id) => (id.to_string(), self.provider().label().to_string()),
|
||||
None => {
|
||||
@@ -547,6 +697,17 @@ impl SetupWizard {
|
||||
};
|
||||
let key = self.api_key();
|
||||
let edits = self.config_edits(&provider_id, &name, key.is_some());
|
||||
let model = self.model.clone();
|
||||
self.queue_save(provider_id, model, key, edits);
|
||||
}
|
||||
|
||||
fn queue_save(
|
||||
&mut self,
|
||||
provider_id: String,
|
||||
model: String,
|
||||
key: Option<String>,
|
||||
edits: Vec<ConfigEdit>,
|
||||
) {
|
||||
let handle = self.ctx.request_handle.clone();
|
||||
let store = KeyStoreTarget {
|
||||
codex_home: self.ctx.codex_home.clone(),
|
||||
@@ -555,7 +716,7 @@ impl SetupWizard {
|
||||
};
|
||||
self.outcome = Some(SetupOutcome {
|
||||
provider_id: provider_id.clone(),
|
||||
model: self.model.clone(),
|
||||
model,
|
||||
palette: self.palette(),
|
||||
});
|
||||
self.pending = Some(Box::pin(async move {
|
||||
@@ -577,6 +738,8 @@ impl SetupWizard {
|
||||
self.base_url = url;
|
||||
if self.key.value().is_some() {
|
||||
self.go(Page::KeyStore);
|
||||
} else if self.endpoint_mode() {
|
||||
self.start_endpoint_check();
|
||||
} else {
|
||||
self.start_models();
|
||||
}
|
||||
@@ -658,6 +821,7 @@ impl SetupWizard {
|
||||
return;
|
||||
}
|
||||
match key.code {
|
||||
KeyCode::Esc if self.endpoint_mode() => self.cancel(),
|
||||
KeyCode::Esc => self.go(Page::Provider),
|
||||
KeyCode::Enter if self.form_focus < 2 => self.form_focus += 1,
|
||||
KeyCode::Enter => self.confirm_form(),
|
||||
@@ -679,6 +843,7 @@ impl SetupWizard {
|
||||
}
|
||||
}
|
||||
match key.code {
|
||||
KeyCode::Enter if self.endpoint_mode() => self.start_endpoint_check(),
|
||||
KeyCode::Enter => self.start_models(),
|
||||
KeyCode::Esc => self.go(Page::Endpoint),
|
||||
_ => {}
|
||||
@@ -801,14 +966,18 @@ impl SetupWizard {
|
||||
|
||||
fn handle_test_key(&mut self, key: KeyEvent) {
|
||||
match (&self.test, key.code) {
|
||||
(_, KeyCode::Esc) if self.endpoint_mode() => self.go(Page::Endpoint),
|
||||
(_, KeyCode::Esc) => self.go(Page::Model),
|
||||
(CheckState::Ok, KeyCode::Enter) if self.endpoint_mode() => self.start_save(),
|
||||
(CheckState::Ok, KeyCode::Enter) => self.go(Page::WebSearch),
|
||||
(CheckState::Failed(_), _) => {
|
||||
if Self::move_index(key, &mut self.test_choice, 2) {
|
||||
return;
|
||||
}
|
||||
if key.code == KeyCode::Enter {
|
||||
if self.test_choice == 0 {
|
||||
if self.test_choice == 0 && self.endpoint_mode() {
|
||||
self.start_endpoint_check();
|
||||
} else if self.test_choice == 0 {
|
||||
let model = self.model.clone();
|
||||
self.start_test(model);
|
||||
} else {
|
||||
@@ -832,6 +1001,10 @@ impl SetupWizard {
|
||||
return;
|
||||
}
|
||||
match (self.searx_focus, key.code) {
|
||||
(1, KeyCode::Enter) if self.searx_keep_available() => {
|
||||
// Keep the configured `[web_search]` as it is.
|
||||
self.start_save();
|
||||
}
|
||||
(0, KeyCode::Enter) | (1, KeyCode::Enter) => {
|
||||
if self.searx_verified.is_some() && self.searx_focus == 1 {
|
||||
self.start_save();
|
||||
@@ -861,6 +1034,7 @@ impl SetupWizard {
|
||||
}
|
||||
match key.code {
|
||||
KeyCode::Enter if self.save_choice == 0 => self.start_save(),
|
||||
KeyCode::Enter | KeyCode::Esc if self.endpoint_mode() => self.go(Page::Endpoint),
|
||||
KeyCode::Enter | KeyCode::Esc => self.go(Page::WebSearch),
|
||||
_ => {}
|
||||
}
|
||||
@@ -1121,9 +1295,13 @@ fn hint_line(parts: &[(&str, &str)], width: usize) -> Line<'static> {
|
||||
|
||||
impl SetupWizard {
|
||||
fn header_line(&self, width: usize) -> Line<'static> {
|
||||
let title = self.page.title();
|
||||
let title = match (self.endpoint_mode(), self.endpoint_edit()) {
|
||||
(true, Some(_)) => "Modifica endpoint",
|
||||
(true, None) => "Nuovo endpoint",
|
||||
(false, _) => self.page.title(),
|
||||
};
|
||||
let mut spans = vec![Span::styled(title.to_string(), accent()).bold()];
|
||||
if let Some(step) = self.page.step() {
|
||||
if let Some(step) = self.page.step().filter(|_| !self.endpoint_mode()) {
|
||||
let step = format!("passo {step} di {STEP_COUNT}");
|
||||
let gap = width.saturating_sub(display_width(title) + display_width(&step));
|
||||
if gap >= 2 {
|
||||
@@ -1150,7 +1328,7 @@ impl SetupWizard {
|
||||
Page::Endpoint => vec![
|
||||
("tab/↑/↓", "campo"),
|
||||
("invio", "avanti"),
|
||||
("esc", "indietro"),
|
||||
("esc", if self.endpoint_mode() { "annulla" } else { "indietro" }),
|
||||
],
|
||||
Page::Model if self.models == ModelsState::Loading => vec![("esc", "indietro")],
|
||||
Page::Model if self.model_input_active() => {
|
||||
@@ -1185,6 +1363,9 @@ impl SetupWizard {
|
||||
],
|
||||
},
|
||||
Page::Test => match self.test {
|
||||
CheckState::Ok if self.endpoint_mode() => {
|
||||
vec![("invio", "salva"), ("esc", "indietro")]
|
||||
}
|
||||
CheckState::Ok => vec![("invio", "continua"), ("esc", "indietro")],
|
||||
CheckState::Failed(_) => {
|
||||
vec![
|
||||
@@ -1263,10 +1444,18 @@ impl SetupWizard {
|
||||
false,
|
||||
width,
|
||||
));
|
||||
let key_placeholder = if self
|
||||
.endpoint_edit()
|
||||
.is_some_and(|edit| edit.stored_key.is_some())
|
||||
{
|
||||
"•••• salvata: lascia vuoto per mantenerla"
|
||||
} else {
|
||||
"facoltativa"
|
||||
};
|
||||
lines.push(field_line(
|
||||
"Chiave API",
|
||||
&self.key,
|
||||
"facoltativa",
|
||||
key_placeholder,
|
||||
self.form_focus == 2,
|
||||
true,
|
||||
width,
|
||||
@@ -1416,12 +1605,30 @@ impl SetupWizard {
|
||||
Line::from(vec!["Server: ".dim(), self.base_url.clone().into()]),
|
||||
w,
|
||||
));
|
||||
lines.push(truncate_line(
|
||||
Line::from(vec!["Modello: ".dim(), self.model.clone().into()]),
|
||||
w,
|
||||
));
|
||||
if !self.endpoint_mode() {
|
||||
lines.push(truncate_line(
|
||||
Line::from(vec!["Modello: ".dim(), self.model.clone().into()]),
|
||||
w,
|
||||
));
|
||||
}
|
||||
lines.push(Line::default());
|
||||
match &self.test {
|
||||
CheckState::Idle | CheckState::Running if self.endpoint_mode() => {
|
||||
lines.push(Line::from("Richiesta dell'elenco dei modelli (/models)…".dim()));
|
||||
}
|
||||
CheckState::Ok if self.endpoint_mode() => {
|
||||
lines.push(Line::from(vec![
|
||||
Span::styled(
|
||||
"✓ ",
|
||||
crate::style::status_style(crate::style::StatusTone::Success),
|
||||
),
|
||||
format!(
|
||||
"Connessione riuscita: {} modelli disponibili.",
|
||||
self.checked_models
|
||||
)
|
||||
.into(),
|
||||
]));
|
||||
}
|
||||
CheckState::Idle | CheckState::Running => {
|
||||
lines.push(Line::from(
|
||||
"Invio di una richiesta minima a /responses…".dim(),
|
||||
@@ -1475,6 +1682,8 @@ impl SetupWizard {
|
||||
lines.push(Line::default());
|
||||
let verify = if self.searx_verified.is_some() {
|
||||
"Continua"
|
||||
} else if self.searx_keep_available() {
|
||||
"Mantieni"
|
||||
} else {
|
||||
"Verifica e continua"
|
||||
};
|
||||
|
||||
@@ -162,6 +162,7 @@ fn model_list_screen() {
|
||||
"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.
|
||||
@@ -331,6 +332,7 @@ fn long_model_list_filters_by_text_and_free_toggle() {
|
||||
"qwen/qwen3-coder:free".to_string(),
|
||||
"google/gemma-3-27b-it:free".to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
})));
|
||||
assert!(
|
||||
wizard.is_text_entry_active(),
|
||||
@@ -353,6 +355,7 @@ fn long_model_list_filters_by_text_and_free_toggle() {
|
||||
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);
|
||||
|
||||
@@ -62,6 +62,7 @@ pub enum SlashCommand {
|
||||
Statusline,
|
||||
Theme,
|
||||
Setup,
|
||||
Endpoint,
|
||||
#[strum(to_string = "pets", serialize = "pet")]
|
||||
Pets,
|
||||
Mcp,
|
||||
@@ -123,6 +124,7 @@ impl SlashCommand {
|
||||
SlashCommand::Statusline => "configure which items appear in the status line",
|
||||
SlashCommand::Theme => "choose the interface palette or syntax highlighting theme",
|
||||
SlashCommand::Setup => "add a model provider with the guided setup",
|
||||
SlashCommand::Endpoint => "gestisci endpoint, modelli e parametri",
|
||||
SlashCommand::Pets => "choose or hide the terminal pet",
|
||||
SlashCommand::Ps => "list background terminals",
|
||||
SlashCommand::Stop => "stop all background terminals",
|
||||
@@ -299,6 +301,7 @@ impl SlashCommand {
|
||||
SlashCommand::Config
|
||||
| SlashCommand::Theme
|
||||
| SlashCommand::Setup
|
||||
| SlashCommand::Endpoint
|
||||
| SlashCommand::Pets => false,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user