| 1 | use std::path::Path; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use serde::{Deserialize, Serialize}; |
| 5 | use serde_json::Value; |
| 6 | |
| 7 | use codewhale_config::ProviderKind; |
| 8 | use codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL; |
| 9 | use codewhale_runtime::config::Config; |
| 10 | |
| 11 | pub const DEEPSEEK_ASR_MODEL: &str = "deepseek-asr"; |
| 12 | pub const DEEPSEEK_TTS_MODEL: &str = "deepseek-tts"; |
| 13 | pub const DEEPSEEK_OCR_MODEL: &str = "deepseek-ocr"; |
| 14 | pub const DEEPSEEK_ASR_MAX_BYTES: usize = 8 * 1024 * 1024; |
| 15 | pub const DEEPSEEK_OCR_MAX_BYTES: usize = 10 * 1024 * 1024; |
| 16 | pub const DEEPSEEK_TTS_MAX_CHARS: usize = 10_000; |
| 17 | pub const DEEPSEEK_TTS_VOICES: &[&str] = &["stella", "tide"]; |
| 18 | const DEEPSEEK_ASR_RESPONSE_MAX_BYTES: usize = 1024 * 1024; |
| 19 | const DEEPSEEK_TTS_RESPONSE_MAX_BYTES: usize = 32 * 1024 * 1024; |
| 20 | const DEEPSEEK_OCR_RESPONSE_MAX_BYTES: usize = 4 * 1024 * 1024; |
| 21 | |
| 22 | #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] |
| 23 | pub struct DeepseekAsrResponse { |
| 24 | #[serde(default)] |
| 25 | pub request_id: Option<String>, |
| 26 | pub text: String, |
| 27 | #[serde(default)] |
| 28 | pub duration_ms: Option<u64>, |
| 29 | } |
| 30 | |
| 31 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 32 | pub struct DeepseekTtsResponse { |
| 33 | pub audio_bytes: Vec<u8>, |
| 34 | pub content_type: String, |
| 35 | pub format: String, |
| 36 | pub model: String, |
| 37 | pub voice: String, |
| 38 | } |
| 39 | |
| 40 | #[derive(Debug, Deserialize)] |
| 41 | struct DeepseekOcrPage { |
| 42 | index: usize, |
| 43 | #[serde(default)] |
| 44 | text: String, |
| 45 | #[serde(default)] |
| 46 | finish_reason: Option<String>, |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Deserialize)] |
| 50 | struct DeepseekOcrPayload { |
| 51 | #[serde(default)] |
| 52 | id: Option<String>, |
| 53 | #[serde(default)] |
| 54 | object: Option<String>, |
| 55 | #[serde(default)] |
| 56 | page_count: Option<usize>, |
| 57 | #[serde(default)] |
| 58 | pages: Vec<DeepseekOcrPage>, |
| 59 | } |
| 60 | |
| 61 | #[derive(Serialize)] |
| 62 | struct DeepseekTtsPayload<'a> { |
| 63 | text: &'a str, |
| 64 | voice_id: &'a str, |
| 65 | format: &'a str, |
| 66 | filter_markdown: bool, |
| 67 | } |
| 68 | |
| 69 | fn strip_root_suffix(url: &str) -> String { |
| 70 | let mut current = url |
| 71 | .trim() |
| 72 | .split(['?', '#']) |
| 73 | .next() |
| 74 | .unwrap_or("") |
| 75 | .trim_end_matches('/'); |
| 76 | loop { |
| 77 | let mut stripped = false; |
| 78 | for suffix in ["/anthropic", "/beta", "/v1"] { |
| 79 | if let Some(prefix) = current.strip_suffix(suffix) { |
| 80 | current = prefix.trim_end_matches('/'); |
| 81 | stripped = true; |
| 82 | break; |
| 83 | } |
| 84 | } |
| 85 | if !stripped { |
| 86 | break; |
| 87 | } |
| 88 | } |
| 89 | current.to_string() |
| 90 | } |
| 91 | |
| 92 | pub fn deepseek_root_url(base_url: &str) -> String { |
| 93 | let stripped = strip_root_suffix(base_url); |
| 94 | if stripped.is_empty() { |
| 95 | strip_root_suffix(DEFAULT_DEEPSEEK_BASE_URL) |
| 96 | } else { |
| 97 | stripped |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | pub fn deepseek_tools_url(base_url: &str, tool: &str) -> String { |
| 102 | format!( |
| 103 | "{}/v1/tools/{}", |
| 104 | deepseek_root_url(base_url), |
| 105 | tool.trim().trim_start_matches('/') |
| 106 | ) |
| 107 | } |
| 108 | |
| 109 | pub fn normalize_deepseek_voice_id(voice: Option<&str>) -> Result<&'static str, String> { |
| 110 | let normalized = voice.unwrap_or("").trim().to_ascii_lowercase(); |
| 111 | match normalized.as_str() { |
| 112 | "" | "default" | "mimo_default" | "female_calm" | "stella" => Ok("stella"), |
| 113 | "tide" => Ok("tide"), |
| 114 | _ => Err(format!( |
| 115 | "unsupported DeepSeek TTS voice '{}' (allowed: {})", |
| 116 | voice.unwrap_or_default().trim(), |
| 117 | DEEPSEEK_TTS_VOICES.join(", ") |
| 118 | )), |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | pub fn normalize_deepseek_tts_format(format: &str) -> Result<(&'static str, &'static str), String> { |
| 123 | match format.trim().to_ascii_lowercase().as_str() { |
| 124 | "" | "wav" => Ok(("wav", "audio/wav")), |
| 125 | "pcm" | "pcm16" => Ok(("pcm", "audio/pcm")), |
| 126 | other => Err(format!( |
| 127 | "unsupported DeepSeek TTS format '{other}' (allowed: wav, pcm)" |
| 128 | )), |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | pub fn normalize_deepseek_asr_mime(mime_type: &str) -> Result<&'static str, String> { |
| 133 | let base = mime_type |
| 134 | .split(';') |
| 135 | .next() |
| 136 | .unwrap_or("") |
| 137 | .trim() |
| 138 | .to_ascii_lowercase(); |
| 139 | match base.as_str() { |
| 140 | "" | "audio/wav" | "audio/x-wav" | "audio/wave" => Ok("audio/wav"), |
| 141 | "audio/ogg" => Ok("audio/ogg"), |
| 142 | other => Err(format!( |
| 143 | "unsupported DeepSeek ASR mime type '{other}' (allowed: audio/wav, audio/ogg)" |
| 144 | )), |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | pub fn normalize_deepseek_ocr_mime(mime_type: &str) -> Result<&'static str, String> { |
| 149 | let base = mime_type |
| 150 | .split(';') |
| 151 | .next() |
| 152 | .unwrap_or("") |
| 153 | .trim() |
| 154 | .to_ascii_lowercase(); |
| 155 | match base.as_str() { |
| 156 | "image/png" => Ok("image/png"), |
| 157 | "image/jpeg" | "image/jpg" => Ok("image/jpeg"), |
| 158 | "image/tiff" | "image/tif" => Ok("image/tiff"), |
| 159 | "application/pdf" => Ok("application/pdf"), |
| 160 | other => Err(format!( |
| 161 | "unsupported DeepSeek OCR mime type '{other}' (allowed: image/png, image/jpeg, image/tiff, application/pdf)" |
| 162 | )), |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | pub fn resolve_deepseek_config_auth(config: &Config) -> Option<(String, String)> { |
| 167 | let read = || { |
| 168 | if let Ok(identity) = config.active_provider_identity() |
| 169 | && matches!( |
| 170 | identity.provider, |
| 171 | ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic |
| 172 | ) |
| 173 | { |
| 174 | let api_key = config |
| 175 | .active_route_api_key_read_only() |
| 176 | .ok() |
| 177 | .map(|value| value.trim().to_string()) |
| 178 | .filter(|value| !value.is_empty())?; |
| 179 | return Some((deepseek_root_url(&config.active_route_base_url()), api_key)); |
| 180 | } |
| 181 | |
| 182 | if codewhale_runtime::config::cli_api_key_source().as_deref() == Some("cli") |
| 183 | || codewhale_runtime::config::explicit_cli_api_key_override().is_some() |
| 184 | { |
| 185 | return None; |
| 186 | } |
| 187 | |
| 188 | for candidate in [ProviderKind::Deepseek, ProviderKind::DeepseekAnthropic] { |
| 189 | let mut scoped = config.clone(); |
| 190 | scoped.provider = Some(candidate.as_str().to_string()); |
| 191 | let Ok(identity) = scoped.active_provider_identity() else { |
| 192 | continue; |
| 193 | }; |
| 194 | let Some(api_key) = scoped |
| 195 | .active_route_api_key_read_only() |
| 196 | .ok() |
| 197 | .map(|value| value.trim().to_string()) |
| 198 | .filter(|value| !value.is_empty()) |
| 199 | else { |
| 200 | continue; |
| 201 | }; |
| 202 | let base_url = scoped.base_url_for_route(&identity); |
| 203 | return Some((deepseek_root_url(&base_url), api_key)); |
| 204 | } |
| 205 | None |
| 206 | }; |
| 207 | #[cfg(any(test, feature = "test-support"))] |
| 208 | { |
| 209 | crate::test_support::with_test_env_lock(read) |
| 210 | } |
| 211 | #[cfg(not(any(test, feature = "test-support")))] |
| 212 | { |
| 213 | read() |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | pub fn deepseek_ocr_explicitly_enabled() -> bool { |
| 218 | let read = || { |
| 219 | std::env::var("CODEWHALE_DEEPSEEK_OCR") |
| 220 | .ok() |
| 221 | .is_some_and(|value| { |
| 222 | matches!( |
| 223 | value.trim().to_ascii_lowercase().as_str(), |
| 224 | "1" | "true" | "yes" | "on" |
| 225 | ) |
| 226 | }) |
| 227 | }; |
| 228 | #[cfg(any(test, feature = "test-support"))] |
| 229 | { |
| 230 | crate::test_support::with_test_env_lock(read) |
| 231 | } |
| 232 | #[cfg(not(any(test, feature = "test-support")))] |
| 233 | { |
| 234 | read() |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | pub fn resolve_deepseek_ocr_auth() -> Option<(String, String)> { |
| 239 | let read = || { |
| 240 | if !deepseek_ocr_explicitly_enabled() { |
| 241 | return None; |
| 242 | } |
| 243 | let api_key = std::env::var("DEEPSEEK_API_KEY") |
| 244 | .ok() |
| 245 | .map(|value| codewhale_secrets::normalize_api_key(&value)) |
| 246 | .filter(|value| !value.trim().is_empty())?; |
| 247 | let base_url = std::env::var("DEEPSEEK_BASE_URL") |
| 248 | .ok() |
| 249 | .map(|value| value.trim().to_string()) |
| 250 | .filter(|value| !value.is_empty()) |
| 251 | .unwrap_or_else(|| DEFAULT_DEEPSEEK_BASE_URL.to_string()); |
| 252 | Some((deepseek_root_url(&base_url), api_key)) |
| 253 | }; |
| 254 | #[cfg(any(test, feature = "test-support"))] |
| 255 | { |
| 256 | crate::test_support::with_test_env_lock(read) |
| 257 | } |
| 258 | #[cfg(not(any(test, feature = "test-support")))] |
| 259 | { |
| 260 | read() |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | fn sanitize_multipart_header_value(raw: &str, fallback: &str) -> String { |
| 265 | let cleaned: String = raw |
| 266 | .chars() |
| 267 | .map(|ch| match ch { |
| 268 | '\r' | '\n' | '"' | '\\' | '/' => '_', |
| 269 | c if c.is_control() => '_', |
| 270 | _ => ch, |
| 271 | }) |
| 272 | .collect(); |
| 273 | let trimmed = cleaned.trim(); |
| 274 | if trimmed.is_empty() { |
| 275 | fallback.to_string() |
| 276 | } else { |
| 277 | trimmed.to_string() |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | fn build_multipart_body( |
| 282 | fields: &[(&str, &str)], |
| 283 | file_field: &str, |
| 284 | file_name: &str, |
| 285 | file_mime: &str, |
| 286 | file_bytes: &[u8], |
| 287 | ) -> (String, Vec<u8>) { |
| 288 | let boundary = format!("----codewhale-boundary-{}", uuid::Uuid::new_v4().simple()); |
| 289 | let safe_name = sanitize_multipart_header_value(file_name, "upload.bin"); |
| 290 | let mut body = Vec::with_capacity(file_bytes.len() + fields.len() * 128 + 256); |
| 291 | |
| 292 | for (name, value) in fields { |
| 293 | let safe_field = sanitize_multipart_header_value(name, "field"); |
| 294 | body.extend_from_slice(b"--"); |
| 295 | body.extend_from_slice(boundary.as_bytes()); |
| 296 | body.extend_from_slice(b"\r\nContent-Disposition: form-data; name=\""); |
| 297 | body.extend_from_slice(safe_field.as_bytes()); |
| 298 | body.extend_from_slice(b"\"\r\n\r\n"); |
| 299 | body.extend_from_slice(value.as_bytes()); |
| 300 | body.extend_from_slice(b"\r\n"); |
| 301 | } |
| 302 | |
| 303 | body.extend_from_slice(b"--"); |
| 304 | body.extend_from_slice(boundary.as_bytes()); |
| 305 | body.extend_from_slice(b"\r\nContent-Disposition: form-data; name=\""); |
| 306 | body.extend_from_slice(file_field.as_bytes()); |
| 307 | body.extend_from_slice(b"\"; filename=\""); |
| 308 | body.extend_from_slice(safe_name.as_bytes()); |
| 309 | body.extend_from_slice(b"\"\r\nContent-Type: "); |
| 310 | body.extend_from_slice(file_mime.as_bytes()); |
| 311 | body.extend_from_slice(b"\r\n\r\n"); |
| 312 | body.extend_from_slice(file_bytes); |
| 313 | body.extend_from_slice(b"\r\n--"); |
| 314 | body.extend_from_slice(boundary.as_bytes()); |
| 315 | body.extend_from_slice(b"--\r\n"); |
| 316 | |
| 317 | (format!("multipart/form-data; boundary={boundary}"), body) |
| 318 | } |
| 319 | |
| 320 | fn standalone_http_client() -> Result<reqwest::Client, String> { |
| 321 | crate::platform_client_builder() |
| 322 | .timeout(Duration::from_secs(60)) |
| 323 | .redirect(reqwest::redirect::Policy::none()) |
| 324 | .retry(reqwest::retry::never()) |
| 325 | .build() |
| 326 | .map_err(|err| { |
| 327 | format!( |
| 328 | "failed to build DeepSeek HTTP client: {}", |
| 329 | err.without_url() |
| 330 | ) |
| 331 | }) |
| 332 | } |
| 333 | |
| 334 | fn redact_secret(text: &str, api_key: &str) -> String { |
| 335 | if api_key.trim().is_empty() { |
| 336 | text.to_string() |
| 337 | } else { |
| 338 | text.replace(api_key, "[redacted]") |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | fn truncate_utf8_prefix(text: &str, max_bytes: usize) -> &str { |
| 343 | if text.len() <= max_bytes { |
| 344 | return text; |
| 345 | } |
| 346 | let mut end = max_bytes; |
| 347 | while end > 0 && !text.is_char_boundary(end) { |
| 348 | end -= 1; |
| 349 | } |
| 350 | &text[..end] |
| 351 | } |
| 352 | |
| 353 | async fn read_bounded_response_bytes( |
| 354 | response: reqwest::Response, |
| 355 | max_bytes: usize, |
| 356 | label: &str, |
| 357 | api_key: &str, |
| 358 | ) -> Result<Vec<u8>, String> { |
| 359 | use futures_util::StreamExt; |
| 360 | |
| 361 | if let Some(len) = response.content_length() |
| 362 | && len > max_bytes as u64 |
| 363 | { |
| 364 | return Err(format!( |
| 365 | "{label} response exceeded maximum of {max_bytes} bytes" |
| 366 | )); |
| 367 | } |
| 368 | let initial = response |
| 369 | .content_length() |
| 370 | .and_then(|len| usize::try_from(len).ok()) |
| 371 | .map(|len| len.min(max_bytes)) |
| 372 | .unwrap_or(0); |
| 373 | let mut stream = response.bytes_stream(); |
| 374 | let mut buf = Vec::with_capacity(initial.min(64 * 1024)); |
| 375 | while let Some(chunk) = stream.next().await { |
| 376 | let chunk = chunk.map_err(|err| { |
| 377 | redact_secret( |
| 378 | &format!("failed to read {label} response: {}", err.without_url()), |
| 379 | api_key, |
| 380 | ) |
| 381 | })?; |
| 382 | if buf.len().saturating_add(chunk.len()) > max_bytes { |
| 383 | return Err(format!( |
| 384 | "{label} response exceeded maximum of {max_bytes} bytes" |
| 385 | )); |
| 386 | } |
| 387 | buf.extend_from_slice(&chunk); |
| 388 | } |
| 389 | Ok(buf) |
| 390 | } |
| 391 | |
| 392 | fn format_error_response(status: reqwest::StatusCode, body: &str, api_key: &str) -> String { |
| 393 | let raw_detail = serde_json::from_str::<Value>(body) |
| 394 | .ok() |
| 395 | .and_then(|value| { |
| 396 | value |
| 397 | .pointer("/error/message") |
| 398 | .and_then(Value::as_str) |
| 399 | .or_else(|| value.get("message").and_then(Value::as_str)) |
| 400 | .map(str::to_string) |
| 401 | }) |
| 402 | .unwrap_or_else(|| body.trim().to_string()); |
| 403 | let redacted = redact_secret(raw_detail.trim(), api_key); |
| 404 | let summary = if redacted.len() > 512 { |
| 405 | format!("{}...", truncate_utf8_prefix(&redacted, 512)) |
| 406 | } else { |
| 407 | redacted |
| 408 | }; |
| 409 | if summary.is_empty() { |
| 410 | format!("DeepSeek Tools API returned HTTP {}", status.as_u16()) |
| 411 | } else { |
| 412 | format!( |
| 413 | "DeepSeek Tools API returned HTTP {}: {summary}", |
| 414 | status.as_u16() |
| 415 | ) |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | pub fn validate_deepseek_tts_inputs( |
| 420 | model: Option<&str>, |
| 421 | text: &str, |
| 422 | instruction: Option<&str>, |
| 423 | voice: Option<&str>, |
| 424 | format: &str, |
| 425 | ) -> Result<(String, &'static str, &'static str, &'static str), String> { |
| 426 | let trimmed_text = text.trim(); |
| 427 | if trimmed_text.is_empty() { |
| 428 | return Err("speech text cannot be empty".to_string()); |
| 429 | } |
| 430 | if text.chars().count() > DEEPSEEK_TTS_MAX_CHARS { |
| 431 | return Err(format!( |
| 432 | "DeepSeek TTS text exceeds maximum of {DEEPSEEK_TTS_MAX_CHARS} characters" |
| 433 | )); |
| 434 | } |
| 435 | if instruction.is_some_and(|value| !value.trim().is_empty()) { |
| 436 | return Err( |
| 437 | "DeepSeek TTS does not support voice instructions or voice design prompts".to_string(), |
| 438 | ); |
| 439 | } |
| 440 | if let Some(raw_voice) = voice |
| 441 | && raw_voice.trim_start().starts_with("data:") |
| 442 | { |
| 443 | return Err("DeepSeek TTS does not support voice cloning data URIs".to_string()); |
| 444 | } |
| 445 | let normalized_model = match model.unwrap_or("").trim().to_ascii_lowercase().as_str() { |
| 446 | "" | "auto" | "deepseek-tts" | "mimo-v2.5-tts" | "mimo-v2-tts" => DEEPSEEK_TTS_MODEL, |
| 447 | other if other.contains("voiceclone") || other.contains("voicedesign") => { |
| 448 | return Err(format!( |
| 449 | "DeepSeek TTS does not support model '{other}'; use '{DEEPSEEK_TTS_MODEL}'" |
| 450 | )); |
| 451 | } |
| 452 | other => { |
| 453 | return Err(format!( |
| 454 | "unsupported DeepSeek TTS model '{other}'; use '{DEEPSEEK_TTS_MODEL}'" |
| 455 | )); |
| 456 | } |
| 457 | }; |
| 458 | let voice_id = normalize_deepseek_voice_id(voice)?; |
| 459 | let (wire_format, content_type) = normalize_deepseek_tts_format(format)?; |
| 460 | Ok(( |
| 461 | normalized_model.to_string(), |
| 462 | voice_id, |
| 463 | wire_format, |
| 464 | content_type, |
| 465 | )) |
| 466 | } |
| 467 | |
| 468 | pub async fn transcribe_deepseek_bytes( |
| 469 | base_url: &str, |
| 470 | api_key: &str, |
| 471 | audio_bytes: &[u8], |
| 472 | file_name: &str, |
| 473 | mime_type: &str, |
| 474 | language: Option<&str>, |
| 475 | ) -> Result<DeepseekAsrResponse, String> { |
| 476 | if api_key.trim().is_empty() { |
| 477 | return Err("DeepSeek ASR requires a configured API key".to_string()); |
| 478 | } |
| 479 | if audio_bytes.is_empty() { |
| 480 | return Err("DeepSeek ASR audio payload cannot be empty".to_string()); |
| 481 | } |
| 482 | if audio_bytes.len() > DEEPSEEK_ASR_MAX_BYTES { |
| 483 | return Err(format!( |
| 484 | "DeepSeek ASR audio payload exceeds maximum of {DEEPSEEK_ASR_MAX_BYTES} bytes" |
| 485 | )); |
| 486 | } |
| 487 | let canonical_mime = normalize_deepseek_asr_mime(mime_type)?; |
| 488 | let default_name = if canonical_mime == "audio/ogg" { |
| 489 | "voice.ogg" |
| 490 | } else { |
| 491 | "voice.wav" |
| 492 | }; |
| 493 | let chosen_name = if file_name.trim().is_empty() { |
| 494 | default_name |
| 495 | } else { |
| 496 | file_name |
| 497 | }; |
| 498 | let mut fields = Vec::new(); |
| 499 | let cleaned_language = language |
| 500 | .map(str::trim) |
| 501 | .filter(|value| !value.is_empty()) |
| 502 | .map(str::to_string); |
| 503 | if let Some(ref lang) = cleaned_language { |
| 504 | fields.push(("language", lang.as_str())); |
| 505 | } |
| 506 | let (content_type, body) = |
| 507 | build_multipart_body(&fields, "file", chosen_name, canonical_mime, audio_bytes); |
| 508 | let url = deepseek_tools_url(base_url, "asr"); |
| 509 | let client = standalone_http_client()?; |
| 510 | let response = client |
| 511 | .post(&url) |
| 512 | .bearer_auth(api_key) |
| 513 | .header(reqwest::header::CONTENT_TYPE, content_type) |
| 514 | .body(body) |
| 515 | .send() |
| 516 | .await |
| 517 | .map_err(|err| { |
| 518 | redact_secret( |
| 519 | &format!("DeepSeek ASR request failed: {}", err.without_url()), |
| 520 | api_key, |
| 521 | ) |
| 522 | })?; |
| 523 | |
| 524 | let status = response.status(); |
| 525 | if !status.is_success() { |
| 526 | let error_text = crate::client::wire::bounded_error_text( |
| 527 | response, |
| 528 | crate::client::wire::ERROR_BODY_MAX_BYTES, |
| 529 | ) |
| 530 | .await; |
| 531 | return Err(format_error_response(status, &error_text, api_key)); |
| 532 | } |
| 533 | let response_bytes = read_bounded_response_bytes( |
| 534 | response, |
| 535 | DEEPSEEK_ASR_RESPONSE_MAX_BYTES, |
| 536 | "DeepSeek ASR", |
| 537 | api_key, |
| 538 | ) |
| 539 | .await?; |
| 540 | let response_text = String::from_utf8(response_bytes) |
| 541 | .map_err(|err| format!("DeepSeek ASR response was not valid UTF-8: {err}"))?; |
| 542 | serde_json::from_str::<DeepseekAsrResponse>(&response_text) |
| 543 | .map_err(|err| format!("failed to parse DeepSeek ASR response JSON: {err}")) |
| 544 | } |
| 545 | |
| 546 | pub async fn synthesize_deepseek_with_client( |
| 547 | http_client: &reqwest::Client, |
| 548 | base_url: &str, |
| 549 | api_key: &str, |
| 550 | request: crate::client::SpeechSynthesisRequest, |
| 551 | ) -> anyhow::Result<crate::client::SpeechSynthesisResponse> { |
| 552 | synthesize_deepseek_with_client_and_options(http_client, base_url, api_key, request, true).await |
| 553 | } |
| 554 | |
| 555 | pub async fn synthesize_deepseek_with_client_and_options( |
| 556 | http_client: &reqwest::Client, |
| 557 | base_url: &str, |
| 558 | api_key: &str, |
| 559 | request: crate::client::SpeechSynthesisRequest, |
| 560 | filter_markdown: bool, |
| 561 | ) -> anyhow::Result<crate::client::SpeechSynthesisResponse> { |
| 562 | if api_key.trim().is_empty() { |
| 563 | anyhow::bail!("DeepSeek TTS requires a configured API key"); |
| 564 | } |
| 565 | let (model, voice_id, wire_format, _content_type) = validate_deepseek_tts_inputs( |
| 566 | Some(request.model.as_str()), |
| 567 | &request.text, |
| 568 | request.instruction.as_deref(), |
| 569 | request.voice.as_deref(), |
| 570 | &request.audio_format, |
| 571 | ) |
| 572 | .map_err(anyhow::Error::msg)?; |
| 573 | let url = deepseek_tools_url(base_url, "tts"); |
| 574 | let payload = DeepseekTtsPayload { |
| 575 | text: &request.text, |
| 576 | voice_id, |
| 577 | format: wire_format, |
| 578 | filter_markdown, |
| 579 | }; |
| 580 | let response = http_client |
| 581 | .post(&url) |
| 582 | .bearer_auth(api_key) |
| 583 | .json(&payload) |
| 584 | .send() |
| 585 | .await |
| 586 | .map_err(|err| { |
| 587 | anyhow::anyhow!(redact_secret( |
| 588 | &format!("DeepSeek TTS request failed: {}", err.without_url()), |
| 589 | api_key |
| 590 | )) |
| 591 | })?; |
| 592 | let status = response.status(); |
| 593 | if !status.is_success() { |
| 594 | let body = crate::client::wire::bounded_error_text( |
| 595 | response, |
| 596 | crate::client::wire::ERROR_BODY_MAX_BYTES, |
| 597 | ) |
| 598 | .await; |
| 599 | anyhow::bail!("{}", format_error_response(status, &body, api_key)); |
| 600 | } |
| 601 | let audio_bytes = read_bounded_response_bytes( |
| 602 | response, |
| 603 | DEEPSEEK_TTS_RESPONSE_MAX_BYTES, |
| 604 | "DeepSeek TTS", |
| 605 | api_key, |
| 606 | ) |
| 607 | .await |
| 608 | .map_err(anyhow::Error::msg)?; |
| 609 | if audio_bytes.is_empty() { |
| 610 | anyhow::bail!("DeepSeek TTS response audio body was empty"); |
| 611 | } |
| 612 | Ok(crate::client::SpeechSynthesisResponse { |
| 613 | model, |
| 614 | audio_format: wire_format.to_string(), |
| 615 | audio_bytes, |
| 616 | transcript: None, |
| 617 | voice: Some(voice_id.to_string()), |
| 618 | }) |
| 619 | } |
| 620 | |
| 621 | pub async fn synthesize_deepseek_bytes( |
| 622 | base_url: &str, |
| 623 | api_key: &str, |
| 624 | text: &str, |
| 625 | voice: Option<&str>, |
| 626 | format: &str, |
| 627 | ) -> Result<DeepseekTtsResponse, String> { |
| 628 | synthesize_deepseek_bytes_with_options(base_url, api_key, text, voice, format, true).await |
| 629 | } |
| 630 | |
| 631 | pub async fn synthesize_deepseek_bytes_with_options( |
| 632 | base_url: &str, |
| 633 | api_key: &str, |
| 634 | text: &str, |
| 635 | voice: Option<&str>, |
| 636 | format: &str, |
| 637 | filter_markdown: bool, |
| 638 | ) -> Result<DeepseekTtsResponse, String> { |
| 639 | let client = standalone_http_client()?; |
| 640 | let (model, voice_id, wire_format, content_type) = |
| 641 | validate_deepseek_tts_inputs(Some(DEEPSEEK_TTS_MODEL), text, None, voice, format)?; |
| 642 | let response = synthesize_deepseek_with_client_and_options( |
| 643 | &client, |
| 644 | base_url, |
| 645 | api_key, |
| 646 | crate::client::SpeechSynthesisRequest { |
| 647 | model, |
| 648 | text: text.to_string(), |
| 649 | instruction: None, |
| 650 | audio_format: wire_format.to_string(), |
| 651 | voice: Some(voice_id.to_string()), |
| 652 | }, |
| 653 | filter_markdown, |
| 654 | ) |
| 655 | .await |
| 656 | .map_err(|err| err.to_string())?; |
| 657 | Ok(DeepseekTtsResponse { |
| 658 | audio_bytes: response.audio_bytes, |
| 659 | content_type: content_type.to_string(), |
| 660 | format: response.audio_format, |
| 661 | model: response.model, |
| 662 | voice: response.voice.unwrap_or_else(|| voice_id.to_string()), |
| 663 | }) |
| 664 | } |
| 665 | |
| 666 | pub fn ocr_mime_for_path(_path: &Path, bytes: &[u8]) -> Result<&'static str, String> { |
| 667 | if bytes.len() >= 12 && bytes.starts_with(b"\x89PNG\r\n\x1a\n") { |
| 668 | return Ok("image/png"); |
| 669 | } |
| 670 | if bytes.len() >= 12 && bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { |
| 671 | return Ok("image/jpeg"); |
| 672 | } |
| 673 | if bytes.len() >= 12 && (bytes.starts_with(b"II*\x00") || bytes.starts_with(b"MM\x00*")) { |
| 674 | return Ok("image/tiff"); |
| 675 | } |
| 676 | if bytes.len() >= 5 && bytes.starts_with(b"%PDF-") { |
| 677 | return Ok("application/pdf"); |
| 678 | } |
| 679 | Err("unsupported file signature for DeepSeek OCR (allowed: png, jpeg, tiff, pdf)".to_string()) |
| 680 | } |
| 681 | |
| 682 | pub async fn ocr_deepseek_bytes( |
| 683 | base_url: &str, |
| 684 | api_key: &str, |
| 685 | file_bytes: &[u8], |
| 686 | file_name: &str, |
| 687 | mime_type: &str, |
| 688 | ) -> Result<String, String> { |
| 689 | if api_key.trim().is_empty() { |
| 690 | return Err("DeepSeek OCR requires a configured API key".to_string()); |
| 691 | } |
| 692 | if file_bytes.is_empty() { |
| 693 | return Err("DeepSeek OCR input file cannot be empty".to_string()); |
| 694 | } |
| 695 | if file_bytes.len() > DEEPSEEK_OCR_MAX_BYTES { |
| 696 | return Err(format!( |
| 697 | "DeepSeek OCR input exceeds maximum of {DEEPSEEK_OCR_MAX_BYTES} bytes" |
| 698 | )); |
| 699 | } |
| 700 | let canonical_mime = normalize_deepseek_ocr_mime(mime_type)?; |
| 701 | let fields = [("purpose", "text_recognition")]; |
| 702 | let (content_type, body) = build_multipart_body( |
| 703 | &fields, |
| 704 | "file", |
| 705 | if file_name.trim().is_empty() { |
| 706 | "document" |
| 707 | } else { |
| 708 | file_name |
| 709 | }, |
| 710 | canonical_mime, |
| 711 | file_bytes, |
| 712 | ); |
| 713 | let url = deepseek_tools_url(base_url, "ocr"); |
| 714 | let client = standalone_http_client()?; |
| 715 | let response = client |
| 716 | .post(&url) |
| 717 | .bearer_auth(api_key) |
| 718 | .header(reqwest::header::CONTENT_TYPE, content_type) |
| 719 | .body(body) |
| 720 | .send() |
| 721 | .await |
| 722 | .map_err(|err| { |
| 723 | redact_secret( |
| 724 | &format!("DeepSeek OCR request failed: {}", err.without_url()), |
| 725 | api_key, |
| 726 | ) |
| 727 | })?; |
| 728 | let status = response.status(); |
| 729 | if !status.is_success() { |
| 730 | let error_text = crate::client::wire::bounded_error_text( |
| 731 | response, |
| 732 | crate::client::wire::ERROR_BODY_MAX_BYTES, |
| 733 | ) |
| 734 | .await; |
| 735 | return Err(format_error_response(status, &error_text, api_key)); |
| 736 | } |
| 737 | let raw_bytes = read_bounded_response_bytes( |
| 738 | response, |
| 739 | DEEPSEEK_OCR_RESPONSE_MAX_BYTES, |
| 740 | "DeepSeek OCR", |
| 741 | api_key, |
| 742 | ) |
| 743 | .await?; |
| 744 | let raw = String::from_utf8(raw_bytes) |
| 745 | .map_err(|err| format!("DeepSeek OCR response was not valid UTF-8: {err}"))?; |
| 746 | let mut payload = serde_json::from_str::<DeepseekOcrPayload>(raw.trim()) |
| 747 | .map_err(|err| format!("failed to parse DeepSeek OCR response JSON: {err}"))?; |
| 748 | let _ = (&payload.id, &payload.object, payload.page_count); |
| 749 | payload.pages.sort_by_key(|page| page.index); |
| 750 | let text = payload |
| 751 | .pages |
| 752 | .into_iter() |
| 753 | .map(|page| { |
| 754 | let _ = page.finish_reason; |
| 755 | page.text.trim().to_string() |
| 756 | }) |
| 757 | .filter(|text| !text.is_empty()) |
| 758 | .collect::<Vec<_>>() |
| 759 | .join("\n\n"); |
| 760 | Ok(text) |
| 761 | } |
| 762 | |
| 763 | #[cfg(test)] |
| 764 | mod tests { |
| 765 | use super::*; |
| 766 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 767 | use wiremock::matchers::{header, method, path}; |
| 768 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 769 | |
| 770 | #[test] |
| 771 | fn root_url_strips_suffixes_and_falls_back_to_default() { |
| 772 | assert_eq!( |
| 773 | deepseek_root_url("https://api.deepseek.com/v1/"), |
| 774 | "https://api.deepseek.com" |
| 775 | ); |
| 776 | assert_eq!( |
| 777 | deepseek_root_url("https://api.deepseek.com/anthropic"), |
| 778 | "https://api.deepseek.com" |
| 779 | ); |
| 780 | assert_eq!( |
| 781 | deepseek_root_url("https://api.deepseek.com/beta"), |
| 782 | "https://api.deepseek.com" |
| 783 | ); |
| 784 | assert_eq!(deepseek_root_url(" "), "https://api.deepseek.com"); |
| 785 | assert_eq!( |
| 786 | deepseek_root_url("https://api.deepseek.com/anthropic/v1"), |
| 787 | "https://api.deepseek.com" |
| 788 | ); |
| 789 | assert_eq!( |
| 790 | deepseek_root_url("https://api.deepseek.com/beta/v1?foo=bar"), |
| 791 | "https://api.deepseek.com" |
| 792 | ); |
| 793 | assert_eq!( |
| 794 | deepseek_tools_url("https://api.deepseek.com/v1", "asr"), |
| 795 | "https://api.deepseek.com/v1/tools/asr" |
| 796 | ); |
| 797 | } |
| 798 | |
| 799 | #[test] |
| 800 | fn voice_and_format_normalization() { |
| 801 | assert_eq!(normalize_deepseek_voice_id(None).unwrap(), "stella"); |
| 802 | assert_eq!( |
| 803 | normalize_deepseek_voice_id(Some("mimo_default")).unwrap(), |
| 804 | "stella" |
| 805 | ); |
| 806 | assert_eq!( |
| 807 | normalize_deepseek_voice_id(Some("female_calm")).unwrap(), |
| 808 | "stella" |
| 809 | ); |
| 810 | assert_eq!(normalize_deepseek_voice_id(Some("tide")).unwrap(), "tide"); |
| 811 | assert!(normalize_deepseek_voice_id(Some("unknown")).is_err()); |
| 812 | |
| 813 | assert_eq!( |
| 814 | normalize_deepseek_tts_format("wav").unwrap(), |
| 815 | ("wav", "audio/wav") |
| 816 | ); |
| 817 | assert_eq!( |
| 818 | normalize_deepseek_tts_format("pcm16").unwrap(), |
| 819 | ("pcm", "audio/pcm") |
| 820 | ); |
| 821 | assert!(normalize_deepseek_tts_format("mp3").is_err()); |
| 822 | } |
| 823 | |
| 824 | #[tokio::test] |
| 825 | async fn asr_wiremock_sends_multipart_and_parses_response() { |
| 826 | let server = MockServer::start().await; |
| 827 | Mock::given(method("POST")) |
| 828 | .and(path("/v1/tools/asr")) |
| 829 | .and(header("authorization", "Bearer ds-secret")) |
| 830 | .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ |
| 831 | "request_id": "req-1", |
| 832 | "text": "hello deepseek", |
| 833 | "duration_ms": 1240 |
| 834 | }))) |
| 835 | .mount(&server) |
| 836 | .await; |
| 837 | |
| 838 | let res = transcribe_deepseek_bytes( |
| 839 | &format!("{}/v1", server.uri()), |
| 840 | "ds-secret", |
| 841 | b"RIFFdata", |
| 842 | "voice.wav", |
| 843 | "audio/x-wav", |
| 844 | Some("en"), |
| 845 | ) |
| 846 | .await |
| 847 | .expect("asr succeeds"); |
| 848 | |
| 849 | assert_eq!(res.text, "hello deepseek"); |
| 850 | assert_eq!(res.duration_ms, Some(1240)); |
| 851 | let received = server.received_requests().await.expect("requests"); |
| 852 | let raw = String::from_utf8_lossy(&received[0].body); |
| 853 | assert!(raw.contains("name=\"language\"\r\n\r\nen\r\n")); |
| 854 | assert!(raw.contains("name=\"file\"; filename=\"voice.wav\"")); |
| 855 | assert!(raw.contains("Content-Type: audio/wav")); |
| 856 | } |
| 857 | |
| 858 | #[tokio::test] |
| 859 | async fn tts_wiremock_sends_json_and_rejects_clone_or_overflow() { |
| 860 | let server = MockServer::start().await; |
| 861 | Mock::given(method("POST")) |
| 862 | .and(path("/v1/tools/tts")) |
| 863 | .and(header("authorization", "Bearer ds-secret")) |
| 864 | .respond_with(ResponseTemplate::new(200).set_body_bytes(b"RIFF_WAV".to_vec())) |
| 865 | .mount(&server) |
| 866 | .await; |
| 867 | |
| 868 | let out = synthesize_deepseek_bytes( |
| 869 | &format!("{}/anthropic", server.uri()), |
| 870 | "ds-secret", |
| 871 | "Read **this** aloud", |
| 872 | Some("tide"), |
| 873 | "wav", |
| 874 | ) |
| 875 | .await |
| 876 | .expect("tts succeeds"); |
| 877 | assert_eq!(out.audio_bytes, b"RIFF_WAV"); |
| 878 | assert_eq!(out.content_type, "audio/wav"); |
| 879 | assert_eq!(out.voice, "tide"); |
| 880 | |
| 881 | let received = server.received_requests().await.expect("requests"); |
| 882 | let sent: Value = serde_json::from_slice(&received[0].body).unwrap(); |
| 883 | assert_eq!( |
| 884 | sent, |
| 885 | serde_json::json!({ |
| 886 | "text": "Read **this** aloud", |
| 887 | "voice_id": "tide", |
| 888 | "format": "wav", |
| 889 | "filter_markdown": true |
| 890 | }) |
| 891 | ); |
| 892 | |
| 893 | assert!( |
| 894 | validate_deepseek_tts_inputs( |
| 895 | Some("deepseek-tts"), |
| 896 | "hi", |
| 897 | None, |
| 898 | Some("data:audio/wav;base64,AA=="), |
| 899 | "wav" |
| 900 | ) |
| 901 | .is_err() |
| 902 | ); |
| 903 | let too_long = "a".repeat(DEEPSEEK_TTS_MAX_CHARS + 1); |
| 904 | assert!(validate_deepseek_tts_inputs(None, &too_long, None, None, "wav").is_err()); |
| 905 | } |
| 906 | |
| 907 | #[tokio::test] |
| 908 | async fn ocr_multipart_puts_purpose_before_file_and_strips_keepalives() { |
| 909 | let server = MockServer::start().await; |
| 910 | Mock::given(method("POST")) |
| 911 | .and(path("/v1/tools/ocr")) |
| 912 | .and(header("authorization", "Bearer ds-secret")) |
| 913 | .respond_with(ResponseTemplate::new(200).set_body_string( |
| 914 | "\n\n\n{\"id\":\"ocr-1\",\"object\":\"ocr\",\"page_count\":2,\"pages\":[{\"index\":1,\"text\":\"Page two\",\"finish_reason\":\"stop\"},{\"index\":0,\"text\":\"Page one\",\"finish_reason\":\"stop\"}]}", |
| 915 | )) |
| 916 | .mount(&server) |
| 917 | .await; |
| 918 | |
| 919 | let text = ocr_deepseek_bytes( |
| 920 | &server.uri(), |
| 921 | "ds-secret", |
| 922 | b"\x89PNG\r\n\x1a\npayload", |
| 923 | "shot.png", |
| 924 | "image/png", |
| 925 | ) |
| 926 | .await |
| 927 | .expect("ocr succeeds"); |
| 928 | assert_eq!(text, "Page one\n\nPage two"); |
| 929 | |
| 930 | let received = server.received_requests().await.expect("requests"); |
| 931 | let raw = String::from_utf8_lossy(&received[0].body); |
| 932 | let purpose_pos = raw |
| 933 | .find("name=\"purpose\"\r\n\r\ntext_recognition") |
| 934 | .unwrap(); |
| 935 | let file_pos = raw.find("name=\"file\"; filename=\"shot.png\"").unwrap(); |
| 936 | assert!(purpose_pos < file_pos); |
| 937 | assert!( |
| 938 | ocr_mime_for_path(Path::new("notes.png"), b"plain text pretending to be png").is_err() |
| 939 | ); |
| 940 | assert!(ocr_mime_for_path(Path::new("short.png"), b"\x89PNG\r\n\x1a\n123").is_err()); |
| 941 | assert!(ocr_mime_for_path(Path::new("fake.pdf"), b"not a pdf payload").is_err()); |
| 942 | assert_eq!( |
| 943 | ocr_mime_for_path(Path::new("doc.pdf"), b"%PDF-1.7\nbody").unwrap(), |
| 944 | "application/pdf" |
| 945 | ); |
| 946 | assert_eq!( |
| 947 | ocr_mime_for_path(Path::new("img.png"), b"\x89PNG\r\n\x1a\n0123").unwrap(), |
| 948 | "image/png" |
| 949 | ); |
| 950 | } |
| 951 | |
| 952 | #[test] |
| 953 | fn ocr_opt_in_requires_flag_and_api_key() { |
| 954 | let _lock = lock_test_env(); |
| 955 | let _flag_off = EnvVarGuard::remove("CODEWHALE_DEEPSEEK_OCR"); |
| 956 | let _key = EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-ocr-key"); |
| 957 | let _base = EnvVarGuard::set("DEEPSEEK_BASE_URL", "https://ds.example/v1"); |
| 958 | assert!(resolve_deepseek_ocr_auth().is_none()); |
| 959 | |
| 960 | let _flag_on = EnvVarGuard::set("CODEWHALE_DEEPSEEK_OCR", "1"); |
| 961 | assert_eq!( |
| 962 | resolve_deepseek_ocr_auth(), |
| 963 | Some(("https://ds.example".to_string(), "ds-ocr-key".to_string())) |
| 964 | ); |
| 965 | } |
| 966 | |
| 967 | #[test] |
| 968 | fn error_formatting_redacts_before_multibyte_utf8_truncation() { |
| 969 | let secret = "ds-secret-key-12345"; |
| 970 | let straddling_body = format!("{}{secret}{}", "é".repeat(250), "错误".repeat(120)); |
| 971 | let formatted = |
| 972 | format_error_response(reqwest::StatusCode::BAD_REQUEST, &straddling_body, secret); |
| 973 | assert!(!formatted.contains(secret), "{formatted}"); |
| 974 | assert!(formatted.contains("[redacted]"), "{formatted}"); |
| 975 | assert!(formatted.ends_with("..."), "{formatted}"); |
| 976 | } |
| 977 | |
| 978 | #[test] |
| 979 | fn config_auth_isolates_foreign_cli_api_key_and_supports_deepseek_anthropic() { |
| 980 | let _lock = lock_test_env(); |
| 981 | let _ds_key = EnvVarGuard::remove("DEEPSEEK_API_KEY"); |
| 982 | let _ds_base = EnvVarGuard::remove("DEEPSEEK_BASE_URL"); |
| 983 | let _cw_base = EnvVarGuard::remove("CODEWHALE_BASE_URL"); |
| 984 | |
| 985 | let openai_with_ds: Config = toml::from_str( |
| 986 | "provider = \"openai\"\n\n[providers.deepseek]\napi_key = \"ds-config-key\"\nbase_url = \"https://api.deepseek.com/v1\"\n", |
| 987 | ) |
| 988 | .expect("openai+deepseek config parses"); |
| 989 | { |
| 990 | let _cli_source = EnvVarGuard::set(codewhale_config::CLI_API_KEY_SOURCE_ENV, "cli"); |
| 991 | let _legacy_cli_source = |
| 992 | EnvVarGuard::remove(codewhale_config::LEGACY_CLI_API_KEY_SOURCE_ENV); |
| 993 | let _cli_key = EnvVarGuard::set(codewhale_config::CLI_API_KEY_ENV, "sk-foreign-cli"); |
| 994 | assert_eq!(resolve_deepseek_config_auth(&openai_with_ds), None); |
| 995 | } |
| 996 | |
| 997 | let _cli_source = EnvVarGuard::remove(codewhale_config::CLI_API_KEY_SOURCE_ENV); |
| 998 | let _legacy_cli_source = |
| 999 | EnvVarGuard::remove(codewhale_config::LEGACY_CLI_API_KEY_SOURCE_ENV); |
| 1000 | let _cli_key = EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 1001 | let anthropic_only: Config = toml::from_str( |
| 1002 | "provider = \"openai\"\n\n[providers.deepseek-anthropic]\napi_key = \"ds-ant\"\nbase_url = \"https://api.deepseek.com/anthropic/v1\"\n", |
| 1003 | ) |
| 1004 | .expect("deepseek-anthropic config parses"); |
| 1005 | assert_eq!( |
| 1006 | resolve_deepseek_config_auth(&anthropic_only), |
| 1007 | Some(("https://api.deepseek.com".to_string(), "ds-ant".to_string())) |
| 1008 | ); |
| 1009 | } |
| 1010 | |
| 1011 | #[tokio::test] |
| 1012 | async fn standalone_client_refuses_http_redirects() { |
| 1013 | let server = MockServer::start().await; |
| 1014 | Mock::given(method("POST")) |
| 1015 | .and(path("/v1/tools/tts")) |
| 1016 | .respond_with( |
| 1017 | ResponseTemplate::new(302) |
| 1018 | .insert_header("location", &format!("{}/elsewhere", server.uri())), |
| 1019 | ) |
| 1020 | .mount(&server) |
| 1021 | .await; |
| 1022 | Mock::given(method("POST")) |
| 1023 | .and(path("/elsewhere")) |
| 1024 | .respond_with(ResponseTemplate::new(200).set_body_bytes(b"SHOULD_NOT_FOLLOW".to_vec())) |
| 1025 | .mount(&server) |
| 1026 | .await; |
| 1027 | |
| 1028 | let err = synthesize_deepseek_bytes(&server.uri(), "ds-secret", "Hello", None, "wav") |
| 1029 | .await |
| 1030 | .expect_err("redirects must fail closed"); |
| 1031 | assert!(err.contains("HTTP 302"), "{err}"); |
| 1032 | let received = server.received_requests().await.expect("requests"); |
| 1033 | assert_eq!(received.len(), 1); |
| 1034 | assert_eq!(received[0].url.path(), "/v1/tools/tts"); |
| 1035 | } |
| 1036 | } |
| 1037 |