Files
resolutionflow/frontend/src/components/flowpilot/FlowPilotSession.tsx
chihlasm 9bad49d568 feat(knowledge-flywheel): add Phase 3 Knowledge Flywheel — AI analysis, review queue, analytics
Phase 3 implementation:
- AI session analysis service that generates flow proposals from resolved sessions
- APScheduler job for batch processing pending analyses (max_instances=1)
- Knowledge gap detection (weak options, high escalation signals)
- Flow proposals CRUD with team admin review workflow (approve/edit/dismiss/reject)
- FlowPilot analytics dashboard with confidence tiers, PSA metrics, knowledge gaps
- In-session script generator component
- Review queue page with filtering and proposal detail panel

Bug fixes from review (12 total):
- Fix "Edit & Publish" navigating to non-existent /editor/new route
- Hide Approve button for enhancement proposals (require Edit & Publish)
- Add max_instances=1 to scheduler to prevent TOCTOU race
- Fix eventual_success case() double-counting failed retries
- Add tree_structure validation before creating tree from proposal
- Simplify script generator rendering condition
- Add severity style fallback, toFixed on rates, Link instead of <a href>
- Add toast.warning on dismiss failure, fix dedup for domain-less sessions
- Cast Decimal to int in knowledge gap evidence dicts

Also updates CLAUDE.md with lessons 67-71 and Phase 3 project structure.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 05:12:10 +00:00

278 lines
9.7 KiB
TypeScript

import { useEffect, useRef, useState } from 'react'
import { Network, Clock, Hash, Play, Ticket } from 'lucide-react'
import type {
AISessionDetail,
AISessionStepResponse,
StepResponseRequest,
ResolveSessionRequest,
EscalateSessionRequest,
SessionDocumentation,
} from '@/types/ai-session'
import { ConfidenceIndicator } from './ConfidenceIndicator'
import { FlowPilotStepCard } from './FlowPilotStepCard'
import { FlowPilotActionBar } from './FlowPilotActionBar'
import { SessionDocView } from './SessionDocView'
import { SessionTicketCard } from './SessionTicketCard'
import { TicketPickerModal } from '@/components/session/TicketPickerModal'
import { aiSessionsApi } from '@/api'
import { toast } from '@/lib/toast'
import type { PSATicketInfo } from '@/types/integrations'
interface FlowPilotSessionProps {
session: AISessionDetail
allSteps: AISessionStepResponse[]
currentStep: AISessionStepResponse | null
isProcessing: boolean
canResolve: boolean
canEscalate: boolean
documentation: SessionDocumentation | null
psaPushStatus?: string | null
psaPushError?: string | null
memberMappingWarning?: string | null
onRespond: (response: StepResponseRequest) => void
onResolve: (data: ResolveSessionRequest) => Promise<SessionDocumentation>
onEscalate: (data: EscalateSessionRequest) => Promise<SessionDocumentation>
onPause?: () => Promise<void>
onResume?: () => Promise<void>
onRate: (rating: number) => void
onReloadSession?: () => Promise<void>
}
export function FlowPilotSession({
session,
allSteps,
currentStep,
isProcessing,
canResolve,
canEscalate,
documentation,
psaPushStatus,
psaPushError,
memberMappingWarning,
onRespond,
onResolve,
onEscalate,
onPause,
onResume,
onRate,
onReloadSession,
}: FlowPilotSessionProps) {
const scrollRef = useRef<HTMLDivElement>(null)
const [showTicketPicker, setShowTicketPicker] = useState(false)
const [linkingTicket, setLinkingTicket] = useState(false)
const handleLinkTicket = async (ticketId: string, _ticket: PSATicketInfo) => {
if (!session.psa_connection_id && !session.ticket_data) {
// Need a connection ID — try to get it from the integrations API
// For now, we'll need it passed in. This will work when ticket_data has it.
toast.error('No PSA connection available')
return
}
setLinkingTicket(true)
setShowTicketPicker(false)
try {
// We need the psa_connection_id. If the session doesn't have one,
// fetch it from the integrations API
let connectionId = session.psa_connection_id
if (!connectionId) {
const { integrationsApi } = await import('@/api/integrations')
const conn = await integrationsApi.getConnection()
if (!conn?.id) {
toast.error('No PSA connection configured')
return
}
connectionId = conn.id
}
await aiSessionsApi.linkTicket(session.id, {
psa_ticket_id: ticketId,
psa_connection_id: connectionId,
})
toast.success(`Linked to ticket #${ticketId}`)
// Reload session to get updated ticket_data
if (onReloadSession) {
await onReloadSession()
}
} catch {
toast.error('Failed to link ticket')
} finally {
setLinkingTicket(false)
}
}
// Auto-scroll to latest step
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight
}
}, [allSteps.length])
const isCompleted = session.status === 'resolved' || session.status === 'escalated'
// Show documentation view for completed sessions
if (isCompleted && documentation) {
return (
<div className="flex h-full flex-col">
<div className="flex-1 overflow-y-auto p-6">
<SessionDocView
documentation={documentation}
onRate={onRate}
currentRating={session.session_rating}
psaPushStatus={psaPushStatus}
psaPushError={psaPushError}
memberMappingWarning={memberMappingWarning}
sessionId={session.id}
ticketId={session.psa_ticket_id}
/>
</div>
</div>
)
}
return (
<div className="flex h-full flex-col">
{/* Main content area: conversation + sidebar */}
<div className="flex flex-1 min-h-0">
{/* Conversation column */}
<div ref={scrollRef} className="flex-1 overflow-y-auto p-6">
<div className="mx-auto max-w-2xl space-y-3">
{allSteps.map((step) => (
<FlowPilotStepCard
key={step.step_id}
step={step}
isCurrentStep={currentStep?.step_id === step.step_id}
isProcessing={isProcessing && currentStep?.step_id === step.step_id}
sessionId={session.id}
onRespond={onRespond}
/>
))}
</div>
</div>
{/* Sidebar */}
<div
className="hidden w-72 shrink-0 overflow-y-auto border-l p-4 lg:block"
style={{ borderColor: 'var(--glass-border)' }}
>
<div className="space-y-4">
{/* Ticket context */}
{session.psa_ticket_id ? (
<SessionTicketCard
ticketId={session.psa_ticket_id}
ticketData={session.ticket_data as Record<string, unknown> | null}
/>
) : session.status === 'active' ? (
<button
onClick={() => setShowTicketPicker(true)}
disabled={linkingTicket}
className="w-full flex items-center gap-2 rounded-xl border border-dashed border-border px-3 py-2.5 text-xs text-muted-foreground hover:text-foreground hover:border-primary/30 transition-colors disabled:opacity-50"
>
<Ticket size={14} />
{linkingTicket ? 'Linking...' : 'Link Ticket'}
</button>
) : null}
{/* Problem summary */}
{session.problem_summary && (
<div>
<h4 className="font-label text-[0.625rem] uppercase tracking-wider text-[#5a6170] mb-1">
Problem
</h4>
<p className="text-sm text-foreground">{session.problem_summary}</p>
</div>
)}
{/* Domain */}
{session.problem_domain && (
<div>
<h4 className="font-label text-[0.625rem] uppercase tracking-wider text-[#5a6170] mb-1">
Domain
</h4>
<span className="font-label rounded-md bg-primary/10 px-2 py-0.5 text-[0.625rem] uppercase tracking-wider text-primary">
{session.problem_domain}
</span>
</div>
)}
{/* Confidence */}
<div>
<h4 className="font-label text-[0.625rem] uppercase tracking-wider text-[#5a6170] mb-1">
Confidence
</h4>
<ConfidenceIndicator
tier={session.confidence_tier}
score={currentStep?.confidence_score ?? 0}
/>
</div>
{/* Matched flow */}
{session.matched_flow_id && (
<div>
<h4 className="font-label text-[0.625rem] uppercase tracking-wider text-[#5a6170] mb-1">
Matched flow
</h4>
<div className="flex items-center gap-2">
<Network size={14} className="text-muted-foreground" />
<span className="text-xs text-foreground">
{session.match_score ? `${Math.round(session.match_score * 100)}% match` : 'Match found'}
</span>
</div>
</div>
)}
{/* Steps */}
<div className="flex items-center gap-4">
<div className="flex items-center gap-1.5">
<Hash size={12} className="text-muted-foreground" />
<span className="text-xs text-muted-foreground">{session.step_count} steps</span>
</div>
<div className="flex items-center gap-1.5">
<Clock size={12} className="text-muted-foreground" />
<span className="text-xs text-muted-foreground">
{new Date(session.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</span>
</div>
</div>
</div>
</div>
</div>
{/* Action bar */}
{session.status === 'active' && (
<FlowPilotActionBar
canResolve={canResolve}
canEscalate={canEscalate}
isProcessing={isProcessing}
hasPsaTicket={!!session.psa_ticket_id}
onResolve={onResolve}
onEscalate={onEscalate}
onPause={onPause}
/>
)}
{/* Paused banner */}
{session.status === 'paused' && onResume && (
<div
className="flex items-center justify-between border-t px-5 py-3"
style={{ borderColor: 'var(--glass-border)', background: 'rgba(16, 17, 20, 0.8)', backdropFilter: 'blur(12px)' }}
>
<span className="text-sm text-muted-foreground">Session paused</span>
<button
onClick={onResume}
className="flex items-center gap-2 rounded-lg bg-gradient-brand px-4 py-2 text-sm font-semibold text-[#101114] shadow-lg shadow-primary/20 hover:opacity-90 active:scale-[0.97] transition-all"
>
<Play size={14} />
Resume Session
</button>
</div>
)}
{/* Ticket picker modal for mid-session linking */}
<TicketPickerModal
open={showTicketPicker}
onClose={() => setShowTicketPicker(false)}
onSelect={handleLinkTicket}
/>
</div>
)
}