All files / web/src/components/agents/skills skill-performance-chart.tsx

74.01% Statements 282/381
78.78% Branches 52/66
28.57% Functions 2/7
74.01% Lines 282/381

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      1x 1x                     1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 11x 11x 11x 11x 11x 11x 11x 11x 11x     11x 11x 11x     11x 11x   11x   11x 11x 11x     11x   11x 11x 11x   11x   287x 287x   62x 287x     225x   225x 225x         287x 287x 287x     11x 11x 24x 24x 24x 24x 24x 24x     11x     11x 11x 24x 24x 72x 72x 24x 24x     11x 11x 24x 24x     11x 24x 24x 24x 24x 24x 72x 72x 72x 72x 72x 24x 24x     11x 24x 24x 24x 24x 24x     11x 11x 24x 600x 600x 24x   24x 24x   24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 11x     11x 11x       11x   11x 8x 200x 200x 8x   8x   8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x     11x     11x 287x 287x     287x     287x   287x 11x     11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x     11x 11x                                                                                               11x     11x 11x     11x                     11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 9x             2x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x                                                                                                   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x     11x 11x 11x 11x 11x 11x   11x 11x   11x 11x 11x 11x   11x  
'use client';
 
import type { SkillEvent } from '@shared/types/data/skill-event';
import { eventColors, eventLabels } from '@web/constants';
import {
  CategoryScale,
  Chart as ChartJS,
  type ChartOptions,
  Legend,
  LinearScale,
  LineElement,
  PointElement,
  Title,
  Tooltip,
} from 'chart.js';
import annotationPlugin from 'chartjs-plugin-annotation';
import { format } from 'date-fns';
import { useMemo, useState } from 'react';
import { Line } from 'react-chartjs-2';
 
// Register Chart.js components
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  annotationPlugin,
);
 
interface SkillPerformanceChartProps {
  evaluationScores: Array<{
    time_bucket: string;
    avg_score: number | null;
    scores_by_evaluation: Record<string, number> | null;
    count: number;
  }>;
  events?: SkillEvent[];
  clusters?: Array<{ id: string; name: string }>; // For cluster name lookup
  size?: 'small' | 'large';
  intervalMinutes?: number; // Bucket size in minutes
  windowHours?: number; // Total time window in hours
  endTime?: Date; // End time for the chart (rightmost bucket)
}
 
const METHOD_COLORS: Record<string, string> = {
  task_completion: 'rgb(59, 130, 246)', // blue
  argument_correctness: 'rgb(168, 85, 247)', // purple
  role_adherence: 'rgb(34, 197, 94)', // green
  turn_relevancy: 'rgb(251, 146, 60)', // orange
  tool_correctness: 'rgb(236, 72, 153)', // pink
  knowledge_retention: 'rgb(14, 165, 233)', // sky
  conversation_completeness: 'rgb(168, 85, 247)', // purple
  hallucination: 'rgb(220, 38, 38)', // red
  custom: 'rgb(148, 163, 184)', // gray
  latency: 'rgb(6, 182, 212)', // cyan
};
 
export function SkillPerformanceChart({
  evaluationScores,
  events = [],
  clusters = [],
  size = 'large',
  intervalMinutes = 60,
  windowHours = 24,
  endTime = new Date(),
}: SkillPerformanceChartProps) {
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
 
  // Create cluster name lookup map
  const clusterNameMap = useMemo(() => {
    const map = new Map<string, string>();
    for (const cluster of clusters) {
      map.set(cluster.id, cluster.name);
    }
    return map;
  }, [clusters]);
 
  const chartData = useMemo(() => {
    // Generate all time buckets for the window
    const now = endTime;
    const startTime = new Date(now.getTime() - windowHours * 60 * 60 * 1000);
    const buckets: Array<{ time: Date; label: string }> = [];
 
    // Generate bucket times
    let bucketTime = new Date(startTime);
    // Round to bucket boundary
    const startMinutes =
      Math.floor(bucketTime.getMinutes() / intervalMinutes) * intervalMinutes;
    bucketTime.setMinutes(startMinutes, 0, 0);
 
    while (bucketTime <= now) {
      // Format label based on interval size and chart size
      let label: string;
      if (size === 'small') {
        // For small charts, show only time
        label = format(bucketTime, 'h:mm a');
      } else if (intervalMinutes >= 1440) {
        // 1 day or more: show only date
        label = format(bucketTime, 'MMM d');
      } else if (intervalMinutes >= 60) {
        // 1 hour to 24 hours: show date and hour
        label = format(bucketTime, 'MMM d, ha');
      } else {
        // Less than 1 hour: show date and time
        label = format(bucketTime, 'MMM d, h:mm a');
      }
 
      buckets.push({ time: new Date(bucketTime), label });
      bucketTime = new Date(bucketTime.getTime() + intervalMinutes * 60 * 1000);
    }
 
    // Create a map of time bucket to score
    const scoreMap = new Map<string, number | null>();
    for (const score of evaluationScores) {
      const bucketTime = new Date(score.time_bucket).getTime();
      scoreMap.set(
        bucketTime.toString(),
        score.avg_score !== null ? score.avg_score * 100 : null,
      );
    }
 
    // Fill in data for all buckets
    const labels = buckets.map((b) => b.label);
 
    // Collect all evaluation methods across all buckets
    const allMethods = new Set<string>();
    for (const score of evaluationScores) {
      if (score.scores_by_evaluation) {
        for (const method of Object.keys(score.scores_by_evaluation)) {
          allMethods.add(method);
        }
      }
    }
 
    // Create a map for each evaluation method
    const methodDataMaps = new Map<string, Map<string, number>>();
    for (const method of allMethods) {
      methodDataMaps.set(method, new Map());
    }
 
    // Fill method maps with scores
    for (const score of evaluationScores) {
      const bucketTime = new Date(score.time_bucket).getTime();
      if (score.scores_by_evaluation) {
        for (const [method, methodScore] of Object.entries(
          score.scores_by_evaluation,
        )) {
          const methodMap = methodDataMaps.get(method);
          if (methodMap) {
            methodMap.set(bucketTime.toString(), methodScore * 100);
          }
        }
      }
    }
 
    // Format method names
    const formatMethodName = (method: string) => {
      return method
        .split('_')
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join(' ');
    };
 
    // Create datasets for each evaluation method
    const methodDatasets = Array.from(methodDataMaps.entries()).map(
      ([method, methodMap]) => {
        const data = buckets.map((b) => {
          const score = methodMap.get(b.time.getTime().toString());
          return score !== undefined ? score : null;
        });
 
        const hasOnlyOnePoint = data.filter((d) => d !== null).length === 1;
        const color = METHOD_COLORS[method] || 'rgb(148, 163, 184)';
 
        return {
          label: formatMethodName(method),
          data,
          borderColor: color,
          backgroundColor: color,
          borderWidth: 2,
          pointRadius: hasOnlyOnePoint ? 2 : 0,
          pointHoverRadius: 8,
          pointHoverBorderWidth: 2,
          pointHoverBackgroundColor: color,
          pointHoverBorderColor: 'white',
          tension: 0.3,
          spanGaps: true,
        };
      },
    );
 
    // Create weighted average dataset (only if more than 1 evaluation method)
    const shouldShowWeightedAverage = allMethods.size > 1;
    const datasets: Array<{
      label: string;
      data: (number | null)[];
      [key: string]: unknown;
    }> = [];
 
    if (shouldShowWeightedAverage) {
      const avgData = buckets.map((b) => {
        const score = scoreMap.get(b.time.getTime().toString());
        return score !== undefined ? score : null;
      });
 
      const hasOnlyOneAvgPoint = avgData.filter((d) => d !== null).length === 1;
 
      datasets.push({
        label: 'Weighted Average',
        data: avgData,
        borderColor: 'rgb(115, 115, 115)', // gray for overall average
        backgroundColor: 'rgb(115, 115, 115)',
        borderWidth: 3, // Thicker line to stand out
        pointRadius: hasOnlyOneAvgPoint ? 3 : 0,
        pointHoverRadius: 8,
        pointHoverBorderWidth: 2,
        pointHoverBackgroundColor: 'rgb(115, 115, 115)',
        pointHoverBorderColor: 'white',
        tension: 0.3,
        spanGaps: true,
      });
    }
 
    // Add method datasets
    datasets.push(...methodDatasets);
 
    // Create event markers dataset for all buckets (invisible, for tooltips only)
    const eventData = buckets.map((bucket) => {
      const bucketTime = bucket.time.getTime();
      const nextBucketTime = bucketTime + intervalMinutes * 60 * 1000;
 
      // Find event in this time bucket
      const event = events.find((e) => {
        const eventTime = new Date(e.created_at).getTime();
        return eventTime >= bucketTime && eventTime < nextBucketTime;
      });
 
      return event ? 50 : null; // Middle of chart (0-100 scale)
    });
 
    // Add events dataset
    datasets.push({
      label: 'Events',
      data: eventData,
      borderColor: 'rgba(0, 0, 0, 0)',
      backgroundColor: 'rgba(0, 0, 0, 0)',
      borderWidth: 0,
      pointRadius: 6, // Invisible point for hover area
      pointHoverRadius: 6,
      pointHoverBorderWidth: 0,
      tension: 0,
      spanGaps: false,
    });
 
    return {
      labels,
      datasets,
      buckets, // Include for event annotation calculation
    };
  }, [evaluationScores, events, intervalMinutes, windowHours, endTime, size]);
 
  // Create event annotations
  const eventAnnotations = useMemo(() => {
    if (events.length === 0 || !chartData.buckets) return {};
 
    const annotations: Record<string, unknown> = {};
 
    // Show all events (both skill-wide and cluster-specific)
    for (const event of events) {
      const eventTime = new Date(event.created_at).getTime();
 
      // Find which time bucket this event falls into
      const xIndex = chartData.buckets.findIndex((bucket) => {
        const bucketTime = bucket.time.getTime();
        const nextBucketTime = bucketTime + intervalMinutes * 60 * 1000;
        return eventTime >= bucketTime && eventTime < nextBucketTime;
      });
 
      if (xIndex !== -1) {
        const color =
          eventColors[event.event_type as keyof typeof eventColors] ||
          'rgba(148, 163, 184, 0.6)';
        const label =
          eventLabels[event.event_type as keyof typeof eventLabels] ||
          event.event_type;
 
        annotations[`event-${event.id}`] = {
          type: 'line',
          xMin: xIndex,
          xMax: xIndex,
          borderColor: color,
          borderWidth: 2,
          borderDash: [5, 5],
          label: {
            display: size === 'large',
            content: label,
            position: 'start',
            rotation: 270,
            backgroundColor: color, // Use event color for label background
            color: 'white',
            font: {
              size: 9,
              weight: 'bold',
            },
            padding: 4,
          },
        };
      }
    }
 
    return annotations;
  }, [events, chartData, intervalMinutes, size]);
 
  // Combine event annotations with hover line
  const allAnnotations = useMemo(() => {
    const combined = { ...eventAnnotations };
 
    // Add vertical hover line (only for large charts)
    if (hoveredIndex !== null && size === 'large') {
      combined.hoverLine = {
        type: 'line',
        xMin: hoveredIndex,
        xMax: hoveredIndex,
        borderColor: 'rgba(0, 0, 0, 0.3)',
        borderWidth: 2,
        borderDash: [5, 5],
      };
    }
 
    return combined;
  }, [eventAnnotations, hoveredIndex, size]);
 
  const options: ChartOptions<'line'> = {
    responsive: true,
    maintainAspectRatio: false,
    animation: {
      duration: 150, // Faster animation (default is 1000ms)
    },
    events: size === 'large' ? undefined : [], // Disable all events for small charts
    interaction: {
      mode: size === 'large' ? 'index' : undefined,
      intersect: false,
    },
    onHover:
      size === 'large'
        ? (_event, activeElements) => {
            if (activeElements.length > 0) {
              setHoveredIndex(activeElements[0].index);
            } else {
              setHoveredIndex(null);
            }
          }
        : undefined,
    plugins: {
      annotation: {
        // biome-ignore lint/suspicious/noExplicitAny: chartjs-plugin-annotation has complex types
        annotations: allAnnotations as any,
      },
      legend: {
        display: true,
        position: 'bottom',
        onClick: size === 'large' ? undefined : () => false, // Disable legend click for small charts
        labels: {
          boxWidth: size === 'large' ? 12 : 8,
          boxHeight: size === 'large' ? 12 : 8,
          padding: size === 'large' ? 12 : 8,
          font: {
            size: size === 'large' ? 11 : 9,
          },
          color: 'rgb(115, 115, 115)',
          filter: (item) => item.text !== 'Events', // Hide Events from legend
        },
      },
      tooltip: {
        enabled: size === 'large',
        mode: 'index',
        intersect: false,
        displayColors: true,
        callbacks: {
          label: (context) => {
            const label = context.dataset.label || '';
 
            // If this is the Events dataset, show event details
            if (label === 'Events') {
              const xIndex = context.dataIndex;
              const bucket = chartData.buckets?.[xIndex];
              if (!bucket) return 'Event';
 
              const bucketTime = bucket.time.getTime();
              const nextBucketTime = bucketTime + intervalMinutes * 60 * 1000;
 
              const eventsAtTime = events.filter((event) => {
                const eventTime = new Date(event.created_at).getTime();
                return eventTime >= bucketTime && eventTime < nextBucketTime;
              });
 
              if (eventsAtTime.length === 0) return 'Event';
 
              const lines: string[] = [];
              for (const event of eventsAtTime) {
                const eventLabel =
                  eventLabels[event.event_type as keyof typeof eventLabels] ||
                  event.event_type;
 
                const eventTime = new Date(event.created_at);
                const timeString = format(eventTime, 'MMM d, h:mm a');
                lines.push(timeString);
                lines.push(eventLabel);
 
                // Add cluster name if this is a cluster-specific event
                if (event.cluster_id) {
                  const clusterName = clusterNameMap.get(event.cluster_id);
                  if (clusterName) {
                    lines.push(`Partition: ${clusterName}`);
                  }
                }
 
                if (event.metadata.model_name) {
                  lines.push(String(event.metadata.model_name));
                }
              }
 
              return lines;
            }
 
            // For performance datasets, show the score
            const value = context.parsed.y;
            return `${label}: ${value!.toFixed(3)}`;
          },
        },
      },
      title: {
        display: size === 'large',
        text: 'Skill Performance Over Time',
        font: {
          size: size === 'large' ? 12 : 11,
        },
        color: 'rgb(115, 115, 115)',
        padding: {
          top: 10,
          bottom: 20,
        },
      },
    },
    scales: {
      x: {
        display: true,
        grid: {
          display: false,
        },
        ticks: {
          font: {
            size: size === 'large' ? 10 : 9,
          },
          color: 'rgb(115, 115, 115)',
          maxRotation: 45,
          minRotation: 45,
          autoSkip: true,
          maxTicksLimit: size === 'large' ? 10 : 5,
        },
      },
      y: {
        display: true,
        grid: {
          color: 'rgba(115, 115, 115, 0.1)',
        },
        ticks: {
          font: {
            size: size === 'large' ? 10 : 9,
          },
          color: 'rgb(115, 115, 115)',
          maxTicksLimit: size === 'large' ? 6 : 4,
          callback: (value) => {
            return Number(value).toFixed(2);
          },
        },
        min: 0,
        max: 100,
      },
    },
  };
 
  return (
    <div className="w-full space-y-2">
      {/* Chart */}
      <div className={`w-full ${size === 'large' ? 'h-64' : 'h-40'}`}>
        <Line data={chartData} options={options} />
      </div>
    </div>
  );
}