import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { Bug } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import { getAgentDiagnostics, getLastPayload, } from "../services/agentService";
import { AgentCostDisplay } from "./AgentCostDisplay";
import { ContentInspectorPopover, } from "./ContentInspectorPopover";
import { formatAgentDiagnosticsEvent, interpretAgentRunDiagnostics, } from "./agentDiagnostics";
function formatDiagnosticTime(value) {
    if (!value)
        return "—";
    const parsed = new Date(value);
    return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString();
}
function yesNo(value) {
    return value ? "Yes" : "No";
}
function lines(values) {
    return values.filter(Boolean).join("\n");
}
function formatMachineCapacityLimit(value) {
    return value > 0 ? String(value) : "Unlimited";
}
function buildMachineCapacitySection(currentAgentId, serverDiagnostics) {
    const machineCapacity = serverDiagnostics.machineCapacity;
    if (!machineCapacity)
        return null;
    const occupantBlocks = machineCapacity.occupants.length > 0
        ? machineCapacity.occupants
            .map((occupant, index) => lines([
            `Slot ${index + 1}: ${occupant.agentName || occupant.agentId}`,
            `Agent ID: ${occupant.agentId}`,
            occupant.runId ? `Run ID: ${occupant.runId}` : null,
            `Status: ${occupant.status || "unknown"}`,
            occupant.mode ? `Mode: ${occupant.mode}` : null,
            occupant.userId ? `User: ${occupant.userId}` : null,
            `Started: ${formatDiagnosticTime(occupant.startedAt)}`,
            `Completed: ${formatDiagnosticTime(occupant.completedAt)}`,
            `Active task: ${yesNo(Boolean(occupant.hasActiveExecutionTask))}`,
            `In execution loop: ${yesNo(Boolean(occupant.isInExecutionLoop))}`,
            occupant.executionTaskStatus
                ? `Task status: ${occupant.executionTaskStatus}`
                : null,
            occupant.sessionId ? `Session ID: ${occupant.sessionId}` : null,
            occupant.agentId === currentAgentId ? "Current agent: Yes" : null,
        ]))
            .join("\n\n")
        : "Current slot holders: None";
    return {
        title: "Machine capacity (admin)",
        content: `${lines([
            `Max running agents: ${formatMachineCapacityLimit(machineCapacity.maxRunningAgents)}`,
            `Actively running executions: ${machineCapacity.runningExecutions}`,
        ])}\n\n${occupantBlocks}`.trim(),
    };
}
function normalizeInspectorText(value) {
    if (typeof value !== "string")
        return null;
    const normalized = value.replace(/\r\n/g, "\n").trim();
    return normalized.length > 0 ? normalized : null;
}
function extractTextFromUnknown(value, depth = 0) {
    if (depth > 5 || value == null)
        return [];
    if (typeof value === "string") {
        const normalized = normalizeInspectorText(value);
        return normalized ? [normalized] : [];
    }
    if (Array.isArray(value)) {
        return value.flatMap((entry) => extractTextFromUnknown(entry, depth + 1));
    }
    if (typeof value !== "object") {
        return [];
    }
    const record = value;
    if (typeof record.text === "string") {
        return extractTextFromUnknown(record.text, depth + 1);
    }
    if (typeof record.content === "string") {
        return extractTextFromUnknown(record.content, depth + 1);
    }
    const candidates = [
        record.content,
        record.parts,
        record.messages,
        record.message,
        record.input,
        record.output,
        record.prompt,
        record.response,
        record.arguments,
    ];
    for (const candidate of candidates) {
        const extracted = extractTextFromUnknown(candidate, depth + 1);
        if (extracted.length > 0)
            return extracted;
    }
    return [];
}
function joinExtractedText(value) {
    const text = extractTextFromUnknown(value)
        .join("\n")
        .trim();
    return text.length > 0 ? text : null;
}
function extractLastPromptFromPayload(payload) {
    const normalizedPayload = normalizeInspectorText(payload);
    if (!normalizedPayload)
        return null;
    try {
        const parsed = JSON.parse(normalizedPayload);
        const messages = Array.isArray(parsed.messages)
            ? parsed.messages
            : Array.isArray(parsed.input)
                ? parsed.input
                : [];
        for (let i = messages.length - 1; i >= 0; i--) {
            const message = messages[i];
            const role = String(message?.role || "").toLowerCase();
            if (role !== "user")
                continue;
            const extracted = joinExtractedText(message?.content ?? message);
            if (extracted)
                return extracted;
        }
        return joinExtractedText(parsed.prompt ?? parsed.input ?? parsed.messages);
    }
    catch {
        return null;
    }
}
function extractLastResponseFromRawResponse(rawResponse) {
    const normalizedResponse = normalizeInspectorText(rawResponse);
    if (!normalizedResponse)
        return null;
    const parseJsonResponse = (jsonText) => {
        try {
            const parsed = JSON.parse(jsonText);
            const choices = Array.isArray(parsed.choices) ? parsed.choices : [];
            const chunks = [];
            for (const choice of choices) {
                const record = choice;
                const content = joinExtractedText(record.message) ||
                    joinExtractedText(record.delta) ||
                    joinExtractedText(record.text);
                if (content) {
                    chunks.push(content);
                }
            }
            if (chunks.length > 0) {
                return chunks.join("");
            }
            return joinExtractedText(parsed.response ?? parsed.output ?? parsed.message);
        }
        catch {
            return null;
        }
    };
    const direct = parseJsonResponse(normalizedResponse);
    if (direct)
        return direct;
    const sseChunks = [];
    for (const line of normalizedResponse.split("\n")) {
        const trimmed = line.trim();
        if (!trimmed.startsWith("data:"))
            continue;
        const data = trimmed.slice(5).trim();
        if (!data || data === "[DONE]")
            continue;
        const chunk = parseJsonResponse(data);
        if (chunk) {
            sseChunks.push(chunk);
        }
    }
    if (sseChunks.length > 0) {
        return sseChunks.join("").trim() || null;
    }
    return null;
}
function extractLastMessageByRole(messages, role) {
    for (let i = messages.length - 1; i >= 0; i--) {
        const message = messages[i];
        if (message?.role !== role)
            continue;
        const content = normalizeInspectorText(message.content);
        if (content)
            return content;
    }
    return null;
}
function toSingleLine(value, maxLength = 140) {
    const normalized = normalizeInspectorText(value);
    if (!normalized)
        return null;
    const singleLine = normalized.replace(/\s+/g, " ").trim();
    if (!singleLine)
        return null;
    return singleLine.length > maxLength
        ? `${singleLine.slice(0, maxLength)}...`
        : singleLine;
}
function getPersistentLogDetailSummary(log) {
    const details = [
        toSingleLine(log.summary, 180),
        log.error ? `Error: ${toSingleLine(log.error, 120)}` : null,
        log.payloadPreview ? `Payload: ${toSingleLine(log.payloadPreview, 90)}` : null,
        log.resultPreview ? `Result: ${toSingleLine(log.resultPreview, 90)}` : null,
        log.metadataJson ? `Metadata: ${toSingleLine(log.metadataJson, 90)}` : null,
    ]
        .filter(Boolean)
        .join(" | ");
    return details || null;
}
function formatPersistentLogEntry(log) {
    const heading = [
        `[${formatDiagnosticTime(log.createdAt)}]`,
        log.eventType || "event",
        log.stage ? `(${log.stage})` : null,
        log.status ? `- ${log.status}` : null,
    ]
        .filter(Boolean)
        .join(" ");
    const details = [
        log.source,
        log.seq != null ? `seq ${log.seq}` : null,
        log.durationMs != null ? `${log.durationMs} ms` : null,
        log.success != null ? (log.success ? "success" : "failed") : null,
        getPersistentLogDetailSummary(log),
    ]
        .filter(Boolean)
        .join(" | ");
    return details ? `${heading} | ${details}` : heading;
}
function renderPersistentLogsTable(persistentLogs) {
    return (_jsx("div", { className: "min-h-0 flex-1 overflow-x-auto overflow-y-auto rounded border border-slate-200 bg-white", children: _jsxs("table", { className: "min-w-[1100px] border-collapse text-[11px] text-slate-700", children: [_jsx("thead", { className: "sticky top-0 z-10 bg-slate-50", children: _jsxs("tr", { className: "border-b border-slate-200 text-left text-[10px] font-semibold tracking-wider text-slate-500 uppercase", children: [_jsx("th", { className: "px-2 py-2", children: "Time" }), _jsx("th", { className: "px-2 py-2", children: "Event" }), _jsx("th", { className: "px-2 py-2", children: "Stage" }), _jsx("th", { className: "px-2 py-2", children: "Status" }), _jsx("th", { className: "px-2 py-2", children: "Source" }), _jsx("th", { className: "px-2 py-2", children: "Details" })] }) }), _jsx("tbody", { children: persistentLogs.map((log) => {
                        const detailSummary = getPersistentLogDetailSummary(log) ?? "—";
                        return (_jsxs("tr", { className: "border-b border-slate-100 align-top last:border-b-0", children: [_jsx("td", { className: "max-w-32 px-2 py-1.5 whitespace-nowrap text-slate-500", children: _jsx("span", { className: "block truncate", title: formatDiagnosticTime(log.createdAt), children: formatDiagnosticTime(log.createdAt) }) }), _jsx("td", { className: "max-w-28 px-2 py-1.5 whitespace-nowrap font-medium text-slate-800", children: _jsx("span", { className: "block truncate", title: log.eventType || "event", children: log.eventType || "event" }) }), _jsx("td", { className: "max-w-24 px-2 py-1.5 whitespace-nowrap", children: _jsx("span", { className: "block truncate", title: log.stage || "—", children: log.stage || "—" }) }), _jsx("td", { className: "max-w-24 px-2 py-1.5 whitespace-nowrap", children: _jsx("span", { className: "block truncate", title: log.status || "—", children: log.status || "—" }) }), _jsx("td", { className: "max-w-28 px-2 py-1.5 whitespace-nowrap", children: _jsx("span", { className: "block truncate", title: log.source || "—", children: log.source || "—" }) }), _jsx("td", { className: "min-w-md px-2 py-1.5 whitespace-nowrap", children: _jsx("span", { className: "block truncate", title: detailSummary, children: detailSummary }) })] }, log.logId));
                    }) })] }) }));
}
function buildPersistentLogsSection(persistentLogs) {
    return {
        title: persistentLogs.length > 0
            ? `Agent logs (${persistentLogs.length})`
            : "Agent logs",
        content: persistentLogs.length > 0
            ? persistentLogs
                .map((log) => formatPersistentLogEntry(log))
                .join("\n")
            : "No persistent agent logs were recorded for this agent yet.",
        contentNode: persistentLogs.length > 0
            ? renderPersistentLogsTable(persistentLogs)
            : undefined,
    };
}
function buildDiagnosticsSections(params) {
    const { socketDiagnostics, runDiagnosticsSnapshot, serverDiagnostics, messages, payload, rawResponse, } = params;
    const summary = interpretAgentRunDiagnostics({
        socketDiagnostics,
        localSnapshot: runDiagnosticsSnapshot,
        serverDiagnostics,
    });
    const lastPrompt = extractLastPromptFromPayload(payload) ||
        extractLastMessageByRole(messages, "user");
    const lastResponse = extractLastResponseFromRawResponse(rawResponse) ||
        extractLastMessageByRole(messages, "assistant");
    const machineCapacitySection = buildMachineCapacitySection(params.agentId, serverDiagnostics);
    const sections = [
        {
            title: "Summary",
            content: lines([
                `Diagnosis: ${summary.title}`,
                summary.detail,
                `Socket: ${socketDiagnostics.readyStateLabel}`,
                `Session connected: ${yesNo(serverDiagnostics.currentSession.isConnected)}`,
                `Session subscribed: ${yesNo(serverDiagnostics.currentSession.isSubscribed)}`,
                `Server status: ${serverDiagnostics.execution.status || "unknown"}`,
                `Last seq: ${serverDiagnostics.transport.lastSeq ?? runDiagnosticsSnapshot.lastSeq ?? "—"}`,
            ]),
        },
        {
            title: "Client connection",
            content: lines([
                `Session ID: ${socketDiagnostics.sessionId || "—"}`,
                `Socket state: ${socketDiagnostics.readyStateLabel}`,
                `Reconnect count: ${socketDiagnostics.reconnectCount}`,
                `Last socket event: ${socketDiagnostics.lastEventType} @ ${formatDiagnosticTime(socketDiagnostics.lastEventAt)}`,
                `Last open: ${formatDiagnosticTime(socketDiagnostics.lastOpenAt)}`,
                `Last message: ${formatDiagnosticTime(socketDiagnostics.lastMessageAt)}`,
                `Last close: ${formatDiagnosticTime(socketDiagnostics.lastCloseAt)}`,
                socketDiagnostics.lastCloseCode != null
                    ? `Last close code: ${socketDiagnostics.lastCloseCode}`
                    : null,
                socketDiagnostics.lastCloseReason
                    ? `Last close reason: ${socketDiagnostics.lastCloseReason}`
                    : null,
                `Last error: ${formatDiagnosticTime(socketDiagnostics.lastErrorAt)}`,
                socketDiagnostics.lastErrorMessage
                    ? `Last error message: ${socketDiagnostics.lastErrorMessage}`
                    : null,
            ]),
        },
        {
            title: "Agent stream",
            content: lines([
                `Submitting: ${yesNo(runDiagnosticsSnapshot.isSubmitting)}`,
                `Connecting: ${yesNo(runDiagnosticsSnapshot.isConnecting)}`,
                `Waiting for response: ${yesNo(runDiagnosticsSnapshot.isWaitingForResponse)}`,
                `Agent thinking: ${yesNo(runDiagnosticsSnapshot.isAgentThinking)}`,
                `Executing: ${yesNo(runDiagnosticsSnapshot.isExecuting)}`,
                runDiagnosticsSnapshot.lastStatusReason
                    ? `Last status reason: ${runDiagnosticsSnapshot.lastStatusReason}`
                    : null,
                runDiagnosticsSnapshot.lastStatusMessage
                    ? `Last status message: ${runDiagnosticsSnapshot.lastStatusMessage}`
                    : null,
                `Active streaming message: ${yesNo(runDiagnosticsSnapshot.hasActiveStreaming)}`,
                `Terminal subscribed: ${yesNo(runDiagnosticsSnapshot.isSubscribed)}`,
                `Last local seq: ${runDiagnosticsSnapshot.lastSeq || "—"}`,
                `Last local event: ${runDiagnosticsSnapshot.lastEventType || "—"} @ ${formatDiagnosticTime(runDiagnosticsSnapshot.lastEventAt)}`,
            ]),
        },
        {
            title: "Tool UI state",
            content: lines([
                `Assistant messages: ${runDiagnosticsSnapshot.assistantMessageCount}`,
                `Assistant groups: ${runDiagnosticsSnapshot.assistantGroupCount}`,
                `Groups with renderable tool calls: ${runDiagnosticsSnapshot.assistantGroupsWithRenderableToolCalls}`,
                `Messages with tool calls: ${runDiagnosticsSnapshot.messagesWithToolCalls}`,
                `Total tool calls in local state: ${runDiagnosticsSnapshot.totalToolCallCount}`,
                `Incomplete tool calls in local state: ${runDiagnosticsSnapshot.incompleteToolCallCount}`,
            ]),
        },
        {
            title: "Server execution",
            content: lines([
                `Status: ${serverDiagnostics.execution.status || "unknown"}`,
                `In-memory execution: ${yesNo(serverDiagnostics.execution.isInMemoryExecution)}`,
                `Started: ${formatDiagnosticTime(serverDiagnostics.execution.startedAt)}`,
                `Completed: ${formatDiagnosticTime(serverDiagnostics.execution.completedAt)}`,
                serverDiagnostics.execution.error
                    ? `Error: ${serverDiagnostics.execution.error}`
                    : null,
                `Last message type: ${serverDiagnostics.transport.lastMessageType || "—"}`,
                `Last delta type: ${serverDiagnostics.transport.lastDeltaType || "—"}`,
                `Last status state: ${serverDiagnostics.transport.lastStatusState || "—"}`,
                `Last lifecycle event: ${serverDiagnostics.transport.lastLifecycleEventType || "—"}`,
                `Last produced: ${formatDiagnosticTime(serverDiagnostics.transport.lastProducedAt)}`,
                `Last broadcast: ${formatDiagnosticTime(serverDiagnostics.transport.lastBroadcastAt)}`,
                `Target sessions: ${serverDiagnostics.transport.targetSessionCount}`,
                `Successful sends: ${serverDiagnostics.transport.successfulSessionCount}`,
                `Failed sends: ${serverDiagnostics.transport.failedSessionCount}`,
                `Connected subscribers: ${serverDiagnostics.transport.connectedSubscriberCount}`,
                serverDiagnostics.transport.lastFailure
                    ? `Last transport failure: ${serverDiagnostics.transport.lastFailure}`
                    : null,
            ]),
        },
        ...(machineCapacitySection ? [machineCapacitySection] : []),
        buildPersistentLogsSection(serverDiagnostics.persistentLogs ?? []),
        {
            title: "Run telemetry",
            content: lines([
                `Run requested: ${formatDiagnosticTime(serverDiagnostics.lastRunRequest?.requestedAt)}`,
                `Run source: ${serverDiagnostics.lastRunRequest?.source || "—"}`,
                serverDiagnostics.lastRunRequest?.detail
                    ? `Run detail: ${serverDiagnostics.lastRunRequest.detail}`
                    : null,
                `Cancel requested: ${formatDiagnosticTime(serverDiagnostics.lastCancellation?.requestedAt)}`,
                `Cancel source: ${serverDiagnostics.lastCancellation?.source || "—"}`,
                serverDiagnostics.lastCancellation?.requestedBy
                    ? `Cancel requested by: ${serverDiagnostics.lastCancellation.requestedBy}`
                    : null,
                serverDiagnostics.lastCancellation?.reason
                    ? `Cancel reason: ${serverDiagnostics.lastCancellation.reason}`
                    : null,
                serverDiagnostics.lastCancellation?.detail
                    ? `Cancel detail: ${serverDiagnostics.lastCancellation.detail}`
                    : null,
                `Cancellation observed: ${formatDiagnosticTime(serverDiagnostics.lastCancellation?.observedAt)}`,
                `Observed by: ${serverDiagnostics.lastCancellation?.observedSource || "—"}`,
                serverDiagnostics.lastCancellation?.observedDetail
                    ? `Observed detail: ${serverDiagnostics.lastCancellation.observedDetail}`
                    : null,
            ]),
        },
        {
            title: "Current session",
            content: lines([
                `Session found: ${yesNo(serverDiagnostics.currentSession.sessionFound)}`,
                `Browser matched: ${yesNo(serverDiagnostics.currentSession.browserMatched)}`,
                `Connected: ${yesNo(serverDiagnostics.currentSession.isConnected)}`,
                `Subscribed: ${yesNo(serverDiagnostics.currentSession.isSubscribed)}`,
                `Connected at: ${formatDiagnosticTime(serverDiagnostics.currentSession.connectedAt)}`,
                `Last delivery attempt: ${formatDiagnosticTime(serverDiagnostics.currentSession.lastDelivery?.lastAttemptAt)}`,
                `Last delivery success: ${formatDiagnosticTime(serverDiagnostics.currentSession.lastDelivery?.lastSuccessAt)}`,
                `Last delivery failure: ${formatDiagnosticTime(serverDiagnostics.currentSession.lastDelivery?.lastFailureAt)}`,
                serverDiagnostics.currentSession.lastDelivery?.lastFailureReason
                    ? `Failure reason: ${serverDiagnostics.currentSession.lastDelivery.lastFailureReason}`
                    : null,
                serverDiagnostics.currentSession.lastDelivery?.lastMessageType
                    ? `Last delivered message: ${serverDiagnostics.currentSession.lastDelivery.lastMessageType}`
                    : null,
                serverDiagnostics.currentSession.lastDelivery?.lastSeq != null
                    ? `Last delivered seq: ${serverDiagnostics.currentSession.lastDelivery.lastSeq}`
                    : null,
            ]),
        },
        {
            title: "Recent client events",
            content: runDiagnosticsSnapshot.recentEvents.length > 0
                ? runDiagnosticsSnapshot.recentEvents
                    .slice()
                    .reverse()
                    .map((event) => formatAgentDiagnosticsEvent(event))
                    .join("\n")
                : "No recent client-side agent stream events were captured for this terminal.",
        },
        {
            title: "Recent tool UI events",
            content: runDiagnosticsSnapshot.recentToolUiEvents.length > 0
                ? runDiagnosticsSnapshot.recentToolUiEvents
                    .slice()
                    .reverse()
                    .map((event) => formatAgentDiagnosticsEvent(event))
                    .join("\n")
                : "No recent tool-specific UI events were captured for this terminal.",
        },
        {
            title: "Recent server events",
            content: serverDiagnostics.transport.recentEvents.length > 0
                ? serverDiagnostics.transport.recentEvents
                    .map((event) => formatAgentDiagnosticsEvent(event))
                    .join("\n")
                : "No recent server-side agent transport events were recorded.",
        },
    ];
    if (payload) {
        sections.splice(1, 0, {
            title: "Raw full prompt",
            content: payload,
        });
    }
    if (rawResponse) {
        sections.splice(payload ? 2 : 1, 0, {
            title: "Raw response",
            content: rawResponse,
        });
    }
    sections.push({
        title: "Last prompt",
        content: lastPrompt ?? "No prompt was captured for this agent run yet.",
    });
    sections.push({
        title: "Last response",
        content: lastResponse ?? "No assistant response was captured for this agent run yet.",
    });
    return sections;
}
export function AgentTerminalStatusBar({ agent, contextWindowStatus, effectiveModelName, socketDiagnostics, runDiagnosticsSnapshot, liveTotals, totalTokens, costLimit, messages, showCompressionPopover, setShowCompressionPopover, }) {
    const hasData = !!contextWindowStatus?.contextWindowTokens;
    const percentValue = hasData
        ? typeof contextWindowStatus?.contextUsedPercent === "number"
            ? contextWindowStatus.contextUsedPercent
            : 0
        : 0;
    const pct = hasData ? `${percentValue.toFixed(1)}%` : "—";
    const resolvedModelName = (contextWindowStatus?.model ||
        effectiveModelName ||
        "").trim();
    const localSummary = useMemo(() => interpretAgentRunDiagnostics({
        socketDiagnostics,
        localSnapshot: runDiagnosticsSnapshot,
    }), [runDiagnosticsSnapshot, socketDiagnostics]);
    const getContextColor = (percent) => {
        if (percent < 50)
            return "#22c55e";
        if (percent < 80)
            return "#f59e0b";
        return "#ef4444";
    };
    const contextColor = hasData
        ? getContextColor(percentValue)
        : "#9ca3af";
    const radius = 15.915;
    const formatTokens = (tokens) => {
        if (tokens >= 1000) {
            return `${(tokens / 1000).toFixed(1)}k`;
        }
        return tokens.toString();
    };
    const [hasDebugPayload, setHasDebugPayload] = useState(false);
    const hasAssistantMessages = messages.some((m) => m.role === "assistant");
    const canOpenDiagnostics = Boolean(agent?.id) && agent?.status !== "new";
    useEffect(() => {
        let cancelled = false;
        if (!agent?.id || agent.status === "new") {
            setHasDebugPayload(false);
            return () => {
                cancelled = true;
            };
        }
        getLastPayload(agent.id)
            .then(({ payload, rawResponse }) => {
            if (!cancelled) {
                setHasDebugPayload(Boolean(payload || rawResponse));
            }
        })
            .catch(() => {
            if (!cancelled) {
                setHasDebugPayload(false);
            }
        });
        return () => {
            cancelled = true;
        };
    }, [agent?.id, agent?.status, agent?.lastMessageDate, agent?.updatedDate]);
    return (_jsxs("div", { className: "mt-1 flex items-center gap-2 text-[11px] text-gray-500", children: [agent?.id && (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("div", { className: "flex cursor-help items-center justify-center", children: _jsxs("svg", { className: "h-3 w-3 shrink-0", viewBox: "0 0 36 36", "aria-hidden": "true", children: [_jsx("circle", { cx: "18", cy: "18", r: radius, fill: "none", stroke: "#e5e7eb", strokeWidth: "4" }), hasData && (_jsx("circle", { cx: "18", cy: "18", r: radius, fill: "none", stroke: contextColor, strokeWidth: "4", strokeDasharray: `${percentValue} 100`, strokeLinecap: "round", style: {
                                            transformOrigin: "center",
                                            transform: "rotate(-90deg)",
                                        } })), !hasData && (_jsx("circle", { cx: "18", cy: "18", r: radius, fill: "none", stroke: contextColor, strokeWidth: "4", strokeDasharray: "0 100", strokeLinecap: "round", opacity: 0.5 }))] }) }) }), _jsx(TooltipContent, { side: "top", sideOffset: 6, children: hasData && contextWindowStatus ? (_jsxs("div", { className: "max-w-[320px] space-y-1 text-[11px]", children: [resolvedModelName && (_jsxs("div", { children: [_jsx("span", { className: "font-semibold", children: "Model:" }), " ", resolvedModelName] })), _jsxs("div", { children: [_jsx("span", { className: "font-semibold", children: "Context window:" }), " ", formatTokens(contextWindowStatus.estimatedInputTokens || 0), " ", "/", " ", formatTokens(contextWindowStatus.contextWindowTokens), " ", "tokens"] }), _jsxs("div", { children: [_jsx("span", { className: "font-semibold", children: "Used:" }), " ", pct] })] })) : (_jsxs("div", { className: "max-w-[320px] space-y-1 text-[11px]", children: [resolvedModelName && (_jsxs("div", { children: [_jsx("span", { className: "font-semibold", children: "Model:" }), " ", resolvedModelName] })), _jsx("div", { children: "Context window usage will appear here when the agent starts processing." })] })) })] })), agent?.compressionMarkerIndex != null && (_jsxs(Popover, { open: showCompressionPopover, onOpenChange: setShowCompressionPopover, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx("button", { type: "button", className: "border-theme-secondary/20 bg-theme-secondary-light/50 text-theme-secondary hover:bg-theme-secondary-light flex cursor-pointer items-center rounded border px-2 py-0.5 text-[11px] transition-colors", onClick: () => setShowCompressionPopover(!showCompressionPopover), children: "Compressed" }) }), _jsx(PopoverContent, { className: "w-96 p-4", align: "start", side: "top", children: _jsxs("div", { className: "space-y-3", children: [_jsxs("div", { children: [_jsx("h3", { className: "text-[10px] font-semibold text-gray-900", children: "Conversation Compressed" }), _jsxs("p", { className: "mt-1 text-[11px] text-gray-600", children: ["First ", agent.compressionMarkerIndex, " messages have been summarized to reduce context usage."] })] }), agent.compressedSummary && (_jsxs("div", { className: "space-y-1", children: [_jsx("div", { className: "text-[11px] font-medium text-gray-700", children: "Summary:" }), _jsx("div", { className: "max-h-64 overflow-y-auto rounded border border-gray-200 bg-gray-50 p-3 text-[11px] whitespace-pre-wrap text-gray-700", children: agent.compressedSummary })] }))] }) })] })), _jsx(AgentCostDisplay, { totalTokens: liveTotals
                    ? {
                        input: liveTotals.input,
                        output: liveTotals.output,
                        cached: liveTotals.cached,
                        cacheWrite: liveTotals.cacheWrite ?? 0,
                        inputCost: liveTotals.inputCost,
                        outputCost: liveTotals.outputCost,
                        cachedCost: liveTotals.cachedCost,
                        cacheWriteCost: liveTotals.cacheWriteCost ?? 0,
                        imageCost: liveTotals.imageCost ?? 0,
                        totalCost: liveTotals.totalCost,
                    }
                    : totalTokens, costLimit: costLimit }), agent?.id && (_jsxs(Tooltip, { children: [_jsx(ContentInspectorPopover, { title: "Run diagnostics", emptyMessage: "No diagnostics are available for this agent yet.", downloadFileName: `agent-${agent.id}-diagnostics.txt`, loadSections: async () => {
                            if (!agent?.id)
                                return [];
                            const [diagnosticsResult, payloadResult] = await Promise.allSettled([
                                getAgentDiagnostics(agent.id, socketDiagnostics.sessionId),
                                getLastPayload(agent.id),
                            ]);
                            if (diagnosticsResult.status !== "fulfilled") {
                                throw diagnosticsResult.reason;
                            }
                            const payload = payloadResult.status === "fulfilled"
                                ? payloadResult.value.payload
                                : "";
                            const rawResponse = payloadResult.status === "fulfilled"
                                ? payloadResult.value.rawResponse
                                : "";
                            return buildDiagnosticsSections({
                                agentId: agent.id,
                                socketDiagnostics,
                                runDiagnosticsSnapshot,
                                serverDiagnostics: diagnosticsResult.value,
                                messages,
                                payload,
                                rawResponse,
                            });
                        }, trigger: _jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { type: "button", "data-testid": "agent-diagnostics-button", disabled: !canOpenDiagnostics, className: "flex items-center text-[10px] text-gray-400 hover:text-gray-600 disabled:cursor-not-allowed disabled:opacity-30", children: _jsx(Bug, { className: "h-3 w-3", strokeWidth: 1.5 }) }) }) }), _jsx(TooltipContent, { side: "top", sideOffset: 6, children: !canOpenDiagnostics
                            ? "Available after the agent starts"
                            : hasAssistantMessages
                                ? `${localSummary.title}: open diagnostics`
                                : hasDebugPayload
                                    ? "Inspect socket, stream, server, and provider diagnostics"
                                    : "Inspect socket, stream, and server diagnostics" })] }))] }));
}
//# sourceMappingURL=AgentTerminalStatusBar.js.map