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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Worksheet Parsing State Machine
*
* Provides a centralized state reducer for all worksheet parsing operations.
* Supports multiple concurrent parsing operations (one per attachment).
*/
import type { BoundingBox, WorksheetParsingResult } from './schemas'
// ============================================================================
// Types
// ============================================================================
/** Stats returned from parsing */
export interface ParsingStats {
totalProblems: number
correctCount: number
incorrectCount: number
unansweredCount: number
accuracy: number | null
skillsDetected: string[]
}
/** Completed problem for progressive highlighting */
export interface CompletedProblem {
problemNumber: number
problemBoundingBox: BoundingBox
}
/** Stream type for distinguishing parse operations */
export type StreamType = 'initial' | 'reparse'
/** Streaming status */
export type StreamingStatus =
| 'idle'
| 'connecting'
| 'reasoning'
| 'processing' // Used during reparse
| 'generating'
| 'complete'
| 'error'
| 'cancelled'
/**
* Streaming sub-state (active during parsing phase)
*
* Tracks real-time LLM output for display in the UI
*/
export interface StreamingState {
/** Current streaming status */
status: StreamingStatus
/** Type of streaming operation */
streamType: StreamType
/** Accumulated reasoning text (model's thinking process) */
reasoningText: string
/** Accumulated output text (partial JSON) */
outputText: string
/** Progress message for display */
progressMessage: string | null
/** Problems that have been fully streamed (for progressive highlighting) */
completedProblems: CompletedProblem[]
/** For reparse: current problem index being processed */
currentProblemIndex?: number
/** For reparse: total problems to process */
totalProblems?: number
/** For reparse: completed problem indices */
completedIndices?: number[]
}
/**
* Full parsing context state
*
* Supports multiple concurrent parsing operations via Map
*/
export interface ParsingContextState {
/** Map of attachment ID to streaming state (supports concurrent parses) */
activeStreams: Map<string, StreamingState>
/** Last successful results per attachment */
lastResults: Map<string, WorksheetParsingResult>
/** Last parsing stats per attachment */
lastStats: Map<string, ParsingStats>
/** Last error messages per attachment */
lastErrors: Map<string, { message: string; code?: string }>
}
// ============================================================================
// Actions
// ============================================================================
export type ParsingAction =
// Start/Stop operations (all require attachmentId for multi-stream support)
| {
type: 'START_STREAMING'
attachmentId: string
streamType: StreamType
totalProblems?: number
}
| { type: 'CANCEL'; attachmentId: string }
| { type: 'CANCEL_ALL' }
| { type: 'RESET' }
// Streaming updates (all require attachmentId)
| { type: 'STREAM_CONNECTING'; attachmentId: string }
| { type: 'STREAM_REASONING'; attachmentId: string; text: string; append?: boolean }
| { type: 'STREAM_OUTPUT'; attachmentId: string; text: string }
| {
type: 'STREAM_PROBLEM_COMPLETE'
attachmentId: string
problem: CompletedProblem
problemIndex?: number
}
| { type: 'STREAM_REPARSE_PROGRESS'; attachmentId: string; current: number; total: number }
| { type: 'STREAM_PROGRESS_MESSAGE'; attachmentId: string; message: string }
// Completion (all require attachmentId)
| {
type: 'PARSE_COMPLETE'
attachmentId: string
result: WorksheetParsingResult | null
stats?: ParsingStats
}
| { type: 'PARSE_FAILED'; attachmentId: string; error: string; code?: string }
// ============================================================================
// Initial State
// ============================================================================
export const initialParsingState: ParsingContextState = {
activeStreams: new Map(),
lastResults: new Map(),
lastStats: new Map(),
lastErrors: new Map(),
}
// ============================================================================
// Helper to update a specific stream
// ============================================================================
function updateStream(
streams: Map<string, StreamingState>,
attachmentId: string,
updater: (stream: StreamingState) => StreamingState
): Map<string, StreamingState> {
const stream = streams.get(attachmentId)
if (!stream) return streams
const newStreams = new Map(streams)
newStreams.set(attachmentId, updater(stream))
return newStreams
}
// ============================================================================
// Reducer
// ============================================================================
export function parsingReducer(
state: ParsingContextState,
action: ParsingAction
): ParsingContextState {
switch (action.type) {
case 'START_STREAMING': {
const newStreams = new Map(state.activeStreams)
newStreams.set(action.attachmentId, {
status: 'connecting',
streamType: action.streamType,
reasoningText: '',
outputText: '',
progressMessage: 'Connecting to AI...',
completedProblems: [],
currentProblemIndex: action.streamType === 'reparse' ? 0 : undefined,
totalProblems: action.totalProblems,
completedIndices: action.streamType === 'reparse' ? [] : undefined,
})
// Clear any previous error for this attachment
const newErrors = new Map(state.lastErrors)
newErrors.delete(action.attachmentId)
return {
...state,
activeStreams: newStreams,
lastErrors: newErrors,
}
}
case 'STREAM_CONNECTING':
return {
...state,
activeStreams: updateStream(state.activeStreams, action.attachmentId, (stream) => ({
...stream,
status: 'connecting',
progressMessage: 'Connecting to AI...',
})),
}
case 'STREAM_REASONING':
return {
...state,
activeStreams: updateStream(state.activeStreams, action.attachmentId, (stream) => ({
...stream,
// For initial parse: set status to "reasoning"
// For reparse: keep current status (should be "processing" from problem_start)
status: stream.streamType === 'initial' ? 'reasoning' : stream.status,
reasoningText: action.append ? stream.reasoningText + action.text : action.text,
progressMessage:
stream.streamType === 'initial' ? 'AI is thinking...' : stream.progressMessage,
})),
}
case 'STREAM_OUTPUT':
return {
...state,
activeStreams: updateStream(state.activeStreams, action.attachmentId, (stream) => ({
...stream,
status: 'generating',
outputText: stream.outputText + action.text,
progressMessage:
stream.completedProblems.length > 0
? `Extracting problems... ${stream.completedProblems.length} found`
: 'Generating results...',
})),
}
case 'STREAM_PROBLEM_COMPLETE':
return {
...state,
activeStreams: updateStream(state.activeStreams, action.attachmentId, (stream) => ({
...stream,
completedProblems: [...stream.completedProblems, action.problem],
completedIndices:
action.problemIndex !== undefined && stream.completedIndices
? [...stream.completedIndices, action.problemIndex]
: stream.completedIndices,
})),
}
case 'STREAM_REPARSE_PROGRESS':
return {
...state,
activeStreams: updateStream(state.activeStreams, action.attachmentId, (stream) => ({
...stream,
// Use "processing" for reparse to match expected UI state
status: 'processing',
currentProblemIndex: action.current,
totalProblems: action.total,
progressMessage: `Analyzing problem ${action.current + 1} of ${action.total}...`,
})),
}
case 'STREAM_PROGRESS_MESSAGE':
return {
...state,
activeStreams: updateStream(state.activeStreams, action.attachmentId, (stream) => ({
...stream,
progressMessage: action.message,
})),
}
case 'PARSE_COMPLETE': {
// Remove from active streams
const newStreams = new Map(state.activeStreams)
newStreams.delete(action.attachmentId)
// Store result if provided
const newResults = new Map(state.lastResults)
if (action.result) {
newResults.set(action.attachmentId, action.result)
}
// Store stats if provided
const newStats = new Map(state.lastStats)
if (action.stats) {
newStats.set(action.attachmentId, action.stats)
}
return {
...state,
activeStreams: newStreams,
lastResults: newResults,
lastStats: newStats,
}
}
case 'PARSE_FAILED': {
// Remove from active streams
const newStreams = new Map(state.activeStreams)
newStreams.delete(action.attachmentId)
// Store error with optional code
const newErrors = new Map(state.lastErrors)
newErrors.set(action.attachmentId, { message: action.error, code: action.code })
return {
...state,
activeStreams: newStreams,
lastErrors: newErrors,
}
}
case 'CANCEL': {
// Remove specific stream
const newStreams = new Map(state.activeStreams)
newStreams.delete(action.attachmentId)
return {
...state,
activeStreams: newStreams,
}
}
case 'CANCEL_ALL': {
return {
...state,
activeStreams: new Map(),
}
}
case 'RESET':
return initialParsingState
default:
return state
}
}
// ============================================================================
// Selectors (helper functions)
// ============================================================================
/**
* Check if currently parsing a specific attachment
*/
export function isParsingAttachment(state: ParsingContextState, attachmentId: string): boolean {
const stream = state.activeStreams.get(attachmentId)
if (!stream) return false
return stream.status !== 'complete' && stream.status !== 'error' && stream.status !== 'cancelled'
}
/**
* Check if any parsing operation is in progress
*/
export function isAnyParsingActive(state: ParsingContextState): boolean {
for (const stream of state.activeStreams.values()) {
if (
stream.status !== 'complete' &&
stream.status !== 'error' &&
stream.status !== 'cancelled'
) {
return true
}
}
return false
}
/**
* Get the current streaming status for an attachment
*/
export function getStreamingStatus(
state: ParsingContextState,
attachmentId: string
): StreamingStatus | null {
return state.activeStreams.get(attachmentId)?.status ?? null
}
/**
* Get the streaming state for a specific attachment
*/
export function getStreamingState(
state: ParsingContextState,
attachmentId: string
): StreamingState | null {
return state.activeStreams.get(attachmentId) ?? null
}
/**
* Get the number of active parsing operations
*/
export function getActiveParsingCount(state: ParsingContextState): number {
let count = 0
for (const stream of state.activeStreams.values()) {
if (
stream.status !== 'complete' &&
stream.status !== 'error' &&
stream.status !== 'cancelled'
) {
count++
}
}
return count
}
// ============================================================================
// Legacy compatibility - single attachment getters
// ============================================================================
/**
* @deprecated Use getStreamingState(state, attachmentId) instead
* Get the "active" attachment ID (returns first active one for backwards compat)
*/
export function getActiveAttachmentId(state: ParsingContextState): string | null {
for (const [attachmentId, stream] of state.activeStreams.entries()) {
if (
stream.status !== 'complete' &&
stream.status !== 'error' &&
stream.status !== 'cancelled'
) {
return attachmentId
}
}
return null
}
/**
* @deprecated Use state.activeStreams.get(attachmentId) instead
* Get "the" streaming state (returns first active one for backwards compat)
*/
export function getActiveStreaming(state: ParsingContextState): StreamingState | null {
for (const stream of state.activeStreams.values()) {
if (
stream.status !== 'complete' &&
stream.status !== 'error' &&
stream.status !== 'cancelled'
) {
return stream
}
}
return null
}
|