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: file upload, thread persistence, simplify use chat

Louisa1d069cc1991
diff --git a/extensions/rag-extension/src/index.ts b/extensions/rag-extension/src/index.ts
index 83ff170c3..3307d973a 100644
--- a/extensions/rag-extension/src/index.ts
+++ b/extensions/rag-extension/src/index.ts
@@ -71,7 +71,7 @@ export default class RagExtension extends RAGExtension {
)
}
- async checkANNAvailability(): Promise<boolean> {
+ async checkANNAvailability() {
try {
const vec = window.core?.extensionManager.get(
ExtensionTypeEnum.VectorDB
@@ -308,7 +308,7 @@ export default class RagExtension extends RAGExtension {
content: [{ type: 'text', text: JSON.stringify(payload) }],
}
} catch (e) {
- const msg = e instanceof Error ? e.message : String(e)
+ const msg = e instanceof Error ? e.message : JSON.stringify(e)
return {
error: msg,
content: [{ type: 'text', text: `Get chunks failed: ${msg}` }],
diff --git a/web-app/src/ai-elements/tool.tsx b/web-app/src/ai-elements/tool.tsx
index 0b5d07d9a..2a55526e0 100644
--- a/web-app/src/ai-elements/tool.tsx
+++ b/web-app/src/ai-elements/tool.tsx
@@ -81,6 +81,7 @@ export const Tool = memo(
export type ToolHeaderProps = {
title?: string
+ state: ToolUIPart['state']
type: ToolUIPart['type']
className?: string
}
@@ -100,8 +101,8 @@ const getStatusText = (status: ToolUIPart['state'], toolName: string) => {
}
export const ToolHeader = memo(
- ({ className, title, type }: ToolHeaderProps) => {
- const { isOpen, state } = useTool()
+ ({ className, title, state, type }: ToolHeaderProps) => {
+ const { isOpen } = useTool()
const toolName = title ?? type.split('-').slice(1).join('-')
return (
@@ -155,7 +156,7 @@ export const ToolInput = memo(
Parameters
</h4>
<div className="rounded-md max-h-40 overflow-auto rounded-md border border-main-view-fg/10 ">
- <CodeBlock code={input} language="json" />
+ <CodeBlock code={JSON.stringify(input, null, 2)} language="json" />
</div>
</div>
)
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index ec6632789..0e61eaf63 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -19,8 +19,10 @@ import {
import { CopyButton } from './CopyButton'
import { AvatarEmoji } from '@/containers/AvatarEmoji'
import { useModelProvider } from '@/hooks/useModelProvider'
-import { IconRefresh } from '@tabler/icons-react'
+import { IconRefresh, IconPaperclip } from '@tabler/icons-react'
import TokenSpeedIndicator from '@/containers/TokenSpeedIndicator'
+import { extractFilesFromPrompt, FileMetadata } from '@/lib/fileMetadata'
+import { useMemo } from 'react'
const CHAT_STATUS = {
STREAMING: 'streaming',
@@ -33,11 +35,6 @@ const CONTENT_TYPE = {
REASONING: 'reasoning',
} as const
-const TOOL_STATE = {
- OUTPUT_AVAILABLE: 'output-available',
- OUTPUT_ERROR: 'output-error',
-} as const
-
export type MessageItemProps = {
message: UIMessage
isFirstMessage: boolean
@@ -71,6 +68,21 @@ export const MessageItem = memo(
const isStreaming = isLastMessage && status === CHAT_STATUS.STREAMING
+ // Extract file metadata from message text (for user messages with attachments)
+ const attachedFiles = useMemo(() => {
+ if (message.role !== 'user') return []
+
+ const textParts = message.parts.filter(
+ (part): part is { type: 'text'; text: string } =>
+ part.type === CONTENT_TYPE.TEXT
+ )
+
+ if (textParts.length === 0) return []
+
+ const { files } = extractFilesFromPrompt(textParts[0].text)
+ return files
+ }, [message.parts, message.role])
+
// Get full text content for copy button
const getFullTextContent = useCallback(() => {
return message.parts
@@ -92,14 +104,52 @@ export const MessageItem = memo(
const isLastPart = partIndex === message.parts.length - 1
+ // For user messages, extract and clean the text from file metadata
+ const displayText =
+ message.role === 'user'
+ ? extractFilesFromPrompt(part.text).cleanPrompt
+ : part.text
+
+ if (
+ !displayText.trim() &&
+ message.role === 'user' &&
+ attachedFiles.length === 0
+ ) {
+ return null
+ }
+
return (
<div key={`${message.id}-${partIndex}`} className="w-full">
{message.role === 'user' ? (
<div className="flex justify-end w-full h-full text-start break-words whitespace-normal">
<div className="bg-main-view-fg/4 relative text-main-view-fg p-2 rounded-md inline-block max-w-[80%]">
- <div className="select-text whitespace-pre-wrap">
- {part.text}
- </div>
+ {/* Show attached files if any */}
+ {attachedFiles.length > 0 && (
+ <div className="flex flex-wrap gap-2 mb-2">
+ {attachedFiles.map((file: FileMetadata, idx: number) => (
+ <div
+ key={`file-${idx}-${file.id}`}
+ className="flex items-center gap-1.5 px-2 py-1 rounded-md bg-main-view-fg/10 text-xs"
+ >
+ <IconPaperclip
+ size={14}
+ className="text-main-view-fg/50"
+ />
+ <span className="font-medium">{file.name}</span>
+ {file.injectionMode && (
+ <span className="text-main-view-fg/50">
+ ({file.injectionMode})
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ {displayText && (
+ <div className="select-text whitespace-pre-wrap">
+ {displayText}
+ </div>
+ )}
</div>
</div>
) : (
@@ -202,40 +252,40 @@ export const MessageItem = memo(
}
const renderToolPart = (part: any, partIndex: number) => {
- if (part.type !== 'tool-invocation') {
+ if (!part.type.startsWith('tool-') || !('state' in part)) {
return null
}
- const toolName = part.toolName || 'Unknown Tool'
- const state =
- part.state === 'result'
- ? TOOL_STATE.OUTPUT_AVAILABLE
- : part.state === 'error'
- ? TOOL_STATE.OUTPUT_ERROR
- : 'input-available'
-
+ const toolName = part.type.split('-').slice(1).join('-')
return (
- <Tool key={`${message.id}-${partIndex}`} state={state} className="mb-4">
+ <Tool
+ key={`${message.id}-${partIndex}`}
+ state={part.state}
+ className="mb-4"
+ >
<ToolHeader
title={toolName}
type={`tool-${toolName}` as `tool-${string}`}
+ state={part.state}
/>
<ToolContent title={toolName}>
- <ToolInput
- input={
- typeof part.args === 'string'
- ? part.args
- : JSON.stringify(part.args)
- }
- />
- {part.state === 'result' && part.result && (
+ {part.input && (
+ <ToolInput
+ input={
+ typeof part.input === 'string'
+ ? part.input
+ : JSON.stringify(part.input)
+ }
+ />
+ )}
+ {part.output && (
<ToolOutput
- output={part.result}
+ output={part.output}
resolver={(input) => Promise.resolve(input)}
errorText={undefined}
/>
)}
- {part.state === 'error' && (
+ {part.state === 'output-error' && (
<ToolOutput
output={undefined}
errorText={part.error || 'Tool execution failed'}
@@ -296,7 +346,7 @@ export const MessageItem = memo(
<div className="flex items-center justify-end gap-2 text-main-view-fg/60 text-xs mt-2">
<CopyButton text={getFullTextContent()} />
- {selectedModel && onRegenerate && (
+ {selectedModel && onRegenerate && status !== CHAT_STATUS.STREAMING && (
<button
className="flex items-center gap-1 hover:text-accent transition-colors cursor-pointer group relative"
onClick={handleRegenerate}
@@ -309,30 +359,37 @@ export const MessageItem = memo(
)}
{/* Message actions for assistant messages (non-tool) */}
- {message.role === 'assistant' && !hasToolCalls && (
- <div className="flex items-center gap-2 text-main-view-fg/60 text-xs">
- <div
- className={cn('flex items-center gap-2', isStreaming && 'hidden')}
- >
- <CopyButton text={getFullTextContent()} />
-
- {selectedModel && onRegenerate && !isStreaming && (
- <button
- className="flex items-center gap-1 hover:text-accent transition-colors cursor-pointer group relative"
- onClick={handleRegenerate}
- title="Regenerate from this message"
- >
- <IconRefresh size={16} />
- </button>
- )}
- </div>
+ {message.role === 'assistant' &&
+ !hasToolCalls &&
+ message.parts.some((p) => p.type === 'text') && (
+ <div className="flex items-center gap-2 text-main-view-fg/60 text-xs">
+ <div
+ className={cn(
+ 'flex items-center gap-2',
+ isStreaming && 'hidden'
+ )}
+ >
+ <CopyButton text={getFullTextContent()} />
- <TokenSpeedIndicator
- streaming={isStreaming}
- metadata={message.metadata as Record<string, unknown> | undefined}
- />
- </div>
- )}
+ {selectedModel && onRegenerate && !isStreaming && (
+ <button
+ className="flex items-center gap-1 hover:text-accent transition-colors cursor-pointer group relative"
+ onClick={handleRegenerate}
+ title="Regenerate from this message"
+ >
+ <IconRefresh size={16} />
+ </button>
+ )}
+ </div>
+
+ <TokenSpeedIndicator
+ streaming={isStreaming}
+ metadata={
+ message.metadata as Record<string, unknown> | undefined
+ }
+ />
+ </div>
+ )}
{/* Image Preview Dialog */}
{previewImage && (
diff --git a/web-app/src/hooks/use-chat.ts b/web-app/src/hooks/use-chat.ts
index 78588953c..624360986 100644
--- a/web-app/src/hooks/use-chat.ts
+++ b/web-app/src/hooks/use-chat.ts
@@ -1,159 +1,162 @@
-import { CustomChatTransport } from "@/lib/custom-chat-transport";
+import {
+ CustomChatTransport,
+ type ServiceHub,
+} from '@/lib/custom-chat-transport'
// import { useCapabilities } from "@/stores/capabilities-store";
import {
Chat,
type UIMessage,
type UseChatOptions,
useChat as useChatSDK,
-} from "@ai-sdk/react";
+} from '@ai-sdk/react'
import {
type ChatInit,
type LanguageModel,
type LanguageModelUsage,
- type UIDataTypes,
- type UITools,
-} from "ai";
-import { useEffect, useMemo, useRef, useCallback } from "react";
-import { useChatSessions } from "@/stores/chat-session-store";
-import { useAppState } from "@/hooks/useAppState";
-
-// Tool call type from AI SDK
-type ToolCall = {
- toolCallId: string;
- toolName: string;
- input: unknown;
-};
-
-type CustomChatOptions = Omit<ChatInit<UIMessage>, "transport"> &
- Pick<UseChatOptions<UIMessage>, "experimental_throttle" | "resume"> & {
- sessionId?: string;
- sessionTitle?: string;
+} from 'ai'
+import { useEffect, useMemo, useRef, useCallback } from 'react'
+import { useChatSessions } from '@/stores/chat-session-store'
+import { useAppState } from '@/hooks/useAppState'
+
+type CustomChatOptions = Omit<ChatInit<UIMessage>, 'transport'> &
+ Pick<UseChatOptions<UIMessage>, 'experimental_throttle' | 'resume'> & {
+ sessionId?: string
+ sessionTitle?: string
+ serviceHub?: ServiceHub
onTokenUsage?: (usage: LanguageModelUsage, messageId: string) => void;
- onFinish?: (params: { message: UIMessage; isAbort?: boolean }) => void;
- onToolCall?: (params: { toolCall: ToolCall }) => void;
- sendAutomaticallyWhen?: (params: {
- messages: UIMessage<unknown, UIDataTypes, UITools>[];
- }) => boolean;
- };
+ }
// This is a wrapper around the AI SDK's useChat hook
// 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
+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,
- experimental_throttle,
+ serviceHub,
onTokenUsage,
- onFinish,
- onToolCall,
- sendAutomaticallyWhen,
...chatInitOptions
- } = options ?? {};
- const ensureSession = useChatSessions((state) => state.ensureSession);
- const setSessionTitle = useChatSessions((state) => state.setSessionTitle);
- const updateStatus = useChatSessions((state) => state.updateStatus);
+ } = options ?? {}
+ const ensureSession = useChatSessions((state) => state.ensureSession)
+ const setSessionTitle = useChatSessions((state) => state.setSessionTitle)
+ const updateStatus = useChatSessions((state) => state.updateStatus)
const existingSessionTransport = sessionId
? useChatSessions.getState().sessions[sessionId]?.transport
- : undefined;
+ : undefined
// Only create transport when model is available
if (model && transportRef.current?.model !== model) {
transportRef.current =
- existingSessionTransport ??
- new CustomChatTransport(
- model,
- );
+ existingSessionTransport ?? new CustomChatTransport(model, serviceHub)
} else if (
existingSessionTransport &&
transportRef.current !== existingSessionTransport
) {
- transportRef.current = existingSessionTransport;
+ transportRef.current = existingSessionTransport
}
useEffect(() => {
if (model && transportRef.current?.model !== model) {
- transportRef.current!.updateModel(model);
- }
- }, [model]);
-
- // Update the token usage callback when it changes
- useEffect(() => {
- if (transportRef.current) {
- transportRef.current.setOnTokenUsage(onTokenUsage);
+ transportRef.current!.updateModel(model)
}
- }, [onTokenUsage]);
-
- // Update the onFinish callback when it changes
- useEffect(() => {
- if (transportRef.current) {
- transportRef.current.setOnFinish(onFinish);
- }
- }, [onFinish]);
+ }, [model])
// Set up streaming token speed callback to update global state
- const setTokenSpeed = useAppState((state) => state.setTokenSpeed);
- const resetTokenSpeed = useAppState((state) => state.resetTokenSpeed);
+ const setTokenSpeed = useAppState((state) => state.setTokenSpeed)
+ const resetTokenSpeed = useAppState((state) => state.resetTokenSpeed)
const handleStreamingTokenSpeed = useCallback(
(tokenCount: number, elapsedMs: number) => {
- const elapsedSec = elapsedMs / 1000;
- const speed = elapsedSec > 0 ? tokenCount / elapsedSec : 0;
+ const elapsedSec = elapsedMs / 1000
+ const speed = elapsedSec > 0 ? tokenCount / elapsedSec : 0
// Use a minimal ThreadMessage-like object for the state update
- setTokenSpeed({ id: sessionId || "" } as Parameters<typeof setTokenSpeed>[0], speed, tokenCount);
+ setTokenSpeed(
+ { id: sessionId || '' } as Parameters<typeof setTokenSpeed>[0],
+ speed,
+ tokenCount
+ )
},
[sessionId, setTokenSpeed]
- );
+ )
+ // Update the token usage callback when it changes
useEffect(() => {
if (transportRef.current) {
- transportRef.current.setOnStreamingTokenSpeed(handleStreamingTokenSpeed);
+ transportRef.current.setOnTokenUsage(onTokenUsage)
}
- }, [handleStreamingTokenSpeed]);
+ }, [onTokenUsage])
+
+ useEffect(() => {
+ if (transportRef.current) {
+ transportRef.current.setOnStreamingTokenSpeed(handleStreamingTokenSpeed)
+ }
+ }, [handleStreamingTokenSpeed])
// Memoize to prevent calling ensureSession (which has side effects) on every render
const chat = useMemo(() => {
- if (!sessionId || !transportRef.current) return undefined;
+ if (!sessionId || !transportRef.current) return undefined
+
return ensureSession(
sessionId,
transportRef.current,
() => new Chat({ ...chatInitOptions, transport: transportRef.current }),
- sessionTitle,
- );
+ sessionTitle
+ )
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [sessionId, ensureSession, model]);
+ }, [sessionId, ensureSession, model])
useEffect(() => {
if (sessionId && sessionTitle) {
- setSessionTitle(sessionId, sessionTitle);
+ setSessionTitle(sessionId, sessionTitle)
}
- }, [sessionId, sessionTitle, setSessionTitle]);
+ }, [sessionId, sessionTitle, setSessionTitle])
const chatResult = useChatSDK({
...(chat
? { chat }
: { transport: transportRef.current, ...chatInitOptions }),
- experimental_throttle,
+ // experimental_throttle,
resume: false,
- onFinish,
- onToolCall,
- sendAutomaticallyWhen,
- });
+ })
useEffect(() => {
if (sessionId) {
- updateStatus(sessionId, chatResult.status);
+ updateStatus(sessionId, chatResult.status)
}
- }, [sessionId, chatResult.status, updateStatus]);
+ }, [sessionId, chatResult.status, updateStatus])
// Reset token speed when streaming stops
useEffect(() => {
- if (chatResult.status !== "streaming") {
- resetTokenSpeed();
+ if (chatResult.status !== 'streaming') {
+ resetTokenSpeed()
}
- }, [chatResult.status, resetTokenSpeed]);
+ }, [chatResult.status, resetTokenSpeed])
+
+ // Expose method to update RAG tools availability
+ const updateRagToolsAvailability = useCallback(
+ async (
+ hasDocuments: boolean,
+ modelSupportsTools: boolean,
+ ragFeatureAvailable: boolean
+ ) => {
+ if (transportRef.current) {
+ await transportRef.current.updateRagToolsAvailability(
+ hasDocuments,
+ modelSupportsTools,
+ ragFeatureAvailable
+ )
+ }
+ },
+ []
+ )
- return chatResult;
+ return {
+ ...chatResult,
+ updateRagToolsAvailability,
+ }
}
diff --git a/web-app/src/hooks/useAppState.ts b/web-app/src/hooks/useAppState.ts
index a712c87ab..f1feec507 100644
--- a/web-app/src/hooks/useAppState.ts
+++ b/web-app/src/hooks/useAppState.ts
@@ -3,6 +3,7 @@ import { ThreadMessage } from '@janhq/core'
import { MCPTool } from '@/types/completion'
import { useAssistant } from './useAssistant'
import { ChatCompletionMessageToolCall } from 'openai/resources'
+import type { LanguageModel } from 'ai'
export type PromptProgress = {
cache: number
@@ -21,6 +22,8 @@ type AppState = {
streamingContent?: ThreadMessage
loadingModel?: boolean
tools: MCPTool[]
+ ragToolNames: Set<string>
+ mcpToolNames: Set<string>
serverStatus: 'running' | 'stopped' | 'pending'
abortControllers: Record<string, AbortController>
tokenSpeed?: TokenSpeed
@@ -29,6 +32,7 @@ type AppState = {
errorMessage?: AppErrorMessage
promptProgress?: PromptProgress
activeModels: string[]
+ languageModel: LanguageModel | null
cancelToolCall?: () => void
setServerStatus: (value: 'running' | 'stopped' | 'pending') => void
updateStreamingContent: (content: ThreadMessage | undefined) => void
@@ -37,6 +41,8 @@ type AppState = {
) => void
updateLoadingModel: (loading: boolean) => void
updateTools: (tools: MCPTool[]) => void
+ updateRagToolNames: (names: string[]) => void
+ updateMcpToolNames: (names: string[]) => void
setAbortController: (threadId: string, controller: AbortController) => void
updateTokenSpeed: (message: ThreadMessage, increment?: number) => void
setTokenSpeed: (
@@ -51,12 +57,15 @@ type AppState = {
setErrorMessage: (error: AppErrorMessage | undefined) => void
updatePromptProgress: (progress: PromptProgress | undefined) => void
setActiveModels: (models: string[]) => void
+ setLanguageModel: (model: LanguageModel | null) => void
}
export const useAppState = create<AppState>()((set) => ({
streamingContent: undefined,
loadingModel: false,
tools: [],
+ ragToolNames: new Set<string>(),
+ mcpToolNames: new Set<string>(),
serverStatus: 'stopped',
abortControllers: {},
tokenSpeed: undefined,
@@ -64,6 +73,7 @@ export const useAppState = create<AppState>()((set) => ({
promptProgress: undefined,
cancelToolCall: undefined,
activeModels: [],
+ languageModel: null,
updateStreamingContent: (content: ThreadMessage | undefined) => {
const assistants = useAssistant.getState().assistants
const currentAssistant = useAssistant.getState().currentAssistant
@@ -95,6 +105,12 @@ export const useAppState = create<AppState>()((set) => ({
updateTools: (tools) => {
set({ tools })
},
+ updateRagToolNames: (names) => {
+ set({ ragToolNames: new Set(names) })
+ },
+ updateMcpToolNames: (names) => {
+ set({ mcpToolNames: new Set(names) })
+ },
setServerStatus: (value) => set({ serverStatus: value }),
setAbortController: (threadId, controller) => {
set((state) => ({
@@ -182,5 +198,10 @@ export const useAppState = create<AppState>()((set) => ({
set(() => ({
activeModels: models,
}))
- }
+ },
+ setLanguageModel: (model) => {
+ set(() => ({
+ languageModel: model,
+ }))
+ },
}))
diff --git a/web-app/src/hooks/useTools.ts b/web-app/src/hooks/useTools.ts
index c0d1e17b8..f744a6907 100644
--- a/web-app/src/hooks/useTools.ts
+++ b/web-app/src/hooks/useTools.ts
@@ -8,6 +8,8 @@ import { ExtensionTypeEnum, MCPExtension } from '@janhq/core'
export const useTools = () => {
const updateTools = useAppState((state) => state.updateTools)
+ const updateRagToolNames = useAppState((state) => state.updateRagToolNames)
+ const updateMcpToolNames = useAppState((state) => state.updateMcpToolNames)
const { isDefaultsInitialized, setDefaultDisabledTools, markDefaultsAsInitialized } = useToolAvailable()
useEffect(() => {
@@ -18,10 +20,19 @@ export const useTools = () => {
ExtensionTypeEnum.MCP
)
- // Fetch tools
- const mcpTools = await getServiceHub().mcp().getTools()
+ // Fetch tools and tool names in parallel
+ const [mcpTools, ragToolNames] = await Promise.all([
+ getServiceHub().mcp().getTools(),
+ getServiceHub().rag().getToolNames?.() ?? Promise.resolve([]),
+ ])
+
+ // Update MCP tools
updateTools(mcpTools)
+ // Update cached tool names for fast synchronous access
+ updateMcpToolNames(mcpTools.map((t) => t.name))
+ updateRagToolNames(ragToolNames)
+
// Initialize default disabled tools for new users (only once)
if (!isDefaultsInitialized() && mcpTools.length > 0 && mcpExtension?.getDefaultDisabledTools) {
const defaultDisabled = await mcpExtension.getDefaultDisabledTools()
diff --git a/web-app/src/lib/__tests__/messages.test.ts b/web-app/src/lib/__tests__/messages.test.ts
index bd7e478b4..978895ca5 100644
--- a/web-app/src/lib/__tests__/messages.test.ts
+++ b/web-app/src/lib/__tests__/messages.test.ts
@@ -1,7 +1,11 @@
import { describe, it, expect } from 'vitest'
-import { CompletionMessagesBuilder } from '../messages'
+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 = (
@@ -562,3 +566,239 @@ 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/completion.ts b/web-app/src/lib/completion.ts
index b049cc36b..f3e5100f7 100644
--- a/web-app/src/lib/completion.ts
+++ b/web-app/src/lib/completion.ts
@@ -59,7 +59,8 @@ export type ChatCompletionResponse =
export const newUserThreadContent = (
threadId: string,
content: string,
- attachments?: Attachment[]
+ attachments?: Attachment[],
+ id?: string
): ThreadMessage => {
// Separate images and documents
const images = attachments?.filter((a) => a.type === 'image') || []
@@ -110,7 +111,7 @@ export const newUserThreadContent = (
type: 'text',
role: ChatCompletionRole.User,
content: contentParts,
- id: ulid(),
+ id: id ?? ulid(),
object: 'thread.message',
thread_id: threadId,
status: MessageStatus.Ready,
@@ -138,7 +139,8 @@ export const newUserThreadContent = (
export const newAssistantThreadContent = (
threadId: string,
content: string,
- metadata: Record<string, unknown> = {}
+ metadata: Record<string, unknown> = {},
+ id?: string,
): ThreadMessage => ({
type: 'text',
role: ChatCompletionRole.Assistant,
@@ -151,7 +153,7 @@ export const newAssistantThreadContent = (
},
},
],
- id: ulid(),
+ id: id ?? ulid(),
object: 'thread.message',
thread_id: threadId,
status: MessageStatus.Ready,
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index d1f8284b0..a4ef0b4a3 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -9,11 +9,36 @@ import {
type Tool,
type CoreMessage,
type LanguageModelUsage,
+ jsonSchema,
} from 'ai'
-export type TokenUsageCallback = (usage: LanguageModelUsage, messageId: string) => void
-export type StreamingTokenSpeedCallback = (tokenCount: number, elapsedMs: number) => void
-export type OnFinishCallback = (params: { message: UIMessage; isAbort?: boolean }) => void
+export type TokenUsageCallback = (
+ usage: LanguageModelUsage,
+ messageId: string
+) => void
+export type StreamingTokenSpeedCallback = (
+ tokenCount: number,
+ elapsedMs: number
+) => void
+export type OnFinishCallback = (params: {
+ message: UIMessage
+ isAbort?: boolean
+}) => void
+export type OnToolCallCallback = (params: {
+ toolCall: { toolCallId: string; toolName: string; input: unknown }
+}) => void
+export type ServiceHub = {
+ rag(): {
+ getTools(): Promise<
+ Array<{ name: string; description: string; inputSchema: unknown }>
+ >
+ }
+ mcp(): {
+ getTools(): Promise<
+ Array<{ name: string; description: string; inputSchema: unknown }>
+ >
+ }
+}
// import { mcpService } from "@/services/mcp-service";
/**
@@ -150,71 +175,141 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
private tools: Record<string, Tool> = {}
private onTokenUsage?: TokenUsageCallback
private onStreamingTokenSpeed?: StreamingTokenSpeedCallback
- private onFinishCallback?: OnFinishCallback
+ private serviceHub?: ServiceHub
+ private hasDocuments = false
+ private modelSupportsTools = false
+ private ragFeatureAvailable = false
- constructor(model: LanguageModel, onTokenUsage?: TokenUsageCallback) {
+ constructor(model: LanguageModel, serviceHub?: ServiceHub) {
this.model = model
- this.onTokenUsage = onTokenUsage
- // this.initializeTools();
+ this.serviceHub = serviceHub
+
+ // Initialize tools asynchronously if serviceHub is provided
+ if (serviceHub) {
+ // Fire and forget - load MCP tools in the background
+ this.loadMCPTools().catch((error) => {
+ console.warn('Failed to load MCP tools during initialization:', error)
+ })
+ }
+ }
+
+ /**
+ * Load MCP tools independently (can be called without RAG dependencies)
+ * @private
+ */
+ private async loadMCPTools() {
+ if (!this.serviceHub) return
+
+ try {
+ const mcpTools = await this.serviceHub.mcp().getTools()
+ if (Array.isArray(mcpTools) && mcpTools.length > 0) {
+ // Convert MCP tools to AI SDK format and merge with existing tools
+ mcpTools.forEach((tool) => {
+ this.tools[tool.name] = {
+ description: tool.description,
+ inputSchema: jsonSchema(
+ tool.inputSchema as Record<string, unknown>
+ ),
+ } as Tool
+ })
+ }
+ } catch (error) {
+ console.warn('Failed to load MCP tools:', error)
+ }
}
updateModel(model: LanguageModel) {
this.model = model
}
+ setOnStreamingTokenSpeed(callback: StreamingTokenSpeedCallback | undefined) {
+ this.onStreamingTokenSpeed = callback
+ }
+
setOnTokenUsage(callback: TokenUsageCallback | undefined) {
this.onTokenUsage = callback
}
- setOnStreamingTokenSpeed(callback: StreamingTokenSpeedCallback | undefined) {
- this.onStreamingTokenSpeed = callback
+ /**
+ * Update RAG tools availability based on thread metadata and model capabilities
+ * @param hasDocuments - Whether the thread has documents attached
+ * @param modelSupportsTools - Whether the current model supports tool calling
+ * @param ragFeatureAvailable - Whether RAG features are available on the platform
+ */
+ async updateRagToolsAvailability(
+ hasDocuments: boolean,
+ modelSupportsTools: boolean,
+ ragFeatureAvailable: boolean
+ ) {
+ this.hasDocuments = hasDocuments
+ this.modelSupportsTools = modelSupportsTools
+ this.ragFeatureAvailable = ragFeatureAvailable
+
+ // Update tools based on current state
+ await this.refreshTools()
}
- setOnFinish(callback: OnFinishCallback | undefined) {
- this.onFinishCallback = callback
+ /**
+ * Refresh tools based on current state
+ * Reloads both RAG and MCP tools and merges them
+ * @private
+ */
+ private async refreshTools() {
+ if (!this.serviceHub) {
+ this.tools = {}
+ return
+ }
+
+ const toolsRecord: Record<string, Tool> = {}
+
+ // Load RAG tools if documents are available and model supports tools
+ if (this.hasDocuments && this.ragFeatureAvailable && this.modelSupportsTools) {
+ try {
+ const ragTools = await this.serviceHub.rag().getTools()
+ if (Array.isArray(ragTools) && ragTools.length > 0) {
+ // Convert RAG tools to AI SDK format
+ ragTools.forEach((tool) => {
+ toolsRecord[tool.name] = {
+ description: tool.description,
+ inputSchema: jsonSchema(
+ tool.inputSchema as Record<string, unknown>
+ ),
+ } as Tool
+ })
+ }
+ } catch (error) {
+ console.warn('Failed to load RAG tools:', error)
+ }
+ }
+
+ // Always reload MCP tools (they don't depend on documents)
+ try {
+ const mcpTools = await this.serviceHub.mcp().getTools()
+ if (Array.isArray(mcpTools) && mcpTools.length > 0) {
+ // Convert MCP tools to AI SDK format
+ // MCP tools added after RAG tools, so they take precedence in case of name conflicts
+ mcpTools.forEach((tool) => {
+ toolsRecord[tool.name] = {
+ description: tool.description,
+ inputSchema: jsonSchema(
+ tool.inputSchema as Record<string, unknown>
+ ),
+ } as Tool
+ })
+ }
+ } catch (error) {
+ console.warn('Failed to load MCP tools:', error)
+ }
+
+ this.tools = toolsRecord
}
/**
- * Initialize MCP tools and convert them to AI SDK format
- * Search tools (google_search, scrape) are always included regardless of user toggle
+ * Get current tools
*/
- // private async initializeTools() {
- // try {
- // // Always include "search" server for google_search and scrape tools
- // // Browser tools are conditional on user preference
- // const servers = this.enableImageTools
- // ? undefined
- // : ([
- // "search", // Always include search tools
- // this.enableBrowse ? "browse" : null,
- // ].filter(Boolean) as string[]);
- // const toolsResponse = await mcpService.getTools(servers);
- // const allowedImageTools = new Set(["generate_image", "edit_image"]);
- // const filteredTools = toolsResponse.data.filter((tool) =>
- // this.enableImageTools
- // ? allowedImageTools.has(tool.name)
- // : !allowedImageTools.has(tool.name),
- // );
-
- // // Convert MCP tools to AI SDK CoreTool format
- // this.tools = filteredTools.reduce(
- // (acc, tool) => {
- // acc[tool.name] = {
- // description: tool.description,
- // inputSchema: jsonSchema(tool.inputSchema),
- // name: tool.name,
- // };
- // return acc;
- // },
- // {} as Record<string, Tool>,
- // );
-
- // console.log(`Initialized ${Object.keys(this.tools).length} MCP tools`);
- // } catch (error) {
- // console.error("Failed to initialize MCP tools:", error);
- // this.tools = {};
- // }
- // }
+ getTools(): Record<string, Tool> {
+ return this.tools
+ }
async sendMessages(
options: {
@@ -226,8 +321,6 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
messageId: string | undefined
} & ChatRequestOptions
): Promise<ReadableStream<UIMessageChunk>> {
- // await this.initializeTools();
-
// Convert UI messages to model messages
const modelMessages = convertToModelMessages(options.messages)
@@ -237,8 +330,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
// Convert image parts to image_url format for the API
const messagesWithImageUrls = convertToImageUrlFormat(filteredMessages)
- // Always include tools if we have any loaded
- // Search tools (google_search, scrape) are always sent regardless of user toggle
+ // Include tools if we have any loaded
const hasTools = Object.keys(this.tools).length > 0
// Track stream timing and token count for token speed calculation
@@ -294,7 +386,10 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
const durationSec = durationMs / 1000
// Use provider's outputTokens, or llama.cpp completionTokens, or fall back to text delta count
- const outputTokens = usage?.outputTokens ?? llamacppMeta?.completionTokens ?? textDeltaCount
+ const outputTokens =
+ usage?.outputTokens ??
+ llamacppMeta?.completionTokens ??
+ textDeltaCount
const inputTokens = usage?.inputTokens ?? llamacppMeta?.promptTokens
// Use llama.cpp's tokens per second if available, otherwise calculate from duration
@@ -311,7 +406,8 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
usage: {
inputTokens: inputTokens,
outputTokens: outputTokens,
- totalTokens: usage?.totalTokens ?? (inputTokens ?? 0) + outputTokens,
+ totalTokens:
+ usage?.totalTokens ?? (inputTokens ?? 0) + outputTokens,
},
tokenSpeed: {
tokenSpeed: Math.round(tokenSpeed * 10) / 10, // Round to 1 decimal
@@ -340,17 +436,16 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
},
onFinish: ({ responseMessage }) => {
// Call the token usage callback with usage data when stream completes
- if (this.onTokenUsage && responseMessage) {
- const metadata = responseMessage.metadata as Record<string, unknown> | undefined
+ if (responseMessage) {
+ const metadata = responseMessage.metadata as
+ | Record<string, unknown>
+ | undefined
const usage = metadata?.usage as LanguageModelUsage | undefined
+ console.log(usage)
if (usage) {
- this.onTokenUsage(usage, responseMessage.id)
+ this.onTokenUsage?.(usage, responseMessage.id)
}
}
- // Call the onFinish callback from useChat hook
- if (this.onFinishCallback && responseMessage) {
- this.onFinishCallback({ message: responseMessage })
- }
},
})
}
diff --git a/web-app/src/lib/messages.ts b/web-app/src/lib/messages.ts
index abf2eaa43..8588adf86 100644
--- a/web-app/src/lib/messages.ts
+++ b/web-app/src/lib/messages.ts
@@ -440,8 +440,10 @@ export const parseReasoning = (text: string) => {
export function convertThreadMessageToUIMessage(
threadMessage: ThreadMessage
): UIMessage {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const parts: any[] = []
+ const reasoningParts: any[] = []
+ const toolParts: any[] = []
+ const textParts: any[] = []
+ const otherParts: any[] = []
// Process content array
for (const content of threadMessage.content || []) {
@@ -458,7 +460,7 @@ export function convertThreadMessageToUIMessage(
/<think>([\s\S]*)<\/think>/
)
if (completedMatch) {
- parts.push({
+ reasoningParts.push({
type: 'reasoning',
text: completedMatch[1],
})
@@ -466,7 +468,7 @@ export function convertThreadMessageToUIMessage(
// In-progress reasoning - extract content after <think> tag
const inProgressMatch = reasoningSegment.match(/<think>([\s\S]*)/)
if (inProgressMatch) {
- parts.push({
+ reasoningParts.push({
type: 'reasoning',
text: inProgressMatch[1],
})
@@ -478,14 +480,14 @@ export function convertThreadMessageToUIMessage(
// Trim leading whitespace/newlines from the text segment
const trimmedText = textSegment.trim()
if (trimmedText) {
- parts.push({
+ textParts.push({
type: 'text',
text: trimmedText,
})
}
}
} else if (content.type === ContentType.Image && content.image_url?.url) {
- parts.push({
+ otherParts.push({
type: 'file',
mediaType: 'image/jpeg',
url: content.image_url.url,
@@ -494,24 +496,40 @@ export function convertThreadMessageToUIMessage(
}
// Handle tool calls from metadata
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
const toolCalls = (threadMessage.metadata as any)?.tool_calls
if (Array.isArray(toolCalls)) {
for (const tc of toolCalls) {
- parts.push({
- type: 'tool-invocation',
+ // Parse the result from the response.content array
+ let result
+ if (tc.response?.content) {
+ // Extract content from the response
+ if (tc.response.content.length === 1 && tc.response.content[0].type === 'text') {
+ // Single text content - return as string
+ result = tc.response.content[0].text
+ } else {
+ // Multiple content parts or non-text - return full content array
+ result = tc.response.content
+ }
+ }
+
+ const toolName = tc.tool?.function?.name || tc.name
+ toolParts.push({
+ type: `tool-${toolName}`,
toolInvocationId: tc.tool?.id || tc.id,
- toolName: tc.tool?.function?.name || tc.name,
- args:
+ toolName: toolName,
+ input:
typeof tc.tool?.function?.arguments === 'string'
? JSON.parse(tc.tool.function.arguments)
: tc.tool?.function?.arguments || tc.args,
- state: tc.state === 'completed' ? 'result' : 'call',
- result: tc.response,
+ state: tc.state === 'ready' ? 'result' : tc.state === 'pending' ? 'call' : tc.state,
+ output: result,
})
}
}
+ // 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({
@@ -536,3 +554,98 @@ export function convertThreadMessagesToUIMessages(
): UIMessage[] {
return threadMessages.map(convertThreadMessageToUIMessage)
}
+
+/**
+ * Extract combined content from UIMessage parts, including reasoning and text.
+ * Reasoning content is wrapped in <think> tags.
+ *
+ * @param message - The UIMessage to extract content from
+ * @returns Combined content string with reasoning in <think> tags followed by text
+ */
+export function extractCombinedContentFromUIMessage(message: UIMessage): string {
+ let combinedContent = ''
+
+ 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>`
+ }
+ }
+
+ // 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
+ }
+
+ 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',
+ }
+ })
+}
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index c8ff0d4d3..13f9bc683 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -1,13 +1,6 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import {
- createFileRoute,
- useParams,
- redirect,
- useNavigate,
-} from '@tanstack/react-router'
+import { useCallback, useEffect, useMemo, useRef } from 'react'
+import { createFileRoute, useParams } from '@tanstack/react-router'
import { cn } from '@/lib/utils'
-import { toast } from 'sonner'
-import { useTranslation } from '@/i18n/react-i18next-compat'
import HeaderPage from '@/containers/HeaderPage'
import { useThreads } from '@/hooks/useThreads'
@@ -22,20 +15,10 @@ import { useAssistant } from '@/hooks/useAssistant'
import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'
import { useSmallScreen, useMobileScreen } from '@/hooks/useMediaQuery'
import { useTools } from '@/hooks/useTools'
+import { useAppState } from '@/hooks/useAppState'
import { PlatformFeatures } from '@/lib/platform/const'
import { PlatformFeature } from '@/lib/platform/types'
-import {
- TEMPORARY_CHAT_ID,
- TEMPORARY_CHAT_QUERY_ID,
- SESSION_STORAGE_KEY,
- SESSION_STORAGE_PREFIX,
-} from '@/constants/chat'
-import { IconInfoCircle } from '@tabler/icons-react'
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from '@/components/ui/tooltip'
+import { SESSION_STORAGE_PREFIX } from '@/constants/chat'
import { useChat } from '@/hooks/use-chat'
import { createLanguageModel } from '@/lib/ai-model'
import { useModelProvider } from '@/hooks/useModelProvider'
@@ -45,77 +28,45 @@ import {
ConversationScrollButton,
} from '@/ai-elements/conversation'
import { Loader } from 'lucide-react'
-import { lastAssistantMessageIsCompleteWithToolCalls } from 'ai'
-import type { UIMessage, UIDataTypes, UITools } from 'ai'
+import { generateId, lastAssistantMessageIsCompleteWithToolCalls } from 'ai'
+import type { UIMessage } from '@ai-sdk/react'
import { useChatSessions } from '@/stores/chat-session-store'
-import { convertThreadMessagesToUIMessages } from '@/lib/messages'
-import { newUserThreadContent, newAssistantThreadContent } from '@/lib/completion'
+import {
+ convertThreadMessagesToUIMessages,
+ extractCombinedContentFromUIMessage,
+ extractToolCallsFromUIMessage,
+} from '@/lib/messages'
+import {
+ newUserThreadContent,
+ newAssistantThreadContent,
+} from '@/lib/completion'
import { createImageAttachment } from '@/types/attachment'
+import {
+ useChatAttachments,
+ NEW_THREAD_ATTACHMENT_KEY,
+} from '@/hooks/useChatAttachments'
+import { processAttachmentsForSend } from '@/lib/attachmentProcessing'
+import { useAttachments } from '@/hooks/useAttachments'
const CHAT_STATUS = {
STREAMING: 'streaming',
SUBMITTED: 'submitted',
} as const
-const CONVERSATION_NOT_FOUND_EVENT = 'conversation-not-found'
-
-const TemporaryChatIndicator = ({ t }: { t: (key: string) => string }) => {
- return (
- <div className="flex items-center gap-1.5 px-3 py-1 rounded-md bg-main-view-fg/5 text-main-view-fg/70 text-sm">
- <span>{t('common:temporaryChat')}</span>
- <Tooltip>
- <TooltipTrigger asChild>
- <div className="relative z-20">
- <IconInfoCircle
- size={14}
- className="text-main-view-fg/50 hover:text-main-view-fg/70 transition-colors cursor-pointer"
- />
- </div>
- </TooltipTrigger>
- <TooltipContent className="z-[9999]">
- <p>{t('common:temporaryChatTooltip')}</p>
- </TooltipContent>
- </Tooltip>
- </div>
- )
-}
-
// as route.threadsDetail
export const Route = createFileRoute('/threads/$threadId')({
- beforeLoad: ({ params }) => {
- // Check if this is the temporary chat being accessed directly
- if (params.threadId === TEMPORARY_CHAT_ID) {
- // Check if we have the navigation flag in sessionStorage
- const hasNavigationFlag = sessionStorage.getItem('temp-chat-nav')
-
- if (!hasNavigationFlag) {
- // Direct access - redirect to home with query parameter
- throw redirect({
- to: '/',
- search: { [TEMPORARY_CHAT_QUERY_ID]: true },
- replace: true,
- })
- }
-
- // Clear the flag immediately after checking
- sessionStorage.removeItem('temp-chat-nav')
- }
- },
component: ThreadDetail,
})
function ThreadDetail() {
const serviceHub = useServiceHub()
const { threadId } = useParams({ from: Route.id })
- const navigate = useNavigate()
- const { t } = useTranslation()
const setCurrentThreadId = useThreads((state) => state.setCurrentThreadId)
const setCurrentAssistant = useAssistant((state) => state.setCurrentAssistant)
const currentAssistant = useAssistant((state) => state.currentAssistant)
const assistants = useAssistant((state) => state.assistants)
const setMessages = useMessages((state) => state.setMessages)
const addMessage = useMessages((state) => state.addMessage)
- const getMessages = useMessages((state) => state.getMessages)
const deleteMessage = useMessages((state) => state.deleteMessage)
const currentThread = useRef<string | undefined>(undefined)
@@ -124,6 +75,13 @@ function ThreadDetail() {
const isMobile = useMobileScreen()
useTools()
+ // Get attachments for this thread
+ const attachmentsKey = threadId ?? NEW_THREAD_ATTACHMENT_KEY
+ const getAttachments = useChatAttachments((state) => state.getAttachments)
+ const clearAttachmentsForThread = useChatAttachments(
+ (state) => state.clearAttachments
+ )
+
// Session data for tool call tracking
const getSessionData = useChatSessions((state) => state.getSessionData)
const sessionData = getSessionData(threadId)
@@ -133,11 +91,7 @@ function ThreadDetail() {
// Check if we should follow up with tool calls (respects abort signal)
const followUpMessage = useCallback(
- ({
- messages,
- }: {
- messages: UIMessage<unknown, UIDataTypes, UITools>[]
- }) => {
+ ({ messages }: { messages: UIMessage[] }) => {
if (
!toolCallAbortController.current ||
toolCallAbortController.current?.signal.aborted
@@ -156,13 +110,18 @@ function ThreadDetail() {
const selectedModel = useModelProvider((state) => state.selectedModel)
const selectedProvider = useModelProvider((state) => state.selectedProvider)
const getProviderByName = useModelProvider((state) => state.getProviderByName)
+ const providers = useModelProvider((state) => state.providers)
- // Create language model for AI SDK (async)
- const [languageModel, setLanguageModel] = useState<Awaited<
- ReturnType<typeof createLanguageModel>
- > | null>(null)
+ // Get language model from appState
+ const languageModel = useAppState((state) => state.languageModel)
+ const setLanguageModel = useAppState((state) => state.setLanguageModel)
useEffect(() => {
+ // Wait for providers to be loaded before attempting to create language model
+ if (providers.length === 0) {
+ return
+ }
+
const provider = getProviderByName(selectedProvider)
const modelId = selectedModel?.id ?? thread?.model?.id ?? ''
if (!modelId || !provider) {
@@ -192,21 +151,39 @@ function ThreadDetail() {
thread?.model?.id,
selectedProvider,
getProviderByName,
+ providers.length,
])
- // Handle onFinish - persist assistant message and execute collected tool calls
- const handleOnFinish = useCallback(
- ({ message, isAbort }: { message: UIMessage; isAbort?: boolean }) => {
+ // Use the AI SDK chat hook
+ const {
+ messages: chatMessages,
+ status,
+ sendMessage,
+ regenerate,
+ setMessages: setChatMessages,
+ stop,
+ addToolOutput,
+ updateRagToolsAvailability,
+ } = useChat(languageModel, {
+ sessionId: threadId,
+ sessionTitle: thread?.title,
+ experimental_throttle: 50,
+ onFinish: ({ message, isAbort }) => {
// Persist assistant message to backend (skip if aborted)
if (!isAbort && message.role === 'assistant') {
- // Extract text content from the message parts
- const textContent = message.parts
- ?.filter((part): part is { type: 'text'; text: string } => part.type === 'text')
- .map((part) => part.text)
- .join('') || ''
-
- if (textContent) {
- const assistantMessage = newAssistantThreadContent(threadId, textContent)
+ 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 } : {}
+
+ const assistantMessage = newAssistantThreadContent(
+ threadId,
+ combinedContent,
+ metadata,
+ message.id
+ )
addMessage(assistantMessage)
}
}
@@ -215,6 +192,10 @@ function ThreadDetail() {
toolCallAbortController.current = new AbortController()
const signal = toolCallAbortController.current.signal
+ // Get cached tool names from store (initialized in useTools hook)
+ const ragToolNames = useAppState.getState().ragToolNames
+ const mcpToolNames = useAppState.getState().mcpToolNames
+
// Execute all collected tool calls
Promise.all(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -225,10 +206,27 @@ function ThreadDetail() {
}
try {
- const result = await serviceHub.mcp().callTool({
- toolName: toolCall.toolName,
- arguments: toolCall.input,
- })
+ const toolName = toolCall.toolName
+ let result
+
+ // Route to the appropriate service based on tool name
+ if (ragToolNames.has(toolName)) {
+ result = await serviceHub.rag().callTool({
+ toolName,
+ arguments: toolCall.input,
+ threadId,
+ })
+ } else if (mcpToolNames.has(toolName)) {
+ result = await serviceHub.mcp().callTool({
+ toolName,
+ arguments: toolCall.input,
+ })
+ } else {
+ // Tool not found in either service
+ result = {
+ error: `Tool '${toolName}' not found in any service`,
+ }
+ }
if (result.error) {
addToolOutput({
@@ -269,71 +267,40 @@ function ThreadDetail() {
toolCallAbortController.current = null
})
},
- [sessionData, serviceHub, threadId, addMessage]
- )
-
- // Handle onToolCall - collect tool calls during streaming
- const handleOnToolCall = useCallback(
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ({ toolCall }: { toolCall: any }) => {
+ onToolCall: ({ toolCall }) => {
sessionData.tools.push(toolCall)
- return
},
- [sessionData]
- )
-
- // Use the AI SDK chat hook
- const {
- messages: chatMessages,
- status,
- sendMessage,
- regenerate,
- setMessages: setChatMessages,
- stop,
- addToolOutput,
- } = useChat(languageModel, {
- sessionId: threadId,
- sessionTitle: thread?.title,
- experimental_throttle: 50,
- onFinish: handleOnFinish,
- onToolCall: handleOnToolCall,
sendAutomaticallyWhen: followUpMessage,
+ serviceHub,
})
- // Use chatMessages directly from useChat
- const messages = chatMessages ?? []
+ // Update RAG tools availability when documents or model changes
+ useEffect(() => {
+ // const hasDocuments = thread?.metadata?.hasDocuments ?? false
+ const ragFeatureAvailable = Boolean(
+ useAttachments.getState().enabled &&
+ PlatformFeatures[PlatformFeature.FILE_ATTACHMENTS]
+ )
+ const modelSupportsTools =
+ selectedModel?.capabilities?.includes('tools') ?? false
+
+ updateRagToolsAvailability(true, modelSupportsTools, ragFeatureAvailable)
+ }, [
+ thread?.metadata?.hasDocuments,
+ selectedModel?.capabilities,
+ updateRagToolsAvailability,
+ ])
// Ref for reasoning container auto-scroll
const reasoningContainerRef = useRef<HTMLDivElement>(null)
- // Listen for conversation not found events
+ // Auto-scroll reasoning container to bottom during streaming
useEffect(() => {
- const handleConversationNotFound = (event: CustomEvent) => {
- const { threadId: notFoundThreadId } = event.detail
- if (notFoundThreadId === threadId) {
- // Skip error handling for temporary chat - it's expected to not exist on server
- if (threadId === TEMPORARY_CHAT_ID) {
- return
- }
-
- toast.error(t('common:conversationNotAvailable'), {
- description: t('common:conversationNotAvailableDescription'),
- })
- navigate({ to: '/', replace: true })
- }
+ if (status === 'streaming' && reasoningContainerRef.current) {
+ reasoningContainerRef.current.scrollTop =
+ reasoningContainerRef.current.scrollHeight
}
-
- window.addEventListener(
- CONVERSATION_NOT_FOUND_EVENT,
- handleConversationNotFound as EventListener
- )
- return () => {
- window.removeEventListener(
- CONVERSATION_NOT_FOUND_EVENT,
- handleConversationNotFound as EventListener
- )
- }
- }, [threadId, navigate, t])
+ }, [status, chatMessages])
useEffect(() => {
setCurrentThreadId(threadId)
@@ -350,7 +317,8 @@ function ThreadDetail() {
const existingSession = useChatSessions.getState().sessions[threadId]
if (
existingSession?.chat.messages.length > 0 ||
- existingSession?.isStreaming || currentThread.current === threadId
+ existingSession?.isStreaming ||
+ currentThread.current === threadId
) {
return
}
@@ -416,75 +384,131 @@ function ThreadDetail() {
if (initialMessageSentRef.current) return
if (!languageModel) return
- const isTemporaryChat = threadId === TEMPORARY_CHAT_ID
- const initialMessageKey = isTemporaryChat
- ? SESSION_STORAGE_KEY.INITIAL_MESSAGE_TEMPORARY
- : `${SESSION_STORAGE_PREFIX.INITIAL_MESSAGE}${threadId}`
+ const initialMessageKey = `${SESSION_STORAGE_PREFIX.INITIAL_MESSAGE}${threadId}`
const storedMessage = sessionStorage.getItem(initialMessageKey)
if (storedMessage) {
- try {
- const message = JSON.parse(storedMessage) as {
- text: string
- files?: Array<{ type: string; mediaType: string; url: string }>
- }
+ // Mark as sent immediately to prevent duplicate sends
+ sessionStorage.removeItem(initialMessageKey)
+ initialMessageSentRef.current = true
+
+ // Process message asynchronously
+ ;(async () => {
+ try {
+ const message = JSON.parse(storedMessage) as {
+ text: string
+ files?: Array<{ type: string; mediaType: string; url: string }>
+ }
- // Clear the stored message immediately to prevent duplicate sends
- sessionStorage.removeItem(initialMessageKey)
- initialMessageSentRef.current = true
-
- // Convert files to attachments for persistence
- const attachments = message.files?.map((file) => {
- const base64 = file.url.split(',')[1] || ''
- return createImageAttachment({
- name: `image-${Date.now()}`,
- mimeType: file.mediaType,
- dataUrl: file.url,
- base64,
- size: Math.ceil((base64.length * 3) / 4), // Estimate size from base64
+ // Get all attachments from the store (includes both images and documents)
+ const allAttachments = getAttachments(attachmentsKey)
+
+ // Convert image files to attachments for persistence
+ const imageAttachments = message.files?.map((file) => {
+ const base64 = file.url.split(',')[1] || ''
+ return createImageAttachment({
+ name: `image-${Date.now()}`,
+ mimeType: file.mediaType,
+ dataUrl: file.url,
+ base64,
+ size: Math.ceil((base64.length * 3) / 4), // Estimate size from base64
+ })
})
- })
- // Create and persist the user message to the backend
- const userMessage = newUserThreadContent(threadId, message.text, attachments)
- addMessage(userMessage)
-
- // Build message parts for AI SDK
- const parts: Array<
- | { type: 'text'; text: string }
- | { type: 'file'; mediaType: string; url: string }
- > = [{ type: 'text', text: message.text }]
-
- if (message.files) {
- message.files.forEach((file) => {
- parts.push({
- type: 'file',
- mediaType: file.mediaType,
- url: file.url,
+ // Combine image attachments with document attachments from the store
+ const combinedAttachments = [
+ ...(imageAttachments || []),
+ ...allAttachments.filter((a) => a.type === 'document'),
+ ]
+
+ // Process attachments (ingest images, parse/index documents)
+ let processedAttachments = combinedAttachments
+ if (combinedAttachments.length > 0) {
+ try {
+ const parsePreference = useAttachments.getState().parseMode
+ const result = await processAttachmentsForSend({
+ attachments: combinedAttachments,
+ threadId,
+ serviceHub,
+ selectedProvider,
+ parsePreference,
+ })
+ processedAttachments = result.processedAttachments
+
+ // Update thread metadata if documents were embedded
+ if (result.hasEmbeddedDocuments) {
+ useThreads.getState().updateThread(threadId, {
+ metadata: { hasDocuments: true },
+ })
+ }
+ } catch (error) {
+ console.error('Failed to process attachments:', error)
+ // Don't send message if attachment processing failed
+ return
+ }
+ }
+ const messageId = generateId()
+ // Create and persist the user message to the backend with all processed attachments
+ const userMessage = newUserThreadContent(
+ threadId,
+ message.text,
+ processedAttachments,
+ messageId
+ )
+ addMessage(userMessage)
+
+ // Build message parts for AI SDK (only images are sent as file parts)
+ const parts: Array<
+ | { type: 'text'; text: string }
+ | { type: 'file'; mediaType: string; url: string }
+ > = [{ type: 'text', text: message.text }]
+
+ if (message.files) {
+ message.files.forEach((file) => {
+ parts.push({
+ type: 'file',
+ mediaType: file.mediaType,
+ url: file.url,
+ })
})
- })
- }
+ }
- // Send the message
- sendMessage({ parts })
- } catch (error) {
- console.error('Failed to parse initial message:', error)
- sessionStorage.removeItem(initialMessageKey)
- }
+ // Send the message
+ sendMessage({ parts, id: messageId })
+
+ // Clear attachments after sending
+ clearAttachmentsForThread(attachmentsKey)
+ } catch (error) {
+ console.error('Failed to parse initial message:', error)
+ }
+ })()
}
- }, [threadId, languageModel, sendMessage, addMessage])
+ }, [
+ threadId,
+ languageModel,
+ sendMessage,
+ addMessage,
+ getAttachments,
+ attachmentsKey,
+ clearAttachmentsForThread,
+ serviceHub,
+ selectedProvider,
+ ])
// Handle submit from ChatInput
const handleSubmit = useCallback(
- (
+ async (
text: string,
files?: Array<{ type: string; mediaType: string; url: string }>
) => {
if (!languageModel) return
- // Convert files to attachments for persistence
- const attachments = files?.map((file) => {
+ // Get all attachments from the store (includes both images and documents)
+ const allAttachments = getAttachments(attachmentsKey)
+
+ // Convert image files from ChatInput to attachments for persistence
+ const imageAttachments = files?.map((file) => {
const base64 = file.url.split(',')[1] || ''
return createImageAttachment({
name: `image-${Date.now()}`,
@@ -495,11 +519,50 @@ function ThreadDetail() {
})
})
- // Persist user message to backend
- const userMessage = newUserThreadContent(threadId, text, attachments)
+ // Combine image attachments with document attachments from the store
+ const combinedAttachments = [
+ ...(imageAttachments || []),
+ ...allAttachments.filter((a) => a.type === 'document'),
+ ]
+
+ // Process attachments (ingest images, parse/index documents)
+ let processedAttachments = combinedAttachments
+ if (combinedAttachments.length > 0) {
+ try {
+ const parsePreference = useAttachments.getState().parseMode
+ const result = await processAttachmentsForSend({
+ attachments: combinedAttachments,
+ threadId,
+ serviceHub,
+ selectedProvider,
+ parsePreference,
+ })
+ processedAttachments = result.processedAttachments
+
+ // Update thread metadata if documents were embedded
+ if (result.hasEmbeddedDocuments) {
+ useThreads.getState().updateThread(threadId, {
+ metadata: { hasDocuments: true },
+ })
+ }
+ } catch (error) {
+ console.error('Failed to process attachments:', error)
+ // Don't send message if attachment processing failed
+ return
+ }
+ }
+
+ const messageId = generateId()
+ // Persist user message to backend with all processed attachments
+ const userMessage = newUserThreadContent(
+ threadId,
+ text,
+ processedAttachments,
+ messageId
+ )
addMessage(userMessage)
- // Build parts for AI SDK
+ // Build parts for AI SDK (only images are sent as file parts)
const parts: Array<
| { type: 'text'; text: string }
| { type: 'file'; mediaType: string; url: string }
@@ -515,59 +578,73 @@ function ThreadDetail() {
})
}
- sendMessage({ parts })
+ sendMessage({ parts, id: messageId })
+
+ // Clear attachments after sending
+ clearAttachmentsForThread(attachmentsKey)
},
- [languageModel, sendMessage, threadId, addMessage]
+ [
+ languageModel,
+ sendMessage,
+ threadId,
+ addMessage,
+ getAttachments,
+ attachmentsKey,
+ clearAttachmentsForThread,
+ serviceHub,
+ selectedProvider,
+ ]
)
// Handle regenerate from any message (user or assistant)
// - For user messages: keeps the user message, deletes all after, regenerates assistant response
- // - For assistant messages: deletes all after, regenerates that assistant response
- const handleRegenerate = useCallback(
- (messageId?: string) => {
- if (!languageModel) {
- console.warn('No language model available')
- return
- }
+ // - For assistant messages: finds the closest preceding user message, deletes from there
+ const handleRegenerate = (messageId?: string) => {
+ if (!languageModel) {
+ console.warn('No language model available')
+ return
+ }
- // If regenerating from a specific message, delete all messages after it
- if (messageId) {
- // Find the message in the current chat messages
- const messageIndex = messages.findIndex((m) => m.id === messageId)
- console.log('messageIndex:', messageIndex)
-
- if (messageIndex !== -1) {
- // Get all messages after the selected message
- const messagesToDelete = messages.slice(messageIndex + 1)
- console.log('messagesToDelete:', messagesToDelete.length)
-
- // Delete from backend storage
- if (messagesToDelete.length > 0) {
- messagesToDelete.forEach((msg) => {
- // Delete from persisted storage
- const currentMessages = getMessages(threadId)
- const persistedMsg = currentMessages.find((m) => m.id === msg.id)
- if (persistedMsg) {
- console.log('Deleting message:', msg.id)
- deleteMessage(threadId, msg.id)
- }
- })
+ const currentLocalMessages = useMessages.getState().getMessages(threadId)
+
+ // If regenerating from a specific message, delete all messages after it
+ if (messageId) {
+ // Find the message in the current chat messages
+ const messageIndex = currentLocalMessages.findIndex(
+ (m) => m.id === messageId
+ )
+
+ if (messageIndex !== -1) {
+ const selectedMessage = currentLocalMessages[messageIndex]
+
+ // If it's an assistant message, find the closest preceding user message
+ let deleteFromIndex = messageIndex
+ if (selectedMessage.role === 'assistant') {
+ // Look backwards to find the closest user message
+ for (let i = messageIndex - 1; i >= 0; i--) {
+ if (currentLocalMessages[i].role === 'user') {
+ deleteFromIndex = i
+ break
+ }
}
}
- }
- // Call the AI SDK regenerate function - it will handle truncating the UI messages
- // and generating a new response from the selected message
- regenerate(messageId ? { messageId } : undefined)
- },
- [languageModel, regenerate, threadId, getMessages, deleteMessage, messages]
- )
+ // Get all messages after the delete point
+ const messagesToDelete = currentLocalMessages.slice(deleteFromIndex + 1)
- // Handle stop
- const handleStop = useCallback(() => {
- stop()
- }, [stop])
+ // Delete from backend storage
+ if (messagesToDelete.length > 0) {
+ messagesToDelete.forEach((msg) => {
+ deleteMessage(threadId, msg.id)
+ })
+ }
+ }
+ }
+ // Call the AI SDK regenerate function - it will handle truncating the UI messages
+ // and generating a new response from the selected message
+ regenerate(messageId ? { messageId } : undefined)
+ }
const threadModel = useMemo(() => thread?.model, [thread])
if (!threadModel) return null
@@ -581,10 +658,6 @@ function ThreadDetail() {
<DropdownAssistant />
)}
</div>
- <div className="flex-1 flex justify-center">
- {threadId === TEMPORARY_CHAT_ID && <TemporaryChatIndicator t={t} />}
- </div>
- <div></div>
</div>
</HeaderPage>
<div className="flex flex-1 flex-col h-full overflow-hidden">
@@ -599,12 +672,13 @@ function ThreadDetail() {
: 'w-full md:w-4/5'
)}
>
- {messages.map((message, index) => {
- const isLastMessage = index === messages.length - 1
+ {chatMessages.map((message, index) => {
+ const isLastMessage = index === chatMessages.length - 1
const isFirstMessage = index === 0
const showAssistant =
message.role === 'assistant' &&
- (isFirstMessage || messages[index - 1]?.role !== 'assistant')
+ (isFirstMessage ||
+ chatMessages[index - 1]?.role !== 'assistant')
return (
<MessageItem
@@ -647,7 +721,7 @@ function ThreadDetail() {
<ChatInput
model={threadModel}
onSubmit={handleSubmit}
- onStop={handleStop}
+ onStop={stop}
chatStatus={status}
/>
</div>