import { useState, useEffect, useRef, useCallback } from 'react' import { useLocation, useNavigate, useParams } from 'react-router-dom' import { Sparkles, Send, Loader2, MessageSquare, Paperclip, Terminal, X, RotateCcw, ImagePlus, ListChecks, FileText, CheckCircle2, ArrowUpRight, MoreHorizontal, Pause } 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, clearTaskState } from '@/components/assistant/TaskLane' import { WhatWeKnow } from '@/components/pilot/sections/WhatWeKnow' import { SuggestedFix } from '@/components/pilot/sections/SuggestedFix' import { ResolutionNotePreview as ResolutionNotePreviewPopover } from '@/components/pilot/ResolutionNotePreview' import { TemplateMatchPanel } from '@/components/pilot/script/TemplateMatchPanel' import { NoTemplateDialog } from '@/components/pilot/script/NoTemplateDialog' import { PILOT_INLINE_SCRIPT_EVENT } from '@/components/layout/CommandPalette' import { sessionFactsApi, type SessionFact } from '@/api/sessionFacts' import { sessionSuggestedFixesApi, type SessionSuggestedFix, type ResolutionNotePreview as ResolutionNotePreviewData, type UserDecision, } from '@/api/sessionSuggestedFixes' import { ConcludeSessionModal } from '@/components/assistant/ConcludeSessionModal' import { StatusUpdateModal } from '@/components/flowpilot/StatusUpdateModal' 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 imageUrls?: string[] } export default function AssistantChatPage() { const location = useLocation() const navigate = useNavigate() const { sessionId: urlSessionId } = useParams<{ sessionId?: string }>() const [chats, setChats] = useState([]) const [activeChatId, setActiveChatId] = useState(() => { if (urlSessionId) return urlSessionId try { return sessionStorage.getItem('rf-active-chat-id') } catch { return null } }) const [messages, setMessages] = useState([]) const [input, setInput] = useState('') const [loading, setLoading] = useState(false) const [showConclude, setShowConclude] = useState(false) const [showStatusUpdate, setShowStatusUpdate] = 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(() => { try { const saved = sessionStorage.getItem('rf-tasklane-meta') if (saved) { const d = JSON.parse(saved); if (d.chatId === activeChatId) return d.questions || [] } } catch { /* ignore */ } return [] }) const [activeActions, setActiveActions] = useState(() => { try { const saved = sessionStorage.getItem('rf-tasklane-meta') if (saved) { const d = JSON.parse(saved); if (d.chatId === activeChatId) return d.actions || [] } } catch { /* ignore */ } return [] }) const [showTaskLane, setShowTaskLane] = useState(() => { try { const saved = sessionStorage.getItem('rf-tasklane-meta') if (saved) { const d = JSON.parse(saved); return d.show === true && d.chatId === activeChatId } } catch { /* ignore */ } return false }) const [sidebarCollapsed, setSidebarCollapsed] = useState(() => localStorage.getItem('rf-chat-sidebar-collapsed') === 'true' ) const [activeSessionStatus, setActiveSessionStatus] = useState(null) const [activePsaTicketId, setActivePsaTicketId] = useState(null) // Phase 2: "What we know" facts for the active session. Refreshed on // selectChat and after each chat send (the AI may have emitted [PROMOTE] // markers that synthesized new facts server-side). const [facts, setFacts] = useState([]) // Phase 3: active suggested fix; Phase 4 extends the preview popover to // support both Resolve and Escalate (kind-parameterized, one active at a time). const [activeFix, setActiveFix] = useState(null) const [previewKind, setPreviewKind] = useState<'resolve' | 'escalate' | null>(null) const [previewData, setPreviewData] = useState(null) const [previewLoading, setPreviewLoading] = useState(false) const [previewError, setPreviewError] = useState(null) const [previewPosting, setPreviewPosting] = useState(false) // Debounce timer for preview refresh — Phase 3 spec calls for 500ms client- // side debounce so rapid edits don't fan out to the LLM (cache absorbs the // dups, but the request itself still costs HTTP RTT). const previewDebounceRef = useRef | null>(null) const previewOpen = previewKind !== null // Phase 5: inline Script Generator panel state. Open <=> the engineer // clicked the Suggested Fix card. Which panel renders is decided by // whether the active fix has a script_template_id. const [scriptPanelOpen, setScriptPanelOpen] = useState(false) const [scriptDecisionBusy, setScriptDecisionBusy] = useState(false) const [showOverflow, setShowOverflow] = useState(false) 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) // Tracks the most recently requested active chat ID so in-flight selectChat // calls that complete after the user switches chats don't clobber new state. const currentChatRef = useRef(activeChatId) // Persist active chat ID to sessionStorage useEffect(() => { try { if (activeChatId) sessionStorage.setItem('rf-active-chat-id', activeChatId) else sessionStorage.removeItem('rf-active-chat-id') } catch { /* ignore */ } }, [activeChatId]) // 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 // Restore session from sessionStorage on mount (when URL has no session ID) useEffect(() => { if (!urlSessionId && activeChatId) { selectChat(activeChatId) } }, []) // 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 () => { // Clear stale task lane from previous session setShowTaskLane(false) setActiveQuestions([]) setActiveActions([]) setActiveSessionStatus('active') setActivePsaTicketId(null) 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) } // Refetch facts + active fix — the AI may have emitted markers. refreshSessionDerived(session.session_id) } catch { toast.error('Failed to start AI conversation') } finally { setLoading(false) } } sendPrefill() // eslint-disable-next-line react-hooks/exhaustive-deps }, []) // Persist task lane metadata to sessionStorage useEffect(() => { try { sessionStorage.setItem('rf-tasklane-meta', JSON.stringify({ show: showTaskLane, chatId: activeChatId, questions: activeQuestions, actions: activeActions, })) } catch { /* ignore */ } }, [showTaskLane, activeChatId, activeQuestions, activeActions]) // Auto-scroll useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [messages]) // Phase 5: Cmd+K → "Open inline Script Generator". Only acts when there // is an active suggested fix on this session — otherwise we'd open an // empty panel. useEffect(() => { const handler = () => { if (activeFix) { setScriptPanelOpen(true) } else { toast.info('No active suggested fix yet — wait for the AI to propose a resolution.') } } window.addEventListener(PILOT_INLINE_SCRIPT_EVENT, handler as EventListener) return () => window.removeEventListener(PILOT_INLINE_SCRIPT_EVENT, handler as EventListener) }, [activeFix]) 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 } } // Phase 2 facts — fetch + handlers. `refreshFacts` is called from selectChat // and after each chat send, because the AI may have emitted [PROMOTE] markers // that synthesized new facts server-side (see unified_chat_service. // _persist_promote_items). const refreshFacts = useCallback(async (chatId: string) => { try { const list = await sessionFactsApi.list(chatId) // Guard: discard stale fetch if the user switched chats mid-flight. if (currentChatRef.current !== chatId) return setFacts(list) // Auto-open the task lane when the session has facts so the engineer // can see them — without this, a session with only facts (no open // questions) would hide the lane and the facts would be invisible. if (list.length > 0) setShowTaskLane(true) } catch { // Best-effort — facts are accessory state. Surfacing a toast on every // refetch failure would be noisy; the empty state explains the absence. } }, []) // Phase 3 — active suggested fix + resolution-note preview. // Declared BEFORE refreshSessionDerived / handleAddNote so the useCallback // dep arrays don't hit a temporal dead zone on React's synchronous render. const refreshActiveFix = useCallback(async (chatId: string) => { try { const fix = await sessionSuggestedFixesApi.getActive(chatId) if (currentChatRef.current !== chatId) return setActiveFix((prev) => { // If the active fix changed (AI emitted a new SUGGEST_FIX that // superseded the prior), close the script panel so the engineer // isn't acting on stale draft state. if (prev?.id !== fix?.id) setScriptPanelOpen(false) return fix }) } catch { // No-fix-yet (404) is normalized to null inside the client. Genuine // failures stay silent — accessory state, not load-bearing. } }, []) // Kind-aware preview fetch: Resolve hits /resolution-note/preview, // Escalate hits /escalation-package/preview. They're cached separately // on the backend, so switching kinds never returns stale markdown. const refreshPreview = useCallback(async (chatId: string, kind?: 'resolve' | 'escalate') => { const effectiveKind = kind ?? previewKind if (!effectiveKind) return setPreviewLoading(true) setPreviewError(null) try { const p = effectiveKind === 'resolve' ? await sessionSuggestedFixesApi.getResolutionNotePreview(chatId) : await sessionSuggestedFixesApi.getEscalationPackagePreview(chatId) if (currentChatRef.current !== chatId) return setPreviewData(p) } catch (err: unknown) { const status = (err as { response?: { status?: number } })?.response?.status setPreviewError( status === 502 ? 'AI provider error drafting the note. Try again in a few seconds.' : 'Could not load preview.', ) } finally { setPreviewLoading(false) } }, [previewKind]) // Trigger preview refresh with a 500ms debounce. The backend cache short- // circuits same-state calls, but the network round-trip is still avoidable // when the user is typing quickly (e.g. editing a fact). const schedulePreviewRefresh = useCallback((chatId: string) => { if (previewDebounceRef.current) clearTimeout(previewDebounceRef.current) previewDebounceRef.current = setTimeout(() => { if (previewOpen && currentChatRef.current === chatId) { refreshPreview(chatId) } }, 500) }, [previewOpen, refreshPreview]) // Phase 3: convenience helper — refresh fact list, active fix, and (if open) // schedule a preview refresh. Called after every chat send so the new state // (PROMOTE-synthesized facts, new SUGGEST_FIX) appears in the lane. const refreshSessionDerived = useCallback(async (chatId: string) => { await Promise.all([refreshFacts(chatId), refreshActiveFix(chatId)]) if (previewOpen) schedulePreviewRefresh(chatId) }, [refreshFacts, refreshActiveFix, previewOpen, schedulePreviewRefresh]) const handleAddNote = async (text: string, summary: string | null) => { if (!activeChatId) return try { const fact = await sessionFactsApi.create(activeChatId, { text, summary }) setFacts(prev => [...prev, fact]) schedulePreviewRefresh(activeChatId) } catch { toast.error('Failed to add note') } } const handleUpdateFact = async (factId: string, text: string, summary: string | null) => { if (!activeChatId) return try { const updated = await sessionFactsApi.update(activeChatId, factId, { text, summary }) setFacts(prev => prev.map(f => f.id === factId ? updated : f)) schedulePreviewRefresh(activeChatId) } catch { toast.error('Failed to update fact') } } const handleDeleteFact = async (factId: string) => { if (!activeChatId) return try { await sessionFactsApi.remove(activeChatId, factId) setFacts(prev => prev.filter(f => f.id !== factId)) schedulePreviewRefresh(activeChatId) } catch { toast.error('Failed to remove fact') } } const handleDismissFix = async () => { if (!activeChatId || !activeFix) return try { await sessionSuggestedFixesApi.recordDecision(activeChatId, activeFix.id, 'dismissed') setActiveFix(null) setScriptPanelOpen(false) // Dismissal bumps state_version on the server; reflect in preview. schedulePreviewRefresh(activeChatId) } catch { toast.error('Failed to dismiss suggestion') } } // Phase 5: handle a path choice from NoTemplateDialog. one_off and // draft_template just record the decision (returning the rendered script // for display); build_template returns a redirect_path to the Script // Builder, which we navigate to. const handleScriptDecision = async ( decision: UserDecision, options: { editedScript: string; parametersUsed: Record }, ) => { if (!activeChatId || !activeFix) return setScriptDecisionBusy(true) try { const out = await sessionSuggestedFixesApi.recordDecision( activeChatId, activeFix.id, decision, { editedScript: options.editedScript, parametersUsed: options.parametersUsed }, ) // Decision endpoint bumps state_version — reflect in preview. schedulePreviewRefresh(activeChatId) if (decision === 'build_template' && out.redirect_path) { navigate(out.redirect_path) return } if (decision === 'one_off') { toast.success('Recorded as one-off — script not added to library') } else if (decision === 'draft_template') { toast.success('Draft template queued — review after Resolve') } // Keep the panel open so the engineer can copy the rendered script. } catch { toast.error('Failed to record decision') } finally { setScriptDecisionBusy(false) } } const handleOpenPreview = (kind: 'resolve' | 'escalate') => { if (!activeChatId) return // Opening a different kind clobbers the cached markdown so the popover // doesn't flash stale content while the new kind fetches. if (previewKind !== kind) setPreviewData(null) setPreviewKind(kind) setPreviewError(null) refreshPreview(activeChatId, kind) } const handleClosePreview = () => { setPreviewKind(null) setPreviewError(null) } const handleConfirmPost = async (markdown: string) => { if (!activeChatId || !previewKind) return setPreviewPosting(true) try { const out = previewKind === 'resolve' ? await sessionSuggestedFixesApi.postResolutionNote(activeChatId, markdown) : await sessionSuggestedFixesApi.postEscalationPackage(activeChatId, markdown) setActiveSessionStatus(out.session_status) if (out.outcome === 'resolved') { toast.success( out.verified_status_id ? `Posted to ${previewData?.target_ticket_ref ?? 'PSA'} · status ${out.verified_status_name}` : `Posted to ${previewData?.target_ticket_ref ?? 'PSA'}${out.status_transition_skipped_reason ? ' · status unchanged' : ''}`, ) } else if (out.outcome === 'escalated') { toast.success( out.verified_status_id ? `Escalated · ${previewData?.target_ticket_ref ?? 'PSA'} status ${out.verified_status_name}` : `Escalated · handoff posted to ${previewData?.target_ticket_ref ?? 'PSA'}`, ) } else if (out.outcome === 'resolved_local') { toast.success('Session resolved locally (no PSA ticket linked)') } else if (out.outcome === 'escalated_local') { toast.success('Session escalated locally (no PSA ticket linked)') } handleClosePreview() } catch (err: unknown) { console.error('[AssistantChat] confirm post failed:', err) const status = (err as { response?: { status?: number }; response?: { data?: { detail?: string } } })?.response?.status const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail if (status === 502) { toast.error(detail || 'PSA posted partially — see server logs.') } else if (status === 409) { toast.warning(detail || 'Session is already in that state.') } else { toast.error('Could not post. Please try again.') } } finally { setPreviewPosting(false) } } const selectChat = useCallback(async (chatId: string) => { currentChatRef.current = chatId setActiveChatId(chatId) // Clear TaskLane when switching chats — will restore from backend if available setShowTaskLane(false) setActiveQuestions([]) setActiveActions([]) setActiveSessionStatus(null) setActivePsaTicketId(null) setFacts([]) setActiveFix(null) setPreviewData(null) setPreviewError(null) setPreviewKind(null) setScriptPanelOpen(false) // Fire facts + active-fix fetches in parallel with session detail. refreshSessionDerived(chatId) try { const detail = await aiSessionsApi.getSession(chatId) // Guard: if the user switched to a different chat while this API call was // in flight (e.g. clicked "New Chat"), discard stale results so we don't // clobber the new session's task lane state. if (currentChatRef.current !== chatId) return setActiveSessionStatus(detail.status) setActivePsaTicketId(detail.psa_ticket_id) setMessages( (detail.conversation_messages || []).map(m => ({ role: m.role as 'user' | 'assistant', content: m.content, })) ) // Restore task lane from persisted state if (detail.pending_task_lane) { const q = detail.pending_task_lane.questions || [] const a = detail.pending_task_lane.actions || [] if (q.length > 0 || a.length > 0) { // Pre-load user's saved responses into sessionStorage BEFORE setting props // so TaskLane can restore them on mount/prop-change const responses = detail.pending_task_lane.responses if (responses && responses.length > 0) { try { sessionStorage.setItem(`rf-tasklane-state:${chatId}`, JSON.stringify(responses)) } catch { /* ignore */ } } setActiveQuestions(q) setActiveActions(a) setShowTaskLane(true) } } } catch { setMessages([]) } }, [refreshSessionDerived]) const handleNewChat = async () => { // Invalidate currentChatRef BEFORE the await so any in-flight handleSend/handleTaskSubmit // for the previous session sees a mismatch and bails — prevents stale task lane appearing // in the new empty session (same pattern as selectChat, which sets ref before its await). currentChatRef.current = null // Clear stale state immediately — don't wait for API to return setShowTaskLane(false) setActiveQuestions([]) setActiveActions([]) setFacts([]) setScriptPanelOpen(false) setMessages([]) setActiveSessionStatus('active') setActivePsaTicketId(null) 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(), } currentChatRef.current = session.session_id setChats(prev => [chatItem, ...prev]) setActiveChatId(session.session_id) } 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 completedUploads = pendingUploads.filter((u) => u.status === 'done' && u.result?.id) const completedUploadIds = completedUploads.map((u) => u.result!.id) const imageUrls = completedUploads .filter((u) => u.preview) .map((u) => u.preview) setInput('') setPendingUploads([]) setMessages(prev => [...prev, { role: 'user', content: userMessage, imageUrls: imageUrls.length > 0 ? imageUrls : undefined }]) setLoading(true) const sentForChatId = activeChatId try { const response = await aiSessionsApi.sendChatMessage(activeChatId, { message: userMessage, upload_ids: completedUploadIds.length > 0 ? completedUploadIds : undefined, }) // Guard: discard if user switched to a different chat while this was in flight if (currentChatRef.current !== sentForChatId) return 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 === sentForChatId ? { ...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 && sentForChatId) { branching.loadBranches(sentForChatId) } // 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) { clearTaskState(sentForChatId) setActiveQuestions(response.questions || []) setActiveActions(response.actions || []) setShowTaskLane(true) } // Refetch facts + active fix; preview refreshes if open. refreshSessionDerived(sentForChatId) } catch (err: unknown) { console.error('[AssistantChat] sendChatMessage failed:', err) const status = (err as { response?: { status?: number } })?.response?.status let errorMsg: string if (status === 429) { errorMsg = "You're sending messages too quickly. Wait a moment and try again." } else if (status === 502 || status === 503) { errorMsg = "The AI is temporarily unavailable. Please try again in a few seconds." } else { errorMsg = "Something went wrong sending your message. Please try again." } // Remove the optimistic user message and restore it to the input so they can retry setMessages(prev => prev.slice(0, -1)) setInput(userMessage) toast.error(errorMsg) } 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. // Pending tasks are included so the AI knows they weren't completed yet. 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)_`) } else { parts.push(`**${name}:** _(not yet completed)_`) } } const userMessage = parts.join('\n\n') setMessages(prev => [...prev, { role: 'user', content: userMessage }]) setLoading(true) const sentForChatId = activeChatId try { const response = await aiSessionsApi.sendChatMessage(activeChatId, { message: userMessage }) // Guard: discard if user switched to a different chat while this was in flight if (currentChatRef.current !== sentForChatId) return setMessages(prev => [ ...prev, { role: 'assistant', content: response.content, suggestedFlows: response.suggested_flows, fork: response.fork, actions: response.actions, questions: response.questions }, ]) if (response.fork && sentForChatId) { branching.loadBranches(sentForChatId) } // Update task lane based on AI response const hasQuestions = response.questions && response.questions.length > 0 const hasActions = response.actions && response.actions.length > 0 clearTaskState(sentForChatId) if (hasQuestions || hasActions) { setActiveQuestions(response.questions || []) setActiveActions(response.actions || []) setShowTaskLane(true) } else { // AI sent no new tasks — clear the lane setShowTaskLane(false) setActiveQuestions([]) setActiveActions([]) } // Refetch facts + active fix; answering tasks is the primary trigger. refreshSessionDerived(sentForChatId) } catch (err: unknown) { console.error('[AssistantChat] handleTaskSubmit failed:', err) const status = (err as { response?: { status?: number } })?.response?.status const errorMsg = status === 429 ? "You're sending messages too quickly. Wait a moment and try again." : "Something went wrong submitting your responses. Please try again." setMessages(prev => prev.slice(0, -1)) toast.error(errorMsg) } finally { setLoading(false) } } const handleConclude = async (outcome: ConclusionOutcome, _notes: string): Promise => { if (!activeChatId) throw new Error('No active chat') if (outcome === 'resolved') { await aiSessionsApi.resolveSession(activeChatId, { resolution_summary: _notes || 'Resolved via assistant chat', }) setActiveSessionStatus('resolved') return activeChatId } else if (outcome === 'escalated') { await aiSessionsApi.escalateSession(activeChatId, { escalation_reason: _notes || 'Escalated from assistant chat', }) setActiveSessionStatus('escalated') return activeChatId } else { await aiSessionsApi.pauseSession(activeChatId) setActiveSessionStatus('paused') return activeChatId } } const handleResumeNew = async (summary: string) => { // Invalidate currentChatRef BEFORE the await — same guard as handleNewChat currentChatRef.current = null // Clear stale state immediately — don't wait for API to return setShowTaskLane(false) setActiveQuestions([]) setActiveActions([]) setActiveSessionStatus('active') setActivePsaTicketId(null) 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(), } currentChatRef.current = session.session_id 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 }) // Guard: discard if user switched to a different chat while this was in flight if (currentChatRef.current !== session.session_id) return 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) } // Refetch facts + active fix — resume turn may emit markers. refreshSessionDerived(session.session_id) } 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 ? ( <> {/* Session header — title + lifecycle actions */} {(() => { const chatTitle = chats.find(c => c.id === activeChatId)?.title const isActive = activeSessionStatus === 'active' || activeSessionStatus === null const canAct = messages.length >= 2 && isActive && !loading const updateLabel = activePsaTicketId ? 'Update Ticket' : 'Share Update' return (

{chatTitle || 'AI Assistant'}

{activeSessionStatus && activeSessionStatus !== 'active' && ( {activeSessionStatus === 'requesting_escalation' ? 'Escalated' : activeSessionStatus.charAt(0).toUpperCase() + activeSessionStatus.slice(1)} )}
{/* Desktop actions — shown when session is active and has messages */}
{isActive && ( <> )} {messages.length >= 2 && ( )} {/* Overflow: Pause / — */} {isActive && messages.length >= 2 && (
{showOverflow && ( <>
setShowOverflow(false)} />
)}
)}
{/* Mobile: single overflow menu */} {messages.length >= 2 && (
{showOverflow && ( <>
setShowOverflow(false)} />
{isActive && ( <> )} {isActive && ( )}
)}
)}
) })()} {/* 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 */}