import { X as escape_html } from './context-zH5kvtGY.js';
import { B as Button } from './Button-Cd4Yzpdy.js';
import { C as CopyTracesDropdown, D as Dropdown, a as ChatApiCallTrace, b as ChatConversationalTrace, c as ChatStepTrace } from './ChatStepTrace-cq26gF4B.js';
import { b as attr_class, s as stringify, e as ensure_array_like, a as attr, g as clsx, c as attr_style } from './index2-BuOY2QE4.js';
import { I as Icon } from './Icon-BgknHaZs.js';
import { t as trpc } from './trpc-client-Bucti7HD.js';
import { g as getEditWorkspaceContext, P as Panel } from './edit-workspace-context-OTOIRCI0.js';
import { b as chatContent, i as isApiCallTrace, d as isStepTrace, e as isConversationalTrace, l as logContent } from './log-content.svelte-B3ZvaoLs.js';
import { I as Input } from './Input-BJW36iKz.js';
import './utils-KcIDVAAe.js';
import './state.svelte-DtOGaiYC.js';
import '@trpc/client';

function History($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let {
      agentStates,
      currentState,
      onSelectState,
      class: className = ""
    } = $$props;
    let isOpen = false;
    let anchorEl = null;
    function toggleDropdown() {
      isOpen = !isOpen;
    }
    function handleSelectState(stateId) {
      onSelectState(stateId);
      isOpen = false;
    }
    function getUserMessage(state) {
      const raw = state.userMessage;
      if (raw == null) return "No message";
      const msg = (typeof raw === "string" ? raw : String(raw)).trim();
      return msg || "No message";
    }
    function truncateMessage(message, maxLength = 50, ellipsis = "…") {
      if (!message) return "";
      if (message.length <= maxLength) return message;
      const slice = message.slice(0, maxLength + 1);
      const lastSpace = Math.max(slice.lastIndexOf(" "), slice.lastIndexOf(" "), slice.lastIndexOf("	"), slice.lastIndexOf("\n"), slice.lastIndexOf("\r"));
      const cut = lastSpace > 0 ? slice.slice(0, lastSpace) : message.slice(0, maxLength);
      return cut.trimEnd() + ellipsis;
    }
    function handleKeyDown(event) {
      if (event.key === "ArrowDown" && !isOpen) {
        isOpen = true;
        event.preventDefault();
      } else if (event.key === "ArrowUp" && isOpen) {
        isOpen = false;
        event.preventDefault();
      }
    }
    let selectedState = agentStates.find((s) => s.id === currentState) ?? null;
    let triggerTitle = selectedState?.name ?? "History";
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      $$renderer3.push(`<div${attr_class(`relative ${className}`)}>`);
      Button($$renderer3, {
        variant: "ghost",
        "aria-expanded": isOpen,
        "aria-haspopup": "listbox",
        "aria-controls": "history-dropdown",
        onclick: toggleDropdown,
        onkeydown: handleKeyDown,
        class: "flex w-60 items-center gap-2 text-nowrap rounded-lg border border-transparent !bg-rc-gray-700 !px-3 !pb-1 !pt-[5px] text-justify text-rc-gray-200 hover:border hover:border-rc-gray-500 focus:outline-none focus:ring-0",
        get el() {
          return anchorEl;
        },
        set el($$value) {
          anchorEl = $$value;
          $$settled = false;
        },
        children: ($$renderer4) => {
          $$renderer4.push(`<span>${escape_html(triggerTitle)}</span> `);
          Icon($$renderer4, {
            name: "chevron-down",
            class: "size-7 text-rc-gray-500 transition-transform duration-200 " + (isOpen ? "rotate-180" : "")
          });
          $$renderer4.push(`<!---->`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----> `);
      {
        let children = function($$renderer4) {
          $$renderer4.push(`<div class="mt-1 max-h-96 w-60 overflow-y-auto rounded-lg border border-rc-gray-110 bg-rc-gray-930 shadow-inner-white-soft backdrop-blur-2xl" role="listbox"><!--[-->`);
          const each_array = ensure_array_like(agentStates.slice().reverse());
          for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
            let state = each_array[$$index];
            Button($$renderer4, {
              variant: "ghost",
              size: "small",
              role: "option",
              "aria-selected": state.id === currentState,
              onclick: () => handleSelectState(state.id),
              class: "group w-full rounded-none border-b border-rc-gray-110 py-2 pr-3 text-left backdrop-blur-2xl last:border-b-0 hover:bg-rc-gray-700 focus:bg-rc-gray-400",
              children: ($$renderer5) => {
                $$renderer5.push(`<div class="flex items-start gap-2"><div class="min-w-0"><div class="p-1 text-sm text-rc-gray-300 group-hover:text-rc-gray-200">${escape_html(state.name)}</div> `);
                if (state.id === currentState) {
                  $$renderer5.push("<!--[-->");
                  $$renderer5.push(`<div class="p-1 text-base font-semibold text-rc-green-200">${escape_html(truncateMessage(getUserMessage(state)))}</div>`);
                } else {
                  $$renderer5.push("<!--[!-->");
                  $$renderer5.push(`<div class="p-1 text-base font-semibold text-rc-gray-100">${escape_html(truncateMessage(getUserMessage(state)))}</div>`);
                }
                $$renderer5.push(`<!--]--></div></div>`);
              },
              $$slots: { default: true }
            });
          }
          $$renderer4.push(`<!--]--></div>`);
        };
        Dropdown($$renderer3, {
          id: "history-dropdown",
          open: isOpen,
          onClose: () => isOpen = false,
          anchorEl,
          placement: "bottom-start",
          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 Dialog($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let dialog;
    let {
      showCloseButton = false,
      children
    } = $$props;
    $$renderer2.push(`<dialog class="dialog m-auto bg-transparent p-0 text-rc-gray-100 shadow-md svelte-jby388">`);
    children($$renderer2);
    $$renderer2.push(`<!----> `);
    if (showCloseButton) {
      $$renderer2.push("<!--[-->");
      Button($$renderer2, {
        variant: "ghost",
        onclick: () => dialog.close(),
        class: "absolute right-2 top-2",
        children: ($$renderer3) => {
          $$renderer3.push(`<!---->✕`);
        },
        $$slots: { default: true }
      });
    } else {
      $$renderer2.push("<!--[!-->");
    }
    $$renderer2.push(`<!--]--></dialog>`);
  });
}
function computeSuggestions(rawQuery, history, limit = 5) {
  if (!history.length) return [];
  const trimmedRaw = rawQuery.trim();
  const trimmedRawLower = trimmedRaw.toLowerCase();
  const normalizedQueryExact = normalizePrefixKey(rawQuery, true);
  const normalizedQueryPrefix = normalizePrefixKey(rawQuery, false);
  if (!normalizedQueryExact) return [];
  const consumeTrailingSeparators = /\s$/u.test(rawQuery);
  const matches = [];
  for (const item of history) {
    const normalizedCandidate = normalizePrefixKey(item.text);
    if (!normalizedCandidate) continue;
    if (item.text.trim().toLowerCase() === trimmedRawLower) continue;
    if (!normalizedCandidate.startsWith(normalizedQueryPrefix)) continue;
    const end = prefixEndIndexIgnoringPunctuation(
      item.text,
      normalizedQueryPrefix,
      consumeTrailingSeparators
    ) ?? rawQuery.length;
    matches.push({ item, prefixEndIndex: Math.max(0, Math.min(item.text.length, end)) });
  }
  matches.sort((a, b) => {
    if (a.item.lastSeen !== b.item.lastSeen) return b.item.lastSeen - a.item.lastSeen;
    if (a.item.uses !== b.item.uses) return b.item.uses - a.item.uses;
    return a.item.text.length - b.item.text.length;
  });
  return matches.slice(0, limit).slice().reverse().map((m) => ({
    text: m.item.text,
    prefixEndIndex: m.prefixEndIndex,
    segments: buildSegments(m.item.text, [[0, m.prefixEndIndex]])
  }));
}
function normalizePrefixKey(value, trimEnd = true) {
  const lower = value.toLowerCase();
  let spaced;
  try {
    spaced = lower.replace(/[\p{P}\p{S}]/gu, " ");
  } catch {
    spaced = lower.replace(/[^a-z0-9\s]/gi, " ");
  }
  const collapsed = spaced.replace(/\s+/g, " ");
  const trimStart = collapsed.replace(/^\s+/u, "");
  return trimEnd ? trimStart.replace(/\s+$/u, "") : trimStart;
}
function prefixEndIndexIgnoringPunctuation(candidate, normalizedQuery, consumeTrailingSeparators) {
  if (!normalizedQuery) return null;
  let normalized = "";
  let lastWasSpace = true;
  for (let i = 0; i < candidate.length; i++) {
    const ch = candidate[i];
    let token;
    if (/\s/u.test(ch)) {
      token = " ";
    } else {
      try {
        token = /[\p{P}\p{S}]/u.test(ch) ? " " : ch.toLowerCase();
      } catch {
        token = /[^a-z0-9\s]/i.test(ch) ? " " : ch.toLowerCase();
      }
    }
    if (token === " ") {
      if (lastWasSpace) continue;
      normalized += " ";
      lastWasSpace = true;
    } else {
      normalized += token;
      lastWasSpace = false;
    }
    if (normalized.length === normalizedQuery.length) {
      if (normalized !== normalizedQuery) return null;
      let end = i + 1;
      if (consumeTrailingSeparators && normalizedQuery.endsWith(" ")) {
        let j = end;
        while (j < candidate.length) {
          const c = candidate[j];
          if (/\s/u.test(c)) {
            j += 1;
            continue;
          }
          try {
            if (/[\p{P}\p{S}]/u.test(c)) {
              j += 1;
              continue;
            }
          } catch {
            if (/[^a-z0-9\s]/i.test(c)) {
              j += 1;
              continue;
            }
          }
          break;
        }
        end = j;
      }
      return end;
    }
    if (normalized.length > normalizedQuery.length) {
      return null;
    }
  }
  return null;
}
function buildSegments(text, ranges) {
  if (!ranges.length) return [{ text, matched: false }];
  const segments = [];
  let cursor = 0;
  for (const [start, end] of ranges) {
    if (start > cursor) {
      segments.push({ text: text.slice(cursor, start), matched: false });
    }
    segments.push({ text: text.slice(start, end), matched: true });
    cursor = end;
  }
  if (cursor < text.length) {
    segments.push({ text: text.slice(cursor), matched: false });
  }
  return segments.filter((s) => s.text.length > 0);
}
function PlaygroundChat($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let {
      class: className,
      context,
      agentId,
      analyzeDisabled = false,
      onAnalyzeTrace
    } = $$props;
    let text = "";
    let imageUrlInputValue = "";
    let inputEl = null;
    let ghostTextStyle = "";
    let userHistory = [];
    let inputFocused = false;
    let autocompleteDismissed = false;
    let selectedSuggestionIndex = null;
    const suggestions = (() => computeSuggestions(text, userHistory))();
    const selectedSuggestion = (() => {
      if (selectedSuggestionIndex == null) return null;
      return suggestions[selectedSuggestionIndex] ?? null;
    })();
    const ghostSuffix = (() => {
      if (!selectedSuggestion) return "";
      return selectedSuggestion.text.slice(selectedSuggestion.prefixEndIndex);
    })();
    const dropdownOpen = (() => {
      if (!inputFocused) return false;
      if (autocompleteDismissed) return false;
      return suggestions.length > 0;
    })();
    function applySuggestion(s) {
      text = s.text;
      selectedSuggestionIndex = null;
      autocompleteDismissed = true;
    }
    function handleInputFocus() {
      inputFocused = true;
      autocompleteDismissed = false;
    }
    function handleInputBlur() {
      inputFocused = false;
      selectedSuggestionIndex = null;
      autocompleteDismissed = false;
    }
    function handleInput() {
      selectedSuggestionIndex = null;
      autocompleteDismissed = false;
    }
    function handleInputKeydown(event) {
      if (event.key === "Escape") {
        if (dropdownOpen) {
          event.preventDefault();
        }
        autocompleteDismissed = true;
        selectedSuggestionIndex = null;
        return;
      }
      if (event.key === "ArrowUp" || event.key === "ArrowDown") {
        if (!suggestions.length) return;
        if (autocompleteDismissed) autocompleteDismissed = false;
        event.preventDefault();
        const max = suggestions.length - 1;
        if (selectedSuggestionIndex === null) {
          selectedSuggestionIndex = event.key === "ArrowUp" ? max : 0;
        } else {
          const delta = event.key === "ArrowUp" ? -1 : 1;
          selectedSuggestionIndex = Math.max(0, Math.min(max, selectedSuggestionIndex + delta));
        }
        return;
      }
      if (event.key === "Enter" || event.key === "Tab" && !event.shiftKey) {
        if (selectedSuggestionIndex === null) return;
        const s = suggestions[selectedSuggestionIndex];
        if (!s) return;
        event.preventDefault();
        applySuggestion(s);
        return;
      }
    }
    function getPromptForDiff(trace) {
      if (!trace) return null;
      if (typeof trace.renderedPrompt === "string") return trace.renderedPrompt;
      return null;
    }
    function findMainComparisonTrace(entries, index) {
      for (let i = index - 1; i >= 0; i--) {
        const entry = entries[i];
        if (isStepTrace(entry) && entry.name === "main" && getPromptForDiff(entry)) return entry;
      }
      for (let i = index - 1; i >= 0; i--) {
        const entry = entries[i];
        if (isStepTrace(entry) && entry.name === "prewarm" && getPromptForDiff(entry)) return entry;
      }
      return null;
    }
    function isRenderableConversationalMessage(trace) {
      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}`;
    }
    const renderableEntries = (() => {
      return chatContent.filter((entry) => {
        if (isApiCallTrace(entry) || isStepTrace(entry)) return true;
        if (isConversationalTrace(entry)) return isRenderableConversationalMessage(entry);
        return false;
      });
    })();
    function findMainStepTraceForConversationTrace(idx) {
      for (let i = idx - 1; i >= 0; i--) {
        const entry = chatContent[i];
        if (!isStepTrace(entry)) continue;
        if (entry.name !== "main" && entry.name !== "mainReply") continue;
        if (typeof entry.renderedPrompt !== "string") continue;
        if (!entry.renderedPrompt.trim()) continue;
        return entry;
      }
      for (let i = idx + 1; i < chatContent.length; i++) {
        const entry = chatContent[i];
        if (!isStepTrace(entry)) continue;
        if (entry.name !== "main" && entry.name !== "mainReply") continue;
        if (typeof entry.renderedPrompt !== "string") continue;
        if (!entry.renderedPrompt.trim()) continue;
        return entry;
      }
      return null;
    }
    function findNearestStringifiedConversation(idx) {
      for (let i = idx - 1; i >= 0; i--) {
        const entry = chatContent[i];
        if (!isStepTrace(entry)) continue;
        if (typeof entry.stringifiedConversation !== "string") continue;
        const sc = entry.stringifiedConversation.trim();
        if (!sc) continue;
        return sc;
      }
      return null;
    }
    function buildAnalyzeTraceInput(trace) {
      const agent = (agentId ?? "").trim();
      if (!agent) throw new Error("Agent id is not available; cannot analyze");
      const idx = chatContent.indexOf(trace);
      if (idx === -1) throw new Error("Could not locate trace in chat history");
      const stepTrace = findMainStepTraceForConversationTrace(idx);
      if (!stepTrace) {
        throw new Error("Could not find main step trace for this message");
      }
      const renderedPrompt = typeof stepTrace.renderedPrompt === "string" ? stepTrace.renderedPrompt : "";
      if (!renderedPrompt.trim()) throw new Error("Main step rendered prompt is missing");
      const stringifiedConversation = typeof stepTrace.stringifiedConversation === "string" && stepTrace.stringifiedConversation.trim() ? stepTrace.stringifiedConversation : findNearestStringifiedConversation(idx) ?? "";
      if (!stringifiedConversation.trim()) throw new Error("Main step conversation is missing");
      const response = String(trace?.content ?? "");
      if (!response.trim()) throw new Error("Message content is missing");
      const model = typeof stepTrace?.model === "string" ? String(stepTrace.model) : void 0;
      const createdAtRaw = trace?.createdAt;
      const createdAt = typeof createdAtRaw === "number" && Number.isFinite(createdAtRaw) ? createdAtRaw : void 0;
      return {
        trace,
        stepTrace,
        renderedPrompt,
        stringifiedConversation,
        response,
        model,
        createdAt
      };
    }
    function handleAnalyzeTrace(trace) {
      if (!onAnalyzeTrace) return;
      try {
        onAnalyzeTrace(buildAnalyzeTraceInput(trace));
      } catch (e) {
        console.error(e);
      }
    }
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      Dialog($$renderer3, {
        showCloseButton: true,
        children: ($$renderer4) => {
          Panel($$renderer4, {
            class: "p-4",
            children: ($$renderer5) => {
              $$renderer5.push(`<form><h2 class="text-l mb-4 text-gray-300">Image URL</h2> `);
              Input($$renderer5, {
                class: "mb-2 w-80",
                get value() {
                  return imageUrlInputValue;
                },
                set value($$value) {
                  imageUrlInputValue = $$value;
                  $$settled = false;
                }
              });
              $$renderer5.push(`<!----> `);
              Button($$renderer5, {
                variant: "secondary",
                type: "submit",
                class: "ml-2 p-2",
                children: ($$renderer6) => {
                  $$renderer6.push(`<!---->Attach`);
                },
                $$slots: { default: true }
              });
              $$renderer5.push(`<!----></form>`);
            }
          });
        }
      });
      $$renderer3.push(`<!----> `);
      Panel($$renderer3, {
        class: `relative flex min-h-0 flex-col p-2 pb-16 ${stringify(className)}`,
        children: ($$renderer4) => {
          $$renderer4.push(`<div class="rc-scroll min-h-0 flex-1 overflow-y-auto pr-1"><!--[-->`);
          const each_array = ensure_array_like(renderableEntries);
          for (let idx = 0, $$length = each_array.length; idx < $$length; idx++) {
            let entry = each_array[idx];
            const current = dateKey(entry.createdAt);
            const previous = idx > 0 ? dateKey(renderableEntries[idx - 1].createdAt) : null;
            const label = formatDateLabel(entry.createdAt);
            if (current && label && current !== previous) {
              $$renderer4.push("<!--[-->");
              $$renderer4.push(`<div class="my-2 flex w-full justify-center"><div class="rounded-full border border-rc-gray-650 bg-rc-gray-800/40 px-3 py-1 text-xs text-rc-gray-200">${escape_html(label)}</div></div>`);
            } else {
              $$renderer4.push("<!--[!-->");
            }
            $$renderer4.push(`<!--]--> <div class="log-element"><div>`);
            if (isApiCallTrace(entry)) {
              $$renderer4.push("<!--[-->");
              ChatApiCallTrace($$renderer4, { trace: entry });
            } else {
              $$renderer4.push("<!--[!-->");
              if (isConversationalTrace(entry)) {
                $$renderer4.push("<!--[-->");
                ChatConversationalTrace($$renderer4, {
                  trace: entry,
                  context,
                  agentId,
                  analyzeDisabled,
                  onAnalyze: onAnalyzeTrace ? handleAnalyzeTrace : void 0
                });
              } else {
                $$renderer4.push("<!--[!-->");
                if (isStepTrace(entry)) {
                  $$renderer4.push("<!--[-->");
                  ChatStepTrace($$renderer4, {
                    trace: entry,
                    compareTrace: entry.name === "main" ? findMainComparisonTrace(renderableEntries, idx) : null
                  });
                } else {
                  $$renderer4.push("<!--[!-->");
                }
                $$renderer4.push(`<!--]-->`);
              }
              $$renderer4.push(`<!--]-->`);
            }
            $$renderer4.push(`<!--]--></div></div>`);
          }
          $$renderer4.push(`<!--]--></div> <form class="absolute bottom-2 left-2 right-2 z-10 flex gap-2 rounded"><div class="relative flex-1">`);
          if (dropdownOpen) {
            $$renderer4.push("<!--[-->");
            $$renderer4.push(`<div class="absolute bottom-full left-0 right-0 mb-1 max-h-60 overflow-y-auto rounded-lg border border-rc-gray-110 bg-rc-gray-930 shadow-inner-white-soft backdrop-blur-2xl" role="listbox"><!--[-->`);
            const each_array_1 = ensure_array_like(suggestions);
            for (let idx = 0, $$length = each_array_1.length; idx < $$length; idx++) {
              let s = each_array_1[idx];
              $$renderer4.push(`<button type="button" role="option"${attr("aria-selected", selectedSuggestionIndex === idx)} tabindex="-1"${attr_class(`w-full select-none border-b border-rc-gray-110 px-3 py-2 text-left font-semibold text-rc-gray-100 last:border-b-0 hover:bg-rc-gray-700/70 ${stringify(selectedSuggestionIndex === idx ? "bg-rc-gray-700/70" : "")}`)}><!--[-->`);
              const each_array_2 = ensure_array_like(s.segments);
              for (let $$index_1 = 0, $$length2 = each_array_2.length; $$index_1 < $$length2; $$index_1++) {
                let seg = each_array_2[$$index_1];
                $$renderer4.push(`<span${attr_class(clsx(seg.matched ? "text-rc-green-200" : ""))}>${escape_html(seg.text)}</span>`);
              }
              $$renderer4.push(`<!--]--></button>`);
            }
            $$renderer4.push(`<!--]--></div>`);
          } else {
            $$renderer4.push("<!--[!-->");
          }
          $$renderer4.push(`<!--]--> `);
          Input($$renderer4, {
            variant: "chat",
            placeholder: "Enter user's message...",
            autocomplete: "off",
            onfocus: handleInputFocus,
            onblur: handleInputBlur,
            oninput: handleInput,
            onkeydown: handleInputKeydown,
            get value() {
              return text;
            },
            set value($$value) {
              text = $$value;
              $$settled = false;
            },
            get el() {
              return inputEl;
            },
            set el($$value) {
              inputEl = $$value;
              $$settled = false;
            }
          });
          $$renderer4.push(`<!----> `);
          if (selectedSuggestionIndex !== null && ghostSuffix) {
            $$renderer4.push("<!--[-->");
            $$renderer4.push(`<div class="pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg" aria-hidden="true"><div class="whitespace-pre text-rc-gray-400/70"${attr_style(ghostTextStyle)}><span class="invisible">${escape_html(text)}</span><span>${escape_html(ghostSuffix)}</span></div></div>`);
          } else {
            $$renderer4.push("<!--[!-->");
          }
          $$renderer4.push(`<!--]--></div> `);
          Button($$renderer4, {
            size: "small",
            variant: "secondary",
            onclick: () => true,
            children: ($$renderer5) => {
              Icon($$renderer5, { name: "paperclip" });
            },
            $$slots: { default: true }
          });
          $$renderer4.push(`<!----> `);
          Button($$renderer4, {
            size: "small",
            type: "submit",
            children: ($$renderer5) => {
              Icon($$renderer5, { name: "send" });
            },
            $$slots: { default: true }
          });
          $$renderer4.push(`<!----></form>`);
        }
      });
      $$renderer3.push(`<!---->`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
  });
}
function _page($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    const { state: workspace, actions } = getEditWorkspaceContext();
    let analyzeRunning = false;
    let copiedLogs = false;
    let logsTimer = null;
    function agentLabel(agentId) {
      const label = (agentId || "").trim();
      if (!label) return "Agent";
      return label.split("/").at(-1) ?? label;
    }
    function formatHHmmss(ms) {
      if (typeof ms !== "number" || !Number.isFinite(ms)) return null;
      const d = new Date(ms);
      if (Number.isNaN(d.getTime())) return null;
      const hh = String(d.getHours()).padStart(2, "0");
      const mm = String(d.getMinutes()).padStart(2, "0");
      const ss = String(d.getSeconds()).padStart(2, "0");
      return `${hh}:${mm}:${ss}`;
    }
    async function handleAnalyzeTrace(input) {
      if (analyzeRunning) return;
      analyzeRunning = true;
      const requestId = actions.openPopover("analyze");
      const time = formatHHmmss(input.createdAt);
      const titleSuffix = time ? ` • ${time}` : "";
      const title = `Analysis — ${agentLabel(workspace.agentId)}${titleSuffix}`;
      try {
        const res = await trpc.agents.analyzeTrace.mutate({
          agentId: workspace.agentId,
          traceId: input.trace?.traceId,
          eventName: input.trace.eventName,
          createdAt: input.createdAt,
          model: input.model,
          renderedPrompt: input.renderedPrompt,
          stringifiedConversation: input.stringifiedConversation,
          response: input.response,
          stepTrace: input.stepTrace
        });
        if (workspace.edit.popover?.requestId !== requestId) return;
        actions.setHighlightQuotes(res.quotes);
        let raw = null;
        try {
          raw = JSON.stringify(res.raw, null, 2);
        } catch {
          raw = null;
        }
        actions.setPopoverReady(requestId, { title, quotes: res.quotes, raw });
      } catch (e) {
        console.error(e);
        const message = typeof e?.message === "string" ? e.message : (() => {
          try {
            return JSON.stringify(e);
          } catch {
            return String(e);
          }
        })();
        actions.setPopoverError(requestId, message || "Failed to analyze this response", { raw: message });
      } finally {
        analyzeRunning = false;
      }
    }
    function tracesForCopy(includePrompts) {
      if (includePrompts) return chatContent;
      return chatContent.map((entry) => {
        if (!isStepTrace(entry)) return entry;
        const {
          receivedPrompt: _receivedPrompt,
          renderedPrompt: _renderedPrompt,
          ...rest
        } = entry;
        return rest;
      });
    }
    async function copyLogs() {
      try {
        await navigator.clipboard.writeText(JSON.stringify(logContent, null, 2));
        copiedLogs = true;
        if (logsTimer) clearTimeout(logsTimer);
        logsTimer = window.setTimeout(
          () => {
            copiedLogs = false;
            logsTimer = null;
          },
          2e3
        );
      } catch (e) {
        console.error("Failed to copy logs", e);
      }
    }
    function handleNewChat() {
      actions.closePopover();
      actions.closeContextPopover();
      actions.selectState(null);
    }
    $$renderer2.push(`<div class="relative flex h-full min-h-0 flex-col"><div class="flex flex-none flex-nowrap items-center justify-end gap-2 border-b border-rc-gray-700 p-2">`);
    if (workspace.agentStates.length > 1) {
      $$renderer2.push("<!--[-->");
      History($$renderer2, {
        agentStates: workspace.agentStates,
        currentState: workspace.currentState,
        onSelectState: (id) => actions.selectState(id)
      });
    } else {
      $$renderer2.push("<!--[!-->");
    }
    $$renderer2.push(`<!--]--> `);
    Button($$renderer2, {
      variant: "secondary",
      size: "small",
      disabled: !workspace.agentId,
      "aria-expanded": workspace.contextPopoverOpen,
      "aria-haspopup": "dialog",
      onclick: actions.toggleContextPopover,
      children: ($$renderer3) => {
        $$renderer3.push(`<!---->Edit context`);
      },
      $$slots: { default: true }
    });
    $$renderer2.push(`<!----> `);
    CopyTracesDropdown($$renderer2, {
      disabled: !chatContent.length,
      getWithPromptsText: () => JSON.stringify(tracesForCopy(true), null, 2),
      getWithoutPromptsText: () => JSON.stringify(tracesForCopy(false), null, 2)
    });
    $$renderer2.push(`<!----> `);
    Button($$renderer2, {
      variant: "secondary",
      size: "small",
      disabled: !logContent.length,
      onclick: (e) => {
        e.stopPropagation();
        copyLogs();
      },
      children: ($$renderer3) => {
        $$renderer3.push(`<!---->${escape_html(copiedLogs ? "Copied logs" : "Copy logs")}`);
      },
      $$slots: { default: true }
    });
    $$renderer2.push(`<!----> `);
    Button($$renderer2, {
      onclick: handleNewChat,
      class: "self-baseline text-sm font-bold",
      children: ($$renderer3) => {
        $$renderer3.push(`<!---->New chat`);
      },
      $$slots: { default: true }
    });
    $$renderer2.push(`<!----></div> <div class="min-h-0 flex-1">`);
    if (!workspace.wsLoaded) {
      $$renderer2.push("<!--[-->");
      $$renderer2.push(`<div class="flex h-full items-center justify-center text-sm text-rc-gray-300">Connecting…</div>`);
    } else {
      $$renderer2.push("<!--[!-->");
      if (!workspace.agentId) {
        $$renderer2.push("<!--[-->");
        $$renderer2.push(`<div class="flex h-full items-center justify-center text-sm text-rc-gray-300">Select an agent to start chatting</div>`);
      } else {
        $$renderer2.push("<!--[!-->");
        $$renderer2.push(`<div class="h-full min-h-0 p-2">`);
        PlaygroundChat($$renderer2, {
          class: "h-full min-w-0 border-thin border-rc-gray-650 shadow-inner-white-soft backdrop-blur-3xl",
          context: workspace.context,
          agentId: workspace.agentId,
          analyzeDisabled: analyzeRunning,
          onAnalyzeTrace: handleAnalyzeTrace
        });
        $$renderer2.push(`<!----></div>`);
      }
      $$renderer2.push(`<!--]-->`);
    }
    $$renderer2.push(`<!--]--></div></div>`);
  });
}

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