🪢 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
fix(prompts): subfolders hiding prompts (#8876)
Nimar5c8e4d641a6c
diff --git a/web/src/__tests__/async/prompts-trpc.servertest.ts b/web/src/__tests__/async/prompts-trpc.servertest.tsindex 45fd1b5bac..d5b79de29e 100644--- a/web/src/__tests__/async/prompts-trpc.servertest.ts+++ b/web/src/__tests__/async/prompts-trpc.servertest.ts@@ -1013,4 +1013,190 @@ describe("prompts trpc", () => {expect(folderCountResult.totalCount).toBe(BigInt(2));});});++ describe("folder navigation with conflicting names", () => {+ it("should handle prompts where individual prompt name conflicts with folder prefix - BUG REPRODUCTION", async () => {+ const { project, caller } = await prepare();++ // Create the exact bug scenario:+ // - a/prompt (individual prompt)+ // - a/prompt/v1 (prompt in subfolder)+ // - a/prompt/v2 (prompt in subfolder)+ // Bug: LFE-6515+ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "a/prompt",+ version: 1,+ type: "text",+ prompt: { text: "This is the individual a/prompt" },+ createdBy: "test-user",+ tags: ["individual"],+ },+ });++ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "a/prompt/v1",+ version: 1,+ type: "text",+ prompt: { text: "This is a/prompt/v1" },+ createdBy: "test-user",+ tags: ["subfolder"],+ },+ });++ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "a/prompt/v2",+ version: 1,+ type: "text",+ prompt: { text: "This is a/prompt/v2" },+ createdBy: "test-user",+ tags: ["subfolder"],+ },+ });++ // Test 1: Root level should show folder "a"+ const rootResults = await caller.prompts.all({+ projectId: project.id,+ page: 0,+ limit: 10,+ filter: [],+ orderBy: { column: "createdAt", order: "DESC" },+ });++ // Should show exactly one item: the "a" folder+ expect(rootResults.prompts).toHaveLength(1);+ expect(rootResults.prompts[0].name).toBe("a");++ // Test 2: Folder "a" level should show BOTH individual "prompt" AND folder entry for "prompt/*"+ const folderAResults = await caller.prompts.all({+ projectId: project.id,+ page: 0,+ limit: 10,+ filter: [],+ orderBy: { column: "createdAt", order: "DESC" },+ pathPrefix: "a",+ });++ // We expect 2 items: individual "prompt" and folder "prompt" (for v1, v2)+ expect(folderAResults.prompts).toHaveLength(2);++ // Should have both an individual prompt and a folder entry+ const promptNames = folderAResults.prompts.map((p) => p.name);+ expect(promptNames).toContain("prompt");++ // Test 3: Folder "a/prompt" level should show v1 and v2+ const subfolderResults = await caller.prompts.all({+ projectId: project.id,+ page: 0,+ limit: 10,+ filter: [],+ orderBy: { column: "createdAt", order: "DESC" },+ pathPrefix: "a/prompt",+ });++ // Should show exactly 2 items: v1 and v2+ expect(subfolderResults.prompts).toHaveLength(2);+ const subfolderNames = subfolderResults.prompts.map((p) => p.name);+ expect(subfolderNames).toContain("v1");+ expect(subfolderNames).toContain("v2");++ // Test 4: Count verification+ const rootCount = await caller.prompts.count({+ projectId: project.id,+ });+ expect(rootCount.totalCount).toBe(BigInt(1)); // Should show 1 folder++ const folderACount = await caller.prompts.count({+ projectId: project.id,+ pathPrefix: "a",+ });+ expect(folderACount.totalCount).toBe(BigInt(2)); // Should show individual + folder entry++ const subfolderCount = await caller.prompts.count({+ projectId: project.id,+ pathPrefix: "a/prompt",+ });+ expect(subfolderCount.totalCount).toBe(BigInt(2)); // Should show v1 and v2+ });++ it("should maintain search functionality across conflicting folder/prompt names", async () => {+ const { project, caller } = await prepare();++ // Create searchable content in conflicting structure+ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "search/test",+ version: 1,+ type: "text",+ prompt: { text: "Individual search test with unique keyword" },+ createdBy: "test-user",+ tags: ["searchable"],+ },+ });++ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "search/test/nested1",+ version: 1,+ type: "text",+ prompt: { text: "Nested prompt with unique keyword" },+ createdBy: "test-user",+ tags: ["nested"],+ },+ });++ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "search/test/nested2",+ version: 1,+ type: "text",+ prompt: { text: "Another nested prompt" },+ createdBy: "test-user",+ tags: ["nested"],+ },+ });++ // Test search at different folder levels+ const searchResults = await caller.prompts.all({+ projectId: project.id,+ page: 0,+ limit: 10,+ filter: [],+ orderBy: { column: "createdAt", order: "DESC" },+ searchQuery: "unique",+ searchType: ["content"],+ });++ // Should find prompts containing "unique" keyword+ expect(searchResults.prompts.length).toBeGreaterThan(0);++ // Test search within specific folder+ const folderSearchResults = await caller.prompts.all({+ projectId: project.id,+ page: 0,+ limit: 10,+ filter: [],+ orderBy: { column: "createdAt", order: "DESC" },+ pathPrefix: "search/test",+ searchQuery: "nested",+ searchType: ["content"],+ });+ // Should find nested prompts within the folder+ expect(folderSearchResults.prompts.length).toBeGreaterThan(0);+ });+ });});diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsxindex fc1b874cdc..178b2c6dc8 100644--- a/web/src/features/prompts/components/prompts-table.tsx+++ b/web/src/features/prompts/components/prompts-table.tsx@@ -37,6 +37,7 @@ import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextStype PromptTableRow = {id: string;name: string;+ fullPath: string; // used for navigation/API callstype: "folder" | "text" | "chat";version?: number;createdAt?: Date;@@ -49,6 +50,7 @@ function createRow(data: Partial<PromptTableRow> & {id: string;name: string;+ fullPath: string;type: "folder" | "text" | "chat";},): PromptTableRow {@@ -62,12 +64,6 @@ function createRow(};}-function isFolder(- row: PromptTableRow,-): row is PromptTableRow & { type: "folder" } {- return row.type === "folder";-}-function createBreadcrumbItems(currentFolderPath: string) {if (!currentFolderPath) return [];@@ -173,56 +169,38 @@ export function PromptTable() {})),);- // Backend returns folder representatives, so we just need to detect them+ const buildFullPath = (currentFolder: string, itemName: string) =>+ currentFolder ? `${currentFolder}/${itemName}` : itemName;++ // Backend returns folder representatives with row_type metadataconst processedRowData = useMemo(() => {if (!promptsRowData.rows) return { ...promptsRowData, rows: [] };const combinedRows: PromptTableRow[] = [];for (const prompt of promptsRowData.rows) {- const promptName = prompt.id;-- // Check if this prompt represents a folder- const isFolderRepresentative = currentFolderPath- ? promptName.includes("/") &&- promptName.startsWith(`${currentFolderPath}/`) &&- promptName.substring(currentFolderPath.length + 1).includes("/")- : promptName.includes("/");-- if (isFolderRepresentative) {- // Convert folder representative to folder item- const folderPath = currentFolderPath- ? `${currentFolderPath}/${promptName.substring(currentFolderPath.length + 1).split("/")[0]}`- : promptName.split("/")[0];-- const folderName = currentFolderPath- ? folderPath.substring(currentFolderPath.length + 1)- : folderPath;-- combinedRows.push(- createRow({- id: folderPath,- name: folderName,- type: "folder",- }),- );- } else {- // Regular prompt- combinedRows.push(- createRow({- id: prompt.id,- name: currentFolderPath- ? prompt.id.substring(currentFolderPath.length + 1)- : prompt.id,- type: prompt.type as "text" | "chat",- version: prompt.version,- createdAt: prompt.createdAt,- labels: prompt.labels,- tags: prompt.tags,- numberOfObservations: Number(prompt.observationCount ?? 0),- }),- );- }+ const isFolder = (prompt as { row_type?: string }).row_type === "folder";+ const itemName = prompt.id; // id actually contains the name due to type mapping+ const fullPath = buildFullPath(currentFolderPath, itemName);+ const type = isFolder ? "folder" : (prompt.type as "text" | "chat");++ combinedRows.push(+ createRow({+ id: `${type}-${fullPath}`, // Unique ID for React keys+ name: itemName,+ fullPath,+ type,+ ...(isFolder+ ? {}+ : {+ version: prompt.version,+ createdAt: prompt.createdAt,+ labels: prompt.labels,+ tags: prompt.tags,+ numberOfObservations: Number(prompt.observationCount ?? 0),+ }),+ }),+ );}return {@@ -272,7 +250,7 @@ export function PromptTable() {const name = row.getValue();const rowData = row.row.original;- if (isFolder(rowData)) {+ if (rowData.type === "folder") {return (<TableLinkpath={""}@@ -286,7 +264,7 @@ export function PromptTable() {}onClick={() => {setQueryParams({- folder: rowData.id, // rowData.id contains the full folder path+ folder: rowData.fullPath,pageIndex: 0,pageSize: queryParams.pageSize,});@@ -298,9 +276,9 @@ export function PromptTable() {return name ? (<TableLink- path={`/project/${projectId}/prompts/${encodeURIComponent(rowData.id)}`}+ path={`/project/${projectId}/prompts/${encodeURIComponent(rowData.fullPath)}`}value={name}- title={rowData.id} // Show full prompt path on hover+ title={rowData.fullPath} // Show full prompt path on hover/>) : undefined;},@@ -311,7 +289,7 @@ export function PromptTable() {enableSorting: true,size: 70,cell: (row) => {- if (isFolder(row.row.original)) return null;+ if (row.row.original.type === "folder") return null;return row.getValue();},}),@@ -330,7 +308,7 @@ export function PromptTable() {enableSorting: true,size: 200,cell: (row) => {- if (isFolder(row.row.original)) return null;+ if (row.row.original.type === "folder") return null;const createdAt = row.getValue();return createdAt ? <LocalIsoDate date={createdAt} /> : null;},@@ -339,12 +317,12 @@ export function PromptTable() {header: "Number of Observations",size: 170,cell: (row) => {- if (isFolder(row.row.original)) return null;+ if (row.row.original.type === "folder") return null;const numberOfObservations = row.getValue();- const promptId = row.row.original.id;+ const promptPath = row.row.original.fullPath;const filter = encodeURIComponent(- `promptName;stringOptions;;any of;${promptId}`,+ `promptName;stringOptions;;any of;${promptPath}`,);if (!promptMetrics.isSuccess) {return <Skeleton className="h-3 w-1/2" />;@@ -364,16 +342,16 @@ export function PromptTable() {size: 120,cell: (row) => {// height h-6 to ensure consistent row height for normal & folder rows- if (isFolder(row.row.original)) return <div className="h-6" />;+ if (row.row.original.type === "folder") return <div className="h-6" />;const tags = row.getValue();- const promptId = row.row.original.id;+ const promptPath = row.row.original.fullPath;return (<TagPromptPopovertags={tags ?? []}availableTags={allTags}projectId={projectId as string}- promptName={promptId}+ promptName={promptPath}promptsFilter={{page: 0,limit: 50,@@ -391,10 +369,10 @@ export function PromptTable() {header: "Actions",size: 70,cell: (row) => {- if (isFolder(row.row.original)) return null;+ if (row.row.original.type === "folder") return null;- const promptId = row.row.original.id;- return <DeletePrompt promptName={promptId} />;+ const promptPath = row.row.original.fullPath;+ return <DeletePrompt promptName={promptPath} />;},}),] as LangfuseColumnDef<PromptTableRow>[];@@ -490,6 +468,7 @@ export function PromptTable() {data: processedRowData.rows?.map((item) => ({id: item.id,name: item.name,+ fullPath: item.fullPath,version: item.version,createdAt: item.createdAt,type: item.type,diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.tsindex 3b533eccd8..d2f06bf358 100644--- a/web/src/features/prompts/server/routers/promptRouter.ts+++ b/web/src/features/prompts/server/routers/promptRouter.ts@@ -134,7 +134,7 @@ export const promptRouter = createTRPCRouter({const [prompts, promptCount] = await Promise.all([// prompts- ctx.prisma.$queryRaw<Array<Prompt>>(+ ctx.prisma.$queryRaw<Array<Prompt & { row_type: "folder" | "prompt" }>>(generatePromptQuery(Prisma.sql`p.id,@@ -146,7 +146,8 @@ export const promptRouter = createTRPCRouter({p.updated_at as "updatedAt",p.created_at as "createdAt",p.labels,- p.tags`,+ p.tags,+ p.row_type`,input.projectId,filterCondition,orderByCondition,@@ -160,7 +161,7 @@ export const promptRouter = createTRPCRouter({// promptCountctx.prisma.$queryRaw<Array<{ totalCount: bigint }>>(generatePromptQuery(- Prisma.sql` count(*) AS "totalCount"`,+ Prisma.sql`count(*) AS "totalCount"`,input.projectId,filterCondition,Prisma.empty,@@ -1397,24 +1398,64 @@ const generatePromptQuery = (if (prefix) {// When we're inside a folder, show individual prompts within that folder// and folder representatives for subfolders- const segmentExpr = Prisma.sql`SPLIT_PART(SUBSTRING(p.name, CHAR_LENGTH(${prefix}) + 2), '/', 1)`;return Prisma.sql`WITH ${latestCTE},- grouped AS (+ individual_prompts_in_folder AS (+ /* Individual prompts exactly at this folder level (no deeper slashes) */SELECT- p.*, /* keep all columns */- ROW_NUMBER() OVER (PARTITION BY ${segmentExpr} ORDER BY p.version DESC) AS rn,- CASE- WHEN SUBSTRING(p.name, CHAR_LENGTH(${prefix}) + 2) LIKE '%/%' THEN 1- ELSE 2- END as sort_priority -- Folders first (1), individual prompts second (2)+ p.id,+ SUBSTRING(p.name, CHAR_LENGTH(${prefix}) + 2) as name, -- Remove prefix, show relative name+ p.version,+ p.project_id,+ p.prompt,+ p.type,+ p.updated_at,+ p.created_at,+ p.labels,+ p.tags,+ p.config,+ p.created_by,+ 2 as sort_priority, -- Individual prompts second+ 'prompt'::text as row_type -- Mark as individual promptFROM latest p+ WHERE SUBSTRING(p.name, CHAR_LENGTH(${prefix}) + 2) NOT LIKE '%/%'+ AND SUBSTRING(p.name, CHAR_LENGTH(${prefix}) + 2) != '' -- Exclude prompts that match prefix exactly+ AND p.name != ${prefix} -- Additional safety check+ ),+ subfolder_representatives AS (+ /* Folder representatives for deeper nested prompts */+ SELECT+ p.id,+ SPLIT_PART(SUBSTRING(p.name, CHAR_LENGTH(${prefix}) + 2), '/', 1) as name, -- First segment after prefix+ p.version,+ p.project_id,+ p.prompt,+ p.type,+ p.updated_at,+ p.created_at,+ p.labels,+ p.tags,+ p.config,+ p.created_by,+ 1 as sort_priority, -- Folders first+ 'folder'::text as row_type, -- Mark as folder representative+ ROW_NUMBER() OVER (PARTITION BY SPLIT_PART(SUBSTRING(p.name, CHAR_LENGTH(${prefix}) + 2), '/', 1) ORDER BY p.version DESC) AS rn+ FROM latest p+ WHERE SUBSTRING(p.name, CHAR_LENGTH(${prefix}) + 2) LIKE '%/%'+ ),+ combined AS (+ SELECT+ id, name, version, project_id, prompt, type, updated_at, created_at, labels, tags, config, created_by, sort_priority, row_type+ FROM individual_prompts_in_folder+ UNION ALL+ SELECT+ id, name, version, project_id, prompt, type, updated_at, created_at, labels, tags, config, created_by, sort_priority, row_type+ FROM subfolder_representatives WHERE rn = 1)SELECT${select}- FROM grouped p- WHERE rn = 1+ FROM combined p${orderAndLimit};`;} else {@@ -1426,22 +1467,35 @@ const generatePromptQuery = (WITH ${latestCTE},individual_prompts AS (/* Individual prompts without folders */- SELECT p.*+ SELECT p.*, 'prompt'::text as row_typeFROM latest pWHERE p.name NOT LIKE '%/%'),folder_representatives AS (- /* One representative per folder */- SELECT p.*,+ /* One representative per folder - return folder name, not full prompt name */+ SELECT+ p.id,+ SPLIT_PART(p.name, '/', 1) as name, -- Return folder segment name instead of full name+ p.version,+ p.project_id,+ p.prompt,+ p.type,+ p.updated_at,+ p.created_at,+ p.labels,+ p.tags,+ p.config,+ p.created_by,+ 'folder'::text as row_type, -- Mark as folder representativeROW_NUMBER() OVER (PARTITION BY SPLIT_PART(p.name, '/', 1) ORDER BY p.version DESC) AS rnFROM latest pWHERE p.name LIKE '%/%'),combined AS (- SELECT ${baseColumns}, 1 as sort_priority -- Folders first+ SELECT ${baseColumns}, row_type, 1 as sort_priority -- Folders firstFROM folder_representatives WHERE rn = 1UNION ALL- SELECT ${baseColumns}, 2 as sort_priority -- Individual prompts second+ SELECT ${baseColumns}, row_type, 2 as sort_priority -- Individual prompts secondFROM individual_prompts)SELECT