import { B as Button } from './Button-qfXYs6Cv.js';
import { D as Dropdown } from './Dropdown-DroDbZQ6.js';
import { b as attr_class, s as stringify, e as ensure_array_like, a as attr, f as clsx, c as attr_style } from './index2-BpEbpEAf.js';
import { I as Icon } from './Icon-SOvOgynh.js';
import { X as escape_html } from './context-B0vutJuA.js';
import { t as trpc } from './trpc-client-Bucti7HD.js';
import { g as getEditWorkspaceContext, P as Panel } from './edit-workspace-context-BQXwYkgE.js';
import { C as ChatApiCallTrace, a as ChatConversationalTrace, b as ChatStepTrace } from './ChatStepTrace-Bvxmgz7y.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-D-7S8dEO.js';
import '@trpc/client';
import './index-server-BI-Ep7Rw.js';
import './utils-KcIDVAAe.js';
import './state.svelte-DbqYHGBV.js';

function History($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let {
      agentStates,
      currentState,
      onSelectState,
      class: className = ""
    } = $$props;
    let isOpen = false;
    let anchorEl = null;
    const MONTHS_SHORT = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ];
    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();
      }
    }
    function formatStateTime(d) {
      const day = d.getDate();
      const month = MONTHS_SHORT[d.getMonth()];
      let hour = d.getHours();
      const ampm = hour >= 12 ? "PM" : "AM";
      hour = hour % 12;
      if (hour === 0) hour = 12;
      const minute = String(d.getMinutes()).padStart(2, "0");
      const now = /* @__PURE__ */ new Date();
      const year = d.getFullYear();
      const yearPart = year !== now.getFullYear() ? ` ${year}` : "";
      return `${day} ${month}${yearPart}, ${hour}:${minute} ${ampm}`;
    }
    function formatStateLabel(state) {
      const fromId = new Date(state.id);
      if (!Number.isNaN(fromId.getTime())) return formatStateTime(fromId);
      const fromName = new Date(state.name);
      if (!Number.isNaN(fromName.getTime())) return formatStateTime(fromName);
      return state.name || "History";
    }
    let selectedState = agentStates.find((s) => s.id === currentState) ?? null;
    let triggerTitle = selectedState ? formatStateLabel(selectedState) : "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: "inline-flex w-40 items-center rounded-lg border border-transparent !bg-rc-gray-700 !px-3 !pb-1 !pt-[5px] 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 class="min-w-0 flex-1 truncate text-left">${escape_html(triggerTitle)}</span> `);
          Icon($$renderer4, {
            name: "chevron-down",
            class: "size-7 shrink-0 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-max min-w-full max-w-[min(26rem,90vw)] overflow-y-auto overflow-x-hidden rounded-lg border border-rc-gray-110 bg-rc-gray-930 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="truncate p-1 text-sm text-rc-gray-300 group-hover:text-rc-gray-200">${escape_html(formatStateLabel(state))}</div> `);
                if (state.id === currentState) {
                  $$renderer5.push("<!--[-->");
                  $$renderer5.push(`<div class="truncate p-1 text-base font-semibold text-rc-green-200">${escape_html(truncateMessage(getUserMessage(state)))}</div>`);
                } else {
                  $$renderer5.push("<!--[!-->");
                  $$renderer5.push(`<div class="truncate 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 normalizedQuery = normalizeMatchText(rawQuery, false).text;
  const consumeTrailingSeparators = /\s$/u.test(rawQuery);
  if (!normalizeMatchText(rawQuery, true).text) return [];
  const matches = [];
  for (const item of history) {
    const normalizedCandidate = normalizeMatchText(item.text);
    if (!normalizedCandidate.text) continue;
    if (item.text.trim().toLowerCase() === trimmedRawLower) continue;
    const match = findMatch(
      normalizedCandidate,
      item.text,
      normalizedQuery,
      consumeTrailingSeparators
    );
    if (!match) continue;
    matches.push({ item, match });
  }
  matches.sort((a, b) => {
    if (a.match.kindRank !== b.match.kindRank) return a.match.kindRank - b.match.kindRank;
    if (a.match.span !== b.match.span) return a.match.span - b.match.span;
    if (a.match.start !== b.match.start) return a.match.start - b.match.start;
    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).map((m) => ({
    text: m.item.text,
    prefixEndIndex: m.match.prefixEndIndex,
    segments: buildSegments(m.item.text, m.match.ranges)
  }));
}
function normalizeMatchText(value, trimEnd = true) {
  const chars = [];
  const ranges = [];
  for (let i = 0; i < value.length; i++) {
    const token = normalizeChar(value[i]);
    if (token === " ") {
      if (!chars.length) continue;
      const last = chars.length - 1;
      if (chars[last] === " ") {
        ranges[last][1] = i + 1;
        continue;
      }
    }
    chars.push(token);
    ranges.push([i, i + 1]);
  }
  if (trimEnd && chars[chars.length - 1] === " ") {
    chars.pop();
    ranges.pop();
  }
  return { text: chars.join(""), ranges };
}
function normalizeChar(ch) {
  if (/\s/u.test(ch)) return " ";
  try {
    return /[\p{P}\p{S}]/u.test(ch) ? " " : ch.toLowerCase();
  } catch {
    return /[^a-z0-9\s]/i.test(ch) ? " " : ch.toLowerCase();
  }
}
function findMatch(normalizedCandidate, rawCandidate, normalizedQuery, consumeTrailingSeparators) {
  if (!normalizedCandidate.text) return null;
  if (normalizedCandidate.text.startsWith(normalizedQuery)) {
    const end = prefixEndIndexIgnoringPunctuation(rawCandidate, normalizedQuery, consumeTrailingSeparators) ?? rawCandidate.length;
    const clampedEnd = Math.max(0, Math.min(rawCandidate.length, end));
    return {
      kindRank: 0,
      start: 0,
      span: normalizedQuery.length,
      ranges: [[0, clampedEnd]],
      prefixEndIndex: clampedEnd
    };
  }
  const substringIndex = normalizedCandidate.text.indexOf(normalizedQuery);
  if (substringIndex !== -1) {
    return {
      kindRank: getSubstringKindRank(
        normalizedCandidate.text,
        substringIndex,
        normalizedQuery.length
      ),
      start: substringIndex,
      span: normalizedQuery.length,
      ranges: normalizedSliceToRawRanges(
        normalizedCandidate,
        substringIndex,
        substringIndex + normalizedQuery.length
      ),
      prefixEndIndex: rawCandidate.length
    };
  }
  return null;
}
function isWordBoundary(value, index) {
  if (index <= 0) return true;
  return value[index - 1] === " ";
}
function isWordEndBoundary(value, index) {
  if (index >= value.length) return true;
  return value[index] === " ";
}
function getSubstringKindRank(value, start, length) {
  const startsAtBoundary = isWordBoundary(value, start);
  const endsAtBoundary = isWordEndBoundary(value, start + length);
  if (startsAtBoundary && endsAtBoundary) return 1;
  if (startsAtBoundary) return 2;
  return 3;
}
function normalizedSliceToRawRanges(normalized, start, end) {
  const clampedStart = Math.max(0, Math.min(normalized.ranges.length, start));
  const clampedEnd = Math.max(clampedStart, Math.min(normalized.ranges.length, end));
  return mergeRanges(normalized.ranges.slice(clampedStart, clampedEnd));
}
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) {
  const merged = mergeRanges(ranges);
  if (!merged.length) return [{ text, matched: false }];
  const segments = [];
  let cursor = 0;
  for (const [start, end] of merged) {
    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 mergeRanges(ranges) {
  if (!ranges.length) return [];
  const sorted = ranges.map(([start, end]) => [Math.max(0, start), Math.max(0, end)]).filter(([start, end]) => end > start).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  if (!sorted.length) return [];
  const merged = [[sorted[0][0], sorted[0][1]]];
  for (let i = 1; i < sorted.length; i++) {
    const [start, end] = sorted[i];
    const current = merged[merged.length - 1];
    if (start <= current[1]) {
      current[1] = Math.max(current[1], end);
      continue;
    }
    merged.push([start, end]);
  }
  return merged;
}
function PlaygroundChat($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let {
      class: className,
      context,
      agentId,
      agentType,
      analyzeDisabled = false,
      onAnalyzeTrace,
      onRegenerateTrace,
      onRevertToState,
      onSeeVariants,
      onHangup,
      variantSourceTrace = null,
      variantChoices = [],
      variantLoading = false,
      variantApplyingId = null,
      variantError = null,
      onRegenerateVariants,
      onChooseOriginalVariant
    } = $$props;
    let text = "";
    let imageUrlInputValue = "";
    let inputEl = null;
    let ghostTextStyle = "";
    let aiGenerating = false;
    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 showGenerateAction = (() => !variantSourceTrace && true && text.trim().length === 0)();
    const dropdownOpen = (() => {
      if (variantSourceTrace) return false;
      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" || trace.eventName === "hangup-requested";
    }
    function isVariantEligibleTrace(trace) {
      return !!(agentId && agentId.trim()) && trace.eventName !== "transfer-requested" && (trace.eventName === "finished-main-streaming-step" || trace.eventName === "sent-message");
    }
    function extractUserText(raw) {
      const value = String(raw ?? "").trim();
      if (!value) return "";
      if (/^\[image\]\s+/.test(value)) return "";
      return value;
    }
    function handleRevertTrace(trace) {
      if (!onRevertToState) return;
      const rawPrev = trace?.bosunPrevStateId;
      const prevStateId = typeof rawPrev === "string" && rawPrev.trim().length > 0 ? rawPrev : null;
      onRevertToState(prevStateId);
      const rawUserMessage = typeof trace?.bosunUserMessage === "string" ? trace.bosunUserMessage : trace.content;
      text = extractUserText(rawUserMessage);
      requestAnimationFrame(() => {
        try {
          inputEl?.focus();
          inputEl?.select();
        } catch {
        }
      });
    }
    function handleSecondaryChatButton() {
      if (agentType === "text") ;
      else if (agentType === "voice") {
        onHangup?.();
      }
    }
    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;
      });
    })();
    const controlsDisabled = (() => {
      return chatContent.findLast((e) => isConversationalTrace(e))?.eventName === "hangup-requested";
    })();
    const lastVariantEligibleTrace = (() => {
      for (let index = renderableEntries.length - 1; index >= 0; index--) {
        const entry = renderableEntries[index];
        if (!isConversationalTrace(entry)) continue;
        if (!isVariantEligibleTrace(entry)) continue;
        return entry;
      }
      return null;
    })();
    const aiResponseContext = (() => {
      const trace = lastVariantEligibleTrace;
      if (!trace) return null;
      try {
        const input = buildAnalyzeTraceInput(trace);
        return {
          model: input.model,
          stringifiedConversation: input.stringifiedConversation,
          response: input.response
        };
      } catch {
        return null;
      }
    })();
    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);
      }
    }
    async function handleGenerateUserResponse() {
      if (aiGenerating) return;
      const request = aiResponseContext;
      if (!request) return;
      autocompleteDismissed = true;
      selectedSuggestionIndex = null;
      aiGenerating = true;
      try {
        const result = await trpc.agents.generateUserResponse.mutate(request);
        text = result.text;
        autocompleteDismissed = true;
        selectedSuggestionIndex = null;
        requestAnimationFrame(() => {
          try {
            inputEl?.focus();
            inputEl?.setSelectionRange(result.text.length, result.text.length);
          } catch {
          }
        });
      } catch (e) {
        console.error("Failed to generate suggested user response", e);
      } finally {
        aiGenerating = false;
      }
    }
    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,
                  onRegenerate: onRegenerateTrace,
                  onRevert: onRevertToState ? handleRevertTrace : void 0,
                  showSeeVariants: !!onSeeVariants && !variantSourceTrace && entry === lastVariantEligibleTrace,
                  onSeeVariants,
                  variantSelectionState: variantSourceTrace && entry === variantSourceTrace ? "source" : "none",
                  onSelectInVariantMode: variantApplyingId === null && variantSourceTrace && entry === variantSourceTrace ? onChooseOriginalVariant : void 0,
                  suppressActionRow: !!variantSourceTrace && entry === variantSourceTrace
                });
              } 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> `);
            if (variantSourceTrace && entry === variantSourceTrace) {
              $$renderer4.push("<!--[-->");
              $$renderer4.push(`<div class="ml-7 mt-2 flex flex-col gap-2">`);
              if (variantLoading) {
                $$renderer4.push("<!--[-->");
                $$renderer4.push(`<div class="rounded-lg border border-rc-green-450 bg-transparent px-3 py-2 text-sm text-rc-gray-300">Generating 9 more variants…</div>`);
              } else {
                $$renderer4.push("<!--[!-->");
              }
              $$renderer4.push(`<!--]--> `);
              if (variantError) {
                $$renderer4.push("<!--[-->");
                $$renderer4.push(`<div class="rounded-lg border border-red-500/70 bg-red-950/20 px-3 py-2 text-sm text-red-200">${escape_html(variantError)}</div>`);
              } else {
                $$renderer4.push("<!--[!-->");
              }
              $$renderer4.push(`<!--]--> <!--[-->`);
              const each_array_1 = ensure_array_like(variantChoices);
              for (let $$index = 0, $$length2 = each_array_1.length; $$index < $$length2; $$index++) {
                let variant = each_array_1[$$index];
                $$renderer4.push(`<button type="button"${attr("disabled", variantApplyingId !== null, true)}${attr_class(`w-full max-w-[83%] cursor-pointer rounded-lg border border-rc-green-450 bg-transparent p-2 pt-1 text-left text-rc-gray-100 backdrop-blur-md transition-colors hover:bg-rc-green-700 focus:outline-none focus-visible:outline-none disabled:cursor-wait disabled:opacity-70 ${stringify(variantApplyingId === variant.id ? "bg-rc-green-700" : "")}`)}><div class="whitespace-pre-line break-words">${escape_html(variant.text)}</div></button>`);
              }
              $$renderer4.push(`<!--]--></div>`);
            } else {
              $$renderer4.push("<!--[!-->");
            }
            $$renderer4.push(`<!--]--></div>`);
          }
          $$renderer4.push(`<!--]--></div> `);
          if (variantSourceTrace) {
            $$renderer4.push("<!--[-->");
            $$renderer4.push(`<div class="absolute bottom-2 left-2 right-2 z-10 flex items-center gap-3 rounded-lg border border-rc-green-450 bg-rc-gray-930/90 px-3 py-3 font-semibold text-rc-gray-100 shadow-inner-white-soft backdrop-blur-3xl"><span>Choose a variant above to continue</span> <button type="button"${attr("disabled", !onRegenerateVariants || variantLoading || variantApplyingId !== null, true)} class="rounded border-0 bg-transparent px-1 py-0.5 text-rc-gray-300 transition-colors hover:bg-rc-gray-900 hover:text-rc-gray-100 focus:outline-none focus-visible:outline-none disabled:cursor-wait disabled:opacity-50">Regenerate</button> <button type="button" class="rounded border-0 bg-transparent px-1 py-0.5 text-rc-gray-300 transition-colors hover:bg-rc-gray-900 hover:text-rc-gray-100 focus:outline-none focus-visible:outline-none">Cancel</button></div>`);
          } else {
            $$renderer4.push("<!--[!-->");
            $$renderer4.push(`<form><fieldset${attr("disabled", controlsDisabled, true)} class="absolute bottom-2 left-2 right-2 z-10 flex gap-2 disabled:opacity-35"><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_2 = ensure_array_like(suggestions);
              for (let idx = 0, $$length = each_array_2.length; idx < $$length; idx++) {
                let s = each_array_2[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_3 = ensure_array_like(s.segments);
                for (let $$index_2 = 0, $$length2 = each_array_3.length; $$index_2 < $$length2; $$index_2++) {
                  let seg = each_array_3[$$index_2];
                  $$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: aiGenerating ? "Generating" : "Enter user's message...",
              autocomplete: "off",
              readonly: aiGenerating,
              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",
              disabled: aiGenerating || !agentType,
              onclick: handleSecondaryChatButton,
              children: ($$renderer5) => {
                if (agentType === "text") {
                  $$renderer5.push("<!--[-->");
                  Icon($$renderer5, { name: "paperclip" });
                } else {
                  $$renderer5.push("<!--[!-->");
                  if (agentType === "voice") {
                    $$renderer5.push("<!--[-->");
                    Icon($$renderer5, { name: "hangup" });
                  } else {
                    $$renderer5.push("<!--[!-->");
                  }
                  $$renderer5.push(`<!--]-->`);
                }
                $$renderer5.push(`<!--]-->`);
              },
              $$slots: { default: true }
            });
            $$renderer4.push(`<!----> `);
            Button($$renderer4, {
              size: "small",
              type: showGenerateAction ? "button" : "submit",
              title: showGenerateAction ? "Generate response" : void 0,
              "aria-label": showGenerateAction ? "Generate response" : "Send message",
              disabled: aiGenerating || showGenerateAction && !aiResponseContext,
              onclick: (event) => {
                if (!showGenerateAction) return;
                event.preventDefault();
                void handleGenerateUserResponse();
              },
              children: ($$renderer5) => {
                if (showGenerateAction) {
                  $$renderer5.push("<!--[-->");
                  Icon($$renderer5, { name: "sparkles" });
                } else {
                  $$renderer5.push("<!--[!-->");
                  Icon($$renderer5, { name: "send" });
                }
                $$renderer5.push(`<!--]-->`);
              },
              $$slots: { default: true }
            });
            $$renderer4.push(`<!----></fieldset></form>`);
          }
          $$renderer4.push(`<!--]-->`);
        }
      });
      $$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 variantMode = null;
    let copied = null;
    let copyTimer = null;
    let copyMenuOpen = false;
    let copyMenuAnchorEl = 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,
          rationales: res.rationales,
          parallelCalls: res.parallelCalls,
          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;
      });
    }
    function setCopied(mode) {
      copied = mode;
      if (copyTimer) clearTimeout(copyTimer);
      copyTimer = window.setTimeout(
        () => {
          copied = null;
          copyTimer = null;
        },
        2e3
      );
    }
    async function copyLogs() {
      try {
        await navigator.clipboard.writeText(JSON.stringify(logContent, null, 2));
        setCopied("logs");
      } catch (e) {
        console.error("Failed to copy logs", e);
      }
    }
    async function copyTraces(includePrompts) {
      try {
        await navigator.clipboard.writeText(JSON.stringify(tracesForCopy(includePrompts), null, 2));
        setCopied(includePrompts ? "with-prompts" : "without-prompts");
      } catch (e) {
        console.error("Failed to copy traces", e);
      }
    }
    function handleNewChat() {
      clearVariantMode();
      actions.closePopover();
      actions.closeContextPopover();
      actions.selectState(null);
    }
    function parseUserMessageHeader(raw) {
      const trimmed = String(raw ?? "").trim();
      if (!trimmed) return null;
      const m = /^\[image\]\s+(.+)$/.exec(trimmed);
      if (m) {
        const url = (m[1] ?? "").trim();
        if (!url) return null;
        return { text: "", imageUrl: url };
      }
      return { text: trimmed };
    }
    function handleRegenerateTrace(trace) {
      clearVariantMode();
      const rawPrevStateId = trace?.bosunPrevStateId;
      const prevStateId = typeof rawPrevStateId === "string" && rawPrevStateId.trim() ? rawPrevStateId : null;
      const rawUserMessage = typeof trace?.bosunUserMessage === "string" && trace.bosunUserMessage || null;
      let message = rawUserMessage ? parseUserMessageHeader(rawUserMessage) : null;
      if (!message) {
        const traceStateId = trace?.bosunStateId;
        if (typeof traceStateId === "string" && traceStateId.trim()) {
          const state = workspace.agentStates.find((s) => s.id === traceStateId);
          message = parseUserMessageHeader(state?.userMessage ?? "");
        }
      }
      if (!message) return;
      actions.selectState(prevStateId);
      actions.sendChatMessage({
        sender: "user",
        text: message.text,
        imageUrl: message.imageUrl
      });
    }
    function clearVariantMode() {
      variantMode = null;
    }
    function currentVariantPromptUpdate() {
      const stepName = workspace.currentStep?.name?.trim();
      if (!stepName) return null;
      const prompt = workspace.promptDrafts[stepName];
      if (typeof prompt !== "string") return null;
      return { step: stepName, prompt };
    }
    function rawUserMessageForTrace(trace) {
      const rawUserMessage = typeof trace?.bosunUserMessage === "string" ? trace.bosunUserMessage : null;
      if (rawUserMessage && rawUserMessage.trim()) return rawUserMessage;
      const traceStateId = trace?.bosunStateId;
      if (typeof traceStateId !== "string" || !traceStateId.trim()) return null;
      const state = workspace.agentStates.find((entry) => entry.id === traceStateId);
      const candidate = typeof state?.userMessage === "string" ? state.userMessage.trim() : "";
      return candidate || null;
    }
    async function requestVariants(trace) {
      const targetStateId = typeof trace?.bosunStateId === "string" && trace.bosunStateId.trim() ? trace.bosunStateId.trim() : null;
      if (!workspace.agentId || !targetStateId) return;
      const rawUserMessage = rawUserMessageForTrace(trace);
      if (!rawUserMessage) return;
      const prevStateId = typeof trace?.bosunPrevStateId === "string" && trace.bosunPrevStateId.trim() ? trace.bosunPrevStateId.trim() : null;
      const promptUpdate = currentVariantPromptUpdate();
      await actions.flushPromptSave();
      variantMode = {
        sourceTrace: trace,
        targetStateId,
        choices: [],
        loading: true,
        applyingId: null,
        error: null
      };
      try {
        const choices = await trpc.agents.generateVariants.mutate({
          agentId: workspace.agentId,
          region: workspace.region,
          prevStateId,
          rawUserMessage,
          context: workspace.context,
          promptUpdate,
          count: 9
        });
        if (!variantMode || variantMode.sourceTrace !== trace || variantMode.targetStateId !== targetStateId) return;
        variantMode = { ...variantMode, choices, loading: false, error: null };
      } catch (error) {
        console.error("Failed to generate variants", error);
        if (!variantMode || variantMode.sourceTrace !== trace || variantMode.targetStateId !== targetStateId) return;
        variantMode = {
          ...variantMode,
          choices: [],
          loading: false,
          error: typeof error?.message === "string" ? error.message : "Failed to generate variants"
        };
      }
    }
    function handleSeeVariants(trace) {
      void requestVariants(trace);
    }
    function handleHangup() {
      actions.hangup();
    }
    function handleRegenerateVariants() {
      const sourceTrace = variantMode?.sourceTrace;
      if (!sourceTrace) return;
      void requestVariants(sourceTrace);
    }
    function handleChooseOriginalVariant() {
      clearVariantMode();
    }
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      $$renderer3.push(`<div class="relative flex h-full min-h-0 flex-col"><div class="flex flex-none flex-nowrap items-center gap-2 p-2">`);
      if (workspace.agentStates.length > 1) {
        $$renderer3.push("<!--[-->");
        History($$renderer3, {
          agentStates: workspace.agentStates,
          currentState: workspace.currentState,
          class: "ml-9",
          onSelectState: (id) => actions.selectState(id)
        });
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]--> <div class="ml-auto flex flex-none flex-nowrap items-center gap-2">`);
      Button($$renderer3, {
        variant: "secondary",
        size: "small",
        disabled: !workspace.agentId,
        "aria-expanded": workspace.contextPopoverOpen,
        "aria-haspopup": "dialog",
        onclick: actions.toggleContextPopover,
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->Edit context`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----> `);
      Button($$renderer3, {
        variant: "secondary",
        size: "small",
        disabled: !chatContent.length && !logContent.length,
        "aria-expanded": copyMenuOpen,
        "aria-haspopup": "listbox",
        "aria-controls": "roleplay-copy-dropdown",
        onclick: (e) => {
          e.stopPropagation();
          copyMenuOpen = !copyMenuOpen;
        },
        get el() {
          return copyMenuAnchorEl;
        },
        set el($$value) {
          copyMenuAnchorEl = $$value;
          $$settled = false;
        },
        children: ($$renderer4) => {
          if (copied === "logs") {
            $$renderer4.push("<!--[-->");
            $$renderer4.push(`Copied logs`);
          } else {
            $$renderer4.push("<!--[!-->");
            if (copied === "with-prompts") {
              $$renderer4.push("<!--[-->");
              $$renderer4.push(`Copied traces (with prompts)`);
            } else {
              $$renderer4.push("<!--[!-->");
              if (copied === "without-prompts") {
                $$renderer4.push("<!--[-->");
                $$renderer4.push(`Copied traces (without prompts)`);
              } else {
                $$renderer4.push("<!--[!-->");
                $$renderer4.push(`Copy...`);
              }
              $$renderer4.push(`<!--]-->`);
            }
            $$renderer4.push(`<!--]-->`);
          }
          $$renderer4.push(`<!--]-->`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----> `);
      {
        let children = function($$renderer4) {
          $$renderer4.push(`<div class="mt-1 w-max 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",
            disabled: !logContent.length,
            onclick: (e) => {
              e.stopPropagation();
              copyMenuOpen = false;
              copyLogs();
            },
            class: "block 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(`<!---->Copy logs`);
            },
            $$slots: { default: true }
          });
          $$renderer4.push(`<!----> `);
          Button($$renderer4, {
            variant: "ghost",
            size: "small",
            role: "option",
            disabled: !chatContent.length,
            onclick: (e) => {
              e.stopPropagation();
              copyMenuOpen = false;
              copyTraces(true);
            },
            class: "block 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(`<!---->Copy traces with prompts`);
            },
            $$slots: { default: true }
          });
          $$renderer4.push(`<!----> `);
          Button($$renderer4, {
            variant: "ghost",
            size: "small",
            role: "option",
            disabled: !chatContent.length,
            onclick: (e) => {
              e.stopPropagation();
              copyMenuOpen = false;
              copyTraces(false);
            },
            class: "block 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(`<!---->Copy traces without prompts`);
            },
            $$slots: { default: true }
          });
          $$renderer4.push(`<!----></div>`);
        };
        Dropdown($$renderer3, {
          id: "roleplay-copy-dropdown",
          open: copyMenuOpen,
          onClose: () => copyMenuOpen = false,
          anchorEl: copyMenuAnchorEl,
          placement: "bottom-end",
          offset: [0, 1],
          children
        });
      }
      $$renderer3.push(`<!----> `);
      Button($$renderer3, {
        size: "small",
        onclick: handleNewChat,
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->New chat`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----></div></div> <div class="min-h-0 flex-1">`);
      if (!workspace.wsLoaded || !workspace.chatReady) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<div class="flex h-full items-center justify-center text-sm text-rc-gray-300">Connecting…</div>`);
      } else {
        $$renderer3.push("<!--[!-->");
        if (!workspace.agentId) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<div class="flex h-full items-center justify-center text-sm text-rc-gray-300">Select an agent to start chatting</div>`);
        } else {
          $$renderer3.push("<!--[!-->");
          $$renderer3.push(`<div class="h-full min-h-0 p-2">`);
          PlaygroundChat($$renderer3, {
            class: "h-full min-w-0",
            context: workspace.context,
            agentId: workspace.agentId,
            agentType: workspace.agentType,
            analyzeDisabled: analyzeRunning,
            onAnalyzeTrace: handleAnalyzeTrace,
            onRegenerateTrace: handleRegenerateTrace,
            onRevertToState: (stateId) => actions.selectState(stateId),
            onSeeVariants: handleSeeVariants,
            onHangup: handleHangup,
            variantSourceTrace: variantMode?.sourceTrace ?? null,
            variantChoices: variantMode?.choices ?? [],
            variantLoading: variantMode?.loading ?? false,
            variantApplyingId: variantMode?.applyingId ?? null,
            variantError: variantMode?.error ?? null,
            onRegenerateVariants: handleRegenerateVariants,
            onChooseOriginalVariant: handleChooseOriginalVariant
          });
          $$renderer3.push(`<!----></div>`);
        }
        $$renderer3.push(`<!--]-->`);
      }
      $$renderer3.push(`<!--]--></div></div>`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
  });
}

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