Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix: glitch UI issues (#6916)

Louis6e9dfa72b35b
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 52ea75520..66cf4ed19 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -4,7 +4,7 @@ import TextareaAutosize from 'react-textarea-autosize'
import { cn } from '@/lib/utils'
import { usePrompt } from '@/hooks/usePrompt'
import { useThreads } from '@/hooks/useThreads'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
import {
Tooltip,
@@ -108,7 +108,14 @@ const ChatInput = ({
const [attachments, setAttachments] = useState<Attachment[]>([])
const [isDragOver, setIsDragOver] = useState(false)
const [hasMmproj, setHasMmproj] = useState(false)
- const [hasActiveModels, setHasActiveModels] = useState(false)
+ const activeModels = useAppState(useShallow((state) => state.activeModels))
+ const hasActiveModels = useMemo(
+ () =>
+ activeModels.length > 0 &&
+ activeModels.some((e) => e === selectedModel?.id),
+ [activeModels, selectedModel?.id]
+ )
+
const attachmentsEnabled = useAttachments((s) => s.enabled)
// Determine whether to show the Attach documents button (simple gating)
const showAttachmentButton =
@@ -119,43 +126,6 @@ const ChatInput = ({
)
const ingestingAny = attachments.some((a) => a.processing)
- // Check for active models
- useEffect(() => {
- const checkActiveModels = async () => {
- try {
- const activeModels = await serviceHub
- .models()
- .getActiveModels('llamacpp')
- const hasMatchingActiveModel = activeModels.some(
- (model) => String(model) === selectedModel?.id
- )
- const newHasActiveModels =
- activeModels.length > 0 && hasMatchingActiveModel
-
- // Only update state if the value has actually changed
- setHasActiveModels((prev) => {
- if (prev === newHasActiveModels) {
- return prev
- }
- return newHasActiveModels
- })
- } catch (error) {
- console.error('Failed to get active models:', error)
- setHasActiveModels((prev) => {
- if (prev === false) return prev
- return false
- })
- }
- }
-
- checkActiveModels()
-
- // Poll for active models every 3 seconds
- const intervalId = setInterval(checkActiveModels, 3000)
-
- return () => clearInterval(intervalId)
- }, [serviceHub, selectedModel?.id])
-
// Check for mmproj existence or vision capability when model changes
useEffect(() => {
const checkMmprojSupport = async () => {
diff --git a/web-app/src/containers/ChatWidthSwitcher.tsx b/web-app/src/containers/ChatWidthSwitcher.tsx
index c58cbb47b..c35062271 100644
--- a/web-app/src/containers/ChatWidthSwitcher.tsx
+++ b/web-app/src/containers/ChatWidthSwitcher.tsx
@@ -12,12 +12,12 @@ export function ChatWidthSwitcher() {
<div className="flex flex-col sm:flex-row sm:gap-4">
<button
className={cn(
- 'w-full overflow-hidden border border-main-view-fg/10 rounded-md my-2 pb-2 cursor-pointer ',
+ 'w-full overflow-hidden border border-main-view-fg/10 rounded-md my-2 pb-2 cursor-pointer',
chatWidth === 'compact' && 'border-accent'
)}
onClick={() => setChatWidth('compact')}
>
- <div className="flex items-center justify-between px-4 py-2 bg-main-view-fg/10">
+ <div className="flex items-center justify-between px-4 pt-3 pb-2 bg-main-view-fg/10 -mt-1">
<span className="font-medium text-xs font-sans">
{t('common:compactWidth')}
</span>
diff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsx
index 3f3391d51..1409981be 100644
--- a/web-app/src/containers/ModelSetting.tsx
+++ b/web-app/src/containers/ModelSetting.tsx
@@ -16,6 +16,7 @@ import { useModelProvider } from '@/hooks/useModelProvider'
import { useServiceHub } from '@/hooks/useServiceHub'
import { cn, getModelDisplayName } from '@/lib/utils'
import { useTranslation } from '@/i18n/react-i18next-compat'
+import { useAppState } from '@/hooks/useAppState'
type ModelSettingProps = {
provider: ProviderObject
@@ -31,12 +32,22 @@ export function ModelSetting({
const { updateProvider } = useModelProvider()
const { t } = useTranslation()
const serviceHub = useServiceHub()
+ const setActiveModels = useAppState((state) => state.setActiveModels)
const [isPlanning, setIsPlanning] = useState(false)
// Create a debounced version of stopModel that waits 500ms after the last call
const debouncedStopModel = debounce((modelId: string) => {
- serviceHub.models().stopModel(modelId)
+ serviceHub
+ .models()
+ .stopModel(modelId)
+ .then(() => {
+ // Refresh active models after stopping
+ serviceHub
+ .models()
+ .getActiveModels()
+ .then((models) => setActiveModels(models || []))
+ })
}, 500)
const handlePlanModelLoad = async () => {
diff --git a/web-app/src/containers/ThreadScrollBehaviorSwitcher.tsx b/web-app/src/containers/ThreadScrollBehaviorSwitcher.tsx
index c0ba284fa..f322c7773 100644
--- a/web-app/src/containers/ThreadScrollBehaviorSwitcher.tsx
+++ b/web-app/src/containers/ThreadScrollBehaviorSwitcher.tsx
@@ -61,7 +61,7 @@ function ScrollOption({
onClick={onSelect}
type="button"
>
- <div className="flex items-center justify-between px-4 py-2 bg-main-view-fg/10">
+ <div className="flex items-center justify-between px-4 pt-3 pb-2 bg-main-view-fg/10 -mt-1">
<span className="font-medium text-xs font-sans">{title}</span>
{isSelected && (
<IconCircleCheckFilled className="size-4 text-accent" />
diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsx
index e6bc593b0..a64134ce2 100644
--- a/web-app/src/containers/__tests__/ChatInput.test.tsx
+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx
@@ -40,6 +40,8 @@ let mockAppState = {
loadingModel: false,
tools: [],
updateTools: vi.fn(),
+ activeModels: [] as string[],
+ cancelToolCall: vi.fn(),
}
vi.mock('@/hooks/useAppState', () => ({
@@ -245,6 +247,8 @@ describe('ChatInput', () => {
mockAppState.abortControllers = {}
mockAppState.loadingModel = false
mockAppState.tools = []
+ mockAppState.activeModels = []
+ mockAppState.cancelToolCall = vi.fn()
})
it('renders chat input textarea', async () => {
diff --git a/web-app/src/hooks/__tests__/useChat.test.ts b/web-app/src/hooks/__tests__/useChat.test.ts
index b1824fdf7..21187f9f8 100644
--- a/web-app/src/hooks/__tests__/useChat.test.ts
+++ b/web-app/src/hooks/__tests__/useChat.test.ts
@@ -63,6 +63,7 @@ vi.mock('../useAppState', () => ({
setAbortController: vi.fn(),
streamingContent: undefined,
setTokenSpeed: vi.fn(), // Added setTokenSpeed mock
+ setActiveModels: vi.fn(),
}
return selector ? selector(state) : state
},
@@ -266,6 +267,7 @@ vi.mock('../useServiceHub', () => ({
startModel: mockStartModel,
stopModel: vi.fn(() => Promise.resolve()),
stopAllModels: vi.fn(() => Promise.resolve()),
+ getActiveModels: vi.fn(() => Promise.resolve([])),
}),
providers: () => ({
updateSettings: vi.fn(() => Promise.resolve()),
diff --git a/web-app/src/hooks/useAppState.ts b/web-app/src/hooks/useAppState.ts
index 4819db05f..a712c87ab 100644
--- a/web-app/src/hooks/useAppState.ts
+++ b/web-app/src/hooks/useAppState.ts
@@ -28,6 +28,7 @@ type AppState = {
showOutOfContextDialog?: boolean
errorMessage?: AppErrorMessage
promptProgress?: PromptProgress
+ activeModels: string[]
cancelToolCall?: () => void
setServerStatus: (value: 'running' | 'stopped' | 'pending') => void
updateStreamingContent: (content: ThreadMessage | undefined) => void
@@ -49,6 +50,7 @@ type AppState = {
setCancelToolCall: (cancel: (() => void) | undefined) => void
setErrorMessage: (error: AppErrorMessage | undefined) => void
updatePromptProgress: (progress: PromptProgress | undefined) => void
+ setActiveModels: (models: string[]) => void
}
export const useAppState = create<AppState>()((set) => ({
@@ -61,6 +63,7 @@ export const useAppState = create<AppState>()((set) => ({
currentToolCall: undefined,
promptProgress: undefined,
cancelToolCall: undefined,
+ activeModels: [],
updateStreamingContent: (content: ThreadMessage | undefined) => {
const assistants = useAssistant.getState().assistants
const currentAssistant = useAssistant.getState().currentAssistant
@@ -175,4 +178,9 @@ export const useAppState = create<AppState>()((set) => ({
promptProgress: progress,
}))
},
+ setActiveModels: (models: string[]) => {
+ set(() => ({
+ activeModels: models,
+ }))
+ }
}))
diff --git a/web-app/src/hooks/useChat.ts b/web-app/src/hooks/useChat.ts
index 4e492a26c..e99f8471f 100644
--- a/web-app/src/hooks/useChat.ts
+++ b/web-app/src/hooks/useChat.ts
@@ -106,7 +106,11 @@ const processStreamingCompletion = async (
currentCall: ChatCompletionMessageToolCall | null,
updateStreamingContent: (content: ThreadMessage | undefined) => void,
updateTokenSpeed: (message: ThreadMessage, increment?: number) => void,
- setTokenSpeed: (message: ThreadMessage, tokensPerSecond: number, totalTokens: number) => void,
+ setTokenSpeed: (
+ message: ThreadMessage,
+ tokensPerSecond: number,
+ totalTokens: number
+ ) => void,
updatePromptProgress: (progress: PromptProgress | undefined) => void,
timeToFirstToken: number,
tokenUsageRef: { current: CompletionUsage | undefined },
@@ -284,79 +288,91 @@ export const useChat = () => {
const setMessages = useMessages((state) => state.setMessages)
const setModelLoadError = useModelLoad((state) => state.setModelLoadError)
const router = useRouter()
+ const setActiveModels = useAppState((state) => state.setActiveModels)
- const getCurrentThread = useCallback(async (projectId?: string) => {
- let currentThread = retrieveThread()
+ const getCurrentThread = useCallback(
+ async (projectId?: string) => {
+ let currentThread = retrieveThread()
- // Check if we're in temporary chat mode
- const isTemporaryMode = window.location.search.includes(`${TEMPORARY_CHAT_QUERY_ID}=true`)
-
- // Clear messages for existing temporary thread on reload to ensure fresh start
- if (isTemporaryMode && currentThread?.id === TEMPORARY_CHAT_ID) {
- setMessages(TEMPORARY_CHAT_ID, [])
- }
+ // Check if we're in temporary chat mode
+ const isTemporaryMode = window.location.search.includes(
+ `${TEMPORARY_CHAT_QUERY_ID}=true`
+ )
- if (!currentThread) {
- // Get prompt directly from store when needed
- const currentPrompt = usePrompt.getState().prompt
- const currentAssistant = useAssistant.getState().currentAssistant
- const assistants = useAssistant.getState().assistants
- const selectedModel = useModelProvider.getState().selectedModel
- const selectedProvider = useModelProvider.getState().selectedProvider
+ // Clear messages for existing temporary thread on reload to ensure fresh start
+ if (isTemporaryMode && currentThread?.id === TEMPORARY_CHAT_ID) {
+ setMessages(TEMPORARY_CHAT_ID, [])
+ }
- // Get project metadata if projectId is provided
- let projectMetadata: { id: string; name: string; updated_at: number } | undefined
- if (projectId) {
- const project = await serviceHub.projects().getProjectById(projectId)
- if (project) {
- projectMetadata = {
- id: project.id,
- name: project.name,
- updated_at: project.updated_at,
+ if (!currentThread) {
+ // Get prompt directly from store when needed
+ const currentPrompt = usePrompt.getState().prompt
+ const currentAssistant = useAssistant.getState().currentAssistant
+ const assistants = useAssistant.getState().assistants
+ const selectedModel = useModelProvider.getState().selectedModel
+ const selectedProvider = useModelProvider.getState().selectedProvider
+
+ // Get project metadata if projectId is provided
+ let projectMetadata:
+ | { id: string; name: string; updated_at: number }
+ | undefined
+ if (projectId) {
+ const project = await serviceHub.projects().getProjectById(projectId)
+ if (project) {
+ projectMetadata = {
+ id: project.id,
+ name: project.name,
+ updated_at: project.updated_at,
+ }
}
}
- }
- currentThread = await createThread(
- {
- id: selectedModel?.id ?? defaultModel(selectedProvider),
- provider: selectedProvider,
- },
- isTemporaryMode ? 'Temporary Chat' : currentPrompt,
- assistants.find((a) => a.id === currentAssistant?.id) || assistants[0],
- projectMetadata,
- isTemporaryMode // pass temporary flag
- )
+ currentThread = await createThread(
+ {
+ id: selectedModel?.id ?? defaultModel(selectedProvider),
+ provider: selectedProvider,
+ },
+ isTemporaryMode ? 'Temporary Chat' : currentPrompt,
+ assistants.find((a) => a.id === currentAssistant?.id) ||
+ assistants[0],
+ projectMetadata,
+ isTemporaryMode // pass temporary flag
+ )
- // Clear messages for temporary chat to ensure fresh start on reload
- if (isTemporaryMode && currentThread?.id === TEMPORARY_CHAT_ID) {
- setMessages(TEMPORARY_CHAT_ID, [])
- }
+ // Clear messages for temporary chat to ensure fresh start on reload
+ if (isTemporaryMode && currentThread?.id === TEMPORARY_CHAT_ID) {
+ setMessages(TEMPORARY_CHAT_ID, [])
+ }
- // Set flag for temporary chat navigation
- if (currentThread.id === TEMPORARY_CHAT_ID) {
- sessionStorage.setItem('temp-chat-nav', 'true')
- }
+ // Set flag for temporary chat navigation
+ if (currentThread.id === TEMPORARY_CHAT_ID) {
+ sessionStorage.setItem('temp-chat-nav', 'true')
+ }
- router.navigate({
- to: route.threadsDetail,
- params: { threadId: currentThread.id },
- })
- }
- return currentThread
- }, [createThread, retrieveThread, router, setMessages, serviceHub])
+ router.navigate({
+ to: route.threadsDetail,
+ params: { threadId: currentThread.id },
+ })
+ }
+ return currentThread
+ },
+ [createThread, retrieveThread, router, setMessages, serviceHub]
+ )
const restartModel = useCallback(
async (provider: ProviderObject, modelId: string) => {
await serviceHub.models().stopAllModels()
- await new Promise((resolve) => setTimeout(resolve, 1000))
updateLoadingModel(true)
await serviceHub
.models()
.startModel(provider, modelId)
.catch(console.error)
+ // Refresh active models after starting
updateLoadingModel(false)
- await new Promise((resolve) => setTimeout(resolve, 1000))
+ serviceHub
+ .models()
+ .getActiveModels()
+ .then((models) => setActiveModels(models || []))
},
[updateLoadingModel, serviceHub]
)
@@ -496,7 +512,9 @@ export const useChat = () => {
updateAttachmentProcessing(img.name, 'processing')
}
// Upload image, get id/URL
- const res = await serviceHub.uploads().ingestImage(activeThread.id, img)
+ const res = await serviceHub
+ .uploads()
+ .ingestImage(activeThread.id, img)
processedAttachments.push({
...img,
id: res.id,
@@ -512,7 +530,9 @@ export const useChat = () => {
updateAttachmentProcessing(img.name, 'error')
}
const desc = err instanceof Error ? err.message : String(err)
- toast.error('Failed to ingest image attachment', { description: desc })
+ toast.error('Failed to ingest image attachment', {
+ description: desc,
+ })
return
}
}
@@ -563,7 +583,6 @@ export const useChat = () => {
useThreads.getState().updateThread(activeThread.id, {
metadata: { hasDocuments: true },
})
-
} catch (err) {
console.error('Failed to ingest documents:', err)
const desc = err instanceof Error ? err.message : String(err)
@@ -607,7 +626,7 @@ export const useChat = () => {
// If continuing, start with the previous content
const accumulatedTextRef = {
- value: continueFromMessage?.content?.[0]?.text?.value || ''
+ value: continueFromMessage?.content?.[0]?.text?.value || '',
}
let currentAssistant: Assistant | undefined | null
@@ -616,6 +635,11 @@ export const useChat = () => {
updateLoadingModel(true)
await serviceHub.models().startModel(activeProvider, selectedModel.id)
updateLoadingModel(false)
+ // Refresh active models after starting
+ serviceHub
+ .models()
+ .getActiveModels()
+ .then((models) => setActiveModels(models || []))
}
currentAssistant = useAssistant.getState().currentAssistant
@@ -657,7 +681,9 @@ export const useChat = () => {
useAttachments.getState().enabled &&
PlatformFeatures[PlatformFeature.FILE_ATTACHMENTS]
// Check if documents were attached in the current thread
- const hasDocuments = useThreads.getState().getThreadById(activeThread.id)?.metadata?.hasDocuments
+ const hasDocuments = useThreads
+ .getState()
+ .getThreadById(activeThread.id)?.metadata?.hasDocuments
if (hasDocuments && ragFeatureAvailable) {
try {
const ragTools = await serviceHub
@@ -680,10 +706,17 @@ export const useChat = () => {
(selectedModel?.capabilities?.includes('proactive') ?? false)
// Proactive mode: Capture initial screenshot/snapshot before first LLM call
- if (isProactiveMode && availableTools.length > 0 && !abortController.signal.aborted) {
- console.log('Proactive mode: Capturing initial screenshots before LLM call')
+ if (
+ isProactiveMode &&
+ availableTools.length > 0 &&
+ !abortController.signal.aborted
+ ) {
+ console.log(
+ 'Proactive mode: Capturing initial screenshots before LLM call'
+ )
try {
- const initialScreenshots = await captureProactiveScreenshots(abortController)
+ const initialScreenshots =
+ await captureProactiveScreenshots(abortController)
// Add initial screenshots to builder
for (const screenshot of initialScreenshots) {
@@ -750,7 +783,10 @@ export const useChat = () => {
if (isCompletionResponse(completion)) {
const message = completion.choices[0]?.message
const newContent = (message?.content as string) || ''
- if (continueFromMessageId && accumulatedTextRef.value.length > 0) {
+ if (
+ continueFromMessageId &&
+ accumulatedTextRef.value.length > 0
+ ) {
accumulatedTextRef.value += newContent
} else {
accumulatedTextRef.value = newContent
@@ -829,6 +865,12 @@ export const useChat = () => {
await serviceHub
.models()
.stopModel(activeThread.model.id, 'llamacpp')
+
+ // Refresh active models after stopping
+ serviceHub
+ .models()
+ .getActiveModels()
+ .then((models) => setActiveModels(models || []))
throw new Error('No response received from the model')
}
@@ -855,7 +897,11 @@ export const useChat = () => {
// Normal completion flow (abort is handled after loop exits)
// Don't add assistant message to builder if continuing - it's already there
if (!continueFromMessageId) {
- builder.addAssistantMessage(accumulatedTextRef.value, undefined, toolCalls)
+ builder.addAssistantMessage(
+ accumulatedTextRef.value,
+ undefined,
+ toolCalls
+ )
}
// Check if proactive mode is enabled for this model
@@ -947,7 +993,8 @@ export const useChat = () => {
// If aborted, save the partial message even though an error occurred
// Only save for llamacpp provider - other providers handle streaming differently
const streamingContent = useAppState.getState().streamingContent
- const hasPartialContent = accumulatedTextRef.value.length > 0 ||
+ const hasPartialContent =
+ accumulatedTextRef.value.length > 0 ||
(streamingContent && streamingContent.content?.[0]?.text?.value)
if (
@@ -956,7 +1003,9 @@ export const useChat = () => {
activeProvider?.provider === 'llamacpp'
) {
// Use streaming content if available, otherwise use accumulatedTextRef
- const contentText = streamingContent?.content?.[0]?.text?.value || accumulatedTextRef.value
+ const contentText =
+ streamingContent?.content?.[0]?.text?.value ||
+ accumulatedTextRef.value
// If continuing, update the existing message; otherwise add new
if (continueFromMessageId && continueFromMessage) {
@@ -982,15 +1031,11 @@ export const useChat = () => {
})
} else {
const partialContent = {
- ...newAssistantThreadContent(
- activeThread.id,
- contentText,
- {
- tokenSpeed: useAppState.getState().tokenSpeed,
- assistant: currentAssistant,
- modelId: selectedModel?.id,
- }
- ),
+ ...newAssistantThreadContent(activeThread.id, contentText, {
+ tokenSpeed: useAppState.getState().tokenSpeed,
+ assistant: currentAssistant,
+ modelId: selectedModel?.id,
+ }),
status: MessageStatus.Stopped,
}
addMessage(partialContent)
diff --git a/web-app/src/providers/DataProvider.tsx b/web-app/src/providers/DataProvider.tsx
index dfd899da0..efa9d210e 100644
--- a/web-app/src/providers/DataProvider.tsx
+++ b/web-app/src/providers/DataProvider.tsx
@@ -24,6 +24,7 @@ export function DataProvider() {
const { setThreads } = useThreads()
const navigate = useNavigate()
const serviceHub = useServiceHub()
+ const setActiveModels = useAppState((state) => state.setActiveModels)
// Local API Server hooks
const {
@@ -139,6 +140,11 @@ export function DataProvider() {
.startModel(modelToStart.provider, modelToStart.model)
.then(() => {
console.log(`Model ${modelToStart.model} started successfully`)
+ // Refresh active models after starting
+ serviceHub
+ .models()
+ .getActiveModels()
+ .then((models) => setActiveModels(models || []))
// Then start the server
return window.core?.api?.startServer({
diff --git a/web-app/src/routes/settings/hardware.tsx b/web-app/src/routes/settings/hardware.tsx
index 83c383198..b45fc5ae9 100644
--- a/web-app/src/routes/settings/hardware.tsx
+++ b/web-app/src/routes/settings/hardware.tsx
@@ -17,6 +17,7 @@ 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-any
export const Route = createFileRoute(route.settings.hardware as any)({
@@ -42,6 +43,7 @@ function HardwareContent() {
updateSystemUsage,
pollingPaused,
} = useHardware()
+ const setActiveModels = useAppState((state) => state.setActiveModels)
const { providers } = useModelProvider()
const llamacpp = providers.find((p) => p.provider === 'llamacpp')
@@ -75,14 +77,18 @@ function HardwareContent() {
useEffect(() => {
setIsLoading(true)
Promise.all([
- serviceHub.hardware().getHardwareInfo()
+ serviceHub
+ .hardware()
+ .getHardwareInfo()
.then((data: HardwareData | null) => {
if (data) setHardwareData(data)
})
.catch((error) => {
console.error('Failed to get hardware info:', error)
}),
- serviceHub.hardware().getSystemUsage()
+ serviceHub
+ .hardware()
+ .getSystemUsage()
.then((data: SystemUsage | null) => {
if (data) updateSystemUsage(data)
})
@@ -94,14 +100,14 @@ function HardwareContent() {
})
}, [serviceHub, setHardwareData, updateSystemUsage])
-
-
useEffect(() => {
if (pollingPaused) {
return
}
const intervalId = setInterval(() => {
- serviceHub.hardware().getSystemUsage()
+ serviceHub
+ .hardware()
+ .getSystemUsage()
.then((data: SystemUsage | null) => {
if (data) updateSystemUsage(data)
})
@@ -309,6 +315,14 @@ function HardwareContent() {
onCheckedChange={() => {
toggleDevice(device.id)
serviceHub.models().stopAllModels()
+
+ // Refresh active models after stopping
+ serviceHub
+ .models()
+ .getActiveModels()
+ .then((models) =>
+ setActiveModels(models || [])
+ )
}}
/>
</div>
diff --git a/web-app/src/routes/settings/local-api-server.tsx b/web-app/src/routes/settings/local-api-server.tsx
index 3ca2922b6..83634fcde 100644
--- a/web-app/src/routes/settings/local-api-server.tsx
+++ b/web-app/src/routes/settings/local-api-server.tsx
@@ -63,6 +63,7 @@ function LocalAPIServerContent() {
const [isApiKeyEmpty, setIsApiKeyEmpty] = useState(
!apiKey || apiKey.toString().trim().length === 0
)
+ const setActiveModels = useAppState((state) => state.setActiveModels)
useEffect(() => {
const checkServerStatus = async () => {
@@ -134,7 +135,11 @@ function LocalAPIServerContent() {
.then(() => {
console.log(`Model ${modelToStart.model} started successfully`)
setIsModelLoading(false) // Model loaded, stop loading state
-
+ // Refresh active models after starting
+ serviceHub
+ .models()
+ .getActiveModels()
+ .then((models) => setActiveModels(models || []))
// Add a small delay for the backend to update state
return new Promise((resolve) => setTimeout(resolve, 500))
})
diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsx
index 0e52cb059..2a92c6228 100644
--- a/web-app/src/routes/settings/providers/$providerName.tsx
+++ b/web-app/src/routes/settings/providers/$providerName.tsx
@@ -42,6 +42,8 @@ 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'
+import { useShallow } from 'zustand/shallow'
// as route.threadsDetail
export const Route = createFileRoute('/settings/providers/$providerName')({
@@ -79,7 +81,9 @@ function ProviderDetail() {
},
]
const { step } = useSearch({ from: Route.id })
- const [activeModels, setActiveModels] = useState<string[]>([])
+ const [activeModels, setActiveModels] = useAppState(
+ useShallow((state) => [state.activeModels, state.setActiveModels])
+ )
const [loadingModels, setLoadingModels] = useState<string[]>([])
const [refreshingModels, setRefreshingModels] = useState(false)
const [isCheckingBackendUpdate, setIsCheckingBackendUpdate] = useState(false)
@@ -173,16 +177,6 @@ function ProviderDetail() {
.models()
.getActiveModels()
.then((models) => setActiveModels(models || []))
-
- // Set up interval for real-time updates
- const intervalId = setInterval(() => {
- serviceHub
- .models()
- .getActiveModels()
- .then((models) => setActiveModels(models || []))
- }, 5000)
-
- return () => clearInterval(intervalId)
}, [serviceHub, setActiveModels])
// Clear importing state when model appears in the provider's model list
@@ -385,7 +379,7 @@ function ProviderDetail() {
await installBackend(selectedFile)
// Extract filename from the selected file path and replace spaces with dashes
- const fileName = basenameNoExt(selectedFile).replace(/\s+/g, "-")
+ const fileName = basenameNoExt(selectedFile).replace(/\s+/g, '-')
toast.success(t('settings:backendInstallSuccess'), {
description: `Llamacpp ${fileName} installed`,
@@ -565,6 +559,14 @@ function ProviderDetail() {
})
serviceHub.models().stopAllModels()
+
+ // Refresh active models after stopping
+ serviceHub
+ .models()
+ .getActiveModels()
+ .then((models) =>
+ setActiveModels(models || [])
+ )
}
}}
/>
diff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.ts
index 9c99ddb37..e2a23fce0 100644
--- a/web-app/src/services/models/default.ts
+++ b/web-app/src/services/models/default.ts
@@ -13,6 +13,7 @@ import {
ContentType,
events,
DownloadEvent,
+ UnloadResult,
} from '@janhq/core'
import { Model as CoreModel } from '@janhq/core'
import type {
@@ -288,8 +289,11 @@ export class DefaultModelsService implements ModelsService {
return this.getEngine(provider)?.getLoadedModels() ?? []
}
- async stopModel(model: string, provider?: string): Promise<void> {
- this.getEngine(provider)?.unload(model)
+ async stopModel(
+ model: string,
+ provider?: string
+ ): Promise<UnloadResult | undefined> {
+ return this.getEngine(provider)?.unload(model)
}
async stopAllModels(): Promise<void> {
diff --git a/web-app/src/services/models/types.ts b/web-app/src/services/models/types.ts
index 4f7ef638f..1b3e2b2c6 100644
--- a/web-app/src/services/models/types.ts
+++ b/web-app/src/services/models/types.ts
@@ -2,7 +2,7 @@
* Models Service Types
*/
-import { SessionInfo, modelInfo, ThreadMessage } from '@janhq/core'
+import { SessionInfo, modelInfo, ThreadMessage, UnloadResult } from '@janhq/core'
import { Model as CoreModel } from '@janhq/core'
// Types for model catalog
@@ -118,7 +118,7 @@ export interface ModelsService {
abortDownload(id: string): Promise<void>
deleteModel(id: string): Promise<void>
getActiveModels(provider?: string): Promise<string[]>
- stopModel(model: string, provider?: string): Promise<void>
+ stopModel(model: string, provider?: string): Promise<UnloadResult | undefined>
stopAllModels(): Promise<void>
startModel(
provider: ProviderObject,