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(providers): say why a model fetch failed instead of 'Unknown error' (#9292) (#9297)

Thinh Le4045cf6eda7a
diff --git a/web-app/src/lib/__tests__/local-network.test.ts b/web-app/src/lib/__tests__/local-network.test.ts
new file mode 100644
index 000000000..d3ca712b7
--- /dev/null
+++ b/web-app/src/lib/__tests__/local-network.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest'
+import { isLocalNetworkUrl, localNetworkHint } from '../local-network'
+
+describe('isLocalNetworkUrl', () => {
+ it.each([
+ 'http://10.1.0.211:11434/v1',
+ 'http://172.16.0.5/v1',
+ 'http://172.31.255.1/v1',
+ 'http://192.168.1.20:8080',
+ 'http://169.254.10.1',
+ 'http://hotrod.local:11434/v1',
+ ])('is true for %s', (url) => {
+ expect(isLocalNetworkUrl(url)).toBe(true)
+ })
+
+ it.each([
+ 'http://localhost:11434/v1',
+ 'http://127.0.0.1:1234',
+ 'http://172.15.0.1',
+ 'http://172.32.0.1',
+ 'http://192.169.1.1',
+ 'https://api.openai.com/v1',
+ 'not a url',
+ ])('is false for %s', (url) => {
+ expect(isLocalNetworkUrl(url)).toBe(false)
+ })
+})
+
+describe('localNetworkHint', () => {
+ it('names the macOS setting for a LAN host', () => {
+ expect(localNetworkHint('http://10.1.0.211:11434/v1', true)).toMatch(
+ /Local Network/
+ )
+ })
+
+ it('is empty off macOS or for a host macOS does not gate', () => {
+ expect(localNetworkHint('http://10.1.0.211:11434/v1', false)).toBe('')
+ expect(localNetworkHint('http://localhost:11434/v1', true)).toBe('')
+ expect(localNetworkHint('https://api.openai.com/v1', true)).toBe('')
+ })
+})
diff --git a/web-app/src/lib/local-network.ts b/web-app/src/lib/local-network.ts
new file mode 100644
index 000000000..0898abef7
--- /dev/null
+++ b/web-app/src/lib/local-network.ts
@@ -0,0 +1,38 @@
+/**
+ * True when `url` points at a device on the local network: a private IPv4
+ * range, a link-local address, or a `.local` mDNS name. Loopback is excluded
+ * because macOS does not gate it.
+ */
+export function isLocalNetworkUrl(url: string): boolean {
+ let host: string
+ try {
+ host = new URL(url).hostname.toLowerCase()
+ } catch {
+ return false
+ }
+ if (host.endsWith('.local')) return true
+
+ const m = host.match(/^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/)
+ if (!m) return false
+ const a = Number(m[1])
+ const b = Number(m[2])
+ return (
+ a === 10 ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 168) ||
+ (a === 169 && b === 254)
+ )
+}
+
+/**
+ * Extra advice for a failed connection to `url`, or '' when it does not apply.
+ *
+ * macOS blocks an app from reaching devices on the local network until the
+ * user allows it under Privacy & Security > Local Network. Until then a
+ * request just fails to connect, which looks like a wrong address, even
+ * though `curl` from a terminal to the same host works.
+ */
+export function localNetworkHint(url: string, onMac: boolean): string {
+ if (!onMac || !isLocalNetworkUrl(url)) return ''
+ return 'If the server is on your local network, allow Jan in System Settings > Privacy & Security > Local Network.'
+}
diff --git a/web-app/src/services/providers/__tests__/tauri.test.ts b/web-app/src/services/providers/__tests__/tauri.test.ts
index e9496bbb2..64939b5b7 100644
--- a/web-app/src/services/providers/__tests__/tauri.test.ts
+++ b/web-app/src/services/providers/__tests__/tauri.test.ts
@@ -70,6 +70,13 @@ vi.mock('@/lib/provider-api-keys', () => ({
API_KEY_FALLBACKS_SETTING_KEY: 'api-key-fallbacks',
}))
+const platform = vi.hoisted(() => ({ mac: false }))
+vi.mock('@/lib/shortcuts/platform', () => ({
+ get isMac() {
+ return platform.mac
+ },
+}))
+
import { fetch as fetchTauri } from '@tauri-apps/plugin-http'
import { invoke } from '@tauri-apps/api/core'
import { EngineManager } from '@janhq/core'
@@ -321,6 +328,53 @@ describe('TauriProvidersService', () => {
errSpy.mockRestore()
})
+ // `@tauri-apps/plugin-http` rejects with a plain string, not an Error.
+ describe('when the request cannot be sent', () => {
+ const reject = (url: string) =>
+ vi
+ .mocked(fetchTauri)
+ .mockRejectedValueOnce(`error sending request for url (${url})`)
+ const lan = { ...baseProvider, base_url: 'http://10.1.0.211:11434/v1' }
+
+ beforeEach(() => {
+ platform.mac = false
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ })
+
+ it('explains the failure instead of saying "Unknown error"', async () => {
+ reject('https://api.test.com/v1/models')
+ const err = await svc.fetchModelsFromProvider(baseProvider).catch((e) => e)
+ expect(err.message).toMatch(/couldn't reach the provider/i)
+ expect(err.message).toContain('https://api.test.com/v1/models')
+ expect(err.message).not.toContain('Unknown error')
+ })
+
+ it('names the macOS Local Network setting for a LAN host', async () => {
+ platform.mac = true
+ reject('http://10.1.0.211:11434/v1/models')
+ const err = await svc.fetchModelsFromProvider(lan).catch((e) => e)
+ expect(err.message).toContain('Local Network')
+ })
+
+ it('does not mention it off macOS or for a public host', async () => {
+ reject('http://10.1.0.211:11434/v1/models')
+ const off = await svc.fetchModelsFromProvider(lan).catch((e) => e)
+ expect(off.message).not.toContain('Local Network')
+
+ platform.mac = true
+ reject('https://api.test.com/v1/models')
+ const pub = await svc.fetchModelsFromProvider(baseProvider).catch((e) => e)
+ expect(pub.message).not.toContain('Local Network')
+ })
+
+ it('keeps the text of a non-Error rejection in the fallback', async () => {
+ vi.mocked(fetchTauri).mockRejectedValueOnce('something odd')
+ await expect(svc.fetchModelsFromProvider(baseProvider)).rejects.toThrow(
+ 'Unexpected error while fetching models from test-provider: something odd'
+ )
+ })
+ })
+
it('adds Origin header for localhost URLs', async () => {
const localProvider = { ...baseProvider, base_url: 'http://localhost:1234' }
vi.mocked(fetchTauri).mockResolvedValueOnce({
diff --git a/web-app/src/services/providers/tauri.ts b/web-app/src/services/providers/tauri.ts
index fd2b25c15..5a3772a29 100644
--- a/web-app/src/services/providers/tauri.ts
+++ b/web-app/src/services/providers/tauri.ts
@@ -17,6 +17,9 @@ import {
providerRemoteApiKeyChain,
} from '@/lib/provider-api-keys'
import { ensureAnthropicHeaders } from '@/lib/remoteModelCatalog'
+import { describeTransportError } from '@/lib/model-factory'
+import { localNetworkHint } from '@/lib/local-network'
+import { isMac } from '@/lib/shortcuts/platform'
export class TauriProvidersService extends DefaultProvidersService {
fetch(): typeof fetch {
@@ -267,8 +270,21 @@ export class TauriProvidersService extends DefaultProvidersService {
throw new Error(error.message)
}
+ // `@tauri-apps/plugin-http` rejects with a plain string, not an Error,
+ // so `error instanceof Error` alone reported every connection failure
+ // as "Unknown error".
+ const friendly = describeTransportError(error)
+ if (friendly) {
+ const hint = localNetworkHint(provider.base_url, isMac)
+ throw new Error(
+ `${friendly} (${provider.base_url}/models)${hint ? ` ${hint}` : ''}`
+ )
+ }
+
+ const message = error instanceof Error ? error.message : String(error)
+
// Provide helpful error message for any connection errors
- if (error instanceof Error && error.message.includes('fetch')) {
+ if (message.includes('fetch')) {
throw new Error(
`Cannot connect to ${provider.provider} at ${provider.base_url}. Please check that the service is running and accessible.`
)
@@ -276,7 +292,7 @@ export class TauriProvidersService extends DefaultProvidersService {
// Generic fallback
throw new Error(
- `Unexpected error while fetching models from ${provider.provider}: ${error instanceof Error ? error.message : 'Unknown error'}`
+ `Unexpected error while fetching models from ${provider.provider}: ${message}`
)
}
}