Skip to content

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

feat(agent): Allow deleting conversations (#14587)

Ben Bachem85a717ae1bb0
diff --git a/web/src/__tests__/server/in-app-agent-router.servertest.ts b/web/src/__tests__/server/in-app-agent-router.servertest.ts
new file mode 100644
index 0000000000..861af6d490
--- /dev/null
+++ b/web/src/__tests__/server/in-app-agent-router.servertest.ts
@@ -0,0 +1,219 @@
+import { randomUUID } from "crypto";
+import type { Session } from "next-auth";
+
+import { prisma } from "@langfuse/shared/src/db";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+
+describe("in-app agent router", () => {
+ it("soft-deletes an owned conversation", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+
+ await caller.inAppAgent.deleteConversation({
+ projectId,
+ conversationId: conversation.id,
+ });
+
+ const deletedConversation =
+ await prisma.inAppAgentConversation.findUniqueOrThrow({
+ where: {
+ id_projectId: {
+ id: conversation.id,
+ projectId,
+ },
+ },
+ });
+
+ expect(deletedConversation.deletedAt).toBeInstanceOf(Date);
+ });
+
+ it("excludes deleted conversations from list and get", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const keptConversation = await createConversation({
+ projectId,
+ userId,
+ title: "Kept conversation",
+ });
+ const deletedConversation = await createConversation({
+ projectId,
+ userId,
+ title: "Deleted conversation",
+ });
+
+ await caller.inAppAgent.deleteConversation({
+ projectId,
+ conversationId: deletedConversation.id,
+ });
+
+ const listedConversations = await caller.inAppAgent.listConversations({
+ projectId,
+ });
+
+ expect(listedConversations.conversations.map(({ id }) => id)).toContain(
+ keptConversation.id,
+ );
+ expect(listedConversations.conversations.map(({ id }) => id)).not.toContain(
+ deletedConversation.id,
+ );
+ await expect(
+ caller.inAppAgent.getConversation({
+ projectId,
+ conversationId: deletedConversation.id,
+ }),
+ ).rejects.toThrow("Agent conversation not found");
+ });
+
+ it("does not delete another user's conversation", async () => {
+ const fixture = await createProjectFixture();
+ const ownerCaller = createCallerForFixture(fixture, fixture.ownerUserId);
+ const otherCaller = createCallerForFixture(fixture, fixture.otherUserId);
+ const conversation = await createConversation({
+ projectId: fixture.projectId,
+ userId: fixture.ownerUserId,
+ });
+
+ await expect(
+ otherCaller.inAppAgent.deleteConversation({
+ projectId: fixture.projectId,
+ conversationId: conversation.id,
+ }),
+ ).rejects.toThrow("Agent conversation not found");
+
+ await ownerCaller.inAppAgent.getConversation({
+ projectId: fixture.projectId,
+ conversationId: conversation.id,
+ });
+ });
+});
+
+async function createCaller() {
+ const fixture = await createProjectFixture();
+
+ return {
+ ...fixture,
+ userId: fixture.ownerUserId,
+ caller: createCallerForFixture(fixture, fixture.ownerUserId),
+ };
+}
+
+async function createProjectFixture() {
+ const id = randomUUID();
+ const orgId = `org-${id}`;
+ const projectId = `project-${id}`;
+ const ownerUserId = `owner-${id}`;
+ const otherUserId = `other-${id}`;
+
+ const org = await prisma.organization.create({
+ data: {
+ id: orgId,
+ name: `In-app Agent Router Test Org ${id}`,
+ aiFeaturesEnabled: true,
+ },
+ });
+ const project = await prisma.project.create({
+ data: {
+ id: projectId,
+ orgId,
+ name: `In-app Agent Router Test Project ${id}`,
+ },
+ });
+
+ await prisma.user.createMany({
+ data: [
+ {
+ id: ownerUserId,
+ email: `${ownerUserId}@example.com`,
+ name: "In-app Agent Router Test Owner",
+ },
+ {
+ id: otherUserId,
+ email: `${otherUserId}@example.com`,
+ name: "In-app Agent Router Test Other User",
+ },
+ ],
+ });
+
+ return {
+ orgId: org.id,
+ orgName: org.name,
+ projectId: project.id,
+ projectName: project.name,
+ ownerUserId,
+ otherUserId,
+ };
+}
+
+function createCallerForFixture(
+ fixture: Awaited<ReturnType<typeof createProjectFixture>>,
+ userId: string,
+) {
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: userId,
+ email: `${userId}@example.com`,
+ name: "In-app Agent Router Test User",
+ canCreateOrganizations: true,
+ organizations: [
+ {
+ id: fixture.orgId,
+ name: fixture.orgName,
+ role: "OWNER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ metadata: {},
+ aiFeaturesEnabled: true,
+ aiTelemetryEnabled: true,
+ projects: [
+ {
+ id: fixture.projectId,
+ name: fixture.projectName,
+ role: "ADMIN",
+ deletedAt: null,
+ retentionDays: null,
+ hasTraces: false,
+ metadata: {},
+ createdAt: new Date().toISOString(),
+ },
+ ],
+ },
+ ],
+ featureFlags: {
+ searchBar: false,
+ templateFlag: true,
+ excludeClickhouseRead: false,
+ observationEvals: false,
+ v4BetaToggleVisible: false,
+ experimentsV4Enabled: false,
+ },
+ admin: false,
+ },
+ environment: {
+ enableExperimentalFeatures: false,
+ selfHostedInstancePlan: "cloud:enterprise",
+ },
+ };
+ const ctx = createInnerTRPCContext({ session, headers: {} });
+
+ return appRouter.createCaller({ ...ctx, prisma });
+}
+
+async function createConversation({
+ projectId,
+ userId,
+ title = "Test conversation",
+}: {
+ projectId: string;
+ userId: string;
+ title?: string;
+}) {
+ return prisma.inAppAgentConversation.create({
+ data: {
+ id: `conv-${randomUUID()}`,
+ projectId,
+ createdByUserId: userId,
+ title,
+ },
+ });
+}
diff --git a/web/src/components/nav/in-app-ai-agent-button.tsx b/web/src/components/nav/in-app-ai-agent-button.tsx
index dd447c2497..b9fe2d4b2d 100644
--- a/web/src/components/nav/in-app-ai-agent-button.tsx
+++ b/web/src/components/nav/in-app-ai-agent-button.tsx
@@ -2,6 +2,7 @@ import { useLayoutEffect, useRef, useState } from "react";
import { BotMessageSquare } from "lucide-react";
import { Button } from "@/src/components/ui/button";
+import { ConfirmDialog } from "@/src/components/ui/confirm-dialog";
import {
Dialog,
DialogBody,
@@ -10,6 +11,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/src/components/ui/dialog";
+import { DialogController } from "@/src/components/ui/dialog-controller";
import { Layer } from "@/src/components/ui/layer";
import { SidebarMenuButton } from "@/src/components/ui/sidebar";
import { ControlledInAppAgentWindow } from "@/src/ee/features/in-app-agent/components";
@@ -18,15 +20,63 @@ import {
useInAppAgentWindowShellPanelControl,
} from "@/src/ee/features/in-app-agent/components/InAppAgentWindowShell";
import { useInAppAiAgent } from "@/src/ee/features/in-app-agent/components/InAppAiAgentProvider";
+import type { InAppAgentWindowConversation } from "@/src/ee/features/in-app-agent/components/InAppAgentWindow";
import { useHasEntitlement } from "@/src/features/entitlements/hooks";
import { AIFeaturesDisabledNotice } from "@/src/features/organizations/components/AIFeaturesDisabledNotice";
import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
+import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";
+
+function DeleteConversationDialog({
+ close,
+ conversation,
+ onDeleteConversation,
+}: {
+ close: () => void;
+ conversation: InAppAgentWindowConversation | null;
+ onDeleteConversation: (conversationId: string) => Promise<void>;
+}) {
+ const [deleteConversation, isDeletingConversation] =
+ useWatchedPromiseCallback(async () => {
+ if (!conversation) {
+ return;
+ }
+
+ try {
+ await onDeleteConversation(conversation.id);
+ close();
+ } catch {
+ // Error is already surfaced by the provider; keep the dialog open for retry.
+ }
+ }, [close, conversation, onDeleteConversation]);
+
+ return (
+ <ConfirmDialog
+ open={conversation !== null}
+ onOpenChange={(open) => {
+ if (!open) {
+ close();
+ }
+ }}
+ title="Delete conversation"
+ description="This removes the conversation from your recent conversations. This action cannot be undone."
+ confirmLabel="Delete conversation"
+ loading={isDeletingConversation}
+ onConfirm={deleteConversation}
+ />
+ );
+}
export const InAppAiAgentButton = () => {
const { organization } = useQueryProjectOrOrganization();
- const { isAvailable, open, setOpen, isExpanded, setIsExpanded } =
- useInAppAiAgent();
+ const {
+ deleteConversation,
+ isAvailable,
+ open,
+ setOpen,
+ isExpanded,
+ setIsExpanded,
+ } = useInAppAiAgent();
const hasInAppAgentEntitlement = useHasEntitlement("in-app-agent");
const { setOpen: setSupportDrawerOpen } = useSupportDrawer();
const buttonRef = useRef<HTMLButtonElement>(null);
@@ -102,35 +152,50 @@ export const InAppAiAgentButton = () => {
Assistant
</SidebarMenuButton>
{open ? (
- // The assistant window lives in the `agent` overlay layer — a
- // <body>-level layer container that floats above page content but below
- // every transient overlay (dropdowns, dialogs, popovers, tooltips,
- // toasts) by DOM order alone. No z-index: layer ORDER stacks it (see
- // components/ui/layer.tsx). This replaces the old body portal + z-51,
- // which fought the nav-user dropdown's z-60 at <body> level.
- <Layer name="agent">
- <InAppAgentWindowShell
- floatingPanelHandle={floatingPanelHandle}
- isExpanded={isExpanded}
- panelRef={panelRef}
- >
- {({ isHeaderDragHandleEnabled }) => (
- <ControlledInAppAgentWindow
- isHeaderDragHandleEnabled={isHeaderDragHandleEnabled}
+ <DialogController<InAppAgentWindowConversation>
+ dialog={(close, conversation) => (
+ <DeleteConversationDialog
+ close={close}
+ conversation={conversation}
+ onDeleteConversation={deleteConversation}
+ />
+ )}
+ >
+ {(deleteConversationDialog) => (
+ // The assistant window lives in the `agent` overlay layer — a
+ // <body>-level layer container that floats above page content but below
+ // every transient overlay (dropdowns, dialogs, popovers, tooltips,
+ // toasts) by DOM order alone. No z-index: layer ORDER stacks it (see
+ // components/ui/layer.tsx). This replaces the old body portal + z-51,
+ // which fought the nav-user dropdown's z-60 at <body> level.
+ <Layer name="agent">
+ <InAppAgentWindowShell
+ floatingPanelHandle={floatingPanelHandle}
isExpanded={isExpanded}
- onExpandedChange={(nextIsExpanded) => {
- previousPanelRectRef.current =
- panelRef.current?.getBoundingClientRect() ?? null;
- setIsExpanded(nextIsExpanded);
- }}
- onClose={() => {
- floatingPanelHandle.clearGeometry();
- setOpen(false);
- }}
- />
- )}
- </InAppAgentWindowShell>
- </Layer>
+ panelRef={panelRef}
+ >
+ {({ isHeaderDragHandleEnabled }) => (
+ <ControlledInAppAgentWindow
+ isHeaderDragHandleEnabled={isHeaderDragHandleEnabled}
+ isExpanded={isExpanded}
+ onDeleteConversation={(conversation) =>
+ deleteConversationDialog.open(conversation)
+ }
+ onExpandedChange={(nextIsExpanded) => {
+ previousPanelRectRef.current =
+ panelRef.current?.getBoundingClientRect() ?? null;
+ setIsExpanded(nextIsExpanded);
+ }}
+ onClose={() => {
+ floatingPanelHandle.clearGeometry();
+ setOpen(false);
+ }}
+ />
+ )}
+ </InAppAgentWindowShell>
+ </Layer>
+ )}
+ </DialogController>
) : null}
<Dialog open={enableDialogOpen} onOpenChange={setEnableDialogOpen}>
<DialogContent>
diff --git a/web/src/components/ui/dialog-controller.tsx b/web/src/components/ui/dialog-controller.tsx
new file mode 100644
index 0000000000..6a311a6ece
--- /dev/null
+++ b/web/src/components/ui/dialog-controller.tsx
@@ -0,0 +1,22 @@
+"use client";
+
+import { type ReactNode, useCallback, useState } from "react";
+
+export function DialogController<T>({
+ children,
+ dialog,
+}: {
+ children: (control: { open: (value: T) => void }) => ReactNode;
+ dialog: (close: () => void, value: T | null) => ReactNode;
+}) {
+ const [value, setValue] = useState<T | null>(null);
+ const open = useCallback((nextValue: T) => setValue(nextValue), []);
+ const close = useCallback(() => setValue(null), []);
+
+ return (
+ <>
+ {dialog(close, value)}
+ {children({ open })}
+ </>
+ );
+}
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 6b54a2c1c0..d21dc43a76 100644
--- a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
+++ b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
@@ -2,12 +2,14 @@
import { useMemo } from "react";
import { InAppAgentWindow } from "./InAppAgentWindow";
+import type { InAppAgentWindowConversation } from "./InAppAgentWindow";
import { useInAppAiAgent } from "./InAppAiAgentProvider";
import { getDrawerMessages } from "./utils/utils";
type ControlledInAppAgentWindowBaseProps = {
isHeaderDragHandleEnabled?: boolean;
isExpanded: boolean;
+ onDeleteConversation: (conversation: InAppAgentWindowConversation) => void;
onExpandedChange: (isExpanded: boolean) => void;
};
@@ -66,6 +68,7 @@ export function ControlledInAppAgentWindow(
isLoadingMoreConversations={isLoadingMoreConversations}
selectedConversationId={selectedConversationId}
onLoadMoreConversations={loadMoreConversations}
+ onDeleteConversation={props.onDeleteConversation}
onSelectConversation={selectConversation}
onNewConversation={() => selectConversation(null)}
onExpandedChange={props.onExpandedChange}
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 45d60bebbc..5846506eb8 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
@@ -430,6 +430,7 @@ const meta = preview.meta({
hasMoreConversations: false,
isLoadingMoreConversations: false,
selectedConversationId: undefined,
+ onDeleteConversation: fn(),
onLoadMoreConversations: fn(),
onNewConversation: fn(),
onSelectConversation: fn(),
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 f6fc875aa9..6f68cb9190 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
@@ -9,6 +9,7 @@ import {
Minus,
Plus,
SendHorizontal,
+ Trash2,
} from "lucide-react";
import { Button } from "@/src/components/ui/button";
import {
@@ -94,6 +95,7 @@ export type InAppAgentWindowProps = {
isLoadingMoreConversations: boolean;
messages: InAppAgentWindowMessage[];
onExpandedChange: (isExpanded: boolean) => void;
+ onDeleteConversation: (conversation: InAppAgentWindowConversation) => void;
onLoadMoreConversations: () => void;
onNewConversation: () => void;
onSelectConversation: (conversationId: string) => void;
@@ -117,6 +119,7 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
isInputDisabled,
isLoadingMoreConversations,
messages,
+ onDeleteConversation,
onExpandedChange,
onLoadMoreConversations,
onNewConversation,
@@ -130,6 +133,8 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
const previousScrollTopRef = useRef(0);
const inputRef = useRef<HTMLTextAreaElement>(null);
const [input, setInput] = useState("");
+ const [isConversationHistoryOpen, setIsConversationHistoryOpen] =
+ useState(false);
const hasUserMessage = messages.some((message) => message.role === "user");
const submitInput = (content: string) => {
@@ -222,7 +227,10 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
</TooltipTrigger>
<TooltipContent>Start new conversation</TooltipContent>
</Tooltip>
- <DropdownMenu>
+ <DropdownMenu
+ open={isConversationHistoryOpen}
+ onOpenChange={setIsConversationHistoryOpen}
+ >
<Tooltip delayDuration={100} disableHoverableContent>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
@@ -255,13 +263,31 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
<DropdownMenuItem
key={conversation.id}
className={cn(
- "truncate",
+ "flex items-center gap-1",
conversation.id === selectedConversationId &&
"bg-accent text-accent-foreground",
)}
onSelect={() => onSelectConversation(conversation.id)}
>
- {conversation.title?.trim() || "Untitled conversation"}
+ <span className="min-w-0 flex-1 truncate">
+ {conversation.title?.trim() || "Untitled conversation"}
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="text-muted-foreground hover:text-destructive -mr-1.5 shrink-0"
+ disabled={isInputDisabled}
+ aria-label="Delete conversation"
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setIsConversationHistoryOpen(false);
+ onDeleteConversation(conversation);
+ }}
+ >
+ <Trash2 className="size-3" />
+ </Button>
</DropdownMenuItem>
))
)}
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 cc273fddb5..2bbf78f052 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
@@ -67,6 +67,7 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {
selectedConversationId: undefined,
loadMoreConversations: () => undefined,
selectConversation: () => undefined,
+ deleteConversation: async () => undefined,
submit: async () => false,
submitFeedback: async () => undefined,
};
@@ -101,6 +102,7 @@ type InAppAiAgentContextType = {
selectedConversationId: string | undefined;
loadMoreConversations: () => void;
selectConversation: (conversationId: string | null) => void;
+ deleteConversation: (conversationId: string) => Promise<void>;
submit: (content: string) => Promise<boolean>;
submitFeedback: (params: {
messageId: string;
@@ -217,6 +219,8 @@ function InAppAiAgentProviderInner({
enabled: open && Boolean(selectedConversationId) && !isSubmitting,
},
);
+ const deleteConversationMutation =
+ api.inAppAgent.deleteConversation.useMutation();
const feedbackMutation = api.inAppAgent.submitFeedback.useMutation();
const conversations = useMemo(
@@ -492,6 +496,61 @@ function InAppAiAgentProviderInner({
[isRunning, resetAgent, selectedConversationId, setSelectedConversationId],
);
+ const deleteConversation = useCallback(
+ async (conversationId: string) => {
+ if (isRunning) {
+ return;
+ }
+
+ try {
+ await deleteConversationMutation.mutateAsync({
+ projectId,
+ conversationId,
+ });
+
+ if (conversationId === selectedConversationId) {
+ resetAgent();
+ setMessages([]);
+ setSelectedConversationId(null);
+ }
+
+ setFeedbackByConversationId((currentFeedback) => {
+ if (!currentFeedback[conversationId]) {
+ return currentFeedback;
+ }
+
+ const nextFeedback = { ...currentFeedback };
+ delete nextFeedback[conversationId];
+ return nextFeedback;
+ });
+
+ await Promise.all([
+ utils.inAppAgent.listConversations.invalidate({ projectId }),
+ utils.inAppAgent.getConversation.invalidate({
+ projectId,
+ conversationId,
+ }),
+ ]);
+ } catch (error) {
+ const errorMessage = getAgentErrorMessage(error);
+ showErrorToast("Failed to delete conversation", errorMessage);
+ console.error("Failed to delete in-app agent conversation", error);
+ throw error;
+ }
+ },
+ [
+ deleteConversationMutation,
+ isRunning,
+ projectId,
+ resetAgent,
+ selectedConversationId,
+ setFeedbackByConversationId,
+ setSelectedConversationId,
+ utils.inAppAgent.getConversation,
+ utils.inAppAgent.listConversations,
+ ],
+ );
+
const submit = useCallback(
async (content: string) => {
if (
@@ -659,6 +718,7 @@ function InAppAiAgentProviderInner({
selectedConversationId: selectedConversationId ?? undefined,
loadMoreConversations,
selectConversation,
+ deleteConversation,
submit,
submitFeedback,
}),
@@ -671,6 +731,7 @@ function InAppAiAgentProviderInner({
isRunning,
isSelectedConversationHydrating,
isSubmitting,
+ deleteConversation,
loadMoreConversations,
messagesWithFeedback,
open,
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 30d9e1983d..acfe56e447 100644
--- a/web/src/ee/features/in-app-agent/server/router.ts
+++ b/web/src/ee/features/in-app-agent/server/router.ts
@@ -127,6 +127,33 @@ export const inAppAgentRouter = createTRPCRouter({
};
}),
+ deleteConversation: protectedProjectProcedureWithoutTracing
+ .input(ConversationIdInput)
+ .mutation(async ({ ctx, input }) => {
+ await assertInAppAgentAvailable({ ctx, projectId: input.projectId });
+
+ await getOwnedConversationOrThrow({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ conversationId: input.conversationId,
+ userId: ctx.session.user.id,
+ });
+
+ await ctx.prisma.inAppAgentConversation.update({
+ where: {
+ id_projectId: {
+ id: input.conversationId,
+ projectId: input.projectId,
+ },
+ },
+ data: {
+ deletedAt: new Date(),
+ },
+ });
+
+ return { success: true };
+ }),
+
submitFeedback: protectedProjectProcedureWithoutTracing
.input(SubmitFeedbackInput)
.mutation(async ({ ctx, input }) => {