refactor: tech debt reduction - extract hooks, deduplicate helpers, update deps, add CI
- Extract useCustomStepFlow hook from TreeNavigationPage (1040 → 759 lines) - Create core/filters.py with shared tree/step visibility filters - Create services/export_service.py from session export logic - Add GitHub Actions CI/CD pipeline (pytest + lint + build) - Add GIN index migration for full-text search on trees - Update FastAPI 0.128.5, Pydantic 2.12.5, SQLAlchemy 2.0.46, +5 more - Fix regex → pattern deprecation in Query() params Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
362
frontend/src/hooks/useCustomStepFlow.ts
Normal file
362
frontend/src/hooks/useCustomStepFlow.ts
Normal file
@@ -0,0 +1,362 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { sessionsApi, stepsApi } from '@/api'
|
||||
import { treesApi } from '@/api'
|
||||
import type { Tree, Session, DecisionRecord, TreeStructure, CustomStep, Step } from '@/types'
|
||||
import type { CustomStepDraft } from '@/components/step-library/CustomStepModal'
|
||||
import type { DescendantNode } from '@/components/session'
|
||||
|
||||
interface UseCustomStepFlowParams {
|
||||
tree: Tree | null
|
||||
session: Session | null
|
||||
currentNodeId: string
|
||||
pathTaken: string[]
|
||||
decisions: DecisionRecord[]
|
||||
notes: string
|
||||
findNode: (nodeId: string, structure?: TreeStructure) => TreeStructure | null
|
||||
setCurrentNodeId: (id: string) => void
|
||||
setPathTaken: (path: string[]) => void
|
||||
setDecisions: (decisions: DecisionRecord[]) => void
|
||||
setNotes: (notes: string) => void
|
||||
setIsCompleting: (completing: boolean) => void
|
||||
setError: (error: string | null) => void
|
||||
isCompleting: boolean
|
||||
}
|
||||
|
||||
export function useCustomStepFlow({
|
||||
tree,
|
||||
session,
|
||||
currentNodeId,
|
||||
pathTaken,
|
||||
decisions,
|
||||
notes,
|
||||
findNode,
|
||||
setCurrentNodeId,
|
||||
setPathTaken,
|
||||
setDecisions,
|
||||
setNotes,
|
||||
setIsCompleting,
|
||||
setError,
|
||||
isCompleting,
|
||||
}: UseCustomStepFlowParams) {
|
||||
const navigate = useNavigate()
|
||||
|
||||
// Custom steps
|
||||
const [customSteps, setCustomSteps] = useState<CustomStep[]>([])
|
||||
const [showCustomStepModal, setShowCustomStepModal] = useState(false)
|
||||
|
||||
// Post-step action flow
|
||||
const [showPostStepModal, setShowPostStepModal] = useState(false)
|
||||
const [pendingStep, setPendingStep] = useState<Step | CustomStepDraft | null>(null)
|
||||
const [pendingStepIsFromLibrary, setPendingStepIsFromLibrary] = useState(false)
|
||||
const [isSavingStep, setIsSavingStep] = useState(false)
|
||||
|
||||
// Continuation flow
|
||||
const [showContinuationModal, setShowContinuationModal] = useState(false)
|
||||
const [branchOriginNodeId, setBranchOriginNodeId] = useState<string | null>(null)
|
||||
const [pendingContinuationNodeId, setPendingContinuationNodeId] = useState<string | null>(null)
|
||||
|
||||
// Custom branch mode
|
||||
const [customBranchMode, setCustomBranchMode] = useState(false)
|
||||
|
||||
// Fork flow
|
||||
const [showForkModal, setShowForkModal] = useState(false)
|
||||
|
||||
const findCustomStep = (nodeId: string): CustomStep | null => {
|
||||
return customSteps.find(cs => cs.id === nodeId) || null
|
||||
}
|
||||
|
||||
// Get descendant nodes two levels deep (grandchildren) from a decision node's options.
|
||||
const getDescendantNodes = (decisionNodeId: string): DescendantNode[] => {
|
||||
const decisionNode = findNode(decisionNodeId, tree?.tree_structure)
|
||||
if (!decisionNode || decisionNode.type !== 'decision' || !decisionNode.options) {
|
||||
return []
|
||||
}
|
||||
|
||||
const descendants: DescendantNode[] = []
|
||||
|
||||
for (const option of decisionNode.options) {
|
||||
if (!option.next_node_id) continue
|
||||
const childNode = findNode(option.next_node_id, tree?.tree_structure)
|
||||
if (!childNode) continue
|
||||
|
||||
if (childNode.type === 'decision' && childNode.options) {
|
||||
for (const childOption of childNode.options) {
|
||||
if (!childOption.next_node_id) continue
|
||||
const grandchild = findNode(childOption.next_node_id, tree?.tree_structure)
|
||||
if (!grandchild) continue
|
||||
|
||||
descendants.push({
|
||||
id: grandchild.id,
|
||||
label: grandchild.question || grandchild.title || 'Untitled',
|
||||
type: grandchild.type,
|
||||
parentOptionLabel: `${option.label} \u2192 ${childOption.label}`
|
||||
})
|
||||
}
|
||||
} else if (childNode.type === 'action' && childNode.next_node_id) {
|
||||
const grandchild = findNode(childNode.next_node_id, tree?.tree_structure)
|
||||
if (grandchild) {
|
||||
descendants.push({
|
||||
id: grandchild.id,
|
||||
label: grandchild.question || grandchild.title || 'Untitled',
|
||||
type: grandchild.type,
|
||||
parentOptionLabel: `${option.label} \u2192 ${childNode.title || 'Action'}`
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return descendants
|
||||
}
|
||||
|
||||
// Navigate back to a previously-created custom step from the decision node
|
||||
const handleNavigateToCustomStep = (customStep: CustomStep) => {
|
||||
const newPath = [...pathTaken, customStep.id]
|
||||
setPathTaken(newPath)
|
||||
setCurrentNodeId(customStep.id)
|
||||
}
|
||||
|
||||
// Called when CustomStepModal submits - show action modal instead of inserting directly
|
||||
const handleStepCreated = (step: Step | CustomStepDraft, isFromLibrary: boolean) => {
|
||||
setPendingStep(step)
|
||||
setPendingStepIsFromLibrary(isFromLibrary)
|
||||
setShowCustomStepModal(false)
|
||||
setShowPostStepModal(true)
|
||||
}
|
||||
|
||||
const resetPendingStep = () => {
|
||||
setShowPostStepModal(false)
|
||||
setPendingStep(null)
|
||||
setPendingStepIsFromLibrary(false)
|
||||
setIsSavingStep(false)
|
||||
}
|
||||
|
||||
// Save to library only, don't insert into session
|
||||
const handleSaveForLater = async () => {
|
||||
if (!pendingStep) return
|
||||
|
||||
setIsSavingStep(true)
|
||||
try {
|
||||
if (!pendingStepIsFromLibrary) {
|
||||
await stepsApi.create({
|
||||
title: pendingStep.title,
|
||||
step_type: pendingStep.step_type,
|
||||
content: pendingStep.content,
|
||||
visibility: 'private',
|
||||
tags: pendingStep.tags || []
|
||||
})
|
||||
}
|
||||
resetPendingStep()
|
||||
} catch (err) {
|
||||
console.error('Failed to save step to library:', err)
|
||||
setIsSavingStep(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Insert into session and show continuation options
|
||||
const handleUseNow = async () => {
|
||||
if (!pendingStep || !session) return
|
||||
|
||||
setIsSavingStep(true)
|
||||
try {
|
||||
setBranchOriginNodeId(currentNodeId)
|
||||
|
||||
const customStep: CustomStep = {
|
||||
id: crypto.randomUUID(),
|
||||
inserted_after_node_id: currentNodeId,
|
||||
step_data: pendingStep,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
|
||||
const newDecision: DecisionRecord = {
|
||||
node_id: customStep.id,
|
||||
question: null,
|
||||
answer: null,
|
||||
action_performed: `Custom Step: ${pendingStep.title}`,
|
||||
notes: pendingStep.content.instructions || null,
|
||||
automation_used: false,
|
||||
timestamp: new Date().toISOString(),
|
||||
attachments: []
|
||||
}
|
||||
|
||||
const newCustomSteps = [...customSteps, customStep]
|
||||
const newDecisions = [...decisions, newDecision]
|
||||
const newPath = [...pathTaken, customStep.id]
|
||||
|
||||
setCustomSteps(newCustomSteps)
|
||||
setDecisions(newDecisions)
|
||||
setPathTaken(newPath)
|
||||
setCurrentNodeId(customStep.id)
|
||||
|
||||
await sessionsApi.update(session.id, {
|
||||
path_taken: newPath,
|
||||
decisions: newDecisions,
|
||||
custom_steps: newCustomSteps
|
||||
})
|
||||
|
||||
resetPendingStep()
|
||||
setShowContinuationModal(true)
|
||||
} catch (err) {
|
||||
console.error('Failed to insert custom step:', err)
|
||||
setIsSavingStep(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Save to library AND insert into session
|
||||
const handleBoth = async () => {
|
||||
if (!pendingStep) return
|
||||
|
||||
setIsSavingStep(true)
|
||||
try {
|
||||
if (!pendingStepIsFromLibrary) {
|
||||
await stepsApi.create({
|
||||
title: pendingStep.title,
|
||||
step_type: pendingStep.step_type,
|
||||
content: pendingStep.content,
|
||||
visibility: 'private',
|
||||
tags: pendingStep.tags || []
|
||||
})
|
||||
}
|
||||
await handleUseNow()
|
||||
} catch (err) {
|
||||
console.error('Failed to save and insert step:', err)
|
||||
setIsSavingStep(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle selecting a descendant node from continuation modal
|
||||
const handleSelectDescendant = (nodeId: string) => {
|
||||
setShowContinuationModal(false)
|
||||
setBranchOriginNodeId(null)
|
||||
setPendingContinuationNodeId(nodeId)
|
||||
}
|
||||
|
||||
// Navigate to the previously-selected descendant node
|
||||
const handleContinueToDescendant = async () => {
|
||||
if (!pendingContinuationNodeId || !session) return
|
||||
|
||||
const newPath = [...pathTaken, pendingContinuationNodeId]
|
||||
setPathTaken(newPath)
|
||||
setCurrentNodeId(pendingContinuationNodeId)
|
||||
setNotes('')
|
||||
setPendingContinuationNodeId(null)
|
||||
|
||||
try {
|
||||
await sessionsApi.update(session.id, { path_taken: newPath })
|
||||
} catch (err) {
|
||||
console.error('Failed to update session path:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// Enter custom branch building mode
|
||||
const handleBuildCustomBranch = () => {
|
||||
setShowContinuationModal(false)
|
||||
setCustomBranchMode(true)
|
||||
}
|
||||
|
||||
// Complete session from custom branch mode
|
||||
const handleCustomBranchComplete = async () => {
|
||||
if (!session) return
|
||||
|
||||
setIsCompleting(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const completionDecision: DecisionRecord = {
|
||||
node_id: currentNodeId,
|
||||
question: null,
|
||||
answer: null,
|
||||
action_performed: 'Custom Branch Completed',
|
||||
notes: notes || 'Issue resolved via custom troubleshooting steps',
|
||||
automation_used: false,
|
||||
timestamp: new Date().toISOString(),
|
||||
attachments: []
|
||||
}
|
||||
|
||||
await sessionsApi.update(session.id, {
|
||||
decisions: [...decisions, completionDecision]
|
||||
})
|
||||
|
||||
await sessionsApi.complete(session.id)
|
||||
|
||||
if (customSteps.length > 0) {
|
||||
setShowForkModal(true)
|
||||
} else {
|
||||
navigate(`/sessions/${session.id}`)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to complete session:', err)
|
||||
setError('Failed to complete session. Please try again.')
|
||||
} finally {
|
||||
setIsCompleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Fork tree with custom branch
|
||||
const handleForkTree = async (name: string, description: string) => {
|
||||
if (!tree) return
|
||||
|
||||
try {
|
||||
const forkedTree = await treesApi.create({
|
||||
name,
|
||||
description,
|
||||
tree_structure: tree.tree_structure,
|
||||
is_public: false
|
||||
})
|
||||
|
||||
navigate(`/trees/${forkedTree.id}/edit`)
|
||||
} catch (err) {
|
||||
console.error('Failed to fork tree:', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Skip forking and go to session detail
|
||||
const handleSkipFork = () => {
|
||||
setShowForkModal(false)
|
||||
navigate(`/sessions/${session!.id}`)
|
||||
}
|
||||
|
||||
// Initialize custom steps when resuming a session
|
||||
const initCustomSteps = (steps: CustomStep[]) => {
|
||||
setCustomSteps(steps)
|
||||
}
|
||||
|
||||
return {
|
||||
// State
|
||||
customSteps,
|
||||
showCustomStepModal,
|
||||
showPostStepModal,
|
||||
pendingStep,
|
||||
pendingStepIsFromLibrary,
|
||||
isSavingStep,
|
||||
showContinuationModal,
|
||||
branchOriginNodeId,
|
||||
pendingContinuationNodeId,
|
||||
customBranchMode,
|
||||
showForkModal,
|
||||
|
||||
// Derived
|
||||
findCustomStep,
|
||||
getDescendantNodes,
|
||||
|
||||
// Actions
|
||||
setShowCustomStepModal,
|
||||
setShowContinuationModal,
|
||||
setShowForkModal,
|
||||
initCustomSteps,
|
||||
handleNavigateToCustomStep,
|
||||
handleStepCreated,
|
||||
resetPendingStep,
|
||||
handleSaveForLater,
|
||||
handleUseNow,
|
||||
handleBoth,
|
||||
handleSelectDescendant,
|
||||
handleContinueToDescendant,
|
||||
handleBuildCustomBranch,
|
||||
handleCustomBranchComplete,
|
||||
handleForkTree,
|
||||
handleSkipFork,
|
||||
isCompleting,
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useParams, useNavigate, useLocation } from 'react-router-dom'
|
||||
import { treesApi, sessionsApi, stepsApi } from '@/api'
|
||||
import { treesApi, sessionsApi } from '@/api'
|
||||
import { useTreeNavigationShortcuts } from '@/hooks/useKeyboardShortcuts'
|
||||
import type { Tree, Session, DecisionRecord, TreeStructure, CustomStep, Step } from '@/types'
|
||||
import type { CustomStepDraft } from '@/components/step-library/CustomStepModal'
|
||||
import { useCustomStepFlow } from '@/hooks/useCustomStepFlow'
|
||||
import type { Tree, Session, DecisionRecord, TreeStructure } from '@/types'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MarkdownContent } from '@/components/ui/MarkdownContent'
|
||||
import { CustomStepModal } from '@/components/step-library/CustomStepModal'
|
||||
import { PostStepActionModal, ContinuationModal, ForkTreeModal, ScratchpadSidebar, type DescendantNode } from '@/components/session'
|
||||
import { PostStepActionModal, ContinuationModal, ForkTreeModal, ScratchpadSidebar } from '@/components/session'
|
||||
import { Plus, CheckCircle, ArrowRight } from 'lucide-react'
|
||||
|
||||
interface LocationState {
|
||||
@@ -35,33 +35,41 @@ export function TreeNavigationPage() {
|
||||
const [clientName, setClientName] = useState<string>('')
|
||||
const [showMetadataForm, setShowMetadataForm] = useState(true)
|
||||
|
||||
// Custom steps
|
||||
const [customSteps, setCustomSteps] = useState<CustomStep[]>([])
|
||||
const [showCustomStepModal, setShowCustomStepModal] = useState(false)
|
||||
|
||||
// Post-step action flow
|
||||
const [showPostStepModal, setShowPostStepModal] = useState(false)
|
||||
const [pendingStep, setPendingStep] = useState<Step | CustomStepDraft | null>(null)
|
||||
const [pendingStepIsFromLibrary, setPendingStepIsFromLibrary] = useState(false)
|
||||
const [isSavingStep, setIsSavingStep] = useState(false)
|
||||
|
||||
// Continuation flow
|
||||
const [showContinuationModal, setShowContinuationModal] = useState(false)
|
||||
const [branchOriginNodeId, setBranchOriginNodeId] = useState<string | null>(null)
|
||||
const [pendingContinuationNodeId, setPendingContinuationNodeId] = useState<string | null>(null)
|
||||
|
||||
// Custom branch mode
|
||||
const [customBranchMode, setCustomBranchMode] = useState(false)
|
||||
|
||||
// Fork flow
|
||||
const [showForkModal, setShowForkModal] = useState(false)
|
||||
|
||||
// Scratchpad state
|
||||
const [scratchpadOpen, setScratchpadOpen] = useState(() => {
|
||||
return localStorage.getItem('scratchpad-collapsed') === 'false'
|
||||
})
|
||||
|
||||
// Scratchpad save handler
|
||||
const findNode = (nodeId: string, structure?: TreeStructure): TreeStructure | null => {
|
||||
if (!structure) return null
|
||||
if (structure.id === nodeId) return structure
|
||||
if (structure.children) {
|
||||
for (const child of structure.children) {
|
||||
const found = findNode(nodeId, child)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Custom step flow (creation, post-step actions, continuation, branching, forking)
|
||||
const customStepFlow = useCustomStepFlow({
|
||||
tree,
|
||||
session,
|
||||
currentNodeId,
|
||||
pathTaken,
|
||||
decisions,
|
||||
notes,
|
||||
findNode,
|
||||
setCurrentNodeId,
|
||||
setPathTaken,
|
||||
setDecisions,
|
||||
setNotes,
|
||||
setIsCompleting,
|
||||
setError,
|
||||
isCompleting,
|
||||
})
|
||||
|
||||
const handleScratchpadSave = async (content: string) => {
|
||||
if (!session) return
|
||||
await sessionsApi.updateScratchpad(session.id, content)
|
||||
@@ -87,7 +95,7 @@ export function TreeNavigationPage() {
|
||||
setPathTaken(sessionData.path_taken)
|
||||
setCurrentNodeId(sessionData.path_taken[sessionData.path_taken.length - 1] || 'root')
|
||||
setDecisions(sessionData.decisions as DecisionRecord[])
|
||||
setCustomSteps(sessionData.custom_steps || [])
|
||||
customStepFlow.initCustomSteps(sessionData.custom_steps || [])
|
||||
setTicketNumber(sessionData.ticket_number || '')
|
||||
setClientName(sessionData.client_name || '')
|
||||
setShowMetadataForm(false)
|
||||
@@ -119,70 +127,6 @@ export function TreeNavigationPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const findNode = (nodeId: string, structure?: TreeStructure): TreeStructure | null => {
|
||||
if (!structure) return null
|
||||
if (structure.id === nodeId) return structure
|
||||
if (structure.children) {
|
||||
for (const child of structure.children) {
|
||||
const found = findNode(nodeId, child)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const findCustomStep = (nodeId: string): CustomStep | null => {
|
||||
return customSteps.find(cs => cs.id === nodeId) || null
|
||||
}
|
||||
|
||||
// Get descendant nodes two levels deep (grandchildren) from a decision node's options.
|
||||
// This skips the immediate children (which often mirror the option labels) and shows
|
||||
// the actual next-level nodes the user would encounter further down each path.
|
||||
const getDescendantNodes = (decisionNodeId: string): DescendantNode[] => {
|
||||
const decisionNode = findNode(decisionNodeId, tree?.tree_structure)
|
||||
if (!decisionNode || decisionNode.type !== 'decision' || !decisionNode.options) {
|
||||
return []
|
||||
}
|
||||
|
||||
const descendants: DescendantNode[] = []
|
||||
|
||||
for (const option of decisionNode.options) {
|
||||
if (!option.next_node_id) continue
|
||||
const childNode = findNode(option.next_node_id, tree?.tree_structure)
|
||||
if (!childNode) continue
|
||||
|
||||
// Go one level deeper: get the grandchildren
|
||||
if (childNode.type === 'decision' && childNode.options) {
|
||||
for (const childOption of childNode.options) {
|
||||
if (!childOption.next_node_id) continue
|
||||
const grandchild = findNode(childOption.next_node_id, tree?.tree_structure)
|
||||
if (!grandchild) continue
|
||||
|
||||
descendants.push({
|
||||
id: grandchild.id,
|
||||
label: grandchild.question || grandchild.title || 'Untitled',
|
||||
type: grandchild.type,
|
||||
parentOptionLabel: `${option.label} \u2192 ${childOption.label}`
|
||||
})
|
||||
}
|
||||
} else if (childNode.type === 'action' && childNode.next_node_id) {
|
||||
const grandchild = findNode(childNode.next_node_id, tree?.tree_structure)
|
||||
if (grandchild) {
|
||||
descendants.push({
|
||||
id: grandchild.id,
|
||||
label: grandchild.question || grandchild.title || 'Untitled',
|
||||
type: grandchild.type,
|
||||
parentOptionLabel: `${option.label} \u2192 ${childNode.title || 'Action'}`
|
||||
})
|
||||
}
|
||||
}
|
||||
// Solution children have no further descendants - skip them
|
||||
}
|
||||
|
||||
return descendants
|
||||
}
|
||||
|
||||
// Handler functions - defined before hook call to avoid temporal dead zone
|
||||
const handleSelectOption = async (_optionId: string, optionLabel: string, nextNodeId: string) => {
|
||||
if (!session || !tree) return
|
||||
|
||||
@@ -208,7 +152,6 @@ export function TreeNavigationPage() {
|
||||
setCurrentNodeId(nextNodeId)
|
||||
setNotes('')
|
||||
|
||||
// Update session on backend
|
||||
try {
|
||||
await sessionsApi.update(session.id, {
|
||||
path_taken: newPath,
|
||||
@@ -259,7 +202,6 @@ export function TreeNavigationPage() {
|
||||
setIsCompleting(true)
|
||||
setError(null)
|
||||
try {
|
||||
// Add final decision
|
||||
const node = findNode(currentNodeId, tree.tree_structure)
|
||||
if (node) {
|
||||
const finalDecision: DecisionRecord = {
|
||||
@@ -296,232 +238,9 @@ export function TreeNavigationPage() {
|
||||
setCurrentNodeId(newPath[newPath.length - 1])
|
||||
}
|
||||
|
||||
// Navigate back to a previously-created custom step from the decision node
|
||||
const handleNavigateToCustomStep = (customStep: CustomStep) => {
|
||||
const newPath = [...pathTaken, customStep.id]
|
||||
setPathTaken(newPath)
|
||||
setCurrentNodeId(customStep.id)
|
||||
}
|
||||
|
||||
// Called when CustomStepModal submits - show action modal instead of inserting directly
|
||||
const handleStepCreated = (step: Step | CustomStepDraft, isFromLibrary: boolean) => {
|
||||
setPendingStep(step)
|
||||
setPendingStepIsFromLibrary(isFromLibrary)
|
||||
setShowCustomStepModal(false)
|
||||
setShowPostStepModal(true)
|
||||
}
|
||||
|
||||
const resetPendingStep = () => {
|
||||
setShowPostStepModal(false)
|
||||
setPendingStep(null)
|
||||
setPendingStepIsFromLibrary(false)
|
||||
setIsSavingStep(false)
|
||||
}
|
||||
|
||||
// Save to library only, don't insert into session
|
||||
const handleSaveForLater = async () => {
|
||||
if (!pendingStep) return
|
||||
|
||||
setIsSavingStep(true)
|
||||
try {
|
||||
if (!pendingStepIsFromLibrary) {
|
||||
await stepsApi.create({
|
||||
title: pendingStep.title,
|
||||
step_type: pendingStep.step_type,
|
||||
content: pendingStep.content,
|
||||
visibility: 'private',
|
||||
tags: pendingStep.tags || []
|
||||
})
|
||||
}
|
||||
resetPendingStep()
|
||||
} catch (err) {
|
||||
console.error('Failed to save step to library:', err)
|
||||
setIsSavingStep(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Insert into session and show continuation options
|
||||
const handleUseNow = async () => {
|
||||
if (!pendingStep || !session) return
|
||||
|
||||
setIsSavingStep(true)
|
||||
try {
|
||||
// Remember where we branched from (for showing descendants later)
|
||||
setBranchOriginNodeId(currentNodeId)
|
||||
|
||||
// Create custom step object
|
||||
const customStep: CustomStep = {
|
||||
id: crypto.randomUUID(),
|
||||
inserted_after_node_id: currentNodeId,
|
||||
step_data: pendingStep,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
|
||||
// Record decision (so it appears in exports)
|
||||
const newDecision: DecisionRecord = {
|
||||
node_id: customStep.id,
|
||||
question: null,
|
||||
answer: null,
|
||||
action_performed: `Custom Step: ${pendingStep.title}`,
|
||||
notes: pendingStep.content.instructions || null,
|
||||
automation_used: false,
|
||||
timestamp: new Date().toISOString(),
|
||||
attachments: []
|
||||
}
|
||||
|
||||
// Update state
|
||||
const newCustomSteps = [...customSteps, customStep]
|
||||
const newDecisions = [...decisions, newDecision]
|
||||
const newPath = [...pathTaken, customStep.id]
|
||||
|
||||
setCustomSteps(newCustomSteps)
|
||||
setDecisions(newDecisions)
|
||||
setPathTaken(newPath)
|
||||
setCurrentNodeId(customStep.id)
|
||||
|
||||
// Persist to backend
|
||||
await sessionsApi.update(session.id, {
|
||||
path_taken: newPath,
|
||||
decisions: newDecisions,
|
||||
custom_steps: newCustomSteps
|
||||
})
|
||||
|
||||
resetPendingStep()
|
||||
|
||||
// Show continuation modal
|
||||
setShowContinuationModal(true)
|
||||
} catch (err) {
|
||||
console.error('Failed to insert custom step:', err)
|
||||
setIsSavingStep(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Save to library AND insert into session
|
||||
const handleBoth = async () => {
|
||||
if (!pendingStep) return
|
||||
|
||||
setIsSavingStep(true)
|
||||
try {
|
||||
// Save to library first
|
||||
if (!pendingStepIsFromLibrary) {
|
||||
await stepsApi.create({
|
||||
title: pendingStep.title,
|
||||
step_type: pendingStep.step_type,
|
||||
content: pendingStep.content,
|
||||
visibility: 'private',
|
||||
tags: pendingStep.tags || []
|
||||
})
|
||||
}
|
||||
|
||||
// Then use now (this will handle the rest and reset pending step)
|
||||
await handleUseNow()
|
||||
} catch (err) {
|
||||
console.error('Failed to save and insert step:', err)
|
||||
setIsSavingStep(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle selecting a descendant node from continuation modal.
|
||||
// Stores the selection so the user can write notes on their custom step first.
|
||||
const handleSelectDescendant = (nodeId: string) => {
|
||||
setShowContinuationModal(false)
|
||||
setBranchOriginNodeId(null)
|
||||
setPendingContinuationNodeId(nodeId)
|
||||
}
|
||||
|
||||
// Navigate to the previously-selected descendant node
|
||||
const handleContinueToDescendant = async () => {
|
||||
if (!pendingContinuationNodeId || !session) return
|
||||
|
||||
const newPath = [...pathTaken, pendingContinuationNodeId]
|
||||
setPathTaken(newPath)
|
||||
setCurrentNodeId(pendingContinuationNodeId)
|
||||
setNotes('')
|
||||
setPendingContinuationNodeId(null)
|
||||
|
||||
try {
|
||||
await sessionsApi.update(session.id, { path_taken: newPath })
|
||||
} catch (err) {
|
||||
console.error('Failed to update session path:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// Enter custom branch building mode
|
||||
const handleBuildCustomBranch = () => {
|
||||
setShowContinuationModal(false)
|
||||
setCustomBranchMode(true)
|
||||
}
|
||||
|
||||
// Complete session from custom branch mode
|
||||
const handleCustomBranchComplete = async () => {
|
||||
if (!session) return
|
||||
|
||||
setIsCompleting(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
// Record completion decision
|
||||
const completionDecision: DecisionRecord = {
|
||||
node_id: currentNodeId,
|
||||
question: null,
|
||||
answer: null,
|
||||
action_performed: 'Custom Branch Completed',
|
||||
notes: notes || 'Issue resolved via custom troubleshooting steps',
|
||||
automation_used: false,
|
||||
timestamp: new Date().toISOString(),
|
||||
attachments: []
|
||||
}
|
||||
|
||||
await sessionsApi.update(session.id, {
|
||||
decisions: [...decisions, completionDecision]
|
||||
})
|
||||
|
||||
await sessionsApi.complete(session.id)
|
||||
|
||||
// Show fork modal if custom steps exist
|
||||
if (customSteps.length > 0) {
|
||||
setShowForkModal(true)
|
||||
} else {
|
||||
navigate(`/sessions/${session.id}`)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to complete session:', err)
|
||||
setError('Failed to complete session. Please try again.')
|
||||
} finally {
|
||||
setIsCompleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Fork tree with custom branch
|
||||
const handleForkTree = async (name: string, description: string) => {
|
||||
if (!tree) return
|
||||
|
||||
try {
|
||||
// Create a forked tree structure
|
||||
// For now, we'll create a simple copy - the custom steps are documented in the session
|
||||
const forkedTree = await treesApi.create({
|
||||
name,
|
||||
description,
|
||||
tree_structure: tree.tree_structure, // Base structure
|
||||
is_public: false
|
||||
})
|
||||
|
||||
navigate(`/trees/${forkedTree.id}/edit`)
|
||||
} catch (err) {
|
||||
console.error('Failed to fork tree:', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Skip forking and go to session detail
|
||||
const handleSkipFork = () => {
|
||||
setShowForkModal(false)
|
||||
navigate(`/sessions/${session!.id}`)
|
||||
}
|
||||
|
||||
// Compute current node for keyboard shortcuts (must be before any returns for hooks rules)
|
||||
const currentNode = tree ? findNode(currentNodeId, tree.tree_structure) : null
|
||||
const currentCustomStep = findCustomStep(currentNodeId)
|
||||
const currentCustomStep = customStepFlow.findCustomStep(currentNodeId)
|
||||
const currentOptions = currentNode?.options || []
|
||||
|
||||
// Keyboard shortcuts - must be called unconditionally (React hooks rules)
|
||||
@@ -669,7 +388,7 @@ export function TreeNavigationPage() {
|
||||
<div className="mb-6 flex items-center gap-2 overflow-x-auto text-sm">
|
||||
{pathTaken.map((nodeId, index) => {
|
||||
const node = findNode(nodeId, tree?.tree_structure)
|
||||
const customStep = findCustomStep(nodeId)
|
||||
const customStep = customStepFlow.findCustomStep(nodeId)
|
||||
const label = node?.question || node?.title || customStep?.step_data.title || nodeId
|
||||
return (
|
||||
<span key={nodeId} className="flex items-center gap-2 whitespace-nowrap">
|
||||
@@ -722,18 +441,18 @@ export function TreeNavigationPage() {
|
||||
))}
|
||||
</div>
|
||||
{/* Previously-created custom steps at this node */}
|
||||
{customSteps.filter(cs => cs.inserted_after_node_id === currentNodeId).length > 0 && (
|
||||
{customStepFlow.customSteps.filter(cs => cs.inserted_after_node_id === currentNodeId).length > 0 && (
|
||||
<div className="mt-2 space-y-2">
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Your Custom Steps
|
||||
</p>
|
||||
{customSteps
|
||||
{customStepFlow.customSteps
|
||||
.filter(cs => cs.inserted_after_node_id === currentNodeId)
|
||||
.map(cs => (
|
||||
<button
|
||||
type="button"
|
||||
key={cs.id}
|
||||
onClick={() => handleNavigateToCustomStep(cs)}
|
||||
onClick={() => customStepFlow.handleNavigateToCustomStep(cs)}
|
||||
className={cn(
|
||||
'w-full rounded-md border border-purple-300 bg-purple-50 p-3 text-left transition-colors',
|
||||
'hover:border-purple-500 hover:bg-purple-100',
|
||||
@@ -752,7 +471,7 @@ export function TreeNavigationPage() {
|
||||
|
||||
{/* Add Custom Step Button */}
|
||||
<button
|
||||
onClick={() => setShowCustomStepModal(true)}
|
||||
onClick={() => customStepFlow.setShowCustomStepModal(true)}
|
||||
className="mt-2 inline-flex items-center gap-1 rounded-md px-2 py-1.5 text-sm text-primary hover:bg-primary/10"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
@@ -802,14 +521,14 @@ export function TreeNavigationPage() {
|
||||
)}
|
||||
|
||||
{/* Continue to selected descendant */}
|
||||
{pendingContinuationNodeId && !customBranchMode && (() => {
|
||||
const targetNode = findNode(pendingContinuationNodeId, tree?.tree_structure)
|
||||
{customStepFlow.pendingContinuationNodeId && !customStepFlow.customBranchMode && (() => {
|
||||
const targetNode = findNode(customStepFlow.pendingContinuationNodeId, tree?.tree_structure)
|
||||
const targetLabel = targetNode?.question || targetNode?.title || 'next step'
|
||||
return (
|
||||
<div className="mt-6 border-t border-purple-200 pt-4 dark:border-purple-700">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleContinueToDescendant}
|
||||
onClick={customStepFlow.handleContinueToDescendant}
|
||||
className={cn(
|
||||
'flex w-full items-center justify-between rounded-md bg-primary px-4 py-3 text-sm font-medium text-primary-foreground',
|
||||
'hover:bg-primary/90'
|
||||
@@ -823,14 +542,14 @@ export function TreeNavigationPage() {
|
||||
})()}
|
||||
|
||||
{/* Custom Branch Controls */}
|
||||
{customBranchMode && (
|
||||
{customStepFlow.customBranchMode && (
|
||||
<div className="mt-6 border-t border-purple-200 pt-4 dark:border-purple-700">
|
||||
<p className="mb-3 text-sm text-amber-600 dark:text-amber-400">
|
||||
Building custom branch - add steps until the issue is resolved
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
onClick={() => setShowCustomStepModal(true)}
|
||||
onClick={() => customStepFlow.setShowCustomStepModal(true)}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-md border border-input px-4 py-2 text-sm font-medium',
|
||||
'bg-background hover:bg-accent hover:text-accent-foreground'
|
||||
@@ -840,7 +559,7 @@ export function TreeNavigationPage() {
|
||||
Add Another Step
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCustomBranchComplete}
|
||||
onClick={customStepFlow.handleCustomBranchComplete}
|
||||
disabled={isCompleting}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-md bg-green-600 px-4 py-2 text-sm font-medium text-white',
|
||||
@@ -985,41 +704,41 @@ export function TreeNavigationPage() {
|
||||
|
||||
{/* Custom Step Modal */}
|
||||
<CustomStepModal
|
||||
isOpen={showCustomStepModal}
|
||||
onClose={() => setShowCustomStepModal(false)}
|
||||
onInsertStep={handleStepCreated}
|
||||
isOpen={customStepFlow.showCustomStepModal}
|
||||
onClose={() => customStepFlow.setShowCustomStepModal(false)}
|
||||
onInsertStep={customStepFlow.handleStepCreated}
|
||||
/>
|
||||
|
||||
{/* Post Step Action Modal */}
|
||||
{pendingStep && (
|
||||
{customStepFlow.pendingStep && (
|
||||
<PostStepActionModal
|
||||
isOpen={showPostStepModal}
|
||||
onClose={resetPendingStep}
|
||||
step={pendingStep}
|
||||
onSaveForLater={handleSaveForLater}
|
||||
onUseNow={handleUseNow}
|
||||
onBoth={handleBoth}
|
||||
isFromLibrary={pendingStepIsFromLibrary}
|
||||
isSaving={isSavingStep}
|
||||
isOpen={customStepFlow.showPostStepModal}
|
||||
onClose={customStepFlow.resetPendingStep}
|
||||
step={customStepFlow.pendingStep}
|
||||
onSaveForLater={customStepFlow.handleSaveForLater}
|
||||
onUseNow={customStepFlow.handleUseNow}
|
||||
onBoth={customStepFlow.handleBoth}
|
||||
isFromLibrary={customStepFlow.pendingStepIsFromLibrary}
|
||||
isSaving={customStepFlow.isSavingStep}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Continuation Modal */}
|
||||
<ContinuationModal
|
||||
isOpen={showContinuationModal}
|
||||
onClose={() => setShowContinuationModal(false)}
|
||||
descendantNodes={branchOriginNodeId ? getDescendantNodes(branchOriginNodeId) : []}
|
||||
onSelectNode={handleSelectDescendant}
|
||||
onBuildCustomBranch={handleBuildCustomBranch}
|
||||
isOpen={customStepFlow.showContinuationModal}
|
||||
onClose={() => customStepFlow.setShowContinuationModal(false)}
|
||||
descendantNodes={customStepFlow.branchOriginNodeId ? customStepFlow.getDescendantNodes(customStepFlow.branchOriginNodeId) : []}
|
||||
onSelectNode={customStepFlow.handleSelectDescendant}
|
||||
onBuildCustomBranch={customStepFlow.handleBuildCustomBranch}
|
||||
/>
|
||||
|
||||
{/* Fork Tree Modal */}
|
||||
<ForkTreeModal
|
||||
isOpen={showForkModal}
|
||||
onClose={() => setShowForkModal(false)}
|
||||
isOpen={customStepFlow.showForkModal}
|
||||
onClose={() => customStepFlow.setShowForkModal(false)}
|
||||
originalTreeName={tree?.name || 'Tree'}
|
||||
onFork={handleForkTree}
|
||||
onSkip={handleSkipFork}
|
||||
onFork={customStepFlow.handleForkTree}
|
||||
onSkip={customStepFlow.handleSkipFork}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user