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 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 | 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 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 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 74x 74x 74x 23x 23x 23x 23x 2x 2x 2x 2x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 15x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 8x 15x 8x 8x 8x 8x 8x 8x 8x 6x 3x 1x 6x 6x 6x 6x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x | 'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import type { Socket } from 'socket.io-client'
import { createSocket } from '@/lib/socket'
import type { SessionPart, SessionPartType, SlotResult } from '@/db/schema/session-plans'
import type { SessionFlowState } from '@/db/schema/session-plans'
import type {
AbacusControlEvent,
PartTransitionCompleteEvent,
PartTransitionEvent,
PracticeStateEvent,
SessionFlowStateEvent,
SessionPausedEvent,
SessionResumedEvent,
VisionFrameEvent,
} from '@/lib/classroom/socket-events'
/**
* Control actions a teacher can send to a student's practice session abacus
*/
export type SessionAbacusControlAction =
| { type: 'show-abacus' }
| { type: 'hide-abacus' }
| { type: 'set-abacus-value'; value: number }
/**
* Complexity data from broadcast
*/
export interface ObservedComplexity {
/** Complexity bounds from slot constraints */
bounds?: { min?: number; max?: number }
/** Total complexity cost from generation trace */
totalCost?: number
/** Number of steps (for per-term average) */
stepCount?: number
/** Pre-formatted target skill name */
targetSkillName?: string
}
/**
* State of an observed practice session
*/
export interface ObservedSessionState {
/** Current problem being worked on */
currentProblem: {
terms: number[]
answer: number
}
/** Current phase of the interaction */
phase: 'problem' | 'feedback' | 'tutorial'
/** Student's current typed answer (digit by digit, empty string if not started) */
studentAnswer: string
/** Whether the answer is correct (null if not yet submitted) */
isCorrect: boolean | null
/** Timing information */
timing: {
startedAt: number
elapsed: number
}
/** Purpose of this problem slot (why it was selected) */
purpose: 'focus' | 'reinforce' | 'review' | 'challenge'
/** Complexity data for tooltip display */
complexity?: ObservedComplexity
/** When this state was received */
receivedAt: number
/** Current problem number (1-indexed for display) */
currentProblemNumber: number
/** Total problems in the session */
totalProblems: number
/** Session structure for progress indicator */
sessionParts?: SessionPart[]
/** Current part index for progress indicator */
currentPartIndex?: number
/** Current slot index within the part */
currentSlotIndex?: number
/** Accumulated results for progress indicator */
slotResults?: SlotResult[]
}
/**
* State of a part transition being observed
*/
export interface ObservedTransitionState {
/** Part type transitioning FROM (null if session start) */
previousPartType: SessionPartType | null
/** Part type transitioning TO */
nextPartType: SessionPartType
/** Timestamp when countdown started (for sync) */
countdownStartTime: number
/** Countdown duration in ms */
countdownDurationMs: number
}
/**
* A recorded result from a completed problem during observation
*/
export interface ObservedResult {
/** Problem number (1-indexed) */
problemNumber: number
/** The problem terms */
terms: number[]
/** Correct answer */
answer: number
/** Student's submitted answer */
studentAnswer: string
/** Whether correct */
isCorrect: boolean
/** Purpose of this problem slot */
purpose: 'focus' | 'reinforce' | 'review' | 'challenge'
/** Response time in ms */
responseTimeMs: number
/** When recorded */
recordedAt: number
}
/**
* Vision frame received from student's abacus camera
*/
export interface ObservedVisionFrame {
/** Base64-encoded JPEG image data */
imageData: string
/** Detected abacus value (null if not yet detected) */
detectedValue: number | null
/** Detection confidence (0-1) */
confidence: number
/** When this frame was received by observer */
receivedAt: number
}
/**
* DVR buffer info for live scrub-back (per-problem scope)
*/
export interface DvrBufferInfo {
/** Start of available buffer (ms from recording start) */
availableFromMs: number
/** End of available buffer (ms from recording start) */
availableToMs: number
/** When the current problem started (ms from recording start), null if not yet shown */
currentProblemStartMs: number | null
/** Current problem number (1-indexed), null if not yet shown */
currentProblemNumber: number | null
}
/**
* State of a game break being observed
*/
export interface ObservedGameBreakState {
/** Arcade room ID */
roomId: string
/** Display name of the game */
gameName: string
/** Game registry ID */
gameId: string
/** Current phase of the game break */
phase: 'selecting' | 'playing' | 'completed'
/** End reason and summary, if break has ended */
endReason?: 'gameFinished' | 'timeout' | 'skipped'
endSummary?: { gameName: string; headline?: string }
}
interface UseSessionObserverResult {
/** Current observed state (null if not yet received) */
state: ObservedSessionState | null
/** Accumulated results from completed problems */
results: ObservedResult[]
/** Current part transition state (null if not in transition) */
transitionState: ObservedTransitionState | null
/**
* Authoritative flow state from the server-side state machine.
* This is the primary signal for what to render — use this over breakState.
* null until first session-flow-state event is received.
*/
flowState: SessionFlowState | null
/** Current game break state (null if no break in progress) */
breakState: ObservedGameBreakState | null
/** Latest vision frame from student's camera (null if vision not enabled) */
visionFrame: ObservedVisionFrame | null
/** Whether connected to the session channel */
isConnected: boolean
/** Whether actively observing (connected and joined session) */
isObserving: boolean
/** Error message if connection failed */
error: string | null
/** Stop observing the session */
stopObserving: () => void
/** Send a control action to the student's abacus */
sendControl: (action: SessionAbacusControlAction) => void
/** Pause the student's session with optional message */
sendPause: (message?: string) => void
/** Resume the student's session */
sendResume: () => void
/** DVR buffer info (null if DVR not available) */
dvrBufferInfo: DvrBufferInfo | null
/** Whether currently viewing live feed (vs scrubbing) */
isLive: boolean
/** Request a scrub frame at specific offset */
scrubTo: (offsetMs: number) => void
/** Return to live feed */
goLive: () => void
/** Signal readiness to join game breaks as a participant */
sendCoPlayReady: (player: { name: string; emoji: string; color: string }) => void
/** Signal no longer available for co-play */
sendCoPlayLeave: () => void
}
/**
* Hook to observe a student's practice session in real-time
*
* Connects to the session's socket channel and receives practice state updates.
* Use this in a teacher's or parent's observation modal to see what the student is doing.
*
* @param sessionId - The session plan ID to observe
* @param observerId - Unique identifier for this observer (e.g., teacher's/parent's user ID)
* @param playerId - The player ID being observed (for authorization check)
* @param enabled - Whether to start observing (default: true)
* @param shareToken - Optional share token for public/guest observation (bypasses user auth)
*/
export function useSessionObserver(
sessionId: string | undefined,
observerId: string | undefined,
playerId: string | undefined,
enabled = true,
shareToken?: string
): UseSessionObserverResult {
const [state, setState] = useState<ObservedSessionState | null>(null)
const [results, setResults] = useState<ObservedResult[]>([])
const [transitionState, setTransitionState] = useState<ObservedTransitionState | null>(null)
const [visionFrame, setVisionFrame] = useState<ObservedVisionFrame | null>(null)
const [observedFlowState, setObservedFlowState] = useState<SessionFlowState | null>(null)
const [breakState, setBreakState] = useState<ObservedGameBreakState | null>(null)
const [isConnected, setIsConnected] = useState(false)
const [isObserving, setIsObserving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [dvrBufferInfo, setDvrBufferInfo] = useState<DvrBufferInfo | null>(null)
const [isLive, setIsLive] = useState(true)
const socketRef = useRef<Socket | null>(null)
// Track which problem numbers we've already recorded to avoid duplicates
const recordedProblemsRef = useRef<Set<number>>(new Set())
// Track if we've seeded historical results from slotResults
const hasSeededHistoryRef = useRef(false)
const stopObserving = useCallback(() => {
if (socketRef.current && sessionId) {
socketRef.current.emit('stop-observing', { sessionId })
socketRef.current.disconnect()
socketRef.current = null
setIsConnected(false)
setIsObserving(false)
setState(null)
setResults([])
setTransitionState(null)
setObservedFlowState(null)
setBreakState(null)
setVisionFrame(null)
setDvrBufferInfo(null)
setIsLive(true)
recordedProblemsRef.current.clear()
hasSeededHistoryRef.current = false
}
}, [sessionId])
useEffect(() => {
// Need sessionId and either (observerId + playerId) or shareToken
const hasAuthCredentials = observerId && playerId
const hasShareToken = !!shareToken
if (!sessionId || (!hasAuthCredentials && !hasShareToken) || !enabled) {
// Clean up if disabled
if (socketRef.current) {
stopObserving()
}
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('[SessionObserver] Connected, joining session:', sessionId)
setIsConnected(true)
setError(null)
// Join the session channel - use shareToken if available, otherwise authenticated flow
if (shareToken) {
socket.emit('observe-session', { sessionId, shareToken })
} else {
socket.emit('observe-session', { sessionId, observerId, playerId })
}
setIsObserving(true)
}
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('[SessionObserver] Socket already connected, triggering connect logic')
handleConnect()
}
socket.on('disconnect', () => {
console.log('[SessionObserver] Disconnected')
setIsConnected(false)
setIsObserving(false)
})
socket.on('connect_error', (err) => {
console.error('[SessionObserver] Connection error:', err)
setError('Failed to connect to session')
})
// Handle authorization errors from server
socket.on('observe-error', (data: { error: string }) => {
console.error('[SessionObserver] Observation error:', data.error)
setError(data.error)
setIsObserving(false)
})
// Listen for practice state updates from the student
socket.on('practice-state', (data: PracticeStateEvent) => {
console.log('[SessionObserver] Received practice-state:', {
phase: data.phase,
answer: data.studentAnswer,
isCorrect: data.isCorrect,
problemNumber: data.currentProblemNumber,
})
const currentProblem = data.currentProblem as {
terms: number[]
answer: number
}
const sessionParts = data.sessionParts as SessionPart[] | undefined
const slotResults = data.slotResults as SlotResult[] | undefined
// Seed historical results from slotResults on first event
if (!hasSeededHistoryRef.current && slotResults && slotResults.length > 0 && sessionParts) {
hasSeededHistoryRef.current = true
console.log(
'[SessionObserver] Seeding historical results from slotResults:',
slotResults.length
)
// Convert slotResults to ObservedResult format
const historicalResults: ObservedResult[] = []
for (const result of slotResults) {
// Calculate problem number from part structure
let problemNumber = 0
for (let p = 0; p < result.partNumber - 1; p++) {
problemNumber += sessionParts[p]?.slots.length ?? 0
}
problemNumber += result.slotIndex + 1
// Get purpose from the slot definition
const slot = sessionParts[result.partNumber - 1]?.slots[result.slotIndex]
const purpose = slot?.purpose ?? 'focus'
// Mark as recorded to avoid duplicates
recordedProblemsRef.current.add(problemNumber)
historicalResults.push({
problemNumber,
terms: result.problem.terms,
answer: result.problem.answer,
studentAnswer: String(result.studentAnswer),
isCorrect: result.isCorrect,
purpose,
responseTimeMs: result.responseTimeMs,
recordedAt: result.timestamp instanceof Date ? result.timestamp.getTime() : Date.now(),
})
}
// Sort by problem number and set results
historicalResults.sort((a, b) => a.problemNumber - b.problemNumber)
setResults(historicalResults)
console.log('[SessionObserver] Seeded', historicalResults.length, 'historical results')
}
// Record result when problem is completed (feedback phase with definite answer)
if (
data.phase === 'feedback' &&
data.isCorrect !== null &&
!recordedProblemsRef.current.has(data.currentProblemNumber)
) {
recordedProblemsRef.current.add(data.currentProblemNumber)
const newResult: ObservedResult = {
problemNumber: data.currentProblemNumber,
terms: currentProblem.terms,
answer: currentProblem.answer,
studentAnswer: data.studentAnswer,
isCorrect: data.isCorrect,
purpose: data.purpose,
responseTimeMs: data.timing.elapsed,
recordedAt: Date.now(),
}
setResults((prev) => [...prev, newResult])
console.log('[SessionObserver] Recorded result:', newResult)
}
setState({
currentProblem,
phase: data.phase,
studentAnswer: data.studentAnswer,
isCorrect: data.isCorrect,
timing: data.timing,
purpose: data.purpose,
complexity: data.complexity,
receivedAt: Date.now(),
currentProblemNumber: data.currentProblemNumber,
totalProblems: data.totalProblems,
// Session structure for progress indicator
sessionParts,
currentPartIndex: data.currentPartIndex,
currentSlotIndex: data.currentSlotIndex,
slotResults,
})
})
// Listen for part transition events
socket.on('part-transition', (data: PartTransitionEvent) => {
console.log('[SessionObserver] Received part-transition:', {
previousPartType: data.previousPartType,
nextPartType: data.nextPartType,
countdownDurationMs: data.countdownDurationMs,
})
setTransitionState({
previousPartType: data.previousPartType,
nextPartType: data.nextPartType,
countdownStartTime: data.countdownStartTime,
countdownDurationMs: data.countdownDurationMs,
})
})
// Listen for part transition complete events
socket.on('part-transition-complete', (_data: PartTransitionCompleteEvent) => {
console.log('[SessionObserver] Part transition complete')
setTransitionState(null)
})
// Listen for vision frames from student's camera (only update if in live mode)
socket.on('vision-frame', (data: VisionFrameEvent) => {
// When in live mode, update the vision frame
// When scrubbing, we'll get frames from vision-scrub-frame events
setIsLive((currentIsLive) => {
if (currentIsLive) {
setVisionFrame({
imageData: data.imageData,
detectedValue: data.detectedValue,
confidence: data.confidence,
receivedAt: Date.now(),
})
}
return currentIsLive
})
})
// Listen for scrub frame responses (DVR playback)
socket.on('vision-scrub-frame', (data: { imageData: string; timestamp: number }) => {
console.log('[SessionObserver] Received scrub frame')
setVisionFrame({
imageData: data.imageData,
detectedValue: null,
confidence: 0,
receivedAt: Date.now(),
})
})
// Listen for DVR buffer info updates
socket.on(
'vision-buffer-info',
(data: {
sessionId: string
availableFromMs: number
availableToMs: number
currentProblemStartMs: number | null
currentProblemNumber: number | null
}) => {
// Only process buffer info for our session
if (data.sessionId !== sessionId) return
console.log('[SessionObserver] Received DVR buffer info:', data)
// Check if problem changed - auto-reset to live when new problem starts
setDvrBufferInfo((prevInfo) => {
const problemChanged =
prevInfo !== null &&
data.currentProblemNumber !== null &&
prevInfo.currentProblemNumber !== data.currentProblemNumber
if (problemChanged) {
console.log(
`[SessionObserver] Problem changed: ${prevInfo?.currentProblemNumber} → ${data.currentProblemNumber}, resetting to live`
)
setIsLive(true)
}
return {
availableFromMs: data.availableFromMs,
availableToMs: data.availableToMs,
currentProblemStartMs: data.currentProblemStartMs,
currentProblemNumber: data.currentProblemNumber,
}
})
}
)
// Listen for authoritative flow state updates
// This is the primary signal for what the observer should render
socket.on('session-flow-state', (data: SessionFlowStateEvent) => {
if (data.sessionId !== sessionId) return
console.log('[SessionObserver] Received session-flow-state:', {
flowState: data.flowState,
hasBreakContext: !!data.breakContext,
})
setObservedFlowState(data.flowState)
// Sync breakState from the authoritative flow state
if (
data.breakContext &&
(data.flowState === 'break_pending' || data.flowState === 'break_active')
) {
setBreakState({
roomId: data.breakContext.roomId,
gameName: data.breakContext.gameName,
gameId: data.breakContext.gameId,
phase: data.breakContext.phase,
})
} else if (
data.flowState === 'practicing' ||
data.flowState === 'break_results' ||
data.flowState === 'completed'
) {
// Break is over or we're in results — clear break state
setBreakState(null)
}
})
// Listen for session ended event
socket.on('session-ended', () => {
console.log('[SessionObserver] Session ended')
stopObserving()
})
return () => {
console.log('[SessionObserver] Cleaning up')
socket.emit('stop-observing', { sessionId })
socket.disconnect()
socketRef.current = null
}
}, [sessionId, observerId, playerId, enabled, stopObserving, shareToken])
// Send control action to student's abacus
const sendControl = useCallback(
(action: SessionAbacusControlAction) => {
if (!socketRef.current || !isConnected || !sessionId) {
console.warn('[SessionObserver] Cannot send control - not connected or no sessionId')
return
}
// Map our action types to the AbacusControlEvent format
let eventAction: 'show' | 'hide' | 'set-value'
let value: number | undefined
switch (action.type) {
case 'show-abacus':
eventAction = 'show'
break
case 'hide-abacus':
eventAction = 'hide'
break
case 'set-abacus-value':
eventAction = 'set-value'
value = action.value
break
}
const event: AbacusControlEvent = {
sessionId,
target: 'hero', // The main practice abacus
action: eventAction,
value,
}
socketRef.current.emit('abacus-control', event)
console.log('[SessionObserver] Sent abacus-control:', action)
},
[isConnected, sessionId]
)
// Send pause command to student's session
const sendPause = useCallback(
(message?: string) => {
if (!socketRef.current || !isConnected || !sessionId) {
console.warn('[SessionObserver] Cannot send pause - not connected or no sessionId')
return
}
const event: SessionPausedEvent = {
sessionId,
reason: 'teacher',
message,
}
socketRef.current.emit('session-pause', event)
console.log('[SessionObserver] Sent session-pause:', { message })
},
[isConnected, sessionId]
)
// Send resume command to student's session
const sendResume = useCallback(() => {
if (!socketRef.current || !isConnected || !sessionId) {
console.warn('[SessionObserver] Cannot send resume - not connected or no sessionId')
return
}
const event: SessionResumedEvent = {
sessionId,
}
socketRef.current.emit('session-resume', event)
console.log('[SessionObserver] Sent session-resume')
}, [isConnected, sessionId])
// Scrub to a specific offset in the DVR buffer
const scrubTo = useCallback(
(offsetMs: number) => {
if (!socketRef.current || !isConnected || !sessionId) {
console.warn('[SessionObserver] Cannot scrub - not connected or no sessionId')
return
}
setIsLive(false)
socketRef.current.emit('vision-scrub', { sessionId, offsetMs })
console.log('[SessionObserver] Requested scrub to:', offsetMs)
},
[isConnected, sessionId]
)
// Return to live feed
const goLive = useCallback(() => {
console.log('[SessionObserver] Going back to live feed')
setIsLive(true)
}, [])
const sendCoPlayReady = useCallback(
(player: { name: string; emoji: string; color: string }) => {
if (!socketRef.current || !sessionId || !observerId) return
socketRef.current.emit('observer-coplay-ready', { sessionId, observerId, player })
},
[sessionId, observerId]
)
const sendCoPlayLeave = useCallback(() => {
if (!socketRef.current || !sessionId || !observerId) return
socketRef.current.emit('observer-coplay-leave', { sessionId, observerId })
}, [sessionId, observerId])
return {
state,
results,
transitionState,
flowState: observedFlowState,
breakState,
visionFrame,
isConnected,
isObserving,
error,
stopObserving,
sendControl,
sendPause,
sendResume,
dvrBufferInfo,
isLive,
scrubTo,
goLive,
sendCoPlayReady,
sendCoPlayLeave,
}
}
|