import { useState, useEffect, useRef, useCallback } from 'react' import { useLocation, useNavigate, useParams } from 'react-router-dom' import { Sparkles, Send, Loader2, Flag, MessageSquare, Paperclip, Terminal, X, RotateCcw, ImagePlus } from 'lucide-react' import { cn } from '@/lib/utils' import { uploadsApi } from '@/api/uploads' import type { PendingUpload } from '@/types/upload' import type { ForkMetadata, ActionItem, QuestionItem } from '@/types/ai-session' import { PageMeta } from '@/components/common/PageMeta' import { aiSessionsApi } from '@/api/aiSessions' import { useBranching } from '@/hooks/useBranching' import { analytics } from '@/lib/analytics' import { toast } from '@/lib/toast' import { ChatSidebar, ChatSidebarCollapsedBar } from '@/components/assistant/ChatSidebar' import { ChatMessage } from '@/components/assistant/ChatMessage' import { TaskLane } from '@/components/assistant/TaskLane' import { ConcludeSessionModal } from '@/components/assistant/ConcludeSessionModal' import type { ChatListItem, ConclusionOutcome } from '@/types/assistant-chat' import type { SuggestedFlow } from '@/types/copilot' interface MessageWithMeta { role: 'user' | 'assistant' content: string suggestedFlows?: SuggestedFlow[] fork?: ForkMetadata | null actions?: ActionItem[] | null questions?: QuestionItem[] | null } export default function AssistantChatPage() { const location = useLocation() const navigate = useNavigate() const { sessionId: urlSessionId } = useParams<{ sessionId?: string }>() const [chats, setChats] = useState([]) const [activeChatId, setActiveChatId] = useState(urlSessionId || null) const [messages, setMessages] = useState([]) const [input, setInput] = useState('') const [loading, setLoading] = useState(false) const [showConclude, setShowConclude] = useState(false) const branching = useBranching() const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false) const [showLogs, setShowLogs] = useState(false) const [logContent, setLogContent] = useState('') const [pendingUploads, setPendingUploads] = useState([]) const [isDragOver, setIsDragOver] = useState(false) const [activeQuestions, setActiveQuestions] = useState([]) const [activeActions, setActiveActions] = useState([]) const [showTaskLane, setShowTaskLane] = useState(false) const [sidebarCollapsed, setSidebarCollapsed] = useState(() => localStorage.getItem('rf-chat-sidebar-collapsed') === 'true' ) const toggleSidebarCollapse = () => { const next = !sidebarCollapsed setSidebarCollapsed(next) localStorage.setItem('rf-chat-sidebar-collapsed', String(next)) } const messagesEndRef = useRef(null) const inputRef = useRef(null) const fileInputRef = useRef(null) const dragCounterRef = useRef(0) const prefillHandledRef = useRef(false) // Load chat list from ai_sessions useEffect(() => { loadChats() }, []) // If URL has a session ID, load it useEffect(() => { if (urlSessionId && urlSessionId !== activeChatId) { selectChat(urlSessionId) } }, [urlSessionId]) // eslint-disable-line react-hooks/exhaustive-deps // Handle prefill from command palette / dashboard handoff useEffect(() => { const state = location.state as { prefill?: string; uploadIds?: string[] } | null const prefill = state?.prefill const uploadIds = state?.uploadIds if (!prefill || prefillHandledRef.current) return prefillHandledRef.current = true navigate(location.pathname, { replace: true, state: {} }) const sendPrefill = async () => { try { const session = await aiSessionsApi.createChatSession({ intake_type: 'free_text', intake_content: { text: prefill }, }) const chatItem: ChatListItem = { id: session.session_id, title: session.title, message_count: 0, pinned: false, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), } setChats(prev => [chatItem, ...prev]) setActiveChatId(session.session_id) setMessages([{ role: 'user', content: prefill }]) setLoading(true) const response = await aiSessionsApi.sendChatMessage(session.session_id, { message: prefill, upload_ids: uploadIds?.length ? uploadIds : undefined, }) setMessages(prev => [ ...prev, { role: 'assistant', content: response.content, suggestedFlows: response.suggested_flows, fork: response.fork, actions: response.actions, questions: response.questions }, ]) setChats(prev => prev.map(c => c.id === session.session_id ? { ...c, message_count: 2, title: prefill.slice(0, 100), updated_at: new Date().toISOString() } : c ) ) // Show task lane if AI sent questions or actions if (response.fork && session.session_id) { branching.loadBranches(session.session_id) } const hasQuestions = response.questions && response.questions.length > 0 const hasActions = response.actions && response.actions.length > 0 if (hasQuestions || hasActions) { setActiveQuestions(response.questions || []) setActiveActions(response.actions || []) setShowTaskLane(true) } } catch { toast.error('Failed to start AI conversation') } finally { setLoading(false) } } sendPrefill() // eslint-disable-next-line react-hooks/exhaustive-deps }, []) // Auto-scroll useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [messages]) const loadChats = async () => { try { const sessions = await aiSessionsApi.listSessions({ session_type: 'chat', limit: 100 }) setChats(sessions.map(s => ({ id: s.id, title: s.title || s.problem_summary || 'New Chat', message_count: s.step_count, pinned: false, created_at: s.created_at, updated_at: s.created_at, }))) } catch { // silently handle } } const selectChat = useCallback(async (chatId: string) => { setActiveChatId(chatId) // Clear TaskLane when switching chats setShowTaskLane(false) setActiveQuestions([]) setActiveActions([]) try { const detail = await aiSessionsApi.getSession(chatId) setMessages( (detail.conversation_messages || []).map(m => ({ role: m.role as 'user' | 'assistant', content: m.content, })) ) } catch { setMessages([]) } }, []) const handleNewChat = async () => { try { const session = await aiSessionsApi.createChatSession({ intake_type: 'free_text', intake_content: { text: '' }, }) const chatItem: ChatListItem = { id: session.session_id, title: session.title, message_count: 0, pinned: false, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), } setChats(prev => [chatItem, ...prev]) setActiveChatId(session.session_id) setMessages([]) // Clear TaskLane from previous session setShowTaskLane(false) setActiveQuestions([]) setActiveActions([]) } catch { toast.error('Failed to create chat') } } const handleDeleteChat = async (chatId: string) => { try { await aiSessionsApi.deleteSession(chatId) setChats(prev => prev.filter(c => c.id !== chatId)) if (activeChatId === chatId) { setActiveChatId(null) setMessages([]) } } catch { toast.error('Failed to delete chat') } } const handleTogglePin = async () => { // Pin/unpin not yet supported on unified sessions — no-op for now toast.info('Pin feature coming soon') } const handleSend = async () => { if (!input.trim() || !activeChatId || loading) return const userMessage = input.trim() const completedUploadIds = pendingUploads .filter((u) => u.status === 'done' && u.result?.id) .map((u) => u.result!.id) setInput('') setPendingUploads([]) setMessages(prev => [...prev, { role: 'user', content: userMessage }]) setLoading(true) try { const response = await aiSessionsApi.sendChatMessage(activeChatId, { message: userMessage, upload_ids: completedUploadIds.length > 0 ? completedUploadIds : undefined, }) analytics.aiFeatureUsed({ feature: 'assistant_chat' }) setMessages(prev => [ ...prev, { role: 'assistant', content: response.content, suggestedFlows: response.suggested_flows, fork: response.fork, actions: response.actions, questions: response.questions }, ]) setChats(prev => prev.map(c => c.id === activeChatId ? { ...c, message_count: c.message_count + 2, title: c.message_count === 0 ? userMessage.slice(0, 100) : c.title, updated_at: new Date().toISOString() } : c ) ) // Load branches if fork was created if (response.fork && activeChatId) { branching.loadBranches(activeChatId) } // Show task lane if AI sent questions or actions const hasQuestions = response.questions && response.questions.length > 0 const hasActions = response.actions && response.actions.length > 0 if (hasQuestions || hasActions) { setActiveQuestions(response.questions || []) setActiveActions(response.actions || []) setShowTaskLane(true) } } catch { setMessages(prev => [ ...prev, { role: 'assistant', content: 'Sorry, something went wrong. Please try again.' }, ]) } finally { setLoading(false) requestAnimationFrame(() => inputRef.current?.focus()) } } const handleTaskSubmit = async (responses: Array<{ type: string; state: string; value: string; text?: string; label?: string }>) => { if (!activeChatId || loading) return // Format task responses into a structured message for the AI const parts: string[] = [] for (const r of responses) { const name = r.type === 'question' ? `Q: ${r.text}` : r.label || 'Check' if (r.state === 'done' && r.value.trim()) { parts.push(`**${name}:**\n\`\`\`\n${r.value.trim()}\n\`\`\``) } else if (r.state === 'skipped') { parts.push(`**${name}:** _(skipped)_`) } } const userMessage = parts.join('\n\n') // Close the task lane setShowTaskLane(false) setActiveQuestions([]) setActiveActions([]) setMessages(prev => [...prev, { role: 'user', content: userMessage }]) setLoading(true) try { const response = await aiSessionsApi.sendChatMessage(activeChatId, { message: userMessage }) setMessages(prev => [ ...prev, { role: 'assistant', content: response.content, suggestedFlows: response.suggested_flows, fork: response.fork, actions: response.actions, questions: response.questions }, ]) if (response.fork && activeChatId) { branching.loadBranches(activeChatId) } // Show task lane again if AI sends more tasks const hasQuestions = response.questions && response.questions.length > 0 const hasActions = response.actions && response.actions.length > 0 if (hasQuestions || hasActions) { setActiveQuestions(response.questions || []) setActiveActions(response.actions || []) setShowTaskLane(true) } } catch { setMessages(prev => [ ...prev, { role: 'assistant', content: 'Sorry, something went wrong processing your responses. Please try again.' }, ]) } finally { setLoading(false) } } const handleConclude = async (outcome: ConclusionOutcome, _notes: string): Promise => { if (!activeChatId) throw new Error('No active chat') // Map conclusion outcomes to ai_sessions actions if (outcome === 'resolved') { const result = await aiSessionsApi.resolveSession(activeChatId, { resolution_summary: _notes || 'Resolved via assistant chat', }) return result.documentation?.problem_summary || 'Session resolved' } else if (outcome === 'escalated') { const result = await aiSessionsApi.escalateSession(activeChatId, { escalation_reason: _notes || 'Escalated from assistant chat', }) return result.documentation?.problem_summary || 'Session escalated' } else { // paused await aiSessionsApi.pauseSession(activeChatId) return 'Session paused' } } const handleResumeNew = async (summary: string) => { try { const resumePrompt = `I'm continuing a previous troubleshooting session. Here's where we left off:\n\n${summary}\n\nPlease review this context and help me continue from where we stopped.` const session = await aiSessionsApi.createChatSession({ intake_type: 'free_text', intake_content: { text: resumePrompt }, }) const chatItem: ChatListItem = { id: session.session_id, title: session.title, message_count: 0, pinned: false, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), } setChats(prev => [chatItem, ...prev]) setActiveChatId(session.session_id) setMessages([{ role: 'user', content: resumePrompt }]) setLoading(true) const response = await aiSessionsApi.sendChatMessage(session.session_id, { message: resumePrompt }) setMessages(prev => [ ...prev, { role: 'assistant', content: response.content, suggestedFlows: response.suggested_flows, fork: response.fork, actions: response.actions, questions: response.questions }, ]) setChats(prev => prev.map(c => c.id === session.session_id ? { ...c, message_count: 2, title: resumePrompt.slice(0, 100), updated_at: new Date().toISOString() } : c ) ) // Show task lane if AI sent questions or actions if (response.fork && session.session_id) { branching.loadBranches(session.session_id) } const hasQuestions = response.questions && response.questions.length > 0 const hasActions = response.actions && response.actions.length > 0 if (hasQuestions || hasActions) { setActiveQuestions(response.questions || []) setActiveActions(response.actions || []) setShowTaskLane(true) } } catch { toast.error('Failed to create resume chat') } finally { setLoading(false) } } const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault() handleSend() } } // Auto-grow textarea useEffect(() => { const el = inputRef.current if (!el) return el.style.height = 'auto' el.style.height = `${Math.min(el.scrollHeight, 150)}px` }, [input]) // ── File handling ────────────────────────────── const ACCEPTED_FILE_TYPES = 'image/png,image/jpeg,image/gif,image/webp,.txt,.log,.csv,.pdf,.docx' const processFiles = useCallback((files: File[]) => { if (files.length === 0) return const newUploads: PendingUpload[] = files.map((file) => ({ id: crypto.randomUUID(), file, preview: file.type.startsWith('image/') ? URL.createObjectURL(file) : '', status: 'uploading' as const, })) setPendingUploads((prev) => [...prev, ...newUploads]) newUploads.forEach((upload) => { uploadsApi.upload(upload.file) .then((result) => { setPendingUploads((prev) => prev.map((u) => u.id === upload.id ? { ...u, status: 'done' as const, result } : u)) }) .catch((err) => { const is503 = err?.response?.status === 503 if (is503) { toast.warning('Image attachments are not available yet — describe the issue in text instead') } else { toast.error(`Upload failed: ${err?.message || 'Unknown error'}`) } setPendingUploads((prev) => prev.filter((u) => u.id !== upload.id)) }) }) }, []) const handlePaste = useCallback((e: React.ClipboardEvent) => { const items = e.clipboardData?.items if (!items) return const imageFiles: File[] = [] for (let i = 0; i < items.length; i++) { if (items[i].type.startsWith('image/')) { const file = items[i].getAsFile() if (file) imageFiles.push(file) } } if (imageFiles.length > 0) { e.preventDefault() processFiles(imageFiles) } }, [processFiles]) const handleDragOver = useCallback((e: React.DragEvent) => { e.preventDefault(); e.dataTransfer.dropEffect = 'copy' }, []) const handleDragEnter = useCallback((e: React.DragEvent) => { e.preventDefault(); dragCounterRef.current++; if (dragCounterRef.current === 1) setIsDragOver(true) }, []) const handleDragLeave = useCallback((e: React.DragEvent) => { e.preventDefault(); dragCounterRef.current--; if (dragCounterRef.current === 0) setIsDragOver(false) }, []) const handleDrop = useCallback((e: React.DragEvent) => { e.preventDefault(); dragCounterRef.current = 0; setIsDragOver(false); processFiles(Array.from(e.dataTransfer.files)) }, [processFiles]) const handleFileSelect = useCallback((e: React.ChangeEvent) => { if (e.target.files) { processFiles(Array.from(e.target.files)); e.target.value = '' } }, [processFiles]) const handleRemoveUpload = useCallback((uploadId: string) => { setPendingUploads((prev) => { const toRemove = prev.find((u) => u.id === uploadId); if (toRemove?.preview) URL.revokeObjectURL(toRemove.preview); return prev.filter((u) => u.id !== uploadId) }) }, []) const retryUpload = useCallback((uploadId: string) => { const upload = pendingUploads.find((u) => u.id === uploadId) if (!upload) return setPendingUploads((prev) => prev.map((u) => u.id === uploadId ? { ...u, status: 'uploading' as const, error: undefined } : u)) uploadsApi.upload(upload.file) .then((result) => { setPendingUploads((prev) => prev.map((u) => u.id === uploadId ? { ...u, status: 'done' as const, result } : u)) }) .catch((err) => { setPendingUploads((prev) => prev.map((u) => u.id === uploadId ? { ...u, status: 'error' as const, error: err?.message || 'Upload failed' } : u)) }) }, [pendingUploads]) // Cleanup blob URLs on unmount useEffect(() => { return () => { pendingUploads.forEach((u) => { if (u.preview) URL.revokeObjectURL(u.preview) }) } }, []) // eslint-disable-line react-hooks/exhaustive-deps return ( <>
{/* Sidebar — hidden on mobile, collapsed to top bar or full sidebar on desktop */} {!sidebarCollapsed && (
)}
setMobileSidebarOpen(false)} />
{/* Main chat area + optional branch sidebar */}
{/* Collapsed sidebar top bar — desktop only */} {sidebarCollapsed && (
)} {/* Chat content row: chat column + TaskLane side by side */}
{/* Mobile header with chat history toggle */}
{activeChatId ? ( <> {/* Messages */}
{messages.length === 0 && !loading && (

AI Assistant

Ask me anything about IT infrastructure, networking, Active Directory, cloud platforms, or troubleshooting. I'll also suggest relevant flows from your team's library.

)} {messages.map((msg, i) => ( ))} {loading && (
)}
{/* Rich Input */}
{/* Drag overlay */} {isDragOver && (
Drop files to attach
)} {/* Textarea */}