🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(web): Clean up `TransferProjectButton` (#16638)
Ben Bachem22b6636d6fc4
diff --git a/web/src/features/projects/components/TransferProjectButton.tsx b/web/src/features/projects/components/TransferProjectButton.tsxdeleted file mode 100644index 1035334b7f..0000000000--- a/web/src/features/projects/components/TransferProjectButton.tsx+++ /dev/null@@ -1,204 +0,0 @@-/* eslint-disable @repo/no-abstracted-overlay-trigger */-import { Button } from "@/src/components/ui/button";-import {- Dialog,- DialogBody,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/src/components/ui/dialog";-import {- Form,- FormControl,- FormDescription,- FormField,- FormItem,- FormLabel,- FormMessage,-} from "@/src/components/ui/form";-import { Input } from "@/src/components/ui/input";-import { api } from "@/src/utils/api";-import * as z from "zod";-import { useForm } from "react-hook-form";-import { zodResolver } from "@hookform/resolvers/zod";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import {- hasOrganizationAccess,- useHasOrganizationAccess,-} from "@/src/features/rbac/utils/checkOrganizationAccess";-import { useQueryProject } from "@/src/features/projects/hooks";-import { useSession } from "next-auth/react";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/src/components/ui/select";-import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";-import { TriangleAlert } from "lucide-react";-import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";--export function TransferProjectButton() {- const capture = usePostHogClientCapture();- const session = useSession();- const { project, organization } = useQueryProject();- const hasAccess = useHasOrganizationAccess({- organizationId: organization?.id,- scope: "projects:transfer_org",- });- const allOrgs = session.data?.user?.organizations ?? [];- const organizationsToTransferTo =- allOrgs.filter((org) =>- hasOrganizationAccess({- session: session.data,- organizationId: org.id,- scope: "projects:transfer_org",- }),- ) ?? [];- const confirmMessage = (organization?.name + "/" + project?.name)- .replaceAll(" ", "-")- .toLowerCase();-- const formSchema = z.object({- name: z.string().includes(confirmMessage, {- message: `Please confirm with "${confirmMessage}"`,- }),- projectId: z.string(),- });-- const transferProject = api.projects.transfer.useMutation({- onSuccess: async () => {- showSuccessToast({- title: "Project transferred",- description:- "The project is successfully transferred to the new organization. Redirecting...",- });- await new Promise((resolve) => setTimeout(resolve, 5000));- session.update();- // Existing hard navigation is accepted during the Next.js 16.3 migration.- // eslint-disable-next-line @next/next/no-location-assign-relative-destination- window.location.href = "/";- },- });-- const form = useForm({- resolver: zodResolver(formSchema),- defaultValues: {- name: "",- projectId: "",- },- });-- const onSubmit = (values: z.infer<typeof formSchema>) => {- if (!project) return;- capture("project_settings:project_delete");- transferProject.mutate({- projectId: project.id,- targetOrgId: values.projectId,- });- };-- return (- <Dialog>- <DialogTrigger asChild>- <Button variant="destructive-secondary" disabled={!hasAccess}>- Transfer Project- </Button>- </DialogTrigger>- <DialogContent className="sm:max-w-[425px]">- <DialogHeader>- <DialogTitle className="text-lg font-bold">- Transfer Project- </DialogTitle>- <Alert className="mt-2">- <TriangleAlert className="h-4 w-4" />- <AlertTitle>Warning</AlertTitle>- <AlertDescription>- Transferring the project will move it to a different organization:- <ul className="list-disc pl-4">- <li>- Members who are not part of the new organization will lose- access.- </li>- <li>- The project remains fully operational as API keys, settings,- and data will remain unchanged. All features (e.g. tracing,- prompt management) will continue to work without interruption.- </li>- </ul>- </AlertDescription>- </Alert>- </DialogHeader>- <Form {...form}>- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">- <DialogBody>- <FormField- control={form.control}- name="projectId"- render={({ field }) => (- <FormItem>- <FormLabel>Select New Organization</FormLabel>- <FormControl>- <Select- onValueChange={field.onChange}- value={field.value}- disabled={transferProject.isPending}- >- <SelectTrigger>- <SelectValue placeholder="Select organization" />- </SelectTrigger>- <SelectContent>- {organizationsToTransferTo- .filter((org) => org.id !== organization?.id)- .map((org) => (- <SelectItem key={org.id} value={org.id}>- {org.name}- </SelectItem>- ))}- </SelectContent>- </Select>- </FormControl>- <FormDescription>- Transfer this project to another organization where you- have the ability to create projects.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem>- <FormLabel>Confirm</FormLabel>- <FormControl>- <Input placeholder={confirmMessage} {...field} />- </FormControl>- <FormDescription>- {`To confirm, type "${confirmMessage}" in the input box `}- </FormDescription>- <FormMessage />- </FormItem>- )}- />- </DialogBody>- <DialogFooter>- <Button- type="submit"- variant="destructive"- loading={transferProject.isPending}- className="w-full"- >- Transfer project- </Button>- </DialogFooter>- </form>- </Form>- </DialogContent>- </Dialog>- );-}diff --git a/web/src/features/projects/components/TransferProjectDialogContent.stories.tsx b/web/src/features/projects/components/TransferProjectDialogContent.stories.tsxnew file mode 100644index 0000000000..0db603b75a--- /dev/null+++ b/web/src/features/projects/components/TransferProjectDialogContent.stories.tsx@@ -0,0 +1,62 @@+import { type ComponentProps } from "react";+import { expect, fn, userEvent, within } from "storybook/test";++import preview from "../../../../.storybook/preview";+import { Dialog } from "@/src/components/ui/dialog";++import { TransferProjectDialogContent } from "./TransferProjectDialogContent";++const defaultArgs = {+ projectName: "Support assistant",+ organizationName: "Acme",+ organizations: [{ id: "organization-2", name: "Example" }],+ isPending: false,+ onConfirm: fn(),+} satisfies ComponentProps<typeof TransferProjectDialogContent>;++const meta = preview.meta({+ component: TransferProjectDialogContent,+ parameters: {+ layout: "fullscreen",+ },+ decorators: [+ (Story) => (+ <Dialog open onOpenChange={fn()}>+ <Story />+ </Dialog>+ ),+ ],+});++export default meta;++export const Default = meta.story({+ args: defaultArgs,+});++export const Loading = meta.story({+ args: {+ ...defaultArgs,+ isPending: true,+ },+});++export const ConfirmsTransfer = meta.story({+ name: "(Test) Confirms transfer",+ args: defaultArgs,+ play: async ({ args, canvasElement }) => {+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(body.getByRole("combobox"));+ await userEvent.keyboard("{ArrowDown}{Enter}");+ await userEvent.type(+ body.getByRole("textbox", { name: "Confirm" }),+ "acme/support-assistant",+ );+ await userEvent.click(+ body.getByRole("button", { name: "Transfer project" }),+ );++ await expect(args.onConfirm).toHaveBeenCalledWith("organization-2");+ },+});diff --git a/web/src/features/projects/components/TransferProjectDialogContent.tsx b/web/src/features/projects/components/TransferProjectDialogContent.tsxnew file mode 100644index 0000000000..a5ed0a6847--- /dev/null+++ b/web/src/features/projects/components/TransferProjectDialogContent.tsx@@ -0,0 +1,168 @@+import { zodResolver } from "@hookform/resolvers/zod";+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";+import { Button } from "@/src/components/ui/button";+import {+ DialogBody,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/src/components/ui/dialog";+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { TriangleAlert } from "lucide-react";+import { useForm } from "react-hook-form";+import * as z from "zod";++export type TransferProjectDialogOrganization = {+ id: string;+ name: string;+};++export interface TransferProjectDialogContentProps {+ projectName: string;+ organizationName: string;+ organizations: TransferProjectDialogOrganization[];+ isPending: boolean;+ onConfirm: (organizationId: string) => void;+}++export function TransferProjectDialogContent({+ projectName,+ organizationName,+ organizations,+ isPending,+ onConfirm,+}: TransferProjectDialogContentProps) {+ const confirmMessage = `${organizationName}/${projectName}`+ .replaceAll(" ", "-")+ .toLowerCase();+ const formSchema = z.object({+ name: z.string().includes(confirmMessage, {+ message: `Please confirm with "${confirmMessage}"`,+ }),+ organizationId: z.string(),+ });+ const form = useForm<z.infer<typeof formSchema>>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ name: "",+ organizationId: "",+ },+ });++ return (+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle>Transfer Project</DialogTitle>+ </DialogHeader>+ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(({ organizationId }) =>+ onConfirm(organizationId),+ )}+ className="flex flex-col gap-8"+ >+ <DialogBody>+ <Alert>+ <TriangleAlert className="h-4 w-4" />+ <AlertTitle>Warning</AlertTitle>+ <AlertDescription>+ Transferring the project will move it to a different+ organization:+ <ul className="list-disc pl-4">+ <li>+ Members who are not part of the new organization will lose+ access.+ </li>+ <li>+ The project remains fully operational as API keys, settings,+ and data will remain unchanged. All features (e.g. tracing,+ prompt management) will continue to work without+ interruption.+ </li>+ </ul>+ </AlertDescription>+ </Alert>+ <FormField+ control={form.control}+ name="organizationId"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Select New Organization</FormLabel>+ <FormControl>+ <Select+ onValueChange={field.onChange}+ value={field.value}+ disabled={isPending}+ >+ <SelectTrigger>+ <SelectValue placeholder="Select organization" />+ </SelectTrigger>+ <SelectContent>+ {organizations.map((organization) => (+ <SelectItem+ key={organization.id}+ value={organization.id}+ >+ {organization.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FormControl>+ <FormDescription>+ Transfer this project to another organization where you have+ the ability to create projects.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Confirm</FormLabel>+ <FormControl>+ <Input placeholder={confirmMessage} {...field} />+ </FormControl>+ <FormDescription>+ {`To confirm, type "${confirmMessage}" in the input box `}+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </DialogBody>+ <DialogFooter>+ <Button+ type="submit"+ variant="destructive"+ loading={isPending}+ className="w-full"+ >+ Transfer project+ </Button>+ </DialogFooter>+ </form>+ </Form>+ </DialogContent>+ );+}diff --git a/web/src/features/projects/components/TransferProjectDialogController.tsx b/web/src/features/projects/components/TransferProjectDialogController.tsxnew file mode 100644index 0000000000..965e1a848c--- /dev/null+++ b/web/src/features/projects/components/TransferProjectDialogController.tsx@@ -0,0 +1,98 @@+import { type ReactNode, useState } from "react";++import { Dialog } from "@/src/components/ui/dialog";+import { TransferProjectDialogContent } from "@/src/features/projects/components/TransferProjectDialogContent";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import {+ hasOrganizationAccess,+ useHasOrganizationAccess,+} from "@/src/features/rbac/utils/checkOrganizationAccess";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { api } from "@/src/utils/api";+import { useSession } from "next-auth/react";++type TransferProjectDialogControllerProps = {+ project: {+ id: string;+ name: string;+ };+ organization: {+ id: string;+ name: string;+ };+ children: (control: {+ disabled: { reason: string } | undefined;+ openDialog: () => void;+ }) => ReactNode;+};++export function TransferProjectDialogController({+ project,+ organization,+ children,+}: TransferProjectDialogControllerProps) {+ const [open, setOpen] = useState(false);+ const capture = usePostHogClientCapture();+ const session = useSession();+ const hasAccess = useHasOrganizationAccess({+ organizationId: organization.id,+ scope: "projects:transfer_org",+ });+ const organizationsToTransferTo = (session.data?.user?.organizations ?? [])+ .filter((org) =>+ hasOrganizationAccess({+ session: session.data,+ organizationId: org.id,+ scope: "projects:transfer_org",+ }),+ )+ .filter((org) => org.id !== organization.id);++ const transferProject = api.projects.transfer.useMutation({+ onSuccess: async () => {+ showSuccessToast({+ title: "Project transferred",+ description:+ "The project is successfully transferred to the new organization. Redirecting...",+ });+ await new Promise((resolve) => setTimeout(resolve, 5000));+ session.update();+ // Existing hard navigation is accepted during the Next.js 16.3 migration.+ // eslint-disable-next-line @next/next/no-location-assign-relative-destination+ window.location.href = "/";+ },+ });++ const disabled = hasAccess+ ? undefined+ : { reason: "You don't have permission to transfer this project." };++ const openDialog = () => {+ if (!hasAccess) return;++ setOpen(true);+ };++ const onConfirm = (organizationId: string) => {+ capture("project_settings:project_delete");+ transferProject.mutate({+ projectId: project.id,+ targetOrgId: organizationId,+ });+ };++ return (+ <>+ {children({ disabled, openDialog })}+ <Dialog open={hasAccess && open} onOpenChange={setOpen}>+ <TransferProjectDialogContent+ projectName={project.name}+ organizationName={organization.name}+ organizations={organizationsToTransferTo}+ isPending={transferProject.isPending}+ onConfirm={onConfirm}+ />+ </Dialog>+ </>+ );+}diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsxindex 6e11d95cb5..f211a7ce93 100644--- a/web/src/pages/project/[projectId]/settings/index.tsx+++ b/web/src/pages/project/[projectId]/settings/index.tsx@@ -14,7 +14,7 @@ import { JSONView } from "@/src/components/ui/CodeJsonViewer";import { PostHogLogo } from "@/src/components/PosthogLogo";import { MixpanelLogo } from "@/src/components/MixpanelLogo";import { Card } from "@/src/components/ui/card";-import { TransferProjectButton } from "@/src/features/projects/components/TransferProjectButton";+import { TransferProjectDialogController } from "@/src/features/projects/components/TransferProjectDialogController";import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { useRouter } from "next/router";@@ -120,7 +120,22 @@ export const getProjectSettingsPages = ({title: "Transfer ownership",description:"Transfer this project to another organization where you have the ability to create projects.",- button: <TransferProjectButton />,+ button: (+ <TransferProjectDialogController+ project={project}+ organization={organization}+ >+ {({ disabled, openDialog }) => (+ <Button+ variant="destructive-secondary"+ disabled={disabled !== undefined}+ onClick={openDialog}+ >+ Transfer Project+ </Button>+ )}+ </TransferProjectDialogController>+ ),},{title: "Delete this project",