Files
resolutionflow/frontend/src/pages/QuickStartPage.tsx
chihlasm 97cd297f46 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>
2026-02-23 00:03:54 -05:00

512 lines
20 KiB
TypeScript

import { useState, useEffect, useRef, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import { Search, Loader2, Star, ChevronLeft, ChevronRight } from 'lucide-react'
import { treesApi } from '@/api/trees'
import { sessionsApi } from '@/api/sessions'
import type { TreeListItem } from '@/types'
import type { Session } from '@/types/session'
import { getTreeNavigatePath } from '@/lib/routing'
import { usePermissions } from '@/hooks/usePermissions'
import { useAuthStore } from '@/store/authStore'
import { usePinnedFlowsStore } from '@/store/pinnedFlowsStore'
import { useUserPreferencesStore } from '@/store/userPreferencesStore'
import { usePaginationParams } from '@/hooks/usePaginationParams'
import { useCachedQuota } from '@/hooks/useCachedQuota'
import { QuickStats } from '@/components/dashboard/QuickStats'
import { SessionsPanel } from '@/components/dashboard/SessionsPanel'
import { TreeGridView } from '@/components/library/TreeGridView'
import { TreeListView } from '@/components/library/TreeListView'
import { TreeTableView } from '@/components/library/TreeTableView'
import { ViewToggle } from '@/components/library/ViewToggle'
import { AIFlowBuilderModal } from '@/components/ai-builder/AIFlowBuilderModal'
import { CreateFlowDropdown } from '@/components/common/CreateFlowDropdown'
import { cn } from '@/lib/utils'
function timeAgo(dateStr: string): string {
const now = Date.now()
const then = new Date(dateStr).getTime()
const diffMs = now - then
const minutes = Math.floor(diffMs / 60000)
if (minutes < 1) return 'just now'
if (minutes < 60) return `${minutes}m ago`
const hours = Math.floor(minutes / 60)
if (hours < 24) return `${hours}h ago`
const days = Math.floor(hours / 24)
if (days === 1) return 'Yesterday'
return `${days}d ago`
}
export function QuickStartPage() {
const navigate = useNavigate()
const { canCreateTrees } = usePermissions()
const user = useAuthStore((s) => s.user)
// Search state
const [query, setQuery] = useState('')
const [searchResults, setSearchResults] = useState<TreeListItem[]>([])
const [isSearching, setIsSearching] = useState(false)
const [showResults, setShowResults] = useState(false)
const searchRef = useRef<HTMLDivElement>(null)
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
// Sessions state
const [activeSessions, setActiveSessions] = useState<Session[]>([])
const [allSessions, setAllSessions] = useState<Session[]>([])
// My Flows state
const [myFlows, setMyFlows] = useState<TreeListItem[]>([])
const [isLoadingFlows, setIsLoadingFlows] = useState(true)
const [hasNextPage, setHasNextPage] = useState(false)
const [allFlowsCeiling, setAllFlowsCeiling] = useState(false)
// Favorites state
const [showAllFavorites, setShowAllFavorites] = useState(false)
// AI Builder
const [showAIBuilder, setShowAIBuilder] = useState(false)
const { aiEnabled } = useCachedQuota()
// Pin store
const pinnedItems = usePinnedFlowsStore((s) => s.items)
const pinnedIsLoading = usePinnedFlowsStore((s) => s.isLoading)
const loadPinned = usePinnedFlowsStore((s) => s.load)
const isMutatingByTreeId = usePinnedFlowsStore((s) => s.isMutatingByTreeId)
const togglePin = usePinnedFlowsStore((s) => s.toggle)
const pinnedTreeIds = useMemo(() => new Set(pinnedItems.map((f) => f.tree_id)), [pinnedItems])
const pinLoadingTreeIds = useMemo(
() => new Set(Object.entries(isMutatingByTreeId).filter(([, v]) => v).map(([k]) => k)),
[isMutatingByTreeId]
)
// Preferences
const { dashboardMyFlowsView, setDashboardMyFlowsView } = useUserPreferencesStore()
// Pagination
const { page, pageSize, setPage, setPageSize } = usePaginationParams({
defaultPageSize: 10,
allowedPageSizes: [10, 25, 50, 'all'],
})
// Load pinned flows
useEffect(() => { loadPinned() }, [loadPinned])
// Load sessions on mount
useEffect(() => {
Promise.all([
sessionsApi.list({ completed: false, size: 5 }).catch(() => []),
sessionsApi.list({ size: 10 }).catch(() => []),
]).then(([active, recent]) => {
setActiveSessions(active)
setAllSessions(recent)
})
}, [])
// Load my flows when page/size or user changes
useEffect(() => {
if (!user?.id) return
const loadFlows = async () => {
setIsLoadingFlows(true)
setAllFlowsCeiling(false)
if (pageSize === 'all') {
// Fetch in chunks of 100, max 500
let allItems: TreeListItem[] = []
let skip = 0
const CHUNK = 100
const MAX = 500
while (true) {
const chunk = await treesApi.list({
author_id: user.id,
sort_by: 'updated_at',
limit: CHUNK,
skip,
})
allItems = [...allItems, ...chunk]
if (chunk.length < CHUNK || allItems.length >= MAX) {
if (allItems.length >= MAX) {
allItems = allItems.slice(0, MAX)
setAllFlowsCeiling(true)
}
break
}
skip += CHUNK
}
setMyFlows(allItems)
setHasNextPage(false)
} else {
const numSize = pageSize as number
const response = await treesApi.list({
author_id: user.id,
sort_by: 'updated_at',
limit: numSize + 1,
skip: (page - 1) * numSize,
})
setHasNextPage(response.length > numSize)
setMyFlows(response.slice(0, numSize))
}
setIsLoadingFlows(false)
}
loadFlows().catch(() => setIsLoadingFlows(false))
}, [user?.id, page, pageSize])
// Debounced search
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current)
if (query.length < 2) {
setSearchResults([])
setShowResults(false)
setIsSearching(false)
return
}
setIsSearching(true)
setShowResults(true)
debounceRef.current = setTimeout(async () => {
try {
const results = await treesApi.search(query, 8)
setSearchResults(results)
} catch {
setSearchResults([])
} finally {
setIsSearching(false)
}
}, 300)
return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }
}, [query])
// Close search dropdown on outside click
useEffect(() => {
function handleClick(e: MouseEvent) {
if (searchRef.current && !searchRef.current.contains(e.target as Node)) {
setShowResults(false)
}
}
document.addEventListener('mousedown', handleClick)
return () => document.removeEventListener('mousedown', handleClick)
}, [])
// Stats
const openSessions = activeSessions.length
const todaySessions = allSessions.filter(s => {
const d = new Date(s.started_at)
const now = new Date()
return d.toDateString() === now.toDateString()
}).length
const completedSessions = allSessions.filter(s => s.completed_at).length
const recentSessionItems = allSessions.slice(0, 5).map(s => ({
id: s.id,
treeName: s.tree_snapshot?.name || 'Unknown',
status: (s.completed_at ? 'completed' : 'in_progress') as 'completed' | 'in_progress',
ticketNumber: s.ticket_number || undefined,
timeAgo: timeAgo(s.started_at),
}))
// Favorites display
const MAX_VISIBLE_FAVORITES = 8
const visibleFavorites = showAllFavorites ? pinnedItems : pinnedItems.slice(0, MAX_VISIBLE_FAVORITES)
const hasMoreFavorites = pinnedItems.length > MAX_VISIBLE_FAVORITES
// Handlers
const handleStartSession = (treeId: string, treeType?: string) => {
navigate(getTreeNavigatePath(treeId, treeType))
}
const handleDeleteTree = () => {} // Not used on dashboard
const handleTagClick = () => {} // Not used on dashboard
const handleFolderCreated = () => {} // Not used on dashboard
// Page size options
const pageSizeOptions: (number | 'all')[] = [10, 25, 50, 'all']
return (
<div className="p-6 space-y-6">
{/* Page Header */}
<div className="flex items-start justify-between">
<div>
<h1 className="font-heading text-[1.375rem] font-bold tracking-tight text-foreground">
Dashboard
</h1>
<p className="mt-1 text-sm text-muted-foreground">
Welcome back. Here&apos;s what&apos;s happening with your flows.
</p>
</div>
<div className="flex items-center gap-2">
{canCreateTrees && (
<CreateFlowDropdown
aiEnabled={aiEnabled}
onOpenAIBuilder={() => setShowAIBuilder(true)}
/>
)}
</div>
</div>
{/* Quick Stats */}
<QuickStats
stats={[
{ label: 'My Flows', value: myFlows.length, gradient: true },
{ label: 'Sessions Today', value: todaySessions, color: '#f59e0b' },
{ label: 'Open Sessions', value: openSessions, meta: `${completedSessions} completed` },
{ label: 'Favorites', value: pinnedItems.length },
]}
/>
{/* Search */}
<div ref={searchRef} className="relative">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
onFocus={() => query.length >= 2 && setShowResults(true)}
placeholder="Search flows, sessions, tags…"
className="w-full rounded-lg border border-border bg-card py-2.5 pl-9 pr-4 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
/>
{showResults && (
<div className="absolute z-10 mt-1 w-full rounded-lg border border-border bg-card shadow-xl overflow-hidden">
{isSearching ? (
<div className="flex items-center justify-center py-6">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : searchResults.length === 0 ? (
<div className="px-4 py-6 text-center text-sm text-muted-foreground">No results found</div>
) : (
<ul className="max-h-72 overflow-y-auto py-1">
{searchResults.map((tree) => (
<li key={tree.id}>
<button
onClick={() => navigate(getTreeNavigatePath(tree.id, tree.tree_type))}
className="w-full px-4 py-3 text-left transition-colors hover:bg-accent"
>
<div className="text-sm font-medium text-foreground">{tree.name}</div>
{tree.description && (
<div className="mt-0.5 line-clamp-1 text-xs text-muted-foreground">{tree.description}</div>
)}
</button>
</li>
))}
</ul>
)}
</div>
)}
</div>
{/* Recent Sessions */}
<SessionsPanel sessions={recentSessionItems} delay={150} />
{/* Favorites Section */}
<div>
<div className="mb-3 flex items-center justify-between">
<h2 className="font-heading text-lg font-semibold text-foreground">
Favorites
{pinnedItems.length > 0 && (
<span className="ml-2 text-sm font-normal text-muted-foreground">({pinnedItems.length})</span>
)}
</h2>
{hasMoreFavorites && (
<button
onClick={() => setShowAllFavorites(!showAllFavorites)}
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
>
{showAllFavorites ? 'Show less' : 'View all favorites'}
</button>
)}
</div>
{pinnedIsLoading ? (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} className="h-20 rounded-xl bg-card border border-border animate-pulse" />
))}
</div>
) : pinnedItems.length === 0 ? (
<p className="text-sm text-muted-foreground py-4">
Star a flow to pin it here for quick access.
</p>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
{visibleFavorites.map((flow) => (
<button
key={flow.tree_id}
onClick={() => navigate(getTreeNavigatePath(flow.tree_id, flow.tree_type))}
className="group relative flex items-center gap-3 rounded-xl bg-card border border-border p-4 text-left transition-colors hover:border-border/80 hover:bg-accent/50"
>
<span className="text-lg shrink-0">
{flow.tree_type === 'procedural' ? '📋' : flow.tree_type === 'maintenance' ? '🛠️' : '🔧'}
</span>
<span className="truncate text-sm font-medium text-foreground">{flow.tree_name}</span>
<button
onClick={(e) => {
e.stopPropagation()
e.preventDefault()
togglePin(flow.tree_id)
}}
aria-label="Remove from favorites"
className="absolute top-2 right-2 rounded-md p-1 text-amber-400 opacity-0 group-hover:opacity-100 hover:text-amber-300 transition-all"
>
<Star size={14} fill="currentColor" />
</button>
</button>
))}
</div>
)}
</div>
{/* My Flows Section */}
<div>
<div className="mb-3 flex items-center justify-between">
<h2 className="font-heading text-lg font-semibold text-foreground">My Flows</h2>
<div className="flex items-center gap-2">
<ViewToggle view={dashboardMyFlowsView} onChange={setDashboardMyFlowsView} />
</div>
</div>
{isLoadingFlows ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="h-32 rounded-xl bg-card border border-border animate-pulse" />
))}
</div>
) : myFlows.length === 0 ? (
<div className="py-12 text-center">
<p className="text-muted-foreground mb-4">You haven&apos;t created any flows yet.</p>
{canCreateTrees && (
<CreateFlowDropdown
aiEnabled={aiEnabled}
onOpenAIBuilder={() => setShowAIBuilder(true)}
label="Create your first flow"
/>
)}
</div>
) : (
<>
{allFlowsCeiling && (
<p className="mb-3 text-sm text-muted-foreground">
Showing first 500 flows. Use search or filters to find specific flows.
</p>
)}
{dashboardMyFlowsView === 'grid' && (
<TreeGridView
trees={myFlows}
onStartSession={handleStartSession}
onTagClick={handleTagClick}
onFolderCreated={handleFolderCreated}
onDeleteTree={handleDeleteTree}
pinnedTreeIds={pinnedTreeIds}
onTogglePin={togglePin}
pinLoadingTreeIds={pinLoadingTreeIds}
/>
)}
{dashboardMyFlowsView === 'list' && (
<TreeListView
trees={myFlows}
onStartSession={handleStartSession}
onTagClick={handleTagClick}
onFolderCreated={handleFolderCreated}
onDeleteTree={handleDeleteTree}
pinnedTreeIds={pinnedTreeIds}
onTogglePin={togglePin}
pinLoadingTreeIds={pinLoadingTreeIds}
/>
)}
{dashboardMyFlowsView === 'table' && (
<TreeTableView
trees={myFlows}
onStartSession={handleStartSession}
onTagClick={handleTagClick}
onFolderCreated={handleFolderCreated}
onDeleteTree={handleDeleteTree}
pinnedTreeIds={pinnedTreeIds}
onTogglePin={togglePin}
pinLoadingTreeIds={pinLoadingTreeIds}
/>
)}
{/* Pagination controls */}
{pageSize !== 'all' && (
<div className="mt-4 flex items-center justify-between">
<div className="flex items-center gap-2">
<button
onClick={() => setPage(page - 1)}
disabled={page <= 1}
className={cn(
'flex items-center gap-1 rounded-md border border-border px-3 py-1.5 text-sm transition-colors',
page <= 1 ? 'opacity-50 cursor-not-allowed' : 'hover:bg-accent'
)}
>
<ChevronLeft size={14} />
Prev
</button>
<span className="text-sm text-muted-foreground">Page {page}</span>
<button
onClick={() => setPage(page + 1)}
disabled={!hasNextPage}
className={cn(
'flex items-center gap-1 rounded-md border border-border px-3 py-1.5 text-sm transition-colors',
!hasNextPage ? 'opacity-50 cursor-not-allowed' : 'hover:bg-accent'
)}
>
Next
<ChevronRight size={14} />
</button>
</div>
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">Show:</span>
<select
value={String(pageSize)}
onChange={(e) => {
const val = e.target.value
setPageSize(val === 'all' ? 'all' : parseInt(val, 10))
}}
className="rounded-md border border-border bg-card px-2 py-1 text-sm text-foreground focus:border-primary focus:outline-none"
>
{pageSizeOptions.map((opt) => (
<option key={String(opt)} value={String(opt)}>
{opt === 'all' ? 'All' : opt}
</option>
))}
</select>
</div>
</div>
)}
{pageSize === 'all' && (
<div className="mt-4 flex items-center justify-end">
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">Show:</span>
<select
value="all"
onChange={(e) => {
const val = e.target.value
setPageSize(val === 'all' ? 'all' : parseInt(val, 10))
}}
className="rounded-md border border-border bg-card px-2 py-1 text-sm text-foreground focus:border-primary focus:outline-none"
>
{pageSizeOptions.map((opt) => (
<option key={String(opt)} value={String(opt)}>
{opt === 'all' ? 'All' : opt}
</option>
))}
</select>
</div>
</div>
)}
</>
)}
</div>
{/* AI Builder Modal */}
{showAIBuilder && (
<AIFlowBuilderModal
isOpen={showAIBuilder}
onClose={() => setShowAIBuilder(false)}
/>
)}
</div>
)
}
export default QuickStartPage