All files / web/src/components/agents agent-view.tsx

94.09% Statements 446/474
74% Branches 37/50
43.75% Functions 7/16
94.09% Lines 446/474

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    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 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   1x 29x 29x 29x 29x   29x 18x 8x 29x   29x       29x 29x 29x 29x 29x 29x 29x 29x 29x   29x 10x 10x 10x 10x     10x     10x 29x     29x 10x 10x 10x     29x     29x     29x 29x 29x 29x 29x     29x 18x 8x 8x 8x 8x 29x     29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 29x 29x 29x     29x 29x 29x 8x 8x 8x 29x 29x 29x     29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 6x     6x 12x 12x 12x 12x 12x 12x 12x 12x 6x   6x 6x 6x 29x 29x 29x   29x 10x               10x   10x 29x   29x           29x               29x 1x 1x 1x 1x 1x 1x   29x               29x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x     20x 20x 20x 20x   20x   9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x   29x 29x 29x 29x 29x   29x   29x 29x 29x   29x 29x   29x 29x 29x 29x 29x 29x 29x   29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x   29x 29x 29x 29x 29x 29x 29x 29x 29x   29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x     29x 29x   29x 29x 54x 54x 54x 54x 54x   54x 54x   29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 8x 8x 8x   1x 1x 1x 1x 1x 1x 1x 1x   29x 29x   29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x   29x 29x   29x 1x 1x 6x 6x 6x 6x 6x 6x 1x 1x 8x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x   1x   7x 7x 14x 14x 14x 14x 14x   14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   14x 14x 12x   2x 2x 2x   2x 2x 2x 2x 2x   14x 14x 14x   7x 7x   29x   29x 29x 29x 29x 29x 29x 29x   29x  
'use client';
 
import { botttsNeutral, shapes } from '@dicebear/collection';
import { createAvatar } from '@dicebear/core';
import type { Skill } from '@shared/types/data';
import { useQuery } from '@tanstack/react-query';
import { getAgentEvaluationScoresByTimeBucket } from '@web/api/v1/super-agents/agents';
import { getSkillEvents } from '@web/api/v1/super-agents/skill-events';
import { getSkillEvaluationScoresByTimeBucket } from '@web/api/v1/super-agents/skills';
import { AgentPerformanceChart } from '@web/components/agents/agent-performance-chart';
import { AgentStatusIndicator } from '@web/components/agents/agent-status-indicator';
import { DeleteAgentDialog } from '@web/components/agents/delete-agent-dialog';
import { SkillPerformanceChart } from '@web/components/agents/skills/skill-performance-chart';
import { SkillStatusIndicator } from '@web/components/agents/skills/skill-status-indicator';
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 { Input } from '@web/components/ui/input';
import { PageHeader } from '@web/components/ui/page-header';
import { Skeleton } from '@web/components/ui/skeleton';
import { ToggleGroup, ToggleGroupItem } from '@web/components/ui/toggle-group';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@web/components/ui/tooltip';
import { usePermissiveNavigate } from '@web/hooks/use-permissive-navigate';
import { useAgents } from '@web/providers/agents';
import { useNavigation } from '@web/providers/navigation';
import { useSkills } from '@web/providers/skills';
import {
  BarChart3Icon,
  Clock,
  Edit,
  MoreVertical,
  PlusIcon,
  SearchIcon,
  Trash2,
} from 'lucide-react';
import { nanoid } from 'nanoid';
import type { ReactElement } from 'react';
import { useEffect, useMemo, useState } from 'react';
 
const createAgentAvatar = (agentName: string) => {
  const svg = createAvatar(botttsNeutral, {
    seed: agentName,
    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)}`;
};
 
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 AgentView(): ReactElement {
  const { navigateToSkillDashboard } = useNavigation();
  const { selectedAgent, deleteAgent } = useAgents();
  const navigate = usePermissiveNavigate();
  const [searchQuery, setSearchQuery] = useState('');
 
  const agentAvatar = useMemo(() => {
    if (!selectedAgent) return '';
    return createAgentAvatar(selectedAgent.name);
  }, [selectedAgent]);
 
  const [isDeleteAgentDialogOpen, setIsDeleteAgentDialogOpen] = 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('agent-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('agent-performance-interval', selectedInterval);
    } catch {
      // localStorage not available
    }
  }, [selectedInterval]);
 
  // End time for charts (defaults to now)
  const [endTime, setEndTime] = useState<Date>(() => new Date());
 
  // Use providers
  const {
    skills,
    isLoading: isLoadingSkills,
    setQueryParams: setSkillQueryParams,
  } = useSkills();
 
  // Update skills query params when agent changes
  useEffect(() => {
    if (!selectedAgent) return;
    setSkillQueryParams({
      agent_id: selectedAgent.id,
      limit: 100,
    });
  }, [selectedAgent, setSkillQueryParams]);
 
  // Fetch agent-level evaluation scores by time bucket
  const {
    data: agentEvaluationScores = [],
    isLoading: isLoadingAgentEvaluationScores,
  } = useQuery({
    queryKey: [
      'agentEvaluationScores',
      selectedAgent?.id,
      selectedInterval,
      INTERVAL_CONFIG[selectedInterval].hours,
      endTime.toISOString(),
    ],
    queryFn: async () => {
      if (!selectedAgent) return [];
      const scores = await getAgentEvaluationScoresByTimeBucket(
        selectedAgent.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(),
        },
      );
      return scores;
    },
    enabled: !!selectedAgent,
    refetchInterval: 60000, // Refetch every minute
  });
 
  // Fetch agent-level skill events
  const { data: agentEvents = [] } = useQuery({
    queryKey: ['agentEvents', selectedAgent?.id],
    queryFn: async () => {
      if (!selectedAgent) return [];
      return await getSkillEvents({ agent_id: selectedAgent.id });
    },
    enabled: !!selectedAgent,
    refetchInterval: 60000, // Refetch every minute
  });
 
  // Fetch skill-level evaluation scores for all skills (small charts)
  const {
    data: skillEvaluationScores = {},
    isLoading: isLoadingSkillEvaluationScores,
  } = useQuery({
    queryKey: [
      'skillEvaluationScores',
      selectedAgent?.id,
      skills.map((s) => s.id).join(','),
      endTime.toISOString(),
    ],
    queryFn: async () => {
      if (!selectedAgent || skills.length === 0) return {};
 
      // Fetch scores for all skills in parallel (30 buckets at 5 min intervals = 2.5 hours)
      const scoresPromises = skills.map(async (skill) => {
        const scores = await getSkillEvaluationScoresByTimeBucket(skill.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 [skill.id, scores] as const;
      });
 
      const scoresArray = await Promise.all(scoresPromises);
      return Object.fromEntries(scoresArray);
    },
    enabled: !!selectedAgent && skills.length > 0,
    refetchInterval: 60000, // Refetch every minute
  });
 
  const filteredSkills = useMemo(() => {
    const filtered = searchQuery
      ? skills.filter(
          (skill) =>
            skill.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
            skill.description
              ?.toLowerCase()
              .includes(searchQuery.toLowerCase()),
        )
      : skills;
 
    return [...filtered].sort((a, b) => a.name.localeCompare(b.name));
  }, [skills, searchQuery]);
 
  const handleSkillSelect = (skill: Skill) => {
    if (selectedAgent) {
      navigateToSkillDashboard(selectedAgent.name, skill.name);
    }
  };
 
  const handleCreateSkill = () => {
    if (selectedAgent) {
      navigate({
        to: `/agents/${encodeURIComponent(selectedAgent.name)}/skills/create`,
      });
    }
  };
 
  const handleEditAgent = () => {
    if (selectedAgent) {
      navigate({
        to: `/agents/${encodeURIComponent(selectedAgent.name)}/edit`,
      });
    }
  };
 
  const handleDeleteAgent = async () => {
    if (!selectedAgent) return;
    await deleteAgent(selectedAgent.id);
    navigate({ to: '/agents' });
  };
 
  // Removed automatic redirect to create skill - let users decide when to create
 
  if (!selectedAgent) {
    return (
      <>
        <PageHeader
          title="Welcome to Agents"
          description="Select an agent from the dropdown above to view its skills and start managing your AI /agents"
          showBackButton={false}
        />
        <div className="flex flex-1 items-center justify-center">
          <div className="text-center">
            <h2 className="text-2xl font-semibold mb-2">Welcome to Agents</h2>
            <p className="text-muted-foreground mb-4">
              Select an agent from the dropdown above to view its skills and
              start managing your AI /agents.
            </p>
          </div>
        </div>
      </>
    );
  }
 
  return (
    <>
      <PageHeader
        title={
          <div className="flex items-center gap-2">
            <img
              src={agentAvatar}
              alt={`${selectedAgent.name} avatar`}
              width={20}
              height={20}
              className="size-5 rounded-sm"
            />
            <span>{selectedAgent.name}</span>
            <AgentStatusIndicator
              agent={selectedAgent}
              variant="badge"
              tooltipSide="bottom"
            />
          </div>
        }
        description={selectedAgent.description || 'No description provided'}
        showBackButton={true}
        onBack={() => navigate({ to: '/agents' })}
        actions={
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="icon" title="More options">
                <MoreVertical className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={handleEditAgent}>
                <Edit className="h-4 w-4 mr-2" />
                Edit Agent
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                onClick={() => setIsDeleteAgentDialogOpen(true)}
                className="text-destructive focus:text-destructive"
              >
                <Trash2 className="h-4 w-4 mr-2" />
                Delete Agent
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        }
      />
      <div className="p-6 space-y-6">
        {/* Agent Performance Chart */}
        <Card>
          <CardHeader className="pb-4">
            <div className="flex items-center gap-2 mb-2">
              <BarChart3Icon className="h-5 w-5 text-muted-foreground" />
              <CardTitle className="text-lg">Agent Performance</CardTitle>
            </div>
            <CardDescription className="mb-4">
              Performance metrics across all skills for this agent
            </CardDescription>
            <div className="flex justify-between items-start 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>
              <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>
          </CardHeader>
          <CardContent>
            {isLoadingAgentEvaluationScores ? (
              <div className="h-64 flex items-center justify-center">
                <Skeleton className="h-full w-full" />
              </div>
            ) : (
              <AgentPerformanceChart
                evaluationScores={agentEvaluationScores}
                events={agentEvents}
                skills={skills}
                intervalMinutes={INTERVAL_CONFIG[selectedInterval].minutes}
                windowHours={INTERVAL_CONFIG[selectedInterval].hours}
                endTime={endTime}
              />
            )}
          </CardContent>
        </Card>
 
        <div className="flex justify-between items-center gap-4">
          <div className="relative flex-1">
            <SearchIcon className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="Search skills..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
            />
          </div>
          <Button onClick={handleCreateSkill}>
            <PlusIcon className="h-4 w-4 mr-2" />
            Create Skill
          </Button>
        </div>
 
        {isLoadingSkills ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 3xl:grid-cols-5 gap-4">
            {Array.from({ length: 6 }).map(() => (
              <Card key={nanoid()}>
                <CardHeader>
                  <Skeleton className="h-6 w-3/4" />
                  <Skeleton className="h-4 w-full" />
                </CardHeader>
              </Card>
            ))}
          </div>
        ) : filteredSkills.length === 0 ? (
          <div className="text-center py-12">
            <h3 className="text-lg font-semibold mb-2">No skills found</h3>
            <p className="text-muted-foreground mb-4">
              {searchQuery
                ? 'No skills match your search criteria.'
                : "This agent doesn't have any skills yet."}
            </p>
            {!searchQuery && (
              <Button onClick={handleCreateSkill}>
                <PlusIcon className="h-4 w-4 mr-2" />
                Create your first skill
              </Button>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 3xl:grid-cols-5 gap-4">
            {filteredSkills.map((skill) => {
              return (
                <Card
                  key={skill.id}
                  className="cursor-pointer hover:shadow-lg hover:border-primary/50 transition-all"
                  onClick={() => handleSkillSelect(skill)}
                >
                  <CardHeader className="pb-2">
                    <div className="flex items-start justify-between gap-2 mb-2">
                      <div className="flex items-center gap-2 min-w-0">
                        <img
                          src={createSkillAvatar(skill.name)}
                          alt={`${skill.name} icon`}
                          width={24}
                          height={24}
                          className="size-6 rounded-sm shrink-0"
                        />
                        <CardTitle className="text-base truncate leading-normal">
                          {skill.name}
                        </CardTitle>
                      </div>
                      <SkillStatusIndicator
                        skill={skill}
                        variant="badge"
                        tooltipSide="left"
                      />
                    </div>
                    <CardDescription className="line-clamp-2 text-sm">
                      {skill.description || 'No description available'}
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="pt-2 border-t">
                      <div className="text-xs text-muted-foreground mb-2">
                        Performance
                      </div>
                      {isLoadingSkillEvaluationScores ? (
                        <Skeleton className="h-32 w-full" />
                      ) : (
                        <SkillPerformanceChart
                          evaluationScores={
                            skillEvaluationScores[skill.id] || []
                          }
                          size="small"
                          intervalMinutes={5}
                          windowHours={2.5}
                          endTime={endTime}
                        />
                      )}
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        )}
      </div>
 
      <DeleteAgentDialog
        agent={selectedAgent}
        open={isDeleteAgentDialogOpen}
        onOpenChange={setIsDeleteAgentDialogOpen}
        onConfirm={handleDeleteAgent}
      />
    </>
  );
}