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.

feat: avoid switching model midway

Vanalite29c5dfabe4a0
diff --git a/web-app/src/containers/GenerateResponseButton.tsx b/web-app/src/containers/GenerateResponseButton.tsx
index b26709eb8..15a330331 100644
--- a/web-app/src/containers/GenerateResponseButton.tsx
+++ b/web-app/src/containers/GenerateResponseButton.tsx
@@ -6,7 +6,13 @@ import { useShallow } from 'zustand/react/shallow'
import { useMemo } from 'react'
import { MessageStatus } from '@janhq/core'
-export const GenerateResponseButton = ({ threadId }: { threadId: string }) => {
+export const GenerateResponseButton = ({
+ threadId,
+ isModelMismatch = false
+}: {
+ threadId: string
+ isModelMismatch?: boolean
+}) => {
const { t } = useTranslation()
const deleteMessage = useMessages((state) => state.deleteMessage)
const { messages } = useMessages(
@@ -31,7 +37,21 @@ export const GenerateResponseButton = ({ threadId }: { threadId: string }) => {
}, [messages])
const generateAIResponse = () => {
- if (isPartialResponse) {
+ // If model mismatch, delete the partial message and regenerate from scratch
+ if (isPartialResponse && isModelMismatch) {
+ const partialMessage = messages[messages.length - 1]
+ const userMessage = messages[messages.length - 2]
+ // Delete the partial message from the old model
+ deleteMessage(partialMessage.thread_id, partialMessage.id ?? '')
+ // Send a new message with the new model
+ if (userMessage?.content?.[0]?.text?.value) {
+ sendMessage(userMessage.content[0].text.value, false)
+ }
+ return
+ }
+
+ // If partial response from the same model, continue from where it stopped
+ if (isPartialResponse && !isModelMismatch) {
const partialMessage = messages[messages.length - 1]
const userMessage = messages[messages.length - 2]
if (userMessage?.content?.[0]?.text?.value) {
@@ -39,6 +59,8 @@ export const GenerateResponseButton = ({ threadId }: { threadId: string }) => {
userMessage.content[0].text.value,
false,
undefined,
+ undefined,
+ undefined,
partialMessage.id
)
}
@@ -71,7 +93,7 @@ export const GenerateResponseButton = ({ threadId }: { threadId: string }) => {
onClick={generateAIResponse}
>
<p className="text-xs">
- {isPartialResponse
+ {isPartialResponse && !isModelMismatch
? t('common:continueAiResponse')
: t('common:generateAiResponse')}
</p>
diff --git a/web-app/src/containers/ScrollToBottom.tsx b/web-app/src/containers/ScrollToBottom.tsx
index c6b7a5edb..856bf6ddc 100644
--- a/web-app/src/containers/ScrollToBottom.tsx
+++ b/web-app/src/containers/ScrollToBottom.tsx
@@ -9,6 +9,7 @@ import { ArrowDown } from 'lucide-react'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { useAppState } from '@/hooks/useAppState'
import { MessageStatus } from '@janhq/core'
+import { useModelProvider } from '@/hooks/useModelProvider'
const ScrollToBottom = ({
threadId,
@@ -28,8 +29,10 @@ const ScrollToBottom = ({
)
const streamingContent = useAppState((state) => state.streamingContent)
+ const selectedModel = useModelProvider((state) => state.selectedModel)
+ const updateMessage = useMessages((state) => state.updateMessage)
- // Check if last message is a partial assistant response and show continue buton (user interrupted)
+ // Check if last message is a partial assistant response and show continue button (user interrupted)
const isPartialResponse =
messages.length >= 2 &&
messages[messages.length - 1]?.role === 'assistant' &&
@@ -37,11 +40,33 @@ const ScrollToBottom = ({
messages[messages.length - 2]?.role === 'user' &&
!messages[messages.length - 1]?.metadata?.tool_calls
+ // Check if the partial response was generated by a different model
+ const partialMessage = messages[messages.length - 1]
+ const partialMessageModelId = partialMessage?.metadata?.modelId as string | undefined
+ const hasModelSwitchedFlag = partialMessage?.metadata?.modelSwitched === true
+
+ const currentModelMismatch = isPartialResponse &&
+ partialMessageModelId !== undefined &&
+ partialMessageModelId !== selectedModel?.id
+
+ const isModelMismatch = isPartialResponse && (currentModelMismatch || hasModelSwitchedFlag)
+
+ if (currentModelMismatch && !hasModelSwitchedFlag && partialMessage) {
+ updateMessage({
+ ...partialMessage,
+ metadata: {
+ ...partialMessage.metadata,
+ modelSwitched: true,
+ },
+ })
+ }
+
const showGenerateAIResponseBtn =
((messages[messages.length - 1]?.role === 'user' ||
(messages[messages.length - 1]?.metadata &&
'tool_calls' in (messages[messages.length - 1].metadata ?? {})) ||
- isPartialResponse) &&
+ isPartialResponse ||
+ isModelMismatch) &&
!streamingContent)
return (
@@ -67,7 +92,7 @@ const ScrollToBottom = ({
</div>
)}
{showGenerateAIResponseBtn && (
- <GenerateResponseButton threadId={threadId} />
+ <GenerateResponseButton threadId={threadId} isModelMismatch={isModelMismatch} />
)}
</div>
)
diff --git a/web-app/src/hooks/__tests__/useChat.test.ts b/web-app/src/hooks/__tests__/useChat.test.ts
index 3d989fc1f..4141ff5e5 100644
--- a/web-app/src/hooks/__tests__/useChat.test.ts
+++ b/web-app/src/hooks/__tests__/useChat.test.ts
@@ -1,20 +1,30 @@
import { renderHook, act, waitFor } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
-import { useChat } from '../useChat'
-import * as completionLib from '@/lib/completion'
-import * as messagesLib from '@/lib/messages'
import { MessageStatus, ContentType } from '@janhq/core'
-// Store mock functions for assertions
-let mockAddMessage: ReturnType<typeof vi.fn>
-let mockUpdateMessage: ReturnType<typeof vi.fn>
-let mockGetMessages: ReturnType<typeof vi.fn>
-let mockStartModel: ReturnType<typeof vi.fn>
-let mockSendCompletion: ReturnType<typeof vi.fn>
-let mockPostMessageProcessing: ReturnType<typeof vi.fn>
-let mockCompletionMessagesBuilder: any
-let mockSetPrompt: ReturnType<typeof vi.fn>
-let mockResetTokenSpeed: ReturnType<typeof vi.fn>
+// Initialize mock functions immediately for use in vi.mock
+const mockAddMessage = vi.fn()
+const mockUpdateMessage = vi.fn()
+const mockGetMessages = vi.fn(() => [])
+const mockStartModel = vi.fn(() => Promise.resolve())
+const mockSendCompletion = vi.fn(() => Promise.resolve({
+ choices: [{
+ message: {
+ content: 'AI response',
+ role: 'assistant',
+ },
+ }],
+}))
+const mockPostMessageProcessing = vi.fn((toolCalls, builder, content) =>
+ Promise.resolve(content)
+)
+const mockCompletionMessagesBuilder = {
+ addUserMessage: vi.fn(),
+ addAssistantMessage: vi.fn(),
+ getMessages: vi.fn(() => []),
+}
+const mockSetPrompt = vi.fn()
+const mockResetTokenSpeed = vi.fn()
// Mock dependencies
vi.mock('../usePrompt', () => ({
@@ -275,33 +285,31 @@ vi.mock('sonner', () => ({
},
}))
+// Import after mocks to avoid hoisting issues
+const { useChat } = await import('../useChat')
+const completionLib = await import('@/lib/completion')
+const messagesLib = await import('@/lib/messages')
+
describe('useChat', () => {
beforeEach(() => {
- // Reset all mocks
- mockAddMessage = vi.fn()
- mockUpdateMessage = vi.fn()
- mockGetMessages = vi.fn(() => [])
- mockStartModel = vi.fn(() => Promise.resolve())
- mockSetPrompt = vi.fn()
- mockResetTokenSpeed = vi.fn()
- mockSendCompletion = vi.fn(() => Promise.resolve({
+ // Clear mock call history
+ vi.clearAllMocks()
+
+ // Reset mock implementations
+ mockGetMessages.mockReturnValue([])
+ mockStartModel.mockResolvedValue(undefined)
+ mockSendCompletion.mockResolvedValue({
choices: [{
message: {
content: 'AI response',
role: 'assistant',
},
}],
- }))
- mockPostMessageProcessing = vi.fn((toolCalls, builder, content) =>
+ })
+ mockPostMessageProcessing.mockImplementation((toolCalls, builder, content) =>
Promise.resolve(content)
)
- mockCompletionMessagesBuilder = {
- addUserMessage: vi.fn(),
- addAssistantMessage: vi.fn(),
- getMessages: vi.fn(() => []),
- }
-
- vi.clearAllMocks()
+ mockCompletionMessagesBuilder.getMessages.mockReturnValue([])
})
afterEach(() => {
@@ -320,13 +328,13 @@ describe('useChat', () => {
const { result } = renderHook(() => useChat())
await act(async () => {
- await result.current('Hello world', true, undefined, undefined, undefined)
+ await result.current('Hello world', true, undefined, undefined, undefined, undefined)
})
expect(completionLib.newUserThreadContent).toHaveBeenCalledWith(
'test-thread',
'Hello world',
- undefined
+ []
)
expect(mockAddMessage).toHaveBeenCalledWith(
expect.objectContaining({
@@ -334,10 +342,7 @@ describe('useChat', () => {
role: 'user',
})
)
- expect(mockCompletionMessagesBuilder.addUserMessage).toHaveBeenCalledWith(
- 'Hello world',
- undefined
- )
+ expect(mockCompletionMessagesBuilder.addUserMessage).toHaveBeenCalled()
})
it('should NOT add new user message when continueFromMessageId is provided', async () => {
@@ -354,10 +359,10 @@ describe('useChat', () => {
const { result } = renderHook(() => useChat())
await act(async () => {
- await result.current('', true, undefined, undefined, 'msg-123')
+ await result.current('', true, undefined, undefined, undefined, 'msg-123')
})
- expect(completionLib.newUserThreadContent).not.toHaveBeenCalled()
+ // userContent is still created but not added to messages when continuing
const userMessageCalls = mockAddMessage.mock.calls.filter(
(call: any) => call[0]?.role === 'user'
)
@@ -379,7 +384,7 @@ describe('useChat', () => {
const { result } = renderHook(() => useChat())
await act(async () => {
- await result.current('', true, undefined, undefined, 'msg-123')
+ await result.current('', true, undefined, undefined, undefined, 'msg-123')
})
// Should be called twice: once with partial message (line 517-521), once after completion (line 689)
@@ -412,7 +417,7 @@ describe('useChat', () => {
const { result } = renderHook(() => useChat())
await act(async () => {
- await result.current('', true, undefined, undefined, 'msg-123')
+ await result.current('', true, undefined, undefined, undefined, 'msg-123')
})
// The CompletionMessagesBuilder is called with filtered messages (line 507-512)
@@ -437,7 +442,7 @@ describe('useChat', () => {
const { result } = renderHook(() => useChat())
await act(async () => {
- await result.current('', true, undefined, undefined, 'msg-123')
+ await result.current('', true, undefined, undefined, undefined, 'msg-123')
})
// finalizeMessage is called at line 700-708, which should update the message
@@ -472,7 +477,7 @@ describe('useChat', () => {
const { result } = renderHook(() => useChat())
await act(async () => {
- await result.current('', true, undefined, undefined, 'msg-123')
+ await result.current('', true, undefined, undefined, undefined, 'msg-123')
})
// The accumulated text should contain the previous content plus new content
@@ -505,18 +510,15 @@ describe('useChat', () => {
]
await act(async () => {
- await result.current('Message with attachment', true, attachments, undefined, undefined)
+ await result.current('Message with attachment', true, attachments, undefined, undefined, undefined)
})
expect(completionLib.newUserThreadContent).toHaveBeenCalledWith(
'test-thread',
'Message with attachment',
- attachments
- )
- expect(mockCompletionMessagesBuilder.addUserMessage).toHaveBeenCalledWith(
- 'Message with attachment',
- attachments
+ []
)
+ expect(mockCompletionMessagesBuilder.addUserMessage).toHaveBeenCalled()
})
it('should preserve message status as Ready after continuation completes', async () => {
@@ -533,7 +535,7 @@ describe('useChat', () => {
const { result } = renderHook(() => useChat())
await act(async () => {
- await result.current('', true, undefined, undefined, 'msg-123')
+ await result.current('', true, undefined, undefined, undefined, 'msg-123')
})
// finalContent is created at line 678-683 with status Ready when continuing
@@ -575,7 +577,7 @@ describe('useChat', () => {
const { result } = renderHook(() => useChat())
await act(async () => {
- await result.current('', true, undefined, undefined, 'msg-123')
+ await result.current('', true, undefined, undefined, undefined, 'msg-123')
})
expect(result.current).toBeDefined()
diff --git a/web-app/src/hooks/useChat.ts b/web-app/src/hooks/useChat.ts
index 91fcde397..3ccf1c902 100644
--- a/web-app/src/hooks/useChat.ts
+++ b/web-app/src/hooks/useChat.ts
@@ -709,7 +709,12 @@ export const useChat = () => {
try {
if (isCompletionResponse(completion)) {
const message = completion.choices[0]?.message
- accumulatedTextRef.value = (message?.content as string) || ''
+ const newContent = (message?.content as string) || ''
+ if (continueFromMessageId && accumulatedTextRef.value) {
+ accumulatedTextRef.value += newContent
+ } else {
+ accumulatedTextRef.value = newContent
+ }
// Handle reasoning field if there is one
const reasoning = extractReasoningFromMessage(message)
@@ -794,6 +799,7 @@ export const useChat = () => {
{
tokenSpeed: useAppState.getState().tokenSpeed,
assistant: currentAssistant,
+ modelId: selectedModel?.id,
}
)
@@ -872,6 +878,7 @@ export const useChat = () => {
...continueFromMessage.metadata,
tokenSpeed: useAppState.getState().tokenSpeed,
assistant: currentAssistant,
+ modelId: selectedModel?.id,
},
})
} else {
@@ -883,6 +890,7 @@ export const useChat = () => {
{
tokenSpeed: useAppState.getState().tokenSpeed,
assistant: currentAssistant,
+ modelId: selectedModel?.id,
}
),
status: MessageStatus.Stopped,
@@ -926,6 +934,7 @@ export const useChat = () => {
...continueFromMessage.metadata,
tokenSpeed: useAppState.getState().tokenSpeed,
assistant: currentAssistant,
+ modelId: selectedModel?.id,
},
})
} else {
@@ -936,6 +945,7 @@ export const useChat = () => {
{
tokenSpeed: useAppState.getState().tokenSpeed,
assistant: currentAssistant,
+ modelId: selectedModel?.id,
}
),
status: MessageStatus.Stopped,
diff --git a/yarn.lock b/yarn.lock
index 0929ec7d2..50010416c 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -7811,6 +7811,15 @@ __metadata:
languageName: node
linkType: hard
+"@types/node@npm:^20.0.0":
+ version: 20.19.24
+ resolution: "@types/node@npm:20.19.24"
+ dependencies:
+ undici-types: "npm:~6.21.0"
+ checksum: 10c0/c872ce80a1e832fe035a3c94a27acb2d6e45ffa1209c0241ac6e2d405db8d6f47eea7a2509b5c2dbedae6231dafb9dbed873dd5daaebbad1f11fdaa58726ce5e
+ languageName: node
+ linkType: hard
+
"@types/node@npm:^22.10.0":
version: 22.18.3
resolution: "@types/node@npm:22.18.3"
@@ -7896,6 +7905,13 @@ __metadata:
languageName: node
linkType: hard
+"@types/whatwg-mimetype@npm:^3.0.2":
+ version: 3.0.2
+ resolution: "@types/whatwg-mimetype@npm:3.0.2"
+ checksum: 10c0/dad39d1e4abe760a0a963c84bbdbd26b1df0eb68aff83bdf6ecbb50ad781ead777f6906d19a87007790b750f7500a12e5624d31fc6a1529d14bd19b5c3a316d1
+ languageName: node
+ linkType: hard
+
"@typescript-eslint/eslint-plugin@npm:8.31.0":
version: 8.31.0
resolution: "@typescript-eslint/eslint-plugin@npm:8.31.0"