Skip to content

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

feat(prompts): add duplicate folder action and tests (#12484)

Jasper Zhengc066fedcac04
diff --git a/web/src/__tests__/server/prompts-trpc.servertest.ts b/web/src/__tests__/server/prompts-trpc.servertest.ts
index d29ae0a2fe..07c6cae0f6 100644
--- a/web/src/__tests__/server/prompts-trpc.servertest.ts
+++ b/web/src/__tests__/server/prompts-trpc.servertest.ts
@@ -1387,4 +1387,205 @@ describe("prompts trpc", () => {
expect(folderSearchResults.prompts.length).toBeGreaterThan(0);
});
});
+
+ describe("prompts.duplicateFolder", () => {
+ it("should duplicate a folder when the target path exists as a prompt and keep intra-folder references self-contained", async () => {
+ const { project, caller } = await prepare();
+ const folderPrefix = `dup-self-contained-${v4().slice(0, 8)}`;
+ const folderAPath = `${folderPrefix}/folder-a`;
+ const folderACopyPath = `${folderPrefix}/folder-a-copy`;
+ const solverPromptName = `${folderAPath}/solver-a`;
+ const rubricPromptName = `${folderAPath}/rubric-a`;
+ const copiedSolverPromptName = `${folderACopyPath}/solver-a`;
+ const copiedRubricPromptName = `${folderACopyPath}/rubric-a`;
+
+ const solverPrompt = await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: solverPromptName,
+ version: 1,
+ type: "text",
+ prompt: `Solve using @@@langfusePrompt:name=${rubricPromptName}|label=production@@@`,
+ createdBy: "test-user",
+ labels: ["latest"],
+ },
+ });
+
+ await prisma.prompt.createMany({
+ data: [
+ {
+ id: v4(),
+ projectId: project.id,
+ name: folderAPath,
+ version: 1,
+ type: "text",
+ prompt: "prompt with same name as source folder",
+ createdBy: "test-user",
+ labels: ["latest"],
+ },
+ {
+ id: v4(),
+ projectId: project.id,
+ name: rubricPromptName,
+ version: 1,
+ type: "text",
+ prompt: "rubric latest-labeled content",
+ createdBy: "test-user",
+ labels: ["production", "latest"],
+ },
+ {
+ id: v4(),
+ projectId: project.id,
+ name: rubricPromptName,
+ version: 2,
+ type: "text",
+ prompt: "rubric higher-version content",
+ createdBy: "test-user",
+ labels: ["staging"],
+ },
+ {
+ id: v4(),
+ projectId: project.id,
+ name: folderACopyPath,
+ version: 1,
+ type: "text",
+ prompt: "prompt with same name as target folder",
+ createdBy: "test-user",
+ labels: ["latest"],
+ },
+ ],
+ });
+
+ await prisma.promptDependency.create({
+ data: {
+ projectId: project.id,
+ parentId: solverPrompt.id,
+ childName: rubricPromptName,
+ childLabel: "production",
+ },
+ });
+
+ const result = await caller.prompts.duplicateFolder({
+ projectId: project.id,
+ sourcePath: folderAPath,
+ targetPath: folderACopyPath,
+ isSingleVersion: true,
+ rewritePromptReferences: true,
+ });
+
+ expect(result.copiedCount).toBe(2);
+ expect(result.copiedPromptNames).toEqual(
+ expect.arrayContaining([
+ copiedSolverPromptName,
+ copiedRubricPromptName,
+ ]),
+ );
+
+ const copiedSolverPrompt = await prisma.prompt.findFirst({
+ where: {
+ projectId: project.id,
+ name: copiedSolverPromptName,
+ },
+ include: {
+ PromptDependency: true,
+ },
+ });
+ expect(copiedSolverPrompt).not.toBeNull();
+ expect(copiedSolverPrompt?.version).toBe(1);
+ expect(copiedSolverPrompt?.prompt).toBe(
+ `Solve using @@@langfusePrompt:name=${copiedRubricPromptName}|label=production@@@`,
+ );
+ expect(copiedSolverPrompt?.PromptDependency).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ childName: copiedRubricPromptName,
+ childLabel: "production",
+ childVersion: null,
+ }),
+ ]),
+ );
+
+ const copiedRubricPrompt = await prisma.prompt.findFirst({
+ where: {
+ projectId: project.id,
+ name: copiedRubricPromptName,
+ },
+ });
+ expect(copiedRubricPrompt).not.toBeNull();
+ expect(copiedRubricPrompt?.prompt).toBe("rubric latest-labeled content");
+
+ const exactTargetPrompt = await prisma.prompt.findMany({
+ where: {
+ projectId: project.id,
+ name: folderACopyPath,
+ },
+ });
+ expect(exactTargetPrompt).toHaveLength(1);
+ expect(exactTargetPrompt[0].prompt).toBe(
+ "prompt with same name as target folder",
+ );
+ });
+
+ it("should reject when the target path already exists as a folder with prompts", async () => {
+ const { project, caller } = await prepare();
+ const folderPrefix = `dup-folder-conflict-${v4().slice(0, 8)}`;
+ const folderAPath = `${folderPrefix}/folder-a`;
+ const folderACopyPath = `${folderPrefix}/folder-a-copy`;
+
+ await prisma.prompt.createMany({
+ data: [
+ {
+ id: v4(),
+ projectId: project.id,
+ name: folderAPath,
+ version: 1,
+ type: "text",
+ prompt: "prompt with same name as source folder",
+ createdBy: "test-user",
+ labels: ["latest"],
+ },
+ {
+ id: v4(),
+ projectId: project.id,
+ name: `${folderAPath}/solver-a`,
+ version: 1,
+ type: "text",
+ prompt: "solver content",
+ createdBy: "test-user",
+ labels: ["latest"],
+ },
+ {
+ id: v4(),
+ projectId: project.id,
+ name: `${folderAPath}/rubric-a`,
+ version: 1,
+ type: "text",
+ prompt: "rubric content",
+ createdBy: "test-user",
+ labels: ["latest"],
+ },
+ {
+ id: v4(),
+ projectId: project.id,
+ name: `${folderACopyPath}/existing`,
+ version: 1,
+ type: "text",
+ prompt: "existing target folder content",
+ createdBy: "test-user",
+ labels: ["latest"],
+ },
+ ],
+ });
+
+ await expect(
+ caller.prompts.duplicateFolder({
+ projectId: project.id,
+ sourcePath: folderAPath,
+ targetPath: folderACopyPath,
+ isSingleVersion: true,
+ }),
+ ).rejects.toThrow(/already exist/i);
+ });
+ });
});
diff --git a/web/src/features/prompts/components/duplicate-folder.tsx b/web/src/features/prompts/components/duplicate-folder.tsx
new file mode 100644
index 0000000000..a150037b60
--- /dev/null
+++ b/web/src/features/prompts/components/duplicate-folder.tsx
@@ -0,0 +1,257 @@
+import { Button } from "@/src/components/ui/button";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { api } from "@/src/utils/api";
+import { useState } from "react";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import { Input } from "@/src/components/ui/input";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { RadioGroup, RadioGroupItem } from "@/src/components/ui/radio-group";
+import { Checkbox } from "@/src/components/ui/checkbox";
+import { useForm } from "react-hook-form";
+import { z } from "zod/v4";
+import { zodResolver } from "@hookform/resolvers/zod";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { Copy } from "lucide-react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useEntitlementLimit } from "@/src/features/entitlements/hooks";
+
+enum CopySettings {
+ LATEST_ONLY = "latest_only",
+ ALL_VERSIONS = "all_versions",
+}
+
+const formSchema = z.object({
+ targetPath: z.string().min(1, "Target folder path is required"),
+ copySettings: z.enum(CopySettings),
+ rewritePromptReferences: z.boolean(),
+});
+
+export function DuplicateFolder({ folderPath }: { folderPath: string }) {
+ const projectId = useProjectIdFromURL();
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const hasAccess = useHasProjectAccess({ projectId, scope: "prompts:CUD" });
+ const promptLimit = useEntitlementLimit("prompt-management-count-prompts");
+ const capture = usePostHogClientCapture();
+
+ const form = useForm({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ targetPath: `${folderPath}-copy`,
+ copySettings: CopySettings.LATEST_ONLY,
+ rewritePromptReferences: false,
+ },
+ });
+
+ const mutDuplicateFolder = api.prompts.duplicateFolder.useMutation({
+ onSuccess: () => {
+ void utils.prompts.invalidate();
+ setError(null);
+ setIsOpen(false);
+ form.reset();
+ },
+ onError: (err) => {
+ setError(err.message);
+ },
+ });
+
+ const allPromptNames = api.prompts.allNames.useQuery(
+ { projectId: projectId as string },
+ {
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ enabled: hasAccess && isOpen,
+ },
+ );
+
+ function onSubmit(values: z.infer<typeof formSchema>) {
+ if (!projectId) return;
+ capture("prompt_detail:duplicate_form_submit");
+ setError(null);
+ mutDuplicateFolder.mutate({
+ projectId,
+ sourcePath: folderPath,
+ targetPath: values.targetPath,
+ isSingleVersion: values.copySettings === CopySettings.LATEST_ONLY,
+ rewritePromptReferences: values.rewritePromptReferences,
+ });
+ }
+
+ return (
+ <Dialog
+ open={hasAccess && isOpen}
+ onOpenChange={(open) => {
+ setIsOpen(open);
+ if (!open) {
+ form.reset();
+ setError(null);
+ }
+ }}
+ >
+ <DialogTrigger asChild>
+ <Button
+ variant="ghost"
+ size="xs"
+ disabled={!hasAccess}
+ title="Duplicate folder including prompts"
+ onClick={() => capture("prompt_detail:duplicate_button_click")}
+ >
+ <Copy className="h-4 w-4" />
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="max-h-[90vh] min-h-0 sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle className="break-all">
+ Duplicate Folder &quot;
+ <i className="font-normal">
+ {folderPath.split("/").pop() ?? folderPath}
+ </i>
+ &quot;
+ </DialogTitle>
+ </DialogHeader>
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="flex h-full flex-1 flex-col gap-4"
+ >
+ <DialogBody>
+ <p className="text-muted-foreground text-sm">
+ Copy all prompts from{" "}
+ <code className="bg-muted relative rounded px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold break-all">
+ {folderPath}/
+ </code>{" "}
+ to a new folder path.
+ </p>
+ <FormField
+ control={form.control}
+ name="targetPath"
+ render={({ field }) => (
+ <FormItem className="flex flex-col gap-2">
+ <FormLabel>Target folder path</FormLabel>
+ <FormControl>
+ <Input {...field} type="text" />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="copySettings"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Version settings</FormLabel>
+ <FormControl>
+ <RadioGroup
+ {...field}
+ onValueChange={field.onChange}
+ defaultValue={field.value}
+ className="flex flex-col space-y-1"
+ >
+ <FormItem className="flex items-center space-y-0 space-x-3">
+ <FormControl>
+ <RadioGroupItem value={CopySettings.LATEST_ONLY} />
+ </FormControl>
+ <FormLabel className="font-normal">
+ Copy only the latest version of each prompt
+ </FormLabel>
+ </FormItem>
+ <FormItem className="flex items-center space-y-0 space-x-3">
+ <FormControl>
+ <RadioGroupItem value={CopySettings.ALL_VERSIONS} />
+ </FormControl>
+ <FormLabel className="font-normal">
+ Copy all versions and labels
+ </FormLabel>
+ </FormItem>
+ </RadioGroup>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="rewritePromptReferences"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-start space-y-0 space-x-3 rounded-md border p-3">
+ <FormControl>
+ <Checkbox
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ <div className="space-y-1 leading-none">
+ <FormLabel>
+ Rewrite prompt references in this folder
+ </FormLabel>
+ <FormDescription>
+ Update references like{" "}
+ <code className="bg-muted rounded px-1 py-0.5 font-mono text-xs">
+ {folderPath}/...
+ </code>{" "}
+ to point at{" "}
+ <code className="bg-muted rounded px-1 py-0.5 font-mono text-xs">
+ {form.watch("targetPath") || `${folderPath}-copy`}/...
+ </code>{" "}
+ when the referenced prompt is also copied.
+ </FormDescription>
+ </div>
+ </FormItem>
+ )}
+ />
+ {form.watch("copySettings") === CopySettings.LATEST_ONLY &&
+ form.watch("rewritePromptReferences") && (
+ <p className="text-muted-foreground text-sm">
+ When copying latest only, labels referenced within the
+ folder may be added to copied prompts so rewritten
+ references continue to work.
+ </p>
+ )}
+ {error && (
+ <div className="rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
+ <p className="font-medium">Error:</p>
+ <p className="whitespace-pre-wrap">{error}</p>
+ </div>
+ )}
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ type="submit"
+ loading={mutDuplicateFolder.isPending}
+ disabled={
+ !!(
+ promptLimit &&
+ allPromptNames.data &&
+ allPromptNames.data.length >= promptLimit
+ )
+ }
+ className="mt-auto w-full"
+ >
+ Duplicate
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsx
index 29cf4a2abd..7add804bd7 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -10,6 +10,7 @@ import { type LangfuseColumnDef } from "@/src/components/table/types";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
import { DeletePrompt } from "@/src/features/prompts/components/delete-prompt";
import { DeleteFolder } from "@/src/features/prompts/components/delete-folder";
+import { DuplicateFolder } from "@/src/features/prompts/components/duplicate-folder";
import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
import { api } from "@/src/utils/api";
import { type RouterOutput } from "@/src/utils/types";
@@ -363,7 +364,12 @@ export function PromptTable() {
cell: (row) => {
const rowData = row.row.original;
if (rowData.type === "folder") {
- return <DeleteFolder folderPath={rowData.fullPath} />;
+ return (
+ <div className="flex gap-1">
+ <DuplicateFolder folderPath={rowData.fullPath} />
+ <DeleteFolder folderPath={rowData.fullPath} />
+ </div>
+ );
}
const promptPath = rowData.fullPath;
diff --git a/web/src/features/prompts/server/actions/createPrompt.ts b/web/src/features/prompts/server/actions/createPrompt.ts
index b2517ad0ec..9b5401a544 100644
--- a/web/src/features/prompts/server/actions/createPrompt.ts
+++ b/web/src/features/prompts/server/actions/createPrompt.ts
@@ -16,6 +16,7 @@ import { updatePromptTagsOnAllVersions } from "@/src/features/prompts/server/uti
import {
PromptContentSchema,
PromptService,
+ escapeSqlLikePattern,
redis,
extractPlaceholderNames,
} from "@langfuse/shared/src/server";
@@ -37,6 +38,17 @@ type DuplicatePromptParams = {
user?: { id: string; name: string | null; email: string | null };
};
+type DuplicateFolderParams = {
+ projectId: string;
+ sourcePath: string;
+ targetPath: string;
+ isSingleVersion: boolean;
+ rewritePromptReferences?: boolean;
+ createdBy: string;
+ prisma: PrismaClient;
+ user?: { id: string; name: string | null; email: string | null };
+};
+
const extractChatVariableAndPlaceholderNames = (
chatPrompt: Array<any>,
): { variables: string[]; placeholders: string[] } => {
@@ -346,3 +358,209 @@ export const duplicatePrompt = async ({
return createdPrompt;
};
+
+const rewriteDuplicatedPromptContent = ({
+ prompt,
+ duplicatedPromptNames,
+ isSingleVersion,
+}: {
+ prompt: ReturnType<typeof PromptContentSchema.parse>;
+ duplicatedPromptNames: Map<string, string>;
+ isSingleVersion: boolean;
+}) => {
+ let rewrittenPrompt = JSON.stringify(prompt);
+
+ for (const dep of parsePromptDependencyTags(prompt)) {
+ const duplicatedDependencyName = duplicatedPromptNames.get(dep.name);
+
+ if (!duplicatedDependencyName) continue;
+
+ const currentTag =
+ dep.type === "version"
+ ? `@@@langfusePrompt:name=${dep.name}|version=${dep.version}@@@`
+ : `@@@langfusePrompt:name=${dep.name}|label=${dep.label}@@@`;
+
+ const rewrittenTag =
+ dep.type === "version"
+ ? `@@@langfusePrompt:name=${duplicatedDependencyName}|version=${isSingleVersion ? 1 : dep.version}@@@`
+ : `@@@langfusePrompt:name=${duplicatedDependencyName}|label=${dep.label}@@@`;
+
+ rewrittenPrompt = rewrittenPrompt.split(currentTag).join(rewrittenTag);
+ }
+
+ return PromptContentSchema.parse(JSON.parse(rewrittenPrompt));
+};
+
+export const duplicateFolder = async ({
+ projectId,
+ sourcePath,
+ targetPath,
+ isSingleVersion,
+ rewritePromptReferences = false,
+ createdBy,
+ prisma,
+ user,
+}: DuplicateFolderParams) => {
+ const escapedTargetPath = escapeSqlLikePattern(targetPath);
+ const escapedSourcePath = escapeSqlLikePattern(sourcePath);
+
+ const existingTargetPrompt = await prisma.prompt.findFirst({
+ where: {
+ projectId,
+ name: { startsWith: `${escapedTargetPath}/` },
+ },
+ });
+
+ if (existingTargetPrompt) {
+ throw new InvalidRequestError(
+ `Prompts already exist under the target path "${targetPath}/". Please choose a different target path.`,
+ );
+ }
+
+ // Find all prompts under the source folder, including nested subfolders
+ const sourcePrompts = await prisma.prompt.findMany({
+ where: {
+ projectId,
+ name: { startsWith: `${escapedSourcePath}/` },
+ },
+ include: {
+ PromptDependency: {
+ select: {
+ childName: true,
+ childLabel: true,
+ childVersion: true,
+ },
+ },
+ },
+ orderBy: [{ name: "asc" }, { version: "asc" }],
+ });
+
+ if (sourcePrompts.length === 0) {
+ throw new InvalidRequestError(
+ `No prompts found under the source path "${sourcePath}/".`,
+ );
+ }
+
+ // Group by name: each unique prompt name may have multiple versions
+ const promptsByName = new Map<string, (typeof sourcePrompts)[number][]>();
+ for (const prompt of sourcePrompts) {
+ const existing = promptsByName.get(prompt.name) ?? [];
+ existing.push(prompt);
+ promptsByName.set(prompt.name, existing);
+ }
+
+ const oldToNewIdMap: Record<string, string> = {};
+ const duplicatedPromptNames = new Map(
+ [...promptsByName.keys()].map((originalName) => [
+ originalName,
+ `${targetPath}${originalName.slice(sourcePath.length)}`,
+ ]),
+ );
+ const allPromptsToCreate: Array<{
+ id: string;
+ name: string;
+ version: number;
+ labels: string[];
+ type: string;
+ prompt: ReturnType<typeof PromptContentSchema.parse>;
+ config: ReturnType<typeof jsonSchema.parse>;
+ tags: string[];
+ projectId: string;
+ createdBy: string;
+ commitMessage: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+ isActive: boolean;
+ }> = [];
+
+ for (const [originalName, versions] of promptsByName) {
+ const latestVersion =
+ versions.find((version) =>
+ version.labels.includes(LATEST_PROMPT_LABEL),
+ ) ?? versions.reduce((a, b) => (a.version > b.version ? a : b));
+
+ const newName =
+ duplicatedPromptNames.get(originalName) ??
+ `${targetPath}${originalName.slice(sourcePath.length)}`;
+
+ const promptsToCopy = isSingleVersion ? [latestVersion] : versions;
+
+ for (const prompt of promptsToCopy) {
+ const newPromptId = uuidv4();
+ oldToNewIdMap[prompt.id] = newPromptId;
+
+ allPromptsToCreate.push({
+ id: newPromptId,
+ name: newName,
+ version: isSingleVersion ? 1 : prompt.version,
+ labels: isSingleVersion
+ ? [...new Set([LATEST_PROMPT_LABEL, ...prompt.labels])]
+ : prompt.labels,
+ type: prompt.type,
+ prompt: rewritePromptReferences
+ ? rewriteDuplicatedPromptContent({
+ prompt: PromptContentSchema.parse(prompt.prompt),
+ duplicatedPromptNames,
+ isSingleVersion,
+ })
+ : PromptContentSchema.parse(prompt.prompt),
+ config: jsonSchema.parse(prompt.config),
+ tags: prompt.tags,
+ projectId,
+ createdBy,
+ commitMessage: prompt.commitMessage,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ isActive: true,
+ });
+ }
+ }
+
+ await prisma.$transaction(async (tx) => {
+ await tx.prompt.createMany({
+ data: allPromptsToCreate,
+ });
+
+ await tx.promptDependency.createMany({
+ data: sourcePrompts
+ .filter((prompt) => oldToNewIdMap[prompt.id] !== undefined)
+ .flatMap((prompt) =>
+ prompt.PromptDependency.map((dep) => {
+ const duplicatedDependencyName = rewritePromptReferences
+ ? duplicatedPromptNames.get(dep.childName)
+ : undefined;
+
+ return {
+ projectId,
+ parentId: oldToNewIdMap[prompt.id],
+ childName: duplicatedDependencyName ?? dep.childName,
+ childVersion:
+ duplicatedDependencyName && dep.childVersion && isSingleVersion
+ ? 1
+ : dep.childVersion,
+ childLabel: dep.childLabel,
+ };
+ }),
+ ),
+ });
+ });
+
+ const promptService = new PromptService(prisma, redis);
+
+ await promptService.invalidateCache({ projectId });
+
+ await Promise.all(
+ allPromptsToCreate.map(async (prompt) =>
+ promptChangeEventSourcing(
+ await promptService.resolvePrompt(prompt),
+ "created",
+ user,
+ ),
+ ),
+ );
+
+ return {
+ copiedPromptNames: [...duplicatedPromptNames.values()],
+ copiedCount: allPromptsToCreate.length,
+ };
+};
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index 5e2fadc30d..47e6aa3a47 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -8,7 +8,11 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { type Prompt, Prisma } from "@langfuse/shared/src/db";
-import { createPrompt, duplicatePrompt } from "../actions/createPrompt";
+import {
+ createPrompt,
+ duplicatePrompt,
+ duplicateFolder,
+} from "../actions/createPrompt";
import { checkHasProtectedLabels } from "../utils/checkHasProtectedLabels";
import {
CreatePromptTRPCSchema,
@@ -373,6 +377,56 @@ export const promptRouter = createTRPCRouter({
return prompt;
}),
+ duplicateFolder: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ sourcePath: StringNoHTMLNonEmpty,
+ targetPath: StringNoHTMLNonEmpty,
+ isSingleVersion: z.boolean(),
+ rewritePromptReferences: z.boolean().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "prompts:CUD",
+ });
+
+ // TODO: Decide product behavior for protected labels on duplication.
+ // We currently preserve labels here to match duplicatePrompt, which also
+ // duplicates protected labels without a separate promptProtectedLabels:CUD
+ // check. If duplicates should be treated as factually new prompts, strip
+ // protected labels in both duplication flows instead of diverging here.
+ const result = await duplicateFolder({
+ projectId: input.projectId,
+ sourcePath: input.sourcePath,
+ targetPath: input.targetPath,
+ isSingleVersion: input.isSingleVersion,
+ rewritePromptReferences: input.rewritePromptReferences,
+ createdBy: ctx.session.user.id,
+ prisma: ctx.prisma,
+ user: {
+ id: ctx.session.user.id,
+ name: ctx.session.user.name ?? null,
+ email: ctx.session.user.email ?? null,
+ },
+ });
+
+ await auditLog(
+ {
+ session: ctx.session,
+ resourceType: "prompt",
+ resourceId: input.targetPath,
+ action: "create",
+ after: result,
+ },
+ ctx.prisma,
+ );
+
+ return result;
+ }),
filterOptions: protectedProjectProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {