Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: local api server improvement
Faisal Amir0a4fcf861f48
diff --git a/web-app/package.json b/web-app/package.jsonindex a480e92b2..dd8295c00 100644--- a/web-app/package.json+++ b/web-app/package.json@@ -75,6 +75,7 @@"motion": "^12.29.2","next-themes": "0.4.6","posthog-js": "1.255.1",+ "radix-ui": "^1.4.3","react": "19.0.0","react-colorful": "5.6.1","react-dom": "19.0.0",diff --git a/web-app/src/components/LogViewer.tsx b/web-app/src/components/LogViewer.tsxnew file mode 100644index 000000000..a4b1009ed--- /dev/null+++ b/web-app/src/components/LogViewer.tsx@@ -0,0 +1,144 @@+import { useEffect, useState, useRef, useCallback } from 'react'+import { useServiceHub } from '@/hooks/useServiceHub'+import type { LogEntry } from '@/services/app/types'+import { useTranslation } from '@/i18n/react-i18next-compat'++interface LogViewerProps {+ className?: string+ maxHeight?: string+ filterTarget?: string+ isVisible?: boolean+}++const SERVER_LOG_TARGET = 'app_lib::core::server::proxy'+const LOG_EVENT_NAME = 'log://log'++export function LogViewer({+ isVisible,+}: LogViewerProps) {+ const { t } = useTranslation()+ const [logs, setLogs] = useState<LogEntry[]>([])+ const logsContainerRef = useRef<HTMLDivElement>(null)+ const serviceHub = useServiceHub()++ const scrollToBottom = useCallback(() => {+ const el = logsContainerRef.current+ if (el) {+ el.scrollTop = el.scrollHeight - el.clientHeight+ }+ }, [])++ // Scroll when visibility changes OR when logs change (and isVisible is true)+ useEffect(() => {+ if (isVisible && logs.length > 0) {+ // Use requestAnimationFrame to ensure DOM is fully rendered+ let rafId1: number+ let rafId2: number++ rafId1 = requestAnimationFrame(() => {+ scrollToBottom()+ // Try again after a frame to handle any animations+ rafId2 = requestAnimationFrame(scrollToBottom)+ })++ return () => {+ cancelAnimationFrame(rafId1)+ cancelAnimationFrame(rafId2)+ }+ }+ }, [isVisible, logs.length, scrollToBottom])++ // Initial scroll to bottom when logs are loaded+ useEffect(() => {+ serviceHub.app().readLogs().then((logData) => {+ const logs = logData+ .filter((log) => log?.target === SERVER_LOG_TARGET)+ .filter(Boolean) as LogEntry[]+ setLogs(logs)++ // Scroll to bottom after initial logs are loaded+ setTimeout(() => {+ scrollToBottom()+ }, 100)+ })+ let unsubscribe = () => {}+ serviceHub.events().listen(LOG_EVENT_NAME, (event) => {+ const { message } = event.payload as { message: string }+ const log: LogEntry | undefined = serviceHub.app().parseLogLine(message)+ if (log?.target === SERVER_LOG_TARGET) {+ setLogs((prevLogs) => {+ const newLogs = [...prevLogs, log]+ // Schedule scroll to bottom after state update+ setTimeout(() => {+ scrollToBottom()+ }, 0)+ return newLogs+ })+ }+ }).then((unsub) => {+ unsubscribe = unsub+ })+ return () => {+ unsubscribe()+ }+ }, [serviceHub, scrollToBottom])++ // Function to get appropriate color for log level+ const getLogLevelColor = (level: string) => {+ switch (level) {+ case 'error':+ return 'text-red-500'+ case 'warn':+ return 'text-yellow-500'+ case 'info':+ return 'text-blue-500'+ case 'debug':+ return 'text-gray-500'+ default:+ return 'text-gray-500'+ }+ }++ // Format timestamp to be more readable+ const formatTimestamp = (timestamp: string | number) => {+ const date = new Date(timestamp)+ return date.toLocaleTimeString('en-US', {+ hour12: false,+ timeZone: 'UTC',+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit'+ })+ }++ return (+ <div ref={logsContainerRef} className="border h-full rounded-md bg-background p-4 px-2 block overflow-y-auto overflow-hidden">+ <div+ >+ <div className="font-mono text-xs">+ {logs.length === 0 ? (+ <div className="text-center text-muted-foreground py-4">+ {t('logs:noLogs')}+ </div>+ ) : (+ logs.map((log, index) => (+ <div key={index} className="mb-1 flex">+ <span className="text-muted-foreground mr-2 shrink-0">+ [{formatTimestamp(log.timestamp)}]+ </span>+ <span+ className={`mr-2 font-semibold shrink-0 ${getLogLevelColor(+ log.level+ )}`}+ >+ {log.level.toUpperCase()}+ </span>+ <span className="break-all">{log.message}</span>+ </div>+ ))+ )}+ </div>+ </div>+ </div>+ )+}\ No newline at end of filediff --git a/web-app/src/components/ui/__tests__/popover.test.tsx b/web-app/src/components/ui/__tests__/popover.test.tsxindex 6219e855c..3f0d3608c 100644--- a/web-app/src/components/ui/__tests__/popover.test.tsx+++ b/web-app/src/components/ui/__tests__/popover.test.tsx@@ -101,13 +101,13 @@ describe('Popover Components', () => {await waitFor(() => {const content = document.querySelector('[data-slot="popover-content"]')expect(content).toBeInTheDocument()- expect(content).toHaveClass('bg-background')- expect(content).toHaveClass('text-foreground')+ expect(content).toHaveClass('bg-popover')+ expect(content).toHaveClass('text-popover-foreground')expect(content).toHaveClass('w-72')expect(content).toHaveClass('rounded-md')expect(content).toHaveClass('border')expect(content).toHaveClass('shadow-md')- })+ }, { timeout: 1000 })})it('applies custom className', async () => {diff --git a/web-app/src/components/ui/popover.tsx b/web-app/src/components/ui/popover.tsxindex 584ef3270..103bec3ed 100644--- a/web-app/src/components/ui/popover.tsx+++ b/web-app/src/components/ui/popover.tsx@@ -1,7 +1,7 @@-import * as React from 'react'-import * as PopoverPrimitive from '@radix-ui/react-popover'+import * as React from "react"+import { Popover as PopoverPrimitive } from "radix-ui"-import { cn } from '@/lib/utils'+import { cn } from "@/lib/utils"function Popover({...props@@ -17,7 +17,7 @@ function PopoverTrigger({function PopoverContent({className,- align = 'center',+ align = "center",sideOffset = 4,...props}: React.ComponentProps<typeof PopoverPrimitive.Content>) {@@ -28,7 +28,7 @@ function PopoverContent({align={align}sideOffset={sideOffset}className={cn(- 'bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden',+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",className)}{...props}@@ -43,4 +43,45 @@ function PopoverAnchor({return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />}-export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }+function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="popover-header"+ className={cn("flex flex-col gap-1 text-sm", className)}+ {...props}+ />+ )+}++function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {+ return (+ <div+ data-slot="popover-title"+ className={cn("font-medium", className)}+ {...props}+ />+ )+}++function PopoverDescription({+ className,+ ...props+}: React.ComponentProps<"p">) {+ return (+ <p+ data-slot="popover-description"+ className={cn("text-muted-foreground", className)}+ {...props}+ />+ )+}++export {+ Popover,+ PopoverTrigger,+ PopoverContent,+ PopoverAnchor,+ PopoverHeader,+ PopoverTitle,+ PopoverDescription,+}diff --git a/web-app/src/containers/dialogs/AddEditCustomCliDialog.tsx b/web-app/src/containers/dialogs/AddEditCustomCliDialog.tsxnew file mode 100644index 000000000..9f7809087--- /dev/null+++ b/web-app/src/containers/dialogs/AddEditCustomCliDialog.tsx@@ -0,0 +1,167 @@+import { useState, useEffect, useRef } from 'react'+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { IconPlus, IconTrash } from '@tabler/icons-react'+import { useTranslation } from '@/i18n/react-i18next-compat'+import type { EnvVar } from '@/hooks/useClaudeCodeModel'++interface AddEditCustomCliProps {+ open: boolean+ onOpenChange: (open: boolean) => void+ initialEnvVars?: EnvVar[]+ initialCustomCli?: string+ onSave: (envVars: EnvVar[], customCli: string) => void+}++export default function AddEditCustomCliDialog({+ open,+ onOpenChange,+ initialEnvVars = [],+ initialCustomCli = '',+ onSave,+}: AddEditCustomCliProps) {+ const { t } = useTranslation()+ const [envVars, setEnvVars] = useState<EnvVar[]>([{ key: '', value: '' }])+ const [customCli, setCustomCli] = useState('')+ const initialized = useRef(false)++ // Initialize once when dialog opens+ useEffect(() => {+ if (open && !initialized.current) {+ setEnvVars(initialEnvVars.length > 0 ? initialEnvVars : [{ key: '', value: '' }])+ setCustomCli(initialCustomCli || '')+ initialized.current = true+ }+ }, [open, initialEnvVars, initialCustomCli])++ // Reset initialized flag when dialog closes+ useEffect(() => {+ if (!open) {+ initialized.current = false+ }+ }, [open])++ const handleAddEnv = () => {+ setEnvVars([...envVars, { key: '', value: '' }])+ }++ const handleRemoveEnv = (index: number) => {+ const newEnvVars = [...envVars]+ newEnvVars.splice(index, 1)+ setEnvVars(newEnvVars.length > 0 ? newEnvVars : [{ key: '', value: '' }])+ }++ const handleEnvKeyChange = (index: number, value: string) => {+ setEnvVars((prev) => {+ const updated = [...prev]+ updated[index] = { ...updated[index], key: value }+ return updated+ })+ }++ const handleEnvValueChange = (index: number, value: string) => {+ setEnvVars((prev) => {+ const updated = [...prev]+ updated[index] = { ...updated[index], value: value }+ return updated+ })+ }++ const handleSave = () => {+ // Filter out empty env vars+ const filteredEnvVars = envVars+ .filter((env) => env.key.trim() !== '')+ .map((env) => ({ key: env.key.trim(), value: env.value.trim() }))++ onSave(filteredEnvVars, customCli.trim())+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ showCloseButton={false}+ onInteractOutside={(e) => {+ e.preventDefault()+ }}+ >+ <DialogHeader>+ <DialogTitle>Custom CLI</DialogTitle>+ </DialogHeader>++ <div className="space-y-4">+ {/* Custom CLI Command */}+ <div className="space-y-2">+ <label className="text-sm mb-2 inline-block">+ Command+ </label>+ <Input+ value={customCli}+ onChange={(e) => setCustomCli(e.target.value)}+ placeholder="Enter custom CLI command"+ />+ </div>++ {/* Environment Variables */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <label className="text-sm">Environment Variables</label>+ <div+ className="size-6 cursor-pointer flex items-center justify-center rounded hover:bg-secondary transition-all duration-200 ease-in-out"+ onClick={handleAddEnv}+ >+ <IconPlus size={16} className="text-muted-foreground" />+ </div>+ </div>++ {envVars.map((env, index) => (+ <div key={`env-${index}`} className="flex items-center gap-2">+ <Input+ value={env.key}+ onChange={(e) => handleEnvKeyChange(index, e.target.value)}+ placeholder="Key"+ className="flex-1"+ />+ <Input+ value={env.value}+ onChange={(e) => handleEnvValueChange(index, e.target.value)}+ placeholder="Value"+ className="flex-1"+ />+ {envVars.length > 1 && (+ <div+ className="size-6 cursor-pointer flex items-center justify-center rounded hover:bg-secondary transition-all duration-200 ease-in-out"+ onClick={() => handleRemoveEnv(index)}+ >+ <IconTrash size={16} className="text-destructive" />+ </div>+ )}+ </div>+ ))}+ </div>+ </div>++ <DialogFooter>+ <Button variant="ghost" size="sm" onClick={() => onOpenChange(false)}>+ {t('common:cancel')}+ </Button>+ <Button+ onClick={() => {+ handleSave()+ onOpenChange(false)+ }}+ size="sm"+ >+ Save+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}\ No newline at end of filediff --git a/web-app/src/hooks/useClaudeCodeModel.ts b/web-app/src/hooks/useClaudeCodeModel.tsnew file mode 100644index 000000000..f085c93c0--- /dev/null+++ b/web-app/src/hooks/useClaudeCodeModel.ts@@ -0,0 +1,109 @@+import { useEffect, useState, useCallback } from 'react'++export type ClaudeCodeModelType = 'big' | 'medium' | 'small'++export interface EnvVar {+ key: string+ value: string+}++interface ClaudeCodeModels {+ big: string | null+ medium: string | null+ small: string | null+ envVars: EnvVar[]+ customCli: string+}++const STORAGE_KEY = 'claude-code-helper-models'++const defaultModels: ClaudeCodeModels = {+ big: null,+ medium: null,+ small: null,+ envVars: [],+ customCli: '',+}++// Load from localStorage once+const loadFromStorage = (): ClaudeCodeModels => {+ if (typeof window === 'undefined') return defaultModels++ try {+ const stored = localStorage.getItem(STORAGE_KEY)+ if (stored) {+ const parsed = JSON.parse(stored)+ // Validate the structure+ if (+ typeof parsed === 'object' &&+ parsed !== null &&+ 'big' in parsed &&+ 'medium' in parsed &&+ 'small' in parsed &&+ Array.isArray(parsed.envVars) &&+ typeof parsed.customCli === 'string'+ ) {+ return {+ big: parsed.big ?? null,+ medium: parsed.medium ?? null,+ small: parsed.small ?? null,+ envVars: parsed.envVars ?? [],+ customCli: parsed.customCli ?? '',+ }+ }+ }+ } catch {+ console.warn('Failed to load claude-code helper models from localStorage')+ }+ return defaultModels+}++export function useClaudeCodeModel() {+ const [models, setModels] = useState<ClaudeCodeModels>(loadFromStorage)++ // Save to localStorage - only when models actually changes+ const saveToStorage = useCallback((data: ClaudeCodeModels) => {+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(data))+ } catch {+ console.warn('Failed to save claude-code helper models to localStorage')+ }+ }, [])++ const setModel = useCallback((type: ClaudeCodeModelType, modelId: string | null) => {+ setModels((prev) => {+ const newModels = { ...prev, [type]: modelId }+ saveToStorage(newModels)+ return newModels+ })+ }, [saveToStorage])++ const setEnvVars = useCallback((envVars: EnvVar[]) => {+ setModels((prev) => {+ const newModels = { ...prev, envVars }+ saveToStorage(newModels)+ return newModels+ })+ }, [saveToStorage])++ const setCustomCli = useCallback((customCli: string) => {+ setModels((prev) => {+ const newModels = { ...prev, customCli }+ saveToStorage(newModels)+ return newModels+ })+ }, [saveToStorage])++ const clearModels = useCallback(() => {+ setModels(defaultModels)+ saveToStorage(defaultModels)+ }, [saveToStorage])++ return {+ models,+ setModel,+ setEnvVars,+ setCustomCli,+ clearModels,+ }+}\ No newline at end of filediff --git a/web-app/src/routes/settings/assistant.tsx b/web-app/src/routes/settings/assistant.tsxindex 7dc03db61..aa4a42623 100644--- a/web-app/src/routes/settings/assistant.tsx+++ b/web-app/src/routes/settings/assistant.tsx@@ -61,7 +61,7 @@ function AssistantContent() {setOpen(true)}}size="sm"- variant="secondary"+ variant="outline"className="relative z-50"><IconCirclePlus size={16} />diff --git a/web-app/src/routes/settings/local-api-server.tsx b/web-app/src/routes/settings/local-api-server.tsxindex 060143587..b9e55243b 100644--- a/web-app/src/routes/settings/local-api-server.tsx+++ b/web-app/src/routes/settings/local-api-server.tsx@@ -12,15 +12,32 @@ import { ProxyTimeoutInput } from '@/containers/ProxyTimeoutInput'import { ApiPrefixInput } from '@/containers/ApiPrefixInput'import { TrustedHostsInput } from '@/containers/TrustedHostsInput'import { useLocalApiServer } from '@/hooks/useLocalApiServer'+import { useClaudeCodeModel } from '@/hooks/useClaudeCodeModel'+import AddEditCustomCliDialog from '@/containers/dialogs/AddEditCustomCliDialog'import { useAppState } from '@/hooks/useAppState'import { useModelProvider } from '@/hooks/useModelProvider'import { useServiceHub } from '@/hooks/useServiceHub'-import { IconLogs } from '@tabler/icons-react'+import { IconSettings2 } from '@tabler/icons-react'import { cn } from '@/lib/utils'import { ApiKeyInput } from '@/containers/ApiKeyInput'-import { useEffect, useState } from 'react'+import { useEffect, useState, useMemo, useRef } from 'react'import { toast } from 'sonner'import { getModelToStart } from '@/utils/getModelToStart'+import { LogViewer } from '@/components/LogViewer'+import {+ Popover,+ PopoverTrigger,+ PopoverContent,+} from '@/components/ui/popover'+import {+ Collapsible,+ CollapsibleTrigger,+ CollapsibleContent,+} from '@/components/ui/collapsible'+import { IconChevronDown, IconExternalLink, IconPlus, IconX } from '@tabler/icons-react'+import ProvidersAvatar from '@/containers/ProvidersAvatar'+import Capabilities from '@/containers/Capabilities'+import { getModelDisplayName } from '@/lib/utils'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.local_api_server as any)({@@ -47,14 +64,20 @@ function LocalAPIServerContent() {} = useLocalApiServer()const { serverStatus, setServerStatus } = useAppState()- const { selectedModel, selectedProvider, getProviderByName } =+ const { providers, selectedModel, selectedProvider, getProviderByName } =useModelProvider()const [showApiKeyError, setShowApiKeyError] = useState(false)- const [isApiKeyEmpty, setIsApiKeyEmpty] = useState(+ const [_, setIsApiKeyEmpty] = useState(!apiKey || apiKey.toString().trim().length === 0)+ const { activeModels } = useAppState()const setActiveModels = useAppState((state) => state.setActiveModels)+ // Helper card state (persisted to localStorage)+ const { models: helperModels, setModel: setHelperModel, setEnvVars, setCustomCli } = useClaudeCodeModel()+ const [isLogVisible, setIsLogVisible] = useState(false)+ const [isCustomCliDialogOpen, setIsCustomCliDialogOpen] = useState(false)+useEffect(() => {const checkServerStatus = async () => {serviceHub@@ -83,10 +106,11 @@ function LocalAPIServerContent() {description: `Attempting to start server on port ${serverPort}`,})- if (!apiKey || apiKey.toString().trim().length === 0) {- setShowApiKeyError(true)- return- }+ // if (!apiKey || apiKey.toString().trim().length === 0) {+ // setShowApiKeyError(true)+ // return+ // }+setShowApiKeyError(false)setServerStatus('pending')@@ -229,177 +253,302 @@ function LocalAPIServerContent() {return (<div className="flex flex-col h-svh w-full"><HeaderPage>- <div className="flex items-center gap-2 w-full">+ <div className="flex items-center justify-between w-full mr-2 pr-4"><span className='font-medium text-base font-studio'>{t('common:settings')}</span>+ <Popover>+ <PopoverTrigger asChild>+ <Button+ size="sm"+ variant="outline"+ className="relative z-50"+ >+ <IconSettings2 size={16} />+ Configuration+ </Button>+ </PopoverTrigger>+ <PopoverContent align='end' className="w-[480px] max-h-[70vh] overflow-y-auto">+ <div className="space-y-4">+ <div className="flex items-center justify-between border-b pb-2">+ <h2 className="font-semibold text-sm">+ {t('settings:localApiServer.serverConfiguration')}+ </h2>+ </div>+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <div className="space-y-0.5">+ <p className="text-sm font-medium">{t('settings:localApiServer.serverHost')}</p>+ <p className="text-xs text-muted-foreground">{t('settings:localApiServer.serverHostDesc')}</p>+ </div>+ <div>++ <ServerHostSwitcher isServerRunning={isServerRunning} />+ </div>+ </div>+ <div className="flex items-center justify-between">+ <div className="space-y-0.5">+ <p className="text-sm font-medium">{t('settings:localApiServer.serverPort')}</p>+ <p className="text-xs text-muted-foreground">{t('settings:localApiServer.serverPortDesc')}</p>+ </div>+ <PortInput isServerRunning={isServerRunning} />+ </div>+ <div className="flex items-center justify-between">+ <div className="space-y-0.5">+ <p className="text-sm font-medium">{t('settings:localApiServer.apiPrefix')}</p>+ <p className="text-xs text-muted-foreground">{t('settings:localApiServer.apiPrefixDesc')}</p>+ </div>+ <ApiPrefixInput isServerRunning={isServerRunning} />+ </div>+ <div className="flex flex-col space-y-1">+ <p className="text-sm font-medium">{t('settings:localApiServer.apiKey')}</p>+ <p className="text-xs text-muted-foreground">{t('settings:localApiServer.apiKeyDesc')}</p>+ <div className="pt-1">+ <ApiKeyInput+ isServerRunning={isServerRunning}+ showError={showApiKeyError}+ onValidationChange={handleApiKeyValidation}+ />+ </div>+ </div>+ <div className="flex flex-col space-y-1">+ <p className="text-sm font-medium">{t('settings:localApiServer.trustedHosts')}</p>+ <p className="text-xs text-muted-foreground">{t('settings:localApiServer.trustedHostsDesc')}</p>+ <div className="pt-1">+ <TrustedHostsInput isServerRunning={isServerRunning} />+ </div>+ </div>+ <div className="flex items-center justify-between">+ <div className="space-y-0.5">+ <p className="text-sm font-medium">{t('settings:localApiServer.proxyTimeout')}</p>+ <p className="text-xs text-muted-foreground">{t('settings:localApiServer.proxyTimeoutDesc')}</p>+ </div>+ <ProxyTimeoutInput isServerRunning={isServerRunning} />+ </div>+ </div>++ <div className="flex items-center justify-between border-t border-border pt-4 mt-4">+ <h2 className="font-semibold text-sm">+ {t('settings:localApiServer.advancedSettings')}+ </h2>+ </div>+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <div className="space-y-0.5">+ <p className="text-sm font-medium">{t('settings:localApiServer.cors')}</p>+ <p className="text-xs text-muted-foreground">{t('settings:localApiServer.corsDesc')}</p>+ </div>+ <Switch+ checked={corsEnabled}+ onCheckedChange={setCorsEnabled}+ disabled={isServerRunning}+ />+ </div>+ <div className="flex items-center justify-between">+ <div className="space-y-0.5">+ <p className="text-sm font-medium">{t('settings:localApiServer.verboseLogs')}</p>+ <p className="text-xs text-muted-foreground">{t('settings:localApiServer.verboseLogsDesc')}</p>+ </div>+ <Switch+ checked={verboseLogs}+ onCheckedChange={setVerboseLogs}+ disabled={isServerRunning}+ />+ </div>+ </div>+ </div>+ </PopoverContent>+ </Popover></div></HeaderPage><div className="flex h-[calc(100%-60px)]"><SettingsMenu />- <div className="p-4 pt-0 w-full overflow-y-auto">- <div className="flex flex-col justify-between gap-4 gap-y-3 w-full">- {/* General Settings */}- <Card- header={- <div className="mb-3 flex w-full items-center border-b pb-2">- <div className="w-full space-y-2">- <h1 className="text-base font-medium text-foreground font-studio">- {t('settings:localApiServer.title')}- </h1>- <p className="text-muted-foreground mb-2">- {t('settings:localApiServer.description')}- </p>+ <div className="flex-1 flex flex-col min-h-0 pl-0">+ <div className="flex-1 overflow-y-auto p-4 pt-0">+ <div className="flex flex-col justify-between gap-4 gap-y-3 w-full">+ {/* General Settings */}+ <Card+ header={+ <div className="mb-3 flex w-full items-center border-b pb-2">+ <div className="w-full space-y-2">+ <h1 className="text-base font-medium text-foreground font-studio">+ {t('settings:localApiServer.title')}+ </h1>+ <p className="text-muted-foreground mb-2">+ {t('settings:localApiServer.description')}+ </p>+ </div>+ <div className="flex items-center gap-2">+ <Button+ onClick={toggleAPIServer}+ variant={isServerRunning ? 'destructive' : 'default'}+ size="sm"+ disabled={serverStatus === 'pending'} // Disable during any loading state+ >+ {getButtonText()}+ </Button>+ </div></div>- <div className="flex items-center gap-2">- <Button- onClick={toggleAPIServer}- variant={isServerRunning ? 'destructive' : 'default'}- size="sm"- disabled={serverStatus === 'pending'} // Disable during any loading state+ }+ >+ <CardItem+ title={t('settings:localApiServer.runOnStartup')}+ description={t('settings:localApiServer.runOnStartupDesc')}+ actions={+ <Switch+ checked={enableOnStartup}+ onCheckedChange={(checked) => {+ if (!apiKey || apiKey.toString().trim().length === 0) {+ setShowApiKeyError(true)+ return+ }+ setEnableOnStartup(checked)+ }}+ />+ }+ />+ </Card>++ <Card>+ <CardItem+ title="Server Status"+ description={+ isServerRunning ? (+ <div className="space-y-1">+ <div>The server is currently running.</div>+ <div className="text-xs font-mono">+ http://{serverHost}:{serverPort}{apiPrefix}+ </div>+ </div>+ ) : (+ "The server is stopped."+ )+ }+ />++ <CardItem+ title={t('settings:localApiServer.swaggerDocs')}+ description={t('settings:localApiServer.swaggerDocsDesc')}+ actions={+ <a+ href={`http://${serverHost}:${serverPort}`}+ target="_blank"+ rel="noopener noreferrer"+ className={cn(isServerRunning ? '' : 'pointer-events-none')}>- {getButtonText()}- </Button>- </div>+ <Button+ variant="outline"+ size="sm"+ disabled={!isServerRunning}+ title={t('settings:localApiServer.swaggerDocs')}+ >+ <span>{t('settings:localApiServer.openDocs')}</span>+ </Button>+ </a>+ }+ />+ </Card>++ {/* Helper Card */}+ <Card title='Run with your Claude Code'>+ <CardItem+ title="Big Model"+ actions ={+ <HelperModelSelector+ providers={providers}+ activeModels={activeModels}+ selectedModel={helperModels.big}+ onSelect={(model) => setHelperModel('big', model)}+ placeholder="Select Big Model"+ />+ }+ />+ <CardItem+ title="Medium Model"+ actions ={+ <HelperModelSelector+ providers={providers}+ activeModels={activeModels}+ selectedModel={helperModels.medium}+ onSelect={(model) => setHelperModel('medium', model)}+ placeholder="Select Medium Model"+ />+ }+ />+ <CardItem+ title="Small Model"+ actions ={+ <HelperModelSelector+ providers={providers}+ activeModels={activeModels}+ selectedModel={helperModels.small}+ onSelect={(model) => setHelperModel('small', model)}+ placeholder="Select Small Model"+ />+ }+ />+ <div className='flex mt-2 justify-between gap-2'>+ <Button size="sm" variant="outline" onClick={() => setIsCustomCliDialogOpen(true)}>+ <IconPlus className='text-muted-foreground' size={14} />+ Custom CLI+ </Button>+ <Button size="sm">Launch claude code</Button></div>- }- >- <CardItem- title={t('settings:localApiServer.runOnStartup')}- description={t('settings:localApiServer.runOnStartupDesc')}- actions={- <Switch- checked={enableOnStartup}- onCheckedChange={(checked) => {- if (!apiKey || apiKey.toString().trim().length === 0) {- setShowApiKeyError(true)- return- }- setEnableOnStartup(checked)- }}- />- }- />- <CardItem- title={t('settings:localApiServer.serverLogs')}- description={t('settings:localApiServer.serverLogsDesc')}- actions={++ {/* Display Custom CLI Configuration */}+ {(helperModels.customCli || helperModels.envVars.length > 0) && (+ <div className="mt-3 text-sm text-muted-foreground">+ {helperModels.customCli && (+ <div>Command: {helperModels.customCli}</div>+ )}+ {helperModels.envVars.length > 0 && (+ <div className="break-all">+ Env:{' '}+ {helperModels.envVars.map((env) => `${env.key}=******`).join(', ')}+ </div>+ )}+ </div>+ )}+ </Card>+ </div>+ </div>+ <AddEditCustomCliDialog+ open={isCustomCliDialogOpen}+ onOpenChange={setIsCustomCliDialogOpen}+ initialEnvVars={helperModels.envVars}+ initialCustomCli={helperModels.customCli}+ onSave={(envVars, customCli) => {+ setEnvVars(envVars)+ setCustomCli(customCli)+ }}+ />+ <div className="p-4 shrink-0">+ <Card>+ <Collapsible defaultOpen={false} onOpenChange={(open) => setIsLogVisible(open)}>+ <div className="flex items-center justify-between">+ <CollapsibleTrigger className="flex items-center gap-2 hover:no-underline">+ <IconChevronDown+ size={16}+ className="transition-transform data-[state=open]:rotate-180"+ />+ <span className="font-medium text-sm">Server Log</span>+ </CollapsibleTrigger><Button- variant="secondary"+ variant="outline"size="sm"- className="p-0"onClick={handleOpenLogs}- title={t('settings:localApiServer.serverLogs')}+ className="text-muted-foreground hover:text-foreground">- <IconLogs size={18} className="text-muted-foreground" />- <span>{t('settings:localApiServer.openLogs')}</span>+ <IconExternalLink size={14} className="mr-1" />+ Open in New Window</Button>- }- />-- <CardItem- title={t('settings:localApiServer.swaggerDocs')}- description={t('settings:localApiServer.swaggerDocsDesc')}- actions={- <a- href={`http://${serverHost}:${serverPort}`}- target="_blank"- rel="noopener noreferrer"- >- <Button- variant="secondary"- size="sm"- disabled={!isServerRunning}- title={t('settings:localApiServer.swaggerDocs')}- >- <span>{t('settings:localApiServer.openDocs')}</span>- </Button>- </a>- }- />- </Card>-- {/* Server Configuration */}- <Card title={t('settings:localApiServer.serverConfiguration')}>- <CardItem- title={t('settings:localApiServer.serverHost')}- description={t('settings:localApiServer.serverHostDesc')}- actions={- <ServerHostSwitcher isServerRunning={isServerRunning} />- }- />- <CardItem- title={t('settings:localApiServer.serverPort')}- description={t('settings:localApiServer.serverPortDesc')}- actions={<PortInput isServerRunning={isServerRunning} />}- />- <CardItem- title={t('settings:localApiServer.apiPrefix')}- description={t('settings:localApiServer.apiPrefixDesc')}- actions={<ApiPrefixInput isServerRunning={isServerRunning} />}- />- <CardItem- title={t('settings:localApiServer.apiKey')}- description={t('settings:localApiServer.apiKeyDesc')}- className={cn(- 'flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-y-2',- isApiKeyEmpty && showApiKeyError && 'pb-6'- )}- classNameWrapperAction="w-full sm:w-auto"- actions={- <ApiKeyInput- isServerRunning={isServerRunning}- showError={showApiKeyError}- onValidationChange={handleApiKeyValidation}- />- }- />- <CardItem- title={t('settings:localApiServer.trustedHosts')}- description={t('settings:localApiServer.trustedHostsDesc')}- className={cn(- 'flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-y-2'- )}- classNameWrapperAction="w-full sm:w-auto"- actions={- <TrustedHostsInput isServerRunning={isServerRunning} />- }- />- <CardItem- title={t('settings:localApiServer.proxyTimeout')}- description={t('settings:localApiServer.proxyTimeoutDesc')}- actions={- <ProxyTimeoutInput isServerRunning={isServerRunning} />- }- />- </Card>-- {/* Advanced Settings */}- <Card title={t('settings:localApiServer.advancedSettings')}>- <CardItem- title={t('settings:localApiServer.cors')}- description={t('settings:localApiServer.corsDesc')}- className={cn(- isServerRunning && 'opacity-50 pointer-events-none'- )}- actions={- <Switch- checked={corsEnabled}- onCheckedChange={setCorsEnabled}- />- }- />- <CardItem- title={t('settings:localApiServer.verboseLogs')}- description={t('settings:localApiServer.verboseLogsDesc')}- className={cn(- isServerRunning && 'opacity-50 pointer-events-none'- )}- actions={- <Switch- checked={verboseLogs}- onCheckedChange={setVerboseLogs}- />- }- />+ </div>+ <CollapsibleContent>+ <div className="pt-3">+ <div className="h-[200px]">+ <LogViewer isVisible={isLogVisible} />+ </div>+ </div>+ </CollapsibleContent>+ </Collapsible></Card></div></div>@@ -407,3 +556,225 @@ function LocalAPIServerContent() {</div>)}++function HelperModelSelector({+ providers,+ activeModels,+ selectedModel,+ onSelect,+ placeholder = 'Select a model',+}: {+ providers: ModelProvider[]+ activeModels: string[]+ selectedModel: string | null+ onSelect: (modelId: string) => void+ placeholder?: string+}) {+ const [open, setOpen] = useState(false)+ const [searchValue, setSearchValue] = useState('')+ const searchInputRef = useRef<HTMLInputElement>(null)++ // Get available models:+ // - llamacpp (local): show only active/downloaded models+ // - Remote providers: show models only if API key is configured+ const availableModels = useMemo(() => {+ return providers+ .filter((p) => p.active)+ .flatMap((p) =>+ p.models.map((m) => ({+ ...m,+ providerName: p.provider,+ isLocal: p.provider === 'llamacpp',+ hasApiKey: !!p.api_key?.length,+ }))+ )+ .filter((m) => {+ // llamacpp: only show active models+ if (m.isLocal) {+ return m.id+ }+ // Remote providers: only show if API key configured+ return m.hasApiKey+ })+ }, [providers, activeModels])++ // Filter models by search value+ const filteredModels = useMemo(() => {+ if (!searchValue.trim()) return availableModels+ const search = searchValue.toLowerCase()+ return availableModels.filter(+ (m) =>+ m.id.toLowerCase().includes(search) ||+ (m.displayName?.toLowerCase() ?? '').includes(search) ||+ m.providerName.toLowerCase().includes(search)+ )+ }, [availableModels, searchValue])++ // Group by provider+ const groupedModels = useMemo(() => {+ const groups: Record<string, typeof filteredModels> = {}+ filteredModels.forEach((model) => {+ if (!groups[model.providerName]) {+ groups[model.providerName] = []+ }+ groups[model.providerName].push(model)+ })+ return groups+ }, [filteredModels])++ const currentModel = availableModels.find(+ (m) => `${m.providerName}:${m.id}` === selectedModel+ )++ const currentProvider = currentModel+ ? providers.find((p) => p.provider === currentModel.providerName)+ : null++ // Format model display name with size+ const formatModelWithSize = (model: NonNullable<typeof currentModel>) => {+ const name = getModelDisplayName(model)+ // Model size is not directly available in provider models+ // Could be extended to show size if available in settings/metadata+ return name+ }++ const handleSelect = (model: typeof filteredModels[0]) => {+ onSelect(`${model.providerName}:${model.id}`)+ setOpen(false)+ setSearchValue('')+ }++ const handleOpenChange = (isOpen: boolean) => {+ setOpen(isOpen)+ if (!isOpen) {+ setSearchValue('')+ } else {+ setTimeout(() => searchInputRef.current?.focus(), 100)+ }+ }++ return (+ <Popover open={open} onOpenChange={handleOpenChange}>+ <PopoverTrigger asChild>+ <Button+ variant="outline"+ size="sm"+ className='max-w-[280px]'+ >+ {currentProvider && (+ <div className="shrink-0">+ <ProvidersAvatar provider={currentProvider} />+ </div>+ )}+ <span+ className={cn(+ 'text-foreground truncate leading-normal',+ !selectedModel && 'text-muted-foreground'+ )}+ >+ {selectedModel && currentModel+ ? formatModelWithSize(currentModel)+ : placeholder}+ </span>+ <IconChevronDown className="size-4 shrink-0 text-muted-foreground" />+ </Button>+ </PopoverTrigger>++ <PopoverContent+ className="w-[280px] p-0 bg-background/95 border"+ align="end"+ sideOffset={8}+ >+ <div className="flex flex-col size-full">+ {/* Search input */}+ <div className="relative p-2 border-b">+ <input+ ref={searchInputRef}+ value={searchValue}+ onChange={(e) => setSearchValue(e.target.value)}+ placeholder="Search models..."+ className="text-sm font-normal outline-0 w-full"+ />+ {searchValue.length > 0 && (+ <div className="absolute right-2 top-0 bottom-0 flex items-center justify-center">+ <IconX+ size={16}+ className="text-muted-foreground cursor-pointer"+ onClick={() => setSearchValue('')}+ />+ </div>+ )}+ </div>++ {/* Model list */}+ <div className="max-h-[300px] overflow-y-auto">+ {Object.keys(groupedModels).length === 0 && searchValue ? (+ <div className="py-3 px-4 text-sm text-muted-foreground">+ No models found for "{searchValue}"+ </div>+ ) : (+ <div className="py-1">+ {Object.entries(groupedModels).map(([providerKey, models]) => {+ const providerInfo = providers.find(+ (p) => p.provider === providerKey+ )+ if (!providerInfo) return null++ return (+ <div+ key={providerKey}+ className="bg-secondary/30 rounded-sm my-1.5 mx-1.5 first:mt-1 py-1"+ >+ {/* Provider header */}+ <div className="flex items-center gap-1.5 px-2 py-1">+ <ProvidersAvatar provider={providerInfo} />+ <span className="capitalize text-sm font-medium text-muted-foreground">+ {providerKey}+ </span>+ </div>++ {/* Models for this provider */}+ {models.map((model) => {+ const isSelected =+ selectedModel === `${model.providerName}:${model.id}`+ const capabilities = model.capabilities || []++ return (+ <div+ key={`${model.providerName}:${model.id}`}+ title={model.id}+ onClick={() => handleSelect(model)}+ className={cn(+ 'mx-1 mb-1 px-2 py-1.5 rounded-sm cursor-pointer flex items-center gap-2 transition-all duration-200',+ 'hover:bg-secondary/40',+ isSelected && 'bg-secondary/60 hover:bg-secondary/60'+ )}+ >+ <div className="flex items-center gap-2 flex-1 min-w-0">+ <span+ className="text-sm truncate"+ title={model.id}+ >+ {getModelDisplayName(model)}+ </span>+ <div className="flex-1"></div>+ {capabilities.length > 0 && (+ <div className="shrink-0 -mr-1.5">+ <Capabilities capabilities={capabilities} />+ </div>+ )}+ </div>+ </div>+ )+ })}+ </div>+ )+ })}+ </div>+ )}+ </div>+ </div>+ </PopoverContent>+ </Popover>+ )+}diff --git a/web-app/src/routes/settings/mcp-servers.tsx b/web-app/src/routes/settings/mcp-servers.tsxindex d1cde6511..0efdd6f6d 100644--- a/web-app/src/routes/settings/mcp-servers.tsx+++ b/web-app/src/routes/settings/mcp-servers.tsx@@ -365,7 +365,7 @@ function MCPServersDesktop() {<HeaderPage><div className="flex items-center gap-2 w-full justify-between pr-4"><span className='font-medium text-base font-studio'>{t('common:settings')}</span>- <Button variant="secondary" size="sm" onClick={() => handleOpenDialog()}>+ <Button variant="outline" size="sm" onClick={() => handleOpenDialog()}><IconPlus size={18} className="text-muted-foreground" />{t('mcp-servers:addServer')}</Button>