Skip to content

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

feat(agent): Feedback buttons (#14150)

Ben Bachem383625000d65
diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
index 76e0b08add..fc9bb6f29f 100644
--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
@@ -348,6 +348,7 @@ describe("in-app agent persistence", () => {
id: "assistant-message-1",
role: "assistant",
content: "I will inspect recent traces and look for outliers.",
+ runId: run1.id,
},
{
id: "user-message-2",
@@ -358,6 +359,7 @@ describe("in-app agent persistence", () => {
id: "assistant-message-2",
role: "assistant",
content: "Next trace inspected.",
+ runId: run2.id,
},
]);
@@ -423,6 +425,55 @@ describe("in-app agent persistence", () => {
);
});
+ it("requires feedback run ids to match persisted assistant messages", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const run = await createConversationRun({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ });
+ const events = await startCompactRun({
+ projectId,
+ conversationId: conversation.id,
+ runId: run.id,
+ messageId: "feedback-user",
+ content: "Answer me",
+ });
+ await appendAssistantText({
+ projectId,
+ conversationId: conversation.id,
+ runId: run.id,
+ events,
+ messageId: "feedback-assistant",
+ chunks: ["Here is an answer"],
+ });
+
+ await expect(
+ caller.submitFeedback({
+ projectId,
+ conversationId: conversation.id,
+ messageId: "feedback-assistant",
+ runId: createInAppAgentRunId(),
+ value: null,
+ comment: null,
+ }),
+ ).rejects.toThrow(
+ "Feedback can only be submitted for persisted assistant messages",
+ );
+
+ await expect(
+ caller.submitFeedback({
+ projectId,
+ conversationId: conversation.id,
+ messageId: "feedback-assistant",
+ runId: run.id,
+ value: null,
+ comment: null,
+ }),
+ ).resolves.toEqual({ feedback: null });
+ });
+
it("does not reduce partial assistant content before the end event", async () => {
const { caller, projectId, userId } = await createCaller();
const conversation = await createConversation({ projectId, userId });
diff --git a/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
index bc22a2dc25..c3c6b11d8a 100644
--- a/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
+++ b/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
@@ -4,6 +4,7 @@ import type { AgUiRunAgentInput } from "@/src/ee/features/in-app-agent/schema";
import { InAppAgentInstrumentation } from "@/src/ee/features/in-app-agent/server/instrumentation";
const traceId = "0123456789abcdef0123456789abcdef";
+const agentRunObservationId = "run-1";
const mocks = vi.hoisted(() => {
const toolSpan = {
@@ -11,7 +12,7 @@ const mocks = vi.hoisted(() => {
end: vi.fn(),
};
const agentSpan = {
- observationId: "agent-span-1",
+ observationId: "run-1",
traceId: "0123456789abcdef0123456789abcdef",
span: vi.fn(() => toolSpan),
update: vi.fn(),
@@ -129,7 +130,11 @@ describe("InAppAgentInstrumentation", () => {
"input",
);
expect(mocks.trace.span).toHaveBeenCalledWith(
- expect.objectContaining({ name: "agent-run", input: "hello" }),
+ expect.objectContaining({
+ id: agentRunObservationId,
+ name: "agent-run",
+ input: "hello",
+ }),
);
expect(mocks.agentSpan.span).not.toHaveBeenCalled();
expect(mocks.handler.langfuse.enqueue).toHaveBeenCalledWith(
@@ -137,7 +142,7 @@ describe("InAppAgentInstrumentation", () => {
expect.objectContaining({
id: "tool-1",
traceId,
- parentObservationId: "agent-span-1",
+ parentObservationId: agentRunObservationId,
name: "listObservations",
input: { limit: 10 },
output: "tool result",
@@ -152,6 +157,10 @@ describe("InAppAgentInstrumentation", () => {
output: "hi there",
}),
);
+ expect(mocks.handler.langfuse.enqueue).not.toHaveBeenCalledWith(
+ "span-create",
+ expect.anything(),
+ );
expect(mocks.trace.update.mock.calls[0][0]).not.toHaveProperty("output");
});
diff --git a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
index f1867e8733..f7580e5d56 100644
--- a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
+++ b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
@@ -47,6 +47,7 @@ export function ControlledInAppAgentWindow(
selectConversation,
selectedConversationId,
submit,
+ submitFeedback,
} = useInAppAiAgent();
const isInputDisabled =
isRunning || isSubmitting || isSelectedConversationHydrating;
@@ -146,10 +147,16 @@ export function ControlledInAppAgentWindow(
if (text.trim() || role === "user") {
mappedMessages.push({
id: message.id,
+ ...(message.role === "assistant" && message.runId
+ ? { runId: message.runId }
+ : {}),
role,
content: {
type: "text",
text,
+ ...(message.role === "assistant" && message.feedback
+ ? { feedback: message.feedback }
+ : {}),
},
});
}
@@ -235,6 +242,7 @@ export function ControlledInAppAgentWindow(
onNewConversation={() => selectConversation(null)}
onExpandedChange={props.onExpandedChange}
onSubmit={submit}
+ onSubmitFeedback={submitFeedback}
{...closeButtonProps}
/>
);
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx
index f13b2cd57b..de4471671a 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx
@@ -1,4 +1,5 @@
import preview from "../../../../../.storybook/preview";
+import { expect, fn, userEvent, waitFor, within } from "storybook/test";
import { InAppAgentMessage } from "./InAppAgentMessage";
const meta = preview.meta({
@@ -15,6 +16,59 @@ export const AssistantText = meta.story({
},
});
+export const AssistantTextWithFeedback = meta.story({
+ args: {
+ role: "assistant",
+ content: {
+ type: "text",
+ text: "Langfuse tracks traces, observations, scores, and metadata so teams can debug LLM applications.",
+ },
+ onSubmitFeedback: fn(),
+ },
+});
+
+export const ShortAssistantTextWithFeedback = meta.story({
+ args: {
+ role: "assistant",
+ content: {
+ type: "text",
+ text: "OK",
+ },
+ onSubmitFeedback: fn(),
+ },
+});
+
+export const AssistantTextWithFeedbackComment = meta.story({
+ args: {
+ role: "assistant",
+ content: {
+ type: "text",
+ text: "Langfuse tracks traces, observations, scores, and metadata so teams can debug LLM applications.",
+ feedback: {
+ value: "thumbs_up",
+ comment: "Helpful answer.",
+ },
+ },
+ onSubmitFeedback: fn(),
+ },
+});
+
+export const AssistantTextWithLongFeedbackComment = meta.story({
+ args: {
+ role: "assistant",
+ content: {
+ type: "text",
+ text: "Langfuse tracks traces, observations, scores, and metadata so teams can debug LLM applications.",
+ feedback: {
+ value: "thumbs_down",
+ comment:
+ "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source.",
+ },
+ },
+ onSubmitFeedback: fn(),
+ },
+});
+
export const AssistantMarkdown = meta.story({
args: {
role: "assistant",
@@ -177,3 +231,40 @@ export const Connecting = meta.story({
},
},
});
+
+export const FeedbackPopoverInteraction = meta.story({
+ name: "(Test) Feedback Popover Interaction",
+ args: {
+ role: "assistant",
+ content: {
+ type: "text",
+ text: "Langfuse tracks traces, observations, scores, and metadata so teams can debug LLM applications.",
+ },
+ onSubmitFeedback: fn(),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(
+ await canvas.findByRole("button", { name: "Good response" }),
+ );
+
+ const commentInput = await body.findByPlaceholderText(
+ "Optional feedback comment",
+ );
+ await expect(commentInput).toBeVisible();
+
+ const saveButton = await body.findByRole("button", {
+ name: "Save comment",
+ });
+ await waitFor(() => expect(saveButton).toBeEnabled());
+ await userEvent.click(saveButton);
+
+ await waitFor(() => {
+ expect(
+ body.queryByPlaceholderText("Optional feedback comment"),
+ ).not.toBeInTheDocument();
+ });
+ },
+});
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
index a3d02fd8ee..9a9b049ef2 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
@@ -1,16 +1,34 @@
"use client";
-import { Loader2, Wrench } from "lucide-react";
+import { Loader2, ThumbsDown, ThumbsUp, Wrench } from "lucide-react";
import { Streamdown } from "streamdown";
import { getSafeLinkUrl } from "@/src/components/ui/safe-url";
import { cn } from "@/src/utils/tailwind";
-import { useMemo } from "react";
+import {
+ forwardRef,
+ useMemo,
+ useRef,
+ useState,
+ type ButtonHTMLAttributes,
+ type ReactNode,
+} from "react";
+import type {
+ InAppAgentMessageFeedback,
+ InAppAgentMessageFeedbackValue,
+} from "@/src/ee/features/in-app-agent/schema";
+import {
+ Popover,
+ PopoverAnchor,
+ PopoverContent,
+} from "@/src/components/ui/popover";
+import { useElementSize } from "@/src/hooks/useElementSize";
+import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";
export type InAppAgentMessageRole = "assistant" | "user";
export type InAppAgentMessageContent =
| { type: "loading"; label?: string }
- | { type: "text"; text: string }
+ | { type: "text"; text: string; feedback?: InAppAgentMessageFeedback }
| {
type: "toolGroup";
tools: InAppAgentToolCallContent[];
@@ -29,15 +47,22 @@ export type InAppAgentMessageProps = {
role: InAppAgentMessageRole;
content: InAppAgentMessageContent;
isCompact?: boolean;
+ isFeedbackDisabled?: boolean;
+ windowZIndex?: number;
+ onSubmitFeedback?: (params: {
+ value: InAppAgentMessageFeedbackValue | null;
+ comment?: string | null;
+ }) => Promise<void>;
};
export function InAppAgentMessage({
role,
content,
isCompact = false,
+ isFeedbackDisabled = false,
+ windowZIndex,
+ onSubmitFeedback,
}: InAppAgentMessageProps) {
- const isUser = role === "user";
-
if (content.type === "toolGroup") {
return (
<div
@@ -57,8 +82,34 @@ export function InAppAgentMessage({
);
}
+ if (content.type === "text" && role === "assistant" && onSubmitFeedback) {
+ return (
+ <AssistantMessageWithFeedback
+ content={content}
+ isCompact={isCompact}
+ isFeedbackDisabled={isFeedbackDisabled}
+ windowZIndex={windowZIndex}
+ onSubmitFeedback={onSubmitFeedback}
+ />
+ );
+ }
+
+ return <MessageCard role={role} content={content} isCompact={isCompact} />;
+}
+
+const MessageCard = forwardRef<
+ HTMLDivElement,
+ {
+ role: InAppAgentMessageRole;
+ content: Exclude<InAppAgentMessageContent, { type: "toolGroup" }>;
+ isCompact: boolean;
+ }
+>(function MessageCard({ role, content, isCompact }, ref) {
+ const isUser = role === "user";
+
return (
<div
+ ref={ref}
className={cn(
"shadow-xs",
isCompact
@@ -76,6 +127,277 @@ export function InAppAgentMessage({
)}
</div>
);
+});
+
+function AssistantMessageWithFeedback({
+ content,
+ isCompact,
+ isFeedbackDisabled,
+ windowZIndex,
+ onSubmitFeedback,
+}: {
+ content: Extract<InAppAgentMessageContent, { type: "text" }>;
+ isCompact: boolean;
+ isFeedbackDisabled: boolean;
+ windowZIndex?: number;
+ onSubmitFeedback: (params: {
+ value: InAppAgentMessageFeedbackValue | null;
+ comment?: string | null;
+ }) => Promise<void>;
+}) {
+ const [messageCardRef, messageCardSize] = useElementSize<HTMLDivElement>();
+
+ return (
+ <div className="flex max-w-full flex-col items-start">
+ <MessageCard
+ ref={messageCardRef}
+ role="assistant"
+ content={content}
+ isCompact={isCompact}
+ />
+ <MessageFeedbackControls
+ feedback={content.feedback}
+ isCompact={isCompact}
+ isFeedbackDisabled={isFeedbackDisabled}
+ windowZIndex={windowZIndex}
+ maxWidth={messageCardSize?.width}
+ onSubmitFeedback={onSubmitFeedback}
+ />
+ </div>
+ );
+}
+
+function MessageFeedbackControls({
+ feedback,
+ isCompact,
+ isFeedbackDisabled,
+ windowZIndex,
+ maxWidth,
+ onSubmitFeedback,
+}: {
+ feedback?: InAppAgentMessageFeedback;
+ isCompact: boolean;
+ isFeedbackDisabled: boolean;
+ windowZIndex?: number;
+ maxWidth?: number;
+ onSubmitFeedback: (params: {
+ value: InAppAgentMessageFeedbackValue | null;
+ comment?: string | null;
+ }) => Promise<void>;
+}) {
+ const [committedComment, setCommittedComment] = useState(
+ feedback?.comment?.trim() ?? "",
+ );
+ const [comment, setComment] = useState(feedback?.comment ?? "");
+ const [selectedValue, setSelectedValue] = useState(feedback?.value);
+ const [isCommentPopoverOpen, setIsCommentPopoverOpen] = useState(false);
+ const isFeedbackDisabledRef = useRef(isFeedbackDisabled);
+ isFeedbackDisabledRef.current = isFeedbackDisabled;
+
+ const [submitFeedback, isSubmittingFeedback] = useWatchedPromiseCallback(
+ async (
+ value: InAppAgentMessageFeedbackValue | null,
+ nextComment: string = committedComment,
+ ) => {
+ await onSubmitFeedback({
+ value,
+ comment: nextComment.trim() || null,
+ });
+ },
+ [committedComment, onSubmitFeedback],
+ );
+
+ const [submitComment, isSubmittingComment] =
+ useWatchedPromiseCallback(async () => {
+ if (!selectedValue) {
+ return;
+ }
+
+ await onSubmitFeedback({
+ value: selectedValue,
+ comment: comment.trim() || null,
+ });
+ setCommittedComment(comment.trim());
+ setIsCommentPopoverOpen(false);
+ }, [comment, onSubmitFeedback, selectedValue]);
+
+ const isSaving = isSubmittingFeedback || isSubmittingComment;
+ const isDisabled = isFeedbackDisabled || isSaving;
+
+ const handleSubmitComment = async () => {
+ if (!selectedValue) {
+ return;
+ }
+
+ await submitComment().catch(() => undefined);
+ };
+
+ const handleSelectFeedback = (value: InAppAgentMessageFeedbackValue) => {
+ if (selectedValue === value) {
+ submitFeedback(null, "")
+ .then(() => {
+ setSelectedValue(undefined);
+ setComment("");
+ setCommittedComment("");
+ setIsCommentPopoverOpen(false);
+ })
+ .catch(() => undefined);
+ return;
+ }
+
+ submitFeedback(value, "")
+ .then(() => {
+ setSelectedValue(value);
+ setComment("");
+ setCommittedComment("");
+ setIsCommentPopoverOpen(!isFeedbackDisabledRef.current);
+ })
+ .catch(() => undefined);
+ };
+
+ return (
+ <div
+ style={maxWidth ? { width: maxWidth, maxWidth: "100%" } : undefined}
+ className={cn(
+ "flex max-w-full min-w-50 flex-col items-start overflow-hidden",
+ isCompact ? "mt-1.5" : "mt-2",
+ )}
+ >
+ <Popover
+ open={!isFeedbackDisabled && isCommentPopoverOpen}
+ onOpenChange={(open) => {
+ if (!isFeedbackDisabled) {
+ setIsCommentPopoverOpen(open);
+ }
+ }}
+ >
+ <div className="flex w-full min-w-0 items-center gap-1">
+ <PopoverAnchor className="inline-flex">
+ <FeedbackButton
+ label="Good response"
+ isSelected={selectedValue === "thumbs_up"}
+ disabled={isDisabled}
+ onClick={() => handleSelectFeedback("thumbs_up")}
+ >
+ <ThumbsUp
+ className={cn(
+ isCompact ? "size-3" : "size-3.5",
+ selectedValue === "thumbs_up" && "text-foreground",
+ )}
+ />
+ </FeedbackButton>
+ </PopoverAnchor>
+ <FeedbackButton
+ label="Bad response"
+ isSelected={selectedValue === "thumbs_down"}
+ disabled={isDisabled}
+ onClick={() => handleSelectFeedback("thumbs_down")}
+ >
+ <ThumbsDown
+ className={cn(
+ isCompact ? "size-3" : "size-3.5",
+ selectedValue === "thumbs_down" && "text-foreground",
+ )}
+ />
+ </FeedbackButton>
+ {committedComment ? (
+ <button
+ type="button"
+ className="text-muted-foreground hover:text-foreground ml-1 min-w-0 flex-1 truncate text-left text-xs disabled:cursor-not-allowed disabled:opacity-60"
+ disabled={isDisabled}
+ onClick={() => setIsCommentPopoverOpen(true)}
+ >
+ Comment: {committedComment}
+ </button>
+ ) : null}
+ </div>
+ {selectedValue ? (
+ <PopoverContent
+ align="start"
+ side="top"
+ className="w-72 space-y-1.5 p-2"
+ style={
+ typeof windowZIndex === "number"
+ ? { zIndex: windowZIndex + 1 }
+ : undefined
+ }
+ >
+ <div>
+ <textarea
+ value={comment}
+ onChange={(event) => setComment(event.target.value)}
+ disabled={isDisabled}
+ placeholder="Optional feedback comment"
+ rows={3}
+ maxLength={500}
+ className={cn(
+ "border-input bg-background text-foreground placeholder:text-muted-foreground w-full resize-none rounded-md border px-2 py-1",
+ isCompact ? "text-xs" : "text-sm",
+ )}
+ />
+ <CommentButton
+ disabled={isDisabled}
+ className={cn(!isCompact && "px-2 py-1.5 text-sm")}
+ onClick={() => {
+ handleSubmitComment().catch(() => undefined);
+ }}
+ >
+ {isSubmittingComment ? "Saving..." : "Save comment"}
+ </CommentButton>
+ </div>
+ </PopoverContent>
+ ) : null}
+ </Popover>
+ </div>
+ );
+}
+
+const CommentButton = forwardRef<
+ HTMLButtonElement,
+ ButtonHTMLAttributes<HTMLButtonElement>
+>(function CommentButton({ children, className, ...props }, ref) {
+ return (
+ <button
+ ref={ref}
+ type="button"
+ className={cn(
+ "text-muted-foreground hover:text-foreground flex items-center gap-1 rounded-md border px-1.5 py-1 text-xs font-medium disabled:cursor-not-allowed disabled:opacity-60",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </button>
+ );
+});
+
+function FeedbackButton({
+ children,
+ disabled,
+ isSelected,
+ label,
+ onClick,
+}: {
+ children: ReactNode;
+ disabled: boolean;
+ isSelected: boolean;
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ aria-pressed={isSelected}
+ disabled={disabled}
+ onClick={onClick}
+ className={cn(
+ "text-muted-foreground/50 hover:text-muted-foreground rounded-md p-1 disabled:cursor-not-allowed",
+ )}
+ >
+ {children}
+ </button>
+ );
}
function ToolCallGroup({
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx
index cc973e5bf5..4b85366f55 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx
@@ -59,6 +59,7 @@ const meta = preview.meta({
onClose: fn(),
onExpandedChange: fn(),
onSubmit: fn(),
+ onSubmitFeedback: fn(),
showCloseButton: true,
},
render: StatefulInAppAgentWindow,
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
index 1842b1e715..9b6324abef 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
@@ -25,11 +25,13 @@ import {
type InAppAgentMessageContent,
type InAppAgentMessageRole,
} from "./InAppAgentMessage";
+import type { InAppAgentMessageFeedbackValue } from "@/src/ee/features/in-app-agent/schema";
const AUTO_SCROLL_THRESHOLD_PX = 200;
export type InAppAgentWindowMessage = {
id: string;
+ runId?: string;
role: InAppAgentMessageRole;
content: InAppAgentMessageContent;
};
@@ -63,6 +65,12 @@ export type InAppAgentWindowProps = {
onNewConversation: () => void;
onSelectConversation: (conversationId: string) => void;
onSubmit: (input: string) => boolean | Promise<boolean>;
+ onSubmitFeedback: (params: {
+ messageId: string;
+ runId: string;
+ value: InAppAgentMessageFeedbackValue | null;
+ comment?: string | null;
+ }) => Promise<void>;
selectedConversationId: string | undefined;
zIndex?: number;
} & InAppAgentWindowCloseButtonProps;
@@ -81,6 +89,7 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
onNewConversation,
onSelectConversation,
onSubmit,
+ onSubmitFeedback,
selectedConversationId,
zIndex,
} = props;
@@ -281,6 +290,11 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
<ol className="flex w-full flex-col gap-3 pb-4">
{messages.map((message) => {
const hasToolContent = message.content.type === "toolGroup";
+ const feedbackRunId =
+ message.role === "assistant" &&
+ message.content.type === "text"
+ ? message.runId
+ : undefined;
return (
<li
@@ -295,6 +309,18 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
role={message.role}
content={message.content}
isCompact={!isExpanded}
+ isFeedbackDisabled={isInputDisabled}
+ windowZIndex={zIndex}
+ onSubmitFeedback={
+ feedbackRunId
+ ? (params) =>
+ onSubmitFeedback({
+ messageId: message.id,
+ runId: feedbackRunId,
+ ...params,
+ })
+ : undefined
+ }
/>
</li>
);
diff --git a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
index 09350eda00..ce8b29e70b 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
@@ -22,6 +22,8 @@ import {
import {
AgUiMessageSchema,
type AgUiMessage,
+ type InAppAgentMessageFeedback,
+ type InAppAgentMessageFeedbackValue,
type InAppAgentRuntimeState,
} from "@/src/ee/features/in-app-agent/schema";
import { useHasEntitlement } from "@/src/features/entitlements/hooks";
@@ -32,6 +34,7 @@ import { createInAppAgentScreenContext } from "@/src/ee/features/in-app-agent/co
const SELECTED_CONVERSATION_STORAGE_KEY_PREFIX =
"langfuse:in-app-ai-agent-selected-conversation";
const OPEN_STORAGE_KEY_PREFIX = "langfuse:in-app-ai-agent-open";
+const FEEDBACK_STORAGE_KEY_PREFIX = "langfuse:in-app-ai-agent-feedback";
const getConversationAgentState = (
projectId: string,
@@ -60,10 +63,16 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {
loadMoreConversations: () => undefined,
selectConversation: () => undefined,
submit: async () => false,
+ submitFeedback: async () => undefined,
};
type InAppAiAgentMessage = AgUiMessage;
+type InAppAiAgentFeedbackByConversationId = Record<
+ string,
+ Record<string, InAppAgentMessageFeedback>
+>;
+
export type InAppAiAgentConversation = {
id: string;
title: string | null;
@@ -88,6 +97,12 @@ type InAppAiAgentContextType = {
loadMoreConversations: () => void;
selectConversation: (conversationId: string | null) => void;
submit: (content: string) => Promise<boolean>;
+ submitFeedback: (params: {
+ messageId: string;
+ runId: string;
+ value: InAppAgentMessageFeedbackValue | null;
+ comment?: string | null;
+ }) => Promise<void>;
};
const InAppAiAgentContext = createContext<InAppAiAgentContextType | null>(null);
@@ -158,12 +173,18 @@ function InAppAiAgentProviderInner({
const [selectedConversationId, setSelectedConversationId] = useSessionStorage<
string | null
>(`${SELECTED_CONVERSATION_STORAGE_KEY_PREFIX}:${projectId}`, null);
+ const [feedbackByConversationId, setFeedbackByConversationId] =
+ useSessionStorage<InAppAiAgentFeedbackByConversationId>(
+ `${FEEDBACK_STORAGE_KEY_PREFIX}:${projectId}`,
+ {},
+ );
const [messages, setMessages] = useState<InAppAiAgentMessage[]>([]);
const [isRunning, setIsRunning] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const agentRef = useRef<HttpAgent | null>(null);
+ const activeRunIdRef = useRef<string | null>(null);
const intentionalAbortRef = useRef(false);
const submitInFlightRef = useRef(false);
const subscriptionRef = useRef<ReturnType<HttpAgent["subscribe"]> | null>(
@@ -187,6 +208,7 @@ function InAppAiAgentProviderInner({
enabled: open && Boolean(selectedConversationId) && !isSubmitting,
},
);
+ const feedbackMutation = api.inAppAgent.submitFeedback.useMutation();
const conversations = useMemo(
() =>
@@ -196,6 +218,16 @@ function InAppAiAgentProviderInner({
);
const hasMoreConversations = conversationListQuery.hasNextPage === true;
const isLoadingMoreConversations = conversationListQuery.isFetchingNextPage;
+ const messagesWithFeedback = useMemo(
+ () =>
+ mergeMessagesWithFeedback(
+ messages,
+ selectedConversationId
+ ? feedbackByConversationId[selectedConversationId]
+ : undefined,
+ ),
+ [feedbackByConversationId, messages, selectedConversationId],
+ );
const fetchNextConversationsPage = conversationListQuery.fetchNextPage;
const loadMoreConversations = useCallback(() => {
if (!hasMoreConversations || isLoadingMoreConversations) {
@@ -239,6 +271,7 @@ function InAppAiAgentProviderInner({
subscriptionRef.current = null;
agentRef.current?.abortRun();
agentRef.current = null;
+ activeRunIdRef.current = null;
}, []);
// Hydrate local state from the selected persisted conversation once it loads.
@@ -314,6 +347,9 @@ function InAppAiAgentProviderInner({
}
subscriptionRef.current = agent.subscribe({
+ onRunStartedEvent: ({ event }) => {
+ activeRunIdRef.current = event.runId;
+ },
onRunErrorEvent: ({ event }) => {
if (intentionalAbortRef.current) {
return;
@@ -324,10 +360,20 @@ function InAppAiAgentProviderInner({
console.error("In-app agent drawer run error", event);
},
onMessagesChanged: ({ messages }) => {
- setMessages(messages.filter(isAgentConversationMessage));
+ setMessages(
+ attachActiveRunIdToAssistantMessages(
+ messages.filter(isAgentConversationMessage),
+ activeRunIdRef.current,
+ ),
+ );
},
onStateChanged: ({ messages }) => {
- setMessages(messages.filter(isAgentConversationMessage));
+ setMessages(
+ attachActiveRunIdToAssistantMessages(
+ messages.filter(isAgentConversationMessage),
+ activeRunIdRef.current,
+ ),
+ );
},
});
}, []);
@@ -386,14 +432,21 @@ function InAppAiAgentProviderInner({
console.error("In-app agent drawer error", error);
})
.finally(() => {
+ const runId = activeRunIdRef.current;
setIsRunning(false);
- setMessages(agent.messages.filter(isAgentConversationMessage));
+ setMessages(
+ attachActiveRunIdToAssistantMessages(
+ agent.messages.filter(isAgentConversationMessage),
+ runId,
+ ),
+ );
utils.inAppAgent.listConversations.invalidate({ projectId });
utils.inAppAgent.getConversation.invalidate({
projectId,
conversationId,
});
releaseSubmitLock();
+ activeRunIdRef.current = null;
intentionalAbortRef.current = false;
});
},
@@ -501,6 +554,62 @@ function InAppAiAgentProviderInner({
],
);
+ const submitFeedback = useCallback(
+ async (params: {
+ messageId: string;
+ runId: string;
+ value: InAppAgentMessageFeedbackValue | null;
+ comment?: string | null;
+ }) => {
+ if (!selectedConversationId) {
+ return;
+ }
+
+ try {
+ const result = await feedbackMutation.mutateAsync({
+ projectId,
+ conversationId: selectedConversationId,
+ messageId: params.messageId,
+ runId: params.runId,
+ value: params.value,
+ comment: params.comment ?? null,
+ });
+
+ setFeedbackByConversationId((currentFeedback) => {
+ const nextFeedback = { ...currentFeedback };
+ const conversationFeedback = {
+ ...(nextFeedback[selectedConversationId] ?? {}),
+ };
+
+ if (result.feedback) {
+ conversationFeedback[params.messageId] = result.feedback;
+ } else {
+ delete conversationFeedback[params.messageId];
+ }
+
+ if (Object.keys(conversationFeedback).length > 0) {
+ nextFeedback[selectedConversationId] = conversationFeedback;
+ } else {
+ delete nextFeedback[selectedConversationId];
+ }
+
+ return nextFeedback;
+ });
+ } catch (error) {
+ const errorMessage = getAgentErrorMessage(error);
+ showErrorToast("Failed to save feedback", errorMessage);
+ console.error("Failed to save in-app agent feedback", error);
+ throw error;
+ }
+ },
+ [
+ feedbackMutation,
+ projectId,
+ selectedConversationId,
+ setFeedbackByConversationId,
+ ],
+ );
+
useEffect(() => {
if (!open) {
setIsExpanded(false);
@@ -518,7 +627,7 @@ function InAppAiAgentProviderInner({
isSubmitting,
isSelectedConversationHydrating,
error,
- messages,
+ messages: messagesWithFeedback,
conversations,
hasMoreConversations,
isLoadingMoreConversations,
@@ -526,6 +635,7 @@ function InAppAiAgentProviderInner({
loadMoreConversations,
selectConversation,
submit,
+ submitFeedback,
}),
[
isExpanded,
@@ -537,12 +647,13 @@ function InAppAiAgentProviderInner({
isSelectedConversationHydrating,
isSubmitting,
loadMoreConversations,
- messages,
+ messagesWithFeedback,
open,
selectConversation,
selectedConversationId,
setOpen,
submit,
+ submitFeedback,
],
);
@@ -572,6 +683,45 @@ function getHydratedMessages(
return storedMessages?.filter(isAgentConversationMessage) ?? [];
}
+function mergeMessagesWithFeedback(
+ messages: InAppAiAgentMessage[],
+ feedbackByMessageId: Record<string, InAppAgentMessageFeedback> | undefined,
+): InAppAiAgentMessage[] {
+ if (!feedbackByMessageId || Object.keys(feedbackByMessageId).length === 0) {
+ return messages;
+ }
+
+ return messages.map((message) => {
+ if (message.role !== "assistant") {
+ return message;
+ }
+
+ const feedback = feedbackByMessageId[message.id];
+ if (!feedback) {
+ return message;
+ }
+
+ return { ...message, feedback };
+ });
+}
+
+function attachActiveRunIdToAssistantMessages(
+ messages: InAppAiAgentMessage[],
+ runId: string | null,
+): InAppAiAgentMessage[] {
+ if (!runId) {
+ return messages;
+ }
+
+ return messages.map((message) => {
+ if (message.role !== "assistant" || message.runId) {
+ return message;
+ }
+
+ return { ...message, runId };
+ });
+}
+
function getAgentErrorMessage(error: unknown): string {
if (error && typeof error === "object") {
const payload = "payload" in error ? error.payload : undefined;
diff --git a/web/src/ee/features/in-app-agent/schema.ts b/web/src/ee/features/in-app-agent/schema.ts
index cc82d93362..20d5b9de3b 100644
--- a/web/src/ee/features/in-app-agent/schema.ts
+++ b/web/src/ee/features/in-app-agent/schema.ts
@@ -23,6 +23,24 @@ const AgUiToolCallSchema = z.object({
encryptedValue: z.string().optional(),
});
+export const InAppAgentMessageFeedbackValueSchema = z.enum([
+ "thumbs_up",
+ "thumbs_down",
+]);
+
+export type InAppAgentMessageFeedbackValue = z.infer<
+ typeof InAppAgentMessageFeedbackValueSchema
+>;
+
+export const InAppAgentMessageFeedbackSchema = z.object({
+ value: InAppAgentMessageFeedbackValueSchema,
+ comment: z.string().nullable(),
+});
+
+export type InAppAgentMessageFeedback = z.infer<
+ typeof InAppAgentMessageFeedbackSchema
+>;
+
const AgUiInputContentSourceSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("data"),
@@ -84,6 +102,8 @@ export const AgUiMessageSchema = z.discriminatedUnion("role", [
role: z.literal("assistant"),
content: z.string().optional(),
toolCalls: z.array(AgUiToolCallSchema).optional(),
+ feedback: InAppAgentMessageFeedbackSchema.optional(),
+ runId: z.string().optional(),
}),
AgUiBaseMessageSchema.extend({
role: z.literal("user"),
diff --git a/web/src/ee/features/in-app-agent/server/instrumentation.ts b/web/src/ee/features/in-app-agent/server/instrumentation.ts
index 23c47b30c2..871ed27f15 100644
--- a/web/src/ee/features/in-app-agent/server/instrumentation.ts
+++ b/web/src/ee/features/in-app-agent/server/instrumentation.ts
@@ -116,6 +116,7 @@ export class InAppAgentInstrumentation {
tags: ["in-app-agent"],
});
this.span = this.trace.span({
+ id: params.input.runId,
name: IN_APP_AGENT_SPAN_NAME,
input: getAgentSpanInput(params.input),
metadata: params.metadata,
diff --git a/web/src/ee/features/in-app-agent/server/persistence.ts b/web/src/ee/features/in-app-agent/server/persistence.ts
index 86bec9888d..e162792df6 100644
--- a/web/src/ee/features/in-app-agent/server/persistence.ts
+++ b/web/src/ee/features/in-app-agent/server/persistence.ts
@@ -32,6 +32,11 @@ export type SerializedInAppAgentConversation = {
updatedAt: Date;
};
+type PersistedConversationEvent = {
+ event: AgUiEvent;
+ runId: string;
+};
+
export function serializeConversation(
conversation: Pick<
InAppAgentConversation,
@@ -262,17 +267,20 @@ export async function getConversationEvents(params: {
prisma: PrismaClient;
projectId: string;
conversationId: string;
-}) {
+}): Promise<PersistedConversationEvent[]> {
const events = await params.prisma.inAppAgentEvent.findMany({
where: {
projectId: params.projectId,
conversationId: params.conversationId,
},
orderBy: { sequenceNumber: "asc" },
- select: { event: true },
+ select: { event: true, runId: true },
});
- return events.map(({ event }) => event as unknown as AgUiEvent);
+ return events.map(({ event, runId }) => ({
+ event: event as unknown as AgUiEvent,
+ runId,
+ }));
}
export async function getConversationMessages(params: {
@@ -280,7 +288,7 @@ export async function getConversationMessages(params: {
projectId: string;
conversationId: string;
}) {
- return getMessagesFromEvents(await getConversationEvents(params));
+ return getMessagesFromPersistedEvents(await getConversationEvents(params));
}
export async function getConversationMessagesForReplay(params: {
@@ -303,12 +311,26 @@ export function getMessagesFromEvents(events: readonly AgUiEvent[]) {
return accumulator.getMessages();
}
+function getMessagesFromPersistedEvents(
+ events: readonly PersistedConversationEvent[],
+) {
+ const accumulator = createConversationMessageAccumulator([]);
+
+ for (const { event, runId } of events) {
+ accumulator.processEvent(event, runId);
+ }
+
+ return accumulator.getMessages();
+}
+
function sanitizeConversationMessagesForReplay(
messages: readonly AgUiMessage[],
): readonly AgUiMessage[] {
const messagesWithoutOrphanToolCalls =
dropUnpairedAssistantToolCalls(messages);
- return dropEmptyAssistantMessages(messagesWithoutOrphanToolCalls);
+ return stripAssistantRunIds(
+ dropEmptyAssistantMessages(messagesWithoutOrphanToolCalls),
+ );
}
export function shouldFlushPersistedEvent(event: AgUiEvent) {
@@ -439,13 +461,17 @@ export function createConversationMessageAccumulator(
) {
const messages: AgUiMessage[] = [];
const messageIndexes = new Map<string, number>();
- const textDrafts = new Map<string, { id: string; content: string }>();
+ const textDrafts = new Map<
+ string,
+ { id: string; content: string; runId?: string }
+ >();
const toolCallDrafts = new Map<
string,
{
parentMessageId: string;
name: string;
args: string;
+ runId?: string;
}
>();
@@ -476,7 +502,7 @@ export function createConversationMessageAccumulator(
upsertMessage(message);
}
- const processEvent = (event: AgUiEvent): boolean => {
+ const processEvent = (event: AgUiEvent, runId?: string): boolean => {
switch (event.type) {
case EventType.RUN_STARTED: {
if (!isRecord(event.input) || !Array.isArray(event.input.messages)) {
@@ -509,22 +535,25 @@ export function createConversationMessageAccumulator(
const draft = textDrafts.get(messageId) ?? {
id: messageId,
content: existingContent ?? "",
+ runId,
};
draft.content += getString(event, "delta") ?? "";
+ draft.runId ??= runId;
textDrafts.set(messageId, draft);
return upsertMessage({
id: draft.id,
role: "assistant",
content: draft.content,
+ ...(draft.runId ? { runId: draft.runId } : {}),
});
}
case EventType.TEXT_MESSAGE_START: {
const messageId = getString(event, "messageId");
if (messageId && getString(event, "role") === "assistant") {
- textDrafts.set(messageId, { id: messageId, content: "" });
+ textDrafts.set(messageId, { id: messageId, content: "", runId });
}
break;
}
@@ -535,6 +564,7 @@ export function createConversationMessageAccumulator(
if (draft) {
draft.content += delta;
+ draft.runId ??= runId;
}
break;
}
@@ -550,6 +580,7 @@ export function createConversationMessageAccumulator(
id: draft.id,
role: "assistant",
content: draft.content,
+ ...((draft.runId ?? runId) ? { runId: draft.runId ?? runId } : {}),
});
textDrafts.delete(draft.id);
@@ -565,6 +596,7 @@ export function createConversationMessageAccumulator(
parentMessageId,
name,
args: "",
+ runId,
});
}
break;
@@ -586,6 +618,7 @@ export function createConversationMessageAccumulator(
const changed = upsertMessage({
id: draft.parentMessageId,
role: "assistant",
+ ...((draft.runId ?? runId) ? { runId: draft.runId ?? runId } : {}),
toolCalls: [
{
id: toolCallId,
@@ -649,6 +682,23 @@ export function createConversationMessageAccumulator(
};
}
+function stripAssistantRunIds(messages: readonly AgUiMessage[]) {
+ let changed = false;
+
+ const sanitizedMessages = messages.map((message): AgUiMessage => {
+ if (message.role !== "assistant" || !message.runId) {
+ return message;
+ }
+
+ changed = true;
+ const sanitizedMessage = { ...message };
+ delete sanitizedMessage.runId;
+ return sanitizedMessage;
+ });
+
+ return changed ? sanitizedMessages : messages;
+}
+
type InAppAgentTx = Prisma.TransactionClient;
async function lockConversation(
diff --git a/web/src/ee/features/in-app-agent/server/router.ts b/web/src/ee/features/in-app-agent/server/router.ts
index 7e8631558b..531f7b0f68 100644
--- a/web/src/ee/features/in-app-agent/server/router.ts
+++ b/web/src/ee/features/in-app-agent/server/router.ts
@@ -1,9 +1,21 @@
import { z } from "zod";
import type { Session } from "next-auth";
-import { BaseError, ForbiddenError } from "@langfuse/shared";
+import {
+ BaseError,
+ ForbiddenError,
+ InvalidRequestError,
+ ScoreDataTypeEnum,
+ ScoreSourceEnum,
+ TEXT_SCORE_MAX_LENGTH,
+} from "@langfuse/shared";
import type { PrismaClient } from "@langfuse/shared/src/db";
+import {
+ convertDateToClickhouseDateTime,
+ upsertScore,
+} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
+import { InAppAgentMessageFeedbackValueSchema } from "@/src/ee/features/in-app-agent/schema";
import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
import {
createTRPCRouter,
@@ -28,6 +40,16 @@ const ConversationIdInput = z.object({
conversationId: z.string(),
});
+const SubmitFeedbackInput = ConversationIdInput.extend({
+ messageId: z.string(),
+ runId: z.string(),
+ value: InAppAgentMessageFeedbackValueSchema.nullable(),
+ comment: z.string().trim().max(TEXT_SCORE_MAX_LENGTH).nullable().optional(),
+});
+
+const IN_APP_AGENT_FEEDBACK_SCORE_NAME = "in_app_agent_feedback";
+const IN_APP_AGENT_FEEDBACK_ENVIRONMENT = "langfuse-in-app-agent";
+
export const inAppAgentRouter = createTRPCRouter({
listConversations: protectedProjectProcedure
.input(
@@ -104,6 +126,86 @@ export const inAppAgentRouter = createTRPCRouter({
},
};
}),
+
+ submitFeedback: protectedProjectProcedureWithoutTracing
+ .input(SubmitFeedbackInput)
+ .mutation(async ({ ctx, input }) => {
+ const projectAvailability = await assertInAppAgentAvailable({
+ ctx,
+ projectId: input.projectId,
+ });
+
+ await getOwnedConversationOrThrow({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ conversationId: input.conversationId,
+ userId: ctx.session.user.id,
+ });
+
+ const messages = await getConversationMessages({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ conversationId: input.conversationId,
+ });
+ const targetMessage = messages.find(
+ (message) => message.id === input.messageId,
+ );
+
+ if (
+ targetMessage?.role !== "assistant" ||
+ typeof targetMessage.content !== "string" ||
+ targetMessage.content.length === 0
+ ) {
+ throw new InvalidRequestError(
+ "Feedback can only be submitted for assistant text messages",
+ );
+ }
+
+ if (targetMessage.runId !== input.runId) {
+ throw new InvalidRequestError(
+ "Feedback can only be submitted for persisted assistant messages",
+ );
+ }
+
+ const comment = input.comment?.trim() ? input.comment.trim() : null;
+ if (input.value === null) {
+ return { feedback: null };
+ }
+
+ const scoreId = `afbs_${input.messageId}_${ctx.session.user.id}`;
+ const now = new Date();
+ const scoreProjectId = env.LANGFUSE_AI_FEATURES_PROJECT_ID;
+
+ if (projectAvailability.aiTelemetryEnabled && scoreProjectId) {
+ await upsertScore({
+ id: scoreId,
+ timestamp: convertDateToClickhouseDateTime(now),
+ project_id: scoreProjectId,
+ environment: IN_APP_AGENT_FEEDBACK_ENVIRONMENT,
+ trace_id: input.conversationId,
+ observation_id: input.runId,
+ session_id: input.conversationId,
+ name: IN_APP_AGENT_FEEDBACK_SCORE_NAME,
+ value: input.value === "thumbs_up" ? 1 : 0,
+ source: ScoreSourceEnum.ANNOTATION,
+ comment,
+ author_user_id: ctx.session.user.id,
+ config_id: null,
+ data_type: ScoreDataTypeEnum.BOOLEAN,
+ string_value: input.value === "thumbs_up" ? "true" : "false",
+ queue_id: null,
+ created_at: convertDateToClickhouseDateTime(now),
+ updated_at: convertDateToClickhouseDateTime(now),
+ metadata: {
+ project_id: input.projectId,
+ conversation_id: input.conversationId,
+ message_id: input.messageId,
+ },
+ });
+ }
+
+ return { feedback: { value: input.value, comment } };
+ }),
});
async function assertInAppAgentAvailable({
@@ -149,6 +251,7 @@ async function assertInAppAgentAvailable({
organization: {
select: {
aiFeaturesEnabled: true,
+ aiTelemetryEnabled: true,
},
},
},
@@ -157,4 +260,8 @@ async function assertInAppAgentAvailable({
if (!project?.organization.aiFeaturesEnabled) {
throw new ForbiddenError("Assistant is not enabled for this organization");
}
+
+ return {
+ aiTelemetryEnabled: project.organization.aiTelemetryEnabled,
+ };
}
diff --git a/web/src/hooks/useElementSize.ts b/web/src/hooks/useElementSize.ts
new file mode 100644
index 0000000000..7fcccfc576
--- /dev/null
+++ b/web/src/hooks/useElementSize.ts
@@ -0,0 +1,37 @@
+import { useEffect, useRef, useState } from "react";
+
+export type ElementSize = {
+ width: number;
+ height: number;
+};
+
+export function useElementSize<TElement extends HTMLElement>() {
+ const ref = useRef<TElement>(null);
+ const [size, setSize] = useState<ElementSize>();
+
+ useEffect(() => {
+ const element = ref.current;
+
+ if (!element) {
+ return;
+ }
+
+ const updateSize = () => {
+ const { width, height } = element.getBoundingClientRect();
+ setSize({ width, height });
+ };
+
+ updateSize();
+
+ if (typeof ResizeObserver === "undefined") {
+ return;
+ }
+
+ const resizeObserver = new ResizeObserver(updateSize);
+ resizeObserver.observe(element);
+
+ return () => resizeObserver.disconnect();
+ }, []);
+
+ return [ref, size] as const;
+}