Skip to content

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

7.2 KB
Raw Blame
import React from "react";
import { Card } from "@/src/components/ui/card";
import { Button } from "@/src/components/ui/button";
import { api } from "@/src/utils/api";
import { useForm } from "react-hook-form";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/src/components/ui/form";
import Header from "@/src/components/layouts/header";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { useHasEntitlement } from "@/src/features/entitlements/hooks";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { XIcon, Check } from "@langfuse/icons";
import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";
import { ActionButton } from "@/src/components/ActionButton";
import { cn } from "@/src/utils/tailwind";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
} from "@/src/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/src/components/ui/popover";

import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";
import {
  LATEST_PROMPT_LABEL,
  PRODUCTION_LABEL,
  PromptLabelSchema,
} from "@langfuse/shared";

const AddLabelFormSchema = z.object({
  label: PromptLabelSchema,
});

type AddLabelFormSchemaType = z.infer<typeof AddLabelFormSchema>;

export default function ProtectedLabelsSettings({
  projectId,
}: {
  projectId: string;
}) {
  const hasAccess = useHasProjectAccess({
    projectId,
    scope: "promptProtectedLabels:CUD",
  });
  const hasEntitlement = useHasEntitlement("prompt-protected-labels");

  const form = useForm({
    resolver: zodResolver(AddLabelFormSchema),
    defaultValues: {
      label: "",
    },
  });

  const utils = api.useUtils();
  const { data: protectedLabels = [] } =
    api.prompts.getProtectedLabels.useQuery(
      { projectId },
      {
        enabled: Boolean(projectId),
      },
    );

  const { data: allLabels = [] } = api.prompts.allLabels.useQuery(
    { projectId },
    {
      enabled: Boolean(projectId),
    },
  );

  // Filter out labels that are already protected
  const availableLabels = allLabels.filter(
    (label) =>
      !protectedLabels.includes(label) && label !== LATEST_PROMPT_LABEL,
  );

  const addProtectedLabel = api.prompts.addProtectedLabel.useMutation({
    onSuccess: () => {
      utils.prompts.getProtectedLabels.invalidate();
      form.reset();
    },
  });

  const removeProtectedLabel = api.prompts.removeProtectedLabel.useMutation({
    onSuccess: () => {
      utils.prompts.getProtectedLabels.invalidate();
    },
  });

  function onSubmit(values: AddLabelFormSchemaType) {
    addProtectedLabel.mutate({
      projectId,
      label: values.label,
    });
  }

  const [open, setOpen] = React.useState(false);

  return (
    <div>
      <Header title="Protected Labels" />
      <Card className="mb-4 p-3">
        <p className="text-primary mb-4 text-sm">
          Protected labels can only be modified by users with admin or owner
          access. This prevents other users from changing or removing these
          labels from prompts and skills.
        </p>
        <div className="mb-4 flex flex-wrap gap-2">
          {protectedLabels.map((label) => (
            <StatusBadge
              type={label}
              key={label}
              isLive={label === PRODUCTION_LABEL}
              preserveCase
            >
              {hasAccess && hasEntitlement && (
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-4 w-4 p-0 hover:bg-transparent"
                  onClick={() => {
                    if (
                      confirm(
                        `Are you sure you want to remove the protected label "${label}"?`,
                      )
                    ) {
                      removeProtectedLabel.mutate({ projectId, label });
                    }
                  }}
                >
                  <XIcon size="base" color="default" />
                </Button>
              )}
            </StatusBadge>
          ))}
        </div>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex items-start gap-2"
          >
            <FormField
              control={form.control}
              name="label"
              render={({ field }) => (
                <FormItem className="flex-1">
                  <Popover open={open} onOpenChange={setOpen}>
                    <PopoverTrigger asChild>
                      <FormControl>
                        <Button
                          variant="outline"
                          // eslint-disable-next-line jsx-a11y/role-has-required-aria-props
                          role="combobox"
                          aria-expanded={open}
                          className={cn(
                            "w-full justify-between gap-2",
                            !field.value && "text-muted-foreground",
                          )}
                          disabled={!hasAccess || !hasEntitlement}
                        >
                          {field.value || "Select or enter a label"}
                          <DropdownIndicator direction="up-down" />
                        </Button>
                      </FormControl>
                    </PopoverTrigger>
                    <PopoverContent className="w-full p-0">
                      <Command>
                        <CommandInput
                          placeholder="Search or enter a new label..."
                          onValueChange={(value) => {
                            field.onChange(value);
                          }}
                        />
                        <CommandEmpty>No label found</CommandEmpty>
                        <CommandGroup>
                          {availableLabels.map((label) => (
                            <CommandItem
                              value={label}
                              key={label}
                              onSelect={() => {
                                field.onChange(label);
                                setOpen(false);
                              }}
                            >
                              <Check
                                size="base"
                                __rawClassName={cn(
                                  "mr-2",
                                  field.value === label
                                    ? "opacity-100"
                                    : "opacity-0",
                                )}
                              />
                              {label}
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </Command>
                    </PopoverContent>
                  </Popover>
                  <FormMessage />
                </FormItem>
              )}
            />
            <ActionButton
              type="submit"
              variant="secondary"
              loading={addProtectedLabel.isPending}
              hasAccess={hasAccess}
              hasEntitlement={hasEntitlement}
            >
              Add
            </ActionButton>
          </form>
        </Form>
      </Card>
    </div>
  );
}