All files / src/components/chat/AgentChat AgentToolsMenu.tsx

92.3% Statements 24/26
88.46% Branches 46/52
83.33% Functions 10/12
95.65% Lines 22/23

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                                                  10x             10x               4x           4x         10x           6x   6x                                                                                                     10x                             7x 7x   7x   4x                                                       6x           1x                             231x                               10x 231x   231x   53x         231x 231x   231x                                                                                                                                    
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { EffectiveTools, ToolEntry } from "@/objects/Agent";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import {
  Calculator,
  ChevronDown,
  ChevronRight,
  Clock,
  ExternalLink,
  Globe,
  Link,
  Puzzle,
  Settings2,
  Wrench,
} from "lucide-react";
import React, { useState } from "react";
 
// ─── Icon map for known general tools ────────────────────────────────────────
 
const GENERAL_TOOL_ICONS: Record<string, React.ReactNode> = {
  calculate: <Calculator className="w-3.5 h-3.5 shrink-0" />,
  web_search: <Globe className="w-3.5 h-3.5 shrink-0" />,
  url_fetch: <Link className="w-3.5 h-3.5 shrink-0" />,
  current_time: <Clock className="w-3.5 h-3.5 shrink-0" />,
};
 
const GENERAL_TOOL_LABELS: Record<string, string> = {
  calculate: "Calculate",
  web_search: "Web Search",
  url_fetch: "URL Fetch",
  current_time: "Current Time",
};
 
function generalIcon(name: string): React.ReactNode {
  return (
    GENERAL_TOOL_ICONS[name] ?? <Settings2 className="w-3.5 h-3.5 shrink-0" />
  );
}
 
function generalLabel(name: string): string {
  return GENERAL_TOOL_LABELS[name] ?? name.replace(/_/g, " ");
}
 
// ─── Single tool pill ─────────────────────────────────────────────────────────
 
const ToolPill: React.FC<{
  tool: ToolEntry;
  isGeneral: boolean;
  open: boolean;
  onToggle: () => void;
}> = ({ tool, isGeneral, open, onToggle }) => {
  const isWebhook: boolean = tool.implementation?.startsWith("http") ?? false;
 
  return (
    <div className="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
      <button
        type="button"
        onClick={onToggle}
        aria-expanded={open}
        className="w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors"
      >
        <span
          className={`flex items-center justify-center ${
            isGeneral
              ? "text-indigo-500 dark:text-indigo-400"
              : "text-emerald-500 dark:text-emerald-400"
          }`}
        >
          {isGeneral ? (
            generalIcon(tool.name)
          ) : isWebhook ? (
            <ExternalLink className="w-3.5 h-3.5 shrink-0" />
          ) : (
            <Puzzle className="w-3.5 h-3.5 shrink-0" />
          )}
        </span>
        <span className="flex-1 text-xs font-medium text-gray-800 dark:text-gray-200 truncate">
          {isGeneral ? generalLabel(tool.name) : tool.name}
        </span>
        {open ? (
          <ChevronDown className="w-3 h-3 text-gray-400 shrink-0" />
        ) : (
          <ChevronRight className="w-3 h-3 text-gray-400 shrink-0" />
        )}
      </button>
 
      {open && (
        <div className="px-3 pb-2.5 pt-0 border-t border-gray-100 dark:border-gray-700/60">
          <p className="text-[11px] text-gray-500 dark:text-gray-400 leading-relaxed mt-2">
            {tool.description || "No description available."}
          </p>
          {isWebhook && tool.implementation && (
            <p className="text-[10px] text-gray-400 dark:text-gray-500 mt-1.5 font-mono truncate">
              {tool.implementation}
            </p>
          )}
        </div>
      )}
    </div>
  );
};
 
// ─── Section ─────────────────────────────────────────────────────────────────
 
const ToolSection: React.FC<{
  title: string;
  badge?: string;
  badgeColor?: string;
  tools: ToolEntry[];
  isGeneral: boolean;
  defaultExpanded?: boolean;
}> = ({
  title,
  badge,
  badgeColor = "bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400",
  tools,
  isGeneral,
  defaultExpanded = false,
}) => {
  const [expanded, setExpanded] = useState(defaultExpanded);
  const [openTool, setOpenTool] = useState<string | null>(null);
 
  if (tools.length === 0) return null;
 
  return (
    <div className="space-y-1.5">
      <button
        type="button"
        onClick={() => setExpanded((v) => !v)}
        aria-expanded={expanded}
        className="w-full flex items-center gap-2 text-left"
      >
        {expanded ? (
          <ChevronDown className="w-3 h-3 text-gray-400 shrink-0" />
        ) : (
          <ChevronRight className="w-3 h-3 text-gray-400 shrink-0" />
        )}
        <span className="text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
          {title}
        </span>
        {badge && (
          <span
            className={`ml-auto text-[10px] px-1.5 py-0.5 rounded-full font-medium ${badgeColor}`}
          >
            {badge}
          </span>
        )}
      </button>
 
      {expanded && (
        <div className="space-y-1 pl-1">
          {tools.map((tool) => (
            <ToolPill
              key={tool.name}
              tool={tool}
              isGeneral={isGeneral}
              open={openTool === tool.name}
              onToggle={() =>
                setOpenTool((prev) => (prev === tool.name ? null : tool.name))
              }
            />
          ))}
        </div>
      )}
    </div>
  );
};
 
// ─── AgentToolsMenu ──────────────────────────────────────────────────────────
 
/** The tools an answer may call, as svc-core resolves them for this agent.
 *  Anything else is read as no tools rather than thrown on. */
function toolLists(data: EffectiveTools | null | undefined): EffectiveTools {
  return {
    general: Array.isArray(data?.general) ? data.general : [],
    specialist: Array.isArray(data?.specialist) ? data.specialist : [],
  };
}
 
interface AgentToolsMenuProps {
  agentId: string;
}
 
/**
 * The chat toolbar's **Tools** dropdown: how many tools the agent's answers
 * may call on the trigger, and each one — its description, and a webhook's
 * URL — in the popover. Fetched with the page, so the count is there before
 * it is opened.
 */
const AgentToolsMenu: React.FC<AgentToolsMenuProps> = ({ agentId }) => {
  const { getApiHandler } = useApiHandler();
 
  const { data, isLoading } = useQuery<EffectiveTools | null>({
    queryKey: [QUERY_KEYS.GET.AGENT_BY_ID, agentId, "effective-tools"],
    queryFn: () => getApiHandler().agent_router.getEffectiveTools(agentId),
    enabled: !!agentId,
    staleTime: 60_000,
  });
 
  const { general, specialist } = toolLists(data);
  const totalCount = general.length + specialist.length;
 
  return (
    <Popover>
      <PopoverTrigger asChild>
        <button
          type="button"
          aria-label={data ? `Tools (${totalCount})` : "Tools"}
          className="shrink-0 inline-flex items-center gap-1.5 h-7 px-2 rounded-md border-0 text-xs font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 data-[state=open]:bg-gray-100 dark:data-[state=open]:bg-gray-800 transition-colors"
        >
          <Wrench className="w-3.5 h-3.5 text-gray-400 dark:text-gray-500 shrink-0" />
          Tools
          {data && totalCount > 0 && (
            <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400 font-medium">
              {totalCount}
            </span>
          )}
          <ChevronDown className="w-3.5 h-3.5 text-gray-400" />
        </button>
      </PopoverTrigger>
      {/* Above full screen's z-[60]: the popover is portaled to <body>. */}
      <PopoverContent
        align="end"
        className="z-[70] w-80 max-w-[calc(100vw-2rem)] max-h-[60vh] overflow-y-auto p-3 space-y-3"
      >
        {isLoading ? (
          <div className="flex items-center gap-2 py-2">
            <div className="w-3 h-3 rounded-full border-2 border-indigo-400 border-t-transparent animate-spin" />
            <span className="text-xs text-gray-400">Loading tools…</span>
          </div>
        ) : !data ? (
          <p className="text-xs text-gray-400 py-1">
            Could not load tool information.
          </p>
        ) : (
          <>
            <ToolSection
              title="System tools"
              badge="always active"
              badgeColor="bg-indigo-50 dark:bg-indigo-900/30 text-indigo-500 dark:text-indigo-400"
              tools={general}
              isGeneral
              defaultExpanded
            />
            <ToolSection
              title="Configured tools"
              badge={
                specialist.length > 0
                  ? `${specialist.length} assigned`
                  : undefined
              }
              tools={specialist}
              isGeneral={false}
              defaultExpanded
            />
            {specialist.length === 0 && (
              <p className="text-[11px] text-gray-400 dark:text-gray-500 pl-5 pb-1">
                No specialist tools assigned — only system tools are active.
              </p>
            )}
          </>
        )}
      </PopoverContent>
    </Popover>
  );
};
 
export default AgentToolsMenu;