Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
refactor: decouple platform guard logics
Louis30f75336e2f2
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex 04c1aff31..12e4c52d1 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -69,8 +69,6 @@ import {import { ExtensionManager } from '@/lib/extension'import { useAttachments } from '@/hooks/useAttachments'import { toast } from 'sonner'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'import { isPlatformTauri } from '@/lib/platform/utils'import { processAttachmentsForSend } from '@/lib/attachmentProcessing'import { useAttachmentIngestionPrompt } from '@/hooks/useAttachmentIngestionPrompt'@@ -184,9 +182,7 @@ const ChatInput = ({const parsePreference = useAttachments((s) => s.parseMode)const maxFileSizeMB = useAttachments((s) => s.maxFileSizeMB)const autoInlineContextRatio = useAttachments((s) => s.autoInlineContextRatio)- // Determine whether to show the Attach documents button (simple gating)- const showAttachmentButton =- attachmentsEnabled && PlatformFeatures[PlatformFeature.FILE_ATTACHMENTS]+// Derived: any document currently processing (ingestion in progress)const attachmentsKey = currentThreadId ?? NEW_THREAD_ATTACHMENT_KEYconst attachments = useChatAttachments(@@ -684,10 +680,6 @@ const ChatInput = ({toast.info('Attachments are disabled in Settings')return}- if (!PlatformFeatures[PlatformFeature.FILE_ATTACHMENTS]) {- toast.info('File attachments are unavailable on this platform')- return- }const selection = await serviceHub.dialog().open({multiple: true,filters: [@@ -1423,11 +1415,7 @@ const ChatInput = ({// - Enter is pressed without Shift// - The streaming content has finished// - Prompt is not empty- if (- !isStreaming &&- prompt.trim() &&- !ingestingAny- ) {+ if (!isStreaming && prompt.trim() && !ingestingAny) {handleSendMessage(prompt)}// When Shift+Enter is pressed, a new line is added (default behavior)@@ -1484,10 +1472,7 @@ const ChatInput = ({{/* RAG document attachments - desktop-only via dialog; shown when feature enabled */}<DropdownMenuItemonClick={handleAttachDocsIngest}- disabled={- !selectedModel?.capabilities?.includes('tools') &&- !showAttachmentButton- }+ disabled={!selectedModel?.capabilities?.includes('tools')}>{ingestingDocs ? (<IconLoader2@@ -1538,50 +1523,50 @@ const ChatInput = ({</TooltipProvider>)}{hasJanBrowserMCPConfig && modelSupportsBrowser && (- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <div- className={cn(- 'h-7 p-1 flex items-center justify-center rounded-sm hover:bg-main-view-fg/10 transition-all duration-200 ease-in-out gap-1 cursor-pointer',- janBrowserMCPActive && 'bg-primary/10',- isJanBrowserMCPLoading &&- 'opacity-70 cursor-not-allowed'- )}- onClick={- isJanBrowserMCPLoading- ? undefined- : handleBrowseClick- }- >- {isJanBrowserMCPLoading ? (- <IconLoader2- size={18}- className="text-primary animate-spin"- />- ) : (- <IconWorld- size={18}- className={cn(- 'text-main-view-fg/50',- janBrowserMCPActive && 'text-primary'- )}- />- )}- </div>- </TooltipTrigger>- <TooltipContent>- <p>- {isJanBrowserMCPLoading- ? 'Starting...'- : janBrowserMCPActive- ? 'Browse (Active)'- : 'Browse'}- </p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- )}+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <div+ className={cn(+ 'h-7 p-1 flex items-center justify-center rounded-sm hover:bg-main-view-fg/10 transition-all duration-200 ease-in-out gap-1 cursor-pointer',+ janBrowserMCPActive && 'bg-primary/10',+ isJanBrowserMCPLoading &&+ 'opacity-70 cursor-not-allowed'+ )}+ onClick={+ isJanBrowserMCPLoading+ ? undefined+ : handleBrowseClick+ }+ >+ {isJanBrowserMCPLoading ? (+ <IconLoader2+ size={18}+ className="text-primary animate-spin"+ />+ ) : (+ <IconWorld+ size={18}+ className={cn(+ 'text-main-view-fg/50',+ janBrowserMCPActive && 'text-primary'+ )}+ />+ )}+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>+ {isJanBrowserMCPLoading+ ? 'Starting...'+ : janBrowserMCPActive+ ? 'Browse (Active)'+ : 'Browse'}+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}{selectedModel?.capabilities?.includes('tools') &&hasActiveMCPServers &&(MCPToolComponent ? (diff --git a/web-app/src/containers/DropdownModelProvider.tsx b/web-app/src/containers/DropdownModelProvider.tsxindex 735039412..24eb15275 100644--- a/web-app/src/containers/DropdownModelProvider.tsx+++ b/web-app/src/containers/DropdownModelProvider.tsx@@ -22,8 +22,6 @@ import { useTranslation } from '@/i18n/react-i18next-compat'import { useFavoriteModel } from '@/hooks/useFavoriteModel'import { predefinedProviders } from '@/constants/providers'import { useServiceHub } from '@/hooks/useServiceHub'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'import { getLastUsedModel } from '@/utils/getModelToStart'type DropdownModelProviderProps = {@@ -179,18 +177,6 @@ const DropdownModelProvider = ({await checkAndUpdateModelVisionCapability(lastUsed.model)}} else {- // For web-only builds, auto-select the first model from jan provider- if (PlatformFeatures[PlatformFeature.WEB_AUTO_MODEL_SELECTION]) {- const janProvider = providers.find(- (p) => p.provider === 'jan' && p.active && p.models.length > 0- )- if (janProvider && janProvider.models.length > 0) {- const firstModel = janProvider.models[0]- selectModelProvider(janProvider.provider, firstModel.id)- return- }- }-// Fallback: auto-select first llamacpp model if availableconst llamacppProvider = providers.find((p) => p.provider === 'llamacpp' && p.active && p.models.length > 0@@ -203,23 +189,6 @@ const DropdownModelProvider = ({selectModelProvider('', '')}}- } else {- // Get current state for web auto-selection check- const currentState = { selectedModel, selectedProvider }- if (- PlatformFeatures[PlatformFeature.WEB_AUTO_MODEL_SELECTION] &&- !currentState.selectedModel &&- !currentState.selectedProvider- ) {- // For web-only builds, auto-select the first model from jan provider only if nothing is selected- const janProvider = providers.find(- (p) => p.provider === 'jan' && p.active && p.models.length > 0- )- if (janProvider && janProvider.models.length > 0) {- const firstModel = janProvider.models[0]- selectModelProvider(janProvider.provider, firstModel.id)- }- }}}@@ -616,26 +585,23 @@ const DropdownModelProvider = ({{getProviderTitle(providerInfo.provider)}</span></div>- {PlatformFeatures[- PlatformFeature.MODEL_PROVIDER_SETTINGS- ] && (- <div- className="size-6 cursor-pointer flex items-center justify-center rounded-sm hover:bg-main-view-fg/10 transition-all duration-200 ease-in-out"- onClick={(e) => {- e.stopPropagation()- navigate({- to: route.settings.providers,- params: { providerName: providerInfo.provider },- })- setOpen(false)- }}- >- <IconSettings- size={16}- className="text-main-view-fg/50"- />- </div>- )}++ <div+ className="size-6 cursor-pointer flex items-center justify-center rounded-sm hover:bg-main-view-fg/10 transition-all duration-200 ease-in-out"+ onClick={(e) => {+ e.stopPropagation()+ navigate({+ to: route.settings.providers,+ params: { providerName: providerInfo.provider },+ })+ setOpen(false)+ }}+ >+ <IconSettings+ size={16}+ className="text-main-view-fg/50"+ />+ </div></div>{/* Models for this provider */}diff --git a/web-app/src/containers/LeftPanel.tsx b/web-app/src/containers/LeftPanel.tsxindex 7153579db..9cf02a6b0 100644--- a/web-app/src/containers/LeftPanel.tsx+++ b/web-app/src/containers/LeftPanel.tsx@@ -22,8 +22,6 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'import { useThreads } from '@/hooks/useThreads'import { useThreadManagement } from '@/hooks/useThreadManagement'@@ -50,8 +48,7 @@ const mainMenus = [title: 'common:projects.title',icon: IconFolderPlus,route: route.project,- isEnabled:- PlatformFeatures[PlatformFeature.PROJECTS] && !(IS_IOS || IS_ANDROID),+ isEnabled: true,},]@@ -60,7 +57,7 @@ const secondaryMenus = [title: 'common:hub',icon: IconApps,route: route.hub.index,- isEnabled: PlatformFeatures[PlatformFeature.MODEL_HUB],+ isEnabled: true,},{title: 'common:settings',@@ -75,7 +72,6 @@ const LeftPanel = () => {const setLeftPanel = useLeftPanel((state) => state.setLeftPanel)const { t } = useTranslation()const navigate = useNavigate()- const projectsEnabled = PlatformFeatures[PlatformFeature.PROJECTS]const [searchDialogOpen, setSearchDialogOpen] = useState(false)const isSmallScreen = useSmallScreen()@@ -171,7 +167,9 @@ const LeftPanel = () => {}, [allThreads])const unFavoritedThreads = useMemo(() => {- return allThreads.filter((t: Thread) => !t.isFavorite && !t.metadata?.project)+ return allThreads.filter(+ (t: Thread) => !t.isFavorite && !t.metadata?.project+ )}, [allThreads])// Project handlers@@ -230,11 +228,11 @@ const LeftPanel = () => {isResizableContext && 'h-full w-full',// Small screen context: fixed positioning and stylingisSmallScreen &&- 'fixed h-full pb-[calc(env(safe-area-inset-bottom)+env(safe-area-inset-top))] bg-main-view z-50 md:border border-left-panel-fg/10 px-1 w-full md:w-48',+ 'fixed h-full pb-[calc(env(safe-area-inset-bottom)+env(safe-area-inset-top))] bg-main-view z-50 md:border border-left-panel-fg/10 px-1 w-full md:w-48',// Default context: original styling!isResizableContext &&- !isSmallScreen &&- 'w-48 shrink-0 rounded-lg m-1.5 mr-0',+ !isSmallScreen &&+ 'w-48 shrink-0 rounded-lg m-1.5 mr-0',// Visibility controlsopen? 'opacity-100 visibility-visible'@@ -308,103 +306,98 @@ const LeftPanel = () => {})}</div>- {projectsEnabled &&- folders.length > 0 &&- !(IS_IOS || IS_ANDROID) && (- <div className="space-y-1 py-1">- <div className="flex items-center justify-between mb-2">- <span className="block text-xs text-left-panel-fg/50 px-1 font-semibold">- {t('common:projects.title')}- </span>- </div>- <div className="flex flex-col max-h-[140px] overflow-y-scroll">- {folders- .slice()- .sort((a, b) => b.updated_at - a.updated_at)- .map((folder) => {- const ProjectItem = () => {- const [openDropdown, setOpenDropdown] = useState(false)- const isProjectActive =- currentPath === `/project/${folder.id}`-- return (- <div key={folder.id} className="mb-1">- <div- className={cn(- 'rounded hover:bg-left-panel-fg/10 flex items-center justify-between gap-2 px-1.5 group/project-list transition-all cursor-pointer',- isProjectActive && 'bg-left-panel-fg/10'- )}- onContextMenu={(e) => {- e.preventDefault()- }}+ {folders.length > 0 && !(IS_IOS || IS_ANDROID) && (+ <div className="space-y-1 py-1">+ <div className="flex items-center justify-between mb-2">+ <span className="block text-xs text-left-panel-fg/50 px-1 font-semibold">+ {t('common:projects.title')}+ </span>+ </div>+ <div className="flex flex-col max-h-[140px] overflow-y-scroll">+ {folders+ .slice()+ .sort((a, b) => b.updated_at - a.updated_at)+ .map((folder) => {+ const ProjectItem = () => {+ const [openDropdown, setOpenDropdown] = useState(false)+ const isProjectActive =+ currentPath === `/project/${folder.id}`++ return (+ <div key={folder.id} className="mb-1">+ <div+ className={cn(+ 'rounded hover:bg-left-panel-fg/10 flex items-center justify-between gap-2 px-1.5 group/project-list transition-all cursor-pointer',+ isProjectActive && 'bg-left-panel-fg/10'+ )}+ onContextMenu={(e) => {+ e.preventDefault()+ }}+ >+ <Link+ to="/project/$projectId"+ params={{ projectId: folder.id }}+ onClick={() =>+ isSmallScreen && setLeftPanel(false)+ }+ className="py-1 pr-2 truncate flex items-center gap-2 flex-1">- <Link- to="/project/$projectId"- params={{ projectId: folder.id }}- onClick={() =>- isSmallScreen && setLeftPanel(false)- }- className="py-1 pr-2 truncate flex items-center gap-2 flex-1"+ <IconFolder+ size={16}+ className="text-left-panel-fg/70 shrink-0"+ />+ <span className="text-sm text-left-panel-fg/90 truncate">+ {folder.name}+ </span>+ </Link>+ <div className="flex items-center">+ <DropdownMenu+ open={openDropdown}+ onOpenChange={(open) => setOpenDropdown(open)}>- <IconFolder- size={16}- className="text-left-panel-fg/70 shrink-0"- />- <span className="text-sm text-left-panel-fg/90 truncate">- {folder.name}- </span>- </Link>- <div className="flex items-center">- <DropdownMenu- open={openDropdown}- onOpenChange={(open) => setOpenDropdown(open)}- >- <DropdownMenuTrigger asChild>- <IconDots- size={14}- className="text-left-panel-fg/60 shrink-0 cursor-pointer px-0.5 -mr-1 data-[state=open]:bg-left-panel-fg/10 rounded group-hover/project-list:data-[state=closed]:size-5 size-5 data-[state=closed]:size-0"- onClick={(e) => {- e.preventDefault()- e.stopPropagation()- }}- />- </DropdownMenuTrigger>- <DropdownMenuContent- side="bottom"- align="end"+ <DropdownMenuTrigger asChild>+ <IconDots+ size={14}+ className="text-left-panel-fg/60 shrink-0 cursor-pointer px-0.5 -mr-1 data-[state=open]:bg-left-panel-fg/10 rounded group-hover/project-list:data-[state=closed]:size-5 size-5 data-[state=closed]:size-0"+ onClick={(e) => {+ e.preventDefault()+ e.stopPropagation()+ }}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent side="bottom" align="end">+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation()+ setEditingProjectKey(folder.id)+ setProjectDialogOpen(true)+ }}>- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation()- setEditingProjectKey(folder.id)- setProjectDialogOpen(true)- }}- >- <IconPencil size={16} />- <span>Edit</span>- </DropdownMenuItem>- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation()- handleProjectDelete(folder.id)- }}- >- <IconTrash size={16} />- <span>Delete</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>+ <IconPencil size={16} />+ <span>Edit</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation()+ handleProjectDelete(folder.id)+ }}+ >+ <IconTrash size={16} />+ <span>Delete</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></div></div>- )- }+ </div>+ )+ }- return <ProjectItem key={folder.id} />- })}- </div>+ return <ProjectItem key={folder.id} />+ })}</div>- )}+ </div>+ )}<div className="flex flex-col h-full overflow-y-scroll w-[calc(100%+6px)]"><div className="flex flex-col w-full h-full overflow-y-auto overflow-x-hidden mb-3">@@ -541,7 +534,7 @@ const LeftPanel = () => {</aside>{/* Project Dialogs */}- {projectsEnabled && (+ {<><AddProjectDialogopen={projectDialogOpen}@@ -563,10 +556,13 @@ const LeftPanel = () => {}/></>- )}+ }{/* Search Dialog */}- <SearchDialog open={searchDialogOpen} onOpenChange={setSearchDialogOpen} />+ <SearchDialog+ open={searchDialogOpen}+ onOpenChange={setSearchDialogOpen}+ /></>)}diff --git a/web-app/src/containers/SettingsMenu.tsx b/web-app/src/containers/SettingsMenu.tsxindex b66e94a23..2c6b10c75 100644--- a/web-app/src/containers/SettingsMenu.tsx+++ b/web-app/src/containers/SettingsMenu.tsx@@ -14,8 +14,6 @@ import { cn } from '@/lib/utils'import { useModelProvider } from '@/hooks/useModelProvider'import { getProviderTitle } from '@/lib/utils'import ProvidersAvatar from '@/containers/ProvidersAvatar'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'const SettingsMenu = () => {const { t } = useTranslation()@@ -31,14 +29,6 @@ const SettingsMenu = () => {const activeProviders = providers.filter((provider) => {if (!provider.active) return false- // On web version, hide llamacpp provider- if (- !PlatformFeatures[PlatformFeature.LOCAL_INFERENCE] &&- provider.provider === 'llama.cpp'- ) {- return false- }-return true})@@ -77,7 +67,7 @@ const SettingsMenu = () => {title: 'common:attachments',route: route.settings.attachments,hasSubMenu: false,- isEnabled: PlatformFeatures[PlatformFeature.FILE_ATTACHMENTS],+ isEnabled: true,},{title: 'common:interface',@@ -89,55 +79,55 @@ const SettingsMenu = () => {title: 'common:privacy',route: route.settings.privacy,hasSubMenu: false,- isEnabled: PlatformFeatures[PlatformFeature.ANALYTICS],+ isEnabled: true,},{title: 'common:modelProviders',route: route.settings.model_providers,hasSubMenu: activeProviders.length > 0,- isEnabled: PlatformFeatures[PlatformFeature.MODEL_PROVIDER_SETTINGS],+ isEnabled: true,},{title: 'common:assistants',route: route.settings.assistant,hasSubMenu: false,- isEnabled: PlatformFeatures[PlatformFeature.ASSISTANTS],+ isEnabled: true,},{title: 'common:keyboardShortcuts',route: route.settings.shortcuts,hasSubMenu: false,- isEnabled: PlatformFeatures[PlatformFeature.SHORTCUT],+ isEnabled: true,},{title: 'common:hardware',route: route.settings.hardware,hasSubMenu: false,- isEnabled: PlatformFeatures[PlatformFeature.HARDWARE_MONITORING],+ isEnabled: true,},{title: 'common:mcp-servers',route: route.settings.mcp_servers,hasSubMenu: false,- isEnabled: PlatformFeatures[PlatformFeature.MCP_SERVERS_SETTINGS],+ isEnabled: true,},{title: 'common:local_api_server',route: route.settings.local_api_server,hasSubMenu: false,- isEnabled: PlatformFeatures[PlatformFeature.LOCAL_API_SERVER],+ isEnabled: true,},{title: 'common:https_proxy',route: route.settings.https_proxy,hasSubMenu: false,- isEnabled: PlatformFeatures[PlatformFeature.HTTPS_PROXY],+ isEnabled: true,},{title: 'common:extensions',route: route.settings.extensions,hasSubMenu: false,- isEnabled: PlatformFeatures[PlatformFeature.EXTENSIONS_SETTINGS],+ isEnabled: true,},]diff --git a/web-app/src/containers/SetupScreen.tsx b/web-app/src/containers/SetupScreen.tsxindex ec646ba01..88ab9563f 100644--- a/web-app/src/containers/SetupScreen.tsx+++ b/web-app/src/containers/SetupScreen.tsx@@ -5,12 +5,7 @@ import { route } from '@/constants/routes'import HeaderPage from './HeaderPage'import { isProd } from '@/lib/version'import { useTranslation } from '@/i18n/react-i18next-compat'-import {- localStorageKey,- CACHE_EXPIRY_MS,-} from '@/constants/localStorage'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform'+import { localStorageKey, CACHE_EXPIRY_MS } from '@/constants/localStorage'import { useDownloadStore } from '@/hooks/useDownloadStore'import { useServiceHub } from '@/hooks/useServiceHub'import { useEffect, useMemo, useCallback, useState, useRef } from 'react'@@ -22,8 +17,6 @@ import {} from '@/constants/models'import { toast } from 'sonner'-const isQuickStartAvailable = PlatformFeatures[PlatformFeature.LOCAL_INFERENCE]-type CacheEntry = {status: 'RED' | 'YELLOW' | 'GREEN' | 'GREY'timestamp: number@@ -57,7 +50,9 @@ function saveCacheToStorage() {}}-function getCachedSupport(modelId: string): 'RED' | 'YELLOW' | 'GREEN' | 'GREY' | null {+function getCachedSupport(+ modelId: string+): 'RED' | 'YELLOW' | 'GREEN' | 'GREY' | null {const entry = modelSupportCache.get(modelId)if (!entry) return null@@ -70,7 +65,10 @@ function getCachedSupport(modelId: string): 'RED' | 'YELLOW' | 'GREEN' | 'GREY'return entry.status}-function setCachedSupport(modelId: string, status: 'RED' | 'YELLOW' | 'GREEN' | 'GREY') {+function setCachedSupport(+ modelId: string,+ status: 'RED' | 'YELLOW' | 'GREEN' | 'GREY'+) {modelSupportCache.set(modelId, {status,timestamp: Date.now(),@@ -106,8 +104,6 @@ function SetupScreen() {const [isSupportCheckComplete, setIsSupportCheckComplete] = useState(false)const fetchJanModel = useCallback(async () => {- if (!isQuickStartAvailable) return-setMetadataFetchFailed(false)try {const repo = await serviceHub@@ -115,7 +111,9 @@ function SetupScreen() {.fetchHuggingFaceRepo(JAN_MODEL_V2_HF_REPO)if (repo) {- const catalogModel = serviceHub.models().convertHfRepoToCatalogModel(repo)+ const catalogModel = serviceHub+ .models()+ .convertHfRepoToCatalogModel(repo)setJanModelV2(catalogModel)} else {setMetadataFetchFailed(true)@@ -155,9 +153,7 @@ function SetupScreen() {if (variant) {const cached = getCachedSupport(variant.model_id)if (cached) {- console.log(- `[SetupScreen] ${variant.model_id}: ${cached} (cached)`- )+ console.log(`[SetupScreen] ${variant.model_id}: ${cached} (cached)`)variantSupportMap.set(variant.model_id, cached)continue}@@ -294,19 +290,17 @@ function SetupScreen() {setQuickStartInitiated(true)addLocalDownloadingModel(defaultVariant.model_id)- serviceHub- .models()- .pullModelWithMetadata(- defaultVariant.model_id,- defaultVariant.path,- (- janModelV2.mmproj_models?.find(- (e) => e.model_id.toLowerCase() === 'mmproj-f16'- ) || janModelV2.mmproj_models?.[0]- )?.path,- undefined, // No HF token needed for public model- true // Skip verification for faster download- )+ serviceHub.models().pullModelWithMetadata(+ defaultVariant.model_id,+ defaultVariant.path,+ (+ janModelV2.mmproj_models?.find(+ (e) => e.model_id.toLowerCase() === 'mmproj-f16'+ ) || janModelV2.mmproj_models?.[0]+ )?.path,+ undefined, // No HF token needed for public model+ true // Skip verification for faster download+ )}, [defaultVariant,janModelV2,@@ -317,7 +311,12 @@ function SetupScreen() {// Process queued quick start when metadata becomes availableuseEffect(() => {- if (quickStartQueued && defaultVariant && janModelV2 && isSupportCheckComplete) {+ if (+ quickStartQueued &&+ defaultVariant &&+ janModelV2 &&+ isSupportCheckComplete+ ) {setQuickStartQueued(false)addLocalDownloadingModel(defaultVariant.model_id)serviceHub@@ -334,7 +333,14 @@ function SetupScreen() {true)}- }, [quickStartQueued, defaultVariant, janModelV2, isSupportCheckComplete, addLocalDownloadingModel, serviceHub])+ }, [+ quickStartQueued,+ defaultVariant,+ janModelV2,+ isSupportCheckComplete,+ addLocalDownloadingModel,+ serviceHub,+ ])// Handle error when quick start is queued but metadata fetch failsuseEffect(() => {@@ -350,7 +356,12 @@ function SetupScreen() {}, [quickStartQueued, metadataFetchFailed, t])useEffect(() => {- if (quickStartInitiated && !quickStartQueued && !isDownloading && !isDownloaded) {+ if (+ quickStartInitiated &&+ !quickStartQueued &&+ !isDownloading &&+ !isDownloaded+ ) {setQuickStartInitiated(false)}}, [quickStartInitiated, quickStartQueued, isDownloading, isDownloaded])@@ -382,126 +393,111 @@ function SetupScreen() {<h1 className="font-studio text-main-view-fg text-4xl">{t('setup:welcome')}</h1>- {!isQuickStartAvailable && (- <p className="text-main-view-fg/70 text-lg mt-2">- {t('setup:descriptionWeb')}- </p>- )}</div><div className="flex gap-4 flex-col">{/* Quick Start Button - Highlighted */}- {PlatformFeatures[PlatformFeature.LOCAL_INFERENCE] && (- <button- onClick={handleQuickStart}- disabled={- quickStartInitiated ||- isDownloading ||- isDownloaded- }- className="w-full text-left"- >- <div className="bg-gradient-to-r from-blue-500/20 to-purple-500/20 p-5 rounded-lg border-2 border-blue-500/50 hover:border-blue-500/70 transition-all hover:shadow-lg disabled:opacity-60 disabled:hover:border-blue-500/50">- <div className="flex items-start gap-3">- <div className="flex-shrink-0 w-10 h-10 bg-blue-500 rounded-lg flex items-center justify-center">- {quickStartInitiated || isDownloading ? (- <svg- xmlns="http://www.w3.org/2000/svg"- className="h-6 w-6 text-white animate-spin"- fill="none"- viewBox="0 0 24 24"- stroke="currentColor"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"- />- </svg>- ) : (- <svg- xmlns="http://www.w3.org/2000/svg"- className="h-6 w-6 text-white"- fill="none"- viewBox="0 0 24 24"- stroke="currentColor"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M13 10V3L4 14h7v7l9-11h-7z"+ <button+ onClick={handleQuickStart}+ disabled={quickStartInitiated || isDownloading || isDownloaded}+ className="w-full text-left"+ >+ <div className="bg-gradient-to-r from-blue-500/20 to-purple-500/20 p-5 rounded-lg border-2 border-blue-500/50 hover:border-blue-500/70 transition-all hover:shadow-lg disabled:opacity-60 disabled:hover:border-blue-500/50">+ <div className="flex items-start gap-3">+ <div className="flex-shrink-0 w-10 h-10 bg-blue-500 rounded-lg flex items-center justify-center">+ {quickStartInitiated || isDownloading ? (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ className="h-6 w-6 text-white animate-spin"+ fill="none"+ viewBox="0 0 24 24"+ stroke="currentColor"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"+ />+ </svg>+ ) : (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ className="h-6 w-6 text-white"+ fill="none"+ viewBox="0 0 24 24"+ stroke="currentColor"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M13 10V3L4 14h7v7l9-11h-7z"+ />+ </svg>+ )}+ </div>+ <div className="flex-1">+ <h1 className="text-main-view-fg font-semibold text-lg mb-1">+ {quickStartInitiated || isDownloading+ ? t('setup:downloading', {+ defaultValue: 'Downloading Jan Model...',+ })+ : t('setup:quickStart')}+ </h1>+ {quickStartInitiated || isDownloading ? (+ <div className="space-y-2">+ <div className="flex items-center gap-3">+ <Progress+ value={downloadProgress * 100}+ className="flex-1"/>- </svg>- )}- </div>- <div className="flex-1">- <h1 className="text-main-view-fg font-semibold text-lg mb-1">- {quickStartInitiated || isDownloading- ? t('setup:downloading', {- defaultValue: 'Downloading Jan Model...',- })- : t('setup:quickStart')}- </h1>- {quickStartInitiated || isDownloading ? (- <div className="space-y-2">- <div className="flex items-center gap-3">- <Progress- value={downloadProgress * 100}- className="flex-1"- />- <span className="text-sm text-main-view-fg/70 font-medium min-w-[3rem] text-right">- {Math.round(downloadProgress * 100)}%- </span>- </div>- <p className="text-main-view-fg/70 text-xs">- {t('setup:downloadingDescription', {- defaultValue:- 'Please wait while we download the model. This may take a few minutes.',- })}- </p>+ <span className="text-sm text-main-view-fg/70 font-medium min-w-[3rem] text-right">+ {Math.round(downloadProgress * 100)}%+ </span></div>- ) : (- <p className="text-main-view-fg/70 text-sm">- {t('setup:quickStartDescription')}+ <p className="text-main-view-fg/70 text-xs">+ {t('setup:downloadingDescription', {+ defaultValue:+ 'Please wait while we download the model. This may take a few minutes.',+ })}</p>- )}- </div>+ </div>+ ) : (+ <p className="text-main-view-fg/70 text-sm">+ {t('setup:quickStartDescription')}+ </p>+ )}</div></div>- </button>- )}+ </div>+ </button>{/* "or" divider */}- {PlatformFeatures[PlatformFeature.LOCAL_INFERENCE] && (- <div className="flex items-center gap-3">- <div className="flex-1 h-px bg-main-view-fg/10"></div>- <span className="text-main-view-fg/50 text-sm font-medium">- {t('setup:orDivider')}- </span>- <div className="flex-1 h-px bg-main-view-fg/10"></div>- </div>- )}+ <div className="flex items-center gap-3">+ <div className="flex-1 h-px bg-main-view-fg/10"></div>+ <span className="text-main-view-fg/50 text-sm font-medium">+ {t('setup:orDivider')}+ </span>+ <div className="flex-1 h-px bg-main-view-fg/10"></div>+ </div>{/* Set up local model */}- {PlatformFeatures[PlatformFeature.LOCAL_INFERENCE] && (- <Link- to={route.hub.index}- search={{- ...(!isProd ? { step: 'setup_local_provider' } : {}),- }}- >- <Card- header={- <div>- <h1 className="text-main-view-fg font-medium text-base">- {t('setup:localModel')}- </h1>- </div>- }- />- </Link>- )}+ <Link+ to={route.hub.index}+ search={{+ ...(!isProd ? { step: 'setup_local_provider' } : {}),+ }}+ >+ <Card+ header={+ <div>+ <h1 className="text-main-view-fg font-medium text-base">+ {t('setup:localModel')}+ </h1>+ </div>+ }+ />+ </Link>{/* Set up remote provider */}<Linkdiff --git a/web-app/src/containers/ThreadList.tsx b/web-app/src/containers/ThreadList.tsxindex ae3377882..75cbce053 100644--- a/web-app/src/containers/ThreadList.tsx+++ b/web-app/src/containers/ThreadList.tsx@@ -26,8 +26,6 @@ import { useLeftPanel } from '@/hooks/useLeftPanel'import { useMessages } from '@/hooks/useMessages'import { cn, extractThinkingContent } from '@/lib/utils'import { useSmallScreen } from '@/hooks/useMediaQuery'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'import {DropdownMenu,@@ -92,8 +90,6 @@ const SortableItem = memo('threadId' in match.params &&match.params.threadId === thread.id)- const projectsEnabled = PlatformFeatures[PlatformFeature.PROJECTS]-const handleClick = (e: MouseEvent<HTMLDivElement>) => {if (openDropdown) {e.stopPropagation()@@ -116,9 +112,6 @@ const SortableItem = memo(}, [thread.title])const availableProjects = useMemo(() => {- if (!projectsEnabled) {- return []- }return folders.filter((f) => {// Exclude the current project page we're on@@ -128,18 +121,9 @@ const SortableItem = memo(return true}).sort((a, b) => b.updated_at - a.updated_at)- }, [- projectsEnabled,- folders,- currentProjectId,- thread.metadata?.project?.id,- ])+ }, [folders, currentProjectId, thread.metadata?.project?.id])const assignThreadToProject = (threadId: string, projectId: string) => {- if (!projectsEnabled) {- return- }-const project = getFolderById(projectId)if (project && updateThread) {const projectMetadata = {@@ -251,39 +235,37 @@ const SortableItem = memo(onDropdownClose={() => setOpenDropdown(false)}/>- {projectsEnabled && (- <DropdownMenuSub>- <DropdownMenuSubTrigger className="gap-2">- <IconFolder size={16} />- <span>{t('common:projects.addToProject')}</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent className="max-h-60 min-w-44 overflow-y-auto">- {availableProjects.length === 0 ? (- <DropdownMenuItem disabled>- <span className="text-left-panel-fg/50">- {t('common:projects.noProjectsAvailable')}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-2">+ <IconFolder size={16} />+ <span>{t('common:projects.addToProject')}</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-60 min-w-44 overflow-y-auto">+ {availableProjects.length === 0 ? (+ <DropdownMenuItem disabled>+ <span className="text-left-panel-fg/50">+ {t('common:projects.noProjectsAvailable')}+ </span>+ </DropdownMenuItem>+ ) : (+ availableProjects.map((folder) => (+ <DropdownMenuItem+ key={folder.id}+ onClick={(e) => {+ e.stopPropagation()+ assignThreadToProject(thread.id, folder.id)+ }}+ >+ <IconFolder size={16} />+ <span className="truncate max-w-[200px]">+ {folder.name}</span></DropdownMenuItem>- ) : (- availableProjects.map((folder) => (- <DropdownMenuItem- key={folder.id}- onClick={(e) => {- e.stopPropagation()- assignThreadToProject(thread.id, folder.id)- }}- >- <IconFolder size={16} />- <span className="truncate max-w-[200px]">- {folder.name}- </span>- </DropdownMenuItem>- ))- )}- </DropdownMenuSubContent>- </DropdownMenuSub>- )}- {projectsEnabled && thread.metadata?.project && (+ ))+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ {thread.metadata?.project && (<><DropdownMenuSeparator /><DropdownMenuItemdiff --git a/web-app/src/hooks/useAssistant.ts b/web-app/src/hooks/useAssistant.tsindex 19192e9e5..0cded79eb 100644--- a/web-app/src/hooks/useAssistant.ts+++ b/web-app/src/hooks/useAssistant.ts@@ -2,8 +2,6 @@ import { getServiceHub } from '@/hooks/useServiceHub'import { Assistant as CoreAssistant } from '@janhq/core'import { create } from 'zustand'import { localStorageKey } from '@/constants/localStorage'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'interface AssistantState {assistants: Assistant[]@@ -50,16 +48,9 @@ export const defaultAssistant: Assistant = {// Platform-aware initial stateconst getInitialAssistantState = () => {- if (PlatformFeatures[PlatformFeature.ASSISTANTS]) {- return {- assistants: [defaultAssistant],- currentAssistant: defaultAssistant,- }- } else {- return {- assistants: [],- currentAssistant: null,- }+ return {+ assistants: [defaultAssistant],+ currentAssistant: defaultAssistant,}}diff --git a/web-app/src/hooks/useAttachments.ts b/web-app/src/hooks/useAttachments.tsindex 54b335521..85e2838c4 100644--- a/web-app/src/hooks/useAttachments.ts+++ b/web-app/src/hooks/useAttachments.ts@@ -1,8 +1,10 @@import { create } from 'zustand'import { ExtensionManager } from '@/lib/extension'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'-import { ExtensionTypeEnum, type RAGExtension, type SettingComponentProps } from '@janhq/core'+import {+ ExtensionTypeEnum,+ type RAGExtension,+ type SettingComponentProps,+} from '@janhq/core'export type AttachmentsSettings = {enabled: boolean@@ -33,17 +35,16 @@ type AttachmentsStore = AttachmentsSettings & {const getRagExtension = (): RAGExtension | undefined => {try {- return ExtensionManager.getInstance().get<RAGExtension>(ExtensionTypeEnum.RAG)+ return ExtensionManager.getInstance().get<RAGExtension>(+ ExtensionTypeEnum.RAG+ )} catch {return undefined}}-const fileAttachmentsFeatureEnabled =- PlatformFeatures[PlatformFeature.FILE_ATTACHMENTS]-export const useAttachments = create<AttachmentsStore>()((set) => ({- enabled: fileAttachmentsFeatureEnabled,+ enabled: true,maxFileSizeMB: 20,retrievalLimit: 3,retrievalThreshold: 0.3,@@ -61,19 +62,22 @@ export const useAttachments = create<AttachmentsStore>()((set) => ({if (!Array.isArray(defs)) return falseconst map = new Map<string, unknown>()- defs.forEach((setting) => map.set(setting.key, setting?.controllerProps?.value))+ defs.forEach((setting) =>+ map.set(setting.key, setting?.controllerProps?.value)+ )set((prev) => ({settingsDefs: defs,- enabled:- fileAttachmentsFeatureEnabled &&- ((map.get('enabled') as boolean | undefined) ?? prev.enabled),+ enabled: (map.get('enabled') as boolean | undefined) ?? prev.enabled,maxFileSizeMB:- (map.get('max_file_size_mb') as number | undefined) ?? prev.maxFileSizeMB,+ (map.get('max_file_size_mb') as number | undefined) ??+ prev.maxFileSizeMB,retrievalLimit:- (map.get('retrieval_limit') as number | undefined) ?? prev.retrievalLimit,+ (map.get('retrieval_limit') as number | undefined) ??+ prev.retrievalLimit,retrievalThreshold:- (map.get('retrieval_threshold') as number | undefined) ?? prev.retrievalThreshold,+ (map.get('retrieval_threshold') as number | undefined) ??+ prev.retrievalThreshold,chunkSizeChars:(map.get('chunk_size_chars') as number | undefined) ??(map.get('chunk_size_tokens') as number | undefined) ??@@ -86,8 +90,12 @@ export const useAttachments = create<AttachmentsStore>()((set) => ({(map.get('search_mode') as 'auto' | 'ann' | 'linear' | undefined) ??prev.searchMode,parseMode:- (map.get('parse_mode') as 'auto' | 'inline' | 'embeddings' | 'prompt' | undefined) ??- prev.parseMode,+ (map.get('parse_mode') as+ | 'auto'+ | 'inline'+ | 'embeddings'+ | 'prompt'+ | undefined) ?? prev.parseMode,autoInlineContextRatio:(map.get('auto_inline_context_ratio') as number | undefined) ??prev.autoInlineContextRatio,@@ -100,167 +108,199 @@ export const useAttachments = create<AttachmentsStore>()((set) => ({}},setEnabled: async (v) => {- if (!fileAttachmentsFeatureEnabled) {- set((s) => ({- enabled: false,- settingsDefs: s.settingsDefs.map((d) =>- d.key === 'enabled'- ? ({- ...d,- controllerProps: { ...d.controllerProps, value: false },- } as SettingComponentProps)- : d- ),- }))- return- }const ext = getRagExtension()if (ext?.updateSettings) {await ext.updateSettings([- { key: 'enabled', controllerProps: { value: !!v } } as Partial<SettingComponentProps>,+ {+ key: 'enabled',+ controllerProps: { value: !!v },+ } as Partial<SettingComponentProps>,])}set((s) => ({enabled: v,settingsDefs: s.settingsDefs.map((d) =>d.key === 'enabled'- ? ({ ...d, controllerProps: { ...d.controllerProps, value: !!v } } as SettingComponentProps)+ ? ({+ ...d,+ controllerProps: { ...d.controllerProps, value: !!v },+ } as SettingComponentProps): d),}))},setMaxFileSizeMB: async (val) => {- if (!fileAttachmentsFeatureEnabled) returnconst ext = getRagExtension()if (ext?.updateSettings) {await ext.updateSettings([- { key: 'max_file_size_mb', controllerProps: { value: val } } as Partial<SettingComponentProps>,+ {+ key: 'max_file_size_mb',+ controllerProps: { value: val },+ } as Partial<SettingComponentProps>,])}set((s) => ({maxFileSizeMB: val,settingsDefs: s.settingsDefs.map((d) =>d.key === 'max_file_size_mb'- ? ({ ...d, controllerProps: { ...d.controllerProps, value: val } } as SettingComponentProps)+ ? ({+ ...d,+ controllerProps: { ...d.controllerProps, value: val },+ } as SettingComponentProps): d),}))},setRetrievalLimit: async (val) => {- if (!fileAttachmentsFeatureEnabled) returnconst ext = getRagExtension()if (ext?.updateSettings) {await ext.updateSettings([- { key: 'retrieval_limit', controllerProps: { value: val } } as Partial<SettingComponentProps>,+ {+ key: 'retrieval_limit',+ controllerProps: { value: val },+ } as Partial<SettingComponentProps>,])}set((s) => ({retrievalLimit: val,settingsDefs: s.settingsDefs.map((d) =>d.key === 'retrieval_limit'- ? ({ ...d, controllerProps: { ...d.controllerProps, value: val } } as SettingComponentProps)+ ? ({+ ...d,+ controllerProps: { ...d.controllerProps, value: val },+ } as SettingComponentProps): d),}))},setRetrievalThreshold: async (val) => {- if (!fileAttachmentsFeatureEnabled) returnconst ext = getRagExtension()if (ext?.updateSettings) {await ext.updateSettings([- { key: 'retrieval_threshold', controllerProps: { value: val } } as Partial<SettingComponentProps>,+ {+ key: 'retrieval_threshold',+ controllerProps: { value: val },+ } as Partial<SettingComponentProps>,])}set((s) => ({retrievalThreshold: val,settingsDefs: s.settingsDefs.map((d) =>d.key === 'retrieval_threshold'- ? ({ ...d, controllerProps: { ...d.controllerProps, value: val } } as SettingComponentProps)+ ? ({+ ...d,+ controllerProps: { ...d.controllerProps, value: val },+ } as SettingComponentProps): d),}))},setChunkSizeChars: async (val) => {- if (!fileAttachmentsFeatureEnabled) returnconst ext = getRagExtension()if (ext?.updateSettings) {await ext.updateSettings([- { key: 'chunk_size_chars', controllerProps: { value: val } } as Partial<SettingComponentProps>,+ {+ key: 'chunk_size_chars',+ controllerProps: { value: val },+ } as Partial<SettingComponentProps>,])}set((s) => ({chunkSizeChars: val,settingsDefs: s.settingsDefs.map((d) =>d.key === 'chunk_size_chars'- ? ({ ...d, controllerProps: { ...d.controllerProps, value: val } } as SettingComponentProps)+ ? ({+ ...d,+ controllerProps: { ...d.controllerProps, value: val },+ } as SettingComponentProps): d),}))},setOverlapChars: async (val) => {- if (!fileAttachmentsFeatureEnabled) returnconst ext = getRagExtension()if (ext?.updateSettings) {await ext.updateSettings([- { key: 'overlap_chars', controllerProps: { value: val } } as Partial<SettingComponentProps>,+ {+ key: 'overlap_chars',+ controllerProps: { value: val },+ } as Partial<SettingComponentProps>,])}set((s) => ({overlapChars: val,settingsDefs: s.settingsDefs.map((d) =>d.key === 'overlap_chars'- ? ({ ...d, controllerProps: { ...d.controllerProps, value: val } } as SettingComponentProps)+ ? ({+ ...d,+ controllerProps: { ...d.controllerProps, value: val },+ } as SettingComponentProps): d),}))},setSearchMode: async (v) => {- if (!fileAttachmentsFeatureEnabled) returnconst ext = getRagExtension()if (ext?.updateSettings) {await ext.updateSettings([- { key: 'search_mode', controllerProps: { value: v } } as Partial<SettingComponentProps>,+ {+ key: 'search_mode',+ controllerProps: { value: v },+ } as Partial<SettingComponentProps>,])}set((s) => ({searchMode: v,settingsDefs: s.settingsDefs.map((d) =>d.key === 'search_mode'- ? ({ ...d, controllerProps: { ...d.controllerProps, value: v } } as SettingComponentProps)+ ? ({+ ...d,+ controllerProps: { ...d.controllerProps, value: v },+ } as SettingComponentProps): d),}))},setParseMode: async (v) => {- if (!fileAttachmentsFeatureEnabled) returnconst ext = getRagExtension()if (ext?.updateSettings) {await ext.updateSettings([- { key: 'parse_mode', controllerProps: { value: v } } as Partial<SettingComponentProps>,+ {+ key: 'parse_mode',+ controllerProps: { value: v },+ } as Partial<SettingComponentProps>,])}set((s) => ({parseMode: v,settingsDefs: s.settingsDefs.map((d) =>d.key === 'parse_mode'- ? ({ ...d, controllerProps: { ...d.controllerProps, value: v } } as SettingComponentProps)+ ? ({+ ...d,+ controllerProps: { ...d.controllerProps, value: v },+ } as SettingComponentProps): d),}))},setAutoInlineContextRatio: async (val) => {- if (!fileAttachmentsFeatureEnabled) returnconst ext = getRagExtension()if (ext?.updateSettings) {await ext.updateSettings([- { key: 'auto_inline_context_ratio', controllerProps: { value: val } } as Partial<SettingComponentProps>,+ {+ key: 'auto_inline_context_ratio',+ controllerProps: { value: val },+ } as Partial<SettingComponentProps>,])}set((s) => ({autoInlineContextRatio: val,settingsDefs: s.settingsDefs.map((d) =>d.key === 'auto_inline_context_ratio'- ? ({ ...d, controllerProps: { ...d.controllerProps, value: val } } as SettingComponentProps)+ ? ({+ ...d,+ controllerProps: { ...d.controllerProps, value: val },+ } as SettingComponentProps): d),}))diff --git a/web-app/src/hooks/useToolApproval.ts b/web-app/src/hooks/useToolApproval.tsindex 446cefbc0..0e49cb462 100644--- a/web-app/src/hooks/useToolApproval.ts+++ b/web-app/src/hooks/useToolApproval.ts@@ -1,8 +1,6 @@import { create } from 'zustand'import { persist, createJSONStorage } from 'zustand/middleware'import { localStorageKey } from '@/constants/localStorage'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'export type ToolApprovalModalProps = {toolName: string@@ -34,7 +32,7 @@ export const useToolApproval = create<ToolApprovalState>()(persist((set, get) => ({approvedTools: {},- allowAllMCPPermissions: PlatformFeatures[PlatformFeature.MCP_AUTO_APPROVE_TOOLS],+ allowAllMCPPermissions: false,isModalOpen: false,modalProps: null,diff --git a/web-app/src/lib/attachmentProcessing.ts b/web-app/src/lib/attachmentProcessing.tsindex ffd08194a..649271637 100644--- a/web-app/src/lib/attachmentProcessing.ts+++ b/web-app/src/lib/attachmentProcessing.ts@@ -1,14 +1,8 @@-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'import { ServiceHub } from '@/services'import { Attachment } from '@/types/attachment'import { toast } from 'sonner'-type AttachmentProcessingStatus =- | 'processing'- | 'done'- | 'error'- | 'clear_all'+type AttachmentProcessingStatus = 'processing' | 'done' | 'error' | 'clear_all'type AttachmentProcessingOptions = {attachments: Attachment[]@@ -38,15 +32,13 @@ const formatAttachmentError = (err: unknown): string => {if (typeof err === 'string') return errif (Array.isArray(err)) {const parts = err.map((e) => formatAttachmentError(e)).filter(Boolean)- return parts.length ? Array.from(new Set(parts)).join('; ') : 'Unknown error'+ return parts.length+ ? Array.from(new Set(parts)).join('; ')+ : 'Unknown error'}if (typeof err === 'object') {const obj = err as Record<string, unknown>- const candidates = [- obj.message,- obj.reason,- obj.detail,- ]+ const candidates = [obj.message, obj.reason, obj.detail]for (const val of candidates) {if (typeof val === 'string' && val.trim().length > 0) {return val@@ -90,7 +82,6 @@ export const processAttachmentsForSend = async (updateAttachmentProcessing,} = options- const fileAttachmentsFeatureEnabled = PlatformFeatures[PlatformFeature.FILE_ATTACHMENTS]const processedAttachments: Attachment[] = []let hasEmbeddedDocuments = falseconst effectiveContextThreshold =@@ -100,7 +91,9 @@ export const processAttachmentsForSend = async (? contextThreshold: undefinedconst notifyUpdate = (- ...args: Parameters<NonNullable<AttachmentProcessingOptions['updateAttachmentProcessing']>>+ ...args: Parameters<+ NonNullable<AttachmentProcessingOptions['updateAttachmentProcessing']>+ >) => updateAttachmentProcessing?.(...args)// Images: ingest before sending@@ -137,126 +130,124 @@ export const processAttachmentsForSend = async (}}- if (fileAttachmentsFeatureEnabled) {- const documents = attachments.filter((a) => a.type === 'document')- for (const doc of documents) {- try {- if (doc.processed && (doc.id || doc.injectionMode === 'inline')) {- hasEmbeddedDocuments = hasEmbeddedDocuments || doc.injectionMode !== 'inline'- processedAttachments.push(doc)- continue- }+ const documents = attachments.filter((a) => a.type === 'document')+ for (const doc of documents) {+ try {+ if (doc.processed && (doc.id || doc.injectionMode === 'inline')) {+ hasEmbeddedDocuments =+ hasEmbeddedDocuments || doc.injectionMode !== 'inline'+ processedAttachments.push(doc)+ continue+ }- notifyUpdate(doc.name, 'processing')+ notifyUpdate(doc.name, 'processing')- const targetPreference = doc.parseMode ?? parsePreference- let targetMode: 'inline' | 'embeddings' =- targetPreference === 'inline' ? 'inline' : 'embeddings'- let parsedContent: string | undefined+ const targetPreference = doc.parseMode ?? parsePreference+ let targetMode: 'inline' | 'embeddings' =+ targetPreference === 'inline' ? 'inline' : 'embeddings'+ let parsedContent: string | undefined- const canInline =- targetPreference !== 'embeddings' && !!doc.path+ const canInline = targetPreference !== 'embeddings' && !!doc.path- if (canInline) {- try {- parsedContent = await serviceHub.rag().parseDocument?.(doc.path!, doc.fileType)- } catch (err) {- console.warn(`Failed to parse ${doc.name} for inline use`, err)- }+ if (canInline) {+ try {+ parsedContent = await serviceHub+ .rag()+ .parseDocument?.(doc.path!, doc.fileType)+ } catch (err) {+ console.warn(`Failed to parse ${doc.name} for inline use`, err)}+ }- if (targetPreference === 'auto') {- // Check if user made a per-file choice for this document- const userChoice = perFileChoices?.get(doc.path || '')- targetMode = userChoice ?? autoFallbackMode ?? 'embeddings'-- // Only do auto-detection if no user choice was made- if (!userChoice && parsedContent && estimateTokens) {- const estimatedTokens = await estimateTokens(parsedContent)- const tokenCount =- typeof estimatedTokens === 'number' &&- Number.isFinite(estimatedTokens) &&- estimatedTokens > 0- ? estimatedTokens- : undefined- if (!effectiveContextThreshold) {- console.debug(- `Attachment ${doc.name}: no context threshold available; defaulting to ${targetMode}`- )- } else if (typeof tokenCount === 'number') {- targetMode =- tokenCount <= effectiveContextThreshold ? 'inline' : 'embeddings'- } else {- console.debug(- `Attachment ${doc.name}: token estimate unavailable or non-positive; defaulting to ${targetMode}`- )- }- } else if (!userChoice && !parsedContent) {+ if (targetPreference === 'auto') {+ // Check if user made a per-file choice for this document+ const userChoice = perFileChoices?.get(doc.path || '')+ targetMode = userChoice ?? autoFallbackMode ?? 'embeddings'++ // Only do auto-detection if no user choice was made+ if (!userChoice && parsedContent && estimateTokens) {+ const estimatedTokens = await estimateTokens(parsedContent)+ const tokenCount =+ typeof estimatedTokens === 'number' &&+ Number.isFinite(estimatedTokens) &&+ estimatedTokens > 0+ ? estimatedTokens+ : undefined+ if (!effectiveContextThreshold) {console.debug(- `Attachment ${doc.name}: parsed content unavailable for token estimation; defaulting to ${targetMode}`+ `Attachment ${doc.name}: no context threshold available; defaulting to ${targetMode}`)- } else if (!userChoice) {+ } else if (typeof tokenCount === 'number') {+ targetMode =+ tokenCount <= effectiveContextThreshold ? 'inline' : 'embeddings'+ } else {console.debug(- `Attachment ${doc.name}: token estimator unavailable; defaulting to ${targetMode}`+ `Attachment ${doc.name}: token estimate unavailable or non-positive; defaulting to ${targetMode}`)}- } else if (targetPreference === 'prompt') {- // Check if user made a per-file choice for this document- const userChoice = perFileChoices?.get(doc.path || '')- targetMode = userChoice ?? autoFallbackMode ?? 'embeddings'+ } else if (!userChoice && !parsedContent) {+ console.debug(+ `Attachment ${doc.name}: parsed content unavailable for token estimation; defaulting to ${targetMode}`+ )+ } else if (!userChoice) {+ console.debug(+ `Attachment ${doc.name}: token estimator unavailable; defaulting to ${targetMode}`+ )}+ } else if (targetPreference === 'prompt') {+ // Check if user made a per-file choice for this document+ const userChoice = perFileChoices?.get(doc.path || '')+ targetMode = userChoice ?? autoFallbackMode ?? 'embeddings'+ }- if (targetMode === 'inline' && parsedContent) {- processedAttachments.push({- ...doc,- processing: false,- processed: true,- inlineContent: parsedContent,- injectionMode: 'inline',- })-- notifyUpdate(doc.name, 'done', {- processing: false,- processed: true,- inlineContent: parsedContent,- injectionMode: 'inline',- })- continue- }-- // Default: ingest as embeddings- notifyUpdate(doc.name, 'processing')-- const res = await serviceHub- .uploads()- .ingestFileAttachment(threadId, doc)-+ if (targetMode === 'inline' && parsedContent) {processedAttachments.push({...doc,- id: res.id,- size: res.size ?? doc.size,- chunkCount: res.chunkCount ?? doc.chunkCount,processing: false,processed: true,- injectionMode: 'embeddings',+ inlineContent: parsedContent,+ injectionMode: 'inline',})- hasEmbeddedDocuments = truenotifyUpdate(doc.name, 'done', {- id: res.id,- size: res.size ?? doc.size,- chunkCount: res.chunkCount ?? doc.chunkCount,processing: false,processed: true,- injectionMode: 'embeddings',+ inlineContent: parsedContent,+ injectionMode: 'inline',})- } catch (err) {- console.error(`Failed to ingest ${doc.name}:`, err)- notifyUpdate(doc.name, 'error')- const desc = formatAttachmentError(err)- toast.error('Failed to index attachments', { description: desc })- throw err instanceof Error ? err : new Error(desc)+ continue}++ // Default: ingest as embeddings+ notifyUpdate(doc.name, 'processing')++ const res = await serviceHub.uploads().ingestFileAttachment(threadId, doc)++ processedAttachments.push({+ ...doc,+ id: res.id,+ size: res.size ?? doc.size,+ chunkCount: res.chunkCount ?? doc.chunkCount,+ processing: false,+ processed: true,+ injectionMode: 'embeddings',+ })+ hasEmbeddedDocuments = true++ notifyUpdate(doc.name, 'done', {+ id: res.id,+ size: res.size ?? doc.size,+ chunkCount: res.chunkCount ?? doc.chunkCount,+ processing: false,+ processed: true,+ injectionMode: 'embeddings',+ })+ } catch (err) {+ console.error(`Failed to ingest ${doc.name}:`, err)+ notifyUpdate(doc.name, 'error')+ const desc = formatAttachmentError(err)+ toast.error('Failed to index attachments', { description: desc })+ throw err instanceof Error ? err : new Error(desc)}}diff --git a/web-app/src/providers/AnalyticProvider.tsx b/web-app/src/providers/AnalyticProvider.tsxindex f26e3f97e..2a18debe2 100644--- a/web-app/src/providers/AnalyticProvider.tsx+++ b/web-app/src/providers/AnalyticProvider.tsx@@ -3,18 +3,12 @@ import { useEffect } from 'react'import { useServiceHub } from '@/hooks/useServiceHub'import { useAnalytic } from '@/hooks/useAnalytic'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'export function AnalyticProvider() {const { productAnalytic } = useAnalytic()const serviceHub = useServiceHub()useEffect(() => {- // Early exit if analytics are disabled for this platform- if (!PlatformFeatures[PlatformFeature.ANALYTICS]) {- return- }if (!POSTHOG_KEY || !POSTHOG_HOST) {console.warn('PostHog not initialized: Missing POSTHOG_KEY or POSTHOG_HOST environment variables'@@ -53,7 +47,9 @@ export function AnalyticProvider() {},})// Attempt to restore distinct Id from app global settings- serviceHub.analytic().getAppDistinctId()+ serviceHub+ .analytic()+ .getAppDistinctId().then((id) => {if (id) posthog.identify(id)})diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsxindex 58f55dbdf..4f4401ec4 100644--- a/web-app/src/routes/__root.tsx+++ b/web-app/src/routes/__root.tsx@@ -33,8 +33,6 @@ import GlobalError from '@/containers/GlobalError'import { GlobalEventHandler } from '@/providers/GlobalEventHandler'import ErrorDialog from '@/containers/dialogs/ErrorDialog'import { ServiceHubProvider } from '@/providers/ServiceHubProvider'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'export const Route = createRootRoute({component: RootLayout,@@ -115,9 +113,7 @@ const AppLayout = () => {{/* Fake absolute panel top to enable window drag */}<div className="absolute w-full h-10 z-10" data-tauri-drag-region /><DialogAppUpdater />- {PlatformFeatures[PlatformFeature.LOCAL_INFERENCE] && (- <BackendUpdater />- )}+ <BackendUpdater />{/* Use ResizablePanelGroup only on larger screens */}{!isSmallScreen && isLeftPanelOpen ? (@@ -169,9 +165,7 @@ const AppLayout = () => {</div>)}</main>- {PlatformFeatures[PlatformFeature.ANALYTICS] && productAnalyticPrompt && (- <PromptAnalytic />- )}+ {productAnalyticPrompt && <PromptAnalytic />}</Fragment>)}diff --git a/web-app/src/routes/hub/$modelId.tsx b/web-app/src/routes/hub/$modelId.tsxindex 37004b3b2..a95e8db3d 100644--- a/web-app/src/routes/hub/$modelId.tsx+++ b/web-app/src/routes/hub/$modelId.tsx@@ -13,8 +13,6 @@ import {} from '@tabler/icons-react'import { route } from '@/constants/routes'import { useModelSources } from '@/hooks/useModelSources'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform'import { extractModelName, extractDescription } from '@/lib/models'import { RenderMarkdown } from '@/containers/RenderMarkdown'import { useEffect, useMemo, useCallback, useState } from 'react'@@ -35,20 +33,12 @@ type SearchParams = {}export const Route = createFileRoute('/hub/$modelId')({- component: HubModelDetail,+ component: HubModelDetailContent,validateSearch: (search: Record<string, unknown>): SearchParams => ({repo: search.repo as SearchParams['repo'],}),})-function HubModelDetail() {- return (- <PlatformGuard feature={PlatformFeature.MODEL_HUB}>- <HubModelDetailContent />- </PlatformGuard>- )-}-function HubModelDetailContent() {const { t } = useTranslation()const { modelId } = useParams({ from: Route.id })diff --git a/web-app/src/routes/hub/index.tsx b/web-app/src/routes/hub/index.tsxindex e2ae36598..5e7dbcec4 100644--- a/web-app/src/routes/hub/index.tsx+++ b/web-app/src/routes/hub/index.tsx@@ -4,8 +4,6 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router'import { route } from '@/constants/routes'import { useModelSources } from '@/hooks/useModelSources'import { cn } from '@/lib/utils'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform'import {useState,useMemo,@@ -56,20 +54,12 @@ type SearchParams = {}export const Route = createFileRoute(route.hub.index as any)({- component: Hub,+ component: HubContent,validateSearch: (search: Record<string, unknown>): SearchParams => ({repo: search.repo as SearchParams['repo'],}),})-function Hub() {- return (- <PlatformGuard feature={PlatformFeature.MODEL_HUB}>- <HubContent />- </PlatformGuard>- )-}-function HubContent() {const parentRef = useRef(null)const huggingfaceToken = useGeneralSetting((state) => state.huggingfaceToken)diff --git a/web-app/src/routes/index.tsx b/web-app/src/routes/index.tsxindex 6d24716fc..9f7f5de15 100644--- a/web-app/src/routes/index.tsx+++ b/web-app/src/routes/index.tsx@@ -22,8 +22,6 @@ import DropdownAssistant from '@/containers/DropdownAssistant'import { useEffect } from 'react'import { useThreads } from '@/hooks/useThreads'import { useMobileScreen } from '@/hooks/useMediaQuery'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'import { TEMPORARY_CHAT_QUERY_ID } from '@/constants/chat'export const Route = createFileRoute(route.home as any)({@@ -88,9 +86,7 @@ function Index() {<div className="flex h-full flex-col justify-center pb-[calc(env(safe-area-inset-bottom)+env(safe-area-inset-top))]"><HeaderPage><div className="flex items-center justify-between w-full pr-2">- {PlatformFeatures[PlatformFeature.ASSISTANTS] && (- <DropdownAssistant />- )}+ <DropdownAssistant /></div></HeaderPage><div@@ -105,11 +101,7 @@ function Index() {isMobile ? 'w-full max-w-full' : 'w-full md:w-4/6')}>- <div- className={cn(- 'text-center mb-4',- )}- >+ <div className={cn('text-center mb-4')}><h1className={cn('text-main-view-fg/90 mt-2 font-studio font-medium',diff --git a/web-app/src/routes/local-api-server/logs.tsx b/web-app/src/routes/local-api-server/logs.tsxindex c9f4ab477..2b6a9fda9 100644--- a/web-app/src/routes/local-api-server/logs.tsx+++ b/web-app/src/routes/local-api-server/logs.tsx@@ -5,22 +5,12 @@ import { useEffect, useState, useRef } from 'react'import { useServiceHub } from '@/hooks/useServiceHub'import type { LogEntry } from '@/services/app/types'import { useTranslation } from '@/i18n/react-i18next-compat'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.localApiServerlogs as any)({- component: LocalApiServerLogsGuarded,+ component: LogsViewer,})-function LocalApiServerLogsGuarded() {- return (- <PlatformGuard feature={PlatformFeature.LOCAL_API_SERVER}>- <LogsViewer />- </PlatformGuard>- )-}-const SERVER_LOG_TARGET = 'app_lib::core::server::proxy'const LOG_EVENT_NAME = 'log://log'diff --git a/web-app/src/routes/logs.tsx b/web-app/src/routes/logs.tsxindex 568226ab4..c245ab0fd 100644--- a/web-app/src/routes/logs.tsx+++ b/web-app/src/routes/logs.tsx@@ -4,22 +4,12 @@ import { route } from '@/constants/routes'import { useEffect, useState, useRef } from 'react'import { useServiceHub } from '@/hooks/useServiceHub'import { useTranslation } from '@/i18n/react-i18next-compat'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.appLogs as any)({- component: LogsViewerGuarded,+ component: LogsViewer,})-function LogsViewerGuarded() {- return (- <PlatformGuard feature={PlatformFeature.SYSTEM_INTEGRATIONS}>- <LogsViewer />- </PlatformGuard>- )-}-// Define log entry typefunction LogsViewer() {@@ -88,7 +78,7 @@ function LogsViewer() {timeZone: 'UTC',hour: '2-digit',minute: '2-digit',- second: '2-digit'+ second: '2-digit',})}diff --git a/web-app/src/routes/project/$projectId.tsx b/web-app/src/routes/project/$projectId.tsxindex 1c8cf4fa6..9389cfdb3 100644--- a/web-app/src/routes/project/$projectId.tsx+++ b/web-app/src/routes/project/$projectId.tsx@@ -10,26 +10,15 @@ import HeaderPage from '@/containers/HeaderPage'import ThreadList from '@/containers/ThreadList'import DropdownAssistant from '@/containers/DropdownAssistant'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform/types'import { IconMessage } from '@tabler/icons-react'import { cn } from '@/lib/utils'import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'import { useSmallScreen } from '@/hooks/useMediaQuery'export const Route = createFileRoute('/project/$projectId')({- component: ProjectPage,+ component: ProjectPageContent,})-function ProjectPage() {- return (- <PlatformGuard feature={PlatformFeature.PROJECTS}>- <ProjectPageContent />- </PlatformGuard>- )-}-function ProjectPageContent() {const { t } = useTranslation()const { projectId } = useParams({ from: '/project/$projectId' })@@ -68,9 +57,7 @@ function ProjectPageContent() {<div className="flex h-full flex-col"><HeaderPage><div className="flex items-center justify-between w-full">- {PlatformFeatures[PlatformFeature.ASSISTANTS] && (- <DropdownAssistant />- )}+ <DropdownAssistant /></div></HeaderPage>diff --git a/web-app/src/routes/project/index.tsx b/web-app/src/routes/project/index.tsxindex f6ac50a5d..fd6a2c1d1 100644--- a/web-app/src/routes/project/index.tsx+++ b/web-app/src/routes/project/index.tsx@@ -4,8 +4,6 @@ import { useState, useMemo } from 'react'import { useThreadManagement } from '@/hooks/useThreadManagement'import { useThreads } from '@/hooks/useThreads'import { useTranslation } from '@/i18n/react-i18next-compat'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform/types'import HeaderPage from '@/containers/HeaderPage'import ThreadList from '@/containers/ThreadList'@@ -26,17 +24,9 @@ import { Button } from '@/components/ui/button'import { formatDate } from '@/utils/formatDate'export const Route = createFileRoute('/project/')({- component: Project,+ component: ProjectContent,})-function Project() {- return (- <PlatformGuard feature={PlatformFeature.PROJECTS}>- <ProjectContent />- </PlatformGuard>- )-}-function ProjectContent() {const { t } = useTranslation()const navigate = useNavigate()@@ -274,9 +264,7 @@ function ProjectContent() {{/* Thread List */}{isExpanded && projectThreads.length > 0 && (- <div- className="mt-3 pl-2 pr-2 max-h-[190px] overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:bg-main-view-fg/20 [&::-webkit-scrollbar-thumb]:rounded-full hover:[&::-webkit-scrollbar-thumb]:bg-main-view-fg/30"- >+ <div className="mt-3 pl-2 pr-2 max-h-[190px] overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:bg-main-view-fg/20 [&::-webkit-scrollbar-thumb]:rounded-full hover:[&::-webkit-scrollbar-thumb]:bg-main-view-fg/30"><ThreadListthreads={projectThreads}variant="project"diff --git a/web-app/src/routes/settings/assistant.tsx b/web-app/src/routes/settings/assistant.tsxindex d4de24a86..cfd70c1cb 100644--- a/web-app/src/routes/settings/assistant.tsx+++ b/web-app/src/routes/settings/assistant.tsx@@ -10,24 +10,14 @@ import AddEditAssistant from '@/containers/dialogs/AddEditAssistant'import { DeleteAssistantDialog } from '@/containers/dialogs'import { AvatarEmoji } from '@/containers/AvatarEmoji'import { useTranslation } from '@/i18n/react-i18next-compat'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform/types'import { Button } from '@/components/ui/button'import SettingsMenu from '@/containers/SettingsMenu'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.assistant as any)({- component: Assistant,+ component: AssistantContent,})-function Assistant() {- return (- <PlatformGuard feature={PlatformFeature.ASSISTANTS}>- <AssistantContent />- </PlatformGuard>- )-}-function AssistantContent() {const { t } = useTranslation()const { assistants, addAssistant, updateAssistant, deleteAssistant } =diff --git a/web-app/src/routes/settings/attachments.tsx b/web-app/src/routes/settings/attachments.tsxindex 60f14f56c..c11aee97e 100644--- a/web-app/src/routes/settings/attachments.tsx+++ b/web-app/src/routes/settings/attachments.tsx@@ -5,9 +5,7 @@ import { Card, CardItem } from '@/containers/Card'import { useAttachments } from '@/hooks/useAttachments'import type { SettingComponentProps } from '@janhq/core'import { useTranslation } from '@/i18n/react-i18next-compat'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'import { DynamicControllerSetting } from '@/containers/dynamicControllerSetting'-import { PlatformFeature } from '@/lib/platform/types'import { useEffect, useState, useCallback, useRef } from 'react'import { useShallow } from 'zustand/react/shallow'@@ -17,7 +15,11 @@ export const Route = createFileRoute('/settings/attachments')({// Helper to extract constraints from settingsDefsfunction getConstraints(def: SettingComponentProps) {- const props = def.controllerProps as Partial<{ min: number; max: number; step: number }>+ const props = def.controllerProps as Partial<{+ min: number+ max: number+ step: number+ }>return {min: props.min ?? -Infinity,max: props.max ?? Infinity,@@ -26,7 +28,11 @@ function getConstraints(def: SettingComponentProps) {}// Helper to validate and clamp numeric values-function clampValue(val: unknown, def: SettingComponentProps, currentValue: number): number {+function clampValue(+ val: unknown,+ def: SettingComponentProps,+ currentValue: number+): number {const num = typeof val === 'number' ? val : Number(val)if (!Number.isFinite(num)) return currentValueconst { min, max, step } = getConstraints(def)@@ -76,7 +82,9 @@ function AttachmentsSettings() {)// Local state for inputs to allow intermediate values while typing- const [localValues, setLocalValues] = useState<Record<string, string | number | boolean | string[]>>({})+ const [localValues, setLocalValues] = useState<+ Record<string, string | number | boolean | string[]>+ >({})// Debounce timersconst timersRef = useRef<Record<string, ReturnType<typeof setTimeout>>>({})@@ -90,165 +98,181 @@ function AttachmentsSettings() {}, [])// Debounced setter with validation- const debouncedSet = useCallback((key: string, val: unknown, def: SettingComponentProps) => {- // Clear existing timer for this key- if (timersRef.current[key]) {- clearTimeout(timersRef.current[key])- }+ const debouncedSet = useCallback(+ (key: string, val: unknown, def: SettingComponentProps) => {+ // Clear existing timer for this key+ if (timersRef.current[key]) {+ clearTimeout(timersRef.current[key])+ }- // Set local value immediately for responsive UI- setLocalValues((prev) => ({- ...prev,- [key]: val as string | number | boolean | string[]- }))+ // Set local value immediately for responsive UI+ setLocalValues((prev) => ({+ ...prev,+ [key]: val as string | number | boolean | string[],+ }))- // For non-numeric inputs, apply immediately without debounce- if (key === 'enabled' || key === 'search_mode' || key === 'parse_mode') {- if (key === 'enabled') sel.setEnabled(!!val)- else if (key === 'search_mode') sel.setSearchMode(val as 'auto' | 'ann' | 'linear')- else if (key === 'parse_mode')- sel.setParseMode(val as 'auto' | 'inline' | 'embeddings' | 'prompt')- return- }+ // For non-numeric inputs, apply immediately without debounce+ if (key === 'enabled' || key === 'search_mode' || key === 'parse_mode') {+ if (key === 'enabled') sel.setEnabled(!!val)+ else if (key === 'search_mode')+ sel.setSearchMode(val as 'auto' | 'ann' | 'linear')+ else if (key === 'parse_mode')+ sel.setParseMode(val as 'auto' | 'inline' | 'embeddings' | 'prompt')+ return+ }++ // For numeric inputs, debounce the validation and sync+ timersRef.current[key] = setTimeout(() => {+ const currentStoreValue = (() => {+ switch (key) {+ case 'max_file_size_mb':+ return sel.maxFileSizeMB+ case 'retrieval_limit':+ return sel.retrievalLimit+ case 'retrieval_threshold':+ return sel.retrievalThreshold+ case 'chunk_size_chars':+ return sel.chunkSizeChars+ case 'overlap_chars':+ return sel.overlapChars+ case 'auto_inline_context_ratio':+ return sel.autoInlineContextRatio+ default:+ return 0+ }+ })()++ const validated = clampValue(val, def, currentStoreValue)- // For numeric inputs, debounce the validation and sync- timersRef.current[key] = setTimeout(() => {- const currentStoreValue = (() => {switch (key) {case 'max_file_size_mb':- return sel.maxFileSizeMB+ sel.setMaxFileSizeMB(validated)+ breakcase 'retrieval_limit':- return sel.retrievalLimit+ sel.setRetrievalLimit(validated)+ breakcase 'retrieval_threshold':- return sel.retrievalThreshold+ sel.setRetrievalThreshold(validated)+ breakcase 'chunk_size_chars':- return sel.chunkSizeChars+ sel.setChunkSizeChars(validated)+ breakcase 'overlap_chars':- return sel.overlapChars+ sel.setOverlapChars(validated)+ breakcase 'auto_inline_context_ratio':- return sel.autoInlineContextRatio- default:- return 0+ sel.setAutoInlineContextRatio(validated)+ break}- })()-- const validated = clampValue(val, def, currentStoreValue)-- switch (key) {- case 'max_file_size_mb':- sel.setMaxFileSizeMB(validated)- break- case 'retrieval_limit':- sel.setRetrievalLimit(validated)- break- case 'retrieval_threshold':- sel.setRetrievalThreshold(validated)- break- case 'chunk_size_chars':- sel.setChunkSizeChars(validated)- break- case 'overlap_chars':- sel.setOverlapChars(validated)- break- case 'auto_inline_context_ratio':- sel.setAutoInlineContextRatio(validated)- break- }- // Update local value to validated one- setLocalValues((prev) => ({- ...prev,- [key]: validated as string | number | boolean | string[]- }))- }, 500) // 500ms debounce- }, [sel])+ // Update local value to validated one+ setLocalValues((prev) => ({+ ...prev,+ [key]: validated as string | number | boolean | string[],+ }))+ }, 500) // 500ms debounce+ },+ [sel]+ )return (- <PlatformGuard feature={PlatformFeature.FILE_ATTACHMENTS}>- <div className="flex flex-col h-full pb-[calc(env(safe-area-inset-bottom)+env(safe-area-inset-top))]">- <HeaderPage>- <h1 className="font-medium">{t('common:settings')}</h1>- </HeaderPage>- <div className="flex h-full w-full flex-col sm:flex-row">- <SettingsMenu />- <div className="p-4 w-full h-[calc(100%-32px)] overflow-y-auto">- <div className="flex flex-col justify-between gap-4 gap-y-3 w-full">- <Card title={t('common:attachments') || 'Attachments'}>- {defs.map((d) => {- // Use local value if typing, else use store value- const storeValue = (() => {- switch (d.key) {- case 'enabled':- return sel.enabled- case 'max_file_size_mb':- return sel.maxFileSizeMB- case 'retrieval_limit':- return sel.retrievalLimit- case 'retrieval_threshold':- return sel.retrievalThreshold- case 'chunk_size_chars':- return sel.chunkSizeChars- case 'overlap_chars':- return sel.overlapChars- case 'search_mode':- return sel.searchMode- case 'parse_mode':- return sel.parseMode- case 'auto_inline_context_ratio':- return sel.autoInlineContextRatio- default:- return d?.controllerProps?.value- }- })()+ <div className="flex flex-col h-full pb-[calc(env(safe-area-inset-bottom)+env(safe-area-inset-top))]">+ <HeaderPage>+ <h1 className="font-medium">{t('common:settings')}</h1>+ </HeaderPage>+ <div className="flex h-full w-full flex-col sm:flex-row">+ <SettingsMenu />+ <div className="p-4 w-full h-[calc(100%-32px)] overflow-y-auto">+ <div className="flex flex-col justify-between gap-4 gap-y-3 w-full">+ <Card title={t('common:attachments') || 'Attachments'}>+ {defs.map((d) => {+ // Use local value if typing, else use store value+ const storeValue = (() => {+ switch (d.key) {+ case 'enabled':+ return sel.enabled+ case 'max_file_size_mb':+ return sel.maxFileSizeMB+ case 'retrieval_limit':+ return sel.retrievalLimit+ case 'retrieval_threshold':+ return sel.retrievalThreshold+ case 'chunk_size_chars':+ return sel.chunkSizeChars+ case 'overlap_chars':+ return sel.overlapChars+ case 'search_mode':+ return sel.searchMode+ case 'parse_mode':+ return sel.parseMode+ case 'auto_inline_context_ratio':+ return sel.autoInlineContextRatio+ default:+ return d?.controllerProps?.value+ }+ })()- const currentValue =- localValues[d.key] !== undefined ? localValues[d.key] : storeValue+ const currentValue =+ localValues[d.key] !== undefined+ ? localValues[d.key]+ : storeValue- // Convert to DynamicControllerSetting compatible props- const baseProps = d.controllerProps- const normalizedValue: string | number | boolean = (() => {- if (Array.isArray(currentValue)) {- return currentValue.join(',')- }- return currentValue as string | number | boolean- })()-- const props = {- value: normalizedValue,- placeholder: 'placeholder' in baseProps ? baseProps.placeholder : undefined,- type: 'type' in baseProps ? baseProps.type : undefined,- options: 'options' in baseProps ? baseProps.options : undefined,- input_actions: 'inputActions' in baseProps ? baseProps.inputActions : undefined,- rows: undefined,- min: 'min' in baseProps ? baseProps.min : undefined,- max: 'max' in baseProps ? baseProps.max : undefined,- step: 'step' in baseProps ? baseProps.step : undefined,- recommended: 'recommended' in baseProps ? baseProps.recommended : undefined,+ // Convert to DynamicControllerSetting compatible props+ const baseProps = d.controllerProps+ const normalizedValue: string | number | boolean = (() => {+ if (Array.isArray(currentValue)) {+ return currentValue.join(',')}+ return currentValue as string | number | boolean+ })()++ const props = {+ value: normalizedValue,+ placeholder:+ 'placeholder' in baseProps+ ? baseProps.placeholder+ : undefined,+ type: 'type' in baseProps ? baseProps.type : undefined,+ options:+ 'options' in baseProps ? baseProps.options : undefined,+ input_actions:+ 'inputActions' in baseProps+ ? baseProps.inputActions+ : undefined,+ rows: undefined,+ min: 'min' in baseProps ? baseProps.min : undefined,+ max: 'max' in baseProps ? baseProps.max : undefined,+ step: 'step' in baseProps ? baseProps.step : undefined,+ recommended:+ 'recommended' in baseProps+ ? baseProps.recommended+ : undefined,+ }- const title = d.titleKey ? t(d.titleKey) : d.title- const description = d.descriptionKey ? t(d.descriptionKey) : d.description-- return (- <CardItem- key={d.key}- title={title}- description={description}- actions={- <DynamicControllerSetting- controllerType={d.controllerType}- controllerProps={props}- onChange={(val) => debouncedSet(d.key, val, d)}- />- }- />- )- })}- </Card>- </div>+ const title = d.titleKey ? t(d.titleKey) : d.title+ const description = d.descriptionKey+ ? t(d.descriptionKey)+ : d.description++ return (+ <CardItem+ key={d.key}+ title={title}+ description={description}+ actions={+ <DynamicControllerSetting+ controllerType={d.controllerType}+ controllerProps={props}+ onChange={(val) => debouncedSet(d.key, val, d)}+ />+ }+ />+ )+ })}+ </Card></div></div></div>- </PlatformGuard>+ </div>)}diff --git a/web-app/src/routes/settings/extensions.tsx b/web-app/src/routes/settings/extensions.tsxindex f278a44b2..e1b4ef0f1 100644--- a/web-app/src/routes/settings/extensions.tsx+++ b/web-app/src/routes/settings/extensions.tsx@@ -8,22 +8,12 @@ import SettingsMenu from '@/containers/SettingsMenu'import { RenderMarkdown } from '@/containers/RenderMarkdown'import { ExtensionManager } from '@/lib/extension'import { useTranslation } from '@/i18n/react-i18next-compat'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.extensions as any)({- component: Extensions,+ component: ExtensionsContent,})-function Extensions() {- return (- <PlatformGuard feature={PlatformFeature.EXTENSIONS_SETTINGS}>- <ExtensionsContent />- </PlatformGuard>- )-}-function ExtensionsContent() {const { t } = useTranslation()const extensions = ExtensionManager.getInstance().listExtensions()diff --git a/web-app/src/routes/settings/general.tsx b/web-app/src/routes/settings/general.tsxindex 39b7b4551..5c5f8eefa 100644--- a/web-app/src/routes/settings/general.tsx+++ b/web-app/src/routes/settings/general.tsx@@ -28,8 +28,6 @@ import { SystemEvent } from '@/types/events'import { Input } from '@/components/ui/input'import { useHardware } from '@/hooks/useHardware'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@@ -182,39 +180,36 @@ function General() {<div className="flex flex-col justify-between gap-4 gap-y-3 w-full">{/* General */}<Card title={t('common:general')}>- {PlatformFeatures[PlatformFeature.SYSTEM_INTEGRATIONS] && (+ <CardItem+ title={t('settings:general.appVersion')}+ actions={+ <span className="text-main-view-fg/80 font-medium">+ v{VERSION}+ </span>+ }+ />+ {!AUTO_UPDATER_DISABLED && (<CardItem- title={t('settings:general.appVersion')}+ title={t('settings:general.checkForUpdates')}+ description={t('settings:general.checkForUpdatesDesc')}+ className="flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-y-2"actions={- <span className="text-main-view-fg/80 font-medium">- v{VERSION}- </span>+ <Button+ variant="link"+ size="sm"+ className="p-0"+ onClick={handleCheckForUpdate}+ disabled={isCheckingUpdate}+ >+ <div className="cursor-pointer rounded-sm hover:bg-main-view-fg/15 bg-main-view-fg/10 transition-all duration-200 ease-in-out px-2 py-1 gap-1">+ {isCheckingUpdate+ ? t('settings:general.checkingForUpdates')+ : t('settings:general.checkForUpdates')}+ </div>+ </Button>}/>)}- {!AUTO_UPDATER_DISABLED &&- PlatformFeatures[PlatformFeature.SYSTEM_INTEGRATIONS] && (- <CardItem- title={t('settings:general.checkForUpdates')}- description={t('settings:general.checkForUpdatesDesc')}- className="flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-y-2"- actions={- <Button- variant="link"- size="sm"- className="p-0"- onClick={handleCheckForUpdate}- disabled={isCheckingUpdate}- >- <div className="cursor-pointer rounded-sm hover:bg-main-view-fg/15 bg-main-view-fg/10 transition-all duration-200 ease-in-out px-2 py-1 gap-1">- {isCheckingUpdate- ? t('settings:general.checkingForUpdates')- : t('settings:general.checkForUpdates')}- </div>- </Button>- }- />- )}<CardItemtitle={t('common:language')}actions={<LanguageSwitcher />}@@ -222,175 +217,163 @@ function General() {</Card>{/* Data folder - Desktop only */}- {PlatformFeatures[PlatformFeature.SYSTEM_INTEGRATIONS] && (- <Card title={t('common:dataFolder')}>- <CardItem- title={t('settings:dataFolder.appData', {- ns: 'settings',- })}- align="start"- className="flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-y-2"- description={- <>- <span>- {t('settings:dataFolder.appDataDesc', {- ns: 'settings',- })}- - </span>- <div className="flex items-center gap-2 mt-1 ">- <div className="">- <span- title={janDataFolder}- className="bg-main-view-fg/10 text-xs px-1 py-0.5 rounded-sm text-main-view-fg/80 line-clamp-1 w-fit"- >- {janDataFolder}- </span>- </div>- <button- onClick={() =>- janDataFolder && copyToClipboard(janDataFolder)- }- className="cursor-pointer flex items-center justify-center rounded hover:bg-main-view-fg/15 bg-main-view-fg/10 transition-all duration-200 ease-in-out p-1"- title={- isCopied- ? t('settings:general.copied')- : t('settings:general.copyPath')- }+ <Card title={t('common:dataFolder')}>+ <CardItem+ title={t('settings:dataFolder.appData', {+ ns: 'settings',+ })}+ align="start"+ className="flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-y-2"+ description={+ <>+ <span>+ {t('settings:dataFolder.appDataDesc', {+ ns: 'settings',+ })}+ + </span>+ <div className="flex items-center gap-2 mt-1 ">+ <div className="">+ <span+ title={janDataFolder}+ className="bg-main-view-fg/10 text-xs px-1 py-0.5 rounded-sm text-main-view-fg/80 line-clamp-1 w-fit">- {isCopied ? (- <div className="flex items-center gap-1">- <IconCopyCheck- size={12}- className="text-accent"- />- <span className="text-xs leading-0">- {t('settings:general.copied')}- </span>- </div>- ) : (- <IconCopy- size={12}- className="text-main-view-fg/50"- />- )}- </button>+ {janDataFolder}+ </span></div>- </>- }- actions={- <>- <Button- variant="link"- size="sm"- className="p-0"- title={t('settings:dataFolder.appData')}- onClick={handleDataFolderChange}- >- <div className="cursor-pointer flex items-center justify-center rounded-sm hover:bg-main-view-fg/15 bg-main-view-fg/10 transition-all duration-200 ease-in-out px-2 py-1 gap-1">- <IconFolder- size={12}- className="text-main-view-fg/50"- />- <span>{t('settings:general.changeLocation')}</span>- </div>- </Button>- {selectedNewPath && (- <ChangeDataFolderLocation- currentPath={janDataFolder || ''}- newPath={selectedNewPath}- onConfirm={confirmDataFolderChange}- open={isDialogOpen}- onOpenChange={(open) => {- setIsDialogOpen(open)- if (!open) {- setSelectedNewPath(null)- }- }}- >- <div />- </ChangeDataFolderLocation>- )}- </>- }- />- <CardItem- title={t('settings:dataFolder.appLogs', {- ns: 'settings',- })}- description={t('settings:dataFolder.appLogsDesc')}- className="flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-y-2"- actions={- <div className="flex items-center gap-2">- <Button- variant="link"- size="sm"- className="p-0"- onClick={handleOpenLogs}- title={t('settings:dataFolder.appLogs')}+ <button+ onClick={() =>+ janDataFolder && copyToClipboard(janDataFolder)+ }+ className="cursor-pointer flex items-center justify-center rounded hover:bg-main-view-fg/15 bg-main-view-fg/10 transition-all duration-200 ease-in-out p-1"+ title={+ isCopied+ ? t('settings:general.copied')+ : t('settings:general.copyPath')+ }>- <div className="cursor-pointer flex items-center justify-center rounded-sm hover:bg-main-view-fg/15 bg-main-view-fg/10 transition-all duration-200 ease-in-out px-2 py-1 gap-1">- <IconLogs+ {isCopied ? (+ <div className="flex items-center gap-1">+ <IconCopyCheck size={12} className="text-accent" />+ <span className="text-xs leading-0">+ {t('settings:general.copied')}+ </span>+ </div>+ ) : (+ <IconCopysize={12}className="text-main-view-fg/50"/>- <span>{t('settings:general.openLogs')}</span>- </div>- </Button>- <Button- variant="link"- size="sm"- className="p-0"- onClick={async () => {- if (janDataFolder) {- try {- const logsPath = `${janDataFolder}/logs`- await serviceHub- .opener()- .revealItemInDir(logsPath)- } catch (error) {- console.error(- 'Failed to reveal logs folder:',- error- )- }+ )}+ </button>+ </div>+ </>+ }+ actions={+ <>+ <Button+ variant="link"+ size="sm"+ className="p-0"+ title={t('settings:dataFolder.appData')}+ onClick={handleDataFolderChange}+ >+ <div className="cursor-pointer flex items-center justify-center rounded-sm hover:bg-main-view-fg/15 bg-main-view-fg/10 transition-all duration-200 ease-in-out px-2 py-1 gap-1">+ <IconFolder+ size={12}+ className="text-main-view-fg/50"+ />+ <span>{t('settings:general.changeLocation')}</span>+ </div>+ </Button>+ {selectedNewPath && (+ <ChangeDataFolderLocation+ currentPath={janDataFolder || ''}+ newPath={selectedNewPath}+ onConfirm={confirmDataFolderChange}+ open={isDialogOpen}+ onOpenChange={(open) => {+ setIsDialogOpen(open)+ if (!open) {+ setSelectedNewPath(null)}}}- title={t('settings:general.revealLogs')}>- <div className="cursor-pointer flex items-center justify-center rounded-sm hover:bg-main-view-fg/15 bg-main-view-fg/10 transition-all duration-200 ease-in-out px-2 py-1 gap-1">- <IconFolder- size={12}- className="text-main-view-fg/50"- />- <span>{openFileTitle()}</span>- </div>- </Button>- </div>- }- />- </Card>- )}+ <div />+ </ChangeDataFolderLocation>+ )}+ </>+ }+ />+ <CardItem+ title={t('settings:dataFolder.appLogs', {+ ns: 'settings',+ })}+ description={t('settings:dataFolder.appLogsDesc')}+ className="flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-y-2"+ actions={+ <div className="flex items-center gap-2">+ <Button+ variant="link"+ size="sm"+ className="p-0"+ onClick={handleOpenLogs}+ title={t('settings:dataFolder.appLogs')}+ >+ <div className="cursor-pointer flex items-center justify-center rounded-sm hover:bg-main-view-fg/15 bg-main-view-fg/10 transition-all duration-200 ease-in-out px-2 py-1 gap-1">+ <IconLogs size={12} className="text-main-view-fg/50" />+ <span>{t('settings:general.openLogs')}</span>+ </div>+ </Button>+ <Button+ variant="link"+ size="sm"+ className="p-0"+ onClick={async () => {+ if (janDataFolder) {+ try {+ const logsPath = `${janDataFolder}/logs`+ await serviceHub.opener().revealItemInDir(logsPath)+ } catch (error) {+ console.error(+ 'Failed to reveal logs folder:',+ error+ )+ }+ }+ }}+ title={t('settings:general.revealLogs')}+ >+ <div className="cursor-pointer flex items-center justify-center rounded-sm hover:bg-main-view-fg/15 bg-main-view-fg/10 transition-all duration-200 ease-in-out px-2 py-1 gap-1">+ <IconFolder+ size={12}+ className="text-main-view-fg/50"+ />+ <span>{openFileTitle()}</span>+ </div>+ </Button>+ </div>+ }+ />+ </Card>{/* Advanced - Desktop only */}- {PlatformFeatures[PlatformFeature.SYSTEM_INTEGRATIONS] && (- <Card title="Advanced">- <CardItem- title={t('settings:others.resetFactory', {- ns: 'settings',- })}- description={t('settings:others.resetFactoryDesc', {- ns: 'settings',- })}- actions={- <FactoryResetDialog onReset={resetApp}>- <Button variant="destructive" size="sm">- {t('common:reset')}- </Button>- </FactoryResetDialog>- }- />- </Card>- )}+ <Card title="Advanced">+ <CardItem+ title={t('settings:others.resetFactory', {+ ns: 'settings',+ })}+ description={t('settings:others.resetFactoryDesc', {+ ns: 'settings',+ })}+ actions={+ <FactoryResetDialog onReset={resetApp}>+ <Button variant="destructive" size="sm">+ {t('common:reset')}+ </Button>+ </FactoryResetDialog>+ }+ />+ </Card>{/* Other */}<Card title={t('common:others')}>@@ -408,93 +391,91 @@ function General() {/>}/>- {PlatformFeatures[PlatformFeature.MODEL_HUB] && (- <CardItem- title={t('settings:general.huggingfaceToken', {- ns: 'settings',- })}- description={t('settings:general.huggingfaceTokenDesc', {- ns: 'settings',- })}- actions={- <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+ <CardItem+ title={t('settings:general.huggingfaceToken', {+ ns: 'settings',+ })}+ description={t('settings:general.huggingfaceTokenDesc', {+ ns: 'settings',+ })}+ actions={+ <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')- 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.',- })+ 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,}- } finally {- clearTimeout(timeoutId)- setIsValidatingToken(false)+ )+ 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.',+ })}- }}- >- Verify- </Button>- </div>- }- />- )}+ } 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>+ }+ /></Card>{/* Resources */}diff --git a/web-app/src/routes/settings/hardware.tsx b/web-app/src/routes/settings/hardware.tsxindex b45fc5ae9..90ae06e04 100644--- a/web-app/src/routes/settings/hardware.tsx+++ b/web-app/src/routes/settings/hardware.tsx@@ -15,23 +15,13 @@ import type { HardwareData, SystemUsage } from '@/services/hardware/types'import { formatMegaBytes } from '@/lib/utils'import { toNumber } from '@/utils/number'import { useModelProvider } from '@/hooks/useModelProvider'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform'import { useAppState } from '@/hooks/useAppState'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.hardware as any)({- component: Hardware,+ component: HardwareContent,})-function Hardware() {- return (- <PlatformGuard feature={PlatformFeature.HARDWARE_MONITORING}>- <HardwareContent />- </PlatformGuard>- )-}-function HardwareContent() {const { t } = useTranslation()const [isLoading, setIsLoading] = useState(false)diff --git a/web-app/src/routes/settings/https-proxy.tsx b/web-app/src/routes/settings/https-proxy.tsxindex f58fa4e55..1b12a63af 100644--- a/web-app/src/routes/settings/https-proxy.tsx+++ b/web-app/src/routes/settings/https-proxy.tsx@@ -9,22 +9,12 @@ import { Input } from '@/components/ui/input'import { EyeOff, Eye } from 'lucide-react'import { useCallback, useState } from 'react'import { useProxyConfig } from '@/hooks/useProxyConfig'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.https_proxy as any)({- component: HTTPSProxy,+ component: HTTPSProxyContent,})-function HTTPSProxy() {- return (- <PlatformGuard feature={PlatformFeature.HTTPS_PROXY}>- <HTTPSProxyContent />- </PlatformGuard>- )-}-function HTTPSProxyContent() {const { t } = useTranslation()const [showPassword, setShowPassword] = useState(false)diff --git a/web-app/src/routes/settings/local-api-server.tsx b/web-app/src/routes/settings/local-api-server.tsxindex 83634fcde..673b9c1a4 100644--- a/web-app/src/routes/settings/local-api-server.tsx+++ b/web-app/src/routes/settings/local-api-server.tsx@@ -19,24 +19,14 @@ import { IconLogs } from '@tabler/icons-react'import { cn } from '@/lib/utils'import { ApiKeyInput } from '@/containers/ApiKeyInput'import { useEffect, useState } from 'react'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform'import { toast } from 'sonner'import { getModelToStart } from '@/utils/getModelToStart'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.local_api_server as any)({- component: LocalAPIServer,+ component: LocalAPIServerContent,})-function LocalAPIServer() {- return (- <PlatformGuard feature={PlatformFeature.LOCAL_API_SERVER}>- <LocalAPIServerContent />- </PlatformGuard>- )-}-function LocalAPIServerContent() {const { t } = useTranslation()const serviceHub = useServiceHub()diff --git a/web-app/src/routes/settings/mcp-servers.tsx b/web-app/src/routes/settings/mcp-servers.tsxindex ee17f4551..aa023d3b5 100644--- a/web-app/src/routes/settings/mcp-servers.tsx+++ b/web-app/src/routes/settings/mcp-servers.tsx@@ -27,8 +27,6 @@ import { useToolApproval } from '@/hooks/useToolApproval'import { toast } from 'sonner'import { useTranslation } from '@/i18n/react-i18next-compat'import { useAppState } from '@/hooks/useAppState'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform'import { listen } from '@tauri-apps/api/event'import { SystemEvent } from '@/types/events'@@ -93,17 +91,9 @@ const maskSensitiveUrl = (url: string) => {// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.mcp_servers as any)({- component: MCPServers,+ component: MCPServersDesktop,})-function MCPServers() {- return (- <PlatformGuard feature={PlatformFeature.MCP_SERVERS_SETTINGS}>- <MCPServersDesktop />- </PlatformGuard>- )-}-function MCPServersDesktop() {const { t } = useTranslation()const serviceHub = useServiceHub()@@ -221,7 +211,9 @@ function MCPServersDesktop() {}deleteServer(serverToDelete)- toast.success(t('mcp-servers:deleteServer.success', { serverName: serverToDelete }))+ toast.success(+ t('mcp-servers:deleteServer.success', { serverName: serverToDelete })+ )setServerToDelete(null)syncServersAndRestart()}@@ -247,7 +239,10 @@ function MCPServersDesktop() {data:| MCPServerConfig| Record<string, MCPServerConfig>- | { mcpServers?: Record<string, MCPServerConfig>; mcpSettings?: MCPSettings }+ | {+ mcpServers?: Record<string, MCPServerConfig>+ mcpSettings?: MCPSettings+ }) => {if (jsonServerName) {try {@@ -368,7 +363,6 @@ function MCPServersDesktop() {return () => {unlisten?.()}-}, [serviceHub, setConnectedServers])return (@@ -441,14 +435,18 @@ function MCPServersDesktop() {/><CardItemtitle={t('mcp-servers:runtimeSettings.toolCallTimeout')}- description={t('mcp-servers:runtimeSettings.toolCallTimeoutDesc')}+ description={t(+ 'mcp-servers:runtimeSettings.toolCallTimeoutDesc'+ )}actions={<Inputtype="number"min={1}step={1}value={settings.toolCallTimeoutSeconds}- onChange={(event) => updateToolCallTimeout(event.target.value)}+ onChange={(event) =>+ updateToolCallTimeout(event.target.value)+ }onBlur={() => {void syncServers()}}diff --git a/web-app/src/routes/settings/privacy.tsx b/web-app/src/routes/settings/privacy.tsxindex 3d0771db7..425c4865a 100644--- a/web-app/src/routes/settings/privacy.tsx+++ b/web-app/src/routes/settings/privacy.tsx@@ -7,8 +7,6 @@ import { Card, CardItem } from '@/containers/Card'import { useTranslation } from '@/i18n/react-i18next-compat'import { useAnalytic } from '@/hooks/useAnalytic'import posthog from 'posthog-js'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.privacy as any)({@@ -28,8 +26,7 @@ function Privacy() {<SettingsMenu /><div className="p-4 w-full h-[calc(100%-32px)] overflow-y-auto"><div className="flex flex-col justify-between gap-4 gap-y-3 w-full">- {PlatformFeatures[PlatformFeature.ANALYTICS] && (- <Card+ <Cardheader={<div className="flex items-center justify-between mb-4"><h1 className="text-main-view-fg font-medium text-base">@@ -85,7 +82,6 @@ function Privacy() {}/></Card>- )}</div></div></div>diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsxindex 0ddfa9c98..3ba284267 100644--- a/web-app/src/routes/settings/providers/$providerName.tsx+++ b/web-app/src/routes/settings/providers/$providerName.tsx@@ -34,8 +34,6 @@ import { useCallback, useEffect, useState } from 'react'import { predefinedProviders } from '@/constants/providers'import { useModelLoad } from '@/hooks/useModelLoad'import { useLlamacppDevices } from '@/hooks/useLlamacppDevices'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'import { useBackendUpdater } from '@/hooks/useBackendUpdater'import { basenameNoExt } from '@/lib/utils'import { useAppState } from '@/hooks/useAppState'@@ -365,30 +363,6 @@ function ProviderDetail() {}}, [provider, serviceHub, refreshSettings, t, installBackend])- // Check if model provider settings are enabled for this platform- if (!PlatformFeatures[PlatformFeature.MODEL_PROVIDER_SETTINGS]) {- return (- <div className="flex flex-col h-full">- <HeaderPage>- <h1 className="font-medium">{t('common:settings')}</h1>- </HeaderPage>- <div className="flex h-full w-full">- <SettingsMenu />- <div className="p-4 w-full h-[calc(100%-32px)] overflow-y-auto flex items-center justify-center">- <div className="text-center">- <h2 className="text-lg font-medium text-main-view-fg/80 mb-2">- {t('common:notAvailable')}- </h2>- <p className="text-main-view-fg/60">- Provider settings are not available on the web platform.- </p>- </div>- </div>- </div>- </div>- )- }-return (<><div className="flex flex-col h-full pb-[calc(env(safe-area-inset-bottom)+env(safe-area-inset-top))]">diff --git a/web-app/src/routes/settings/providers/index.tsx b/web-app/src/routes/settings/providers/index.tsxindex 9876c2efe..34c1770ec 100644--- a/web-app/src/routes/settings/providers/index.tsx+++ b/web-app/src/routes/settings/providers/index.tsx@@ -17,8 +17,6 @@ import { openAIProviderSettings } from '@/constants/providers'import cloneDeep from 'lodash/cloneDeep'import { toast } from 'sonner'import { useServiceHub } from '@/hooks/useServiceHub'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.model_providers as any)({@@ -60,30 +58,6 @@ function ModelProviders() {[providers, addProvider, t, navigate])- // Check if model provider settings are enabled for this platform- if (!PlatformFeatures[PlatformFeature.MODEL_PROVIDER_SETTINGS]) {- return (- <div className="flex flex-col h-full">- <HeaderPage>- <h1 className="font-medium">{t('common:settings')}</h1>- </HeaderPage>- <div className="flex h-full w-full flex-col sm:flex-row">- <SettingsMenu />- <div className="p-4 w-full h-[calc(100%-32px)] overflow-y-auto flex items-center justify-center">- <div className="text-center">- <h2 className="text-lg font-medium text-main-view-fg/80 mb-2">- {t('common:notAvailable')}- </h2>- <p className="text-main-view-fg/60">- Model provider settings are not available on the web platform.- </p>- </div>- </div>- </div>- </div>- )- }-return (<div className="flex flex-col h-full"><HeaderPage>diff --git a/web-app/src/routes/system-monitor.tsx b/web-app/src/routes/system-monitor.tsxindex 78c2ecc43..74669d1b4 100644--- a/web-app/src/routes/system-monitor.tsx+++ b/web-app/src/routes/system-monitor.tsx@@ -10,21 +10,11 @@ import { useTranslation } from '@/i18n/react-i18next-compat'import { toNumber } from '@/utils/number'import { useLlamacppDevices } from '@/hooks/useLlamacppDevices'import { useServiceHub } from '@/hooks/useServiceHub'-import { PlatformGuard } from '@/lib/platform/PlatformGuard'-import { PlatformFeature } from '@/lib/platform'export const Route = createFileRoute(route.systemMonitor as any)({- component: SystemMonitor,+ component: SystemMonitorContent,})-function SystemMonitor() {- return (- <PlatformGuard feature={PlatformFeature.HARDWARE_MONITORING}>- <SystemMonitorContent />- </PlatformGuard>- )-}-function SystemMonitorContent() {const { t } = useTranslation()const { hardwareData, systemUsage, updateSystemUsage } = useHardware()diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex e00c6336a..0fb6ee894 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -16,8 +16,6 @@ import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'import { useSmallScreen, useMobileScreen } from '@/hooks/useMediaQuery'import { useTools } from '@/hooks/useTools'import { useAppState } from '@/hooks/useAppState'-import { PlatformFeatures } from '@/lib/platform/const'-import { PlatformFeature } from '@/lib/platform/types'import { SESSION_STORAGE_PREFIX } from '@/constants/chat'import { useChat } from '@/hooks/use-chat'import { useModelProvider } from '@/hooks/useModelProvider'@@ -319,10 +317,7 @@ function ThreadDetail() {// Update RAG tools availability when documents, model, or tool availability changesuseEffect(() => {const hasDocuments = Boolean(thread?.metadata?.hasDocuments)- const ragFeatureAvailable = Boolean(- useAttachments.getState().enabled &&- PlatformFeatures[PlatformFeature.FILE_ATTACHMENTS]- )+ const ragFeatureAvailable = Boolean(useAttachments.getState().enabled)const modelSupportsTools =selectedModel?.capabilities?.includes('tools') ?? false@@ -664,12 +659,7 @@ function ThreadDetail() {setTimeout(() => {handleRegenerate()}, 1000)- }, [- selectedModel,- selectedProvider,- getProviderByName,- serviceHub,- ])+ }, [selectedModel, selectedProvider, getProviderByName, serviceHub])const threadModel = useMemo(() => thread?.model, [thread])@@ -680,9 +670,7 @@ function ThreadDetail() {<HeaderPage><div className="flex items-center justify-between w-full pr-2"><div>- {PlatformFeatures[PlatformFeature.ASSISTANTS] && (- <DropdownAssistant />- )}+ <DropdownAssistant /></div></div></HeaderPage>diff --git a/web-app/src/test/setup.ts b/web-app/src/test/setup.tsindex 30a953692..3fc6bd621 100644--- a/web-app/src/test/setup.ts+++ b/web-app/src/test/setup.ts@@ -5,31 +5,6 @@ import * as matchers from '@testing-library/jest-dom/matchers'// extends Vitest's expect method with methods from react-testing-libraryexpect.extend(matchers)-// Global mock for platform features to enable all features in tests-// This ensures consistent behavior across all tests and enables testing of-// platform-specific features like Hub, Hardware monitoring, etc.-vi.mock('@/lib/platform/const', () => ({- PlatformFeatures: {- hardwareMonitoring: true,- localInference: true,- localApiServer: true,- modelHub: true,- systemIntegrations: true,- httpsProxy: true,- defaultProviders: true,- projects: true,- analytics: true,- webAutoModelSelection: false,- modelProviderSettings: true,- mcpAutoApproveTools: false,- mcpServersSettings: true,- extensionsSettings: true,- assistants: true,- authentication: false,- attachments: true,- }-}))-// Create a mock ServiceHubconst mockServiceHub = {theme: () => ({