import { f as store_get, u as unsubscribe_stores, d as bind_props, h as head, e as ensure_array_like, a as attr, b as attr_class } from './index2-BuOY2QE4.js';
import { a1 as fallback, X as escape_html, Y as getContext } from './context-zH5kvtGY.js';
import './utils-KcIDVAAe.js';
import './state.svelte-DtOGaiYC.js';
import { T as TelescopeClient, g as getPersistedTelescopeSourceId, m as mockGenerator } from './source-selection-Dx7LqMVs.js';
import { B as Button } from './Button-DZYrr6c0.js';
import { C as ChatApiCallTrace, b as ChatStepTrace, a as ChatConversationalTrace, D as Dropdown } from './ChatStepTrace-B5HQ8Zv3.js';
import { I as Icon, h as html } from './Icon-BgknHaZs.js';
import { M as Modal } from './Modal-D4tx0Bdo.js';
import 'zod';
import './trpc-client-Bucti7HD.js';
import '@trpc/client';
import './index-server-CefdgakO.js';
import './events-M0vvlm3M.js';

const getStores = () => {
  const stores$1 = getContext("__svelte__");
  return {
    /** @type {typeof page} */
    page: {
      subscribe: stores$1.page.subscribe
    },
    /** @type {typeof navigating} */
    navigating: {
      subscribe: stores$1.navigating.subscribe
    },
    /** @type {typeof updated} */
    updated: stores$1.updated
  };
};
const page = {
  subscribe(fn) {
    const store = getStores().page;
    return store.subscribe(fn);
  }
};
function CopyTracesDropdown($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let {
      disabled = false,
      getWithPromptsText,
      getWithoutPromptsText,
      dropdownId = "copy-traces-dropdown"
    } = $$props;
    let open = false;
    let anchorEl = null;
    let copied = null;
    let timer = null;
    async function copy(mode) {
      try {
        const text = mode === "with-prompts" ? getWithPromptsText() : getWithoutPromptsText();
        await navigator.clipboard.writeText(text);
        copied = mode;
        if (timer) clearTimeout(timer);
        timer = window.setTimeout(
          () => {
            copied = null;
            timer = null;
          },
          2e3
        );
      } catch (e) {
        console.error("Failed to copy traces", e);
      }
    }
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      $$renderer3.push(`<div>`);
      Button($$renderer3, {
        variant: "secondary",
        size: "small",
        disabled,
        "aria-expanded": open,
        "aria-haspopup": "listbox",
        "aria-controls": dropdownId,
        onclick: (e) => {
          e.stopPropagation();
          open = !open;
        },
        class: "flex items-center gap-1",
        get el() {
          return anchorEl;
        },
        set el($$value) {
          anchorEl = $$value;
          $$settled = false;
        },
        children: ($$renderer4) => {
          if (copied === "without-prompts") {
            $$renderer4.push("<!--[-->");
            $$renderer4.push(`Copied traces (without prompts)`);
          } else {
            $$renderer4.push("<!--[!-->");
            if (copied === "with-prompts") {
              $$renderer4.push("<!--[-->");
              $$renderer4.push(`Copied traces (with prompts)`);
            } else {
              $$renderer4.push("<!--[!-->");
              $$renderer4.push(`Copy traces`);
            }
            $$renderer4.push(`<!--]-->`);
          }
          $$renderer4.push(`<!--]--> `);
          Icon($$renderer4, {
            name: "chevron-down",
            class: "size-5 text-rc-gray-400 transition-transform duration-200 " + (open ? "rotate-180" : "")
          });
          $$renderer4.push(`<!---->`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----> `);
      {
        let children = function($$renderer4) {
          $$renderer4.push(`<div class="mt-1 overflow-hidden rounded-lg border border-rc-gray-110 bg-rc-gray-930 shadow-inner-white-soft backdrop-blur-2xl" role="listbox">`);
          Button($$renderer4, {
            variant: "ghost",
            size: "small",
            role: "option",
            onclick: (e) => {
              e.stopPropagation();
              open = false;
              copy("without-prompts");
            },
            class: "w-full rounded-none border-b border-rc-gray-110 py-2 pr-3 text-left backdrop-blur-2xl hover:bg-rc-gray-700 focus:bg-rc-gray-400",
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->Without prompts`);
            },
            $$slots: { default: true }
          });
          $$renderer4.push(`<!----> `);
          Button($$renderer4, {
            variant: "ghost",
            size: "small",
            role: "option",
            onclick: (e) => {
              e.stopPropagation();
              open = false;
              copy("with-prompts");
            },
            class: "w-full rounded-none py-2 pr-3 text-left backdrop-blur-2xl hover:bg-rc-gray-700 focus:bg-rc-gray-400",
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->With prompts`);
            },
            $$slots: { default: true }
          });
          $$renderer4.push(`<!----></div>`);
        };
        Dropdown($$renderer3, {
          id: dropdownId,
          open,
          onClose: () => open = false,
          anchorEl,
          placement: "bottom-end",
          offset: [0, 1],
          children
        });
      }
      $$renderer3.push(`<!----></div>`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
  });
}
function CollapseExpand($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let value = fallback($$props["value"], "");
    let limit = fallback($$props["limit"], 200);
    let maxLines = fallback($$props["maxLines"], null);
    let className = fallback($$props["className"], "");
    let collapsedLabel = fallback($$props["collapsedLabel"], "...more");
    let initiallyExpanded = fallback($$props["initiallyExpanded"], false);
    let stopPropagation = fallback($$props["stopPropagation"], true);
    let expanded = fallback($$props["expanded"], initiallyExpanded);
    let treatPlainText = fallback($$props["treatPlainText"], false);
    let highlightPrompt = fallback($$props["highlightPrompt"], false);
    function escapeHtml(text) {
      return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    }
    function highlightPromptText(raw) {
      const s = normalizeNewlines(raw);
      let html2 = escapeHtml(s);
      const curlyBlocks = [];
      html2 = html2.replace(/(\{+[\s\S]*?\}+)/g, (match) => {
        const id = curlyBlocks.length;
        curlyBlocks.push(match);
        return `__CURLY${id}__`;
      });
      html2 = html2.replace(/^(\s*#.*)$/gm, '<span class="prompt-heading">$1</span>');
      html2 = html2.replace(/(&lt;[^&]*?&gt;)/g, '<span class="mtk8">$1</span>');
      html2 = html2.replace(/^(\s*)(\d+)([.)])(\s+)/gm, (_match, p1, p2, p3, p4) => `${p1}<span class="mtk8">${p2}${p3}</span>${p4}`);
      curlyBlocks.forEach((block, idx) => {
        const highlighted = `<span class="mtk5">${block}</span>`;
        html2 = html2.replace(`__CURLY${idx}__`, highlighted);
      });
      html2 = html2.replace(/\n/g, "<br/>");
      return html2;
    }
    function normalizeNewlines(s) {
      let result = s.replace(/\r\n/g, "\n");
      result = result.replace(/\\n/g, "\n");
      return result;
    }
    function getPlain(v) {
      try {
        if (Array.isArray(v)) {
          const s = v.map((s2) => s2?.text ?? s2?.content ?? JSON.stringify(s2)).join(" ");
          return normalizeNewlines(s);
        }
        if (typeof v === "string") {
          try {
            const parsed = JSON.parse(v);
            if (Array.isArray(parsed)) {
              const s = parsed.map((s2) => s2?.text ?? s2?.content ?? JSON.stringify(s2)).join(" ");
              return normalizeNewlines(s);
            }
            return normalizeNewlines(v);
          } catch {
            return normalizeNewlines(v);
          }
        }
        return normalizeNewlines(JSON.stringify(v));
      } catch {
        return normalizeNewlines(String(v ?? ""));
      }
    }
    function getFull(v) {
      try {
        if (Array.isArray(v)) {
          const s = v.map((s2) => s2?.text ?? s2?.content ?? JSON.stringify(s2)).join("\n");
          return normalizeNewlines(s);
        }
        if (typeof v === "string") {
          try {
            const parsed = JSON.parse(v);
            if (Array.isArray(parsed)) {
              const s = parsed.map((s2) => s2?.text ?? s2?.content ?? JSON.stringify(s2)).join("\n");
              return normalizeNewlines(s);
            }
            return normalizeNewlines(v);
          } catch {
            return normalizeNewlines(v);
          }
        }
        return normalizeNewlines(JSON.stringify(v, null, 2));
      } catch {
        return normalizeNewlines(String(v ?? ""));
      }
    }
    function parseLine(raw) {
      const s = normalizeNewlines(raw);
      const lines = s.split(/\n+/).map((l) => l.trim()).filter((l) => l.length > 0);
      const segments2 = [];
      let currentRole = void 0;
      let currentText = "";
      for (const line of lines) {
        const m = line.match(/^(user|assistant|system|customer|caller|tool|model|agent)\s*[:\-]\s*(.*)$/i);
        if (m) {
          if (currentText) {
            segments2.push({ text: currentText, role: currentRole });
          }
          currentRole = m[1].toLowerCase();
          currentText = m[2] ?? "";
        } else {
          if (currentText) {
            currentText += "\n" + line;
          } else {
            currentText = line;
          }
        }
      }
      if (currentText) {
        segments2.push({ text: currentText, role: currentRole });
      }
      return segments2;
    }
    function asSegments(v) {
      try {
        let raw = v;
        if (typeof v === "string") {
          try {
            raw = JSON.parse(v);
          } catch {
            if (!treatPlainText) return [];
            return parseLine(v);
          }
        }
        if (!Array.isArray(raw)) {
          if (Array.isArray(raw?.messages)) {
            raw = raw.messages;
          } else {
            return [];
          }
        }
        return raw.map((s) => {
          let text;
          if (s?.text != null) {
            text = String(s.text);
          } else if (s?.content != null) {
            if (Array.isArray(s.content)) {
              text = s.content.map((part) => {
                if (typeof part === "string") return part;
                if (typeof part?.text === "string") return part.text;
                if (typeof part?.text?.value === "string") return part.text.value;
                return JSON.stringify(part);
              }).join(" ");
            } else if (typeof s.content === "string") {
              text = s.content;
            } else {
              text = JSON.stringify(s.content);
            }
          } else if (typeof s === "string") {
            text = s;
          } else {
            text = JSON.stringify(s);
          }
          return {
            text: normalizeNewlines(text),
            role: s?.role,
            time: s?.time,
            duration: s?.duration
          };
        }).filter((s) => s.text && String(s.text).trim().length > 0);
      } catch {
        return [];
      }
    }
    const plain = () => getPlain(value);
    const full = () => getFull(value);
    const plainLines = () => plain().split("\n");
    const segments = () => asSegments(value);
    const hasStructuredTranscript = () => segments().length > 0;
    const isLong = () => {
      if (maxLines != null) {
        return plainLines().length > maxLines;
      }
      return plain().length > limit;
    };
    const collapsedText = () => {
      const p = plain();
      if (!isLong()) return p;
      if (maxLines != null) {
        return plainLines().slice(0, maxLines).join("\n");
      }
      return p.slice(0, limit);
    };
    function formatTime(raw) {
      if (!raw) return null;
      try {
        const d = new Date(raw);
        if (Number.isNaN(d.getTime())) return raw;
        return d.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit", second: "2-digit" });
      } catch {
        return raw;
      }
    }
    function formatDuration(raw) {
      if (raw == null || !Number.isFinite(raw)) return null;
      const total = Number(raw);
      const totalSec = Math.floor(total);
      const m = Math.floor(totalSec / 60);
      const s = totalSec % 60;
      const mm = String(m).padStart(2, "0");
      const ss = String(s).padStart(2, "0");
      return `${mm}:${ss}`;
    }
    function normalizeRole(role) {
      if (!role) return "Assistant";
      const r = role.trim();
      if (!r) return "Assistant";
      return r.charAt(0).toUpperCase() + r.slice(1);
    }
    function isUserRole(role) {
      const r = role?.toLowerCase() ?? "";
      return r === "user" || r === "customer" || r === "caller";
    }
    function splitSystem(text) {
      const system = [];
      const main = text.replace(/<([^>]+)>/g, (_m, inner) => {
        const cleaned = String(inner).trim();
        if (cleaned) system.push(cleaned);
        return "";
      }).trim();
      return { main, system };
    }
    if (expanded) {
      $$renderer2.push("<!--[-->");
      if (hasStructuredTranscript()) {
        $$renderer2.push("<!--[-->");
        $$renderer2.push(`<div class="space-y-3"><!--[-->`);
        const each_array = ensure_array_like(segments());
        for (let $$index_1 = 0, $$length = each_array.length; $$index_1 < $$length; $$index_1++) {
          let seg = each_array[$$index_1];
          const userSide = isUserRole(seg.role);
          const isSystem = (seg.role ?? "").toLowerCase() === "system";
          const parts = splitSystem(seg.text);
          const t = formatTime(seg.time);
          const d = formatDuration(seg.duration);
          $$renderer2.push(`<div${attr_class(`flex ${userSide ? "justify-end" : "justify-start"}`)}><div${attr_class(`max-w-[70%] break-words rounded-md px-3 py-2 text-sm shadow-sm ${userSide ? "bg-rc-gray-600 text-rc-gray-100" : "bg-rc-gray-700 text-rc-gray-100"}`)}><div${attr_class(`my-1 text-xs font-semibold uppercase ${isSystem ? "text-rc-blue " + (userSide ? "text-right" : "text-left") : "text-rc-green-200 " + (userSide ? "text-right" : "text-left")}`)}>${escape_html(normalizeRole(seg.role))}</div> <div${attr_class(`whitespace-pre-wrap break-words py-1 text-sm ${userSide ? "text-justify" : "text-left"} ${isSystem ? "italic text-rc-gray-200" : ""}`)}>`);
          if (parts.main) {
            $$renderer2.push("<!--[-->");
            $$renderer2.push(`<div>${escape_html(parts.main)}</div>`);
          } else {
            $$renderer2.push("<!--[!-->");
          }
          $$renderer2.push(`<!--]--> <!--[-->`);
          const each_array_1 = ensure_array_like(parts.system);
          for (let $$index = 0, $$length2 = each_array_1.length; $$index < $$length2; $$index++) {
            let sys = each_array_1[$$index];
            $$renderer2.push(`<div class="mt-1 whitespace-pre-wrap break-words text-xs italic text-rc-gray-200">&lt;${escape_html(sys)}></div>`);
          }
          $$renderer2.push(`<!--]--></div> `);
          if (t || d) {
            $$renderer2.push("<!--[-->");
            $$renderer2.push(`<div${attr_class(`mt-1 text-xs text-rc-gray-300 ${userSide ? "text-right" : "text-left"}`)}>`);
            if (t) {
              $$renderer2.push("<!--[-->");
              $$renderer2.push(`${escape_html(t)}`);
            } else {
              $$renderer2.push("<!--[!-->");
            }
            $$renderer2.push(`<!--]--> `);
            if (t && d) {
              $$renderer2.push("<!--[-->");
              $$renderer2.push(`·`);
            } else {
              $$renderer2.push("<!--[!-->");
            }
            $$renderer2.push(`<!--]--> `);
            if (d) {
              $$renderer2.push("<!--[-->");
              $$renderer2.push(`${escape_html(d)}`);
            } else {
              $$renderer2.push("<!--[!-->");
            }
            $$renderer2.push(`<!--]--></div>`);
          } else {
            $$renderer2.push("<!--[!-->");
          }
          $$renderer2.push(`<!--]--></div></div>`);
        }
        $$renderer2.push(`<!--]--></div>`);
      } else {
        $$renderer2.push("<!--[!-->");
        $$renderer2.push(`<div class="whitespace-pre-wrap break-words">`);
        if (highlightPrompt) {
          $$renderer2.push("<!--[-->");
          $$renderer2.push(`${html(highlightPromptText(full()))}`);
        } else {
          $$renderer2.push("<!--[!-->");
          $$renderer2.push(`${escape_html(full())}`);
        }
        $$renderer2.push(`<!--]--></div>`);
      }
      $$renderer2.push(`<!--]-->`);
    } else {
      $$renderer2.push("<!--[!-->");
      $$renderer2.push(`<div${attr_class(`mt-1 cursor-text select-text rounded bg-rc-gray-900 p-2 text-sm text-rc-gray-200 ${className}`)}><span class="whitespace-pre-wrap break-words">`);
      if (highlightPrompt) {
        $$renderer2.push("<!--[-->");
        $$renderer2.push(`${html(highlightPromptText(collapsedText()))}`);
      } else {
        $$renderer2.push("<!--[!-->");
        $$renderer2.push(`${escape_html(collapsedText())}`);
      }
      $$renderer2.push(`<!--]--></span> `);
      if (isLong()) {
        $$renderer2.push("<!--[-->");
        $$renderer2.push(`<button class="inline-flex text-sm text-rc-green-200 hover:text-rc-green-100">${escape_html(collapsedLabel)}</button>`);
      } else {
        $$renderer2.push("<!--[!-->");
      }
      $$renderer2.push(`<!--]--></div>`);
    }
    $$renderer2.push(`<!--]-->`);
    bind_props($$props, {
      value,
      limit,
      maxLines,
      className,
      collapsedLabel,
      initiallyExpanded,
      stopPropagation,
      expanded,
      treatPlainText,
      highlightPrompt
    });
  });
}
function _page($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    var $$store_subs;
    let useMock = fallback($$props["useMock"], false);
    const client = new TelescopeClient(fetch);
    client.setSourceId(getPersistedTelescopeSourceId() ?? void 0);
    let traces = [];
    let renderableTraces = [];
    let tracesLoading = false;
    let tracesLoadingMore = false;
    let tracesError = null;
    let lastLoadedConversationId = null;
    let lastTraceId = null;
    let hasMoreTraces = false;
    let conversation = null;
    let conversationLoading = false;
    let conversationError = null;
    let recordingOpen = false;
    let transcriptOpen = false;
    let tracesRequestId = 0;
    let conversationRequestId = 0;
    function normalizeNonEmptyString(value) {
      if (typeof value !== "string") return null;
      const trimmed = value.trim();
      return trimmed ? trimmed : null;
    }
    function dedupeTracesByTraceId(items) {
      const seen = /* @__PURE__ */ new Set();
      return items.filter((trace) => {
        const id = normalizeNonEmptyString(trace?.traceId);
        if (!id) return true;
        if (seen.has(id)) return false;
        seen.add(id);
        return true;
      });
    }
    function tracesForCopy(includePrompts) {
      if (includePrompts) return traces;
      return traces.map((trace) => {
        if (trace.traceType !== "STEP") return trace;
        const {
          receivedPrompt: _receivedPrompt,
          renderedPrompt: _renderedPrompt,
          ...rest
        } = trace;
        return rest;
      });
    }
    function getPromptForDiff(trace) {
      if (!trace) return null;
      if (typeof trace.renderedPrompt === "string") return trace.renderedPrompt;
      return null;
    }
    function findMainComparisonTrace(items, index) {
      for (let i = index - 1; i >= 0; i--) {
        const trace = items[i];
        if (trace.traceType !== "STEP") continue;
        const step = trace;
        if (step.name === "main" && getPromptForDiff(step)) return step;
      }
      for (let i = index - 1; i >= 0; i--) {
        const trace = items[i];
        if (trace.traceType !== "STEP") continue;
        const step = trace;
        if (step.name === "prewarm" && getPromptForDiff(step)) return step;
      }
      return null;
    }
    function hasRecording(conv) {
      return !!(conv?.audioUrl && String(conv.audioUrl).trim());
    }
    function hasTranscript(conv) {
      const transcript = conv?.transcript;
      if (typeof transcript === "string") return transcript.trim() !== "";
      if (Array.isArray(transcript)) return transcript.length > 0;
      return false;
    }
    function transcriptToText(conv) {
      const transcript = conv?.transcript;
      if (!transcript) return "";
      if (typeof transcript === "string") return transcript;
      if (Array.isArray(transcript)) {
        return transcript.map((seg) => {
          const time = typeof seg?.time === "string" ? seg.time : "";
          const role = typeof seg?.role === "string" ? seg.role : "";
          const text = typeof seg?.text === "string" ? seg.text : "";
          const header = [time, role].filter(Boolean).join(" • ");
          return header ? `${header}
${text}` : text;
        }).join("\n\n");
      }
      return "";
    }
    async function copyTranscript() {
      try {
        await navigator.clipboard.writeText(transcriptToText(conversation));
      } catch (e) {
        console.error("Failed to copy transcript", e);
      }
    }
    async function copyRecordingUrl() {
      try {
        const url = conversation?.audioUrl;
        if (!url) return;
        await navigator.clipboard.writeText(url);
      } catch (e) {
        console.error("Failed to copy recording URL", e);
      }
    }
    function isRenderableConversationalMessage(trace) {
      if (trace.traceType !== "CONVERSATIONAL") return false;
      return trace.eventName === "received-message" || trace.eventName === "llm-handler-stream-requested" || trace.eventName === "finished-main-streaming-step" || trace.eventName === "sent-message" || trace.eventName === "transfer-requested";
    }
    const MONTHS_SHORT = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ];
    function dateKey(ms) {
      if (typeof ms !== "number" || !Number.isFinite(ms)) return null;
      const d = new Date(ms);
      if (Number.isNaN(d.getTime())) return null;
      const yyyy = d.getFullYear();
      const mm = String(d.getMonth() + 1).padStart(2, "0");
      const dd = String(d.getDate()).padStart(2, "0");
      return `${yyyy}-${mm}-${dd}`;
    }
    function formatDateLabel(ms) {
      if (typeof ms !== "number" || !Number.isFinite(ms)) return null;
      const d = new Date(ms);
      if (Number.isNaN(d.getTime())) return null;
      const day = d.getDate();
      const month = MONTHS_SHORT[d.getMonth()];
      const year = d.getFullYear();
      return `${day} ${month} ${year}`;
    }
    async function loadConversation(conversationId) {
      const requestId = ++conversationRequestId;
      conversationLoading = true;
      conversationError = null;
      conversation = null;
      try {
        if (useMock) {
          return;
        }
        const resp = await client.getConversation(conversationId);
        if (requestId !== conversationRequestId) return;
        conversation = resp;
      } catch (e) {
        if (requestId !== conversationRequestId) return;
        conversationError = e.message;
        conversation = null;
      } finally {
        if (requestId !== conversationRequestId) return;
        conversationLoading = false;
      }
    }
    async function loadTraces(conversationId) {
      if (!conversationId || conversationId === lastLoadedConversationId) return;
      const requestId = ++tracesRequestId;
      lastLoadedConversationId = conversationId;
      tracesLoading = true;
      tracesLoadingMore = false;
      tracesError = null;
      lastTraceId = null;
      hasMoreTraces = false;
      recordingOpen = false;
      transcriptOpen = false;
      void loadConversation(conversationId);
      try {
        let items = [];
        let nextLastTraceId = null;
        let nextHasMoreTraces = false;
        if (useMock) {
          items = (await mockGenerator.fetchTraces(conversationId)).items ?? [];
        } else {
          const resp = await client.getTraces(conversationId, 100);
          items = resp.items ?? [];
          nextLastTraceId = resp.lastTraceId ?? null;
          nextHasMoreTraces = nextLastTraceId != null;
        }
        if (requestId !== tracesRequestId) return;
        lastTraceId = nextLastTraceId;
        hasMoreTraces = nextHasMoreTraces;
        traces = dedupeTracesByTraceId(items).slice().sort((a, b) => a.createdAt - b.createdAt);
      } catch (e) {
        if (requestId !== tracesRequestId) return;
        tracesError = e.message;
        traces = [];
        console.error("Failed to load traces:", e);
      } finally {
        if (requestId !== tracesRequestId) return;
        tracesLoading = false;
      }
    }
    async function loadMoreTraces() {
      if (!lastLoadedConversationId || !lastTraceId || tracesLoadingMore) return;
      const conversationId = lastLoadedConversationId;
      const requestId = tracesRequestId;
      tracesLoadingMore = true;
      tracesError = null;
      try {
        const resp = await client.getTraces(conversationId, 100, lastTraceId);
        const items = resp.items ?? [];
        if (conversationId !== lastLoadedConversationId || requestId !== tracesRequestId) return;
        const nextLastTraceId = resp.lastTraceId ?? null;
        lastTraceId = nextLastTraceId;
        hasMoreTraces = nextLastTraceId != null;
        traces = dedupeTracesByTraceId(traces.concat(items)).slice().sort((a, b) => a.createdAt - b.createdAt);
      } catch (e) {
        if (conversationId !== lastLoadedConversationId || requestId !== tracesRequestId) return;
        tracesError = e.message;
        console.error("Failed to load more traces:", e);
      } finally {
        if (conversationId !== lastLoadedConversationId || requestId !== tracesRequestId) return;
        tracesLoadingMore = false;
      }
    }
    renderableTraces = traces.filter((trace) => {
      return trace.traceType === "API_CALL" || trace.traceType === "STEP" || isRenderableConversationalMessage(trace);
    });
    {
      const cid = store_get($$store_subs ??= {}, "$page", page).params.conversationId;
      if (cid && cid !== lastLoadedConversationId) {
        loadTraces(cid);
      }
    }
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      head($$renderer3, ($$renderer4) => {
        $$renderer4.title(($$renderer5) => {
          $$renderer5.push(`<title>Bosun: Telescope</title>`);
        });
      });
      $$renderer3.push(`<div class="flex h-full w-full flex-col bg-rc-gray-700"><div class="flex-none border-b border-rc-gray-300/40 p-4"><div class="flex flex-wrap items-start justify-between gap-3"><h2 class="text-lg font-semibold text-rc-gray-100">Traces `);
      if (store_get($$store_subs ??= {}, "$page", page).params.conversationId) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<span class="text-rc-gray-100">for conversation Id:</span> <span class="text-rc-green-200">${escape_html(store_get($$store_subs ??= {}, "$page", page).params.conversationId)}</span>`);
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]--></h2> `);
      if (store_get($$store_subs ??= {}, "$page", page).params.conversationId) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<div class="flex flex-wrap items-center gap-2">`);
        if (hasRecording(conversation)) {
          $$renderer3.push("<!--[-->");
          Button($$renderer3, {
            variant: "secondary",
            size: "small",
            onclick: () => recordingOpen = true,
            children: ($$renderer4) => {
              $$renderer4.push(`<!---->Recording`);
            },
            $$slots: { default: true }
          });
        } else {
          $$renderer3.push("<!--[!-->");
        }
        $$renderer3.push(`<!--]--> `);
        if (hasTranscript(conversation)) {
          $$renderer3.push("<!--[-->");
          Button($$renderer3, {
            variant: "secondary",
            size: "small",
            onclick: () => transcriptOpen = true,
            children: ($$renderer4) => {
              $$renderer4.push(`<!---->Transcript`);
            },
            $$slots: { default: true }
          });
        } else {
          $$renderer3.push("<!--[!-->");
        }
        $$renderer3.push(`<!--]--> `);
        CopyTracesDropdown($$renderer3, {
          disabled: !traces.length || tracesLoading,
          getWithPromptsText: () => JSON.stringify(tracesForCopy(true), null, 2),
          getWithoutPromptsText: () => JSON.stringify(tracesForCopy(false), null, 2)
        });
        $$renderer3.push(`<!----></div>`);
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]--></div> `);
      if (conversationLoading) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<div class="mt-2 text-sm text-rc-gray-400">Loading call details…</div>`);
      } else {
        $$renderer3.push("<!--[!-->");
        if (conversationError) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<div class="mt-2 text-sm text-rc-gray-300">Call details unavailable: ${escape_html(conversationError)}</div>`);
        } else {
          $$renderer3.push("<!--[!-->");
        }
        $$renderer3.push(`<!--]-->`);
      }
      $$renderer3.push(`<!--]--></div> <div class="rc-scroll min-h-0 flex-1 overflow-scroll p-4">`);
      if (!store_get($$store_subs ??= {}, "$page", page).params.conversationId) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<div class="py-8 text-center text-rc-gray-300">No conversation selected</div>`);
      } else {
        $$renderer3.push("<!--[!-->");
        if (tracesLoading) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<div class="py-8 text-center text-rc-gray-200">Loading traces...</div>`);
        } else {
          $$renderer3.push("<!--[!-->");
          if (tracesError) {
            $$renderer3.push("<!--[-->");
            $$renderer3.push(`<div class="z-50 py-8 text-center text-red-400">Error: ${escape_html(tracesError)}</div>`);
          } else {
            $$renderer3.push("<!--[!-->");
            if (!renderableTraces.length) {
              $$renderer3.push("<!--[-->");
              $$renderer3.push(`<div class="py-8 text-center text-rc-gray-300">No traces found</div>`);
            } else {
              $$renderer3.push("<!--[!-->");
              $$renderer3.push(`<div><!--[-->`);
              const each_array = ensure_array_like(renderableTraces);
              for (let idx = 0, $$length = each_array.length; idx < $$length; idx++) {
                let trace = each_array[idx];
                const current = dateKey(trace.createdAt);
                const previous = idx > 0 ? dateKey(renderableTraces[idx - 1].createdAt) : null;
                const label = formatDateLabel(trace.createdAt);
                if (current && label && current !== previous) {
                  $$renderer3.push("<!--[-->");
                  $$renderer3.push(`<div class="my-3 flex w-full justify-center"><div class="rounded-full border border-rc-gray-650 bg-rc-gray-900/40 px-3 py-1 text-xs text-rc-gray-200">${escape_html(label)}</div></div>`);
                } else {
                  $$renderer3.push("<!--[!-->");
                }
                $$renderer3.push(`<!--]--> `);
                if (trace.traceType === "API_CALL") {
                  $$renderer3.push("<!--[-->");
                  ChatApiCallTrace($$renderer3, { trace });
                } else {
                  $$renderer3.push("<!--[!-->");
                  if (trace.traceType === "STEP") {
                    $$renderer3.push("<!--[-->");
                    ChatStepTrace($$renderer3, {
                      trace,
                      compareTrace: trace.name === "main" ? findMainComparisonTrace(renderableTraces, idx) : null
                    });
                  } else {
                    $$renderer3.push("<!--[!-->");
                    ChatConversationalTrace($$renderer3, { trace, context: null, agentId: void 0 });
                  }
                  $$renderer3.push(`<!--]-->`);
                }
                $$renderer3.push(`<!--]-->`);
              }
              $$renderer3.push(`<!--]--></div> `);
              if (hasMoreTraces) {
                $$renderer3.push("<!--[-->");
                $$renderer3.push(`<div class="mt-3 flex justify-center">`);
                Button($$renderer3, {
                  variant: "secondary",
                  size: "small",
                  disabled: tracesLoadingMore,
                  onclick: loadMoreTraces,
                  children: ($$renderer4) => {
                    $$renderer4.push(`<!---->${escape_html(tracesLoadingMore ? "Loading more…" : "Load more")}`);
                  },
                  $$slots: { default: true }
                });
                $$renderer3.push(`<!----></div>`);
              } else {
                $$renderer3.push("<!--[!-->");
              }
              $$renderer3.push(`<!--]-->`);
            }
            $$renderer3.push(`<!--]-->`);
          }
          $$renderer3.push(`<!--]-->`);
        }
        $$renderer3.push(`<!--]-->`);
      }
      $$renderer3.push(`<!--]--></div></div> `);
      if (recordingOpen && hasRecording(conversation)) {
        $$renderer3.push("<!--[-->");
        {
          let children = function($$renderer4) {
            $$renderer4.push(`<audio class="w-full" controls${attr("src", conversation?.audioUrl)}></audio> <div class="mt-3 break-all text-sm text-rc-gray-300">${escape_html(conversation?.audioUrl)}</div>`);
          }, footer = function($$renderer4) {
            Button($$renderer4, {
              variant: "secondary",
              size: "small",
              onclick: copyRecordingUrl,
              children: ($$renderer5) => {
                $$renderer5.push(`<!---->Copy URL`);
              },
              $$slots: { default: true }
            });
            $$renderer4.push(`<!----> `);
            Button($$renderer4, {
              variant: "secondary",
              size: "small",
              onclick: () => recordingOpen = false,
              children: ($$renderer5) => {
                $$renderer5.push(`<!---->Close`);
              },
              $$slots: { default: true }
            });
            $$renderer4.push(`<!---->`);
          };
          Modal($$renderer3, {
            title: "Recording",
            class: "!max-w-3xl",
            get open() {
              return recordingOpen;
            },
            set open($$value) {
              recordingOpen = $$value;
              $$settled = false;
            },
            children,
            footer,
            $$slots: { default: true, footer: true }
          });
        }
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]--> `);
      if (transcriptOpen && hasTranscript(conversation)) {
        $$renderer3.push("<!--[-->");
        {
          let children = function($$renderer4) {
            $$renderer4.push(`<div class="rc-scroll flex max-h-[60vh] flex-col gap-4 overflow-scroll p-2">`);
            if (typeof conversation?.transcript === "string") {
              $$renderer4.push("<!--[-->");
              CollapseExpand($$renderer4, { value: conversation.transcript, limit: 500, expanded: true });
            } else {
              $$renderer4.push("<!--[!-->");
            }
            $$renderer4.push(`<!--]--></div>`);
          }, footer = function($$renderer4) {
            $$renderer4.push(`<div class="flex w-full items-center justify-end gap-5">`);
            Button($$renderer4, {
              onclick: copyTranscript,
              children: ($$renderer5) => {
                $$renderer5.push(`<!---->Copy transcript`);
              },
              $$slots: { default: true }
            });
            $$renderer4.push(`<!----> `);
            Button($$renderer4, {
              variant: "secondary",
              onclick: () => transcriptOpen = false,
              children: ($$renderer5) => {
                $$renderer5.push(`<!---->Close`);
              },
              $$slots: { default: true }
            });
            $$renderer4.push(`<!----></div>`);
          };
          Modal($$renderer3, {
            title: "Transcript",
            class: "!max-w-4xl",
            get open() {
              return transcriptOpen;
            },
            set open($$value) {
              transcriptOpen = $$value;
              $$settled = false;
            },
            children,
            footer,
            $$slots: { default: true, footer: true }
          });
        }
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]-->`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
    if ($$store_subs) unsubscribe_stores($$store_subs);
    bind_props($$props, { useMock });
  });
}

export { _page as default };
//# sourceMappingURL=_page.svelte-Dl3GoTy1.js.map
