Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

feat(ai): pick the provider from the table in Settings - AI

xJaroslav690066d1c445f4
diff --git a/src-tauri/omniget-core/src/core/ai.rs b/src-tauri/omniget-core/src/core/ai.rs
index fa85ead6..ebd31132 100644
--- a/src-tauri/omniget-core/src/core/ai.rs
+++ b/src-tauri/omniget-core/src/core/ai.rs
@@ -17,6 +17,11 @@ pub enum AiProvider {
pub struct AiConfig {
#[serde(default)]
pub provider: AiProvider,
+ /// Provedor da tabela (`ai_keys::KINDS`) por trás do `provider`: é ele que
+ /// diz qual endereço usar e se a chave é obrigatória. Vazio nas configurações
+ /// antigas, feitas quando só existia "OpenAI / Anthropic / local".
+ #[serde(default)]
+ pub kind: String,
#[serde(default)]
pub openai_key: String,
#[serde(default)]
@@ -32,6 +37,7 @@ pub struct AiConfig {
#[derive(Clone, Debug, Serialize)]
pub struct AiConfigView {
pub provider: AiProvider,
+ pub kind: String,
pub model: String,
pub local_base_url: String,
pub has_openai_key: bool,
@@ -42,6 +48,7 @@ impl AiConfig {
pub fn view(&self) -> AiConfigView {
AiConfigView {
provider: self.provider,
+ kind: self.kind.clone(),
model: self.model.clone(),
local_base_url: self.local_base_url.clone(),
has_openai_key: !self.openai_key.is_empty(),
@@ -54,7 +61,20 @@ impl AiConfig {
AiProvider::None => false,
AiProvider::Openai => !self.openai_key.is_empty(),
AiProvider::Anthropic => !self.anthropic_key.is_empty(),
- AiProvider::Local => !self.local_base_url.is_empty(),
+ // Config antiga (sem `kind`): basta o endereço, como sempre foi.
+ // Com provedor da tabela, quem não dispensa chave precisa dela.
+ AiProvider::Local => {
+ !self.local_base_url.is_empty()
+ && (!self.kind_needs_key() || !self.openai_key.is_empty())
+ }
+ }
+ }
+
+ fn kind_needs_key(&self) -> bool {
+ match crate::core::tools::ai_keys::find_kind(&self.kind) {
+ Some(kind) => kind.needs_key(),
+ // Provedor fora da tabela é desconhecido: pede chave.
+ None => !self.kind.is_empty(),
}
}
}
@@ -66,9 +86,21 @@ fn store() -> &'static Mutex<AiConfig> {
}
fn file_path() -> Option<std::path::PathBuf> {
+ // Nos testes o arquivo vai para uma pasta temporária: a configuração real do
+ // usuário não pode ser tocada por um `cargo test`.
+ #[cfg(test)]
+ if let Some(dir) = TEST_DIR.with(|d| d.borrow().clone()) {
+ return Some(dir.join(AI_CONFIG_FILE));
+ }
crate::core::paths::app_data_dir().map(|d| d.join(AI_CONFIG_FILE))
}
+#[cfg(test)]
+thread_local! {
+ static TEST_DIR: std::cell::RefCell<Option<std::path::PathBuf>> =
+ const { std::cell::RefCell::new(None) };
+}
+
fn load_from_disk() -> AiConfig {
let Some(path) = file_path() else {
return AiConfig::default();
@@ -139,6 +171,73 @@ pub fn set(
guard.clone()
}
+/// O que fazer com a credencial guardada quando a tela salva a configuração.
+/// O formulário nunca recebe o segredo de volta, então "não mexi no campo" e
+/// "apaguei o campo" precisam chegar aqui como coisas diferentes.
+pub enum KeyAction<'a> {
+ /// Mantém a chave guardada.
+ Keep,
+ /// Substitui pela chave digitada.
+ Set(&'a str),
+ /// Apaga a credencial (troca de provedor, ou campo esvaziado).
+ Clear,
+}
+
+fn provider_for_kind(kind: &str) -> AiProvider {
+ match kind {
+ "openai" => AiProvider::Openai,
+ "anthropic" => AiProvider::Anthropic,
+ // Todo o resto fala o dialeto OpenAI (cada um no seu endereço).
+ _ => AiProvider::Local,
+ }
+}
+
+fn apply_kind(cfg: &mut AiConfig, kind: &str, model: String, base_url: String, key: KeyAction<'_>) {
+ let kind = kind.trim();
+ cfg.provider = provider_for_kind(kind);
+ cfg.kind = kind.to_string();
+ cfg.model = model.trim().to_string();
+ cfg.local_base_url = if cfg.provider == AiProvider::Local {
+ crate::core::tools::ai_keys::app_base_url(kind, &base_url)
+ } else {
+ String::new()
+ };
+ match key {
+ KeyAction::Keep => {}
+ KeyAction::Set(k) => {
+ let k = k.trim().to_string();
+ if cfg.provider == AiProvider::Anthropic {
+ cfg.anthropic_key = k;
+ } else {
+ cfg.openai_key = k;
+ }
+ }
+ KeyAction::Clear => {
+ cfg.openai_key.clear();
+ cfg.anthropic_key.clear();
+ }
+ }
+}
+
+/// Salva a escolha da tela de IA: o provedor da tabela define a rota e a
+/// necessidade de chave, e `key` decide o destino da credencial guardada.
+pub fn set_with_kind(kind: &str, model: String, base_url: String, key: KeyAction<'_>) -> AiConfig {
+ let mut guard = store().lock().unwrap();
+ apply_kind(&mut guard, kind, model, base_url, key);
+ write_to_disk(&guard);
+ guard.clone()
+}
+
+/// Desliga a IA (provedor "none"): some o provedor e o tipo; endereço, modelo e
+/// chave ficam guardados para quando o usuário religar.
+pub fn clear() -> AiConfig {
+ let mut guard = store().lock().unwrap();
+ guard.provider = AiProvider::None;
+ guard.kind = String::new();
+ write_to_disk(&guard);
+ guard.clone()
+}
+
fn http_client() -> Result<reqwest::Client, String> {
let builder = reqwest::Client::builder().timeout(std::time::Duration::from_secs(120));
crate::core::http_client::apply_global_proxy(builder)
@@ -436,6 +535,7 @@ mod tests {
fn view_hides_keys() {
let cfg = AiConfig {
provider: AiProvider::Openai,
+ kind: "openai".to_string(),
openai_key: "secret".to_string(),
anthropic_key: String::new(),
local_base_url: String::new(),
@@ -444,6 +544,7 @@ mod tests {
let v = cfg.view();
assert!(v.has_openai_key);
assert!(!v.has_anthropic_key);
+ assert_eq!(v.kind, "openai");
let json = serde_json::to_string(&v).unwrap();
assert!(!json.contains("secret"));
}
@@ -457,4 +558,165 @@ mod tests {
cfg.anthropic_key = "k".to_string();
assert!(cfg.is_configured());
}
+
+ #[test]
+ fn a_kindless_local_config_still_counts_as_configured() {
+ // Configuração antiga (antes do `kind`): só o endereço, sem chave.
+ let cfg = AiConfig {
+ provider: AiProvider::Local,
+ kind: String::new(),
+ local_base_url: "http://localhost:11434/v1".to_string(),
+ model: "llama3".to_string(),
+ ..AiConfig::default()
+ };
+ assert!(cfg.is_configured());
+ }
+
+ #[test]
+ fn a_table_provider_that_needs_a_key_asks_for_one() {
+ let mut cfg = AiConfig {
+ provider: AiProvider::Local,
+ kind: "deepseek".to_string(),
+ local_base_url: "https://api.deepseek.com".to_string(),
+ ..AiConfig::default()
+ };
+ assert!(!cfg.is_configured());
+ cfg.openai_key = "sk-x".to_string();
+ assert!(cfg.is_configured());
+
+ // Ollama roda na máquina do usuário: chave não é obrigatória.
+ let ollama = AiConfig {
+ provider: AiProvider::Local,
+ kind: "ollama".to_string(),
+ local_base_url: "http://localhost:11434/v1".to_string(),
+ ..AiConfig::default()
+ };
+ assert!(ollama.is_configured());
+
+ // Provedor fora da tabela é desconhecido: pede chave.
+ let unknown = AiConfig {
+ provider: AiProvider::Local,
+ kind: "provedor-novo".to_string(),
+ local_base_url: "https://exemplo.com/v1".to_string(),
+ ..AiConfig::default()
+ };
+ assert!(!unknown.is_configured());
+ }
+
+ #[test]
+ fn the_kind_decides_the_route_and_the_provider() {
+ let mut cfg = AiConfig::default();
+ apply_kind(
+ &mut cfg,
+ "deepseek",
+ "deepseek-chat".to_string(),
+ String::new(),
+ KeyAction::Set("sk-d"),
+ );
+ assert_eq!(cfg.provider, AiProvider::Local);
+ assert_eq!(cfg.kind, "deepseek");
+ assert_eq!(cfg.local_base_url, "https://api.deepseek.com");
+ assert_eq!(cfg.openai_key, "sk-d");
+
+ apply_kind(
+ &mut cfg,
+ "anthropic",
+ "claude-3-5-sonnet".to_string(),
+ String::new(),
+ KeyAction::Set("sk-a"),
+ );
+ assert_eq!(cfg.provider, AiProvider::Anthropic);
+ assert_eq!(cfg.anthropic_key, "sk-a");
+ // Provedor da OpenAI não guarda endereço.
+ assert!(cfg.local_base_url.is_empty());
+
+ apply_kind(
+ &mut cfg,
+ "gemini",
+ "gemini-2.0-flash".to_string(),
+ String::new(),
+ KeyAction::Keep,
+ );
+ assert_eq!(
+ cfg.local_base_url,
+ "https://generativelanguage.googleapis.com/v1beta/openai"
+ );
+ // O endereço digitado pelo usuário vence o da tabela.
+ apply_kind(
+ &mut cfg,
+ "custom",
+ "meu-modelo".to_string(),
+ "http://localhost:1234/v1".to_string(),
+ KeyAction::Keep,
+ );
+ assert_eq!(cfg.local_base_url, "http://localhost:1234/v1");
+ }
+
+ #[test]
+ fn switching_provider_can_drop_the_previous_credential() {
+ let mut cfg = AiConfig {
+ provider: AiProvider::Anthropic,
+ kind: "anthropic".to_string(),
+ anthropic_key: "sk-ant".to_string(),
+ ..AiConfig::default()
+ };
+ apply_kind(
+ &mut cfg,
+ "openai",
+ "gpt-4o-mini".to_string(),
+ String::new(),
+ KeyAction::Clear,
+ );
+ assert!(cfg.openai_key.is_empty());
+ assert!(cfg.anthropic_key.is_empty());
+ assert_eq!(cfg.provider, AiProvider::Openai);
+ }
+
+ #[test]
+ fn the_store_keeps_the_credential_where_it_belongs() {
+ // Passa pelo mesmo caminho da tela de IA (store + arquivo), só que numa
+ // pasta temporária: é o teste que pega troca de provedor vazando a chave.
+ let dir = std::env::temp_dir().join(format!("omniget-ai-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ TEST_DIR.with(|d| *d.borrow_mut() = Some(dir.clone()));
+
+ let saved = set_with_kind(
+ "deepseek",
+ "deepseek-chat".to_string(),
+ String::new(),
+ KeyAction::Set("sk-deepseek"),
+ );
+ assert_eq!(saved.provider, AiProvider::Local);
+ assert_eq!(saved.kind, "deepseek");
+ assert_eq!(saved.local_base_url, "https://api.deepseek.com");
+
+ // O que ficou gravado é o que uma próxima execução vai ler.
+ let on_disk: AiConfig = serde_json::from_str(
+ &std::fs::read_to_string(dir.join(AI_CONFIG_FILE)).expect("config escrita"),
+ )
+ .unwrap();
+ assert_eq!(on_disk.kind, "deepseek");
+ assert_eq!(on_disk.model, "deepseek-chat");
+ assert!(on_disk.is_configured());
+
+ // Trocar de provedor com o campo de chave vazio apaga a credencial antiga.
+ let switched = set_with_kind(
+ "openai",
+ "gpt-4o-mini".to_string(),
+ String::new(),
+ KeyAction::Clear,
+ );
+ assert_eq!(switched.provider, AiProvider::Openai);
+ assert!(switched.openai_key.is_empty());
+ assert!(switched.anthropic_key.is_empty());
+
+ // "Desligar" tira o provedor e o tipo.
+ let off = clear();
+ assert_eq!(off.provider, AiProvider::None);
+ assert!(off.kind.is_empty());
+ assert!(!get().is_configured());
+
+ TEST_DIR.with(|d| *d.borrow_mut() = None);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/src-tauri/omniget-core/src/core/tools/ai_keys.rs b/src-tauri/omniget-core/src/core/tools/ai_keys.rs
index ba8acac4..230469ef 100644
--- a/src-tauri/omniget-core/src/core/tools/ai_keys.rs
+++ b/src-tauri/omniget-core/src/core/tools/ai_keys.rs
@@ -196,10 +196,75 @@ pub const KINDS: &[Kind] = &[
];
fn kind_of(id: &str) -> &'static Kind {
- KINDS
- .iter()
- .find(|k| k.id == id)
- .unwrap_or(&KINDS[KINDS.len() - 1])
+ find_kind(id).unwrap_or(&KINDS[KINDS.len() - 1])
+}
+
+/// A linha da tabela com este id, quando existe: quem não está na tabela é
+/// desconhecido, e desconhecido não é o mesmo que "OpenAI-compatível".
+pub fn find_kind(id: &str) -> Option<&'static Kind> {
+ KINDS.iter().find(|k| k.id == id)
+}
+
+impl Kind {
+ /// O provedor exige chave de API. Ollama roda na máquina do usuário e um
+ /// endpoint próprio ("custom") pode não ter autenticação; todo o resto tem.
+ pub fn needs_key(&self) -> bool {
+ !matches!(self.id, "ollama" | "custom")
+ }
+
+ /// O endereço da tabela é só um exemplo (Ollama local, relay New API,
+ /// endpoint próprio) — nesses casos quem digita é o usuário.
+ pub fn base_url_editable(&self) -> bool {
+ matches!(self.id, "ollama" | "custom") || self.base_url.contains("seu-site.com")
+ }
+}
+
+/// O que a tela de IA precisa da tabela: os dados do provedor e as duas
+/// capacidades do formulário (pede chave? pede endereço?).
+#[derive(Debug, Clone, Serialize)]
+pub struct KindView {
+ pub id: &'static str,
+ pub name: &'static str,
+ pub base_url: &'static str,
+ pub balance: bool,
+ pub env: &'static str,
+ pub needs_key: bool,
+ pub base_url_editable: bool,
+}
+
+impl KindView {
+ pub fn of(kind: &Kind) -> Self {
+ KindView {
+ id: kind.id,
+ name: kind.name,
+ base_url: kind.base_url,
+ balance: kind.balance,
+ env: kind.env,
+ needs_key: kind.needs_key(),
+ base_url_editable: kind.base_url_editable(),
+ }
+ }
+}
+
+/// A tabela como o frontend a vê (`tool_keys_kinds`).
+pub fn kinds_view() -> Vec<KindView> {
+ KINDS.iter().map(KindView::of).collect()
+}
+
+/// Endereço que o chat do app usa: o que o usuário digitou ou o da tabela.
+/// O Gemini só fala o dialeto OpenAI na rota `/openai`.
+pub fn app_base_url(kind: &str, base: &str) -> String {
+ let raw = if base.trim().is_empty() {
+ kind_of(kind).base_url
+ } else {
+ base.trim()
+ };
+ let trimmed = raw.trim_end_matches('/');
+ if kind == "gemini" && !trimmed.ends_with("/openai") {
+ format!("{}/openai", trimmed)
+ } else {
+ trimmed.to_string()
+ }
}
// ── Armazenamento ──────────────────────────────────────────────────────
@@ -624,19 +689,15 @@ pub fn export(format: &str, ids: &[String]) -> anyhow::Result<String> {
/// Usa esta chave como a IA do OmniGet (Ajustes → IA).
pub fn use_in_app(id: &str) -> anyhow::Result<()> {
let e = get(id)?;
- use crate::core::ai::{self, AiProvider};
- match e.kind.as_str() {
- "openai" => {
- ai::set(AiProvider::Openai, e.model.clone(), String::new(), Some(e.key.clone()), None);
- }
- "anthropic" => {
- ai::set(AiProvider::Anthropic, e.model.clone(), String::new(), None, Some(e.key.clone()));
- }
- "gemini" => return Err(anyhow!("o chat do OmniGet fala OpenAI/Anthropic; use a rota OpenAI-compatível do Gemini (…/v1beta/openai) como personalizado")),
- _ => {
- ai::set(AiProvider::Local, e.model.clone(), e.base_url.clone(), Some(e.key.clone()), None);
- }
- }
+ use crate::core::ai::{self, KeyAction};
+ // Guarda também o provedor da tabela (`kind`): sem ele a tela de IA não
+ // sabe qual endereço usar nem se a chave é obrigatória.
+ ai::set_with_kind(
+ &e.kind,
+ e.model.clone(),
+ e.base_url.clone(),
+ KeyAction::Set(&e.key),
+ );
Ok(())
}
@@ -652,4 +713,54 @@ mod tests {
assert_eq!(site_of("https://x.com/v1/"), "https://x.com");
assert_eq!(site_of("https://x.com"), "https://x.com");
}
+
+ #[test]
+ fn the_payload_carries_the_form_flags() {
+ // A tela de IA decide o formulário por estes dois campos; se eles não
+ // saírem no JSON, o formulário some (foi o bug do PR #352).
+ let json = serde_json::to_value(kinds_view()).unwrap();
+ let arr = json.as_array().unwrap();
+ let find = |id: &str| {
+ arr.iter()
+ .find(|k| k["id"] == id)
+ .unwrap_or_else(|| panic!("sem {}", id))
+ .clone()
+ };
+ assert_eq!(find("deepseek")["needs_key"], serde_json::json!(true));
+ assert_eq!(
+ find("deepseek")["base_url_editable"],
+ serde_json::json!(false)
+ );
+ assert_eq!(find("ollama")["needs_key"], serde_json::json!(false));
+ assert_eq!(find("ollama")["base_url_editable"], serde_json::json!(true));
+ assert_eq!(find("newapi")["needs_key"], serde_json::json!(true));
+ assert_eq!(find("newapi")["base_url_editable"], serde_json::json!(true));
+ assert_eq!(find("custom")["base_url_editable"], serde_json::json!(true));
+ }
+
+ #[test]
+ fn gemini_uses_its_openai_compatible_route() {
+ assert_eq!(
+ app_base_url("gemini", ""),
+ "https://generativelanguage.googleapis.com/v1beta/openai"
+ );
+ assert_eq!(
+ app_base_url(
+ "gemini",
+ "https://generativelanguage.googleapis.com/v1beta/openai"
+ ),
+ "https://generativelanguage.googleapis.com/v1beta/openai"
+ );
+ assert_eq!(app_base_url("deepseek", ""), "https://api.deepseek.com");
+ assert_eq!(
+ app_base_url("custom", "http://localhost:1234/v1/"),
+ "http://localhost:1234/v1"
+ );
+ }
+
+ #[test]
+ fn unknown_kinds_are_not_the_custom_row() {
+ assert!(find_kind("nao-existe").is_none());
+ assert_eq!(kind_of("nao-existe").id, "custom");
+ }
}
diff --git a/src-tauri/src/commands/ai.rs b/src-tauri/src/commands/ai.rs
index 89e85ef2..aba4936b 100644
--- a/src-tauri/src/commands/ai.rs
+++ b/src-tauri/src/commands/ai.rs
@@ -1,4 +1,4 @@
-use omniget_core::core::ai::{self, AiConfigView, AiHistoryEntry, AiProvider};
+use omniget_core::core::ai::{self, AiConfigView, AiHistoryEntry, AiProvider, KeyAction};
use serde::Serialize;
const MAX_TRANSCRIPT_CHARS: usize = 12000;
@@ -8,15 +8,37 @@ pub fn ai_get_config() -> AiConfigView {
ai::get().view()
}
+// A tela manda o provedor da tabela (`kind`) junto do `provider` genérico, e a
+// intenção sobre a chave em `key_action`: "keep" mantém a guardada, "clear"
+// apaga (troca de provedor com o campo vazio) e "set" grava a digitada. O
+// segredo nunca volta para a UI, então a intenção precisa ser explícita.
#[tauri::command]
pub fn ai_set_config(
provider: AiProvider,
+ kind: Option<String>,
model: String,
local_base_url: String,
- openai_key: Option<String>,
- anthropic_key: Option<String>,
-) -> AiConfigView {
- ai::set(provider, model, local_base_url, openai_key, anthropic_key).view()
+ key_action: Option<String>,
+ key: Option<String>,
+) -> Result<AiConfigView, String> {
+ let action = match key_action.as_deref() {
+ None | Some("keep") => KeyAction::Keep,
+ Some("clear") => KeyAction::Clear,
+ Some("set") => match key.as_deref().map(str::trim) {
+ Some(k) if !k.is_empty() => KeyAction::Set(k),
+ _ => KeyAction::Clear,
+ },
+ Some(other) => return Err(format!("unknown key_action: {}", other)),
+ };
+ let kind = kind.unwrap_or_default();
+ if provider == AiProvider::None || kind.trim() == "none" {
+ return Ok(ai::clear().view());
+ }
+ // Cliente antigo (sem `kind`): mantém o caminho de antes.
+ if kind.trim().is_empty() {
+ return Ok(ai::set(provider, model, local_base_url, None, None).view());
+ }
+ Ok(ai::set_with_kind(&kind, model, local_base_url, action).view())
}
#[tauri::command]
diff --git a/src-tauri/src/commands/tools/ai.rs b/src-tauri/src/commands/tools/ai.rs
index 3a5ebbdf..e35a272b 100644
--- a/src-tauri/src/commands/tools/ai.rs
+++ b/src-tauri/src/commands/tools/ai.rs
@@ -65,8 +65,8 @@ pub fn tool_usage_clear() -> Result<(), String> {
// ── Chaves de API (estudo 24) ──
#[tauri::command]
-pub fn tool_keys_kinds() -> Vec<ai_keys::Kind> {
- ai_keys::KINDS.to_vec()
+pub fn tool_keys_kinds() -> Vec<ai_keys::KindView> {
+ ai_keys::kinds_view()
}
#[tauri::command]
diff --git a/src/components/settings/SettingsAI.svelte b/src/components/settings/SettingsAI.svelte
index 835e8f24..00606c96 100644
--- a/src/components/settings/SettingsAI.svelte
+++ b/src/components/settings/SettingsAI.svelte
@@ -4,9 +4,41 @@
import { t } from "$lib/i18n";
import { showToast } from "$lib/stores/toast-store.svelte";
+ // the provider table the LLM layer routes on (ai_keys::KINDS). Kept in sync by
+ // reading it instead of repeating it here: the list was hardcoded to three entries
+ // while twelve exist, which is what left deepseek and the other eight unreachable
+ // from this panel even though every other surface could already use them.
+ // needs_key / base_url_editable come from the same rows, so a provider added later
+ // cannot be missing from a second list kept somewhere else.
+ type Kind = {
+ id: string;
+ name: string;
+ base_url: string;
+ balance: boolean;
+ env: string;
+ needs_key: boolean;
+ base_url_editable: boolean;
+ };
+ // a model name is not available from the registry, so these are placeholders only -
+ // the field stays free text and whatever the provider accepts is what works
+ const MODEL_HINTS: Record<string, string> = {
+ openai: "gpt-4o-mini",
+ anthropic: "claude-sonnet-4-5",
+ deepseek: "deepseek-chat",
+ openrouter: "openai/gpt-4o-mini",
+ gemini: "gemini-2.5-flash",
+ groq: "llama-3.3-70b-versatile",
+ xai: "grok-3",
+ mistral: "mistral-large-latest",
+ siliconflow: "deepseek-ai/DeepSeek-V3",
+ newapi: "gpt-4o-mini",
+ ollama: "llama3.2"
+ };
+
type Provider = "none" | "openai" | "anthropic" | "local";
type ConfigView = {
provider: Provider;
+ kind: string;
model: string;
local_base_url: string;
has_openai_key: boolean;
@@ -21,13 +53,16 @@
created_at_ms: number;
};
- let provider = $state<Provider>("none");
+ let kinds = $state<Kind[]>([]);
+ // "none" | a kind id. The kind is the selection; the legacy `provider` string is
+ // derived from it server-side so a request still has a wire to speak.
+ let kind = $state<string>("none");
+ // the kind the saved config already had, so a switch can be told from a re-save
+ let savedKind = $state<string>("none");
let model = $state("");
let localBaseUrl = $state("");
- let openaiKey = $state("");
- let anthropicKey = $state("");
- let hasOpenaiKey = $state(false);
- let hasAnthropicKey = $state(false);
+ let keyInput = $state("");
+ let hasKey = $state(false);
let testing = $state(false);
let summarizeUrl = $state("");
@@ -36,16 +71,30 @@
let summaryLang = $state("");
let history = $state<HistoryEntry[]>([]);
+ const selectedKind = $derived(kinds.find((k) => k.id === kind));
+ const needsKey = $derived(!!selectedKind?.needs_key);
+ const needsBaseUrl = $derived(!!selectedKind?.base_url_editable);
+
+ async function loadKinds() {
+ try {
+ kinds = await invoke<Kind[]>("tool_keys_kinds");
+ } catch {
+ kinds = [];
+ }
+ }
+
async function loadConfig() {
try {
const c = await invoke<ConfigView>("ai_get_config");
- provider = c.provider;
+ // an older build stored no kind at all. `custom` is what the server falls back to
+ // for a bare local endpoint, so the picker shows that instead of a name it does
+ // not carry, and the endpoint stays editable
+ kind = c.kind || (c.provider === "local" ? "custom" : c.provider);
+ savedKind = kind;
model = c.model;
localBaseUrl = c.local_base_url;
- hasOpenaiKey = c.has_openai_key;
- hasAnthropicKey = c.has_anthropic_key;
- openaiKey = "";
- anthropicKey = "";
+ hasKey = c.provider === "anthropic" ? c.has_anthropic_key : c.has_openai_key;
+ keyInput = "";
} catch (e: any) {
showToast("error", typeof e === "string" ? e : $t("common.error"));
}
@@ -60,18 +109,39 @@
}
onMount(() => {
+ loadKinds();
loadConfig();
loadHistory();
});
+ // the endpoint belongs to the provider, so it follows the choice instead of being
+ // retyped. Providers whose table URL is real keep it; the ones whose URL only has a
+ // shape (ollama, custom, and a relay that is deployed per site) take what is typed.
+ function onKindChange() {
+ const k = selectedKind;
+ if (!k) {
+ localBaseUrl = "";
+ return;
+ }
+ localBaseUrl = k.base_url_editable ? (localBaseUrl.trim() ? localBaseUrl : k.base_url) : "";
+ }
+
async function save() {
try {
+ // leaving the field blank keeps the stored credential, but only while the
+ // provider stays the same: switching providers has to clear it, or the previous
+ // provider's key is sent to the new endpoint as a bearer token
+ const switched = kind !== savedKind;
+ const entered = keyInput.trim();
+ const keyAction = entered ? "set" : switched ? "clear" : "keep";
+
await invoke("ai_set_config", {
- provider,
+ provider: kind === "none" ? "none" : "local",
+ kind: kind === "none" ? null : kind,
model: model.trim(),
- localBaseUrl: localBaseUrl.trim(),
- openaiKey: openaiKey.trim() !== "" ? openaiKey.trim() : null,
- anthropicKey: anthropicKey.trim() !== "" ? anthropicKey.trim() : null,
+ localBaseUrl: needsBaseUrl ? localBaseUrl.trim() : "",
+ keyAction,
+ key: entered ? entered : null,
});
await loadConfig();
showToast("success", $t("settings.ai.saved") as string);
@@ -141,68 +211,70 @@
<span class="setting-label">{$t('settings.ai.provider')}</span>
<span class="setting-path">{$t('settings.ai.provider_desc')}</span>
</div>
- <select class="input-text select" bind:value={provider}>
+ <select class="input-text select" bind:value={kind} onchange={onKindChange}>
<option value="none">{$t('settings.ai.provider_none')}</option>
- <option value="openai">OpenAI</option>
- <option value="anthropic">Anthropic</option>
- <option value="local">{$t('settings.ai.provider_local')}</option>
+ {#each kinds as k (k.id)}
+ <option value={k.id}>{k.name}</option>
+ {/each}
</select>
</div>
- {#if provider !== "none"}
+ {#if kind !== "none"}
<div class="divider"></div>
<div class="setting-row">
<div class="setting-col">
<span class="setting-label">{$t('settings.ai.model')}</span>
<span class="setting-path">{$t('settings.ai.model_desc')}</span>
</div>
- <input type="text" class="input-text" placeholder={$t('settings.ai.model_placeholder')} bind:value={model} />
- </div>
- {/if}
-
- {#if provider === "openai"}
- <div class="divider"></div>
- <div class="setting-row">
- <div class="setting-col">
- <span class="setting-label">{$t('settings.ai.openai_key')}</span>
- <span class="setting-path">{hasOpenaiKey ? $t('settings.ai.key_set') : $t('settings.ai.key_unset')}</span>
- </div>
- <input type="password" class="input-text" placeholder={hasOpenaiKey ? "••••••••" : "sk-…"} bind:value={openaiKey} />
+ <input
+ type="text"
+ class="input-text"
+ placeholder={MODEL_HINTS[kind] ?? ($t('settings.ai.model_placeholder') as string)}
+ bind:value={model}
+ />
</div>
{/if}
- {#if provider === "anthropic"}
+ {#if needsKey}
<div class="divider"></div>
<div class="setting-row">
<div class="setting-col">
- <span class="setting-label">{$t('settings.ai.anthropic_key')}</span>
- <span class="setting-path">{hasAnthropicKey ? $t('settings.ai.key_set') : $t('settings.ai.key_unset')}</span>
+ <span class="setting-label">{$t('settings.ai.api_key')}</span>
+ <span class="setting-path">
+ {hasKey ? $t('settings.ai.key_set') : $t('settings.ai.key_unset')}
+ {#if selectedKind}· {selectedKind.env}{/if}
+ </span>
</div>
- <input type="password" class="input-text" placeholder={hasAnthropicKey ? "••••••••" : "sk-ant-…"} bind:value={anthropicKey} />
+ <input type="password" class="input-text" placeholder={hasKey ? "••••••••" : "sk-…"} bind:value={keyInput} />
</div>
{/if}
- {#if provider === "local"}
+ {#if needsBaseUrl}
<div class="divider"></div>
<div class="setting-row">
<div class="setting-col">
<span class="setting-label">{$t('settings.ai.local_url')}</span>
<span class="setting-path">{$t('settings.ai.local_url_desc')}</span>
</div>
- <input type="text" class="input-text" placeholder="http://localhost:11434/v1" bind:value={localBaseUrl} />
+ <input
+ type="text"
+ class="input-text"
+ placeholder={selectedKind?.base_url ?? "http://localhost:11434/v1"}
+ bind:value={localBaseUrl}
+ />
</div>
{/if}
<div class="divider"></div>
<div class="actions-row">
<button class="primary-btn" onclick={save}>{$t('settings.ai.save')}</button>
- {#if provider !== "none"}
+ {#if kind !== "none"}
<button class="ghost-btn" disabled={testing} onclick={runTest}>{$t('settings.ai.test')}</button>
{/if}
</div>
</div>
- {#if provider !== "none"}
+ {#if kind !== "none"}
<h5 class="section-title">{$t('settings.ai.summarize_title')}</h5>
<div class="card">
<div class="add-row">
diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.json
index 0b3b95a0..8ff9afd3 100644
--- a/src/lib/i18n/el.json
+++ b/src/lib/i18n/el.json
@@ -4247,6 +4247,7 @@
"model": "Μοντέλο",
"model_desc": "Το αναγνωριστικό μοντέλου για τον επιλεγμένο πάροχο.",
"model_placeholder": "π.χ. gpt-4o-mini, claude-3-5-sonnet-latest, llama3",
+ "api_key": "API key",
"openai_key": "Κλειδί API OpenAI",
"anthropic_key": "Κλειδί API Anthropic",
"key_set": "Υπάρχει αποθηκευμένο κλειδί. Άφησέ το κενό για να διατηρηθεί.",
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index 64f2b52c..703f697a 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -4247,6 +4247,7 @@
"model": "Model",
"model_desc": "The model identifier for the chosen provider.",
"model_placeholder": "e.g. gpt-4o-mini, claude-3-5-sonnet-latest, llama3",
+ "api_key": "API key",
"openai_key": "OpenAI API key",
"anthropic_key": "Anthropic API key",
"key_set": "A key is saved. Leave blank to keep it.",
diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.json
index c022038a..13615a51 100644
--- a/src/lib/i18n/es.json
+++ b/src/lib/i18n/es.json
@@ -4247,6 +4247,7 @@
"model": "Modelo",
"model_desc": "El identificador del modelo para el proveedor elegido.",
"model_placeholder": "p. ej. gpt-4o-mini, claude-3-5-sonnet-latest, llama3",
+ "api_key": "API key",
"openai_key": "Clave API de OpenAI",
"anthropic_key": "Clave API de Anthropic",
"key_set": "Hay una clave guardada. Déjalo en blanco para conservarla.",
diff --git a/src/lib/i18n/fa.json b/src/lib/i18n/fa.json
index 1463d9b2..398d4a5f 100644
--- a/src/lib/i18n/fa.json
+++ b/src/lib/i18n/fa.json
@@ -4247,6 +4247,7 @@
"model": "Model",
"model_desc": "The model identifier for the chosen provider.",
"model_placeholder": "e.g. gpt-4o-mini, claude-3-5-sonnet-latest, llama3",
+ "api_key": "API key",
"openai_key": "OpenAI API key",
"anthropic_key": "Anthropic API key",
"key_set": "A key is saved. Leave blank to keep it.",
diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.json
index ead7ca6b..d0b8ad2a 100644
--- a/src/lib/i18n/fr.json
+++ b/src/lib/i18n/fr.json
@@ -4247,6 +4247,7 @@
"model": "Modèle",
"model_desc": "L'identifiant du modèle pour le fournisseur choisi.",
"model_placeholder": "ex. gpt-4o-mini, claude-3-5-sonnet-latest, llama3",
+ "api_key": "API key",
"openai_key": "Clé API OpenAI",
"anthropic_key": "Clé API Anthropic",
"key_set": "Une clé est enregistrée. Laissez vide pour la conserver.",
diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.json
index 4e334e95..cc9adc1d 100644
--- a/src/lib/i18n/it.json
+++ b/src/lib/i18n/it.json
@@ -4247,6 +4247,7 @@
"model": "Modello",
"model_desc": "L'identificatore del modello per il provider scelto.",
"model_placeholder": "es. gpt-4o-mini, claude-3-5-sonnet-latest, llama3",
+ "api_key": "API key",
"openai_key": "Chiave API OpenAI",
"anthropic_key": "Chiave API Anthropic",
"key_set": "Una chiave è salvata. Lascia vuoto per mantenerla.",
diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.json
index 62fd3c38..09dec64f 100644
--- a/src/lib/i18n/ja.json
+++ b/src/lib/i18n/ja.json
@@ -4247,6 +4247,7 @@
"model": "モデル",
"model_desc": "選択したプロバイダーのモデル識別子。",
"model_placeholder": "例: gpt-4o-mini, claude-3-5-sonnet-latest, llama3",
+ "api_key": "API key",
"openai_key": "OpenAI API キー",
"anthropic_key": "Anthropic API キー",
"key_set": "キーは保存済みです。空欄のままにすると保持されます。",
diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.ts
index 81d98e07..15672ddc 100644
--- a/src/lib/i18n/keys.ts
+++ b/src/lib/i18n/keys.ts
@@ -2039,6 +2039,7 @@ export type TranslationKeys =
| 'settings.advanced.user_agent_desc'
| 'settings.advanced.user_agent_placeholder'
| 'settings.ai.anthropic_key'
+ | 'settings.ai.api_key'
| 'settings.ai.history'
| 'settings.ai.history_clear'
| 'settings.ai.history_clear_confirm'
diff --git a/src/lib/i18n/lo.json b/src/lib/i18n/lo.json
index b694e755..c838492b 100644
--- a/src/lib/i18n/lo.json
+++ b/src/lib/i18n/lo.json
@@ -4247,6 +4247,7 @@
"model": "ໂມເດວ",
"model_desc": "ຕົວລະບຸໂມເດວສຳລັບຜູ້ໃຫ້ບໍລິການທີ່ເລືອກ.",
"model_placeholder": "ເຊັ່ນ gpt-4o-mini, claude-3-5-sonnet-latest, llama3",
+ "api_key": "API key",
"openai_key": "ຄີ API OpenAI",
"anthropic_key": "ຄີ API Anthropic",
"key_set": "ບັນທຶກຄີແລ້ວ. ປະວ່າງໄວ້ເພື່ອໃຊ້ຄີເດີມ.",
diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.json
index 246ca7bd..e66d144f 100644
--- a/src/lib/i18n/pt.json
+++ b/src/lib/i18n/pt.json
@@ -4247,6 +4247,7 @@
"model": "Modelo",
"model_desc": "O identificador do modelo para o provedor escolhido.",
"model_placeholder": "ex.: gpt-4o-mini, claude-3-5-sonnet-latest, llama3",
+ "api_key": "API key",
"openai_key": "Chave da API OpenAI",
"anthropic_key": "Chave da API Anthropic",
"key_set": "Uma chave está salva. Deixe em branco para mantê-la.",
diff --git a/src/lib/i18n/ru.json b/src/lib/i18n/ru.json
index ae31d363..358edba1 100644
--- a/src/lib/i18n/ru.json
+++ b/src/lib/i18n/ru.json
@@ -4247,6 +4247,7 @@
"model": "Модель",
"model_desc": "Идентификатор модели для выбранного провайдера.",
"model_placeholder": "например gpt-4o-mini, claude-3-5-sonnet-latest, llama3",
+ "api_key": "Ключ API",
"openai_key": "Ключ API OpenAI",
"anthropic_key": "Ключ API Anthropic",
"key_set": "Ключ сохранён. Оставьте пустым, чтобы не менять.",
diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.json
index 289c2bd5..cb46d9aa 100644
--- a/src/lib/i18n/zh-TW.json
+++ b/src/lib/i18n/zh-TW.json
@@ -4247,6 +4247,7 @@
"model": "模型",
"model_desc": "所選提供者的模型識別碼。",
"model_placeholder": "例如 gpt-4o-mini、claude-3-5-sonnet-latest、llama3",
+ "api_key": "API key",
"openai_key": "OpenAI API 金鑰",
"anthropic_key": "Anthropic API 金鑰",
"key_set": "已儲存金鑰。留空以保留。",
diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.json
index 09906f55..133f8c8c 100644
--- a/src/lib/i18n/zh.json
+++ b/src/lib/i18n/zh.json
@@ -4247,6 +4247,7 @@
"model": "模型",
"model_desc": "所选提供方的模型标识符。",
"model_placeholder": "例如 gpt-4o-mini、claude-3-5-sonnet-latest、llama3",
+ "api_key": "API key",
"openai_key": "OpenAI API 密钥",
"anthropic_key": "Anthropic API 密钥",
"key_set": "已保存密钥。留空以保留。",