Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: Improve toast messages and errors (#6892)
Roushan Kumar Singhab3410722a0e
diff --git a/web-app/src/containers/DownloadButton.tsx b/web-app/src/containers/DownloadButton.tsxindex 9a97ce8d1..5be6bcf77 100644--- a/web-app/src/containers/DownloadButton.tsx+++ b/web-app/src/containers/DownloadButton.tsx@@ -10,6 +10,9 @@ import { cn, sanitizeModelId } from '@/lib/utils'import { CatalogModel } from '@/services/models/types'import { DownloadEvent, DownloadState, events } from '@janhq/core'import { useCallback, useEffect, useMemo, useState } from 'react'+import { toast } from 'sonner'+import { route } from '@/constants/routes'+import { useNavigate } from '@tanstack/react-router'import { useShallow } from 'zustand/shallow'import { DEFAULT_MODEL_QUANTIZATIONS } from '@/constants/models'@@ -37,6 +40,7 @@ export function DownloadButtonPlaceholder({const serviceHub = useServiceHub()const huggingfaceToken = useGeneralSetting((state) => state.huggingfaceToken)const [isDownloaded, setDownloaded] = useState<boolean>(false)+ const navigate = useNavigate()const quant =model.quants.find((e) =>@@ -107,8 +111,71 @@ export function DownloadButtonPlaceholder({const isRecommended = isRecommendedModel(model.model_name)- const handleDownload = () => {- // Immediately set local downloading state+ const handleDownload = async () => {+ // Preflight check for gated repos/artifacts+ const preflight = await serviceHub+ .models()+ .preflightArtifactAccess(modelUrl, huggingfaceToken)++ if (!preflight.ok) {+ const repoPage = `https://huggingface.co/${model.model_name}`++ if (preflight.reason === 'AUTH_REQUIRED') {+ toast.error('Hugging Face token required', {+ description:+ 'This model requires a Hugging Face access token. Add your token in Settings and retry.',+ action: {+ label: 'Open Settings',+ onClick: () => navigate({ to: route.settings.general }),+ },+ })+ return+ }++ if (preflight.reason === 'LICENSE_NOT_ACCEPTED') {+ toast.error('Accept model license on Hugging Face', {+ description:+ 'You must accept the model’s license on its Hugging Face page before downloading.',+ action: {+ label: 'Open model page',+ onClick: () => window.open(repoPage, '_blank'),+ },+ })+ return+ }++ if (preflight.reason === 'RATE_LIMITED') {+ toast.error('Rate limited by Hugging Face', {+ description:+ 'You have been rate-limited. Adding a token can increase rate limits. Please try again later.',+ action: {+ label: 'Open Settings',+ onClick: () => navigate({ to: route.settings.general }),+ },+ })+ return+ }++ if (preflight.reason === 'NOT_FOUND') {+ toast.error('File not found', {+ description:+ 'The requested artifact was not found in the repository. Try another quant or check the model page.',+ action: {+ label: 'Open model page',+ onClick: () => window.open(repoPage, '_blank'),+ },+ })+ return+ }++ toast.error('Model download error', {+ description:+ 'We could not start the download. Check your network or try again later.',+ })+ return+ }++ // Immediately set local downloading state and start downloadaddLocalDownloadingModel(modelId)const mmprojPath = (model.mmproj_models?.find(diff --git a/web-app/src/containers/DownloadManegement.tsx b/web-app/src/containers/DownloadManegement.tsxindex e0d829740..4b79ebd90 100644--- a/web-app/src/containers/DownloadManegement.tsx+++ b/web-app/src/containers/DownloadManegement.tsx@@ -13,9 +13,12 @@ import { IconDownload, IconX } from '@tabler/icons-react'import { useCallback, useEffect, useMemo, useState } from 'react'import { toast } from 'sonner'import { useTranslation } from '@/i18n/react-i18next-compat'+import { useNavigate } from '@tanstack/react-router'+import { route } from '@/constants/routes'export function DownloadManagement() {const { t } = useTranslation()+ const navigate = useNavigate()const { open: isLeftPanelOpen } = useLeftPanel()const [isPopoverOpen, setIsPopoverOpen] = useState(false)const serviceHub = useServiceHub()@@ -159,6 +162,45 @@ export function DownloadManagement() {console.debug('onFileDownloadError', state)removeDownload(state.modelId)removeLocalDownloadingModel(state.modelId)++ const anyState = state as unknown as { error?: string }+ const err = anyState?.error || ''++ if (err.includes('HTTP status 401')) {+ toast.error('Hugging Face token required', {+ id: 'download-failed',+ description:+ 'This model requires a Hugging Face access token. Add your token in Settings and retry.',+ action: {+ label: 'Open Settings',+ onClick: () => navigate({ to: route.settings.general }),+ },+ })+ return+ }++ if (err.includes('HTTP status 403')) {+ toast.error('Accept model license on Hugging Face', {+ id: 'download-failed',+ description:+ 'You must accept the model’s license on its Hugging Face page before downloading.',+ })+ return+ }++ if (err.includes('HTTP status 429')) {+ toast.error('Rate limited by Hugging Face', {+ id: 'download-failed',+ description:+ 'You have been rate-limited. Adding a token can increase rate limits. Please try again later.',+ action: {+ label: 'Open Settings',+ onClick: () => navigate({ to: route.settings.general }),+ },+ })+ return+ }+toast.error(t('common:toast.downloadFailed.title'), {id: 'download-failed',description: t('common:toast.downloadFailed.description', {@@ -166,7 +208,7 @@ export function DownloadManagement() {}),})},- [removeDownload, removeLocalDownloadingModel, t]+ [removeDownload, removeLocalDownloadingModel, t, navigate])const onModelValidationStarted = useCallback(diff --git a/web-app/src/containers/ModelDownloadAction.tsx b/web-app/src/containers/ModelDownloadAction.tsxindex b6dab283c..e32fd642d 100644--- a/web-app/src/containers/ModelDownloadAction.tsx+++ b/web-app/src/containers/ModelDownloadAction.tsx@@ -10,6 +10,7 @@ import { CatalogModel } from '@/services/models/types'import { IconDownload } from '@tabler/icons-react'import { useNavigate } from '@tanstack/react-router'import { useCallback, useMemo } from 'react'+import { toast } from 'sonner'export const ModelDownloadAction = ({variant,@@ -54,6 +55,101 @@ export const ModelDownloadAction = ({[navigate])+ const handleDownloadModel = useCallback(async () => {+ const preflight = await serviceHub+ .models()+ .preflightArtifactAccess(variant.path, huggingfaceToken)++ const repoPage = `https://huggingface.co/${model.model_name}`++ if (!preflight.ok) {+ if (preflight.reason === 'AUTH_REQUIRED') {+ toast.error('Hugging Face token required', {+ description:+ 'This model requires a Hugging Face access token. Add your token in Settings and retry.',+ action: {+ label: 'Open Settings',+ onClick: () =>+ navigate({+ to: route.settings.general,+ params: {},+ }),+ },+ })+ return+ }++ if (preflight.reason === 'LICENSE_NOT_ACCEPTED') {+ toast.error('Accept model license on Hugging Face', {+ description:+ 'You must accept the model’s license on its Hugging Face page before downloading.',+ action: {+ label: 'Open model page',+ onClick: () => window.open(repoPage, '_blank'),+ },+ })+ return+ }++ if (preflight.reason === 'RATE_LIMITED') {+ toast.error('Rate limited by Hugging Face', {+ description:+ 'You have been rate-limited. Adding a token can increase rate limits. Please try again later.',+ action: {+ label: 'Open Settings',+ onClick: () =>+ navigate({+ to: route.settings.general,+ params: {},+ }),+ },+ })+ return+ }++ if (preflight.reason === 'NOT_FOUND') {+ toast.error('Model file not found', {+ description:+ 'The requested model could not be found. Please verify the model URL',+ action: {+ label: 'Open model page',+ onClick: () => window.open(repoPage, '_blank'),+ },+ })+ return+ }++ toast.error('Unable to start download', {+ description:+ 'Jan encountered an issue. Please check your connection and try again.',+ })+ return+ }++ addLocalDownloadingModel(variant.model_id)+ serviceHub+ .models()+ .pullModelWithMetadata(+ variant.model_id,+ variant.path,+ (+ model.mmproj_models?.find(+ (e) => e.model_id.toLowerCase() === 'mmproj-f16'+ ) || model.mmproj_models?.[0]+ )?.path,+ huggingfaceToken+ )+ }, [+ serviceHub,+ variant.path,+ variant.model_id,+ huggingfaceToken,+ model.model_name,+ model.mmproj_models,+ navigate,+ addLocalDownloadingModel,+ ])+const isDownloading =localDownloadingModels.has(variant.model_id) ||downloadProcesses.some((e) => e.id === variant.model_id)@@ -97,21 +193,7 @@ export const ModelDownloadAction = ({<divclassName="size-6 cursor-pointer flex items-center justify-center rounded hover:bg-main-view-fg/10 transition-all duration-200 ease-in-out"title={t('hub:downloadModel')}- onClick={() => {- addLocalDownloadingModel(variant.model_id)- serviceHub- .models()- .pullModelWithMetadata(- variant.model_id,- variant.path,- (- model.mmproj_models?.find(- (e) => e.model_id.toLowerCase() === 'mmproj-f16'- ) || model.mmproj_models?.[0]- )?.path,- huggingfaceToken- )- }}+ onClick={handleDownloadModel}><IconDownload size={16} className="text-main-view-fg/80" /></div>diff --git a/web-app/src/routes/settings/general.tsx b/web-app/src/routes/settings/general.tsxindex 6f30bf7f7..39b7b4551 100644--- a/web-app/src/routes/settings/general.tsx+++ b/web-app/src/routes/settings/general.tsx@@ -31,6 +31,7 @@ import LanguageSwitcher from '@/containers/LanguageSwitcher'import { PlatformFeatures } from '@/lib/platform/const'import { PlatformFeature } from '@/lib/platform/types'import { isRootDir } from '@/utils/path'+const TOKEN_VALIDATION_TIMEOUT_MS = 10_000// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.general as any)({@@ -63,6 +64,7 @@ function General() {const [selectedNewPath, setSelectedNewPath] = useState<string | null>(null)const [isDialogOpen, setIsDialogOpen] = useState(false)const [isCheckingUpdate, setIsCheckingUpdate] = useState(false)+ const [isValidatingToken, setIsValidatingToken] = useState(false)useEffect(() => {const fetchDataFolder = async () => {@@ -415,13 +417,81 @@ function General() {ns: 'settings',})}actions={- <Input- id="hf-token"- value={huggingfaceToken || ''}- onChange={(e) => setHuggingfaceToken(e.target.value)}- placeholder={'hf_xxx'}- required- />+ <div className="flex items-center gap-2">+ <Input+ id="hf-token"+ value={huggingfaceToken || ''}+ onChange={(e) => setHuggingfaceToken(e.target.value)}+ placeholder={'hf_xxx'}+ required+ />+ <Button+ variant={+ (huggingfaceToken || '').trim() ? 'default' : 'link'+ }+ className={+ (huggingfaceToken || '').trim()+ ? 'bg-green-600 text-white hover:bg-green-700'+ : ''+ }+ disabled={isValidatingToken}+ onClick={async () => {+ const token = (huggingfaceToken || '').trim()+ if (!token) {+ toast.error(+ 'Please enter a Hugging Face token to validate'+ )+ return+ }+ setIsValidatingToken(true)+ const controller = new AbortController()+ const timeoutId = setTimeout(+ () => controller.abort(),+ TOKEN_VALIDATION_TIMEOUT_MS+ )+ try {+ const resp = await fetch(+ 'https://huggingface.co/api/whoami-v2',+ {+ headers: { Authorization: `Bearer ${token}` },+ signal: controller.signal,+ }+ )+ if (resp.ok) {+ const data = await resp.json()+ toast.success('Token is valid', {+ description: data?.name+ ? `Signed in as ${data.name}`+ : 'Your Hugging Face token is valid.',+ })+ } else {+ toast.error('Token invalid', {+ description:+ 'The provided Hugging Face token is invalid. Please check your token and try again.',+ })+ }+ } catch (e) {+ const name = (e as { name?: string })?.name+ if (name === 'AbortError') {+ toast.error('Validation timed out', {+ description:+ 'The validation request timed out. Please check your network connection and try again.',+ })+ } else {+ toast.error('Validation failed', {+ description:+ 'A network error occurred while validating the token. Please check your internet connection.',+ })+ }+ } finally {+ clearTimeout(timeoutId)+ setIsValidatingToken(false)+ }+ }}+ >+ Verify+ </Button>+ </div>}/>)}diff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.tsindex 11d167a3a..65aabc152 100644--- a/web-app/src/services/models/default.ts+++ b/web-app/src/services/models/default.ts@@ -24,6 +24,7 @@ import type {ModelValidationResult,ModelPlan,} from './types'+import { PreflightResult } from './types'// TODO: Replace this with the actual provider laterconst defaultProvider = 'llamacpp'@@ -105,6 +106,37 @@ export class DefaultModelsService implements ModelsService {}}+ async preflightArtifactAccess(+ url: string,+ hfToken?: string+ ): Promise<PreflightResult> {+ try {+ const resp = await fetch(url, {+ method: 'HEAD',+ headers: hfToken+ ? {+ Authorization: `Bearer ${hfToken}`,+ }+ : {},+ })++ if (resp.ok) {+ return { ok: true, status: resp.status }+ }++ const status = resp.status+ if (status === 401) return { ok: false, status, reason: 'AUTH_REQUIRED' }+ if (status === 403)+ return { ok: false, status, reason: 'LICENSE_NOT_ACCEPTED' }+ if (status === 404) return { ok: false, status, reason: 'NOT_FOUND' }+ if (status === 429) return { ok: false, status, reason: 'RATE_LIMITED' }+ return { ok: false, status, reason: 'UNKNOWN' }+ } catch (e) {+ console.warn('Preflight artifact access failed:', e)+ return { ok: false, reason: 'NETWORK' }+ }+ }+convertHfRepoToCatalogModel(repo: HuggingFaceRepo): CatalogModel {// Format file size helperconst formatFileSize = (size?: number) => {diff --git a/web-app/src/services/models/types.ts b/web-app/src/services/models/types.tsindex 80e3c218c..8aef92db4 100644--- a/web-app/src/services/models/types.ts+++ b/web-app/src/services/models/types.ts@@ -90,6 +90,20 @@ export interface ModelPlan {mode: 'GPU' | 'Hybrid' | 'CPU' | 'Unsupported'}+export type PreflightReason =+ | 'AUTH_REQUIRED'+ | 'LICENSE_NOT_ACCEPTED'+ | 'NOT_FOUND'+ | 'RATE_LIMITED'+ | 'NETWORK'+ | 'UNKNOWN'++export interface PreflightResult {+ ok: boolean+ status?: number+ reason?: PreflightReason+}+export interface ModelsService {getModel(modelId: string): Promise<modelInfo | undefined>fetchModels(): Promise<modelInfo[]>@@ -99,6 +113,10 @@ export interface ModelsService {hfToken?: string): Promise<HuggingFaceRepo | null>convertHfRepoToCatalogModel(repo: HuggingFaceRepo): CatalogModel+ preflightArtifactAccess(+ url: string,+ hfToken?: string+ ): Promise<PreflightResult>updateModel(modelId: string, model: Partial<CoreModel>): Promise<void>pullModel(id: string,