: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
feat(posthog-ai): mirror LangGraph conversations into tasks after each turn (#98936)
Jake Ruth8649c104d9c7
diff --git a/ee/api/conversation.py b/ee/api/conversation.pyindex c9579729bf5c..c728e79ba1f6 100644--- a/ee/api/conversation.py+++ b/ee/api/conversation.py@@ -52,10 +52,7 @@ from posthog.temporal.ai.research_agent import (ResearchAgentWorkflowInputs,)-from products.posthog_ai.backend.context_wrapper import (- ALLOWED_TYPES as ALLOWED_ATTACHED_CONTEXT_TYPES,- ContextService,-)+from products.posthog_ai.backend.context_wrapper import ALLOWED_TYPES as ALLOWED_ATTACHED_CONTEXT_TYPESfrom products.posthog_ai.backend.message_routing import SandboxSessionfrom products.posthog_ai.backend.models.assistant import Conversationfrom products.tasks.backend.facade import api as tasks_facade@@ -330,8 +327,11 @@ class ConversationViewSet(if self.action != "retrieve":queryset = queryset.filter(user=self.request.user)else:+ # A LangGraph conversation stays readable by link even once the mirror has linked a task+ # to it: the task is a copy, not the source, and must not narrow who can read the chat.queryset = queryset.filter(Q(task_id__isnull=True)+ | Q(agent_runtime=Conversation.AgentRuntime.LANGGRAPH)| (Q(task__team_id=self.team_id, task__deleted=False)& tasks_facade.visible_tasks_q(self.request.user.id, relation="task")@@ -734,21 +734,15 @@ class ConversationViewSet(if conversation.task_id is not None:_validate_sandbox_task(conversation.task_id, self.team.id, request.user.id)- has_content = bool(serializer.validated_data.get("content"))- convert_to_acp, resumed_context = self._compute_sandbox_conversion(request, conversation, has_content)-- # Sandbox-only endpoint. A converting LangGraph thread is still LANGGRAPH here (the flip happens- # inside the routing service), so allow it through; reject any other non-sandbox conversation.- if conversation.agent_runtime != Conversation.AgentRuntime.SANDBOX and not convert_to_acp:+ if conversation.agent_runtime != Conversation.AgentRuntime.SANDBOX:raise exceptions.ValidationError("This conversation is not on the sandbox runtime.")+ has_content = bool(serializer.validated_data.get("content"))if has_content and conversation.title is None:conversation.title = serializer.validated_data["content"][:80]conversation.save(update_fields=["title"])- return self._route_sandbox_message(- request, conversation, resumed_context=resumed_context, convert_to_acp=convert_to_acp, created=created- )+ return self._route_sandbox_message(request, conversation, created=created)def _get_or_create_sandbox_conversation(self, request: Request, *, bind_task: uuid.UUID | None = None@@ -791,35 +785,6 @@ class ConversationViewSet(raise exceptions.NotFound("Conversation does not exist")return conversation, False- def _compute_sandbox_conversion(- self, request: Request, conversation: Conversation, has_content: bool- ) -> tuple[bool, str | None]:- """Detect + prepare a legacy LangGraph→sandbox conversion on the first new message.-- A reopened LangGraph thread converts to sandbox on its first message: read the current- conversation window into a one-time resumed-context block (while still LangGraph), then the- routing service flips the runtime + links the Task atomically. Warm (`content`-less) never- converts. A failed read never blocks — the user continues, the legacy thread stays rendered.- """- convert_to_acp = bool(- has_content- and conversation.agent_runtime == Conversation.AgentRuntime.LANGGRAPH- and conversation.task_id is None- and conversation.status == Conversation.Status.IDLE- and has_sandbox_mode_feature_flag(self.team, cast(User, request.user))- )- if not convert_to_acp:- return False, None- try:- resumed_context = asgi_async_to_sync(ContextService().abuild_resumed_legacy_context)(- conversation, self.team, cast(User, request.user)- )- except Exception as e:- # A failed read must not block the conversion — continue with no resumed context.- capture_exception(e)- resumed_context = None- return True, resumed_context-def _auto_route_repository(self, request: Request, conversation: Conversation, user: User) -> str | None:"""Auto-select the repository a sandbox conversation's first message is about.@@ -842,15 +807,11 @@ class ConversationViewSet(request: Request,conversation: Conversation,*,- resumed_context: str | None = None,- convert_to_acp: bool = False,created: bool = False,) -> Response:user = cast(User, request.user)repository = self._auto_route_repository(request, conversation, user)- result = SandboxSession(conversation, user).open(- request.data, resumed_context=resumed_context, convert_to_acp=convert_to_acp, repository=repository- )+ result = SandboxSession(conversation, user).open(request.data, repository=repository)if result is None:# Warm intent that provisioned nothing (pool full / released) — no run to open. Drop the# row if we created it this request so a content-less warm can't leave orphaned conversations.@@ -867,7 +828,6 @@ class ConversationViewSet("conversation_id": str(conversation.id),"execution_type": "sandbox","agent_runtime": "sandbox",- "converted_to_acp": convert_to_acp,"just_created_run": result.just_created_run,"has_attached_context": result.attached_context_count > 0,"attached_context_count": result.attached_context_count,@@ -916,6 +876,9 @@ class ConversationViewSet(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())+ if instance.task_id is not None:+ # The task is the chat's other representation; a deleted chat must not stay readable there.+ tasks_facade.soft_delete_task(instance.task_id, self.team_id, cast(User, request.user).id)return Response(status=status.HTTP_204_NO_CONTENT)@action(detail=True, methods=["POST"], url_path="append_message")diff --git a/ee/api/tests/test_conversation.py b/ee/api/tests/test_conversation.pyindex 96a3537a2fd3..ec4a75330217 100644--- a/ee/api/tests/test_conversation.py+++ b/ee/api/tests/test_conversation.py@@ -584,6 +584,18 @@ class TestConversation(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["id"], str(conversation.id))+ # The mirror links a private task to the chat; a LangGraph chat stays readable by link anyway.+ private_task = Task.objects.create(+ team=self.team,+ title="copy",+ description="",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.other_user,+ )+ Conversation.objects.filter(id=conversation.id).update(task=private_task)+ response = self.client.get(f"/api/environments/{self.team.id}/conversations/{conversation.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+def test_retrieve_other_teams_conversation_fails(self):"""Test that user cannot retrieve conversation from another team"""conversation = Conversation.objects.create(@@ -1213,6 +1225,21 @@ class TestConversationSoftDelete(APIBaseTest):self.assertGreaterEqual(refreshed.deleted_at, before)self.assertLessEqual(refreshed.deleted_at, after)+ def test_delete_also_soft_deletes_the_linked_task(self):+ task = Task.objects.create(+ team=self.team,+ title="copy",+ description="",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ conversation = self._make_conversation(task=task)++ response = self.client.delete(f"/api/environments/{self.team.id}/conversations/{conversation.id}/")++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertTrue(Task.objects.get(pk=task.pk).deleted)+def test_delete_other_users_conversation_returns_404(self):other_user = User.objects.create_and_join(organization=self.organization,@@ -1833,8 +1860,8 @@ class TestConversationSandboxRoute(APIBaseTest):viewset.organization = self.organizationself.assertEqual(viewset.get_throttles(), [])- def test_open_rejects_langgraph_conversation_not_converting(self):- # A non-sandbox LangGraph conversation that isn't converting (no flag) is rejected.+ def test_open_rejects_langgraph_conversation(self):+ # The sandbox endpoint serves sandbox conversations only, whatever flags the user has.conversation = Conversation.objects.create(user=self.user,team=self.team,@@ -1843,7 +1870,7 @@ class TestConversationSandboxRoute(APIBaseTest):agent_runtime=Conversation.AgentRuntime.LANGGRAPH,)with (- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=False),+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),patch("ee.api.conversation.SandboxSession") as m_session,):response = self.client.post(@@ -1854,70 +1881,6 @@ class TestConversationSandboxRoute(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)m_session.assert_not_called()- def _idle_langgraph_conversation(self) -> Conversation:- return Conversation.objects.create(- user=self.user,- team=self.team,- title="A chat",- type=Conversation.Type.ASSISTANT,- agent_runtime=Conversation.AgentRuntime.LANGGRAPH,- status=Conversation.Status.IDLE,- )-- def test_open_converts_idle_langgraph_thread_on_first_message(self):- # A reopened idle LangGraph thread converts to sandbox on its first message via `open`:- # the legacy window is read into resumed_context and routed with convert_to_acp=True.- conversation = self._idle_langgraph_conversation()- block = "<posthog_context>This session was resumed from the legacy implementation.</posthog_context>"- sentinel = SandboxRouteResult(- task_id="t", run_id="r", trace_id=None, run_status="queued", just_created_run=True- )- with (- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),- patch("ee.api.conversation.ContextService") as m_ctx,- patch("ee.api.conversation.SandboxSession") as m_session,- patch("ee.api.conversation.report_user_action"),- ):- m_ctx.return_value.abuild_resumed_legacy_context = AsyncMock(return_value=block)- m_session.return_value.open.return_value = sentinel- response = self.client.post(- f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",- {"content": "convert me", "trace_id": str(uuid.uuid4())},- format="json",- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- kwargs = m_session.return_value.open.call_args.kwargs- self.assertTrue(kwargs["convert_to_acp"])- self.assertEqual(kwargs["resumed_context"], block)-- def test_open_conversion_context_read_failure_degrades(self):- # A failed legacy read must not block the conversion — route with convert_to_acp but no context.- conversation = self._idle_langgraph_conversation()- sentinel = SandboxRouteResult(- task_id="t", run_id="r", trace_id=None, run_status="queued", just_created_run=True- )- with (- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),- patch("ee.api.conversation.ContextService") as m_ctx,- patch("ee.api.conversation.SandboxSession") as m_session,- patch("ee.api.conversation.capture_exception") as m_capture,- patch("ee.api.conversation.report_user_action"),- ):- m_ctx.return_value.abuild_resumed_legacy_context = AsyncMock(side_effect=RuntimeError("boom"))- m_session.return_value.open.return_value = sentinel- response = self.client.post(- f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",- {"content": "convert me", "trace_id": str(uuid.uuid4())},- format="json",- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- m_capture.assert_called_once()- kwargs = m_session.return_value.open.call_args.kwargs- self.assertTrue(kwargs["convert_to_acp"])- self.assertIsNone(kwargs["resumed_context"])-@override_settings(DEBUG=False)def test_open_applies_ai_throttles(self):# `open` provisions a sandbox Run whether or not it carries a message, so it takes thediff --git a/ee/hogai/api/serializers.py b/ee/hogai/api/serializers.pyindex 02d8e354150b..ee912b5c0771 100644--- a/ee/hogai/api/serializers.py+++ b/ee/hogai/api/serializers.py@@ -56,24 +56,34 @@ class ConversationStateResult:interrupt_payloads: dict[str, dict[str, Any]]-async def aget_conversation_state(conversation: Conversation, team: Any, user: Any) -> ConversationStateResult:+async def aget_conversation_state(+ conversation: Conversation, team: Any, user: Any, *, raise_on_error: bool = False+) -> ConversationStateResult:"""Compile the LangGraph graph, replay the checkpoint, and validate the typed state.Single source of truth for the LangGraph history read path — both the conversation- serializer (history-load) and the legacy-history converter (products/posthog_ai) call this so+ serializer (history-load) and the conversation mirror (products/posthog_ai) call this sothe graph-compile + checkpoint-replay logic is never duplicated.Returns a ConversationStateResult. `state` is None for born-sandboxconversations (no checkpoint) and on any read/validation error — errors degrade gracefullyand are captured rather than raised so a bad checkpoint can't 500 a conversation load.+ `raise_on_error` re-raises read errors instead, for a caller that retries (the copy activity);+ unsupported content still comes back as a result, since a retry cannot fix it."""# Born-sandbox conversations have no LangGraph checkpoint — skip the graph compile entirely.- # A CONVERTED conversation (now sandbox, but kept its legacy checkpoint) falls through so its- # legacy thread still renders above the "history was converted" divider.+ # A conversation moved from LangGraph keeps its checkpoint, but its history is in the task's+ # import run, which the thread renders from the run log; reading the checkpoint too would show+ # every turn twice. Only a conversion that predates the mirror (no import run) still renders+ # its legacy thread above the "history was converted" divider.if conversation.agent_runtime == Conversation.AgentRuntime.SANDBOX:- has_checkpoint = await sync_to_async(conversation.checkpoints.exists)()- if not has_checkpoint:- return ConversationStateResult(state=None, has_unsupported_content=False, interrupt_payloads={})+ empty = ConversationStateResult(state=None, has_unsupported_content=False, interrupt_payloads={})+ if not await sync_to_async(conversation.checkpoints.exists)():+ return empty+ if conversation.task_id is not None and await sync_to_async(tasks_facade.get_imported_task_run)(+ conversation.task_id, conversation.team_id+ ):+ return emptytry:graph_class, state_class = CONVERSATION_TYPE_MAP[conversation.type] # type: ignore[index]@@ -104,6 +114,8 @@ async def aget_conversation_state(conversation: Conversation, team: Any, user: A)return ConversationStateResult(state=None, has_unsupported_content=True, interrupt_payloads={})except Exception as e:+ if raise_on_error:+ raise# Broad exception handler to gracefully degrade UI instead of 500s.# Captures all errors (context access, graph compilation, validation, etc.) to PostHog.capture_exception(@@ -296,9 +308,10 @@ class ConversationSerializer(ConversationMinimalSerializer):read_only=True,help_text=("Runtime that owns this conversation. 'langgraph' conversations return their messages "- "in the `messages` field; born-'sandbox' conversations return an empty `messages` array "- "and load history from the products/tasks logs endpoint. A converted conversation is "- "'sandbox' but still returns its legacy thread in `messages`."+ "in the `messages` field. 'sandbox' conversations return an empty `messages` array and "+ "load history from the products/tasks logs endpoint; a conversation copied into a task "+ "carries its legacy thread in that task's import run. Only a conversion that predates "+ "the copy still returns its legacy thread in `messages`."),)messages = serializers.SerializerMethodField()@@ -308,12 +321,12 @@ class ConversationSerializer(ConversationMinimalSerializer):pending_approvals = serializers.SerializerMethodField()def get_messages(self, conversation: Conversation) -> list[dict[str, Any]]:- # Born-sandbox conversations have no checkpoint — their history lives in S3 ACP logs- # (fetched via the products/tasks `logs/` endpoint), so `_get_cached_state` returns None and- # messages are []; the cached `messages_json` is intentionally ignored on this path. A- # CONVERTED conversation keeps its legacy checkpoint, so its full legacy thread is returned- # (rendered above the conversion divider). LangGraph conversations use the cached- # `messages_json` when present, else compile + replay the checkpoint.+ # Sandbox conversations render their history from the task run logs (fetched via the+ # products/tasks `logs/` endpoint), so `_get_cached_state` returns None and messages are [];+ # the cached `messages_json` is intentionally ignored on this path. The one exception is a+ # conversion that predates the mirror (see `aget_conversation_state`). LangGraph+ # conversations use the cached `messages_json` when present, else compile + replay the+ # checkpoint.if conversation.agent_runtime == Conversation.AgentRuntime.SANDBOX:return self._render_state_messages(self._get_cached_state(conversation).state)diff --git a/ee/hogai/utils/feature_flags.py b/ee/hogai/utils/feature_flags.pyindex 8f01f5b973d0..fd908b893613 100644--- a/ee/hogai/utils/feature_flags.py+++ b/ee/hogai/utils/feature_flags.py@@ -114,6 +114,17 @@ def has_sandbox_mode_feature_flag(team: Team, user: User) -> bool:)+def has_conversation_task_mirror_feature_flag(team: Team, user: User) -> bool:+ """Whether LangGraph conversations are mirrored into the task world after each turn."""+ return feature_enabled_or_false(+ "phai-conversation-task-mirror",+ str(user.distinct_id),+ groups={"organization": str(team.organization_id)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ send_feature_flag_events=False,+ )++def has_user_interview_mode_feature_flag(team: Team, user: User) -> bool:return feature_enabled_or_false("user-interviews",diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.test.ts b/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.test.tsindex 8bdc26699fe6..b10d1c3b8e57 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.test.ts+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.test.ts@@ -105,4 +105,22 @@ describe('groupAiHistory', () => {expect(items.map((item) => item.key)).toEqual(['task:task-id', 'conversation:conversation-id'])})++ it('shows a chat that has a task as the task once the task list holds it, and as the chat until then', () => {+ // Older than the task rows, so the order below does not depend on same-millisecond timestamps.+ const chatWithTask = {+ ...conversation,+ updated_at: new Date(Date.now() - 2_000).toISOString(),+ task: { id: 'task-id', latest_run: null },+ }+ const otherTask = { ...baseTask, id: 'other-task-id' }++ const withTask = groupAiHistory([chatWithTask], [baseTask]).flatMap((group) => group.items)+ const taskNotLoadedYet = groupAiHistory([chatWithTask], [otherTask]).flatMap((group) => group.items)+ const chatsOnly = groupAiHistory([chatWithTask], []).flatMap((group) => group.items)++ expect(withTask.map((item) => item.key)).toEqual(['task:task-id'])+ expect(taskNotLoadedYet.map((item) => item.key)).toEqual(['task:other-task-id', 'conversation:conversation-id'])+ expect(chatsOnly.map((item) => item.key)).toEqual(['conversation:conversation-id'])+ })})diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.tsx b/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.tsxindex 4f1483c36133..1e810a6080ec 100644--- a/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.tsx+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.tsx@@ -82,12 +82,18 @@ export function groupAiHistory(filter: TaskAssigneeFilter = 'for_you'): AiHistoryGroup[] {const items: AiHistoryItem[] = []+ const loadedTaskIds = new Set(tasks.map((task) => task.id))const showConversations = filter === 'for_you' || filter === 'posthog_ai' || filter === 'all_team'for (const conversation of showConversations ? conversationHistory : []) {if (!conversation) {continue}+ // A chat copied into a task shows as that task once the task list holds it. Until the task list+ // catches up, the chat row stays, so the chat is never missing from the list.+ if (conversation.task && loadedTaskIds.has(conversation.task.id)) {+ continue+ }const title = conversation.title || 'Untitled conversation'items.push({kind: 'conversation',diff --git a/frontend/src/scenes/max/maxGlobalLogic.test.ts b/frontend/src/scenes/max/maxGlobalLogic.test.tsindex 0dbe0bfafebb..269eb36d2bbc 100644--- a/frontend/src/scenes/max/maxGlobalLogic.test.ts+++ b/frontend/src/scenes/max/maxGlobalLogic.test.ts@@ -10,6 +10,8 @@ import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { tasksLogic } from 'products/posthog_ai/frontend/logics/tasksLogic'+import { TOOL_DEFINITIONS, ToolDefinition } from './max-constants'import { STATIC_TOOLS, maxGlobalLogic } from './maxGlobalLogic'import { SIDE_PANEL_PANEL_ID, maxLogic } from './maxLogic'@@ -180,4 +182,86 @@ describe('maxGlobalLogic', () => {})})++ // A chat and its task are deleted together on the server. Each list only knows about its own+ // delete, so the other list has to be reloaded or the deleted item resurfaces as the other row.+ describe('deleting from the merged list', () => {+ let taskListRequests = 0+ let conversationListRequests = 0+ let tasks: ReturnType<typeof tasksLogic.build>++ beforeEach(async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/tasks/': () => {+ taskListRequests += 1+ return [200, { results: [], count: 0 }]+ },+ '/api/environments/:team_id/conversations/': () => {+ conversationListRequests += 1+ return [200, { results: [] }]+ },+ },+ delete: {+ '/api/environments/:team_id/conversations/:id/': () => [204, null],+ '/api/projects/:team_id/tasks/:id/': () => [204, null],+ },+ })+ tasks = tasksLogic()+ tasks.mount()+ await expectLogic(tasks).toFinishAllListeners()+ await expectLogic(logic).toFinishAllListeners()+ taskListRequests = 0+ conversationListRequests = 0+ })++ afterEach(() => {+ tasks.unmount()+ })++ it('reloads the chats when a task is deleted', async () => {+ tasks.actions.deleteTask({ taskId: 'task-id' })+ await expectLogic(tasks).toFinishAllListeners()+ await expectLogic(logic).toFinishAllListeners()++ expect(conversationListRequests).toBe(1)+ })++ it('reloads the tasks when a chat is deleted', async () => {+ logic.actions.deleteConversation('conversation-id')+ await expectLogic(logic).toFinishAllListeners()+ await expectLogic(tasks).toFinishAllListeners()++ expect(taskListRequests).toBe(1)+ })+ })++ // A chat made on the legacy view is copied into a task while the task list sits unchanged since+ // mount; without this reload the merged list would hide the chat behind a task row it has not loaded.+ describe('switching to the new view', () => {+ it.each([+ { mode: 'new', reloads: 1 },+ { mode: 'legacy', reloads: 0 },+ ] as const)('reloads the task list $reloads time(s) when switching to $mode', async ({ mode, reloads }) => {+ let taskListRequests = 0+ useMocks({+ get: {+ '/api/projects/:team_id/tasks/': () => {+ taskListRequests += 1+ return [200, { results: [], count: 0 }]+ },+ },+ })+ const tasks = tasksLogic()+ tasks.mount()+ await expectLogic(tasks).toFinishAllListeners()+ taskListRequests = 0++ logic.actions.setPhaiViewMode(mode)+ await expectLogic(tasks).toFinishAllListeners()++ expect(taskListRequests).toBe(reloads)+ tasks.unmount()+ })+ })})diff --git a/frontend/src/scenes/max/maxGlobalLogic.tsx b/frontend/src/scenes/max/maxGlobalLogic.tsxindex 49c86d6d505b..79291c9f554b 100644--- a/frontend/src/scenes/max/maxGlobalLogic.tsx+++ b/frontend/src/scenes/max/maxGlobalLogic.tsx@@ -20,6 +20,7 @@ import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePaneimport { Conversation, ConversationDetail, SidePanelTab } from '~/types'import { conversationsDestroy } from 'products/posthog_ai/frontend/generated/api'+import { tasksLogic } from 'products/posthog_ai/frontend/logics/tasksLogic'import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'import type { OrganizationType, PreflightStatus } from '../../types'@@ -391,6 +392,19 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([],}),listeners(({ actions, values }) => ({+ setPhaiViewMode: ({ mode }) => {+ // The task list only loads on mount. A chat made on the legacy view has a task copy by the+ // time the user switches, and the merged list shows it as that task once it is loaded.+ const tasks = tasksLogic.findMounted()+ if (mode === 'new' && tasks) {+ tasks.actions.loadTasks(tasks.values.taskListParams)+ }+ },+ // A chat and its task are deleted together on the server, so removing a task from the merged+ // list must drop the chat row too, or the chat resurfaces as a row of its own.+ [tasksLogic.actionTypes.deleteTaskSuccess]: () => {+ actions.loadConversationHistory()+ },askSidePanelMax: ({ prompt }) => {newInternalTab(urls.ai(undefined, prompt))},@@ -438,6 +452,11 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([}}actions.loadConversationHistory()+ // The chat's task is deleted with it; the merged list must not keep its task row.+ const tasks = tasksLogic.findMounted()+ if (tasks) {+ tasks.actions.loadTasks(tasks.values.taskListParams)+ }} catch {lemonToast.error('Failed to delete chat')}diff --git a/posthog/temporal/ai/__init__.py b/posthog/temporal/ai/__init__.pyindex e77e174289d7..ca8c6116abf2 100644--- a/posthog/temporal/ai/__init__.py+++ b/posthog/temporal/ai/__init__.py@@ -14,6 +14,9 @@ from posthog.temporal.ai.slack_app.posthog_slack_inbox_onboarding import PostHogfrom posthog.temporal.ai.slack_app.slack_app_fork import SlackAppForkThreadWorkflowfrom posthog.temporal.ai.slack_app.slack_app_mention import SlackAppMentionWorkflow+from products.posthog_ai.backend.temporal.activities import mirror_conversation_to_task_activity+from products.posthog_ai.backend.temporal.workflows import ConversationMirrorWorkflow+from .llm_traces_summaries.summarize_traces import (SummarizeLLMTracesInputs,SummarizeLLMTracesWorkflow,@@ -42,6 +45,7 @@ POSTHOG_CODE_SLACK_WORKFLOWS = [POSTHOG_CODE_SLACK_ACTIVITIES = [*SLACK_APP_ACTIVITIES]AI_WORKFLOWS = [+ ConversationMirrorWorkflow,SyncVectorsWorkflow,AssistantConversationRunnerWorkflow,ChatAgentWorkflow,@@ -57,6 +61,7 @@ AI_ACTIVITIES = [batch_embed_and_sync_actions,process_conversation_activity,process_chat_agent_activity,+ mirror_conversation_to_task_activity,process_research_agent_activity,summarize_llm_traces_activity,investigate_anomaly_activity,diff --git a/posthog/temporal/ai/chat_agent.py b/posthog/temporal/ai/chat_agent.pyindex c0829c3006b7..5496a1f92521 100644--- a/posthog/temporal/ai/chat_agent.py+++ b/posthog/temporal/ai/chat_agent.py@@ -10,8 +10,10 @@ from django.conf import settingsimport pydanticimport structlog+from asgiref.sync import sync_to_asyncfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicy+from temporalio.workflow import ParentClosePolicyfrom posthog.schema import AgentMode, AssistantEventType, HumanMessage, MaxBillingContext@@ -20,10 +22,13 @@ from posthog.temporal.ai.base import AgentBaseWorkflowfrom posthog.temporal.common.client import async_connectfrom products.posthog_ai.backend.models.assistant import Conversation+from products.posthog_ai.backend.temporal.activities import MirrorConversationInputs+from products.posthog_ai.backend.temporal.workflows import ConversationMirrorWorkflowfrom ee.hogai.chat_agent.runner import ChatAgentRunnerfrom ee.hogai.queue import ConversationQueueMessage, ConversationQueueStorefrom ee.hogai.stream.redis_stream import ConversationRedisStream, get_conversation_stream_key+from ee.hogai.utils.feature_flags import has_conversation_task_mirror_feature_flagfrom ee.hogai.utils.types import AssistantMode, AssistantOutputlogger = structlog.get_logger(__name__)@@ -104,6 +109,12 @@ class AssistantConversationRunnerWorkflow(AgentBaseWorkflow):)+@dataclass(frozen=True)+class ChatAgentActivityResult:+ # False for turns that predate this field, so a chat in flight at deploy never starts the copy.+ mirror_enabled: bool = False++@dataclassclass ChatAgentWorkflowInputs:"""Inputs for the chat agent workflow."""@@ -139,7 +150,7 @@ class ChatAgentWorkflow(AgentBaseWorkflow):@workflow.runasync def run(self, inputs: ChatAgentWorkflowInputs) -> None:"""Execute the agent workflow."""- await workflow.execute_activity(+ result = await workflow.execute_activity(process_chat_agent_activity,inputs,start_to_close_timeout=timedelta(seconds=CHAT_AGENT_WORKFLOW_TIMEOUT),@@ -151,10 +162,26 @@ class ChatAgentWorkflow(AgentBaseWorkflow):),heartbeat_timeout=timedelta(seconds=CHAT_AGENT_ACTIVITY_HEARTBEAT_TIMEOUT),)+ if not inputs.use_checkpointer or result is None or not result.mirror_enabled:+ # A subagent run shares the conversation but writes no turn of its own; only the main+ # turn has something to copy, and only while the kill switch is on for its owner.+ return+ # The turn is persisted and streamed by now. The copy into the task runs as a detached child+ # so this workflow closes at once: its id is fixed per conversation, and a follow-up sent+ # while it is still open would join it and lose its message.+ await workflow.start_child_workflow(+ ConversationMirrorWorkflow.run,+ MirrorConversationInputs(+ team_id=inputs.team_id, user_id=inputs.user_id, conversation_id=str(inputs.conversation_id)+ ),+ id=f"conversation-mirror-{inputs.conversation_id}-{workflow.info().run_id}",+ task_queue=workflow.info().task_queue,+ parent_close_policy=ParentClosePolicy.ABANDON,+ )@activity.defn-async def process_chat_agent_activity(inputs: ChatAgentWorkflowInputs) -> None:+async def process_chat_agent_activity(inputs: ChatAgentWorkflowInputs) -> ChatAgentActivityResult:"""Process a chat agent task and stream results to Redis.Args:@@ -167,6 +194,10 @@ async def process_chat_agent_activity(inputs: ChatAgentWorkflowInputs) -> None:Conversation.objects.aget(id=inputs.conversation_id),)+ result = ChatAgentActivityResult(+ mirror_enabled=await sync_to_async(has_conversation_task_mirror_feature_flag)(team, user)+ )+human_message = HumanMessage.model_validate(inputs.message) if inputs.message else Nonequeue_store = ConversationQueueStore(str(inputs.conversation_id))should_stop_queue = False@@ -299,12 +330,12 @@ async def process_chat_agent_activity(inputs: ChatAgentWorkflowInputs) -> None:if should_stop_queue:await queue_store.clear_async()await redis_stream.mark_complete()- return+ return resultqueued_workflow = await build_queued_workflow_inputs()if queued_workflow is None:await redis_stream.mark_complete()- return+ return resultnext_inputs, queued_message = queued_workflowtry:@@ -317,6 +348,7 @@ async def process_chat_agent_activity(inputs: ChatAgentWorkflowInputs) -> None:)await queue_store.requeue_front_async(queued_message)raise+ return result@activity.defndiff --git a/posthog/temporal/tests/ai/test_chat_agent_activity.py b/posthog/temporal/tests/ai/test_chat_agent_activity.pyindex 394f4a99ab1b..14f7f07d3bb0 100644--- a/posthog/temporal/tests/ai/test_chat_agent_activity.py+++ b/posthog/temporal/tests/ai/test_chat_agent_activity.py@@ -87,6 +87,22 @@ class TestProcessChatAgentActivity:mock_redis_stream_class.assert_called_once_with(conversation_inputs.stream_key)mock_redis_stream.write_to_stream.assert_called_once()+ @pytest.mark.asyncio+ @pytest.mark.parametrize("mirror_enabled", [True, False])+ async def test_activity_reports_whether_the_copy_is_enabled(+ self, conversation_inputs, mock_redis_stream, mock_assistant, mirror_enabled+ ):+ with (+ patch("posthog.temporal.ai.chat_agent.ConversationRedisStream", return_value=mock_redis_stream),+ patch("posthog.temporal.ai.chat_agent.ChatAgentRunner", return_value=mock_assistant),+ patch(+ "posthog.temporal.ai.chat_agent.has_conversation_task_mirror_feature_flag", return_value=mirror_enabled+ ),+ ):+ result = await process_chat_agent_activity(conversation_inputs)++ assert result.mirror_enabled is mirror_enabled+@pytest.mark.asyncioasync def test_process_conversation_activity_streaming_error(self,diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex d80f5fffd9b8..376f185e13c0 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -17,6 +17,7 @@ class TestAITemporalModuleIntegrity:"SyncVectorsWorkflow","AssistantConversationRunnerWorkflow","ChatAgentWorkflow",+ "ConversationMirrorWorkflow","ResearchAgentWorkflow","SummarizeLLMTracesWorkflow","AnomalyInvestigationWorkflow",@@ -44,6 +45,7 @@ class TestAITemporalModuleIntegrity:"batch_embed_and_sync_actions","process_conversation_activity","process_chat_agent_activity",+ "mirror_conversation_to_task_activity","process_research_agent_activity","summarize_llm_traces_activity","investigate_anomaly_activity",diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex be021f0c4db4..7dc113efa7af 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -207,6 +207,7 @@ post_save:products.feature_flags.backend.local_evaluation.experiment_changedpost_save:products.feature_flags.backend.local_evaluation.feature_flag_changedpost_save:products.feature_flags.backend.session_recording_links.relink_teams_on_key_changepost_save:products.managed_warehouse.backend.models._observe_duckgres_server_save+post_save:products.posthog_ai.backend.receivers.mark_conversation_sandbox_on_first_runpost_save:products.review_hog.backend.receivers.handle_task_run_savedpost_save:products.signals.backend.receivers.arm_pending_checks_when_report_resolvedpost_save:products.signals.backend.receivers.capture_status_change_analyticsdiff --git a/products/posthog_ai/backend/apps.py b/products/posthog_ai/backend/apps.pyindex 681452c93248..c29c366feea7 100644--- a/products/posthog_ai/backend/apps.py+++ b/products/posthog_ai/backend/apps.py@@ -5,3 +5,9 @@ class PosthogAiConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.posthog_ai.backend"label = "posthog_ai"++ def ready(self) -> None:+ # Deferred import: models aren't loadable at module import time, and ready() must stay light.+ from products.posthog_ai.backend import receivers # noqa: PLC0415++ receivers.connect()diff --git a/products/posthog_ai/backend/context_wrapper.py b/products/posthog_ai/backend/context_wrapper.pyindex 61e8103c149f..ca84447643b6 100644--- a/products/posthog_ai/backend/context_wrapper.py+++ b/products/posthog_ai/backend/context_wrapper.py@@ -9,20 +9,13 @@ the frontend (`products/posthog_ai/frontend/utils/posthogContextBlock.ts`); do nhere — the frontend replay stripper keeps understanding this legacy `<posthog_context>` tag untilthe bridge is deleted.-NOT deprecated: `abuild_resumed_legacy_context` (the conversation migration service) stays."""-import json-import time-from collections.abc import Iterable, Sequence-from typing import TYPE_CHECKING, Any, Literal, TypedDict, get_args--import posthoganalytics+from collections.abc import Iterable+from typing import TYPE_CHECKING, Literal, TypedDict, get_argsif TYPE_CHECKING:- from posthog.models import Team, User-- from products.posthog_ai.backend.models.assistant import Conversation+ pass# Allowed attachment types.AttachedContextType = Literal[@@ -42,10 +35,6 @@ ALLOWED_TYPES: frozenset[str] = frozenset(get_args(AttachedContextType))MAX_ATTACHED_ITEMS = 32MAX_TEXT_LENGTH = 4096-# Preamble for the one-time `<posthog_context>` block that carries a converted conversation's-# legacy history into its first sandbox message.-RESUMED_CONTEXT_PREFIX = "This session was resumed from the legacy implementation."-class AttachedContext(TypedDict, total=False):"""A single typed attachment carried by a user message.@@ -149,88 +138,3 @@ class ContextService:if name:line += f' ("{self._defang(name)}")'return line-- async def abuild_resumed_legacy_context(- self, conversation: "Conversation", team: "Team", user: "User"- ) -> str | None:- """Render a converted conversation's legacy history into a one-time `<posthog_context>` block.-- Called once, on the conversion event, while the conversation is still on the LangGraph- runtime: it reads the legacy state via the shared serializer path and limits it to the- current conversation window — the same window the agent runs on (see- `ee/hogai/core/agent_modes/executables.py`). Returns None when there's no readable state or- no renderable turns, so the caller just forwards the user's message without an empty block.- """- # Deferred: keeps the LangGraph graph-compile + compaction (heavy) off the sandbox- # message-routing import path — only the conversion event pays for them.- from ee.hogai.api.serializers import (- aget_conversation_state, # noqa: PLC0415 — keeps LangGraph off the sandbox import path- )- from ee.hogai.core.agent_modes.compaction_manager import ( # noqa: PLC0415 — heavy compaction dep- AnthropicConversationCompactionManager,- )- from ee.hogai.utils.types import AssistantState # noqa: PLC0415 — keeps LangGraph off the sandbox import path-- started_at = time.monotonic()- state_result = await aget_conversation_state(conversation, team, user)- # Legacy conversions are assistant conversations (see CONVERSATION_TYPE_MAP); the broad- # AssistantMaxGraphState union also admits TaxonomyAgentState, which carries no window anchor.- if not isinstance(state_result.state, AssistantState):- return None-- window = AnthropicConversationCompactionManager().get_messages_in_window(- state_result.state.messages, state_result.state.root_conversation_start_id- )- transcript = self._render_legacy_transcript(window)-- posthoganalytics.capture(- distinct_id=str(user.distinct_id),- event="phai_legacy_conversion",- properties={- "conversation_id": str(conversation.id),- "messages_total": len(state_result.state.messages),- "window_messages": len(window),- "duration_ms": int((time.monotonic() - started_at) * 1000),- },- groups={"organization": str(team.organization_id)},- )-- if not transcript:- return None- return f"<posthog_context>{RESUMED_CONTEXT_PREFIX}\n{transcript}</posthog_context>"-- def _render_legacy_transcript(self, messages: Sequence[Any]) -> str:- """Render windowed legacy messages to a plain-text transcript for the resumed prompt.-- Covers user turns, assistant prose, tool calls + results, thinking/reasoning, and context- messages so the new agent sees the substance of the legacy turn — not just the chat text.- Visualization/notebook cards degrade to a short label; types with no useful text are skipped.- """- from posthog.schema import ( # noqa: PLC0415 — large schema module- AssistantMessage,- AssistantToolCallMessage,- ContextMessage,- HumanMessage,- ReasoningMessage,- )-- lines: list[str] = []- for message in messages:- if isinstance(message, HumanMessage):- if message.content:- lines.append(f"User: {message.content}")- elif isinstance(message, ReasoningMessage):- if message.content:- lines.append(f"Thinking: {message.content}")- elif isinstance(message, ContextMessage):- if message.content:- lines.append(f"Context: {message.content}")- elif isinstance(message, AssistantMessage):- if message.content:- lines.append(f"Assistant: {message.content}")- for tool_call in message.tool_calls or []:- lines.append(f"Tool call {tool_call.name}({json.dumps(tool_call.args, default=str)})")- elif isinstance(message, AssistantToolCallMessage):- if message.content:- lines.append(f"Tool result: {message.content}")- return "\n".join(lines)diff --git a/products/posthog_ai/backend/conversation_mirror.py b/products/posthog_ai/backend/conversation_mirror.pynew file mode 100644index 000000000000..c1359dc0b3a5--- /dev/null+++ b/products/posthog_ai/backend/conversation_mirror.py@@ -0,0 +1,433 @@+"""Mirror a LangGraph conversation into the task world.++The new PostHog AI renders and resumes a chat from a task run's S3 log. A LangGraph conversation+stores its history in Postgres checkpoints instead, so nothing in the task world can see it. This+module keeps a task-world copy of every LangGraph conversation up to date: one Task, one completed+"import run" that never executed, and an S3 log written in the same wire format a real sandbox run+produces. The task viewer and the agent-server's resume path then treat the conversation exactly+like a native task.++The mirror runs after each completed LangGraph turn (see the chat agent workflow). It reads the+conversation's messages, reads how many were copied before (stored on the import run's state), and+appends the rest. A failed mirror is retried on the next turn from the same count, so it never has+to remember partial work.+"""++from __future__ import annotations++import json+from datetime import datetime+from typing import Any+from uuid import UUID++from django.utils import timezone++import structlog+from asgiref.sync import sync_to_async++from posthog.schema import ContextMessage++from posthog.dataclasses import frozen+from posthog.models import Team, User++from products.posthog_ai.backend.models.assistant import Conversation+from products.tasks.backend.facade import (+ api as tasks_facade,+ contracts as tasks_contracts,+)++logger = structlog.get_logger(__name__)++IMPORTED_FROM_CONVERSATION = "conversation"+# Run-state fields that record how far the conversation has been copied into the import run.+MESSAGES_COPIED_KEY = "conversation_messages_copied"+LAST_MESSAGE_ID_KEY = "conversation_last_message_id"+IMPORTED_TASK_ORIGIN_KEY_PREFIX = "phai-conversation:"++# The task thread and the agent-server both recognize a PostHog tool call by this Claude Code tool+# name; the inner tool is parsed out of the exec command. Legacy tool calls are written in the same+# shape so the product widgets (insight, recordings, ...) render them.+_EXEC_TOOL_NAME = "mcp__posthog__exec"++# The task thread keys its widgets (insight card, SQL result, recordings list) on the exec sub-tool+# names; a legacy tool call is written under the sub-tool name so the same widget renders it.+_EXEC_SUB_TOOL_BY_LEGACY_NAME = {+ "create_insight": "insight-create",+ "execute_sql": "execute-sql",+ "search_session_recordings": "query-session-recordings-list",+ "filter_session_recordings": "query-session-recordings-list",+}+++def _tool_meta(tool_call_id: str, **claude_code: Any) -> dict[str, Any]:+ # The sandbox resume parser rebuilds tool history only from _meta.claudeCode, not the ACP top-level fields.+ return {"claudeCode": {"toolName": _EXEC_TOOL_NAME, "toolCallId": tool_call_id, **claude_code}, "imported": True}+++@frozen+class CopyProgress:+ message_count: int+ last_message_id: str | None+++class CopyConflict(Exception):+ """Another copy of the same conversation moved the run on first; the caller retries."""+++@frozen+class MirrorResult:+ skipped_reason: str | None+ task_id: UUID | None+ run_id: UUID | None+ appended_frames: int+++def origin_key_for_conversation(conversation_id: UUID | str) -> str:+ return f"{IMPORTED_TASK_ORIGIN_KEY_PREFIX}{conversation_id}"+++def _frame(method: str, params: dict[str, Any]) -> dict[str, Any]:+ # LangGraph messages carry no time of their own, so copied lines carry no `timestamp`. The+ # thread renders no timing for them instead of a time we would have to invent.+ return {"type": "notification", "notification": {"jsonrpc": "2.0", "method": method, "params": params}}+++def _session_update(session_id: str, update: dict[str, Any]) -> dict[str, Any]:+ return _frame("session/update", {"sessionId": session_id, "update": update})+++def _text_content(text: str) -> dict[str, Any]:+ return {"type": "text", "text": text}+++def _tool_result_output(+ tool_message: dict[str, Any], artifact: dict[str, Any] | None, call_args: dict[str, Any]+) -> dict[str, Any]:+ text = tool_message.get("content") or ""+ output: dict[str, Any] = {"0": _text_content(text)}+ if artifact is not None:+ content = artifact.get("content") or {}+ output.update(+ {+ "artifact_id": artifact.get("artifact_id"),+ "query": content.get("query"),+ "name": content.get("name"),+ "description": content.get("description"),+ "content_type": content.get("content_type"),+ }+ )+ recordings_filters = call_args.get("recordings_filters")+ # RecordingsWidget renders a ready-made universal-filters object from rawOutput.filters.+ if isinstance(recordings_filters, dict) and "filter_group" in recordings_filters:+ output["filters"] = recordings_filters+ return output+++def project_legacy_messages(+ messages: list[dict[str, Any]],+ *,+ run_id: str,+ include_run_start: bool,+) -> list[dict[str, Any]]:+ """Convert serialized LangGraph messages into task-run log frames.++ Frame shapes are copied from real sandbox run logs, because two consumers parse this log+ without knowing it was imported: the task thread projection (web) and the agent-server's resume+ parser. User turns use the `importedUserPrompt` convention that `TaskRun.clear_conversation`+ established for user text written without an agent. Every frame carries an `imported` marker so+ provenance stays visible in the data.+ """+ session_id = run_id+ frames: list[dict[str, Any]] = []+ if include_run_start:+ # Without a run_started frame the viewer keeps the run in its "provisioning" phase.+ frames.append(_frame("_posthog/run_started", {"runId": run_id, "imported": True}))++ pending_artifact: dict[str, Any] | None = None+ call_args_by_id: dict[str, dict[str, Any]] = {}+ turn_has_agent_output = False++ for message in messages:+ message_type = message.get("type")+ if message_type in ("human", "context"):+ if turn_has_agent_output:+ frames.append(_frame("_posthog/turn_complete", {}))+ turn_has_agent_output = False+ content = _text_content(message.get("content") or "")+ if message_type == "context":+ # LangGraph sends context messages (compaction summary, mode notes) to the model as user+ # turns nobody typed. The hidden marker keeps them out of the thread and in the resumed history.+ content["_meta"] = {"ui": {"hidden": True}}+ frames.append(+ _session_update(+ session_id,+ {+ "sessionUpdate": "user_message_chunk",+ "content": content,+ "_meta": {"importedUserPrompt": True, "imported": True},+ },+ )+ )+ elif message_type == "ai":+ for thought in (message.get("meta") or {}).get("thinking") or []:+ if thought.get("thinking"):+ frames.append(+ _session_update(+ session_id,+ {+ "sessionUpdate": "agent_thought_chunk",+ "content": _text_content(thought["thinking"]),+ "_meta": {"imported": True},+ },+ )+ )+ if message.get("content"):+ frames.append(+ _session_update(+ session_id,+ {+ "sessionUpdate": "agent_message",+ "content": _text_content(message["content"]),+ "_meta": {"imported": True},+ },+ )+ )+ turn_has_agent_output = True+ for tool_call in message.get("tool_calls") or []:+ args = tool_call.get("args") or {}+ call_args_by_id[tool_call["id"]] = args+ sub_tool = _EXEC_SUB_TOOL_BY_LEGACY_NAME.get(tool_call["name"], tool_call["name"])+ command = f"call {sub_tool} {json.dumps(args)}"+ base = {+ "_meta": _tool_meta(tool_call["id"], toolInput={"command": command}),+ "toolCallId": tool_call["id"],+ "title": "exec",+ "kind": "other",+ "content": [],+ }+ frames.append(+ _session_update(+ session_id,+ {**base, "sessionUpdate": "tool_call", "rawInput": {}, "status": "pending"},+ )+ )+ frames.append(+ _session_update(+ session_id,+ {**base, "sessionUpdate": "tool_call_update", "rawInput": {"command": command}},+ )+ )+ turn_has_agent_output = True+ elif message_type == "ai/artifact":+ # The artifact precedes the tool result that produced it; its query rides that result.+ pending_artifact = message+ elif message_type == "tool":+ tool_call_id = message["tool_call_id"]+ output = _tool_result_output(message, pending_artifact, call_args_by_id.get(tool_call_id, {}))+ pending_artifact = None+ frames.append(+ _session_update(+ session_id,+ {+ "_meta": _tool_meta(tool_call_id, toolResponse=output),+ "toolCallId": tool_call_id,+ "sessionUpdate": "tool_call_update",+ "status": "completed",+ "title": "exec",+ "kind": "other",+ "content": [{"type": "content", "content": _text_content(message.get("content") or "")}],+ "rawOutput": output,+ },+ )+ )+ elif message_type == "ai/failure":+ frames.append(_frame("_posthog/error", {"message": message.get("content") or "Something went wrong"}))+ turn_has_agent_output = True+ else:+ # Kept explicit so the backfill can count what it could not port instead of dropping it.+ frames.append(+ _frame("_posthog/legacy_unmapped", {"legacy_type": message_type, "_meta": {"imported": True}})+ )++ if turn_has_agent_output:+ frames.append(_frame("_posthog/turn_complete", {}))+ return frames+++async def _aload_messages(conversation: Conversation, team: Team, user: User) -> list[dict[str, Any]] | None:+ """The conversation's completed turns, or None when the checkpoint holds content this copy cannot read.++ A read error raises so the activity retries; unsupported content does not change on retry.+ """+ # Deferred: keeps the LangGraph graph compile off this module's import path; only the mirror pays for it.+ from ee.hogai.api.serializers import aget_conversation_state # noqa: PLC0415 — keeps LangGraph off the import path+ from ee.hogai.artifacts.manager import ArtifactManager # noqa: PLC0415 — same+ from ee.hogai.utils.helpers import should_output_assistant_message # noqa: PLC0415 — same++ state_result = await aget_conversation_state(conversation, team, user, raise_on_error=True)+ if state_result.has_unsupported_content:+ return None+ if state_result.state is None:+ return []+ enriched = await ArtifactManager(team, user).aenrich_messages(list(state_result.state.messages))+ # Context messages are model-only; the thread never shows them, but the resumed agent needs them.+ messages = [+ message.model_dump()+ for message in enriched+ if isinstance(message, ContextMessage) or should_output_assistant_message(message)+ ]+ return _completed_turns(messages)+++def _completed_turns(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Drop a trailing turn that is still in progress.++ A turn is complete once the assistant gave its final answer or failed. A trailing tool call+ without its result, or an approval the user has not answered yet, is copied by the next run,+ after the turn has ended.+ """+ for index in range(len(messages) - 1, -1, -1):+ message = messages[index]+ if message.get("type") == "ai/failure" or (message.get("type") == "ai" and not message.get("tool_calls")):+ return messages[: index + 1]+ return []+++def _read_copy_progress(run_state: dict[str, Any]) -> CopyProgress:+ return CopyProgress(+ message_count=int(run_state.get(MESSAGES_COPIED_KEY) or 0),+ last_message_id=run_state.get(LAST_MESSAGE_ID_KEY),+ )+++def _uncopied_messages(progress: CopyProgress, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """The messages after the last copied one.++ The anchor is the last copied message's id, not its position: LangGraph compaction replaces+ the stored list with a shorter window, so positions move. An anchor still in the list means+ everything after it is new. An anchor that is gone means the window starts after it, so+ everything in the list is new.+ """+ if progress.last_message_id is None:+ return messages+ for index in range(len(messages) - 1, -1, -1):+ if messages[index].get("id") == progress.last_message_id:+ return messages[index + 1 :]+ return messages+++def _ensure_import_target(+ conversation: Conversation, team: Team, user: User, *, created_at: datetime, updated_at: datetime+) -> tuple[UUID, tasks_contracts.TaskRunDetailDTO] | None:+ """Find the conversation's task and import run, creating both on first touch.++ Returns None when the conversation's task was deleted: the chat has no task-world copy anymore.+ """+ origin_key = origin_key_for_conversation(conversation.id)+ existing = tasks_facade.get_task_by_origin_key(team.id, origin_key)+ if conversation.task_id is not None and existing is None:+ return None+ task_id: UUID | None = existing.id if existing is not None else None+ if task_id is None:+ created = tasks_facade.create_imported_task(+ team.id,+ user.id,+ title=conversation.title or "Imported chat",+ origin_key=origin_key,+ internal=bool(conversation.is_internal),+ created_at=created_at,+ )+ task_id = created.id+ # `task__isnull` keeps a concurrent first touch from re-pointing a conversation that already got linked.+ Conversation.objects.filter(id=conversation.id, task__isnull=True).update(task_id=task_id)++ run = tasks_facade.get_imported_task_run(task_id, team.id)+ if run is None:+ run = tasks_facade.create_imported_task_run(+ task_id,+ team.id,+ state={+ "imported_from": IMPORTED_FROM_CONVERSATION,+ "conversation_id": str(conversation.id),+ MESSAGES_COPIED_KEY: 0,+ LAST_MESSAGE_ID_KEY: None,+ },+ created_at=created_at,+ completed_at=updated_at,+ )+ return task_id, run+++async def amirror_conversation(conversation_id: UUID | str, team_id: int, user_id: int) -> MirrorResult:+ """Append the conversation's not-yet-mirrored messages to its task-world import run."""+ conversation = await Conversation.objects.aget(id=conversation_id, team_id=team_id)+ if conversation.deleted:+ return MirrorResult(skipped_reason="deleted", task_id=None, run_id=None, appended_frames=0)+ if conversation.is_internal:+ # A support agent made this chat while impersonating the customer, who must never see it; a task would be theirs.+ return MirrorResult(skipped_reason="internal", task_id=None, run_id=None, appended_frames=0)+ if conversation.type != Conversation.Type.ASSISTANT:+ return MirrorResult(skipped_reason="type", task_id=None, run_id=None, appended_frames=0)+ if conversation.agent_runtime != Conversation.AgentRuntime.LANGGRAPH:+ # Sandbox conversations already are tasks; a converted one continues natively from here on.+ return MirrorResult(skipped_reason="runtime", task_id=None, run_id=None, appended_frames=0)+ if conversation.user_id != user_id:+ # The copy runs as the chat's owner: only the owner can send it messages, and the task is theirs.+ return MirrorResult(skipped_reason="owner_mismatch", task_id=None, run_id=None, appended_frames=0)++ team = await Team.objects.aget(id=team_id)+ user = await User.objects.aget(id=user_id)++ messages = await _aload_messages(conversation, team, user)+ if messages is None:+ return MirrorResult(skipped_reason="unsupported_content", task_id=None, run_id=None, appended_frames=0)+ if not messages:+ return MirrorResult(skipped_reason="no_messages", task_id=None, run_id=None, appended_frames=0)++ # The model declares these nullable; a persisted conversation always has both.+ updated_at = conversation.updated_at or timezone.now()+ created_at = conversation.created_at or updated_at+ target = await sync_to_async(_ensure_import_target)(+ conversation, team, user, created_at=created_at, updated_at=updated_at+ )+ if target is None:+ return MirrorResult(skipped_reason="task_deleted", task_id=None, run_id=None, appended_frames=0)+ task_id, run = target+ progress = _read_copy_progress(run.state)+ new_messages = _uncopied_messages(progress, messages)+ if not new_messages:+ return MirrorResult(skipped_reason=None, task_id=task_id, run_id=run.id, appended_frames=0)++ frames = project_legacy_messages(+ new_messages, run_id=str(run.id), include_run_start=progress.last_message_id is None+ )+ appended = await sync_to_async(tasks_facade.append_imported_task_run_log)(+ run.id,+ task_id,+ team_id,+ entries=frames,+ batch_id=f"after:{progress.message_count}",+ expected_state={MESSAGES_COPIED_KEY: progress.message_count},+ state_updates={+ MESSAGES_COPIED_KEY: progress.message_count + len(new_messages),+ LAST_MESSAGE_ID_KEY: new_messages[-1].get("id"),+ },+ completed_at=updated_at,+ )+ if not appended:+ # The run's copied count is no longer what this copy read: another copy of the same+ # conversation moved it on. It may have copied fewer turns than this one saw, so the retry+ # re-reads the run and appends whatever is still missing.+ raise CopyConflict(f"conversation {conversation.id}: copied count moved past {progress.message_count}")+ await sync_to_async(tasks_facade.touch_imported_task)(+ task_id, team_id, title=conversation.title, last_activity_at=updated_at+ )+ logger.info(+ "conversation_mirror.appended",+ conversation_id=str(conversation.id),+ task_id=str(task_id),+ run_id=str(run.id),+ frames=len(frames),+ message_count=len(messages),+ )+ return MirrorResult(skipped_reason=None, task_id=task_id, run_id=run.id, appended_frames=len(frames))diff --git a/products/posthog_ai/backend/message_routing.py b/products/posthog_ai/backend/message_routing.pyindex e66307c59968..58492fbc6b5c 100644--- a/products/posthog_ai/backend/message_routing.py+++ b/products/posthog_ai/backend/message_routing.py@@ -119,14 +119,7 @@ class SandboxSession(BaseSandboxService):super().__init__(team=conversation.team, user=user)self.conversation: Conversation = conversation- def open(- self,- data: Mapping[str, Any],- *,- resumed_context: str | None = None,- convert_to_acp: bool = False,- repository: str | None = None,- ) -> SandboxRouteResult | None:+ def open(self, data: Mapping[str, Any], *, repository: str | None = None) -> SandboxRouteResult | None:task = self.conversation.taskif task is not None and (task.created_by_id != self.conversation.user_id or task.created_by_id != self.user.id):detach_conversations_for_task_handoff(task.id, task.created_by_id)@@ -146,16 +139,13 @@ class SandboxSession(BaseSandboxService):attached_context = self._validate_attached_context(data.get("attached_context"))if self.conversation.task_id is None:- # `resumed_context` / `convert_to_acp` only apply to the conversion event, which is- # always a first message (the gate requires `task_id is None`). `repository` is the- # auto-routed repo for this first message — followups/resumes reuse the existing Task.+ # `repository` is the auto-routed repo for this first message — followups/resumes reuse+ # the existing Task.return self._handle_first_message(content=content,trace_id=trace_id,attached_context=attached_context,initial_permission_mode=initial_permission_mode,- resumed_context=resumed_context,- convert_to_acp=convert_to_acp,repository=repository,)@@ -268,18 +258,12 @@ class SandboxSession(BaseSandboxService):trace_id: str | None,attached_context: list[AttachedContext],initial_permission_mode: InitialPermissionMode,- resumed_context: str | None = None,- convert_to_acp: bool = False,repository: str | None = None,) -> SandboxRouteResult:context_service = ContextService()# First turn — the prior-seen set is empty, so dedupe is a no-op.deduped = context_service.prune_repeated_entity_refs(attached_context, prior=[])wrapped = context_service.wrap_user_message(content, deduped)- if resumed_context:- # Conversion event: lead the first prompt with the legacy conversation window so the- # sandbox agent has continuity, then the user's own attachments + message.- wrapped = f"{resumed_context}\n\n{wrapped}"system_prompt = PromptService(self.team, self.user).build()@@ -312,36 +296,31 @@ class SandboxSession(BaseSandboxService):initial_permission_mode=initial_permission_mode,interaction_origin=POSTHOG_AI_INTERACTION_ORIGIN,pending_user_message=wrapped,- converted_from_langgraph=convert_to_acp,)state_updates = ph_state.model_dump(mode="json", by_alias=True, exclude_unset=True)# Persist the enriched run state and conversation linkage together, under the row lock so a- # concurrent first message / conversion in another tab can't double-link. Re-check- # `task_id is None` inside the lock; a half-write would orphan the run (enriched state, but- # conversation.task still NULL) and the next retry would look like a fresh first message. On- # a conversion, the runtime flip to sandbox happens here too, atomically with the link.+ # concurrent first message in another tab can't double-link. Re-check `task_id is None`+ # inside the lock; a half-write would orphan the run (enriched state, but conversation.task+ # still NULL) and the next retry would look like a fresh first message. A conversation+ # linked to a task is on the sandbox runtime, whatever runtime it was born on.+ previous_runtime = self.conversation.agent_runtimewith lock_conversation_for_followup(str(self.conversation.id), self.team.pk) as locked:if locked.task_id is not None:raise Conflict("This conversation was just resumed in another tab. Please try again.")tasks_facade.update_task_run_state(run_dto.id, updates=state_updates)locked.task_id = created.task_id- update_fields = ["task", "updated_at"]- if convert_to_acp:- locked.agent_runtime = Conversation.AgentRuntime.SANDBOX- update_fields = ["task", "agent_runtime", "updated_at"]- locked.save(update_fields=update_fields)+ locked.agent_runtime = Conversation.AgentRuntime.SANDBOX+ locked.save(update_fields=["task", "agent_runtime", "updated_at"])# Mirror the committed writes onto the in-memory instance for the response + the rollback below.self.conversation.task_id = created.task_id- if convert_to_acp:- self.conversation.agent_runtime = Conversation.AgentRuntime.SANDBOX+ self.conversation.agent_runtime = Conversation.AgentRuntime.SANDBOX# Start the run after the commit. `posthog_mcp_scopes="full"` mirrors the legacy# first-message path: the agent creates insights, dashboards, and notebooks, so it# needs write scopes (the workflow client otherwise defaults to read-only). If the- # start fails, un-link the conversation so the user's retry is a fresh first message- # rather than a follow-up onto a run that never started; on a conversion, also revert the- # runtime flip so the user is left on a clean idle LangGraph conversation.+ # start fails, un-link the conversation and restore its runtime so the user's retry is a+ # fresh first message rather than a follow-up onto a run that never started.try:dispatch_task_processing_workflow(task_id=str(created.task_id),@@ -353,11 +332,8 @@ class SandboxSession(BaseSandboxService):)except Exception:self.conversation.task_id = None- revert_fields = ["task", "updated_at"]- if convert_to_acp:- self.conversation.agent_runtime = Conversation.AgentRuntime.LANGGRAPH- revert_fields = ["task", "agent_runtime", "updated_at"]- self.conversation.save(update_fields=revert_fields)+ self.conversation.agent_runtime = previous_runtime+ self.conversation.save(update_fields=["task", "agent_runtime", "updated_at"])raisereturn SandboxRouteResult(diff --git a/products/posthog_ai/backend/receivers.py b/products/posthog_ai/backend/receivers.pynew file mode 100644index 000000000000..be2498a9e948--- /dev/null+++ b/products/posthog_ai/backend/receivers.py@@ -0,0 +1,134 @@+"""Keep a copied chat and its task in step once the task runs for real.++Both hooks connect through the tasks facade so no model class crosses the product boundary.++- Before a run starts: the copy runs a few seconds behind the chat, so a run started in that window+ would resume without the last turn. The guard copies what is still missing and refuses the run+ when it cannot, or when the chat's owner is not on the sandbox runtime yet.+- After a run is saved: the first run that is not the import run marks the chat as sandbox, whichever+ path created it. From then on the legacy chat screen routes the conversation through the sandbox+ path too, so a chat can never fork back into LangGraph after it has been continued as a task.+- When tasks are read: a user without the sandbox runtime does not see the copies of their chats. The+ copy is written for everyone so the switch is instant later, but until then their chats are chats.+"""++import logging+from collections.abc import Iterable+from typing import Any+from uuid import UUID++from asgiref.sync import async_to_sync++from posthog.models import Team, User++from products.posthog_ai.backend.models.assistant import Conversation+from products.tasks.backend.facade.task_run_signals import (+ TaskOriginProduct,+ connect_task_run_post_save,+ register_task_read_exclusion,+ register_task_run_start_guard,+)++logger = logging.getLogger(__name__)++COPY_BEHIND_MESSAGE = "This chat is still being copied into the task. Try again in a moment."+SANDBOX_MODE_REQUIRED_MESSAGE = "Continuing this chat as a task is not available to you yet."+++def _feature_flags() -> Any:+ """The flag helpers, or None in a build without ``ee``, where every hook here is a no-op."""+ # Deferred: the flag helpers pull in the LLM clients; this module loads at Django startup and must stay light.+ try:+ from ee.hogai.utils import feature_flags # noqa: PLC0415+ except ImportError:+ return None+ return feature_flags+++def connect() -> None:+ register_task_read_exclusion(copied_chats_hidden_without_sandbox_mode, name="posthog_ai_copied_chats")+ register_task_run_start_guard(catch_up_conversation_copy_before_run, name="posthog_ai_conversation_copy")+ connect_task_run_post_save(+ mark_conversation_sandbox_on_first_run, dispatch_uid="posthog_ai_conversation_follows_task_run"+ )+++def copied_chats_hidden_without_sandbox_mode(team_id: int, user_id: int | None) -> Iterable[UUID]:+ """The user's tasks that are copies of their LangGraph chats, while they are not on the sandbox runtime.++ Copies are only ever visible to the chat's owner, so the owner's own chats are the whole set.+ """+ flags = _feature_flags()+ if flags is None or user_id is None:+ return ()+ # Every task read calls this, and most users have no copied chat: answer that with one query+ # before paying for the team, the user and a flag evaluation.+ copied_task_ids = list(+ Conversation.objects.filter(+ team_id=team_id, user_id=user_id, task_id__isnull=False, agent_runtime=Conversation.AgentRuntime.LANGGRAPH+ ).values_list("task_id", flat=True)+ )+ if not copied_task_ids:+ return ()+ team = Team.objects.filter(id=team_id).only("id", "organization_id").first()+ user = User.objects.filter(id=user_id).only("id", "distinct_id").first()+ if team is None or user is None or flags.has_sandbox_mode_feature_flag(team, user):+ return ()+ return copied_task_ids+++def catch_up_conversation_copy_before_run(task_id: str, team_id: int, user_id: int | None) -> str | None:+ """Copy a LangGraph chat's missing turns into its task before the task's first real run."""+ flags = _feature_flags()+ if flags is None:+ return None+ # Deferred: the copy pulls in the tasks facade and the LangGraph graph.+ from products.posthog_ai.backend.conversation_mirror import amirror_conversation # noqa: PLC0415++ conversation = (+ Conversation.objects.select_related("user", "team")+ .filter(task_id=task_id, team_id=team_id, agent_runtime=Conversation.AgentRuntime.LANGGRAPH, deleted=False)+ .first()+ )+ if conversation is None:+ return None+ if not flags.has_sandbox_mode_feature_flag(conversation.team, conversation.user):+ return SANDBOX_MODE_REQUIRED_MESSAGE+ if not flags.has_conversation_task_mirror_feature_flag(conversation.team, conversation.user):+ # The kill switch stops copying altogether; a stale copy is then expected, not a reason to refuse.+ return None+ try:+ result = async_to_sync(amirror_conversation)(conversation.id, team_id, conversation.user_id)+ except Exception:+ logger.exception("conversation_copy_before_run_failed", extra={"task_id": task_id})+ return COPY_BEHIND_MESSAGE+ # Content the copy cannot read stays uncopied on every retry, so it must not hold the run back.+ if result.skipped_reason not in (None, "no_messages", "unsupported_content"):+ return COPY_BEHIND_MESSAGE+ return None+++def mark_conversation_sandbox_on_first_run(sender: type, instance: Any, created: bool, **kwargs: Any) -> None:+ # Runs on every TaskRun save (a hot model): cheapest checks first, and never raise into tasks' save path.+ state = instance.state or {}+ # A warm run only prepares a sandbox; the chat moves when a run carries a message.+ if not created or state.get("imported_from") or state.get("await_user_message"):+ return+ try:+ if instance.task.origin_product != TaskOriginProduct.POSTHOG_AI:+ return+ flags = _feature_flags()+ if flags is None:+ return+ conversations = Conversation.objects.select_related("user", "team").filter(+ task_id=instance.task_id, agent_runtime=Conversation.AgentRuntime.LANGGRAPH+ )+ for conversation in conversations:+ if not flags.has_sandbox_mode_feature_flag(conversation.team, conversation.user):+ # Without the flag the legacy screen cannot send to the sandbox path, so the chat stays put.+ continue+ Conversation.objects.filter(id=conversation.id, agent_runtime=Conversation.AgentRuntime.LANGGRAPH).update(+ agent_runtime=Conversation.AgentRuntime.SANDBOX+ )+ except Exception:+ logger.exception("conversation_follows_task_run_failed", extra={"run_id": str(instance.id)})diff --git a/products/posthog_ai/backend/run_state.py b/products/posthog_ai/backend/run_state.pyindex 4f31d2aeea33..766bf9624fc2 100644--- a/products/posthog_ai/backend/run_state.py+++ b/products/posthog_ai/backend/run_state.py@@ -30,7 +30,3 @@ class PostHogAIRunState(RunState):# (``state__await_user_message=True`` in products/tasks/backend/logic/services/warm.py), so an alias# here would change the stored key and silently stop the filter from matching — opening the cap.await_user_message: bool = False- # Set on the first Run of a conversation that moved here from the LangGraph runtime. The- # conversation carries its history across the flip, so its chat analytics must not report it- # as a new one (products/tasks/.../update_task_run_status.py reads this key).- converted_from_langgraph: bool = Falsediff --git a/products/posthog_ai/backend/task_ownership.py b/products/posthog_ai/backend/task_ownership.pyindex dc6e81419a6b..7f3b69993c14 100644--- a/products/posthog_ai/backend/task_ownership.py+++ b/products/posthog_ai/backend/task_ownership.py@@ -1,6 +1,7 @@from uuid import UUIDfrom django.db.models import Q+from django.utils import timezonefrom products.posthog_ai.backend.models.assistant import Conversation@@ -11,3 +12,8 @@ def detach_conversations_for_task_handoff(task_id: UUID, new_owner_id: int | Nonif new_owner_id is not None:conversations = conversations.exclude(user_id=new_owner_id)return conversations.update(task=None, sandbox_task_id=None, sandbox_run_id=None)+++def soft_delete_conversations_for_task(task_id: UUID) -> int:+ """A task and its conversation are one chat; deleting the task deletes the chat too."""+ return Conversation.objects.filter(task_id=task_id, deleted=False).update(deleted=True, deleted_at=timezone.now())diff --git a/products/posthog_ai/backend/temporal/__init__.py b/products/posthog_ai/backend/temporal/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/posthog_ai/backend/temporal/activities.py b/products/posthog_ai/backend/temporal/activities.pynew file mode 100644index 000000000000..71d576a136e4--- /dev/null+++ b/products/posthog_ai/backend/temporal/activities.py@@ -0,0 +1,36 @@+from dataclasses import dataclass++import structlog+from asgiref.sync import sync_to_async+from temporalio import activity++from posthog.models import Team, User++from products.posthog_ai.backend.conversation_mirror import MirrorResult, amirror_conversation++from ee.hogai.utils.feature_flags import has_conversation_task_mirror_feature_flag++logger = structlog.get_logger(__name__)+++@dataclass(frozen=True)+class MirrorConversationInputs:+ team_id: int+ user_id: int+ conversation_id: str+++async def mirror_conversation_to_task_activity(inputs: MirrorConversationInputs) -> None:+ team = await Team.objects.aget(id=inputs.team_id)+ user = await User.objects.aget(id=inputs.user_id)+ if not await sync_to_async(has_conversation_task_mirror_feature_flag)(team, user):+ result = MirrorResult(skipped_reason="flag", task_id=None, run_id=None, appended_frames=0)+ else:+ result = await amirror_conversation(inputs.conversation_id, inputs.team_id, inputs.user_id)+ logger.info(+ "conversation_mirror.activity_done",+ conversation_id=inputs.conversation_id,+ skipped_reason=result.skipped_reason,+ appended_frames=result.appended_frames,+ )diff --git a/products/posthog_ai/backend/temporal/workflows.py b/products/posthog_ai/backend/temporal/workflows.pynew file mode 100644index 000000000000..015ded110f1c--- /dev/null+++ b/products/posthog_ai/backend/temporal/workflows.py@@ -0,0 +1,39 @@+import json+from datetime import timedelta++from temporalio import workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow++from products.posthog_ai.backend.temporal.activities import (+ MirrorConversationInputs,+ mirror_conversation_to_task_activity,+)++MIRROR_ACTIVITY_TIMEOUT = 2 * 60 # 2 minutes+MIRROR_ACTIVITY_MAX_ATTEMPTS = 3++[email protected](name="conversation-mirror")+class ConversationMirrorWorkflow(PostHogWorkflow):+ """Copy a LangGraph conversation's newest turn into its task.++ The chat workflow starts this as a detached child and closes without waiting for it. The chat+ workflow's id is fixed per conversation, so a follow-up sent while it is still open joins the+ old execution and loses its message; keeping the copy out of that workflow keeps that window as+ short as it was before the copy existed.+ """++ @staticmethod+ def parse_inputs(inputs: list[str]) -> MirrorConversationInputs:+ return MirrorConversationInputs(**json.loads(inputs[0]))++ @workflow.run+ async def run(self, inputs: MirrorConversationInputs) -> None:+ await workflow.execute_activity(+ mirror_conversation_to_task_activity,+ inputs,+ start_to_close_timeout=timedelta(seconds=MIRROR_ACTIVITY_TIMEOUT),+ retry_policy=RetryPolicy(maximum_attempts=MIRROR_ACTIVITY_MAX_ATTEMPTS),+ )diff --git a/products/posthog_ai/backend/tests/test_context_wrapper.py b/products/posthog_ai/backend/tests/test_context_wrapper.pyindex 8705988e2512..8e6d5d4eb1c9 100644--- a/products/posthog_ai/backend/tests/test_context_wrapper.py+++ b/products/posthog_ai/backend/tests/test_context_wrapper.py@@ -1,22 +1,4 @@-from posthog.test.base import APIBaseTest-from unittest.mock import patch--from asgiref.sync import async_to_sync--from posthog.schema import (- AssistantMessage,- AssistantToolCall,- AssistantToolCallMessage,- ContextMessage,- HumanMessage,- ReasoningMessage,-)-from products.posthog_ai.backend.context_wrapper import AttachedContext, ContextService-from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.api.serializers import ConversationStateResult-from ee.hogai.utils.types import AssistantStateSERIALIZERS = "ee.hogai.api.serializers"WRAPPER = "products.posthog_ai.backend.context_wrapper"@@ -138,101 +120,3 @@ def test_prune_then_wrap_empties_to_bare_content():attached: list[AttachedContext] = [{"type": "dashboard", "id": 1, "name": "Funnel"}]deduped = ContextService().prune_repeated_entity_refs(attached, prior=prior)assert ContextService().wrap_user_message("just text", deduped) == "just text"---class TestResumedLegacyContext(APIBaseTest):- """`abuild_resumed_legacy_context` — the one-time legacy-history block on a conversion event."""-- def setUp(self):- super().setUp()- self.conversation = Conversation.objects.create(- user=self.user,- team=self.team,- agent_runtime=Conversation.AgentRuntime.LANGGRAPH,- )-- def _build(self, state):- async def _aget(conversation, team, user):- return ConversationStateResult(state=state, has_unsupported_content=False, interrupt_payloads={})-- with (- patch(f"{SERIALIZERS}.aget_conversation_state", side_effect=_aget),- patch(f"{WRAPPER}.posthoganalytics.capture") as m_capture,- ):- block = async_to_sync(ContextService().abuild_resumed_legacy_context)(- self.conversation, self.team, self.user- )- return block, m_capture-- def test_renders_full_window_as_transcript(self):- state = AssistantState(- messages=[- HumanMessage(content="why did checkout drop?", id="h1"),- AssistantMessage(content="let me check", id="a1"),- ]- )- block, _ = self._build(state)- assert block == (- "<posthog_context>This session was resumed from the legacy implementation.\n"- "User: why did checkout drop?\nAssistant: let me check</posthog_context>"- )-- def test_window_truncates_to_root_start_id(self):- # Only the current window (from root_conversation_start_id onward) feeds the resumed block.- state = AssistantState(- messages=[- HumanMessage(content="old", id="h1"),- AssistantMessage(content="old answer", id="a1"),- HumanMessage(content="current", id="h2"),- ],- root_conversation_start_id="h2",- )- block, _ = self._build(state)- assert block is not None- assert "old" not in block- assert block.endswith("User: current</posthog_context>")-- def test_renders_tool_calls_thinking_and_context(self):- state = AssistantState(- messages=[- HumanMessage(content="why did checkout drop?", id="h1"),- ContextMessage(content="user is on the growth plan", id="c1"),- ReasoningMessage(content="let me query the funnel", id="r1"),- AssistantMessage(- content="checking",- id="a1",- tool_calls=[AssistantToolCall(id="tc1", name="query_runner", args={"q": "funnel"})],- ),- AssistantToolCallMessage(content="3 steps, 40% drop at payment", id="t1", tool_call_id="tc1"),- ]- )- block, _ = self._build(state)- assert block is not None- assert "User: why did checkout drop?" in block- assert "Context: user is on the growth plan" in block- assert "Thinking: let me query the funnel" in block- assert "Assistant: checking" in block- assert 'Tool call query_runner({"q": "funnel"})' in block- assert "Tool result: 3 steps, 40% drop at payment" in block-- def test_returns_none_when_no_state(self):- block, m_capture = self._build(None)- assert block is None- m_capture.assert_not_called()-- def test_returns_none_when_transcript_empty(self):- # An empty assistant message is filtered by should_output_assistant_message — no transcript.- state = AssistantState(messages=[AssistantMessage(content="", id="a1")])- block, _ = self._build(state)- assert block is None-- def test_emits_telemetry_without_frame_fields(self):- state = AssistantState(messages=[HumanMessage(content="q", id="h1"), AssistantMessage(content="a", id="a1")])- _, m_capture = self._build(state)- calls = [c for c in m_capture.call_args_list if c.kwargs.get("event") == "phai_legacy_conversion"]- assert len(calls) == 1- props = calls[0].kwargs["properties"]- assert props["messages_total"] == 2- assert props["window_messages"] == 2- assert "duration_ms" in props- assert not any(key.startswith("frames_") for key in props)diff --git a/products/posthog_ai/backend/tests/test_conversation_mirror.py b/products/posthog_ai/backend/tests/test_conversation_mirror.pynew file mode 100644index 000000000000..90266057c56d--- /dev/null+++ b/products/posthog_ai/backend/tests/test_conversation_mirror.py@@ -0,0 +1,518 @@+import json+from datetime import UTC, datetime+from typing import Any++import pytest+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import SimpleTestCase+from django.utils import timezone++from asgiref.sync import async_to_sync+from parameterized import parameterized++from posthog.schema import AssistantMessage, AssistantToolCall, AssistantToolCallMessage, ContextMessage, HumanMessage++from posthog.models import User++from products.posthog_ai.backend.conversation_mirror import (+ LAST_MESSAGE_ID_KEY,+ MESSAGES_COPIED_KEY,+ CopyConflict,+ CopyProgress,+ amirror_conversation,+ origin_key_for_conversation,+ project_legacy_messages,+)+from products.posthog_ai.backend.models.assistant import Conversation, ConversationCheckpoint+from products.posthog_ai.backend.temporal.activities import (+ MirrorConversationInputs,+ mirror_conversation_to_task_activity,+)+from products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.models import Task, TaskRun++from ee.hogai.api.serializers import (+ ConversationStateResult,+ aget_conversation_state as real_aget_conversation_state,+)+from ee.hogai.utils.types import AssistantState++SERIALIZERS = "ee.hogai.api.serializers"+MIRROR = "products.posthog_ai.backend.conversation_mirror"+ACTIVITIES = "products.posthog_ai.backend.temporal.activities"+MODELS = "products.tasks.backend.models"+++def _method(frame: dict[str, Any]) -> str:+ notification = frame["notification"]+ method = notification["method"]+ if method == "session/update":+ return f"{method}:{notification['params']['update']['sessionUpdate']}"+ return method+++VIZ_TURN: list[dict[str, Any]] = [+ {"type": "human", "id": "h1", "content": "Show me pageviews for the last 7 days"},+ {+ "type": "ai",+ "id": "a1",+ "content": "",+ "meta": {"thinking": [{"type": "thinking", "thinking": "A trends insight fits."}]},+ "tool_calls": [{"id": "toolu_1", "name": "create_insight", "args": {"insight_type": "trends"}}],+ },+ {+ "type": "ai/artifact",+ "id": "art1",+ "artifact_id": "Ab12",+ "content": {+ "content_type": "visualization",+ "name": "Pageviews",+ "description": "Daily",+ "query": {"kind": "TrendsQuery"},+ },+ },+ {"type": "tool", "id": "t1", "tool_call_id": "toolu_1", "content": "Name: Pageviews\nArtifact ID: Ab12"},+ {"type": "ai", "id": "a2", "content": "Here is your trend."},+]+++class TestProjectLegacyMessages(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "viz_turn",+ VIZ_TURN,+ [+ "_posthog/run_started",+ "session/update:user_message_chunk",+ "session/update:agent_thought_chunk",+ "session/update:tool_call",+ "session/update:tool_call_update",+ "session/update:tool_call_update",+ "session/update:agent_message",+ "_posthog/turn_complete",+ ],+ ),+ (+ "failed_turn",+ [+ {"type": "human", "id": "h1", "content": "hi"},+ {"type": "ai/failure", "id": "f1", "content": "Oops"},+ ],+ [+ "_posthog/run_started",+ "session/update:user_message_chunk",+ "_posthog/error",+ "_posthog/turn_complete",+ ],+ ),+ (+ "unanswered_question_has_no_separator",+ [{"type": "human", "id": "h1", "content": "hi"}],+ ["_posthog/run_started", "session/update:user_message_chunk"],+ ),+ (+ "compaction_summary_is_a_user_turn",+ [+ {"type": "context", "id": "c1", "content": "Summary of earlier turns"},+ {"type": "human", "id": "h2", "content": "and now?"},+ {"type": "ai", "id": "a2", "content": "Now this."},+ ],+ [+ "_posthog/run_started",+ "session/update:user_message_chunk",+ "session/update:user_message_chunk",+ "session/update:agent_message",+ "_posthog/turn_complete",+ ],+ ),+ ]+ )+ def test_frame_sequence(self, _name: str, messages: list[dict[str, Any]], expected: list[str]) -> None:+ frames = project_legacy_messages(+ messages,+ run_id="run-1",+ include_run_start=True,+ )+ assert [_method(f) for f in frames] == expected++ def test_tool_frames_carry_exec_origin_and_artifact_query(self) -> None:+ frames = project_legacy_messages(+ VIZ_TURN,+ run_id="run-1",+ include_run_start=False,+ )+ user = frames[0]["notification"]["params"]+ assert user["sessionId"] == "run-1"+ assert user["update"]["_meta"] == {"importedUserPrompt": True, "imported": True}+ call, call_input, result = (f["notification"]["params"]["update"] for f in frames[2:5])+ assert call["_meta"]["claudeCode"]["toolName"] == "mcp__posthog__exec"+ # The thread renders the insight card only for the exec sub-tool name, not the legacy one.+ assert call_input["rawInput"]["command"] == 'call insight-create {"insight_type": "trends"}'+ assert result["status"] == "completed"+ assert result["rawOutput"]["artifact_id"] == "Ab12"+ assert result["rawOutput"]["query"] == {"kind": "TrendsQuery"}+ # The sandbox resume parser reads tool history only from _meta.claudeCode.+ for frame in (call, call_input, result):+ assert frame["_meta"]["claudeCode"]["toolCallId"] == "toolu_1"+ assert call["_meta"]["claudeCode"]["toolInput"] == {"command": call_input["rawInput"]["command"]}+ assert result["_meta"]["claudeCode"]["toolResponse"] == result["rawOutput"]+ assert result["content"][0]["content"]["text"].startswith("Name: Pageviews")++ def test_context_messages_are_hidden_from_the_thread(self) -> None:+ frames = project_legacy_messages(+ [+ {"type": "context", "id": "c1", "content": "Summary of earlier turns"},+ {"type": "human", "id": "h2", "content": "and now?"},+ ],+ run_id="run-1",+ include_run_start=False,+ )+ summary, question = (f["notification"]["params"]["update"]["content"] for f in frames)+ assert summary == {"type": "text", "text": "Summary of earlier turns", "_meta": {"ui": {"hidden": True}}}+ assert question == {"type": "text", "text": "and now?"}++ def test_recordings_filters_ride_the_tool_result(self) -> None:+ filters = {"date_from": "-7d", "duration": [], "filter_group": {"type": "AND", "values": []}}+ messages: list[dict[str, Any]] = [+ {+ "type": "ai",+ "id": "a1",+ "content": "",+ "tool_calls": [+ {"id": "c1", "name": "filter_session_recordings", "args": {"recordings_filters": filters}}+ ],+ },+ {"type": "tool", "id": "t1", "tool_call_id": "c1", "content": "Found 3 recordings"},+ ]+ frames = project_legacy_messages(+ messages,+ run_id="r",+ include_run_start=False,+ )+ assert frames[-2]["notification"]["params"]["update"]["rawOutput"]["filters"] == filters+++class TestMirrorConversation(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.conversation = Conversation.objects.create(user=self.user, team=self.team, title="Pageviews chat")+ self.logs: dict[str, str] = {}+ self.state_messages: list[Any] = []+ self._patches = [+ patch(f"{SERIALIZERS}.aget_conversation_state", side_effect=self._aget_state),+ patch(f"{MODELS}.object_storage.read", side_effect=lambda key, **kw: self.logs.get(key)),+ patch(+ f"{MODELS}.object_storage.write",+ side_effect=lambda key, content, **kw: self.logs.__setitem__(key, content),+ ),+ patch(f"{MODELS}.object_storage.tag"),+ ]+ for p in self._patches:+ p.start()+ self.addCleanup(p.stop)++ async def _aget_state(+ self, conversation: Conversation, team: Any, user: Any, **kwargs: Any+ ) -> ConversationStateResult:+ return ConversationStateResult(+ state=AssistantState(messages=self.state_messages), has_unsupported_content=False, interrupt_payloads={}+ )++ def _mirror(self):+ return async_to_sync(amirror_conversation)(self.conversation.id, self.team.id, self.user.id)++ def _log_methods(self) -> list[str]:+ (content,) = self.logs.values()+ return [_method(json.loads(line)) for line in content.strip().split("\n")]++ def test_first_touch_creates_task_and_import_run_then_appends(self) -> None:+ self.state_messages = [HumanMessage(content="hello", id="h1"), AssistantMessage(content="hi there", id="a1")]+ started_at = datetime(2026, 5, 1, 12, 0, tzinfo=UTC)+ Conversation.objects.filter(id=self.conversation.id).update(created_at=started_at)++ result = self._mirror()++ assert result.skipped_reason is None+ task = Task.objects.get(id=result.task_id)+ assert task.origin_key == origin_key_for_conversation(self.conversation.id)+ assert task.origin_product == Task.OriginProduct.POSTHOG_AI+ assert task.title == "Pageviews chat"+ assert task.title_manually_set is False+ assert task.channel_id is not None+ assert task.created_at == started_at+ self.conversation.refresh_from_db()+ assert self.conversation.task_id == task.id+ run = TaskRun.objects.get(id=result.run_id)+ assert run.status == TaskRun.Status.COMPLETED+ assert run.created_at == started_at+ assert run.state["imported_from"] == "conversation"+ assert run.state[MESSAGES_COPIED_KEY] == 2+ assert run.state[LAST_MESSAGE_ID_KEY] == "a1"+ assert run.completed_at == self.conversation.updated_at+ assert self._log_methods() == [+ "_posthog/run_started",+ "session/update:user_message_chunk",+ "session/update:agent_message",+ "_posthog/turn_complete",+ ]++ self.state_messages = [+ *self.state_messages,+ HumanMessage(content="more", id="h2"),+ AssistantMessage(content="sure", id="a2"),+ ]+ continued_at = datetime(2026, 5, 2, 9, 30, tzinfo=UTC)+ Conversation.objects.filter(id=self.conversation.id).update(updated_at=continued_at)+ second = self._mirror()++ assert (second.task_id, second.run_id) == (result.task_id, result.run_id)+ assert second.appended_frames == 3+ assert self._log_methods()[-3:] == [+ "session/update:user_message_chunk",+ "session/update:agent_message",+ "_posthog/turn_complete",+ ]+ run.refresh_from_db()+ assert run.state[MESSAGES_COPIED_KEY] == 4+ assert run.state[LAST_MESSAGE_ID_KEY] == "a2"+ assert run.completed_at == continued_at+ assert TaskRun.objects.filter(task_id=result.task_id).count() == 1++ third = self._mirror()+ assert third.appended_frames == 0+ assert len(self._log_methods()) == 7++ def test_artifact_query_survives_the_round_trip(self) -> None:+ self.state_messages = [+ HumanMessage(content="pageviews?", id="h1"),+ AssistantMessage(+ content="",+ id="a1",+ tool_calls=[AssistantToolCall(id="toolu_1", name="create_insight", args={"insight_type": "trends"})],+ ),+ AssistantToolCallMessage(content="Name: Pageviews", id="t1", tool_call_id="toolu_1"),+ AssistantMessage(content="done", id="a2"),+ ]+ result = self._mirror()+ assert result.appended_frames == 7+ assert "session/update:tool_call_update" in self._log_methods()++ def test_compaction_that_keeps_the_last_copied_message_copies_only_what_follows(self) -> None:+ self.state_messages = [+ HumanMessage(content="one", id="h1"),+ AssistantMessage(content="1", id="a1"),+ HumanMessage(content="two", id="h2"),+ AssistantMessage(content="2", id="a2"),+ ]+ first = self._mirror()+ # Compaction dropped the first turn from the stored list; the anchor a2 is still there.+ self.state_messages = [+ HumanMessage(content="two", id="h2"),+ AssistantMessage(content="2", id="a2"),+ HumanMessage(content="three", id="h3"),+ AssistantMessage(content="3", id="a3"),+ ]+ second = self._mirror()+ assert second.appended_frames == 3+ assert self._log_methods().count("session/update:user_message_chunk") == 3+ run = TaskRun.objects.get(id=first.run_id)+ assert run.state[LAST_MESSAGE_ID_KEY] == "a3"+ assert run.state[MESSAGES_COPIED_KEY] == 6++ def test_compaction_that_dropped_the_last_copied_message_copies_the_whole_window(self) -> None:+ self.state_messages = [HumanMessage(content="one", id="h1"), AssistantMessage(content="1", id="a1")]+ self._mirror()+ # Everything copied so far was compacted away; the window holds only newer turns.+ self.state_messages = [HumanMessage(content="four", id="h4"), AssistantMessage(content="4", id="a4")]+ second = self._mirror()+ assert second.appended_frames == 3+ assert self._log_methods().count("session/update:user_message_chunk") == 2+ assert TaskRun.objects.get(id=second.run_id).state[LAST_MESSAGE_ID_KEY] == "a4"++ def test_a_concurrent_copy_that_already_moved_the_run_on_raises_so_the_activity_retries(self):+ self.state_messages = [HumanMessage(content="hello", id="h1"), AssistantMessage(content="hi", id="a1")]+ self._mirror()+ # A second copier that read the run before the first one wrote it sees nothing copied yet.+ with (+ patch(f"{MIRROR}._read_copy_progress", return_value=CopyProgress(message_count=0, last_message_id=None)),+ pytest.raises(CopyConflict),+ ):+ self._mirror()+ assert len(self._log_methods()) == 4++ def test_a_title_the_user_set_on_the_task_survives_later_copies(self) -> None:+ self.state_messages = [HumanMessage(content="hello", id="h1"), AssistantMessage(content="hi", id="a1")]+ first = self._mirror()+ Task.objects.filter(id=first.task_id).update(title="My renamed task", title_manually_set=True)+ self.state_messages += [HumanMessage(content="more", id="h2"), AssistantMessage(content="ok", id="a2")]++ self._mirror()++ assert Task.objects.get(id=first.task_id).title == "My renamed task"++ def test_read_failure_raises_so_the_activity_retries(self) -> None:+ ConversationCheckpoint.objects.create(thread=self.conversation)+ with (+ patch(f"{SERIALIZERS}.CONVERSATION_TYPE_MAP", {}),+ patch(f"{SERIALIZERS}.capture_exception") as capture,+ ):+ lenient = async_to_sync(real_aget_conversation_state)(self.conversation, self.team, self.user)+ with pytest.raises(KeyError):+ async_to_sync(real_aget_conversation_state)(+ self.conversation, self.team, self.user, raise_on_error=True+ )+ assert lenient.state is None+ capture.assert_called_once()++ def test_unsupported_content_is_a_named_skip(self) -> None:+ unsupported = ConversationStateResult(state=None, has_unsupported_content=True, interrupt_payloads={})+ with patch(f"{SERIALIZERS}.aget_conversation_state", return_value=unsupported):+ result = self._mirror()+ assert result.skipped_reason == "unsupported_content"+ assert not Task.objects.filter(team=self.team).exists()++ def test_skips_a_copy_requested_by_someone_other_than_the_owner(self) -> None:+ self.state_messages = [HumanMessage(content="hello", id="h1"), AssistantMessage(content="hi", id="a1")]+ other = User.objects.create_and_join(self.organization, "[email protected]", None)+ result = async_to_sync(amirror_conversation)(self.conversation.id, self.team.id, other.id)+ assert result.skipped_reason == "owner_mismatch"+ assert not Task.objects.filter(team=self.team).exists()++ def test_retry_after_a_failed_state_write_does_not_copy_the_turn_twice(self):+ self.state_messages = [HumanMessage(content="hello", id="h1"), AssistantMessage(content="hi", id="a1")]+ # The log append succeeds, then the state write fails and rolls the transaction back.+ original_save = TaskRun.save++ def save_but_fail_the_progress_write(run, *args, **kwargs):+ if kwargs.get("update_fields") == ["state", "completed_at"]:+ raise RuntimeError("db down")+ return original_save(run, *args, **kwargs)++ with patch.object(TaskRun, "save", save_but_fail_the_progress_write), self.assertRaises(RuntimeError):+ self._mirror()+ assert len(self._log_methods()) == 4+ assert TaskRun.objects.get(state__has_key="imported_from").state[MESSAGES_COPIED_KEY] == 0++ result = self._mirror()++ assert result.appended_frames == 4+ assert len(self._log_methods()) == 4+ assert TaskRun.objects.get(id=result.run_id).state[MESSAGES_COPIED_KEY] == 2++ def test_a_turn_still_in_progress_waits_for_the_next_copy(self) -> None:+ self.state_messages = [+ HumanMessage(content="hello", id="h1"),+ AssistantMessage(content="hi", id="a1"),+ HumanMessage(content="chart it", id="h2"),+ AssistantMessage(+ content="",+ id="a2",+ tool_calls=[AssistantToolCall(id="c1", name="create_insight", args={})],+ ),+ ]+ first = self._mirror()+ assert first.appended_frames == 4+ assert TaskRun.objects.get(id=first.run_id).state[MESSAGES_COPIED_KEY] == 2++ self.state_messages = [+ *self.state_messages,+ AssistantToolCallMessage(content="done", id="t1", tool_call_id="c1"),+ AssistantMessage(content="here it is", id="a3"),+ ]+ second = self._mirror()+ assert second.run_id == first.run_id+ assert TaskRun.objects.get(id=first.run_id).state[MESSAGES_COPIED_KEY] == 6+ assert self._log_methods().count("session/update:user_message_chunk") == 2++ def test_concurrent_first_touches_share_one_import_run(self) -> None:+ self.state_messages = [HumanMessage(content="hello", id="h1"), AssistantMessage(content="hi", id="a1")]+ first = self._mirror()+ assert first.task_id is not None+ duplicate = tasks_facade.create_imported_task_run(+ first.task_id,+ self.team.id,+ state={"imported_from": "conversation"},+ created_at=self.conversation.created_at or timezone.now(),+ completed_at=timezone.now(),+ )+ assert duplicate.id == first.run_id+ assert TaskRun.objects.filter(task_id=first.task_id, state__has_key="imported_from").count() == 1++ def test_deleting_the_task_deletes_the_chat_and_stops_the_copy(self) -> None:+ self.state_messages = [HumanMessage(content="hello", id="h1"), AssistantMessage(content="hi", id="a1")]+ first = self._mirror()+ assert first.task_id is not None++ assert tasks_facade.soft_delete_task(first.task_id, self.team.id, self.user.id)++ self.conversation.refresh_from_db()+ assert self.conversation.deleted+ Conversation.objects.filter(id=self.conversation.id).update(deleted=False)+ self.state_messages = [+ *self.state_messages,+ HumanMessage(content="more", id="h2"),+ AssistantMessage(content="ok", id="a2"),+ ]+ assert self._mirror().skipped_reason == "task_deleted"+ assert len(self._log_methods()) == 4++ def test_compaction_summary_is_copied(self) -> None:+ self.state_messages = [+ ContextMessage(content="Summary: the user asked about pageviews", id="c1"),+ HumanMessage(content="and by device?", id="h2"),+ AssistantMessage(content="Mostly mobile.", id="a2"),+ ]++ result = self._mirror()++ assert TaskRun.objects.get(id=result.run_id).state[MESSAGES_COPIED_KEY] == 3+ (content,) = self.logs.values()+ assert '"hidden": true' in content and "Summary: the user asked about pageviews" in content++ def test_moved_conversation_renders_no_checkpoint_history(self):+ # Once the history is in the task's import run, the checkpoint must not render as well.+ self.state_messages = [HumanMessage(content="hello", id="h1"), AssistantMessage(content="hi", id="a1")]+ self._mirror()+ ConversationCheckpoint.objects.create(thread=self.conversation)+ Conversation.objects.filter(id=self.conversation.id).update(agent_runtime=Conversation.AgentRuntime.SANDBOX)+ self.conversation.refresh_from_db()++ with patch(f"{SERIALIZERS}.capture_exception") as capture:+ result = async_to_sync(real_aget_conversation_state)(self.conversation, self.team, self.user)++ assert result.state is None+ capture.assert_not_called()++ @parameterized.expand(+ [+ ("sandbox_runtime", {"agent_runtime": Conversation.AgentRuntime.SANDBOX}, "runtime"),+ ("tool_call_type", {"type": Conversation.Type.TOOL_CALL}, "type"),+ ("deleted", {"deleted": True}, "deleted"),+ ("support_impersonation", {"is_internal": True}, "internal"),+ ]+ )+ def test_skips_conversations_that_must_not_be_mirrored(+ self, _name: str, setup: dict[str, Any], reason: str+ ) -> None:+ self.state_messages = [HumanMessage(content="hello", id="h1"), AssistantMessage(content="hi", id="a1")]+ for field, value in setup.items():+ setattr(self.conversation, field, value)+ self.conversation.save()+ result = self._mirror()+ assert result.skipped_reason == reason+ assert not Task.objects.filter(team=self.team).exists()+ assert self.logs == {}+++class TestMirrorActivity(APIBaseTest):+ def test_kill_switch_skips_the_copy(self) -> None:+ inputs = MirrorConversationInputs(team_id=self.team.id, user_id=self.user.id, conversation_id="c")+ with (+ patch(f"{ACTIVITIES}.has_conversation_task_mirror_feature_flag", return_value=False),+ patch(f"{ACTIVITIES}.amirror_conversation") as m_mirror,+ ):+ async_to_sync(mirror_conversation_to_task_activity)(inputs)+ m_mirror.assert_not_called()diff --git a/products/posthog_ai/backend/tests/test_message_routing.py b/products/posthog_ai/backend/tests/test_message_routing.pyindex b7ddeaad4e3a..1ce00df94cd8 100644--- a/products/posthog_ai/backend/tests/test_message_routing.py+++ b/products/posthog_ai/backend/tests/test_message_routing.py@@ -696,11 +696,10 @@ class TestAwaitUserMessageStoredKey:assert dumped == {"await_user_message": True}-class TestSandboxFirstMessageConversion(APIBaseTest):- """Converting an idle LangGraph conversation on its first sandbox message.+class TestSandboxFirstMessageOnLangGraphConversation(APIBaseTest):+ """A LangGraph conversation with no task takes the ordinary first-message path.- Conversion is just: flip the runtime + link the Task on the normal first-message path, with the- legacy window prepended to the first prompt. No ACP seeding, no synthetic historical run.+ Linking the task marks the conversation sandbox; nothing else about the path changes."""def setUp(self):@@ -713,20 +712,13 @@ class TestSandboxFirstMessageConversion(APIBaseTest):status=Conversation.Status.IDLE,)- def _block(self) -> str:- return "<posthog_context>This session was resumed from the legacy implementation.\nUser: hi</posthog_context>"-- def _open(self, *, resumed_context=None, convert_to_acp=False, content="continue here"):+ def _open(self, *, content="continue here"):with patch(f"{ROUTING}.dispatch_task_processing_workflow") as m_workflow:- result = SandboxSession(self.conversation, self.user).open(- {"content": content, "trace_id": "t"},- resumed_context=resumed_context,- convert_to_acp=convert_to_acp,- )+ result = SandboxSession(self.conversation, self.user).open({"content": content, "trace_id": "t"})return result, m_workflow- def test_first_message_conversion_flips_runtime_and_links_task(self):- result, m_workflow = self._open(resumed_context=self._block(), convert_to_acp=True)+ def test_first_message_links_task_and_marks_runtime_sandbox(self):+ result, m_workflow = self._open()self.conversation.refresh_from_db()assert self.conversation.agent_runtime == Conversation.AgentRuntime.SANDBOX@@ -735,33 +727,16 @@ class TestSandboxFirstMessageConversion(APIBaseTest):task = self.conversation.taskassert task is not Noneassert task.origin_product == Task.OriginProduct.POSTHOG_AI- # The live first run, not a synthetic terminal one.assert task.runs.count() == 1first_run = task.runs.first()assert first_run is not Noneassert first_run.status != TaskRun.Status.COMPLETED+ assert first_run.state["pending_user_message"] == "continue here"assert result is not Noneassert result.just_created_run is Truem_workflow.assert_called_once()- def test_first_message_conversion_does_not_seed_s3_log(self):- with patch.object(TaskRun, "append_log") as m_append:- self._open(resumed_context=self._block(), convert_to_acp=True)- m_append.assert_not_called()-- def test_first_message_conversion_prepends_window_context(self):- self._open(resumed_context=self._block(), convert_to_acp=True)-- self.conversation.refresh_from_db()- task = self.conversation.task- assert task is not None- run = task.runs.first()- assert run is not None- pending = run.state["pending_user_message"]- assert pending.startswith(self._block())- assert pending.endswith("continue here")-- def test_first_message_conversion_idempotent_under_lock(self):+ def test_first_message_idempotent_under_lock(self):# Simulate a concurrent winner: the DB row is linked to a Task after this request's entry# check but before it takes the lock. The under-lock re-check must surface a Conflict.other_task = Task.objects.create(@@ -774,19 +749,15 @@ class TestSandboxFirstMessageConversion(APIBaseTest):Conversation.objects.filter(id=self.conversation.id).update(task=other_task)with self.assertRaises(Conflict):- self._open(resumed_context=self._block(), convert_to_acp=True)+ self._open()self.conversation.refresh_from_db()assert self.conversation.task_id == other_task.id- def test_first_message_conversion_reverts_on_workflow_start_failure(self):+ def test_first_message_reverts_on_workflow_start_failure(self):with patch(f"{ROUTING}.dispatch_task_processing_workflow", side_effect=RuntimeError("boom")):with self.assertRaises(RuntimeError):- SandboxSession(self.conversation, self.user).open(- {"content": "continue here", "trace_id": "t"},- resumed_context=self._block(),- convert_to_acp=True,- )+ SandboxSession(self.conversation, self.user).open({"content": "continue here", "trace_id": "t"})# A failed start leaves a clean idle LangGraph conversation the user can retry.self.conversation.refresh_from_db()@@ -806,7 +777,7 @@ class TestSandboxFirstMessageConversion(APIBaseTest):assert result.just_created_run is Truem_workflow.assert_called_once()- def test_born_sandbox_first_message_has_no_resumed_context(self):+ def test_born_sandbox_first_message_carries_only_the_user_message(self):self.conversation.agent_runtime = Conversation.AgentRuntime.SANDBOXself.conversation.save(update_fields=["agent_runtime"])diff --git a/products/posthog_ai/backend/tests/test_receivers.py b/products/posthog_ai/backend/tests/test_receivers.pynew file mode 100644index 000000000000..e3c8cff4f561--- /dev/null+++ b/products/posthog_ai/backend/tests/test_receivers.py@@ -0,0 +1,145 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized++from products.posthog_ai.backend.conversation_mirror import MirrorResult+from products.posthog_ai.backend.models.assistant import Conversation+from products.posthog_ai.backend.receivers import (+ COPY_BEHIND_MESSAGE,+ SANDBOX_MODE_REQUIRED_MESSAGE,+ catch_up_conversation_copy_before_run,+)+from products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.models import Task, TaskRun++FLAGS = "ee.hogai.utils.feature_flags"+++class ConversationTaskTestMixin(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ for flag in ("has_sandbox_mode_feature_flag", "has_conversation_task_mirror_feature_flag"):+ p = patch(f"{FLAGS}.{flag}", return_value=True)+ p.start()+ self.addCleanup(p.stop)++ def _linked_conversation(self, origin_product: str = Task.OriginProduct.POSTHOG_AI) -> tuple[Conversation, Task]:+ task = Task.objects.create(+ team=self.team, title="t", description="d", origin_product=origin_product, created_by=self.user+ )+ conversation = Conversation.objects.create(+ user=self.user, team=self.team, agent_runtime=Conversation.AgentRuntime.LANGGRAPH, task=task+ )+ return conversation, task+++class TestConversationFollowsTaskRun(ConversationTaskTestMixin):+ @parameterized.expand(+ [+ ("import_run", {"imported_from": "conversation"}, Conversation.AgentRuntime.LANGGRAPH),+ ("warm_run", {"await_user_message": True}, Conversation.AgentRuntime.LANGGRAPH),+ ("real_run", {}, Conversation.AgentRuntime.SANDBOX),+ ]+ )+ def test_only_a_real_run_marks_the_conversation_sandbox(self, _name: str, state: dict, expected: str) -> None:+ conversation, task = self._linked_conversation()+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED, state=state)+ conversation.refresh_from_db()+ assert conversation.agent_runtime == expected++ def test_runs_of_other_products_leave_the_conversation_alone(self) -> None:+ conversation, task = self._linked_conversation(Task.OriginProduct.USER_CREATED)+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED, state={})+ conversation.refresh_from_db()+ assert conversation.agent_runtime == Conversation.AgentRuntime.LANGGRAPH++ def test_an_owner_without_sandbox_mode_keeps_the_langgraph_runtime(self) -> None:+ conversation, task = self._linked_conversation()+ with patch(f"{FLAGS}.has_sandbox_mode_feature_flag", return_value=False):+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED, state={})+ conversation.refresh_from_db()+ assert conversation.agent_runtime == Conversation.AgentRuntime.LANGGRAPH+++class TestCatchUpBeforeRun(ConversationTaskTestMixin):+ def _guard(self, task: Task) -> str | None:+ return catch_up_conversation_copy_before_run(str(task.id), self.team.id, self.user.id)++ def _copied(self, **kwargs) -> MirrorResult:+ defaults = {"skipped_reason": None, "task_id": None, "run_id": None, "appended_frames": 2}+ return MirrorResult(**{**defaults, **kwargs})++ def test_copies_the_missing_turns_then_lets_the_run_start(self) -> None:+ conversation, task = self._linked_conversation()+ with patch(f"products.posthog_ai.backend.conversation_mirror.amirror_conversation") as copy:+ copy.return_value = self._copied()+ assert self._guard(task) is None+ copy.assert_called_once_with(conversation.id, self.team.id, self.user.id)++ @parameterized.expand([("failed", RuntimeError("db down")), ("skipped", None)])+ def test_refuses_the_run_when_the_copy_did_not_catch_up(self, _name: str, error: Exception | None) -> None:+ _, task = self._linked_conversation()+ with patch(f"products.posthog_ai.backend.conversation_mirror.amirror_conversation") as copy:+ if error is not None:+ copy.side_effect = error+ else:+ copy.return_value = self._copied(skipped_reason="task_deleted")+ assert self._guard(task) == COPY_BEHIND_MESSAGE++ def test_refuses_the_run_for_an_owner_without_sandbox_mode(self) -> None:+ _, task = self._linked_conversation()+ with (+ patch(f"{FLAGS}.has_sandbox_mode_feature_flag", return_value=False),+ patch(f"products.posthog_ai.backend.conversation_mirror.amirror_conversation") as copy,+ ):+ assert self._guard(task) == SANDBOX_MODE_REQUIRED_MESSAGE+ copy.assert_not_called()++ def test_leaves_tasks_without_a_langgraph_chat_alone(self) -> None:+ conversation, task = self._linked_conversation()+ conversation.agent_runtime = Conversation.AgentRuntime.SANDBOX+ conversation.save()+ with patch(f"products.posthog_ai.backend.conversation_mirror.amirror_conversation") as copy:+ assert self._guard(task) is None+ copy.assert_not_called()+++class TestCopiedChatsHiddenWithoutSandboxMode(ConversationTaskTestMixin):+ def _tasks(self) -> tuple[Task, Task, Task]:+ _, copied = self._linked_conversation()+ continued_chat, continued = self._linked_conversation()+ continued_chat.agent_runtime = Conversation.AgentRuntime.SANDBOX+ continued_chat.save()+ plain = Task.objects.create(+ team=self.team,+ title="plain",+ description="d",+ origin_product=Task.OriginProduct.USER_CREATED,+ created_by=self.user,+ )+ return copied, continued, plain++ def _visible_ids(self) -> set:+ listed = {task.id for task in tasks_facade.list_tasks(self.team.id, self.user.id, filters={})}+ detail = {+ task.id+ for task in Task.objects.filter(team=self.team)+ if tasks_facade.get_task_detail(task.id, self.team.id, self.user.id) is not None+ }+ assert listed == detail+ return listed++ def test_a_user_without_sandbox_mode_sees_no_copied_chat(self) -> None:+ copied, continued, plain = self._tasks()+ with patch(f"{FLAGS}.has_sandbox_mode_feature_flag", return_value=False):+ assert self._visible_ids() == {continued.id, plain.id}++ def test_a_user_with_sandbox_mode_sees_the_copies(self) -> None:+ copied, continued, plain = self._tasks()+ assert self._visible_ids() == {copied.id, continued.id, plain.id}++ def test_a_build_without_ee_hides_nothing_and_still_serves_task_reads(self) -> None:+ copied, continued, plain = self._tasks()+ with patch("products.posthog_ai.backend.receivers._feature_flags", return_value=None):+ assert self._visible_ids() == {copied.id, continued.id, plain.id}diff --git a/products/posthog_ai/frontend/generated/api.schemas.ts b/products/posthog_ai/frontend/generated/api.schemas.tsindex 8d523b89ec3b..2a09a9b6055c 100644--- a/products/posthog_ai/frontend/generated/api.schemas.ts+++ b/products/posthog_ai/frontend/generated/api.schemas.ts@@ -372,7 +372,7 @@ export interface ConversationApi {readonly has_unsupported_content: boolean/** @nullable */readonly agent_mode: string | null- /** Runtime that owns this conversation. 'langgraph' conversations return their messages in the `messages` field; born-'sandbox' conversations return an empty `messages` array and load history from the products/tasks logs endpoint. A converted conversation is 'sandbox' but still returns its legacy thread in `messages`.+ /** Runtime that owns this conversation. 'langgraph' conversations return their messages in the `messages` field. 'sandbox' conversations return an empty `messages` array and load history from the products/tasks logs endpoint; a conversation copied into a task carries its legacy thread in that task's import run. Only a conversion that predates the copy still returns its legacy thread in `messages`.** * `langgraph` - LangGraph* * `sandbox` - Sandbox */@@ -443,7 +443,7 @@ export interface PatchedConversationApi {readonly has_unsupported_content?: boolean/** @nullable */readonly agent_mode?: string | null- /** Runtime that owns this conversation. 'langgraph' conversations return their messages in the `messages` field; born-'sandbox' conversations return an empty `messages` array and load history from the products/tasks logs endpoint. A converted conversation is 'sandbox' but still returns its legacy thread in `messages`.+ /** Runtime that owns this conversation. 'langgraph' conversations return their messages in the `messages` field. 'sandbox' conversations return an empty `messages` array and load history from the products/tasks logs endpoint; a conversation copied into a task carries its legacy thread in that task's import run. Only a conversion that predates the copy still returns its legacy thread in `messages`.** * `langgraph` - LangGraph* * `sandbox` - Sandbox */diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsxindex 55e1f1a3b581..e95aa7e46f13 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx@@ -31,7 +31,8 @@ export function TaskRunMetadata({ selectedRun }: { selectedRun: TaskRunDetailDTO</dd></dl>)}- {selectedRun.completed_at && selectedRun.created_at && (+ {/* An import run holds a chat copied from the legacy runtime and never executed, so it has no duration. */}+ {selectedRun.completed_at && selectedRun.created_at && !selectedRun.state?.imported_from && (<dl className="inline-flex gap-1 items-center"><dt className="m-0">Duration:</dt><dd className="m-0 inline-flex items-center">diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 5e20138896a7..6f2d912fb9cb 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -54,7 +54,10 @@ from posthog.models.oauth import OAuthAccessToken, OAuthRefreshTokenfrom posthog.utils import absolute_urifrom products.canvas.backend.models import Canvas-from products.posthog_ai.backend.task_ownership import detach_conversations_for_task_handoff+from products.posthog_ai.backend.task_ownership import (+ detach_conversations_for_task_handoff,+ soft_delete_conversations_for_task,+)from products.tasks.backend.constants import (AGENT_OTEL_TELEMETRY_STATE_KEY,AGENT_PEER_MESSAGING_FEATURE_FLAG,@@ -153,6 +156,7 @@ from products.tasks.backend.visibility import ()from . import contracts+from .task_run_signals import hidden_task_ids, task_run_start_refusallogger = logging.getLogger(__name__)@@ -192,7 +196,13 @@ __all__ = ["TaskRunEnvironment","TaskRunStatus","WarmRunActivationUnavailable",+ "append_imported_task_run_log","append_task_run_log",+ "create_imported_task",+ "create_imported_task_run",+ "get_imported_task_run",+ "get_task_by_origin_key",+ "touch_imported_task","apply_task_run_model_config","task_run_model_outside_gateway_pin","ensure_task_run_session",@@ -459,6 +469,11 @@ _TASK_RUN_PUBLIC_STATE_KEYS = frozenset("context_window","custom_image_id","fast_mode",+ # An imported transcript's provenance and mirror cursor: the viewer marks the run as+ # imported, and the legacy mirror reads its own cursor back through this DTO.+ "conversation_last_message_id",+ "conversation_messages_copied",+ "imported_from","initial_permission_mode","mode","model",@@ -3268,6 +3283,132 @@ def append_task_run_log(return _task_run_detail_to_dto(run)+def get_task_by_origin_key(team_id: int, origin_key: str) -> contracts.TaskDetailDTO | None:+ """The live task carrying ``origin_key`` in ``team_id``, or None. Bypasses visibility: an+ origin key is an idempotency handle for a system writer, not a user-facing lookup."""+ task = Task.objects.filter(team_id=team_id, origin_key=origin_key, deleted=False).first()+ return _task_detail_to_dto(task) if task is not None else None+++def get_imported_task_run(task_id: str | UUID, team_id: int) -> contracts.TaskRunDetailDTO | None:+ """The run that holds a task's imported transcript (``state.imported_from`` set), or None."""+ run = (+ TaskRun.objects.filter(task_id=task_id, team_id=team_id, state__has_key="imported_from")+ .order_by("created_at", "id")+ .first()+ )+ return _task_run_detail_to_dto(run) if run is not None else None+++def create_imported_task(+ team_id: int,+ user_id: int,+ *,+ title: str,+ origin_key: str,+ internal: bool,+ created_at: datetime,+) -> contracts.TaskDetailDTO:+ """Create the task that hosts a transcript imported from elsewhere.++ Backdated to the source's creation time so the task list keeps the order the user remembers.+ The title comes from the source, not the user, so a later rename of the task must win over it.+ """+ return create_task(+ team_id,+ user_id,+ validated_data={+ "title": title,+ "title_manually_set": False,+ "description": "",+ "origin_product": Task.OriginProduct.POSTHOG_AI,+ "origin_key": origin_key,+ "internal": internal,+ "created_at": created_at,+ },+ )+++def create_imported_task_run(+ task_id: str | UUID,+ team_id: int,+ *,+ state: dict,+ created_at: datetime,+ completed_at: datetime,+) -> contracts.TaskRunDetailDTO:+ """Create a completed run that never executed, to host a transcript imported from elsewhere.++ The run is backdated to the source's timestamps so the task sorts and reads as old as the+ conversation it came from. Nothing dispatches a workflow for it; a later real run chains to it+ through ``resume_from_run_id`` like any earlier run. A task holds one import run: the create+ runs under the task's row lock and returns the existing run when a concurrent import won.+ """+ with transaction.atomic():+ task = Task.objects.select_for_update().get(id=task_id, team_id=team_id)+ existing = (+ TaskRun.objects.filter(task=task, team_id=team_id, state__has_key="imported_from")+ .order_by("created_at", "id")+ .first()+ )+ if existing is not None:+ return _task_run_detail_to_dto(existing)+ run = TaskRun.objects.create(+ task=task,+ team_id=team_id,+ status=TaskRun.Status.COMPLETED,+ environment=TaskRun.Environment.CLOUD,+ state=state,+ completed_at=completed_at,+ )+ # created_at is auto_now_add, so the backdate has to go through update().+ TaskRun.objects.filter(id=run.id).update(created_at=created_at)+ run.refresh_from_db()+ return _task_run_detail_to_dto(run)+++def append_imported_task_run_log(+ run_id: str | UUID,+ task_id: str | UUID,+ team_id: int,+ *,+ entries: list[dict],+ batch_id: str,+ expected_state: dict,+ state_updates: dict,+ completed_at: datetime,+) -> bool:+ """Append lines to an import run's log and record how far the source has been copied.++ Holds the run's row lock across the append so two copies of the same source cannot both+ append the same lines: the append only happens while ``expected_state`` still matches the+ run's state, and returns False when another writer moved it on first. ``batch_id`` names+ this batch in the log, so a retry after the append succeeded but the state write failed+ skips the append instead of writing the lines twice. Imported transcripts are user chat+ history, so the log is never tagged for expiry, and there is no workflow to heartbeat.+ ``completed_at`` follows the source so the run reads as current as the conversation it copies.+ """+ with transaction.atomic():+ run = TaskRun.objects.select_for_update().get(id=run_id, task_id=task_id, team_id=team_id)+ state = run.state or {}+ if any(state.get(key) != value for key, value in expected_state.items()):+ return False+ run.append_log(entries, ttl_days=None, batch_id=batch_id)+ run.state = {**state, **state_updates}+ run.completed_at = completed_at+ run.save(update_fields=["state", "completed_at"])+ return True+++def touch_imported_task(task_id: str | UUID, team_id: int, *, title: str | None, last_activity_at: datetime) -> None:+ """Keep an imported task's list row in step with its source conversation."""+ tasks = Task.objects.filter(id=task_id, team_id=team_id)+ tasks.update(last_activity_at=last_activity_at)+ if title:+ # A title the user set on the task outranks the source's generated one.+ tasks.filter(title_manually_set=False).update(title=title)++def clear_task_run_conversation(run_id: str | UUID, task_id: str | UUID, team_id: int) -> tuple[Literal["cleared", "not_found", "not_terminal"], contracts.TaskRunDetailDTO | None]:@@ -5569,6 +5710,11 @@ def _visible_task_qs(team_id: int, user_id: int | None, *, bypass_visibility: boqs = qs.filter(task_control_q(user_id) if for_control else task_visibility_q(user_id) | _shared_slack_thread_q())+ # Another product may hide tasks it owns from this user, for example the copies of chats a+ # user cannot continue as tasks yet.+ hidden = hidden_task_ids(team_id, user_id)+ if hidden:+ qs = qs.exclude(id__in=hidden)return qs@@ -6701,6 +6847,7 @@ def soft_delete_task(task_id: str | UUID, team_id: int, user_id: int | None) ->return Falselogger.info("Soft deleting task %s", task.id)task.soft_delete()+ soft_delete_conversations_for_task(task.id)return True@@ -7639,6 +7786,8 @@ def warm_task_resume_sandbox(for protected_key in ("wizard_head_branch", "self_driving_head_branch", "github_read_access"):if protected_key in (previous_run.state or {}):extra_state[protected_key] = (previous_run.state or {})[protected_key]+ if "imported_from" in (previous_run.state or {}):+ extra_state["resume_from_import_run"] = Trueextra_state = {key: value for key, value in extra_state.items() if value is not None or key == "pr_base_branch"}stable_selection = {key: value@@ -7722,6 +7871,11 @@ def run_task(task = _visible_task_qs(team_id, user_id, for_control=True).filter(id=task_id).first()if task is None:return None+ # Another product may need to finish something before this task runs, for example a chat that+ # is copied into the task a few seconds behind each turn.+ refusal = task_run_start_refusal(str(task.id), team_id, user_id)+ if refusal is not None:+ return contracts.TaskRunResult(error=contracts.TaskValidationError(kind="detail", detail=refusal))report_id_for_slot_check = (str(task.signal_report_id)if task.signal_report_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORT@@ -7756,12 +7910,14 @@ def run_task(is_pi_task = task.runtime == Task.Runtime.PIprevious_run: TaskRun | None = Noneprevious_state = None+ previous_is_import_run = Falseif resume_from_run_id:previous_run = task.runs.filter(id=resume_from_run_id).first()if previous_run is None:return contracts.TaskRunResult(error=contracts.TaskValidationError(kind="detail", detail="Invalid resume_from_run_id"))+ previous_is_import_run = "imported_from" in (previous_run.state or {})if not previous_run.matches_task_ownership(task):return contracts.TaskRunResult(error=contracts.TaskValidationError(@@ -7795,10 +7951,11 @@ def run_task(team_id, task.repositories[0] if task.repositories else task.repository)- if not resume_from_run_id:+ if not resume_from_run_id or previous_is_import_run:# Fill team/user default AI run preferences before warm matching: a warm run# provisioned under the default triple must still match a submit that pinned- # nothing. Resumes instead carry the previous run's selection (below).+ # nothing. Resumes instead carry the previous run's selection (below), except from+ # an import run, which never ran and so pins no selection to carry.validated_data = _with_ai_run_defaults(validated_data,team_id=task.team_id,@@ -7956,6 +8113,8 @@ def run_task(if not is_pi_task:extra_state["resume_from_run_id"] = str(resume_from_run_id)extra_state.update(prev_state.resume_snapshot_carry_state())+ if previous_is_import_run:+ extra_state["resume_from_import_run"] = True# The resumed agent still pushes the head branch baked into the original prompt, so the# PR webhook must be able to match this run, not the terminal predecessor.diff --git a/products/tasks/backend/facade/task_run_signals.py b/products/tasks/backend/facade/task_run_signals.pyindex 6e0944e63958..88d1f2b9fd1d 100644--- a/products/tasks/backend/facade/task_run_signals.py+++ b/products/tasks/backend/facade/task_run_signals.py@@ -1,9 +1,45 @@-from collections.abc import Callable+from collections.abc import Callable, Iterable+from uuid import UUIDfrom django.db.models.signals import post_save-from products.tasks.backend.models import TaskRun+from products.tasks.backend.models import Task, TaskRun++# Re-exported here so a startup receiver can read it without importing the request facade.+TaskOriginProduct = Task.OriginProductdef connect_task_run_post_save(receiver: Callable[..., None], *, dispatch_uid: str) -> None:post_save.connect(receiver, sender=TaskRun, dispatch_uid=dispatch_uid)+++# A guard gets (task_id, team_id, user_id) before a run starts and returns a message to refuse it with, or None.+TaskRunStartGuard = Callable[[str, int, int | None], str | None]+_task_run_start_guards: dict[str, TaskRunStartGuard] = {}+++def register_task_run_start_guard(guard: TaskRunStartGuard, *, name: str) -> None:+ _task_run_start_guards[name] = guard+++def task_run_start_refusal(task_id: str, team_id: int, user_id: int | None) -> str | None:+ """The first registered guard's reason to refuse starting a run for this task, if any."""+ for guard in _task_run_start_guards.values():+ refusal = guard(task_id, team_id, user_id)+ if refusal is not None:+ return refusal+ return None+++# An exclusion gets (team_id, user_id) and returns the ids of tasks this user must not see.+TaskReadExclusion = Callable[[int, int | None], Iterable[UUID]]+_task_read_exclusions: dict[str, TaskReadExclusion] = {}+++def register_task_read_exclusion(exclusion: TaskReadExclusion, *, name: str) -> None:+ _task_read_exclusions[name] = exclusion+++def hidden_task_ids(team_id: int, user_id: int | None) -> set[UUID]:+ """Every registered product's task ids to hide from this user."""+ return {task_id for exclusion in _task_read_exclusions.values() for task_id in exclusion(team_id, user_id)}diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 0f75ef96828b..228f834a3e1b 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -2740,7 +2740,14 @@ class TaskRun(models.Model):# expiry — user history must not silently vanish after 30 days.DEFAULT_LOG_TTL_DAYS = 30- def append_log(self, entries: list[dict], *, ttl_days: int | None = DEFAULT_LOG_TTL_DAYS, lock_attempts: int = 3):+ def append_log(+ self,+ entries: list[dict],+ *,+ ttl_days: int | None = DEFAULT_LOG_TTL_DAYS,+ lock_attempts: int = 3,+ batch_id: str | None = None,+ ):"""Append log entries to S3 storage.`ttl_days` tags a newly-created log file for expiry; pass `None` to write a log that is@@ -2753,7 +2760,7 @@ class TaskRun(models.Model):if not entries:return- is_new_file = append_jsonl_object(self.log_url, entries, lock_attempts=lock_attempts)+ is_new_file = append_jsonl_object(self.log_url, entries, lock_attempts=lock_attempts, batch_id=batch_id)self._mirror_logs_to_posthog_logs(entries)diff --git a/products/tasks/backend/storage.py b/products/tasks/backend/storage.pyindex d4380a6149c1..b63fc3bb8ef1 100644--- a/products/tasks/backend/storage.py+++ b/products/tasks/backend/storage.py@@ -56,10 +56,22 @@ def _append_lock(object_storage_key: str, attempts: int) -> Iterator[None]:logger.warning("task_log_append_lock_release_failed", object_storage_key=object_storage_key, exc_info=True)-def append_jsonl_object(object_storage_key: str, entries: list[dict[str, Any]], *, lock_attempts: int = 1) -> bool:+def append_jsonl_object(+ object_storage_key: str, entries: list[dict[str, Any]], *, lock_attempts: int = 1, batch_id: str | None = None+) -> bool:+ """Append ``entries`` as JSON lines. Returns whether the object was created by this call.++ ``batch_id`` makes the append idempotent: every entry is written with ``"batch": batch_id``,+ and the append is skipped when the object already holds that batch. A caller that appended,+ then failed before recording it, can retry without writing the lines twice.+ """with _append_lock(object_storage_key, lock_attempts):existing_content = object_storage.read(object_storage_key, missing_ok=True) or ""is_new_object = not existing_content+ if batch_id is not None:+ if f'"batch": {json.dumps(batch_id)}' in existing_content:+ return False+ entries = [{**entry, "batch": batch_id} for entry in entries]new_lines = "\n".join(json.dumps(entry) for entry in entries)content = existing_content + ("\n" if existing_content else "") + new_linesdiff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.pyindex a88f0c0d50cf..eda6b9d8e7d6 100644--- a/products/tasks/backend/temporal/metrics.py+++ b/products/tasks/backend/temporal/metrics.py@@ -155,10 +155,14 @@ def _model_label(value: str | None) -> str:return normalized if runtime_adapter_for(normalized) else "other"-def resume_mode_label(*, same_run_resume: bool, using_modal_snapshot: bool) -> str:+def resume_mode_label(*, same_run_resume: bool, using_modal_snapshot: bool, from_import_run: bool = False) -> str:if same_run_resume:return "same_run_and_snapshot" if using_modal_snapshot else "same_run"- return "snapshot_only" if using_modal_snapshot else "neither"+ if using_modal_snapshot:+ return "snapshot_only"+ # An import run never had a sandbox, so there is no working tree to lose: the successor+ # starts from the transcript alone by design, not because a snapshot went missing.+ return "imported_transcript" if from_import_run else "neither"def increment_resume_mode(mode: str, *, origin_product: str | None) -> None:@@ -167,7 +171,8 @@ def increment_resume_mode(mode: str, *, origin_product: str | None) -> None:"tasks_process_resume_mode","Resuming process-task runs by the resume state available at provision time. ""same_run labels identify a restart of the current run. neither means no snapshot "- "or same-run state accompanied the resume, so the prior working tree could not be restored.",+ "or same-run state accompanied the resume, so the prior working tree could not be restored. "+ "imported_transcript means the resumed run only held an imported transcript and had no tree.",).add(1)except Exception:passdiff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 8acd70eee557..4bdefc104622 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -699,6 +699,7 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Presume_mode = resume_mode_label(same_run_resume=run_state.same_run_resume,using_modal_snapshot=resume_snapshot_external_id is not None,+ from_import_run=run_state.resume_from_import_run,)resume_decision_log = (activity.logger.warning if is_resume and resume_mode == "neither" else activity.logger.infodiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.pyindex bcb2bdfd0a8b..fd8ee5d8ac88 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py@@ -240,16 +240,27 @@ def test_modal_sandbox_backend_label(monkeypatch: pytest.MonkeyPatch, value: str@pytest.mark.parametrize(- ("same_run_resume", "using_modal_snapshot", "expected"),+ ("same_run_resume", "using_modal_snapshot", "from_import_run", "expected"),[- (True, False, "same_run"),- (True, True, "same_run_and_snapshot"),- (False, True, "snapshot_only"),- (False, False, "neither"),+ (True, False, False, "same_run"),+ (True, True, False, "same_run_and_snapshot"),+ (False, True, False, "snapshot_only"),+ (False, False, False, "neither"),+ (False, False, True, "imported_transcript"),+ (False, True, True, "snapshot_only"),],)-def test_resume_mode_label(same_run_resume: bool, using_modal_snapshot: bool, expected: str) -> None:- assert resume_mode_label(same_run_resume=same_run_resume, using_modal_snapshot=using_modal_snapshot) == expected+def test_resume_mode_label(+ same_run_resume: bool, using_modal_snapshot: bool, from_import_run: bool, expected: str+) -> None:+ assert (+ resume_mode_label(+ same_run_resume=same_run_resume,+ using_modal_snapshot=using_modal_snapshot,+ from_import_run=from_import_run,+ )+ == expected+ )@pytest.mark.asynciodiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.pyindex fc81837cbab8..ebee73ee276b 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py@@ -432,9 +432,9 @@ class TestUpdateTaskRunStatusActivity:# An earlier prewarm nobody typed into does not — the next message resumes into a# successor, so counting it would report the first real chat as a continuation.({"prewarmed": True, "await_user_message": True}, {}, True),- # A conversation carried over from LangGraph is continued, however little sandbox- # history it has: the conversion starts it on a fresh task with no earlier run.- (None, {"converted_from_langgraph": True}, False),+ # A chat copied from LangGraph is an earlier run that held a chat, so the conversation+ # is continued however little sandbox history it has.+ ({"imported_from": "conversation"}, {}, False),(None, {}, True),],)diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.pyindex 2d4baff08387..729843b82fa3 100644--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py@@ -211,15 +211,10 @@ def _is_first_chat_run_of_task(task_run: TaskRun, state: dict[str, Any]) -> bool"""Whether this run opened the conversation, the run-level reading of `is_new_conversation`.A terminal run resumes into a successor rather than reopening, so "no earlier run" is what- separates a new conversation from a continued one. Two kinds of earlier history do not count:-- - A prewarm nobody typed into. It idles out on its own and the next message resumes into a- successor, so counting it would report the user's first real chat as a continuation.- - The LangGraph half of a converted conversation. That conversation already counted once on- the legacy runtime, and its sandbox side starts on a fresh task with no earlier run.+ separates a new conversation from a continued one. One kind of earlier history does not count:+ a prewarm nobody typed into. It idles out on its own and the next message resumes into a+ successor, so counting it would report the user's first real chat as a continuation."""- if state.get("converted_from_langgraph"):- return False# Match the prewarm on the key's absence rather than with `exclude`. A queryset `exclude` on a# JSON key compares NULL for every row that lacks the key, so it would drop exactly the earlier# runs that did hold a chat and report every conversation as new.diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex a822b2c7f5fc..09f3a2e1b4a2 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -337,6 +337,7 @@ class RunState(BaseModel, extra="allow"):fast_mode: bool | None = Noneclaude_model_access: Literal["posthog-gateway", "own-subscription"] | None = Noneresume_from_run_id: str | None = None+ resume_from_import_run: bool = Falsesame_run_resume: bool = Falsesame_run_resume_idle: bool = Falsesnapshot_external_id: str | None = Nonediff --git a/products/tasks/backend/tests/test_ai_run_defaults.py b/products/tasks/backend/tests/test_ai_run_defaults.pyindex e7166c73da7a..095cfd598218 100644--- a/products/tasks/backend/tests/test_ai_run_defaults.py+++ b/products/tasks/backend/tests/test_ai_run_defaults.py@@ -22,7 +22,7 @@ from products.tasks.backend.logic.services.ai_run_defaults import (update_user_ai_run_preferences,validate_ai_run_preferences,)-from products.tasks.backend.models import Task, TeamTasksConfig, UserTasksConfig+from products.tasks.backend.models import Task, TaskRun, TeamTasksConfig, UserTasksConfigfrom products.tasks.backend.presentation.serializers import TaskRunCreateRequestSerializerFACADE = "products.tasks.backend.facade.api"@@ -437,6 +437,45 @@ class TestRunTaskWarmMatchingUnderDefaults(APIBaseTest):warm_run.refresh_from_db()assert "await_user_message" not in warm_run.state+ def test_default_carrying_warm_run_is_activated_by_a_continue_from_an_import_run(self):+ update_team_ai_run_preferences(self.team.id, **TEAM_TRIPLE)+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ import_run = task.create_run(mode="interactive", extra_state={"imported_from": "conversation"})+ import_run.status = TaskRun.Status.COMPLETED+ import_run.save(update_fields=["status"])+ warm_run = task.create_run(+ mode="interactive",+ extra_state={+ "await_user_message": True,+ "resume_from_run_id": str(import_run.id),+ "initial_permission_mode": "default",+ },+ )+ assert warm_run.state["model"] == "claude-opus-4-8"++ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True):+ result = facade.run_task(+ task.id,+ self.team.id,+ self.user.id,+ validated_data={+ "mode": "interactive",+ "resume_from_run_id": str(import_run.id),+ "pending_user_message": "go",+ },+ )++ assert result is not None and result.error is None+ assert task.runs.count() == 2+ warm_run.refresh_from_db()+ assert "await_user_message" not in warm_run.state+class TestTasksConfigAPI(APIBaseTest):def setUp(self) -> None:diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 6d5e5a1032a9..b5d7ba85a8b3 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -608,8 +608,8 @@ class TestFacadeReadsAndMappers(TestCase):)# The runs this path prefetches already carry the earlier PR, so finding it costs- # no second trip to the database.- with self.assertNumQueries(3):+ # no second trip to the database. One of the four is the read exclusion PostHog AI registers.+ with self.assertNumQueries(4):dto = facade.get_task_detail(task.id, self.team.id, self.user.id)assert dto is not None and dto.latest_run is not None and dto.latest_run.output is not None@@ -860,8 +860,9 @@ class TestFacadeReadsAndMappers(TestCase):)TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)- # The page costs one inherited-PR query, whatever the number of tasks on it.- with self.assertNumQueries(6):+ # The page costs one inherited-PR query, whatever the number of tasks on it. One of the+ # seven is the read exclusion PostHog AI registers.+ with self.assertNumQueries(7):dtos = facade.list_tasks(self.team.id, self.user.id, filters={})by_title = {dto.title: dto for dto in dtos}@@ -1063,6 +1064,52 @@ class TestFacadeReadsAndMappers(TestCase):new_run = task.runs.exclude(id=previous_run.id).get()self.assertEqual(new_run.state.get("prior_run_summary"), "Reviewing the API")+ def test_a_registered_read_exclusion_hides_a_task_from_reads(self):+ hidden = self._make_task()+ shown = self._make_task()+ exclusions = {"test": lambda team_id, user_id: [hidden.id]}++ with patch.dict("products.tasks.backend.facade.task_run_signals._task_read_exclusions", exclusions, clear=True):+ assert facade.get_task_detail(hidden.id, self.team.id, self.user.id) is None+ assert facade.get_task_detail(shown.id, self.team.id, self.user.id) is not None+ assert (+ facade.run_task(hidden.id, self.team.id, self.user.id, validated_data={"mode": "interactive"}) is None+ )++ def test_run_task_refuses_when_a_start_guard_objects(self):+ task = self._make_task()+ guards = {"test": lambda task_id, team_id, user_id: "Not yet"}++ with (+ patch.dict("products.tasks.backend.facade.task_run_signals._task_run_start_guards", guards, clear=True),+ patch("products.tasks.backend.facade.api._trigger_task_processing_workflow") as trigger,+ ):+ result = facade.run_task(task.id, self.team.id, self.user.id, validated_data={"mode": "interactive"})++ assert result is not None and result.error is not None+ self.assertEqual(result.error.detail, "Not yet")+ trigger.assert_not_called()+ assert not task.runs.exists()++ def test_run_task_resumed_from_an_import_run_marks_the_new_run(self):+ task = self._make_task()+ import_run = TaskRun.objects.create(+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, state={"imported_from": "conversation"}+ )++ with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None):+ result = facade.run_task(+ task.id,+ self.team.id,+ self.user.id,+ validated_data={"mode": "interactive", "resume_from_run_id": str(import_run.id)},+ )++ assert result is not None and result.error is None+ new_run = task.runs.exclude(id=import_run.id).get()+ assert new_run.state["resume_from_import_run"] is True+ assert "imported_from" not in new_run.state+def test_run_task_resume_exposes_pending_prompt_to_agent(self):task = self._make_task()previous_run = TaskRun.objects.create(diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.pyindex a29ca670165b..943439c1707a 100644--- a/products/tasks/backend/tests/test_warm_facade.py+++ b/products/tasks/backend/tests/test_warm_facade.py@@ -1267,6 +1267,33 @@ class TestWarmRunRelease(APIBaseTest):class TestWarmTaskResumeSandbox(APIBaseTest):+ def test_warm_resume_from_an_import_run_marks_the_warm_run(self):+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ import_run = task.create_run(mode="interactive", extra_state={"imported_from": "conversation"})+ import_run.status = TaskRun.Status.COMPLETED+ import_run.save(update_fields=["status"])++ with (+ patch("products.tasks.backend.logic.services.warm.is_team_limited", return_value=False),+ patch("products.tasks.backend.logic.services.warm.execute_task_processing_workflow"),+ self.captureOnCommitCallbacks(execute=True),+ ):+ warmed = facade.warm_task_resume_sandbox(+ task.id, self.team.id, self.user.id, resume_from_run_id=import_run.id+ )++ assert warmed is not None+ warm_run = TaskRun.objects.get(id=warmed.run_id)+ assert warm_run.state["resume_from_run_id"] == str(import_run.id)+ assert warm_run.state["resume_from_import_run"] is True+ assert "imported_from" not in warm_run.state+@parameterized.expand(["release", None])def test_warms_and_activates_a_successor_for_the_latest_terminal_run(self, base_branch):task = Task.objects.create(diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ec4188f224ae..b19488dc251d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -20903,7 +20903,7 @@ export namespace Schemas {readonly has_unsupported_content: boolean;/** @nullable */readonly agent_mode: string | null;- /** Runtime that owns this conversation. 'langgraph' conversations return their messages in the `messages` field; born-'sandbox' conversations return an empty `messages` array and load history from the products/tasks logs endpoint. A converted conversation is 'sandbox' but still returns its legacy thread in `messages`.+ /** Runtime that owns this conversation. 'langgraph' conversations return their messages in the `messages` field. 'sandbox' conversations return an empty `messages` array and load history from the products/tasks logs endpoint; a conversation copied into a task carries its legacy thread in that task's import run. Only a conversion that predates the copy still returns its legacy thread in `messages`.** * `langgraph` - LangGraph* * `sandbox` - Sandbox */@@ -66754,7 +66754,7 @@ export namespace Schemas {readonly has_unsupported_content?: boolean;/** @nullable */readonly agent_mode?: string | null;- /** Runtime that owns this conversation. 'langgraph' conversations return their messages in the `messages` field; born-'sandbox' conversations return an empty `messages` array and load history from the products/tasks logs endpoint. A converted conversation is 'sandbox' but still returns its legacy thread in `messages`.+ /** Runtime that owns this conversation. 'langgraph' conversations return their messages in the `messages` field. 'sandbox' conversations return an empty `messages` array and load history from the products/tasks logs endpoint; a conversation copied into a task carries its legacy thread in that task's import run. Only a conversion that predates the copy still returns its legacy thread in `messages`.** * `langgraph` - LangGraph* * `sandbox` - Sandbox */