Skip to content

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

fix(prompts): don't comment fetching on many prompt versions (#13870)

Nimar099cbc76d0bd
diff --git a/web/src/__tests__/server/prompts-trpc.servertest.ts b/web/src/__tests__/server/prompts-trpc.servertest.ts
index 07c6cae0f6..b5dfdf1aef 100644
--- a/web/src/__tests__/server/prompts-trpc.servertest.ts
+++ b/web/src/__tests__/server/prompts-trpc.servertest.ts
@@ -58,6 +58,57 @@ describe("prompts trpc", () => {
afterAll(async () => {
await disconnectQueues();
});
+ describe("prompts.allVersions", () => {
+ it("returns comment counts for the requested prompt version page only", async () => {
+ const { project, caller } = await prepare();
+ const promptName = `test-prompt-comments-${v4()}`;
+ const promptVersions = Array.from({ length: 350 }, (_, index) => ({
+ id: v4(),
+ projectId: project.id,
+ name: promptName,
+ version: index + 1,
+ type: "text" as const,
+ prompt: { text: `Hello world v${index + 1}` },
+ createdBy: "API",
+ }));
+
+ await prisma.prompt.createMany({
+ data: promptVersions,
+ });
+
+ await prisma.comment.createMany({
+ data: [
+ {
+ projectId: project.id,
+ content: "old version comment",
+ objectId: promptVersions[0].id,
+ objectType: "PROMPT",
+ },
+ {
+ projectId: project.id,
+ content: "latest version comment",
+ objectId: promptVersions[349].id,
+ objectType: "PROMPT",
+ },
+ ],
+ });
+
+ const result = await caller.prompts.allVersions({
+ projectId: project.id,
+ name: promptName,
+ page: 0,
+ limit: 10,
+ includeCommentCounts: true,
+ });
+
+ expect(result.promptVersions).toHaveLength(10);
+ expect(result.promptVersions[0]?.version).toBe(350);
+ expect(result.commentCounts).toEqual(
+ new Map([[promptVersions[349].id, 1]]),
+ );
+ });
+ });
+
describe("prompts.setLabels", () => {
it("should set labels on a prompt and remove them from other versions", async () => {
const { project, caller } = await prepare();
diff --git a/web/src/features/comments/CommentDrawerButton.tsx b/web/src/features/comments/CommentDrawerButton.tsx
index 5a09f53e51..ba0842742f 100644
--- a/web/src/features/comments/CommentDrawerButton.tsx
+++ b/web/src/features/comments/CommentDrawerButton.tsx
@@ -25,6 +25,7 @@ export function CommentDrawerButton({
size = "default",
pendingSelection,
onSelectionUsed,
+ onCommentChange,
isOpen: controlledIsOpen,
onOpenChange: controlledOnOpenChange,
}: {
@@ -37,6 +38,7 @@ export function CommentDrawerButton({
size?: ButtonProps["size"];
pendingSelection?: SelectionData | null;
onSelectionUsed?: () => void;
+ onCommentChange?: () => void | Promise<void>;
isOpen?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
@@ -212,6 +214,7 @@ export function CommentDrawerButton({
isDrawerOpen={isDrawerOpen}
pendingSelection={pendingSelection}
onSelectionUsed={onSelectionUsed}
+ onCommentChange={onCommentChange}
/>
</div>
</div>
diff --git a/web/src/features/comments/CommentList.tsx b/web/src/features/comments/CommentList.tsx
index d3db403c95..88e69e9229 100644
--- a/web/src/features/comments/CommentList.tsx
+++ b/web/src/features/comments/CommentList.tsx
@@ -89,6 +89,7 @@ export function CommentList({
isDrawerOpen = false,
pendingSelection,
onSelectionUsed,
+ onCommentChange,
}: {
projectId: string;
objectId: string;
@@ -100,6 +101,7 @@ export function CommentList({
isDrawerOpen?: boolean;
pendingSelection?: SelectionData | null;
onSelectionUsed?: () => void;
+ onCommentChange?: () => void | Promise<void>;
}) {
const session = useSession();
const router = useRouter();
@@ -294,10 +296,16 @@ export function CommentList({
}, [isDrawerOpen]);
const utils = api.useUtils();
+ const invalidateCommentQueries = async () => {
+ void (async () => {
+ await onCommentChange?.();
+ })().catch(() => undefined);
+
+ await utils.comments.invalidate();
+ };
const createCommentMutation = api.comments.create.useMutation({
onSuccess: async () => {
- await Promise.all([utils.comments.invalidate()]);
form.reset();
// Clear pending selection after successful comment creation
@@ -308,6 +316,8 @@ export function CommentList({
textareaRef.current.style.height = "auto";
}
+ await invalidateCommentQueries();
+
// Scroll to bottom of comments list (newest comment in chronological order)
if (commentsContainerRef.current) {
commentsContainerRef.current.scrollTo({
@@ -357,7 +367,7 @@ export function CommentList({
const deleteCommentMutation = api.comments.delete.useMutation({
onSuccess: async () => {
- await Promise.all([utils.comments.invalidate()]);
+ await invalidateCommentQueries();
},
});
diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsx
index be253c563c..38555c6e67 100644
--- a/web/src/features/prompts/components/prompt-detail.tsx
+++ b/web/src/features/prompts/components/prompt-detail.tsx
@@ -145,13 +145,21 @@ export const PromptDetail = ({
projectId,
scope: "promptExperiments:CUD",
});
- const promptHistory = api.prompts.allVersions.useQuery(
- {
+ const hasCommentReadAccess = useHasProjectAccess({
+ projectId,
+ scope: "comments:read",
+ });
+ const promptHistoryInput = useMemo(
+ () => ({
name: promptName,
projectId: projectId as string, // Typecast as query is enabled only when projectId is present
- },
- { enabled: Boolean(projectId) },
+ includeCommentCounts: hasCommentReadAccess,
+ }),
+ [hasCommentReadAccess, projectId, promptName],
);
+ const promptHistory = api.prompts.allVersions.useQuery(promptHistoryInput, {
+ enabled: Boolean(projectId),
+ });
const prompt = currentPromptVersion
? promptHistory.data?.promptVersions.find(
(prompt) => prompt.version === currentPromptVersion,
@@ -230,27 +238,7 @@ export const PromptDetail = ({
).data?.tags ?? []
).map((t) => t.value);
- const promptIds = useMemo(
- () => promptHistory.data?.promptVersions.map((p) => p.id) ?? [],
- [promptHistory.data?.promptVersions],
- );
-
- const commentCounts = api.comments.getCountByObjectIds.useQuery(
- {
- projectId: projectId as string,
- objectType: "PROMPT",
- objectIds: promptIds,
- },
- {
- enabled: Boolean(projectId) && promptIds.length > 0,
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- refetchOnMount: false, // prevents refetching loops
- },
- );
+ const commentCounts = promptHistory.data?.commentCounts;
const { pythonCode, jsCode } = useMemo(() => {
if (!prompt?.id) return { pythonCode: null, jsCode: null };
@@ -315,6 +303,7 @@ export const PromptDetail = ({
availableTags={allTags}
projectId={projectId as string}
promptName={prompt.name}
+ includeCommentCounts={promptHistoryInput.includeCommentCounts}
/>
),
actionButtonsRight: (
@@ -371,7 +360,7 @@ export const PromptDetail = ({
setCurrentPromptVersion(version);
setCurrentPromptLabel(null);
}}
- commentCounts={commentCounts.data}
+ commentCounts={commentCounts}
/>
</div>
</Command>
@@ -454,8 +443,11 @@ export const PromptDetail = ({
projectId={projectId as string}
objectId={prompt.id}
objectType="PROMPT"
- count={getNumberFromMap(commentCounts?.data, prompt.id)}
+ count={getNumberFromMap(commentCounts, prompt.id)}
variant="outline"
+ onCommentChange={() =>
+ utils.prompts.allVersions.invalidate(promptHistoryInput)
+ }
/>
<DropdownMenu>
<DropdownMenuTrigger asChild>
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index 29be972edd..d0a4b04589 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -14,6 +14,7 @@ import {
} from "../actions/createPrompt";
import { checkHasProtectedLabels } from "../utils/checkHasProtectedLabels";
import {
+ CommentObjectType,
CreatePromptTRPCSchema,
LATEST_PROMPT_LABEL,
optionalPaginationZod,
@@ -1172,6 +1173,7 @@ export const promptRouter = createTRPCRouter({
z.object({
projectId: z.string(),
name: z.string(),
+ includeCommentCounts: z.boolean().optional(),
...optionalPaginationZod,
}),
)
@@ -1181,6 +1183,14 @@ export const promptRouter = createTRPCRouter({
projectId: input.projectId,
scope: "prompts:read",
});
+ if (input.includeCommentCounts) {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "comments:read",
+ });
+ }
+
const [prompts, totalCount] = await Promise.all([
ctx.prisma.prompt.findMany({
where: {
@@ -1200,6 +1210,31 @@ export const promptRouter = createTRPCRouter({
}),
]);
+ let commentCounts = new Map<string, number>();
+ if (input.includeCommentCounts) {
+ const promptIds = prompts.map((p) => p.id);
+ if (promptIds.length > 0) {
+ const groupedCommentCounts = await ctx.prisma.comment.groupBy({
+ by: ["objectId"],
+ where: {
+ projectId: input.projectId,
+ objectType: CommentObjectType.PROMPT,
+ objectId: { in: promptIds },
+ },
+ _count: {
+ objectId: true,
+ },
+ });
+
+ commentCounts = new Map(
+ groupedCommentCounts.map(({ objectId, _count }) => [
+ objectId,
+ _count.objectId,
+ ]),
+ );
+ }
+ }
+
const userIds = prompts
.map((p) => p.createdBy)
.filter((id) => id !== "API");
@@ -1231,7 +1266,11 @@ export const promptRouter = createTRPCRouter({
creator: user?.name,
};
});
- return { promptVersions: joinedPromptAndUsers, totalCount };
+ return {
+ promptVersions: joinedPromptAndUsers,
+ totalCount,
+ ...(input.includeCommentCounts ? { commentCounts } : {}),
+ };
}),
versionMetrics: protectedProjectProcedure
.input(
diff --git a/web/src/features/tag/components/TagPromptDetailsPopover.tsx b/web/src/features/tag/components/TagPromptDetailsPopover.tsx
index 030293611c..34c944d450 100644
--- a/web/src/features/tag/components/TagPromptDetailsPopover.tsx
+++ b/web/src/features/tag/components/TagPromptDetailsPopover.tsx
@@ -10,6 +10,7 @@ type TagPromptDetailsPopoverProps = {
availableTags: string[];
projectId: string;
promptName: string;
+ includeCommentCounts: boolean;
className?: string;
};
@@ -18,49 +19,53 @@ export function TagPromptDetailsPopover({
availableTags,
projectId,
promptName,
+ includeCommentCounts,
className,
}: TagPromptDetailsPopoverProps) {
const [isLoading, setIsLoading] = useState(false);
const hasAccess = useHasProjectAccess({ projectId, scope: "objects:tag" });
+ const allVersionsInput = {
+ projectId,
+ name: promptName,
+ includeCommentCounts,
+ };
const utils = api.useUtils();
const mutTags = api.prompts.updateTags.useMutation({
onMutate: async () => {
- await utils.prompts.byId.cancel();
+ await Promise.all([
+ utils.prompts.byId.cancel(),
+ utils.prompts.allVersions.cancel(allVersionsInput),
+ ]);
setIsLoading(true);
// Snapshot the previous value
- const prev = utils.prompts.allVersions.getData({
- projectId: projectId,
- name: promptName,
- });
+ const prev = utils.prompts.allVersions.getData(allVersionsInput);
return { prev };
},
onError: (err, _newTags, context) => {
- setIsLoading(false);
trpcErrorToast(err);
// Rollback to the previous value if mutation fails
- utils.prompts.allVersions.setData(
- { projectId: projectId, name: promptName },
- context?.prev,
- );
+ utils.prompts.allVersions.setData(allVersionsInput, context?.prev);
},
- onSettled: (data, error, { projectId: projectId, tags }) => {
- setIsLoading(false);
+ onSuccess: (_data, { tags }) => {
utils.prompts.allVersions.setData(
- { projectId: projectId, name: promptName },
+ allVersionsInput,
(oldQueryData: RouterOutput["prompts"]["allVersions"] | undefined) => {
return oldQueryData
? {
+ ...oldQueryData,
promptVersions: oldQueryData.promptVersions.map((prompt) => {
return prompt.name === promptName
? { ...prompt, tags }
: prompt;
}),
- totalCount: oldQueryData.totalCount,
}
: undefined;
},
);
+ },
+ onSettled: () => {
+ setIsLoading(false);
void utils.prompts.all.invalidate();
void utils.prompts.allVersions.invalidate();
void utils.prompts.filterOptions.invalidate();
diff --git a/web/src/server/api/routers/comments.ts b/web/src/server/api/routers/comments.ts
index 15b2714802..0c76b7de63 100644
--- a/web/src/server/api/routers/comments.ts
+++ b/web/src/server/api/routers/comments.ts
@@ -298,52 +298,6 @@ export const commentsRouter = createTRPCRouter({
]),
);
}),
- getCountByObjectIds: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- objectType: z.enum(CommentObjectType),
- objectIds: z.array(z.string()).min(1),
- }),
- )
- .query(async ({ input, ctx }) => {
- try {
- throwIfNoProjectAccess({
- session: ctx.session,
- projectId: input.projectId,
- scope: "comments:read",
- });
-
- const commentCounts = await ctx.prisma.comment.groupBy({
- by: ["objectId"],
- where: {
- projectId: input.projectId,
- objectType: input.objectType,
- objectId: { in: input.objectIds },
- },
- _count: {
- objectId: true,
- },
- });
-
- // Return as a Map<string, number>
- return new Map(
- commentCounts.map(({ objectId, _count }) => [
- objectId,
- _count.objectId,
- ]),
- );
- } catch (error) {
- logger.error("Failed to call comments.getCountByObjectIds", error);
- if (error instanceof TRPCError) {
- throw error;
- }
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Fetching comment counts by object ids failed.",
- });
- }
- }),
getTraceCommentCountsBySessionId: protectedProjectProcedure
.input(
z.object({