All files / web/src/hooks useSessionBroadcast.ts

68.94% Statements 373/541
94.11% Branches 32/34
100% Functions 2/2
68.94% Lines 373/541

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 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 5421x 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 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 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 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 37x 36x 36x 36x 36x 36x 37x 37x 37x 37x 37x 37x 37x 14x 14x 14x 14x 37x 37x 3x 3x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 14x 14x 14x 14x 14x 14x 14x 1x 1x           1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 22x 22x 22x 22x 22x 22x 22x 22x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x     13x 13x 13x 13x 1x 1x 1x 1x 1x 13x 13x 13x 13x                                                   13x 13x 13x 13x         13x 13x 13x 13x         13x 13x 13x 13x           13x 13x 13x 13x           13x 13x 13x 13x               13x 13x 13x       13x 13x 13x 13x 13x 13x 13x 13x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x                                                 14x 14x 14x 14x 14x                     14x 14x 14x 14x 14x 6x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 14x 14x 14x 14x 14x                                         14x 14x 14x 14x                         14x 14x 14x 14x 14x                                                                                     14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x  
'use client'
 
import { useCallback, useEffect, useRef, useState } from 'react'
import type { Socket } from 'socket.io-client'
import { createSocket } from '@/lib/socket'
import type { BroadcastState } from '@/components/practice'
import type { SessionPartType } from '@/db/schema/session-plans'
import type { SessionFlowState } from '@/db/schema/session-plans'
import type {
  AbacusControlEvent,
  ObserverCoPlayLeaveEvent,
  ObserverCoPlayReadyEvent,
  PartTransitionCompleteEvent,
  PartTransitionEvent,
  PracticeStateEvent,
  SessionFlowStateEvent,
  SessionPausedEvent,
  SessionResumedEvent,
  VisionFrameEvent,
} from '@/lib/classroom/socket-events'
 
/**
 * Abacus control action received from teacher
 */
export type ReceivedAbacusControl =
  | { type: 'show-abacus' }
  | { type: 'hide-abacus' }
  | { type: 'set-value'; value: number }
 
/**
 * Pause request from teacher
 */
export interface TeacherPauseRequest {
  /** Optional message from teacher to display on pause screen */
  message?: string
}
 
/**
 * Options for useSessionBroadcast hook
 */
export interface UseSessionBroadcastOptions {
  /** Callback when an abacus control event is received from teacher */
  onAbacusControl?: (control: ReceivedAbacusControl) => void
  /** Callback when teacher pauses the session */
  onTeacherPause?: (request: TeacherPauseRequest) => void
  /** Callback when teacher resumes the session */
  onTeacherResume?: () => void
}
 
/**
 * Hook to broadcast practice session state to observers via WebSocket
 *
 * Broadcasts to any observer (teacher in classroom or parent at home).
 * Always connects when there's an active session - observers join the channel.
 *
 * @param sessionId - The session plan ID
 * @param playerId - The student's player ID
 * @param state - Current practice state (or null if not in active practice)
 * @param options - Optional callbacks for receiving observer control events
 */
export interface UseSessionBroadcastResult {
  isConnected: boolean
  isBroadcasting: boolean
  /** Whether vision recording is active */
  isRecording: boolean
  /** Recording ID if currently recording */
  recordingId: string | null
  /** Observers who are ready to join game breaks as participants */
  readyObservers: ReadyObserver[]
  /** Send part transition event to observers */
  sendPartTransition: (
    previousPartType: SessionPartType | null,
    nextPartType: SessionPartType,
    countdownStartTime: number,
    countdownDurationMs: number
  ) => void
  /** Send part transition complete event to observers */
  sendPartTransitionComplete: () => void
  /** Send vision frame to observers (when student has vision mode enabled) */
  sendVisionFrame: (imageData: string, detectedValue: number | null, confidence: number) => void
  /** Start vision recording for this session */
  startVisionRecording: () => void
  /** Stop vision recording for this session */
  stopVisionRecording: () => void
  /** Send a problem marker for timeline synchronization */
  sendProblemMarker: (
    problemNumber: number,
    partIndex: number,
    eventType: 'problem-shown' | 'answer-submitted' | 'feedback-shown',
    isCorrect?: boolean,
    /** Retry context for multi-attempt support */
    retryContext?: {
      epochNumber: number
      attemptNumber: number
      isRetry: boolean
      isManualRedo: boolean
    },
    /** Slot ID identifying this problem (same ID used in answer validation) */
    slotId?: string,
    /** Problem data for problem-shown markers */
    problem?: { terms: number[]; answer: number }
  ) => void
}
 
/**
 * An observer who is ready to join game breaks as a participant.
 */
export interface ReadyObserver {
  observerId: string
  player: {
    name: string
    emoji: string
    color: string
  }
}
 
/**
 * Break context for game breaks — passed to broadcastFlowState so observers
 * know which game is being played and in what phase.
 */
export interface BreakContext {
  roomId: string
  gameName: string
  gameId: string
  phase: 'selecting' | 'playing' | 'completed'
}
 
export function useSessionBroadcast(
  sessionId: string | undefined,
  playerId: string | undefined,
  state: BroadcastState | null,
  flowState: SessionFlowState,
  breakContext: BreakContext | null,
  options?: UseSessionBroadcastOptions
): UseSessionBroadcastResult {
  const socketRef = useRef<Socket | null>(null)
  const isConnectedRef = useRef(false)
  // Keep state in a ref so socket event handlers can access current state
  const stateRef = useRef<BroadcastState | null>(null)
  stateRef.current = state
 
  // Keep options in a ref so socket event handlers can access current callbacks
  const optionsRef = useRef(options)
  optionsRef.current = options
 
  // Vision recording state
  const isRecordingRef = useRef(false)
  const recordingIdRef = useRef<string | null>(null)
 
  // Ready observers for co-play
  const [readyObservers, setReadyObservers] = useState<ReadyObserver[]>([])
 
  // Track current flow state in ref for socket handlers
  const flowStateRef = useRef<SessionFlowState>(flowState)
  flowStateRef.current = flowState
 
  // Track current break context in ref for socket handlers
  const breakContextRef = useRef<BreakContext | null>(breakContext)
  breakContextRef.current = breakContext
 
  // Helper to broadcast current flow state (authoritative state for observers)
  const broadcastFlowState = useCallback(() => {
    if (!socketRef.current || !isConnectedRef.current || !sessionId) return
 
    const event: SessionFlowStateEvent = {
      sessionId,
      flowState: flowStateRef.current,
      breakContext: breakContextRef.current ?? undefined,
    }
 
    socketRef.current.emit('session-flow-state', event)
    console.log('[SessionBroadcast] Emitted session-flow-state:', {
      flowState: event.flowState,
      hasBreakContext: !!event.breakContext,
    })
  }, [sessionId])
 
  // Helper to broadcast current state
  const broadcastState = useCallback(() => {
    const currentState = stateRef.current
    if (!socketRef.current || !isConnectedRef.current || !sessionId || !currentState) {
      return
    }
 
    const event: PracticeStateEvent = {
      sessionId,
      currentProblem: currentState.currentProblem,
      phase: currentState.phase,
      studentAnswer: currentState.studentAnswer,
      isCorrect: currentState.isCorrect,
      timing: {
        startedAt: currentState.startedAt,
        elapsed: Date.now() - currentState.startedAt,
      },
      purpose: currentState.purpose,
      complexity: currentState.complexity,
      currentProblemNumber: currentState.currentProblemNumber,
      totalProblems: currentState.totalProblems,
      // Session structure for progress indicator
      sessionParts: currentState.sessionParts,
      currentPartIndex: currentState.currentPartIndex,
      currentSlotIndex: currentState.currentSlotIndex,
      slotResults: currentState.slotResults,
    }
 
    socketRef.current.emit('practice-state', event)
    console.log('[SessionBroadcast] Emitted practice-state:', {
      phase: currentState.phase,
      answer: currentState.studentAnswer,
      isCorrect: currentState.isCorrect,
    })
  }, [sessionId])
 
  // Connect to socket and join session channel when there's an active session
  // This enables both teachers (classroom) and parents (home) to observe
  useEffect(() => {
    // Only connect if we have a session
    if (!sessionId || !playerId) {
      // Clean up if we were connected
      if (socketRef.current) {
        console.log('[SessionBroadcast] Disconnecting - session ended')
        socketRef.current.disconnect()
        socketRef.current = null
        isConnectedRef.current = false
      }
      return
    }
 
    // Create socket connection
    const socket = createSocket({
      reconnection: true,
      reconnectionDelay: 1000,
      reconnectionAttempts: 5,
    })
    socketRef.current = socket
 
    // Handler for when socket connects
    const handleConnect = () => {
      console.log('[SessionBroadcast] Connected, joining session channel:', sessionId)
      isConnectedRef.current = true
      // Join the session channel so we can receive 'observer-joined' events
      socket.emit('join-session', { sessionId })
      // Broadcast current state immediately so any waiting observers get it
      broadcastFlowState()
      broadcastState()
    }
 
    socket.on('connect', handleConnect)
 
    // IMPORTANT: If socket is already connected (shared Manager), the 'connect' event
    // won't fire. We need to manually trigger the connect logic in this case.
    if (socket.connected) {
      console.log('[SessionBroadcast] Socket already connected, triggering connect logic')
      handleConnect()
    }
 
    socket.on('disconnect', () => {
      console.log('[SessionBroadcast] Disconnected')
      isConnectedRef.current = false
    })
 
    // When an observer joins, re-broadcast current state so they see it immediately
    socket.on('observer-joined', (data: { observerId: string }) => {
      console.log('[SessionBroadcast] Observer joined:', data.observerId, '- re-broadcasting state')
      // Always send authoritative flow state first — this is the primary state signal
      broadcastFlowState()
      // Then send practice state if available (may be null during game breaks)
      broadcastState()
    })
 
    // Listen for abacus control events from teacher
    socket.on('abacus-control', (data: AbacusControlEvent) => {
      console.log('[SessionBroadcast] Received abacus-control:', data)
      // Only handle controls for our session and the main practice abacus ('hero')
      if (data.sessionId !== sessionId || data.target !== 'hero') {
        return
      }

      // Map the socket event to our ReceivedAbacusControl type
      let control: ReceivedAbacusControl
      switch (data.action) {
        case 'show':
          control = { type: 'show-abacus' }
          break
        case 'hide':
          control = { type: 'hide-abacus' }
          break
        case 'set-value':
          if (data.value === undefined) return // Invalid event
          control = { type: 'set-value', value: data.value }
          break
        default:
          return // Unknown action
      }

      // Call the callback if provided
      optionsRef.current?.onAbacusControl?.(control)
    })
 
    // Listen for pause events from teacher
    socket.on('session-paused', (data: SessionPausedEvent) => {
      console.log('[SessionBroadcast] Received session-paused:', data)
      if (data.sessionId !== sessionId) return

      optionsRef.current?.onTeacherPause?.({ message: data.message })
    })
 
    // Listen for resume events from teacher
    socket.on('session-resumed', (data: SessionResumedEvent) => {
      console.log('[SessionBroadcast] Received session-resumed:', data)
      if (data.sessionId !== sessionId) return

      optionsRef.current?.onTeacherResume?.()
    })
 
    // Listen for recording started event
    socket.on('vision-recording-started', (data: { sessionId: string; recordingId: string }) => {
      console.log('[SessionBroadcast] Recording started:', data.recordingId)
      if (data.sessionId === sessionId) {
        isRecordingRef.current = true
        recordingIdRef.current = data.recordingId
      }
    })
 
    // Listen for recording stopped event
    socket.on('vision-recording-stopped', (data: { sessionId: string; durationMs: number }) => {
      console.log('[SessionBroadcast] Recording stopped, duration:', data.durationMs)
      if (data.sessionId === sessionId) {
        isRecordingRef.current = false
        recordingIdRef.current = null
      }
    })
 
    // Listen for observer co-play readiness
    socket.on('observer-coplay-ready', (data: ObserverCoPlayReadyEvent) => {
      if (data.sessionId !== sessionId) return
      console.log('[SessionBroadcast] Observer ready for co-play:', data.observerId)
      setReadyObservers((prev) => {
        // Replace existing entry for same observer, or add new
        const filtered = prev.filter((o) => o.observerId !== data.observerId)
        return [...filtered, { observerId: data.observerId, player: data.player }]
      })
    })
 
    socket.on('observer-coplay-leave', (data: ObserverCoPlayLeaveEvent) => {
      if (data.sessionId !== sessionId) return
      console.log('[SessionBroadcast] Observer leaving co-play:', data.observerId)
      setReadyObservers((prev) => prev.filter((o) => o.observerId !== data.observerId))
    })
 
    return () => {
      console.log('[SessionBroadcast] Cleaning up socket connection')
      socket.disconnect()
      socketRef.current = null
      isConnectedRef.current = false
    }
  }, [sessionId, playerId, broadcastState])
 
  // Broadcast flow state whenever it or break context changes
  useEffect(() => {
    broadcastFlowState()
  }, [broadcastFlowState, flowState, breakContext])
 
  // Broadcast practice state changes
  useEffect(() => {
    broadcastState()
  }, [
    broadcastState,
    state?.currentProblem?.answer, // New problem
    state?.phase, // Phase change
    state?.studentAnswer, // Answer submitted
    state?.isCorrect, // Result received
    state?.purpose, // Purpose change
  ])
 
  // Broadcast part transition to observers
  const sendPartTransition = useCallback(
    (
      previousPartType: SessionPartType | null,
      nextPartType: SessionPartType,
      countdownStartTime: number,
      countdownDurationMs: number
    ) => {
      if (!socketRef.current || !isConnectedRef.current || !sessionId) {
        return
      }

      const event: PartTransitionEvent = {
        sessionId,
        previousPartType,
        nextPartType,
        countdownStartTime,
        countdownDurationMs,
      }

      socketRef.current.emit('part-transition', event)
      console.log('[SessionBroadcast] Emitted part-transition:', {
        previousPartType,
        nextPartType,
        countdownDurationMs,
      })
    },
    [sessionId]
  )
 
  // Broadcast part transition complete to observers
  const sendPartTransitionComplete = useCallback(() => {
    if (!socketRef.current || !isConnectedRef.current || !sessionId) {
      return
    }

    const event: PartTransitionCompleteEvent = {
      sessionId,
    }

    socketRef.current.emit('part-transition-complete', event)
    console.log('[SessionBroadcast] Emitted part-transition-complete')
  }, [sessionId])
 
  // Broadcast vision frame to observers
  const sendVisionFrame = useCallback(
    (imageData: string, detectedValue: number | null, confidence: number) => {
      if (!socketRef.current || !isConnectedRef.current || !sessionId) {
        return
      }
 
      const event: VisionFrameEvent = {
        sessionId,
        imageData,
        detectedValue,
        confidence,
        timestamp: Date.now(),
      }
 
      socketRef.current.emit('vision-frame', event)
    },
    [sessionId]
  )
 
  // Start vision recording for this session
  const startVisionRecording = useCallback(() => {
    console.log('[SessionBroadcast] startVisionRecording called', {
      hasSocket: !!socketRef.current,
      isConnected: isConnectedRef.current,
      sessionId,
      playerId,
      isRecording: isRecordingRef.current,
    })

    if (!socketRef.current || !isConnectedRef.current || !sessionId || !playerId) {
      console.warn('[SessionBroadcast] Cannot start recording - not connected or missing IDs')
      return
    }

    if (isRecordingRef.current) {
      console.log('[SessionBroadcast] Recording already active')
      return
    }

    console.log('[SessionBroadcast] Emitting start-vision-recording event')
    socketRef.current.emit('start-vision-recording', { sessionId, playerId })
  }, [sessionId, playerId])
 
  // Stop vision recording for this session
  const stopVisionRecording = useCallback(() => {
    if (!socketRef.current || !isConnectedRef.current || !sessionId) {
      console.warn('[SessionBroadcast] Cannot stop recording - not connected')
      return
    }

    if (!isRecordingRef.current) {
      console.log('[SessionBroadcast] No recording active')
      return
    }

    console.log('[SessionBroadcast] Stopping vision recording')
    socketRef.current.emit('stop-vision-recording', { sessionId })
  }, [sessionId])
 
  // Send a problem marker for timeline synchronization
  const sendProblemMarker = useCallback(
    (
      problemNumber: number,
      partIndex: number,
      eventType: 'problem-shown' | 'answer-submitted' | 'feedback-shown',
      isCorrect?: boolean,
      retryContext?: {
        epochNumber: number
        attemptNumber: number
        isRetry: boolean
        isManualRedo: boolean
      },
      slotId?: string,
      problem?: { terms: number[]; answer: number }
    ) => {
      if (!socketRef.current || !isConnectedRef.current || !sessionId) {
        return
      }

      // Always send markers - server will capture metadata even without video frames
      // This enables playback of student answers even when camera wasn't enabled

      socketRef.current.emit('vision-problem-marker', {
        sessionId,
        playerId, // Include playerId for auto-starting metadata-only sessions
        problemNumber,
        partIndex,
        eventType,
        isCorrect,
        epochNumber: retryContext?.epochNumber ?? 0,
        attemptNumber: retryContext?.attemptNumber ?? 1,
        isRetry: retryContext?.isRetry ?? false,
        isManualRedo: retryContext?.isManualRedo ?? false,
        slotId,
        problem,
      })
      console.log('[SessionBroadcast] Sent problem marker:', {
        problemNumber,
        partIndex,
        eventType,
        isCorrect,
        retryContext,
      })
    },
    [sessionId, playerId]
  )
 
  return {
    isConnected: isConnectedRef.current,
    isBroadcasting: isConnectedRef.current && !!state,
    isRecording: isRecordingRef.current,
    recordingId: recordingIdRef.current,
    readyObservers,
    sendPartTransition,
    sendPartTransitionComplete,
    sendVisionFrame,
    startVisionRecording,
    stopVisionRecording,
    sendProblemMarker,
  }
}