import { useEffect, useRef, useState } from 'react' import { useParams, useSearchParams, useLocation, useBlocker, useNavigate } from 'react-router-dom' import { Sparkles, Loader2, AlertTriangle } from 'lucide-react' import { useFlowPilotSession } from '@/hooks/useFlowPilotSession' import { FlowPilotIntake, FlowPilotSession, SessionBriefing } from '@/components/flowpilot' import { aiSessionsApi } from '@/api' import { toast } from '@/lib/toast' export default function FlowPilotSessionPage() { const { sessionId } = useParams<{ sessionId?: string }>() const [searchParams, setSearchParams] = useSearchParams() const navigate = useNavigate() const location = useLocation() const prefill = (location.state as { prefill?: string } | null)?.prefill || '' const isPickup = searchParams.get('pickup') === 'true' const fp = useFlowPilotSession() const prefillHandledRef = useRef(false) // Block navigation when session is active const isActiveSession = fp.session?.status === 'active' const blocker = useBlocker( ({ currentLocation, nextLocation }) => !!isActiveSession && currentLocation.pathname !== nextLocation.pathname ) // Auto-submit when navigating from dashboard with prefilled problem useEffect(() => { if (prefill && !prefillHandledRef.current && !sessionId && !fp.session && !fp.isLoading) { prefillHandledRef.current = true fp.startSession({ intake_type: 'free_text', intake_content: { text: prefill } }) } }, [prefill, sessionId, fp.session, fp.isLoading]) // eslint-disable-line react-hooks/exhaustive-deps const [pickingUp, setPickingUp] = useState(false) // Load existing session if ID in URL useEffect(() => { if (sessionId && !fp.session) { fp.loadSession(sessionId) } }, [sessionId]) // eslint-disable-line react-hooks/exhaustive-deps const handlePickupContinue = async () => { if (!sessionId) return setPickingUp(true) try { await aiSessionsApi.pickupSession(sessionId, { resume_mode: 'continue' }) // Clear pickup param and reload the session as active setSearchParams({}) await fp.loadSession(sessionId) } catch (e: unknown) { const message = e instanceof Error ? e.message : 'Failed to pick up session' toast.error(message) } finally { setPickingUp(false) } } const handlePickupFresh = async (context: string) => { if (!sessionId) return setPickingUp(true) try { await aiSessionsApi.pickupSession(sessionId, { resume_mode: 'fresh', additional_context: context, }) setSearchParams({}) await fp.loadSession(sessionId) } catch (e: unknown) { const message = e instanceof Error ? e.message : 'Failed to pick up session' toast.error(message) } finally { setPickingUp(false) } } // Error state if (fp.error && !fp.session) { return (
{fp.error}
You have an active troubleshooting session. If you leave, your session will be paused and you can resume it later.