import { client } from '@/ui/api/client' import { ScrollArea } from '@/ui/components/ui/scroll-area' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/ui/components/ui/select' import { cn } from '@/ui/lib/utils' import { m } from '@/ui/paraglide/messages.js' import { useChatbotStore } from '@/ui/stores/chatbot' import { useTeamContextStore } from '@/ui/stores/team-context' import { useDroppable } from '@dnd-kit/react' import type { ChatMessage } from '@shumai/dtos' import { useQuery } from '@tanstack/react-query' import { ArrowLeft, ArrowUp, Bot, Brain, ChevronDown, History, Loader2, Plus, Trash2, Wrench, } from 'lucide-react' import { useEffect, useRef, useState } from 'react' import Markdown from 'react-markdown' import { formatTimeAgo } from '../lib/time' interface ChatbotSidebarProps { projectId: string contextAssetId?: string } export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProps) { const { isHistoryMode, setIsHistoryMode, currentSessionId, chatAssets, removeAsset, messages, historySessions, isStreaming, fetchHistorySessions, loadSession, deleteSession, startNewSession, sendMessage, abortActiveSession, selectedAgentId, setSelectedAgentId, } = useChatbotStore() const { teamId, ensureTeamIdForProject } = useTeamContextStore() useEffect(() => { if (projectId) { ensureTeamIdForProject(projectId) } }, [projectId, ensureTeamIdForProject]) const { data: agents = [] } = useQuery({ queryKey: ['agents', teamId], queryFn: async () => { if (!teamId) return [] const res = await client.api.teams[':teamId'].agents.$get({ param: { teamId }, }) if (!res.ok) throw new Error('failed to fetch agents') return res.json() }, enabled: !!teamId, }) const chatAgents = agents.filter((a) => a.type === 'chat' && a.enabled) useEffect(() => { if (chatAgents.length > 0) { const exists = chatAgents.some((a) => a.id === selectedAgentId) if (!exists) { setSelectedAgentId(chatAgents[0].id) } } }, [chatAgents, selectedAgentId, setSelectedAgentId]) const [inputText, setInputText] = useState('') const messagesEndRef = useRef(null) const scrollAreaRef = useRef(null) const isFirstScrollRef = useRef(true) const isRestoringRef = useRef(true) useEffect(() => { isRestoringRef.current = true isFirstScrollRef.current = true }, [projectId, contextAssetId, isHistoryMode]) // Restore scroll position on mount or when navigation changes the project/context useEffect(() => { const viewport = scrollAreaRef.current?.querySelector('[data-slot="scroll-area-viewport"]') if (!viewport) return const { scrollTop, isAtBottom } = useChatbotStore.getState() // Use a timeout to ensure the DOM has settled and scrollHeight is fully calculated const timer = setTimeout(() => { if (isAtBottom) { viewport.scrollTop = viewport.scrollHeight } else { viewport.scrollTop = scrollTop } // Allow scroll events triggered by this restoration to fire and be ignored before tracking const enableTimer = setTimeout(() => { isRestoringRef.current = false }, 50) return () => clearTimeout(enableTimer) }, 0) return () => clearTimeout(timer) }, [projectId, contextAssetId, isHistoryMode]) // Listen to scroll events on the viewport to save scroll state useEffect(() => { const viewport = scrollAreaRef.current?.querySelector('[data-slot="scroll-area-viewport"]') if (!viewport) return const handleScroll = () => { if (isRestoringRef.current) return const scrollTop = viewport.scrollTop // We consider the user at the bottom if they are within 10px of the bottom boundary const isAtBottom = viewport.scrollHeight - scrollTop - viewport.clientHeight < 10 useChatbotStore.getState().setScrollState(scrollTop, isAtBottom) } viewport.addEventListener('scroll', handleScroll) return () => { viewport.removeEventListener('scroll', handleScroll) } }, [projectId, contextAssetId, isHistoryMode]) const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({ id: 'chatbot-sidebar', data: { type: 'chatbot-sidebar', }, }) // Auto-scroll messages list to bottom useEffect(() => { if (!isHistoryMode) { const { isAtBottom } = useChatbotStore.getState() if (isAtBottom || isStreaming) { const behavior = isFirstScrollRef.current ? 'auto' : 'smooth' messagesEndRef.current?.scrollIntoView({ behavior }) } isFirstScrollRef.current = false } }, [messages, isStreaming, isHistoryMode]) // Fetch history when entering history mode useEffect(() => { if (isHistoryMode && teamId) { fetchHistorySessions(teamId) } }, [isHistoryMode, fetchHistorySessions, teamId]) const handleSend = () => { if (!inputText.trim() || isStreaming || !teamId) return sendMessage(teamId, inputText, projectId, contextAssetId) setInputText('') } const handleKeyDown = (e: React.KeyboardEvent) => { if (e.nativeEvent.isComposing) return if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault() handleSend() } } const getMessageText = (content: unknown): string => { if (typeof content === 'string') return content if (Array.isArray(content)) { return content .map((c) => { if (typeof c === 'string') return c if (c && typeof c === 'object' && 'type' in c && c.type === 'text' && 'text' in c) { return String((c as { text: unknown }).text) } return '' }) .join('') } return '' } const preprocessMarkdown = (text: string): string => { return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:') } const renderMessage = (msg: ChatMessage) => { switch (msg.role as string) { case 'user': { const msgObj = msg as unknown as Record return (
{getMessageText(msgObj.content)}
) } case 'assistant': { const msgObj = msg as unknown as Record const content = msgObj.content as unknown[] if (!content) return null const renderedBlocks: React.ReactNode[] = [] content.forEach((block: unknown, idx: number) => { if (!block || typeof block !== 'object') return const b = block as unknown as Record switch (b.type) { case 'text': { const text = b.text if (typeof text !== 'string' || !text.trim()) return renderedBlocks.push(
(
                      ),
                    }}
                  >
                    {preprocessMarkdown(text)}
                  
                
, ) break } case 'thinking': { const thinking = b.thinking if (typeof thinking !== 'string' || !thinking.trim()) return renderedBlocks.push(
{m.role_thinking() || 'Thinking'}
{preprocessMarkdown(thinking)}
, ) break } case 'toolCall': { const toolName = String(b.name || b.toolName || m.unknown()) const toolArgs = b.arguments || b.args renderedBlocks.push(
{m.calling_tool()} {toolName} {!!toolArgs && (
{m.tool_arguments() || 'Arguments'}
                        {JSON.stringify(toolArgs, null, 2)}
                      
)}
, ) break } case 'image': { const mimeType = String(b.mimeType || 'image/png') const data = String(b.data || '') renderedBlocks.push(
{data ? ( Attached asset ) : (
{m.image_object()}
)}
, ) break } default: { const stringified = JSON.stringify(block, null, 2) if (stringified === '{}') return renderedBlocks.push(
                  {stringified}
                
, ) } } }) if (renderedBlocks.length === 0) return null let shouldShowFooter = false if (content.length > 0) { const lastBlock = content[content.length - 1] if (typeof lastBlock === 'string' && lastBlock.trim().length > 0) { shouldShowFooter = true } else if (lastBlock && typeof lastBlock === 'object') { const lb = lastBlock as Record if (lb.type === 'text' && typeof lb.text === 'string' && lb.text.trim().length > 0) { shouldShowFooter = true } } } return (
{renderedBlocks}
{shouldShowFooter && (
{m.created_by_agent()}
)}
) } case 'toolResult': { return (
{m.tool_result_with_name({ name: (msg as { toolName?: string }).toolName || 'tool' })}
) } case 'thinking_level_change': case 'custom': { const msgObj = msg as unknown as Record if (msgObj.customType === 'context_display_info') { const details = msgObj.details as | { assets?: Array<{ id: string; name: string; type: string }> } | undefined const assets = details?.assets || [] if (assets.length === 0) return null return (
{m.assets_added_to_context()}
    {assets.map((asset) => (
  • {asset.name} ({asset.type})
  • ))}
) } const systemContent = msgObj.content || '' return (
{getMessageText(systemContent)}
) } default: return null } } return (
{isOver && (
{m.chatbot_drag_drop_hint() || 'Drop assets here'}
)} {/* Header section */}
{isHistoryMode ? ( <>
{m.history()}
) : ( <>
{m.shumai_agent()}
)}
{/* Main body view */} {isHistoryMode ? ( {historySessions.length === 0 ? (

{m.no_history_sessions()}

) : (
{historySessions.map((sess) => { const isActive = sess.id === currentSessionId return (
teamId && loadSession(teamId, sess.id)} className="flex-1 min-w-0 pr-6" >
{sess.name || m.new_chat()}
{formatTimeAgo(sess.createdAt)}
) })}
)}
) : ( <> {/* Active Chat view */} {messages.length === 0 ? (

{m.chatbot_drag_drop_hint()}

) : (
{messages.map(renderMessage)} {isStreaming && messages.length > 0 && messages[messages.length - 1].role === 'user' && (
Thinking...
)}
)} {/* Input Area (nested inside the border exactly like comment input) */}
{/* Context assets list at the top inside the border */} {chatAssets.length > 0 && (
{chatAssets.map((asset) => (
{asset.name} {asset.type}
))}
)} {/* Textarea inside the border */}