feat: flow export/import + procedural Flow Assist (#96)

* feat: add flow export/import backend (migration, endpoints, schemas)

Add .rfflow file export/import support:
- Migration 050: import_metadata JSONB column on trees
- GET /trees/{id}/export?format=json|xml endpoint
- POST /trees/import endpoint (creates draft, resolves categories/tags)
- FlowExportEnvelope, FlowImportRequest/Response schemas
- import_metadata field on TreeResponse

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add flow export/import frontend + backend tests

Frontend:
- ExportFlowModal with JSON/XML format selection + download
- ImportFlowModal with drag-drop file picker + preview step
- rfflowParser for client-side JSON/XML .rfflow parsing
- Export buttons on editor toolbar and library action menus
- Import button on library page next to Create New
- Provenance display for imported flows in editor
- flowTransfer API client + types

Backend:
- Fix regex->pattern deprecation in export endpoint
- 12 integration tests covering export, import, round-trip,
  access control, tag/category creation, version validation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: remove XML export, JSON-only for .rfflow files

- Remove XML builder, format query param, and XML tests
- Simplify ExportFlowModal (no format picker)
- Simplify rfflowParser (JSON-only)
- Remove format field from schemas and types

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: match Flow Assist chat input to AI Assistant styling + strengthen one-question prompt

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add procedural flow support to AI chat builder (Flow Assist)

- Add procedural-specific system prompts (schema, interview protocol, response format)
- Dispatch prompts by flow_type: procedural/maintenance use flat steps schema, troubleshooting uses decision tree schema
- Parse [STEPS_UPDATE] and [INTAKE_FORM] markers in AI responses
- Add validate_generated_procedural_steps() validator
- Handle intake form extraction in AI chat import endpoint
- Add StaticStepsPreview component for procedural flow preview
- Update store and page to render correct preview by flow type

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add flow type selection to Flow Assist entry points

- CreateFlowDropdown now shows "Build with Flow Assist" under each flow type
- Library page "Flow Assist" button respects current type filter
- Clean up unused AIFlowBuilderModal references

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: update CLAUDE.md with AI chat builder and intake form learnings

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: refine assistant chat prompt for concise answers and focused questions

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: switch AI provider to Claude Sonnet 4.6 + add shift+enter hint to chat inputs

- Default AI_PROVIDER changed from gemini to anthropic
- AI_MODEL and AI_MODEL_ANTHROPIC updated to claude-sonnet-4-6
- Added "Shift + Enter for a new line" hint below all chat textareas

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: update CLAUDE.md with AI provider and chat input learnings

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: add editor-embedded Flow Assist design document

Design for replacing the standalone /ai/chat page with context-aware
AI side panels embedded in each editor (Troubleshooting + Procedural).
Covers ghost node suggestion system, output-based thresholds,
config-driven model routing, knowledge integration, and per-flow
chat persistence.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: add editor-embedded Flow Assist implementation plan

25-task plan across 9 phases covering backend foundation, frontend
infrastructure, tree/procedural editor integration, AI-assisted create,
old code removal, action-type dispatch, suggestion audit trail, and
build verification.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use actual root node ID in orphan validation check

AI-generated trees use descriptive IDs (e.g., "verify-account-exists")
instead of "root", causing the root node to be falsely flagged as orphaned.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add config-driven AI model tier routing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: extend AI chat session with tree_id and archived_at

Add tree_id FK (CASCADE) for editor-embedded sessions and archived_at
timestamp column to ai_chat_sessions table.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add AI suggestion audit trail table

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add action_type and focal_node_id to AI chat message API

- Add VALID_ACTION_TYPES literal and action_type/focal_node_id fields to
  AIChatMessageRequest schema
- Add tree_id field to AIChatStartRequest schema for editor-embedded sessions
- Update send_message() signature with action_type and focal_node_id params
- Update start_chat_session() signature with tree_id param
- Pass new params through endpoints to service functions
- All new params have defaults so existing behavior is unchanged

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: route AI model selection through action-type config

Update get_ai_provider() to accept an optional model override parameter
(applied only to AnthropicProvider; Gemini always uses its own model).
Thread action_type-based model resolution through send_message() and
generate_final_tree() in the AI chat service.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add TypeScript types for editor-embedded AI

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add shared ContextMenu component

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add useEditorAI hook and editorAI API client

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add EditorAIPanel component with Chat and Suggestions tabs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: integrate AI panel, context menu, and ghost nodes in tree editor

- Add AI Assist panel toggle button to tree editor toolbar
- Wire EditorAIPanel alongside TreeEditorLayout with single-panel rule
- Thread onNodeContextMenu through TreeEditorLayout → FlowCanvas → FlowCanvasNode
- Add right-click context menu with Generate Branch, Explain Node, Delete actions
- Add ghost node detection (_suggestion flag) with dashed border + opacity styling
- Add Accept/Dismiss overlay buttons on ghost nodes for future suggestion handling

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: integrate AI panel, context menu, and ghost steps in procedural editor

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add AI prompt dialog and wire into CreateFlowDropdown

Replace navigation to /ai/chat with an inline AIPromptDialog modal
that collects a single prompt, generates a flow via the editor AI API,
imports it, and navigates to the editor with the AI panel open.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add glassmorphism to AI prompt dialog + maintenance Flow Assist button

- Use .glass-card-static on AIPromptDialog card for consistent design system
- Add "Build with Flow Assist" button to maintenance section in CreateFlowDropdown

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: remove standalone Flow Assist page and old AI chat components

Remove the old /ai/chat page, AI wizard modal, and all associated
components/stores/types now replaced by the editor-embedded AI panel.

Deleted:
- AIChatBuilderPage, ai-chat/ components, aiChatStore, aiChat API, ai-chat types
- AIFlowBuilderModal, ai-builder/ components, aiFlowBuilderStore

Cleaned up:
- Router (removed /ai/chat route)
- Sidebar (removed Flow Assist nav item)
- MyTreesPage (removed AI builder modal and button)
- TreeLibraryPage (removed Flow Assist button)
- API and type barrel exports

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add delta response parsing and action-type prompt dispatch

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add AI suggestion audit trail endpoints

Create/list/resolve endpoints for tracking AI-applied changes to flows.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add APScheduler task to auto-archive stale AI chat sessions

Archives AI chat sessions with no activity for 30 days, runs daily at 3 AM.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: update project status for editor-embedded Flow Assist

- Add Editor-Embedded Flow Assist to CURRENT-STATE.md in-progress items
- Update CLAUDE.md: fix stale lessons (#41, #46), add new patterns (#47 editor AI architecture, #48 orphan validation)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use correct model alias in AI_MODEL_TIERS standard tier

The dated model ID `claude-sonnet-4-6-20250514` was causing 502 errors.
Use the alias `claude-sonnet-4-6` which matches AI_MODEL_ANTHROPIC.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: send live flow context to AI Assist for full editor awareness

The AI panel now sends the current tree structure (troubleshooting) or
steps + intake form (procedural/maintenance) with each message. This
gives the AI full visibility into node details, questions, descriptions,
options, and intake form fields — not just the node ID.

- Backend: add flow_context param to schema, endpoint, and service
- Frontend: add getFlowContext callback to useEditorAI hook
- TreeEditorPage: passes treeStructure as flow context
- ProceduralEditorPage: passes steps + intakeForm as flow context

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: include flow name and description in AI Assist context

Both editors now send name and description alongside the flow structure,
so the AI can reference what the flow is about when responding.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: increase AI timeout to 120s and limit retries to 1

The 45s timeout was too short for generation tasks with full flow
context in the system prompt. The Anthropic SDK's default 2 retries
caused requests to hang for ~136s before failing. Now: 120s timeout
with max 1 retry = faster failure if it does timeout.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: wire AI-generated flow structures into editor stores

The useEditorAI hook was ignoring result.working_tree from AI responses,
so generated steps/trees never appeared in the editor. Now:
- useEditorAI calls onFlowUpdate when working_tree is present in response
- ProceduralEditorPage handles steps + intake form updates via replaceSteps
- TreeEditorPage handles tree structure updates via replaceTreeStructure
- Both stores have new bulk-replace methods for AI integration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: add lessons learned for full-stack integration, Anthropic retries, model tiers

#49 Always verify frontend consumes backend response fields
#50 Anthropic SDK max_retries=1 to avoid 3× timeout
#51 AI model tier routing via settings.get_model_for_action()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: move AI Assist panel to full-height side layout in both editors

The AI panel was nested inside the content area, only spanning the
step list / canvas section. Now it sits at the outermost flex level,
spanning the full page height alongside all content (toolbar,
collapsible sections, steps/canvas). This prevents the panel from
overlapping content and lets the editor area properly shrink.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: AI Assist panel as fixed right drawer (matching Copilot/Scratchpad)

Convert EditorAIPanel from in-flow flex child to fixed right-side drawer
overlay, same pattern as CopilotPanel and ScratchpadSidebar. The panel
is fixed at right:0 spanning full viewport height, and editor pages add
pr-[380px] padding when open so content shifts left without overlap.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: AI Assist panel sits below topbar with slide-in animation

- Panel now uses top:56px to sit below the app shell topbar instead of
  covering it (matches the main-content grid cell area)
- Added slideInRight CSS animation for smooth drawer entrance
- Editor pages use dynamic paddingRight via PANEL_WIDTH constant
- ChatTab upgraded: markdown rendering, CopilotPanel-style message
  bubbles, auto-focus input, Shift+Enter hint
- All borders use --glass-border for consistent glassmorphism

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: AI Assist panel as in-flow flex sibling (not fixed/overlay)

Replace fixed positioning with in-flow flex layout. The outermost div
is now a horizontal flex row: content column (flex-1 min-w-0) + panel
(w-[380px] shrink-0). When the panel opens, the content column
automatically shrinks — no padding hacks or z-index stacking needed.
This guarantees the content shifts left and stays fully visible.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: AI Copilot panel as in-flow flex sibling in session navigation pages

Changed CopilotPanel from fixed overlay to flex layout sibling so it
pushes main content instead of covering it during active sessions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: remove duplicate CLAUDE.md lessons #47-48

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit was merged in pull request #96.
This commit is contained in:
chihlasm
2026-03-07 15:51:37 -05:00
committed by GitHub
parent 0fb1ef33a0
commit 0dc6123c0c
90 changed files with 7637 additions and 2472 deletions

View File

@@ -1,158 +0,0 @@
import { useCallback, useEffect, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useAIChatStore } from '@/store/aiChatStore'
import { ChatPanel } from '@/components/ai-chat/ChatPanel'
import { ChatToolbar } from '@/components/ai-chat/ChatToolbar'
import { EmptyPreview } from '@/components/ai-chat/EmptyPreview'
import { StaticTreePreview } from '@/components/ai-chat/StaticTreePreview'
import { Spinner } from '@/components/common/Spinner'
import { getTreeEditorPath } from '@/lib/routing'
import { toast } from '@/lib/toast'
import type { TreeStructure } from '@/types'
export function AIChatBuilderPage() {
const navigate = useNavigate()
const [searchParams, setSearchParams] = useSearchParams()
const flowType = searchParams.get('type') === 'procedural' ? 'procedural' : 'troubleshooting'
const {
sessionId,
status,
currentPhase,
messages,
isResponding,
workingTree,
treeMetadata,
generatedTree,
isGenerating,
error,
startSession,
sendMessage,
generateTree,
importToEditor,
abandonSession,
resumeSession,
} = useAIChatStore()
// Start or resume session on mount
useEffect(() => {
const resumeId = searchParams.get('session')
if (resumeId && !sessionId) {
resumeSession(resumeId)
} else if (!sessionId && status === 'idle') {
startSession(flowType)
}
}, []) // eslint-disable-line react-hooks/exhaustive-deps
// Store sessionId in URL for resume support
useEffect(() => {
if (sessionId && !searchParams.get('session')) {
setSearchParams((prev) => {
const next = new URLSearchParams(prev)
next.set('session', sessionId)
return next
}, { replace: true })
}
}, [sessionId, searchParams, setSearchParams])
const handleSendMessage = useCallback(
(content: string) => {
sendMessage(content)
},
[sendMessage]
)
const [isSaving, setIsSaving] = useState(false)
const handleGenerate = useCallback(() => {
generateTree()
}, [generateTree])
const handleSave = useCallback(async () => {
if (isSaving) return
setIsSaving(true)
try {
const treeId = await importToEditor({
name: treeMetadata?.name,
description: treeMetadata?.description,
tags: treeMetadata?.tags,
})
const path = getTreeEditorPath(treeId, flowType)
navigate(path)
toast.success('Flow saved to library')
} catch {
toast.error('Failed to save flow')
} finally {
setIsSaving(false)
}
}, [isSaving, importToEditor, treeMetadata, flowType, navigate])
const handleReset = useCallback(async () => {
await abandonSession()
// Clear session from URL
setSearchParams((prev) => {
const next = new URLSearchParams(prev)
next.delete('session')
return next
}, { replace: true })
startSession(flowType)
}, [abandonSession, startSession, flowType, setSearchParams])
// Show error toast
useEffect(() => {
if (error) {
toast.error(error)
}
}, [error])
if (status === 'idle' && !sessionId) {
return (
<div className="flex h-full items-center justify-center">
<Spinner />
</div>
)
}
const previewTree = (generatedTree || workingTree) as TreeStructure | null
return (
<div className="flex h-full flex-col">
<ChatToolbar
currentPhase={currentPhase}
status={status}
isGenerating={isGenerating}
hasGeneratedTree={!!generatedTree}
isSaving={isSaving}
onGenerate={handleGenerate}
onSave={handleSave}
onReset={handleReset}
/>
<div className="flex flex-1 overflow-hidden">
{/* Left panel: Chat (60%) */}
<div className="flex w-3/5 flex-col border-r border-border max-lg:w-full">
<ChatPanel
messages={messages}
isResponding={isResponding}
onSendMessage={handleSendMessage}
disabled={status !== 'active'}
/>
</div>
{/* Right panel: Tree preview (40%) — hidden below 1024px */}
<div className="w-2/5 overflow-hidden bg-background max-lg:hidden">
{previewTree ? (
<StaticTreePreview
tree={previewTree}
name={treeMetadata?.name}
/>
) : (
<EmptyPreview />
)}
</div>
</div>
</div>
)
}
export default AIChatBuilderPage

View File

@@ -233,39 +233,42 @@ export default function AssistantChatPage() {
{/* Input */}
<div className="px-6 py-4 border-t shrink-0" style={{ borderColor: 'var(--glass-border)' }}>
<div className="flex items-end gap-3 max-w-3xl mx-auto">
<textarea
ref={inputRef}
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Ask about IT, networking, troubleshooting..."
rows={3}
className="flex-1 resize-none rounded-xl border bg-card text-foreground text-sm placeholder:text-muted-foreground px-4 py-3 focus:outline-none focus:border-[rgba(6,182,212,0.3)]"
style={{ borderColor: 'var(--glass-border)' }}
disabled={loading}
/>
<div className="flex flex-col gap-2">
<button
onClick={handleSend}
disabled={!input.trim() || loading}
className="bg-gradient-brand text-[#101114] p-3 rounded-xl hover:opacity-90 active:scale-[0.97] transition-all disabled:opacity-40"
title="Send message"
>
<Send size={18} />
</button>
{messages.length >= 2 && (
<div className="max-w-3xl mx-auto">
<div className="flex items-end gap-3">
<textarea
ref={inputRef}
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Ask about IT, networking, troubleshooting..."
rows={3}
className="flex-1 resize-none rounded-xl border bg-card text-foreground text-sm placeholder:text-muted-foreground px-4 py-3 focus:outline-none focus:border-[rgba(6,182,212,0.3)]"
style={{ borderColor: 'var(--glass-border)' }}
disabled={loading}
/>
<div className="flex flex-col gap-2">
<button
onClick={() => setShowConclude(true)}
disabled={loading}
className="p-3 rounded-xl border text-muted-foreground hover:text-amber-400 hover:border-amber-400/30 hover:bg-amber-400/10 transition-all disabled:opacity-40"
style={{ borderColor: 'var(--glass-border)' }}
title="Conclude session"
onClick={handleSend}
disabled={!input.trim() || loading}
className="bg-gradient-brand text-[#101114] p-3 rounded-xl hover:opacity-90 active:scale-[0.97] transition-all disabled:opacity-40"
title="Send message"
>
<Flag size={18} />
<Send size={18} />
</button>
)}
{messages.length >= 2 && (
<button
onClick={() => setShowConclude(true)}
disabled={loading}
className="p-3 rounded-xl border text-muted-foreground hover:text-amber-400 hover:border-amber-400/30 hover:bg-amber-400/10 transition-all disabled:opacity-40"
style={{ borderColor: 'var(--glass-border)' }}
title="Conclude session"
>
<Flag size={18} />
</button>
)}
</div>
</div>
<p className="text-[0.625rem] text-muted-foreground mt-1.5 px-1">Shift + Enter for a new line</p>
</div>
</div>
</>

View File

@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { Play, Pencil, Share2, Trash2, GitBranch, Clock, TrendingUp, FolderTree, Plus, ListOrdered, ChevronDown, Wrench, Sparkles } from 'lucide-react'
import { Play, Pencil, Share2, Trash2, GitBranch, Clock, TrendingUp, FolderTree, Plus, ListOrdered, ChevronDown, Wrench } from 'lucide-react'
import { treesApi } from '@/api/trees'
import { sessionsApi } from '@/api/sessions'
import type { TreeListItem } from '@/types'
@@ -12,8 +12,6 @@ import { cn } from '@/lib/utils'
import { useAuthStore } from '@/store/authStore'
import { usePermissions } from '@/hooks/usePermissions'
import { toast } from '@/lib/toast'
import { AIFlowBuilderModal } from '@/components/ai-builder/AIFlowBuilderModal'
import { aiBuilderApi } from '@/api/aiBuilder'
import { ForkModal } from '@/components/library/ForkModal'
interface TreeWithStats extends TreeListItem {
@@ -35,18 +33,12 @@ export function MyTreesPage() {
const [treeToShare, setTreeToShare] = useState<TreeWithStats | null>(null)
const [showShareModal, setShowShareModal] = useState(false)
const [showCreateMenu, setShowCreateMenu] = useState(false)
const [showAIBuilder, setShowAIBuilder] = useState(false)
const [aiEnabled, setAiEnabled] = useState(false)
const [forkTarget, setForkTarget] = useState<TreeWithStats | null>(null)
useEffect(() => {
loadMyTrees()
}, [user?.id])
useEffect(() => {
aiBuilderApi.getQuota().then((q) => setAiEnabled(q.ai_enabled)).catch(() => {})
}, [])
const loadMyTrees = async () => {
if (!user?.id) return
setIsLoading(true)
@@ -178,25 +170,6 @@ export function MyTreesPage() {
<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={() => {
setShowCreateMenu(false)
setShowAIBuilder(true)
}}
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">Flow Assist</div>
<div className="text-xs text-muted-foreground">AI-powered flow builder</div>
</div>
</button>
</>
)}
</div>
</>
)}
@@ -425,11 +398,6 @@ export function MyTreesPage() {
/>
)}
{/* AI Flow Builder Modal */}
<AIFlowBuilderModal
isOpen={showAIBuilder}
onClose={() => setShowAIBuilder(false)}
/>
</div>
)
}

View File

@@ -1,6 +1,6 @@
import { useEffect, useState, useCallback } from 'react'
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
import { Save, ArrowLeft, ListOrdered, Wrench, Settings, FileText, Calendar } from 'lucide-react'
import { Save, ArrowLeft, ListOrdered, Wrench, Settings, FileText, Calendar, Sparkles, Layers } from 'lucide-react'
import { treesApi } from '@/api/trees'
import { useProceduralEditorStore } from '@/store/proceduralEditorStore'
import { CollapsibleEditorSection } from '@/components/procedural-editor/CollapsibleEditorSection'
@@ -10,8 +10,12 @@ import { getScheduleSummary } from '@/components/procedural-editor/scheduleUtils
import { StepList } from '@/components/procedural-editor/StepList'
import { TagInput } from '@/components/common/TagInput'
import { Spinner } from '@/components/common/Spinner'
import { EditorAIPanel } from '@/components/editor-ai/EditorAIPanel'
import { ContextMenu } from '@/components/common/ContextMenu'
import { useEditorAI } from '@/hooks/useEditorAI'
import { cn } from '@/lib/utils'
import { toast } from '@/lib/toast'
import type { TreeType, MaintenanceSchedule, TargetList } from '@/types'
import type { TreeType, MaintenanceSchedule, TargetList, ProceduralStep, IntakeFormField } from '@/types'
type SectionKey = 'details' | 'intake' | 'schedule'
@@ -42,8 +46,34 @@ export function ProceduralEditorPage() {
setIsSaving,
markSaved,
getTreeForSave,
replaceSteps,
} = useProceduralEditorStore()
const steps = useProceduralEditorStore(s => s.steps)
const handleFlowUpdate = useCallback((workingTree: Record<string, unknown>, metadata?: Record<string, unknown> | null) => {
const stepsData = workingTree.steps as ProceduralStep[] | undefined
if (stepsData && Array.isArray(stepsData)) {
// Intake form may be in working_tree or in metadata
const intakeData = (workingTree.intake_form || metadata?.intake_form) as IntakeFormField[] | undefined
replaceSteps(stepsData, intakeData)
}
}, [replaceSteps])
const editorAI = useEditorAI({
flowType: 'procedural',
treeId: id,
getFlowContext: useCallback(() => {
return {
name,
description,
steps: steps as unknown as Record<string, unknown>[],
intake_form: intakeForm,
}
}, [steps, intakeForm, name, description]),
onFlowUpdate: handleFlowUpdate,
})
const isMaintenance = treeType === 'maintenance'
const flowLabel = isMaintenance ? 'Maintenance Flow' : 'Procedure'
@@ -150,7 +180,9 @@ export function ProceduralEditorPage() {
}
return (
<div className="flex h-full flex-col overflow-hidden">
<div className="flex h-full overflow-hidden">
{/* Main content column */}
<div className="flex min-w-0 flex-1 flex-col overflow-hidden">
{/* Toolbar — sticky */}
<div className="flex shrink-0 items-center justify-between border-b border-border bg-card px-4 py-2">
<div className="flex items-center gap-3">
@@ -175,6 +207,19 @@ export function ProceduralEditorPage() {
{isDirty && (
<span className="text-xs text-muted-foreground">Unsaved changes</span>
)}
<button
onClick={() => editorAI.isOpen ? editorAI.closePanel() : editorAI.openPanel()}
title="Toggle AI Assist panel"
className={cn(
'flex items-center gap-1.5 rounded-md border border-border px-3 py-2 text-sm font-medium transition-colors',
editorAI.isOpen
? 'bg-primary/10 text-primary border-primary/30'
: 'text-muted-foreground hover:bg-accent hover:text-foreground'
)}
>
<Sparkles className="h-4 w-4" />
AI Assist
</button>
<button
onClick={() => handleSave('draft')}
disabled={isSaving}
@@ -272,10 +317,55 @@ export function ProceduralEditorPage() {
)}
</div>
{/* Step List — flex-1, scrolls independently */}
{/* Step List */}
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
<StepList />
<StepList onStepContextMenu={editorAI.openContextMenu} />
</div>
{editorAI.contextMenu && (
<ContextMenu
position={editorAI.contextMenu.position}
items={[
{
id: 'generate-steps',
label: 'Generate Steps After',
icon: <Sparkles className="h-4 w-4" />,
onClick: () => editorAI.triggerAction(
editorAI.contextMenu!.nodeId,
'add_steps',
`Generate steps after this step`
),
},
{
id: 'expand-step',
label: 'Expand Step',
icon: <Layers className="h-4 w-4" />,
onClick: () => editorAI.triggerAction(
editorAI.contextMenu!.nodeId,
'quick_action',
`Expand this step into detailed substeps`
),
},
]}
onClose={editorAI.closeContextMenu}
/>
)}
</div>{/* end main content column */}
<EditorAIPanel
isOpen={editorAI.isOpen}
onClose={editorAI.closePanel}
focalNode={null}
flowName={name}
flowType={isMaintenance ? 'maintenance' : 'procedural'}
nodeCount={steps.length}
messages={editorAI.messages}
input={editorAI.input}
onInputChange={editorAI.setInput}
onSend={editorAI.sendMessage}
isLoading={editorAI.isLoading}
suggestions={editorAI.suggestions}
/>
</div>
)
}

View File

@@ -599,7 +599,7 @@ export function ProceduralNavigationPage() {
)}
</div>
{/* Right panel - step detail */}
{/* Right panel - step detail + copilot */}
<div className="min-h-0 flex-1 overflow-y-auto overscroll-y-contain p-4 sm:p-6">
{currentStep && (
<StepDetail
@@ -636,6 +636,17 @@ export function ProceduralNavigationPage() {
</div>
)}
</div>
{/* AI Copilot - in-flow panel */}
{treeId && copilotOpen && (
<CopilotPanel
isOpen={copilotOpen}
onClose={() => setCopilotOpen(false)}
treeId={treeId}
sessionId={session?.id}
currentNodeId={runtimeSteps[currentStepIndex]?.id}
/>
)}
</div>
{/* CSAT Modal */}
@@ -708,18 +719,9 @@ export function ProceduralNavigationPage() {
/>
)}
{/* AI Copilot */}
{/* AI Copilot toggle button */}
{treeId && (
<>
<CopilotToggle isOpen={copilotOpen} onToggle={() => setCopilotOpen(true)} />
<CopilotPanel
isOpen={copilotOpen}
onClose={() => setCopilotOpen(false)}
treeId={treeId}
sessionId={session?.id}
currentNodeId={runtimeSteps[currentStepIndex]?.id}
/>
</>
<CopilotToggle isOpen={copilotOpen} onToggle={() => setCopilotOpen(true)} />
)}
</div>
)

View File

@@ -17,7 +17,7 @@ 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'
import { toast } from '@/lib/toast'
@@ -67,7 +67,6 @@ export function QuickStartPage() {
const [showAllFavorites, setShowAllFavorites] = useState(false)
// AI Builder
const [showAIBuilder, setShowAIBuilder] = useState(false)
const { aiEnabled } = useCachedQuota()
// Tab state
@@ -454,7 +453,7 @@ export function QuickStartPage() {
{activeTab === 'mine' && canCreateTrees && (
<CreateFlowDropdown
aiEnabled={aiEnabled}
onOpenAIBuilder={() => setShowAIBuilder(true)}
/>
)}
<ViewToggle view={dashboardMyFlowsView} onChange={setDashboardMyFlowsView} />
@@ -481,7 +480,7 @@ export function QuickStartPage() {
{activeTab === 'mine' && canCreateTrees && (
<CreateFlowDropdown
aiEnabled={aiEnabled}
onOpenAIBuilder={() => setShowAIBuilder(true)}
label="Create your first flow"
/>
)}
@@ -646,13 +645,6 @@ export function QuickStartPage() {
</div>
)}
{/* AI Builder Modal */}
{showAIBuilder && (
<AIFlowBuilderModal
isOpen={showAIBuilder}
onClose={() => setShowAIBuilder(false)}
/>
)}
</div>
)
}

View File

@@ -1,7 +1,7 @@
import { useEffect, useState, useCallback } from 'react'
import { useEffect, useState, useCallback, useRef } from 'react'
import { useParams, useNavigate, useBlocker } from 'react-router-dom'
import { useStore } from 'zustand'
import { Undo2, Redo2, Save, CheckCircle2, Monitor, FileText, Code2, LayoutList, BarChart3, Settings } from 'lucide-react'
import { Undo2, Redo2, Save, CheckCircle2, Monitor, FileText, Code2, LayoutList, BarChart3, Settings, Download, Sparkles } from 'lucide-react'
import { getMonacoEditor } from '@/components/tree-editor/code-mode'
import { treesApi } from '@/api/trees'
import { treeMarkdownApi } from '@/api/treeMarkdown'
@@ -16,6 +16,11 @@ import { Spinner } from '@/components/common/Spinner'
import { cn, safeGetItem } from '@/lib/utils'
import { toast } from '@/lib/toast'
import { FlowAnalyticsPanel } from '@/components/analytics/FlowAnalyticsPanel'
import { ExportFlowModal } from '@/components/library/ExportFlowModal'
import { EditorAIPanel } from '@/components/editor-ai/EditorAIPanel'
import { ContextMenu } from '@/components/common/ContextMenu'
import { useEditorAI } from '@/hooks/useEditorAI'
import { findNodeInTree } from '@/store/treeEditorStore'
/** Recursively check if any node in the tree has type 'answer' */
function hasAnswerNodes(node: TreeStructure): boolean {
@@ -31,11 +36,13 @@ export function TreeEditorPage() {
const {
name,
description,
isDirty,
isLoading,
isSaving,
validationErrors,
editorMode,
treeStructure,
initNewTree,
loadTree,
loadDraft,
@@ -48,7 +55,10 @@ export function TreeEditorPage() {
setSaving,
selectNode,
updateNode,
deleteNode,
setEditorMode,
getAllNodeIds,
replaceTreeStructure,
} = useTreeEditorStore()
// Access undo/redo from temporal store
@@ -61,6 +71,8 @@ export function TreeEditorPage() {
const [editingNodeId, setEditingNodeId] = useState<string | null>(null)
const [isFixing, setIsFixing] = useState(false)
const [fixProposals, setFixProposals] = useState<AIFixProposal[] | null>(null)
const [showExportModal, setShowExportModal] = useState(false)
const [importMetadata, setImportMetadata] = useState<Record<string, string | null> | null>(null)
// Mobile detection
const [isMobile, setIsMobile] = useState(false)
@@ -71,6 +83,38 @@ export function TreeEditorPage() {
return () => window.removeEventListener('resize', check)
}, [])
// AI Assist panel
const handleFlowUpdate = useCallback((workingTree: Record<string, unknown>) => {
// For troubleshooting flows, working_tree is the tree structure directly
if (workingTree.type && workingTree.id) {
replaceTreeStructure(workingTree as unknown as TreeStructure)
}
}, [replaceTreeStructure])
const editorAI = useEditorAI({
flowType: 'troubleshooting',
treeId: id,
getFlowContext: useCallback(() => {
if (!treeStructure) return null
return {
name,
description,
tree_structure: treeStructure as unknown as Record<string, unknown>,
}
}, [treeStructure, name, description]),
onFlowUpdate: handleFlowUpdate,
})
const previousEditingNodeRef = useRef<string | null>(null)
const handleAIPanelClose = useCallback(() => {
editorAI.closePanel()
if (previousEditingNodeRef.current) {
setEditingNodeId(previousEditingNodeRef.current)
previousEditingNodeRef.current = null
}
}, [editorAI])
// Calculate if there are blocking errors
const hasBlockingErrors = validationErrors.some(e => e.severity === 'error')
@@ -166,6 +210,7 @@ export function TreeEditorPage() {
}
loadTree(tree)
setTreeStatus(tree.status) // Load status from existing tree
if (tree.import_metadata) setImportMetadata(tree.import_metadata)
} catch (err) {
console.error('Failed to load tree:', err)
toast.error('Failed to load flow')
@@ -477,7 +522,9 @@ export function TreeEditorPage() {
}
return (
<div className="flex h-full flex-col overflow-hidden">
<div className="flex h-full overflow-hidden">
{/* Main content column */}
<div className="flex min-w-0 flex-1 flex-col overflow-hidden">
{/* Draft Restore Prompt */}
{showDraftPrompt && (
@@ -687,6 +734,45 @@ export function TreeEditorPage() {
)}
{/* Validate */}
{isEditMode && (
<button
onClick={() => setShowExportModal(true)}
title="Export flow as .rfflow file"
className={cn(
'flex items-center gap-2 rounded-md border border-border bg-card px-3 py-2 text-sm font-medium text-muted-foreground',
'hover:bg-accent hover:text-foreground'
)}
>
<Download className="h-4 w-4" />
Export
</button>
)}
{/* AI Assist toggle */}
<button
onClick={() => {
if (editorAI.isOpen) {
handleAIPanelClose()
} else {
if (editingNodeId) {
previousEditingNodeRef.current = editingNodeId
setEditingNodeId(null)
}
editorAI.openPanel()
}
}}
title="Toggle AI Assist panel"
className={cn(
'flex items-center gap-2 rounded-md border border-border px-3 py-2 text-sm font-medium transition-colors',
editorAI.isOpen
? 'bg-primary/10 text-primary border-primary/30'
: 'bg-card text-muted-foreground hover:bg-accent hover:text-foreground'
)}
>
<Sparkles className="h-4 w-4" />
AI Assist
</button>
<button
onClick={handleManualValidate}
disabled={isSaving}
@@ -742,15 +828,29 @@ export function TreeEditorPage() {
</div>
)}
{/* Import provenance */}
{importMetadata && (
<div className="mx-4 mb-2 flex items-center gap-2 text-xs font-label text-muted-foreground">
<FileText className="h-3 w-3" />
<span>
Imported{importMetadata.original_author_name ? ` from ${importMetadata.original_author_name}` : ''}
{importMetadata.imported_at ? ` on ${new Date(importMetadata.imported_at).toLocaleDateString()}` : ''}
</span>
</div>
)}
{/* Main Editor */}
<TreeEditorLayout
isMobile={isMobile}
isMetadataOpen={isMetadataOpen}
onCloseMetadata={() => setIsMetadataOpen(false)}
editingNodeId={editingNodeId}
onNodeSelect={handleNodeSelect}
onSelectAnswerType={handleSelectAnswerType}
/>
<div className="min-h-0 flex-1 overflow-hidden">
<TreeEditorLayout
isMobile={isMobile}
isMetadataOpen={isMetadataOpen}
onCloseMetadata={() => setIsMetadataOpen(false)}
editingNodeId={editorAI.isOpen ? null : editingNodeId}
onNodeSelect={handleNodeSelect}
onSelectAnswerType={handleSelectAnswerType}
onNodeContextMenu={editorAI.openContextMenu}
/>
</div>
{/* Flow Analytics Panel (collapsible) */}
{showAnalytics && id && (
@@ -768,6 +868,87 @@ export function TreeEditorPage() {
onClose={handleCloseFixModal}
/>
)}
{/* Export Modal */}
{showExportModal && id && (
<ExportFlowModal
treeId={id}
treeName={name || 'flow'}
onClose={() => setShowExportModal(false)}
/>
)}
{/* AI Context Menu */}
{editorAI.contextMenu && (
<ContextMenu
position={editorAI.contextMenu.position}
items={[
{
id: 'generate-branch',
label: 'Generate Branch',
icon: <Sparkles className="h-4 w-4" />,
onClick: () => {
if (editingNodeId) {
previousEditingNodeRef.current = editingNodeId
setEditingNodeId(null)
}
editorAI.triggerAction(
editorAI.contextMenu!.nodeId,
'generate_branch',
`Generate a branch from this node`
)
},
},
{
id: 'explain',
label: 'Explain Node',
icon: <Sparkles className="h-4 w-4" />,
onClick: () => {
if (editingNodeId) {
previousEditingNodeRef.current = editingNodeId
setEditingNodeId(null)
}
editorAI.triggerAction(
editorAI.contextMenu!.nodeId,
'quick_action',
`Explain what this node does`
)
},
},
{
id: 'sep1',
label: '',
onClick: () => {},
separator: true,
},
{
id: 'delete',
label: 'Delete Node',
variant: 'danger' as const,
onClick: () => deleteNode(editorAI.contextMenu!.nodeId),
},
]}
onClose={editorAI.closeContextMenu}
/>
)}
</div>{/* end main content column */}
<EditorAIPanel
isOpen={editorAI.isOpen}
onClose={handleAIPanelClose}
focalNode={editorAI.focalNodeId && treeStructure
? findNodeInTree(editorAI.focalNodeId, treeStructure)
: null}
flowName={name}
flowType="troubleshooting"
nodeCount={treeStructure ? getAllNodeIds().length : 0}
messages={editorAI.messages}
input={editorAI.input}
onInputChange={editorAI.setInput}
onSend={editorAI.sendMessage}
isLoading={editorAI.isLoading}
suggestions={editorAI.suggestions}
/>
</div>
)
}

View File

@@ -1,6 +1,6 @@
import { useEffect, useState, useCallback, useMemo } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { X, RotateCcw, Play, Sparkles } from 'lucide-react'
import { X, RotateCcw, Play, FileUp } from 'lucide-react'
import { treesApi } from '@/api/trees'
import { categoriesApi } from '@/api/categories'
import { foldersApi } from '@/api/folders'
@@ -8,6 +8,8 @@ import { sessionsApi } from '@/api/sessions'
import type { TreeListItem, CategoryListItem, FolderListItem, Session } from '@/types'
import { FolderEditModal } from '@/components/library/FolderEditModal'
import { ForkModal } from '@/components/library/ForkModal'
import { ExportFlowModal } from '@/components/library/ExportFlowModal'
import { ImportFlowModal } from '@/components/library/ImportFlowModal'
import { ConfirmDialog } from '@/components/common/ConfirmDialog'
import { TreeGridView } from '@/components/library/TreeGridView'
import { TreeListView } from '@/components/library/TreeListView'
@@ -20,7 +22,6 @@ import { usePermissions } from '@/hooks/usePermissions'
import { useUserPreferencesStore } from '@/store/userPreferencesStore'
import { usePinnedFlowsStore } from '@/store/pinnedFlowsStore'
import { useCachedQuota } from '@/hooks/useCachedQuota'
import { AIFlowBuilderModal } from '@/components/ai-builder/AIFlowBuilderModal'
import { CreateFlowDropdown } from '@/components/common/CreateFlowDropdown'
import { Spinner } from '@/components/common/Spinner'
import { EmptyState } from '@/components/common/EmptyState'
@@ -76,8 +77,12 @@ export function TreeLibraryPage() {
// Fork modal state
const [forkTarget, setForkTarget] = useState<TreeListItem | null>(null)
// Import/Export modal state
const [showImportModal, setShowImportModal] = useState(false)
const [exportTarget, setExportTarget] = useState<TreeListItem | null>(null)
// AI builder state
const [showAIBuilder, setShowAIBuilder] = useState(false)
const { aiEnabled } = useCachedQuota()
// Pin store
@@ -250,6 +255,11 @@ export function TreeLibraryPage() {
if (tree) setForkTarget(tree)
}
const handleExportTree = (treeId: string) => {
const tree = trees.find((t) => t.id === treeId)
if (tree) setExportTarget(tree)
}
const hasActiveFilters =
selectedCategoryId || selectedTags.length > 0 || searchQuery || selectedFolderId
@@ -273,18 +283,16 @@ export function TreeLibraryPage() {
</div>
{canCreateTrees && (
<div className="flex items-center gap-2">
{aiEnabled && (
<button
onClick={() => navigate('/ai/chat')}
className="flex items-center gap-2 rounded-lg bg-gradient-brand px-4 py-2 text-sm font-medium text-white shadow-lg shadow-primary/20 hover:opacity-90 transition-opacity"
>
<Sparkles className="h-4 w-4" />
Flow Assist
</button>
)}
<button
onClick={() => setShowImportModal(true)}
className="flex items-center gap-2 rounded-lg border border-border bg-[rgba(255,255,255,0.04)] px-4 py-2 text-sm font-medium text-foreground hover:border-[rgba(255,255,255,0.12)] transition-colors"
>
<FileUp className="h-4 w-4" />
Import
</button>
<CreateFlowDropdown
aiEnabled={aiEnabled}
onOpenAIBuilder={() => setShowAIBuilder(true)}
label="Create New"
/>
</div>
@@ -493,6 +501,7 @@ export function TreeLibraryPage() {
setShowDeleteConfirm(true)
}}
onForkTree={handleForkTree}
onExportTree={handleExportTree}
pinnedTreeIds={pinnedTreeIds}
onTogglePin={togglePin}
pinLoadingTreeIds={pinLoadingTreeIds}
@@ -509,6 +518,7 @@ export function TreeLibraryPage() {
setShowDeleteConfirm(true)
}}
onForkTree={handleForkTree}
onExportTree={handleExportTree}
pinnedTreeIds={pinnedTreeIds}
onTogglePin={togglePin}
pinLoadingTreeIds={pinLoadingTreeIds}
@@ -530,6 +540,7 @@ export function TreeLibraryPage() {
)
}}
onForkTree={handleForkTree}
onExportTree={handleExportTree}
pinnedTreeIds={pinnedTreeIds}
onTogglePin={togglePin}
pinLoadingTreeIds={pinLoadingTreeIds}
@@ -567,13 +578,6 @@ export function TreeLibraryPage() {
isLoading={isDeleting}
/>
{/* AI Builder Modal */}
{showAIBuilder && (
<AIFlowBuilderModal
isOpen={showAIBuilder}
onClose={() => setShowAIBuilder(false)}
/>
)}
{forkTarget && (
<ForkModal
@@ -582,6 +586,20 @@ export function TreeLibraryPage() {
onClose={() => setForkTarget(null)}
/>
)}
{exportTarget && (
<ExportFlowModal
treeId={exportTarget.id}
treeName={exportTarget.name}
onClose={() => setExportTarget(null)}
/>
)}
{showImportModal && (
<ImportFlowModal
onClose={() => { setShowImportModal(false); loadTrees() }}
/>
)}
</div>
)
}

View File

@@ -626,9 +626,9 @@ export function TreeNavigationPage() {
}
return (
<div className="h-full">
<div className="h-full flex overflow-hidden">
{/* Main Content */}
<div className={cn('h-full overflow-y-auto px-4 py-8 transition-[padding] duration-200', scratchpadOpen && 'sm:pr-[440px]')}>
<div className={cn('h-full flex-1 min-w-0 overflow-y-auto px-4 py-8 transition-[padding] duration-200', scratchpadOpen && 'sm:pr-[440px]')}>
<div className="mx-auto max-w-4xl">
{/* Header */}
<div className="mb-6 flex items-center justify-between">
@@ -1264,6 +1264,17 @@ export function TreeNavigationPage() {
</div>
</div>
{/* AI Copilot - in-flow panel */}
{treeId && copilotOpen && (
<CopilotPanel
isOpen={copilotOpen}
onClose={() => setCopilotOpen(false)}
treeId={treeId}
sessionId={session?.id}
currentNodeId={currentNodeId}
/>
)}
{/* Scratchpad Sidebar */}
{session && (
<ScratchpadSidebar
@@ -1274,18 +1285,9 @@ export function TreeNavigationPage() {
/>
)}
{/* AI Copilot */}
{/* AI Copilot toggle button */}
{treeId && (
<>
<CopilotToggle isOpen={copilotOpen} onToggle={() => setCopilotOpen(true)} />
<CopilotPanel
isOpen={copilotOpen}
onClose={() => setCopilotOpen(false)}
treeId={treeId}
sessionId={session?.id}
currentNodeId={currentNodeId}
/>
</>
<CopilotToggle isOpen={copilotOpen} onToggle={() => setCopilotOpen(true)} />
)}
</div>
)