All files / web/src/lib/flowchart-workshop state-machine.ts

0% Statements 0/287
0% Branches 0/1
0% Functions 0/1
0% Lines 0/287

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * State Machine for Flowchart Workshop streaming lifecycle
 *
 * Manages the state transitions during flowchart generation and refinement,
 * tracking progress, reasoning, and results.
 *
 * @module flowchart-workshop/state-machine
 */

import type { FlowchartDefinition } from '../flowcharts/schema'

/**
 * Result from a successful generation
 */
export interface FlowchartGenerateResult {
  definition: FlowchartDefinition
  mermaidContent: string
  title: string
  description: string
  emoji: string
  difficulty: string
  notes: string[]
  usage?: {
    promptTokens: number
    completionTokens: number
    reasoningTokens?: number
  }
}

/**
 * Result from a successful refinement
 */
export interface FlowchartRefineResult {
  definition: FlowchartDefinition
  mermaidContent: string
  emoji: string
  changesSummary: string
  notes: string[]
  usage?: {
    promptTokens: number
    completionTokens: number
    reasoningTokens?: number
  }
}

/**
 * Union type for complete results
 */
export type FlowchartCompleteResult = FlowchartGenerateResult | FlowchartRefineResult

/**
 * Check if result is a generation result (has title/description)
 */
export function isGenerateResult(
  result: FlowchartCompleteResult
): result is FlowchartGenerateResult {
  return 'title' in result && 'description' in result
}

/**
 * Possible streaming statuses
 */
export type StreamingStatus =
  | 'idle' // No operation in progress
  | 'connecting' // Initial connection being established
  | 'reasoning' // LLM is thinking (reasoning being streamed)
  | 'generating' // Structured output being generated
  | 'validating' // Result is being validated
  | 'complete' // Operation completed successfully
  | 'error' // Operation failed
  | 'cancelled' // Operation was cancelled by user

/**
 * Type of streaming operation
 */
export type StreamType = 'generate' | 'refine'

/**
 * State for the streaming lifecycle
 */
export interface StreamingState {
  /** Current status of the streaming operation */
  status: StreamingStatus

  /** Type of operation (generate or refine) */
  streamType: StreamType | null

  /** Response ID from the LLM (for debugging/tracking) */
  responseId: string | null

  /** Accumulated reasoning text from the LLM */
  reasoningText: string

  /** Accumulated partial output text */
  outputText: string

  /** Current progress stage */
  progressStage: string | null

  /** Current progress message (user-facing) */
  progressMessage: string | null

  /** Final result when complete */
  result: FlowchartCompleteResult | null

  /** Error message if operation failed */
  error: string | null

  /** Error code if available */
  errorCode: string | null

  /** Token usage statistics */
  usage: {
    promptTokens: number
    completionTokens: number
    reasoningTokens?: number
  } | null
}

/**
 * Initial state
 */
export const initialStreamingState: StreamingState = {
  status: 'idle',
  streamType: null,
  responseId: null,
  reasoningText: '',
  outputText: '',
  progressStage: null,
  progressMessage: null,
  result: null,
  error: null,
  errorCode: null,
  usage: null,
}

/**
 * Actions that can be dispatched to the state machine
 */
export type StreamingAction =
  | { type: 'START_STREAMING'; streamType: StreamType }
  | { type: 'STREAM_STARTED'; responseId: string }
  | { type: 'STREAM_PROGRESS'; stage: string; message: string }
  | { type: 'STREAM_REASONING'; text: string; append: boolean }
  | { type: 'STREAM_OUTPUT'; text: string; append: boolean }
  | { type: 'STREAM_COMPLETE'; result: FlowchartCompleteResult }
  | { type: 'STREAM_ERROR'; message: string; code?: string }
  | { type: 'STREAM_CANCELLED' }
  | { type: 'RESET' }

/**
 * Reducer function for the streaming state machine
 */
export function streamingReducer(state: StreamingState, action: StreamingAction): StreamingState {
  switch (action.type) {
    case 'START_STREAMING':
      return {
        ...initialStreamingState,
        status: 'connecting',
        streamType: action.streamType,
        progressMessage:
          action.streamType === 'generate' ? 'Starting generation...' : 'Starting refinement...',
      }

    case 'STREAM_STARTED':
      return {
        ...state,
        status: 'reasoning',
        responseId: action.responseId,
        progressMessage: 'AI is thinking...',
      }

    case 'STREAM_PROGRESS': {
      // Map progress stages to status
      let newStatus = state.status
      if (action.stage === 'preparing') {
        newStatus = 'connecting'
      } else if (action.stage === 'validating') {
        newStatus = 'validating'
      }
      return {
        ...state,
        status: newStatus,
        progressStage: action.stage,
        progressMessage: action.message,
      }
    }

    case 'STREAM_REASONING':
      return {
        ...state,
        status: 'reasoning',
        reasoningText: action.append ? state.reasoningText + action.text : action.text,
        progressMessage: 'AI is thinking...',
      }

    case 'STREAM_OUTPUT':
      return {
        ...state,
        status: 'generating',
        outputText: action.append ? state.outputText + action.text : action.text,
        progressMessage: 'Generating flowchart...',
      }

    case 'STREAM_COMPLETE':
      return {
        ...state,
        status: 'complete',
        result: action.result,
        progressStage: 'complete',
        progressMessage:
          state.streamType === 'generate' ? 'Flowchart generated!' : 'Flowchart refined!',
        usage: 'usage' in action.result ? (action.result.usage ?? null) : null,
      }

    case 'STREAM_ERROR':
      return {
        ...state,
        status: 'error',
        error: action.message,
        errorCode: action.code ?? null,
        progressMessage: null,
      }

    case 'STREAM_CANCELLED':
      return {
        ...state,
        status: 'cancelled',
        progressMessage: 'Operation cancelled',
      }

    case 'RESET':
      return initialStreamingState

    default:
      return state
  }
}

/**
 * Helper to determine if an operation is in progress
 */
export function isStreaming(status: StreamingStatus): boolean {
  return (
    status === 'connecting' ||
    status === 'reasoning' ||
    status === 'generating' ||
    status === 'validating'
  )
}

/**
 * Helper to determine if the operation completed (successfully or not)
 */
export function isFinished(status: StreamingStatus): boolean {
  return status === 'complete' || status === 'error' || status === 'cancelled'
}

/**
 * Get a user-friendly status message
 */
export function getStatusMessage(state: StreamingState): string {
  if (state.progressMessage) {
    return state.progressMessage
  }

  switch (state.status) {
    case 'idle':
      return ''
    case 'connecting':
      return 'Connecting...'
    case 'reasoning':
      return 'AI is thinking...'
    case 'generating':
      return 'Generating flowchart...'
    case 'validating':
      return 'Validating result...'
    case 'complete':
      return 'Complete!'
    case 'error':
      return state.error || 'An error occurred'
    case 'cancelled':
      return 'Cancelled'
    default:
      return ''
  }
}