Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

6.1 KB
Raw Blame
import { useMemo, type ReactNode } from "react";
import { useForm, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@/src/components/ui/button";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/src/components/ui/form";
import { Switch } from "@/src/components/design-system/Switch/Switch";
import {
  type AnalyticsIntegrationExportSource,
  BlobStorageIntegrationFileType,
  type ExportSourceContext,
} from "@langfuse/shared";
import {
  blobStorageIntegrationFormSchema,
  type BlobStorageIntegrationFormSchema,
} from "@/src/features/blobstorage-integration/types";
import { isExportSourceSelectable } from "@/src/features/analytics-integrations/exportSource";
import { type BlobStorageFormValues } from "@/src/features/blobstorage-integration/components/formValues";
import { StorageProviderFields } from "@/src/features/blobstorage-integration/components/StorageProviderFields";
import { ExportScheduleFields } from "@/src/features/blobstorage-integration/components/ExportScheduleFields";
import { ExportSourceField } from "@/src/features/blobstorage-integration/components/ExportSourceField";
import { ExportFieldGroupsField } from "@/src/features/blobstorage-integration/components/ExportFieldGroupsField";

// Disposable draft layer. The container mounts one instance per entity
// identity (project + config existence, via React key) after all async
// inputs have resolved. Initial state flows in once through defaultValues;
// edits flow out only through onSubmit. There is deliberately no reset
// logic and no tRPC access here — a stale draft is discarded by remount,
// never patched in place.
export const BlobStorageIntegrationForm = ({
  initialValues,
  exportSourceCtx,
  persistedExportSource,
  isSaving,
  onSubmit,
  children,
}: {
  initialValues: BlobStorageFormValues;
  exportSourceCtx: ExportSourceContext;
  persistedExportSource: AnalyticsIntegrationExportSource | null | undefined;
  isSaving: boolean;
  // Call `onSaved` once the values are persisted; a failed save never calls
  // it, so the draft stays dirty.
  onSubmit: (
    values: BlobStorageIntegrationFormSchema,
    onSaved: () => void,
  ) => void;
  // Entity-scoped action buttons (Validate / Run Now / Reset) rendered by
  // the container next to Save — they act on the persisted entity, not on
  // this draft. `isDirty` lets them refuse to act while the draft has
  // unsaved edits that the persisted entity does not reflect.
  children?: (state: { isDirty: boolean }) => ReactNode;
}) => {
  // Block the save when the persisted source is no longer selectable rather
  // than silently rewriting it (LFE-10296). The policy context is fixed for
  // the lifetime of this mount: it derives from the project and config
  // identity, and any identity change remounts the form via the container key.
  const formSchema = useMemo(
    () =>
      blobStorageIntegrationFormSchema.superRefine((data, ctx) => {
        if (!isExportSourceSelectable(data.exportSource, exportSourceCtx)) {
          ctx.addIssue({
            code: "custom",
            path: ["exportSource"],
            message:
              "This export source is not available on this deployment. Select an available export source to save.",
          });
        }
      }),
    [exportSourceCtx],
  );

  const blobStorageForm = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: initialValues,
  });

  const control = blobStorageForm.control;
  const fileType = useWatch({ control, name: "fileType" });
  const { isDirty } = blobStorageForm.formState;

  // After a successful save, the submitted values become the clean baseline.
  // Same-entity saves do not remount (see container key), so without this the
  // draft would stay dirty. keepValues preserves anything typed mid-save.
  const submit = blobStorageForm.handleSubmit((values) => {
    const submitted = blobStorageForm.getValues();
    onSubmit(values, () =>
      blobStorageForm.reset(submitted, { keepValues: true }),
    );
  });

  return (
    <Form {...blobStorageForm}>
      <form className="space-y-3" onSubmit={submit}>
        <StorageProviderFields
          control={control}
          setValue={blobStorageForm.setValue}
        />
        <ExportScheduleFields control={control} />
        <ExportSourceField
          control={control}
          persistedExportSource={persistedExportSource}
          exportSourceCtx={exportSourceCtx}
        />
        <ExportFieldGroupsField control={control} />
        {/* Parquet compresses internally — gzip does not apply. */}
        {fileType !== BlobStorageIntegrationFileType.PARQUET && (
          <FormField
            control={control}
            name="compressed"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Gzip Compression</FormLabel>
                <FormControl>
                  <div className="mt-1 ml-4">
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </div>
                </FormControl>
                <FormDescription>
                  Compress exported files with gzip (.csv.gz, .json.gz,
                  .jsonl.gz)
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        )}
        <FormField
          control={control}
          name="enabled"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Export enabled</FormLabel>
              <FormControl>
                <div className="mt-1 ml-4">
                  <Switch
                    checked={field.value}
                    onCheckedChange={field.onChange}
                  />
                </div>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
      </form>
      <div className="mt-8 flex gap-2">
        <Button loading={isSaving} onClick={submit}>
          Save
        </Button>
        {children?.({ isDirty })}
      </div>
    </Form>
  );
};