import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useMemo, memo, useEffect } from "react";
import { JsonView, defaultStyles } from "react-json-view-lite";
import "react-json-view-lite/dist/index.css";
import { Spinner } from "../../../ui/Spinner";
import { CopyButton } from "../../../../components/ui/copy-button";
import { Tooltip, TooltipTrigger, TooltipContent, } from "../../../../components/ui/tooltip";
import { formatTime, formatDateTime } from "../../../utils";
// Custom dark theme styles for JSON view
const darkJsonStyles = {
    ...defaultStyles,
    container: "dark-json-container",
    label: "dark-json-label",
    punctuation: "dark-json-punctuation",
    stringValue: "dark-json-string",
    numberValue: "dark-json-number",
    booleanValue: "dark-json-boolean",
    nullValue: "dark-json-null",
    undefinedValue: "dark-json-undefined",
};
// JSON view light theme CSS
const JsonLightThemeStyles = () => (_jsx("style", { children: `
    .dark-json-container { color: var(--color-neutral-grey-100); }
    .dark-json-label { color: var(--color-feedback-blue); font-weight: 500; }
    .dark-json-punctuation { color: var(--color-neutral-grey-50); }
    .dark-json-string { color: var(--color-feedback-green); }
    .dark-json-number { color: var(--color-feedback-orange); }
    .dark-json-boolean { color: var(--color-highlight-100); }
    .dark-json-null { color: var(--color-feedback-red); }
    .dark-json-undefined { color: var(--color-feedback-red); }
  ` }));
import { ChevronDown, ChevronRight, CheckCircle2, XCircle, Wrench, } from "lucide-react";
const ToolCallStatusIcon = ({ failed }) => {
    const Icon = failed ? XCircle : CheckCircle2;
    return (_jsx(Icon, { strokeWidth: 1, size: 14, className: failed ? "text-feedback-red" : "text-feedback-green" }));
};
const formatToolDuration = (durationMs) => {
    if (typeof durationMs !== "number" ||
        !Number.isFinite(durationMs) ||
        durationMs < 0) {
        return null;
    }
    if (durationMs < 1000) {
        return `${Math.round(durationMs)}ms`;
    }
    if (durationMs < 10_000) {
        return `${(durationMs / 1000).toFixed(1)}s`;
    }
    if (durationMs < 60_000) {
        return `${Math.round(durationMs / 1000)}s`;
    }
    const totalSeconds = Math.round(durationMs / 1000);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    if (minutes < 60) {
        return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
    }
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
};
const formatToolCallMeta = (createdDate, durationMs) => {
    const parts = [];
    let tooltip = null;
    if (createdDate) {
        const parsed = new Date(createdDate);
        if (!Number.isNaN(parsed.getTime())) {
            parts.push(formatTime(parsed));
            tooltip = formatDateTime(parsed);
        }
    }
    const duration = formatToolDuration(durationMs);
    if (duration) {
        parts.push(duration);
    }
    return parts.length > 0 ? { display: parts.join(" • "), tooltip } : null;
};
// Helper function to normalize tool calls to a common format
const normalizeToolCall = (toolCall) => {
    if ("functionName" in toolCall) {
        // Agent tool call format
        return {
            id: toolCall.toolCallId,
            displayName: toolCall.functionName,
            function: {
                name: toolCall.functionName,
                arguments: toolCall.functionArguments,
                result: toolCall.functionResultRichContent || toolCall.functionResult,
                error: toolCall.functionError,
            },
            requiresApproval: toolCall.requiresApproval,
            isPruned: toolCall.isPruned,
            prunedAt: toolCall.prunedAt,
            responseTimeMs: toolCall.responseTimeMs,
            createdDate: toolCall.createdDate,
        };
    }
    // Already in base format
    return toolCall;
};
// Memoized JSON viewer component to prevent re-renders during streaming
const MemoizedJsonView = memo(({ data }) => {
    return (_jsxs("div", { className: "font-mono text-xs", style: { fontSize: "12px" }, children: [_jsx(JsonLightThemeStyles, {}), _jsx(JsonView, { data: data, shouldExpandNode: (level) => level < 2, style: darkJsonStyles })] }));
}, (prevProps, nextProps) => {
    // Only re-render if the data actually changed (deep comparison by stringifying)
    return JSON.stringify(prevProps.data) === JSON.stringify(nextProps.data);
});
MemoizedJsonView.displayName = "MemoizedJsonView";
const MAX_AUTO_PARSE_JSON_CHARS = 25_000;
// Helper function to parse JSON string to object
const parseJsonString = (json) => {
    // If it's already an object, return it directly
    if (typeof json === "object" && json !== null) {
        return json;
    }
    // Convert to string if not already
    const jsonString = typeof json === "string" ? json : String(json);
    const trimmed = jsonString.trim();
    if (!trimmed || trimmed.length > MAX_AUTO_PARSE_JSON_CHARS) {
        return null;
    }
    const firstChar = trimmed[0];
    if (firstChar !== "{" && firstChar !== "[" && firstChar !== '"') {
        return null;
    }
    // Try to parse as JSON
    try {
        let parsed = JSON.parse(trimmed);
        // If the result is still a string that looks like JSON, parse it again
        if (typeof parsed === "string" &&
            (parsed.startsWith("{") || parsed.startsWith("["))) {
            try {
                parsed = JSON.parse(parsed);
            }
            catch {
                // Keep the first parsed value when nested JSON is incomplete.
            }
        }
        return parsed;
    }
    catch {
        // Try to handle double-escaped JSON
        try {
            const unescaped = trimmed.replace(/\\"/g, '"').replace(/\\\\/g, "\\");
            const parsed = JSON.parse(unescaped);
            return parsed;
        }
        catch {
            // If all parsing fails, return null to indicate we should display as plain text
            return null;
        }
    }
};
const isImageDataUrl = (value) => {
    return typeof value === "string" && /^data:image\//i.test(value.trim());
};
const getInlineImageSource = (value) => {
    if (isImageDataUrl(value)) {
        return value.trim();
    }
    if (!value || typeof value !== "object") {
        return null;
    }
    const candidate = value;
    if (isImageDataUrl(candidate.dataUrl)) {
        return candidate.dataUrl.trim();
    }
    if (isImageDataUrl(candidate.url)) {
        return candidate.url.trim();
    }
    if (isImageDataUrl(candidate.src)) {
        return candidate.src.trim();
    }
    const imageUrlCandidate = candidate.imageUrl ?? candidate.image_url;
    if (imageUrlCandidate && typeof imageUrlCandidate === "object") {
        const imageUrlRecord = imageUrlCandidate;
        if (isImageDataUrl(imageUrlRecord.url)) {
            return imageUrlRecord.url.trim();
        }
    }
    return null;
};
export const extractInlineToolResultImage = (value) => {
    const directSource = getInlineImageSource(value);
    if (directSource) {
        return {
            src: directSource,
            alt: "Tool result image",
        };
    }
    if (Array.isArray(value)) {
        for (const entry of value) {
            const preview = extractInlineToolResultImage(entry);
            if (preview) {
                return preview;
            }
        }
        return null;
    }
    if (!value || typeof value !== "object") {
        return null;
    }
    const candidate = value;
    const nestedImage = candidate.image && typeof candidate.image === "object"
        ? candidate.image
        : undefined;
    const richImageSource = getInlineImageSource(candidate.imageUrl ??
        candidate.image_url);
    const src = isImageDataUrl(nestedImage?.dataUrl)
        ? nestedImage?.dataUrl.trim()
        : isImageDataUrl(candidate.dataUrl)
            ? candidate.dataUrl.trim()
            : richImageSource
                ? richImageSource
                : null;
    if (!src) {
        return null;
    }
    const width = typeof candidate.imageWidth === "number" &&
        Number.isFinite(candidate.imageWidth)
        ? candidate.imageWidth
        : typeof nestedImage?.width === "number" &&
            Number.isFinite(nestedImage.width)
            ? nestedImage.width
            : undefined;
    const height = typeof candidate.imageHeight === "number" &&
        Number.isFinite(candidate.imageHeight)
        ? candidate.imageHeight
        : typeof nestedImage?.height === "number" &&
            Number.isFinite(nestedImage.height)
            ? nestedImage.height
            : undefined;
    return {
        src,
        alt: candidate.scope
            ? `Screenshot result (${candidate.scope})`
            : "Tool result image",
        fileName: nestedImage?.fileName || candidate.fileName,
        dimensions: width && height
            ? `${Math.round(width)} x ${Math.round(height)}`
            : undefined,
    };
};
const sanitizeInlineImageDataForDisplay = (value) => {
    if (isImageDataUrl(value)) {
        return "[image data URL omitted from preview]";
    }
    if (Array.isArray(value)) {
        let hasChanges = false;
        const sanitizedItems = value.map((entry) => {
            const sanitizedEntry = sanitizeInlineImageDataForDisplay(entry);
            if (sanitizedEntry !== entry) {
                hasChanges = true;
            }
            return sanitizedEntry;
        });
        return hasChanges ? sanitizedItems : value;
    }
    if (!value || typeof value !== "object") {
        return value;
    }
    const candidate = value;
    let hasChanges = false;
    const clone = {};
    Object.entries(candidate).forEach(([key, entryValue]) => {
        const sanitizedValue = sanitizeInlineImageDataForDisplay(entryValue);
        clone[key] = sanitizedValue;
        if (sanitizedValue !== entryValue) {
            hasChanges = true;
        }
    });
    return hasChanges ? clone : value;
};
export const InlineToolResultPreview = ({ preview, className = "border-border-default hover:border-border-default mb-2 block overflow-hidden rounded border bg-white transition-colors", imageClassName = "bg-neutral-grey-5 max-h-40 w-auto max-w-full object-contain", testId, }) => {
    return (_jsxs("a", { href: preview.src, target: "_blank", rel: "noopener noreferrer", className: className, "data-testid": testId, children: [_jsx("img", { src: preview.src, alt: preview.alt, loading: "eager", decoding: "async", className: imageClassName }), (preview.fileName || preview.dimensions) && (_jsxs("div", { className: "border-border-default badge-pad text-neutral-grey-50 flex items-center justify-between gap-3 border-t text-[10px]", children: [_jsx("span", { className: "truncate", children: preview.fileName || "Screenshot" }), preview.dimensions && (_jsx("span", { className: "shrink-0", children: preview.dimensions }))] }))] }));
};
// Helper function to render JSON or text
const renderJsonOrText = (json) => {
    const parsed = parseJsonString(json);
    if (parsed !== null) {
        return _jsx(MemoizedJsonView, { data: parsed });
    }
    // If parsing failed, display as plain text
    const jsonString = typeof json === "string" ? json : String(json);
    return (_jsx("div", { className: "text-neutral-grey-100 font-mono text-xs wrap-break-word whitespace-pre-wrap", children: jsonString }));
};
const DISCLOSURE_TRANSITION_MS = 200;
const AnimatedDisclosureContent = ({ isExpanded, children, contentClassName = "min-h-0 overflow-hidden", }) => {
    const [shouldRender, setShouldRender] = useState(isExpanded);
    const [isAnimatingOpen, setIsAnimatingOpen] = useState(isExpanded);
    useEffect(() => {
        if (isExpanded) {
            setShouldRender(true);
            setIsAnimatingOpen(false);
            let secondAnimationFrameId = null;
            const animationFrameId = window.requestAnimationFrame(() => {
                secondAnimationFrameId = window.requestAnimationFrame(() => {
                    setIsAnimatingOpen(true);
                });
            });
            return () => {
                window.cancelAnimationFrame(animationFrameId);
                if (secondAnimationFrameId !== null) {
                    window.cancelAnimationFrame(secondAnimationFrameId);
                }
            };
        }
        setIsAnimatingOpen(false);
        const timeoutId = window.setTimeout(() => {
            setShouldRender(false);
        }, DISCLOSURE_TRANSITION_MS);
        return () => window.clearTimeout(timeoutId);
    }, [isExpanded]);
    if (!shouldRender) {
        return null;
    }
    return (_jsx("div", { className: "grid transition-[grid-template-rows,opacity,transform] duration-200 ease-out motion-reduce:transition-none", style: {
            gridTemplateRows: isAnimatingOpen ? "1fr" : "0fr",
            opacity: isAnimatingOpen ? 1 : 0,
            transform: isAnimatingOpen ? "translateY(0)" : "translateY(-2px)",
        }, "aria-hidden": !isExpanded, children: _jsx("div", { className: contentClassName, children: children }) }));
};
// Expandable panel component
const ExpandablePanel = ({ title, children, defaultExpanded = false, actionButton, }) => {
    const [isExpanded, setIsExpanded] = useState(defaultExpanded);
    return (_jsxs("div", { className: "border-border-default border-b last:border-b-0", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "hover:bg-neutral-grey-5/50 flex flex-1 cursor-pointer items-center gap-1.5 px-3 py-1.5 transition-colors", onClick: () => setIsExpanded(!isExpanded), children: [_jsx(ChevronRight, { size: 12, strokeWidth: 1, className: `text-neutral-grey-50 transition-transform duration-200 ease-out motion-reduce:transition-none ${isExpanded ? "rotate-90" : "rotate-0"}` }), _jsx("span", { className: "text-neutral-grey-50 text-[10px] font-medium", children: title })] }), actionButton && (_jsx("div", { className: "pr-2", onClick: (e) => e.stopPropagation(), children: actionButton }))] }), _jsx(AnimatedDisclosureContent, { isExpanded: isExpanded, contentClassName: "min-h-0 w-full overflow-auto px-3 pb-2", children: children })] }));
};
// Helper function to create expandable tool call details
const ToolCallDetails = memo(({ toolCall, result, }) => {
    const isPruned = !!toolCall.isPruned;
    const hasError = !!toolCall.function?.error && !isPruned;
    const hasOutput = !!result || hasError || isPruned;
    const prunedOutput = useMemo(() => {
        if (!isPruned)
            return "";
        return result || toolCall.function?.error || "";
    }, [isPruned, result, toolCall.function?.error]);
    // Memoize parsed input data to prevent re-parsing on every render
    const parsedInput = useMemo(() => {
        return parseJsonString(toolCall.function?.arguments || "");
    }, [toolCall.function?.arguments]);
    // Memoize parsed output data to prevent re-parsing on every render
    const parsedOutput = useMemo(() => {
        return parseJsonString(result || "");
    }, [result]);
    const parsedPrunedOutput = useMemo(() => {
        return parseJsonString(prunedOutput);
    }, [prunedOutput]);
    const outputPreview = useMemo(() => {
        if (isPruned) {
            return extractInlineToolResultImage(parsedPrunedOutput ?? prunedOutput);
        }
        if (hasError) {
            return null;
        }
        return extractInlineToolResultImage(parsedOutput ?? (result || ""));
    }, [
        hasError,
        isPruned,
        parsedOutput,
        parsedPrunedOutput,
        prunedOutput,
        result,
    ]);
    const displayPrunedOutput = useMemo(() => {
        return sanitizeInlineImageDataForDisplay(parsedPrunedOutput ?? prunedOutput);
    }, [parsedPrunedOutput, prunedOutput]);
    const displayOutput = useMemo(() => {
        return sanitizeInlineImageDataForDisplay(parsedOutput ?? (result || ""));
    }, [parsedOutput, result]);
    // Get text to copy for input
    const inputTextToCopy = useMemo(() => {
        const args = toolCall.function?.arguments || "";
        if (parsedInput !== null) {
            return JSON.stringify(parsedInput, null, 2);
        }
        return args;
    }, [toolCall.function?.arguments, parsedInput]);
    // Get text to copy for output
    const outputTextToCopy = useMemo(() => {
        if (isPruned) {
            if (parsedPrunedOutput !== null) {
                return JSON.stringify(parsedPrunedOutput, null, 2);
            }
            return typeof prunedOutput === "object"
                ? JSON.stringify(prunedOutput, null, 2)
                : prunedOutput;
        }
        if (hasError) {
            return toolCall.function?.error || "";
        }
        if (parsedOutput !== null) {
            return JSON.stringify(parsedOutput, null, 2);
        }
        if (typeof result === "object") {
            return JSON.stringify(result, null, 2);
        }
        return result || "";
    }, [
        hasError,
        isPruned,
        toolCall.function?.error,
        parsedOutput,
        parsedPrunedOutput,
        prunedOutput,
        result,
    ]);
    return (_jsxs("div", { className: "border-border-default/60 bg-neutral-grey-5/40 mt-1 ml-5 overflow-hidden rounded border", children: [_jsx(ExpandablePanel, { title: "Input", defaultExpanded: !hasOutput, actionButton: _jsx(CopyButton, { textToCopy: inputTextToCopy, iconOnly: true, className: "text-neutral-grey-50 hover:text-neutral-grey-50 cursor-pointer" }), children: _jsx("div", { className: "rounded bg-white p-2 text-xs", children: parsedInput !== null ? (_jsx(MemoizedJsonView, { data: parsedInput })) : (_jsx("div", { className: "text-neutral-grey-100 font-mono text-xs wrap-break-word whitespace-pre-wrap", children: toolCall.function?.arguments || "" })) }) }), hasOutput && (_jsx(ExpandablePanel, { title: isPruned ? "Pruned" : hasError ? "Error" : "Output", defaultExpanded: true, actionButton: _jsx(CopyButton, { textToCopy: outputTextToCopy, iconOnly: true, className: "text-neutral-grey-50 hover:text-neutral-grey-50 cursor-pointer" }), children: isPruned ? (_jsxs("div", { className: "border-border-default bg-neutral-grey-5/70 text-neutral-grey-100 rounded border-l-2 p-2 text-xs", children: [_jsx("div", { className: "text-neutral-grey-50 mb-1 text-[10px] font-medium", children: "Pruned from AI context" }), _jsx("div", { className: "text-neutral-grey-50 mb-2", children: "This tool call completed, but its output was pruned from future agent context to save tokens." }), prunedOutput ? (_jsxs("div", { className: "rounded bg-white p-2 text-xs", children: [outputPreview && (_jsx(InlineToolResultPreview, { preview: outputPreview })), displayPrunedOutput !== null &&
                                    typeof displayPrunedOutput === "object" ? (_jsx(MemoizedJsonView, { data: displayPrunedOutput })) : (_jsx("div", { className: "text-neutral-grey-100 font-mono text-xs wrap-break-word whitespace-pre-wrap", children: String(displayPrunedOutput ?? prunedOutput) }))] })) : null] })) : hasError ? (_jsxs("div", { className: "border-feedback-red bg-feedback-red-light/60 text-feedback-red rounded border-l-2 p-2 text-xs", children: [_jsx("div", { className: "text-feedback-red mb-1 text-[10px] font-medium", children: "Error" }), _jsx("div", { className: "text-feedback-red", children: toolCall.function?.error })] })) : (_jsxs("div", { className: "rounded bg-white p-2 text-xs", children: [outputPreview && (_jsx(InlineToolResultPreview, { preview: outputPreview })), displayOutput !== null && typeof displayOutput === "object" ? (_jsx(MemoizedJsonView, { data: displayOutput })) : (_jsx("div", { className: "text-neutral-grey-100 font-mono text-xs wrap-break-word whitespace-pre-wrap", children: String(displayOutput ?? (result || "")) }))] })) }))] }));
}, (prevProps, nextProps) => {
    // Only re-render if the data actually changed
    return (prevProps.toolCall.id === nextProps.toolCall.id &&
        prevProps.toolCall.function?.arguments ===
            nextProps.toolCall.function?.arguments &&
        prevProps.result === nextProps.result &&
        prevProps.toolCall.function?.error ===
            nextProps.toolCall.function?.error &&
        prevProps.toolCall.isPruned === nextProps.toolCall.isPruned);
});
ToolCallDetails.displayName = "ToolCallDetails";
const AnimatedToolCallDetails = ({ isExpanded, children, }) => {
    return (_jsx(AnimatedDisclosureContent, { isExpanded: isExpanded, children: children }));
};
export function ToolCallDisplay({ toolCalls, finished, isLive = false, openPopovers, setOpenPopovers, messageId, }) {
    // Always starts collapsed — pending approvals are surfaced by the
    // ApprovalCard after the activity, never by force-expanding diagnostics.
    const [isGroupExpanded, setIsGroupExpanded] = useState(false);
    const [userToggled, setUserToggled] = useState(false);
    const groupSummary = useMemo(() => {
        if (!toolCalls || toolCalls.length === 0)
            return null;
        const uniqueNames = [
            ...new Set(toolCalls
                .map((tc) => {
                const normalized = normalizeToolCall(tc);
                return (("functionName" in tc
                    ? tc.functionName
                    : normalized.function?.name) || "")
                    .replace(/ \(approved\)/g, "")
                    .replace(/ \(rejected\)/g, "")
                    .replace(/ \(pending approval\)/g, "")
                    .trim();
            })
                .filter(Boolean)),
        ];
        const errorCount = toolCalls.filter((tc) => {
            const normalized = normalizeToolCall(tc);
            return !!normalized.function?.error && !normalized.isPruned;
        }).length;
        return { uniqueNames, errorCount };
    }, [toolCalls]);
    const allToolCallsCompleted = useMemo(() => {
        if (!toolCalls || toolCalls.length === 0)
            return false;
        return toolCalls.every((tc) => {
            const isAgentToolCall = "isCompleted" in tc;
            if (isAgentToolCall)
                return tc.isCompleted;
            const normalized = normalizeToolCall(tc);
            const approvalInfo = tc.requiresApproval || normalized.requiresApproval;
            return (!!(normalized.function?.result || normalized.function?.error) &&
                !approvalInfo);
        });
    }, [toolCalls]);
    const groupHasFailedToolCall = useMemo(() => {
        if (!toolCalls || toolCalls.length === 0)
            return false;
        return toolCalls.some((tc) => {
            const normalized = normalizeToolCall(tc);
            const functionName = ("functionName" in tc ? tc.functionName : normalized.function?.name) ||
                "";
            const isRejected = functionName.toLowerCase().includes("(rejected)");
            return ((!!normalized.function?.error && !normalized.isPruned) || isRejected);
        });
    }, [toolCalls]);
    if (!toolCalls || toolCalls.length === 0) {
        return null;
    }
    const showGroupHeader = toolCalls.length > 0;
    const isGroupActive = !groupHasFailedToolCall && (isLive || !allToolCallsCompleted);
    return (_jsxs("div", { className: "flex flex-col", children: [showGroupHeader && (_jsxs("div", { className: "group text-neutral-grey-50 hover:bg-neutral-grey-5/60 hover:text-neutral-grey-100 flex cursor-pointer items-center gap-1.5 rounded-md px-1 py-1 text-xs transition-all", "data-testid": "agent-toolcalls-group", onClick: () => {
                    setIsGroupExpanded(!isGroupExpanded);
                    setUserToggled(true);
                }, children: [_jsx("div", { className: "flex h-4 w-4 shrink-0 items-center justify-center transition-transform group-hover:scale-110", children: isGroupExpanded ? (_jsx(ChevronDown, { size: 14, strokeWidth: 1, className: "text-neutral-grey-50" })) : (_jsx(ChevronRight, { size: 14, strokeWidth: 1, className: "text-neutral-grey-50" })) }), _jsx("div", { className: "text-neutral-grey-50 flex h-4 w-4 shrink-0 items-center justify-center", children: _jsx(Wrench, { strokeWidth: 1, size: 14 }) }), _jsxs("span", { className: `leading-4 font-medium ${isGroupActive ? "animate-text-shimmer" : ""}`, children: [toolCalls.length, " tool call", toolCalls.length !== 1 ? "s" : ""] }), !isGroupExpanded && groupSummary && (_jsx("span", { className: "text-neutral-grey-50 ml-1 min-w-0 flex-1 truncate text-[10px] leading-4", children: groupSummary.uniqueNames.length <= 3
                            ? groupSummary.uniqueNames.join(", ")
                            : `${groupSummary.uniqueNames.slice(0, 2).join(", ")} +${groupSummary.uniqueNames.length - 2} more` })), groupSummary && groupSummary.errorCount > 0 && (_jsxs("span", { className: "text-feedback-red ml-1 shrink-0 text-[10px] leading-4", children: ["(", groupSummary.errorCount, " error", groupSummary.errorCount !== 1 ? "s" : "", ")"] })), _jsx("div", { className: "ml-auto flex h-4 w-4 shrink-0 items-center justify-center", children: groupHasFailedToolCall ? (_jsx(ToolCallStatusIcon, { failed: true })) : isGroupActive ? (_jsx(Spinner, { size: "xs" })) : (_jsx(ToolCallStatusIcon, { failed: false })) })] })), _jsx("div", { className: userToggled
                    ? "grid transition-[grid-template-rows] duration-200 ease-out"
                    : "grid", style: {
                    gridTemplateRows: isGroupExpanded ? "1fr" : "0fr",
                }, "aria-hidden": !isGroupExpanded, children: _jsx("div", { className: "overflow-hidden", children: _jsx("div", { className: "ml-4", children: toolCalls.map((originalToolCall, toolIndex) => {
                            const toolCall = normalizeToolCall(originalToolCall);
                            const toolResult = toolCall.function?.result;
                            const isAgentToolCall = "isCompleted" in originalToolCall;
                            const toolCallKey = ("toolCallId" in originalToolCall
                                ? originalToolCall.toolCallId
                                : toolCall.id) || `${messageId}-${toolIndex}`;
                            const popoverKey = `${messageId}-${toolCallKey}`;
                            const isPruned = !!toolCall.isPruned;
                            const toolCallMeta = formatToolCallMeta(toolCall.createdDate, toolCall.responseTimeMs);
                            // Get approval information to check if tool call is pending approval
                            const approvalInfo = originalToolCall.requiresApproval || toolCall.requiresApproval;
                            const isCompleted = isAgentToolCall
                                ? originalToolCall.isCompleted
                                : !!(toolResult || toolCall.function?.error) && !approvalInfo;
                            // Check if tool call is currently streaming (arguments still being generated)
                            const isStreaming = isAgentToolCall &&
                                "isStreaming" in originalToolCall &&
                                originalToolCall.isStreaming === true;
                            // Use the approval info from the backend
                            const finalApprovalInfo = approvalInfo;
                            // Check if this tool call has been approved/rejected (look for status indicators in function name)
                            // The AgentTerminal adds " (approved)" or " (rejected)" or " (pending approval)" to the functionName field
                            const originalFunctionName = ("functionName" in originalToolCall
                                ? originalToolCall.functionName
                                : toolCall?.function?.name) || "";
                            const isApproved = originalFunctionName.includes("(approved)");
                            const isRejected = originalFunctionName.includes("(rejected)");
                            // Treat only approved/rejected as final; pending should still show buttons
                            const hasApprovalStatus = isApproved || isRejected;
                            const hasFailed = (!!toolCall.function?.error && !isPruned) || isRejected;
                            const isAwaitingApproval = !!finalApprovalInfo && !hasApprovalStatus;
                            const showPendingStatus = !hasFailed &&
                                !isCompleted &&
                                (isAwaitingApproval || isStreaming || !finished);
                            // Debug logging removed for performance
                            const isExpanded = openPopovers[popoverKey] || false;
                            return (_jsxs("div", { children: [_jsxs("div", { className: "group text-neutral-grey-50 hover:bg-neutral-grey-5/60 hover:text-neutral-grey-100 flex cursor-pointer items-center gap-1.5 rounded-md px-1 py-1 text-xs transition-all", onClick: () => {
                                            setOpenPopovers((prev) => ({
                                                ...prev,
                                                [popoverKey]: !prev[popoverKey],
                                            }));
                                        }, children: [_jsx("div", { className: "flex h-4 w-4 shrink-0 items-center justify-center transition-transform group-hover:scale-110", children: _jsx(ChevronRight, { size: 14, strokeWidth: 1, className: `text-neutral-grey-50 transition-transform duration-200 ease-out motion-reduce:transition-none ${isExpanded ? "rotate-90" : "rotate-0"}` }) }), _jsx("div", { className: "text-neutral-grey-50 flex h-4 w-4 shrink-0 items-center justify-center", children: _jsx(Wrench, { strokeWidth: 1, size: 14 }) }), _jsxs("div", { className: "inline-flex min-w-0 flex-1 items-center gap-2", children: [_jsxs("span", { className: `shrink-0 leading-4 font-medium transition-colors ${toolCall.function?.error && !isPruned
                                                            ? "text-feedback-red"
                                                            : isPruned
                                                                ? "text-neutral-grey-50"
                                                                : ""}`, children: [(originalFunctionName ||
                                                                toolCall?.function?.name ||
                                                                toolCall?.displayName ||
                                                                "(function name missing)")
                                                                .replace(" (approved)", "")
                                                                .replace(" (rejected)", "")
                                                                .replace(" (pending approval)", ""), toolCall.function?.error &&
                                                                !isRejected &&
                                                                !isPruned && (_jsx("span", { className: "text-feedback-red ml-1 leading-4", children: "(error)" })), isPruned && (_jsxs("span", { className: "rounded-badge bg-neutral-grey-5 badge-pad-sm text-2xs text-neutral-grey-100 ml-2 inline-flex items-center gap-1 font-medium", children: [_jsx("span", { children: "\u2702" }), " Pruned"] })), finalApprovalInfo && isRejected && (_jsxs("span", { className: "rounded-badge bg-feedback-red-light badge-pad-sm text-2xs text-feedback-red ml-2 inline-flex items-center gap-1 font-medium", children: [_jsx("span", { children: "\u2717" }), " Rejected"] }))] }), finalApprovalInfo?.summary && (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: "text-neutral-grey-50 min-w-0 flex-1 cursor-help truncate text-xs leading-4 italic", children: finalApprovalInfo.summary }) }), _jsx(TooltipContent, { side: "top", className: "max-w-md", children: finalApprovalInfo.summary })] })), _jsxs("div", { className: "ml-auto flex shrink-0 items-center gap-1.5", children: [toolCallMeta &&
                                                                (toolCallMeta.tooltip ? (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: "text-neutral-grey-50 cursor-help text-[10px] leading-4", children: toolCallMeta.display }) }), _jsx(TooltipContent, { side: "top", children: toolCallMeta.tooltip })] })) : (_jsx("span", { className: "text-neutral-grey-50 text-[10px] leading-4", children: toolCallMeta.display }))), _jsx("div", { className: "flex h-4 w-4 shrink-0 items-center justify-center transition-all", children: hasFailed ? (_jsx(ToolCallStatusIcon, { failed: true })) : showPendingStatus ? (_jsx(Spinner, { size: "xs" })) : (_jsx(ToolCallStatusIcon, { failed: false })) })] })] })] }), _jsx(AnimatedToolCallDetails, { isExpanded: isExpanded, children: _jsx(ToolCallDetails, { toolCall: toolCall, result: toolResult }) })] }, toolCallKey));
                        }) }) }) })] }));
}
//# sourceMappingURL=ToolCallDisplay.js.map