feat: Step Library sync + service account for default tree ownership

* feat: maintenance flow UX redesign — batch status hub, context strip, detail page upgrades (#85)

- Add BatchStatusPage (/flows/:id/batches/:batchId): per-target Start/Resume/View cards, progress bar, 5s polling while in-progress, completion outcome summary
- Add BatchStatusCard: handles not-started/in-progress/complete states with step progress for in-progress targets
- Add ActiveBatchBanner: amber banner on detail page when a batch is running, links to BatchStatusPage
- Add MaintenanceContextStrip: amber strip in ProceduralNavigationPage for maintenance flows showing target name, batch progress (X/Y complete), and Back to Batch nav
- Update MaintenanceFlowDetailPage: active batch banner, clickable run history rows with mini progress dots and outcome summaries, Run button loading state, post-launch navigates to BatchStatusPage
- Update ProceduralNavigationPage: renders MaintenanceContextStrip between top bar and content when tree_type === 'maintenance'; fetches batch progress once on mount
- Add batch_id filter to GET /sessions backend endpoint and SessionListParams frontend type
- Add /flows/:id/batches/:batchId route to router

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

* feat: session detail page — completion action + outcome summary card

- In-progress sessions: amber banner with "Complete Session" button opens
  SessionOutcomeModal to set outcome/notes/next-steps and finalize
- Completed sessions: colored outcome summary card (icon + outcome label +
  duration + notes + next steps) replaces dense header metadata; "Copy for
  Ticket" promoted to primary action inside the card
- Export toolbar de-emphasized to secondary row of smaller controls below
  the summary card

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

* feat: add library-page action props to StepCard (edit/delete/save)

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

* feat: pass library-page action props through StepLibraryBrowser + refreshKey

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

* feat: StepFormModal wrapper + submitLabel/isSubmitting props on StepForm

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

* feat: Step Library page — create, edit, delete, save-to-library

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

* feat: add RuntimeStep union type for procedural custom steps

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

* feat: StepChecklist accepts RuntimeStep[], renders amber Custom badge

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

* feat: StepDetail accepts RuntimeStep, renders Custom Step badge for custom steps

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

* feat: custom step insertion in procedural flow sessions

Engineers can add custom steps inline during execution. Steps are
persisted to session.custom_steps and restored on resume.

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

* fix: suppress StepFeedback on custom steps, fix resume stepState seeding, functional updater for step index

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

* docs: add tree forking UI design doc

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

* docs: add tree fork UI implementation plan

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

* feat: add ForkInfo type and fork fields to Tree/TreeListItem

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

* fix: align ForkInfo type with backend schema, remove redundant fork fields

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

* fix: ForkInfo placement, required fork_info field, add JSDoc

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

* feat: add ForkModal component with name and reason fields

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

* fix: ForkModal accessibility and UX (escape, click-outside, labels, maxLength)

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

* feat: open ForkModal on fork action in TreeLibraryPage

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

* feat: add ForkModal to MyTreesPage

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

* feat: show Fork chip badge on forked tree cards

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

* docs: add flow-to-library step sync design doc

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

* docs: add flow-to-library sync implementation plan

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

* feat: add sync tracking columns to step_library

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

* feat: add sync columns and source_tree relationship to StepLibrary model

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

* feat: add group_label to StepContent, is_flow_synced/source_tree_name to StepLibraryResponse

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

* feat: include is_flow_synced and source_tree_name in step list/detail responses

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

* fix: add is_flow_synced and source_tree_name to step list response

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

* fix: add selectinload and sync fields to search and get_step endpoints

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

* feat: add step_sync module with extraction and upsert logic

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

* fix: safe NOT IN placeholders for asyncpg, add deactivate docstring

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

* feat: trigger step library sync on tree publish and deactivate on delete

- Call sync_steps_from_tree in update_tree whenever the tree is published
  (status transitions to 'published' or is already published and structure changes)
- Call deactivate_synced_steps_for_tree in delete_tree before db.commit()
  so the FK SET NULL does not nullify source_tree_id before the WHERE clause runs
- Fix ::jsonb cast syntax in step_sync.py (asyncpg rejects :: operator in text()
  queries; replaced with CAST(:content AS jsonb))
- Add UniqueConstraint('source_tree_id','source_node_id') to StepLibrary model
  so Base.metadata.create_all (used by tests) creates the constraint that the
  ON CONFLICT clause in sync_steps_from_tree depends on

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

* feat: add is_flow_synced and source_tree_name to Step types

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

* feat: show From Flow badge and lock icon on flow-synced StepCard

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

* feat: show source flow name in StepDetailModal for synced steps

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

* feat: add Library Visibility select to procedural StepEditor

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

* fix: address code review issues in flow-to-library sync

- Fix sync trigger: only fire on publish transition, not every PUT
- Add TestSyncOnPublish integration tests (2 tests, 16 total passing)
- Add group_label to frontend StepContent interface
- Guard Library Visibility select to procedure_step nodes only
- Block API edits to flow-synced steps (400 read-only guard)

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

* fix: handle None author_id in step sync to avoid invalid UUID error

When a system/default tree has no author (author_id is None),
str(None) produces the literal string 'None' which asyncpg
rejects as an invalid UUID for the created_by column.

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

* fix: add ResolutionFlow service account to own default tree steps in library

Default/system trees had no author_id (NULL), causing a NOT NULL violation
when syncing steps to step_library.created_by on publish.

- Add is_service_account flag to users table (migration 4f4137ce)
- Add service_account.py: idempotent ensure_service_account() creates
  noreply@resolutionflow.com with unusable password on startup
- Cache service account ID on app.state at lifespan startup
- Add get_service_account_id() FastAPI dep (returns None in tests)
- sync_steps_from_tree: resolve author_id or service_account_id as created_by
- create_tree: set author_id=service_account_id for is_default trees
- Migration 1490781700bc: backfill author_id on 31 existing default trees

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit was merged in pull request #89.
This commit is contained in:
chihlasm
2026-02-25 23:17:29 -05:00
committed by GitHub
parent a6abd23727
commit e6a0c0549b
45 changed files with 4261 additions and 270 deletions

View File

@@ -1,9 +1,12 @@
import { useEffect, useState, useRef } from 'react'
import { useParams, useNavigate, useLocation } from 'react-router-dom'
import { ChevronLeft, ChevronRight, ListOrdered, Settings2, X } from 'lucide-react'
import { ChevronLeft, ChevronRight, ListOrdered, Settings2, X, Plus } from 'lucide-react'
import { treesApi } from '@/api/trees'
import { sessionsApi } from '@/api/sessions'
import type { Tree, Session, ProceduralStep, DecisionRecord } from '@/types'
import { stepsApi } from '@/api/steps'
import type { Tree, Session, ProceduralStep, DecisionRecord, RuntimeStep, CustomProceduralStep } from '@/types'
import type { CustomStep } from '@/types/session'
import type { Step } from '@/types/step'
import { IntakeFormModal } from '@/components/procedural/IntakeFormModal'
import { StepChecklist } from '@/components/procedural/StepChecklist'
import { StepDetail } from '@/components/procedural/StepDetail'
@@ -16,6 +19,10 @@ import { toast } from '@/lib/toast'
import { StepFeedback } from '@/components/session/StepFeedback'
import { CSATModal } from '@/components/session/CSATModal'
import { hasBeenRated } from '@/components/session/csatUtils'
import { MaintenanceContextStrip } from '@/components/maintenance/MaintenanceContextStrip'
import { CustomStepModal } from '@/components/step-library/CustomStepModal'
import type { CustomStepDraft } from '@/components/step-library/CustomStepModal'
import { PostStepActionModal } from '@/components/session/PostStepActionModal'
interface StepState {
notes: string
@@ -23,6 +30,29 @@ interface StepState {
completedAt: string | null
}
function buildRuntimeSteps(baseSteps: ProceduralStep[], customSteps: CustomStep[]): RuntimeStep[] {
const result: RuntimeStep[] = [...baseSteps]
const sorted = [...customSteps].sort((a, b) => a.timestamp.localeCompare(b.timestamp))
for (const cs of sorted) {
const afterIdx = result.findIndex((s) => s.id === cs.inserted_after_node_id)
const insertAt = afterIdx >= 0 ? afterIdx + 1 : result.length
const runtimeCustom: CustomProceduralStep = {
id: cs.id,
type: 'procedure_step',
title: cs.step_data.title,
description: cs.step_data.content?.instructions,
content_type: 'action',
commands: cs.step_data.content?.commands?.map((c) => ({
code: c.command,
label: c.label,
})),
isCustom: true,
}
result.splice(insertAt, 0, runtimeCustom)
}
return result
}
export function ProceduralNavigationPage() {
const { id: treeId } = useParams<{ id: string }>()
const navigate = useNavigate()
@@ -43,8 +73,18 @@ export function ProceduralNavigationPage() {
const [paramsOpen, setParamsOpen] = useState(false)
const [showCsatModal, setShowCsatModal] = useState(false)
const [elapsedMinutes, setElapsedMinutes] = useState(0)
const [batchProgress, setBatchProgress] = useState<{ completed: number; total: number } | null>(null)
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
// Custom step state
const [runtimeSteps, setRuntimeSteps] = useState<RuntimeStep[]>([])
const [sessionCustomSteps, setSessionCustomSteps] = useState<CustomStep[]>([])
const [showCustomStepModal, setShowCustomStepModal] = useState(false)
const [showPostStepModal, setShowPostStepModal] = useState(false)
const [pendingCustomStep, setPendingCustomStep] = useState<Step | CustomStepDraft | null>(null)
const [pendingIsFromLibrary, setPendingIsFromLibrary] = useState(false)
const [isSavingStep, setIsSavingStep] = useState(false)
// Get procedural steps from tree
const getSteps = (): ProceduralStep[] => {
if (!tree) return []
@@ -53,7 +93,7 @@ export function ProceduralNavigationPage() {
}
const steps = getSteps()
const procedureSteps = steps.filter((s) => s.type === 'procedure_step')
const procedureSteps = runtimeSteps.filter((s) => s.type === 'procedure_step')
const completedStepIds = new Set(
Array.from(stepStates.entries())
.filter(([, state]) => state.completedAt)
@@ -61,7 +101,7 @@ export function ProceduralNavigationPage() {
)
const estimatedTotalMinutes = procedureSteps.reduce(
(sum, step) => sum + (step.estimated_minutes || 0),
(sum, step) => sum + (('estimated_minutes' in step ? step.estimated_minutes : undefined) || 0),
0
)
@@ -97,6 +137,19 @@ export function ProceduralNavigationPage() {
}
}, [session, isComplete])
// Fetch batch progress once when session loads (maintenance flows only)
useEffect(() => {
if (!session?.batch_id) return
sessionsApi.list({ batch_id: session.batch_id, size: 100 })
.then(data => {
if (Array.isArray(data) && data.length > 0) {
const completed = data.filter(s => s.completed_at).length
setBatchProgress({ completed, total: data.length })
}
})
.catch(() => {})
}, [session?.batch_id])
const loadTree = async (id: string) => {
setIsLoading(true)
try {
@@ -144,6 +197,8 @@ export function ProceduralNavigationPage() {
initialStates.set(step.id, { notes: '', verificationValue: '', completedAt: null })
}
setStepStates(initialStates)
setRuntimeSteps(allSteps)
setSessionCustomSteps([])
} catch {
toast.error('Failed to start session')
}
@@ -158,9 +213,18 @@ export function ProceduralNavigationPage() {
// Initialize step states from session decisions
const allSteps = getStepsFromTree(treeData)
// Initialize custom steps from session data
const customSteps = sessionData.custom_steps || []
setSessionCustomSteps(customSteps)
const hydrated = buildRuntimeSteps(allSteps, customSteps)
setRuntimeSteps(hydrated)
const initialStates = new Map<string, StepState>()
for (const step of allSteps) {
initialStates.set(step.id, { notes: '', verificationValue: '', completedAt: null })
for (const step of hydrated) {
if (step.type === 'procedure_step') {
initialStates.set(step.id, { notes: '', verificationValue: '', completedAt: null })
}
}
// Hydrate completed steps from decisions
@@ -176,7 +240,7 @@ export function ProceduralNavigationPage() {
setStepStates(initialStates)
// Set current step to first incomplete step
const pSteps = allSteps.filter((s) => s.type === 'procedure_step')
const pSteps = hydrated.filter((s) => s.type === 'procedure_step')
const firstIncomplete = pSteps.findIndex((s) => !initialStates.get(s.id)?.completedAt)
setCurrentStepIndex(firstIncomplete >= 0 ? firstIncomplete : pSteps.length - 1)
} catch {
@@ -288,6 +352,112 @@ export function ProceduralNavigationPage() {
setShowCsatModal(false)
}
const handleStepCreated = (step: Step | CustomStepDraft, isFromLibrary: boolean) => {
setPendingCustomStep(step)
setPendingIsFromLibrary(isFromLibrary)
setShowCustomStepModal(false)
setShowPostStepModal(true)
}
const handleInsertCustomStep = async (step: Step | CustomStepDraft) => {
if (!session) return
const id = crypto.randomUUID()
const currentStep = procedureSteps[currentStepIndex]
const insertedAfterId = currentStep?.id ?? ''
const runtimeCustom: CustomProceduralStep = {
id,
type: 'procedure_step',
title: step.title,
description: step.content?.instructions,
content_type: 'action',
commands: step.content?.commands?.map((c) => ({
code: c.command,
label: c.label,
})),
isCustom: true,
}
setRuntimeSteps((prev) => {
const next = [...prev]
const globalIdx = next.findIndex((s) => s.id === insertedAfterId)
const insertAt = globalIdx >= 0 ? globalIdx + 1 : next.length
next.splice(insertAt, 0, runtimeCustom)
return next
})
setStepStates((prev) => {
const next = new Map(prev)
next.set(id, { notes: '', verificationValue: '', completedAt: null })
return next
})
const newCustomStep: CustomStep = {
id,
inserted_after_node_id: insertedAfterId,
step_data: step,
timestamp: new Date().toISOString(),
}
const newCustomSteps = [...sessionCustomSteps, newCustomStep]
setSessionCustomSteps(newCustomSteps)
try {
await sessionsApi.update(session.id, { custom_steps: newCustomSteps })
} catch {
toast.error('Failed to save custom step')
}
setCurrentStepIndex(prev => prev + 1)
}
const handleSaveForLater = async () => {
if (!pendingCustomStep || pendingIsFromLibrary) return
setIsSavingStep(true)
try {
await stepsApi.create({
title: pendingCustomStep.title,
step_type: pendingCustomStep.step_type,
content: pendingCustomStep.content,
visibility: 'private',
})
toast.success('Step saved to library')
} catch {
toast.error('Failed to save step')
} finally {
setIsSavingStep(false)
setShowPostStepModal(false)
setPendingCustomStep(null)
}
}
const handleUseNow = async () => {
if (!pendingCustomStep) return
setShowPostStepModal(false)
await handleInsertCustomStep(pendingCustomStep)
setPendingCustomStep(null)
}
const handleBoth = async () => {
if (!pendingCustomStep || pendingIsFromLibrary) return
setIsSavingStep(true)
try {
await stepsApi.create({
title: pendingCustomStep.title,
step_type: pendingCustomStep.step_type,
content: pendingCustomStep.content,
visibility: 'private',
})
} catch {
toast.error('Failed to save step to library')
} finally {
setIsSavingStep(false)
}
setShowPostStepModal(false)
await handleInsertCustomStep(pendingCustomStep)
setPendingCustomStep(null)
}
// Loading state
if (isLoading) {
return (
@@ -382,6 +552,16 @@ export function ProceduralNavigationPage() {
</div>
</div>
{/* Maintenance context strip */}
{tree?.tree_type === 'maintenance' && session && (
<MaintenanceContextStrip
treeId={treeId!}
targetLabel={session.target_label}
batchId={session.batch_id}
batchProgress={batchProgress}
/>
)}
{/* Main content */}
<div className="flex min-h-0 flex-1 overflow-hidden">
{/* Left sidebar - step checklist */}
@@ -394,7 +574,7 @@ export function ProceduralNavigationPage() {
{sidebarOpen && (
<>
<StepChecklist
steps={steps}
steps={runtimeSteps}
currentStepIndex={currentStepIndex}
completedStepIds={completedStepIds}
onStepClick={setCurrentStepIndex}
@@ -433,7 +613,21 @@ export function ProceduralNavigationPage() {
isLast={currentStepIndex === procedureSteps.length - 1}
/>
)}
{session && currentStep && (
{/* Add custom step — only on current active incomplete non-custom step */}
{currentStep && !completedStepIds.has(currentStep.id) && !('isCustom' in currentStep && currentStep.isCustom) && (
<div className="mt-4">
<button
onClick={() => setShowCustomStepModal(true)}
className="flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-border px-4 py-2.5 text-sm text-muted-foreground transition-colors hover:border-primary/50 hover:text-foreground"
>
<Plus className="h-4 w-4" />
Add Step
</button>
</div>
)}
{session && currentStep && !('isCustom' in currentStep && currentStep.isCustom) && (
<div className="mt-3 flex justify-end">
<StepFeedback stepId={currentStep.id} sessionId={session.id} />
</div>
@@ -489,6 +683,27 @@ export function ProceduralNavigationPage() {
</div>
</div>
)}
{/* Custom Step Modal */}
<CustomStepModal
isOpen={showCustomStepModal}
onClose={() => setShowCustomStepModal(false)}
onInsertStep={handleStepCreated}
/>
{/* Post Step Action Modal */}
{pendingCustomStep && (
<PostStepActionModal
isOpen={showPostStepModal}
onClose={() => { setShowPostStepModal(false); setPendingCustomStep(null) }}
step={pendingCustomStep}
onSaveForLater={handleSaveForLater}
onUseNow={handleUseNow}
onBoth={handleBoth}
isFromLibrary={pendingIsFromLibrary}
isSaving={isSavingStep}
/>
)}
</div>
)
}