Files
imeai-aKode/akode-rs/tui/src/onboarding/setup_wizard_tests.rs
andrea.difonzo 9636b74c7d aKode 0.2.0: protezione dai loop, errori del server chiari, pulizia
- Protezione dai loop: se il modello ripete lo stesso comando con lo stesso
  errore 3 volte di fila il turno si ferma con un messaggio chiaro (e un
  suggerimento su /permissions per i blocchi della sandbox); configurabile
  con [agent] max_repeated_failures (0 = disattivata).
- Errori dello stream: si mostra il messaggio del server invece di
  "stream closed before response.completed"; il contesto superato
  (llama.cpp, vLLM) diventa un messaggio in italiano; avviso una volta se il
  prompt iniziale supera la finestra del modello.
- Pulizia: tolta la logica morta per le chiavi OpenAI nel credential broker
  (prefisso "sk-", watermark, prefissi ignorati); link alla documentazione
  OpenAI nella TUI sostituiti con il README del repository; test dello
  snapshot del broker adattato al token GitHub.
- Versione 0.2.0 e sezione Novità nel README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:47:47 +01:00

524 lines
18 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 {
include_theme: true,
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 theme_screen_with_preview() {
let mut wizard = wizard();
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.page, Page::Theme);
wizard.palette_idx = 0;
wizard.handle_key_event(key(KeyCode::Down));
wizard.handle_key_event(key(KeyCode::Down));
wizard.handle_key_event(key(KeyCode::Down));
wizard.handle_key_event(key(KeyCode::Down));
assert_eq!(wizard.palette(), UiPalette::Colorblind);
assert_eq!(ui_theme::active_palette(), Some(UiPalette::Colorblind));
snapshot_all_widths("setup_theme", &wizard, 24);
// A short terminal falls back to the compact preview.
insta::assert_snapshot!("setup_theme_60x16", render(&wizard, 60, 16));
wizard.cancel();
assert_eq!(ui_theme::active_palette(), None);
}
#[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 web_search_screen() {
let mut wizard = wizard();
wizard.go(Page::WebSearch);
type_text(&mut wizard, "http://192.168.40.57:8080");
snapshot_all_widths("setup_websearch", &wizard, 14);
wizard.handle_key_event(key(KeyCode::Enter));
assert_eq!(wizard.searx, CheckState::Running);
wizard.apply(Outcome::Searx(Ok("http://192.168.40.57:8080".to_string())));
assert_eq!(wizard.searx_focus, 1);
snapshot_all_widths("setup_websearch_ok", &wizard, 16);
}
#[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();
wizard.searx_verified = Some("http://192.168.40.57:8080".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")),
(
"web_search",
serde_json::json!({"backend": "searxng", "url": "http://192.168.40.57:8080"})
),
(
"tui.ui_theme",
serde_json::json!(wizard.palette().config_value())
),
]
);
}
#[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));
}
#[test]
fn configured_searxng_is_prefilled_and_kept() {
let ctx = SetupContext {
searx_url: Some("http://192.168.40.57:8080".to_string()),
..Default::default()
};
let mut wizard = SetupWizard::new(FrameRequester::test_dummy(), ctx);
wizard.page = Page::WebSearch;
assert!(wizard.searx_keep_available());
assert_eq!(wizard.searx_focus, 1);
let text = render(&wizard, 80, 14);
assert!(text.contains("http://192.168.40.57:8080"));
assert!(text.contains("› [ Mantieni ]"));
assert!(
wizard
.config_edits("p", "P", false)
.iter()
.all(|e| e.key_path != "web_search")
);
}