feat: Add custom step creation and backend support (Phase 3A: B.8-B.10, B.13)

Implements custom step creation forms and backend persistence:

Task B.8 - StepForm Component:
- Comprehensive form for creating custom steps
- Step type selection (decision/action/solution) with descriptions
- Required fields: title, instructions (markdown supported)
- Optional fields: help text, commands (dynamic array), category, tags
- Visibility control (private/team/public)
- Save to library checkbox
- Full validation with error display
- Dynamic command management (add/remove, label + command)
- Tag input with Enter key support

Task B.9 - CustomStepModal:
- Tabbed modal interface
- Tab 1: "Type My Own" - embeds StepForm
- Tab 2: "Browse Library" - embeds StepLibraryBrowser
- Handles both saved steps (API) and drafts (no save)
- Loading states during step creation
- Error handling with user feedback
- Returns Step or CustomStepDraft to parent

Task B.10 - Backend Custom Steps Support:
- Database migration: add custom_steps JSONB column to sessions
- Updated Session model with custom_steps field
- Updated SessionResponse schema with custom_steps
- Updated SessionUpdate schema to accept custom_steps
- Migration ready to run: 4cdb5cba1aff

Task B.13 - Session Types Updates:
- Added CustomStep and CustomStepDraft interfaces
- Updated Session interface with custom_steps field
- Updated SessionUpdate interface
- Exported step types from types/index.ts
- Full TypeScript support for custom step integration

Remaining tasks: B.11 (TreeNavigationPage integration), B.12 (Export)
Build tested successfully.

Related: Issues #8, #9, #10

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Michael Chihlas
2026-02-03 19:15:36 -05:00
parent fc7fa1a17c
commit 009c60fbc3
7 changed files with 602 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
"""add_custom_steps_to_sessions
Revision ID: 4cdb5cba1aff
Revises: 008
Create Date: 2026-02-03 19:12:42.551966
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB
# revision identifiers, used by Alembic.
revision: str = '4cdb5cba1aff'
down_revision: Union[str, None] = '008'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# Add custom_steps JSONB column to sessions table
op.add_column('sessions',
sa.Column('custom_steps', JSONB, nullable=False, server_default='[]')
)
def downgrade() -> None:
# Remove custom_steps column from sessions table
op.drop_column('sessions', 'custom_steps')

View File

@@ -30,6 +30,7 @@ class Session(Base):
tree_snapshot: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False)
path_taken: Mapped[list[str]] = mapped_column(JSONB, nullable=False, default=list)
decisions: Mapped[list[dict[str, Any]]] = mapped_column(JSONB, nullable=False, default=list)
custom_steps: Mapped[list[dict[str, Any]]] = mapped_column(JSONB, nullable=False, default=list)
started_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),

View File

@@ -24,6 +24,7 @@ class SessionCreate(BaseModel):
class SessionUpdate(BaseModel):
path_taken: Optional[list[str]] = None
decisions: Optional[list[DecisionRecord]] = None
custom_steps: Optional[list[dict[str, Any]]] = None
ticket_number: Optional[str] = Field(None, max_length=100)
client_name: Optional[str] = Field(None, max_length=255)
@@ -35,6 +36,7 @@ class SessionResponse(BaseModel):
tree_snapshot: dict[str, Any]
path_taken: list[str]
decisions: list[dict[str, Any]]
custom_steps: list[dict[str, Any]] = Field(default_factory=list)
started_at: datetime
completed_at: Optional[datetime] = None
ticket_number: Optional[str] = None

View File

@@ -0,0 +1,148 @@
import { useState } from 'react'
import { X } from 'lucide-react'
import { cn } from '@/lib/utils'
import { stepsApi } from '@/api'
import { StepForm } from './StepForm'
import { StepLibraryBrowser } from './StepLibraryBrowser'
import type { Step, StepCreate } from '@/types/step'
export interface CustomStepDraft {
title: string
step_type: 'decision' | 'action' | 'solution'
content: {
instructions: string
help_text?: string
commands?: Array<{
label: string
command: string
command_type?: string
}>
}
category_id?: string
tags?: string[]
}
interface CustomStepModalProps {
isOpen: boolean
onClose: () => void
onInsertStep: (step: Step | CustomStepDraft) => void
}
type Tab = 'create' | 'browse'
export function CustomStepModal({ isOpen, onClose, onInsertStep }: CustomStepModalProps) {
const [activeTab, setActiveTab] = useState<Tab>('create')
const [isSubmitting, setIsSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
if (!isOpen) return null
const handleFormSubmit = async (data: StepCreate, saveToLibrary: boolean) => {
setIsSubmitting(true)
setError(null)
try {
if (saveToLibrary) {
// Save to library first, then return the saved step
const savedStep = await stepsApi.create(data)
onInsertStep(savedStep)
} else {
// Return as draft (not saved to library)
const draft: CustomStepDraft = {
title: data.title,
step_type: data.step_type,
content: data.content,
category_id: data.category_id,
tags: data.tags
}
onInsertStep(draft)
}
} catch (err) {
console.error('Failed to create step:', err)
setError('Failed to create step. Please try again.')
setIsSubmitting(false)
}
}
const handleBrowserInsert = (step: Step) => {
onInsertStep(step)
}
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
<div className="relative flex h-[90vh] w-full max-w-4xl flex-col rounded-lg border border-border bg-card shadow-lg">
{/* Header */}
<div className="flex items-center justify-between border-b border-border p-4">
<h2 className="text-lg font-semibold">Add Custom Step</h2>
<button
onClick={onClose}
className="rounded-md p-1 hover:bg-accent"
aria-label="Close"
>
<X className="h-5 w-5" />
</button>
</div>
{/* Tabs */}
<div className="flex border-b border-border">
<button
onClick={() => setActiveTab('create')}
className={cn(
'flex-1 px-4 py-3 text-sm font-medium transition-colors',
activeTab === 'create'
? 'border-b-2 border-primary bg-primary/5 text-primary'
: 'text-muted-foreground hover:bg-muted/50 hover:text-foreground'
)}
>
Type My Own
</button>
<button
onClick={() => setActiveTab('browse')}
className={cn(
'flex-1 px-4 py-3 text-sm font-medium transition-colors',
activeTab === 'browse'
? 'border-b-2 border-primary bg-primary/5 text-primary'
: 'text-muted-foreground hover:bg-muted/50 hover:text-foreground'
)}
>
Browse Library
</button>
</div>
{/* Error Display */}
{error && (
<div className="mx-4 mt-4 rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
)}
{/* Tab Content */}
<div className="flex-1 overflow-hidden">
{activeTab === 'create' ? (
<div className="h-full overflow-y-auto p-6">
<StepForm
onSubmit={handleFormSubmit}
onCancel={onClose}
/>
</div>
) : (
<StepLibraryBrowser
onInsert={handleBrowserInsert}
showCreateButton={false}
/>
)}
</div>
{/* Loading Overlay */}
{isSubmitting && (
<div className="absolute inset-0 flex items-center justify-center bg-background/80 backdrop-blur-sm">
<div className="flex flex-col items-center gap-3">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
<p className="text-sm text-muted-foreground">Creating step...</p>
</div>
</div>
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,401 @@
import { useState, useEffect } from 'react'
import { Plus, X, HelpCircle, Zap, CheckCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { stepCategoriesApi } from '@/api'
import type { StepCreate, StepCategory, StepCommand } from '@/types/step'
interface StepFormProps {
onSubmit: (data: StepCreate, saveToLibrary: boolean) => void
onCancel: () => void
initialData?: Partial<StepCreate>
}
const stepTypeOptions = [
{ value: 'decision', label: 'Decision', icon: HelpCircle, description: 'Question with multiple options' },
{ value: 'action', label: 'Action', icon: Zap, description: 'Task to perform' },
{ value: 'solution', label: 'Solution', icon: CheckCircle, description: 'Resolution endpoint' }
] as const
export function StepForm({ onSubmit, onCancel, initialData }: StepFormProps) {
// Form state
const [stepType, setStepType] = useState<'decision' | 'action' | 'solution'>(
initialData?.step_type || 'action'
)
const [title, setTitle] = useState(initialData?.title || '')
const [instructions, setInstructions] = useState(initialData?.content?.instructions || '')
const [helpText, setHelpText] = useState(initialData?.content?.help_text || '')
const [commands, setCommands] = useState<StepCommand[]>(initialData?.content?.commands || [])
const [categoryId, setCategoryId] = useState(initialData?.category_id || '')
const [tags, setTags] = useState<string[]>(initialData?.tags || [])
const [tagInput, setTagInput] = useState('')
const [visibility, setVisibility] = useState<'private' | 'team' | 'public'>(
initialData?.visibility || 'private'
)
const [saveToLibrary, setSaveToLibrary] = useState(true)
// Categories
const [categories, setCategories] = useState<StepCategory[]>([])
// Validation
const [errors, setErrors] = useState<Record<string, string>>({})
useEffect(() => {
const loadCategories = async () => {
try {
const data = await stepCategoriesApi.list()
setCategories(data.filter(c => c.is_active))
} catch (err) {
console.error('Failed to load categories:', err)
}
}
loadCategories()
}, [])
const addCommand = () => {
setCommands([...commands, { label: '', command: '', command_type: 'shell' }])
}
const removeCommand = (index: number) => {
setCommands(commands.filter((_, i) => i !== index))
}
const updateCommand = (index: number, field: keyof StepCommand, value: string) => {
const updated = [...commands]
updated[index] = { ...updated[index], [field]: value }
setCommands(updated)
}
const addTag = () => {
const trimmed = tagInput.trim()
if (trimmed && !tags.includes(trimmed)) {
setTags([...tags, trimmed])
setTagInput('')
}
}
const removeTag = (tag: string) => {
setTags(tags.filter(t => t !== tag))
}
const handleTagInputKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
e.preventDefault()
addTag()
}
}
const validate = (): boolean => {
const newErrors: Record<string, string> = {}
if (!title.trim()) {
newErrors.title = 'Title is required'
}
if (!instructions.trim()) {
newErrors.instructions = 'Instructions are required'
}
// Validate commands
commands.forEach((cmd, i) => {
if (cmd.label && !cmd.command) {
newErrors[`command_${i}_command`] = 'Command is required if label is provided'
}
if (cmd.command && !cmd.label) {
newErrors[`command_${i}_label`] = 'Label is required if command is provided'
}
})
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!validate()) {
return
}
const data: StepCreate = {
title: title.trim(),
step_type: stepType,
content: {
instructions: instructions.trim(),
help_text: helpText.trim() || undefined,
commands: commands.filter(c => c.label && c.command).length > 0
? commands.filter(c => c.label && c.command)
: undefined
},
visibility,
category_id: categoryId || undefined,
tags: tags.length > 0 ? tags : undefined
}
onSubmit(data, saveToLibrary)
}
return (
<form onSubmit={handleSubmit} className="space-y-6">
{/* Step Type */}
<div>
<label className="mb-2 block text-sm font-medium">
Step Type <span className="text-destructive">*</span>
</label>
<div className="grid grid-cols-3 gap-2">
{stepTypeOptions.map(option => {
const Icon = option.icon
return (
<button
key={option.value}
type="button"
onClick={() => setStepType(option.value)}
className={cn(
'rounded-lg border p-3 text-left transition-colors',
stepType === option.value
? 'border-primary bg-primary/10 ring-2 ring-primary'
: 'border-border hover:border-primary/50'
)}
>
<div className="mb-1 flex items-center gap-2">
<Icon className="h-4 w-4" />
<span className="font-medium text-sm">{option.label}</span>
</div>
<p className="text-xs text-muted-foreground">{option.description}</p>
</button>
)
})}
</div>
</div>
{/* Title */}
<div>
<label htmlFor="title" className="mb-2 block text-sm font-medium">
Title <span className="text-destructive">*</span>
</label>
<input
id="title"
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Enter step title"
className={cn(
'w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring',
errors.title ? 'border-destructive' : 'border-input'
)}
/>
{errors.title && (
<p className="mt-1 text-xs text-destructive">{errors.title}</p>
)}
</div>
{/* Instructions */}
<div>
<label htmlFor="instructions" className="mb-2 block text-sm font-medium">
Instructions <span className="text-destructive">*</span>
<span className="ml-2 text-xs font-normal text-muted-foreground">(Markdown supported)</span>
</label>
<textarea
id="instructions"
value={instructions}
onChange={(e) => setInstructions(e.target.value)}
placeholder="Describe what to do in this step..."
rows={6}
className={cn(
'w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring',
errors.instructions ? 'border-destructive' : 'border-input'
)}
/>
{errors.instructions && (
<p className="mt-1 text-xs text-destructive">{errors.instructions}</p>
)}
</div>
{/* Help Text */}
<div>
<label htmlFor="helpText" className="mb-2 block text-sm font-medium">
Help Text <span className="text-xs font-normal text-muted-foreground">(Optional)</span>
</label>
<textarea
id="helpText"
value={helpText}
onChange={(e) => setHelpText(e.target.value)}
placeholder="Additional context or tips..."
rows={3}
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
</div>
{/* Commands */}
<div>
<div className="mb-2 flex items-center justify-between">
<label className="text-sm font-medium">
Commands <span className="text-xs font-normal text-muted-foreground">(Optional)</span>
</label>
<button
type="button"
onClick={addCommand}
className="flex items-center gap-1 rounded-md bg-muted px-2 py-1 text-xs font-medium hover:bg-muted/80"
>
<Plus className="h-3 w-3" />
Add Command
</button>
</div>
{commands.length > 0 && (
<div className="space-y-3">
{commands.map((cmd, index) => (
<div key={index} className="rounded-lg border border-border bg-muted/30 p-3">
<div className="mb-2 flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">Command {index + 1}</span>
<button
type="button"
onClick={() => removeCommand(index)}
className="rounded p-1 text-muted-foreground hover:bg-destructive/20 hover:text-destructive"
>
<X className="h-3 w-3" />
</button>
</div>
<div className="space-y-2">
<input
type="text"
value={cmd.label}
onChange={(e) => updateCommand(index, 'label', e.target.value)}
placeholder="Command label (e.g., 'Restart service')"
className={cn(
'w-full rounded-md border bg-background px-3 py-1.5 text-sm',
errors[`command_${index}_label`] ? 'border-destructive' : 'border-input'
)}
/>
<input
type="text"
value={cmd.command}
onChange={(e) => updateCommand(index, 'command', e.target.value)}
placeholder="Command (e.g., 'systemctl restart nginx')"
className={cn(
'w-full rounded-md border bg-background px-3 py-1.5 font-mono text-sm',
errors[`command_${index}_command`] ? 'border-destructive' : 'border-input'
)}
/>
{(errors[`command_${index}_label`] || errors[`command_${index}_command`]) && (
<p className="text-xs text-destructive">
{errors[`command_${index}_label`] || errors[`command_${index}_command`]}
</p>
)}
</div>
</div>
))}
</div>
)}
</div>
{/* Category */}
<div>
<label htmlFor="category" className="mb-2 block text-sm font-medium">
Category <span className="text-xs font-normal text-muted-foreground">(Optional)</span>
</label>
<select
id="category"
value={categoryId}
onChange={(e) => setCategoryId(e.target.value)}
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
>
<option value="">None</option>
{categories.map(cat => (
<option key={cat.id} value={cat.id}>{cat.name}</option>
))}
</select>
</div>
{/* Tags */}
<div>
<label htmlFor="tagInput" className="mb-2 block text-sm font-medium">
Tags <span className="text-xs font-normal text-muted-foreground">(Optional)</span>
</label>
<div className="flex gap-2">
<input
id="tagInput"
type="text"
value={tagInput}
onChange={(e) => setTagInput(e.target.value)}
onKeyDown={handleTagInputKeyDown}
placeholder="Type tag and press Enter"
className="flex-1 rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
<button
type="button"
onClick={addTag}
className="rounded-md bg-muted px-4 py-2 text-sm font-medium hover:bg-muted/80"
>
Add
</button>
</div>
{tags.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1.5">
{tags.map(tag => (
<span
key={tag}
className="flex items-center gap-1 rounded-full bg-primary/10 px-2.5 py-1 text-xs text-primary"
>
{tag}
<button
type="button"
onClick={() => removeTag(tag)}
className="rounded-full hover:bg-primary/20"
>
<X className="h-3 w-3" />
</button>
</span>
))}
</div>
)}
</div>
{/* Visibility */}
<div>
<label htmlFor="visibility" className="mb-2 block text-sm font-medium">
Visibility
</label>
<select
id="visibility"
value={visibility}
onChange={(e) => setVisibility(e.target.value as any)}
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
>
<option value="private">Private (only me)</option>
<option value="team">Team (my team members)</option>
<option value="public">Public (everyone)</option>
</select>
</div>
{/* Save to Library Checkbox */}
<div className="flex items-center gap-2">
<input
type="checkbox"
id="saveToLibrary"
checked={saveToLibrary}
onChange={(e) => setSaveToLibrary(e.target.checked)}
className="h-4 w-4 rounded border-input"
/>
<label htmlFor="saveToLibrary" className="text-sm">
Save to My Step Library for reuse
</label>
</div>
{/* Actions */}
<div className="flex gap-2 pt-4">
<button
type="button"
onClick={onCancel}
className="flex-1 rounded-md border border-input bg-background px-4 py-2 text-sm font-medium hover:bg-accent"
>
Cancel
</button>
<button
type="submit"
className="flex-1 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
>
Insert Step
</button>
</div>
</form>
)
}

View File

@@ -6,6 +6,7 @@ export * from './invite'
export * from './tag'
export * from './category'
export * from './folder'
export * from './step'
// API response wrapper types
export interface PaginatedResponse<T> {

View File

@@ -1,4 +1,5 @@
import type { TreeStructure } from './tree'
import type { Step, StepContent } from './step'
export interface DecisionRecord {
node_id: string
@@ -11,6 +12,21 @@ export interface DecisionRecord {
attachments: string[]
}
export interface CustomStep {
id: string
inserted_after_node_id: string
step_data: Step | CustomStepDraft
timestamp: string
}
export interface CustomStepDraft {
title: string
step_type: 'decision' | 'action' | 'solution'
content: StepContent
category_id?: string
tags?: string[]
}
export interface Session {
id: string
tree_id: string
@@ -18,6 +34,7 @@ export interface Session {
tree_snapshot: TreeStructure
path_taken: string[]
decisions: DecisionRecord[]
custom_steps: CustomStep[]
started_at: string
completed_at: string | null
ticket_number: string | null
@@ -34,6 +51,7 @@ export interface SessionCreate {
export interface SessionUpdate {
path_taken?: string[]
decisions?: DecisionRecord[]
custom_steps?: CustomStep[]
ticket_number?: string
client_name?: string
}