|
1 | 1 | //! Tauri command surface — every IPC entry the React UI invokes lives here. |
2 | 2 |
|
3 | 3 | use std::sync::Arc; |
| 4 | +use std::time::Duration; |
4 | 5 |
|
| 6 | +use serde::Serialize; |
| 7 | +use serde_json::Value; |
5 | 8 | use tauri::{AppHandle, State}; |
6 | 9 |
|
7 | 10 | use crate::coordinator::Coordinator; |
@@ -81,6 +84,123 @@ pub fn read_credential(account: String) -> Result<Option<String>, String> { |
81 | 84 | CredentialsVault::get(acc).map_err(|e| e.to_string()) |
82 | 85 | } |
83 | 86 |
|
| 87 | +#[derive(Serialize)] |
| 88 | +#[serde(rename_all = "camelCase")] |
| 89 | +pub struct ProviderCheckResult { |
| 90 | + ok: bool, |
| 91 | + model_count: usize, |
| 92 | +} |
| 93 | + |
| 94 | +#[derive(Serialize)] |
| 95 | +pub struct ProviderModelsResult { |
| 96 | + models: Vec<String>, |
| 97 | +} |
| 98 | + |
| 99 | +#[tauri::command] |
| 100 | +pub async fn validate_provider_credentials(kind: String) -> Result<ProviderCheckResult, String> { |
| 101 | + let config = read_openai_provider_config(&kind)?; |
| 102 | + fetch_provider_models(&config) |
| 103 | + .await |
| 104 | + .map(|models| ProviderCheckResult { |
| 105 | + ok: true, |
| 106 | + model_count: models.len(), |
| 107 | + }) |
| 108 | +} |
| 109 | + |
| 110 | +#[tauri::command] |
| 111 | +pub async fn list_provider_models(kind: String) -> Result<ProviderModelsResult, String> { |
| 112 | + let config = read_openai_provider_config(&kind)?; |
| 113 | + fetch_provider_models(&config) |
| 114 | + .await |
| 115 | + .map(|models| ProviderModelsResult { models }) |
| 116 | +} |
| 117 | + |
| 118 | +struct ProviderConfig { |
| 119 | + base_url: String, |
| 120 | + api_key: String, |
| 121 | +} |
| 122 | + |
| 123 | +fn read_openai_provider_config(kind: &str) -> Result<ProviderConfig, String> { |
| 124 | + let (api_key_account, endpoint_account) = match kind { |
| 125 | + "llm" => (CredentialAccount::ArkApiKey, CredentialAccount::ArkEndpoint), |
| 126 | + "asr" => (CredentialAccount::AsrApiKey, CredentialAccount::AsrEndpoint), |
| 127 | + _ => return Err(format!("unknown provider kind: {kind}")), |
| 128 | + }; |
| 129 | + let api_key = CredentialsVault::get(api_key_account) |
| 130 | + .map_err(|e| e.to_string())? |
| 131 | + .unwrap_or_default(); |
| 132 | + let base_url = CredentialsVault::get(endpoint_account) |
| 133 | + .map_err(|e| e.to_string())? |
| 134 | + .unwrap_or_default(); |
| 135 | + if api_key.trim().is_empty() { |
| 136 | + return Err("API Key 为空".to_string()); |
| 137 | + } |
| 138 | + if base_url.trim().is_empty() { |
| 139 | + return Err("Endpoint 为空".to_string()); |
| 140 | + } |
| 141 | + Ok(ProviderConfig { base_url, api_key }) |
| 142 | +} |
| 143 | + |
| 144 | +async fn fetch_provider_models(config: &ProviderConfig) -> Result<Vec<String>, String> { |
| 145 | + let url = models_url(&config.base_url); |
| 146 | + log::info!("[provider-check] GET {url}"); |
| 147 | + let client = reqwest::Client::builder() |
| 148 | + .timeout(Duration::from_secs(15)) |
| 149 | + .build() |
| 150 | + .map_err(|e| format!("HTTP client 初始化失败: {e}"))?; |
| 151 | + let response = client |
| 152 | + .get(&url) |
| 153 | + .header("Authorization", format!("Bearer {}", config.api_key)) |
| 154 | + .send() |
| 155 | + .await |
| 156 | + .map_err(|e| { |
| 157 | + if e.is_timeout() { |
| 158 | + "请求超时".to_string() |
| 159 | + } else { |
| 160 | + format!("网络错误: {e}") |
| 161 | + } |
| 162 | + })?; |
| 163 | + let status = response.status(); |
| 164 | + let body = response |
| 165 | + .text() |
| 166 | + .await |
| 167 | + .map_err(|e| format!("读取响应失败: {e}"))?; |
| 168 | + if !status.is_success() { |
| 169 | + return Err(format!("providerHttpStatus:{}", status.as_u16())); |
| 170 | + } |
| 171 | + parse_model_ids(&body) |
| 172 | +} |
| 173 | + |
| 174 | +fn models_url(base_url: &str) -> String { |
| 175 | + let trimmed = base_url.trim().trim_end_matches('/'); |
| 176 | + if trimmed.ends_with("/models") { |
| 177 | + return trimmed.to_string(); |
| 178 | + } |
| 179 | + if let Some(prefix) = trimmed.strip_suffix("/chat/completions") { |
| 180 | + return format!("{prefix}/models"); |
| 181 | + } |
| 182 | + format!("{trimmed}/models") |
| 183 | +} |
| 184 | + |
| 185 | +fn parse_model_ids(body: &str) -> Result<Vec<String>, String> { |
| 186 | + let json: Value = |
| 187 | + serde_json::from_str(body).map_err(|e| format!("模型列表不是有效 JSON: {e}"))?; |
| 188 | + let data = json |
| 189 | + .get("data") |
| 190 | + .and_then(|v| v.as_array()) |
| 191 | + .ok_or_else(|| "模型列表缺少 data 数组".to_string())?; |
| 192 | + let mut models = data |
| 193 | + .iter() |
| 194 | + .filter_map(|item| item.get("id").and_then(|id| id.as_str())) |
| 195 | + .map(str::trim) |
| 196 | + .filter(|id| !id.is_empty()) |
| 197 | + .map(ToOwned::to_owned) |
| 198 | + .collect::<Vec<_>>(); |
| 199 | + models.sort(); |
| 200 | + models.dedup(); |
| 201 | + Ok(models) |
| 202 | +} |
| 203 | + |
84 | 204 | fn parse_account(s: &str) -> Result<CredentialAccount, String> { |
85 | 205 | match s { |
86 | 206 | "volcengine.app_key" => Ok(CredentialAccount::VolcengineAppKey), |
@@ -325,3 +445,28 @@ pub fn trigger_microphone_prompt(app: AppHandle) -> Result<(), String> { |
325 | 445 |
|
326 | 446 | #[allow(dead_code)] |
327 | 447 | fn _ensure_snapshot_used(_: CredentialsSnapshot) {} |
| 448 | + |
| 449 | +#[cfg(test)] |
| 450 | +mod tests { |
| 451 | + use super::{models_url, parse_model_ids}; |
| 452 | + |
| 453 | + #[test] |
| 454 | + fn models_url_accepts_base_or_chat_endpoint() { |
| 455 | + assert_eq!( |
| 456 | + models_url("https://api.openai.com/v1"), |
| 457 | + "https://api.openai.com/v1/models" |
| 458 | + ); |
| 459 | + assert_eq!( |
| 460 | + models_url("https://api.openai.com/v1/chat/completions"), |
| 461 | + "https://api.openai.com/v1/models" |
| 462 | + ); |
| 463 | + } |
| 464 | + |
| 465 | + #[test] |
| 466 | + fn parse_model_ids_sorts_and_deduplicates() { |
| 467 | + let models = |
| 468 | + parse_model_ids(r#"{ "data": [{ "id": "b" }, { "id": "a" }, { "id": "b" }] }"#) |
| 469 | + .unwrap(); |
| 470 | + assert_eq!(models, vec!["a".to_string(), "b".to_string()]); |
| 471 | + } |
| 472 | +} |
0 commit comments