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 { useUiStore } from '@/ui/stores/ui' import { useDroppable } from '@dnd-kit/react' import type { AssetInfo, ChatMessage, ShumaiMessageContext } from '@shumai/dtos' import { useQuery, useQueryClient } from '@tanstack/react-query' import { ArrowLeft, Bot, Brain, ChevronDown, Download, FileIcon, Folder, History, Loader2, Plus, Trash2, Wrench, XIcon, } from 'lucide-react' import { useCallback, useEffect, useRef, useState } from 'react' import Markdown from 'react-markdown' import { formatTimeAgo } from '../lib/time' import { ChatInput } from './chat/message-input' import { DrawAnnotation } from './ui/icons' import { formatTimecode } from './viewers/video/utils' import { isImageFileName } from '@/ui/lib/media' interface ChatbotSidebarProps { projectId: string contextAssetId?: string file?: AssetInfo | null currentTime?: number frameRate?: number startTimecode?: string formatTimestamp?: (second: number) => string onTyping?: () => void onSelectMessage?: (message: ChatMessage) => void selectedMessageId?: string | null } export function ChatbotSidebar({ projectId, contextAssetId, file, currentTime, frameRate, startTimecode, formatTimestamp, onTyping, onSelectMessage, selectedMessageId, }: ChatbotSidebarProps) { const { isHistoryMode, setIsHistoryMode, currentSessionId, chatAssets, removeAsset, messages, historySessions, isStreaming, fetchHistorySessions, loadSession, deleteSession, startNewSession, sendMessage, abortActiveSession, selectedAgentId, setSelectedAgentId, inputText, setInputText, } = useChatbotStore() const { teamId, ensureTeamIdForProject } = useTeamContextStore() const { videoTimeDisplayMode } = useUiStore() const [previewImage, setPreviewImage] = useState<{ url: string; name: string } | null>(null) useEffect(() => { if (projectId) { ensureTeamIdForProject(projectId) } }, [projectId, ensureTeamIdForProject]) const { data: agents = [], isSuccess } = useQuery({ queryKey: ['chat-agents', projectId], queryFn: async () => { if (!projectId) return [] const res = await client.api.projects[':projectId']['chat-agents'].$get({ param: { projectId }, }) if (!res.ok) throw new Error('failed to fetch agents') return res.json() }, enabled: !!projectId, }) const chatAgents = agents.filter((a) => a.type === 'chat' && a.enabled) useEffect(() => { if (!isSuccess) return if (chatAgents.length > 0) { const exists = chatAgents.some((a) => a.id === selectedAgentId) if (!exists) { setSelectedAgentId(chatAgents[0].id) } } else if (selectedAgentId !== null) { setSelectedAgentId(null) } }, [isSuccess, chatAgents, selectedAgentId, setSelectedAgentId]) 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 queryClient = useQueryClient() const handleAssetMutation = useCallback(() => { queryClient.invalidateQueries({ queryKey: ['search'] }) queryClient.invalidateQueries({ queryKey: ['folders'] }) queryClient.invalidateQueries({ queryKey: ['files'] }) queryClient.invalidateQueries({ queryKey: ['file'] }) queryClient.invalidateQueries({ queryKey: ['version_stacks'] }) queryClient.invalidateQueries({ queryKey: ['projects'] }) }, [queryClient]) 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': case 'custom': { const msgObj = msg as unknown as Record if (msg.role === 'custom' && 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})
  • ))}
) } if (msg.role === 'user' || msgObj.customType === 'shumai_message') { const details = msgObj.details as ShumaiMessageContext | undefined const referencedAssets = details?.referencedAssets || [] const attachedFiles = details?.attachedFiles || [] const position = details?.position const hasAnnotations = details?.annotation || (details?.annotations && details.annotations.length > 0) const isCurrentAssetMatch = !details?.currentAsset?.id || (contextAssetId && details.currentAsset.id === contextAssetId) || (file?.id && details.currentAsset.id === file.id) const isSelected = selectedMessageId === msg.id let timeStr = '' if (position?.type === 'time') { if (formatTimestamp) { timeStr = formatTimestamp(position.seconds) } else if (frameRate) { const frameIndex = Math.round(position.seconds * frameRate) timeStr = formatTimecode(frameIndex, frameRate, videoTimeDisplayMode, startTimecode) } else { const mins = Math.floor(position.seconds / 60) const secs = Math.floor(position.seconds % 60) timeStr = `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}` } } else if (position?.type === 'page') { timeStr = m.page_prefix({ page: position.page }) } const messageText = getMessageText(msgObj.content) const hasAttachmentsOrAssets = attachedFiles.length > 0 || referencedAssets.length > 0 const handleCardClick = () => { if (isCurrentAssetMatch && onSelectMessage) { onSelectMessage(msg) } } return (
{hasAnnotations && ( )} {position && ( {timeStr} )} {messageText && {messageText}}
{attachedFiles.length > 0 && (
{m.attachments()}
{attachedFiles.map((att) => { const name = att.name || 'file' const isImage = isImageFileName(name) || att.mediaType === 'image' || att.mimeType?.startsWith('image/') return (
{ e.stopPropagation() if (att.url) { if (isImage) { setPreviewImage({ url: att.url, name }) } else { window.open(att.url, '_blank', 'noreferrer') } } }} > {isImage && att.url ? (
{name}
) : ( )}

{name}

{att.url && ( e.stopPropagation()} title={m.download()} > )}
) })}
)} {referencedAssets.length > 0 && (
{m.assets()}
{referencedAssets.map((asset) => (
{asset.type === 'folder' ? ( ) : ( )} {asset.name}
{asset.type}
))}
)}
) } const systemContent = msgObj.content || '' return (
{getMessageText(systemContent)}
) } 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': { const msgObj = msg as unknown as Record const systemContent = msgObj.content || '' return (
{getMessageText(systemContent)}
) } default: return null } } return (
{isOver && (
{m.chatbot_drag_drop_hint()}
)} {/* Header */}
{isHistoryMode && ( )} {isHistoryMode ? m.history() : m.shumai_agent()}
{!isHistoryMode ? ( <> ) : ( )}
{/* Body */} {isHistoryMode ? ( {historySessions.length === 0 ? (
{m.no_history_sessions()}
) : (
{historySessions.map((session) => { const isCurrent = session.id === currentSessionId return (
{ if (teamId) { loadSession(teamId, session.id) setIsHistoryMode(false) } }} className={cn( 'group flex items-center justify-between p-2.5 rounded-lg text-xs cursor-pointer transition-all border border-transparent', isCurrent ? 'bg-accent/80 text-accent-foreground font-medium border-border/40' : 'hover:bg-muted/60 text-muted-foreground hover:text-foreground', )} >
{session.name || m.untitled_session()} {formatTimeAgo(session.updatedAt)}
) })}
)}
) : ( <> {messages.length === 0 ? (

{m.chatbot_drag_drop_hint()}

) : (
{messages.map(renderMessage)} {isStreaming && messages.length > 0 && (messages[messages.length - 1].role === 'user' || ( messages[messages.length - 1] as unknown as { customType?: string } ).customType === 'shumai_message') && (
{m.thinking_status()}
)}
)}
{ if (teamId) { abortActiveSession(teamId) } }} allowMentions={false} allowAttachments={true} workspaceAssets={chatAssets} onRemoveWorkspaceAsset={removeAsset} allowMarkup={true} canMarkup={!!file && ['image', 'video', 'pdf'].includes(file.proxyType || '')} markupDisabledTooltip={ !file ? m.open_file_to_add_markup() : m.markup_not_supported_for_this_file() } allowTimestamp={file?.proxyType === 'video' || file?.proxyType === 'pdf'} currentTime={currentTime} frameRate={frameRate || file?.media?.metadata?.frameRate || 30} startTimecode={startTimecode || file?.media?.metadata?.startTimecode} formatTimestamp={ formatTimestamp || (file?.proxyType === 'pdf' ? (sec: number) => m.page_prefix({ page: Math.round(sec) }) : undefined) } onTyping={onTyping} onSendMessage={( text, attachmentIds, annotations, _replyToId, second, attachedFilesMeta, ) => { if (!teamId) return sendMessage( teamId, text, projectId, contextAssetId, handleAssetMutation, attachmentIds, annotations, second, attachedFilesMeta, ) }} bottomLeftExtra={
{chatAgents.length > 0 ? ( ) : (
{m.no_chat_agents_warning()}
)}
} />
)} {previewImage && (
setPreviewImage(null)} >
{previewImage.name} { e.stopPropagation() setPreviewImage(null) }} />
{previewImage.name}
)}
) }