Skip to content

armgit / Handy

Public Imported from GitHub
0

A free, open source, and extensible speech-to-text application that works completely offline.

fix: preserve HTTP transport error causes (#1823)

CJ Pais4223e7ac6741
diff --git a/src-tauri/src/llm_client.rs b/src-tauri/src/llm_client.rs
index 381f3a75..f5695b51 100644
--- a/src-tauri/src/llm_client.rs
+++ b/src-tauri/src/llm_client.rs
@@ -1,9 +1,10 @@
use crate::settings::PostProcessProvider;
-use log::{debug, info};
+use log::{debug, error, info};
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE, REFERER, USER_AGENT};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashSet;
+use std::error::Error as StdError;
use std::sync::{Mutex, OnceLock};
#[derive(Debug, Serialize)]
@@ -177,7 +178,120 @@ fn create_client(provider: &PostProcessProvider, api_key: &str) -> Result<reqwes
reqwest::Client::builder()
.default_headers(headers)
.build()
- .map_err(|e| format!("Failed to build HTTP client: {}", e))
+ .map_err(|e| report_reqwest_error("Failed to build HTTP client", &e))
+}
+
+/// Format a bounded error source chain.
+///
+/// `reqwest::Error`'s Display implementation intentionally gives only a short
+/// summary. Nested causes contain the useful transport details, such as a
+/// certificate validation failure, an HTTP/2 error, or a connection reset.
+/// Callers must skip source types whose Display text can quote payload data.
+fn error_source_chain(error: &(dyn StdError + 'static)) -> Vec<String> {
+ let mut causes = Vec::new();
+ let mut source = error.source();
+
+ // Defensive cap in case a third-party error exposes a cyclic source chain.
+ for _ in 0..16 {
+ let Some(cause) = source else {
+ break;
+ };
+ causes.push(cause.to_string());
+ source = cause.source();
+ }
+
+ causes
+}
+
+fn reqwest_error_kinds(error: &reqwest::Error) -> String {
+ let mut kinds = Vec::new();
+
+ if error.is_builder() {
+ kinds.push("builder");
+ }
+ if error.is_connect() {
+ kinds.push("connect");
+ }
+ if error.is_request() {
+ kinds.push("request");
+ }
+ if error.is_redirect() {
+ kinds.push("redirect");
+ }
+ if error.is_timeout() {
+ kinds.push("timeout");
+ }
+ if error.is_status() {
+ kinds.push("status");
+ }
+ if error.is_body() {
+ kinds.push("body");
+ }
+ if error.is_decode() {
+ kinds.push("decode");
+ }
+ if error.is_upgrade() {
+ kinds.push("upgrade");
+ }
+
+ if kinds.is_empty() {
+ "unknown".to_string()
+ } else {
+ kinds.join(", ")
+ }
+}
+
+fn sanitized_url(url: &reqwest::Url) -> String {
+ let mut url = url.clone();
+
+ // Custom endpoints should not contain credentials or query-string tokens,
+ // but omit them from diagnostics in case one does.
+ let _ = url.set_username("");
+ let _ = url.set_password(None);
+ url.set_query(None);
+ url.set_fragment(None);
+
+ url.to_string()
+}
+
+fn sanitized_url_for_log(url: &str) -> String {
+ reqwest::Url::parse(url)
+ .map(|url| sanitized_url(&url))
+ // Do not echo an invalid URL: the parse failure might have been caused
+ // by sensitive data entered in the custom endpoint field.
+ .unwrap_or_else(|_| "<invalid URL>".to_string())
+}
+
+fn report_reqwest_error(context: &str, error: &reqwest::Error) -> String {
+ let kinds = reqwest_error_kinds(error);
+ let url = error
+ .url()
+ .map(sanitized_url)
+ .map(|url| format!(", url: {url}"))
+ .unwrap_or_default();
+
+ // serde_json's error text can quote values from a malformed response. That
+ // response may contain transcription content, so retain the useful decode
+ // classification but never put its nested source in logs or UI errors.
+ let causes = if error.is_decode() {
+ Vec::new()
+ } else {
+ error_source_chain(error)
+ };
+ let cause_details = if !causes.is_empty() {
+ format!(": caused by: {}", causes.join(" -> "))
+ } else if error.url().is_none() {
+ // Reqwest's short Display text is safe when it cannot append a raw URL.
+ format!(": {error}")
+ } else {
+ // The sanitized URL is already included above. Avoid formatting the
+ // original error because its Display implementation includes the raw URL.
+ String::new()
+ };
+
+ let details = format!("{context} (kind: {kinds}{url}){cause_details}");
+ error!("{details}");
+ details
}
/// Send a chat completion request to an OpenAI-compatible API
@@ -224,7 +338,10 @@ pub async fn send_chat_completion_with_schema(
let base_url = provider.base_url.trim_end_matches('/');
let url = format!("{}/chat/completions", base_url);
- debug!("Sending chat completion request to: {}", url);
+ debug!(
+ "Sending chat completion request to: {}",
+ sanitized_url_for_log(&url)
+ );
let client = create_client(provider, &api_key)?;
@@ -275,8 +392,14 @@ pub async fn send_chat_completion_with_schema(
.json(&request_body)
.send()
.await
- .map_err(|e| format!("HTTP request failed: {}", e))?;
+ .map_err(|e| report_reqwest_error("HTTP request failed", &e))?;
let mut status = response.status();
+ debug!(
+ "Chat completion response received with status {} over {:?} from {}",
+ status,
+ response.version(),
+ sanitized_url(response.url())
+ );
// A 400/422 on a request carrying reasoning-disable fields is almost always
// the endpoint rejecting those fields — retry once without them.
@@ -284,10 +407,9 @@ pub async fn send_chat_completion_with_schema(
&& matches!(status.as_u16(), 400 | 422)
&& !request_body.reasoning.is_empty()
{
- let error_text = response
- .text()
- .await
- .unwrap_or_else(|_| "Failed to read error response".to_string());
+ let error_text = response.text().await.unwrap_or_else(|e| {
+ report_reqwest_error("Failed to read reasoning rejection response", &e)
+ });
info!(
"Endpoint rejected request with reasoning disabled (status {}): {}. Retrying without reasoning fields",
status, error_text
@@ -299,13 +421,19 @@ pub async fn send_chat_completion_with_schema(
.json(&request_body)
.send()
.await
- .map_err(|e| format!("HTTP request failed: {}", e))?;
+ .map_err(|e| report_reqwest_error("HTTP retry failed", &e))?;
status = response.status();
+ debug!(
+ "Chat completion retry response received with status {} over {:?} from {}",
+ status,
+ response.version(),
+ sanitized_url(response.url())
+ );
if status.is_success() {
info!(
"Retry without reasoning fields succeeded; '{}' (model '{}') will skip them from now on",
- base_url, model
+ sanitized_url_for_log(base_url), model
);
remember_rejection(key);
}
@@ -315,7 +443,7 @@ pub async fn send_chat_completion_with_schema(
let error_text = response
.text()
.await
- .unwrap_or_else(|_| "Failed to read error response".to_string());
+ .unwrap_or_else(|e| report_reqwest_error("Failed to read API error response", &e));
return Err(format!(
"API request failed with status {}: {}",
status, error_text
@@ -325,7 +453,7 @@ pub async fn send_chat_completion_with_schema(
let completion: ChatCompletionResponse = response
.json()
.await
- .map_err(|e| format!("Failed to parse API response: {}", e))?;
+ .map_err(|e| report_reqwest_error("Failed to parse API response", &e))?;
Ok(completion
.choices
@@ -342,7 +470,7 @@ pub async fn fetch_models(
let base_url = provider.base_url.trim_end_matches('/');
let url = format!("{}/models", base_url);
- debug!("Fetching models from: {}", url);
+ debug!("Fetching models from: {}", sanitized_url_for_log(&url));
let client = create_client(provider, &api_key)?;
@@ -350,14 +478,20 @@ pub async fn fetch_models(
.get(&url)
.send()
.await
- .map_err(|e| format!("Failed to fetch models: {}", e))?;
+ .map_err(|e| report_reqwest_error("Failed to fetch models", &e))?;
let status = response.status();
+ debug!(
+ "Model list response received with status {} over {:?} from {}",
+ status,
+ response.version(),
+ sanitized_url(response.url())
+ );
if !status.is_success() {
let error_text = response
.text()
.await
- .unwrap_or_else(|_| "Unknown error".to_string());
+ .unwrap_or_else(|e| report_reqwest_error("Failed to read model list error", &e));
return Err(format!(
"Model list request failed ({}): {}",
status, error_text
@@ -367,7 +501,7 @@ pub async fn fetch_models(
let parsed: serde_json::Value = response
.json()
.await
- .map_err(|e| format!("Failed to parse response: {}", e))?;
+ .map_err(|e| report_reqwest_error("Failed to parse model list response", &e))?;
let mut models = Vec::new();
@@ -396,6 +530,28 @@ pub async fn fetch_models(
#[cfg(test)]
mod tests {
use super::*;
+ use std::fmt;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ #[derive(Debug)]
+ struct TestError {
+ message: &'static str,
+ source: Option<Box<TestError>>,
+ }
+
+ impl fmt::Display for TestError {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str(self.message)
+ }
+ }
+
+ impl StdError for TestError {
+ fn source(&self) -> Option<&(dyn StdError + 'static)> {
+ self.source
+ .as_deref()
+ .map(|source| source as &(dyn StdError + 'static))
+ }
+ }
fn provider(id: &str, base_url: &str) -> PostProcessProvider {
PostProcessProvider {
@@ -422,6 +578,90 @@ mod tests {
serde_json::to_value(&request).unwrap()
}
+ async fn serve_one_response(status: &str, body: &str) -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let response = format!(
+ "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+
+ tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ let mut request = [0_u8; 2048];
+ let _ = stream.read(&mut request).await.unwrap();
+ stream.write_all(response.as_bytes()).await.unwrap();
+ });
+
+ format!("http://{address}")
+ }
+
+ #[test]
+ fn error_source_chain_includes_all_nested_causes() {
+ let error = TestError {
+ message: "request failed",
+ source: Some(Box::new(TestError {
+ message: "TLS handshake failed",
+ source: Some(Box::new(TestError {
+ message: "unknown certificate authority",
+ source: None,
+ })),
+ })),
+ };
+
+ assert_eq!(
+ error_source_chain(&error),
+ vec!["TLS handshake failed", "unknown certificate authority"]
+ );
+ }
+
+ #[test]
+ fn log_url_sanitization_removes_credentials_and_tokens() {
+ let url = "https://user:[email protected]/v1/models?api_key=secret#private";
+ assert_eq!(sanitized_url_for_log(url), "https://example.com/v1/models");
+ }
+
+ #[test]
+ fn invalid_log_urls_are_not_echoed() {
+ assert_eq!(
+ sanitized_url_for_log("not a URL containing secret"),
+ "<invalid URL>"
+ );
+ }
+
+ #[tokio::test]
+ async fn decode_error_does_not_echo_response_values() {
+ let base_url =
+ serve_one_response("200 OK", r#"{"choices":"PRIVATE TRANSCRIPTION CONTENT"}"#).await;
+ let error = reqwest::get(base_url)
+ .await
+ .unwrap()
+ .json::<ChatCompletionResponse>()
+ .await
+ .unwrap_err();
+
+ let details = report_reqwest_error("Failed to parse API response", &error);
+ assert!(details.contains("kind: decode"));
+ assert!(!details.contains("PRIVATE TRANSCRIPTION CONTENT"));
+ }
+
+ #[tokio::test]
+ async fn raw_error_url_is_not_reintroduced_without_a_source() {
+ let base_url = serve_one_response("400 Bad Request", "bad request").await;
+ let error = reqwest::get(format!(
+ "{base_url}/private?api_key=SECRET_QUERY_TOKEN#private"
+ ))
+ .await
+ .unwrap()
+ .error_for_status()
+ .unwrap_err();
+
+ let details = report_reqwest_error("Request failed", &error);
+ assert!(details.contains(&format!("url: {base_url}/private")));
+ assert!(!details.contains("SECRET_QUERY_TOKEN"));
+ assert!(!details.contains("#private"));
+ }
+
#[test]
fn requests_explicitly_disable_streaming() {
let json = request_json(ReasoningParams::default());