Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(web-app): show the unreachable-provider message in the model-fetch toast (#9351) (#9354)
Thinh Lece8fcd25230d
diff --git a/web-app/src/lib/__tests__/provider-unreachable.test.ts b/web-app/src/lib/__tests__/provider-unreachable.test.tsnew file mode 100644index 000000000..66c5381a7--- /dev/null+++ b/web-app/src/lib/__tests__/provider-unreachable.test.ts@@ -0,0 +1,134 @@+import { describe, it, expect, vi } from 'vitest'++vi.mock('@tauri-apps/plugin-http', () => ({ fetch: vi.fn() }))++const platform = vi.hoisted(() => ({ mac: false }))+vi.mock('@/lib/shortcuts/platform', () => ({+ get isMac() {+ return platform.mac+ },+}))++import {+ ProviderUnreachableError,+ refreshFailureText,+ withUnreachableErrors,+} from '../provider-unreachable'+import { fetchTopRemoteModels } from '../remoteModelCatalog'++const generic =+ 'Failed to fetch models from acme. Please check your API key and base URL.'++describe('refreshFailureText', () => {+ it('shows the unreachable message, which names the URL, instead of blaming the key', () => {+ const err = new ProviderUnreachableError(+ "Couldn't reach the provider - the connection failed. (http://10.0.0.5:11434/v1/models)"+ )+ expect(refreshFailureText(err, generic)).toBe(err.message)+ })++ it('keeps the generic text for an HTTP status error', () => {+ expect(+ refreshFailureText(new Error('Authentication failed for acme'), generic)+ ).toBe(generic)+ })++ it('keeps the generic text for a non-Error rejection', () => {+ expect(refreshFailureText('boom', generic)).toBe(generic)+ })+})++describe('withUnreachableErrors', () => {+ const url = 'http://10.1.0.211:8080/v1/models'+ // `@tauri-apps/plugin-http` rejects with a plain string, not an Error.+ const rejecting = (reason: unknown) =>+ withUnreachableErrors(vi.fn().mockRejectedValue(reason) as never)++ it('turns a failed connection into an unreachable error naming the URL', async () => {+ const err = await rejecting(`error sending request for url (${url})`)(+ url+ ).catch((e) => e)+ expect(err).toBeInstanceOf(ProviderUnreachableError)+ expect(err.message).toMatch(/couldn't reach the provider/i)+ expect(err.message).toContain(url)+ })++ it('adds the macOS Local Network hint for a LAN address only on macOS', async () => {+ platform.mac = true+ const mac = await rejecting('error sending request')(url).catch((e) => e)+ expect(mac.message).toContain('Local Network')+ const publicHost = await rejecting('error sending request')(+ 'https://api.test.com/v1/models'+ ).catch((e) => e)+ expect(publicHost.message).not.toContain('Local Network')++ platform.mac = false+ const other = await rejecting('error sending request')(url).catch((e) => e)+ expect(other.message).not.toContain('Local Network')+ })++ it('rethrows a rejection that is not a transport failure unchanged', async () => {+ const boom = new Error('something else broke')+ await expect(rejecting(boom)(url)).rejects.toBe(boom)+ })++ it('passes a response through, including an HTTP error status', async () => {+ const response = { ok: false, status: 401 } as Response+ const wrapped = withUnreachableErrors(+ vi.fn().mockResolvedValue(response) as never+ )+ await expect(wrapped(url)).resolves.toBe(response)+ })+})++// The refresh button on a provider with a remote catalog (api_type+// 'anthropic', Gemini, ...) goes through `fetchTopRemoteModels`, not through+// the provider service, so its failures reach the toast by a different route.+describe('refreshing a provider with a remote catalog', () => {+ it('shows the unreachable message when the gateway cannot be reached', async () => {+ const provider = {+ provider: 'acme',+ base_url: 'https://gateway.acme.test/v1',+ api_type: 'anthropic',+ api_key: 'k',+ } as never+ const fetchImpl = vi+ .fn()+ .mockRejectedValue('error sending request for url (https://gateway.acme.test/v1/models)')++ const err = await fetchTopRemoteModels(+ provider,+ withUnreachableErrors(fetchImpl as never)+ ).catch((e) => e)++ expect(refreshFailureText(err, generic)).toMatch(/couldn't reach the provider/i)+ expect(refreshFailureText(err, generic)).toContain(+ 'https://gateway.acme.test/v1/models'+ )+ })++ it('keeps the generic text when the gateway answers with an error status', async () => {+ const provider = {+ provider: 'acme',+ base_url: 'https://gateway.acme.test/v1',+ api_type: 'anthropic',+ api_key: 'k',+ } as never+ const fetchImpl = vi.fn().mockResolvedValue({+ ok: false,+ status: 500,+ statusText: 'Internal Server Error',+ json: async () => ({}),+ })++ const err = await fetchTopRemoteModels(+ provider,+ withUnreachableErrors(fetchImpl as never)+ ).catch((e) => e)++ // The message contains "Failed to fetch models", which must not be taken+ // for a connection failure.+ expect(err).not.toBeInstanceOf(ProviderUnreachableError)+ expect(refreshFailureText(err, generic)).toBe(generic)+ })+})diff --git a/web-app/src/lib/provider-unreachable.ts b/web-app/src/lib/provider-unreachable.tsnew file mode 100644index 000000000..1177c3544--- /dev/null+++ b/web-app/src/lib/provider-unreachable.ts@@ -0,0 +1,65 @@+import { describeTransportError } from '@/lib/model-factory'+import { localNetworkHint } from '@/lib/local-network'+import { isMac } from '@/lib/shortcuts/platform'++/**+ * A provider request that never got an HTTP response: DNS, connect, TLS or+ * timeout. The message is already written for the user (what failed, the URL,+ * and on macOS the Local Network hint), so it can be shown as it is. HTTP+ * status errors (401, 403, 404) are not this type and keep their own wording.+ */+export class ProviderUnreachableError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'ProviderUnreachableError'+ }+}++/**+ * The unreachable error for a request to `url` that rejected with `error`, or+ * null when `error` is not a transport failure. Call it on what the fetch+ * itself rejected with, never on an error built from a response status: those+ * can contain words such as "failed to fetch" without being a connection+ * failure.+ */+export function toProviderUnreachable(+ error: unknown,+ url: string+): ProviderUnreachableError | null {+ const friendly = describeTransportError(error)+ if (!friendly) return null+ const hint = localNetworkHint(url, isMac)+ return new ProviderUnreachableError(+ `${friendly} (${url})${hint ? ` ${hint}` : ''}`+ )+}++/**+ * `fetchImpl`, with a transport failure rethrown as a `ProviderUnreachableError`+ * naming the URL. Responses, including HTTP error statuses, pass through.+ */+export function withUnreachableErrors(+ fetchImpl: typeof fetch+): typeof fetch {+ return async (input, init) => {+ try {+ return await fetchImpl(input, init)+ } catch (error) {+ const url =+ typeof input === 'string'+ ? input+ : input instanceof URL+ ? input.toString()+ : input.url+ throw toProviderUnreachable(error, url) ?? error+ }+ }+}++/**+ * The text for a failed model-list refresh: the unreachable message when that+ * is what happened, otherwise the generic localized `fallback`.+ */+export function refreshFailureText(error: unknown, fallback: string): string {+ return error instanceof ProviderUnreachableError ? error.message : fallback+}diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsxindex a12153777..8cc54d9b6 100644--- a/web-app/src/routes/settings/providers/$providerName.tsx+++ b/web-app/src/routes/settings/providers/$providerName.tsx@@ -49,6 +49,10 @@ import {supportsRemoteCatalog,fetchTopRemoteModels,} from '@/lib/remoteModelCatalog'+import {+ refreshFailureText,+ withUnreachableErrors,+} from '@/lib/provider-unreachable'// as route.threadsDetailexport const Route = createFileRoute('/settings/providers/$providerName')({@@ -486,7 +490,10 @@ function ProviderDetail() {try {let newModels: Model[]if (supportsRemoteCatalog(provider)) {- const catalog = await fetchTopRemoteModels(provider, serviceHub.providers().fetch())+ const catalog = await fetchTopRemoteModels(+ provider,+ withUnreachableErrors(serviceHub.providers().fetch())+ )newModels = catalog.map((m) => ({id: m.id,model: m.id,@@ -564,10 +571,11 @@ function ProviderDetail() {t('providers:refreshModelsFailed', { provider: provider.provider }),error)+ const generic = t('providers:refreshModelsFailed', {+ provider: provider.provider,+ })toast.error(t('providers:models'), {- description: t('providers:refreshModelsFailed', {- provider: provider.provider,- }),+ description: refreshFailureText(error, generic),})} finally {setRefreshingModels(false)diff --git a/web-app/src/services/providers/__tests__/tauri.test.ts b/web-app/src/services/providers/__tests__/tauri.test.tsindex 64939b5b7..9ee0b32f2 100644--- a/web-app/src/services/providers/__tests__/tauri.test.ts+++ b/web-app/src/services/providers/__tests__/tauri.test.ts@@ -83,6 +83,7 @@ import { EngineManager } from '@janhq/core'import { ExtensionManager } from '@/lib/extension'import { providerRemoteApiKeyChain } from '@/lib/provider-api-keys'import { TauriProvidersService } from '../tauri'+import { ProviderUnreachableError } from '@/lib/provider-unreachable'describe('TauriProvidersService', () => {let svc: TauriProvidersService@@ -271,6 +272,18 @@ describe('TauriProvidersService', () => {errSpy.mockRestore()})+ it('does not tag an HTTP status error as unreachable', async () => {+ vi.mocked(fetchTauri).mockResolvedValueOnce({+ ok: false,+ status: 401,+ statusText: 'Unauthorized',+ } as any)++ vi.spyOn(console, 'error').mockImplementation(() => {})+ const err = await svc.fetchModelsFromProvider(baseProvider).catch((e) => e)+ expect(err).not.toBeInstanceOf(ProviderUnreachableError)+ })+it('throws structured error on 403', async () => {vi.mocked(fetchTauri).mockResolvedValueOnce({ok: false,@@ -344,6 +357,7 @@ describe('TauriProvidersService', () => {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).toBeInstanceOf(ProviderUnreachableError)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')diff --git a/web-app/src/services/providers/tauri.ts b/web-app/src/services/providers/tauri.tsindex 5a3772a29..ae8d2d798 100644--- a/web-app/src/services/providers/tauri.ts+++ b/web-app/src/services/providers/tauri.ts@@ -17,9 +17,7 @@ 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'+import { toProviderUnreachable } from '@/lib/provider-unreachable'export class TauriProvidersService extends DefaultProvidersService {fetch(): typeof fetch {@@ -273,13 +271,11 @@ export class TauriProvidersService extends DefaultProvidersService {// `@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 unreachable = toProviderUnreachable(+ error,+ `${provider.base_url}/models`+ )+ if (unreachable) throw unreachableconst message = error instanceof Error ? error.message : String(error)