"use client";
import { DatasourceFormModal } from './chunk-5RM6NGZ6.mjs';
import { useSubworkflowStore, SaveStatusBadge, WorkflowListBar, NodePalette, AutoSaveWorkspace, AgentModal, PipelineSettingsModal, SubworkflowModal, RunPanel, RunInputDialog, PreviewPanel } from './chunk-2WXRRQM3.mjs';
import { validateWorkflowGraph } from './chunk-LEXBTVGM.mjs';
import { useWorkflowStore, useModalStore, WorkflowBuilderProvider } from './chunk-PCYL4MII.mjs';
import { useNotifications, PageErrorState, PageEmptyState, CopyableId, Button, DynamicIslandConfirm } from './chunk-JN6IL6OH.mjs';
import { useLocale, useTranslations } from './chunk-7VJ7CMMT.mjs';
import { executeWorkflow, getWorkflowById, getAgentConfigsWithPrompts, getAgentModels, getAgentToolDefinitions, getAgentRules, getDatasources, listModelProviderConnections, getAgentTools, getWorkflows, saveWorkflowDraft, publishWorkflow, createWorkflow, deleteWorkflow, updateAgentTool, updateAgentRule, createDatasource, getDatasourceSchema, getDatasourceTables, updateAgentConfig, createAgentConfig, updateWorkflowSettings, getWorkflowRuns, buildAuthenticatedApiUrl } from './chunk-ZV5EZXXO.mjs';
import { useState, useRef, useCallback, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router';
import { ChartBarIcon, StopIcon, PlayIcon, DocumentCheckIcon } from '@heroicons/react/24/outline';
import { jsx, jsxs } from 'react/jsx-runtime';

var WS_ENDPOINT = import.meta.env.VITE_WS_ENDPOINT ?? "";
var useWebSocket = WS_ENDPOINT.length > 0;
function connectSSE(workflowId, runId, callbacks) {
  let eventSource = null;
  let cancelled = false;
  buildAuthenticatedApiUrl(
    `/workflows/${encodeURIComponent(workflowId)}/runs/${encodeURIComponent(runId)}/events`,
    { includeAccessToken: true }
  ).then((url) => {
    if (cancelled) return;
    eventSource = new EventSource(url);
    eventSource.addEventListener("connected", () => callbacks.onConnected());
    eventSource.addEventListener("execution", (messageEvent) => {
      try {
        callbacks.onEvent(JSON.parse(messageEvent.data));
      } catch {
      }
    });
    eventSource.addEventListener("done", (messageEvent) => {
      try {
        const data = JSON.parse(messageEvent.data);
        callbacks.onDone(data.status === "run_completed" ? "completed" : "failed");
      } catch {
        callbacks.onDone("completed");
      }
      eventSource?.close();
    });
    eventSource.addEventListener("error", () => {
      eventSource?.close();
      callbacks.onError();
    });
  }).catch(() => callbacks.onError());
  return () => {
    cancelled = true;
    eventSource?.close();
  };
}
function connectWebSocket(_workflowId, runId, callbacks) {
  const ws = new WebSocket(WS_ENDPOINT);
  ws.addEventListener("open", () => {
    ws.send(JSON.stringify({ action: "subscribe", runId }));
    callbacks.onConnected();
  });
  ws.addEventListener("message", (messageEvent) => {
    try {
      const data = JSON.parse(messageEvent.data);
      if (data.type === "run_completed" || data.type === "run_failed") {
        callbacks.onDone(data.type === "run_completed" ? "completed" : "failed");
        ws.send(JSON.stringify({ action: "unsubscribe", runId }));
        ws.close();
        return;
      }
      callbacks.onEvent(data);
    } catch {
    }
  });
  ws.addEventListener("error", () => {
    callbacks.onError();
  });
  ws.addEventListener("close", () => {
  });
  return () => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ action: "unsubscribe", runId }));
    }
    ws.close();
  };
}
function useRunEvents(workflowId, runId) {
  const [events, setEvents] = useState([]);
  const [status, setStatus] = useState("idle");
  const [error, setError] = useState(null);
  const cleanupRef = useRef(null);
  const retriesRef = useRef(0);
  const connect = useCallback(() => {
    if (!workflowId || !runId) return;
    const connectFn = useWebSocket ? connectWebSocket : connectSSE;
    const callbacks = {
      onConnected: () => {
        setStatus("streaming");
        setError(null);
        retriesRef.current = 0;
      },
      onEvent: (event) => {
        setEvents((prev) => [...prev, event]);
      },
      onDone: (terminalStatus) => {
        setStatus(terminalStatus);
        cleanupRef.current = null;
      },
      onError: () => {
        cleanupRef.current = null;
        if (retriesRef.current < 3) {
          retriesRef.current++;
          const delay = Math.min(1e3 * Math.pow(2, retriesRef.current - 1), 5e3);
          setTimeout(connect, delay);
        } else {
          setStatus("error");
          setError("Connection lost after 3 retries");
        }
      }
    };
    cleanupRef.current = connectFn(workflowId, runId, callbacks);
  }, [workflowId, runId]);
  useEffect(() => {
    if (!workflowId || !runId) return;
    setEvents([]);
    setStatus("streaming");
    setError(null);
    retriesRef.current = 0;
    connect();
    return () => {
      if (cleanupRef.current) {
        cleanupRef.current();
        cleanupRef.current = null;
      }
    };
  }, [workflowId, runId, connect]);
  return {
    events,
    isStreaming: status === "streaming",
    status,
    error
  };
}
function resetWorkflowRunPresentation(actions) {
  actions.clearNodeResults();
  actions.setIsRunning(false);
}
function applyWorkflowExecutionEventToStore(actions, event) {
  switch (event.type) {
    case "run_started":
      actions.clearNodeResults();
      actions.setIsRunning(true);
      return;
    case "node_started":
      if (!event.nodeId) return;
      actions.setNodeResult(event.nodeId, {
        status: "running",
        durationMs: event.durationMs
      });
      return;
    case "node_completed":
      if (!event.nodeId) return;
      actions.setNodeResult(event.nodeId, {
        status: "success",
        data: event.outputs,
        durationMs: event.durationMs
      });
      return;
    case "node_error":
      if (!event.nodeId) return;
      actions.setNodeResult(event.nodeId, {
        status: "error",
        error: event.error,
        durationMs: event.durationMs
      });
      return;
    case "run_completed":
    case "run_failed":
      actions.setIsRunning(false);
      return;
    default:
      return;
  }
}
function useWorkflowRunPresentation(events, status) {
  const clearNodeResults = useWorkflowStore((state) => state.clearNodeResults);
  const setIsRunning = useWorkflowStore((state) => state.setIsRunning);
  const setNodeResult = useWorkflowStore((state) => state.setNodeResult);
  useEffect(() => {
    if (status === "idle") {
      resetWorkflowRunPresentation({ clearNodeResults, setIsRunning, setNodeResult });
      return;
    }
    clearNodeResults();
    for (const event of events) {
      applyWorkflowExecutionEventToStore({ clearNodeResults, setIsRunning, setNodeResult }, event);
    }
    if (status === "completed" || status === "failed" || status === "error") {
      setIsRunning(false);
    } else if (status === "streaming") {
      setIsRunning(true);
    }
  }, [clearNodeResults, events, setIsRunning, setNodeResult, status]);
}

// src/hooks/use-workflow-execution.ts
function useWorkflowExecution(workflowId) {
  const [activeRunId, setActiveRunId] = useState(null);
  const [isLaunching, setIsLaunching] = useState(false);
  const stream = useRunEvents(workflowId || null, activeRunId);
  const clearNodeResults = useWorkflowStore((state) => state.clearNodeResults);
  const setIsRunning = useWorkflowStore((state) => state.setIsRunning);
  const setNodeResult = useWorkflowStore((state) => state.setNodeResult);
  useWorkflowRunPresentation(stream.events, activeRunId ? stream.status : "idle");
  useEffect(() => {
    if (stream.status === "completed" || stream.status === "failed" || stream.status === "error") {
      setIsLaunching(false);
    }
  }, [stream.status]);
  const run = useCallback(async (inputVariables) => {
    if (!workflowId) return;
    setIsLaunching(true);
    try {
      const runRecord = await executeWorkflow(workflowId, inputVariables);
      setActiveRunId(runRecord.id);
    } finally {
      setIsLaunching(false);
    }
  }, [workflowId]);
  const stop = useCallback(() => {
    setActiveRunId(null);
    setIsLaunching(false);
    resetWorkflowRunPresentation({ clearNodeResults, setIsRunning, setNodeResult });
  }, [clearNodeResults, setIsRunning, setNodeResult]);
  useEffect(() => {
    setActiveRunId(null);
    setIsLaunching(false);
    resetWorkflowRunPresentation({ clearNodeResults, setIsRunning, setNodeResult });
  }, [clearNodeResults, setIsRunning, setNodeResult, workflowId]);
  return {
    isRunning: isLaunching || stream.status === "streaming",
    execute: run,
    stop,
    runId: activeRunId,
    runStatus: activeRunId ? stream.status : "idle"
  };
}
function getPublishableKey() {
  return import.meta.env.VITE_WORKFLOW_BUILDER_PUBLISHABLE_KEY ?? "";
}
function useDatasourceLabels() {
  const t = useTranslations("platform.datasources");
  return useMemo(() => {
    const keys = [
      "title",
      "subtitle",
      "addDatasource",
      "createTitle",
      "emptyTitle",
      "emptyDescription",
      "stepSelectType",
      "stepConfigure",
      "categoryRelational",
      "categoryNoSql",
      "categoryWarehouse",
      "categoryTimeSeries",
      "categoryGraph",
      "categoryKeyValue",
      "categorySearch",
      "fieldName",
      "fieldNamePlaceholder",
      "fieldHost",
      "fieldHostPlaceholder",
      "fieldPort",
      "fieldDatabase",
      "fieldDatabasePlaceholder",
      "fieldUsername",
      "fieldUsernamePlaceholder",
      "fieldPassword",
      "fieldPasswordPlaceholder",
      "fieldSchema",
      "fieldSchemaPlaceholder",
      "fieldSsl",
      "fieldReadOnly",
      "fieldReadOnlyHelp",
      "fieldConnectionString",
      "fieldConnectionStringPlaceholder",
      "fieldProjectId",
      "fieldProjectIdPlaceholder",
      "fieldDataset",
      "fieldDatasetPlaceholder",
      "fieldKeyFile",
      "fieldKeyFilePlaceholder",
      "fieldAccount",
      "fieldAccountPlaceholder",
      "fieldWarehouse",
      "fieldWarehousePlaceholder",
      "fieldRegion",
      "fieldRegionPlaceholder",
      "fieldBucket",
      "fieldBucketPlaceholder",
      "fieldToken",
      "fieldTokenPlaceholder",
      "fieldApiKey",
      "fieldApiKeyPlaceholder",
      "fieldEnvironment",
      "fieldEnvironmentPlaceholder",
      "fieldIndex",
      "fieldIndexPlaceholder",
      "fieldUrl",
      "fieldUrlPlaceholder",
      "testConnection",
      "testing",
      "connectionSuccess",
      "connectionFailed",
      "save",
      "saving",
      "cancel",
      "back",
      "enabled",
      "disabled",
      "dialect",
      "created",
      "deleted",
      "deleteConfirm"
    ];
    const labels = {};
    for (const key of keys) labels[key] = t(key);
    return labels;
  }, [t]);
}
function AgentsWorkspace({ workflowId, messages }) {
  const navigate = useNavigate();
  const locale = useLocale();
  const tWorkflow = useTranslations("agents.workflow");
  const tCommon = useTranslations("common");
  const datasourceLabels = useDatasourceLabels();
  const { error: notifyError, success: notifySuccess } = useNotifications();
  const showSuccess = useCallback((title, message) => {
    notifySuccess(title, message);
  }, [notifySuccess]);
  const showError = useCallback((title, message) => {
    notifyError(title, message);
    if (message) {
      console.error("[AgentsWorkspace]", message);
    }
  }, []);
  const [isLoading, setIsLoading] = useState(true);
  const [loadError, setLoadError] = useState(null);
  const [isLoadingWorkflows, setIsLoadingWorkflows] = useState(true);
  const [isPublishing, setIsPublishing] = useState(false);
  const [workflows, setWorkflows] = useState([]);
  const [workflow, setWorkflow] = useState(null);
  const [agents, setAgents] = useState([]);
  const [models, setModels] = useState([]);
  const [tools, setTools] = useState([]);
  const [agentToolDefs, setAgentToolDefs] = useState([]);
  const [rules, setRules] = useState([]);
  const [datasources, setDatasources] = useState([]);
  const [modelConnections, setModelConnections] = useState([]);
  const [showDatasourceModal, setShowDatasourceModal] = useState(false);
  const openPipelineSettingsModal = useModalStore((s) => s.openPipelineSettingsModal);
  const [showRunInputDialog, setShowRunInputDialog] = useState(false);
  const [showPreviewPanel, setShowPreviewPanel] = useState(false);
  const [isCreatingAgent, setIsCreatingAgent] = useState(false);
  const openSubworkflowModal = useSubworkflowStore((s) => s.openModal);
  const closeSubworkflowModal = useSubworkflowStore((s) => s.closeModal);
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [saveStatus, setSaveStatus] = useState("idle");
  const latestGraphRef = useRef(null);
  const saveTimerRef = useRef(null);
  const skipInitialAutoSaveRef = useRef(true);
  const showRunPanel = useWorkflowStore((state) => state.showRunPanel);
  const toggleRunPanel = useWorkflowStore((state) => state.toggleRunPanel);
  const workflowNodes = useWorkflowStore((state) => state.nodes);
  const { execute: executeWorkflowRun, stop: stopWorkflowRun, isRunning } = useWorkflowExecution(workflowId);
  const loadWorkspaceData = useCallback(async () => {
    setIsLoading(true);
    setLoadError(null);
    try {
      const [workflowData, agentList, modelList, agentToolDefList, ruleList, datasourceList, connectionList] = await Promise.all([
        getWorkflowById(workflowId),
        getAgentConfigsWithPrompts(),
        getAgentModels(),
        getAgentToolDefinitions().catch(() => []),
        getAgentRules(),
        getDatasources().catch(() => []),
        listModelProviderConnections().catch(() => [])
      ]);
      const toolResults = await Promise.all(
        agentList.map((agent) => getAgentTools(agent.agentId).catch(() => []))
      );
      const toolList = toolResults.flat();
      setWorkflow(workflowData);
      latestGraphRef.current = workflowData.graph;
      setAgents(agentList);
      setModels(modelList);
      setTools(toolList);
      setAgentToolDefs(agentToolDefList);
      setRules(ruleList);
      setDatasources(datasourceList);
      setModelConnections(connectionList);
    } catch (error) {
      const message = error instanceof Error ? error.message : tCommon("loadWorkspaceFailed");
      setWorkflow(null);
      setAgents([]);
      setModels([]);
      setTools([]);
      setAgentToolDefs([]);
      setRules([]);
      setDatasources([]);
      setModelConnections([]);
      setLoadError(message);
      notifyError(tCommon("serverError"), message);
    } finally {
      setIsLoading(false);
    }
  }, [workflowId]);
  const loadWorkflowList = useCallback(async () => {
    setIsLoadingWorkflows(true);
    try {
      const list = await getWorkflows();
      setWorkflows(list);
    } catch {
      setWorkflows([]);
    } finally {
      setIsLoadingWorkflows(false);
    }
  }, []);
  useEffect(() => {
    void loadWorkspaceData();
  }, [loadWorkspaceData]);
  useEffect(() => {
    void loadWorkflowList();
  }, [loadWorkflowList]);
  useEffect(() => {
    skipInitialAutoSaveRef.current = true;
  }, [workflowId]);
  useEffect(() => {
    return () => {
      if (saveTimerRef.current) {
        clearTimeout(saveTimerRef.current);
      }
    };
  }, []);
  const handleAutoSaveGraph = useCallback((graph) => {
    latestGraphRef.current = graph;
    if (isLoading || skipInitialAutoSaveRef.current) {
      skipInitialAutoSaveRef.current = false;
      return;
    }
    if (saveTimerRef.current) {
      clearTimeout(saveTimerRef.current);
    }
    setSaveStatus("saving");
    saveTimerRef.current = setTimeout(() => {
      void saveWorkflowDraft(workflowId, graph).then((updatedWorkflow) => {
        setWorkflow(updatedWorkflow);
        setWorkflows((current) => current.map((item) => item.id === updatedWorkflow.id ? updatedWorkflow : item));
        setSaveStatus("saved");
        setTimeout(() => setSaveStatus("idle"), 900);
      }).catch(() => {
        setSaveStatus("idle");
      });
    }, 800);
  }, [workflowId]);
  const handlePublish = useCallback(async () => {
    if (!latestGraphRef.current) return;
    const validation = validateWorkflowGraph(latestGraphRef.current, { locale });
    if (!validation.valid) {
      showError(tWorkflow("validationError"), validation.errors[0] ?? tWorkflow("validation"));
      return;
    }
    setIsPublishing(true);
    try {
      const published = await publishWorkflow(workflowId);
      setWorkflow(published);
      setWorkflows((current) => current.map((item) => item.id === published.id ? published : item));
    } finally {
      setIsPublishing(false);
    }
  }, [locale, showError, tWorkflow, workflowId]);
  const handleSelectWorkflow = useCallback((selected) => {
    if (selected.id === workflowId) return;
    navigate(`/workflows/edit?workflowId=${encodeURIComponent(selected.id)}`);
  }, [navigate, workflowId]);
  const handleCreateWorkflow = useCallback(async () => {
    const created = await createWorkflow({
      name: tWorkflow("defaultWorkflowName")
    });
    navigate(`/workflows/edit?workflowId=${encodeURIComponent(created.id)}`);
  }, [navigate, tWorkflow]);
  const handleDeleteWorkflow = useCallback((id, name) => {
    setDeleteTarget({ id, name });
  }, []);
  const confirmDelete = useCallback(async () => {
    if (!deleteTarget) return;
    await deleteWorkflow(deleteTarget.id);
    const remaining = workflows.filter((item) => item.id !== deleteTarget.id);
    if (remaining.length > 0) {
      navigate(`/workflows/edit?workflowId=${encodeURIComponent(remaining[0].id)}`);
    } else {
      navigate("/workflows");
    }
    setDeleteTarget(null);
  }, [deleteTarget, workflows, navigate]);
  const handleOpenRunDialog = useCallback(() => {
    const startNode = workflowNodes.find((node) => node.type === "start");
    const hasEndNode = workflowNodes.some((node) => node.type === "end");
    const hasValidStartConfig = Boolean(
      startNode && typeof startNode.data === "object" && startNode.data !== null && "config" in startNode.data && startNode.data.config && startNode.data.config.type === "start"
    );
    if (!hasValidStartConfig) {
      showError(tWorkflow("validationError"), tWorkflow("startNodeRequired"));
      return;
    }
    if (!hasEndNode) {
      showError(tWorkflow("validationError"), tWorkflow("endNodeRequired"));
      return;
    }
    setShowRunInputDialog(true);
  }, [workflowNodes, showError, tWorkflow]);
  const handleCreateAgent = useCallback(() => {
    setIsCreatingAgent(true);
  }, []);
  const handleCancelCreateAgent = useCallback(() => {
    setIsCreatingAgent(false);
  }, []);
  const handleAgentSaved = useCallback(async () => {
    const nextAgents = await getAgentConfigsWithPrompts();
    setAgents(nextAgents);
    setIsCreatingAgent(false);
  }, []);
  const handleToggleTool = useCallback(async (tool) => {
    try {
      const updated = await updateAgentTool(tool.toolId, { enabled: !tool.enabled });
      setTools((current) => current.map((item) => item.toolId === tool.toolId ? updated : item));
      showSuccess(
        tWorkflow("toolsSection"),
        updated.enabled ? tWorkflow("published") : tWorkflow("draftBadge")
      );
    } catch (error) {
      showError(
        tWorkflow("validationError"),
        error instanceof Error ? error.message : tWorkflow("publishError")
      );
    }
  }, [showError, showSuccess, tWorkflow]);
  const handleToggleRule = useCallback(async (rule) => {
    try {
      const updated = await updateAgentRule(rule.ruleId, { ...rule, enabled: !rule.enabled });
      setRules((current) => current.map((item) => item.ruleId === rule.ruleId ? updated : item));
      showSuccess(
        tWorkflow("rulesSection"),
        updated.enabled ? tWorkflow("published") : tWorkflow("draftBadge")
      );
    } catch (error) {
      showError(
        tWorkflow("validationError"),
        error instanceof Error ? error.message : tWorkflow("publishError")
      );
    }
  }, [showError, showSuccess, tWorkflow]);
  const handleCreateTool = useCallback(() => {
    openSubworkflowModal({ toolId: "", name: "", category: "external", enabled: true });
  }, [openSubworkflowModal]);
  const handleCreateRule = useCallback(() => {
  }, []);
  const handleCreateAgentTool = useCallback(() => {
  }, []);
  const handleConvertToSubworkflow = useCallback((workflow2) => {
    openSubworkflowModal({
      toolId: "",
      name: workflow2.name,
      description: workflow2.description ?? "",
      category: "external",
      enabled: true,
      config: { type: "workflow", graph: workflow2.graph }
    });
  }, [openSubworkflowModal]);
  const handleEditTool = useCallback((tool) => {
    openSubworkflowModal(tool);
  }, [openSubworkflowModal]);
  const handleCreateDatasource = useCallback(() => {
    setShowDatasourceModal(true);
  }, []);
  const handleSaveDatasource = useCallback(async (data) => {
    try {
      const created = await createDatasource(data);
      setDatasources((current) => [...current, created]);
      showSuccess(tWorkflow("dataSourcesSection"), tCommon("created") ?? "Created");
    } catch (error) {
      showError(
        tWorkflow("dataSourcesSection"),
        error instanceof Error ? error.message : tCommon("createDatasourceFailed")
      );
    }
  }, [showSuccess, showError, tWorkflow, tCommon]);
  const datasourceEntities = useMemo(
    () => datasources.map((ds) => ({
      id: ds.id,
      label: ds.name ?? ds.id,
      description: ds.dialect ?? "",
      defaultLimit: 100,
      fields: []
    })),
    [datasources]
  );
  const datasourceDefinitions = useMemo(
    () => datasources.map((ds) => ({
      id: ds.id,
      name: ds.name ?? ds.id,
      dialect: ds.dialect ?? "postgres"
    })),
    [datasources]
  );
  const paletteModelProviders = useMemo(() => {
    const toPaletteKey = (slug) => {
      switch (slug) {
        case "anthropic_api":
          return "anthropic";
        case "openai_api":
          return "openai";
        case "aws_bedrock":
          return "amazon";
        case "google_vertex":
          return "google";
        default:
          return slug ?? "custom";
      }
    };
    return modelConnections.map((connection) => ({
      id: connection.id,
      name: connection.name,
      provider: toPaletteKey(connection.providerSlug),
      modelCount: connection.modelFilter?.length ?? 1,
      configured: connection.enabled
    }));
  }, [modelConnections]);
  if (isLoading) {
    return /* @__PURE__ */ jsx("div", { className: "flex h-[calc(100vh-120px)] flex-col", children: /* @__PURE__ */ jsxs("div", { className: "liquid-surface flex h-full flex-col overflow-hidden rounded-2xl", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-shrink-0 items-center justify-between px-5 py-3", children: [
        /* @__PURE__ */ jsx("div", { className: "shimmer h-6 w-40 rounded-lg" }),
        /* @__PURE__ */ jsx("div", { className: "shimmer h-8 w-24 rounded-lg" })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "liquid-divider border-t" }),
      /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 overflow-hidden", children: [
        /* @__PURE__ */ jsxs("div", { className: "w-56 border-r border-white/20 p-4 dark:border-white/10", children: [
          /* @__PURE__ */ jsx("div", { className: "shimmer mb-3 h-5 w-24 rounded" }),
          /* @__PURE__ */ jsx("div", { className: "space-y-2", children: [1, 2, 3].map((index) => /* @__PURE__ */ jsx("div", { className: "shimmer h-10 w-full rounded-lg" }, index)) })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "flex flex-1 items-center justify-center", children: /* @__PURE__ */ jsx("div", { className: "shimmer h-8 w-48 rounded-lg" }) })
      ] })
    ] }) });
  }
  if (!workflow) {
    return /* @__PURE__ */ jsx("div", { className: "flex h-[calc(100vh-120px)] items-center justify-center", children: loadError ? /* @__PURE__ */ jsx(
      PageErrorState,
      {
        statusCode: 500,
        title: tCommon("serverError"),
        message: loadError,
        onRetry: () => {
          void loadWorkspaceData();
        },
        retryLabel: tCommon("retry")
      }
    ) : /* @__PURE__ */ jsx(
      PageEmptyState,
      {
        title: tWorkflow("emptyTitle"),
        message: tWorkflow("emptyDescription"),
        iconName: "cpu-chip"
      }
    ) });
  }
  return /* @__PURE__ */ jsx(WorkflowBuilderProvider, { publishableKey: getPublishableKey(), children: /* @__PURE__ */ jsxs("div", { className: "flex h-[calc(100vh-120px)] flex-col", "data-testid": "agents-workspace", children: [
    /* @__PURE__ */ jsxs("div", { className: "liquid-surface flex h-full flex-col overflow-hidden rounded-2xl", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-shrink-0 items-center justify-between px-5 py-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsx(
            "button",
            {
              type: "button",
              onClick: () => openPipelineSettingsModal(
                workflow.name,
                workflow.description ?? "",
                {
                  slug: workflow.slug ?? null,
                  isDraft: workflow.isDraft,
                  isActive: workflow.isActive
                }
              ),
              className: "rounded-lg px-2.5 py-1 text-sm font-semibold text-gray-900 transition-colors hover:bg-gray-100/80 dark:text-white dark:hover:bg-white/10",
              title: tWorkflow("editName"),
              children: workflow.name || tWorkflow("title")
            }
          ),
          /* @__PURE__ */ jsx(CopyableId, { id: workflowId, className: "text-[10px]" }),
          workflow.isDraft ? /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-amber-100 px-2.5 py-0.5 text-[10px] font-semibold text-amber-800 dark:bg-amber-900/30 dark:text-amber-300", children: tWorkflow("draftBadge") }) : /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-[10px] font-semibold text-green-800 dark:bg-green-900/30 dark:text-green-300", children: tWorkflow("published") }),
          /* @__PURE__ */ jsx(SaveStatusBadge, { status: saveStatus })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "xs",
              plain: true,
              onClick: () => setShowPreviewPanel((previous) => !previous),
              title: tWorkflow("previewPanel.title"),
              children: /* @__PURE__ */ jsx(ChartBarIcon, { className: "h-3.5 w-3.5", "data-slot": "icon" })
            }
          ),
          isRunning ? /* @__PURE__ */ jsxs(Button, { size: "xs", outline: true, onClick: stopWorkflowRun, children: [
            /* @__PURE__ */ jsx(StopIcon, { className: "h-3.5 w-3.5", "data-slot": "icon" }),
            tWorkflow("runPanel.stop")
          ] }) : /* @__PURE__ */ jsxs(
            Button,
            {
              size: "xs",
              outline: true,
              onClick: handleOpenRunDialog,
              disabled: !workflow.publishedGraph && !latestGraphRef.current,
              title: !workflow.publishedGraph && !latestGraphRef.current ? tWorkflow("noPublishedWorkflow") : void 0,
              children: [
                /* @__PURE__ */ jsx(PlayIcon, { className: "h-3.5 w-3.5", "data-slot": "icon" }),
                tWorkflow("runPanel.run")
              ]
            }
          ),
          /* @__PURE__ */ jsxs(Button, { gradient: true, size: "xs", onClick: () => {
            void handlePublish();
          }, disabled: isPublishing, children: [
            /* @__PURE__ */ jsx(DocumentCheckIcon, { className: "h-3.5 w-3.5", "data-slot": "icon" }),
            tWorkflow("publish")
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "liquid-divider border-t" }),
      /* @__PURE__ */ jsx("div", { className: "px-4 pt-3", children: /* @__PURE__ */ jsx(
        WorkflowListBar,
        {
          workflows,
          activeWorkflowId: workflowId,
          isLoading: isLoadingWorkflows,
          onSelect: handleSelectWorkflow,
          onCreate: () => {
            void handleCreateWorkflow();
          },
          onDelete: handleDeleteWorkflow,
          onConvertToSubworkflow: handleConvertToSubworkflow
        }
      ) }),
      /* @__PURE__ */ jsx("div", { className: "liquid-divider border-t" }),
      /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 overflow-hidden", children: [
        /* @__PURE__ */ jsx(
          NodePalette,
          {
            agents,
            tools,
            agentTools: agentToolDefs,
            rules,
            entities: datasourceEntities,
            modelProviders: paletteModelProviders,
            onCreateAgent: handleCreateAgent,
            onCreateTool: () => {
              void handleCreateTool();
            },
            onCreateAgentTool: () => {
              void handleCreateAgentTool();
            },
            onCreateRule: () => {
              void handleCreateRule();
            },
            onCreateDatasource: handleCreateDatasource
          }
        ),
        /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
          AutoSaveWorkspace,
          {
            workflowId,
            className: "h-full w-full",
            locale,
            ...messages ? { messages } : {},
            initialGraph: workflow.graph,
            agents,
            models,
            tools,
            agentTools: agentToolDefs,
            rules,
            datasources: datasourceDefinitions,
            onLoadTables: getDatasourceTables,
            onLoadSchema: getDatasourceSchema,
            onEditTool: handleEditTool,
            onToggleTool: handleToggleTool,
            onToggleRule: handleToggleRule,
            onAgentSaved: () => {
              void handleAgentSaved();
            },
            isCreatingAgent,
            onCancelCreateAgent: handleCancelCreateAgent,
            onAutoSaveGraph: handleAutoSaveGraph,
            onGraphSnapshot: (graph) => {
              latestGraphRef.current = graph;
            },
            renderAgentModal: (props) => /* @__PURE__ */ jsx(
              AgentModal,
              {
                ...props,
                onSaved: () => {
                  props.onSaved();
                  void handleAgentSaved();
                },
                onPersist: async (payload) => {
                  const body = {
                    name: payload.name,
                    displayName: payload.displayName,
                    description: payload.description,
                    avatar: payload.avatar,
                    modelId: payload.modelId,
                    modelProviderId: payload.connectionId,
                    framework: payload.framework,
                    systemPrompt: payload.systemPrompt,
                    instruction: payload.systemPrompt,
                    temperature: payload.temperature,
                    maxOutputTokens: payload.maxOutputTokens,
                    maxTokens: payload.maxOutputTokens,
                    topP: payload.topP,
                    topK: payload.topK,
                    elo: payload.elo,
                    status: payload.status,
                    tags: payload.tags,
                    agentToolIds: payload.enabledToolIds
                  };
                  if (payload.agentId) {
                    await updateAgentConfig(payload.agentId, body);
                  } else {
                    await createAgentConfig(body);
                  }
                }
              }
            )
          }
        ) })
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      PipelineSettingsModal,
      {
        onSave: async (changes) => {
          const metadata = {
            name: changes.name,
            description: changes.description
          };
          if (changes.slug !== void 0) metadata.slug = changes.slug;
          if (changes.isDraft !== void 0) metadata.isDraft = changes.isDraft;
          if (changes.isActive !== void 0) metadata.isActive = changes.isActive;
          const updated = latestGraphRef.current ? await saveWorkflowDraft(workflowId, latestGraphRef.current, metadata) : await updateWorkflowSettings(workflowId, metadata);
          setWorkflow(updated);
          setWorkflows((current) => current.map((item) => item.id === updated.id ? updated : item));
        }
      }
    ),
    /* @__PURE__ */ jsx(
      SubworkflowModal,
      {
        onMaximize: (subworkflowId) => {
          closeSubworkflowModal();
          navigate(`/workflows/edit?workflowId=${encodeURIComponent(subworkflowId)}`);
        },
        onSaved: async (saved) => {
          const isNew = !saved.toolId;
          if (isNew) {
            const created = await createWorkflow({
              name: saved.name,
              description: saved.description
            });
            closeSubworkflowModal();
            navigate(`/workflows/edit?workflowId=${encodeURIComponent(created.id)}`);
          } else {
            const updated = await updateAgentTool(saved.toolId, saved);
            setTools((current) => current.map((item) => item.toolId === saved.toolId ? updated : item));
            closeSubworkflowModal();
          }
        }
      }
    ),
    /* @__PURE__ */ jsx(
      RunPanel,
      {
        open: showRunPanel,
        onClose: toggleRunPanel,
        onRun: handleOpenRunDialog,
        onStop: stopWorkflowRun
      }
    ),
    /* @__PURE__ */ jsx(
      RunInputDialog,
      {
        open: showRunInputDialog,
        onClose: () => setShowRunInputDialog(false),
        onRun: (inputVariables) => {
          void executeWorkflowRun(inputVariables);
          if (!showRunPanel) {
            toggleRunPanel();
          }
        }
      }
    ),
    /* @__PURE__ */ jsx(
      PreviewPanel,
      {
        open: showPreviewPanel,
        onClose: () => setShowPreviewPanel(false),
        workflowId,
        loadRuns: getWorkflowRuns
      }
    ),
    /* @__PURE__ */ jsx(
      DatasourceFormModal,
      {
        open: showDatasourceModal,
        onClose: () => setShowDatasourceModal(false),
        labels: datasourceLabels,
        onSave: (data) => {
          void handleSaveDatasource(data);
        }
      }
    ),
    /* @__PURE__ */ jsx(
      DynamicIslandConfirm,
      {
        open: deleteTarget !== null,
        onClose: () => setDeleteTarget(null),
        onConfirm: () => {
          void confirmDelete();
        },
        title: `${tWorkflow("deleteWorkflowConfirm")} ${deleteTarget?.name ?? ""}?`
      }
    )
  ] }) });
}

export { AgentsWorkspace, applyWorkflowExecutionEventToStore, resetWorkflowRunPresentation, useRunEvents, useWorkflowExecution, useWorkflowRunPresentation };
//# sourceMappingURL=chunk-BR2GAZKG.mjs.map
//# sourceMappingURL=chunk-BR2GAZKG.mjs.map