Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(downloads): say why a network error stopped a model download (#9294)

Thinh Le052da5503526
diff --git a/src-tauri/src/core/downloads/helpers.rs b/src-tauri/src/core/downloads/helpers.rs
index 2ba73fda7..2c0480c5a 100644
--- a/src-tauri/src/core/downloads/helpers.rs
+++ b/src-tauri/src/core/downloads/helpers.rs
@@ -54,6 +54,23 @@ pub fn err_to_string<E: std::fmt::Display>(e: E) -> String {
format!("Error: {e}")
}
+/// Like `err_to_string` but keeps the whole `source()` chain. reqwest's `Display` stops at
+/// "error sending request for url (...)"; the part that says why (DNS, refused, TLS, timeout) is
+/// only in the sources, and the download toast needs it to tell a firewall from a bad proxy.
+pub fn err_chain_to_string(e: &(dyn std::error::Error + 'static)) -> String {
+ let mut out = format!("Error: {e}");
+ let mut source = e.source();
+ while let Some(cause) = source {
+ let text = cause.to_string();
+ if !out.ends_with(&text) {
+ out.push_str(": ");
+ out.push_str(&text);
+ }
+ source = cause.source();
+ }
+ out
+}
+
/// Converts a URL to Jan mirror URL if applicable
/// e.g., https://huggingface.co/... -> https://apps.jan.ai/huggingface.co/...
/// or for nightly: https://huggingface.co/... -> https://apps-nightly.jan.ai/huggingface.co/...
@@ -678,7 +695,7 @@ async fn download_single_file(
return Err("Download cancelled".to_string());
}
- let chunk = chunk.map_err(err_to_string)?;
+ let chunk = chunk.map_err(|e| err_chain_to_string(&e))?;
writer.write_all(&chunk).await.map_err(err_to_string)?;
download_delta += chunk.len() as u64;
total_transferred += chunk.len() as u64;
@@ -794,7 +811,7 @@ async fn _get_maybe_resume_with_hmac(
request = request.header(key, value);
}
- let resp = request.send().await.map_err(err_to_string)?;
+ let resp = request.send().await.map_err(|e| err_chain_to_string(&e))?;
if start_bytes > 0 {
if resp.status() != reqwest::StatusCode::PARTIAL_CONTENT {
@@ -827,7 +844,7 @@ async fn _get_maybe_resume_internal(
.header("Range", format!("bytes={start_bytes}-"))
.send()
.await
- .map_err(err_to_string)?;
+ .map_err(|e| err_chain_to_string(&e))?;
if resp.status() != reqwest::StatusCode::PARTIAL_CONTENT {
return Err(format!(
"Failed to resume download: HTTP status {}, {}",
@@ -837,7 +854,11 @@ async fn _get_maybe_resume_internal(
}
Ok(resp)
} else {
- let resp = client.get(url).send().await.map_err(err_to_string)?;
+ let resp = client
+ .get(url)
+ .send()
+ .await
+ .map_err(|e| err_chain_to_string(&e))?;
if !resp.status().is_success() {
return Err(format!(
"Failed to download: HTTP status {}, {}",
@@ -860,7 +881,7 @@ pub async fn _get_maybe_resume(
.header("Range", format!("bytes={start_bytes}-"))
.send()
.await
- .map_err(err_to_string)?;
+ .map_err(|e| err_chain_to_string(&e))?;
if resp.status() != reqwest::StatusCode::PARTIAL_CONTENT {
return Err(format!(
"Failed to resume download: HTTP status {}, {}",
@@ -870,7 +891,11 @@ pub async fn _get_maybe_resume(
}
Ok(resp)
} else {
- let resp = client.get(url).send().await.map_err(err_to_string)?;
+ let resp = client
+ .get(url)
+ .send()
+ .await
+ .map_err(|e| err_chain_to_string(&e))?;
if !resp.status().is_success() {
return Err(format!(
"Failed to download: HTTP status {}, {}",
diff --git a/src-tauri/src/core/downloads/tests.rs b/src-tauri/src/core/downloads/tests.rs
index 53f670d58..c3d65243a 100644
--- a/src-tauri/src/core/downloads/tests.rs
+++ b/src-tauri/src/core/downloads/tests.rs
@@ -441,6 +441,72 @@ fn test_err_to_string_with_io_error() {
assert!(s.contains("missing"));
}
+#[derive(Debug)]
+struct Layered(&'static str, Option<Box<dyn std::error::Error + 'static>>);
+
+impl std::fmt::Display for Layered {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(self.0)
+ }
+}
+
+impl std::error::Error for Layered {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ self.1.as_deref()
+ }
+}
+
+#[test]
+fn err_chain_keeps_the_cause_err_to_string_drops() {
+ // reqwest's Display is only the outer layer; the reason is two sources down.
+ let io = std::io::Error::other("connection refused (os error 10061)");
+ let connect = Layered("tcp connect error", Some(Box::new(io)));
+ let outer = Layered("error sending request for url (https://huggingface.co/x.gguf)", Some(Box::new(connect)));
+
+ assert_eq!(
+ err_to_string(&outer),
+ "Error: error sending request for url (https://huggingface.co/x.gguf)"
+ );
+ assert_eq!(
+ err_chain_to_string(&outer),
+ "Error: error sending request for url (https://huggingface.co/x.gguf): tcp connect error: connection refused (os error 10061)"
+ );
+}
+
+#[tokio::test]
+async fn a_refused_connection_surfaces_its_cause_through_reqwest() {
+ // Bind then drop, so the port is closed and the connect is refused rather than timing out.
+ let port = std::net::TcpListener::bind("127.0.0.1:0")
+ .unwrap()
+ .local_addr()
+ .unwrap()
+ .port();
+ let err = reqwest::Client::new()
+ .get(format!("http://127.0.0.1:{port}/model.gguf"))
+ .send()
+ .await
+ .unwrap_err();
+
+ let plain = err_to_string(&err);
+ let chain = err_chain_to_string(&err);
+ assert!(plain.starts_with("Error: error sending request for url"));
+ assert!(chain.len() > plain.len(), "no cause appended: {chain}");
+ assert!(chain.starts_with(&plain));
+}
+
+#[test]
+fn err_chain_does_not_repeat_a_cause_the_parent_already_prints() {
+ let inner = Layered("timed out", None);
+ let outer = Layered("request failed: timed out", Some(Box::new(inner)));
+ assert_eq!(err_chain_to_string(&outer), "Error: request failed: timed out");
+}
+
+#[test]
+fn err_chain_of_a_plain_error_matches_err_to_string() {
+ let e = std::io::Error::new(std::io::ErrorKind::NotFound, "missing");
+ assert_eq!(err_chain_to_string(&e), err_to_string(&e));
+}
+
// ===== _convert_headers edge cases =====
#[test]
diff --git a/web-app/src/hooks/__tests__/useDownloadEvents.test.tsx b/web-app/src/hooks/__tests__/useDownloadEvents.test.tsx
index 6d5768f04..88ea8c2fd 100644
--- a/web-app/src/hooks/__tests__/useDownloadEvents.test.tsx
+++ b/web-app/src/hooks/__tests__/useDownloadEvents.test.tsx
@@ -29,7 +29,10 @@ vi.mock('@/hooks/useDownloadStore', () => {
})
vi.mock('@/i18n/react-i18next-compat', () => ({
- useTranslation: () => ({ t: (k: string) => k }),
+ // Echo the interpolated reason so a test can tell which message was chosen.
+ useTranslation: () => ({
+ t: (k: string, o?: { reason?: string }) => (o?.reason ? `${k}|${o.reason}` : k),
+ }),
}))
vi.mock('@tanstack/react-router', () => ({
@@ -37,7 +40,7 @@ vi.mock('@tanstack/react-router', () => ({
}))
vi.mock('@/constants/routes', () => ({
- route: { settings: { general: '/settings/general' } },
+ route: { settings: { general: '/settings/general' }, appLogs: '/logs' },
}))
vi.mock('@janhq/core', () => ({
@@ -157,6 +160,30 @@ describe('useDownloadEvents', () => {
)
})
+ it('names the cause when a network error carries no HTTP status', () => {
+ mount()
+ hoisted.eventHandlers['fde']({
+ modelId: 'embed',
+ error:
+ 'Error: error sending request for url (https://huggingface.co/x.gguf): client error (Connect): dns error: failed to lookup address information',
+ })
+ const [title, opts] = hoisted.toastMock.error.mock.calls[0]
+ expect(title).toBe('common:toast.downloadFailed.title')
+ expect(opts.description).toBe(
+ 'common:toast.downloadFailed.descriptionWithReason|common:toast.downloadFailed.reason.dns'
+ )
+ })
+
+ it('points at the logs when the error has no recognisable cause', () => {
+ mount()
+ hoisted.eventHandlers['fde']({ modelId: 'w', error: 'Error: disk full' })
+ const [, opts] = hoisted.toastMock.error.mock.calls[0]
+ expect(opts.description).toBe('common:toast.downloadFailed.description')
+ expect(opts.action.label).toBe('common:toast.openLogs')
+ opts.action.onClick()
+ expect(hoisted.navigateMock).toHaveBeenCalledWith({ to: '/logs' })
+ })
+
it('clears the download on success', () => {
mount()
hoisted.eventHandlers['fds']({ modelId: 'ok' })
diff --git a/web-app/src/hooks/useDownloadEvents.ts b/web-app/src/hooks/useDownloadEvents.ts
index bb190101e..997943c6b 100644
--- a/web-app/src/hooks/useDownloadEvents.ts
+++ b/web-app/src/hooks/useDownloadEvents.ts
@@ -5,6 +5,7 @@ import { useNavigate } from '@tanstack/react-router'
import { route } from '@/constants/routes'
import { useDownloadStore } from '@/hooks/useDownloadStore'
import { useTranslation } from '@/i18n/react-i18next-compat'
+import { classifyDownloadError } from '@/lib/downloadError'
/**
* Bridges download events into the download store.
@@ -76,11 +77,23 @@ export function useDownloadEvents() {
return
}
+ // The reason keeps a firewall, proxy, TLS or DNS problem from looking like
+ // every other failure; with no recognisable cause the toast points at the logs.
+ const reason = classifyDownloadError(err)
toast.error(t('common:toast.downloadFailed.title'), {
id: 'download-failed',
- description: t('common:toast.downloadFailed.description', {
- item: state.modelId,
- }),
+ description: reason
+ ? t('common:toast.downloadFailed.descriptionWithReason', {
+ item: state.modelId,
+ reason: t(`common:toast.downloadFailed.reason.${reason}`),
+ })
+ : t('common:toast.downloadFailed.description', {
+ item: state.modelId,
+ }),
+ action: {
+ label: t('common:toast.openLogs'),
+ onClick: () => navigate({ to: route.appLogs }),
+ },
})
},
[removeDownload, removeLocalDownloadingModel, t, navigate]
diff --git a/web-app/src/lib/__tests__/downloadError.test.ts b/web-app/src/lib/__tests__/downloadError.test.ts
new file mode 100644
index 000000000..ffea173d7
--- /dev/null
+++ b/web-app/src/lib/__tests__/downloadError.test.ts
@@ -0,0 +1,54 @@
+import { describe, it, expect } from 'vitest'
+import { classifyDownloadError } from '../downloadError'
+
+describe('classifyDownloadError', () => {
+ it.each([
+ ['dns error: failed to lookup address information', 'dns'],
+ ['tcp connect error: No such host is known. (os error 11001)', 'dns'],
+ ['tcp connect error: connection refused (os error 10061)', 'refused'],
+ [
+ // Captured from reqwest on Windows against a closed local port.
+ 'Error: error sending request for url (http://127.0.0.1:55420/model.gguf): client error (Connect): tcp connect error: No connection could be made because the target machine actively refused it. (os error 10061)',
+ 'refused',
+ ],
+ ['operation timed out', 'timeout'],
+ ['A connection attempt failed (os error 10060)', 'timeout'],
+ ['invalid peer certificate: UnknownIssuer', 'tls'],
+ ['error trying to connect: tls handshake eof', 'tls'],
+ ['proxy connect error: tunnel error', 'proxy'],
+ ] as const)('%s -> %s', (error, reason) => {
+ expect(classifyDownloadError(error)).toBe(reason)
+ })
+
+ it('prefers the specific cause over the generic request wrapper', () => {
+ expect(
+ classifyDownloadError(
+ 'Error: error sending request for url (https://x): tcp connect error: connection refused (os error 10061)'
+ )
+ ).toBe('refused')
+ })
+
+ it('never reads the requested URL as a cause', () => {
+ expect(
+ classifyDownloadError(
+ 'Error: error sending request for url (https://huggingface.co/org/proxy-tls-timeout-model/resolve/main/m.gguf?download=true): client error (Connect): tcp connect error: connection refused (os error 10061)'
+ )
+ ).toBe('refused')
+ expect(
+ classifyDownloadError(
+ 'Error: error sending request for url (https://hf.co/proxy/connection-reset/m.gguf)'
+ )
+ ).toBe('unreachable')
+ })
+
+ it('falls back to a generic unreachable reason for a bare request failure', () => {
+ expect(
+ classifyDownloadError('Error: error sending request for url (https://x)')
+ ).toBe('unreachable')
+ })
+
+ it('has no opinion on errors that are not network failures', () => {
+ expect(classifyDownloadError('')).toBeUndefined()
+ expect(classifyDownloadError('Error: No space left on device')).toBeUndefined()
+ })
+})
diff --git a/web-app/src/lib/downloadError.ts b/web-app/src/lib/downloadError.ts
new file mode 100644
index 000000000..33e8bdbaf
--- /dev/null
+++ b/web-app/src/lib/downloadError.ts
@@ -0,0 +1,34 @@
+export type DownloadFailureReason =
+ | 'dns'
+ | 'refused'
+ | 'timeout'
+ | 'tls'
+ | 'proxy'
+ | 'unreachable'
+
+// Order matters: the first match wins, so a specific cause beats the generic
+// "error sending request" wrapper that every reqwest connect failure carries.
+const RULES: ReadonlyArray<readonly [DownloadFailureReason, RegExp]> = [
+ ['tls', /certificate|\btls\b|\bssl\b|handshake|invalid peer/i],
+ ['proxy', /proxy/i],
+ ['dns', /dns error|failed to lookup|no such host|name or service not known|nodename nor servname|os error 11001/i],
+ ['timeout', /timed out|timeout|os error 10060/i],
+ ['refused', /connection refused|os error 10061|actively refused/i],
+ ['unreachable', /error sending request|error trying to connect|tcp connect error|network is unreachable|connection (reset|closed|aborted)|os error (10051|10054|10053)/i],
+]
+
+/**
+ * Names the network cause inside a download error string, or undefined when
+ * the text carries nothing a user could act on (the toast then points at the logs).
+ */
+export function classifyDownloadError(
+ error: string
+): DownloadFailureReason | undefined {
+ // reqwest embeds the requested URL: "error sending request for url (https://…)".
+ // A model path such as /proxy/ or /connection-reset/ must not read as a cause.
+ const cause = error.replace(/https?:\/\/[^\s)]*/gi, '')
+ for (const [reason, pattern] of RULES) {
+ if (pattern.test(cause)) return reason
+ }
+ return undefined
+}
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 8714a640c..dd9672933 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -537,9 +537,19 @@
},
"downloadFailed": {
"title": "Download Failed",
- "description": "{{item}} download failed"
+ "description": "{{item}} download failed",
+ "descriptionWithReason": "{{item}} download failed: {{reason}}",
+ "reason": {
+ "dns": "the server name could not be resolved",
+ "refused": "the connection was refused",
+ "timeout": "the connection timed out",
+ "tls": "a secure connection could not be established",
+ "proxy": "the proxy could not be reached",
+ "unreachable": "the server could not be reached"
+ }
},
"openSettings": "Open Settings",
+ "openLogs": "Open logs",
"downloadTokenRequired": {
"title": "Hugging Face token required",
"description": "This model requires a Hugging Face access token. Add your token in Settings and retry."