import { a as attr, s as stringify, e as ensure_array_like, b as attr_class } from './index2-BuOY2QE4.js';
import { s as setEditWorkspaceContext, P as Panel, g as getEditWorkspaceContext } from './edit-workspace-context-OTOIRCI0.js';
import { B as Button } from './Button-DZYrr6c0.js';
import { T as Tabs, a as Tab } from './Tab-ClYAMM-e.js';
import { M as Modal } from './Modal-D4tx0Bdo.js';
import { X as escape_html } from './context-zH5kvtGY.js';
import { o as onDestroy } from './index-server-CefdgakO.js';
import { p as page, g as goto } from './index3-DeV2OWZf.js';
import { p as public_env } from './shared-server-DaWdgxVh.js';
import { t as trpc } from './trpc-client-Bucti7HD.js';
import 'nunjucks';
import { A as AgentSidebar } from './AgentSidebar-BB_yQ9s0.js';
import { g as getAgentsContext } from './agents-context-BrlIlkOW.js';
import { C as ContextEditor } from './ContextEditor-ByGoXY5_.js';
import { c as clearChatContent, a as clearLogs } from './log-content.svelte-B3ZvaoLs.js';
import './index-DxaLoiKh.js';
import './events-M0vvlm3M.js';
import './state.svelte-DtOGaiYC.js';
import './utils-KcIDVAAe.js';
import '@trpc/client';
import './Icon-BgknHaZs.js';
import 'js-yaml';

function PopoverModal($$renderer, $$props) {
  let { title, onClose, children } = $$props;
  $$renderer.push(`<div class="absolute inset-0 z-20 bg-black/20"></div> <div class="absolute inset-2 z-30 flex min-w-0 flex-col overflow-hidden rounded-lg border border-rc-gray-600 bg-rc-gray-900 shadow-2xl"><div class="flex items-center justify-between border-b border-rc-gray-700 px-3 py-2"><button type="button" class="inline-flex h-7 w-7 items-center justify-center rounded-md text-rc-gray-200 hover:bg-rc-gray-700" aria-label="Close" title="Close">X</button> <div class="text-sm font-semibold text-rc-gray-200">${escape_html(title)}</div> <div class="w-7"></div></div> <div class="flex min-h-0 flex-1 flex-col overflow-hidden">`);
  children($$renderer);
  $$renderer.push(`<!----></div></div>`);
}
class WebSocketClient {
  constructor(wsUrl) {
    this.wsUrl = wsUrl;
  }
  ws = null;
  openHandler = null;
  closeHandler = null;
  errorHandler = null;
  messageHandler = null;
  retries = 0;
  maxRetries = 5;
  retryDelay = 500;
  retryTimeout = null;
  isOpen = false;
  isDestroyed = false;
  agentsLoaded = false;
  init = () => {
    if (this.isOpen) {
      return;
    }
    this.agentsLoaded = false;
    console.log(`Initializing websocket connection with [${this.wsUrl}]`);
    try {
      this.ws = new WebSocket(this.wsUrl);
    } catch (e) {
      this.retryConnect();
      return;
    }
    this.isDestroyed = false;
    this.ws.onmessage = (event) => {
      const message = JSON.parse(event.data);
      if (message.channel === "error") {
        this.errorHandler?.(message.message);
      } else if (message.channel === "app-events") {
        console.log("MSG:", message.event.type);
        if (message.event.type === "agents-loaded") {
          this.agentsLoaded = true;
        }
      } else if (message.channel === "log") {
        console.log(`MSG: log [${message.message.severity}]`, message.message.message);
      } else if (message.channel === "api-call-trace") {
        console.log(
          "MSG: api-call-trace",
          message.trace?.operationName,
          message.trace?.method,
          message.trace?.path
        );
      } else if (message.channel === "conversational-trace") {
        console.log(
          "MSG: conversational-trace",
          message.trace?.eventName,
          message.trace?.role,
          message.trace?.medium
        );
      }
      this.messageHandler?.(message);
    };
    this.ws.onerror = (error) => {
      console.error("Websocket error:", error);
      this.ws?.close();
      this.retryConnect();
    };
    this.ws.onclose = () => {
      console.log("Websocket closed");
      this.isOpen = false;
      this.retryConnect();
    };
    this.ws.onopen = () => {
      this.retries = 0;
      this.isOpen = true;
      if (this.retryTimeout) {
        clearTimeout(this.retryTimeout);
      }
      this.openHandler?.();
      console.log("Websocket connected");
    };
  };
  destroy = () => {
    this.isDestroyed = true;
    this.ws?.close();
  };
  onOpen = (handler) => {
    this.openHandler = handler;
    if (this.isOpen) {
      handler();
    }
  };
  onClose = (handler) => {
    this.closeHandler = handler;
    if (!this.isOpen) {
      handler();
    }
  };
  onError = (handler) => {
    this.errorHandler = handler;
  };
  onMessage = (handler) => {
    this.messageHandler = handler;
  };
  sendMessage = (message) => {
    if (message.channel === "app-events") ;
    this.ws?.send(JSON.stringify(message));
  };
  isReady = () => this.isOpen && this.agentsLoaded;
  retryConnect = () => {
    if (this.isDestroyed) return;
    if (!this.isOpen && this.retries < this.maxRetries) {
      this.retries++;
      this.init();
      this.retryTimeout = setTimeout(this.retryConnect, this.retryDelay);
    } else {
      this.errorHandler?.("WebSocket Error, please reload the browser");
      this.closeHandler?.();
    }
  };
}
const wsHost = public_env.PUBLIC_WS_HOST ?? "ws://localhost:8080";
const wsClient = new WebSocketClient(wsHost);
function SchemaEditor($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let editor = null;
    let model = null;
    let disposables = [];
    let { class: className } = $$props;
    onDestroy(() => {
      for (const d of disposables) {
        try {
          d.dispose();
        } catch {
        }
      }
      disposables = [];
      const toDisposeModel = model;
      model = null;
      try {
        if (editor) {
          try {
            editor.setModel(null);
          } catch {
          }
          editor.dispose();
        }
      } finally {
        editor = null;
      }
      try {
        toDisposeModel?.dispose();
      } catch {
      }
    });
    Panel($$renderer2, {
      class: `overflow-hidden ${stringify(className)}`,
      children: ($$renderer3) => {
        $$renderer3.push(`<div class="flex h-full flex-col"><div class="h-full w-full"></div></div>`);
      }
    });
  });
}
function PromptEditor($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let {
      class: className,
      showSchemaButton,
      onSchemaClick,
      readOnly = false,
      showPreviewToggle = true,
      preview = null
    } = $$props;
    let internalPreview = false;
    const effectivePreview = preview !== null ? preview : internalPreview;
    Panel($$renderer2, {
      class: `relative overflow-hidden ${stringify(className)}`,
      children: ($$renderer3) => {
        $$renderer3.push(`<div class="prompt-editor flex h-full flex-col"><div class="relative flex-1"><div class="h-full w-full"></div> `);
        if (showPreviewToggle && !readOnly) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<label class="absolute right-6 top-1 z-10 inline-flex cursor-pointer items-center gap-2 bg-transparent text-rc-gray-100 focus:outline-none focus:ring-0"><input type="checkbox"${attr("checked", effectivePreview, true)} class="checkbox svelte-1br1z62"/> <span>Preview</span></label>`);
        } else {
          $$renderer3.push("<!--[!-->");
        }
        $$renderer3.push(`<!--]--></div> `);
        if (showSchemaButton && onSchemaClick) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<div class="flex justify-end">`);
          Button($$renderer3, {
            variant: "secondary",
            onclick: onSchemaClick,
            class: "absolute bottom-2 right-6 !font-medium",
            children: ($$renderer4) => {
              $$renderer4.push(`<!---->Schema`);
            },
            $$slots: { default: true }
          });
          $$renderer3.push(`<!----></div>`);
        } else {
          $$renderer3.push("<!--[!-->");
        }
        $$renderer3.push(`<!--]--></div>`);
      }
    });
  });
}
function ModeAsyncPopoverContent($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    const { state: workspace, actions } = getEditWorkspaceContext();
    let popoverTab = "results";
    if (workspace.edit.popover) {
      $$renderer2.push("<!--[-->");
      const popover = workspace.edit.popover;
      $$renderer2.push(`<div class="border-b border-rc-gray-700 px-2 py-1">`);
      Tabs($$renderer2, {
        value: popoverTab,
        ariaLabel: "Popover tabs",
        onChange: ({ value }) => popoverTab = value,
        children: ($$renderer3) => {
          Tab($$renderer3, {
            value: "results",
            children: ($$renderer4) => {
              $$renderer4.push(`<!---->Results`);
            }
          });
          $$renderer3.push(`<!----> `);
          Tab($$renderer3, {
            value: "raw",
            children: ($$renderer4) => {
              $$renderer4.push(`<!---->Raw`);
            }
          });
          $$renderer3.push(`<!---->`);
        },
        $$slots: { default: true }
      });
      $$renderer2.push(`<!----></div> <div class="min-h-0 flex-1 overflow-auto p-3">`);
      if (popover.status === "loading") {
        $$renderer2.push("<!--[-->");
        $$renderer2.push(`<div class="flex h-full items-center justify-center text-sm text-rc-gray-300">Loading</div>`);
      } else {
        $$renderer2.push("<!--[!-->");
        if (popover.status === "error") {
          $$renderer2.push("<!--[-->");
          if (popoverTab === "raw") {
            $$renderer2.push("<!--[-->");
            const raw = typeof popover.data?.raw === "string" ? popover.data.raw : popover.error;
            $$renderer2.push(`<pre class="whitespace-pre-wrap font-mono text-xs text-rc-gray-200">${escape_html(raw || "—")}</pre>`);
          } else {
            $$renderer2.push("<!--[!-->");
            $$renderer2.push(`<div class="flex h-full flex-col gap-3"><div class="text-sm text-red-400">${escape_html(popover.error)}</div></div>`);
          }
          $$renderer2.push(`<!--]-->`);
        } else {
          $$renderer2.push("<!--[!-->");
          const data = popover.data;
          if (popoverTab === "raw") {
            $$renderer2.push("<!--[-->");
            $$renderer2.push(`<pre class="whitespace-pre-wrap font-mono text-xs text-rc-gray-200">${escape_html(typeof data?.raw === "string" ? data.raw : "—")}</pre>`);
          } else {
            $$renderer2.push("<!--[!-->");
            if (popover.kind === "analyze") {
              $$renderer2.push("<!--[-->");
              $$renderer2.push(`<div class="mb-3 text-sm font-semibold text-rc-gray-100">${escape_html(data?.title ?? "Analysis")}</div> `);
              if (Array.isArray(data?.quotes) && data.quotes.length > 0) {
                $$renderer2.push("<!--[-->");
                $$renderer2.push(`<div class="flex flex-col gap-2"><!--[-->`);
                const each_array = ensure_array_like(data.quotes);
                for (let i = 0, $$length = each_array.length; i < $$length; i++) {
                  let q = each_array[i];
                  $$renderer2.push(`<button type="button" class="rounded-md border border-rc-gray-700 bg-rc-gray-900/40 px-3 py-2 text-left hover:border-rc-gray-500"><div class="flex items-center justify-between text-xs text-rc-gray-400"><div>Quote ${escape_html(i + 1)}</div> <div>x${escape_html(q.count)}/10</div></div> <div class="whitespace-pre-wrap break-words text-sm text-rc-gray-100">${escape_html(q.quote)}</div></button>`);
                }
                $$renderer2.push(`<!--]--></div>`);
              } else {
                $$renderer2.push("<!--[!-->");
                $$renderer2.push(`<div class="text-sm text-rc-gray-300">No quotes returned.</div>`);
              }
              $$renderer2.push(`<!--]-->`);
            } else {
              $$renderer2.push("<!--[!-->");
              $$renderer2.push(`<div class="mb-3 text-sm font-semibold text-rc-gray-100">${escape_html(data?.title ?? "Prompt issues")}</div> `);
              if (Array.isArray(data?.issues) && data.issues.length > 0) {
                $$renderer2.push("<!--[-->");
                $$renderer2.push(`<div class="flex flex-col gap-3"><!--[-->`);
                const each_array_1 = ensure_array_like(data.issues);
                for (let i = 0, $$length = each_array_1.length; i < $$length; i++) {
                  let issue = each_array_1[i];
                  $$renderer2.push(`<div class="rounded-md border border-rc-gray-700 bg-rc-gray-900/40 p-3"><div class="flex items-start justify-between gap-3"><div class="text-xs font-semibold text-rc-gray-400">Issue ${escape_html(i + 1)}</div> <div class="text-xs text-rc-gray-500">${escape_html(issue.type)}</div></div> <div class="mt-1 whitespace-pre-wrap break-words text-sm text-rc-gray-100">${escape_html(issue.reason)}</div> `);
                  if (issue.contradictingQuotes && issue.contradictingQuotes.length > 0) {
                    $$renderer2.push("<!--[-->");
                    $$renderer2.push(`<div class="mt-3 flex flex-col gap-2"><!--[-->`);
                    const each_array_2 = ensure_array_like(issue.contradictingQuotes);
                    for (let $$index_1 = 0, $$length2 = each_array_2.length; $$index_1 < $$length2; $$index_1++) {
                      let q = each_array_2[$$index_1];
                      $$renderer2.push(`<button type="button" class="rounded-md border border-rc-gray-700 bg-rc-gray-900/40 px-3 py-2 text-left hover:border-rc-gray-500"><div class="whitespace-pre-wrap break-words text-sm text-rc-gray-100">${escape_html(q)}</div></button>`);
                    }
                    $$renderer2.push(`<!--]--></div>`);
                  } else {
                    $$renderer2.push("<!--[!-->");
                  }
                  $$renderer2.push(`<!--]--></div>`);
                }
                $$renderer2.push(`<!--]--></div>`);
              } else {
                $$renderer2.push("<!--[!-->");
                $$renderer2.push(`<div class="text-sm text-rc-gray-300">No issues found.</div>`);
              }
              $$renderer2.push(`<!--]-->`);
            }
            $$renderer2.push(`<!--]-->`);
          }
          $$renderer2.push(`<!--]-->`);
        }
        $$renderer2.push(`<!--]-->`);
      }
      $$renderer2.push(`<!--]--></div>`);
    } else {
      $$renderer2.push("<!--[!-->");
    }
    $$renderer2.push(`<!--]-->`);
  });
}
function ModeContextPopoverContent($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    const tmp = getEditWorkspaceContext(), workspace = tmp.state, actions = tmp.actions;
    function handleContextChanged(newContext) {
      workspace.context = newContext;
      actions.sendAppEvent({ type: "context-updated", context: newContext });
    }
    $$renderer2.push(`<div class="min-h-0 flex-1 overflow-hidden p-3">`);
    ContextEditor($$renderer2, {
      class: "h-full min-h-0 border-thin border-rc-gray-650 shadow-inner-white-soft backdrop-blur-3xl focus:outline-none focus:ring-0",
      context: workspace.context,
      onContextChanged: handleContextChanged,
      suppressErrors: true
    });
    $$renderer2.push(`<!----></div>`);
  });
}
function safeDecodeURIComponent(raw) {
  try {
    return decodeURIComponent(raw);
  } catch {
    return raw;
  }
}
function parseEditPath(pathname) {
  const cleaned = String(pathname || "").split("?")[0]?.split("#")[0] ?? "";
  const parts = cleaned.split("/").filter(Boolean);
  if (parts[0] !== "edit") return { agentId: null, tab: null };
  if (parts.length === 1) return { agentId: null, tab: null };
  const agentId = safeDecodeURIComponent(parts[1] ?? "");
  const maybeTab = parts[2] ?? null;
  if (!maybeTab) return { agentId, tab: "roleplay" };
  if (maybeTab === "roleplay") return { agentId, tab: "roleplay" };
  if (maybeTab === "tests") return { agentId, tab: "tests" };
  return { agentId, tab: null };
}
function initEditState(input) {
  const parsed = parseEditPath(input.pathname);
  const tab = parsed.tab ?? "roleplay";
  return {
    tab,
    popover: null,
    highlights: null,
    requestSeq: 0
  };
}
function openPopover(state, input) {
  const requestSeq = state.requestSeq + 1;
  return {
    ...state,
    requestSeq,
    popover: {
      kind: input.kind,
      status: "loading",
      requestId: requestSeq
    },
    highlights: null
  };
}
function setPopoverReady(state, input) {
  if (!state.popover) return state;
  if (state.popover.requestId !== input.requestId) return state;
  return {
    ...state,
    popover: { ...state.popover, status: "ready", data: input.data, error: void 0 }
  };
}
function setPopoverError(state, input) {
  if (!state.popover) return state;
  if (state.popover.requestId !== input.requestId) return state;
  return {
    ...state,
    popover: {
      ...state.popover,
      status: "error",
      error: String(input.error || "Unknown error"),
      data: input.data
    }
  };
}
function closePopover(state) {
  return {
    ...state,
    popover: null,
    highlights: null
  };
}
function setHighlightQuotes(state, quotes) {
  return {
    ...state,
    highlights: {
      quotes: quotes ?? [],
      focusQuote: null,
      focusNonce: 0
    }
  };
}
function focusQuote(state, quote) {
  const q = String(quote || "");
  if (!q) return state;
  const prev = state.highlights ?? { quotes: [], focusQuote: null, focusNonce: 0 };
  return {
    ...state,
    highlights: {
      ...prev,
      focusQuote: q,
      focusNonce: (prev.focusNonce ?? 0) + 1
    }
  };
}
function _layout($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let { params, children } = $$props;
    const { onError } = getAgentsContext();
    let agents = [];
    const dec = (s) => {
      try {
        return s ? decodeURIComponent(s) : "";
      } catch {
        return s || "";
      }
    };
    const enc = (s) => encodeURIComponent(s);
    function normalizeAgentId(raw) {
      return dec(raw).trim().replace(/^\/+|\/+$/g, "");
    }
    (() => normalizeAgentId(params.agent))();
    const workspace = {
      agentId: normalizeAgentId(params.agent),
      wsLoaded: false,
      steps: [],
      currentStep: null,
      prompt: "",
      context: null,
      promptContext: null,
      agentStates: [],
      currentState: null,
      contextPopoverOpen: false,
      edit: initEditState({ pathname: page.url.pathname })
    };
    function sendAppEvent(event) {
      wsClient.sendMessage({ channel: "app-events", event });
    }
    const schemaValue = workspace.currentStep?.schema ?? null;
    const hasSchema = !!schemaValue && schemaValue.trim().length > 0;
    let schemaModalOpen = false;
    function openSchemaModal() {
      if (!schemaValue) return;
      schemaModalOpen = true;
    }
    function handleModeTabChange({ value }) {
      if (value === workspace.edit.tab) return;
      closeAllPopovers();
      page.url.searchParams.get("step");
      `/edit/${enc(workspace.agentId)}/${value}`;
      goto();
    }
    const activeTopTab = (() => {
      const head = page.url.pathname.split("/")[1];
      return head === "traces" ? "view" : head;
    })();
    function handleTopTabChange({ value }) {
      if (value === activeTopTab) return;
      closeAllPopovers();
      if (value === "edit") return goto();
      if (value === "view") return goto();
      goto();
    }
    function openModePopover(kind) {
      workspace.contextPopoverOpen = false;
      workspace.edit = openPopover(workspace.edit, { kind });
      return workspace.edit.popover?.requestId ?? 0;
    }
    function setModePopoverReady(requestId, data) {
      workspace.edit = setPopoverReady(workspace.edit, { requestId, data });
    }
    function setModePopoverError(requestId, error, data) {
      workspace.edit = setPopoverError(workspace.edit, { requestId, error, data });
    }
    function closeModePopover() {
      workspace.edit = closePopover(workspace.edit);
    }
    function openContextPopover() {
      closeModePopover();
      workspace.contextPopoverOpen = true;
    }
    function closeContextPopover() {
      workspace.contextPopoverOpen = false;
    }
    function toggleContextPopover() {
      if (workspace.contextPopoverOpen) closeContextPopover();
      else openContextPopover();
    }
    function closeAllPopovers() {
      closeModePopover();
      closeContextPopover();
    }
    function popoverTitle(kind) {
      if (kind === "analyze") return "Analyze";
      return "Find issues";
    }
    function setQuotes(quotes) {
      workspace.edit = setHighlightQuotes(workspace.edit, quotes);
    }
    function focusOnQuote(quote) {
      workspace.edit = focusQuote(workspace.edit, quote);
    }
    let promptHighlighter = null;
    let previewEnabled = false;
    function clamp(n, min, max) {
      return Math.max(min, Math.min(max, n));
    }
    function buildQuoteCountsFromIssues(issues) {
      const counts = /* @__PURE__ */ new Map();
      for (const issue of issues || []) {
        for (const raw of issue.contradictingQuotes || []) {
          const q = String(raw || "").trim();
          if (!q) continue;
          counts.set(q, (counts.get(q) || 0) + 1);
        }
      }
      return [...counts.entries()].map(([quote, count]) => ({ quote, count: clamp(count, 1, 10) })).sort((a, b) => b.count - a.count || a.quote.localeCompare(b.quote));
    }
    let findIssuesRunning = false;
    async function handleFindIssues() {
      if (findIssuesRunning) return;
      if (!workspace.currentStep) return;
      findIssuesRunning = true;
      const requestId = openModePopover("findIssues");
      try {
        const res = await trpc.tests.findPromptIssues.mutate({
          agent: workspace.agentId,
          step: workspace.currentStep.name,
          prompt: workspace.prompt ?? ""
        });
        const quoteCounts = buildQuoteCountsFromIssues(res.issues || []);
        if (workspace.edit.popover?.requestId !== requestId) return;
        setQuotes(quoteCounts);
        let raw = null;
        try {
          raw = JSON.stringify(res.raw, null, 2);
        } catch {
          raw = null;
        }
        setModePopoverReady(requestId, {
          title: `Prompt issues — ${workspace.currentStep.name}`,
          issues: res.issues,
          raw
        });
      } catch (e) {
        console.error(e);
        const message = typeof e?.message === "string" ? e.message : (() => {
          try {
            return JSON.stringify(e);
          } catch {
            return String(e);
          }
        })();
        setModePopoverError(requestId, message || "Failed to find issues in this prompt", {
          title: `Prompt issues failed — ${workspace.currentStep.name}`,
          raw: message
        });
      } finally {
        findIssuesRunning = false;
      }
    }
    function handleAgentClick(agentId) {
      closeAllPopovers();
      page.url.searchParams.get("step");
      `/edit/${enc(agentId)}/${workspace.edit.tab}`;
      goto();
    }
    setEditWorkspaceContext({
      state: workspace,
      actions: {
        openPopover: openModePopover,
        setPopoverReady: setModePopoverReady,
        setPopoverError: setModePopoverError,
        closePopover: closeModePopover,
        setHighlightQuotes: setQuotes,
        focusQuote: focusOnQuote,
        openContextPopover,
        closeContextPopover,
        toggleContextPopover,
        sendAppEvent,
        sendChatMessage: (message) => wsClient.sendMessage({ channel: "chat", message }),
        selectState: (stateId) => {
          closeAllPopovers();
          workspace.currentState = stateId;
          clearChatContent();
          clearLogs();
          sendAppEvent({
            type: "select-agent",
            agent: workspace.agentId,
            state: stateId
          });
        }
      }
    });
    onDestroy(() => {
      promptHighlighter?.dispose();
      promptHighlighter = null;
    });
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      $$renderer3.push(`<div class="flex h-screen">`);
      AgentSidebar($$renderer3, {
        className: "flex-none",
        agents,
        currentAgent: workspace.agentId,
        onAgentClick: handleAgentClick
      });
      $$renderer3.push(`<!----> <div class="flex h-full min-w-0 flex-1 flex-col bg-rc-gray-980 pb-3 pr-4 pt-2"><nav class="flex flex-none items-center justify-center bg-rc-gray-980">`);
      Tabs($$renderer3, {
        value: activeTopTab,
        ariaLabel: "Top tabs",
        onChange: handleTopTabChange,
        children: ($$renderer4) => {
          Tab($$renderer4, {
            value: "edit",
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->Edit`);
            }
          });
          $$renderer4.push(`<!----> `);
          Tab($$renderer4, {
            value: "view",
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->View`);
            }
          });
          $$renderer4.push(`<!---->`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----></nav> <div class="flex-1 overflow-hidden"><div class="grid h-full w-full grid-cols-[minmax(140px,2fr)_minmax(0,10fr)_minmax(0,11fr)]">`);
      Panel($$renderer3, {
        class: "flex h-full min-w-0 flex-col !rounded-none p-0",
        children: ($$renderer4) => {
          $$renderer4.push(`<div class="rc-scroll min-h-0 flex-1 overflow-auto p-2">`);
          if (!workspace.wsLoaded) {
            $$renderer4.push("<!--[-->");
            $$renderer4.push(`<div class="p-2 text-rc-gray-400">Connecting…</div>`);
          } else {
            $$renderer4.push("<!--[!-->");
            if (workspace.steps.length === 0) {
              $$renderer4.push("<!--[-->");
              $$renderer4.push(`<div class="p-2 text-rc-gray-400">No steps</div>`);
            } else {
              $$renderer4.push("<!--[!-->");
              $$renderer4.push(`<!--[-->`);
              const each_array = ensure_array_like(workspace.steps);
              for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
                let step = each_array[$$index];
                $$renderer4.push(`<button${attr_class(`my-1 w-full rounded-lg px-3 py-2 text-left text-rc-gray-200 hover:bg-rc-gray-700 ${stringify(step.name === workspace.currentStep?.name ? "bg-rc-gray-600" : "bg-transparent")}`)}><span class="block truncate">${escape_html(step.name)}</span></button>`);
              }
              $$renderer4.push(`<!--]-->`);
            }
            $$renderer4.push(`<!--]-->`);
          }
          $$renderer4.push(`<!--]--></div>`);
        }
      });
      $$renderer3.push(`<!----> <div class="flex h-full min-w-0 flex-col"><div class="flex h-14 flex-none items-center justify-between gap-3 border-b border-rc-gray-700 p-2"><div class="min-w-0"><div class="truncate font-semibold text-rc-gray-100">${escape_html(workspace.currentStep?.name ?? "Prompt")}</div></div> <div class="flex items-center gap-3"><label class="inline-flex items-center gap-2 text-rc-gray-300"><input type="checkbox"${attr("checked", previewEnabled, true)}${attr("disabled", !workspace.currentStep, true)} aria-label="Preview rendered prompt" class="h-4 w-4 appearance-none rounded border border-rc-gray-300 bg-rc-gray-600 !accent-rc-gray-600 outline-none ring-0 checked:border-rc-gray-200 checked:bg-rc-gray-600 hover:border-rc-gray-200 hover:bg-rc-gray-600 focus:outline-none focus:ring-0 active:border-rc-gray-200 active:bg-rc-gray-600 disabled:cursor-not-allowed disabled:opacity-50"/> <span>Preview</span></label> `);
      Button($$renderer3, {
        variant: "secondary",
        disabled: !workspace.currentStep || findIssuesRunning,
        onclick: handleFindIssues,
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->Find issues`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----></div></div> <div class="min-h-0 flex-1">`);
      if (workspace.currentStep) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<!---->`);
        {
          PromptEditor($$renderer3, {
            class: "h-full min-w-0 border-thin border-rc-gray-650 bg-rc-gray-800 shadow-inner-white-soft backdrop-blur-3xl focus:outline-none focus:ring-0",
            prompt: workspace.prompt ?? "",
            agentId: workspace.agentId,
            showSchemaButton: hasSchema,
            onSchemaClick: openSchemaModal,
            showPreviewToggle: false,
            preview: previewEnabled
          });
        }
        $$renderer3.push(`<!---->`);
      } else {
        $$renderer3.push("<!--[!-->");
        Panel($$renderer3, {
          class: "flex h-full min-w-0 items-center justify-center !rounded-none p-4 text-sm text-rc-gray-400",
          children: ($$renderer4) => {
            $$renderer4.push(`<!---->Select a step to edit its prompt`);
          }
        });
      }
      $$renderer3.push(`<!--]--></div></div> `);
      Panel($$renderer3, {
        class: "relative flex h-full min-w-0 flex-col overflow-hidden !rounded-none p-0",
        children: ($$renderer4) => {
          $$renderer4.push(`<div class="border-b border-rc-gray-700 p-2">`);
          Tabs($$renderer4, {
            value: workspace.edit.tab,
            ariaLabel: "Mode tabs",
            onChange: handleModeTabChange,
            children: ($$renderer5) => {
              Tab($$renderer5, {
                value: "roleplay",
                children: ($$renderer6) => {
                  $$renderer6.push(`<!---->Roleplay`);
                }
              });
              $$renderer5.push(`<!----> `);
              Tab($$renderer5, {
                value: "tests",
                children: ($$renderer6) => {
                  $$renderer6.push(`<!---->Tests`);
                }
              });
              $$renderer5.push(`<!---->`);
            },
            $$slots: { default: true }
          });
          $$renderer4.push(`<!----></div> <div class="min-h-0 flex-1">`);
          children($$renderer4);
          $$renderer4.push(`<!----></div> `);
          if (workspace.edit.popover) {
            $$renderer4.push("<!--[-->");
            {
              let children2 = function($$renderer5) {
                ModeAsyncPopoverContent($$renderer5);
              };
              PopoverModal($$renderer4, {
                title: popoverTitle(workspace.edit.popover.kind),
                onClose: closeModePopover,
                children: children2
              });
            }
          } else {
            $$renderer4.push("<!--[!-->");
          }
          $$renderer4.push(`<!--]--> `);
          if (workspace.contextPopoverOpen) {
            $$renderer4.push("<!--[-->");
            {
              let children2 = function($$renderer5) {
                ModeContextPopoverContent($$renderer5);
              };
              PopoverModal($$renderer4, {
                title: "Edit context",
                onClose: closeContextPopover,
                children: children2
              });
            }
          } else {
            $$renderer4.push("<!--[!-->");
          }
          $$renderer4.push(`<!--]-->`);
        }
      });
      $$renderer3.push(`<!----></div></div></div></div> `);
      if (schemaValue) {
        $$renderer3.push("<!--[-->");
        {
          let children2 = function($$renderer4) {
            SchemaEditor($$renderer4, {
              class: "h-[70vh] min-w-0"
            });
          };
          Modal($$renderer3, {
            title: "Schema",
            class: "!w-[80vw] !max-w-5xl",
            get open() {
              return schemaModalOpen;
            },
            set open($$value) {
              schemaModalOpen = $$value;
              $$settled = false;
            },
            children: children2,
            $$slots: { default: true }
          });
        }
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]-->`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
  });
}

export { _layout as default };
//# sourceMappingURL=_layout.svelte-Fo2hGNeP.js.map
