All files / web/src/components/toys/euclid/chat useEuclidChat.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
'use client'

/**
 * Euclid text chat hook — thin wrapper around useCharacterChat.
 *
 * Provides Euclid-specific context serialization (construction graph,
 * proof facts, tool state, step list) while delegating SSE streaming,
 * message state, and open/close to the generic hook.
 *
 * In author mode, includes axiom-framed tools and dispatches tool calls
 * to construction mutation + fact store callbacks.
 */

import { useCallback, useRef, useMemo } from 'react'
import { useGeometryTeacher } from '../GeometryTeacherContext'
import { useCharacterChat } from '@/lib/character/useCharacterChat'
import type { UseCharacterChatReturn } from '@/lib/character/useCharacterChat'
import type {
  ConstructionState,
  ConstructionPoint,
  ActiveTool,
  CompassPhase,
  StraightedgePhase,
  ExtendPhase,
  MacroPhase,
  PropositionStep,
} from '../types'
import type { ProofFact } from '../engine/facts'
import {
  serializeConstructionGraph,
  serializeProofFacts,
  serializeToolState,
  type ToolStateInfo,
} from '../agent/serializeProofState'
import { getAttitude } from '../agent/attitudes'
import type { AttitudeId } from '../agent/attitudes/types'

// Re-export ChatMessage from the generic types for backward compatibility
export type { ChatMessage } from '@/lib/character/types'

// Re-export AuthorToolCallbacks from shared location
import type { AuthorToolCallbacks } from '../authorToolCallbacks'
export type { AuthorToolCallbacks } from '../authorToolCallbacks'
import { dispatchAuthorTool } from '../agent/dispatchAuthorTool'

export interface UseEuclidChatOptions {
  canvasRef: React.RefObject<HTMLCanvasElement | null>
  constructionRef: React.RefObject<ConstructionState>
  proofFactsRef: React.RefObject<ProofFact[]>
  currentStepRef: React.RefObject<number>
  propositionId: number
  isComplete: boolean
  playgroundMode: boolean
  activeToolRef: React.RefObject<ActiveTool>
  compassPhaseRef: React.RefObject<CompassPhase>
  straightedgePhaseRef: React.RefObject<StraightedgePhase>
  extendPhaseRef: React.RefObject<ExtendPhase>
  macroPhaseRef: React.RefObject<MacroPhase>
  dragPointIdRef: React.RefObject<string | null>
  steps: PropositionStep[]
  /** Ref holding a pending action description (set by push notifier, consumed on send) */
  pendingActionRef?: React.RefObject<string | null>
  /** Whether the user is on a mobile device — triggers concise response mode */
  isMobile?: boolean
  /** Current attitude ID — when 'author', includes tools in chat */
  attitudeId?: AttitudeId
  /** Callbacks for author-mode tool dispatch */
  authorCallbacks?: AuthorToolCallbacks
}

export interface UseEuclidChatReturn extends UseCharacterChatReturn {
  /** Async-markup a message with entity markers. Pass the content to avoid stale closure issues. */
  markupMessage: (messageId: string, content: string, strict?: boolean) => void
}

export function useEuclidChat(options: UseEuclidChatOptions): UseEuclidChatReturn {
  const teacherConfig = useGeometryTeacher()

  const {
    canvasRef,
    constructionRef,
    proofFactsRef,
    currentStepRef,
    propositionId,
    isComplete,
    playgroundMode,
    activeToolRef,
    compassPhaseRef,
    straightedgePhaseRef,
    extendPhaseRef,
    macroPhaseRef,
    dragPointIdRef,
    steps,
    pendingActionRef,
    isMobile,
    attitudeId,
    authorCallbacks,
  } = options

  // Look up attitude tools
  const attitude = attitudeId ? getAttitude(attitudeId) : undefined
  const chatTools = attitude?.chatTools

  const readToolState = useCallback(
    (): ToolStateInfo => ({
      activeTool: activeToolRef.current ?? 'compass',
      compassPhase: compassPhaseRef.current ?? { tag: 'idle' },
      straightedgePhase: straightedgePhaseRef.current ?? { tag: 'idle' },
      extendPhase: extendPhaseRef.current ?? { tag: 'idle' },
      macroPhase: macroPhaseRef.current ?? { tag: 'idle' },
      dragPointId: dragPointIdRef.current ?? null,
    }),
    [
      activeToolRef,
      compassPhaseRef,
      straightedgePhaseRef,
      extendPhaseRef,
      macroPhaseRef,
      dragPointIdRef,
    ]
  )

  // Stable ref for authorCallbacks to avoid stale closures in onToolCall
  const authorCallbacksRef = useRef(authorCallbacks)
  authorCallbacksRef.current = authorCallbacks

  const buildRequestBody = useCallback(
    (
      messages: Array<{ role: string; content: string; toolCallId?: string }>,
      screenshot: string | undefined
    ): Record<string, unknown> => {
      const emptyState = { elements: [], nextLabelIndex: 0, nextColorIndex: 0 } as ConstructionState
      const state = constructionRef.current ?? emptyState
      const facts = proofFactsRef.current ?? []
      const step = currentStepRef.current ?? 0
      const toolInfo = readToolState()

      const constructionGraph = serializeConstructionGraph(state)
      const proofFactsText = serializeProofFacts(facts)
      const toolState = serializeToolState(toolInfo, state, step, steps, isComplete)

      // Build step list
      let stepList: string
      if (isComplete) {
        stepList = 'Construction is COMPLETE. Student is exploring freely.'
      } else {
        const stepLines = steps.map((s, i) => {
          const marker = i === step ? '\u2192' : i < step ? '\u2713' : ' '
          const citation = s.citation ? ` [${s.citation}]` : ''
          return `  ${marker} Step ${i + 1}: ${s.instruction}${citation}`
        })
        stepList = `Step ${step + 1} of ${steps.length}:\n${stepLines.join('\n')}`
      }

      // Read pending action (not cleared — the notifier overwrites it on next event)
      const recentAction = pendingActionRef?.current ?? null

      const body: Record<string, unknown> = {
        messages,
        propositionId,
        characterId: teacherConfig.definition.id,
        currentStep: step,
        isComplete,
        playgroundMode,
        constructionGraph,
        toolState,
        proofFacts: proofFactsText,
        stepList,
        screenshot,
        ...(recentAction ? { recentAction } : {}),
        ...(isMobile ? { isMobile: true } : {}),
      }

      // Include attitude and tools for author mode
      if (attitudeId) {
        body.attitudeId = attitudeId
      }
      if (chatTools) {
        body.tools = chatTools
      }

      console.log(
        '[euclid-chat] buildRequestBody: step=%d, isComplete=%s, recentAction=%s, messageCount=%d, attitude=%s',
        step,
        isComplete,
        recentAction,
        messages.length,
        attitudeId ?? 'default'
      )
      return body
    },
    [
      constructionRef,
      proofFactsRef,
      currentStepRef,
      propositionId,
      teacherConfig,
      isComplete,
      playgroundMode,
      steps,
      readToolState,
      pendingActionRef,
      isMobile,
      attitudeId,
      chatTools,
    ]
  )

  // Tool call handler for author mode
  const onToolCall = useMemo(() => {
    if (!chatTools) return undefined

    return async (name: string, args: Record<string, unknown>): Promise<unknown> => {
      const cb = authorCallbacksRef.current
      if (!cb) return { success: false, error: 'No author callbacks available' }
      return dispatchAuthorTool(name, args, cb)
    }
  }, [chatTools])

  const markupMessageImpl = useCallback(
    (
      messageId: string,
      content: string,
      strict?: boolean,
      updateFn?: (id: string, content: string) => void
    ) => {
      if (!content) return
      // Skip if already has markers
      if (/\{(seg|tri|ang|pt|def|post|cn|prop):/.test(content)) return

      // Gather point labels from the construction
      const state = constructionRef.current
      const pointLabels = state
        ? state.elements
            .filter((e): e is ConstructionPoint => e.kind === 'point' && !!e.label)
            .map((e) => e.label)
        : []

      fetch('/api/realtime/euclid/markup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          text: content,
          propositionId,
          pointLabels,
          ...(strict ? { strict: true } : {}),
        }),
      })
        .then((res) => res.json())
        .then((data) => {
          if (data.markedText && data.markedText !== content) {
            updateFn?.(messageId, data.markedText)
          }
        })
        .catch(() => {
          // Silently fail — original text remains
        })
    },
    [constructionRef, propositionId]
  )

  // Ref to access chat.updateMessageContent in the onUserMessageAdded callback without circular deps
  const chatRef = useRef<UseCharacterChatReturn | null>(null)

  // Callback for typed user messages — markup with strict validation
  const onUserMessageAdded = useCallback(
    (messageId: string, content: string) => {
      markupMessageImpl(messageId, content, true, chatRef.current?.updateMessageContent)
    },
    [markupMessageImpl]
  )

  const chat = useCharacterChat({
    chatEndpoint: teacherConfig.voice.chatEndpoint,
    buildRequestBody,
    canvasRef,
    onUserMessageAdded,
    tools: chatTools,
    onToolCall,
  })

  chatRef.current = chat

  const markupMessage = useCallback(
    (messageId: string, content: string, strict?: boolean) => {
      markupMessageImpl(messageId, content, strict, chat.updateMessageContent)
    },
    [markupMessageImpl, chat.updateMessageContent]
  )

  return { ...chat, markupMessage }
}