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: system message from assistant

Louis73a22637a6fb
diff --git a/core/src/types/message/messageEntity.ts b/core/src/types/message/messageEntity.ts
index 20979c68e..10d180637 100644
--- a/core/src/types/message/messageEntity.ts
+++ b/core/src/types/message/messageEntity.ts
@@ -138,7 +138,9 @@ export enum ErrorCode {
*/
export enum ContentType {
Text = 'text',
+ Reasoning = 'reasoning',
Image = 'image_url',
+ ToolCall = 'tool_call',
}
/**
@@ -165,8 +167,15 @@ export type ImageContentValue = {
*/
export type ThreadContent = {
type: ContentType
+ // For text and reasoning content
text?: ContentValue
+ // For image content
image_url?: ImageContentValue
+ // For tool call content
+ tool_call_id?: string
+ tool_name?: string
+ input?: unknown
+ output?: unknown
}
export interface Attachment {
diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsx
deleted file mode 100644
index 842152b2c..000000000
--- a/web-app/src/containers/__tests__/ChatInput.test.tsx
+++ /dev/null
@@ -1,457 +0,0 @@
-import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
-import { describe, it, expect, vi, beforeEach } from 'vitest'
-import userEvent from '@testing-library/user-event'
-import { RouterProvider, createRouter, createRootRoute, createMemoryHistory } from '@tanstack/react-router'
-import ChatInput from '../ChatInput'
-import { usePrompt } from '@/hooks/usePrompt'
-import { useThreads } from '@/hooks/useThreads'
-import { useAppState } from '@/hooks/useAppState'
-import { useGeneralSetting } from '@/hooks/useGeneralSetting'
-import { useModelProvider } from '@/hooks/useModelProvider'
-import { useChat } from '@/hooks/useChat'
-import type { ThreadModel } from '@/types/threads'
-
-// Mock dependencies with mutable state
-let mockPromptState = {
- prompt: '',
- setPrompt: vi.fn(),
-}
-
-vi.mock('@/hooks/usePrompt', () => ({
- usePrompt: (selector: any) => {
- return selector ? selector(mockPromptState) : mockPromptState
- },
-}))
-
-vi.mock('@/hooks/useThreads', () => ({
- useThreads: (selector: any) => {
- const state = {
- currentThreadId: null,
- getCurrentThread: vi.fn(),
- }
- return selector ? selector(state) : state
- },
-}))
-
-// Mock the useAppState with a mutable state
-let mockAppState = {
- streamingContent: null,
- abortControllers: {},
- loadingModel: false,
- tools: [],
- updateTools: vi.fn(),
- activeModels: [] as string[],
- cancelToolCall: vi.fn(),
-}
-
-vi.mock('@/hooks/useAppState', () => ({
- useAppState: (selector?: any) => selector ? selector(mockAppState) : mockAppState,
-}))
-
-vi.mock('@/hooks/useGeneralSetting', () => ({
- useGeneralSetting: (selector?: any) => {
- const state = {
- allowSendWhenUnloaded: false,
- spellCheckChatInput: true,
- experimentalFeatures: true,
- }
- return selector ? selector(state) : state
- },
-}))
-
-vi.mock('@/hooks/useModelProvider', () => ({
- useModelProvider: (selector: any) => {
- const state = {
- selectedModel: {
- id: 'test-model',
- capabilities: ['vision', 'tools'],
- },
- providers: [],
- getModelBy: vi.fn(),
- selectModelProvider: vi.fn(),
- selectedProvider: 'llamacpp',
- setProviders: vi.fn(),
- getProviderByName: vi.fn(),
- updateProvider: vi.fn(),
- addProvider: vi.fn(),
- deleteProvider: vi.fn(),
- deleteModel: vi.fn(),
- deletedModels: [],
- }
- return selector ? selector(state) : state
- },
-}))
-
-vi.mock('@/hooks/useChat', () => ({
- useChat: vi.fn(() => vi.fn()), // useChat returns sendMessage function directly
-}))
-
-vi.mock('@/i18n/react-i18next-compat', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}))
-
-// Mock the global core API
-Object.defineProperty(globalThis, 'core', {
- value: {
- api: {
- existsSync: vi.fn(() => true),
- getJanDataFolderPath: vi.fn(() => '/mock/path'),
- },
- },
- writable: true,
-})
-
-// Mock the useTools hook
-vi.mock('@/hooks/useTools', () => ({
- useTools: vi.fn(),
-}))
-
-// Mock the ServiceHub
-const mockGetConnectedServers = vi.fn(() => Promise.resolve(['server1']))
-const mockGetTools = vi.fn(() => Promise.resolve([]))
-const mockStopAllModels = vi.fn()
-const mockCheckMmprojExists = vi.fn(() => Promise.resolve(true))
-const mockGetActiveModels = vi.fn(() => Promise.resolve([]))
-
-const mockListen = vi.fn(() => Promise.resolve(() => {}))
-
-const mockServiceHub = {
- mcp: () => ({
- getConnectedServers: mockGetConnectedServers,
- getTools: mockGetTools,
- }),
- models: () => ({
- stopAllModels: mockStopAllModels,
- checkMmprojExists: mockCheckMmprojExists,
- getActiveModels: mockGetActiveModels,
- }),
- events: () => ({
- listen: mockListen,
- }),
-}
-
-vi.mock('@/hooks/useServiceHub', () => ({
- getServiceHub: () => mockServiceHub,
- useServiceHub: () => mockServiceHub,
-}))
-
-vi.mock('../MovingBorder', () => ({
- MovingBorder: ({ children }: { children: React.ReactNode }) => <div data-testid="moving-border">{children}</div>,
-}))
-
-vi.mock('../DropdownModelProvider', () => ({
- __esModule: true,
- default: () => <div data-testid="model-dropdown" data-slot="popover-trigger">Model Dropdown</div>,
-}))
-
-vi.mock('../loaders/ModelLoader', () => ({
- ModelLoader: () => <div data-testid="model-loader">Model Loader</div>,
-}))
-
-vi.mock('../DropdownToolsAvailable', () => ({
- __esModule: true,
- default: ({ children }: { children: (isOpen: boolean, toolsCount: number) => React.ReactNode }) => {
- return <div data-testid="tools-dropdown">{children(false, 0)}</div>
- },
-}))
-
-vi.mock('@/components/ui/button', () => ({
- Button: ({ children, onClick, disabled, ...props }: any) => (
- <button
- onClick={onClick}
- disabled={disabled}
- data-test-id={props['data-test-id']}
- data-testid={props['data-test-id']}
- {...props}
- >
- {children}
- </button>
- ),
-}))
-
-vi.mock('@/components/ui/tooltip', () => ({
- Tooltip: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- TooltipContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- TooltipProvider: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- TooltipTrigger: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
-vi.mock('@/components/ui/dropdown-menu', () => ({
- DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DropdownMenuItem: ({ children, onClick }: { children: React.ReactNode; onClick?: () => void }) => (
- <div onClick={onClick}>{children}</div>
- ),
- DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
-vi.mock('react-textarea-autosize', () => ({
- default: ({ value, onChange, onKeyDown, placeholder, disabled, className, minRows, maxRows, onHeightChange, ...props }: any) => (
- <textarea
- value={value}
- onChange={onChange}
- onKeyDown={onKeyDown}
- placeholder={placeholder}
- disabled={disabled}
- className={className}
- data-testid={props['data-testid']}
- rows={minRows || 1}
- style={{ resize: 'none' }}
- />
- ),
-}))
-
-// Mock icons
-vi.mock('lucide-react', () => ({
- ArrowRight: () => <svg data-testid="arrow-right-icon">ArrowRight</svg>,
- PlusIcon: () => <svg data-testid="plus-icon">PlusIcon</svg>,
-}))
-
-vi.mock('@tabler/icons-react', () => ({
- IconPhoto: () => <svg data-testid="photo-icon">Photo</svg>,
- IconWorld: () => <svg data-testid="world-icon">World</svg>,
- IconAtom: () => <svg data-testid="atom-icon">Atom</svg>,
- IconTool: () => <svg data-testid="tool-icon">Tool</svg>,
- IconCodeCircle2: () => <svg data-testid="code-icon">Code</svg>,
- IconPaperclip: () => <svg data-testid="paperclip-icon">Paperclip</svg>,
- IconLoader2: () => <svg data-testid="loader-icon">Loader</svg>,
- IconCheck: () => <svg data-testid="check-icon">Check</svg>,
- IconPlayerStopFilled: () => <svg className="tabler-icon-player-stop-filled" data-testid="stop-icon">Stop</svg>,
- IconX: () => <svg data-testid="x-icon">X</svg>,
-}))
-
-describe('ChatInput', () => {
- const mockSendMessage = vi.fn()
- const mockSetPrompt = vi.fn()
-
- const createTestRouter = () => {
- const MockComponent = () => <ChatInput />
- const rootRoute = createRootRoute({
- component: MockComponent,
- })
-
- return createRouter({
- routeTree: rootRoute,
- history: createMemoryHistory({
- initialEntries: ['/'],
- }),
- })
- }
-
- const renderWithRouter = () => {
- const router = createTestRouter()
- return render(<RouterProvider router={router} />)
- }
-
-
- beforeEach(() => {
- vi.clearAllMocks()
-
- // Reset mock states
- mockPromptState.prompt = ''
- mockPromptState.setPrompt = vi.fn()
-
- mockAppState.streamingContent = null
- mockAppState.abortControllers = {}
- mockAppState.loadingModel = false
- mockAppState.tools = []
- mockAppState.activeModels = []
- mockAppState.cancelToolCall = vi.fn()
- })
-
- it('renders chat input textarea', async () => {
- await act(async () => {
- renderWithRouter()
- })
-
- const textarea = screen.getByTestId('chat-input')
- expect(textarea).toBeInTheDocument()
- expect(textarea).toHaveAttribute('placeholder', 'common:placeholder.chatInput')
- })
-
- it('renders send button', async () => {
- await act(async () => {
- renderWithRouter()
- })
-
- const sendButton = document.querySelector('[data-test-id="send-message-button"]')
- expect(sendButton).toBeInTheDocument()
- })
-
- it('disables send button when prompt is empty', async () => {
- await act(async () => {
- renderWithRouter()
- })
-
- const sendButton = document.querySelector('[data-test-id="send-message-button"]')
- expect(sendButton).toBeDisabled()
- })
-
- it('enables send button when prompt has content', async () => {
- // Set prompt content
- mockPromptState.prompt = 'Hello world'
-
- await act(async () => {
- renderWithRouter()
- })
-
- const sendButton = document.querySelector('[data-test-id="send-message-button"]')
- expect(sendButton).not.toBeDisabled()
- })
-
- it('calls setPrompt when typing in textarea', async () => {
- const user = userEvent.setup()
- await act(async () => {
- renderWithRouter()
- })
-
- const textarea = screen.getByTestId('chat-input')
- await act(async () => {
- await user.type(textarea, 'Hello')
- })
-
- // setPrompt is called for each character typed
- expect(mockPromptState.setPrompt).toHaveBeenCalledTimes(5)
- expect(mockPromptState.setPrompt).toHaveBeenLastCalledWith('o')
- })
-
- it('calls sendMessage when send button is clicked', async () => {
- const user = userEvent.setup()
-
- // Set prompt content
- mockPromptState.prompt = 'Hello world'
-
- await act(async () => {
- renderWithRouter()
- })
-
- const sendButton = document.querySelector('[data-test-id="send-message-button"]')
- await act(async () => {
- await user.click(sendButton)
- })
-
- // Note: Since useChat now returns the sendMessage function directly, we need to mock it differently
- // For now, we'll just check that the button was clicked successfully
- expect(sendButton).toBeInTheDocument()
- })
-
- it('sends message when Enter key is pressed', async () => {
- const user = userEvent.setup()
-
- // Set prompt content
- mockPromptState.prompt = 'Hello world'
-
- await act(async () => {
- renderWithRouter()
- })
-
- const textarea = screen.getByTestId('chat-input')
- await act(async () => {
- await user.type(textarea, '{Enter}')
- })
-
- // Just verify the textarea exists and Enter was processed
- expect(textarea).toBeInTheDocument()
- })
-
- it('does not send message when Shift+Enter is pressed', async () => {
- const user = userEvent.setup()
-
- // Set prompt content
- mockPromptState.prompt = 'Hello world'
-
- await act(async () => {
- renderWithRouter()
- })
-
- const textarea = screen.getByTestId('chat-input')
- await act(async () => {
- await user.type(textarea, '{Shift>}{Enter}{/Shift}')
- })
-
- // Just verify the textarea exists
- expect(textarea).toBeInTheDocument()
- })
-
- it('shows stop button when streaming', async () => {
- // Mock streaming state
- mockAppState.streamingContent = { thread_id: 'test-thread' }
-
- await act(async () => {
- renderWithRouter()
- })
-
- // Stop button should be rendered (as SVG with tabler-icon-player-stop-filled class)
- const stopButton = document.querySelector('.tabler-icon-player-stop-filled')
- expect(stopButton).toBeInTheDocument()
- })
-
-
- it('shows model selection dropdown', async () => {
- await act(async () => {
- renderWithRouter()
- })
-
- // Model selection dropdown should be rendered (look for popover trigger)
- const modelDropdown = document.querySelector('[data-slot="popover-trigger"]')
- expect(modelDropdown).toBeInTheDocument()
- })
-
- it('shows error message when no model is selected', async () => {
- const user = userEvent.setup()
-
- // Mock no selected model and prompt with content
- mockPromptState.prompt = 'Hello world'
-
- await act(async () => {
- renderWithRouter()
- })
-
- const sendButton = document.querySelector('[data-test-id="send-message-button"]')
- await act(async () => {
- await user.click(sendButton)
- })
-
- // The component should still render without crashing when no model is selected
- expect(sendButton).toBeInTheDocument()
- })
-
- it('handles file upload', async () => {
- const user = userEvent.setup()
- await act(async () => {
- renderWithRouter()
- })
-
- // Wait for async effects to complete (mmproj check)
- await waitFor(() => {
- // File upload is rendered as hidden input element
- const fileInput = document.querySelector('input[type="file"]')
- expect(fileInput).toBeInTheDocument()
- })
- })
-
- it('shows tools dropdown when model supports tools and MCP servers are connected', async () => {
- // Mock connected servers
- mockGetConnectedServers.mockResolvedValue(['server1'])
- mockAppState.tools = [{ name: 'test-tool' } as any]
-
- await act(async () => {
- renderWithRouter()
- })
-
- await waitFor(() => {
- // Tools dropdown should be rendered
- const toolsDropdown = screen.getByTestId('tools-dropdown')
- expect(toolsDropdown).toBeInTheDocument()
- })
- })
-
- it('uses selectedProvider for provider checks', async () => {
- // This test ensures the component renders without errors when using selectedProvider
- await act(async () => {
- expect(() => renderWithRouter()).not.toThrow()
- })
- })
-})
diff --git a/web-app/src/hooks/__tests__/useTools.test.ts b/web-app/src/hooks/__tests__/useTools.test.ts
index 82561e2db..b78982630 100644
--- a/web-app/src/hooks/__tests__/useTools.test.ts
+++ b/web-app/src/hooks/__tests__/useTools.test.ts
@@ -19,6 +19,9 @@ vi.mock('@/hooks/useServiceHub', () => ({
mcp: () => ({
getTools: mockGetTools,
}),
+ rag: () => ({
+ getToolNames: vi.fn(() => Promise.resolve([])),
+ }),
events: () => ({
listen: mockListen,
}),
diff --git a/web-app/src/hooks/use-chat.ts b/web-app/src/hooks/use-chat.ts
index 624360986..e08a56062 100644
--- a/web-app/src/hooks/use-chat.ts
+++ b/web-app/src/hooks/use-chat.ts
@@ -1,6 +1,5 @@
import {
CustomChatTransport,
- type ServiceHub,
} from '@/lib/custom-chat-transport'
// import { useCapabilities } from "@/stores/capabilities-store";
import {
@@ -11,7 +10,6 @@ import {
} from '@ai-sdk/react'
import {
type ChatInit,
- type LanguageModel,
type LanguageModelUsage,
} from 'ai'
import { useEffect, useMemo, useRef, useCallback } from 'react'
@@ -22,7 +20,7 @@ type CustomChatOptions = Omit<ChatInit<UIMessage>, 'transport'> &
Pick<UseChatOptions<UIMessage>, 'experimental_throttle' | 'resume'> & {
sessionId?: string
sessionTitle?: string
- serviceHub?: ServiceHub
+ systemMessage?: string
onTokenUsage?: (usage: LanguageModelUsage, messageId: string) => void;
}
@@ -30,14 +28,13 @@ type CustomChatOptions = Omit<ChatInit<UIMessage>, 'transport'> &
// It implements model switching and uses the custom chat transport,
// making a nice reusable hook for chat functionality.
export function useChat(
- model: LanguageModel | null,
options?: CustomChatOptions
) {
const transportRef = useRef<CustomChatTransport | undefined>(undefined) // Using a ref here so we can update the model used in the transport without having to reload the page or recreate the transport
const {
sessionId,
sessionTitle,
- serviceHub,
+ systemMessage,
onTokenUsage,
...chatInitOptions
} = options ?? {}
@@ -45,14 +42,18 @@ export function useChat(
const setSessionTitle = useChatSessions((state) => state.setSessionTitle)
const updateStatus = useChatSessions((state) => state.updateStatus)
+ // Get serviceHub and model metadata from app state
+ const languageModelId = useAppState((state) => state.languageModelId)
+ const languageModelProvider = useAppState((state) => state.languageModelProvider)
+
const existingSessionTransport = sessionId
? useChatSessions.getState().sessions[sessionId]?.transport
: undefined
- // Only create transport when model is available
- if (model && transportRef.current?.model !== model) {
+ // Create transport immediately with modelId and provider
+ if (!transportRef.current) {
transportRef.current =
- existingSessionTransport ?? new CustomChatTransport(model, serviceHub)
+ existingSessionTransport ?? new CustomChatTransport(languageModelId, languageModelProvider, systemMessage)
} else if (
existingSessionTransport &&
transportRef.current !== existingSessionTransport
@@ -60,11 +61,18 @@ export function useChat(
transportRef.current = existingSessionTransport
}
+ // Update model metadata when it changes
useEffect(() => {
- if (model && transportRef.current?.model !== model) {
- transportRef.current!.updateModel(model)
+ if (languageModelId && languageModelProvider && transportRef.current) {
+ transportRef.current.updateModelMetadata(languageModelId, languageModelProvider)
+ }
+ }, [languageModelId, languageModelProvider])
+
+ useEffect(() => {
+ if (transportRef.current) {
+ transportRef.current.updateSystemMessage(systemMessage)
}
- }, [model])
+ }, [systemMessage])
// Set up streaming token speed callback to update global state
const setTokenSpeed = useAppState((state) => state.setTokenSpeed)
@@ -108,7 +116,7 @@ export function useChat(
sessionTitle
)
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [sessionId, ensureSession, model])
+ }, [sessionId, ensureSession, languageModelId, languageModelProvider])
useEffect(() => {
if (sessionId && sessionTitle) {
diff --git a/web-app/src/hooks/useAppState.ts b/web-app/src/hooks/useAppState.ts
index f1feec507..85877bcdf 100644
--- a/web-app/src/hooks/useAppState.ts
+++ b/web-app/src/hooks/useAppState.ts
@@ -33,6 +33,8 @@ type AppState = {
promptProgress?: PromptProgress
activeModels: string[]
languageModel: LanguageModel | null
+ languageModelId?: string
+ languageModelProvider?: ProviderObject
cancelToolCall?: () => void
setServerStatus: (value: 'running' | 'stopped' | 'pending') => void
updateStreamingContent: (content: ThreadMessage | undefined) => void
@@ -57,7 +59,11 @@ type AppState = {
setErrorMessage: (error: AppErrorMessage | undefined) => void
updatePromptProgress: (progress: PromptProgress | undefined) => void
setActiveModels: (models: string[]) => void
- setLanguageModel: (model: LanguageModel | null) => void
+ setLanguageModel: (
+ model: LanguageModel | null,
+ modelId?: string,
+ provider?: ProviderObject
+ ) => void
}
export const useAppState = create<AppState>()((set) => ({
@@ -74,6 +80,8 @@ export const useAppState = create<AppState>()((set) => ({
cancelToolCall: undefined,
activeModels: [],
languageModel: null,
+ languageModelId: undefined,
+ languageModelProvider: undefined,
updateStreamingContent: (content: ThreadMessage | undefined) => {
const assistants = useAssistant.getState().assistants
const currentAssistant = useAssistant.getState().currentAssistant
@@ -199,9 +207,11 @@ export const useAppState = create<AppState>()((set) => ({
activeModels: models,
}))
},
- setLanguageModel: (model) => {
+ setLanguageModel: (model, modelId, provider) => {
set(() => ({
languageModel: model,
+ languageModelId: modelId,
+ languageModelProvider: provider,
}))
},
}))
diff --git a/web-app/src/hooks/useServiceHub.ts b/web-app/src/hooks/useServiceHub.ts
index 0a0b00d05..947416b5c 100644
--- a/web-app/src/hooks/useServiceHub.ts
+++ b/web-app/src/hooks/useServiceHub.ts
@@ -6,7 +6,7 @@ interface ServiceState {
setServiceHub: (serviceHub: ServiceHub) => void
}
-const useServiceStore = create<ServiceState>()((set) => ({
+export const useServiceStore = create<ServiceState>()((set) => ({
serviceHub: null,
setServiceHub: (serviceHub: ServiceHub) => set({ serviceHub }),
}))
@@ -17,11 +17,11 @@ const useServiceStore = create<ServiceState>()((set) => ({
*/
export const useServiceHub = (): ServiceHub => {
const serviceHub = useServiceStore((state) => state.serviceHub)
-
+
if (!serviceHub) {
throw new Error('ServiceHub not initialized. Make sure services are initialized before using this hook.')
}
-
+
return serviceHub
}
@@ -31,11 +31,11 @@ export const useServiceHub = (): ServiceHub => {
*/
export const getServiceHub = (): ServiceHub => {
const serviceHub = useServiceStore.getState().serviceHub
-
+
if (!serviceHub) {
throw new Error('ServiceHub not initialized. Make sure services are initialized before accessing services.')
}
-
+
return serviceHub
}
diff --git a/web-app/src/lib/__tests__/messages.test.ts b/web-app/src/lib/__tests__/messages.test.ts
index 978895ca5..888682613 100644
--- a/web-app/src/lib/__tests__/messages.test.ts
+++ b/web-app/src/lib/__tests__/messages.test.ts
@@ -1,11 +1,9 @@
import { describe, it, expect } from 'vitest'
import {
CompletionMessagesBuilder,
- extractToolCallsFromUIMessage,
} from '../messages'
import { ThreadMessage } from '@janhq/core'
import { ChatCompletionMessageToolCall } from 'openai/resources'
-import type { UIMessage } from '@ai-sdk/react'
// Mock thread messages for testing
const createMockThreadMessage = (
@@ -567,238 +565,3 @@ describe('CompletionMessagesBuilder', () => {
})
})
-describe('extractToolCallsFromUIMessage', () => {
- it('should return undefined when message has no tool calls', () => {
- const message: UIMessage = {
- id: 'msg-123',
- role: 'assistant',
- parts: [{ type: 'text', text: 'Hello, how can I help?' }],
- } as UIMessage
-
- const result = extractToolCallsFromUIMessage(message)
- expect(result).toBeUndefined()
- })
-
- it('should extract tool calls with string output', () => {
- const message: UIMessage = {
- id: 'msg-123',
- role: 'assistant',
- parts: [
- {
- type: 'tool-get_weather',
- toolInvocationId: 'call_123',
- toolName: 'get_weather',
- input: { location: 'New York' },
- output: 'The weather is 72°F and sunny',
- },
- ],
- } as UIMessage
-
- const result = extractToolCallsFromUIMessage(message)
- expect(result).toHaveLength(1)
- expect(result?.[0]).toEqual({
- tool: {
- id: 'call_123',
- type: 'function',
- function: {
- name: 'get_weather',
- arguments: JSON.stringify({ location: 'New York' }),
- },
- },
- response: {
- content: [{ type: 'text', text: 'The weather is 72°F and sunny' }],
- },
- state: 'ready',
- })
- })
-
- it('should extract tool calls with array output', () => {
- const message: UIMessage = {
- id: 'msg-123',
- role: 'assistant',
- parts: [
- {
- type: 'tool-search',
- toolInvocationId: 'call_456',
- toolName: 'search',
- input: { query: 'test' },
- output: [
- { type: 'text', text: 'Search result 1' },
- { type: 'text', text: 'Search result 2' },
- ],
- },
- ],
- } as UIMessage
-
- const result = extractToolCallsFromUIMessage(message)
- expect(result).toHaveLength(1)
- expect(result?.[0].response?.content).toEqual([
- { type: 'text', text: 'Search result 1' },
- { type: 'text', text: 'Search result 2' },
- ])
- })
-
- it('should extract tool calls with object containing content property', () => {
- const message: UIMessage = {
- id: 'msg-123',
- role: 'assistant',
- parts: [
- {
- type: 'tool-analyze',
- toolInvocationId: 'call_789',
- toolName: 'analyze',
- input: { data: 'sample' },
- result: {
- content: [{ type: 'text', text: 'Analysis complete' }],
- },
- },
- ],
- } as UIMessage
-
- const result = extractToolCallsFromUIMessage(message)
- expect(result).toHaveLength(1)
- expect(result?.[0].response?.content).toEqual([
- { type: 'text', text: 'Analysis complete' },
- ])
- })
-
- it('should handle tool calls with complex object output (fallback to stringify)', () => {
- const message: UIMessage = {
- id: 'msg-123',
- role: 'assistant',
- parts: [
- {
- type: 'tool-complex',
- toolInvocationId: 'call_999',
- toolName: 'complex',
- input: { param: 'value' },
- output: { foo: 'bar', nested: { key: 'value' } },
- },
- ],
- } as UIMessage
-
- const result = extractToolCallsFromUIMessage(message)
- expect(result).toHaveLength(1)
- expect(result?.[0].response?.content).toEqual([
- { type: 'text', text: JSON.stringify({ foo: 'bar', nested: { key: 'value' } }) },
- ])
- })
-
- it('should handle tool calls with toolCallId instead of toolInvocationId', () => {
- const message: UIMessage = {
- id: 'msg-123',
- role: 'assistant',
- parts: [
- {
- type: 'tool-test',
- toolCallId: 'call_alt',
- toolName: 'test',
- args: { key: 'value' },
- output: 'Test result',
- },
- ],
- } as UIMessage
-
- const result = extractToolCallsFromUIMessage(message)
- expect(result).toHaveLength(1)
- expect(result?.[0].tool.id).toBe('call_alt')
- })
-
- it('should handle tool calls with args instead of input', () => {
- const message: UIMessage = {
- id: 'msg-123',
- role: 'assistant',
- parts: [
- {
- type: 'tool-test',
- toolInvocationId: 'call_abc',
- toolName: 'test',
- args: { param: 'value' },
- output: 'Result',
- },
- ],
- } as UIMessage
-
- const result = extractToolCallsFromUIMessage(message)
- expect(result).toHaveLength(1)
- expect(result?.[0].tool.function.arguments).toBe(
- JSON.stringify({ param: 'value' })
- )
- })
-
- it('should handle multiple tool calls', () => {
- const message: UIMessage = {
- id: 'msg-123',
- role: 'assistant',
- parts: [
- {
- type: 'tool-first',
- toolInvocationId: 'call_1',
- toolName: 'first',
- input: { a: 1 },
- output: 'First result',
- },
- { type: 'text', text: 'Some text between' },
- {
- type: 'tool-second',
- toolInvocationId: 'call_2',
- toolName: 'second',
- input: { b: 2 },
- output: 'Second result',
- },
- ],
- } as UIMessage
-
- const result = extractToolCallsFromUIMessage(message)
- expect(result).toHaveLength(2)
- expect(result?.[0].tool.function.name).toBe('first')
- expect(result?.[1].tool.function.name).toBe('second')
- })
-
- it('should ignore tool parts without output or result', () => {
- const message: UIMessage = {
- id: 'msg-123',
- role: 'assistant',
- parts: [
- {
- type: 'tool-pending',
- toolInvocationId: 'call_pending',
- toolName: 'pending',
- input: { data: 'test' },
- // No output or result
- },
- {
- type: 'tool-completed',
- toolInvocationId: 'call_completed',
- toolName: 'completed',
- input: { data: 'test' },
- output: 'Completed result',
- },
- ],
- } as UIMessage
-
- const result = extractToolCallsFromUIMessage(message)
- expect(result).toHaveLength(1)
- expect(result?.[0].tool.function.name).toBe('completed')
- })
-
- it('should handle string input arguments', () => {
- const message: UIMessage = {
- id: 'msg-123',
- role: 'assistant',
- parts: [
- {
- type: 'tool-test',
- toolInvocationId: 'call_str',
- toolName: 'test',
- input: '{"key": "value"}',
- output: 'Result',
- },
- ],
- } as UIMessage
-
- const result = extractToolCallsFromUIMessage(message)
- expect(result).toHaveLength(1)
- expect(result?.[0].tool.function.arguments).toBe('{"key": "value"}')
- })
-})
diff --git a/web-app/src/lib/ai-model.ts b/web-app/src/lib/ai-model.ts
index d7a2e6840..ed52bb931 100644
--- a/web-app/src/lib/ai-model.ts
+++ b/web-app/src/lib/ai-model.ts
@@ -1,8 +1,5 @@
import { createOpenAICompatible } from '@ai-sdk/openai-compatible'
import type { LanguageModel } from 'ai'
-import { getServiceHub } from '@/hooks/useServiceHub'
-import { invoke } from '@tauri-apps/api/core'
-import { SessionInfo } from '@janhq/core'
/**
* Llama.cpp timings structure from the response
@@ -68,41 +65,27 @@ const llamaCppMetadataExtractor = {
* Creates a LanguageModel instance for the AI SDK based on the provider configuration.
* This allows using Jan's model providers with the AI SDK's useChat hook.
*
- * For local llamacpp models, this will start the model and get the actual
- * port and api_key from the running session.
+ * Note: This function is synchronous and does not load the model or construct URLs.
+ * URL construction should happen elsewhere after the model is ready.
*/
-export async function createLanguageModel(
+export function createLanguageModel(
modelId: string,
provider?: ModelProvider | null,
providerObject?: ProviderObject | null
-): Promise<LanguageModel> {
+): LanguageModel {
if (!provider) {
throw new Error('Provider configuration is required')
}
- const serviceHub = getServiceHub()
-
- // For llamacpp provider, we need to start the model and get the session info
+ // For llamacpp provider, create a placeholder configuration
+ // The actual URL and authentication will be updated later when the model is loaded
if (provider.provider === 'llamacpp' && providerObject) {
- // Start the model if not already running
- await serviceHub.models().startModel(providerObject, modelId)
-
- // Get session info which includes port and api_key
- const sessionInfo = await invoke<SessionInfo | null>(
- 'plugin:llamacpp|find_session_by_model',
- { modelId }
- )
-
- if (!sessionInfo) {
- throw new Error(`No running session found for model: ${modelId}`)
- }
-
- // Create provider with direct connection to llama.cpp server
+ // Create provider with placeholder connection info
const openAICompatible = createOpenAICompatible({
name: 'llamacpp',
- baseURL: `http://localhost:${sessionInfo.port}/v1`,
+ baseURL: 'http://localhost:1337/v1', // Placeholder - will be updated when model loads
headers: {
- Authorization: `Bearer ${sessionInfo.api_key}`,
+ Authorization: 'Bearer placeholder', // Placeholder - will be updated when model loads
Origin: 'tauri://localhost',
},
// Include usage data in streaming responses for token speed calculation
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index a4ef0b4a3..8b8c0b7f6 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -11,6 +11,70 @@ import {
type LanguageModelUsage,
jsonSchema,
} from 'ai'
+import { createOpenAICompatible } from '@ai-sdk/openai-compatible'
+import { invoke } from '@tauri-apps/api/core'
+import { SessionInfo } from '@janhq/core'
+import { useServiceStore } from '@/hooks/useServiceHub'
+
+/**
+ * Llama.cpp timings structure from the response
+ */
+interface LlamaCppTimings {
+ prompt_n?: number
+ predicted_n?: number
+ predicted_per_second?: number
+ prompt_per_second?: number
+}
+
+interface LlamaCppChunk {
+ timings?: LlamaCppTimings
+}
+
+/**
+ * Custom metadata extractor for llama.cpp that extracts timing information
+ * and converts it to token usage format
+ */
+const llamaCppMetadataExtractor = {
+ extractMetadata: async ({ parsedBody }: { parsedBody: unknown }) => {
+ const body = parsedBody as LlamaCppChunk
+ if (body?.timings) {
+ return {
+ llamacpp: {
+ promptTokens: body.timings.prompt_n ?? null,
+ completionTokens: body.timings.predicted_n ?? null,
+ tokensPerSecond: body.timings.predicted_per_second ?? null,
+ promptPerSecond: body.timings.prompt_per_second ?? null,
+ },
+ }
+ }
+ return undefined
+ },
+ createStreamExtractor: () => {
+ let lastTimings: LlamaCppTimings | undefined
+
+ return {
+ processChunk: (parsedChunk: unknown) => {
+ const chunk = parsedChunk as LlamaCppChunk
+ if (chunk?.timings) {
+ lastTimings = chunk.timings
+ }
+ },
+ buildMetadata: () => {
+ if (lastTimings) {
+ return {
+ llamacpp: {
+ promptTokens: lastTimings.prompt_n ?? null,
+ completionTokens: lastTimings.predicted_n ?? null,
+ tokensPerSecond: lastTimings.predicted_per_second ?? null,
+ promptPerSecond: lastTimings.prompt_per_second ?? null,
+ },
+ }
+ }
+ return undefined
+ },
+ }
+ },
+}
export type TokenUsageCallback = (
usage: LanguageModelUsage,
@@ -38,6 +102,9 @@ export type ServiceHub = {
Array<{ name: string; description: string; inputSchema: unknown }>
>
}
+ models(): {
+ startModel(provider: ProviderObject, model: string): Promise<unknown>
+ }
}
// import { mcpService } from "@/services/mcp-service";
@@ -171,21 +238,30 @@ function filterBase64FromMessages(messages: CoreMessage[]): CoreMessage[] {
}
export class CustomChatTransport implements ChatTransport<UIMessage> {
- public model: LanguageModel
+ public model: LanguageModel | null
private tools: Record<string, Tool> = {}
private onTokenUsage?: TokenUsageCallback
private onStreamingTokenSpeed?: StreamingTokenSpeedCallback
- private serviceHub?: ServiceHub
private hasDocuments = false
private modelSupportsTools = false
private ragFeatureAvailable = false
-
- constructor(model: LanguageModel, serviceHub?: ServiceHub) {
- this.model = model
- this.serviceHub = serviceHub
-
+ private systemMessage?: string
+ private modelId?: string
+ private provider?: ProviderObject
+ private serviceHub: ServiceHub | null
+
+ constructor(
+ modelId: string | undefined,
+ provider: ProviderObject | undefined,
+ systemMessage?: string
+ ) {
+ this.model = null
+ this.modelId = modelId
+ this.provider = provider
+ this.systemMessage = systemMessage
+ this.serviceHub = useServiceStore.getState().serviceHub
// Initialize tools asynchronously if serviceHub is provided
- if (serviceHub) {
+ if (this.serviceHub) {
// Fire and forget - load MCP tools in the background
this.loadMCPTools().catch((error) => {
console.warn('Failed to load MCP tools during initialization:', error)
@@ -218,8 +294,15 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
}
}
- updateModel(model: LanguageModel) {
- this.model = model
+ updateModelMetadata(modelId: string, provider: ProviderObject) {
+ this.modelId = modelId
+ this.provider = provider
+ // Reset model so it gets recreated with new metadata on next sendMessages
+ this.model = null
+ }
+
+ updateSystemMessage(systemMessage: string | undefined) {
+ this.systemMessage = systemMessage
}
setOnStreamingTokenSpeed(callback: StreamingTokenSpeedCallback | undefined) {
@@ -263,7 +346,11 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
const toolsRecord: Record<string, Tool> = {}
// Load RAG tools if documents are available and model supports tools
- if (this.hasDocuments && this.ragFeatureAvailable && this.modelSupportsTools) {
+ if (
+ this.hasDocuments &&
+ this.ragFeatureAvailable &&
+ this.modelSupportsTools
+ ) {
try {
const ragTools = await this.serviceHub.rag().getTools()
if (Array.isArray(ragTools) && ragTools.length > 0) {
@@ -321,6 +408,78 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
messageId: string | undefined
} & ChatRequestOptions
): Promise<ReadableStream<UIMessageChunk>> {
+ // Initialize model if not already initialized
+ if (this.serviceHub && this.modelId && this.provider) {
+ try {
+ // Start the model (this will be a no-op for remote providers)
+ await this.serviceHub.models().startModel(this.provider, this.modelId)
+
+ // For llamacpp provider, get session info and recreate the model with actual URL and API key
+ if (this.provider.provider === 'llamacpp') {
+ // Get session info which includes port and api_key
+ const sessionInfo = await invoke<SessionInfo | null>(
+ 'plugin:llamacpp|find_session_by_model',
+ { modelId: this.modelId }
+ )
+
+ if (!sessionInfo) {
+ throw new Error(
+ `No running session found for model: ${this.modelId}`
+ )
+ }
+
+ // Recreate the model with actual connection info
+ const openAICompatible = createOpenAICompatible({
+ name: 'llamacpp',
+ baseURL: `http://localhost:${sessionInfo.port}/v1`,
+ headers: {
+ Authorization: `Bearer ${sessionInfo.api_key}`,
+ Origin: 'tauri://localhost',
+ },
+ includeUsage: true,
+ })
+
+ // Update the model with the new instance that has correct URL and API key
+ this.model = openAICompatible.languageModel(this.modelId, {
+ metadataExtractor: llamaCppMetadataExtractor,
+ })
+ } else {
+ // For all other providers (OpenAI, Azure, Anthropic, etc.)
+ // Create OpenAI-compatible model with provider's base_url and api_key
+ const headers: Record<string, string> = {}
+
+ // Add custom headers if specified
+ if (this.provider.custom_header) {
+ this.provider.custom_header.forEach((customHeader) => {
+ headers[customHeader.header] = customHeader.value
+ })
+ }
+
+ // Add authorization header if api_key is present
+ if (this.provider.api_key) {
+ headers['Authorization'] = `Bearer ${this.provider.api_key}`
+ }
+
+ const openAICompatible = createOpenAICompatible({
+ name: this.provider.provider,
+ baseURL: this.provider.base_url || 'https://api.openai.com/v1',
+ headers,
+ includeUsage: true,
+ })
+
+ // Create the model instance
+ this.model = openAICompatible.languageModel(this.modelId)
+ }
+ } catch (error) {
+ console.error('Failed to start model:', error)
+ throw new Error(
+ `Failed to start model: ${error instanceof Error ? error.message : String(error)}`
+ )
+ }
+ } else {
+ throw new Error('ServiceHub not initialized or model/provider missing.')
+ }
+
// Convert UI messages to model messages
const modelMessages = convertToModelMessages(options.messages)
@@ -346,6 +505,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
experimental_download: passUrlsDirectly,
tools: hasTools ? this.tools : undefined,
toolChoice: 'auto',
+ system: this.systemMessage,
})
return result.toUIMessageStream({
diff --git a/web-app/src/lib/messages.ts b/web-app/src/lib/messages.ts
index 8588adf86..1586206e1 100644
--- a/web-app/src/lib/messages.ts
+++ b/web-app/src/lib/messages.ts
@@ -436,31 +436,35 @@ export const parseReasoning = (text: string) => {
/**
* Convert Jan's ThreadMessage format to AI SDK UIMessage format.
* This is used to load existing messages into the AI SDK chat.
+ * Tool calls are now part of the content array and will be converted to tool parts.
*/
export function convertThreadMessageToUIMessage(
threadMessage: ThreadMessage
): UIMessage {
- const reasoningParts: any[] = []
- const toolParts: any[] = []
- const textParts: any[] = []
- const otherParts: any[] = []
+ const parts: any[] = []
- // Process content array
+ // Process content array - preserve original order (including tool calls)
for (const content of threadMessage.content || []) {
- if (content.type === ContentType.Text && content.text?.value) {
- // Check for reasoning content wrapped in <think> tags
+ if (content.type === 'reasoning' && content.text?.value) {
+ // Reasoning content - direct conversion
+ parts.push({
+ type: 'reasoning',
+ text: content.text.value,
+ })
+ } else if (content.type === 'text' && content.text?.value) {
+ // Text content - check if it contains old-format reasoning in <think> tags
const { reasoningSegment, textSegment } = parseReasoning(
content.text.value
)
+ // BACKWARD COMPATIBILITY: Handle old format with <think> tags
if (reasoningSegment) {
// Extract reasoning text from <think> tags
- // Handle both completed (<think>...</think>) and in-progress (<think>...) formats
const completedMatch = reasoningSegment.match(
/<think>([\s\S]*)<\/think>/
)
if (completedMatch) {
- reasoningParts.push({
+ parts.push({
type: 'reasoning',
text: completedMatch[1],
})
@@ -468,7 +472,7 @@ export function convertThreadMessageToUIMessage(
// In-progress reasoning - extract content after <think> tag
const inProgressMatch = reasoningSegment.match(/<think>([\s\S]*)/)
if (inProgressMatch) {
- reasoningParts.push({
+ parts.push({
type: 'reasoning',
text: inProgressMatch[1],
})
@@ -480,22 +484,39 @@ export function convertThreadMessageToUIMessage(
// Trim leading whitespace/newlines from the text segment
const trimmedText = textSegment.trim()
if (trimmedText) {
- textParts.push({
+ parts.push({
type: 'text',
text: trimmedText,
})
}
+ } else if (!reasoningSegment) {
+ // No reasoning segment, just add the text as-is
+ parts.push({
+ type: 'text',
+ text: content.text.value,
+ })
}
- } else if (content.type === ContentType.Image && content.image_url?.url) {
- otherParts.push({
+ } else if (content.type === 'image_url' && content.image_url?.url) {
+ parts.push({
type: 'file',
mediaType: 'image/jpeg',
url: content.image_url.url,
})
+ } else if (content.type === 'tool_call') {
+ // Handle tool call content items - direct conversion from flat structure
+ parts.push({
+ type: `tool-${content.tool_name}`,
+ toolInvocationId: content.tool_call_id,
+ toolName: content.tool_name,
+ input: content.input,
+ state: content.output ? 'result' : 'call',
+ output: content.output,
+ })
}
}
- // Handle tool calls from metadata
+ // BACKWARD COMPATIBILITY: Handle tool calls from metadata (old format)
+ // New messages will have tool calls as separate messages with tool_call_id
const toolCalls = (threadMessage.metadata as any)?.tool_calls
if (Array.isArray(toolCalls)) {
for (const tc of toolCalls) {
@@ -513,7 +534,7 @@ export function convertThreadMessageToUIMessage(
}
const toolName = tc.tool?.function?.name || tc.name
- toolParts.push({
+ parts.push({
type: `tool-${toolName}`,
toolInvocationId: tc.tool?.id || tc.id,
toolName: toolName,
@@ -527,9 +548,6 @@ export function convertThreadMessageToUIMessage(
}
}
- // Combine parts in the correct order: reasoning -> tool calls -> text -> other
- const parts = [...reasoningParts, ...toolParts, ...textParts, ...otherParts]
-
// Ensure at least one text part exists
if (parts.length === 0) {
parts.push({
@@ -548,104 +566,93 @@ export function convertThreadMessageToUIMessage(
/**
* Convert an array of Jan's ThreadMessages to AI SDK UIMessage format.
+ * Tool calls are now part of the content array, so no special merging is needed.
*/
export function convertThreadMessagesToUIMessages(
threadMessages: ThreadMessage[]
): UIMessage[] {
- return threadMessages.map(convertThreadMessageToUIMessage)
+ return threadMessages
+ .map(convertThreadMessageToUIMessage)
+ .filter((msg): msg is UIMessage => msg !== null)
}
/**
- * Extract combined content from UIMessage parts, including reasoning and text.
- * Reasoning content is wrapped in <think> tags.
+ * Extract content from UIMessage parts as separate ThreadContent items.
+ * This preserves the structure of multiple text/reasoning/tool call parts instead of combining them.
*
* @param message - The UIMessage to extract content from
- * @returns Combined content string with reasoning in <think> tags followed by text
+ * @returns Array of ThreadContent items (including tool calls)
*/
-export function extractCombinedContentFromUIMessage(message: UIMessage): string {
- let combinedContent = ''
-
+export function extractContentPartsFromUIMessage(message: UIMessage): ThreadContent[] {
+ const content: ThreadContent[] = []
const parts = (message.parts ?? []) as any[]
- // First, extract reasoning parts and wrap in <think> tags
- const reasoningParts = parts.filter((part) => part.type === 'reasoning')
- if (reasoningParts.length > 0) {
- const reasoningText = reasoningParts
- .map((part) => part.reasoning ?? part.text ?? '')
- .join('')
- if (reasoningText) {
- combinedContent = `<think>${reasoningText}</think>`
+ for (const part of parts) {
+ if (part.type === 'reasoning') {
+ // Add reasoning content as separate item
+ const reasoningText = part.reasoning ?? part.text ?? ''
+ if (reasoningText) {
+ const reasoningContent = {
+ type: 'reasoning' as ContentType.Reasoning,
+ text: {
+ value: reasoningText,
+ annotations: [],
+ },
+ }
+ content.push(reasoningContent)
+ }
+ } else if (part.type === 'text') {
+ // Add text content as separate item
+ const textContent = part.text ?? ''
+ if (textContent) {
+ content.push({
+ type: 'text' as ContentType.Text,
+ text: {
+ value: textContent,
+ annotations: [],
+ },
+ })
+ }
+ } else if (part.type === 'file' && part.mediaType) {
+ // Handle file parts (images)
+ const mediaType = part.mediaType as string
+ if (mediaType?.startsWith('image/')) {
+ content.push({
+ type: 'image_url' as ContentType.Image,
+ image_url: {
+ url: part.url,
+ detail: 'auto',
+ },
+ })
+ }
+ } else if (part.type.startsWith('tool-')) {
+ // Handle tool call parts - flatten structure to match parts format
+ const toolName = (part.type as string).replace('tool-', '')
+ const toolCallId = part.toolInvocationId || part.toolCallId
+ const input = part.input || part.args
+ const output = part.output || part.result
+
+ const toolCallContent = {
+ type: 'tool_call' as ContentType.ToolCall,
+ tool_call_id: toolCallId,
+ tool_name: toolName,
+ input: input,
+ output: output,
+ }
+ content.push(toolCallContent)
}
}
- // Then, extract text parts
- const textParts = parts.filter((part) => part.type === 'text')
- if (textParts.length > 0) {
- const textContent = textParts.map((part) => part.text).join('')
- combinedContent += textContent
- }
-
- return combinedContent
-}
-
-/**
- * Extract and normalize tool calls from UIMessage parts for persistence.
- * Converts AI SDK tool invocation format to Jan's thread message metadata format.
- *
- * @param message - The UIMessage to extract tool calls from
- * @returns Array of tool calls in persistence format, or undefined if none exist
- */
-export function extractToolCallsFromUIMessage(message: UIMessage) {
- const parts = (message.parts ?? []) as any[]
-
- // Filter tool invocation parts that have output or result
- const toolInvocations = parts.filter(
- (part) => part.type.startsWith('tool-') && (part.output || part.result)
- )
-
- if (toolInvocations.length === 0) {
- return undefined
+ // If no content was extracted, add empty text
+ if (content.length === 0) {
+ content.push({
+ type: 'text' as ContentType.Text,
+ text: {
+ value: '',
+ annotations: [],
+ },
+ })
}
- return toolInvocations.map((part) => {
- // Parse result content properly
- let contentArray
- const resultData = part.output || part.result
-
- if (resultData) {
- if (typeof resultData === 'string') {
- // If result is a string, wrap it in the content array format
- contentArray = [{ type: 'text', text: resultData }]
- } else if (Array.isArray(resultData)) {
- // If result is already an array, use it directly
- contentArray = resultData
- } else if (resultData.content) {
- // If result has a content property, use that
- contentArray = resultData.content
- } else {
- // Fallback: stringify the result
- contentArray = [{ type: 'text', text: JSON.stringify(resultData) }]
- }
- }
-
- const argsData = part.input || part.args
-
- return {
- tool: {
- id: part.toolInvocationId || part.toolCallId,
- type: 'function' as const,
- function: {
- name: (part.type as string).replace('tool-', ''),
- arguments:
- typeof argsData === 'string' ? argsData : JSON.stringify(argsData),
- },
- },
- response: contentArray
- ? {
- content: contentArray,
- }
- : undefined,
- state: 'ready',
- }
- })
+ return content
}
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 13f9bc683..28b9129cf 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -20,8 +20,8 @@ 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 { createLanguageModel } from '@/lib/ai-model'
import { useModelProvider } from '@/hooks/useModelProvider'
+import { renderInstructions } from '@/lib/instructionTemplate'
import {
Conversation,
ConversationContent,
@@ -33,13 +33,10 @@ import type { UIMessage } from '@ai-sdk/react'
import { useChatSessions } from '@/stores/chat-session-store'
import {
convertThreadMessagesToUIMessages,
- extractCombinedContentFromUIMessage,
- extractToolCallsFromUIMessage,
+ extractContentPartsFromUIMessage,
} from '@/lib/messages'
-import {
- newUserThreadContent,
- newAssistantThreadContent,
-} from '@/lib/completion'
+import { newUserThreadContent } from '@/lib/completion'
+import { ThreadMessage, MessageStatus, ChatCompletionRole } from '@janhq/core'
import { createImageAttachment } from '@/types/attachment'
import {
useChatAttachments,
@@ -67,6 +64,7 @@ function ThreadDetail() {
const assistants = useAssistant((state) => state.assistants)
const setMessages = useMessages((state) => state.setMessages)
const addMessage = useMessages((state) => state.addMessage)
+ const updateMessage = useMessages((state) => state.updateMessage)
const deleteMessage = useMessages((state) => state.deleteMessage)
const currentThread = useRef<string | undefined>(undefined)
@@ -112,12 +110,13 @@ function ThreadDetail() {
const getProviderByName = useModelProvider((state) => state.getProviderByName)
const providers = useModelProvider((state) => state.providers)
- // Get language model from appState
- const languageModel = useAppState((state) => state.languageModel)
+ // Store model metadata in appState for the chat transport
const setLanguageModel = useAppState((state) => state.setLanguageModel)
+ const languageModelId = useAppState((state) => state.languageModelId)
+ const languageModelProvider = useAppState((state) => state.languageModelProvider)
useEffect(() => {
- // Wait for providers to be loaded before attempting to create language model
+ // Wait for providers to be loaded before attempting to set model metadata
if (providers.length === 0) {
return
}
@@ -125,35 +124,26 @@ function ThreadDetail() {
const provider = getProviderByName(selectedProvider)
const modelId = selectedModel?.id ?? thread?.model?.id ?? ''
if (!modelId || !provider) {
- setLanguageModel(null)
+ setLanguageModel(null, undefined, undefined)
return
}
- let cancelled = false
- createLanguageModel(modelId, provider, provider)
- .then((model) => {
- if (!cancelled) {
- setLanguageModel(model)
- }
- })
- .catch((error) => {
- console.error('Failed to create language model:', error)
- if (!cancelled) {
- setLanguageModel(null)
- }
- })
-
- return () => {
- cancelled = true
- }
+ // Store model metadata (no need to create LanguageModel here)
+ setLanguageModel(null, modelId, provider)
}, [
selectedModel?.id,
thread?.model?.id,
selectedProvider,
getProviderByName,
providers.length,
+ setLanguageModel,
])
+ // Get system message from current assistant's instructions
+ const systemMessage = currentAssistant?.instructions
+ ? renderInstructions(currentAssistant.instructions)
+ : undefined
+
// Use the AI SDK chat hook
const {
messages: chatMessages,
@@ -164,27 +154,44 @@ function ThreadDetail() {
stop,
addToolOutput,
updateRagToolsAvailability,
- } = useChat(languageModel, {
+ } = useChat({
sessionId: threadId,
sessionTitle: thread?.title,
+ systemMessage,
experimental_throttle: 50,
onFinish: ({ message, isAbort }) => {
// Persist assistant message to backend (skip if aborted)
if (!isAbort && message.role === 'assistant') {
- const combinedContent = extractCombinedContentFromUIMessage(message)
-
- if (combinedContent) {
- // Extract tool calls from UIMessage parts to preserve them
- const toolCalls = extractToolCallsFromUIMessage(message)
- const metadata = toolCalls ? { tool_calls: toolCalls } : {}
+ // Extract content parts (including tool calls) as separate items in the content array
+ // This preserves the natural ordering: text -> tool call -> text -> tool call, etc.
+ const contentParts = extractContentPartsFromUIMessage(message)
+
+ if (contentParts.length > 0) {
+ // Create assistant message with content parts (including tool calls)
+ const assistantMessage: ThreadMessage = {
+ type: 'text',
+ role: ChatCompletionRole.Assistant,
+ content: contentParts,
+ id: message.id,
+ object: 'thread.message',
+ thread_id: threadId,
+ status: MessageStatus.Ready,
+ created_at: Date.now(),
+ completed_at: Date.now(),
+ metadata: {},
+ }
- const assistantMessage = newAssistantThreadContent(
- threadId,
- combinedContent,
- metadata,
- message.id
+ // Check if message with this ID already exists (onFinish can be called multiple times)
+ const existingMessages = useMessages.getState().getMessages(threadId)
+ const existingMessage = existingMessages.find(
+ (m) => m.id === message.id
)
- addMessage(assistantMessage)
+
+ if (existingMessage) {
+ updateMessage(assistantMessage)
+ } else {
+ addMessage(assistantMessage)
+ }
}
}
@@ -271,7 +278,6 @@ function ThreadDetail() {
sessionData.tools.push(toolCall)
},
sendAutomaticallyWhen: followUpMessage,
- serviceHub,
})
// Update RAG tools availability when documents or model changes
@@ -382,7 +388,7 @@ function ThreadDetail() {
useEffect(() => {
// Prevent duplicate sends
if (initialMessageSentRef.current) return
- if (!languageModel) return
+ if (!languageModelId || !languageModelProvider) return
const initialMessageKey = `${SESSION_STORAGE_PREFIX.INITIAL_MESSAGE}${threadId}`
@@ -486,7 +492,8 @@ function ThreadDetail() {
}
}, [
threadId,
- languageModel,
+ languageModelId,
+ languageModelProvider,
sendMessage,
addMessage,
getAttachments,
@@ -502,7 +509,7 @@ function ThreadDetail() {
text: string,
files?: Array<{ type: string; mediaType: string; url: string }>
) => {
- if (!languageModel) return
+ if (!languageModelId || !languageModelProvider) return
// Get all attachments from the store (includes both images and documents)
const allAttachments = getAttachments(attachmentsKey)
@@ -584,7 +591,8 @@ function ThreadDetail() {
clearAttachmentsForThread(attachmentsKey)
},
[
- languageModel,
+ languageModelId,
+ languageModelProvider,
sendMessage,
threadId,
addMessage,
@@ -600,7 +608,7 @@ function ThreadDetail() {
// - For user messages: keeps the user message, deletes all after, regenerates assistant response
// - For assistant messages: finds the closest preceding user message, deletes from there
const handleRegenerate = (messageId?: string) => {
- if (!languageModel) {
+ if (!languageModelId || !languageModelProvider) {
console.warn('No language model available')
return
}
@@ -675,10 +683,10 @@ function ThreadDetail() {
{chatMessages.map((message, index) => {
const isLastMessage = index === chatMessages.length - 1
const isFirstMessage = index === 0
- const showAssistant =
- message.role === 'assistant' &&
- (isFirstMessage ||
- chatMessages[index - 1]?.role !== 'assistant')
+ // const showAssistant =
+ // message.role === 'assistant' &&
+ // (isFirstMessage ||
+ // chatMessages[index - 1]?.role !== 'assistant')
return (
<MessageItem
@@ -689,15 +697,15 @@ function ThreadDetail() {
status={status}
reasoningContainerRef={reasoningContainerRef}
onRegenerate={handleRegenerate}
- showAssistant={showAssistant}
- assistant={
- currentAssistant
- ? {
- avatar: currentAssistant.avatar,
- name: currentAssistant.name,
- }
- : undefined
- }
+ // showAssistant={showAssistant}
+ // assistant={
+ // currentAssistant
+ // ? {
+ // avatar: currentAssistant.avatar,
+ // name: currentAssistant.name,
+ // }
+ // : undefined
+ // }
/>
)
})}
diff --git a/web-app/src/ui/drawer.tsx b/web-app/src/ui/drawer.tsx
index 69333162f..4000a1ba1 100644
--- a/web-app/src/ui/drawer.tsx
+++ b/web-app/src/ui/drawer.tsx
@@ -1,5 +1,3 @@
-"use client";
-
import * as React from "react";
import { Drawer as DrawerPrimitive } from "vaul";
diff --git a/web-app/src/ui/input-group.tsx b/web-app/src/ui/input-group.tsx
index b0cb6c460..203766201 100644
--- a/web-app/src/ui/input-group.tsx
+++ b/web-app/src/ui/input-group.tsx
@@ -1,5 +1,3 @@
-"use client";
-
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
diff --git a/web-app/src/ui/select.tsx b/web-app/src/ui/select.tsx
index 6426d6ade..09b1179c2 100644
--- a/web-app/src/ui/select.tsx
+++ b/web-app/src/ui/select.tsx
@@ -1,5 +1,3 @@
-"use client";
-
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";