Skip to content

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

fix(prompts): prompt folder pagination fix (#7776)

Nimarbacd44abb176
diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsx
index d8c24a3e26..ada407f345 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -68,12 +68,6 @@ function isFolder(
return row.type === "folder";
}
-function getDisplayName(fullPath: string, currentFolderPath: string): string {
- return currentFolderPath === ""
- ? fullPath
- : fullPath.substring(currentFolderPath.length + 1);
-}
-
function createBreadcrumbItems(currentFolderPath: string) {
if (!currentFolderPath) return [];
@@ -180,76 +174,58 @@ export function PromptTable() {
})),
);
- // Filter and group prompts based on current folder path
+ // Backend returns folder representatives, so we just need to detect them
const processedRowData = useMemo(() => {
if (!promptsRowData.rows) return { ...promptsRowData, rows: [] };
- const uniqueFolders = new Set<string>();
- const matchingPrompts: typeof promptsRowData.rows = [];
+ const combinedRows: PromptTableRow[] = [];
- // Identify immediate subfolders from backend-filtered prompts
for (const prompt of promptsRowData.rows) {
const promptName = prompt.id;
- if (currentFolderPath) {
- const prefix = `${currentFolderPath}/`;
- if (promptName.startsWith(prefix)) {
- const remainingPath = promptName.substring(prefix.length);
- const slashIndex = remainingPath.indexOf("/");
-
- if (slashIndex > 0) {
- // Subfolder
- const subFolderName = remainingPath.substring(0, slashIndex);
- const fullSubFolderPath = `${currentFolderPath}/${subFolderName}`;
- uniqueFolders.add(fullSubFolderPath);
- } else {
- // Direct prompt in current folder
- matchingPrompts.push(prompt);
- }
- }
+ // 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 {
- // Root level
- const slashIndex = promptName.indexOf("/");
- if (slashIndex > 0) {
- const folderName = promptName.substring(0, slashIndex);
- uniqueFolders.add(folderName);
- } else {
- matchingPrompts.push(prompt);
- }
+ // 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),
+ }),
+ );
}
}
- // Create combined rows: folders first, then prompts
- const combinedRows: PromptTableRow[] = [];
-
- // Add folder rows
- for (const folderPath of uniqueFolders) {
- const folderName = getDisplayName(folderPath, currentFolderPath);
- combinedRows.push(
- createRow({
- id: folderPath,
- name: folderName,
- type: "folder",
- }),
- );
- }
-
- // Add matching prompts
- for (const prompt of matchingPrompts) {
- combinedRows.push(
- createRow({
- id: prompt.id,
- name: 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),
- }),
- );
- }
-
return {
...promptsRowData,
rows: combinedRows,
@@ -298,26 +274,25 @@ export function PromptTable() {
const rowData = row.row.original;
if (isFolder(rowData)) {
- const displayName = getDisplayName(rowData.id, currentFolderPath);
return (
<TableLink
path={""}
- value={displayName} // To satisfy table-link, fallback
+ value={name} // To satisfy table-link, fallback
className="flex items-center gap-2"
icon={
<>
<Folder className="h-4 w-4" />
- {displayName}
+ {name}
</>
}
onClick={() => {
setQueryParams({
- folder: rowData.id,
+ folder: rowData.id, // rowData.id contains the full folder path
pageIndex: 0,
pageSize: queryParams.pageSize,
});
}}
- title={displayName || ""}
+ title={name || ""}
/>
);
}
@@ -326,6 +301,7 @@ export function PromptTable() {
<TableLink
path={`/project/${projectId}/prompts/${encodeURIComponent(rowData.id)}`}
value={name}
+ title={rowData.id} // Show full prompt path on hover
/>
) : undefined;
},
@@ -508,12 +484,7 @@ export function PromptTable() {
isError: false,
data: processedRowData.rows?.map((item) => ({
id: item.id,
- name:
- item.type === "folder"
- ? item.name
- : currentFolderPath
- ? item.name.substring(currentFolderPath.length + 1)
- : item.name,
+ name: item.name,
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.ts
index 150b1ff371..99a7da5041 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -88,13 +88,23 @@ export const promptRouter = createTRPCRouter({
"prompts",
);
+ // pathFilter: SQL WHERE clause to filter prompts by folder (e.g., "AND p.name LIKE 'folder/%'")
const pathFilter = input.pathPrefix
- ? Prisma.sql` AND (p.name LIKE ${input.pathPrefix + "/%"} OR p.name = ${input.pathPrefix})`
+ ? (() => {
+ const prefix = input.pathPrefix;
+ return Prisma.sql` AND (p.name LIKE ${`${prefix}/%`} OR p.name = ${prefix})`;
+ })()
: Prisma.empty;
- const searchFilter = input.searchQuery
- ? Prisma.sql` AND (p.name ILIKE ${`%${input.searchQuery}%`} OR EXISTS (SELECT 1 FROM UNNEST(p.tags) AS tag WHERE tag ILIKE ${`%${input.searchQuery}%`}))`
- : Prisma.empty;
+ const searchFilter =
+ input.searchQuery !== undefined &&
+ input.searchQuery !== null &&
+ input.searchQuery !== ""
+ ? (() => {
+ const q = input.searchQuery;
+ return Prisma.sql` AND (p.name ILIKE ${`%${q}%`} OR EXISTS (SELECT 1 FROM UNNEST(p.tags) AS tag WHERE tag ILIKE ${`%${q}%`}))`;
+ })()
+ : Prisma.empty;
const [prompts, promptCount] = await Promise.all([
// prompts
@@ -116,8 +126,9 @@ export const promptRouter = createTRPCRouter({
orderByCondition,
input.limit,
input.page,
- pathFilter,
+ pathFilter, // SQL WHERE clause: filters DB to only prompts in current folder, derived from prefix.
searchFilter,
+ input.pathPrefix, // Raw folder path: used for segment splitting & folder detection logic
),
),
// promptCount
@@ -128,9 +139,10 @@ export const promptRouter = createTRPCRouter({
filterCondition,
Prisma.empty,
1, // limit
- 0, // page,
+ 0, // input.page,
pathFilter,
searchFilter,
+ input.pathPrefix,
),
),
]);
@@ -1296,25 +1308,89 @@ const generatePromptQuery = (
page: number,
pathFilter: Prisma.Sql = Prisma.empty,
searchFilter: Prisma.Sql = Prisma.empty,
+ pathPrefix?: string,
) => {
- return Prisma.sql`
- SELECT
- ${select}
- FROM prompts p
- WHERE (name, version) IN (
- SELECT name, MAX(version)
- FROM prompts p
- WHERE "project_id" = ${projectId}
- ${filterCondition}
- ${pathFilter}
- ${searchFilter}
- GROUP BY name
- )
- AND "project_id" = ${projectId}
- ${filterCondition}
- ${pathFilter}
- ${searchFilter}
- ${orderCondition}
- LIMIT ${limit} OFFSET ${page * limit};
-`;
+ const prefix = pathPrefix ?? "";
+
+ // CTE to get latest versions (same for root and folder queries)
+ const latestCTE = Prisma.sql`
+ latest AS (
+ SELECT p.*
+ FROM prompts p
+ WHERE (p.name, p.version) IN (
+ SELECT name, MAX(version)
+ FROM prompts p
+ WHERE p.project_id = ${projectId}
+ ${filterCondition}
+ ${pathFilter}
+ ${searchFilter}
+ GROUP BY name
+ )
+ AND p.project_id = ${projectId}
+ ${filterCondition}
+ ${pathFilter}
+ ${searchFilter}
+ )`;
+
+ // Common ORDER BY and LIMIT clauses
+ const orderAndLimit = Prisma.sql`
+ ${orderCondition.sql ? Prisma.sql`ORDER BY p.sort_priority, ${Prisma.raw(orderCondition.sql.replace(/ORDER BY /i, ""))}` : Prisma.empty}
+ LIMIT ${limit} OFFSET ${page * limit}`;
+
+ 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 (
+ 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)
+ FROM latest p
+ )
+ SELECT
+ ${select}
+ FROM grouped p
+ WHERE rn = 1
+ ${orderAndLimit};
+ `;
+ } else {
+ const baseColumns = Prisma.sql`id, name, version, project_id, prompt, type, updated_at, created_at, labels, tags, config, created_by`;
+
+ // When we're at the root level, show all individual prompts that don't have folders
+ // and one representative per folder for prompts that do have folders
+ return Prisma.sql`
+ WITH ${latestCTE},
+ individual_prompts AS (
+ /* Individual prompts without folders */
+ SELECT p.*
+ FROM latest p
+ WHERE p.name NOT LIKE '%/%'
+ ),
+ folder_representatives AS (
+ /* One representative per folder */
+ SELECT p.*,
+ ROW_NUMBER() OVER (PARTITION BY SPLIT_PART(p.name, '/', 1) ORDER BY p.version DESC) AS rn
+ FROM latest p
+ WHERE p.name LIKE '%/%'
+ ),
+ combined AS (
+ SELECT ${baseColumns}, 1 as sort_priority -- Folders first
+ FROM folder_representatives WHERE rn = 1
+ UNION ALL
+ SELECT ${baseColumns}, 2 as sort_priority -- Individual prompts second
+ FROM individual_prompts
+ )
+ SELECT
+ ${select}
+ FROM combined p
+ ${orderAndLimit};
+ `;
+ }
};