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: onFinish callback to persist messages

Louisee857472491d
diff --git a/web-app/package.json b/web-app/package.json
index bacb84b53..9824d00df 100644
--- a/web-app/package.json
+++ b/web-app/package.json
@@ -52,7 +52,7 @@
"@types/react-syntax-highlighter": "15.5.13",
"@types/uuid": "10.0.0",
"@uiw/react-textarea-code-editor": "3.1.1",
- "ai": "5.0.108",
+ "ai": "5.0.121",
"class-variance-authority": "0.7.1",
"culori": "4.0.1",
"emoji-picker-react": "4.12.2",
diff --git a/web-app/src/constants/chat.ts b/web-app/src/constants/chat.ts
index e1649049f..4e8f60912 100644
--- a/web-app/src/constants/chat.ts
+++ b/web-app/src/constants/chat.ts
@@ -4,3 +4,14 @@
export const TEMPORARY_CHAT_ID = 'temporary-chat'
export const TEMPORARY_CHAT_QUERY_ID = 'temporary-chat'
+
+/**
+ * Session storage keys for initial messages
+ */
+export const SESSION_STORAGE_KEY = {
+ INITIAL_MESSAGE_TEMPORARY: 'initial-message-temporary',
+} as const
+
+export const SESSION_STORAGE_PREFIX = {
+ INITIAL_MESSAGE: 'initial-message-',
+} as const
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index e501e7921..af9d6cea4 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -37,8 +37,17 @@ import { useModelProvider } from '@/hooks/useModelProvider'
import { useAppState } from '@/hooks/useAppState'
import { MovingBorder } from './MovingBorder'
-import { useChat } from '@/hooks/useChat'
import type { ChatStatus } from 'ai'
+import { useRouter } from '@tanstack/react-router'
+import { route } from '@/constants/routes'
+import {
+ TEMPORARY_CHAT_ID,
+ TEMPORARY_CHAT_QUERY_ID,
+ SESSION_STORAGE_KEY,
+ SESSION_STORAGE_PREFIX,
+} from '@/constants/chat'
+import { defaultModel } from '@/lib/models'
+import { useAssistant } from '@/hooks/useAssistant'
import DropdownModelProvider from '@/containers/DropdownModelProvider'
import { ModelLoader } from '@/containers/loaders/ModelLoader'
import DropdownToolsAvailable from '@/containers/DropdownToolsAvailable'
@@ -119,6 +128,10 @@ const ChatInput = ({
(state) => state.tokenCounterCompact
)
useTools()
+ const router = useRouter()
+ const createThread = useThreads((state) => state.createThread)
+ const currentAssistant = useAssistant((state) => state.currentAssistant)
+ const assistants = useAssistant((state) => state.assistants)
// Get current thread messages for token counting
const threadMessages = useMessages(
@@ -132,7 +145,6 @@ const ChatInput = ({
const selectedModel = useModelProvider((state) => state.selectedModel)
const selectedProvider = useModelProvider((state) => state.selectedProvider)
- const legacySendMessage = useChat()
const [message, setMessage] = useState('')
const [dropdownToolsAvailable, setDropdownToolsAvailable] = useState(false)
const [tooltipToolsAvailable, setTooltipToolsAvailable] = useState(false)
@@ -288,7 +300,7 @@ const ChatInput = ({
setMessage('')
- // Use onSubmit prop if available (AI SDK), otherwise fall back to legacy hook
+ // Use onSubmit prop if available (AI SDK), otherwise create thread and navigate
if (onSubmit) {
// Build file parts for AI SDK
const files = attachments
@@ -300,15 +312,84 @@ const ChatInput = ({
}))
onSubmit(prompt, files.length > 0 ? files : undefined)
+ setPrompt('')
} else {
- // Fall back to legacy sendMessage for complex scenarios
- legacySendMessage(
- prompt,
- true,
- attachments.length > 0 ? attachments : undefined,
- projectId,
- updateAttachmentProcessing
+ // No onSubmit provided - create a new thread and navigate to it
+ // Store the initial message in sessionStorage for the thread page to read
+ const isTemporaryChat = window.location.search.includes(
+ `${TEMPORARY_CHAT_QUERY_ID}=true`
)
+
+ // Build message payload with attachments
+ const files = attachments
+ .filter((att) => att.type === 'image' && att.dataUrl)
+ .map((att) => ({
+ type: 'file',
+ mediaType: att.mimeType ?? 'image/jpeg',
+ url: att.dataUrl!,
+ }))
+
+ const messagePayload = {
+ text: prompt,
+ files: files.length > 0 ? files : [],
+ }
+
+ if (isTemporaryChat) {
+ // For temporary chat, store message and navigate to temporary thread
+ sessionStorage.setItem(
+ SESSION_STORAGE_KEY.INITIAL_MESSAGE_TEMPORARY,
+ JSON.stringify(messagePayload)
+ )
+ sessionStorage.setItem('temp-chat-nav', 'true')
+ router.navigate({
+ to: route.threadsDetail,
+ params: { threadId: TEMPORARY_CHAT_ID },
+ })
+ } else {
+ // Create a new thread and navigate to it
+ const assistant = assistants.find((a) => a.id === currentAssistant?.id) || assistants[0]
+
+ // Get project metadata if projectId is provided
+ let projectMetadata: { id: string; name: string; updated_at: number } | undefined
+ if (projectId) {
+ try {
+ const project = await serviceHub.projects().getProjectById(projectId)
+ if (project) {
+ projectMetadata = {
+ id: project.id,
+ name: project.name,
+ updated_at: project.updated_at,
+ }
+ }
+ } catch (e) {
+ console.warn('Failed to fetch project metadata:', e)
+ }
+ }
+
+ const newThread = await createThread(
+ {
+ id: selectedModel?.id ?? defaultModel(selectedProvider),
+ provider: selectedProvider,
+ },
+ prompt, // Use prompt as thread title
+ assistant,
+ projectMetadata
+ )
+
+ // Store the initial message for the new thread
+ sessionStorage.setItem(
+ `${SESSION_STORAGE_PREFIX.INITIAL_MESSAGE}${newThread.id}`,
+ JSON.stringify(messagePayload)
+ )
+
+ router.navigate({
+ to: route.threadsDetail,
+ params: { threadId: newThread.id },
+ })
+ }
+
+ setPrompt('')
+ clearAttachmentsForThread(attachmentsKey)
}
}
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index f920eb319..b7f0aae42 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -20,7 +20,6 @@ import { CopyButton } from './CopyButton'
import { AvatarEmoji } from '@/containers/AvatarEmoji'
import { useModelProvider } from '@/hooks/useModelProvider'
import { IconRefresh } from '@tabler/icons-react'
-import { useTranslation } from '@/i18n/react-i18next-compat'
import TokenSpeedIndicator from '@/containers/TokenSpeedIndicator'
const CHAT_STATUS = {
@@ -53,7 +52,6 @@ export type MessageItemProps = {
export const MessageItem = memo(
({
message,
- isFirstMessage,
isLastMessage,
status,
reasoningContainerRef,
@@ -61,7 +59,6 @@ export const MessageItem = memo(
assistant,
showAssistant,
}: MessageItemProps) => {
- const { t } = useTranslation()
const selectedModel = useModelProvider((state) => state.selectedModel)
const [previewImage, setPreviewImage] = useState<{
url: string
diff --git a/web-app/src/hooks/use-chat.ts b/web-app/src/hooks/use-chat.ts
index a8bc3fa15..78588953c 100644
--- a/web-app/src/hooks/use-chat.ts
+++ b/web-app/src/hooks/use-chat.ts
@@ -86,6 +86,13 @@ export function useChat(model: LanguageModel | null, options?: CustomChatOptions
}
}, [onTokenUsage]);
+ // Update the onFinish callback when it changes
+ useEffect(() => {
+ if (transportRef.current) {
+ transportRef.current.setOnFinish(onFinish);
+ }
+ }, [onFinish]);
+
// Set up streaming token speed callback to update global state
const setTokenSpeed = useAppState((state) => state.setTokenSpeed);
const resetTokenSpeed = useAppState((state) => state.resetTokenSpeed);
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 6c6940e4e..d1f8284b0 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -13,6 +13,7 @@ import {
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
// import { mcpService } from "@/services/mcp-service";
/**
@@ -149,6 +150,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
private tools: Record<string, Tool> = {}
private onTokenUsage?: TokenUsageCallback
private onStreamingTokenSpeed?: StreamingTokenSpeedCallback
+ private onFinishCallback?: OnFinishCallback
constructor(model: LanguageModel, onTokenUsage?: TokenUsageCallback) {
this.model = model
@@ -168,6 +170,10 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
this.onStreamingTokenSpeed = callback
}
+ setOnFinish(callback: OnFinishCallback | undefined) {
+ this.onFinishCallback = callback
+ }
+
/**
* Initialize MCP tools and convert them to AI SDK format
* Search tools (google_search, scrape) are always included regardless of user toggle
@@ -341,6 +347,10 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
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/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index b52f018d2..0fb44381f 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -24,7 +24,12 @@ import { useSmallScreen, useMobileScreen } from '@/hooks/useMediaQuery'
import { useTools } from '@/hooks/useTools'
import { PlatformFeatures } from '@/lib/platform/const'
import { PlatformFeature } from '@/lib/platform/types'
-import { TEMPORARY_CHAT_ID, TEMPORARY_CHAT_QUERY_ID } from '@/constants/chat'
+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,
@@ -44,6 +49,8 @@ import { lastAssistantMessageIsCompleteWithToolCalls } from 'ai'
import type { UIMessage, UIDataTypes, UITools } from 'ai'
import { useChatSessions } from '@/stores/chat-session-store'
import { convertThreadMessagesToUIMessages } from '@/lib/messages'
+import { newUserThreadContent, newAssistantThreadContent } from '@/lib/completion'
+import { createImageAttachment } from '@/types/attachment'
const CHAT_STATUS = {
STREAMING: 'streaming',
@@ -107,6 +114,7 @@ function ThreadDetail() {
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 chatWidth = useInterfaceSettings((state) => state.chatWidth)
const isSmallScreen = useSmallScreen()
@@ -183,66 +191,83 @@ function ThreadDetail() {
getProviderByName,
])
- // Handle onFinish - execute collected tool calls
- const handleOnFinish = useCallback(() => {
- // Create a new AbortController for tool calls
- toolCallAbortController.current = new AbortController()
- const signal = toolCallAbortController.current.signal
-
- // Execute all collected tool calls
- Promise.all(
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- sessionData.tools.map(async (toolCall: any) => {
- // Check if already aborted before starting
- if (signal.aborted) {
- return
+ // Handle onFinish - persist assistant message and execute collected tool calls
+ const handleOnFinish = useCallback(
+ ({ message, isAbort }: { message: UIMessage; isAbort?: boolean }) => {
+ // 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)
+ addMessage(assistantMessage)
}
+ }
- try {
- const result = await serviceHub.mcp().callTool({
- toolName: toolCall.toolName,
- arguments: toolCall.input,
- })
+ // Create a new AbortController for tool calls
+ toolCallAbortController.current = new AbortController()
+ const signal = toolCallAbortController.current.signal
- if (result.error) {
- addToolOutput({
- state: 'output-error',
- tool: toolCall.toolName,
- toolCallId: toolCall.toolCallId,
- errorText: `Error: ${result.error}`,
- })
- } else {
- addToolOutput({
- tool: toolCall.toolName,
- toolCallId: toolCall.toolCallId,
- output: result.content,
+ // Execute all collected tool calls
+ Promise.all(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ sessionData.tools.map(async (toolCall: any) => {
+ // Check if already aborted before starting
+ if (signal.aborted) {
+ return
+ }
+
+ try {
+ const result = await serviceHub.mcp().callTool({
+ toolName: toolCall.toolName,
+ arguments: toolCall.input,
})
+
+ if (result.error) {
+ addToolOutput({
+ state: 'output-error',
+ tool: toolCall.toolName,
+ toolCallId: toolCall.toolCallId,
+ errorText: `Error: ${result.error}`,
+ })
+ } else {
+ addToolOutput({
+ tool: toolCall.toolName,
+ toolCallId: toolCall.toolCallId,
+ output: result.content,
+ })
+ }
+ } catch (error) {
+ // Ignore abort errors
+ if ((error as Error).name !== 'AbortError') {
+ console.error('Tool call error:', error)
+ addToolOutput({
+ state: 'output-error',
+ tool: toolCall.toolName,
+ toolCallId: toolCall.toolCallId,
+ errorText: `Error: ${(error as Error).message}`,
+ })
+ }
}
- } catch (error) {
+ })
+ )
+ .catch((error) => {
// Ignore abort errors
- if ((error as Error).name !== 'AbortError') {
+ if (error.name !== 'AbortError') {
console.error('Tool call error:', error)
- addToolOutput({
- state: 'output-error',
- tool: toolCall.toolName,
- toolCallId: toolCall.toolCallId,
- errorText: `Error: ${(error as Error).message}`,
- })
}
- }
- })
- )
- .catch((error) => {
- // Ignore abort errors
- if (error.name !== 'AbortError') {
- console.error('Tool call error:', error)
- }
- })
- .finally(() => {
- sessionData.tools = []
- toolCallAbortController.current = null
- })
- }, [sessionData, serviceHub])
+ })
+ .finally(() => {
+ sessionData.tools = []
+ toolCallAbortController.current = null
+ })
+ },
+ [sessionData, serviceHub, threadId, addMessage]
+ )
// Handle onToolCall - collect tool calls during streaming
const handleOnToolCall = useCallback(
@@ -380,6 +405,72 @@ function ThreadDetail() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
+ // Check for and send initial message from sessionStorage
+ const initialMessageSentRef = useRef(false)
+ useEffect(() => {
+ // Prevent duplicate sends
+ 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 storedMessage = sessionStorage.getItem(initialMessageKey)
+
+ if (storedMessage) {
+ 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
+ })
+ })
+
+ // 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,
+ })
+ })
+ }
+
+ // Send the message
+ sendMessage({ parts })
+ } catch (error) {
+ console.error('Failed to parse initial message:', error)
+ sessionStorage.removeItem(initialMessageKey)
+ }
+ }
+ }, [threadId, languageModel, sendMessage, addMessage])
+
// Handle submit from ChatInput
const handleSubmit = useCallback(
(
@@ -388,6 +479,23 @@ function ThreadDetail() {
) => {
if (!languageModel) return
+ // Convert files to attachments for persistence
+ const attachments = 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),
+ })
+ })
+
+ // Persist user message to backend
+ const userMessage = newUserThreadContent(threadId, text, attachments)
+ addMessage(userMessage)
+
+ // Build parts for AI SDK
const parts: Array<
| { type: 'text'; text: string }
| { type: 'file'; mediaType: string; url: string }
@@ -405,7 +513,7 @@ function ThreadDetail() {
sendMessage({ parts })
},
- [languageModel, sendMessage]
+ [languageModel, sendMessage, threadId, addMessage]
)
// Handle regenerate from ThreadContent