Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

18.6 KB
Raw Blame
import debounce from "lodash/debounce";
import {
  CircleCheck,
  CirclePlay,
  EllipsisVertical,
  FastForward,
  Info,
  LoaderCircle,
  RefreshCw,
  Trash2,
} from "lucide-react";
import PropTypes from "prop-types";
import { useEffect, useMemo, useRef, useState } from "react";
import { Button } from "@/components/ui/shims/antd-button";
import { Checkbox, Input } from "@/components/ui/shims/antd-inputs";
import { Col, Row } from "@/components/ui/shims/antd-layout";
import { Tag } from "@/components/ui/shims/antd-leaves";
import { Dropdown, Tooltip } from "@/components/ui/shims/antd-overlays";

import {
  PROMPT_RUN_TYPES,
  promptStudioUpdateStatus,
} from "../../../helpers/GetStaticData";
import { useCustomToolStore } from "../../../store/custom-tool-store";
import { ConfirmModal } from "../../widgets/confirm-modal/ConfirmModal";
import { EditableText } from "../editable-text/EditableText";
import { ExpandCardBtn } from "./ExpandCardBtn";

let PromptRunBtnSps;
try {
  const mod = await import(
    "../../../plugins/simple-prompt-studio/PromptRunBtnSps"
  );
  PromptRunBtnSps = mod.PromptRunBtnSps;
} catch {
  // The component will remain 'undefined' it is not available
}

let PromptChangeIndicator;
try {
  const mod = await import(
    "../../../plugins/prompt-change-indicator/PromptChangeIndicator"
  );
  PromptChangeIndicator = mod.PromptChangeIndicator;
} catch {
  // Cloud-only feedback loop indicator; stays undefined in OSS builds
}

let LookupMenuItem;
try {
  const mod = await import(
    "../../../plugins/lookup-studio/prompt-card/LookupMenuItem"
  );
  LookupMenuItem = mod.LookupMenuItem;
} catch {}

let usePromptRunGatePlugin;
let lookupPluginLoadError;
try {
  const mod = await import(
    "../../../plugins/lookup-studio/hooks/usePromptRunGate"
  );
  usePromptRunGatePlugin = mod.usePromptRunGate;
} catch (err) {
  lookupPluginLoadError = err;
}

// Sibling plugin loaded but this hook didn't — surface so the no-op fallback
// doesn't silently disable the run gate.
if (lookupPluginLoadError && LookupMenuItem) {
  console.warn(
    "[Header] lookup-studio plugin loaded but usePromptRunGate failed to import",
    lookupPluginLoadError,
  );
}

// Stable identity — avoid conditional hook call.
const usePromptRunGate = usePromptRunGatePlugin || (() => null);

function Header({
  promptDetails,
  promptKey,
  setPromptKey,
  progressMsg,
  handleRun,
  handleChange,
  handleDelete,
  updateStatus,
  updatePlaceHolder,
  isCoverageLoading,
  isEditingTitle,
  setIsEditingTitle,
  expandCard,
  setExpandCard,
  spsLoading,
  handleSpsLoading,
  enforceType,
  isAgenticTableReady = true,
  promptKeyError,
}) {
  const {
    selectedDoc,
    singlePassExtractMode,
    isSinglePassExtractLoading,
    indexDocs,
    isPublicSource,
    isSimplePromptStudio,
    details,
  } = useCustomToolStore();
  const runGate = usePromptRunGate(promptDetails);

  const [isDisablePrompt, setIsDisablePrompt] = useState(null);
  const [required, setRequired] = useState(false);
  const [webhookEnabled, setWebhookEnabled] = useState(false);
  const [webhookUrl, setWebhookUrl] = useState("");

  // Stable debounced functions using useRef
  const debouncedWebhookEnabledChangeRef = useRef(
    debounce((value, promptId, handleChangeFn, setStateFn) => {
      handleChangeFn(
        value,
        promptId,
        "enable_postprocessing_webhook",
        true,
        true,
      ).catch(() => {
        setStateFn(!value);
      });
    }, 300),
  );

  const debouncedWebhookUrlChangeRef = useRef(
    debounce((value, promptId, handleChangeFn, setStateFn) => {
      handleChangeFn(
        value,
        promptId,
        "postprocessing_webhook_url",
        true,
        true,
      ).catch(() => {
        setStateFn(promptDetails?.postprocessing_webhook_url || "");
      });
    }, 500),
  );

  const handleRunBtnClick = (promptRunType, docId = null) => {
    setExpandCard(true);
    handleRun(promptRunType, promptDetails?.prompt_id, null, docId);
  };

  const handleDisablePrompt = (event) => {
    const check = event?.target?.checked;
    setIsDisablePrompt(check);
    handleChange(check, promptDetails?.prompt_id, "active", true, true).catch(
      () => {
        setIsDisablePrompt(!check);
      },
    );
  };
  const handleRequiredChange = (value) => {
    const newValue = value === required ? null : value; // Allow deselection
    setRequired(newValue);
    handleChange(
      newValue,
      promptDetails?.prompt_id,
      "required",
      true,
      true,
    ).catch(() => {
      setRequired(promptDetails?.required || null); // Rollback state in case of error
    });
  };

  const handleWebhookEnabledChange = (e) => {
    const newValue = e.target.checked;
    setWebhookEnabled(newValue);
    debouncedWebhookEnabledChangeRef.current(
      newValue,
      promptDetails?.prompt_id,
      handleChange,
      setWebhookEnabled,
    );
  };

  const handleWebhookUrlChange = (value) => {
    setWebhookUrl(value);
    debouncedWebhookUrlChangeRef.current(
      value,
      promptDetails?.prompt_id,
      handleChange,
      setWebhookUrl,
    );
  };
  /*
   * One effect per field, keyed on that field's own value. Keyed on the whole
   * `promptDetails` object (plus `details`, which none of these fields read),
   * the effect re-ran on every *unrelated* optimistic update and re-seeded all
   * four from the last persisted prompt — so the webhook toggle's own save
   * landing mid-keystroke blanked the URL input the user was still typing in.
   */
  useEffect(() => {
    setIsDisablePrompt(promptDetails?.active);
  }, [promptDetails?.prompt_id, promptDetails?.active]);

  useEffect(() => {
    setRequired(promptDetails?.required);
  }, [promptDetails?.prompt_id, promptDetails?.required]);

  useEffect(() => {
    setWebhookEnabled(promptDetails?.enable_postprocessing_webhook || false);
  }, [promptDetails?.prompt_id, promptDetails?.enable_postprocessing_webhook]);

  useEffect(() => {
    setWebhookUrl(promptDetails?.postprocessing_webhook_url || "");
  }, [promptDetails?.prompt_id, promptDetails?.postprocessing_webhook_url]);

  /*
   * Derived, NOT state written from an effect. The webhook URL <Input> lives
   * inside these menu entries, so with `setItems` in an effect its `value` prop
   * trailed `webhookUrl` by one render: the render right after a keystroke
   * still carried the previous string, and React wrote that back onto the DOM
   * input. Typing at speed therefore dropped characters. useMemo builds the
   * entries in the same pass that updates the state they read.
   */
  const items = useMemo(() => {
    const dropdownItems = [
      {
        label: (
          <Checkbox checked={isDisablePrompt} onChange={handleDisablePrompt}>
            {isDisablePrompt ? "Enabled" : "Disabled"}
          </Checkbox>
        ),
        key: "enable",
      },
      {
        label: (
          <div>
            {["json", "table", "record"].indexOf(enforceType) === -1 && (
              <Checkbox
                checked={required === "all"}
                onChange={() => handleRequiredChange("all")}
              >
                Value Required{" "}
                <Tooltip title="Marks this as a required field. Saving this record won't be allowed in Human Quality Review should this field be empty.">
                  <span>
                    <Info />
                  </span>
                </Tooltip>
              </Checkbox>
            )}
            {enforceType === "json" && (
              <>
                {/*
                 * Each checkbox is grouped with its own tooltip icon so the
                 * two never separate, and the pairs share a row as they did
                 * under antd. `required-checkbox-padding`, which used to sit
                 * on the second checkbox, has no rule anywhere in the app —
                 * the gap came from antd's own adjacent-wrapper margin.
                 */}
                <div className="flex flex-wrap items-center gap-x-4 gap-y-1">
                  <span className="inline-flex items-center gap-1">
                    <Checkbox
                      checked={required === "all"}
                      onChange={() => handleRequiredChange("all")}
                    >
                      All JSON Values Required
                    </Checkbox>
                    <Tooltip title="When set, saving this record won't be allowed in Human Quality Review without all key/values filled in this JSON structure.">
                      <span>
                        <Info />
                      </span>
                    </Tooltip>
                  </span>
                  <span className="inline-flex items-center gap-1">
                    <Checkbox
                      checked={required === "any"}
                      onChange={() => handleRequiredChange("any")}
                    >
                      At least 1 JSON Value Required
                    </Checkbox>
                    <Tooltip title="When set, saving this record won't be allowed in Human Quality Review without at least one value filled in this JSON structure.">
                      <span>
                        <Info />
                      </span>
                    </Tooltip>
                  </span>
                </div>
                <div
                  style={{
                    marginTop: "8px",
                    borderTop: "1px solid #f0f0f0",
                    paddingTop: "8px",
                  }}
                >
                  <Checkbox
                    checked={webhookEnabled}
                    onChange={handleWebhookEnabledChange}
                    onClick={(e) => e.stopPropagation()}
                  >
                    Enable Postprocessing Webhook{" "}
                    <Tooltip title="Enable external webhook call to postprocess JSON responses before returning to user.">
                      <span>
                        <Info />
                      </span>
                    </Tooltip>
                  </Checkbox>
                  {webhookEnabled && (
                    <div style={{ marginTop: "8px", marginLeft: "24px" }}>
                      <Input
                        placeholder="https://example.com/webhook"
                        value={webhookUrl}
                        onChange={(e) => handleWebhookUrlChange(e.target.value)}
                        onClick={(e) => e.stopPropagation()}
                        size="small"
                        style={{ width: "280px" }}
                      />
                      <div
                        style={{
                          fontSize: "11px",
                          color: "#999",
                          marginTop: "4px",
                        }}
                      >
                        External service URL for JSON postprocessing
                      </div>
                    </div>
                  )}
                </div>
              </>
            )}
          </div>
        ),
        key: "required",
      },
      {
        label: (
          <ConfirmModal
            handleConfirm={() => handleDelete(promptDetails?.prompt_id)}
            content="The prompt will be permanently deleted."
          >
            <Trash2 /> Delete
          </ConfirmModal>
        ),
        key: "delete",
        disabled:
          isCoverageLoading ||
          isSinglePassExtractLoading ||
          indexDocs?.includes(selectedDoc?.document_id) ||
          isPublicSource,
      },
    ];
    if (LookupMenuItem && !isSimplePromptStudio) {
      dropdownItems.splice(
        -1,
        0,
        {
          type: "divider",
        },
        {
          label: <LookupMenuItem promptDetails={promptDetails} />,
          key: "lookup",
        },
      );
    }

    if (isSimplePromptStudio) {
      dropdownItems.splice(0, 1);
    }

    return dropdownItems;
  }, [isDisablePrompt, required, enforceType, webhookEnabled, webhookUrl]);

  return (
    <Row>
      <Col span={12}>
        <EditableText
          isEditing={isEditingTitle}
          setIsEditing={setIsEditingTitle}
          text={promptKey}
          setText={setPromptKey}
          promptId={promptDetails?.prompt_id}
          defaultText={promptDetails?.prompt_key}
          handleChange={handleChange}
          placeHolder={updatePlaceHolder}
          isCoverageLoading={isCoverageLoading}
          error={promptKeyError}
        />
      </Col>
      <Col span={12} className="display-flex-right">
        <div>
          {progressMsg?.message && (
            <Tooltip title={progressMsg?.message || ""}>
              <Tag
                icon={isCoverageLoading && <LoaderCircle spin />}
                color={progressMsg?.level === "ERROR" ? "error" : "processing"}
                className="display-flex-align-center"
              >
                <div className="tag-max-width ellipsis">
                  {progressMsg?.message}
                </div>
              </Tag>
            </Tooltip>
          )}
        </div>
        {updateStatus?.promptId === promptDetails?.prompt_id && (
          <>
            <div>
              {updateStatus?.status === promptStudioUpdateStatus.isUpdating && (
                <Tag
                  icon={<RefreshCw spin />}
                  color="processing"
                  className="display-flex-align-center"
                >
                  Updating
                </Tag>
              )}
            </div>
            <div>
              {updateStatus?.status === promptStudioUpdateStatus.done && (
                <Tag
                  icon={<CircleCheck />}
                  color="success"
                  className="display-flex-align-center"
                >
                  Done
                </Tag>
              )}
            </div>
            <div>
              {updateStatus?.status ===
                promptStudioUpdateStatus.validationError && (
                <Tag
                  icon={<CircleCheck />}
                  color="error"
                  className="display-flex-align-center"
                >
                  Invalid JSON Key
                </Tag>
              )}
            </div>
          </>
        )}
        {!singlePassExtractMode && !isSimplePromptStudio && (
          <>
            <Tooltip
              title={runGate?.reason || "Run all LLMs for current document"}
            >
              <Button
                data-testid={`ps-prompt-run-doc-${promptDetails?.prompt_id}`}
                size="small"
                type="text"
                className="prompt-card-action-button"
                onClick={() =>
                  handleRunBtnClick(
                    PROMPT_RUN_TYPES.RUN_ONE_PROMPT_ALL_LLMS_ONE_DOC,
                    selectedDoc?.document_id,
                  )
                }
                disabled={
                  !isAgenticTableReady ||
                  (updateStatus?.promptId === promptDetails?.prompt_id &&
                    updateStatus?.status ===
                      promptStudioUpdateStatus?.isUpdating) ||
                  isCoverageLoading ||
                  indexDocs?.includes(selectedDoc?.document_id) ||
                  isPublicSource ||
                  spsLoading?.[selectedDoc?.document_id] ||
                  !!runGate?.disabled
                }
              >
                <CirclePlay className="prompt-card-actions-head" />
              </Button>
            </Tooltip>
            <Tooltip
              title={runGate?.reason || "Run all LLMs for all documents"}
            >
              <Button
                data-testid={`ps-prompt-run-all-docs-${promptDetails?.prompt_id}`}
                size="small"
                type="text"
                className="prompt-card-action-button"
                onClick={() =>
                  handleRunBtnClick(
                    PROMPT_RUN_TYPES.RUN_ONE_PROMPT_ALL_LLMS_ALL_DOCS,
                  )
                }
                disabled={
                  !isAgenticTableReady ||
                  (updateStatus?.promptId === promptDetails?.prompt_id &&
                    updateStatus?.status ===
                      promptStudioUpdateStatus?.isUpdating) ||
                  isCoverageLoading ||
                  indexDocs?.includes(selectedDoc?.document_id) ||
                  isPublicSource ||
                  !!runGate?.disabled
                }
              >
                {/*
                 * "All documents" needs a DIFFERENT glyph from the
                 * "current document" button beside it. antd used
                 * PlayCircleFilled vs PlayCircleOutlined; the icon migration
                 * collapsed both to CirclePlay, leaving two identical buttons
                 * distinguished only by their tooltips. The double-chevron
                 * play reads as "run across everything".
                 */}
                <FastForward className="prompt-card-actions-head" />
              </Button>
            </Tooltip>
          </>
        )}
        <ExpandCardBtn
          expandCard={expandCard}
          setExpandCard={setExpandCard}
          testId={`ps-prompt-expand-${promptDetails?.prompt_id}`}
        />
        {PromptChangeIndicator && (
          <PromptChangeIndicator
            promptDetails={promptDetails}
            toolDetails={details}
          />
        )}
        {isSimplePromptStudio && PromptRunBtnSps && (
          <PromptRunBtnSps
            spsLoading={spsLoading}
            handleSpsLoading={handleSpsLoading}
            handleGetOutput={() => {
              // No-op: output fetching handled elsewhere
            }}
            promptDetails={promptDetails}
          />
        )}
        <Dropdown menu={{ items }} trigger={["click"]} placement="bottomLeft">
          <Button
            data-testid={`ps-prompt-menu-${promptDetails?.prompt_id}`}
            size="small"
            type="text"
            className="prompt-card-action-button"
          >
            <EllipsisVertical className="prompt-card-actions-head" />
          </Button>
        </Dropdown>
      </Col>
    </Row>
  );
}

Header.propTypes = {
  promptDetails: PropTypes.object.isRequired,
  promptKey: PropTypes.string,
  setPromptKey: PropTypes.func.isRequired,
  progressMsg: PropTypes.object.isRequired,
  handleRun: PropTypes.func.isRequired,
  handleChange: PropTypes.func.isRequired,
  handleDelete: PropTypes.func.isRequired,
  updateStatus: PropTypes.object.isRequired,
  updatePlaceHolder: PropTypes.string,
  isCoverageLoading: PropTypes.bool.isRequired,
  isEditingTitle: PropTypes.bool.isRequired,
  setIsEditingTitle: PropTypes.func.isRequired,
  expandCard: PropTypes.bool.isRequired,
  setExpandCard: PropTypes.func.isRequired,
  spsLoading: PropTypes.object,
  handleSpsLoading: PropTypes.func.isRequired,
  enforceType: PropTypes.string,
  isAgenticTableReady: PropTypes.bool,
  promptKeyError: PropTypes.string,
};

export { Header };