import { h as head, b as attr_class, a as attr, s as stringify, e as ensure_array_like, c as attr_style, j as attributes } from './index2-BuOY2QE4.js';
import { g as getEditWorkspaceContext, P as Panel } from './edit-workspace-context-OTOIRCI0.js';
import { B as Button } from './Button-Cd4Yzpdy.js';
import { M as Modal } from './Modal-D4tx0Bdo.js';
import { C as ContextEditor, P as PopoverModal } from './ContextEditor-CfjBPLpI.js';
import { I as Input } from './Input-BJW36iKz.js';
import { o as onDestroy } from './index-server-CefdgakO.js';
import { I as Icon$1, h as html } from './Icon-BgknHaZs.js';
import { t as trpc } from './trpc-client-Bucti7HD.js';
import { X as escape_html } from './context-zH5kvtGY.js';
import './events-M0vvlm3M.js';
import 'js-yaml';
import '@trpc/client';

const matchIconName = /^[a-z0-9]+(-[a-z0-9]+)*$/;
const stringToIcon = (value, validate, allowSimpleName, provider = "") => {
  const colonSeparated = value.split(":");
  if (value.slice(0, 1) === "@") {
    if (colonSeparated.length < 2 || colonSeparated.length > 3) return null;
    provider = colonSeparated.shift().slice(1);
  }
  if (colonSeparated.length > 3 || !colonSeparated.length) return null;
  if (colonSeparated.length > 1) {
    const name$1 = colonSeparated.pop();
    const prefix = colonSeparated.pop();
    const result = {
      provider: colonSeparated.length > 0 ? colonSeparated[0] : provider,
      prefix,
      name: name$1
    };
    return validate && !validateIconName(result) ? null : result;
  }
  const name = colonSeparated[0];
  const dashSeparated = name.split("-");
  if (dashSeparated.length > 1) {
    const result = {
      provider,
      prefix: dashSeparated.shift(),
      name: dashSeparated.join("-")
    };
    return validate && !validateIconName(result) ? null : result;
  }
  if (allowSimpleName && provider === "") {
    const result = {
      provider,
      prefix: "",
      name
    };
    return validate && !validateIconName(result, allowSimpleName) ? null : result;
  }
  return null;
};
const validateIconName = (icon, allowSimpleName) => {
  if (!icon) return false;
  return !!((allowSimpleName && icon.prefix === "" || !!icon.prefix) && !!icon.name);
};
function getIconsTree(data, names) {
  const icons = data.icons;
  const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  const resolved = /* @__PURE__ */ Object.create(null);
  function resolve(name) {
    if (icons[name]) return resolved[name] = [];
    if (!(name in resolved)) {
      resolved[name] = null;
      const parent = aliases[name] && aliases[name].parent;
      const value = parent && resolve(parent);
      if (value) resolved[name] = [parent].concat(value);
    }
    return resolved[name];
  }
  Object.keys(icons).concat(Object.keys(aliases)).forEach(resolve);
  return resolved;
}
const defaultIconDimensions = Object.freeze({
  left: 0,
  top: 0,
  width: 16,
  height: 16
});
const defaultIconTransformations = Object.freeze({
  rotate: 0,
  vFlip: false,
  hFlip: false
});
const defaultIconProps = Object.freeze({
  ...defaultIconDimensions,
  ...defaultIconTransformations
});
const defaultExtendedIconProps = Object.freeze({
  ...defaultIconProps,
  body: "",
  hidden: false
});
function mergeIconTransformations(obj1, obj2) {
  const result = {};
  if (!obj1.hFlip !== !obj2.hFlip) result.hFlip = true;
  if (!obj1.vFlip !== !obj2.vFlip) result.vFlip = true;
  const rotate = ((obj1.rotate || 0) + (obj2.rotate || 0)) % 4;
  if (rotate) result.rotate = rotate;
  return result;
}
function mergeIconData(parent, child) {
  const result = mergeIconTransformations(parent, child);
  for (const key in defaultExtendedIconProps) if (key in defaultIconTransformations) {
    if (key in parent && !(key in result)) result[key] = defaultIconTransformations[key];
  } else if (key in child) result[key] = child[key];
  else if (key in parent) result[key] = parent[key];
  return result;
}
function internalGetIconData(data, name, tree) {
  const icons = data.icons;
  const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  let currentProps = {};
  function parse(name$1) {
    currentProps = mergeIconData(icons[name$1] || aliases[name$1], currentProps);
  }
  parse(name);
  tree.forEach(parse);
  return mergeIconData(data, currentProps);
}
function parseIconSet(data, callback) {
  const names = [];
  if (typeof data !== "object" || typeof data.icons !== "object") return names;
  if (data.not_found instanceof Array) data.not_found.forEach((name) => {
    callback(name, null);
    names.push(name);
  });
  const tree = getIconsTree(data);
  for (const name in tree) {
    const item = tree[name];
    if (item) {
      callback(name, internalGetIconData(data, name, item));
      names.push(name);
    }
  }
  return names;
}
const optionalPropertyDefaults = {
  provider: "",
  aliases: {},
  not_found: {},
  ...defaultIconDimensions
};
function checkOptionalProps(item, defaults) {
  for (const prop in defaults) if (prop in item && typeof item[prop] !== typeof defaults[prop]) return false;
  return true;
}
function quicklyValidateIconSet(obj) {
  if (typeof obj !== "object" || obj === null) return null;
  const data = obj;
  if (typeof data.prefix !== "string" || !obj.icons || typeof obj.icons !== "object") return null;
  if (!checkOptionalProps(obj, optionalPropertyDefaults)) return null;
  const icons = data.icons;
  for (const name in icons) {
    const icon = icons[name];
    if (!name || typeof icon.body !== "string" || !checkOptionalProps(icon, defaultExtendedIconProps)) return null;
  }
  const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  for (const name in aliases) {
    const icon = aliases[name];
    const parent = icon.parent;
    if (!name || typeof parent !== "string" || !icons[parent] && !aliases[parent] || !checkOptionalProps(icon, defaultExtendedIconProps)) return null;
  }
  return data;
}
const dataStorage = /* @__PURE__ */ Object.create(null);
function newStorage(provider, prefix) {
  return {
    provider,
    prefix,
    icons: /* @__PURE__ */ Object.create(null),
    missing: /* @__PURE__ */ new Set()
  };
}
function getStorage(provider, prefix) {
  const providerStorage = dataStorage[provider] || (dataStorage[provider] = /* @__PURE__ */ Object.create(null));
  return providerStorage[prefix] || (providerStorage[prefix] = newStorage(provider, prefix));
}
function addIconSet(storage2, data) {
  if (!quicklyValidateIconSet(data)) return [];
  return parseIconSet(data, (name, icon) => {
    if (icon) storage2.icons[name] = icon;
    else storage2.missing.add(name);
  });
}
function addIconToStorage(storage2, name, icon) {
  try {
    if (typeof icon.body === "string") {
      storage2.icons[name] = { ...icon };
      return true;
    }
  } catch (err) {
  }
  return false;
}
let simpleNames = false;
function allowSimpleNames(allow) {
  if (typeof allow === "boolean") simpleNames = allow;
  return simpleNames;
}
function getIconData(name) {
  const icon = typeof name === "string" ? stringToIcon(name, true, simpleNames) : name;
  if (icon) {
    const storage2 = getStorage(icon.provider, icon.prefix);
    const iconName = icon.name;
    return storage2.icons[iconName] || (storage2.missing.has(iconName) ? null : void 0);
  }
}
function addIcon(name, data) {
  const icon = stringToIcon(name, true, simpleNames);
  if (!icon) return false;
  const storage2 = getStorage(icon.provider, icon.prefix);
  if (data) return addIconToStorage(storage2, icon.name, data);
  else {
    storage2.missing.add(icon.name);
    return true;
  }
}
function addCollection(data, provider) {
  if (typeof data !== "object") return false;
  if (typeof provider !== "string") provider = data.provider || "";
  if (simpleNames && !provider && !data.prefix) {
    let added = false;
    if (quicklyValidateIconSet(data)) {
      data.prefix = "";
      parseIconSet(data, (name, icon) => {
        if (addIcon(name, icon)) added = true;
      });
    }
    return added;
  }
  const prefix = data.prefix;
  if (!validateIconName({
    prefix,
    name: "a"
  })) return false;
  const storage2 = getStorage(provider, prefix);
  return !!addIconSet(storage2, data);
}
const defaultIconSizeCustomisations = Object.freeze({
  width: null,
  height: null
});
const defaultIconCustomisations = Object.freeze({
  ...defaultIconSizeCustomisations,
  ...defaultIconTransformations
});
const unitsSplit = /(-?[0-9.]*[0-9]+[0-9.]*)/g;
const unitsTest = /^-?[0-9.]*[0-9]+[0-9.]*$/g;
function calculateSize(size, ratio, precision) {
  if (ratio === 1) return size;
  precision = precision || 100;
  if (typeof size === "number") return Math.ceil(size * ratio * precision) / precision;
  if (typeof size !== "string") return size;
  const oldParts = size.split(unitsSplit);
  if (oldParts === null || !oldParts.length) return size;
  const newParts = [];
  let code = oldParts.shift();
  let isNumber = unitsTest.test(code);
  while (true) {
    if (isNumber) {
      const num = parseFloat(code);
      if (isNaN(num)) newParts.push(code);
      else newParts.push(Math.ceil(num * ratio * precision) / precision);
    } else newParts.push(code);
    code = oldParts.shift();
    if (code === void 0) return newParts.join("");
    isNumber = !isNumber;
  }
}
function splitSVGDefs(content, tag = "defs") {
  let defs = "";
  const index = content.indexOf("<" + tag);
  while (index >= 0) {
    const start = content.indexOf(">", index);
    const end = content.indexOf("</" + tag);
    if (start === -1 || end === -1) break;
    const endEnd = content.indexOf(">", end);
    if (endEnd === -1) break;
    defs += content.slice(start + 1, end).trim();
    content = content.slice(0, index).trim() + content.slice(endEnd + 1);
  }
  return {
    defs,
    content
  };
}
function mergeDefsAndContent(defs, content) {
  return defs ? "<defs>" + defs + "</defs>" + content : content;
}
function wrapSVGContent(body, start, end) {
  const split = splitSVGDefs(body);
  return mergeDefsAndContent(split.defs, start + split.content + end);
}
const isUnsetKeyword = (value) => value === "unset" || value === "undefined" || value === "none";
function iconToSVG(icon, customisations) {
  const fullIcon = {
    ...defaultIconProps,
    ...icon
  };
  const fullCustomisations = {
    ...defaultIconCustomisations,
    ...customisations
  };
  const box = {
    left: fullIcon.left,
    top: fullIcon.top,
    width: fullIcon.width,
    height: fullIcon.height
  };
  let body = fullIcon.body;
  [fullIcon, fullCustomisations].forEach((props) => {
    const transformations = [];
    const hFlip = props.hFlip;
    const vFlip = props.vFlip;
    let rotation = props.rotate;
    if (hFlip) if (vFlip) rotation += 2;
    else {
      transformations.push("translate(" + (box.width + box.left).toString() + " " + (0 - box.top).toString() + ")");
      transformations.push("scale(-1 1)");
      box.top = box.left = 0;
    }
    else if (vFlip) {
      transformations.push("translate(" + (0 - box.left).toString() + " " + (box.height + box.top).toString() + ")");
      transformations.push("scale(1 -1)");
      box.top = box.left = 0;
    }
    let tempValue;
    if (rotation < 0) rotation -= Math.floor(rotation / 4) * 4;
    rotation = rotation % 4;
    switch (rotation) {
      case 1:
        tempValue = box.height / 2 + box.top;
        transformations.unshift("rotate(90 " + tempValue.toString() + " " + tempValue.toString() + ")");
        break;
      case 2:
        transformations.unshift("rotate(180 " + (box.width / 2 + box.left).toString() + " " + (box.height / 2 + box.top).toString() + ")");
        break;
      case 3:
        tempValue = box.width / 2 + box.left;
        transformations.unshift("rotate(-90 " + tempValue.toString() + " " + tempValue.toString() + ")");
        break;
    }
    if (rotation % 2 === 1) {
      if (box.left !== box.top) {
        tempValue = box.left;
        box.left = box.top;
        box.top = tempValue;
      }
      if (box.width !== box.height) {
        tempValue = box.width;
        box.width = box.height;
        box.height = tempValue;
      }
    }
    if (transformations.length) body = wrapSVGContent(body, '<g transform="' + transformations.join(" ") + '">', "</g>");
  });
  const customisationsWidth = fullCustomisations.width;
  const customisationsHeight = fullCustomisations.height;
  const boxWidth = box.width;
  const boxHeight = box.height;
  let width;
  let height;
  if (customisationsWidth === null) {
    height = customisationsHeight === null ? "1em" : customisationsHeight === "auto" ? boxHeight : customisationsHeight;
    width = calculateSize(height, boxWidth / boxHeight);
  } else {
    width = customisationsWidth === "auto" ? boxWidth : customisationsWidth;
    height = customisationsHeight === null ? calculateSize(width, boxHeight / boxWidth) : customisationsHeight === "auto" ? boxHeight : customisationsHeight;
  }
  const attributes2 = {};
  const setAttr = (prop, value) => {
    if (!isUnsetKeyword(value)) attributes2[prop] = value.toString();
  };
  setAttr("width", width);
  setAttr("height", height);
  const viewBox = [
    box.left,
    box.top,
    boxWidth,
    boxHeight
  ];
  attributes2.viewBox = viewBox.join(" ");
  return {
    attributes: attributes2,
    viewBox,
    body
  };
}
const regex = /\sid="(\S+)"/g;
const randomPrefix = "IconifyId" + Date.now().toString(16) + (Math.random() * 16777216 | 0).toString(16);
let counter = 0;
function replaceIDs(body, prefix = randomPrefix) {
  const ids = [];
  let match;
  while (match = regex.exec(body)) ids.push(match[1]);
  if (!ids.length) return body;
  const suffix = "suffix" + (Math.random() * 16777216 | Date.now()).toString(16);
  ids.forEach((id) => {
    const newID = typeof prefix === "function" ? prefix(id) : prefix + (counter++).toString();
    const escapedID = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    body = body.replace(new RegExp('([#;"])(' + escapedID + ')([")]|\\.[a-z])', "g"), "$1" + newID + suffix + "$3");
  });
  body = body.replace(new RegExp(suffix, "g"), "");
  return body;
}
const storage = /* @__PURE__ */ Object.create(null);
function setAPIModule(provider, item) {
  storage[provider] = item;
}
function getAPIModule(provider) {
  return storage[provider] || storage[""];
}
function createAPIConfig(source) {
  let resources;
  if (typeof source.resources === "string") resources = [source.resources];
  else {
    resources = source.resources;
    if (!(resources instanceof Array) || !resources.length) return null;
  }
  const result = {
    resources,
    path: source.path || "/",
    maxURL: source.maxURL || 500,
    rotate: source.rotate || 750,
    timeout: source.timeout || 5e3,
    random: source.random === true,
    index: source.index || 0,
    dataAfterTimeout: source.dataAfterTimeout !== false
  };
  return result;
}
const configStorage = /* @__PURE__ */ Object.create(null);
const fallBackAPISources = ["https://api.simplesvg.com", "https://api.unisvg.com"];
const fallBackAPI = [];
while (fallBackAPISources.length > 0) if (fallBackAPISources.length === 1) fallBackAPI.push(fallBackAPISources.shift());
else if (Math.random() > 0.5) fallBackAPI.push(fallBackAPISources.shift());
else fallBackAPI.push(fallBackAPISources.pop());
configStorage[""] = createAPIConfig({ resources: ["https://api.iconify.design"].concat(fallBackAPI) });
function addAPIProvider(provider, customConfig) {
  const config = createAPIConfig(customConfig);
  if (config === null) return false;
  configStorage[provider] = config;
  return true;
}
function getAPIConfig(provider) {
  return configStorage[provider];
}
const detectFetch = () => {
  let callback;
  try {
    callback = fetch;
    if (typeof callback === "function") return callback;
  } catch (err) {
  }
};
let fetchModule = detectFetch();
function calculateMaxLength(provider, prefix) {
  const config = getAPIConfig(provider);
  if (!config) return 0;
  let result;
  if (!config.maxURL) result = 0;
  else {
    let maxHostLength = 0;
    config.resources.forEach((item) => {
      const host = item;
      maxHostLength = Math.max(maxHostLength, host.length);
    });
    const url = prefix + ".json?icons=";
    result = config.maxURL - maxHostLength - config.path.length - url.length;
  }
  return result;
}
function shouldAbort(status) {
  return status === 404;
}
const prepare = (provider, prefix, icons) => {
  const results = [];
  const maxLength = calculateMaxLength(provider, prefix);
  const type = "icons";
  let item = {
    type,
    provider,
    prefix,
    icons: []
  };
  let length = 0;
  icons.forEach((name, index) => {
    length += name.length + 1;
    if (length >= maxLength && index > 0) {
      results.push(item);
      item = {
        type,
        provider,
        prefix,
        icons: []
      };
      length = name.length;
    }
    item.icons.push(name);
  });
  results.push(item);
  return results;
};
function getPath(provider) {
  if (typeof provider === "string") {
    const config = getAPIConfig(provider);
    if (config) return config.path;
  }
  return "/";
}
const send = (host, params, callback) => {
  if (!fetchModule) {
    callback("abort", 424);
    return;
  }
  let path = getPath(params.provider);
  switch (params.type) {
    case "icons": {
      const prefix = params.prefix;
      const icons = params.icons;
      const iconsList = icons.join(",");
      const urlParams = new URLSearchParams({ icons: iconsList });
      path += prefix + ".json?" + urlParams.toString();
      break;
    }
    case "custom": {
      const uri = params.uri;
      path += uri.slice(0, 1) === "/" ? uri.slice(1) : uri;
      break;
    }
    default:
      callback("abort", 400);
      return;
  }
  let defaultError = 503;
  fetchModule(host + path).then((response) => {
    const status = response.status;
    if (status !== 200) {
      setTimeout(() => {
        callback(shouldAbort(status) ? "abort" : "next", status);
      });
      return;
    }
    defaultError = 501;
    return response.json();
  }).then((data) => {
    if (typeof data !== "object" || data === null) {
      setTimeout(() => {
        if (data === 404) callback("abort", data);
        else callback("next", defaultError);
      });
      return;
    }
    setTimeout(() => {
      callback("success", data);
    });
  }).catch(() => {
    callback("next", defaultError);
  });
};
const fetchAPIModule = {
  prepare,
  send
};
function removeCallback(storages, id) {
  storages.forEach((storage2) => {
    const items = storage2.loaderCallbacks;
    if (items) storage2.loaderCallbacks = items.filter((row) => row.id !== id);
  });
}
function updateCallbacks(storage2) {
  if (!storage2.pendingCallbacksFlag) {
    storage2.pendingCallbacksFlag = true;
    setTimeout(() => {
      storage2.pendingCallbacksFlag = false;
      const items = storage2.loaderCallbacks ? storage2.loaderCallbacks.slice(0) : [];
      if (!items.length) return;
      let hasPending = false;
      const provider = storage2.provider;
      const prefix = storage2.prefix;
      items.forEach((item) => {
        const icons = item.icons;
        const oldLength = icons.pending.length;
        icons.pending = icons.pending.filter((icon) => {
          if (icon.prefix !== prefix) return true;
          const name = icon.name;
          if (storage2.icons[name]) icons.loaded.push({
            provider,
            prefix,
            name
          });
          else if (storage2.missing.has(name)) icons.missing.push({
            provider,
            prefix,
            name
          });
          else {
            hasPending = true;
            return true;
          }
          return false;
        });
        if (icons.pending.length !== oldLength) {
          if (!hasPending) removeCallback([storage2], item.id);
          item.callback(icons.loaded.slice(0), icons.missing.slice(0), icons.pending.slice(0), item.abort);
        }
      });
    });
  }
}
let idCounter = 0;
function storeCallback(callback, icons, pendingSources) {
  const id = idCounter++;
  const abort = removeCallback.bind(null, pendingSources, id);
  if (!icons.pending.length) return abort;
  const item = {
    id,
    icons,
    callback,
    abort
  };
  pendingSources.forEach((storage2) => {
    (storage2.loaderCallbacks || (storage2.loaderCallbacks = [])).push(item);
  });
  return abort;
}
function sortIcons(icons) {
  const result = {
    loaded: [],
    missing: [],
    pending: []
  };
  const storage2 = /* @__PURE__ */ Object.create(null);
  icons.sort((a, b) => {
    if (a.provider !== b.provider) return a.provider.localeCompare(b.provider);
    if (a.prefix !== b.prefix) return a.prefix.localeCompare(b.prefix);
    return a.name.localeCompare(b.name);
  });
  let lastIcon = {
    provider: "",
    prefix: "",
    name: ""
  };
  icons.forEach((icon) => {
    if (lastIcon.name === icon.name && lastIcon.prefix === icon.prefix && lastIcon.provider === icon.provider) return;
    lastIcon = icon;
    const provider = icon.provider;
    const prefix = icon.prefix;
    const name = icon.name;
    const providerStorage = storage2[provider] || (storage2[provider] = /* @__PURE__ */ Object.create(null));
    const localStorage = providerStorage[prefix] || (providerStorage[prefix] = getStorage(provider, prefix));
    let list;
    if (name in localStorage.icons) list = result.loaded;
    else if (prefix === "" || localStorage.missing.has(name)) list = result.missing;
    else list = result.pending;
    const item = {
      provider,
      prefix,
      name
    };
    list.push(item);
  });
  return result;
}
function listToIcons(list, validate = true, simpleNames2 = false) {
  const result = [];
  list.forEach((item) => {
    const icon = typeof item === "string" ? stringToIcon(item, validate, simpleNames2) : item;
    if (icon) result.push(icon);
  });
  return result;
}
const defaultConfig = {
  resources: [],
  index: 0,
  timeout: 2e3,
  rotate: 750,
  random: false,
  dataAfterTimeout: false
};
function sendQuery(config, payload, query, done) {
  const resourcesCount = config.resources.length;
  const startIndex = config.random ? Math.floor(Math.random() * resourcesCount) : config.index;
  let resources;
  if (config.random) {
    let list = config.resources.slice(0);
    resources = [];
    while (list.length > 1) {
      const nextIndex = Math.floor(Math.random() * list.length);
      resources.push(list[nextIndex]);
      list = list.slice(0, nextIndex).concat(list.slice(nextIndex + 1));
    }
    resources = resources.concat(list);
  } else resources = config.resources.slice(startIndex).concat(config.resources.slice(0, startIndex));
  const startTime = Date.now();
  let status = "pending";
  let queriesSent = 0;
  let lastError;
  let timer = null;
  let queue = [];
  let doneCallbacks = [];
  if (typeof done === "function") doneCallbacks.push(done);
  function resetTimer() {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
  }
  function abort() {
    if (status === "pending") status = "aborted";
    resetTimer();
    queue.forEach((item) => {
      if (item.status === "pending") item.status = "aborted";
    });
    queue = [];
  }
  function subscribe(callback, overwrite) {
    if (overwrite) doneCallbacks = [];
    if (typeof callback === "function") doneCallbacks.push(callback);
  }
  function getQueryStatus() {
    return {
      startTime,
      payload,
      status,
      queriesSent,
      queriesPending: queue.length,
      subscribe,
      abort
    };
  }
  function failQuery() {
    status = "failed";
    doneCallbacks.forEach((callback) => {
      callback(void 0, lastError);
    });
  }
  function clearQueue() {
    queue.forEach((item) => {
      if (item.status === "pending") item.status = "aborted";
    });
    queue = [];
  }
  function moduleResponse(item, response, data) {
    const isError = response !== "success";
    queue = queue.filter((queued) => queued !== item);
    switch (status) {
      case "pending":
        break;
      case "failed":
        if (isError || !config.dataAfterTimeout) return;
        break;
      default:
        return;
    }
    if (response === "abort") {
      lastError = data;
      failQuery();
      return;
    }
    if (isError) {
      lastError = data;
      if (!queue.length) if (!resources.length) failQuery();
      else execNext();
      return;
    }
    resetTimer();
    clearQueue();
    if (!config.random) {
      const index = config.resources.indexOf(item.resource);
      if (index !== -1 && index !== config.index) config.index = index;
    }
    status = "completed";
    doneCallbacks.forEach((callback) => {
      callback(data);
    });
  }
  function execNext() {
    if (status !== "pending") return;
    resetTimer();
    const resource = resources.shift();
    if (resource === void 0) {
      if (queue.length) {
        timer = setTimeout(() => {
          resetTimer();
          if (status === "pending") {
            clearQueue();
            failQuery();
          }
        }, config.timeout);
        return;
      }
      failQuery();
      return;
    }
    const item = {
      status: "pending",
      resource,
      callback: (status$1, data) => {
        moduleResponse(item, status$1, data);
      }
    };
    queue.push(item);
    queriesSent++;
    timer = setTimeout(execNext, config.rotate);
    query(resource, payload, item.callback);
  }
  setTimeout(execNext);
  return getQueryStatus;
}
function initRedundancy(cfg) {
  const config = {
    ...defaultConfig,
    ...cfg
  };
  let queries = [];
  function cleanup() {
    queries = queries.filter((item) => item().status === "pending");
  }
  function query(payload, queryCallback, doneCallback) {
    const query$1 = sendQuery(config, payload, queryCallback, (data, error) => {
      cleanup();
      if (doneCallback) doneCallback(data, error);
    });
    queries.push(query$1);
    return query$1;
  }
  function find(callback) {
    return queries.find((value) => {
      return callback(value);
    }) || null;
  }
  const instance = {
    query,
    find,
    setIndex: (index) => {
      config.index = index;
    },
    getIndex: () => config.index,
    cleanup
  };
  return instance;
}
function emptyCallback$1() {
}
const redundancyCache = /* @__PURE__ */ Object.create(null);
function getRedundancyCache(provider) {
  if (!redundancyCache[provider]) {
    const config = getAPIConfig(provider);
    if (!config) return;
    const redundancy = initRedundancy(config);
    const cachedReundancy = {
      config,
      redundancy
    };
    redundancyCache[provider] = cachedReundancy;
  }
  return redundancyCache[provider];
}
function sendAPIQuery(target, query, callback) {
  let redundancy;
  let send2;
  if (typeof target === "string") {
    const api = getAPIModule(target);
    if (!api) {
      callback(void 0, 424);
      return emptyCallback$1;
    }
    send2 = api.send;
    const cached = getRedundancyCache(target);
    if (cached) redundancy = cached.redundancy;
  } else {
    const config = createAPIConfig(target);
    if (config) {
      redundancy = initRedundancy(config);
      const moduleKey = target.resources ? target.resources[0] : "";
      const api = getAPIModule(moduleKey);
      if (api) send2 = api.send;
    }
  }
  if (!redundancy || !send2) {
    callback(void 0, 424);
    return emptyCallback$1;
  }
  return redundancy.query(query, send2, callback)().abort;
}
function emptyCallback() {
}
function loadedNewIcons(storage2) {
  if (!storage2.iconsLoaderFlag) {
    storage2.iconsLoaderFlag = true;
    setTimeout(() => {
      storage2.iconsLoaderFlag = false;
      updateCallbacks(storage2);
    });
  }
}
function checkIconNamesForAPI(icons) {
  const valid = [];
  const invalid = [];
  icons.forEach((name) => {
    (name.match(matchIconName) ? valid : invalid).push(name);
  });
  return {
    valid,
    invalid
  };
}
function parseLoaderResponse(storage2, icons, data) {
  function checkMissing() {
    const pending = storage2.pendingIcons;
    icons.forEach((name) => {
      if (pending) pending.delete(name);
      if (!storage2.icons[name]) storage2.missing.add(name);
    });
  }
  if (data && typeof data === "object") try {
    const parsed = addIconSet(storage2, data);
    if (!parsed.length) {
      checkMissing();
      return;
    }
  } catch (err) {
    console.error(err);
  }
  checkMissing();
  loadedNewIcons(storage2);
}
function parsePossiblyAsyncResponse(response, callback) {
  if (response instanceof Promise) response.then((data) => {
    callback(data);
  }).catch(() => {
    callback(null);
  });
  else callback(response);
}
function loadNewIcons(storage2, icons) {
  if (!storage2.iconsToLoad) storage2.iconsToLoad = icons;
  else storage2.iconsToLoad = storage2.iconsToLoad.concat(icons).sort();
  if (!storage2.iconsQueueFlag) {
    storage2.iconsQueueFlag = true;
    setTimeout(() => {
      storage2.iconsQueueFlag = false;
      const { provider, prefix } = storage2;
      const icons$1 = storage2.iconsToLoad;
      delete storage2.iconsToLoad;
      if (!icons$1 || !icons$1.length) return;
      const customIconLoader = storage2.loadIcon;
      if (storage2.loadIcons && (icons$1.length > 1 || !customIconLoader)) {
        parsePossiblyAsyncResponse(storage2.loadIcons(icons$1, prefix, provider), (data) => {
          parseLoaderResponse(storage2, icons$1, data);
        });
        return;
      }
      if (customIconLoader) {
        icons$1.forEach((name) => {
          const response = customIconLoader(name, prefix, provider);
          parsePossiblyAsyncResponse(response, (data) => {
            const iconSet = data ? {
              prefix,
              icons: { [name]: data }
            } : null;
            parseLoaderResponse(storage2, [name], iconSet);
          });
        });
        return;
      }
      const { valid, invalid } = checkIconNamesForAPI(icons$1);
      if (invalid.length) parseLoaderResponse(storage2, invalid, null);
      if (!valid.length) return;
      const api = prefix.match(matchIconName) ? getAPIModule(provider) : null;
      if (!api) {
        parseLoaderResponse(storage2, valid, null);
        return;
      }
      const params = api.prepare(provider, prefix, valid);
      params.forEach((item) => {
        sendAPIQuery(provider, item, (data) => {
          parseLoaderResponse(storage2, item.icons, data);
        });
      });
    });
  }
}
const loadIcons = (icons, callback) => {
  const cleanedIcons = listToIcons(icons, true, allowSimpleNames());
  const sortedIcons = sortIcons(cleanedIcons);
  if (!sortedIcons.pending.length) {
    let callCallback = true;
    if (callback) setTimeout(() => {
      if (callCallback) callback(sortedIcons.loaded, sortedIcons.missing, sortedIcons.pending, emptyCallback);
    });
    return () => {
      callCallback = false;
    };
  }
  const newIcons = /* @__PURE__ */ Object.create(null);
  const sources = [];
  let lastProvider, lastPrefix;
  sortedIcons.pending.forEach((icon) => {
    const { provider, prefix } = icon;
    if (prefix === lastPrefix && provider === lastProvider) return;
    lastProvider = provider;
    lastPrefix = prefix;
    sources.push(getStorage(provider, prefix));
    const providerNewIcons = newIcons[provider] || (newIcons[provider] = /* @__PURE__ */ Object.create(null));
    if (!providerNewIcons[prefix]) providerNewIcons[prefix] = [];
  });
  sortedIcons.pending.forEach((icon) => {
    const { provider, prefix, name } = icon;
    const storage2 = getStorage(provider, prefix);
    const pendingQueue = storage2.pendingIcons || (storage2.pendingIcons = /* @__PURE__ */ new Set());
    if (!pendingQueue.has(name)) {
      pendingQueue.add(name);
      newIcons[provider][prefix].push(name);
    }
  });
  sources.forEach((storage2) => {
    const list = newIcons[storage2.provider][storage2.prefix];
    if (list.length) loadNewIcons(storage2, list);
  });
  return callback ? storeCallback(callback, sortedIcons, sources) : emptyCallback;
};
function mergeCustomisations(defaults, item) {
  const result = { ...defaults };
  for (const key in item) {
    const value = item[key];
    const valueType = typeof value;
    if (key in defaultIconSizeCustomisations) {
      if (value === null || value && (valueType === "string" || valueType === "number")) result[key] = value;
    } else if (valueType === typeof result[key]) result[key] = key === "rotate" ? value % 4 : value;
  }
  return result;
}
const separator = /[\s,]+/;
function flipFromString(custom, flip) {
  flip.split(separator).forEach((str) => {
    const value = str.trim();
    switch (value) {
      case "horizontal":
        custom.hFlip = true;
        break;
      case "vertical":
        custom.vFlip = true;
        break;
    }
  });
}
function rotateFromString(value, defaultValue = 0) {
  const units = value.replace(/^-?[0-9.]*/, "");
  function cleanup(value$1) {
    while (value$1 < 0) value$1 += 4;
    return value$1 % 4;
  }
  if (units === "") {
    const num = parseInt(value);
    return isNaN(num) ? 0 : cleanup(num);
  } else if (units !== value) {
    let split = 0;
    switch (units) {
      case "%":
        split = 25;
        break;
      case "deg":
        split = 90;
    }
    if (split) {
      let num = parseFloat(value.slice(0, value.length - units.length));
      if (isNaN(num)) return 0;
      num = num / split;
      return num % 1 === 0 ? cleanup(num) : 0;
    }
  }
  return defaultValue;
}
function iconToHTML(body, attributes2) {
  let renderAttribsHTML = body.indexOf("xlink:") === -1 ? "" : ' xmlns:xlink="http://www.w3.org/1999/xlink"';
  for (const attr2 in attributes2) renderAttribsHTML += " " + attr2 + '="' + attributes2[attr2] + '"';
  return '<svg xmlns="http://www.w3.org/2000/svg"' + renderAttribsHTML + ">" + body + "</svg>";
}
function encodeSVGforURL(svg) {
  return svg.replace(/"/g, "'").replace(/%/g, "%25").replace(/#/g, "%23").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\s+/g, " ");
}
function svgToData(svg) {
  return "data:image/svg+xml," + encodeSVGforURL(svg);
}
function svgToURL(svg) {
  return 'url("' + svgToData(svg) + '")';
}
const defaultExtendedIconCustomisations = {
  ...defaultIconCustomisations,
  inline: false
};
const svgDefaults = {
  "xmlns": "http://www.w3.org/2000/svg",
  "xmlns:xlink": "http://www.w3.org/1999/xlink",
  "aria-hidden": true,
  "role": "img"
};
const commonProps = {
  display: "inline-block"
};
const monotoneProps = {
  "background-color": "currentColor"
};
const coloredProps = {
  "background-color": "transparent"
};
const propsToAdd = {
  image: "var(--svg)",
  repeat: "no-repeat",
  size: "100% 100%"
};
const propsToAddTo = {
  "-webkit-mask": monotoneProps,
  "mask": monotoneProps,
  "background": coloredProps
};
for (const prefix in propsToAddTo) {
  const list = propsToAddTo[prefix];
  for (const prop in propsToAdd) {
    list[prefix + "-" + prop] = propsToAdd[prop];
  }
}
function fixSize(value) {
  return value + (value.match(/^[-0-9.]+$/) ? "px" : "");
}
function render(icon, props) {
  const customisations = mergeCustomisations(defaultExtendedIconCustomisations, props);
  const mode = props.mode || "svg";
  const componentProps = mode === "svg" ? { ...svgDefaults } : {};
  if (icon.body.indexOf("xlink:") === -1) {
    delete componentProps["xmlns:xlink"];
  }
  let style = typeof props.style === "string" ? props.style : "";
  for (let key in props) {
    const value = props[key];
    if (value === void 0) {
      continue;
    }
    switch (key) {
      case "icon":
      case "style":
      case "onLoad":
      case "mode":
      case "ssr":
        break;
      case "inline":
      case "hFlip":
      case "vFlip":
        customisations[key] = value === true || value === "true" || value === 1;
        break;
      case "flip":
        if (typeof value === "string") {
          flipFromString(customisations, value);
        }
        break;
      case "color":
        style = style + (style.length > 0 && style.trim().slice(-1) !== ";" ? ";" : "") + "color: " + value + "; ";
        break;
      case "rotate":
        if (typeof value === "string") {
          customisations[key] = rotateFromString(value);
        } else if (typeof value === "number") {
          customisations[key] = value;
        }
        break;
      case "ariaHidden":
      case "aria-hidden":
        if (value !== true && value !== "true") {
          delete componentProps["aria-hidden"];
        }
        break;
      default:
        if (key.slice(0, 3) === "on:") {
          break;
        }
        if (defaultExtendedIconCustomisations[key] === void 0) {
          componentProps[key] = value;
        }
    }
  }
  const item = iconToSVG(icon, customisations);
  const renderAttribs = item.attributes;
  if (customisations.inline) {
    style = "vertical-align: -0.125em; " + style;
  }
  if (mode === "svg") {
    Object.assign(componentProps, renderAttribs);
    if (style !== "") {
      componentProps.style = style;
    }
    let localCounter = 0;
    let id = props.id;
    if (typeof id === "string") {
      id = id.replace(/-/g, "_");
    }
    return {
      svg: true,
      attributes: componentProps,
      body: replaceIDs(item.body, id ? () => id + "ID" + localCounter++ : "iconifySvelte")
    };
  }
  const { body, width, height } = icon;
  const useMask = mode === "mask" || (mode === "bg" ? false : body.indexOf("currentColor") !== -1);
  const html2 = iconToHTML(body, {
    ...renderAttribs,
    width: width + "",
    height: height + ""
  });
  const url = svgToURL(html2);
  const styles = {
    "--svg": url
  };
  const size = (prop) => {
    const value = renderAttribs[prop];
    if (value) {
      styles[prop] = fixSize(value);
    }
  };
  size("width");
  size("height");
  Object.assign(styles, commonProps, useMask ? monotoneProps : coloredProps);
  let customStyle = "";
  for (const key in styles) {
    customStyle += key + ": " + styles[key] + ";";
  }
  componentProps.style = customStyle + style;
  return {
    svg: false,
    attributes: componentProps
  };
}
allowSimpleNames(true);
setAPIModule("", fetchAPIModule);
if (typeof document !== "undefined" && typeof window !== "undefined") {
  const _window = window;
  if (_window.IconifyPreload !== void 0) {
    const preload = _window.IconifyPreload;
    const err = "Invalid IconifyPreload syntax.";
    if (typeof preload === "object" && preload !== null) {
      (preload instanceof Array ? preload : [preload]).forEach((item) => {
        try {
          if (
            // Check if item is an object and not null/array
            typeof item !== "object" || item === null || item instanceof Array || // Check for 'icons' and 'prefix'
            typeof item.icons !== "object" || typeof item.prefix !== "string" || // Add icon set
            !addCollection(item)
          ) {
            console.error(err);
          }
        } catch (e) {
          console.error(err);
        }
      });
    }
  }
  if (_window.IconifyProviders !== void 0) {
    const providers = _window.IconifyProviders;
    if (typeof providers === "object" && providers !== null) {
      for (let key in providers) {
        const err = "IconifyProviders[" + key + "] is invalid.";
        try {
          const value = providers[key];
          if (typeof value !== "object" || !value || value.resources === void 0) {
            continue;
          }
          if (!addAPIProvider(key, value)) {
            console.error(err);
          }
        } catch (e) {
          console.error(err);
        }
      }
    }
  }
}
function checkIconState(icon, state, mounted, callback, onload) {
  function abortLoading() {
    if (state.loading) {
      state.loading.abort();
      state.loading = null;
    }
  }
  if (typeof icon === "object" && icon !== null && typeof icon.body === "string") {
    state.name = "";
    abortLoading();
    return { data: { ...defaultIconProps, ...icon } };
  }
  let iconName;
  if (typeof icon !== "string" || (iconName = stringToIcon(icon, false, true)) === null) {
    abortLoading();
    return null;
  }
  const data = getIconData(iconName);
  if (!data) {
    if (mounted && (!state.loading || state.loading.name !== icon)) {
      abortLoading();
      state.name = "";
      state.loading = {
        name: icon,
        abort: loadIcons([iconName], callback)
      };
    }
    return null;
  }
  abortLoading();
  if (state.name !== icon) {
    state.name = icon;
    if (onload && !state.destroyed) {
      setTimeout(() => {
        onload(icon);
      });
    }
  }
  const classes = ["iconify"];
  if (iconName.prefix !== "") {
    classes.push("iconify--" + iconName.prefix);
  }
  if (iconName.provider !== "") {
    classes.push("iconify--" + iconName.provider);
  }
  return { data, classes };
}
function generateIcon(icon, props) {
  return icon ? render({
    ...defaultIconProps,
    ...icon
  }, props) : null;
}
function Icon($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    const iconState = {
      // Last icon name
      name: "",
      // Loading status
      loading: null,
      // Destroyed status
      destroyed: false
    };
    const { $$slots, $$events, ...props } = $$props;
    let mounted = false;
    let isMounted = !!props.ssr || mounted;
    let iconData = (() => {
      return checkIconState(props.icon, iconState, isMounted, loaded, props.onload);
    })();
    let data = (() => {
      const generatedData = iconData ? generateIcon(iconData.data, props) : null;
      if (generatedData && iconData.classes) {
        generatedData.attributes["class"] = (typeof props["class"] === "string" ? props["class"] + " " : "") + iconData.classes.join(" ");
      }
      return generatedData;
    })();
    function loaded() {
    }
    onDestroy(() => {
      iconState.destroyed = true;
      if (iconState.loading) {
        iconState.loading.abort();
        iconState.loading = null;
      }
    });
    if (data) {
      $$renderer2.push("<!--[-->");
      if (data.svg) {
        $$renderer2.push("<!--[-->");
        $$renderer2.push(`<svg${attributes({ ...data.attributes }, void 0, void 0, void 0, 3)}>${html(data.body)}</svg>`);
      } else {
        $$renderer2.push("<!--[!-->");
        $$renderer2.push(`<span${attributes({ ...data.attributes })}></span>`);
      }
      $$renderer2.push(`<!--]-->`);
    } else {
      $$renderer2.push("<!--[!-->");
    }
    $$renderer2.push(`<!--]-->`);
  });
}
function MiniEditor($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let editor = null;
    let model = null;
    let disposables = [];
    let editorElement;
    let {
      height = 120
    } = $$props;
    function handleWheelCapture(e) {
      e.stopPropagation();
    }
    onDestroy(() => {
      try {
        editorElement.removeEventListener("wheel", handleWheelCapture, { capture: true });
      } catch {
      }
      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 {
      }
    });
    $$renderer2.push(`<div class="w-full"${attr_style(
      // Update language when prop changes without recreating the editor
      // External value changes should update the model (avoid loops)
      `height:${height}px`
    )}></div>`);
  });
}
function _page($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    const { state: workspace, actions } = getEditWorkspaceContext();
    const agent = workspace.agentId;
    function safeClone(v) {
      try {
        return structuredClone(v);
      } catch {
        try {
          return JSON.parse(JSON.stringify(v));
        } catch {
          return v;
        }
      }
    }
    function clamp(n, min, max) {
      return Math.max(min, Math.min(max, n));
    }
    let repeats = 1;
    let concurrency = 1;
    let defaultContext = {};
    let defaultContextDraft = {};
    let showDefaultContextModal = false;
    let testContextPopoverTestId = null;
    let testContextDraft = {};
    let showViewerModal = false;
    let viewerTitle = "";
    let analyzeRunning = false;
    const baseAssertionTypes = [
      { value: "llm-rubric", label: "LLM" },
      { value: "answer-relevance", label: "Answer Relevance (LLM)" },
      {
        value: "context-faithfulness",
        label: "Context Faithfulness (LLM)"
      },
      { value: "context-recall", label: "Context Recall (LLM)" },
      { value: "context-relevance", label: "Context Relevance (LLM)" },
      {
        value: "model-graded-closedqa",
        label: "Model-Graded Closed QA"
      },
      {
        value: "model-graded-factuality",
        label: "Model-Graded Factuality"
      },
      { value: "moderation", label: "Moderation" },
      { value: "classifier", label: "Classifier" },
      { value: "g-eval", label: "G-Eval" },
      { value: "factuality", label: "Factuality" },
      {
        value: "conversation-relevance",
        label: "Conversation Relevance"
      },
      { value: "equals", label: "Equals" },
      { value: "contains", label: "Contains" },
      { value: "icontains", label: "Contains (case-insensitive)" },
      { value: "contains-all", label: "Contains All" },
      { value: "contains-any", label: "Contains Any" },
      { value: "icontains-all", label: "Contains All (iCase)" },
      { value: "icontains-any", label: "Contains Any (iCase)" },
      { value: "starts-with", label: "Starts With" },
      { value: "regex", label: "Regex" },
      { value: "levenshtein", label: "Levenshtein Distance" },
      { value: "is-refusal", label: "Is Refusal" },
      { value: "is-html", label: "Is HTML" },
      { value: "contains-html", label: "Contains HTML" },
      { value: "is-json", label: "Is JSON" },
      { value: "contains-json", label: "Contains JSON" },
      { value: "is-xml", label: "Is XML" },
      { value: "contains-xml", label: "Contains XML" },
      { value: "is-sql", label: "Is SQL" },
      { value: "contains-sql", label: "Contains SQL" },
      { value: "similar", label: "Semantic Similarity" },
      { value: "rouge-n", label: "ROUGE-N" },
      { value: "bleu", label: "BLEU" },
      { value: "gleu", label: "GLEU" },
      { value: "meteor", label: "METEOR" },
      { value: "perplexity", label: "Perplexity" },
      { value: "perplexity-score", label: "Perplexity Score" },
      { value: "latency", label: "Latency" },
      { value: "cost", label: "Cost" },
      { value: "finish-reason", label: "Finish Reason" },
      { value: "trace-error-spans", label: "Trace Error Spans" },
      { value: "trace-span-count", label: "Trace Span Count" },
      { value: "trace-span-duration", label: "Trace Span Duration" },
      {
        value: "is-valid-function-call",
        label: "Is Valid Function Call"
      },
      {
        value: "is-valid-openai-function-call",
        label: "Is Valid OpenAI Function Call"
      },
      {
        value: "is-valid-openai-tools-call",
        label: "Is Valid OpenAI Tools Call"
      },
      { value: "guardrails", label: "Guardrails" },
      { value: "javascript", label: "JavaScript (custom)" },
      { value: "python", label: "Python (custom)" },
      { value: "webhook", label: "Webhook (custom)" },
      { value: "pi", label: "Pi Scorer" }
    ];
    const assertionTypes = [
      ...baseAssertionTypes,
      ...baseAssertionTypes.map((opt) => ({ value: `not-${opt.value}`, label: `Not ${opt.label}` }))
    ];
    let tests = [];
    let running = false;
    let canceling = false;
    let cancelRequested = false;
    let runScope = null;
    let runSingleTestId = null;
    let runDone = 0;
    let runTotal = 0;
    let runExpectedRuns = 1;
    let pollInFlight = false;
    let pollTimer = null;
    let runToken = 0;
    const pendingSaves = /* @__PURE__ */ new Set();
    let pendingSaveCount = 0;
    const isSaving = pendingSaveCount > 0;
    let hasFetchedTests = false;
    function trackSave(p) {
      pendingSaves.add(p);
      pendingSaveCount += 1;
      p.finally(() => {
        pendingSaves.delete(p);
        pendingSaveCount -= 1;
      });
      return p;
    }
    function makeResult(id, rr) {
      const rawRuns = Array.isArray(rr.results) ? rr.results : [];
      const successCount = rawRuns.reduce((acc, run2) => acc + (run2?.success ? 1 : 0), 0);
      return {
        success_rate: rr.success_rate,
        successes: successCount,
        total_runs: rawRuns.length,
        isOld: !!rr.is_old,
        previous: rr.previous && typeof rr.previous === "object" ? {
          success_count: Number(rr.previous.success_count ?? 0),
          total_runs: Number(rr.previous.total_runs ?? 0),
          report_timestamp: String(rr.previous.report_timestamp ?? "")
        } : void 0,
        runs: rawRuns.map((run2, idx) => {
          const timestamp = rr.report_timestamp;
          const params = { agent, id, timestamp, run: idx };
          return {
            index: idx + 1,
            success: !!run2.success,
            text: String(run2.result || ""),
            evaluation: String(run2.evaluation || ""),
            links: {
              renderedPrompt: { ...params, key: "rendered_prompt" },
              receivedPrompt: { ...params, key: "received_prompt" },
              conversation: { ...params, key: "stringified_conversation" },
              context: { ...params, key: "received_context" },
              logs: { ...params, key: "logs" },
              traces: { ...params, key: "traces" }
            }
          };
        }).reverse()
      };
    }
    async function refresh() {
      if (!agent) return;
      try {
        const [{ rows }, config, results] = await Promise.all([
          trpc.tests.list.query({ agent }),
          trpc.tests.config.query({ agent }),
          trpc.tests.latestResult.query({ agent })
        ]);
        repeats = config.repeats ?? 1;
        concurrency = config.concurrency ?? 1;
        defaultContext = config.defaultContext ?? {};
        tests = rows.map((r) => {
          const id = r.id;
          const rr = results[id];
          return {
            id,
            pinned: String(r.pinned).toUpperCase() === "TRUE",
            scenario: r.scenario || "",
            step: String(r.step ?? ""),
            author: r.author || "",
            assertion_type: r.assertion_type || "llm-rubric",
            assertion_value: r.assertion_value || "",
            conversation: r.conversation || "",
            expected_output: r.expected_output || "",
            conversation_ui: buildConversationEditorValue(r.conversation || "", r.expected_output || ""),
            timeout: Number(r.timeout ?? 0),
            similarity_threshold: Number(r.similarity_threshold ?? 60),
            context: JSON.stringify(r.context),
            result: rr ? makeResult(id, rr) : void 0
          };
        });
      } catch (e) {
        console.error(e);
        tests = [];
        repeats = 1;
        concurrency = 1;
        defaultContext = {};
      } finally {
        hasFetchedTests = true;
      }
    }
    async function pollLatestResults(activeToken) {
      if (pollInFlight) return;
      pollInFlight = true;
      try {
        const results = await trpc.tests.latestResult.query({ agent });
        if (activeToken !== runToken) return;
        const nextTests = tests.map((t) => {
          const rr = results[t.id];
          return { ...t, result: rr ? makeResult(t.id, rr) : void 0 };
        });
        tests = nextTests;
        const scope = runScope;
        const expectedRuns = Math.max(1, Number(runExpectedRuns) || 1);
        const done = nextTests.reduce(
          (acc, t) => {
            if (scope === "single" && t.id !== runSingleTestId) return acc;
            if (scope === "pinned" && !t.pinned) return acc;
            return t.result && !t.result.isOld && t.result.total_runs >= expectedRuns ? acc + 1 : acc;
          },
          0
        );
        runDone = done;
      } catch (e) {
        console.error(e);
      } finally {
        pollInFlight = false;
      }
    }
    async function run(scope) {
      running = true;
      cancelRequested = false;
      runScope = scope;
      runSingleTestId = null;
      runTotal = scope === "all" ? tests.length : tests.filter((t) => t.pinned).length;
      runDone = 0;
      runExpectedRuns = Math.max(1, Number(repeats) || 1);
      runToken += 1;
      const activeToken = runToken;
      await Promise.all([...pendingSaves]);
      if (pollTimer) clearInterval(pollTimer);
      pollTimer = setInterval(() => pollLatestResults(activeToken), 800);
      void pollLatestResults(activeToken);
      try {
        await trpc.tests.runTests.mutate({ agent, scope });
      } finally {
        if (pollTimer) clearInterval(pollTimer);
        pollTimer = null;
        try {
          await refresh();
        } finally {
          running = false;
          runScope = null;
        }
      }
    }
    async function runSingle(testId) {
      if (!agent) return;
      running = true;
      cancelRequested = false;
      runScope = "single";
      runSingleTestId = testId;
      runTotal = 1;
      runDone = 0;
      runExpectedRuns = Math.max(1, Number(repeats) || 1);
      runToken += 1;
      const activeToken = runToken;
      await Promise.all([...pendingSaves]);
      if (pollTimer) clearInterval(pollTimer);
      pollTimer = setInterval(() => pollLatestResults(activeToken), 800);
      void pollLatestResults(activeToken);
      try {
        await trpc.tests.runTests.mutate({ agent, testId });
      } finally {
        if (pollTimer) clearInterval(pollTimer);
        pollTimer = null;
        try {
          await refresh();
        } finally {
          running = false;
          runScope = null;
          runSingleTestId = null;
        }
      }
    }
    async function cancelCurrentRun() {
      if (!running || canceling || cancelRequested) return;
      canceling = true;
      try {
        const ok = await trpc.tests.cancelRun.mutate({ agent });
        if (ok) cancelRequested = true;
      } catch (e) {
        console.error(e);
      } finally {
        canceling = false;
      }
    }
    const pinnedCount = tests.filter((t) => t.pinned).length;
    const hasPinned = pinnedCount > 0;
    tests.length > 0 && pinnedCount === tests.length;
    async function addTest() {
      const res = await trpc.tests.addTest.mutate({ agent, seed: {}, mergeContexts: true });
      tests = [parseTest(res), ...tests];
    }
    function parseTest(res) {
      return {
        ...res,
        step: String(res.step ?? ""),
        pinned: res.pinned === "TRUE",
        timeout: Number(res.timeout),
        similarity_threshold: Number(res.similarity_threshold),
        context: JSON.stringify(res.context),
        conversation_ui: buildConversationEditorValue(res.conversation || "", res.expected_output || "")
      };
    }
    function formatEvaluation(ev) {
      if (!ev) return "";
      try {
        return ev.replace(/^\s*\d+\s*[:.)-]?\s*(?:[❌✖️✔✅✗xX])?\s*/u, "");
      } catch {
        return ev;
      }
    }
    function parseJson(s) {
      try {
        return s && s.trim() ? JSON.parse(s) : {};
      } catch {
        return {};
      }
    }
    const roleMatch = (line) => line.match(/^\s*(agent|assistant|user|system)\s*:\s*(.*)$/i);
    function formatExpectedAsAgentBlock(expected) {
      const trimmed = String(expected ?? "").trimEnd();
      if (!trimmed) return "";
      if (/^\s*(agent|assistant)\s*:/i.test(trimmed)) return trimmed;
      return `Agent: ${trimmed}`;
    }
    function buildConversationEditorValue(conversation, expected) {
      const conv = String(conversation ?? "").trimEnd();
      const expectedBlock = formatExpectedAsAgentBlock(expected);
      if (!expectedBlock) return conv;
      if (!conv) return expectedBlock;
      return `${conv}
${expectedBlock}`;
    }
    function parseExpectedFromConversationEditor(text) {
      const raw = String(text ?? "");
      const lines = raw.split(/\r?\n/);
      const blocks = [];
      let current = null;
      for (let i = 0; i < lines.length; i++) {
        const m2 = roleMatch(lines[i]);
        if (!m2) continue;
        if (current) {
          blocks.push({ ...current, endLine: i });
        }
        const roleRaw = String(m2[1] ?? "").toLowerCase();
        const role = roleRaw === "assistant" ? "agent" : roleRaw;
        current = { role, startLine: i + 1 };
      }
      if (current) blocks.push({ ...current, endLine: lines.length });
      const expectedBlock = blocks.at(-1);
      const promptBlock = blocks.length >= 2 ? blocks.at(-2) : null;
      const canExtractExpected = expectedBlock?.role === "agent";
      const valid = canExtractExpected && promptBlock?.role === "user";
      if (!canExtractExpected || !expectedBlock) {
        return { valid: false, expected: "", conversation: raw.trimEnd() };
      }
      const expectedLines = lines.slice(expectedBlock.startLine - 1, expectedBlock.endLine);
      const first = expectedLines[0] ?? "";
      const m = roleMatch(first);
      const firstContent = m ? m[2] ?? "" : "";
      const expected = [firstContent, ...expectedLines.slice(1)].join("\n").trimEnd();
      const conversation = lines.slice(0, expectedBlock.startLine - 1).join("\n").trimEnd();
      return {
        valid,
        expected,
        conversation,
        highlight: {
          startLine: expectedBlock.startLine,
          endLine: expectedBlock.endLine
        }
      };
    }
    function erf(x) {
      const sign = x < 0 ? -1 : 1;
      const ax = Math.abs(x);
      const a1 = 0.254829592;
      const a2 = -0.284496736;
      const a3 = 1.421413741;
      const a4 = -1.453152027;
      const a5 = 1.061405429;
      const p = 0.3275911;
      const t = 1 / (1 + p * ax);
      const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-ax * ax);
      return sign * y;
    }
    function normalCdf(x) {
      return 0.5 * (1 + erf(x / Math.SQRT2));
    }
    function twoProportionZTestPValue(x1, n1, x2, n2) {
      if (!Number.isFinite(x1) || !Number.isFinite(n1) || !Number.isFinite(x2) || !Number.isFinite(n2)) return null;
      if (n1 <= 0 || n2 <= 0) return null;
      const p1 = x1 / n1;
      const p2 = x2 / n2;
      const pooled = (x1 + x2) / (n1 + n2);
      const denom = Math.sqrt(pooled * (1 - pooled) * (1 / n1 + 1 / n2));
      if (!Number.isFinite(denom) || denom <= 0) return null;
      const z = (p2 - p1) / denom;
      const p = 2 * (1 - normalCdf(Math.abs(z)));
      return Math.max(0, Math.min(1, p));
    }
    function getExpectedTrend(result, expectedRuns) {
      if (!result || result.isOld) return null;
      const doneRuns = result.total_runs;
      if (doneRuns <= 0) return null;
      const prev = result.previous;
      const prevRate = prev && prev.total_runs > 0 ? prev.success_count / prev.total_runs : null;
      const currRate = result.successes / doneRuns;
      const direction = prevRate === null ? "higher" : currRate >= prevRate ? "higher" : "lower";
      const significant = (() => {
        if (doneRuns <= 5 || !prev || prev.total_runs <= 0) return false;
        const pValue = twoProportionZTestPValue(prev.success_count, prev.total_runs, result.successes, doneRuns);
        return pValue !== null && pValue < 0.05;
      })();
      const showExpected = Number.isFinite(expectedRuns) && expectedRuns > 0 && doneRuns < expectedRuns;
      if (!showExpected && !significant) return null;
      const expectedSuccesses = showExpected ? Math.round(result.successes / doneRuns * expectedRuns) : void 0;
      return {
        showExpected,
        expectedSuccesses,
        expectedRuns,
        significant,
        direction
      };
    }
    async function saveRow(id, patch) {
      await trpc.tests.patchTest.mutate({ agent, id, patch });
    }
    function openTestContext(row) {
      if (!agent) return;
      testContextPopoverTestId = row.id;
      testContextDraft = safeClone(parseJson(row.context));
    }
    async function closeTestContextPopover() {
      const id = testContextPopoverTestId;
      if (!id || !agent) {
        testContextPopoverTestId = null;
        return;
      }
      const draft = safeClone(testContextDraft);
      testContextPopoverTestId = null;
      tests = tests.map((t) => t.id === id ? { ...t, context: JSON.stringify(draft) } : t);
      try {
        await trackSave(saveRow(id, { context: draft }));
      } catch (e) {
        console.error(e);
        await refresh();
      }
    }
    async function saveConfigPatch(patch) {
      await trpc.tests.updateConfig.mutate({ agent, cfg: patch });
    }
    onDestroy(() => {
      if (pollTimer) clearInterval(pollTimer);
    });
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      head($$renderer3, ($$renderer4) => {
        $$renderer4.push(`<link rel="preload" href="/ui/arrow_tests.svg" as="image"/>`);
      });
      {
        let children = function($$renderer4) {
          ContextEditor($$renderer4, {
            class: "h-[70vh]",
            context: defaultContextDraft,
            onContextChanged: (ctx) => defaultContextDraft = ctx,
            suppressErrors: true,
            defaultFormat: "json",
            hideHeader: true
          });
        }, footer = function($$renderer4) {
          Button($$renderer4, {
            variant: "outlined",
            size: "small",
            onclick: () => showDefaultContextModal = false,
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->Cancel`);
            },
            $$slots: { default: true }
          });
          $$renderer4.push(`<!----> `);
          Button($$renderer4, {
            size: "small",
            onclick: async () => {
              defaultContext = defaultContextDraft;
              await trackSave(saveConfigPatch({ defaultContext }));
              showDefaultContextModal = false;
            },
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->Save`);
            },
            $$slots: { default: true }
          });
          $$renderer4.push(`<!---->`);
        };
        Modal($$renderer3, {
          title: "Default Context",
          get open() {
            return showDefaultContextModal;
          },
          set open($$value) {
            showDefaultContextModal = $$value;
            $$settled = false;
          },
          children,
          footer,
          $$slots: { default: true, footer: true }
        });
      }
      $$renderer3.push(`<!----> `);
      {
        let children = function($$renderer4) {
          {
            $$renderer4.push("<!--[!-->");
            {
              $$renderer4.push("<!--[!-->");
              $$renderer4.push(`<pre class="whitespace-pre-wrap font-mono text-gray-200">${escape_html("—")}</pre>`);
            }
            $$renderer4.push(`<!--]-->`);
          }
          $$renderer4.push(`<!--]-->`);
        }, footer = function($$renderer4) {
          Button($$renderer4, {
            variant: "outlined",
            size: "small",
            onclick: () => showViewerModal = false,
            children: ($$renderer5) => {
              $$renderer5.push(`<!---->Close`);
            },
            $$slots: { default: true }
          });
        };
        Modal($$renderer3, {
          title: viewerTitle,
          class: "!w-[80vw] !max-w-5xl",
          get open() {
            return showViewerModal;
          },
          set open($$value) {
            showViewerModal = $$value;
            $$settled = false;
          },
          children,
          footer,
          $$slots: { default: true, footer: true }
        });
      }
      $$renderer3.push(`<!----> <div class="flex h-full min-h-0 flex-col"><div class="flex flex-none items-center justify-between gap-3 border-b border-rc-gray-700 p-2"><div class="flex items-center gap-3">`);
      Button($$renderer3, {
        variant: "secondary",
        disabled: running || isSaving || !agent,
        onclick: () => {
          defaultContextDraft = safeClone(defaultContext);
          showDefaultContextModal = true;
        },
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->Edit default context`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----> <div class="relative inline-flex items-center">`);
      Button($$renderer3, {
        variant: "secondary",
        onclick: addTest,
        disabled: isSaving || running || !agent,
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->New test`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----> `);
      if (hasFetchedTests && tests.length === 0) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<div class="pointer-events-none absolute -left-28 top-full mt-4 inline-flex -translate-x-1/2 flex-col items-center"><div class="relative w-50vw max-w-2xl"><img src="/ui/arrow_tests.svg" alt="Arrow" class="block h-auto w-full object-contain"/> <span class="absolute inset-0 mt-48 flex items-center justify-center text-center text-4xl font-extrabold text-rc-gray-200">No tests yet.<br/>Add the first one</span></div></div>`);
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]--></div></div> <div class="flex flex-wrap items-center gap-3">`);
      if (running) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<div class="mr-3 flex items-center gap-3"><span class="animate-pulse rounded bg-rc-green-200 px-3 py-1 text-white">Running… ${escape_html(runDone)}/${escape_html(runTotal)}</span> `);
        Button($$renderer3, {
          variant: "secondary",
          disabled: canceling || cancelRequested,
          onclick: cancelCurrentRun,
          children: ($$renderer4) => {
            $$renderer4.push(`<!---->${escape_html(cancelRequested ? "Cancel requested…" : canceling ? "Canceling…" : "Cancel")}`);
          },
          $$slots: { default: true }
        });
        $$renderer3.push(`<!----></div>`);
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]--> <div class="flex items-center gap-2"><label class="text-rc-gray-300">Repeats</label> `);
      Input($$renderer3, {
        type: "number",
        min: "0",
        max: "500",
        class: "w-16",
        onchange: () => {
          repeats = clamp(+repeats || 0, 0, 500);
          trackSave(saveConfigPatch({ repeats }));
        },
        get value() {
          return repeats;
        },
        set value($$value) {
          repeats = $$value;
          $$settled = false;
        }
      });
      $$renderer3.push(`<!----></div> <div class="flex items-center gap-2"><label class="text-rc-gray-300">Concurrency</label> `);
      Input($$renderer3, {
        type: "number",
        min: "0",
        max: "20",
        class: "w-16",
        onchange: () => {
          concurrency = clamp(+concurrency || 0, 0, 20);
          trackSave(saveConfigPatch({ concurrency }));
        },
        get value() {
          return concurrency;
        },
        set value($$value) {
          concurrency = $$value;
          $$settled = false;
        }
      });
      $$renderer3.push(`<!----></div> `);
      Button($$renderer3, {
        class: "disabled:cursor-not-allowed disabled:opacity-50",
        disabled: running || isSaving || tests.length === 0 || hasPinned && pinnedCount === 0,
        onclick: () => run(hasPinned ? "pinned" : "all"),
        children: ($$renderer4) => {
          $$renderer4.push(`<!---->▶ ${escape_html(hasPinned ? "Run pinned" : "Run all")}`);
        },
        $$slots: { default: true }
      });
      $$renderer3.push(`<!----></div></div> <div class="min-h-0 flex-1 overflow-hidden p-2">`);
      Panel($$renderer3, {
        class: "relative flex h-full min-w-0 flex-col overflow-hidden !rounded-none p-0",
        children: ($$renderer4) => {
          $$renderer4.push(`<div class="rc-scroll min-h-0 flex-1 overflow-auto"><div class="grid grid-cols-[2.25rem,1fr] items-center gap-2 border-b border-rc-gray-700 p-2"><button${attr_class(
            `icon-btn justify-self-center ${stringify(hasPinned ? "text-rc-green-350 hover:text-rc-green-250" : "text-gray-300 hover:text-gray-100")}`,
            "svelte-rdft55"
          )} aria-label="Pin/unpin all" title="Pin/unpin all"${attr("disabled", running || isSaving || tests.length === 0, true)}>`);
          Icon($$renderer4, {
            class: "block",
            icon: hasPinned ? "mdi:pin" : "mdi:pin-outline",
            width: 18,
            height: 18
          });
          $$renderer4.push(`<!----></button> <span class="text-left text-rc-gray-300">Pinned: ${escape_html(pinnedCount)}/${escape_html(tests.length)}</span></div> `);
          if (!hasFetchedTests) {
            $$renderer4.push("<!--[-->");
            $$renderer4.push(`<div class="p-3 text-gray-400">Loading tests…</div>`);
          } else {
            $$renderer4.push("<!--[!-->");
            if (tests.length === 0) {
              $$renderer4.push("<!--[-->");
              $$renderer4.push(`<div class="p-3 text-gray-400">—</div>`);
            } else {
              $$renderer4.push("<!--[!-->");
              $$renderer4.push(`<div class="flex flex-col space-y-5"><!--[-->`);
              const each_array = ensure_array_like(tests);
              for (let i = 0, $$length = each_array.length; i < $$length; i++) {
                let t = each_array[i];
                const expectedInfo = parseExpectedFromConversationEditor(t.conversation_ui);
                $$renderer4.push(`<div class="border-b border-rc-gray-700 p-2"${attr("data-id", t.id)}><div class="grid grid-cols-[2.25rem,1fr] gap-2"><div class="flex flex-col items-center gap-1"><button${attr_class(
                  `icon-btn ${stringify(t.pinned ? "text-rc-green-350 hover:text-rc-green-250" : "text-gray-300 hover:text-gray-100")}`,
                  "svelte-rdft55"
                )}${attr("aria-label", t.pinned ? "Unpin" : "Pin")}${attr("title", t.pinned ? "Unpin" : "Pin")}${attr("disabled", running || isSaving, true)}>`);
                Icon($$renderer4, {
                  class: "block",
                  icon: t.pinned ? "mdi:pin" : "mdi:pin-outline",
                  width: 18,
                  height: 18
                });
                $$renderer4.push(`<!----></button> <button title="Duplicate" class="icon-btn text-gray-300 hover:text-gray-100 disabled:cursor-not-allowed disabled:opacity-50 svelte-rdft55"${attr("disabled", running || isSaving, true)}>`);
                Icon($$renderer4, { icon: "mdi:content-copy", width: 18, height: 18 });
                $$renderer4.push(`<!----></button> <button title="Delete" class="icon-btn text-gray-300 hover:text-gray-100 disabled:cursor-not-allowed disabled:opacity-50 svelte-rdft55"${attr("disabled", running || isSaving, true)}>`);
                Icon($$renderer4, { icon: "mdi:trash-can-outline", width: 18, height: 18 });
                $$renderer4.push(`<!----></button></div> <div class="min-w-0"><div${attr_class(`left-details-bg flex flex-col rounded border ${expectedInfo.valid ? "border-rc-gray-700" : "border-rc-red-600"}`, "svelte-rdft55")}><div class="left-details-bg sticky top-0 z-10 rounded-t border-b border-rc-gray-700 px-2 pb-1 pt-2 svelte-rdft55"><input class="card-input-title svelte-rdft55" type="text" placeholder="Scenario"${attr("value", t.scenario)}/></div> <div class="flex flex-col gap-2 p-2">`);
                if (!expectedInfo.valid) {
                  $$renderer4.push("<!--[-->");
                  $$renderer4.push(`<div class="text-rc-red-600">Invalid test: expected must be the last block (“Agent: …”), with a prompt
													“User: …” block right above it</div>`);
                } else {
                  $$renderer4.push("<!--[!-->");
                }
                $$renderer4.push(`<!--]--> <input class="card-input-subtle svelte-rdft55" type="text" placeholder="Author"${attr("value", t.author)}/> <div class="flex items-center gap-2">`);
                $$renderer4.select(
                  {
                    class: "rc-scroll rc-input w-36",
                    value: t.assertion_type,
                    "aria-label": "Assertion Type",
                    onchange: () => saveRow(t.id, { assertion_type: t.assertion_type })
                  },
                  ($$renderer5) => {
                    $$renderer5.push(`<!--[-->`);
                    const each_array_1 = ensure_array_like(assertionTypes);
                    for (let $$index = 0, $$length2 = each_array_1.length; $$index < $$length2; $$index++) {
                      let opt = each_array_1[$$index];
                      $$renderer5.option({ value: opt.value }, ($$renderer6) => {
                        $$renderer6.push(`${escape_html(opt.label)}`);
                      });
                    }
                    $$renderer5.push(`<!--]-->`);
                  },
                  "svelte-rdft55"
                );
                $$renderer4.push(` <input class="rc-input min-w-0 flex-1 svelte-rdft55" type="text"${attr("value", t.assertion_value)} placeholder="Assertion value"/></div> <div class="flex flex-wrap items-center gap-3"><div class="flex items-center gap-2"><span class="text-rc-gray-300">Timeout (s)</span> <input class="rc-input no-spin w-16 svelte-rdft55" type="number" min="0" max="999"${attr("value", t.timeout)} placeholder="Timeout"/></div> <div class="flex items-center gap-2"><span class="text-rc-gray-300">Similarity (%)</span> <input class="rc-input no-spin w-16 svelte-rdft55" type="number" min="0" max="100"${attr("value", t.similarity_threshold)} placeholder="Similarity (%)"/></div> `);
                Button($$renderer4, {
                  variant: "secondary",
                  size: "small",
                  disabled: running || isSaving,
                  onclick: () => openTestContext(t),
                  children: ($$renderer5) => {
                    $$renderer5.push(`<!---->Edit context`);
                  },
                  $$slots: { default: true }
                });
                $$renderer4.push(`<!----></div> `);
                MiniEditor($$renderer4, {
                  value: t.conversation_ui,
                  highlights: expectedInfo.highlight ? [
                    {
                      startLine: expectedInfo.highlight.startLine,
                      endLine: expectedInfo.highlight.endLine,
                      className: "test-expected-output"
                    }
                  ] : void 0,
                  height: 220
                });
                $$renderer4.push(`<!----></div> <div class="rounded-b border-t border-rc-gray-700 bg-rc-gray-980 p-2"><div class="flex flex-wrap items-center gap-3">`);
                Button($$renderer4, {
                  size: "small",
                  disabled: running || isSaving || !expectedInfo.valid,
                  title: !expectedInfo.valid ? "Expected must be the last block (“Agent: …”) and there must be a prompt “User: …” block right above it" : "Run",
                  onclick: () => runSingle(t.id),
                  children: ($$renderer5) => {
                    $$renderer5.push(`<!---->▶ Run`);
                  },
                  $$slots: { default: true }
                });
                $$renderer4.push(`<!----> `);
                if (t.result) {
                  $$renderer4.push("<!--[-->");
                  const trend = getExpectedTrend(t.result, runExpectedRuns);
                  $$renderer4.push(`<div class="text-lg font-extrabold"><span class="text-rc-gray-200">${escape_html(t.result.successes)}/${escape_html(t.result.total_runs)}</span> `);
                  if (trend?.showExpected) {
                    $$renderer4.push("<!--[-->");
                    $$renderer4.push(`<span class="ml-2 text-rc-gray-400">(${escape_html(trend.expectedSuccesses)}/${escape_html(trend.expectedRuns)} expected)</span>`);
                  } else {
                    $$renderer4.push("<!--[!-->");
                  }
                  $$renderer4.push(`<!--]--> `);
                  if (trend?.significant) {
                    $$renderer4.push("<!--[-->");
                    $$renderer4.push(`<span${attr_class(`ml-2 whitespace-nowrap font-semibold ${trend.direction === "higher" ? "text-rc-green-200" : "text-rc-red-600"}`, "svelte-rdft55")}>`);
                    Icon$1($$renderer4, {
                      name: trend.direction === "higher" ? "chevron-up" : "chevron-down",
                      width: 18,
                      height: 18,
                      class: "inline-block align-text-bottom"
                    });
                    $$renderer4.push(`<!----><span class="ml-1">significant</span></span>`);
                  } else {
                    $$renderer4.push("<!--[!-->");
                  }
                  $$renderer4.push(`<!--]--> `);
                  if (t.result.isOld) {
                    $$renderer4.push("<!--[-->");
                    $$renderer4.push(`<span class="text-rc-gray-400">(old)</span>`);
                  } else {
                    $$renderer4.push("<!--[!-->");
                  }
                  $$renderer4.push(`<!--]--></div>`);
                } else {
                  $$renderer4.push("<!--[!-->");
                }
                $$renderer4.push(`<!--]--></div> `);
                if (t.result) {
                  $$renderer4.push("<!--[-->");
                  $$renderer4.push(`<div class="mt-3 flex flex-col gap-4"><!--[-->`);
                  const each_array_2 = ensure_array_like(t.result.runs);
                  for (let $$index_1 = 0, $$length2 = each_array_2.length; $$index_1 < $$length2; $$index_1++) {
                    let run2 = each_array_2[$$index_1];
                    $$renderer4.push(`<div class="flex flex-col gap-2"><div${attr_class(`w-full whitespace-pre-wrap break-words rounded-lg px-3 py-2 text-rc-gray-100 ${run2.success ? "bg-rc-green-700 backdrop-blur-md" : ""}`, "svelte-rdft55")}${attr_style(!run2.success ? "background-color: rgb(156 80 80)" : "")}>${escape_html(run2.text || "—")}</div> <div${attr_class(`flex w-full flex-col gap-x-4 whitespace-pre-wrap break-words ${run2.success ? "text-rc-green-200" : "text-rc-red-800"}`, "svelte-rdft55")}><div class="flex items-center gap-0">`);
                    if (run2.success) {
                      $$renderer4.push("<!--[-->");
                      Icon$1($$renderer4, {
                        name: "checkmark",
                        width: 20,
                        height: 20,
                        class: "shrink-0 self-end"
                      });
                    } else {
                      $$renderer4.push("<!--[!-->");
                      Icon$1($$renderer4, {
                        name: "close",
                        width: 18,
                        height: 18,
                        class: "shrink-0 scale-110 self-start"
                      });
                    }
                    $$renderer4.push(`<!--]--> <span>${escape_html(run2.success ? "Pass" : formatEvaluation(run2.evaluation) || "Fail")}</span></div> <div class="mt-1 flex flex-wrap items-center gap-x-4"><button type="button" class="pseudolink svelte-rdft55">Rendered prompt</button> <button type="button" class="pseudolink svelte-rdft55">Received prompt</button> <button type="button" class="pseudolink svelte-rdft55">Conversation</button> <button type="button" class="pseudolink svelte-rdft55">Context</button> <button type="button" class="pseudolink svelte-rdft55">Logs</button> <button type="button" class="pseudolink svelte-rdft55">Traces</button> <button type="button" class="pseudolink svelte-rdft55"${attr("disabled", analyzeRunning, true)}>Analyze</button></div></div></div>`);
                  }
                  $$renderer4.push(`<!--]--></div>`);
                } else {
                  $$renderer4.push("<!--[!-->");
                }
                $$renderer4.push(`<!--]--></div></div></div></div></div>`);
              }
              $$renderer4.push(`<!--]--></div>`);
            }
            $$renderer4.push(`<!--]-->`);
          }
          $$renderer4.push(`<!--]--></div> `);
          if (testContextPopoverTestId) {
            $$renderer4.push("<!--[-->");
            const row = tests.find((t) => t.id === testContextPopoverTestId);
            {
              let children = function($$renderer5) {
                $$renderer5.push(`<div class="min-h-0 flex-1 overflow-hidden p-3"><!---->`);
                {
                  ContextEditor($$renderer5, {
                    class: "h-full min-h-0 border-thin border-rc-gray-650 shadow-inner-white-soft backdrop-blur-3xl",
                    context: testContextDraft,
                    suppressErrors: true,
                    defaultFormat: "yaml",
                    hideHeader: true,
                    onContextChanged: (ctx) => testContextDraft = ctx
                  });
                }
                $$renderer5.push(`<!----></div>`);
              };
              PopoverModal($$renderer4, {
                title: `Test context — ${row?.scenario || "Test"}`,
                onClose: () => void closeTestContextPopover(),
                children
              });
            }
          } else {
            $$renderer4.push("<!--[!-->");
          }
          $$renderer4.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-C1YaC_Qg.js.map
