All files / web/src/components/agents/skills skill-dashboard-view.tsx

61.93% Statements 423/683
64.58% Branches 31/48
17.64% Functions 3/17
61.93% Lines 423/683

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 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849    1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x             1x 1x             1x 1x 1x           1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                           1x   1x 1x 1x 1x 1x           1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   1x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x       4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x     4x     4x 4x     4x 4x 4x 4x     4x     4x     4x     4x 4x 4x 4x 4x 4x     4x     4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x   4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                                           4x 4x 4x     4x 4x     4x 4x 3x 3x 4x 1x 1x 1x 4x     4x 4x 1x 1x 1x 3x 4x     4x 4x 1x 1x 1x 3x 4x     4x 4x 1x 1x 1x 3x 4x   4x                 4x                                                 4x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   4x 4x 4x 4x 4x 4x   4x   4x 4x 4x 4x           4x   4x   4x 4x 4x 4x 4x 4x 4x 4x 4x                   4x   4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x   4x   4x 4x 4x 4x   4x 4x                                                                                                 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x   4x 4x 18x 18x 18x 18x 18x   18x 18x   4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x                     4x 4x     4x 4x 4x 4x 4x   4x 4x 4x 4x   4x                                                   3x 3x 3x 3x 3x   3x 3x   3x 3x 3x                                                                                                                                   4x 4x 4x 4x 4x   4x 4x 4x 4x   4x 4x 4x       4x 4x 4x 4x 4x 4x 4x 4x 4x           3x 3x   3x                                                                         4x 4x     4x 4x 4x                   4x 4x 4x 4x 4x 4x 4x 4x 4x 3x   3x                                                           4x 4x 4x 4x     4x 3x 3x 3x 3x 3x       4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x   4x  
'use client';
 
import { shapes } from '@dicebear/collection';
import { createAvatar } from '@dicebear/core';
import { PrettyFunctionName } from '@shared/types/api/request/function-name';
import { useQuery } from '@tanstack/react-query';
import {
  getSkillEvaluationScoresByTimeBucket,
  resetSkill,
} from '@web/api/v1/super-agents/skills';
import { ManageSkillModelsDialog } from '@web/components/agents/skills/manage-skill-models-dialog';
import { SkillStatusIndicator } from '@web/components/agents/skills/skill-status-indicator';
import { SkillWarmingUpIndicator } from '@web/components/agents/skills/skill-warming-up-indicator';
import { Badge } from '@web/components/ui/badge';
import { Button } from '@web/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@web/components/ui/card';
import { DateTimePicker } from '@web/components/ui/date-time-picker';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@web/components/ui/dropdown-menu';
import { PageHeader } from '@web/components/ui/page-header';
import { Skeleton } from '@web/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableRow,
} from '@web/components/ui/table';
import { ToggleGroup, ToggleGroupItem } from '@web/components/ui/toggle-group';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@web/components/ui/tooltip';
import { eventLabels } from '@web/constants';
import { usePermissiveNavigate } from '@web/hooks/use-permissive-navigate';
import { useSkillValidation } from '@web/hooks/use-skill-validation';
import { useToast } from '@web/hooks/use-toast';
import { useAgents } from '@web/providers/agents';
import { useLogs } from '@web/providers/logs';
import { useModels } from '@web/providers/models';
import { useNavigation } from '@web/providers/navigation';
import { useSkillEvents } from '@web/providers/skill-events';
import { useSkillOptimizationClusters } from '@web/providers/skill-optimization-clusters';
import { useSkills } from '@web/providers/skills';
import {
  AlertCircle,
  CalendarIcon,
  CheckCircle2,
  Clock,
  CpuIcon,
  Edit,
  FileTextIcon,
  LayersIcon,
  MoreVertical,
  PlusIcon,
  RotateCcwIcon,
  Trash2,
} from 'lucide-react';
import { nanoid } from 'nanoid';
import type { ReactElement } from 'react';
import { useEffect, useState } from 'react';
import { ClusterPerformanceChart } from './clusters/cluster-performance-chart';
import { DeleteSkillDialog } from './delete-skill-dialog';
import { ResetSkillDialog } from './reset-skill-dialog';
import { SkillPerformanceChart } from './skill-performance-chart';
 
// ============================================================================
// Utility Functions
// ============================================================================
 
const createSkillAvatar = (skillName: string) => {
  const svg = createAvatar(shapes, {
    seed: skillName,
    size: 24,
    backgroundColor: [
      '00acc1',
      '039be5',
      '1e88e5',
      '43a047',
      '546e7a',
      '5e35b1',
      '6d4c41',
      '757575',
      '7cb342',
      '8e24aa',
      'c0ca33',
      'd81b60',
      'e53935',
      'f4511e',
      'fb8c00',
      'fdd835',
      'ffb300',
      '00897b',
      '3949ab',
    ],
  }).toString();
  return `data:image/svg+xml,${encodeURIComponent(svg)}`;
};
 
export function SkillDashboardView(): ReactElement {
  const { navigateToLogs, navigateToClusterArms } = useNavigation();
  const navigate = usePermissiveNavigate();
  const { toast } = useToast();
  const { navigateToEvaluations } = useNavigation();
 
  const { selectedAgent } = useAgents();
  const { selectedSkill, deleteSkill, refetch: refetchSkills } = useSkills();
  const [isManageModelsOpen, setIsManageModelsOpen] = useState(false);
  const [isDeleteSkillDialogOpen, setIsDeleteSkillDialogOpen] = useState(false);
  const [isResetSkillDialogOpen, setIsResetSkillDialogOpen] = useState(false);
  const [isResettingSkill, setIsResettingSkill] = useState(false);
 
  // Time interval controls for chart (30 buckets fixed)
  type TimeInterval = '1min' | '5min' | '15min' | '1hour' | '6hour' | '24hour';
  const BUCKETS = 30; // Fixed number of buckets
  const INTERVAL_CONFIG = {
    '1min': { label: '1 Min', minutes: 1, hours: (BUCKETS * 1) / 60 },
    '5min': { label: '5 Min', minutes: 5, hours: (BUCKETS * 5) / 60 },
    '15min': { label: '15 Min', minutes: 15, hours: (BUCKETS * 15) / 60 },
    '1hour': { label: '1 Hour', minutes: 60, hours: (BUCKETS * 60) / 60 },
    '6hour': { label: '6 Hours', minutes: 360, hours: (BUCKETS * 360) / 60 },
    '24hour': { label: '1 Day', minutes: 1440, hours: (BUCKETS * 1440) / 60 },
  } as const;
 
  const [selectedInterval, setSelectedInterval] = useState<TimeInterval>(() => {
    if (typeof window === 'undefined') return '1hour';
    try {
      const stored = localStorage.getItem('skill-performance-interval');
      if (stored && stored in INTERVAL_CONFIG) {
        return stored as TimeInterval;
      }
    } catch {
      // localStorage not available
    }
    return '1hour';
  });
 
  // Save interval preference
  useEffect(() => {
    try {
      localStorage.setItem('skill-performance-interval', selectedInterval);
    } catch {
      // localStorage not available
    }
  }, [selectedInterval]);
 
  // End time for charts (defaults to now)
  const [endTime, setEndTime] = useState<Date>(() => new Date());
 
  // Skill validation
  const { isReady, missingRequirements } = useSkillValidation(selectedSkill);
 
  // Logs via provider
  const {
    logs: recentLogs = [],
    isLoading: isLoadingLogs,
    setAgentId: setLogsAgentId,
    setSkillId: setLogsSkillId,
  } = useLogs();
 
  // Models via provider
  const { setSkillId } = useModels();
 
  // Cluster states via provider
  const {
    clusters: clusterStates,
    isLoading: isLoadingClusterStates,
    setSkillId: setClusterStatesSkillId,
  } = useSkillOptimizationClusters();
 
  // Fetch skill-level evaluation scores by time bucket (more efficient than full runs)
  const {
    data: skillEvaluationScores = [],
    isLoading: isLoadingSkillEvaluationScores,
  } = useQuery({
    queryKey: [
      'skillEvaluationScores',
      selectedSkill?.id,
      selectedInterval,
      endTime.toISOString(),
    ],
    queryFn: () =>
      selectedSkill
        ? getSkillEvaluationScoresByTimeBucket(selectedSkill.id, {
            interval_minutes: INTERVAL_CONFIG[selectedInterval].minutes,
            start_time: new Date(
              endTime.getTime() -
                INTERVAL_CONFIG[selectedInterval].hours * 60 * 60 * 1000,
            ).toISOString(),
            end_time: endTime.toISOString(),
          })
        : Promise.resolve([]),
    enabled: !!selectedSkill,
    refetchInterval: 60000, // Refetch every minute
  });
 
  // Fetch cluster-level evaluation scores for all clusters
  const {
    data: clusterEvaluationScores = {},
    isLoading: isLoadingClusterEvaluationScores,
  } = useQuery({
    queryKey: [
      'clusterEvaluationScores',
      selectedSkill?.id,
      clusterStates.map((c) => c.id).join(','),
      endTime.toISOString(),
    ],
    queryFn: async () => {
      if (!selectedSkill || clusterStates.length === 0) return {};
 
      // Fetch scores for all clusters in parallel (30 buckets at 5 min intervals = 2.5 hours)
      const scoresPromises = clusterStates.map(async (cluster) => {
        const scores = await getSkillEvaluationScoresByTimeBucket(
          selectedSkill.id,
          {
            cluster_id: cluster.id,
            interval_minutes: 5, // 5 min intervals
            start_time: new Date(
              endTime.getTime() - 2.5 * 60 * 60 * 1000,
            ).toISOString(), // Last 2.5 hours (30 buckets)
            end_time: endTime.toISOString(),
          },
        ).catch(() => []);
        return [cluster.id, scores] as const;
      });
 
      const scoresArray = await Promise.all(scoresPromises);
      return Object.fromEntries(scoresArray);
    },
    enabled: !!selectedSkill && clusterStates.length > 0,
    refetchInterval: 60000, // Refetch every minute
  });
 
  // Skill events via provider
  const { events: skillEvents = [], setSkillId: setSkillEventsSkillId } =
    useSkillEvents();
 
  // Update logs agentId and skillId
  useEffect(() => {
    if (selectedAgent && selectedSkill) {
      setLogsAgentId(selectedAgent.id);
      setLogsSkillId(selectedSkill.id);
    } else {
      setLogsAgentId(null);
      setLogsSkillId(null);
    }
  }, [selectedAgent, selectedSkill, setLogsAgentId, setLogsSkillId]);
 
  // Update models query params
  useEffect(() => {
    if (!selectedSkill) {
      setSkillId(null);
      return;
    }
    setSkillId(selectedSkill.id);
  }, [selectedSkill, setSkillId]);
 
  // Update cluster states skill ID
  useEffect(() => {
    if (!selectedSkill) {
      setClusterStatesSkillId(null);
      return;
    }
    setClusterStatesSkillId(selectedSkill.id);
  }, [selectedSkill, setClusterStatesSkillId]);
 
  // Update skill events skill ID
  useEffect(() => {
    if (!selectedSkill) {
      setSkillEventsSkillId(null);
      return;
    }
    setSkillEventsSkillId(selectedSkill.id);
  }, [selectedSkill, setSkillEventsSkillId]);
 
  const handleDeleteSkill = async () => {
    if (!selectedSkill || !selectedAgent) return;
    await deleteSkill(selectedSkill.id);
    navigate({
      to: '/agents/$agentName',
      params: { agentName: selectedAgent.name },
    });
  };
 
  const handleResetSkill = async (clearObservabilityCount: boolean) => {
    if (!selectedSkill) return;
 
    setIsResettingSkill(true);
    try {
      await resetSkill(selectedSkill.id, clearObservabilityCount);
      await refetchSkills();
      toast({
        title: 'Skill reset successfully',
        description: `${selectedSkill.name} has been reset and is regenerating.`,
      });
    } catch (error) {
      console.error('Failed to reset skill:', error);
      toast({
        title: 'Failed to reset skill',
        description:
          error instanceof Error ? error.message : 'Please try again.',
        variant: 'destructive',
      });
    } finally {
      setIsResettingSkill(false);
    }
  };
 
  // Early return if no skill or agent selected - AFTER all hooks
  if (!selectedSkill || !selectedAgent) {
    return (
      <>
        <PageHeader
          title="Skill Dashboard"
          description="No skill selected. Please select a skill to view its dashboard."
        />
        <div className="p-6">
          <div className="text-center text-muted-foreground">
            No skill selected. Please select a skill to view its dashboard.
          </div>
        </div>
      </>
    );
  }
 
  return (
    <>
      <PageHeader
        title={
          <div className="flex items-center gap-2">
            <img
              src={createSkillAvatar(selectedSkill.name)}
              alt={`${selectedSkill.name} icon`}
              width={20}
              height={20}
              className="h-5 w-5 rounded-sm"
            />
            <span>{selectedSkill.name}</span>
            <SkillStatusIndicator
              skill={selectedSkill}
              variant="badge"
              tooltipSide="bottom"
            />
            <SkillWarmingUpIndicator
              skill={selectedSkill}
              variant="badge"
              tooltipSide="bottom"
            />
          </div>
        }
        description={selectedSkill.description || 'No description available'}
        actions={
          <div className="flex gap-2">
            <Button
              variant="outline"
              onClick={() => setIsManageModelsOpen(true)}
            >
              <CpuIcon className="h-4 w-4 mr-2" />
              Manage Models
            </Button>
            <Button
              variant="outline"
              onClick={() =>
                selectedAgent &&
                selectedSkill &&
                navigateToEvaluations(selectedAgent.name, selectedSkill.name)
              }
            >
              <CheckCircle2 className="h-4 w-4 mr-2" />
              Manage Evaluations
            </Button>
 
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" title="More options">
                  <MoreVertical className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem
                  onClick={() =>
                    navigate({
                      to: '/agents/$agentName/skills/$skillName/edit',
                      params: {
                        agentName: selectedAgent.name,
                        skillName: selectedSkill.name,
                      },
                    })
                  }
                >
                  <Edit className="h-4 w-4 mr-2" />
                  Edit Skill
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setIsResetSkillDialogOpen(true)}
                  disabled={isResettingSkill}
                >
                  <RotateCcwIcon className="h-4 w-4 mr-2" />
                  {isResettingSkill ? 'Resetting...' : 'Reset Skill'}
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onClick={() => setIsDeleteSkillDialogOpen(true)}
                  className="text-destructive focus:text-destructive"
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  Delete Skill
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        }
      />
      {!isReady && (
        <div className="mx-6 mt-6">
          <Card className="bg-orange-100 dark:bg-orange-950 border-orange-200 dark:border-orange-800">
            <CardContent className="flex items-start gap-3 pt-4">
              <AlertCircle className="h-5 w-5 text-orange-800 dark:text-orange-200 shrink-0 mt-0.5" />
              <div className="flex-1">
                <h3 className="font-semibold text-orange-800 dark:text-orange-200 mb-1">
                  Skill Not Ready
                </h3>
                <p className="text-sm text-orange-800 dark:text-orange-200 mb-3">
                  This skill is missing required components:
                </p>
                <ul className="text-sm text-orange-800 dark:text-orange-200 list-disc pl-5 space-y-1 mb-3">
                  {missingRequirements.map((req) => (
                    <li key={req}>{req}</li>
                  ))}
                </ul>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setIsManageModelsOpen(true)}
                    className="bg-white dark:bg-orange-900 hover:bg-orange-50 dark:hover:bg-orange-800 border-orange-300 dark:border-orange-700"
                  >
                    <PlusIcon className="h-3 w-3 mr-1" />
                    Add Model
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() =>
                      selectedAgent &&
                      selectedSkill &&
                      navigateToEvaluations(
                        selectedAgent.name,
                        selectedSkill.name,
                      )
                    }
                    className="bg-white dark:bg-orange-900 hover:bg-orange-50 dark:hover:bg-orange-800 border-orange-300 dark:border-orange-700"
                  >
                    <CheckCircle2 className="h-3 w-3 mr-1" />
                    Add Evaluation
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
      <div className="p-6 space-y-6">
        {/* Performance Chart - Full Width */}
        <Card>
          <CardContent className="pt-6">
            <div className="flex justify-between items-start mb-4 gap-4">
              <div className="flex flex-col gap-2">
                <div className="flex items-center gap-2">
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-2">
                        <DateTimePicker
                          date={endTime}
                          onDateChange={setEndTime}
                        />
                      </div>
                    </TooltipTrigger>
                    <TooltipContent side="bottom">
                      <p>
                        Select the end time for the chart (rightmost data point)
                      </p>
                    </TooltipContent>
                  </Tooltip>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        variant="outline"
                        size="icon"
                        onClick={() => setEndTime(new Date())}
                      >
                        <Clock className="h-4 w-4" />
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent side="bottom">
                      <p>Jump to current time</p>
                    </TooltipContent>
                  </Tooltip>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground">
                    Total Requests:
                  </span>
                  <Badge variant="secondary">
                    {clusterStates
                      .reduce(
                        (sum, cluster) =>
                          sum + cluster.observability_total_requests,
                        0,
                      )
                      .toLocaleString()}
                  </Badge>
                </div>
              </div>
              <Tooltip>
                <TooltipTrigger asChild>
                  <ToggleGroup
                    type="single"
                    value={selectedInterval}
                    onValueChange={(value) => {
                      if (value) setSelectedInterval(value as TimeInterval);
                    }}
                    size="sm"
                    className="border rounded-lg gap-0 overflow-hidden"
                  >
                    {(Object.keys(INTERVAL_CONFIG) as TimeInterval[]).map(
                      (interval) => (
                        <ToggleGroupItem
                          key={interval}
                          value={interval}
                          aria-label={`Toggle ${INTERVAL_CONFIG[interval].label} interval`}
                          className="text-xs rounded-none"
                        >
                          {INTERVAL_CONFIG[interval].label}
                        </ToggleGroupItem>
                      ),
                    )}
                  </ToggleGroup>
                </TooltipTrigger>
                <TooltipContent side="bottom">
                  <p>Select time interval for chart buckets</p>
                </TooltipContent>
              </Tooltip>
            </div>
            {isLoadingSkillEvaluationScores ? (
              <div className="h-64 flex items-center justify-center">
                <Skeleton className="h-full w-full" />
              </div>
            ) : (
              <SkillPerformanceChart
                evaluationScores={skillEvaluationScores}
                events={skillEvents}
                clusters={clusterStates}
                intervalMinutes={INTERVAL_CONFIG[selectedInterval].minutes}
                windowHours={INTERVAL_CONFIG[selectedInterval].hours}
                endTime={endTime}
              />
            )}
          </CardContent>
        </Card>
 
        {/* Partitions - Horizontal Scroll */}
        <div>
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="text-lg font-semibold">Partitions</h3>
              <p className="text-sm text-muted-foreground">
                Optimization partitions for this skill
              </p>
            </div>
            <Badge variant="secondary">{clusterStates.length} total</Badge>
          </div>
 
          {isLoadingClusterStates ? (
            <div className="flex gap-4 overflow-x-auto pb-4">
              {Array.from({ length: 3 }).map(() => (
                <Card key={nanoid()} className="min-w-[300px]">
                  <CardHeader className="pb-2">
                    <Skeleton className="h-6 w-24 mb-2" />
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      <div className="flex items-center justify-between">
                        <Skeleton className="h-4 w-24" />
                        <Skeleton className="h-5 w-12" />
                      </div>
                      <div className="flex items-center justify-between">
                        <Skeleton className="h-3 w-20" />
                        <Skeleton className="h-3 w-8" />
                      </div>
                      <div className="pt-2 border-t">
                        <Skeleton className="h-3 w-32 mb-2" />
                        <Skeleton className="h-32 w-full" />
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          ) : clusterStates.length === 0 ? (
            <Card>
              <CardContent className="pt-6 text-center">
                <LayersIcon className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                <h3 className="text-lg font-semibold mb-2">
                  No partitions found
                </h3>
                <p className="text-muted-foreground">
                  This skill has no optimization partitions yet.
                </p>
              </CardContent>
            </Card>
          ) : (
            <div className="flex gap-4 overflow-x-auto pb-4">
              {clusterStates.map((cluster) => (
                <Card
                  key={cluster.id}
                  className="min-w-[300px] cursor-pointer hover:shadow-lg hover:border-primary/50 transition-all"
                  onClick={() =>
                    navigateToClusterArms(
                      selectedAgent.name,
                      selectedSkill.name,
                      cluster.name,
                    )
                  }
                >
                  <CardHeader className="pb-2">
                    <CardTitle className="text-lg leading-none mb-2">
                      {cluster.name}
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-muted-foreground">
                          Total Requests
                        </span>
                        <Badge variant="secondary">
                          {cluster.observability_total_requests.toString()}
                        </Badge>
                      </div>
                      <div className="flex items-center justify-between text-xs">
                        <span className="text-muted-foreground">
                          Since Reflection
                        </span>
                        <span className="text-muted-foreground">
                          {cluster.total_steps.toString()}
                        </span>
                      </div>
                      <div className="pt-2 border-t">
                        <div className="text-xs text-muted-foreground mb-2">
                          Performance
                        </div>
                        {isLoadingClusterEvaluationScores ? (
                          <Skeleton className="h-32 w-full" />
                        ) : (
                          <ClusterPerformanceChart
                            evaluationScores={
                              clusterEvaluationScores[cluster.id] || []
                            }
                            events={skillEvents.filter(
                              (e) =>
                                e.cluster_id === cluster.id ||
                                e.cluster_id === null,
                            )}
                            intervalMinutes={5}
                            windowHours={2.5}
                            endTime={endTime}
                          />
                        )}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-lg font-semibold">Observability</h3>
            <p className="text-sm text-muted-foreground">
              Monitor and analyze the performance and behavior of your skill
            </p>
          </div>
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-1 xl:grid-cols-2 gap-4">
          {/* Recent Logs Card */}
          <Card
            className="cursor-pointer hover:shadow-lg hover:border-primary/50 transition-all"
            onClick={() =>
              navigateToLogs(selectedAgent.name, selectedSkill.name)
            }
          >
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <div>
                <CardTitle className="text-base font-medium">Logs</CardTitle>
                <CardDescription>Recent requests</CardDescription>
              </div>
              <FileTextIcon className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent className="p-0">
              {isLoadingLogs ? (
                <div className="p-6 space-y-1">
                  {Array.from({ length: 5 }).map(() => (
                    <Skeleton key={nanoid()} className="h-8 w-full" />
                  ))}
                </div>
              ) : recentLogs.length === 0 ? (
                <p className="p-6 text-sm text-muted-foreground">
                  No logs available
                </p>
              ) : (
                <div className="m-4 border rounded-lg overflow-hidden">
                  <Table>
                    <TableBody>
                      {recentLogs.slice(0, 5).map((log) => {
                        const cluster = clusterStates.find(
                          (c) => c.id === log.cluster_id,
                        );
                        return (
                          <TableRow
                            key={log.id}
                            className="hover:bg-transparent"
                          >
                            <TableCell className="font-medium">
                              {PrettyFunctionName[log.function_name] ||
                                log.function_name ||
                                'N/A'}
                            </TableCell>
                            <TableCell className="text-muted-foreground">
                              {log.model}
                            </TableCell>
                            {cluster && (
                              <TableCell className="text-muted-foreground">
                                {cluster.name}
                              </TableCell>
                            )}
                            <TableCell className="text-right text-muted-foreground">
                              {log.duration.toFixed(0)}ms
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
 
          {/* Events Card */}
          <Card
            className="cursor-pointer hover:shadow-lg hover:border-primary/50 transition-all"
            onClick={() =>
              navigate({
                to: '/agents/$agentName/skills/$skillName/events',
                params: {
                  agentName: selectedAgent.name,
                  skillName: selectedSkill.name,
                },
              })
            }
          >
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <div>
                <CardTitle className="text-base font-medium">Events</CardTitle>
                <CardDescription>Skill changes and updates</CardDescription>
              </div>
              <CalendarIcon className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent className="p-0">
              {skillEvents.length === 0 ? (
                <p className="p-6 text-sm text-muted-foreground">
                  No events available
                </p>
              ) : (
                <div className="m-4 border rounded-lg overflow-hidden">
                  <Table>
                    <TableBody>
                      {skillEvents.slice(0, 5).map((event) => {
                        const label =
                          eventLabels[event.event_type] || event.event_type;
 
                        return (
                          <TableRow
                            key={event.id}
                            className="hover:bg-transparent"
                          >
                            <TableCell className="font-medium">
                              {label}
                              {event.metadata.model_name
                                ? `: ${event.metadata.model_name}`
                                : ''}
                            </TableCell>
                            <TableCell className="text-right text-muted-foreground">
                              {new Date(event.created_at).toLocaleString()}
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
 
      {/* Manage Models Dialog */}
      {selectedSkill && (
        <ManageSkillModelsDialog
          open={isManageModelsOpen}
          onOpenChange={setIsManageModelsOpen}
          skillId={selectedSkill.id}
        />
      )}
 
      {/* Delete Skill Dialog */}
      <DeleteSkillDialog
        skill={selectedSkill || null}
        open={isDeleteSkillDialogOpen}
        onOpenChange={setIsDeleteSkillDialogOpen}
        onConfirm={handleDeleteSkill}
      />
 
      {/* Reset Skill Dialog */}
      <ResetSkillDialog
        skill={selectedSkill || null}
        open={isResetSkillDialogOpen}
        onOpenChange={setIsResetSkillDialogOpen}
        onConfirm={handleResetSkill}
        isResetting={isResettingSkill}
      />
    </>
  );
}