All files / web/src/components/toys/euclid EuclidContextDebugPanel.tsx

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

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

/**
 * Debug panel showing all context shared with voice and text chat.
 *
 * Only renders when Visual Debug is enabled (useVisualDebugSafe).
 * Positioned top-left, clear of chat (bottom-right) and ToyDebugPanel (bottom-right).
 */

import { useState, useEffect } from 'react'
import { useVisualDebugSafe } from '@/contexts/VisualDebugContext'
import type {
  ConstructionState,
  ActiveTool,
  CompassPhase,
  StraightedgePhase,
  ExtendPhase,
  MacroPhase,
  PropositionStep,
} from './types'
import type { ProofFact } from './engine/facts'
import type { CallState } from '@/lib/voice/types'
import type { ConstructionNotifier, NotifierLogEntry } from './agent/useConstructionNotifier'
import {
  serializeConstructionGraph,
  serializeProofFacts,
  serializeToolState,
  type ToolStateInfo,
} from './agent/serializeProofState'

interface EuclidContextDebugPanelProps {
  constructionRef: React.RefObject<ConstructionState>
  proofFactsRef: React.RefObject<ProofFact[]>
  currentStepRef: React.RefObject<number>
  steps: PropositionStep[]
  isComplete: 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>
  pendingActionRef: React.RefObject<string | null>
  voiceState: CallState
  isSpeaking: boolean
  notifierRef: React.RefObject<ConstructionNotifier>
  chatMessageCount: number
  /** Compaction state from useConversationCompaction */
  compaction: {
    headSummary: string | null
    coversUpTo: number
    isSummarizingRef: React.RefObject<boolean>
  }
}

const SECTION_STYLE: React.CSSProperties = {
  borderTop: '1px solid rgba(255,255,255,0.1)',
  paddingTop: 6,
  marginTop: 4,
}

const LABEL_STYLE: React.CSSProperties = {
  fontWeight: 600,
  fontSize: 10,
  textTransform: 'uppercase' as const,
  letterSpacing: '0.04em',
  opacity: 0.5,
  marginBottom: 2,
  cursor: 'pointer',
  userSelect: 'none' as const,
}

const VALUE_STYLE: React.CSSProperties = {
  fontSize: 10,
  lineHeight: 1.4,
  whiteSpace: 'pre-wrap' as const,
  wordBreak: 'break-word' as const,
  maxHeight: 120,
  overflow: 'auto',
  fontFamily: 'monospace',
  opacity: 0.85,
}

function CollapsibleSection({
  title,
  children,
  defaultOpen = false,
}: {
  title: string
  children: React.ReactNode
  defaultOpen?: boolean
}) {
  const [open, setOpen] = useState(defaultOpen)
  return (
    <div style={SECTION_STYLE}>
      <div
        style={LABEL_STYLE}
        onClick={() => setOpen((p) => !p)}
        data-element="debug-section-header"
      >
        {open ? '\u25BE' : '\u25B8'} {title}
      </div>
      {open && <div style={VALUE_STYLE}>{children}</div>}
    </div>
  )
}

export function EuclidContextDebugPanel(props: EuclidContextDebugPanelProps) {
  const { isVisualDebugEnabled } = useVisualDebugSafe()
  const [, setTick] = useState(0)

  // Re-render every 500ms to pick up ref changes
  useEffect(() => {
    if (!isVisualDebugEnabled) return
    const id = setInterval(() => setTick((t) => t + 1), 500)
    return () => clearInterval(id)
  }, [isVisualDebugEnabled])

  if (!isVisualDebugEnabled) return null

  const {
    constructionRef,
    proofFactsRef,
    currentStepRef,
    steps,
    isComplete,
    activeToolRef,
    compassPhaseRef,
    straightedgePhaseRef,
    extendPhaseRef,
    macroPhaseRef,
    dragPointIdRef,
    pendingActionRef,
    voiceState,
    isSpeaking,
    notifierRef,
    chatMessageCount,
    compaction,
  } = props

  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: 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,
  }

  const constructionText = serializeConstructionGraph(state)
  const toolText = serializeToolState(toolInfo, state, step, steps, isComplete)
  const factsText = serializeProofFacts(facts)
  const recentEvents = notifierRef.current?.recentEvents ?? []
  const pendingAction = pendingActionRef.current

  return (
    <div
      data-component="euclid-context-debug-panel"
      style={{
        position: 'fixed',
        top: 'calc(var(--app-nav-height, 56px) + 16px)',
        left: 16,
        zIndex: 9999,
        background: 'rgba(17,24,39,0.88)',
        backdropFilter: 'blur(8px)',
        borderRadius: 8,
        padding: '10px 14px',
        color: 'rgba(243,244,246,1)',
        fontSize: 11,
        minWidth: 220,
        maxWidth: 320,
        maxHeight: 'calc(100vh - var(--app-nav-height, 56px) - 32px)',
        overflow: 'auto',
        display: 'flex',
        flexDirection: 'column',
        gap: 4,
        boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
        pointerEvents: 'auto',
      }}
    >
      <div
        style={{
          fontWeight: 700,
          fontSize: 10,
          textTransform: 'uppercase',
          letterSpacing: '0.05em',
          opacity: 0.5,
        }}
      >
        Context Debug
      </div>

      {/* Voice Session */}
      <CollapsibleSection title="Voice Session" defaultOpen>
        <div>
          State: <strong>{voiceState}</strong>
        </div>
        <div>Speaking: {isSpeaking ? 'yes' : 'no'}</div>
      </CollapsibleSection>

      {/* Last Action */}
      <CollapsibleSection title="Last Action" defaultOpen>
        {pendingAction ?? <span style={{ opacity: 0.4 }}>(none)</span>}
      </CollapsibleSection>

      {/* Construction State */}
      <CollapsibleSection title="Construction State">{constructionText}</CollapsibleSection>

      {/* Tool State */}
      <CollapsibleSection title="Tool State" defaultOpen>
        {toolText}
      </CollapsibleSection>

      {/* Proven Facts */}
      <CollapsibleSection title="Proven Facts">{factsText}</CollapsibleSection>

      {/* Text Chat Context */}
      <CollapsibleSection title="Text Chat">
        <div>Messages: {chatMessageCount}</div>
        <div>Pending action: {pendingAction ?? '(none)'}</div>
      </CollapsibleSection>

      {/* Conversation Compaction */}
      <CollapsibleSection title="Compaction" defaultOpen>
        {(() => {
          const isSummarizing = compaction.isSummarizingRef.current
          const hasSummary = !!compaction.headSummary
          const status = isSummarizing ? 'summarizing...' : hasSummary ? 'ready' : 'idle'
          const tailSize = hasSummary ? chatMessageCount - compaction.coversUpTo : chatMessageCount
          const statusColor = isSummarizing ? '#fcd34d' : hasSummary ? '#86efac' : 'inherit'
          return (
            <>
              <div>
                Status: <span style={{ color: statusColor }}>{status}</span>
              </div>
              <div>
                Coverage: {compaction.coversUpTo} / {chatMessageCount} msgs summarized
              </div>
              <div>Tail: {tailSize} msgs verbatim</div>
              {hasSummary && (
                <div style={{ marginTop: 4, opacity: 0.7, fontSize: 9 }}>
                  {compaction.headSummary!.slice(0, 200)}
                  {compaction.headSummary!.length > 200 ? '...' : ''}
                </div>
              )}
            </>
          )
        })()}
      </CollapsibleSection>

      {/* Push Log */}
      <CollapsibleSection title={`Push Log (${recentEvents.length})`}>
        {recentEvents.length === 0 ? (
          <span style={{ opacity: 0.4 }}>(no events yet)</span>
        ) : (
          recentEvents
            .slice()
            .reverse()
            .map((evt: NotifierLogEntry, i: number) => (
              <div
                key={i}
                style={{
                  borderBottom: '1px solid rgba(255,255,255,0.05)',
                  paddingBottom: 2,
                  marginBottom: 2,
                }}
              >
                <span style={{ opacity: 0.5 }}>{new Date(evt.timestamp).toLocaleTimeString()}</span>{' '}
                <span
                  style={{
                    color:
                      evt.type === 'construction'
                        ? '#86efac'
                        : evt.type === 'tool'
                          ? '#93c5fd'
                          : '#fcd34d',
                  }}
                >
                  [{evt.type}]
                </span>{' '}
                {evt.action}
                {evt.delivered ? (
                  ''
                ) : (
                  <span style={{ color: '#f87171', marginLeft: 4 }}>(not delivered)</span>
                )}
              </div>
            ))
        )}
      </CollapsibleSection>
    </div>
  )
}