:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(posthog-ai): Allow users to delete Posthog AI conversations (#59850)
Jordan Mryyan6c25e8fc80da
diff --git a/ee/api/conversation.py b/ee/api/conversation.pyindex 1b2f75f403f1..3e78a39fab60 100644--- a/ee/api/conversation.py+++ b/ee/api/conversation.py@@ -7,6 +7,7 @@ from typing import castfrom django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.http import StreamingHttpResponse+from django.utils import timezoneimport pydanticimport structlog@@ -18,7 +19,7 @@ from prometheus_client import Histogramfrom rest_framework import exceptions, serializers, statusfrom rest_framework.decorators import actionfrom rest_framework.exceptions import Throttled-from rest_framework.mixins import ListModelMixin, RetrieveModelMixin+from rest_framework.mixins import DestroyModelMixin, ListModelMixin, RetrieveModelMixinfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.viewsets import GenericViewSet@@ -186,7 +187,9 @@ class QueueMessageUpdateSerializer(serializers.Serializer):@extend_schema(tags=["max"])-class ConversationViewSet(TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMixin, GenericViewSet):+class ConversationViewSet(+ TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMixin, DestroyModelMixin, GenericViewSet+):scope_object = "conversation"serializer_class = ConversationSerializerqueryset = Conversation.objects.all()@@ -203,7 +206,7 @@ class ConversationViewSet(TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMdef _ensure_queue_access(self, request: Request, conversation_id: str) -> Response | None:try:# nosemgrep: idor-lookup-without-team (instance scoped to team via get_queryset)- conversation = Conversation.objects.get(id=conversation_id)+ conversation = Conversation.objects.exclude(deleted=True).get(id=conversation_id)except Conversation.DoesNotExist:return Response({"error": "Conversation not found"}, status=status.HTTP_404_NOT_FOUND)if conversation.user != request.user or conversation.team != self.team:@@ -214,7 +217,7 @@ class ConversationViewSet(TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMreturn Response({"messages": queue, "max_queue_messages": queue_store.max_messages})def safely_get_queryset(self, queryset):- queryset = queryset.select_related("user")+ queryset = queryset.select_related("user").exclude(deleted=True)# Only single retrieval of a specific conversation is allowed for other users' conversations (if ID known)if self.action != "retrieve":@@ -250,7 +253,7 @@ class ConversationViewSet(TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMconversation_id = request.data.get("conversation")if conversation_id:try:- conversation = Conversation.objects.get(id=conversation_id, team=self.team)+ conversation = Conversation.objects.exclude(deleted=True).get(id=conversation_id, team=self.team)if conversation.type == Conversation.Type.DEEP_RESEARCH:return Trueexcept (Conversation.DoesNotExist, ValidationError):@@ -347,6 +350,8 @@ class ConversationViewSet(TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMreturn Response({"error": "Cannot access other users' conversations"}, status=status.HTTP_400_BAD_REQUEST)+ if conversation.deleted:+ return Response({"error": "Conversation does not exist"}, status=status.HTTP_404_NOT_FOUND)except Conversation.DoesNotExist:# Conversation doesn't exist, create it if we have a messageif not has_message:@@ -583,6 +588,15 @@ class ConversationViewSet(TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMreturn Response(status=status.HTTP_204_NO_CONTENT)+ @extend_schema(+ description="Delete a conversation.",+ responses={204: None},+ )+ def destroy(self, request: Request, *args, **kwargs) -> Response:+ instance: Conversation = self.get_object()+ Conversation.objects.filter(pk=instance.pk).update(deleted=True, deleted_at=timezone.now())+ return Response(status=status.HTTP_204_NO_CONTENT)+@action(detail=True, methods=["POST"], url_path="append_message")def append_message(self, request: Request, *args, **kwargs):"""diff --git a/ee/api/test/test_conversation.py b/ee/api/test/test_conversation.pyindex d20afbba4f49..94bc3f1d5d9a 100644--- a/ee/api/test/test_conversation.py+++ b/ee/api/test/test_conversation.py@@ -1153,3 +1153,95 @@ class TestConversation(APIBaseTest):workflow_inputs = mock_astream.call_args[0][1]self.assertIsNotNone(workflow_inputs.billing_context.spend_history)self.assertEqual(len(workflow_inputs.billing_context.spend_history), 20)+++class TestConversationSoftDelete(APIBaseTest):+ def _make_conversation(self, **overrides) -> Conversation:+ defaults: dict[str, Any] = {+ "user": self.user,+ "team": self.team,+ "title": "A chat",+ "type": Conversation.Type.ASSISTANT,+ }+ defaults.update(overrides)+ return Conversation.objects.create(**defaults)++ def test_delete_marks_row_soft_deleted(self):+ conversation = self._make_conversation()++ before = timezone.now()+ response = self.client.delete(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/",+ )+ after = timezone.now()++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ refreshed = Conversation.objects.get(pk=conversation.pk)+ self.assertTrue(refreshed.deleted)+ assert refreshed.deleted_at is not None+ self.assertGreaterEqual(refreshed.deleted_at, before)+ self.assertLessEqual(refreshed.deleted_at, after)++ def test_delete_other_users_conversation_returns_404(self):+ other_user = User.objects.create_and_join(+ organization=self.organization,+ email="[email protected]",+ password="password",+ first_name="Other",+ )+ conversation = self._make_conversation(user=other_user)++ response = self.client.delete(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/",+ )++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ refreshed = Conversation.objects.get(pk=conversation.pk)+ self.assertFalse(refreshed.deleted)++ def test_delete_already_deleted_returns_404(self):+ conversation = self._make_conversation(deleted=True, deleted_at=timezone.now())++ response = self.client.delete(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/",+ )++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_list_excludes_soft_deleted(self):+ kept = self._make_conversation(title="kept")+ self._make_conversation(title="gone", deleted=True, deleted_at=timezone.now())++ with patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock):+ response = self.client.get(f"/api/environments/{self.team.id}/conversations/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ ids = [c["id"] for c in response.json()["results"]]+ self.assertEqual(ids, [str(kept.id)])++ def test_retrieve_soft_deleted_returns_404(self):+ conversation = self._make_conversation(deleted=True, deleted_at=timezone.now())++ with patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock):+ response = self.client.get(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/",+ )++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_create_with_deleted_id_does_not_resurrect(self):+ conversation = self._make_conversation(deleted=True, deleted_at=timezone.now())++ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/",+ {+ "content": "hello",+ "trace_id": str(uuid.uuid4()),+ "conversation": str(conversation.id),+ },+ )++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ still_deleted = Conversation.objects.get(pk=conversation.pk)+ self.assertTrue(still_deleted.deleted)+ self.assertEqual(Conversation.objects.filter(pk=conversation.pk).count(), 1)diff --git a/ee/migrations/0044_conversation_deleted_conversation_deleted_at.py b/ee/migrations/0044_conversation_deleted_conversation_deleted_at.pynew file mode 100644index 000000000000..ed596ec89211--- /dev/null+++ b/ee/migrations/0044_conversation_deleted_conversation_deleted_at.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.14 on 2026-05-23 22:25++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("ee", "0043_teamsessionsummariesconfig_custom_tags"),+ ]++ operations = [+ migrations.AddField(+ model_name="conversation",+ name="deleted",+ field=models.BooleanField(blank=True, default=False, null=True),+ ),+ migrations.AddField(+ model_name="conversation",+ name="deleted_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/ee/migrations/max_migration.txt b/ee/migrations/max_migration.txtindex 62e1e1129baf..ec53f3ad0119 100644--- a/ee/migrations/max_migration.txt+++ b/ee/migrations/max_migration.txt@@ -1 +1 @@-0043_teamsessionsummariesconfig_custom_tags+0044_conversation_deleted_conversation_deleted_atdiff --git a/ee/models/assistant.py b/ee/models/assistant.pyindex d10d11facfd8..d7f1c287bd1b 100644--- a/ee/models/assistant.py+++ b/ee/models/assistant.py@@ -19,7 +19,7 @@ def generate_short_id():return "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(4))-class Conversation(UUIDTModel):+class Conversation(UUIDTModel, DeletedMetaFields):TITLE_MAX_LENGTH = 250class Meta:diff --git a/frontend/src/scenes/max/ConversationHistory.tsx b/frontend/src/scenes/max/ConversationHistory.tsxindex bd1863babfe6..6dead4c7bc49 100644--- a/frontend/src/scenes/max/ConversationHistory.tsx+++ b/frontend/src/scenes/max/ConversationHistory.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { combineUrl } from 'kea-router'-import { IconExternal, IconPlus } from '@posthog/icons'+import { IconExternal, IconPlus, IconTrash } from '@posthog/icons'import { LemonButton, LemonSkeleton, LemonTag, Link, Spinner } from '@posthog/lemon-ui'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'@@ -11,6 +11,7 @@ import { userLogic } from 'scenes/userLogic'import { ProductKey } from '~/queries/schema/schema-general'import { Conversation, ConversationStatus, ConversationType } from '~/types'+import { openDeleteConversationDialog } from './conversationDialogs'import { maxLogic } from './maxLogic'import { formatConversationDate, getSlackThreadUrl } from './utils'@@ -21,7 +22,7 @@ export interface ConversationHistoryProps {export function ConversationHistory({ sidePanel = false, compact = false }: ConversationHistoryProps): JSX.Element {const { conversationHistory, conversationHistoryLoading, conversationId } = useValues(maxLogic)- const { toggleConversationHistory, openConversation } = useActions(maxLogic)+ const { toggleConversationHistory, openConversation, deleteConversation } = useActions(maxLogic)const { updateHasSeenProductIntroFor } = useActions(userLogic)if (compact) {@@ -63,6 +64,7 @@ export function ConversationHistory({ sidePanel = false, compact = false }: Convconversation={conversation}openConversation={openConversation}sidePanel={sidePanel}+ deleteConversation={deleteConversation}/>))) : conversationHistoryLoading ? (@@ -108,9 +110,15 @@ interface ConversationCardProps {conversation: ConversationopenConversation: (conversationId: string) => voidsidePanel: boolean+ deleteConversation: (conversationId: string) => void}-function ConversationCard({ conversation, openConversation, sidePanel }: ConversationCardProps): JSX.Element {+function ConversationCard({+ conversation,+ openConversation,+ sidePanel,+ deleteConversation,+}: ConversationCardProps): JSX.Element {return (<LinkclassName="p-4 flex flex-row bg-surface-primary rounded-lg gap-2 w-full min-h-14 items-center justify-between"@@ -123,7 +131,7 @@ function ConversationCard({ conversation, openConversation, sidePanel }: Convers}}}>- <div className="flex items-center gap-2">+ <div className="flex items-center gap-2 flex-1 min-w-0"><span className="flex-1 line-clamp-1">{conversation.title}</span>{conversation.is_internal && <LemonTag type="muted">Impersonated</LemonTag>}{conversation.type === ConversationType.DeepResearch && <LemonTag>Research</LemonTag>}@@ -141,11 +149,25 @@ function ConversationCard({ conversation, openConversation, sidePanel }: Convers</LemonTag>)}</div>- {conversation.status === ConversationStatus.InProgress ? (- <Spinner className="h-4 w-4" />- ) : (- <span className="text-secondary">{formatConversationDate(conversation.updated_at)}</span>- )}+ <div className="flex items-center gap-2 shrink-0">+ {conversation.status === ConversationStatus.InProgress ? (+ <Spinner className="h-4 w-4" />+ ) : (+ <span className="text-secondary">{formatConversationDate(conversation.updated_at)}</span>+ )}+ <LemonButton+ size="small"+ icon={<IconTrash />}+ status="danger"+ data-attr="max-conversation-delete"+ aria-label="Delete chat"+ onClick={(e) => {+ e.preventDefault()+ e.stopPropagation()+ openDeleteConversationDialog(() => deleteConversation(conversation.id))+ }}+ />+ </div></Link>)}diff --git a/frontend/src/scenes/max/components/List/AiChatListItem.tsx b/frontend/src/scenes/max/components/List/AiChatListItem.tsxindex 885575a90ddf..bad228dc42e2 100644--- a/frontend/src/scenes/max/components/List/AiChatListItem.tsx+++ b/frontend/src/scenes/max/components/List/AiChatListItem.tsx@@ -1,7 +1,7 @@import { useActions } from 'kea'import { combineUrl } from 'kea-router'-import { IconMessage, IconOpenSidebar, IconShare } from '@posthog/icons'+import { IconMessage, IconOpenSidebar, IconShare, IconTrash } from '@posthog/icons'import { Spinner } from '@posthog/lemon-ui'import { Link } from 'lib/lemon-ui/Link'@@ -14,6 +14,7 @@ import { urls } from 'scenes/urls'import { BrowserLikeMenuItems } from '~/layout/panel-layout/ProjectTree/menus/BrowserLikeMenuItems'import { ConversationStatus } from '~/types'+import { openDeleteConversationDialog } from '../../conversationDialogs'import { maxGlobalLogic } from '../../maxGlobalLogic'import { formatConversationDate } from '../../utils'@@ -48,7 +49,7 @@ function Content({}function Actions({ conversationId }: { conversationId: string }): JSX.Element {- const { openSidePanelMax } = useActions(maxGlobalLogic)+ const { openSidePanelMax, deleteConversation } = useActions(maxGlobalLogic)return (<LinkListItem.Actions>@@ -79,6 +80,16 @@ function Actions({ conversationId }: { conversationId: string }): JSX.Element {Open in context panel</ButtonPrimitive></DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem asChild>+ <ButtonPrimitive+ menuItem+ onClick={() => openDeleteConversationDialog(() => deleteConversation(conversationId))}+ >+ <IconTrash className="size-4 text-danger" />+ <span className="text-danger">Delete chat</span>+ </ButtonPrimitive>+ </DropdownMenuItem></DropdownMenuGroup></LinkListItem.Actions>)diff --git a/frontend/src/scenes/max/conversationDialogs.tsx b/frontend/src/scenes/max/conversationDialogs.tsxnew file mode 100644index 000000000000..a55a659a54ee--- /dev/null+++ b/frontend/src/scenes/max/conversationDialogs.tsx@@ -0,0 +1,14 @@+import { LemonDialog } from '@posthog/lemon-ui'++export function openDeleteConversationDialog(onConfirm: () => void): void {+ LemonDialog.open({+ title: 'Delete chat?',+ description: 'The chat will be removed from your history.',+ primaryButton: {+ children: 'Delete',+ status: 'danger',+ onClick: onConfirm,+ },+ secondaryButton: { children: 'Cancel' },+ })+}diff --git a/frontend/src/scenes/max/maxGlobalLogic.tsx b/frontend/src/scenes/max/maxGlobalLogic.tsxindex f39d7e2c14a1..102888fb051e 100644--- a/frontend/src/scenes/max/maxGlobalLogic.tsx+++ b/frontend/src/scenes/max/maxGlobalLogic.tsx@@ -10,11 +10,14 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { newInternalTab } from 'lib/utils/newInternalTab'import { organizationLogic } from 'scenes/organizationLogic'import { sceneLogic } from 'scenes/sceneLogic'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { Conversation, ConversationDetail, SidePanelTab } from '~/types'+import { conversationsDestroy } from 'products/conversations/frontend/generated/api'+import { TOOL_DEFINITIONS, ToolRegistration } from './max-constants'import type { maxGlobalLogicType } from './maxGlobalLogicType'import { maxLogic, mergeConversationHistory, mergeConversations } from './maxLogic'@@ -80,6 +83,8 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([['currentOrganization'],sceneLogic,['sceneId', 'sceneConfig'],+ teamLogic,+ ['currentTeamIdStrict'],featureFlagLogic,['featureFlags'],sidePanelStateLogic,@@ -94,6 +99,7 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([registerTool: (tool: ToolRegistration) => ({ tool }),deregisterTool: (key: string) => ({ key }),prependOrReplaceConversation: (conversation: ConversationDetail | Conversation) => ({ conversation }),+ deleteConversation: (id: string) => ({ id }),dismissLiabilityNotice: true,dismissDataProcessing: true,}),@@ -195,6 +201,22 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([loadConversationHistoryFailure: ({ errorObject }) => {lemonToast.error(errorObject?.data?.detail || 'Failed to load conversation history.')},+ deleteConversation: async ({ id }) => {+ try {+ await conversationsDestroy(String(values.currentTeamIdStrict), id)+ if (values.currentConversationId === id) {+ router.actions.push(urls.aiHistory())+ }+ for (const logic of maxLogic.findAllMounted()) {+ if (logic.values.conversationId === id) {+ logic.actions.startNewConversation()+ }+ }+ actions.loadConversationHistory()+ } catch {+ lemonToast.error('Failed to delete chat')+ }+ },})),afterMount(({ actions }) => {actions.loadConversationHistory()diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsxindex 9cf79c852b7a..e957d2015dde 100644--- a/frontend/src/scenes/max/maxLogic.tsx+++ b/frontend/src/scenes/max/maxLogic.tsx@@ -166,7 +166,12 @@ export const maxLogic = kea<maxLogicType>([maxContextLogic,['resetContext'],maxGlobalLogic,- ['loadConversationHistory', 'prependOrReplaceConversation', 'loadConversationHistorySuccess'],+ [+ 'loadConversationHistory',+ 'prependOrReplaceConversation',+ 'loadConversationHistorySuccess',+ 'deleteConversation',+ ],tabUiStateLogic,['setChatDraftForTab'],],diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex 6e1b442f7606..d0ba286a2719 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -111,6 +111,24 @@ export const conversationsRetrieve = async (})}+export const getConversationsDestroyUrl = (projectId: string, conversation: string) => {+ return `/api/environments/${projectId}/conversations/${conversation}/`+}++/**+ * Delete a conversation.+ */+export const conversationsDestroy = async (+ projectId: string,+ conversation: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getConversationsDestroyUrl(projectId, conversation), {+ ...options,+ method: 'DELETE',+ })+}+export const getConversationsAppendMessageCreateUrl = (projectId: string, conversation: string) => {return `/api/environments/${projectId}/conversations/${conversation}/append_message/`}diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yamlindex d45ee339914e..8fe9b01d5c0e 100644--- a/products/conversations/mcp/tools.yaml+++ b/products/conversations/mcp/tools.yaml@@ -18,6 +18,9 @@ tools:conversations-create:operation: conversations_createenabled: false+ conversations-destroy:+ operation: conversations_destroy+ enabled: falseconversations-list:operation: conversations_listenabled: false