feat: AI-assisted flow builder with 4-stage wizard (#87)
* feat: AI-assisted flow builder with 4-stage wizard Implements the complete AI flow builder feature using a guided 4-stage wizard (Foundation → Scaffold → Branch Detail → Review & Assemble). AI assists at bounded points using Claude Haiku for cost-efficient structured JSON generation (~$0.01-0.03/flow). Backend: new models (ai_conversations, ai_usage), Alembic migration, quota enforcement with billing anchor, Anthropic API integration with prompt caching, tree validation, conversation CRUD with 24h TTL, APScheduler cleanup job, 5 API endpoints, Pydantic schemas. Frontend: TypeScript types, API client, Zustand store for wizard state, 7 components (modal, step indicator, foundation form, branch selector, branch detail view, tree preview, quota display), MyTreesPage integration with "Build with AI" button (hidden when AI not configured). Tests: 14 validator unit tests + 11 endpoint integration tests with mocked Anthropic (zero real API spend). All 25 tests passing. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: dashboard design doc and implementation plan Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: Phase 1 — pinnedFlowsStore, pagination hook, cached quota hook, sidebar refactor - Add pin() to pinnedFlowsApi - Create pinnedFlowsStore (Zustand) — single source of truth for pin state - Add dashboardMyFlowsView preference to userPreferencesStore - Create usePaginationParams hook (URL-synced) - Create useCachedQuota hook (5-min TTL) - Sidebar uses pinnedFlowsStore instead of local state Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: Phase 2 — pin/favorite buttons on all library view components - TreeGridView: star in top-right corner of cards - TreeListView: star at end of each row - TreeTableView: dedicated leftmost Favorite column - All with proper a11y (aria-label), event isolation, loading states Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: Phase 3 — Library page create dropdown + AI Builder + pin wiring - Replace single Create link with dropdown menu (3 flow types + AI Builder) - Wire pinnedFlowsStore to all view components - AI Builder modal integration via useCachedQuota hook Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: Phase 4 — Dashboard refactor with Favorites grid + paginated My Flows - Favorites section: compact grid from pinnedFlowsStore, max 2 rows, expandable - My Flows: author_id filter, URL-synced pagination (10/25/50/All) - View toggle (grid/list/table) with independent preference - Skeleton loaders, empty states with CTAs - Create dropdown with AI Builder option - 500-item ceiling for "Show All" mode Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: Phase 5 — Sidebar pinned section dual collapse + show more/less - Header collapse hides entire section, resets to 5 items on re-expand - List truncation: show first 5, "Show more (N)" expands to all - Clicking a flow auto-collapses back to 5 - Smooth max-height CSS transition (250ms ease-out) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stabilize usePaginationParams to prevent infinite re-render loop allowedPageSizes array was recreated every render as a useMemo dep, causing infinite updates. Use useRef to stabilize the reference. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: remove Set-based Zustand selectors causing infinite re-render loop Zustand selectors returning new Set() on every call fail Object.is equality check, triggering continuous re-renders. Replaced with useMemo-derived Sets in consuming components. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: pin route ordering and star icon overlap in grid view Move GET /pinned and PATCH /pinned/reorder before GET /{tree_id} to prevent FastAPI from matching "pinned" as a UUID path parameter (422). Relocate star button from absolute positioning into the header row to avoid overlapping privacy icons and category badges. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: code review fixes — date calc, input validation, rate limits, shared components - Fix monthly_reset_at crash when billing anchor day exceeds next month's length - Add environment_tags sanitization (max 20 tags, 100 chars each) to prevent prompt injection - Add @limiter.limit("10/minute") rate limiting to all AI endpoints - Use getTreeNavigatePath() routing helper instead of hardcoded paths - Extract shared CreateFlowDropdown component from QuickStartPage and TreeLibraryPage - Clear useCachedQuota on logout to prevent stale data across user sessions - Add useRef guard to scaffold useEffect to prevent potential double-fire - Use node.id as React key instead of array index in BranchDetailView - Remove redundant dead logic in ai_tree_validator Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: correct Anthropic model ID to full dated version claude-haiku-4-5 is not a valid model alias — Anthropic requires the full dated model ID claude-haiku-4-5-20251001. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: strip markdown code fences from AI JSON responses Haiku sometimes wraps its JSON in ```json ... ``` despite the prompt instructing otherwise. Strip fences before parsing to avoid JSONDecodeError at char 0. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: increase branch_detail max_tokens to 8192 and add response logging Truncated output at 4096 tokens produces invalid JSON mid-generation. Also logs stop_reason and output_tokens per attempt to diagnose failures. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: pass explicit status='draft' when creating AI-generated flow Tree model defaults to 'published' in the DB schema, but passing status=None from the constructor overrides that default, causing a nullable=False violation and a 500 on save. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: auto-advance branch detail and pin navigation bar - Auto-advance to next undetailed branch after generation completes, using a useEffect that watches the count of detailed branches - Cap tree preview at max-h-48 with internal scroll so the nav bar is never pushed off screen - Make nav bar sticky bottom-0 with bg-card so it stays visible regardless of content height Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: increase branch retries to 3 and relax cross-reference validation on final attempt next_node_id mismatches are a common model hallucination that the retry prompt doesn't reliably fix. On the final (3rd) attempt, accept the branch with strict=False so only truly fatal errors (missing fields, dead ends, bad JSON) cause a hard failure. Cross-reference issues are minor and fixable in the tree editor. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: strengthen prompt to prevent next_node_id mismatches, keep strict validation Rather than lowering the validation bar, improve the system prompt: - Rule 6 now explicitly states next_node_id must match a direct child's id - Added rule 10: build tree bottom-up to avoid forward-reference errors - Corrective prompt now calls out the ID mismatch constraint specifically Reverts the strict=False fallback — flows must be correct before saving. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: persist branch viewing index in store to survive phase remounts Local useState resets to 0 every time phase transitions from 'generating' back to 'detailing', causing the view to snap back to branch 1. Move viewingIndex to store's currentBranchIndex (already existed) and advance it in generateBranchDetail after success. Component reads from store so remounts no longer lose position. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: correct publish validation to check title instead of action/solution fields The publish validator was checking for an 'action' field on action nodes and a 'solution' field on solution nodes, but the actual node schema (confirmed from seed data and frontend types) uses 'title'/'description'. This caused all AI-generated trees to fail publish validation. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: correct action node schema and improve AI flow quality - Fix action nodes to use next_node_id (not children) for continuation, matching how TreeNavigationPage.tsx navigates action nodes - Validator now requires next_node_id on all action nodes and flags missing ones as broken dead ends - Update _check_branch_termination: action nodes are not dead ends since they continue via next_node_id (validated separately) - Improve scaffold prompt: branch names must describe observable symptoms users can self-identify, not internal category names - Update branch_detail prompt with clearer action node schema, corrected few-shot example showing proper next_node_id on action nodes - Improve assemble_tree root question to be more user-facing Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * docs: add AI flow builder gotchas to CLAUDE.md (#23-25) - Action nodes use next_node_id (not children) for navigation - Anthropic model IDs require full dated version string - Claude API may wrap JSON in markdown fences Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: resolve CI lint errors and httpx dependency conflict - Fix httpx version conflict: requirements-dev.txt now uses >=0.27.0 to match requirements.txt - Extract CSAT helper functions to csatUtils.ts to fix react-refresh/only-export-components - Remove default export from admin/EmptyState.tsx shim (same rule) - Fix empty catch block in Modal.tsx (no-empty) - Add eslint-disable comments for intentional setState-in-effect patterns in FlowAnalyticsPanel, QuickLaunch, NodeEditorPanel, useCachedQuota, MyAnalyticsPage, TeamAnalyticsPage - Add eslint-disable comments for intentional _children destructure in NodeEditorPanel - Fix _parentId unused var in useTreeLayout.ts - Rewrite usePaginationParams.ts to avoid reading refs during render Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: update tests to match action node schema (next_node_id, not children) - Update _make_valid_tree() in test_ai_tree_validator to use next_node_id on action nodes (solution is a sibling, not a child) - Fix test_dead_end_action_node → test_dead_end_decision_node (action nodes don't have child-based dead ends; dead ends are decision nodes with no children) - Add test_action_missing_next_node_id for the new validation rule - Update BRANCH_DETAIL_JSON in test_ai_endpoints to use next_node_id pattern - Update test_draft_trees.py to use "title" field for action/solution nodes (tree_validation.py was updated this branch to require "title" not "action"/"solution") Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: update remaining tests and session_to_tree for title field rename - test_tree_validation.py: replace "action"/"solution" content fields with "title" - test_procedural_flows.py: update solution node fixtures to use "title" - test_save_session_as_tree.py: update fixtures and assertions for "title" field - session_to_tree.py: generate "title" instead of "action"/"solution" on converted nodes; fall back to legacy field names when reading from old tree snapshots for compatibility Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit was merged in pull request #87.
This commit is contained in:
@@ -1,2 +1 @@
|
||||
export { EmptyState } from '@/components/common/EmptyState'
|
||||
export { default } from '@/components/common/EmptyState'
|
||||
|
||||
138
frontend/src/components/ai-builder/AIFlowBuilderModal.tsx
Normal file
138
frontend/src/components/ai-builder/AIFlowBuilderModal.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Modal } from '@/components/common/Modal'
|
||||
import { useAIFlowBuilderStore } from '@/store/aiFlowBuilderStore'
|
||||
import { treesApi } from '@/api/trees'
|
||||
import { toast } from '@/lib/toast'
|
||||
import { WizardStepIndicator } from './WizardStepIndicator'
|
||||
import { FoundationForm } from './FoundationForm'
|
||||
import { BranchSelector } from './BranchSelector'
|
||||
import { BranchDetailView } from './BranchDetailView'
|
||||
import { TreePreviewCard } from './TreePreviewCard'
|
||||
import { GeneratingAnimation } from './GeneratingAnimation'
|
||||
|
||||
interface AIFlowBuilderModalProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function AIFlowBuilderModal({ isOpen, onClose }: AIFlowBuilderModalProps) {
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
phase,
|
||||
metadata,
|
||||
assembledTree,
|
||||
loadQuota,
|
||||
scaffold,
|
||||
reset,
|
||||
} = useAIFlowBuilderStore()
|
||||
|
||||
// Load quota when modal opens
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
loadQuota()
|
||||
}
|
||||
}, [isOpen, loadQuota])
|
||||
|
||||
// Auto-trigger scaffold after conversation starts (ref prevents double-fire)
|
||||
const hasTriggeredScaffold = useRef(false)
|
||||
useEffect(() => {
|
||||
if (phase === 'scaffolding' && !hasTriggeredScaffold.current && !useAIFlowBuilderStore.getState().suggestedBranches.length) {
|
||||
hasTriggeredScaffold.current = true
|
||||
scaffold()
|
||||
}
|
||||
}, [phase, scaffold])
|
||||
|
||||
const handleClose = () => {
|
||||
reset()
|
||||
onClose()
|
||||
}
|
||||
|
||||
const handleOpenInEditor = async () => {
|
||||
if (!assembledTree) return
|
||||
try {
|
||||
const tree = await treesApi.create({
|
||||
name: assembledTree.suggested_name,
|
||||
description: assembledTree.suggested_description,
|
||||
tree_structure: assembledTree.tree_structure,
|
||||
tree_type: metadata.flow_type,
|
||||
status: 'draft',
|
||||
})
|
||||
handleClose()
|
||||
const editorPath =
|
||||
metadata.flow_type === 'procedural'
|
||||
? `/flows/${tree.id}/edit`
|
||||
: `/trees/${tree.id}/edit`
|
||||
navigate(editorPath)
|
||||
} catch {
|
||||
toast.error('Failed to create flow. Please try again.')
|
||||
}
|
||||
}
|
||||
|
||||
const getTitle = () => {
|
||||
switch (phase) {
|
||||
case 'foundation':
|
||||
return 'Build with AI'
|
||||
case 'scaffolding':
|
||||
case 'generating':
|
||||
return 'AI Scaffold'
|
||||
case 'detailing':
|
||||
return 'Branch Detail'
|
||||
case 'reviewing':
|
||||
return 'Review & Assemble'
|
||||
case 'error':
|
||||
return 'AI Flow Builder'
|
||||
default:
|
||||
return 'Build with AI'
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={handleClose}
|
||||
title={getTitle()}
|
||||
size="lg"
|
||||
footer={
|
||||
<WizardStepIndicator phase={phase} />
|
||||
}
|
||||
>
|
||||
{phase === 'foundation' && <FoundationForm />}
|
||||
{phase === 'scaffolding' && <BranchSelector />}
|
||||
{phase === 'generating' && <GeneratingAnimation />}
|
||||
{phase === 'detailing' && <BranchDetailView />}
|
||||
{phase === 'reviewing' && (
|
||||
<TreePreviewCard onOpenInEditor={handleOpenInEditor} />
|
||||
)}
|
||||
{phase === 'error' && <ErrorView />}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
function ErrorView() {
|
||||
const { error, reset, setPhase } = useAIFlowBuilderStore()
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4 py-8">
|
||||
<div className="rounded-lg border border-red-400/20 bg-red-400/5 px-4 py-3 text-sm text-red-400">
|
||||
{error || 'An unexpected error occurred.'}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPhase('foundation')}
|
||||
className="rounded-lg border border-border px-4 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
Go Back
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={reset}
|
||||
className="rounded-lg bg-gradient-brand px-4 py-2 text-sm font-medium text-white shadow-lg shadow-primary/20 hover:opacity-90"
|
||||
>
|
||||
Start Over
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
212
frontend/src/components/ai-builder/BranchDetailView.tsx
Normal file
212
frontend/src/components/ai-builder/BranchDetailView.tsx
Normal file
@@ -0,0 +1,212 @@
|
||||
import { Check, RefreshCw, SkipForward, ChevronRight, ChevronLeft } from 'lucide-react'
|
||||
import { useAIFlowBuilderStore } from '@/store/aiFlowBuilderStore'
|
||||
import { GeneratingAnimation } from './GeneratingAnimation'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function BranchDetailView() {
|
||||
const {
|
||||
selectedBranches,
|
||||
currentBranchIndex,
|
||||
generateBranchDetail,
|
||||
assemble,
|
||||
isLoading,
|
||||
error,
|
||||
phase,
|
||||
setError,
|
||||
} = useAIFlowBuilderStore()
|
||||
|
||||
const viewingIndex = currentBranchIndex
|
||||
const setViewingIndex = (i: number) => useAIFlowBuilderStore.setState({ currentBranchIndex: i })
|
||||
const currentBranch = selectedBranches[viewingIndex]
|
||||
|
||||
const allBranchesHaveDetail = selectedBranches.every((b) => b.steps)
|
||||
const branchesWithDetail = selectedBranches.filter((b) => b.steps).length
|
||||
|
||||
const handleGenerate = async (branchName: string) => {
|
||||
setError(null)
|
||||
await generateBranchDetail(branchName)
|
||||
}
|
||||
|
||||
const handleAssemble = async () => {
|
||||
await assemble()
|
||||
}
|
||||
|
||||
if (phase === 'generating' && isLoading) {
|
||||
return <GeneratingAnimation />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Content area */}
|
||||
<div className="space-y-4">
|
||||
{/* Branch tabs */}
|
||||
<div className="flex items-center gap-2 overflow-x-auto pb-1">
|
||||
{selectedBranches.map((branch, i) => (
|
||||
<button
|
||||
key={branch.name}
|
||||
type="button"
|
||||
onClick={() => setViewingIndex(i)}
|
||||
className={cn(
|
||||
'flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors',
|
||||
viewingIndex === i
|
||||
? 'border-primary/30 bg-primary/10 text-foreground'
|
||||
: 'border-border text-muted-foreground hover:bg-accent',
|
||||
branch.steps && 'pr-2'
|
||||
)}
|
||||
>
|
||||
{branch.name}
|
||||
{branch.steps && (
|
||||
<Check className="h-3 w-3 text-green-400" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Current branch detail */}
|
||||
{currentBranch && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-foreground">{currentBranch.name}</h3>
|
||||
<p className="text-xs text-muted-foreground">{currentBranch.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{currentBranch.steps ? (
|
||||
<div className="space-y-3">
|
||||
{/* Mini tree preview */}
|
||||
<div className="max-h-48 overflow-y-auto rounded-lg border border-border bg-accent/30 p-3">
|
||||
<NodePreview node={currentBranch.steps} depth={0} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleGenerate(currentBranch.name)}
|
||||
disabled={isLoading}
|
||||
className="flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
Regenerate
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-border bg-accent/20 py-8">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Generate AI detail for this branch
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleGenerate(currentBranch.name)}
|
||||
disabled={isLoading}
|
||||
className={cn(
|
||||
'rounded-lg bg-gradient-brand px-4 py-2 text-sm font-medium text-white shadow-lg shadow-primary/20',
|
||||
isLoading ? 'cursor-not-allowed opacity-50' : 'hover:opacity-90'
|
||||
)}
|
||||
>
|
||||
Generate Detail
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (viewingIndex < selectedBranches.length - 1) {
|
||||
setViewingIndex(viewingIndex + 1)
|
||||
}
|
||||
}}
|
||||
className="flex items-center gap-1 rounded-lg border border-border px-3 py-2 text-sm text-muted-foreground hover:bg-accent"
|
||||
>
|
||||
<SkipForward className="h-3.5 w-3.5" />
|
||||
Skip
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="rounded-lg border border-red-400/20 bg-red-400/5 px-3 py-2 text-sm text-red-400">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Navigation — sticky so it's always visible */}
|
||||
<div className="sticky bottom-0 flex items-center justify-between border-t border-border bg-card pt-3 pb-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setViewingIndex(Math.max(0, viewingIndex - 1))}
|
||||
disabled={viewingIndex === 0}
|
||||
className="flex items-center gap-1 rounded-lg border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent disabled:opacity-30"
|
||||
>
|
||||
<ChevronLeft className="h-3.5 w-3.5" />
|
||||
Previous
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setViewingIndex(Math.min(selectedBranches.length - 1, viewingIndex + 1))
|
||||
}
|
||||
disabled={viewingIndex === selectedBranches.length - 1}
|
||||
className="flex items-center gap-1 rounded-lg border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent disabled:opacity-30"
|
||||
>
|
||||
Next
|
||||
<ChevronRight className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{branchesWithDetail}/{selectedBranches.length} detailed
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAssemble}
|
||||
disabled={!allBranchesHaveDetail || isLoading}
|
||||
className={cn(
|
||||
'rounded-lg bg-gradient-brand px-4 py-2 text-sm font-medium text-white shadow-lg shadow-primary/20',
|
||||
allBranchesHaveDetail && !isLoading
|
||||
? 'hover:opacity-90'
|
||||
: 'cursor-not-allowed opacity-50'
|
||||
)}
|
||||
>
|
||||
Assemble Tree
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Recursive mini-preview of a node tree */
|
||||
function NodePreview({ node, depth }: { node: Record<string, unknown>; depth: number }) {
|
||||
const type = node.type as string
|
||||
const label =
|
||||
type === 'decision'
|
||||
? (node.question as string)
|
||||
: (node.title as string) || 'Untitled'
|
||||
const children = (node.children as Record<string, unknown>[]) || []
|
||||
|
||||
const typeColors: Record<string, string> = {
|
||||
decision: 'bg-blue-400',
|
||||
action: 'bg-amber-400',
|
||||
solution: 'bg-green-400',
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ marginLeft: depth * 16 }}>
|
||||
<div className="flex items-center gap-2 py-0.5">
|
||||
<div className={cn('h-2 w-2 rounded-full', typeColors[type] || 'bg-muted-foreground')} />
|
||||
<span className="text-xs text-foreground truncate">{label}</span>
|
||||
<span className="text-[10px] font-label text-muted-foreground">{type}</span>
|
||||
</div>
|
||||
{children.map((child) => (
|
||||
<NodePreview key={child.id as string ?? crypto.randomUUID()} node={child} depth={depth + 1} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
280
frontend/src/components/ai-builder/BranchSelector.tsx
Normal file
280
frontend/src/components/ai-builder/BranchSelector.tsx
Normal file
@@ -0,0 +1,280 @@
|
||||
import { useState } from 'react'
|
||||
import { GripVertical, Plus, X, Pencil, Check } from 'lucide-react'
|
||||
import { useAIFlowBuilderStore } from '@/store/aiFlowBuilderStore'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { AIBranch } from '@/types'
|
||||
|
||||
export function BranchSelector() {
|
||||
const {
|
||||
suggestedBranches,
|
||||
selectedBranches,
|
||||
selectBranches,
|
||||
setPhase,
|
||||
error,
|
||||
} = useAIFlowBuilderStore()
|
||||
|
||||
const [editingIndex, setEditingIndex] = useState<number | null>(null)
|
||||
const [editName, setEditName] = useState('')
|
||||
const [editDesc, setEditDesc] = useState('')
|
||||
const [showAddForm, setShowAddForm] = useState(false)
|
||||
const [newName, setNewName] = useState('')
|
||||
const [newDesc, setNewDesc] = useState('')
|
||||
|
||||
const toggleBranch = (branch: AIBranch) => {
|
||||
const isSelected = selectedBranches.some((b) => b.name === branch.name)
|
||||
if (isSelected) {
|
||||
selectBranches(selectedBranches.filter((b) => b.name !== branch.name))
|
||||
} else {
|
||||
selectBranches([...selectedBranches, branch])
|
||||
}
|
||||
}
|
||||
|
||||
const startEditing = (index: number) => {
|
||||
const branch = selectedBranches[index]
|
||||
setEditingIndex(index)
|
||||
setEditName(branch.name)
|
||||
setEditDesc(branch.description)
|
||||
}
|
||||
|
||||
const saveEdit = () => {
|
||||
if (editingIndex === null || !editName.trim()) return
|
||||
const updated = [...selectedBranches]
|
||||
updated[editingIndex] = {
|
||||
...updated[editingIndex],
|
||||
name: editName.trim(),
|
||||
description: editDesc.trim(),
|
||||
}
|
||||
selectBranches(updated)
|
||||
setEditingIndex(null)
|
||||
}
|
||||
|
||||
const addCustomBranch = () => {
|
||||
if (!newName.trim()) return
|
||||
const branch: AIBranch = {
|
||||
name: newName.trim(),
|
||||
description: newDesc.trim(),
|
||||
isCustom: true,
|
||||
}
|
||||
selectBranches([...selectedBranches, branch])
|
||||
setNewName('')
|
||||
setNewDesc('')
|
||||
setShowAddForm(false)
|
||||
}
|
||||
|
||||
const moveBranch = (fromIndex: number, direction: 'up' | 'down') => {
|
||||
const toIndex = direction === 'up' ? fromIndex - 1 : fromIndex + 1
|
||||
if (toIndex < 0 || toIndex >= selectedBranches.length) return
|
||||
const updated = [...selectedBranches]
|
||||
;[updated[fromIndex], updated[toIndex]] = [updated[toIndex], updated[fromIndex]]
|
||||
selectBranches(updated)
|
||||
}
|
||||
|
||||
const canProceed = selectedBranches.length >= 2
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
AI suggested {suggestedBranches.length} branches. Select, reorder, rename, or add your own.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Branch list */}
|
||||
<div className="space-y-2">
|
||||
{suggestedBranches.map((branch) => {
|
||||
const isSelected = selectedBranches.some((b) => b.name === branch.name)
|
||||
const selectedIndex = selectedBranches.findIndex((b) => b.name === branch.name)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={branch.name}
|
||||
className={cn(
|
||||
'flex items-start gap-3 rounded-lg border p-3 transition-colors cursor-pointer',
|
||||
isSelected
|
||||
? 'border-primary/30 bg-primary/5'
|
||||
: 'border-border bg-card hover:bg-accent/50'
|
||||
)}
|
||||
onClick={() => toggleBranch(branch)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border',
|
||||
isSelected
|
||||
? 'border-primary bg-primary text-white'
|
||||
: 'border-border'
|
||||
)}
|
||||
>
|
||||
{isSelected && <Check className="h-3 w-3" />}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
{editingIndex !== null && selectedIndex === editingIndex ? (
|
||||
<div className="space-y-2" onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
type="text"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
className="w-full rounded border border-border bg-card px-2 py-1 text-sm text-foreground focus:border-primary focus:outline-none"
|
||||
autoFocus
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={editDesc}
|
||||
onChange={(e) => setEditDesc(e.target.value)}
|
||||
className="w-full rounded border border-border bg-card px-2 py-1 text-xs text-muted-foreground focus:border-primary focus:outline-none"
|
||||
/>
|
||||
<div className="flex gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={saveEdit}
|
||||
className="rounded bg-primary px-2 py-0.5 text-xs text-white"
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditingIndex(null)}
|
||||
className="rounded border border-border px-2 py-0.5 text-xs text-muted-foreground"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-sm font-medium text-foreground">{branch.name}</div>
|
||||
<div className="text-xs text-muted-foreground">{branch.description}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{isSelected && editingIndex !== selectedIndex && (
|
||||
<div className="flex items-center gap-0.5" onClick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => moveBranch(selectedIndex, 'up')}
|
||||
disabled={selectedIndex === 0}
|
||||
className="rounded p-1 text-muted-foreground hover:text-foreground disabled:opacity-30"
|
||||
title="Move up"
|
||||
>
|
||||
<GripVertical className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => startEditing(selectedIndex)}
|
||||
className="rounded p-1 text-muted-foreground hover:text-foreground"
|
||||
title="Edit"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Custom branches (not in suggested) */}
|
||||
{selectedBranches
|
||||
.filter((b) => b.isCustom)
|
||||
.map((branch, i) => {
|
||||
return (
|
||||
<div
|
||||
key={`custom-${i}`}
|
||||
className="flex items-start gap-3 rounded-lg border border-primary/30 bg-primary/5 p-3"
|
||||
>
|
||||
<div className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border border-primary bg-primary text-white">
|
||||
<Check className="h-3 w-3" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-foreground">{branch.name}</div>
|
||||
<div className="text-xs text-muted-foreground">{branch.description}</div>
|
||||
<span className="mt-1 inline-block rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-label text-primary">
|
||||
Custom
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
selectBranches(selectedBranches.filter((b) => b.name !== branch.name))
|
||||
}
|
||||
className="rounded p-1 text-muted-foreground hover:text-red-400"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Add custom branch */}
|
||||
{showAddForm ? (
|
||||
<div className="space-y-2 rounded-lg border border-dashed border-border p-3">
|
||||
<input
|
||||
type="text"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
placeholder="Branch name"
|
||||
className="w-full rounded border border-border bg-card px-2 py-1.5 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none"
|
||||
autoFocus
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={newDesc}
|
||||
onChange={(e) => setNewDesc(e.target.value)}
|
||||
placeholder="Brief description"
|
||||
className="w-full rounded border border-border bg-card px-2 py-1.5 text-xs text-muted-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:outline-none"
|
||||
/>
|
||||
<div className="flex gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={addCustomBranch}
|
||||
disabled={!newName.trim()}
|
||||
className="rounded bg-primary px-2.5 py-1 text-xs text-white disabled:opacity-50"
|
||||
>
|
||||
Add
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAddForm(false)}
|
||||
className="rounded border border-border px-2.5 py-1 text-xs text-muted-foreground"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAddForm(true)}
|
||||
className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
Add custom branch
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="rounded-lg border border-red-400/20 bg-red-400/5 px-3 py-2 text-sm text-red-400">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{selectedBranches.length} branch{selectedBranches.length !== 1 ? 'es' : ''} selected (min 2)
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPhase('detailing')}
|
||||
disabled={!canProceed}
|
||||
className={cn(
|
||||
'rounded-lg bg-gradient-brand px-4 py-2 text-sm font-medium text-white shadow-lg shadow-primary/20',
|
||||
canProceed ? 'hover:opacity-90' : 'cursor-not-allowed opacity-50'
|
||||
)}
|
||||
>
|
||||
Continue to Detail
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
163
frontend/src/components/ai-builder/FoundationForm.tsx
Normal file
163
frontend/src/components/ai-builder/FoundationForm.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import { useState } from 'react'
|
||||
import { useAIFlowBuilderStore } from '@/store/aiFlowBuilderStore'
|
||||
import { QuotaDisplay } from './QuotaDisplay'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function FoundationForm() {
|
||||
const { metadata, setMetadata, quota, start, isLoading, error } = useAIFlowBuilderStore()
|
||||
const [tagInput, setTagInput] = useState('')
|
||||
|
||||
const canSubmit =
|
||||
metadata.name.trim().length > 0 &&
|
||||
metadata.description.trim().length > 0 &&
|
||||
!isLoading &&
|
||||
(quota?.allowed !== false)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!canSubmit) return
|
||||
await start()
|
||||
}
|
||||
|
||||
const addTag = () => {
|
||||
const tag = tagInput.trim()
|
||||
if (tag && !metadata.environment_tags.includes(tag)) {
|
||||
setMetadata({ environment_tags: [...metadata.environment_tags, tag] })
|
||||
}
|
||||
setTagInput('')
|
||||
}
|
||||
|
||||
const removeTag = (tag: string) => {
|
||||
setMetadata({ environment_tags: metadata.environment_tags.filter((t) => t !== tag) })
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
{quota && <QuotaDisplay quota={quota} />}
|
||||
|
||||
{/* Flow Type */}
|
||||
<div>
|
||||
<label className="mb-2 block font-label text-[0.6875rem] uppercase tracking-wide text-muted-foreground">
|
||||
Flow Type
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
{(['troubleshooting', 'procedural'] as const).map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
type="button"
|
||||
onClick={() => setMetadata({ flow_type: type })}
|
||||
className={cn(
|
||||
'flex-1 rounded-lg border px-3 py-2.5 text-sm font-medium transition-colors',
|
||||
metadata.flow_type === type
|
||||
? 'border-primary/30 bg-primary/10 text-foreground'
|
||||
: 'border-border bg-card text-muted-foreground hover:bg-accent'
|
||||
)}
|
||||
>
|
||||
{type === 'troubleshooting' ? 'Troubleshooting' : 'Procedural'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Name */}
|
||||
<div>
|
||||
<label className="mb-2 block font-label text-[0.6875rem] uppercase tracking-wide text-muted-foreground">
|
||||
Flow Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={metadata.name}
|
||||
onChange={(e) => setMetadata({ name: e.target.value })}
|
||||
placeholder="e.g. DNS Resolution Failures"
|
||||
className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
|
||||
maxLength={255}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div>
|
||||
<label className="mb-2 block font-label text-[0.6875rem] uppercase tracking-wide text-muted-foreground">
|
||||
Description
|
||||
</label>
|
||||
<textarea
|
||||
value={metadata.description}
|
||||
onChange={(e) => setMetadata({ description: e.target.value })}
|
||||
placeholder="Describe what this flow covers. The more detail you provide, the better the AI suggestions will be."
|
||||
rows={4}
|
||||
className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20 resize-none"
|
||||
maxLength={2000}
|
||||
/>
|
||||
<p className="mt-1 text-right text-[10px] text-muted-foreground">
|
||||
{metadata.description.length}/2000
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Environment Tags */}
|
||||
<div>
|
||||
<label className="mb-2 block font-label text-[0.6875rem] uppercase tracking-wide text-muted-foreground">
|
||||
Environment Tags <span className="normal-case tracking-normal text-muted-foreground/60">(optional)</span>
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={tagInput}
|
||||
onChange={(e) => setTagInput(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
addTag()
|
||||
}
|
||||
}}
|
||||
placeholder="e.g. Windows Server, Active Directory"
|
||||
className="flex-1 rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={addTag}
|
||||
className="rounded-lg border border-border px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
Add
|
||||
</button>
|
||||
</div>
|
||||
{metadata.environment_tags.length > 0 && (
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
{metadata.environment_tags.map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="inline-flex items-center gap-1 rounded-full bg-card border border-border px-2.5 py-0.5 font-label text-xs text-muted-foreground"
|
||||
>
|
||||
{tag}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeTag(tag)}
|
||||
className="ml-0.5 text-muted-foreground/60 hover:text-foreground"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="rounded-lg border border-red-400/20 bg-red-400/5 px-3 py-2 text-sm text-red-400">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!canSubmit}
|
||||
className={cn(
|
||||
'w-full rounded-lg bg-gradient-brand py-2.5 text-sm font-medium text-white shadow-lg shadow-primary/20',
|
||||
canSubmit ? 'hover:opacity-90' : 'cursor-not-allowed opacity-50'
|
||||
)}
|
||||
>
|
||||
{isLoading ? 'Creating...' : 'Continue to AI Scaffold'}
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
33
frontend/src/components/ai-builder/GeneratingAnimation.tsx
Normal file
33
frontend/src/components/ai-builder/GeneratingAnimation.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Sparkles } from 'lucide-react'
|
||||
|
||||
const MESSAGES = [
|
||||
'Analyzing your flow requirements...',
|
||||
'Building decision paths...',
|
||||
'Generating troubleshooting logic...',
|
||||
'Crafting resolution steps...',
|
||||
'Structuring the flow...',
|
||||
]
|
||||
|
||||
export function GeneratingAnimation() {
|
||||
const [messageIndex, setMessageIndex] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setMessageIndex((prev) => (prev + 1) % MESSAGES.length)
|
||||
}, 3000)
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-12">
|
||||
<div className="relative">
|
||||
<div className="h-12 w-12 animate-spin rounded-full border-4 border-border border-t-primary" />
|
||||
<Sparkles className="absolute left-1/2 top-1/2 h-5 w-5 -translate-x-1/2 -translate-y-1/2 text-primary" />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground animate-pulse">
|
||||
{MESSAGES[messageIndex]}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
48
frontend/src/components/ai-builder/QuotaDisplay.tsx
Normal file
48
frontend/src/components/ai-builder/QuotaDisplay.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { AIQuotaStatus } from '@/types'
|
||||
|
||||
interface QuotaDisplayProps {
|
||||
quota: AIQuotaStatus
|
||||
compact?: boolean
|
||||
}
|
||||
|
||||
export function QuotaDisplay({ quota, compact = false }: QuotaDisplayProps) {
|
||||
if (!quota.ai_enabled) return null
|
||||
|
||||
const monthlyRemaining =
|
||||
quota.monthly_limit !== null
|
||||
? Math.max(0, quota.monthly_limit - quota.monthly_used)
|
||||
: null
|
||||
|
||||
const getColor = () => {
|
||||
if (!quota.allowed) return 'text-red-400'
|
||||
if (monthlyRemaining !== null && monthlyRemaining <= 1) return 'text-amber-400'
|
||||
return 'text-green-400'
|
||||
}
|
||||
|
||||
if (compact) {
|
||||
return (
|
||||
<span className={cn('text-xs font-label', getColor())}>
|
||||
{monthlyRemaining !== null
|
||||
? `${monthlyRemaining}/${quota.monthly_limit} builds`
|
||||
: 'Unlimited'}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-border bg-accent/50 px-3 py-1.5">
|
||||
<div className={cn('h-2 w-2 rounded-full', getColor().replace('text-', 'bg-'))} />
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{monthlyRemaining !== null ? (
|
||||
<>
|
||||
<span className={cn('font-medium', getColor())}>{monthlyRemaining}</span>
|
||||
{' '}of {quota.monthly_limit} AI builds remaining
|
||||
</>
|
||||
) : (
|
||||
'Unlimited AI builds'
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
85
frontend/src/components/ai-builder/TreePreviewCard.tsx
Normal file
85
frontend/src/components/ai-builder/TreePreviewCard.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import { GitBranch, Layers, CheckCircle, ArrowRight, RotateCcw } from 'lucide-react'
|
||||
import { useAIFlowBuilderStore } from '@/store/aiFlowBuilderStore'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface TreePreviewCardProps {
|
||||
onOpenInEditor: () => void
|
||||
}
|
||||
|
||||
export function TreePreviewCard({ onOpenInEditor }: TreePreviewCardProps) {
|
||||
const { assembledTree, reset, isLoading } = useAIFlowBuilderStore()
|
||||
|
||||
if (!assembledTree) return null
|
||||
|
||||
const { summary } = assembledTree
|
||||
|
||||
const stats = [
|
||||
{ label: 'Nodes', value: summary.node_count, icon: Layers },
|
||||
{ label: 'Decisions', value: summary.decision_count, icon: GitBranch },
|
||||
{ label: 'Solutions', value: summary.solution_count, icon: CheckCircle },
|
||||
{ label: 'Depth', value: summary.depth, icon: Layers },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="text-center">
|
||||
<div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-green-400/10">
|
||||
<CheckCircle className="h-6 w-6 text-green-400" />
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold text-foreground">
|
||||
Tree Assembled
|
||||
</h3>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
"{assembledTree.suggested_name}" is ready to review in the editor.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Stats grid */}
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{stats.map(({ label, value, icon: Icon }) => (
|
||||
<div
|
||||
key={label}
|
||||
className="flex flex-col items-center rounded-lg border border-border bg-accent/30 p-2.5"
|
||||
>
|
||||
<Icon className="mb-1 h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg font-semibold text-gradient-brand">{value}</span>
|
||||
<span className="text-[10px] font-label uppercase tracking-wide text-muted-foreground">
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
{assembledTree.suggested_description && (
|
||||
<div className="rounded-lg border border-border bg-accent/20 p-3">
|
||||
<p className="text-xs text-muted-foreground">{assembledTree.suggested_description}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpenInEditor}
|
||||
disabled={isLoading}
|
||||
className={cn(
|
||||
'flex flex-1 items-center justify-center gap-2 rounded-lg bg-gradient-brand py-2.5 text-sm font-medium text-white shadow-lg shadow-primary/20',
|
||||
'hover:opacity-90'
|
||||
)}
|
||||
>
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
Open in Editor
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={reset}
|
||||
className="flex items-center gap-2 rounded-lg border border-border px-4 py-2.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
Start Over
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
70
frontend/src/components/ai-builder/WizardStepIndicator.tsx
Normal file
70
frontend/src/components/ai-builder/WizardStepIndicator.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { AIWizardPhase } from '@/types'
|
||||
|
||||
const STEPS = [
|
||||
{ key: 'foundation', label: 'Foundation' },
|
||||
{ key: 'scaffolding', label: 'Scaffold' },
|
||||
{ key: 'detailing', label: 'Detail' },
|
||||
{ key: 'reviewing', label: 'Review' },
|
||||
] as const
|
||||
|
||||
const PHASE_ORDER: Record<string, number> = {
|
||||
foundation: 0,
|
||||
scaffolding: 1,
|
||||
generating: 1,
|
||||
detailing: 2,
|
||||
reviewing: 3,
|
||||
completed: 4,
|
||||
error: -1,
|
||||
}
|
||||
|
||||
interface WizardStepIndicatorProps {
|
||||
phase: AIWizardPhase
|
||||
}
|
||||
|
||||
export function WizardStepIndicator({ phase }: WizardStepIndicatorProps) {
|
||||
const currentIndex = PHASE_ORDER[phase] ?? 0
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1 px-2">
|
||||
{STEPS.map((step, i) => {
|
||||
const isCompleted = currentIndex > i
|
||||
const isCurrent = currentIndex === i
|
||||
|
||||
return (
|
||||
<div key={step.key} className="flex items-center gap-1">
|
||||
{i > 0 && (
|
||||
<div
|
||||
className={cn(
|
||||
'h-px w-4 sm:w-6',
|
||||
isCompleted ? 'bg-primary' : 'bg-border'
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-5 w-5 items-center justify-center rounded-full text-[10px] font-medium',
|
||||
isCompleted && 'bg-primary text-white',
|
||||
isCurrent && 'bg-primary/20 text-primary ring-1 ring-primary/40',
|
||||
!isCompleted && !isCurrent && 'bg-accent text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{isCompleted ? <Check className="h-3 w-3" /> : i + 1}
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
'hidden text-xs sm:inline',
|
||||
isCurrent ? 'font-medium text-foreground' : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{step.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -37,7 +37,9 @@ export function FlowAnalyticsPanel({ treeId }: FlowAnalyticsPanelProps) {
|
||||
const [error, setError] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setLoading(true)
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setError(false)
|
||||
analyticsApi
|
||||
.getFlowAnalytics(treeId, period)
|
||||
|
||||
93
frontend/src/components/common/CreateFlowDropdown.tsx
Normal file
93
frontend/src/components/common/CreateFlowDropdown.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import { useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Plus, ChevronDown, Sparkles, FolderTree, ListOrdered, Wrench } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface CreateFlowDropdownProps {
|
||||
aiEnabled: boolean
|
||||
onOpenAIBuilder: () => void
|
||||
className?: string
|
||||
/** Button label — defaults to "Create Flow" */
|
||||
label?: string
|
||||
}
|
||||
|
||||
export function CreateFlowDropdown({
|
||||
aiEnabled,
|
||||
onOpenAIBuilder,
|
||||
className,
|
||||
label = 'Create Flow',
|
||||
}: CreateFlowDropdownProps) {
|
||||
const [showMenu, setShowMenu] = useState(false)
|
||||
|
||||
return (
|
||||
<div className={cn('relative', className)}>
|
||||
<button
|
||||
onClick={() => setShowMenu(!showMenu)}
|
||||
className="flex items-center gap-2 rounded-lg bg-gradient-brand px-4 py-2 text-sm font-semibold text-white shadow-lg shadow-primary/20 hover:opacity-90 transition-opacity"
|
||||
>
|
||||
<Plus size={16} />
|
||||
{label}
|
||||
<ChevronDown size={14} />
|
||||
</button>
|
||||
{showMenu && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-10" onClick={() => setShowMenu(false)} />
|
||||
<div className="absolute right-0 z-20 mt-1 w-56 rounded-lg border border-border bg-card p-1 shadow-xl backdrop-blur-sm">
|
||||
<Link
|
||||
to="/trees/new"
|
||||
onClick={() => setShowMenu(false)}
|
||||
className="flex items-center gap-3 rounded-md px-3 py-2.5 text-sm text-foreground hover:bg-accent"
|
||||
>
|
||||
<FolderTree className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<div className="font-medium">Troubleshooting Tree</div>
|
||||
<div className="text-xs text-muted-foreground">Branching decision flow</div>
|
||||
</div>
|
||||
</Link>
|
||||
<Link
|
||||
to="/flows/new"
|
||||
onClick={() => setShowMenu(false)}
|
||||
className="flex items-center gap-3 rounded-md px-3 py-2.5 text-sm text-foreground hover:bg-accent"
|
||||
>
|
||||
<ListOrdered className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<div className="font-medium">Procedural Flow</div>
|
||||
<div className="text-xs text-muted-foreground">Step-by-step procedure</div>
|
||||
</div>
|
||||
</Link>
|
||||
<Link
|
||||
to="/flows/new?type=maintenance"
|
||||
onClick={() => setShowMenu(false)}
|
||||
className="flex items-center gap-3 rounded-md px-3 py-2.5 text-sm text-foreground hover:bg-accent"
|
||||
>
|
||||
<Wrench className="h-4 w-4 text-amber-400" />
|
||||
<div>
|
||||
<div className="font-medium">Maintenance Flow</div>
|
||||
<div className="text-xs text-muted-foreground">Scheduled multi-target tasks</div>
|
||||
</div>
|
||||
</Link>
|
||||
{aiEnabled && (
|
||||
<>
|
||||
<div className="my-1 border-t border-border" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setShowMenu(false)
|
||||
onOpenAIBuilder()
|
||||
}}
|
||||
className="flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-sm text-foreground hover:bg-accent"
|
||||
>
|
||||
<Sparkles className="h-4 w-4 text-primary" />
|
||||
<div className="text-left">
|
||||
<div className="font-medium">Build with AI</div>
|
||||
<div className="text-xs text-muted-foreground">AI-assisted flow creation</div>
|
||||
</div>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -29,7 +29,9 @@ export function Modal({ isOpen, onClose, title, children, footer, size = 'md', a
|
||||
setIsFullScreen(next)
|
||||
try {
|
||||
localStorage.setItem('rf-editor-fullscreen', String(next))
|
||||
} catch {}
|
||||
} catch {
|
||||
// localStorage unavailable — ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Close on Escape key
|
||||
|
||||
@@ -40,6 +40,7 @@ export function QuickLaunch({ open, onClose }: QuickLaunchProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setSelectedIndex(0)
|
||||
treesApi.list({ sort_by: 'updated_at' })
|
||||
.then(trees => setRecentTrees(trees.slice(0, 4)))
|
||||
|
||||
@@ -2,32 +2,36 @@ import { useEffect, useState } from 'react'
|
||||
import { LayoutGrid, Box, PenLine, Clock, FileText, Bookmark, BarChart3, Settings, PanelLeftClose, PanelLeftOpen, MessageSquareText } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useUserPreferencesStore } from '@/store/userPreferencesStore'
|
||||
import { usePinnedFlowsStore } from '@/store/pinnedFlowsStore'
|
||||
import { PinnedFlowsSection } from '@/components/sidebar/PinnedFlowsSection'
|
||||
import { NavItem } from './NavItem'
|
||||
import { sessionsApi, treesApi } from '@/api'
|
||||
import { pinnedFlowsApi } from '@/api/pinnedFlows'
|
||||
import type { PinnedFlow } from '@/api/pinnedFlows'
|
||||
import { toast } from '@/lib/toast'
|
||||
|
||||
export function Sidebar() {
|
||||
const sidebarCollapsed = useUserPreferencesStore(s => s.sidebarCollapsed)
|
||||
const toggleSidebar = useUserPreferencesStore(s => s.toggleSidebar)
|
||||
|
||||
const pinnedItems = usePinnedFlowsStore((s) => s.items)
|
||||
const loadPinned = usePinnedFlowsStore((s) => s.load)
|
||||
const unpinFlow = usePinnedFlowsStore((s) => s.unpin)
|
||||
|
||||
const [activeSessionCount, setActiveSessionCount] = useState(0)
|
||||
const [pinnedFlows, setPinnedFlows] = useState<PinnedFlow[]>([])
|
||||
const [treeCounts, setTreeCounts] = useState({ total: 0, troubleshooting: 0, procedural: 0, maintenance: 0 })
|
||||
|
||||
// Load pinned flows on mount
|
||||
useEffect(() => {
|
||||
loadPinned()
|
||||
}, [loadPinned])
|
||||
|
||||
// Fetch sidebar data on mount
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const [activeSessions, allTrees, pinnedData] = await Promise.all([
|
||||
const [activeSessions, allTrees] = await Promise.all([
|
||||
sessionsApi.list({ completed: false, size: 50 }).catch(() => []),
|
||||
treesApi.list({ sort_by: 'name' }).catch(() => []),
|
||||
pinnedFlowsApi.list().catch(() => ({ items: [], count: 0 })),
|
||||
])
|
||||
setActiveSessionCount(activeSessions.length)
|
||||
setPinnedFlows(pinnedData.items)
|
||||
|
||||
const total = allTrees.length
|
||||
const troubleshooting = allTrees.filter(t => t.tree_type === 'troubleshooting').length
|
||||
@@ -41,16 +45,6 @@ export function Sidebar() {
|
||||
fetchData()
|
||||
}, [])
|
||||
|
||||
const handleUnpin = async (treeId: string) => {
|
||||
try {
|
||||
await pinnedFlowsApi.unpin(treeId)
|
||||
setPinnedFlows(prev => prev.filter(f => f.tree_id !== treeId))
|
||||
toast.success('Unpinned from sidebar')
|
||||
} catch {
|
||||
toast.error('Failed to unpin flow')
|
||||
}
|
||||
}
|
||||
|
||||
const handleSidebarWheel = (e: React.WheelEvent<HTMLElement>) => {
|
||||
const sidebar = e.currentTarget
|
||||
const canSidebarScroll = sidebar.scrollHeight > sidebar.clientHeight
|
||||
@@ -89,7 +83,7 @@ export function Sidebar() {
|
||||
) : (
|
||||
<>
|
||||
{/* Pinned Flows */}
|
||||
<PinnedFlowsSection flows={pinnedFlows} onUnpin={handleUnpin} />
|
||||
<PinnedFlowsSection flows={pinnedItems} onUnpin={unpinFlow} />
|
||||
|
||||
<div className="border-b border-[hsl(var(--border-subtle))]" />
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Pencil, Globe, Lock, Trash2, GitBranch, FileText, Wrench } from 'lucide-react'
|
||||
import { Pencil, Globe, Lock, Trash2, GitBranch, FileText, Wrench, Star } from 'lucide-react'
|
||||
import type { TreeListItem } from '@/types'
|
||||
import { TagBadges } from '@/components/common/TagBadges'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -13,6 +13,9 @@ interface TreeGridViewProps {
|
||||
onFolderCreated: (parentId?: string | null) => void
|
||||
onDeleteTree: (tree: TreeListItem) => void
|
||||
onForkTree?: (treeId: string) => void
|
||||
pinnedTreeIds?: Set<string>
|
||||
onTogglePin?: (treeId: string) => void
|
||||
pinLoadingTreeIds?: Set<string>
|
||||
}
|
||||
|
||||
export function TreeGridView({
|
||||
@@ -21,6 +24,9 @@ export function TreeGridView({
|
||||
onTagClick,
|
||||
onDeleteTree,
|
||||
onForkTree,
|
||||
pinnedTreeIds,
|
||||
onTogglePin,
|
||||
pinLoadingTreeIds,
|
||||
}: TreeGridViewProps) {
|
||||
const { canEditTree, canDeleteTree } = usePermissions()
|
||||
|
||||
@@ -29,7 +35,7 @@ export function TreeGridView({
|
||||
{trees.map((tree) => (
|
||||
<div
|
||||
key={tree.id}
|
||||
className="bg-card border border-border rounded-2xl p-4 transition-all hover:-translate-y-0.5 hover:border-primary/30 hover:shadow-md sm:p-6"
|
||||
className="relative bg-card border border-border rounded-2xl p-4 transition-all hover:-translate-y-0.5 hover:border-primary/30 hover:shadow-md sm:p-6"
|
||||
>
|
||||
<div className="mb-2 flex items-start justify-between gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -48,6 +54,26 @@ export function TreeGridView({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{onTogglePin && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
onTogglePin(tree.id)
|
||||
}}
|
||||
disabled={pinLoadingTreeIds?.has(tree.id)}
|
||||
aria-label={pinnedTreeIds?.has(tree.id) ? 'Remove from favorites' : 'Add to favorites'}
|
||||
className={cn(
|
||||
'rounded-md p-1 transition-colors',
|
||||
pinnedTreeIds?.has(tree.id)
|
||||
? 'text-amber-400 hover:text-amber-300'
|
||||
: 'text-muted-foreground/40 hover:text-amber-400',
|
||||
pinLoadingTreeIds?.has(tree.id) && 'opacity-50 pointer-events-none'
|
||||
)}
|
||||
>
|
||||
<Star size={14} fill={pinnedTreeIds?.has(tree.id) ? 'currentColor' : 'none'} />
|
||||
</button>
|
||||
)}
|
||||
{tree.is_public ? (
|
||||
<span title="Public tree">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Pencil, Globe, Lock, GitBranch, FileText, Trash2, Wrench } from 'lucide-react'
|
||||
import { Pencil, Globe, Lock, GitBranch, FileText, Trash2, Wrench, Star } from 'lucide-react'
|
||||
import type { TreeListItem } from '@/types'
|
||||
import { TagBadges } from '@/components/common/TagBadges'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -13,6 +13,9 @@ interface TreeListViewProps {
|
||||
onFolderCreated: (parentId?: string | null) => void
|
||||
onDeleteTree: (tree: TreeListItem) => void
|
||||
onForkTree?: (treeId: string) => void
|
||||
pinnedTreeIds?: Set<string>
|
||||
onTogglePin?: (treeId: string) => void
|
||||
pinLoadingTreeIds?: Set<string>
|
||||
}
|
||||
|
||||
export function TreeListView({
|
||||
@@ -21,6 +24,9 @@ export function TreeListView({
|
||||
onTagClick,
|
||||
onDeleteTree,
|
||||
onForkTree,
|
||||
pinnedTreeIds,
|
||||
onTogglePin,
|
||||
pinLoadingTreeIds,
|
||||
}: TreeListViewProps) {
|
||||
const { canEditTree } = usePermissions()
|
||||
|
||||
@@ -84,6 +90,26 @@ export function TreeListView({
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{onTogglePin && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
onTogglePin(tree.id)
|
||||
}}
|
||||
disabled={pinLoadingTreeIds?.has(tree.id)}
|
||||
aria-label={pinnedTreeIds?.has(tree.id) ? 'Remove from favorites' : 'Add to favorites'}
|
||||
className={cn(
|
||||
'shrink-0 rounded-md p-1 transition-colors',
|
||||
pinnedTreeIds?.has(tree.id)
|
||||
? 'text-amber-400 hover:text-amber-300'
|
||||
: 'text-muted-foreground/40 hover:text-amber-400',
|
||||
pinLoadingTreeIds?.has(tree.id) && 'opacity-50 pointer-events-none'
|
||||
)}
|
||||
>
|
||||
<Star size={16} fill={pinnedTreeIds?.has(tree.id) ? 'currentColor' : 'none'} />
|
||||
</button>
|
||||
)}
|
||||
{onForkTree && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Pencil, Globe, Lock, ChevronUp, ChevronDown, GitBranch, FileText, Trash2, Wrench } from 'lucide-react'
|
||||
import { Pencil, Globe, Lock, ChevronUp, ChevronDown, GitBranch, FileText, Trash2, Wrench, Star } from 'lucide-react'
|
||||
import type { TreeListItem } from '@/types'
|
||||
import { TagBadges } from '@/components/common/TagBadges'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -15,6 +15,9 @@ interface TreeTableViewProps {
|
||||
onDeleteTree: (tree: TreeListItem) => void
|
||||
onSortChange?: (sortBy: string) => void
|
||||
onForkTree?: (treeId: string) => void
|
||||
pinnedTreeIds?: Set<string>
|
||||
onTogglePin?: (treeId: string) => void
|
||||
pinLoadingTreeIds?: Set<string>
|
||||
}
|
||||
|
||||
type SortColumn = 'name' | 'category' | 'version' | 'usage' | 'updated'
|
||||
@@ -26,6 +29,9 @@ export function TreeTableView({
|
||||
onDeleteTree,
|
||||
onSortChange,
|
||||
onForkTree,
|
||||
pinnedTreeIds,
|
||||
onTogglePin,
|
||||
pinLoadingTreeIds,
|
||||
}: TreeTableViewProps) {
|
||||
const { canEditTree } = usePermissions()
|
||||
const [sortColumn, setSortColumn] = useState<SortColumn | null>(null)
|
||||
@@ -73,6 +79,11 @@ export function TreeTableView({
|
||||
<table className="w-full">
|
||||
<thead className="bg-accent/50 sticky top-0 z-10">
|
||||
<tr className="border-b border-border">
|
||||
{onTogglePin && (
|
||||
<th className="w-10 px-2 py-3 text-center">
|
||||
<Star size={14} className="inline text-muted-foreground" />
|
||||
</th>
|
||||
)}
|
||||
<th
|
||||
className="px-4 py-3 text-left text-sm font-medium text-muted-foreground cursor-pointer hover:text-foreground"
|
||||
onClick={() => handleSort('name')}
|
||||
@@ -132,6 +143,28 @@ export function TreeTableView({
|
||||
<tbody className="bg-transparent">
|
||||
{trees.map((tree) => (
|
||||
<tr key={tree.id} className="border-b border-border last:border-0 hover:bg-accent/50">
|
||||
{onTogglePin && (
|
||||
<td className="w-10 px-2 py-3 text-center">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
onTogglePin(tree.id)
|
||||
}}
|
||||
disabled={pinLoadingTreeIds?.has(tree.id)}
|
||||
aria-label={pinnedTreeIds?.has(tree.id) ? 'Remove from favorites' : 'Add to favorites'}
|
||||
className={cn(
|
||||
'rounded-md p-1 transition-colors',
|
||||
pinnedTreeIds?.has(tree.id)
|
||||
? 'text-amber-400 hover:text-amber-300'
|
||||
: 'text-muted-foreground/40 hover:text-amber-400',
|
||||
pinLoadingTreeIds?.has(tree.id) && 'opacity-50 pointer-events-none'
|
||||
)}
|
||||
>
|
||||
<Star size={14} fill={pinnedTreeIds?.has(tree.id) ? 'currentColor' : 'none'} />
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium text-foreground truncate max-w-[200px]">
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Star } from 'lucide-react'
|
||||
import { Modal } from '@/components/common/Modal'
|
||||
import { analyticsApi } from '@/api'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { markSessionRated } from './csatUtils'
|
||||
|
||||
interface CSATModalProps {
|
||||
isOpen: boolean
|
||||
@@ -10,26 +11,6 @@ interface CSATModalProps {
|
||||
sessionId: string
|
||||
}
|
||||
|
||||
const RATED_SESSIONS_KEY = 'rf-rated-sessions'
|
||||
|
||||
function getRatedSessions(): string[] {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(RATED_SESSIONS_KEY) || '[]')
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function markSessionRated(sessionId: string) {
|
||||
const rated = getRatedSessions()
|
||||
rated.push(sessionId)
|
||||
localStorage.setItem(RATED_SESSIONS_KEY, JSON.stringify(rated.slice(-100)))
|
||||
}
|
||||
|
||||
export function hasBeenRated(sessionId: string): boolean {
|
||||
return getRatedSessions().includes(sessionId)
|
||||
}
|
||||
|
||||
export function CSATModal({ isOpen, onClose, sessionId }: CSATModalProps) {
|
||||
const [rating, setRating] = useState(0)
|
||||
const [hoveredRating, setHoveredRating] = useState(0)
|
||||
|
||||
19
frontend/src/components/session/csatUtils.ts
Normal file
19
frontend/src/components/session/csatUtils.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
const RATED_SESSIONS_KEY = 'rf-rated-sessions'
|
||||
|
||||
export function getRatedSessions(): string[] {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(RATED_SESSIONS_KEY) || '[]')
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export function markSessionRated(sessionId: string) {
|
||||
const rated = getRatedSessions()
|
||||
rated.push(sessionId)
|
||||
localStorage.setItem(RATED_SESSIONS_KEY, JSON.stringify(rated.slice(-100)))
|
||||
}
|
||||
|
||||
export function hasBeenRated(sessionId: string): boolean {
|
||||
return getRatedSessions().includes(sessionId)
|
||||
}
|
||||
@@ -10,51 +10,89 @@ interface PinnedFlowsSectionProps {
|
||||
onUnpin: (treeId: string) => void
|
||||
}
|
||||
|
||||
const TRUNCATE_COUNT = 5
|
||||
|
||||
export function PinnedFlowsSection({ flows, onUnpin }: PinnedFlowsSectionProps) {
|
||||
const navigate = useNavigate()
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
const [showAll, setShowAll] = useState(false)
|
||||
|
||||
const handleToggleCollapse = () => {
|
||||
if (collapsed) {
|
||||
setShowAll(false) // Reset to truncated on re-expand
|
||||
}
|
||||
setCollapsed(!collapsed)
|
||||
}
|
||||
|
||||
const visibleFlows = showAll ? flows : flows.slice(0, TRUNCATE_COUNT)
|
||||
const hasMore = flows.length > TRUNCATE_COUNT
|
||||
|
||||
const handleFlowClick = (flow: PinnedFlow) => {
|
||||
setShowAll(false) // Collapse back to 5 on navigation
|
||||
navigate(getTreeNavigatePath(flow.tree_id, flow.tree_type))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="px-3 py-2">
|
||||
<button
|
||||
onClick={() => setCollapsed(!collapsed)}
|
||||
onClick={handleToggleCollapse}
|
||||
className="flex w-full items-center gap-1 px-3 mb-1 font-heading text-[0.6875rem] font-bold uppercase tracking-[0.04em] text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{collapsed ? <ChevronRight size={12} /> : <ChevronDown size={12} />}
|
||||
Pinned
|
||||
{flows.length > 0 && (
|
||||
<span className="ml-auto text-[0.625rem] font-normal">{flows.length}</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{!collapsed && (
|
||||
<div className="space-y-0.5 max-h-[280px] overflow-y-auto">
|
||||
<div
|
||||
className="overflow-hidden transition-[max-height] duration-[250ms] ease-out"
|
||||
style={{
|
||||
maxHeight: collapsed ? 0 : showAll
|
||||
? `${flows.length * 36 + 40}px`
|
||||
: `${Math.min(flows.length, TRUNCATE_COUNT) * 36 + 40}px`,
|
||||
}}
|
||||
>
|
||||
<div className="space-y-0.5">
|
||||
{flows.length === 0 ? (
|
||||
<p className="px-3 py-2 text-xs text-muted-foreground">
|
||||
Pin your most-used flows here
|
||||
</p>
|
||||
) : (
|
||||
flows.map(flow => (
|
||||
<button
|
||||
key={flow.tree_id}
|
||||
onClick={() => navigate(getTreeNavigatePath(flow.tree_id, flow.tree_type))}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault()
|
||||
onUnpin(flow.tree_id)
|
||||
}}
|
||||
className={cn(
|
||||
'group flex w-full items-center gap-2.5 rounded-lg px-3 py-1.5 text-[0.8125rem] font-medium transition-colors',
|
||||
'text-muted-foreground hover:bg-[hsl(var(--sidebar-hover))] hover:text-foreground'
|
||||
)}
|
||||
title={`${flow.tree_name} (right-click to unpin)`}
|
||||
>
|
||||
<span className="text-sm shrink-0">
|
||||
{flow.tree_type === 'procedural' ? '📋' : flow.tree_type === 'maintenance' ? '🛠️' : '🔧'}
|
||||
</span>
|
||||
<span className="truncate flex-1 text-left">{flow.tree_name}</span>
|
||||
<Pin size={12} className="shrink-0 opacity-0 group-hover:opacity-40 transition-opacity" />
|
||||
</button>
|
||||
))
|
||||
<>
|
||||
{visibleFlows.map(flow => (
|
||||
<button
|
||||
key={flow.tree_id}
|
||||
onClick={() => handleFlowClick(flow)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault()
|
||||
onUnpin(flow.tree_id)
|
||||
}}
|
||||
className={cn(
|
||||
'group flex w-full items-center gap-2.5 rounded-lg px-3 py-1.5 text-[0.8125rem] font-medium transition-colors',
|
||||
'text-muted-foreground hover:bg-[hsl(var(--sidebar-hover))] hover:text-foreground'
|
||||
)}
|
||||
title={`${flow.tree_name} (right-click to unpin)`}
|
||||
>
|
||||
<span className="text-sm shrink-0">
|
||||
{flow.tree_type === 'procedural' ? '📋' : flow.tree_type === 'maintenance' ? '🛠️' : '🔧'}
|
||||
</span>
|
||||
<span className="truncate flex-1 text-left">{flow.tree_name}</span>
|
||||
<Pin size={12} className="shrink-0 opacity-0 group-hover:opacity-40 transition-opacity" />
|
||||
</button>
|
||||
))}
|
||||
{hasMore && (
|
||||
<button
|
||||
onClick={() => setShowAll(!showAll)}
|
||||
className="w-full px-3 py-1 text-xs text-muted-foreground hover:text-foreground transition-colors text-left"
|
||||
>
|
||||
{showAll ? 'Show less' : `Show more (${flows.length})`}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ const TYPE_CONFIG: Record<Exclude<NodeType, 'answer'>, { icon: typeof HelpCircle
|
||||
}
|
||||
|
||||
function cloneWithoutChildren(node: TreeStructure): TreeStructure {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { children: _children, ...rest } = node
|
||||
return structuredClone(rest) as TreeStructure
|
||||
}
|
||||
@@ -44,8 +45,11 @@ export function NodeEditorPanel({ nodeId, onClose, onSelectType }: NodeEditorPan
|
||||
// (e.g., answer stub → decision/action/solution via type picker)
|
||||
useEffect(() => {
|
||||
if (node) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setDraft(cloneWithoutChildren(node))
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setIsDirty(false)
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setShowDeleteConfirm(false)
|
||||
}
|
||||
}, [nodeId, node?.type]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
@@ -57,6 +61,7 @@ export function NodeEditorPanel({ nodeId, onClose, onSelectType }: NodeEditorPan
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
if (!draft || !node) return
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { children: _children, ...draftWithoutChildren } = draft
|
||||
updateNode(nodeId, draftWithoutChildren)
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ export function useTreeLayout(): UseTreeLayoutResult {
|
||||
|
||||
if (!treeStructure) return { rawNodes: nodes, rawEdges: edges }
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function walk(node: TreeStructure, _parentId?: string | null) {
|
||||
const isCollapsed = collapsedNodeIds.has(node.id)
|
||||
const hasChildren = (node.children?.length ?? 0) > 0
|
||||
|
||||
Reference in New Issue
Block a user