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: ai-sdk

Louis156d321ceba2
diff --git a/web-app/package.json b/web-app/package.json
index bde0b67aa..e3e3ee144 100644
--- a/web-app/package.json
+++ b/web-app/package.json
@@ -18,6 +18,8 @@
"build:serve:web": "yarn build:web && yarn serve:web"
},
"dependencies": {
+ "@ai-sdk/openai-compatible": "^1.0.28",
+ "@ai-sdk/react": "^2.0.109",
"@dnd-kit/core": "6.3.1",
"@dnd-kit/modifiers": "9.0.0",
"@dnd-kit/sortable": "10.0.0",
diff --git a/web-app/src/containers/CopyButton.tsx b/web-app/src/containers/CopyButton.tsx
new file mode 100644
index 000000000..f9eb9ed57
--- /dev/null
+++ b/web-app/src/containers/CopyButton.tsx
@@ -0,0 +1,38 @@
+import { useTranslation } from "@/i18n"
+import { Tooltip, TooltipContent, TooltipTrigger } from "@radix-ui/react-tooltip"
+import { IconCopy, IconCopyCheck } from "@tabler/icons-react"
+import { useState } from "react"
+
+export const CopyButton = ({ text }: { text: string }) => {
+ const [copied, setCopied] = useState(false)
+ const { t } = useTranslation()
+
+ const handleCopy = () => {
+ navigator.clipboard.writeText(text)
+ setCopied(true)
+ setTimeout(() => setCopied(false), 2000)
+ }
+
+ return (
+ <button
+ className="flex items-center gap-1 hover:text-accent transition-colors group relative cursor-pointer"
+ onClick={handleCopy}
+ >
+ {copied ? (
+ <>
+ <IconCopyCheck size={16} className="text-accent" />
+ <span className="opacity-100">{t('copied')}</span>
+ </>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconCopy size={16} />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{t('copy')}</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </button>
+ )
+}
diff --git a/web-app/src/containers/ThreadContent.tsx b/web-app/src/containers/ThreadContent.tsx
index 372523e68..6783259ac 100644
--- a/web-app/src/containers/ThreadContent.tsx
+++ b/web-app/src/containers/ThreadContent.tsx
@@ -61,40 +61,8 @@ import {
ToolInput,
ToolOutput,
} from '@/ai-elements/tool'
+import { CopyButton } from './CopyButton'
-const CopyButton = ({ text }: { text: string }) => {
- const [copied, setCopied] = useState(false)
- const { t } = useTranslation()
-
- const handleCopy = () => {
- navigator.clipboard.writeText(text)
- setCopied(true)
- setTimeout(() => setCopied(false), 2000)
- }
-
- return (
- <button
- className="flex items-center gap-1 hover:text-accent transition-colors group relative cursor-pointer"
- onClick={handleCopy}
- >
- {copied ? (
- <>
- <IconCopyCheck size={16} className="text-accent" />
- <span className="opacity-100">{t('copied')}</span>
- </>
- ) : (
- <Tooltip>
- <TooltipTrigger asChild>
- <IconCopy size={16} />
- </TooltipTrigger>
- <TooltipContent>
- <p>{t('copy')}</p>
- </TooltipContent>
- </Tooltip>
- )}
- </button>
- )
-}
// Use memo to prevent unnecessary re-renders, but allow re-renders when props change
export const ThreadContent = memo(
diff --git a/web-app/src/hooks/use-chat.ts b/web-app/src/hooks/use-chat.ts
new file mode 100644
index 000000000..2ae59aff8
--- /dev/null
+++ b/web-app/src/hooks/use-chat.ts
@@ -0,0 +1,86 @@
+import { CustomChatTransport } from "@/lib/custom-chat-transport";
+// import { useCapabilities } from "@/stores/capabilities-store";
+import {
+ Chat,
+ type UIMessage,
+ type UseChatOptions,
+ useChat as useChatSDK,
+} from "@ai-sdk/react";
+import { type ChatInit, type LanguageModel } from "ai";
+import { useEffect, useMemo, useRef } from "react";
+import { useChatSessions } from "@/stores/chat-session-store";
+
+type CustomChatOptions = Omit<ChatInit<UIMessage>, "transport"> &
+ Pick<UseChatOptions<UIMessage>, "experimental_throttle" | "resume"> & {
+ sessionId?: string;
+ sessionTitle?: string;
+ };
+
+// 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, 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, ...chatInitOptions } =
+ 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;
+
+ if (!transportRef.current) {
+ transportRef.current =
+ existingSessionTransport ??
+ new CustomChatTransport(
+ model,
+ );
+ } else if (
+ existingSessionTransport &&
+ transportRef.current !== existingSessionTransport
+ ) {
+ transportRef.current = existingSessionTransport;
+ }
+
+ useEffect(() => {
+ if (transportRef.current) {
+ transportRef.current.updateModel(model);
+ }
+ }, [model]);
+
+ // Memoize to prevent calling ensureSession (which has side effects) on every render
+ const chat = useMemo(() => {
+ if (!sessionId || !transportRef.current) return undefined;
+ return ensureSession(
+ sessionId,
+ transportRef.current,
+ () => new Chat({ ...chatInitOptions, transport: transportRef.current }),
+ sessionTitle,
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [sessionId, ensureSession]);
+
+ useEffect(() => {
+ if (sessionId && sessionTitle) {
+ setSessionTitle(sessionId, sessionTitle);
+ }
+ }, [sessionId, sessionTitle, setSessionTitle]);
+
+ const chatResult = useChatSDK({
+ ...(chat
+ ? { chat }
+ : { transport: transportRef.current, ...chatInitOptions }),
+ experimental_throttle,
+ resume: false,
+ });
+
+ useEffect(() => {
+ if (sessionId) {
+ updateStatus(sessionId, chatResult.status);
+ }
+ }, [sessionId, chatResult.status, updateStatus]);
+
+ return chatResult;
+}
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
new file mode 100644
index 000000000..a1f558fd1
--- /dev/null
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -0,0 +1,264 @@
+import { type UIMessage } from '@ai-sdk/react'
+import {
+ convertToModelMessages,
+ streamText,
+ type ChatRequestOptions,
+ type ChatTransport,
+ type LanguageModel,
+ type UIMessageChunk,
+ type Tool,
+ type CoreMessage,
+} from 'ai'
+// import { mcpService } from "@/services/mcp-service";
+
+/**
+ * Custom download function that returns null for all URLs.
+ * This tells the AI SDK to pass URLs directly to the model
+ * instead of downloading and converting to base64.
+ *
+ * This avoids CORS issues with presigned S3 URLs and reduces payload size.
+ */
+async function passUrlsDirectly(
+ options: Array<{ url: URL; isUrlSupportedByModel: boolean }>
+): Promise<Array<{ data: Uint8Array; mediaType: string | undefined } | null>> {
+ // Return null for all URLs to pass them directly to the model
+ return options.map(() => null)
+}
+
+/**
+ * Convert file parts to custom image_url format for the API.
+ * The server expects: { type: "image_url", image_url: { url: "<image url>", detail: "auto" } }
+ */
+function convertToImageUrlFormat(messages: CoreMessage[]): CoreMessage[] {
+ return messages.map((message) => {
+ if (message.role === 'user' && Array.isArray(message.content)) {
+ return {
+ ...message,
+ content: message.content.map((part) => {
+ // Convert image parts to image_url format
+ if (part.type === 'image' && 'image' in part) {
+ const imageData = part.image
+ // If it's a URL string
+ if (typeof imageData === 'string') {
+ return {
+ type: 'image_url',
+ image_url: {
+ url: imageData,
+ detail: 'auto',
+ },
+ }
+ }
+ }
+ return part
+ }),
+ }
+ }
+ return message
+ }) as CoreMessage[]
+}
+
+/**
+ * Filter out base64 image data from tool messages to reduce payload size.
+ * Browser MCP tools return screenshots as base64 which are very large.
+ * We replace them with a placeholder to avoid sending huge payloads to the API.
+ */
+function filterBase64FromMessages(messages: CoreMessage[]): CoreMessage[] {
+ const base64Pattern = /data:image\/[^;]+;base64,[A-Za-z0-9+/=]{100,}/g
+
+ return messages.map((message) => {
+ if (message.role === 'tool') {
+ // Tool messages have content as array of ToolResultPart
+ if (Array.isArray(message.content)) {
+ return {
+ ...message,
+ content: message.content.map((part) => {
+ // ToolResultPart has type 'tool-result' with a result property
+ // The result can contain text with embedded base64
+ if ('result' in part && part.result) {
+ const resultStr =
+ typeof part.result === 'string'
+ ? part.result
+ : JSON.stringify(part.result)
+
+ if (base64Pattern.test(resultStr)) {
+ return {
+ ...part,
+ result: resultStr.replace(
+ base64Pattern,
+ '[base64 image data removed]'
+ ),
+ }
+ }
+ }
+ return part
+ }),
+ }
+ }
+ }
+
+ // Handle user messages with image parts
+ if (message.role === 'user' && Array.isArray(message.content)) {
+ return {
+ ...message,
+ content: message.content.map((part) => {
+ // Check for image parts with base64 data
+ if (part.type === 'image') {
+ const imageData = 'image' in part ? part.image : null
+ if (
+ typeof imageData === 'string' &&
+ (imageData.startsWith('data:') || imageData.length > 10000)
+ ) {
+ // Replace with placeholder text
+ return {
+ type: 'text',
+ text: `[Image: screenshot captured]`,
+ }
+ }
+ }
+ // Check for text parts with embedded base64
+ if (
+ part.type === 'text' &&
+ 'text' in part &&
+ typeof part.text === 'string'
+ ) {
+ if (base64Pattern.test(part.text)) {
+ return {
+ ...part,
+ text: part.text.replace(
+ base64Pattern,
+ '[base64 image data removed]'
+ ),
+ }
+ }
+ }
+ return part
+ }),
+ }
+ }
+
+ return message
+ })
+}
+
+export class CustomChatTransport implements ChatTransport<UIMessage> {
+ private model: LanguageModel
+ private tools: Record<string, Tool> = {}
+
+ constructor(
+ model: LanguageModel,
+ ) {
+ this.model = model
+ // this.initializeTools();
+ }
+
+ updateModel(model: LanguageModel) {
+ this.model = model
+ }
+
+ /**
+ * Initialize MCP tools and convert them to AI SDK format
+ * Search tools (google_search, scrape) are always included regardless of user toggle
+ */
+ // 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 = {};
+ // }
+ // }
+
+ async sendMessages(
+ options: {
+ chatId: string
+ messages: UIMessage[]
+ abortSignal: AbortSignal | undefined
+ } & {
+ trigger: 'submit-message' | 'regenerate-message'
+ messageId: string | undefined
+ } & ChatRequestOptions
+ ): Promise<ReadableStream<UIMessageChunk>> {
+ // await this.initializeTools();
+
+ // Convert UI messages to model messages
+ const modelMessages = convertToModelMessages(options.messages)
+
+ // Filter out base64 data from tool results
+ const filteredMessages = filterBase64FromMessages(modelMessages)
+
+ // 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
+ const hasTools = Object.keys(this.tools).length > 0
+ const result = streamText({
+ model: this.model,
+ messages: messagesWithImageUrls,
+ abortSignal: options.abortSignal,
+ // Pass URLs directly to the model instead of downloading
+ // This avoids CORS issues with presigned S3 URLs
+ experimental_download: passUrlsDirectly,
+ tools: hasTools ? this.tools : undefined,
+ toolChoice: 'auto',
+ })
+
+ return result.toUIMessageStream({
+ onError: (error) => {
+ // Note: By default, the AI SDK will return "An error occurred",
+ // which is intentionally vague in case the error contains sensitive information like API keys.
+ // If you want to provide more detailed error messages, keep the code below. Otherwise, remove this whole onError callback.
+ if (error == null) {
+ return 'Unknown error'
+ }
+ if (typeof error === 'string') {
+ return error
+ }
+ if (error instanceof Error) {
+ return error.message
+ }
+ return JSON.stringify(error)
+ },
+ })
+ }
+
+ async reconnectToStream(
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _options: {
+ chatId: string
+ } & ChatRequestOptions
+ ): Promise<ReadableStream<UIMessageChunk> | null> {
+ // This function normally handles reconnecting to a stream on the backend, e.g. /api/chat
+ // Since this project has no backend, we can't reconnect to a stream, so this is intentionally no-op.
+ return null
+ }
+}
diff --git a/web-app/src/lib/messages.ts b/web-app/src/lib/messages.ts
index 27861056e..32ac2c546 100644
--- a/web-app/src/lib/messages.ts
+++ b/web-app/src/lib/messages.ts
@@ -272,3 +272,43 @@ export class CompletionMessagesBuilder {
return result
}
}
+
+/**
+ * Parse reasoning segments from the given text.
+ * @param text - The text to parse reasoning from.
+ * @returns
+ */
+export const parseReasoning = (text: string) => {
+ // Check for thinking formats
+ const hasThinkTag = text.includes('<think>') && !text.includes('</think>')
+ const hasAnalysisChannel =
+ text.includes('<|channel|>analysis<|message|>') &&
+ !text.includes('<|start|>assistant<|channel|>final<|message|>')
+
+ if (hasThinkTag || hasAnalysisChannel)
+ return { reasoningSegment: text, textSegment: '' }
+
+ // Check for completed think tag format
+ const thinkMatch = text.match(/<think>([\s\S]*?)<\/think>/)
+ if (thinkMatch?.index !== undefined) {
+ const splitIndex = thinkMatch.index + thinkMatch[0].length
+ return {
+ reasoningSegment: text.slice(0, splitIndex),
+ textSegment: text.slice(splitIndex),
+ }
+ }
+
+ // Check for completed analysis channel format
+ const analysisMatch = text.match(
+ /<\|channel\|>analysis<\|message\|>([\s\S]*?)<\|start\|>assistant<\|channel\|>final<\|message\|>/
+ )
+ if (analysisMatch?.index !== undefined) {
+ const splitIndex = analysisMatch.index + analysisMatch[0].length
+ return {
+ reasoningSegment: text.slice(0, splitIndex),
+ textSegment: text.slice(splitIndex),
+ }
+ }
+
+ return { reasoningSegment: undefined, textSegment: text }
+}
diff --git a/web-app/src/stores/chat-session-store.ts b/web-app/src/stores/chat-session-store.ts
new file mode 100644
index 000000000..1a92545b4
--- /dev/null
+++ b/web-app/src/stores/chat-session-store.ts
@@ -0,0 +1,250 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { create } from "zustand";
+import type { Chat, UIMessage } from "@ai-sdk/react";
+import type { ChatStatus } from "ai";
+import { CustomChatTransport } from "@/lib/custom-chat-transport";
+// import { showChatCompletionToast } from "@/components/toasts/chat-completion-toast";
+
+export type SessionData = {
+ tools: any[];
+ messages: UIMessage[];
+ idMap: Map<string, string>;
+};
+
+export type ChatSession = {
+ chat: Chat<UIMessage>;
+ transport: CustomChatTransport;
+ status: ChatStatus;
+ title?: string;
+ isStreaming: boolean;
+ unsubscribers: Array<() => void>;
+ data: SessionData;
+};
+
+interface ChatSessionState {
+ sessions: Record<string, ChatSession>;
+ activeConversationId?: string;
+ setActiveConversationId: (conversationId?: string) => void;
+ ensureSession: (
+ sessionId: string,
+ transport: CustomChatTransport,
+ createChat: () => Chat<UIMessage>,
+ title?: string,
+ ) => Chat<UIMessage>;
+ getSessionData: (sessionId: string) => SessionData;
+ updateStatus: (sessionId: string, status: ChatStatus) => void;
+ setSessionTitle: (sessionId: string, title?: string) => void;
+ removeSession: (sessionId: string) => void;
+ clearSessions: () => void;
+}
+
+const STREAMING_STATUSES: ChatStatus[] = [
+ 'submitted',
+ 'streaming',
+];
+
+// Pure helper function for checking if a session is busy (for reactive use in components)
+export function isSessionBusy(session: ChatSession | undefined): boolean {
+ return session?.isStreaming || (session?.data?.tools?.length ?? 0) > 0;
+}
+
+const createSessionData = (): SessionData => ({
+ tools: [],
+ messages: [],
+ idMap: new Map<string, string>(),
+});
+
+// Standalone data store for sessions that don't have a Chat yet
+const standaloneData: Record<string, SessionData> = {};
+
+export const useChatSessions = create<ChatSessionState>((set, get) => ({
+ sessions: {},
+ activeConversationId: undefined,
+ setActiveConversationId: (conversationId) =>
+ set({ activeConversationId: conversationId }),
+ ensureSession: (sessionId, transport, createChat, title) => {
+ // Set active immediately - prevents toast for this session during status sync
+ // Only update activeConversationId if it changed (avoid unnecessary state updates during render)
+ if (get().activeConversationId !== sessionId) {
+ set({ activeConversationId: sessionId });
+ }
+
+ const existing = get().sessions[sessionId];
+ if (existing) {
+ // Keep transport and title in sync if they changed
+ if (existing.transport !== transport || existing.title !== title) {
+ set((state) => ({
+ sessions: {
+ ...state.sessions,
+ [sessionId]: {
+ ...existing,
+ transport,
+ title: title ?? existing.title,
+ },
+ },
+ }));
+ }
+ return existing.chat;
+ }
+
+ const chat = createChat();
+ const syncStatus = () => {
+ get().updateStatus(sessionId, chat.status);
+ };
+ const unsubscribeStatus = chat["~registerStatusCallback"]
+ ? chat["~registerStatusCallback"](syncStatus)
+ : undefined;
+
+ // Use existing standalone data if available, otherwise create new
+ const data = standaloneData[sessionId] ?? createSessionData();
+ delete standaloneData[sessionId]; // Move to session
+
+ const newSession: ChatSession = {
+ chat,
+ transport,
+ status: chat.status,
+ title,
+ isStreaming: STREAMING_STATUSES.includes(chat.status),
+ unsubscribers: unsubscribeStatus ? [unsubscribeStatus] : [],
+ data,
+ };
+
+ set((state) => ({
+ sessions: {
+ ...state.sessions,
+ [sessionId]: newSession,
+ },
+ }));
+
+ return chat;
+ },
+ getSessionData: (sessionId) => {
+ const existing = get().sessions[sessionId];
+ if (existing) {
+ return existing.data;
+ }
+ // Return or create standalone data for sessions without a Chat yet
+ if (!standaloneData[sessionId]) {
+ standaloneData[sessionId] = createSessionData();
+ }
+ return standaloneData[sessionId];
+ },
+ updateStatus: (sessionId, status) => {
+ set((state) => {
+ const existing = state.sessions[sessionId];
+ if (!existing) {
+ return state;
+ }
+
+ const wasStreaming = existing.isStreaming;
+ const isStreaming = STREAMING_STATUSES.includes(status);
+ if (existing.status === status && wasStreaming === isStreaming) {
+ return state;
+ }
+
+ // Only notify if:
+ // 1. Was streaming and now stopped
+ // 2. Not the active conversation
+ // 3. Chat has messages (not a brand new session)
+ // 4. No pending tool calls (tools are still being executed)
+ // const hasMessages = existing.chat.messages.length > 0;
+ // const hasPendingTools = existing.data.tools.length > 0;
+ // const shouldNotify =
+ // wasStreaming &&
+ // !isStreaming &&
+ // hasMessages &&
+ // !hasPendingTools &&
+ // state.activeConversationId !== sessionId;
+
+ // if (shouldNotify) {
+ // const title = existing.title ?? "Conversation";
+ // showChatCompletionToast(title, existing.chat.messages, sessionId);
+ // }
+
+ return {
+ sessions: {
+ ...state.sessions,
+ [sessionId]: {
+ ...existing,
+ status,
+ isStreaming,
+ },
+ },
+ };
+ });
+ },
+ setSessionTitle: (sessionId, title) => {
+ if (!title) return;
+
+ set((state) => {
+ const existing = state.sessions[sessionId];
+ if (!existing || existing.title === title) {
+ return state;
+ }
+
+ return {
+ sessions: {
+ ...state.sessions,
+ [sessionId]: { ...existing, title },
+ },
+ };
+ });
+ },
+ removeSession: (sessionId) => {
+ const existing = get().sessions[sessionId];
+ if (!existing) {
+ delete standaloneData[sessionId];
+ return;
+ }
+
+ // Remove from store FIRST - prevents updateStatus from showing toast during cleanup
+ set((state) => {
+ if (!state.sessions[sessionId]) {
+ return state;
+ }
+ const rest = { ...state.sessions };
+ delete rest[sessionId];
+ return { sessions: rest };
+ });
+
+ // Then cleanup (existing is a copy, safe to use after removal)
+ existing.unsubscribers.forEach((unsubscribe) => {
+ try {
+ unsubscribe();
+ } catch (error) {
+ console.error("Failed to unsubscribe chat session listener", error);
+ }
+ });
+ try {
+ existing.chat.stop();
+ } catch (error) {
+ console.error("Failed to stop chat session", error);
+ }
+
+ delete standaloneData[sessionId];
+ },
+ clearSessions: () => {
+ const sessions = get().sessions;
+ Object.values(sessions).forEach((session) => {
+ session.unsubscribers.forEach((unsubscribe) => {
+ try {
+ unsubscribe();
+ } catch (error) {
+ console.error("Failed to unsubscribe chat session listener", error);
+ }
+ });
+ try {
+ session.chat.stop();
+ } catch (error) {
+ console.error("Failed to stop chat session", error);
+ }
+ });
+
+ // Clear standalone data
+ Object.keys(standaloneData).forEach((key) => {
+ delete standaloneData[key];
+ });
+
+ set({ sessions: {}, activeConversationId: undefined });
+ },
+}));