import { ScrollArea } from '@/ui/components/ui/scroll-area' import { cn } from '@/ui/lib/utils' import { m } from '@/ui/paraglide/messages.js' import { useChatbotStore } from '@/ui/stores/chatbot' import { useDroppable } from '@dnd-kit/react' import type { ChatMessage } from '@shumai/dtos' 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, } = useChatbotStore() const [inputText, setInputText] = useState('') const messagesEndRef = useRef(null) const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({ id: 'chatbot-sidebar', data: { type: 'chatbot-sidebar', }, }) // Auto-scroll messages list to bottom useEffect(() => { if (!isHistoryMode) { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }) } }, [messages, isStreaming, isHistoryMode]) // Fetch history when entering history mode useEffect(() => { if (isHistoryMode) { fetchHistorySessions() } }, [isHistoryMode, fetchHistorySessions]) const handleSend = () => { if (!inputText.trim() || isStreaming) return sendMessage(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 && (
                      {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 return (
{renderedBlocks}
{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 (
loadSession(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 */}