Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

31.0 KB
Raw Blame
import { clone, create } from "@bufbuild/protobuf";
import { Loader2, Pencil, Table, Upload } from "lucide-react";
import {
  type ChangeEvent,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useTranslation } from "react-i18next";
import {
  planServiceClientConnect,
  releaseServiceClientConnect,
  sheetServiceClientConnect,
} from "@/api";
import {
  captureEditorViewAnchor,
  type EditorViewAnchor,
  focusEditorAtAnchor,
  type IStandaloneCodeEditor,
  lineViewAnchor,
  MonacoEditor,
  type MonacoModule,
  ReadonlyMonaco,
} from "@/components/monaco";
import { ReleaseInfoCard } from "@/components/release/ReleaseInfoCard";
import { Alert } from "@/components/ui/alert";
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { seedSheetStatement } from "@/hooks/useSheetStatement";
import {
  AGENT_PLAN_DRAFT_EVENT,
  type AgentPlanDraftEventDetail,
  appendAgentPlanDraftSQL,
} from "@/lib/plan/agentDraftHandoff";
import { cn } from "@/lib/utils";
import { openAgentWithPrompt } from "@/modules/agent/logic/instanceConnectionHelp";
import { buildPlanCreatePrompt } from "@/modules/agent/logic/planIssueAssistance";
import { getDatabaseMentionLabel } from "@/modules/agent/logic/resourceMention";
import { useAgentStore } from "@/modules/agent/store/agent";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import {
  isValidDatabaseName,
  isValidReleaseName,
  languageOfEngineV1,
} from "@/types";
import {
  type Plan_Spec,
  Plan_SpecSchema,
  type PlanCheckRun,
  PlanSchema,
  UpdatePlanRequestSchema,
} from "@/types/proto-es/v1/plan_service_pb";
import {
  GetReleaseRequestSchema,
  type Release,
} from "@/types/proto-es/v1/release_service_pb";
import { GetSheetRequestSchema } from "@/types/proto-es/v1/sheet_service_pb";
import { unknownDatabase } from "@/types/v1/database";
import { extractDatabaseResourceName, hasProjectPermissionV2 } from "@/utils";
import { sqlReviewV2Enabled } from "@/utils/featureGates";
import { engineSupportsSchemaEditor } from "@/utils/schemaEditor";
import { getStatementSize, MAX_UPLOAD_FILE_SIZE_MB } from "@/utils/sheet";
import { getInstanceResource } from "@/utils/v1/database";
import { sheetNameOfSpec } from "@/utils/v1/issue/plan";
import {
  exceedsSheetPreviewLimit,
  extractSheetUID,
  getSheetStatement,
  setSheetStatement,
} from "@/utils/v1/sheet";
import { usePlanDetailStore } from "../shared/stores/usePlanDetailStore";
import { usePlanDetailContext } from "../shell/PlanDetailContext";
import {
  createEmptyLocalSheet,
  getLocalSheetByName,
  removeLocalSheet,
  setLocalSheetStatement,
} from "../utils/localSheet";
import { getSQLAdviceMarkers } from "../utils/sqlAdvice";
import { statementSummary } from "../utils/statementSummary";
import { SchemaEditorSheet } from "./SchemaEditorSheet";
import { StatementThreadsLayer } from "./threads/StatementThreadsLayer";
import {
  completePreviewLineCount,
  sheetSha256OfName,
} from "./threads/threadModel";

// Both modes reserve the same gutter so line numbers and SQL stay aligned
// when entering or leaving edit mode. Keep these options stable: MonacoEditor
// re-applies options on every new object.
const STATEMENT_EDITOR_OPTIONS = {
  glyphMargin: true,
  lineNumbersMinChars: 2,
  lineDecorationsWidth: 24,
  selectionHighlight: false,
  occurrencesHighlight: "off",
} as const;

// Sticky scroll would pin statement lines over the thread view zones.
const THREADS_EDITOR_OPTIONS = {
  ...STATEMENT_EDITOR_OPTIONS,
  selectOnLineNumbers: false,
  stickyScroll: { enabled: false },
} as const;

export function PlanDetailStatementSection({
  className,
  planCheckRuns = [],
  spec,
  statementVersion = 0,
}: {
  className?: string;
  planCheckRuns?: PlanCheckRun[];
  spec: Plan_Spec;
  statementVersion?: number;
}) {
  const { t } = useTranslation();
  const page = usePlanDetailContext();
  const { setEditing } = page;
  const databasesByName = useAppStore((s) => s.databasesByName);
  const currentUser = page.currentUser;
  const project = page.project;
  const releaseName =
    spec.config?.case === "changeDatabaseConfig"
      ? spec.config.value.release
      : "";
  const sheetName = useMemo(() => sheetNameOfSpec(spec), [spec]);
  const [release, setRelease] = useState<Release>();
  const [isLoading, setIsLoading] = useState(() =>
    isValidReleaseName(releaseName)
      ? false
      : seedSheetStatement(sheetName, getLocalSheetByName).isLoading
  );
  const [isSheetOversize, setIsSheetOversize] = useState(
    () => seedSheetStatement(sheetName, getLocalSheetByName).isTruncated
  );
  const [isDownloading, setIsDownloading] = useState(false);
  const [isEditing, setIsEditing] = useState(page.isCreating);
  const [isSaving, setIsSaving] = useState(false);
  const [statement, setStatement] = useState(
    () => seedSheetStatement(sheetName, getLocalSheetByName).statement
  );
  const [draftStatement, setDraftStatement] = useState("");
  const [isSchemaEditorOpen, setIsSchemaEditorOpen] = useState(false);
  const [pendingAgentDraft, setPendingAgentDraft] =
    useState<AgentPlanDraftEventDetail>();
  const inputRef = useRef<HTMLInputElement>(null);
  // The read-only editor instance, captured whenever one is created so the
  // threads layer can attach even if threads become enabled later. Editing,
  // an asynchronous sheet load, or an emptied statement unmounts and disposes
  // it; forget it whenever that happens so the layer never binds to a
  // disposed editor while the next one is still loading.
  const showsReadonlyEditor =
    !isLoading && !isEditing && Boolean(statement || draftStatement);
  const [readonlyEditor, setReadonlyEditor] = useState<{
    editor: IStandaloneCodeEditor;
    monaco: MonacoModule;
  }>();
  const [editingEditor, setEditingEditor] = useState<IStandaloneCodeEditor>();
  const editAnchorRef = useRef<EditorViewAnchor | undefined>(undefined);
  const threadFocus = usePlanDetailStore((state) => state.threadFocus);
  const clearThreadFocus = usePlanDetailStore(
    (state) => state.clearThreadFocus
  );
  useEffect(() => {
    if (!showsReadonlyEditor) setReadonlyEditor(undefined);
  }, [showsReadonlyEditor]);
  useEffect(() => {
    if (isEditing) return;
    setEditingEditor(undefined);
    editAnchorRef.current = undefined;
  }, [isEditing]);
  // The edit editor lands on a pending Activity anchor, which may arrive
  // before or after it mounts, or else on the place captured by Edit.
  useEffect(() => {
    if (!isEditing || !editingEditor) return;
    const activityLine =
      threadFocus?.specId === spec.id ? threadFocus.lineNumber : undefined;
    const anchor = activityLine
      ? lineViewAnchor(activityLine)
      : editAnchorRef.current;
    editAnchorRef.current = undefined;
    if (!anchor) return;
    focusEditorAtAnchor(editingEditor, anchor);
    if (activityLine && threadFocus) {
      // Activity lives in another phase section, so the editor may be off
      // screen.
      editingEditor.getDomNode()?.scrollIntoView({ block: "nearest" });
      clearThreadFocus(threadFocus.nonce);
    }
  }, [clearThreadFocus, editingEditor, isEditing, spec.id, threadFocus]);

  const editingScope = useMemo(() => `statement:${spec.id}`, [spec.id]);
  const targetDatabaseName = useMemo(() => {
    if (spec.config?.case !== "changeDatabaseConfig") {
      return "";
    }
    return (spec.config.value.targets ?? []).find(isValidDatabaseName) ?? "";
  }, [spec]);
  // All valid database targets — used by Schema Editor to load template metadata.
  const targetDatabaseNames = useMemo(() => {
    if (spec.config?.case !== "changeDatabaseConfig") return [];
    return (spec.config.value.targets ?? []).filter(isValidDatabaseName);
  }, [spec]);
  // Hydrate target databases so the engine check below isn't flying blind on
  // the unknownDatabase() stub returned for cache misses.
  useEffect(() => {
    if (targetDatabaseNames.length > 0) {
      void useAppStore.getState().batchGetOrFetchDatabases(targetDatabaseNames);
    }
  }, [targetDatabaseNames]);
  // Show Schema Editor only when at least one target's engine supports it.
  // Memoized on the databasesByName subscription so eligibility flips on once
  // the store hydrates the targets — otherwise a Plan opened before its targets
  // are cached would render with the button perpetually hidden.
  const schemaEditorEligible = useMemo(() => {
    if (targetDatabaseNames.length === 0) return false;
    return targetDatabaseNames.some((name) => {
      const db = databasesByName[name];
      if (!db || !isValidDatabaseName(db.name)) return false;
      return engineSupportsSchemaEditor(getInstanceResource(db).engine);
    });
  }, [targetDatabaseNames, databasesByName]);
  const language = useMemo(() => {
    if (!targetDatabaseName) return "sql";
    const database = databasesByName[targetDatabaseName] ?? unknownDatabase();
    return languageOfEngineV1(getInstanceResource(database).engine);
  }, [databasesByName, targetDatabaseName]);
  const autoCompleteContext = useMemo(() => {
    if (!targetDatabaseName) return undefined;
    return {
      instance: extractDatabaseResourceName(targetDatabaseName).instance,
      database: targetDatabaseName,
      scene: "all" as const,
    };
  }, [targetDatabaseName]);
  const statementTitle =
    language === "sql" ? t("common.sql") : t("common.statement");
  const displayedStatement = isEditing ? draftStatement : statement;
  const isEmpty = displayedStatement.trim() === "";
  const markers = useMemo(
    () => getSQLAdviceMarkers(planCheckRuns),
    [planCheckRuns]
  );
  // Under SQL Review V2 the summary report is not a check; it describes the
  // statement here.
  const summary = useMemo(
    () => (sqlReviewV2Enabled() ? statementSummary(planCheckRuns) : undefined),
    [planCheckRuns]
  );
  const summaryText = summary
    ? [
        summary.types.join(", "),
        summary.affectedRows > 0n
          ? t("plan.statement-summary.affected-rows", {
              count: Number(summary.affectedRows),
            })
          : "",
      ]
        .filter(Boolean)
        .join(" · ")
    : "";

  useEffect(() => {
    if (!isEditing) {
      setDraftStatement(statement);
    }
  }, [isEditing, statement]);

  useEffect(() => {
    setEditing(editingScope, isEditing);
    return () => setEditing(editingScope, false);
  }, [editingScope, isEditing, setEditing]);

  // Pending draft specs (not yet on the backend) start in edit mode so the
  // user can immediately type the SQL that will commit the spec.
  const isPendingDraft = !page.plan.specs.some(
    (candidate) => candidate.id === spec.id
  );
  useEffect(() => {
    // Depend on the boolean (not the specs array) so poll-driven refreshes
    // — which produce a new specs reference but the same membership — don't
    // wipe the user's in-progress edits.
    setIsEditing(page.isCreating || isPendingDraft);
    setDraftStatement("");
  }, [page.isCreating, isPendingDraft, spec.id]);

  useEffect(() => {
    let canceled = false;

    const load = async () => {
      if (isValidReleaseName(releaseName)) {
        try {
          setIsLoading(true);
          const nextRelease = await releaseServiceClientConnect.getRelease(
            create(GetReleaseRequestSchema, { name: releaseName })
          );
          if (!canceled) {
            setRelease(nextRelease);
          }
        } catch {
          if (!canceled) {
            setRelease(undefined);
          }
        } finally {
          if (!canceled) setIsLoading(false);
        }
        return;
      }

      if (!sheetName) {
        setStatement("");
        setDraftStatement("");
        setRelease(undefined);
        setIsSheetOversize(false);
        return;
      }

      // Resolve already-in-memory sheets synchronously (no loading/"No data"
      // flash on the first paint); only an uncached remote sheet needs a fetch.
      const seed = seedSheetStatement(sheetName, getLocalSheetByName);
      if (!seed.isLoading) {
        setStatement(seed.statement);
        setDraftStatement(seed.statement);
        setIsSheetOversize(seed.isTruncated);
        setIsLoading(false);
        return;
      }

      try {
        setIsLoading(true);
        const sheet = await useAppStore
          .getState()
          .getOrFetchSheetByName(sheetName);
        if (!sheet || canceled) return;
        const nextStatement = getSheetStatement(sheet);
        setStatement(nextStatement);
        setDraftStatement(nextStatement);
        setIsSheetOversize(getStatementSize(nextStatement) < sheet.contentSize);
      } finally {
        if (!canceled) setIsLoading(false);
      }
    };

    void load();
    return () => {
      canceled = true;
    };
  }, [releaseName, sheetName, statementVersion]);

  const hasSingleDatabaseTarget =
    spec.config?.case === "changeDatabaseConfig" &&
    spec.config.value.targets?.length === 1 &&
    isValidDatabaseName(spec.config.value.targets[0]);

  const updateLocalStatement = useCallback(
    (nextStatement: string) => {
      if (!sheetName) return;
      const sheet = getLocalSheetByName(sheetName);
      // Notifying write: the empty-statement validation subscribes to local
      // sheets. (Previously this cloned the plan into patchState purely to
      // force a re-render — the identity-preserving snapshot rightly ignores a
      // content-identical clone, so the signal must be explicit.)
      setLocalSheetStatement(sheet, nextStatement);
      setStatement(nextStatement);
      setDraftStatement(nextStatement);
      setIsSheetOversize(false);
    },
    [sheetName]
  );

  useEffect(() => {
    if (!page.isCreating) return;
    const handleAgentDraft = (event: Event) => {
      const detail = (event as CustomEvent<AgentPlanDraftEventDetail>).detail;
      if (
        !detail ||
        detail.handled ||
        detail.project !== project?.name ||
        !hasSingleDatabaseTarget ||
        targetDatabaseNames[0] !== detail.database
      ) {
        return;
      }
      detail.handled = true;
      if (!sheetName || !detail.sql.trim() || isLoading) {
        pushNotification({
          module: "bytebase",
          style: "CRITICAL",
          title: t("agent.plan-draft.current-plan-unavailable"),
        });
        return;
      }
      if (statement.trim()) {
        // This route-owned AlertDialog renders below the Agent overlay.
        if (useAgentStore.getState().visible) {
          useAgentStore.getState().minimize();
        }
        setPendingAgentDraft(detail);
        return;
      }
      updateLocalStatement(detail.sql);
    };

    window.addEventListener(AGENT_PLAN_DRAFT_EVENT, handleAgentDraft);
    return () =>
      window.removeEventListener(AGENT_PLAN_DRAFT_EVENT, handleAgentDraft);
  }, [
    hasSingleDatabaseTarget,
    isLoading,
    page.isCreating,
    project?.name,
    sheetName,
    statement,
    t,
    targetDatabaseNames,
    updateLocalStatement,
  ]);

  if (isValidReleaseName(releaseName)) {
    return (
      <PlanDetailReleaseStatement
        className={className}
        isLoading={isLoading}
        release={release}
        releaseName={releaseName}
      />
    );
  }

  const canModifyStatement = Boolean(
    !page.readonly &&
      !page.plan.hasRollout &&
      sheetName &&
      project &&
      (page.isCreating ||
        currentUser.name === page.plan.creator ||
        hasProjectPermissionV2(project, "bb.plans.update"))
  );
  const canEdit = canModifyStatement && !isSheetOversize && !page.isCreating;
  // An active edit session (not whole-plan creation) shows Save/Cancel.
  const isInlineEditing = isEditing && !page.isCreating;
  // Hide Upload/Schema editor only when editing an already-persisted statement;
  // a new pending-draft spec still needs them to author its first statement.
  const isEditingExistingStatement = isInlineEditing && !isPendingDraft;
  const hasChanges = page.isCreating
    ? draftStatement !== statement
    : isEditing && draftStatement !== statement;
  const canSave =
    !isSaving &&
    !isLoading &&
    Boolean(sheetName) &&
    draftStatement.trim() !== "" &&
    hasChanges;

  const selectedDatabaseName = hasSingleDatabaseTarget
    ? targetDatabaseNames[0]
    : undefined;
  const selectedDatabase = selectedDatabaseName
    ? databasesByName[selectedDatabaseName]
    : undefined;
  const selectedDatabaseLabel = selectedDatabase
    ? getDatabaseMentionLabel(selectedDatabase)
    : selectedDatabaseName?.split("/").at(-1);
  const askAgentToDraftSQL = () => {
    if (!project || !selectedDatabaseName || !selectedDatabaseLabel) return;
    openAgentWithPrompt(buildPlanCreatePrompt(), [
      {
        kind: "database",
        name: selectedDatabaseName,
        project: project.name,
        label: selectedDatabaseLabel,
      },
    ]);
  };

  const applyAgentDraft = (sql: string) => {
    updateLocalStatement(sql);
    setPendingAgentDraft(undefined);
  };

  const handleUploadClick = () => inputRef.current?.click();

  const handleFileUpload = async (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    event.target.value = "";
    if (!file) return;
    if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
      pushNotification({
        module: "bytebase",
        style: "CRITICAL",
        title: t("issue.upload-sql-file-max-size-exceeded", {
          size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
        }),
      });
      return;
    }
    const nextStatement = await file.text();
    if (isSheetOversize && statement.trim() !== "") {
      const confirmed = window.confirm(t("issue.overwrite-current-statement"));
      if (!confirmed) return;
    }
    if (page.isCreating) {
      updateLocalStatement(nextStatement);
      return;
    }
    setDraftStatement(nextStatement);
    setIsEditing(true);
  };

  const handleBeginEdit = () => {
    editAnchorRef.current =
      readonlyEditor && captureEditorViewAnchor(readonlyEditor.editor);
    setIsEditing(true);
  };

  const handleSchemaEditorInsert = (nextStatement: string) => {
    if (page.isCreating) {
      updateLocalStatement(nextStatement);
      return;
    }
    setDraftStatement(nextStatement);
    setIsEditing(true);
  };

  const patchPlanStatement = (nextSheetName: string) => {
    const planPatch = clone(PlanSchema, page.plan);
    const existingIdx = planPatch.specs.findIndex(
      (candidate) => candidate.id === spec.id
    );
    if (existingIdx === -1) {
      // Pending new spec — append it on the first save so the spec and
      // its sheet are committed together. This avoids creating an
      // empty-statement spec on the backend.
      if (spec.config?.case !== "changeDatabaseConfig") {
        return undefined;
      }
      const newSpec = clone(Plan_SpecSchema, spec);
      if (newSpec.config.case === "changeDatabaseConfig") {
        newSpec.config.value.sheet = nextSheetName;
      }
      planPatch.specs = [...planPatch.specs, newSpec];
      return planPatch;
    }
    const specToPatch = planPatch.specs[existingIdx];
    if (specToPatch.config?.case !== "changeDatabaseConfig") {
      return undefined;
    }
    specToPatch.config.value.sheet = nextSheetName;
    return planPatch;
  };

  const handleSave = async () => {
    if (!project || !sheetName || !canSave) return;

    if (page.isCreating) {
      updateLocalStatement(draftStatement);
      return;
    }

    try {
      setIsSaving(true);
      const sheet = createEmptyLocalSheet();
      setSheetStatement(sheet, draftStatement);
      const previousSheetName = sheetName;
      const createdSheet = await useAppStore
        .getState()
        .createSheet(project.name, sheet);
      const nextPlan = patchPlanStatement(createdSheet.name);
      if (!nextPlan) return;
      const request = create(UpdatePlanRequestSchema, {
        plan: nextPlan,
        updateMask: { paths: ["specs"] },
      });
      const response = await planServiceClientConnect.updatePlan(request);
      page.patchState({ plan: response });
      // Drop the orphaned local sheet only after the spec is committed
      // to the new server sheet — otherwise an updatePlan failure would
      // leave the spec pointing at a now-empty local entry, losing the
      // user's typed content on the next read.
      if (
        previousSheetName &&
        extractSheetUID(previousSheetName).startsWith("-")
      ) {
        removeLocalSheet(previousSheetName);
      }
      setStatement(draftStatement);
      setIsEditing(false);
      pushNotification({
        module: "bytebase",
        style: "SUCCESS",
        title: t("common.updated"),
      });
      void page.refreshState();
    } catch (error) {
      pushNotification({
        module: "bytebase",
        style: "CRITICAL",
        title: t("common.error"),
        description: String(error),
      });
    } finally {
      setIsSaving(false);
    }
  };

  const downloadSheet = async () => {
    if (!sheetName) return;
    try {
      setIsDownloading(true);
      const uid = extractSheetUID(sheetName);
      const content = uid.startsWith("-")
        ? statement
        : new TextDecoder().decode(
            (
              await sheetServiceClientConnect.getSheet(
                create(GetSheetRequestSchema, {
                  name: sheetName,
                  raw: true,
                })
              )
            ).content
          );
      const filename = `${sheetName.split("/").pop() || "sheet"}.sql`;
      const blob = new Blob([content], { type: "text/plain" });
      const url = URL.createObjectURL(blob);
      const anchor = document.createElement("a");
      anchor.href = url;
      anchor.download = filename;
      document.body.appendChild(anchor);
      anchor.click();
      document.body.removeChild(anchor);
      URL.revokeObjectURL(url);
    } catch (error) {
      pushNotification({
        module: "bytebase",
        style: "CRITICAL",
        title: t("common.error"),
        description: String(error),
      });
    } finally {
      setIsDownloading(false);
    }
  };

  const editorContent = page.isCreating ? statement : draftStatement;

  // Inline threads anchor to the saved sheet of a persisted spec. A truncated
  // preview can still show threads on its complete lines.
  const sheetSha256 = sheetSha256OfName(sheetName);
  const issue = page.issue;
  const showLargeSheetWarning = useMemo(
    () =>
      isEditing
        ? exceedsSheetPreviewLimit(draftStatement)
        : isSheetOversize ||
          (!isLoading &&
            Boolean(sheetSha256) &&
            exceedsSheetPreviewLimit(statement)),
    [
      draftStatement,
      isEditing,
      isLoading,
      isSheetOversize,
      sheetSha256,
      statement,
    ]
  );
  const previewEndLine = useMemo(
    () =>
      isSheetOversize ? completePreviewLineCount(statement, true) : undefined,
    [isSheetOversize, statement]
  );
  const threadsEnabled = Boolean(
    issue && !page.isCreating && !isPendingDraft && sheetSha256
  );

  return (
    <div className={cn("flex flex-col gap-y-1", className)}>
      <div className="flex flex-wrap items-start justify-between gap-2">
        <div
          className={cn(
            "flex items-center gap-x-1 textlabel uppercase",
            isEmpty && "text-error"
          )}
        >
          <span>{statementTitle}</span>
          {isEmpty && <span className="text-error">*</span>}
          {summaryText && !isEmpty && (
            <span
              className="ml-2 text-xs font-normal normal-case text-control-light"
              data-testid="statement-summary"
            >
              {summaryText}
            </span>
          )}
        </div>
        <Input
          ref={inputRef}
          accept=".sql,.txt,application/sql,text/plain"
          className="hidden"
          onChange={(event) => void handleFileUpload(event)}
          type="file"
        />
        {(canModifyStatement || isEditing) && (
          <div className="ml-auto flex w-full max-w-full flex-wrap items-center justify-end gap-x-2 gap-y-2 sm:w-auto">
            {page.isCreating &&
              project &&
              hasSingleDatabaseTarget &&
              selectedDatabaseName && (
                <Button
                  className="h-auto max-w-full whitespace-normal text-left"
                  onClick={askAgentToDraftSQL}
                  size="xs"
                  appearance="outline"
                >
                  {t("agent.plan-assistance.ask-draft-sql")}
                </Button>
              )}
            {!isEditingExistingStatement && (
              <>
                <Button
                  onClick={handleUploadClick}
                  size="xs"
                  appearance="outline"
                >
                  <Upload className="h-3.5 w-3.5" />
                  {t("issue.upload-sql")}
                </Button>
                {schemaEditorEligible && (
                  <Button
                    onClick={() => setIsSchemaEditorOpen(true)}
                    size="xs"
                    appearance="outline"
                  >
                    <Table className="h-3.5 w-3.5" />
                    {t("schema-editor.self")}
                  </Button>
                )}
              </>
            )}
            {!isEditing && canEdit && (
              <Button onClick={handleBeginEdit} size="xs" appearance="outline">
                <Pencil className="h-3.5 w-3.5" />
                {t("common.edit")}
              </Button>
            )}
            {isInlineEditing && (
              <>
                <Button
                  disabled={!canSave}
                  onClick={() => void handleSave()}
                  size="xs"
                  appearance="outline"
                >
                  {isSaving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
                  {t("common.save")}
                </Button>
                <Button
                  onClick={() => {
                    setDraftStatement(statement);
                    setIsEditing(false);
                  }}
                  size="xs"
                  appearance="secondary"
                >
                  {t("common.cancel")}
                </Button>
              </>
            )}
          </div>
        )}
      </div>
      {showLargeSheetWarning && (
        <Alert
          variant="warning"
          description={
            <div className="flex items-center justify-between gap-x-4">
              <span>
                {isEditing
                  ? t("issue.statement-exceeds-preview-limit")
                  : t("issue.statement-from-sheet-warning")}
              </span>
              {!isEditing && sheetName && (
                <Button
                  disabled={isDownloading}
                  onClick={() => void downloadSheet()}
                  size="xs"
                  appearance="outline"
                >
                  {isDownloading && (
                    <Loader2 className="h-3.5 w-3.5 animate-spin" />
                  )}
                  {t("common.download")}
                </Button>
              )}
            </div>
          }
        />
      )}
      {isLoading ? (
        <div className="rounded-sm border border-control-border bg-background px-4 py-3 text-sm text-control-light">
          {t("common.loading")}
        </div>
      ) : isEditing || showsReadonlyEditor ? (
        <div className="relative overflow-hidden rounded-sm border border-control-border">
          {isEditing ? (
            <MonacoEditor
              advices={page.isCreating ? markers : []}
              autoCompleteContext={autoCompleteContext}
              className="relative h-auto max-h-[600px] min-h-[120px]"
              content={editorContent}
              language={language}
              options={STATEMENT_EDITOR_OPTIONS}
              onReady={(_monaco, editor) => setEditingEditor(editor)}
              onChange={(nextStatement) => {
                if (page.isCreating) {
                  updateLocalStatement(nextStatement);
                  return;
                }
                setDraftStatement(nextStatement);
              }}
            />
          ) : (
            <>
              <ReadonlyMonaco
                advices={markers}
                className="relative h-auto max-h-[600px] min-h-[120px]"
                content={statement}
                language={language}
                onReady={(monaco, editor) =>
                  setReadonlyEditor({ editor, monaco })
                }
                options={
                  threadsEnabled
                    ? THREADS_EDITOR_OPTIONS
                    : STATEMENT_EDITOR_OPTIONS
                }
              />
              {threadsEnabled && issue && sheetSha256 && readonlyEditor && (
                <StatementThreadsLayer
                  editor={readonlyEditor.editor}
                  issue={issue}
                  key={sheetSha256}
                  monaco={readonlyEditor.monaco}
                  previewEndLine={previewEndLine}
                  sheetSha256={sheetSha256}
                  spec={spec}
                />
              )}
            </>
          )}
        </div>
      ) : (
        <div className="rounded-sm border border-control-border bg-background px-4 py-3 text-sm text-control-light">
          {t("common.no-data")}
        </div>
      )}
      {project && schemaEditorEligible && (
        <SchemaEditorSheet
          open={isSchemaEditorOpen}
          onOpenChange={setIsSchemaEditorOpen}
          databaseNames={targetDatabaseNames}
          project={project}
          onInsert={handleSchemaEditorInsert}
        />
      )}
      <AlertDialog
        open={Boolean(pendingAgentDraft)}
        onOpenChange={(open) => {
          if (!open) setPendingAgentDraft(undefined);
        }}
      >
        <AlertDialogContent>
          <AlertDialogTitle>
            {t("agent.plan-draft.existing-sql-title")}
          </AlertDialogTitle>
          <AlertDialogDescription>
            {t("agent.plan-draft.existing-sql-description")}
          </AlertDialogDescription>
          <AlertDialogFooter className="flex-wrap gap-y-2">
            <Button
              appearance="secondary"
              onClick={() => setPendingAgentDraft(undefined)}
            >
              {t("common.cancel")}
            </Button>
            <Button
              appearance="outline"
              onClick={() => {
                if (!pendingAgentDraft) return;
                applyAgentDraft(
                  appendAgentPlanDraftSQL(statement, pendingAgentDraft.sql)
                );
              }}
            >
              {t("agent.plan-draft.append-sql")}
            </Button>
            <Button
              onClick={() => {
                if (!pendingAgentDraft) return;
                applyAgentDraft(pendingAgentDraft.sql);
              }}
            >
              {t("agent.plan-draft.replace-sql")}
            </Button>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

function PlanDetailReleaseStatement({
  className,
  isLoading,
  release,
  releaseName,
}: {
  className?: string;
  isLoading: boolean;
  release?: Release;
  releaseName: string;
}) {
  return (
    <ReleaseInfoCard
      className={cn("h-full", className)}
      isLoading={isLoading}
      release={release}
      releaseName={releaseName}
    />
  );
}