: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(phai): sandbox backend — models, message routing, and MCP (#65164)
Georgiy Tarasov9d72cd76e357
diff --git a/ee/api/conversation.py b/ee/api/conversation.pyindex c76038e993f3..0f4e5b23ff08 100644--- a/ee/api/conversation.py+++ b/ee/api/conversation.py@@ -1,7 +1,7 @@import timeimport uuidimport asyncio-from collections.abc import AsyncGenerator+from collections.abc import AsyncGenerator, Iterablefrom typing import castfrom django.conf import settings@@ -13,7 +13,7 @@ import pydanticimport structlogfrom asgiref.sync import async_to_sync as asgi_async_to_syncfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, extend_schema+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom loginas.utils import is_impersonated_sessionfrom prometheus_client import Histogramfrom rest_framework import exceptions, serializers, status@@ -27,6 +27,7 @@ from rest_framework.viewsets import GenericViewSetfrom posthog.schema import AgentMode, AssistantMessage, HumanMessage, MaxBillingContextfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.event_usage import report_user_actionfrom posthog.exceptions import Conflict, QuotaLimitExceededfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.user import User@@ -50,16 +51,24 @@ 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.message_routing import SandboxSessionfrom products.posthog_ai.backend.models.assistant import Conversation+from products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.facade.contracts import TaskDetailDTO+from products.tasks.backend.facade.run_config import INITIAL_PERMISSION_MODE_CHOICESfrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limitedfrom ee.hogai.api.serializers import ConversationMinimalSerializer, ConversationSerializerfrom ee.hogai.chat_agent import AssistantGraphfrom ee.hogai.core.executor import AgentExecutorfrom ee.hogai.queue import ConversationQueueMessage, ConversationQueueStore, QueueFullError, build_queue_message-from ee.hogai.sandbox.executor import handle_sandbox_messagefrom ee.hogai.stream.redis_stream import get_conversation_stream_keyfrom ee.hogai.utils.aio import async_to_sync+from ee.hogai.utils.feature_flags import has_sandbox_mode_feature_flagfrom ee.hogai.utils.sse import AssistantSSESerializerfrom ee.hogai.utils.types import PartialAssistantState@@ -187,6 +196,85 @@ class QueueMessageUpdateSerializer(serializers.Serializer):content = serializers.CharField(required=True, allow_blank=False, max_length=40000)+class SandboxAttachedContextItemSerializer(serializers.Serializer):+ """One typed attachment carried by a sandbox message."""++ type = serializers.ChoiceField(+ choices=sorted(ALLOWED_ATTACHED_CONTEXT_TYPES),+ help_text="Attachment kind. Entity types carry `id` (+ optional `name`); `text` carries `value`.",+ )+ id = serializers.JSONField(+ required=False,+ help_text="Entity identifier — integer for `dashboard`/`action`, string short_id/UUID otherwise. Absent for `text`.",+ )+ name = serializers.CharField(+ required=False, help_text="Optional human-readable label rendered in the context block."+ )+ value = serializers.CharField(required=False, help_text="Free-text content. Only for `text` attachments.")+++class SandboxOpenSerializer(serializers.Serializer):+ """Request body for `POST /conversations/{id}/open/`. A string `content` processes a turn; a+ null/absent `content` warms a sandbox that idles awaiting the first message."""++ content = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ max_length=40000,+ help_text="The user's message text. Omit or null to warm a sandbox (boot + idle) ahead of the first message.",+ )+ trace_id = serializers.UUIDField(+ required=False, help_text="Client-generated trace id correlated with the resulting Run's SSE stream."+ )+ attached_context = serializers.ListField(+ required=False,+ child=SandboxAttachedContextItemSerializer(),+ help_text="Typed PostHog entities (and free text) attached to this message.",+ )+ initial_permission_mode = serializers.ChoiceField(+ choices=INITIAL_PERMISSION_MODE_CHOICES,+ required=False,+ help_text=(+ "Initial permission mode for the sandbox agent session. "+ "Defaults to `auto`, which allows safe tool use while preserving explicit confirmations."+ ),+ )+ task_id = serializers.UUIDField(+ required=False,+ help_text=(+ "Bind a brand-new sandbox conversation to an existing Task so the first message resumes "+ "that Task's run. Honored only when this request creates the conversation row; ignored "+ "for an already-existing conversation."+ ),+ )++ def validate_task_id(self, value: uuid.UUID) -> uuid.UUID:+ """Resolve the Task to bind, scoped to the team and the requesting user's visibility.++ Mirrors the tasks API's `task_visibility_q` gate so a team member can't bind a conversation+ to a teammate's private task by guessing its id. Returns the validated id (consumed directly+ by the view), so an unreadable id surfaces as a 400 here rather than failing deeper in routing.+ """+ team = self.context["team"]+ user = self.context["user"]+ if not tasks_facade.task_visible(value, team.id, user.id):+ raise serializers.ValidationError("Task not found or not accessible.")+ return value+++class SandboxMessageResponseSerializer(serializers.Serializer):+ """Response for `POST /conversations/{id}/open/` — the IDs the frontend opens SSE against."""++ task_id = serializers.CharField(help_text="The products/tasks Task backing the conversation.")+ run_id = serializers.CharField(help_text="The Run the frontend opens SSE against.")+ trace_id = serializers.CharField(allow_null=True, help_text="Echo of the request trace id, if provided.")+ run_status = serializers.CharField(help_text="Current status of the targeted Run (e.g. `queued`, `in_progress`).")+ just_created_run = serializers.BooleanField(+ help_text="True when a new Run was created (first message, terminal resume, or fresh warm); false for an in-progress follow-up or a reused warm Run."+ )++@extend_schema(tags=["max"])class ConversationViewSet(TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMixin, DestroyModelMixin, GenericViewSet@@ -238,8 +326,8 @@ class ConversationViewSet(return querysetdef get_throttles(self):- # For create action, throttling is handled in check_throttles() for conditional logic- if self.action == "create":+ # For message-sending / warming actions, throttling is handled in check_throttles() for conditional logic+ if self.action in ("create", "open"):return []return super().get_throttles()@@ -264,8 +352,9 @@ class ConversationViewSet(return Falsedef check_throttles(self, request: Request):- # Only apply custom throttling for create action- if self.action != "create":+ # Apply the AI throttles to the message-sending / warming actions — `open` provisions a real+ # sandbox Run whether or not it carries a message, so it shares the same rate limit as `create`.+ if self.action not in ("create", "open"):return super().check_throttles(request)# Skip throttling in local development@@ -314,8 +403,29 @@ class ConversationViewSet(return ConversationMinimalSerializerreturn super().get_serializer_class()+ def get_serializer(self, *args, **kwargs):+ if self.action in ("list", "retrieve") and args:+ context = kwargs.pop("context", self.get_serializer_context())+ context["conversation_task_dtos_by_id"] = self._conversation_task_dtos_by_id(args[0])+ kwargs["context"] = context+ return super().get_serializer(*args, **kwargs)++ def _conversation_task_dtos_by_id(self, instance) -> dict[str, TaskDetailDTO]:+ conversations = (+ [instance] if isinstance(instance, Conversation) else list(cast(Iterable[Conversation], instance))+ )+ task_ids = list({conversation.task_id for conversation in conversations if conversation.task_id is not None})+ return {+ str(task_id): task+ for task_id, task in tasks_facade.get_conversation_task_dtos(task_ids, self.team_id).items()+ }+def get_serializer_context(self):context = super().get_serializer_context()+ # drf-spectacular introspects with a fake view (no URL kwargs), so `self.team` would+ # raise KeyError: 'team_id'. Skip the eager team/user lookup during schema generation.+ if getattr(self, "swagger_fake_view", False):+ return contextcontext["team"] = self.teamcontext["user"] = cast(User, self.request.user)return context@@ -363,22 +473,32 @@ class ConversationViewSet(# Mark conversation as internal if created during an impersonated session (support agents)is_impersonated = is_impersonated_session(request)conversation_type = Conversation.Type.DEEP_RESEARCH if is_research else Conversation.Type.ASSISTANT+ # This endpoint is LangGraph-only — sandbox conversations are created via `open`. New rows+ # are always LangGraph (the model default), never stamped from the sandbox flag here.conversation = Conversation.objects.create(user=cast(User, request.user),team=self.team,id=conversation_id,type=conversation_type,is_internal=is_impersonated,+ agent_runtime=Conversation.AgentRuntime.LANGGRAPH,)is_new_conversation = Trueis_idle = conversation.status == Conversation.Status.IDLEhas_message = serializer.validated_data.get("message") is not Nonehas_resume_payload = serializer.validated_data.get("resume_payload") is not None- is_sandbox = (- serializer.validated_data.get("is_sandbox", False)++ # Sandbox conversations — including the legacy LangGraph→sandbox conversion of a reopened+ # thread — are served exclusively by the `open` endpoint. Reject any that reach this one,+ # whether an already-sandbox row or a sandbox-signalling body, so a sandbox conversation can+ # never fall through to the LangGraph workflow below.+ if (+ conversation.agent_runtime == Conversation.AgentRuntime.SANDBOX+ or serializer.validated_data.get("is_sandbox", False)or serializer.validated_data.get("agent_mode") == AgentMode.SANDBOX- )+ ):+ raise exceptions.ValidationError("Sandbox conversations must be opened via the open endpoint.")if conversation.type == Conversation.Type.DEEP_RESEARCH:if not is_new_conversation and is_idle and has_message and not has_resume_payload:@@ -388,7 +508,7 @@ class ConversationViewSet(else:is_research = True- if has_message and not is_idle and not is_sandbox:+ if has_message and not is_idle:raise Conflict("Cannot resume streaming with a new message")# If the frontend is trying to resume streaming for a finished conversation, return a conflict errorif not has_message and conversation.status == Conversation.Status.IDLE and not has_resume_payload:@@ -396,16 +516,6 @@ class ConversationViewSet(is_impersonated = is_impersonated_session(request)- if is_sandbox and has_message:- return handle_sandbox_message(- conversation=conversation,- conversation_id=str(conversation_id),- content=serializer.validated_data["content"],- user=cast(User, request.user),- team=self.team,- is_new_conversation=is_new_conversation,- )-workflow_inputs: ChatAgentWorkflowInputs | ResearchAgentWorkflowInputsworkflow_class: type[ChatAgentWorkflow] | type[ResearchAgentWorkflow]if is_research:@@ -567,8 +677,188 @@ class ConversationViewSet(queue_store = ConversationQueueStore(conversation_id)return self._queue_response(queue_store, queue_store.clear())+ @extend_schema(+ request=SandboxOpenSerializer,+ responses={+ 200: SandboxMessageResponseSerializer,+ 204: OpenApiResponse(description="Warm request that provisioned nothing (pool full / released)."),+ 400: OpenApiResponse(description="Conversation is not on the sandbox runtime."),+ },+ description=(+ "Create-or-resume a sandbox conversation — the single sandbox session opener. With `content`, "+ "processes the turn (first message, in-progress follow-up, or terminal resume); without `content`, "+ "warms a sandbox that idles awaiting the first message. Returns the `(task, run)` handle the "+ "frontend opens SSE against. The conversation row is created on first use from the URL id."+ ),+ )+ @action(detail=True, methods=["POST"], url_path="open")+ def open(self, request: Request, *args, **kwargs):+ # Both warming and messaging launch a Run, so gate both on the AI-credit quota.+ if is_team_limited(self.team.api_token, QuotaResource.AI_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY):+ raise QuotaLimitExceeded(+ "Your organization reached its AI credit usage limit. Increase the limits in Billing settings, or ask an org admin to do so."+ )+ serializer = SandboxOpenSerializer(data=request.data, context=self.get_serializer_context())+ serializer.is_valid(raise_exception=True)++ conversation, created = self._get_or_create_sandbox_conversation(+ request, bind_task=serializer.validated_data.get("task_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:+ raise exceptions.ValidationError("This conversation is not on the sandbox runtime.")++ 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+ )++ def _get_or_create_sandbox_conversation(+ self, request: Request, *, bind_task: uuid.UUID | None = None+ ) -> tuple[Conversation, bool]:+ """Resolve the URL-keyed conversation, creating it on first use (the client mints the id).++ `open` is create-or-resume: a brand-new conversation (first warm or first message) has no row+ yet, so a plain `get_object()` would 404. A brand-new row is only born on the sandbox runtime,+ and only for a sandbox-eligible caller — otherwise we'd persist an orphaned LangGraph row that+ `open` immediately rejects. Returns whether the row was created this request so the caller can+ drop it again if nothing ends up being provisioned.++ `bind_task` (already validated for team + visibility by `SandboxOpenSerializer`) binds the new+ row to an existing Task, so the first message resumes that Task's run instead of starting a+ fresh task. It only applies on create — an existing conversation keeps the Task it was born with.+ """+ conversation_id = self.kwargs[self.lookup_url_kwarg]+ user = cast(User, request.user)+ try:+ # nosemgrep: idor-lookup-without-team, idor-taint-user-input-to-model-get (user+team checked below)+ conversation = Conversation.objects.get(id=conversation_id)+ except Conversation.DoesNotExist:+ # Gate first-use creation on eligibility so a non-sandbox caller can't spam orphaned rows+ # by POSTing `open` with random ids — `open` would create then reject each one otherwise.+ if not has_sandbox_mode_feature_flag(self.team, user):+ raise exceptions.ValidationError("This conversation is not on the sandbox runtime.")+ conversation = Conversation.objects.create(+ user=user,+ team=self.team,+ id=conversation_id,+ type=Conversation.Type.ASSISTANT,+ is_internal=is_impersonated_session(request),+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ task_id=bind_task,+ )+ return conversation, True+ if conversation.user != user or conversation.team != self.team:+ raise exceptions.PermissionDenied("Cannot access other users' conversations")+ if conversation.deleted:+ 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.++ Runs only on a first message — no backing Task yet (`task_id is None`) and real content.+ Followups and resumes reuse the existing Task's repository, and warming has no message to+ route on, so neither triggers the (potentially heavy) selection. Selection never raises;+ any failure degrades to None — a repo-less sandbox — so it can't block the conversation.+ """+ if conversation.task_id is not None:+ return None+ content = request.data.get("content")+ if not isinstance(content, str) or not content.strip():+ return None+ return asgi_async_to_sync(tasks_facade.select_repository_for_message)(+ self.team_id, user.pk, content, origin_product=tasks_facade.TaskOriginProduct.POSTHOG_AI+ )++ def _route_sandbox_message(+ self,+ 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+ )+ 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.+ if created:+ conversation.delete()+ return Response(status=status.HTTP_204_NO_CONTENT)+ content = request.data.get("content")+ if isinstance(content, str) and content.strip():+ report_user_action(+ user,+ "prompt sent",+ {+ "trace_id": result.trace_id,+ "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,+ },+ team=self.team,+ request=request,+ )+ # attached_context_count is internal telemetry plumbing — keep it out of the response body.+ return Response(result.model_dump(exclude={"attached_context_count"}), status=status.HTTP_200_OK)++ @extend_schema(+ description="Cancel the conversation's in-progress LangGraph run.",+ responses={+ 204: OpenApiResponse(description="Cancellation accepted, or already cancelling."),+ 422: OpenApiResponse(description="Failed to cancel the conversation."),+ },+ )@action(detail=True, methods=["PATCH"])def cancel(self, request: Request, *args, **kwargs):+ # Sandbox runs cancel through the generic tasks relay (`runs/{run}/command/`); this endpoint+ # serves the LangGraph runtime only.conversation = self.get_object()# IDLE is intentionally not short-circuited: during the handoff between the maindiff --git a/ee/api/test/test_conversation.py b/ee/api/tests/test_conversation.pysimilarity index 58%rename from ee/api/test/test_conversation.pyrename to ee/api/tests/test_conversation.pyindex fb82bebbb34e..481ac56322c9 100644--- a/ee/api/test/test_conversation.py+++ b/ee/api/tests/test_conversation.py@@ -5,11 +5,15 @@ from typing import Any, castfrom posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, patch+from django.db import connectionfrom django.http import StreamingHttpResponsefrom django.test import override_settings+from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom rest_framework import status+from rest_framework.exceptions import Throttled+from rest_framework.test import APIRequestFactoryfrom posthog.schema import (AgentMode,@@ -27,10 +31,13 @@ from posthog.schema import (from posthog.models.team.team import Teamfrom posthog.models.user import User+from posthog.rate_limit import AIBurstRateThrottlefrom posthog.temporal.ai.chat_agent import ChatAgentWorkflow, ChatAgentWorkflowInputsfrom posthog.temporal.ai.research_agent import ResearchAgentWorkflow, ResearchAgentWorkflowInputs+from products.posthog_ai.backend.message_routing import SandboxRouteResultfrom products.posthog_ai.backend.models.assistant import Conversation+from products.tasks.backend.models import Task, TaskRunfrom ee.api.conversation import ConversationViewSet@@ -1246,3 +1253,825 @@ class TestConversationSoftDelete(APIBaseTest):still_deleted = Conversation.objects.get(pk=conversation.pk)self.assertTrue(still_deleted.deleted)self.assertEqual(Conversation.objects.filter(pk=conversation.pk).count(), 1)+++class TestConversationSandboxRoute(APIBaseTest):+ def setUp(self):+ super().setUp()+ # Repo auto-routing runs on every first message; mock it so these tests stay deterministic+ # and never reach the GitHub-integration lookups. Individual tests override the return value.+ patcher = patch(+ "products.tasks.backend.facade.api.select_repository_for_message", new=AsyncMock(return_value=None)+ )+ self.mock_select_repo = patcher.start()+ self.addCleanup(patcher.stop)++ def _sandbox_conversation(self) -> Conversation:+ return Conversation.objects.create(+ user=self.user,+ team=self.team,+ title="A chat",+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ )++ def test_open_with_content_reachable_and_delegates_to_session(self):+ conversation = self._sandbox_conversation()+ sentinel = SandboxRouteResult(+ task_id="t",+ run_id="r",+ trace_id=None,+ run_status="queued",+ just_created_run=True,+ attached_context_count=2,+ )+ with (+ patch("ee.api.conversation.SandboxSession") as m_session,+ patch("ee.api.conversation.report_user_action") as m_telemetry,+ ):+ m_session.return_value.open.return_value = sentinel+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {"content": "hello", "trace_id": str(uuid.uuid4()), "initial_permission_mode": "auto"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ # attached_context_count is internal telemetry plumbing, excluded from the response body.+ self.assertEqual(response.json(), sentinel.model_dump(exclude={"attached_context_count"}))+ m_session.return_value.open.assert_called_once()+ self.assertEqual(m_session.return_value.open.call_args[0][0]["initial_permission_mode"], "auto")+ # The session receives the resolved conversation, not just an id.+ passed_conversation = m_session.call_args[0][0]+ self.assertEqual(passed_conversation.id, conversation.id)+ # Telemetry fires once at the API boundary with sandbox-path field parity, derived+ # from the routing result.+ m_telemetry.assert_called_once()+ props = m_telemetry.call_args[0][2]+ self.assertEqual(props["execution_type"], "sandbox")+ self.assertEqual(props["agent_runtime"], "sandbox")+ self.assertTrue(props["has_attached_context"])+ self.assertEqual(props["attached_context_count"], 2)++ def test_open_with_content_creates_new_conversation_row(self):+ # `open` is create-or-resume — a brand-new conversation has no row yet; the first message+ # creates it (origin product posthog_ai, born sandbox under the flag) and returns the handle.+ conversation_id = str(uuid.uuid4())+ 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.SandboxSession") as m_session,+ patch("ee.api.conversation.report_user_action"),+ ):+ m_session.return_value.open.return_value = sentinel+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation_id}/open/",+ {"content": "first message please", "trace_id": str(uuid.uuid4())},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), sentinel.model_dump(exclude={"attached_context_count"}))+ conversation = Conversation.objects.get(id=conversation_id)+ self.assertEqual(conversation.user, self.user)+ self.assertEqual(conversation.team, self.team)+ self.assertEqual(conversation.agent_runtime, Conversation.AgentRuntime.SANDBOX)+ # The first message stamps the title from the content.+ self.assertEqual(conversation.title, "first message please")+ passed_conversation = m_session.call_args[0][0]+ self.assertEqual(str(passed_conversation.id), str(conversation.id))++ def test_open_binds_new_conversation_to_existing_task(self):+ # "Open task" opens a blank chat pre-bound to an existing Task: the first message creates the+ # conversation row bound to that Task, so routing resumes the Task's run (terminal-resume)+ # instead of starting a fresh task.+ task = Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ task.create_run(mode="background")+ conversation_id = str(uuid.uuid4())+ sentinel = SandboxRouteResult(+ task_id=str(task.id), 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.SandboxSession") as m_session,+ patch("ee.api.conversation.report_user_action"),+ ):+ m_session.return_value.open.return_value = sentinel+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation_id}/open/",+ {"content": "continue this task", "trace_id": str(uuid.uuid4()), "task_id": str(task.id)},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ conversation = Conversation.objects.get(id=conversation_id)+ self.assertEqual(conversation.task_id, task.id)+ self.assertEqual(conversation.agent_runtime, Conversation.AgentRuntime.SANDBOX)+ # The session opens against the bound conversation, so its task_id drives terminal-run resume+ # — no repository is auto-routed (the resumed Task already has one).+ passed_conversation = m_session.call_args[0][0]+ self.assertEqual(passed_conversation.task_id, task.id)+ self.mock_select_repo.assert_not_awaited()++ def test_open_rejects_task_id_from_another_team(self):+ # IDOR guard: a Task from another team isn't visible, so the serializer rejects it (400) and+ # no conversation row is created.+ other_team = Team.objects.create(organization=self.organization, name="other team")+ other_task = Task.objects.create(+ team=other_team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ conversation_id = str(uuid.uuid4())+ with (+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),+ patch("ee.api.conversation.SandboxSession") as m_session,+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation_id}/open/",+ {"content": "continue this task", "trace_id": str(uuid.uuid4()), "task_id": str(other_task.id)},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(Conversation.objects.filter(id=conversation_id).exists())+ m_session.return_value.open.assert_not_called()++ def test_open_rejects_task_not_visible_to_user(self):+ # A teammate's personal task isn't visible (task_visibility_q), so it can't be bound by id.+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ teammate_task = Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=teammate,+ )+ conversation_id = str(uuid.uuid4())+ with (+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),+ patch("ee.api.conversation.SandboxSession") as m_session,+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation_id}/open/",+ {"content": "continue this task", "trace_id": str(uuid.uuid4()), "task_id": str(teammate_task.id)},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(Conversation.objects.filter(id=conversation_id).exists())+ m_session.return_value.open.assert_not_called()++ def test_retrieve_other_users_sandbox_conversation_includes_task(self):+ # Read follows the conversation (the share-by-link unit): a teammate handed the link reads its+ # backing task too, even though a direct task read would hide a non-creator's task (task_visibility_q).+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ task = Task.objects.create(+ team=self.team,+ title="t",+ description="secret description",+ repository="acme/widgets",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=teammate,+ )+ conversation = Conversation.objects.create(+ user=teammate,+ team=self.team,+ title="A chat",+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ task=task,+ )++ response = self.client.get(f"/api/environments/{self.team.id}/conversations/{conversation.id}/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["task"]["id"], str(task.id))+ self.assertEqual(response.json()["task"]["repository"], "acme/widgets")++ def test_open_other_users_conversation_rejected(self):+ # Write/send stays creator-only: a teammate can read the shared conversation but cannot provision+ # a run on it, so reading a task can never escalate to acting on it.+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ conversation = Conversation.objects.create(+ user=teammate,+ team=self.team,+ title="A chat",+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ )+ with (+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),+ patch("ee.api.conversation.SandboxSession") as m_session,+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {"content": "hi", "trace_id": str(uuid.uuid4())},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ m_session.return_value.open.assert_not_called()++ def test_open_binds_team_visible_signal_report_task(self):+ # Signals tasks are team-scoped artifacts visible to any team member, even when created under a+ # system-picked user — so a teammate's signal-report task can be bound.+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ signal_task = Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ created_by=teammate,+ )+ conversation_id = str(uuid.uuid4())+ sentinel = SandboxRouteResult(+ task_id=str(signal_task.id), 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.SandboxSession") as m_session,+ patch("ee.api.conversation.report_user_action"),+ ):+ m_session.return_value.open.return_value = sentinel+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation_id}/open/",+ {"content": "continue this task", "trace_id": str(uuid.uuid4()), "task_id": str(signal_task.id)},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(Conversation.objects.get(id=conversation_id).task_id, signal_task.id)++ def test_open_ignores_task_id_for_existing_conversation(self):+ # Binding only happens on create — an existing conversation keeps the Task it was born with+ # (here: none), even if a later `open` carries a `task_id`.+ conversation = self._sandbox_conversation()+ task = Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ sentinel = SandboxRouteResult(+ task_id="t", run_id="r", trace_id=None, run_status="queued", just_created_run=True+ )+ with (+ patch("ee.api.conversation.SandboxSession") as m_session,+ patch("ee.api.conversation.report_user_action"),+ ):+ m_session.return_value.open.return_value = sentinel+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {"content": "hello", "trace_id": str(uuid.uuid4()), "task_id": str(task.id)},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ conversation.refresh_from_db()+ self.assertIsNone(conversation.task_id)++ def test_open_first_message_routes_repository_into_session(self):+ # The auto-routed repository for a first message is threaded into the session opener.+ conversation = self._sandbox_conversation()+ self.mock_select_repo.return_value = "posthog/posthog-js"+ sentinel = SandboxRouteResult(+ task_id="t", run_id="r", trace_id=None, run_status="queued", just_created_run=True+ )+ with (+ patch("ee.api.conversation.SandboxSession") as m_session,+ patch("ee.api.conversation.report_user_action"),+ ):+ m_session.return_value.open.return_value = sentinel+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {"content": "fix the SDK", "trace_id": str(uuid.uuid4())},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.mock_select_repo.assert_awaited_once()+ self.assertEqual(m_session.return_value.open.call_args.kwargs["repository"], "posthog/posthog-js")++ def test_open_warm_does_not_route_repository(self):+ # A content-less warm has no message to route on, so selection must not run.+ conversation = self._sandbox_conversation()+ sentinel = SandboxRouteResult(+ task_id="t", run_id="r", trace_id=None, run_status="queued", just_created_run=True+ )+ with patch("ee.api.conversation.SandboxSession") as m_session:+ m_session.return_value.open.return_value = sentinel+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {"content": None},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.mock_select_repo.assert_not_awaited()+ self.assertIsNone(m_session.return_value.open.call_args.kwargs["repository"])++ def test_open_followup_does_not_route_repository(self):+ # A conversation already backed by a Task is a followup/resume — it reuses the existing+ # repository, so selection must not run again.+ conversation = self._sandbox_conversation()+ task = Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ conversation.task = task+ conversation.save(update_fields=["task"])+ sentinel = SandboxRouteResult(+ task_id="t", run_id="r", trace_id=None, run_status="queued", just_created_run=False+ )+ with (+ patch("ee.api.conversation.SandboxSession") as m_session,+ patch("ee.api.conversation.report_user_action"),+ ):+ m_session.return_value.open.return_value = sentinel+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {"content": "follow up", "trace_id": str(uuid.uuid4())},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.mock_select_repo.assert_not_awaited()+ self.assertIsNone(m_session.return_value.open.call_args.kwargs["repository"])++ def test_open_without_content_warms(self):+ # A null/absent content warms a sandbox; the session returns a fresh warm handle (200), or+ # None (204) when the pool provisioned nothing.+ conversation = self._sandbox_conversation()+ sentinel = SandboxRouteResult(+ task_id="t", run_id="r", trace_id=None, run_status="queued", just_created_run=True+ )+ with (+ patch("ee.api.conversation.SandboxSession") as m_session,+ patch("ee.api.conversation.report_user_action") as m_telemetry,+ ):+ m_session.return_value.open.return_value = sentinel+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {"content": None},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), sentinel.model_dump(exclude={"attached_context_count"}))+ m_session.return_value.open.assert_called_once()+ # A warm carries no message, so it must not fire "prompt sent" telemetry.+ m_telemetry.assert_not_called()++ def test_open_warm_provisioning_nothing_returns_204(self):+ # When the warm pool is full, the session returns None — the action surfaces a 204.+ conversation = self._sandbox_conversation()+ with (+ patch("ee.api.conversation.SandboxSession") as m_session,+ patch("ee.api.conversation.report_user_action") as m_telemetry,+ ):+ m_session.return_value.open.return_value = None+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ m_session.return_value.open.assert_called_once()+ m_telemetry.assert_not_called()+ # An existing conversation is never dropped by a no-op warm — only rows created this request are.+ self.assertTrue(Conversation.objects.filter(id=conversation.id).exists())++ def test_open_new_conversation_without_flag_is_rejected_without_creating_row(self):+ # A caller without the sandbox flag must not be able to spam orphaned rows by POSTing `open`+ # with random ids — first-use creation is gated on eligibility, so no row is persisted.+ conversation_id = str(uuid.uuid4())+ with (+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=False),+ patch("ee.api.conversation.SandboxSession") as m_session,+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation_id}/open/",+ {"content": "hello", "trace_id": str(uuid.uuid4())},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ m_session.assert_not_called()+ self.assertFalse(Conversation.objects.filter(id=conversation_id).exists())++ def test_open_new_conversation_warm_provisioning_nothing_drops_created_row(self):+ # A content-less warm on a brand-new id creates the row, but if the pool provisions nothing the+ # action returns 204 and removes the row it created — no orphaned conversations accumulate.+ conversation_id = str(uuid.uuid4())+ with (+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),+ patch("ee.api.conversation.SandboxSession") as m_session,+ ):+ m_session.return_value.open.return_value = None+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation_id}/open/",+ {"content": None},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ m_session.return_value.open.assert_called_once()+ self.assertFalse(Conversation.objects.filter(id=conversation_id).exists())++ def test_open_blocked_when_quota_limited(self):+ conversation = self._sandbox_conversation()+ with (+ patch("ee.api.conversation.is_team_limited", return_value=True),+ patch("ee.api.conversation.SandboxSession") as m_session,+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {"content": "hello"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_402_PAYMENT_REQUIRED)+ m_session.assert_not_called()++ def test_open_validates_request_body(self):+ conversation = self._sandbox_conversation()+ bad_payloads = [+ {"content": "x" * 40001}, # over the content length cap+ {"content": "hello", "trace_id": "not-a-uuid"}, # malformed trace id+ {"content": "hello", "initial_permission_mode": "full-access"}, # Codex-only mode, not valid for Claude+ ]+ for payload in bad_payloads:+ with patch("ee.api.conversation.SandboxSession") as m_session:+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ payload,+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, payload)+ m_session.assert_not_called()++ def test_open_rejects_other_users_conversation(self):+ other_user = User.objects.create_and_join(+ organization=self.organization,+ email="[email protected]",+ password="password",+ first_name="Other",+ )+ conversation = Conversation.objects.create(+ user=other_user,+ team=self.team,+ title="A chat",+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ )+ with patch("ee.api.conversation.SandboxSession") as m_session:+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {"content": "hello"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ m_session.assert_not_called()++ @override_settings(DEBUG=False)+ def test_get_throttles_returns_empty_for_open_action(self):+ # Like create, the open action's AI throttles are applied conditionally in check_throttles().+ viewset = ConversationViewSet()+ viewset.action = "open"+ viewset.team_id = self.team.id+ viewset.organization = self.organization+ self.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.+ conversation = Conversation.objects.create(+ user=self.user,+ team=self.team,+ title="A chat",+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.LANGGRAPH,+ )+ with (+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=False),+ patch("ee.api.conversation.SandboxSession") as m_session,+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/{conversation.id}/open/",+ {"content": "hello"},+ format="json",+ )+ 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 the+ # AI-throttle branch and is rejected once the burst throttle denies.+ viewset = ConversationViewSet()+ viewset.action = "open"+ viewset.team_id = self.team.id+ viewset.organization = self.organization++ request = APIRequestFactory().post("/")+ with (+ patch.object(ConversationViewSet, "_is_research_request", return_value=False) as m_research,+ patch.object(AIBurstRateThrottle, "allow_request", return_value=False),+ patch.object(AIBurstRateThrottle, "wait", return_value=30),+ ):+ with self.assertRaises(Throttled):+ viewset.check_throttles(request)+ m_research.assert_called_once()+++class TestConversationListTaskHandle(APIBaseTest):+ def _task(self) -> Task:+ return Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )++ def _sandbox_conversation(self, title: str) -> TaskRun:+ task = self._task()+ latest = task.create_run(mode="interactive")+ Conversation.objects.create(+ user=self.user,+ team=self.team,+ title=title,+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ task=task,+ )+ return latest++ def test_list_surfaces_task_handle_with_run_id(self):+ latest = self._sandbox_conversation("Sandbox chat")++ with patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock):+ response = self.client.get(f"/api/environments/{self.team.id}/conversations/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ results = response.json()["results"]+ self.assertEqual(len(results), 1)+ self.assertEqual(results[0]["task"]["id"], str(latest.task_id))+ # The handle carries the latest run as a bare id (not the nested run detail).+ self.assertEqual(results[0]["task"]["latest_run"], str(latest.id))++ def test_list_reports_null_task_for_langgraph(self):+ Conversation.objects.create(+ user=self.user,+ team=self.team,+ title="LangGraph chat",+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.LANGGRAPH,+ )++ with patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock):+ response = self.client.get(f"/api/environments/{self.team.id}/conversations/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ results = response.json()["results"]+ self.assertEqual(len(results), 1)+ self.assertIsNone(results[0]["task"])++ def test_retrieve_surfaces_task_handle_with_run_id(self):+ # A sandbox conversation backed by a Task with runs, and one with no Task at all.+ latest = self._sandbox_conversation("With task")+ with_task = Conversation.objects.get(task_id=latest.task_id)+ without_task = Conversation.objects.create(+ user=self.user,+ team=self.team,+ title="No task",+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ )++ base = f"/api/environments/{self.team.id}/conversations/"+ with patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock):+ r_with = self.client.get(f"{base}{with_task.id}/")+ r_without = self.client.get(f"{base}{without_task.id}/")++ self.assertEqual(r_with.status_code, status.HTTP_200_OK)+ self.assertEqual(r_without.status_code, status.HTTP_200_OK)+ self.assertEqual(r_with.json()["task"]["id"], str(latest.task_id))+ self.assertEqual(r_with.json()["task"]["latest_run"], str(latest.id))+ self.assertIsNone(r_without.json()["task"])++ def test_list_query_count_does_not_scale_with_conversation_count(self):+ url = f"/api/environments/{self.team.id}/conversations/"++ with patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock):+ # One sandbox conversation establishes the baseline query count. Warm the request+ # first so one-time session/auth queries don't skew the comparison.+ self._sandbox_conversation("Chat 1")+ self.client.get(url)+ with CaptureQueriesContext(connection) as ctx:+ response = self.client.get(url)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ baseline = len(ctx.captured_queries)++ # More sandbox conversations (each with its own Task + runs) must not add per-row+ # queries — the backing tasks load in one batched facade call without run lookups.+ self._sandbox_conversation("Chat 2")+ self._sandbox_conversation("Chat 3")++ with self.assertNumQueries(baseline):+ response = self.client.get(url)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(response.json()["results"]), 3)+++class TestConversationCreateRuntime(APIBaseTest):+ """`POST /conversations` is LangGraph-only — it never serves or converts to the sandbox runtime."""++ def _langgraph_conversation(self, **overrides) -> Conversation:+ defaults: dict[str, Any] = {+ "user": self.user,+ "team": self.team,+ "title": "A chat",+ "type": Conversation.Type.ASSISTANT,+ "agent_runtime": Conversation.AgentRuntime.LANGGRAPH,+ "status": Conversation.Status.IDLE,+ }+ defaults.update(overrides)+ return Conversation.objects.create(**defaults)++ def _send(self, conversation: Conversation, content: str = "resume on sandbox"):+ return self.client.post(+ f"/api/environments/{self.team.id}/conversations/",+ {"content": content, "trace_id": str(uuid.uuid4()), "conversation": str(conversation.id)},+ )++ def _mock_streaming_response(self, streaming_content: Any, *args: Any, **kwargs: Any) -> StreamingHttpResponse:+ return StreamingHttpResponse([b""], content_type="text/event-stream")++ def test_retrieve_does_not_convert(self):+ # Opening a conversation never converts — conversion only fires on a new message.+ conversation = self._langgraph_conversation()+ with (+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),+ patch("ee.api.conversation.SandboxSession") as m_routing,+ patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock),+ ):+ response = self.client.get(f"/api/environments/{self.team.id}/conversations/{conversation.id}/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ m_routing.assert_not_called()+ conversation.refresh_from_db()+ self.assertEqual(conversation.agent_runtime, Conversation.AgentRuntime.LANGGRAPH)+ self.assertIsNone(conversation.task_id)++ def test_create_new_conversation_is_langgraph_even_with_sandbox_flag(self):+ # `open` owns sandbox creation, so a conversation born via create is always LangGraph —+ # even for a user on the sandbox flag — and never touches the sandbox router.+ conversation_id = str(uuid.uuid4())+ with (+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),+ patch("ee.api.conversation.SandboxSession") as m_routing,+ patch("ee.hogai.core.executor.AgentExecutor.astream", return_value=_async_generator()),+ patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._mock_streaming_response),+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/",+ {"content": "hello", "trace_id": str(uuid.uuid4()), "conversation": conversation_id},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ m_routing.assert_not_called()+ self.assertEqual(+ Conversation.objects.get(id=conversation_id).agent_runtime, Conversation.AgentRuntime.LANGGRAPH+ )++ def test_create_rejects_sandbox_signalling_body(self):+ # A sandbox-signalling body is refused — sandbox conversations must use `open`.+ conversation = self._langgraph_conversation()+ for body in ({"is_sandbox": True}, {"agent_mode": "sandbox"}):+ with patch("ee.api.conversation.SandboxSession") as m_routing:+ response = self.client.post(+ f"/api/environments/{self.team.id}/conversations/",+ {+ "content": "hi",+ "trace_id": str(uuid.uuid4()),+ "conversation": str(conversation.id),+ **body,+ },+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, body)+ m_routing.assert_not_called()++ def test_create_rejects_existing_sandbox_conversation(self):+ # A sandbox conversation that reaches create is refused outright — it must go through `open`,+ # never fall through to the LangGraph workflow.+ conversation = self._langgraph_conversation(agent_runtime=Conversation.AgentRuntime.SANDBOX)+ with patch("ee.api.conversation.SandboxSession") as m_routing:+ response = self._send(conversation)++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ m_routing.assert_not_called()++ def test_create_no_sandbox_flag_streams_langgraph(self):+ # Without the sandbox flag, a reopened LangGraph thread stays LangGraph and the message+ # takes the streaming path — never the sandbox router.+ conversation = self._langgraph_conversation()+ with (+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=False),+ patch("ee.api.conversation.SandboxSession") as m_routing,+ patch("ee.hogai.core.executor.AgentExecutor.astream", return_value=_async_generator()),+ patch("ee.api.conversation.StreamingHttpResponse", side_effect=self._mock_streaming_response),+ ):+ response = self._send(conversation, content="keep me on langgraph")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ m_routing.assert_not_called()+ conversation.refresh_from_db()+ self.assertEqual(conversation.agent_runtime, Conversation.AgentRuntime.LANGGRAPH)++ def test_create_non_idle_langgraph_does_not_convert(self):+ # Conversion requires an idle conversation; a non-idle LangGraph thread getting a new+ # message hits the existing "cannot resume streaming" conflict instead.+ conversation = self._langgraph_conversation(status=Conversation.Status.IN_PROGRESS)+ with (+ patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),+ patch("ee.api.conversation.SandboxSession") as m_routing,+ ):+ response = self._send(conversation)++ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ m_routing.assert_not_called()diff --git a/ee/hogai/api/serializers.py b/ee/hogai/api/serializers.pyindex 404094e080cb..1e19477b37dc 100644--- a/ee/hogai/api/serializers.py+++ b/ee/hogai/api/serializers.py@@ -1,14 +1,19 @@from typing import Anyimport pydantic-from asgiref.sync import async_to_sync+from asgiref.sync import async_to_sync, sync_to_async+from drf_spectacular.utils import extend_schema_fieldfrom langgraph.graph.state import CompiledStateGraphfrom rest_framework import serializers+from rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.shared import UserBasicSerializerfrom posthog.exceptions_capture import capture_exceptionfrom products.posthog_ai.backend.models.assistant import Conversation+from products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.facade.contracts import TaskDetailDTO, TaskRunDetailDTO, TaskUserBasicInfo+from products.tasks.backend.facade.run_config import PUBLIC_REASONING_EFFORTS, LLMProvider, RuntimeAdapterfrom ee.hogai.artifacts.manager import ArtifactManagerfrom ee.hogai.chat_agent import AssistantGraph@@ -43,13 +48,218 @@ CONVERSATION_TYPE_MAP: dict[}+async def aget_conversation_state(+ conversation: Conversation, team: Any, user: Any+) -> tuple[AssistantMaxGraphState | None, bool, dict[str, dict[str, Any]]]:+ """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+ the graph-compile + checkpoint-replay logic is never duplicated.++ Returns (state, has_unsupported_content, interrupt_payloads). `state` is None for born-sandbox+ conversations (no checkpoint) and on any read/validation error — errors degrade gracefully+ and are captured rather than raised so a bad checkpoint can't 500 a conversation load.+ """+ # 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.+ if conversation.agent_runtime == Conversation.AgentRuntime.SANDBOX:+ has_checkpoint = await sync_to_async(conversation.checkpoints.exists)()+ if not has_checkpoint:+ return None, False, {}++ try:+ graph_class, state_class = CONVERSATION_TYPE_MAP[conversation.type] # type: ignore[index]+ graph: CompiledStateGraph = graph_class(team, user).compile_full_graph()+ snapshot = await graph.aget_state({"configurable": {"thread_id": str(conversation.id), "checkpoint_ns": ""}})+ state = state_class.model_validate(snapshot.values)++ # Extract interrupt payloads from pending tasks — the single source of truth for payload data.+ interrupt_payloads: dict[str, dict[str, Any]] = {}+ for task in snapshot.tasks:+ for interrupt in task.interrupts:+ if isinstance(interrupt.value, dict) and interrupt.value.get("status") == PENDING_APPROVAL_STATUS:+ proposal_id = interrupt.value.get("proposal_id")+ if proposal_id:+ interrupt_payloads[proposal_id] = interrupt.value++ return state, False, interrupt_payloads+ except pydantic.ValidationError as e:+ capture_exception(+ e,+ additional_properties={+ "tag": "max_ai",+ "exception_type": "ValidationError",+ "conversation_id": str(conversation.id),+ },+ )+ return None, True, {}+ except Exception as e:+ # Broad exception handler to gracefully degrade UI instead of 500s.+ # Captures all errors (context access, graph compilation, validation, etc.) to PostHog.+ capture_exception(+ e,+ additional_properties={+ "tag": "max_ai",+ "exception_type": type(e).__name__,+ "conversation_id": str(conversation.id),+ },+ )+ return None, False, {}+++class TaskUserBasicInfoSerializer(DataclassSerializer):+ """Response shape for a task creator, mirroring core ``UserBasicSerializer`` output."""++ class Meta:+ dataclass = TaskUserBasicInfo+++class TaskRunArtifactResponseSerializer(serializers.Serializer):+ id = serializers.CharField(required=False, help_text="Stable identifier for the artifact within this run")+ name = serializers.CharField(help_text="Artifact file name")+ type = serializers.CharField(help_text="Artifact classification, such as plan or output")+ source = serializers.CharField( # type: ignore[assignment] # field literally named `source`; shadows base `Field.source`+ required=False,+ allow_blank=True,+ help_text="Source of the artifact, such as agent_output or user_attachment",+ )+ size = serializers.IntegerField(required=False, help_text="Artifact size in bytes")+ content_type = serializers.CharField(required=False, allow_blank=True, help_text="Optional MIME type")+ storage_path = serializers.CharField(help_text="S3 object key for the artifact")+ uploaded_at = serializers.CharField(help_text="Timestamp when the artifact was uploaded")+++class TaskRunDetailSerializer(DataclassSerializer):+ """Detail response for the latest task run when a caller includes it."""++ task = serializers.UUIDField(help_text="Parent task id this run belongs to.")+ log_url = serializers.URLField(allow_null=True, required=False, help_text="Presigned S3 URL for log access.")+ artifacts = TaskRunArtifactResponseSerializer(many=True, read_only=True)+ runtime_adapter = serializers.ChoiceField(+ choices=[adapter.value for adapter in RuntimeAdapter],+ allow_null=True,+ required=False,+ help_text="Configured runtime adapter for this run, such as 'claude' or 'codex'.",+ )+ provider = serializers.ChoiceField(+ choices=[provider.value for provider in LLMProvider],+ allow_null=True,+ required=False,+ help_text="Configured LLM provider for this run, such as 'anthropic' or 'openai'.",+ )+ model = serializers.CharField(+ allow_null=True, required=False, help_text="Configured LLM model identifier for this run."+ )+ reasoning_effort = serializers.ChoiceField(+ choices=[effort.value for effort in PUBLIC_REASONING_EFFORTS],+ allow_null=True,+ required=False,+ help_text="Configured reasoning effort for this run when the selected model supports it.",+ )++ class Meta:+ dataclass = TaskRunDetailDTO+ fields = [+ "id",+ "task",+ "stage",+ "branch",+ "status",+ "environment",+ "runtime_adapter",+ "provider",+ "model",+ "reasoning_effort",+ "log_url",+ "error_message",+ "output",+ "state",+ "artifacts",+ "created_at",+ "updated_at",+ "completed_at",+ ]+++class TaskSerializer(DataclassSerializer):+ """Local serializer for the products/tasks task DTO exposed in conversation responses."""++ latest_run = TaskRunDetailSerializer(allow_null=True, required=False, help_text="Latest run details for this task")+ created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)++ class Meta:+ dataclass = TaskDetailDTO+ fields = [+ "id",+ "task_number",+ "slug",+ "title",+ "title_manually_set",+ "description",+ "origin_product",+ "repository",+ "github_integration",+ "github_user_integration",+ "signal_report",+ "json_schema",+ "internal",+ "archived",+ "archived_at",+ "latest_run",+ "created_at",+ "updated_at",+ "created_by",+ "ci_prompt",+ ]+++class ConversationTaskSerializer(TaskSerializer):+ """Conversation envelope variant: ``latest_run`` is just the latest run's id, not the nested+ run detail. The frontend only needs the id to reconnect to sandbox logs, and emitting the id+ avoids presigning a log URL per conversation.++ Read access here follows the conversation (the share-by-link unit), not per-creator task+ visibility — write/send stays creator-gated. See ``tasks_facade.get_conversation_task_dtos``."""++ latest_run = serializers.UUIDField( # type: ignore[assignment] # intentional narrowing of the base nested-run field to its id+ source="latest_run_id",+ allow_null=True,+ read_only=True,+ help_text="Id of the latest TaskRun; null when the task has no runs.",+ )++class ConversationMinimalSerializer(serializers.ModelSerializer):class Meta:model = Conversation- fields = _conversation_fields+ # `task` is exposed here (not in `_conversation_fields`) so it stays out of the full+ # serializer's field list, which already appends `task` itself — listing it twice+ # would raise a DRF duplicate-field error.+ fields = [*_conversation_fields, "task"]read_only_fields = fieldsuser = UserBasicSerializer(read_only=True)+ task = serializers.SerializerMethodField()++ @extend_schema_field(ConversationTaskSerializer(allow_null=True))+ def get_task(self, conversation: Conversation) -> dict[str, Any] | None:+ if conversation.task_id is None:+ return None++ task_dtos = self.context.get("conversation_task_dtos_by_id")+ task_dto: TaskDetailDTO | None = (+ task_dtos.get(str(conversation.task_id)) if isinstance(task_dtos, dict) else None+ )+ if task_dto is None:+ team = self.context["team"]+ task_dto = tasks_facade.get_conversation_task_dtos([conversation.task_id], team.id).get(+ conversation.task_id+ )+ if task_dto is None:+ return None+ return ConversationTaskSerializer(task_dto).dataclass ConversationSerializer(ConversationMinimalSerializer):@@ -60,11 +270,23 @@ class ConversationSerializer(ConversationMinimalSerializer):"messages","has_unsupported_content","agent_mode",+ "agent_runtime","is_sandbox","pending_approvals",+ "task",]read_only_fields = fields+ agent_runtime = serializers.ChoiceField(+ choices=Conversation.AgentRuntime.choices,+ 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`."+ ),+ )messages = serializers.SerializerMethodField()has_unsupported_content = serializers.SerializerMethodField()agent_mode = serializers.SerializerMethodField()@@ -72,22 +294,31 @@ 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.+ if conversation.agent_runtime == Conversation.AgentRuntime.SANDBOX:+ state, _, _ = self._get_cached_state(conversation)+ return self._render_state_messages(state)+if conversation.messages_json is not None:return conversation.messages_jsonstate, _, _ = self._get_cached_state(conversation)+ return self._render_state_messages(state)++ def _render_state_messages(self, state: AssistantMaxGraphState | None) -> list[dict[str, Any]]:if state is None:return []-try:team = self.context["team"]user = self.context["user"]artifact_manager = ArtifactManager(team, user)enriched_messages = async_to_sync(artifact_manager.aenrich_messages)(list(state.messages))- messages = [- message.model_dump() for message in enriched_messages if should_output_assistant_message(message)- ]- return messages+ return [message.model_dump() for message in enriched_messages if should_output_assistant_message(message)]except Exception as e:capture_exception(e)return []@@ -103,7 +334,7 @@ class ConversationSerializer(ConversationMinimalSerializer):return Nonedef get_is_sandbox(self, conversation: Conversation) -> bool:- return conversation.sandbox_task_id is not None+ return conversation.agent_runtime == Conversation.AgentRuntime.SANDBOXdef get_pending_approvals(self, conversation: Conversation) -> list[dict[str, Any]]:"""@@ -163,46 +394,4 @@ class ConversationSerializer(ConversationMinimalSerializer):Tuple of (state, has_unsupported_content, interrupt_payloads).interrupt_payloads is a dict mapping proposal_id to the interrupt value (including payload)."""- try:- team = self.context["team"]- user = self.context["user"]- graph_class, state_class = CONVERSATION_TYPE_MAP[conversation.type] # type: ignore[index]- graph: CompiledStateGraph = graph_class(team, user).compile_full_graph()- snapshot = await graph.aget_state(- {"configurable": {"thread_id": str(conversation.id), "checkpoint_ns": ""}}- )- state = state_class.model_validate(snapshot.values)-- # Extract interrupt payloads from pending tasks- # This is the single source of truth for payload data- interrupt_payloads: dict[str, dict[str, Any]] = {}- for task in snapshot.tasks:- for interrupt in task.interrupts:- if isinstance(interrupt.value, dict) and interrupt.value.get("status") == PENDING_APPROVAL_STATUS:- proposal_id = interrupt.value.get("proposal_id")- if proposal_id:- interrupt_payloads[proposal_id] = interrupt.value-- return state, False, interrupt_payloads- except pydantic.ValidationError as e:- capture_exception(- e,- additional_properties={- "tag": "max_ai",- "exception_type": "ValidationError",- "conversation_id": str(conversation.id),- },- )- return None, True, {}- except Exception as e:- # Broad exception handler to gracefully degrade UI instead of 500s- # Captures all errors (context access, graph compilation, validation, etc.) to PostHog- capture_exception(- e,- additional_properties={- "tag": "max_ai",- "exception_type": type(e).__name__,- "conversation_id": str(conversation.id),- },- )- return None, False, {}+ return await aget_conversation_state(conversation, self.context["team"], self.context["user"])diff --git a/ee/hogai/api/test/__init__.py b/ee/hogai/api/tests/__init__.pysimilarity index 100%rename from ee/hogai/api/test/__init__.pyrename to ee/hogai/api/tests/__init__.pydiff --git a/ee/hogai/api/test/test_serializers.py b/ee/hogai/api/tests/test_serializers.pysimilarity index 58%rename from ee/hogai/api/test/test_serializers.pyrename to ee/hogai/api/tests/test_serializers.pyindex 11852b8cf8ac..75bafea291e1 100644--- a/ee/hogai/api/test/test_serializers.py+++ b/ee/hogai/api/tests/test_serializers.py@@ -1,3 +1,4 @@+from dataclasses import replacefrom uuid import uuid4from posthog.test.base import APIBaseTest@@ -13,8 +14,15 @@ from posthog.schema import ()from products.posthog_ai.backend.models.assistant import AgentArtifact, Conversation--from ee.hogai.api.serializers import ConversationSerializer+from products.tasks.backend.facade.contracts import TaskDetailDTO, TaskRunDetailDTO+from products.tasks.backend.models import Task++from ee.hogai.api.serializers import (+ ConversationMinimalSerializer,+ ConversationSerializer,+ ConversationTaskSerializer,+ TaskSerializer,+)from ee.hogai.chat_agent import AssistantGraphfrom ee.hogai.utils.types import AssistantStatefrom ee.hogai.utils.types.base import ArtifactRefMessage@@ -234,6 +242,275 @@ class TestConversationSerializers(APIBaseTest):self.assertEqual(mock_get_state.call_count, 1)+class TestConversationSerializerRuntimeMessages(APIBaseTest):+ def test_sandbox_conversation_returns_empty_messages(self):+ """Sandbox conversations don't persist messages Django-side — `messages` is always empty."""+ conversation = Conversation.objects.create(+ user=self.user,+ team=self.team,+ title="Sandbox conversation",+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ messages_json=[{"type": "ai", "content": "should be ignored on the sandbox path"}],+ )++ # aget_state must never be invoked for a sandbox conversation — the guard short-circuits first.+ with patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock) as mock_get_state:+ data = ConversationSerializer(+ conversation,+ context={"team": self.team, "user": self.user},+ ).data++ self.assertEqual(data["messages"], [])+ self.assertEqual(data["agent_runtime"], Conversation.AgentRuntime.SANDBOX.value)+ mock_get_state.assert_not_called()++ def test_langgraph_conversation_returns_populated_messages(self):+ """LangGraph conversations keep today's behavior — messages come from the graph state."""+ conversation = Conversation.objects.create(+ user=self.user,+ team=self.team,+ title="LangGraph conversation",+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.LANGGRAPH,+ )++ state = AssistantState(messages=[AssistantMessage(content="Hello from LangGraph", type="ai")])++ with patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock) as mock_get_state:++ class MockSnapshot:+ values = state.model_dump()+ tasks = []++ mock_get_state.return_value = MockSnapshot()++ data = ConversationSerializer(+ conversation,+ context={"team": self.team, "user": self.user},+ ).data++ self.assertEqual(data["agent_runtime"], Conversation.AgentRuntime.LANGGRAPH.value)+ self.assertEqual(len(data["messages"]), 1)+ self.assertEqual(data["messages"][0]["content"], "Hello from LangGraph")+++class TestConversationSerializerTaskField(APIBaseTest):+ def _serialize(self, conversation: Conversation) -> dict:+ return ConversationSerializer(conversation, context={"team": self.team, "user": self.user}).data++ def _sandbox_conversation(self, task: Task | None = None) -> Conversation:+ return Conversation.objects.create(+ user=self.user,+ team=self.team,+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ task=task,+ )++ def _task(self) -> Task:+ return Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )++ def _task_dto(self) -> TaskDetailDTO:+ task_id = uuid4()+ run = TaskRunDetailDTO(+ id=uuid4(),+ task=task_id,+ stage=None,+ branch=None,+ status="queued",+ environment="local",+ runtime_adapter=None,+ provider=None,+ model=None,+ reasoning_effort=None,+ log_url=None,+ error_message=None,+ output=None,+ state={},+ )+ return TaskDetailDTO(+ id=task_id,+ task_number=1,+ slug="task-1",+ title="t",+ title_manually_set=False,+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ repository=None,+ github_integration=None,+ github_user_integration=None,+ signal_report=None,+ json_schema=None,+ internal=False,+ archived=False,+ archived_at=None,+ ci_prompt=None,+ latest_run=run,+ latest_run_id=run.id,+ )++ def test_task_serializer_nests_latest_run_detail(self):+ task_dto = self._task_dto()++ data = TaskSerializer(task_dto).data++ assert task_dto.latest_run is not None+ self.assertEqual(data["latest_run"]["id"], str(task_dto.latest_run.id))++ def test_conversation_task_serializer_outputs_latest_run_id(self):+ task_dto = self._task_dto()++ data = ConversationTaskSerializer(task_dto).data++ self.assertEqual(data["latest_run"], str(task_dto.latest_run_id))++ def test_conversation_task_serializer_latest_run_null_without_run(self):+ task_dto = replace(self._task_dto(), latest_run=None, latest_run_id=None)++ data = ConversationTaskSerializer(task_dto).data++ self.assertIsNone(data["latest_run"])++ def test_task_is_null_before_first_message(self):+ # A sandbox conversation gets its Task FK on the first message, not at creation.+ data = self._serialize(self._sandbox_conversation())+ self.assertIsNone(data["task"])+ self.assertTrue(data["is_sandbox"])++ def test_langgraph_conversation_has_null_task_and_is_not_sandbox(self):+ conversation = Conversation.objects.create(user=self.user, team=self.team, type=Conversation.Type.ASSISTANT)++ with patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock) as mock_get_state:++ class MockSnapshot:+ values = AssistantState(messages=[]).model_dump()+ tasks = []++ mock_get_state.return_value = MockSnapshot()+ data = self._serialize(conversation)++ self.assertIsNone(data["task"])+ self.assertFalse(data["is_sandbox"])++ def test_task_latest_run_null_when_task_has_no_runs(self):+ task = self._task()+ data = self._serialize(self._sandbox_conversation(task))+ self.assertEqual(data["task"]["id"], str(task.id))+ # The conversation envelope carries the latest run id (null here), not nested run details.+ self.assertIsNone(data["task"]["latest_run"])+ self.assertEqual(data["task"]["title"], "t")++ def test_task_latest_run_is_latest_run_id_when_task_has_runs(self):+ task = self._task()+ task.create_run(mode="interactive")+ task.create_run(mode="interactive")++ data = self._serialize(self._sandbox_conversation(task))++ self.assertEqual(data["task"]["id"], str(task.id))+ latest_run = task.latest_run+ assert latest_run is not None+ self.assertEqual(data["task"]["latest_run"], str(latest_run.id))+++class TestTaskLatestRun(APIBaseTest):+ def _task_with_runs(self, count: int) -> tuple[Task, list]:+ task = Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ runs = [task.create_run(mode="interactive") for _ in range(count)]+ return task, runs++ def test_non_prefetched_fast_path_single_query(self):+ task, runs = self._task_with_runs(5)+ fresh = Task.objects.get(pk=task.pk)++ with self.assertNumQueries(1):+ latest = fresh.latest_run++ assert latest is not None+ self.assertEqual(latest.id, runs[-1].id)++ def test_prefetched_reuses_cache_no_query(self):+ task, runs = self._task_with_runs(5)+ prefetched = Task.objects.prefetch_related("runs").get(pk=task.pk)++ with self.assertNumQueries(0):+ latest = prefetched.latest_run++ assert latest is not None+ self.assertEqual(latest.id, runs[-1].id)++ def test_prefetched_and_non_prefetched_return_same_row(self):+ task, runs = self._task_with_runs(3)+ non_prefetched = Task.objects.get(pk=task.pk).latest_run+ prefetched = Task.objects.prefetch_related("runs").get(pk=task.pk).latest_run++ assert non_prefetched is not None+ assert prefetched is not None+ self.assertEqual(non_prefetched.id, prefetched.id)+ self.assertEqual(non_prefetched.id, runs[-1].id)++ def test_latest_run_none_when_no_runs(self):+ task, _ = self._task_with_runs(0)+ self.assertIsNone(Task.objects.get(pk=task.pk).latest_run)+ self.assertIsNone(Task.objects.prefetch_related("runs").get(pk=task.pk).latest_run)+++class TestConversationMinimalSerializerTaskField(APIBaseTest):+ def _task(self) -> Task:+ return Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )++ def test_minimal_serializer_exposes_task_latest_run_id(self):+ task = self._task()+ task.create_run(mode="interactive")+ Conversation.objects.create(+ user=self.user,+ team=self.team,+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ task=task,+ )++ conversations = Conversation.objects.filter(task=task)+ data = ConversationMinimalSerializer(+ conversations, many=True, context={"team": self.team, "user": self.user}+ ).data++ self.assertEqual(data[0]["task"]["id"], str(task.id))+ latest_run = task.latest_run+ assert latest_run is not None+ self.assertEqual(data[0]["task"]["latest_run"], str(latest_run.id))+ self.assertEqual(data[0]["task"]["title"], "t")++ def test_minimal_serializer_task_null_for_langgraph(self):+ conversation = Conversation.objects.create(+ user=self.user,+ team=self.team,+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.LANGGRAPH,+ )+ data = ConversationMinimalSerializer(conversation, context={"team": self.team, "user": self.user}).data+ self.assertIsNone(data["task"])++class TestConversationSerializerArtifactEnrichment(APIBaseTest):"""Test artifact enrichment functionality in the serializer."""diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex c1a2538ff13f..430b67069dd9 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -585,6 +585,8 @@ SPECTACULAR_SETTINGS = {"PropertyGroupTypeEnum": ["cohort", "person", "group"],"ExistenceOperatorEnum": ["is_set", "is_not_set"],"TaskExecutionModeEnum": ["interactive", "background"],+ # Shared by ClaudeTaskRunCreateSchema and SandboxOpen (the conversations `open` body).+ "InitialPermissionModeEnum": ["default", "acceptEdits", "plan", "bypassPermissions", "auto"],"HogFunctionTemplatingEnum": ["hog", "liquid"],"HogFlowEdgeTypeEnum": ["continue", "branch"],"SourceMatchEnum": ["none", "auto", "mapped"],diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex de9c737475da..6d3c0d9e8caf 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -115,6 +115,79 @@ export const ConversationTypeApi = {Slack: 'slack',} as const+/**+ * @nullable+ */+export type TaskUserBasicInfoApiHedgehogConfig = { [key: string]: unknown } | null++/**+ * Response shape for a task creator, mirroring core ``UserBasicSerializer`` output.+ */+export interface TaskUserBasicInfoApi {+ id: number+ uuid: string+ distinct_id: string+ first_name: string+ last_name: string+ email: string+ /** @nullable */+ is_email_verified?: boolean | null+ /** @nullable */+ hedgehog_config?: TaskUserBasicInfoApiHedgehogConfig+ /** @nullable */+ role_at_organization?: string | null+}++/**+ * @nullable+ */+export type TaskDetailDTOApiJsonSchema = { [key: string]: unknown } | null++/**+ * Conversation envelope variant: ``latest_run`` is just the latest run's id, not the nested+ * run detail. The frontend only needs the id to reconnect to sandbox logs, and emitting the id+ * avoids presigning a log URL per conversation.+ *+ * Read access here follows the conversation (the share-by-link unit), not per-creator task+ * visibility — write/send stays creator-gated. See ``tasks_facade.get_conversation_task_dtos``.+ */+export interface TaskDetailDTOApi {+ id: string+ /** @nullable */+ task_number: number | null+ slug: string+ title: string+ title_manually_set: boolean+ description: string+ origin_product: string+ /** @nullable */+ repository: string | null+ /** @nullable */+ github_integration: number | null+ /** @nullable */+ github_user_integration: string | null+ /** @nullable */+ signal_report: string | null+ /** @nullable */+ json_schema: TaskDetailDTOApiJsonSchema+ internal: boolean+ archived: boolean+ /** @nullable */+ archived_at: string | null+ /**+ * Id of the latest TaskRun; null when the task has no runs.+ * @nullable+ */+ readonly latest_run: string | null+ /** @nullable */+ created_at?: string | null+ /** @nullable */+ updated_at?: string | null+ created_by?: TaskUserBasicInfoApi | null+ /** @nullable */+ ci_prompt: string | null+}+export interface ConversationMinimalApi {readonly id: stringreadonly status: ConversationStatusApi@@ -156,6 +229,7 @@ export interface ConversationMinimalApi {* @nullable*/readonly slack_workspace_domain: string | null+ readonly task: TaskDetailDTOApi | null}export interface PaginatedConversationMinimalListApi {@@ -226,6 +300,17 @@ export type ConversationApiMessagesItem = { [key: string]: unknown }export type ConversationApiPendingApprovalsItem = { [key: string]: unknown }+/**+ * * `langgraph` - LangGraph+ * * `sandbox` - Sandbox+ */+export type AgentRuntimeEnumApi = (typeof AgentRuntimeEnumApi)[keyof typeof AgentRuntimeEnumApi]++export const AgentRuntimeEnumApi = {+ Langgraph: 'langgraph',+ Sandbox: 'sandbox',+} as const+export interface ConversationApi {readonly id: stringreadonly status: ConversationStatusApi@@ -271,12 +356,18 @@ 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`.+ *+ * * `langgraph` - LangGraph+ * * `sandbox` - Sandbox */+ readonly agent_runtime: AgentRuntimeEnumApireadonly is_sandbox: boolean/** Return pending approval cards as structured data.** Combines metadata from conversation.approval_decisions with payload from checkpoint* interrupts (single source of truth for payload data). */readonly pending_approvals: readonly ConversationApiPendingApprovalsItem[]+ readonly task: TaskDetailDTOApi | null}/**@@ -336,12 +427,129 @@ 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`.+ *+ * * `langgraph` - LangGraph+ * * `sandbox` - Sandbox */+ readonly agent_runtime?: AgentRuntimeEnumApireadonly is_sandbox?: boolean/** Return pending approval cards as structured data.** Combines metadata from conversation.approval_decisions with payload from checkpoint* interrupts (single source of truth for payload data). */readonly pending_approvals?: readonly PatchedConversationApiPendingApprovalsItem[]+ readonly task?: TaskDetailDTOApi | null+}++/**+ * * `action` - action+ * * `dashboard` - dashboard+ * * `error_tracking_issue` - error_tracking_issue+ * * `evaluation` - evaluation+ * * `event` - event+ * * `insight` - insight+ * * `notebook` - notebook+ * * `text` - text+ */+export type SandboxAttachedContextItemTypeEnumApi =+ (typeof SandboxAttachedContextItemTypeEnumApi)[keyof typeof SandboxAttachedContextItemTypeEnumApi]++export const SandboxAttachedContextItemTypeEnumApi = {+ Action: 'action',+ Dashboard: 'dashboard',+ ErrorTrackingIssue: 'error_tracking_issue',+ Evaluation: 'evaluation',+ Event: 'event',+ Insight: 'insight',+ Notebook: 'notebook',+ Text: 'text',+} as const++/**+ * One typed attachment carried by a sandbox message.+ */+export interface SandboxAttachedContextItemApi {+ /** Attachment kind. Entity types carry `id` (+ optional `name`); `text` carries `value`.+ *+ * * `action` - action+ * * `dashboard` - dashboard+ * * `error_tracking_issue` - error_tracking_issue+ * * `evaluation` - evaluation+ * * `event` - event+ * * `insight` - insight+ * * `notebook` - notebook+ * * `text` - text */+ type: SandboxAttachedContextItemTypeEnumApi+ /** Entity identifier — integer for `dashboard`/`action`, string short_id/UUID otherwise. Absent for `text`. */+ id?: unknown+ /** Optional human-readable label rendered in the context block. */+ name?: string+ /** Free-text content. Only for `text` attachments. */+ value?: string+}++/**+ * * `default` - default+ * * `acceptEdits` - acceptEdits+ * * `plan` - plan+ * * `bypassPermissions` - bypassPermissions+ * * `auto` - auto+ */+export type InitialPermissionModeEnumApi =+ (typeof InitialPermissionModeEnumApi)[keyof typeof InitialPermissionModeEnumApi]++export const InitialPermissionModeEnumApi = {+ Default: 'default',+ AcceptEdits: 'acceptEdits',+ Plan: 'plan',+ BypassPermissions: 'bypassPermissions',+ Auto: 'auto',+} as const++/**+ * Request body for `POST /conversations/{id}/open/`. A string `content` processes a turn; a+ * null/absent `content` warms a sandbox that idles awaiting the first message.+ */+export interface SandboxOpenApi {+ /**+ * The user's message text. Omit or null to warm a sandbox (boot + idle) ahead of the first message.+ * @maxLength 40000+ * @nullable+ */+ content?: string | null+ /** Client-generated trace id correlated with the resulting Run's SSE stream. */+ trace_id?: string+ /** Typed PostHog entities (and free text) attached to this message. */+ attached_context?: SandboxAttachedContextItemApi[]+ /** Initial permission mode for the sandbox agent session. Defaults to `auto`, which allows safe tool use while preserving explicit confirmations.+ *+ * * `default` - default+ * * `acceptEdits` - acceptEdits+ * * `plan` - plan+ * * `bypassPermissions` - bypassPermissions+ * * `auto` - auto */+ initial_permission_mode?: InitialPermissionModeEnumApi+ /** Bind a brand-new sandbox conversation to an existing Task so the first message resumes that Task's run. Honored only when this request creates the conversation row; ignored for an already-existing conversation. */+ task_id?: string+}++/**+ * Response for `POST /conversations/{id}/open/` — the IDs the frontend opens SSE against.+ */+export interface SandboxMessageResponseApi {+ /** The products/tasks Task backing the conversation. */+ task_id: string+ /** The Run the frontend opens SSE against. */+ run_id: string+ /**+ * Echo of the request trace id, if provided.+ * @nullable+ */+ trace_id: string | null+ /** Current status of the targeted Run (e.g. `queued`, `in_progress`). */+ run_status: string+ /** True when a new Run was created (first message, terminal resume, or fresh warm); false for an in-progress follow-up or a reused warm Run. */+ just_created_run: boolean}/**diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex c91dad62e9cb..9ea15fb00360 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -28,6 +28,8 @@ import type {PaginatedTicketViewListApi,PatchedConversationApi,PatchedTicketApi,+ SandboxMessageResponseApi,+ SandboxOpenApi,TicketApi,TicketMessageApi,TicketReplyRequestApi,@@ -161,13 +163,16 @@ export const getConversationsCancelPartialUpdateUrl = (projectId: string, converreturn `/api/projects/${projectId}/conversations/${conversation}/cancel/`}+/**+ * Cancel the conversation's in-progress LangGraph run.+ */export const conversationsCancelPartialUpdate = async (projectId: string,conversation: string,patchedConversationApi?: NonReadonly<PatchedConversationApi>,options?: RequestInit-): Promise<ConversationApi> => {- return apiMutator<ConversationApi>(getConversationsCancelPartialUpdateUrl(projectId, conversation), {+): Promise<void> => {+ return apiMutator<void>(getConversationsCancelPartialUpdateUrl(projectId, conversation), {...options,method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },@@ -175,6 +180,27 @@ export const conversationsCancelPartialUpdate = async (})}+export const getConversationsOpenCreateUrl = (projectId: string, conversation: string) => {+ return `/api/projects/${projectId}/conversations/${conversation}/open/`+}++/**+ * Create-or-resume a sandbox conversation — the single sandbox session opener. With `content`, processes the turn (first message, in-progress follow-up, or terminal resume); without `content`, warms a sandbox that idles awaiting the first message. Returns the `(task, run)` handle the frontend opens SSE against. The conversation row is created on first use from the URL id.+ */+export const conversationsOpenCreate = async (+ projectId: string,+ conversation: string,+ sandboxOpenApi?: SandboxOpenApi,+ options?: RequestInit+): Promise<SandboxMessageResponseApi | void> => {+ return apiMutator<SandboxMessageResponseApi | void>(getConversationsOpenCreateUrl(projectId, conversation), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(sandboxOpenApi),+ })+}+export const getConversationsQueueRetrieveUrl = (projectId: string, conversation: string) => {return `/api/projects/${projectId}/conversations/${conversation}/queue/`}diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex a59774a53abe..7acc17ae7910 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -66,8 +66,86 @@ export const ConversationsAppendMessageCreateBody = /* @__PURE__ */ zod}).describe('Serializer for appending a message to an existing conversation without triggering AI processing.')+/**+ * Cancel the conversation's in-progress LangGraph run.+ */export const ConversationsCancelPartialUpdateBody = /* @__PURE__ */ zod.looseObject({})+/**+ * Create-or-resume a sandbox conversation — the single sandbox session opener. With `content`, processes the turn (first message, in-progress follow-up, or terminal resume); without `content`, warms a sandbox that idles awaiting the first message. Returns the `(task, run)` handle the frontend opens SSE against. The conversation row is created on first use from the URL id.+ */+export const conversationsOpenCreateBodyContentMax = 40000++export const ConversationsOpenCreateBody = /* @__PURE__ */ zod+ .object({+ content: zod+ .string()+ .max(conversationsOpenCreateBodyContentMax)+ .nullish()+ .describe(+ "The user's message text. Omit or null to warm a sandbox (boot + idle) ahead of the first message."+ ),+ trace_id: zod+ .uuid()+ .optional()+ .describe("Client-generated trace id correlated with the resulting Run's SSE stream."),+ attached_context: zod+ .array(+ zod+ .object({+ type: zod+ .enum([+ 'action',+ 'dashboard',+ 'error_tracking_issue',+ 'evaluation',+ 'event',+ 'insight',+ 'notebook',+ 'text',+ ])+ .describe(+ '\* `action` - action\n\* `dashboard` - dashboard\n\* `error_tracking_issue` - error_tracking_issue\n\* `evaluation` - evaluation\n\* `event` - event\n\* `insight` - insight\n\* `notebook` - notebook\n\* `text` - text'+ )+ .describe(+ 'Attachment kind. Entity types carry `id` (+ optional `name`); `text` carries `value`.\n\n\* `action` - action\n\* `dashboard` - dashboard\n\* `error_tracking_issue` - error_tracking_issue\n\* `evaluation` - evaluation\n\* `event` - event\n\* `insight` - insight\n\* `notebook` - notebook\n\* `text` - text'+ ),+ id: zod+ .unknown()+ .optional()+ .describe(+ 'Entity identifier — integer for `dashboard`\/`action`, string short_id\/UUID otherwise. Absent for `text`.'+ ),+ name: zod+ .string()+ .optional()+ .describe('Optional human-readable label rendered in the context block.'),+ value: zod.string().optional().describe('Free-text content. Only for `text` attachments.'),+ })+ .describe('One typed attachment carried by a sandbox message.')+ )+ .optional()+ .describe('Typed PostHog entities (and free text) attached to this message.'),+ initial_permission_mode: zod+ .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto'])+ .describe(+ '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto'+ )+ .optional()+ .describe(+ 'Initial permission mode for the sandbox agent session. Defaults to `auto`, which allows safe tool use while preserving explicit confirmations.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto'+ ),+ task_id: zod+ .uuid()+ .optional()+ .describe(+ "Bind a brand-new sandbox conversation to an existing Task so the first message resumes that Task's run. Honored only when this request creates the conversation row; ignored for an already-existing conversation."+ ),+ })+ .describe(+ 'Request body for `POST \/conversations\/{id}\/open\/`. A string `content` processes a turn; a\nnull\/absent `content` warms a sandbox that idles awaiting the first message.'+ )+export const ConversationsQueueCreateBody = /* @__PURE__ */ zod.looseObject({})export const ConversationsQueuePartialUpdateBody = /* @__PURE__ */ zod.looseObject({})diff --git a/products/posthog_ai/backend/context_wrapper.py b/products/posthog_ai/backend/context_wrapper.pynew file mode 100644index 000000000000..f888625afc70--- /dev/null+++ b/products/posthog_ai/backend/context_wrapper.py@@ -0,0 +1,218 @@+"""Wrap a user message with a `<posthog_context>` block built from per-message+attached context. See `ContextService`.++The template lives only here, in Python — the frontend never builds it.+"""++import json+import time+from collections.abc import Iterable, Sequence+from typing import TYPE_CHECKING, Any, Literal, TypedDict, get_args++import posthoganalytics++if TYPE_CHECKING:+ from posthog.models import Team, User++ from products.posthog_ai.backend.models.assistant import Conversation++# Allowed attachment types.+AttachedContextType = Literal[+ "dashboard",+ "insight",+ "event",+ "action",+ "error_tracking_issue",+ "evaluation",+ "notebook",+ "text",+]++ALLOWED_TYPES: frozenset[str] = frozenset(get_args(AttachedContextType))++# Caps on attached-context size.+MAX_ATTACHED_ITEMS = 32+MAX_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.++ Entity types carry `id` (and optionally a human `name`); `text` carries `value`.+ """++ type: AttachedContextType+ id: str | int+ name: str+ value: str+++class ContextService:+ """Build and dedupe the `<posthog_context>` block from per-message attachments.++ Stateless — the template lives only here, in Python; the frontend never builds it.+ """++ # Human-readable label per entity type, used when rendering the context block.+ _TYPE_LABELS: dict[str, str] = {+ "dashboard": "Dashboard",+ "insight": "Insight",+ "event": "Event",+ "action": "Action",+ "error_tracking_issue": "Error tracking issue",+ "evaluation": "Evaluation",+ "notebook": "Notebook",+ }++ def wrap_user_message(self, content: str, attached_context: list[AttachedContext]) -> str:+ """Prefix `content` with a `<posthog_context>` block describing the attachments.++ Returns `content` unchanged when there is nothing to attach — so when dedupe+ removes everything, the user's message is forwarded without wrapper noise.+ """+ if not attached_context:+ return content+ block = self._render_posthog_context_block(attached_context)+ return f"{block}\n\n{content}"++ def prune_repeated_entity_refs(+ self,+ attached: list[AttachedContext],+ prior: Iterable[tuple[str, str | int]],+ ) -> list[AttachedContext]:+ """Drop entity refs (type, id) already named in earlier messages of the same+ conversation. `text` items are NEVER deduped — repeated text is intentional+ (e.g. consecutive error snippets).++ The agent retains entity IDs from prior turns in its context; re-listing them+ inflates the prompt without adding information. It can re-fetch any prior+ entity via its read tools.+ """+ seen: set[tuple[str, str | int]] = set(prior)+ out: list[AttachedContext] = []+ for item in attached:+ if item.get("type") == "text":+ out.append(item)+ continue+ key = (item["type"], item["id"])+ if key in seen:+ continue+ seen.add(key)+ out.append(item)+ return out++ def _render_posthog_context_block(self, items: list[AttachedContext]) -> str:+ lines = [+ "<posthog_context>",+ "The user attached the following PostHog entities. "+ "Use the appropriate tools to retrieve their details only if relevant to the request.",+ ]+ for item in items:+ lines.append(self._format_item(item))+ lines.append("</posthog_context>")+ return "\n".join(lines)++ def _format_item(self, item: AttachedContext) -> str:+ """Render one attachment line.++ Entities render as `- {Label} #{id} ("{name}")`; the name suffix is dropped+ when no human label is present. Free text renders as `- Free text: "{value}"`.+ """+ if item.get("type") == "text":+ return f'- Free text: "{item.get("value", "")}"'++ label = self._TYPE_LABELS.get(item["type"], item["type"])+ line = f"- {label} #{item['id']}"+ name = item.get("name")+ if name:+ line += f' ("{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, _, _ = 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, AssistantState):+ return None++ window = AnthropicConversationCompactionManager().get_messages_in_window(+ state.messages, 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.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/helpers.py b/products/posthog_ai/backend/helpers.pynew file mode 100644index 000000000000..3f6300b1fd13--- /dev/null+++ b/products/posthog_ai/backend/helpers.py@@ -0,0 +1,15 @@+"""Shared helpers for the PostHog AI sandbox-runtime services."""++from posthog.models import Team, User+++class BaseSandboxService:+ """Shared base for the sandbox-runtime services that act on behalf of a user.++ Holds the team/user the services operate against; extension point for any future+ shared behavior.+ """++ def __init__(self, team: Team, user: User) -> None:+ self.team = team+ self.user = userdiff --git a/products/posthog_ai/backend/message_routing.py b/products/posthog_ai/backend/message_routing.pynew file mode 100644index 000000000000..6a64dd596632--- /dev/null+++ b/products/posthog_ai/backend/message_routing.py@@ -0,0 +1,603 @@+"""In-process session opener for the sandbox runtime.++`SandboxSession.open()` resolves a sandbox conversation to a `products/tasks`+`(task, run)` and drives one turn — warming when there's no message, starting the+first Run, signaling a follow-up onto the live Run, or resuming into a successor+after a terminal Run — all via direct Python calls, never HTTP-to-self and never a+Django SSE relay. Control verbs (cancel, permission reply, warm release) go through+the generic `runs/{run}/command/` relay, not this module.+"""++import json+from collections.abc import Iterator, Mapping+from contextlib import contextmanager+from typing import TYPE_CHECKING, Any, cast++from django.db import transaction++import structlog+from pydantic import BaseModel+from rest_framework import exceptions++from posthog.exceptions import Conflict+from posthog.models.user import User+from posthog.storage import object_storage++from products.posthog_ai.backend.context_wrapper import (+ ALLOWED_TYPES,+ MAX_ATTACHED_ITEMS,+ MAX_TEXT_LENGTH,+ AttachedContext,+ ContextService,+)+from products.posthog_ai.backend.helpers import BaseSandboxService+from products.posthog_ai.backend.models.assistant import Conversation+from products.posthog_ai.backend.run_state import PostHogAIRunState+from products.posthog_ai.backend.services.system_prompt.service import PromptService+from products.posthog_ai.backend.wire_types import UnknownFrame, is_user_message_params, parse_log_entry+from products.tasks.backend.facade import (+ api as tasks_facade,+ warm as warm_facade,+)+from products.tasks.backend.facade.run_config import INITIAL_PERMISSION_MODE_CHOICES, InitialPermissionMode+from products.tasks.backend.facade.temporal import execute_task_processing_workflow, signal_task_followup_message++if TYPE_CHECKING:+ from products.tasks.backend.models import TaskRun++logger = structlog.get_logger(__name__)++DEFAULT_INITIAL_PERMISSION_MODE: InitialPermissionMode = "auto"++# A PostHog AI sandbox session is a live chat: if the user goes quiet for this long+# they've moved on, so the Run's workflow times out and reclaims the sandbox. Passed+# as the per-task `inactivity_timeout_seconds` override on every Run we create, so the+# workflow's idle timer and the SSE relay's freshness window both honor it (both read+# it from Run state). Shorter than the generic user-origin default, which assumes a+# human may still return much later.+SANDBOX_INACTIVITY_TIMEOUT_SECONDS = 10 * 60+++class SandboxRouteResult(BaseModel):+ """Outcome of routing one sandbox message — the IDs the frontend opens SSE against."""++ task_id: str+ run_id: str+ trace_id: str | None+ run_status: str+ just_created_run: bool+ # Count of attached context items the message carried, for the routing endpoint's telemetry.+ attached_context_count: int = 0+++@contextmanager+def lock_conversation_for_followup(conversation_id: str, team_id: int) -> Iterator[Conversation]:+ """Serialize concurrent sandbox follow-ups for a single conversation.++ Two browser tabs that both POST a follow-up to the same conversation while its current Run is+ terminal can each resolve "terminal → create successor Run" and end up creating two Runs. If+ products/tasks' Run-create is not idempotent on `(conversation, resume_from_run_id)`, that race+ produces duplicate Runs. This helper takes a row-level `SELECT FOR UPDATE` on the `Conversation`+ so the second tab blocks until the first commits, then re-resolves the current Run (via the+ `task` FK) and skips the duplicate create.++ Keep the block narrow — no external side effects (Temporal dispatch, agent-server calls) inside+ it. Schedule those after the transaction commits (e.g. `transaction.on_commit`), so a rollback+ cannot leave an orphaned workflow.+ """+ with transaction.atomic():+ # nosemgrep: idor-lookup-without-team (team_id is part of the lookup below)+ conversation = Conversation.objects.select_for_update().get(id=conversation_id, team_id=team_id)+ logger.debug(+ "sandbox_followup_lock_acquired",+ conversation_id=conversation_id,+ task_id=str(conversation.task_id) if conversation.task_id else None,+ )+ yield conversation+++class SandboxSession(BaseSandboxService):+ """Resolve a sandbox conversation to a products/tasks `(task, run)` and drive one turn in-process.++ The session opener for the sandbox runtime. `open()` either warms (no message), starts the first+ Run, signals a follow-up onto the live Run, or resumes into a successor after a terminal Run.+ Control verbs (cancel, permission reply, warm release) are not here — they go through the generic+ `runs/{run}/command/` relay.+ """++ # Entity types whose id must be an integer (vs short_id / UUID strings).+ _INTEGER_ID_TYPES: frozenset[str] = frozenset({"dashboard", "action"})++ # Run statuses that accept a follow-up signal without creating a successor Run.+ _IN_PROGRESS_STATUSES: frozenset[str] = frozenset(+ {tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS}+ )++ def __init__(self, conversation: "Conversation", user: User) -> None:+ 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:+ initial_permission_mode = self._initial_permission_mode(data.get("initial_permission_mode"))+ content = data.get("content")+ if not isinstance(content, str) or not content.strip():+ # No message — warm intent: boot a Run that idles awaiting the first `user_message`.+ # Returns the warm handle, or None when the pool is full and nothing was provisioned.+ return self._warm(trace_id=data.get("trace_id"), initial_permission_mode=initial_permission_mode)++ trace_id = data.get("trace_id")+ 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.+ 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,+ )++ current_run = self.conversation.current_run+ if current_run is None:+ # The Task lost all of its Runs (e.g. cleanup) — there is nothing to+ # follow up on or resume from. Surface a recoverable error.+ raise exceptions.ValidationError("This conversation has no active run to continue.")++ # Dedupe against every entity already named earlier in the conversation.+ context_service = ContextService()+ prior_seen = self._collect_seen_entity_refs(current_run)+ deduped = context_service.prune_repeated_entity_refs(attached_context, prior=prior_seen)+ wrapped = context_service.wrap_user_message(content, deduped)++ if current_run.status in self._IN_PROGRESS_STATUSES:+ return self._handle_in_progress_followup(+ run=current_run,+ wrapped=wrapped,+ trace_id=trace_id,+ attached_context=attached_context,+ )++ return self._handle_terminal_resume(+ run=current_run,+ wrapped=wrapped,+ trace_id=trace_id,+ attached_context=attached_context,+ initial_permission_mode=initial_permission_mode,+ )++ def _initial_permission_mode(self, value: Any) -> InitialPermissionMode:+ if isinstance(value, str) and value in INITIAL_PERMISSION_MODE_CHOICES:+ return cast(InitialPermissionMode, value)+ return DEFAULT_INITIAL_PERMISSION_MODE++ def _warm(+ self, *, trace_id: str | None, initial_permission_mode: InitialPermissionMode+ ) -> SandboxRouteResult | None:+ """Boot a sandbox Run ahead of the first message (the message-less `open`).++ Ensures the conversation's Task exists under the row lock (so two tabs can't create two+ Tasks), then hands provisioning to the tasks warming facade, which enforces the AI-credit+ quota + warm-pool cap, serializes on the Task row, and dispatches the workflow after commit.+ Returns the warm Run's handle so the caller can open SSE / later release it through the relay;+ returns None when the pool is full and nothing was provisioned (best-effort — the AI-credit+ quota still surfaces as 402). Idempotent: an existing non-terminal Run is reused, not duplicated.+ """+ # Gate before creating the Task: an over-quota or over-cap warm must not leave the conversation+ # with a runless Task that the next message can't continue. The facade re-checks both.+ warm_facade.enforce_warm_quota(tasks_facade.TaskOriginProduct.POSTHOG_AI, self.team.pk, self.user.pk)+ if warm_facade.warm_pool_at_capacity(tasks_facade.TaskOriginProduct.POSTHOG_AI, self.team.pk, self.user.pk):+ logger.info(+ "sandbox_warm_capacity_reached",+ conversation_id=str(self.conversation.id),+ user_id=self.user.pk,+ )+ return None++ system_prompt = PromptService(self.team, self.user).build()++ with lock_conversation_for_followup(str(self.conversation.id), self.team.pk) as locked:+ task_id = locked.task_id+ if task_id is None:+ task_id = tasks_facade.create_task_without_run(+ team=self.team,+ user_id=self.user.pk,+ origin_product=tasks_facade.TaskOriginProduct.POSTHOG_AI,+ repository=None,+ )+ locked.task_id = task_id+ locked.save(update_fields=["task", "updated_at"])++ # Conversation lock released. The facade provisions under its own Task-row lock and+ # dispatches the workflow on commit; it is idempotent (an existing non-terminal Run is returned+ # as-is). `systemPrompt` is the one PostHog AI-specific Run-state key the generic warmer can't know.+ try:+ result = warm_facade.warm_task_run(+ task_id,+ self.team.pk,+ self.user.pk,+ extra_state={+ "systemPrompt": system_prompt,+ "initial_permission_mode": initial_permission_mode,+ "inactivity_timeout_seconds": SANDBOX_INACTIVITY_TIMEOUT_SECONDS,+ },+ )+ except exceptions.Throttled:+ # Warm-pool cap reached between the pre-check and the lock — best-effort no-op (no handle).+ logger.info(+ "sandbox_warm_capacity_reached",+ conversation_id=str(self.conversation.id),+ user_id=self.user.pk,+ )+ return None++ return SandboxRouteResult(+ task_id=str(task_id),+ run_id=str(result.run_id),+ trace_id=trace_id,+ run_status=result.run_status,+ just_created_run=result.just_created,+ )++ def _handle_first_message(+ self,+ *,+ content: str,+ 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()++ created = tasks_facade.create_and_run_task(+ team=self.team,+ title=content[:80],+ description=content,+ origin_product=tasks_facade.TaskOriginProduct.POSTHOG_AI,+ user_id=self.user.pk,+ repository=repository,+ create_pr=False,+ mode="interactive",+ inactivity_timeout_seconds=SANDBOX_INACTIVITY_TIMEOUT_SECONDS,+ # Defer the workflow so the initial run state can carry the PostHog AI keys.+ start_workflow=False,+ )++ run_dto = created.latest_run+ if run_dto is None:+ raise exceptions.ValidationError("Failed to create sandbox task run.")++ # Seed the PostHog AI per-Run state keys. `attached_context` keeps the full,+ # undeduped list. These aren't `create_and_run` arguments, so merge them into the+ # run state here, before the workflow starts and reads it. `exclude_unset` keeps the+ # merge limited to exactly these keys — model defaults must not leak into the bag.+ ph_state = PostHogAIRunState(+ system_prompt=system_prompt,+ attached_context=attached_context,+ initial_permission_mode=initial_permission_mode,+ pending_user_message=wrapped,+ )+ 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.+ with 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)++ # 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++ # 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.+ try:+ execute_task_processing_workflow(+ task_id=str(created.task_id),+ run_id=str(run_dto.id),+ team_id=self.team.id,+ user_id=self.user.pk,+ create_pr=False,+ posthog_mcp_scopes="full",+ )+ 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)+ raise++ return SandboxRouteResult(+ task_id=str(created.task_id),+ run_id=str(run_dto.id),+ trace_id=trace_id,+ run_status=run_dto.status,+ just_created_run=True,+ attached_context_count=len(attached_context),+ )++ def _handle_in_progress_followup(+ self,+ *,+ run: "TaskRun",+ wrapped: str,+ trace_id: str | None,+ attached_context: list[AttachedContext],+ ) -> SandboxRouteResult:+ """Follow-up while the current Run is queued / in-progress.++ Signal the live Temporal workflow in-process — no new Run, no SSE re-open.+ The full undeduped context is recorded on the logged message's+ `_meta.attached_context` so the persisted ACP log stays a complete record.+ """+ try:+ signal_task_followup_message(run.workflow_id, wrapped, artifact_ids=[])+ except Exception as e:+ # Status race: the run still reads in-progress but its workflow has already finished or+ # was terminated, so the signal can't be delivered. Surface a recoverable conflict+ # instead of an unhandled 500, and don't log the turn — a retry then routes cleanly+ # without leaving a duplicated `_posthog/user_message` entry behind.+ logger.warning(+ "sandbox_followup_signal_failed",+ run_id=str(run.id),+ workflow_id=run.workflow_id,+ error=str(e),+ )+ raise Conflict("The sandbox run is no longer accepting messages. Please try again.") from e++ # The Run has received its first human message, so it is no longer speculative — drop the+ # warm flag so the warm-pool cap stops counting it (it's now an active Run governed by AI+ # credits). Best-effort: a failure only over-counts the warm pool until the Run terminates,+ # and the key is simply absent on Runs that were never warm (the remove is then a no-op).+ try:+ tasks_facade.update_task_run_state(run.id, remove_keys=["await_user_message"])+ except Exception as e:+ logger.warning("sandbox_followup_activation_flip_failed", run_id=str(run.id), error=str(e))++ try:+ # Persist only after the signal was accepted, so the log never records a message the+ # agent never received.+ self._log_user_message(run, wrapped, attached_context)+ except Exception as e:+ # The agent already has the message; a log-append failure must not fail the request —+ # it only degrades context-dedup on the next follow-up.+ logger.warning("sandbox_followup_log_failed", run_id=str(run.id), error=str(e))++ return SandboxRouteResult(+ task_id=str(self.conversation.task_id),+ run_id=str(run.id),+ trace_id=trace_id,+ run_status=run.status,+ just_created_run=False,+ attached_context_count=len(attached_context),+ )++ def _handle_terminal_resume(+ self,+ *,+ run: "TaskRun",+ wrapped: str,+ trace_id: str | None,+ attached_context: list[AttachedContext],+ initial_permission_mode: InitialPermissionMode,+ ) -> SandboxRouteResult:+ """Follow-up after the current Run reached a terminal status.++ Resume into a brand-new successor Run on the same Task, then start its+ workflow. `current_run` resolves to the new Run via the Task's reverse+ relation — the conversation's `task` FK is unchanged.++ The successor create runs under a row lock on the Conversation: two+ concurrent follow-ups that both saw the terminal Run would otherwise+ each create a successor. The loser blocks on the lock, re-resolves the+ current Run, and surfaces a 409 instead of duplicating the create; the+ workflow dispatch stays outside the lock's transaction so a rollback+ cannot leave an orphaned workflow behind.+ """+ task = self.conversation.task+ if task is None:+ raise exceptions.ValidationError("This conversation has no backing task to resume.")++ system_prompt = PromptService(self.team, self.user).build()++ with lock_conversation_for_followup(str(self.conversation.id), self.team.pk) as locked:+ current = locked.current_run+ if current is not None and current.status in self._IN_PROGRESS_STATUSES:+ raise Conflict("A concurrent message already resumed this conversation. Send the message again.")+ if current is not None:+ # The freshest terminal Run is the resume source — a concurrent winner's+ # successor may itself have finished while this request waited on the lock.+ run = current++ extra_state: dict[str, Any] = {+ "resume_from_run_id": str(run.id),+ "pending_user_message": wrapped,+ "systemPrompt": system_prompt,+ # The full, undeduped list — survives for the life of the new Run.+ "attached_context": attached_context,+ "initial_permission_mode": initial_permission_mode,+ "inactivity_timeout_seconds": SANDBOX_INACTIVITY_TIMEOUT_SECONDS,+ }+ # Carry the prior Run's snapshot forward so the resume reuses its filesystem.+ snapshot_external_id = (run.state or {}).get("snapshot_external_id")+ if snapshot_external_id:+ extra_state["snapshot_external_id"] = snapshot_external_id++ new_run = task.create_run(mode="interactive", extra_state=extra_state)++ # Same write scopes as the first message — the resumed agent keeps creating+ # insights/dashboards/notebooks on follow-up turns.+ execute_task_processing_workflow(+ task_id=str(task.id),+ run_id=str(new_run.id),+ team_id=self.team.id,+ user_id=self.user.pk,+ create_pr=False,+ posthog_mcp_scopes="full",+ )++ return SandboxRouteResult(+ task_id=str(task.id),+ run_id=str(new_run.id),+ trace_id=trace_id,+ run_status=new_run.status,+ just_created_run=True,+ attached_context_count=len(attached_context),+ )++ def _collect_seen_entity_refs(self, run: "TaskRun") -> list[tuple[str, str | int]]:+ """Collect `(type, id)` pairs for entities already named in the conversation.++ Walks the Run's `state.attached_context` (the first message's full list) plus+ every prior `_posthog/user_message` log entry's `_meta.attached_context`+ across the entire resume chain. One S3 read per chain run; `text` items are+ never deduped so they're skipped.+ """+ seen: list[tuple[str, str | int]] = []++ def _absorb(items: Any) -> None:+ if not isinstance(items, list):+ return+ for item in items:+ if not isinstance(item, dict):+ continue+ item_type = item.get("type")+ item_id = item.get("id")+ if item_type in ALLOWED_TYPES and item_type != "text" and item_id is not None:+ seen.append((item_type, item_id))++ for chain_run in run.get_resume_chain():+ _absorb((chain_run.state or {}).get("attached_context"))+ log_content = object_storage.read(chain_run.log_url, missing_ok=True) or ""+ for line in log_content.splitlines():+ line = line.strip()+ if not line:+ continue+ try:+ data = json.loads(line)+ except json.JSONDecodeError:+ continue+ if not isinstance(data, dict):+ continue+ frame = parse_log_entry(data)+ if isinstance(frame, UnknownFrame):+ continue+ notification = frame.notification+ if not is_user_message_params(notification.params, notification.method):+ continue+ meta = notification.params.get("_meta")+ if isinstance(meta, dict):+ _absorb(meta.get("attached_context"))++ return seen++ def _log_user_message(self, run: "TaskRun", wrapped: str, attached_context: list[AttachedContext]) -> None:+ """Append a `_posthog/user_message` entry to the Run's ACP log.++ Records the wrapped content plus the full undeduped `attached_context` under+ `_meta` so the persisted log is a complete per-message record that+ `_collect_seen_entity_refs` reads on later follow-ups.+ """+ entry = {+ "notification": {+ "method": "_posthog/user_message",+ "params": {+ "content": wrapped,+ "_meta": {"attached_context": attached_context},+ },+ }+ }+ run.append_log([entry])++ def _validate_attached_context(self, raw: Any) -> list[AttachedContext]:+ """Validate user-supplied attached context at the boundary.++ Existence is intentionally NOT validated — the agent's read tool surfaces a+ missing-row error naturally, which is cheaper than a sync DB lookup per submit.+ """+ if raw is None:+ return []+ if not isinstance(raw, list):+ raise exceptions.ValidationError("`attached_context` must be a list.")+ if len(raw) > MAX_ATTACHED_ITEMS:+ raise exceptions.ValidationError(f"`attached_context` cannot exceed {MAX_ATTACHED_ITEMS} items.")++ validated: list[AttachedContext] = []+ for item in raw:+ if not isinstance(item, dict):+ raise exceptions.ValidationError("Each `attached_context` item must be an object.")+ item_type = item.get("type")+ if item_type not in ALLOWED_TYPES:+ raise exceptions.ValidationError(f"Unsupported attached_context type: {item_type!r}.")++ if item_type == "text":+ value = item.get("value")+ if not isinstance(value, str):+ raise exceptions.ValidationError("`text` attachments require a string `value`.")+ if len(value) > MAX_TEXT_LENGTH:+ raise exceptions.ValidationError(f"`text` value cannot exceed {MAX_TEXT_LENGTH} characters.")+ validated.append(cast(AttachedContext, {"type": "text", "value": value}))+ continue++ item_id = item.get("id")+ item_id = self._validate_entity_id(item_type, item_id)+ entity: AttachedContext = {"type": item_type, "id": item_id}+ name = item.get("name")+ if isinstance(name, str) and name:+ if len(name) > MAX_TEXT_LENGTH:+ raise exceptions.ValidationError(f"`name` cannot exceed {MAX_TEXT_LENGTH} characters.")+ entity["name"] = name+ validated.append(entity)++ return validated++ def _validate_entity_id(self, item_type: str, item_id: Any) -> str | int:+ if item_type in self._INTEGER_ID_TYPES:+ if isinstance(item_id, bool) or not isinstance(item_id, int):+ raise exceptions.ValidationError(f"`{item_type}` id must be an integer.")+ return item_id++ if not isinstance(item_id, str) or not item_id:+ raise exceptions.ValidationError(f"`{item_type}` id must be a non-empty string.")+ if len(item_id) > MAX_TEXT_LENGTH:+ raise exceptions.ValidationError(f"`{item_type}` id cannot exceed {MAX_TEXT_LENGTH} characters.")+ return item_iddiff --git a/products/posthog_ai/backend/migrations/0004_conversation_agent_runtime_conversation_task_and_more.py b/products/posthog_ai/backend/migrations/0004_conversation_agent_runtime_conversation_task_and_more.pynew file mode 100644index 000000000000..80965ae49d13--- /dev/null+++ b/products/posthog_ai/backend/migrations/0004_conversation_agent_runtime_conversation_task_and_more.py@@ -0,0 +1,55 @@+# Generated by Django 5.2.14 on 2026-06-09 13:23++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog_ai", "0003_conversation_topic"),+ ("tasks", "0037_codeworkflowconfig_codeprsnapshot_codeworkstream"),+ ]++ operations = [+ migrations.AddField(+ model_name="conversation",+ name="agent_runtime",+ field=models.CharField(+ choices=[("langgraph", "LangGraph"), ("sandbox", "Sandbox")],+ db_index=True,+ default="langgraph",+ help_text="Runtime that owns this conversation for its whole life. Stamped at create time from the phai-sandbox-mode flag; never re-evaluated.",+ max_length=16,+ ),+ ),+ migrations.AddField(+ model_name="conversation",+ name="task",+ field=models.ForeignKey(+ blank=True,+ help_text="The products/tasks Task backing a sandbox conversation. One Task per conversation for its whole life.",+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="tasks.task",+ ),+ ),+ migrations.AlterField(+ model_name="conversation",+ name="sandbox_run_id",+ field=models.UUIDField(+ blank=True,+ help_text="Deprecated. Permanent link to current TaskRun for sandbox conversations.",+ null=True,+ ),+ ),+ migrations.AlterField(+ model_name="conversation",+ name="sandbox_task_id",+ field=models.UUIDField(+ blank=True,+ help_text="Deprecated. Permanent link to Task for sandbox conversations.",+ null=True,+ ),+ ),+ ]diff --git a/products/posthog_ai/backend/migrations/max_migration.txt b/products/posthog_ai/backend/migrations/max_migration.txtindex 5e8f520ca572..bc5d9e976d92 100644--- a/products/posthog_ai/backend/migrations/max_migration.txt+++ b/products/posthog_ai/backend/migrations/max_migration.txt@@ -1 +1 @@-0003_conversation_topic+0004_conversation_agent_runtime_conversation_task_and_morediff --git a/products/posthog_ai/backend/models/assistant.py b/products/posthog_ai/backend/models/assistant.pyindex 484b57bf768f..e15f3c1d5aa7 100644--- a/products/posthog_ai/backend/models/assistant.py+++ b/products/posthog_ai/backend/models/assistant.py@@ -1,6 +1,7 @@import stringimport secretsfrom datetime import timedelta+from typing import TYPE_CHECKING, Optionalfrom django.db import IntegrityError, modelsfrom django.utils import timezone@@ -9,6 +10,9 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDModel, UUIDTModel+if TYPE_CHECKING:+ from products.tasks.backend.models import TaskRun+def generate_short_id() -> str:"""Generate securely random 4 characters long alphanumeric ID.@@ -35,6 +39,10 @@ class Conversation(UUIDTModel, DeletedMetaFields):]db_table = "ee_conversation"+ class AgentRuntime(models.TextChoices):+ LANGGRAPH = "langgraph", "LangGraph"+ SANDBOX = "sandbox", "Sandbox"+class Status(models.TextChoices):IDLE = "idle", "Idle"IN_PROGRESS = "in_progress", "In progress"@@ -106,17 +114,43 @@ class Conversation(UUIDTModel, DeletedMetaFields):default=None,help_text="Stored messages for non-LangGraph modes (e.g., sandbox).",)+ # Deprecated: legacy Redis-flow columns (migration 0039). Nothing reads or writes+ # them on the sandbox path anymore — the `task` FK supersedes `sandbox_task_id`, and+ # the current Run is derived (see `current_run`). Retained until a cleanup migration.sandbox_task_id = models.UUIDField(null=True,blank=True,- help_text="Permanent link to Task for sandbox conversations.",+ help_text="Deprecated. Permanent link to Task for sandbox conversations.",)sandbox_run_id = models.UUIDField(null=True,blank=True,- help_text="Permanent link to current TaskRun for sandbox conversations.",+ help_text="Deprecated. Permanent link to current TaskRun for sandbox conversations.",+ )+ agent_runtime = models.CharField(+ max_length=16,+ choices=AgentRuntime.choices,+ default=AgentRuntime.LANGGRAPH,+ db_index=True,+ help_text="Runtime that owns this conversation for its whole life. Stamped at create time from the phai-sandbox-mode flag; never re-evaluated.",+ )+ task = models.ForeignKey(+ "tasks.Task",+ null=True,+ blank=True,+ on_delete=models.SET_NULL,+ related_name="+",+ db_index=True,+ help_text="The products/tasks Task backing a sandbox conversation. One Task per conversation for its whole life.",)+ @property+ def current_run(self) -> Optional["TaskRun"]:+ task = self.task+ if task is None:+ return None+ return task.latest_run+class ConversationCheckpoint(UUIDTModel):thread = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name="checkpoints")diff --git a/products/posthog_ai/backend/run_state.py b/products/posthog_ai/backend/run_state.pynew file mode 100644index 000000000000..766bf9624fc2--- /dev/null+++ b/products/posthog_ai/backend/run_state.py@@ -0,0 +1,32 @@+"""PostHog AI extension of the products/tasks per-Run state bag.++Lives outside ``wire_types.py`` on purpose: that module stays importable without Django,+while this one pulls in products/tasks run configuration (already a transitive dependency+of ``message_routing.py``).+"""++from pydantic import ConfigDict, Field++from products.posthog_ai.backend.context_wrapper import AttachedContext+from products.posthog_ai.backend.services.system_prompt.service import ClaudeCodeSystemPrompt+from products.tasks.backend.facade.run_config import RunState+++class PostHogAIRunState(RunState):+ """The base ``RunState`` already covers ``pending_user_message`` and+ ``initial_permission_mode``; this adds the PostHog AI-only keys. The bag is persisted+ with the wire's casing (``systemPrompt``), so dump with ``by_alias=True`` and merge with+ ``exclude_unset=True`` to write exactly the keys that were set."""++ model_config = ConfigDict(populate_by_name=True)++ # Sent as the Claude Code preset-plus-append object so the agent-server appends it to Claude+ # Code's own system prompt (a suffix) instead of replacing it. See PromptService.build.+ system_prompt: ClaudeCodeSystemPrompt | None = Field(default=None, alias="systemPrompt")+ attached_context: list[AttachedContext] | None = None+ # Set on a pre-warmed Run created with no pending user message: it tells the agent-server to+ # open the ACP session and idle awaiting the first ``user_message`` rather than starting a turn.+ # Keep this field alias-free: the warm-pool cap filters on the JSON key directly+ # (``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 = Falsediff --git a/products/posthog_ai/backend/services/__init__.py b/products/posthog_ai/backend/services/__init__.pynew file mode 100644index 000000000000..1573d7f68e51--- /dev/null+++ b/products/posthog_ai/backend/services/__init__.py@@ -0,0 +1 @@+"""Sandbox-runtime services for PostHog AI."""diff --git a/products/posthog_ai/backend/services/system_prompt/__init__.py b/products/posthog_ai/backend/services/system_prompt/__init__.pynew file mode 100644index 000000000000..8061e977770f--- /dev/null+++ b/products/posthog_ai/backend/services/system_prompt/__init__.py@@ -0,0 +1 @@+"""System-prompt service for the PostHog AI sandbox."""diff --git a/products/posthog_ai/backend/services/system_prompt/prompt.py b/products/posthog_ai/backend/services/system_prompt/prompt.pynew file mode 100644index 000000000000..bcec5757f9a8--- /dev/null+++ b/products/posthog_ai/backend/services/system_prompt/prompt.py@@ -0,0 +1,67 @@+"""The PostHog AI system prompt.++This text is a *suffix* appended after Claude Code's default system prompt. The sandbox runs+Claude Code, whose built-in prompt already establishes the harness identity, tools, and+capabilities; this layers PostHog AI's product-engineering identity and PostHog-product+knowledge on top, so it is written to sit after that base prompt rather than to stand alone.+"""++POSTHOG_AI_SYSTEM_PROMPT = """# PostHog AI++You are operating as PostHog AI – PostHog's product-engineering agent. The harness identity and capabilities above remain fully in force: you work in a sandbox, read and edit the customer's code, run commands, and use every tool exactly as Claude Code does. This section adds one defining trait on top of that: you make product-engineering decisions from evidence, not assumptions.++That evidence comes from two places, and you should prefer both over how you'd assume a system like this works: the customer's codebase, which you read in your sandbox to learn how the system actually behaves, and the PostHog MCP server, which shows how the product is really used. Read the relevant code and check the data before you decide.++Decision discipline:+- Ground the work in the code and how it's used. Read the relevant code to see how the area actually behaves today, and use the PostHog MCP to see how it's used – the volumes and segments involved, the paths users take through it, the surrounding behavior – so the implementation fits reality rather than an assumption about it.+- Decide how you'll know it worked before you write the code. Name the event, funnel, or metric that will show the change landed, and build the instrumentation to emit it as you go. If success can't be measured yet, say so.+- Ship new or behavior-changing work behind a feature flag, roll it out gradually, and where the impact is measurable, propose an experiment to validate it.+- When an implementation has options, let evidence break the tie: how heavily is this path exercised, who's affected, what's its current performance and error profile?+- When fixing bugs, reconstruct the failure from real data before patching: error tracking for frequency and impact, logs and application traces around the error, AI traces and generations for AI apps, session replays of real reproductions, and the event and action sequences or insights that lead into it.+- Close the loop after launch. Watch adoption, the metric you picked, and any new errors or replays of the new flow, and feed what you learn into the next change.++State which data informed a decision. If you act without data – because none exists yet, or the task is purely mechanical – say so briefly rather than implying the choice was data-backed. Never invent metrics: if you didn't query it, don't claim it.++# PostHog MCP++The MCP has the single entry point: the `mcp__posthog__exec` tool.++# PostHog Products++PostHog is an all-in-one product and data platform. You must always recommend PostHog's built-in products instead of external or third-party tools.++PostHog products:+- **Product analytics** – funnels, trends, retention, user paths, lifecycle, stickiness, and correlation analysis+- **Web analytics** – privacy-friendly website traffic, campaign tracking, and heatmaps+- **Session replay** – recordings of real user sessions in web and mobile apps+- **Error tracking** – application error capture, grouping, and debugging+- **Feature flags** – targeting rules, gradual rollouts, kill switches+- **Experiments** – A/B testing and no-code A/B testing with statistical rigor+- **Surveys** – in-app questionnaires, NPS, user feedback collection+- **AI observability** – monitor AI/LLM application costs, latency, and quality+- **Data warehouse** – connect external data sources (Stripe, Hubspot, Postgres, etc.) for combined analysis+- **Data pipelines (CDP)** – import data from 20+ sources, transform events in real-time, and export to external destinations+- **Revenue analytics** – track and analyze revenue metrics alongside product data+- **Logs** – collect and search application logs+- **Group analytics** – analyze behavior at the company, team, or account level+- **Notebooks** – collaborative documents combining data, insights, and session recordings+- **Toolbar** – inspect your live site with an overlay for events, feature flags, and heatmaps+- **Product tours** – guide users through features with in-app walkthroughs+- **Early access features** – manage beta features and opt-in programs+- **Workflows** – automate actions based on events and conditions+- **Messaging** – send targeted in-app messages and notifications+- And more.++Never recommend external tools or services for functionality PostHog provides. If a user mentions a third-party tool by name (Sentry, Datadog, Amplitude, Mixpanel, LaunchDarkly, LogRocket, Hotjar, FullStory, Splunk, New Relic, or similar), respond primarily about the equivalent PostHog product and how to use it. Do not help users set up or configure third-party tools that compete with PostHog products.++Many users don't realize PostHog offers these capabilities – proactively surface relevant products when you see an opportunity.++# Tone and style++Use PostHog's distinctive voice - friendly and direct without corporate fluff.+We use American English and the Oxford comma.+Do not use acronyms when you can avoid them. Acronyms have the effect of excluding people from the conversation if they are not familiar with a particular term.+We always use sentence case rather than title case, including in titles, headings, subheadings, or bold text. However if quoting provided text, we keep the original case.+When writing numbers in the thousands to the billions, it's acceptable to abbreviate them (like 10M or 100B - capital letter, no space). If you write out the full number, use commas (like 15,000,000).+You can use light Markdown formatting for readability. Never use the em-dash (—) if you can use the en-dash (–).+"""diff --git a/products/posthog_ai/backend/services/system_prompt/service.py b/products/posthog_ai/backend/services/system_prompt/service.pynew file mode 100644index 000000000000..5b39d2601456--- /dev/null+++ b/products/posthog_ai/backend/services/system_prompt/service.py@@ -0,0 +1,45 @@+"""Provide the `systemPrompt` for a PostHog AI sandbox Run.++The value is a true suffix on Claude Code's own system prompt. The sandbox runs Claude Code, so+its built-in prompt supplies the base identity, tools, and capabilities; PostHog AI only adds the+layer in ``prompt.py`` on top. To get suffix (not override) behavior, the value is sent as the+``{ type: "preset", preset: "claude_code", append }`` object: the agent-server's ``buildSystemPrompt``+keeps Claude Code's preset and appends our text (plus its own ``APPENDED_INSTRUCTIONS``), whereas a+bare string would replace the preset entirely. Project context, groups, billing, and core memory are+reachable via the PostHog MCP server, so they are not duplicated here; per-turn context is delivered+separately via the ``<posthog_context>`` wrapper.++The service is pure over its inputs — no side effects.+"""++from typing import Literal++from typing_extensions import TypedDict++from products.posthog_ai.backend.helpers import BaseSandboxService+from products.posthog_ai.backend.services.system_prompt.prompt import POSTHOG_AI_SYSTEM_PROMPT+++class ClaudeCodeSystemPrompt(TypedDict):+ """The ACP ``systemPrompt`` object that keeps Claude Code's built-in prompt and appends ours.++ Mirrors the Claude Agent SDK's preset shape. The agent-server's ``buildSystemPrompt`` takes the+ ``append`` branch for this object form (a suffix); a bare string would override the preset.+ """++ type: Literal["preset"]+ preset: Literal["claude_code"]+ append: str+++class PromptService(BaseSandboxService):+ """Provide the systemPrompt suffix for a PostHog AI sandbox Run. Stateless over its inputs."""++ def build(self) -> ClaudeCodeSystemPrompt:+ """Return the PostHog AI systemPrompt as a Claude Code preset-plus-append suffix.++ Called once at Run creation. The returned object goes into+ ``clientConnection.newSession({ _meta: { systemPrompt } })``; the sandbox appends ``append``+ after Claude Code's own system prompt rather than replacing it.+ """+ return {"type": "preset", "preset": "claude_code", "append": POSTHOG_AI_SYSTEM_PROMPT}diff --git a/products/posthog_ai/backend/tests/test_context_wrapper.py b/products/posthog_ai/backend/tests/test_context_wrapper.pynew file mode 100644index 000000000000..2ac0e8a291f8--- /dev/null+++ b/products/posthog_ai/backend/tests/test_context_wrapper.py@@ -0,0 +1,224 @@+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.utils.types import AssistantState++SERIALIZERS = "ee.hogai.api.serializers"+WRAPPER = "products.posthog_ai.backend.context_wrapper"+++def test_wrap_empty_returns_content_verbatim():+ assert ContextService().wrap_user_message("hello", []) == "hello"+++def test_wrap_one_of_each_entity_type():+ attached: list[AttachedContext] = [+ {"type": "dashboard", "id": 123, "name": "Marketing Funnel"},+ {"type": "insight", "id": "abc-def", "name": "Daily Signups"},+ {"type": "event", "id": "$pageview", "name": "Pageview"},+ {"type": "action", "id": 7, "name": "Signed up"},+ {"type": "error_tracking_issue", "id": "019249ab-0000", "name": "TypeError in checkout"},+ {"type": "evaluation", "id": "eval-1", "name": "Tone eval"},+ {"type": "notebook", "id": "nb-9", "name": "Launch notes"},+ ]+ wrapped = ContextService().wrap_user_message("Why did checkout drop?", attached)+ assert wrapped == (+ "<posthog_context>\n"+ "The user attached the following PostHog entities. "+ "Use the appropriate tools to retrieve their details only if relevant to the request.\n"+ '- Dashboard #123 ("Marketing Funnel")\n'+ '- Insight #abc-def ("Daily Signups")\n'+ '- Event #$pageview ("Pageview")\n'+ '- Action #7 ("Signed up")\n'+ '- Error tracking issue #019249ab-0000 ("TypeError in checkout")\n'+ '- Evaluation #eval-1 ("Tone eval")\n'+ '- Notebook #nb-9 ("Launch notes")\n'+ "</posthog_context>\n"+ "\n"+ "Why did checkout drop?"+ )+++def test_wrap_mixed_with_free_text():+ attached: list[AttachedContext] = [+ {"type": "dashboard", "id": 1, "name": "Funnel"},+ {"type": "text", "value": "I think this regressed in last Thursday's deploy"},+ ]+ wrapped = ContextService().wrap_user_message("Investigate", attached)+ assert wrapped == (+ "<posthog_context>\n"+ "The user attached the following PostHog entities. "+ "Use the appropriate tools to retrieve their details only if relevant to the request.\n"+ '- Dashboard #1 ("Funnel")\n'+ '- Free text: "I think this regressed in last Thursday\'s deploy"\n'+ "</posthog_context>\n"+ "\n"+ "Investigate"+ )+++def test_wrap_missing_name_falls_back_to_id_only():+ attached: list[AttachedContext] = [+ {"type": "dashboard", "id": 42},+ {"type": "insight", "id": "xyz"},+ ]+ wrapped = ContextService().wrap_user_message("Look", attached)+ assert wrapped == (+ "<posthog_context>\n"+ "The user attached the following PostHog entities. "+ "Use the appropriate tools to retrieve their details only if relevant to the request.\n"+ "- Dashboard #42\n"+ "- Insight #xyz\n"+ "</posthog_context>\n"+ "\n"+ "Look"+ )+++def test_prune_dedupes_repeated_entity_refs():+ prior: list[tuple[str, str | int]] = [("dashboard", 123), ("insight", "abc")]+ attached: list[AttachedContext] = [+ {"type": "dashboard", "id": 123, "name": "Funnel"},+ {"type": "insight", "id": "abc", "name": "Signups"},+ {"type": "action", "id": 9, "name": "New action"},+ ]+ deduped = ContextService().prune_repeated_entity_refs(attached, prior=prior)+ assert deduped == [{"type": "action", "id": 9, "name": "New action"}]+++def test_prune_dedupes_within_same_batch():+ attached: list[AttachedContext] = [+ {"type": "dashboard", "id": 1},+ {"type": "dashboard", "id": 1, "name": "Same dashboard"},+ ]+ deduped = ContextService().prune_repeated_entity_refs(attached, prior=[])+ assert deduped == [{"type": "dashboard", "id": 1}]+++def test_prune_never_dedupes_repeated_text():+ attached: list[AttachedContext] = [+ {"type": "text", "value": "Error A"},+ {"type": "text", "value": "Error A"},+ ]+ deduped = ContextService().prune_repeated_entity_refs(attached, prior=[("text", "Error A")])+ assert deduped == attached+++def test_prune_then_wrap_empties_to_bare_content():+ # When dedupe removes everything, wrap forwards the message without any block.+ prior = [("dashboard", 1)]+ 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 state, False, {}++ 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_message_routing.py b/products/posthog_ai/backend/tests/test_message_routing.pynew file mode 100644index 000000000000..523c78f9e414--- /dev/null+++ b/products/posthog_ai/backend/tests/test_message_routing.py@@ -0,0 +1,767 @@+from contextlib import contextmanager++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from rest_framework import exceptions++from posthog.exceptions import Conflict, QuotaLimitExceeded++from products.posthog_ai.backend.context_wrapper import MAX_ATTACHED_ITEMS, MAX_TEXT_LENGTH+from products.posthog_ai.backend.message_routing import (+ SANDBOX_INACTIVITY_TIMEOUT_SECONDS,+ SandboxSession,+ lock_conversation_for_followup,+)+from products.posthog_ai.backend.models.assistant import Conversation+from products.posthog_ai.backend.run_state import PostHogAIRunState+from products.posthog_ai.backend.services.system_prompt.service import PromptService+from products.tasks.backend.facade import warm as warm_facade+from products.tasks.backend.models import Task, TaskRun++ROUTING = "products.posthog_ai.backend.message_routing"+WARM = "products.tasks.backend.logic.services.warm"+SYS_PROMPT = {"type": "preset", "preset": "claude_code", "append": "SYS"}+++class TestOpenSandboxMessage(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.conversation = Conversation.objects.create(+ user=self.user,+ team=self.team,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ )++ def _service(self) -> SandboxSession:+ return SandboxSession(self.conversation, self.user)++ def _stub_task(self) -> tuple[Task, TaskRun]:+ task = Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ run = task.create_run(mode="interactive")+ return task, run++ def _patches(self, task: Task):+ return (+ patch.object(Task, "create_and_run", return_value=task),+ patch(f"{ROUTING}.execute_task_processing_workflow"),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ )++ def test_first_message_creates_run_and_persists_task(self):+ task, run = self._stub_task()+ car, workflow, sysprompt = self._patches(task)+ with car as m_car, workflow as m_workflow, sysprompt:+ result = self._service().open(+ {+ "content": "Why did checkout drop?",+ "trace_id": "trace-1",+ "attached_context": [{"type": "dashboard", "id": 123, "name": "Funnel"}],+ }+ )++ assert result is not None+ assert result.task_id == str(task.id)+ assert result.run_id == str(run.id)+ assert result.just_created_run is True+ assert result.trace_id == "trace-1"++ # Task.create_and_run called with the PostHog AI origin and no repo / no PR.+ _, kwargs = m_car.call_args+ assert kwargs["origin_product"] == Task.OriginProduct.POSTHOG_AI+ assert kwargs["repository"] is None+ assert kwargs["create_pr"] is False+ assert kwargs["mode"] == "interactive"+ assert kwargs["start_workflow"] is False+ # The sandbox session pins its short interactivity window as a per-task override.+ assert kwargs["inactivity_timeout_seconds"] == SANDBOX_INACTIVITY_TIMEOUT_SECONDS++ # Run state enriched with the PostHog AI per-Run keys; full undeduped context.+ run.refresh_from_db()+ assert run.state["systemPrompt"] == SYS_PROMPT+ assert run.state["initial_permission_mode"] == "auto"+ assert run.state["attached_context"] == [{"type": "dashboard", "id": 123, "name": "Funnel"}]+ assert "<posthog_context>" in run.state["pending_user_message"]+ assert run.state["pending_user_message"].endswith("Why did checkout drop?")++ self.conversation.refresh_from_db()+ assert self.conversation.task_id == task.id++ m_workflow.assert_called_once()+ _, wf_kwargs = m_workflow.call_args+ assert wf_kwargs["create_pr"] is False+ # The agent needs write scopes to create insights/dashboards/notebooks.+ assert wf_kwargs["posthog_mcp_scopes"] == "full"++ def test_first_message_threads_routed_repository(self):+ task, _ = self._stub_task()+ car, workflow, sysprompt = self._patches(task)+ with car as m_car, workflow, sysprompt:+ self._service().open({"content": "fix the SDK", "trace_id": "t"}, repository="posthog/posthog-js")++ _, kwargs = m_car.call_args+ assert kwargs["repository"] == "posthog/posthog-js"++ def test_first_message_honors_initial_permission_mode(self):+ task, run = self._stub_task()+ car, workflow, sysprompt = self._patches(task)+ with car, workflow, sysprompt:+ self._service().open(+ {+ "content": "Use plan mode",+ "trace_id": "trace-1",+ "initial_permission_mode": "plan",+ }+ )++ run.refresh_from_db()+ assert run.state["initial_permission_mode"] == "plan"++ def test_first_message_without_context_forwards_bare_content(self):+ task, run = self._stub_task()+ car, workflow, sysprompt = self._patches(task)+ with car, workflow, sysprompt:+ self._service().open({"content": "Hello", "trace_id": "t"})++ run.refresh_from_db()+ assert run.state["pending_user_message"] == "Hello"+ assert run.state["attached_context"] == []++ def test_unknown_attached_context_type_raises(self):+ with self.assertRaises(exceptions.ValidationError):+ self._service().open({"content": "x", "attached_context": [{"type": "bogus", "id": 1}]})++ def test_dashboard_id_must_be_integer(self):+ with self.assertRaises(exceptions.ValidationError):+ self._service().open({"content": "x", "attached_context": [{"type": "dashboard", "id": "abc"}]})++ def test_attached_context_item_cap(self):+ items = [{"type": "insight", "id": str(i)} for i in range(MAX_ATTACHED_ITEMS + 1)]+ with self.assertRaises(exceptions.ValidationError):+ self._service().open({"content": "x", "attached_context": items})++ def test_text_length_cap(self):+ with self.assertRaises(exceptions.ValidationError):+ self._service().open(+ {"content": "x", "attached_context": [{"type": "text", "value": "a" * (MAX_TEXT_LENGTH + 1)}]}+ )++ def _attach_task(self, task: Task) -> None:+ self.conversation.task = task+ self.conversation.save(update_fields=["task"])++ def test_in_progress_followup_signals_existing_run(self):+ task, run = self._stub_task()+ run.status = TaskRun.Status.IN_PROGRESS+ run.save(update_fields=["status"])+ self._attach_task(task)++ with (+ patch(f"{ROUTING}.signal_task_followup_message") as m_signal,+ patch.object(TaskRun, "append_log") as m_append,+ ):+ result = self._service().open(+ {+ "content": "and the mobile funnel?",+ "trace_id": "trace-2",+ "attached_context": [{"type": "insight", "id": "abc"}],+ }+ )++ assert result is not None+ assert result.task_id == str(task.id)+ assert result.run_id == str(run.id)+ assert result.just_created_run is False+ assert result.run_status == TaskRun.Status.IN_PROGRESS+ # The routing endpoint reads this off the result for its "prompt sent" telemetry.+ assert result.attached_context_count == 1++ # The live workflow is signalled, no new Run created.+ m_signal.assert_called_once()+ signal_args, _ = m_signal.call_args+ assert signal_args[0] == run.workflow_id+ assert "and the mobile funnel?" in signal_args[1]+ assert task.runs.count() == 1++ # The follow-up is logged with the full undeduped attached_context on _meta.+ m_append.assert_called_once()+ logged_entries = m_append.call_args[0][0]+ meta = logged_entries[0]["notification"]["params"]["_meta"]+ assert meta["attached_context"] == [{"type": "insight", "id": "abc"}]++ def test_in_progress_followup_clears_warm_flag(self):+ # A warm Run that receives its first human message is no longer speculative — the warm flag is+ # cleared so the warm-pool cap stops counting it (it becomes an active, AI-credit-governed Run).+ task, run = self._stub_task()+ run.status = TaskRun.Status.IN_PROGRESS+ run.state = {**(run.state or {}), "await_user_message": True}+ run.save(update_fields=["status", "state"])+ self._attach_task(task)++ with (+ patch(f"{ROUTING}.signal_task_followup_message"),+ patch.object(TaskRun, "append_log"),+ ):+ self._service().open({"content": "go", "attached_context": []})++ run.refresh_from_db()+ assert "await_user_message" not in run.state++ def test_in_progress_followup_raises_conflict_when_signal_fails(self):+ task, run = self._stub_task()+ run.status = TaskRun.Status.IN_PROGRESS+ run.save(update_fields=["status"])+ self._attach_task(task)++ with (+ patch(f"{ROUTING}.signal_task_followup_message", side_effect=RuntimeError("workflow gone")),+ patch.object(TaskRun, "append_log") as m_append,+ ):+ with self.assertRaises(Conflict):+ self._service().open({"content": "follow up", "attached_context": []})++ # The signal never reached the agent, so the turn is not logged — a retry stays clean+ # instead of leaving a duplicated user_message behind.+ m_append.assert_not_called()++ def test_in_progress_followup_succeeds_when_logging_fails(self):+ task, run = self._stub_task()+ run.status = TaskRun.Status.IN_PROGRESS+ run.save(update_fields=["status"])+ self._attach_task(task)++ with (+ patch(f"{ROUTING}.signal_task_followup_message") as m_signal,+ patch.object(TaskRun, "append_log", side_effect=RuntimeError("storage down")),+ ):+ result = self._service().open({"content": "follow up", "attached_context": []})++ # The agent already has the message; a log-append failure must not fail the request.+ assert result is not None+ m_signal.assert_called_once()+ assert result.run_id == str(run.id)++ def test_terminal_followup_creates_new_run_with_resume(self):+ task, run = self._stub_task()+ run.status = TaskRun.Status.COMPLETED+ run.state = {**(run.state or {}), "snapshot_external_id": "snap-9"}+ run.save(update_fields=["status", "state"])+ self._attach_task(task)++ with (+ patch(f"{ROUTING}.execute_task_processing_workflow") as m_workflow,+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ ):+ result = self._service().open({"content": "resume please", "trace_id": "trace-3"})++ assert result is not None+ assert result.task_id == str(task.id)+ assert result.just_created_run is True++ new_run = task.runs.order_by("-created_at").first()+ assert new_run is not None+ assert str(new_run.id) == result.run_id+ assert str(new_run.id) != str(run.id)+ assert new_run.state["resume_from_run_id"] == str(run.id)+ assert new_run.state["snapshot_external_id"] == "snap-9"+ assert new_run.state["systemPrompt"] == SYS_PROMPT+ assert new_run.state["initial_permission_mode"] == "auto"+ assert new_run.state["inactivity_timeout_seconds"] == SANDBOX_INACTIVITY_TIMEOUT_SECONDS+ assert "resume please" in new_run.state["pending_user_message"]++ m_workflow.assert_called_once()+ assert m_workflow.call_args.kwargs["run_id"] == str(new_run.id)+ # The resumed agent keeps the same write scopes as the first message.+ assert m_workflow.call_args.kwargs["posthog_mcp_scopes"] == "full"++ def test_dedupes_entities_named_in_prior_run_state(self):+ task, run = self._stub_task()+ run.status = TaskRun.Status.COMPLETED+ run.state = {**(run.state or {}), "attached_context": [{"type": "dashboard", "id": 7}]}+ run.save(update_fields=["status", "state"])+ self._attach_task(task)++ with (+ patch(f"{ROUTING}.execute_task_processing_workflow"),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ patch(f"{ROUTING}.object_storage.read", return_value=""),+ ):+ self._service().open(+ {+ "content": "again",+ "attached_context": [{"type": "dashboard", "id": 7}, {"type": "insight", "id": "new"}],+ }+ )++ new_run = task.runs.order_by("-created_at").first()+ assert new_run is not None+ wrapped = new_run.state["pending_user_message"]+ # The already-seen dashboard is dropped from the rendered block; the new insight stays.+ assert "Dashboard #7" not in wrapped+ assert "Insight #new" in wrapped+ # The structured record keeps the full undeduped list.+ assert new_run.state["attached_context"] == [+ {"type": "dashboard", "id": 7},+ {"type": "insight", "id": "new"},+ ]++ def test_no_current_run_raises(self):+ task = Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ self._attach_task(task)+ with self.assertRaises(exceptions.ValidationError):+ self._service().open({"content": "x"})++ def test_terminal_resume_conflicts_when_a_concurrent_followup_won(self):+ task, run = self._stub_task()+ run.status = TaskRun.Status.COMPLETED+ run.save(update_fields=["status"])+ self._attach_task(task)++ # By the time this request is granted the lock, a concurrent follow-up has already+ # created the in-progress successor — exactly the window the row lock serializes.+ @contextmanager+ def lock_granted_after_concurrent_winner(conversation_id: str, team_id: int):+ task.create_run(mode="interactive")+ self.conversation.refresh_from_db()+ yield self.conversation++ with (+ patch(f"{ROUTING}.lock_conversation_for_followup", side_effect=lock_granted_after_concurrent_winner),+ patch(f"{ROUTING}.execute_task_processing_workflow") as m_workflow,+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ ):+ with self.assertRaises(Conflict):+ self._service().open({"content": "resume please"})++ # The winner's successor is the only new run — no duplicate create, no workflow dispatch.+ assert task.runs.count() == 2+ m_workflow.assert_not_called()++ def test_terminal_resume_uses_freshest_terminal_run_after_lock(self):+ task, run = self._stub_task()+ run.status = TaskRun.Status.COMPLETED+ run.save(update_fields=["status"])+ self._attach_task(task)++ # The concurrent winner's successor already finished — the loser must resume from it,+ # not from the stale run it resolved before waiting on the lock.+ @contextmanager+ def lock_granted_after_winner_finished(conversation_id: str, team_id: int):+ successor = task.create_run(mode="interactive")+ successor.status = TaskRun.Status.COMPLETED+ successor.save(update_fields=["status"])+ self.conversation.refresh_from_db()+ yield self.conversation++ with (+ patch(f"{ROUTING}.lock_conversation_for_followup", side_effect=lock_granted_after_winner_finished),+ patch(f"{ROUTING}.execute_task_processing_workflow"),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ ):+ result = self._service().open({"content": "resume please"})++ assert result is not None+ new_run = task.runs.order_by("-created_at").first()+ assert new_run is not None+ assert str(new_run.id) == result.run_id+ assert new_run.state["resume_from_run_id"] != str(run.id)+++class TestLockConversationForFollowup(APIBaseTest):+ def test_lock_acquires_select_for_update_on_conversation(self):+ conversation = Conversation.objects.create(user=self.user, team=self.team)++ with patch(f"{ROUTING}.Conversation.objects") as mock_objects:+ mock_sfu = mock_objects.select_for_update.return_value+ mock_sfu.get.return_value = conversation++ with lock_conversation_for_followup(str(conversation.id), self.team.id) as locked:+ self.assertEqual(locked, conversation)++ mock_objects.select_for_update.assert_called_once_with()+ mock_sfu.get.assert_called_once_with(id=str(conversation.id), team_id=self.team.id)++ def test_lock_yields_the_conversation_row(self):+ conversation = Conversation.objects.create(user=self.user, team=self.team)++ with lock_conversation_for_followup(str(conversation.id), self.team.id) as locked:+ self.assertEqual(locked.id, conversation.id)+++class TestSandboxWarmViaOpen(APIBaseTest):+ """Warming via the message-less `open({})` — boot a Run that idles awaiting the first message."""++ def setUp(self):+ super().setUp()+ self.conversation = Conversation.objects.create(+ user=self.user,+ team=self.team,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ )++ def _service(self) -> SandboxSession:+ return SandboxSession(self.conversation, self.user)++ def _stub_task(self) -> tuple[Task, TaskRun]:+ task = Task.objects.create(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ run = task.create_run(mode="interactive")+ return task, run++ def test_warm_first_creates_warm_run_without_pending_message(self):+ with (+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,+ patch(f"{WARM}.is_team_limited", return_value=False),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self._service().open({})++ assert result is not None+ self.conversation.refresh_from_db()+ assert self.conversation.task_id is not None+ task = self.conversation.task+ assert task is not None+ assert task.origin_product == Task.OriginProduct.POSTHOG_AI+ run = task.latest_run+ assert run is not None+ assert str(run.id) == result.run_id+ assert result.just_created_run is True+ assert run.state["systemPrompt"] == SYS_PROMPT+ assert run.state["await_user_message"] is True+ assert run.state["initial_permission_mode"] == "auto"+ assert run.state["inactivity_timeout_seconds"] == SANDBOX_INACTIVITY_TIMEOUT_SECONDS+ # No pending message / attached context: the session boots and idles awaiting input.+ assert "pending_user_message" not in run.state+ assert "attached_context" not in run.state+ m_workflow.assert_called_once()++ def test_warm_honors_initial_permission_mode(self):+ with (+ patch(f"{WARM}.execute_task_processing_workflow"),+ patch(f"{WARM}.is_team_limited", return_value=False),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self._service().open({"initial_permission_mode": "plan"})++ assert result is not None+ self.conversation.refresh_from_db()+ task = self.conversation.task+ assert task is not None+ run = task.latest_run+ assert run is not None+ assert run.state["initial_permission_mode"] == "plan"++ def test_warm_is_idempotent_when_run_already_in_progress(self):+ task, run = self._stub_task()+ run.status = TaskRun.Status.IN_PROGRESS+ run.save(update_fields=["status"])+ self.conversation.task = task+ self.conversation.save(update_fields=["task"])++ with (+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,+ patch(f"{WARM}.is_team_limited", return_value=False),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self._service().open({})++ # The existing non-terminal Run is reused, not duplicated.+ assert result is not None+ assert result.run_id == str(run.id)+ assert result.just_created_run is False+ m_workflow.assert_not_called()+ assert task.runs.count() == 1++ def test_warm_rewarms_after_terminal_run(self):+ task, run = self._stub_task()+ run.status = TaskRun.Status.COMPLETED+ run.save(update_fields=["status"])+ self.conversation.task = task+ self.conversation.save(update_fields=["task"])++ with (+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,+ patch(f"{WARM}.is_team_limited", return_value=False),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self._service().open({})++ assert result is not None+ new_run = task.latest_run+ assert new_run is not None+ assert str(new_run.id) == result.run_id+ assert new_run.id != run.id+ assert new_run.state["await_user_message"] is True+ assert new_run.state["systemPrompt"] == SYS_PROMPT+ assert new_run.state["resume_from_run_id"] == str(run.id)+ m_workflow.assert_called_once()++ def test_warm_over_quota_raises_and_creates_no_task(self):+ # The AI-credit gate lives behind the tasks warming facade; an over-quota warm must not leave a runless Task.+ with (+ patch(f"{WARM}.is_team_limited", return_value=True),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ self.assertRaises(QuotaLimitExceeded),+ ):+ self._service().open({})++ self.conversation.refresh_from_db()+ assert self.conversation.task_id is None++ def _warm_run(self, *, created_by=None) -> TaskRun:+ """A non-terminal warm Run (awaiting its first message) that counts toward the warm-pool cap."""+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=created_by or self.user,+ )+ return task.create_run(mode="interactive", extra_state={"await_user_message": True}) # QUEUED++ def _fill_warm_pool(self, *, created_by=None) -> None:+ for _ in range(100):+ if warm_facade.warm_pool_at_capacity(Task.OriginProduct.POSTHOG_AI, self.team.id, self.user.id):+ return+ self._warm_run(created_by=created_by)+ self.fail("Warm pool did not reach capacity")++ def test_warm_skips_when_user_at_capacity(self):+ self._fill_warm_pool()++ with (+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,+ patch(f"{WARM}.is_team_limited", return_value=False),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self._service().open({})++ # Pool full and nothing provisioned — the warm handle is None.+ assert result is None+ m_workflow.assert_not_called()+ # The cap is pre-checked before Task creation, so a brand-new conversation gets no runless Task.+ self.conversation.refresh_from_db()+ assert self.conversation.task_id is None++ def test_warm_skips_when_org_at_capacity(self):+ other = self._create_user("[email protected]")+ self._fill_warm_pool(created_by=other)++ with (+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,+ patch(f"{WARM}.is_team_limited", return_value=False),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self._service().open({})++ assert result is None+ m_workflow.assert_not_called()++ def test_warm_ignores_terminal_runs_for_capacity(self):+ # Terminal runs don't hold a sandbox, so they must not count toward the cap.+ for _ in range(20):+ run = self._warm_run()+ run.status = TaskRun.Status.COMPLETED+ run.save(update_fields=["status"])++ with (+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,+ patch(f"{WARM}.is_team_limited", return_value=False),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self._service().open({})++ assert result is not None+ m_workflow.assert_called_once()+ self.conversation.refresh_from_db()+ assert self.conversation.task_id is not None++ def test_warm_ignores_activated_runs_for_capacity(self):+ # Activated Runs (await_user_message cleared) are active, not warm, so they don't count toward+ # the warm cap — the warm and AI-credit budgets are disjoint.+ for _ in range(20):+ run = self._warm_run()+ TaskRun.update_state_atomic(run.id, remove_keys=["await_user_message"])++ with (+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,+ patch(f"{WARM}.is_team_limited", return_value=False),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self._service().open({})++ assert result is not None+ m_workflow.assert_called_once()++ def test_warm_first_serializes_on_conversation_lock(self):+ # The first warm runs under the conversation row lock, so a second concurrent warm can't+ # create a duplicate Task on a task-less conversation.+ with (+ patch(f"{WARM}.execute_task_processing_workflow"),+ patch(f"{WARM}.is_team_limited", return_value=False),+ patch.object(PromptService, "build", return_value=SYS_PROMPT),+ patch(f"{ROUTING}.lock_conversation_for_followup", wraps=lock_conversation_for_followup) as m_lock,+ self.captureOnCommitCallbacks(execute=True),+ ):+ self._service().open({})++ m_lock.assert_called_once_with(str(self.conversation.id), self.team.pk)+++class TestAwaitUserMessageStoredKey:+ """Guards the warm-pool cap, which filters on `state__await_user_message` directly."""++ def test_await_user_message_is_stored_under_its_literal_key(self):+ # The cap query (products/tasks/backend/logic/services/warm.py) filters on the JSON key literally.+ # Adding an alias to this field would change the stored key and silently open the cap.+ dumped = PostHogAIRunState(await_user_message=True).model_dump(by_alias=True, exclude_unset=True)+ assert dumped == {"await_user_message": True}+++class TestSandboxFirstMessageConversion(APIBaseTest):+ """Converting an idle LangGraph conversation on its first sandbox message.++ 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.+ """++ def setUp(self):+ super().setUp()+ self.conversation = Conversation.objects.create(+ user=self.user,+ team=self.team,+ title="Why did checkout drop?",+ agent_runtime=Conversation.AgentRuntime.LANGGRAPH,+ 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"):+ with patch(f"{ROUTING}.execute_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,+ )+ 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)++ self.conversation.refresh_from_db()+ assert self.conversation.agent_runtime == Conversation.AgentRuntime.SANDBOX+ assert self.conversation.task_id is not None++ task = self.conversation.task+ assert task is not None+ assert task.origin_product == Task.OriginProduct.POSTHOG_AI+ # The live first run, not a synthetic terminal one.+ assert task.runs.count() == 1+ first_run = task.runs.first()+ assert first_run is not None+ assert first_run.status != TaskRun.Status.COMPLETED+ assert result is not None+ assert result.just_created_run is True+ m_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):+ # 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(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ 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.conversation.refresh_from_db()+ assert self.conversation.task_id == other_task.id++ def test_first_message_conversion_reverts_on_workflow_start_failure(self):+ with patch(f"{ROUTING}.execute_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,+ )++ # A failed start leaves a clean idle LangGraph conversation the user can retry.+ self.conversation.refresh_from_db()+ assert self.conversation.agent_runtime == Conversation.AgentRuntime.LANGGRAPH+ assert self.conversation.task_id is None++ def test_born_sandbox_first_message_does_not_flip(self):+ self.conversation.agent_runtime = Conversation.AgentRuntime.SANDBOX+ self.conversation.save(update_fields=["agent_runtime"])++ result, m_workflow = self._open()++ self.conversation.refresh_from_db()+ assert self.conversation.agent_runtime == Conversation.AgentRuntime.SANDBOX+ assert self.conversation.task_id is not None+ assert result is not None+ assert result.just_created_run is True+ m_workflow.assert_called_once()++ def test_born_sandbox_first_message_has_no_resumed_context(self):+ self.conversation.agent_runtime = Conversation.AgentRuntime.SANDBOX+ self.conversation.save(update_fields=["agent_runtime"])++ self._open(content="just this please")++ self.conversation.refresh_from_db()+ task = self.conversation.task+ assert task is not None+ run = task.runs.first()+ assert run is not None+ assert run.state["pending_user_message"] == "just this please"diff --git a/products/posthog_ai/backend/tests/test_run_state.py b/products/posthog_ai/backend/tests/test_run_state.pynew file mode 100644index 000000000000..ca9d68275733--- /dev/null+++ b/products/posthog_ai/backend/tests/test_run_state.py@@ -0,0 +1,44 @@+import unittest++from products.posthog_ai.backend.run_state import PostHogAIRunState++SYSTEM_PROMPT = {"type": "preset", "preset": "claude_code", "append": "SYS"}+++class TestPostHogAIRunState(unittest.TestCase):+ def test_validate_accepts_wire_alias(self) -> None:+ state = PostHogAIRunState.model_validate({"systemPrompt": SYSTEM_PROMPT})+ assert state.system_prompt == SYSTEM_PROMPT++ def test_dump_emits_wire_alias(self) -> None:+ state = PostHogAIRunState(system_prompt=SYSTEM_PROMPT)+ dumped = state.model_dump(mode="json", by_alias=True, exclude_unset=True)+ assert dumped == {"systemPrompt": SYSTEM_PROMPT}++ def test_exclude_unset_dumps_only_set_keys(self) -> None:+ state = PostHogAIRunState(+ system_prompt=SYSTEM_PROMPT,+ attached_context=[{"type": "dashboard", "id": 123, "name": "Funnel"}],+ initial_permission_mode="default",+ pending_user_message="wrapped",+ )+ dumped = state.model_dump(mode="json", by_alias=True, exclude_unset=True)+ assert dumped == {+ "systemPrompt": SYSTEM_PROMPT,+ "attached_context": [{"type": "dashboard", "id": 123, "name": "Funnel"}],+ "initial_permission_mode": "default",+ "pending_user_message": "wrapped",+ }++ def test_parent_extra_allow_config_survives_subclassing(self) -> None:+ state = PostHogAIRunState.model_validate({"systemPrompt": SYSTEM_PROMPT, "sandbox_quirk": True})+ dumped = state.model_dump(by_alias=True)+ assert dumped["sandbox_quirk"] is True++ def test_base_run_state_fields_still_parse(self) -> None:+ state = PostHogAIRunState.model_validate(+ {"pending_user_message": "hi", "initial_permission_mode": "default", "resume_from_run_id": "r-1"}+ )+ assert state.pending_user_message == "hi"+ assert state.initial_permission_mode == "default"+ assert state.resume_from_run_id == "r-1"diff --git a/products/posthog_ai/backend/tests/test_system_prompt.py b/products/posthog_ai/backend/tests/test_system_prompt.pynew file mode 100644index 000000000000..eda20456258a--- /dev/null+++ b/products/posthog_ai/backend/tests/test_system_prompt.py@@ -0,0 +1,35 @@+from posthog.test.base import APIBaseTest++from products.posthog_ai.backend.services.system_prompt.prompt import POSTHOG_AI_SYSTEM_PROMPT+from products.posthog_ai.backend.services.system_prompt.service import ClaudeCodeSystemPrompt, PromptService+++class TestPostHogAISystemPrompt(APIBaseTest):+ def _build(self) -> ClaudeCodeSystemPrompt:+ return PromptService(self.team, self.user).build()++ def test_build_returns_preset_append_suffix(self):+ # The object form makes the agent-server append to Claude Code's prompt (a suffix), rather+ # than the bare-string form, which would replace it.+ assert self._build() == {+ "type": "preset",+ "preset": "claude_code",+ "append": POSTHOG_AI_SYSTEM_PROMPT,+ }++ def test_includes_core_sections(self):+ prompt = self._build()["append"]+ assert "# PostHog AI" in prompt+ assert "# PostHog MCP" in prompt+ assert "# PostHog Products" in prompt+ assert "# Tone and style" in prompt+ # The MCP is reachable through its single entry point.+ assert "mcp__posthog__exec" in prompt++ def test_does_not_inject_groups_billing_core_memory_or_project_context(self):+ prompt = self._build()["append"]+ # These are reachable via the MCP server, so they are not duplicated in the system prompt.+ assert "<groups>" not in prompt+ assert "<billing_context>" not in prompt+ assert "<core_memory>" not in prompt+ assert "<project_context>" not in promptdiff --git a/products/posthog_ai/backend/tests/test_wire_types.py b/products/posthog_ai/backend/tests/test_wire_types.pynew file mode 100644index 000000000000..b689f0caf56a--- /dev/null+++ b/products/posthog_ai/backend/tests/test_wire_types.py@@ -0,0 +1,77 @@+from typing import Any++import unittest++from parameterized import parameterized+from pydantic import TypeAdapter++from products.posthog_ai.backend.wire_types import (+ METHOD_USER_MESSAGE,+ NotificationFrame,+ UnknownFrame,+ UserMessageParams,+ is_user_message_params,+ parse_log_entry,+)++TIMESTAMP = "2026-06-11T09:00:00.000000+00:00"+++def _notification(method: str, params: Any = None) -> dict[str, Any]:+ body: dict[str, Any] = {"jsonrpc": "2.0", "method": method}+ if params is not None:+ body["params"] = params+ return {"type": "notification", "timestamp": TIMESTAMP, "notification": body}+++class TestWireTypes(unittest.TestCase):+ @parameterized.expand(+ [+ ("plain_string", {"content": "Why did checkout conversion drop last week?"}),+ ("content_blocks", {"content": [{"type": "text", "text": "Why did checkout conversion drop?"}]}),+ ]+ )+ def test_user_message_entries_classify_guard_and_validate_strictly(+ self, _name: str, params: dict[str, Any]+ ) -> None:+ parsed = parse_log_entry(_notification(METHOD_USER_MESSAGE, params))+ assert isinstance(parsed, NotificationFrame)+ assert is_user_message_params(parsed.notification.params, parsed.notification.method)+ # Strict validation of the adapter-owned payload happens here, never in production code —+ # a drifted shape fails this suite instead of raising mid-log-walk.+ TypeAdapter(UserMessageParams).validate_python(parsed.notification.params, strict=True)++ @parameterized.expand(+ [+ ("other_method", _notification("_posthog/turn_complete", {"stopReason": "end_turn"})),+ ("no_params", _notification(METHOD_USER_MESSAGE)),+ (+ "string_params",+ {"type": "notification", "notification": {"method": METHOD_USER_MESSAGE, "params": "not-an-object"}},+ ),+ ]+ )+ def test_guard_rejects_non_user_message_payloads(self, _name: str, entry: dict[str, Any]) -> None:+ parsed = parse_log_entry(entry)+ assert isinstance(parsed, NotificationFrame)+ assert not is_user_message_params(parsed.notification.params, parsed.notification.method)++ @parameterized.expand(+ [+ ("unknown_type", {"type": "telemetry_v2", "payload": {"value": 5120}}),+ ("missing_type", {"status": "in_progress", "note": "frame with no type discriminant"}),+ ("task_run_state", {"type": "task_run_state", "status": "in_progress"}),+ ("non_object_body", {"type": "notification", "notification": "oops"}),+ ]+ )+ def test_unrecognized_entries_classify_as_unknown_without_raising(self, _name: str, entry: dict[str, Any]) -> None:+ parsed = parse_log_entry(entry)+ assert isinstance(parsed, UnknownFrame)+ assert parsed.raw == entry++ def test_extra_envelope_fields_are_tolerated(self) -> None:+ entry = _notification(METHOD_USER_MESSAGE, {"content": "hi", "futureField": True})+ entry["futureEnvelopeField"] = "later"+ parsed = parse_log_entry(entry)+ assert isinstance(parsed, NotificationFrame)+ assert is_user_message_params(parsed.notification.params, parsed.notification.method)diff --git a/products/posthog_ai/backend/wire_types.py b/products/posthog_ai/backend/wire_types.pynew file mode 100644index 000000000000..c9f4f40eb194--- /dev/null+++ b/products/posthog_ai/backend/wire_types.py@@ -0,0 +1,79 @@+"""Typed views of the slice of the sandbox agent wire format the Python backend consumes.++The backend only ever reads persisted log entries (S3 NDJSON replayed via the products/tasks+``logs/`` path) — today to walk prior ``_posthog/user_message`` notifications for context+dedup on follow-ups. Live SSE frames are consumed exclusively by the frontend, where the full+contract is typed at ``frontend/src/scenes/max/types/sandboxWireTypes.ts``; keep that copy in+mind when extending this one.++The envelope is validated with tolerant pydantic models (we co-own its shape with+products/tasks); ``notification.params`` is owned by the external agent adapters, so it is+typed via TypedDict + TypeGuard and never runtime-validated outside tests — old S3 log entries+replay forever, and a parse path that raises on a historical or future shape would break+conversation loads.+"""++from typing import Any, Literal, NotRequired, TypedDict, TypeGuard++from pydantic import BaseModel, ConfigDict, ValidationError+++class AcpError(BaseModel):+ model_config = ConfigDict(extra="allow")++ code: int | None = None+ message: str | None = None+++class AcpNotificationBody(BaseModel):+ """JSON-RPC notification carried inside a ``notification`` log entry."""++ model_config = ConfigDict(extra="allow")++ jsonrpc: str | None = None+ method: str | None = None+ # Adapter-owned; narrow with the TypeGuards below instead of validating here.+ params: Any = None+ result: Any = None+ error: AcpError | None = None+++class NotificationFrame(BaseModel):+ model_config = ConfigDict(extra="allow")++ type: Literal["notification"]+ timestamp: str | None = None+ notification: AcpNotificationBody+++class UnknownFrame(BaseModel):+ """Fallback for entries this module doesn't recognize. Carries the raw payload untouched."""++ raw: dict[str, Any]+++def parse_log_entry(data: dict[str, Any]) -> NotificationFrame | UnknownFrame:+ """Classify a raw persisted log entry. Never raises — unknown or malformed entries come+ back as ``UnknownFrame`` so a single bad entry can't abort a log walk."""+ if data.get("type") != "notification":+ return UnknownFrame(raw=data)+ try:+ return NotificationFrame.model_validate(data)+ except ValidationError:+ return UnknownFrame(raw=data)+++METHOD_USER_MESSAGE = "_posthog/user_message"+++class UserMessageParams(TypedDict):+ """Params of a ``_posthog/user_message`` notification — the user's message as the+ agent-server echoed it into the log (plain string or ACP content blocks)."""++ content: NotRequired[str | list[dict[str, Any]]]+ # Carries `attached_context` — the full undeduped context recorded with the message.+ _meta: NotRequired[dict[str, Any]]+++def is_user_message_params(params: object, method: str | None) -> TypeGuard[UserMessageParams]:+ return method == METHOD_USER_MESSAGE and isinstance(params, dict)diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex f61be2d8244a..d25345f8c099 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -8,9 +8,9 @@ Responsibilities:- Stay thin and stable.This module is deliberately light: it imports the models and small helpers only. The-heavy behavioral surfaces (sandbox provisioning, the multi-turn agent machinery, temporal-workflows, max tools) live in sibling facade submodules (``sandbox``, ``agents``,-``temporal``, ``max_tools``, ``webhooks``, ``streams``, ``repo_selection``) so a+heavy behavioral surfaces (sandbox provisioning, warming, the multi-turn agent machinery,+temporal workflows, max tools) live in sibling facade submodules (``sandbox``, ``warm``,+``agents``, ``temporal``, ``max_tools``, ``webhooks``, ``streams``, ``repo_selection``) so aconfig-only importer never drags docker/temporalio onto the ``django.setup()`` path.Functions that bridge to those heavy surfaces import them lazily inside the function body."""@@ -105,6 +105,7 @@ __all__ = ["create_sandbox_environment","create_task","create_task_automation",+ "create_task_without_run","create_task_run_connection_token","claim_and_fail_stale_run","delete_sandbox_environment",@@ -114,6 +115,7 @@ __all__ = ["finalize_task_staged_artifacts","get_code_home","get_code_workflow_config",+ "get_conversation_task_dtos","get_latest_pr_url_by_task","get_latest_run_by_task","get_sandbox_environment",@@ -155,6 +157,7 @@ __all__ = ["save_code_workflow_bindings","send_cancel","send_user_message",+ "select_repository_for_message","set_task_run_output","signal_report_queryset","signal_task_run_user_message",@@ -325,14 +328,21 @@ def _task_run_detail_to_dto(run: TaskRun) -> contracts.TaskRunDetailDTO:)-def _task_detail_to_dto(task: Task) -> contracts.TaskDetailDTO:+def _task_detail_to_dto(task: Task, *, include_latest_run: bool = True) -> contracts.TaskDetailDTO:"""Map a ``Task`` to its HTTP detail DTO.Mirrors ``TaskSerializer`` output exactly. ``latest_run`` is the task's most-recent run(by ``created_at``) mapped to a ``TaskRunDetailDTO``; pass a queryset that has``prefetch_related("runs")`` and ``select_related("created_by")`` to avoid N+1s.+ Set ``include_latest_run=False`` for consumers that render the task envelope without+ nested run details."""- latest_run = task.latest_run+ latest_run = task.latest_run if include_latest_run else None+ # Prefer a cheap `_latest_run_id` subquery annotation (conversation envelope); otherwise derive+ # it from a populated nested run so the id is always consistent with `latest_run`.+ latest_run_id = getattr(task, "_latest_run_id", None)+ if latest_run_id is None and latest_run is not None:+ latest_run_id = latest_run.idreturn contracts.TaskDetailDTO(id=task.id,task_number=task.task_number,@@ -354,6 +364,7 @@ def _task_detail_to_dto(task: Task) -> contracts.TaskDetailDTO:created_at=task.created_at,updated_at=task.updated_at,created_by=_user_basic_info(task.created_by if task.created_by_id else None),+ latest_run_id=latest_run_id,)@@ -610,6 +621,31 @@ def create_and_run_task()+def create_task_without_run(+ *,+ team,+ user_id: int,+ origin_product: "Task.OriginProduct",+ title: str = "",+ description: str = "",+ repository: str | None = None,+) -> UUID:+ """Create a Task row with no initial run, returning its id.++ For callers that own run creation themselves — e.g. the sandbox warm path, which boots the first+ run via the warming facade. ``team`` is a core ``posthog.Team`` (not a tasks model).+ """+ task = Task.create_without_run(+ team=team,+ title=title,+ description=description,+ origin_product=origin_product,+ user_id=user_id,+ repository=repository,+ )+ return task.id++def create_run(task_id: str | UUID,*,@@ -2273,6 +2309,31 @@ def get_task_detail(return _task_detail_to_dto(task) if task is not None else None+def get_conversation_task_dtos(task_ids: Sequence[str | UUID], team_id: int) -> dict[UUID, contracts.TaskDetailDTO]:+ """Task payloads for the Max conversation API, keyed by task id.++ Intentionally team-scoped, with no ``task_visibility_q(user_id)`` gate: the conversation is the+ read-share unit, so anyone who can ``retrieve`` a conversation may read its backing task. Broad+ read here does not grant action — write/send to a task stays creator-gated in the conversation+ viewset (``create``/``open``/``queue``) and at bind time (``validate_task_id``). Direct task reads+ (``get_task_detail``) gate by creator because that is the task-enumeration path; this one is not.++ ``latest_run`` (the nested run payload) stays excluded so conversation lists never presign per-row+ log URLs; instead a single ``latest_run_id`` subquery carries the latest run id, which the frontend+ needs to reconnect to sandbox logs.+ """+ if not task_ids:+ return {}++ latest_run_id_sq = TaskRun.objects.filter(task=OuterRef("pk")).order_by("-created_at", "-id").values("id")[:1]+ tasks = (+ Task.objects.filter(team_id=team_id, id__in=task_ids)+ .select_related("created_by", "team")+ .annotate(_latest_run_id=Subquery(latest_run_id_sq))+ )+ return {task.id: _task_detail_to_dto(task, include_latest_run=False) for task in tasks}++def task_visible(task_id: str | UUID, team_id: int, user_id: int | None) -> bool:"""Whether a non-deleted task exists for the team and is visible to the user.@@ -2283,6 +2344,21 @@ def task_visible(task_id: str | UUID, team_id: int, user_id: int | None) -> boolreturn _visible_task_qs(team_id, user_id).filter(id=task_id).exists()+async def select_repository_for_message(team_id: int, user_id: int, message: str, *, origin_product: str) -> str | None:+ """Pick the repository a free-form chat message is most likely about.++ Kept as a lazy facade wrapper so API importers do not load the repo-selection agent or+ sandbox/Temporal dependencies on their request import path.+ """+ from products.tasks.backend.logic.repo_selection.cascade import ( # noqa: PLC0415 — keeps repo-selection agent imports lazy+ select_repository_for_message as select_repository_for_message_impl,+ )++ return await select_repository_for_message_impl(+ team_id, user_id, message, origin_product=Task.OriginProduct(origin_product)+ )++def list_tasks(team_id: int, user_id: int | None, *, filters: dict, is_debug_or_staff: bool) -> list[contracts.TaskDetailDTO]:diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex 21b764d825f7..7f5fcbf22a3d 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -10,8 +10,9 @@ with runtime validation on construction) so a malformed mapper surfaces aBehavioral/wiring surfaces (sandbox classes, the multi-turn agent machinery, temporalworkflows, max tools, webhook handlers) are NOT data and are not modelled here — they-are re-exported as objects through the sibling facade submodules (``sandbox``,-``agents``, ``temporal``, ``max_tools``, ``webhooks``, …).+cross the boundary through sibling facade submodules (``sandbox``, ``warm``,+``agents``, ``temporal``, ``max_tools``, ``webhooks``, …), with DTOs here only for+their data results."""from datetime import datetime@@ -73,6 +74,16 @@ class TaskRunDTO:pr_url: str | None = None+@dataclass(frozen=True)+class WarmRunDTO:+ """Outcome of ensuring a warm sandbox run exists for a task."""++ task_id: UUID+ run_id: UUID+ run_status: str+ just_created: bool++@dataclass(frozen=True)class TaskDetailDTO:"""The HTTP detail representation of a task.@@ -81,7 +92,9 @@ class TaskDetailDTO:``github_user_integration`` are the integration primary keys (or ``None``), matching theoriginal ``PrimaryKeyRelatedField`` output. ``signal_report`` is the linked report id (or``None``). ``latest_run`` is the most-recent run as a ``TaskRunDetailDTO`` (or ``None``).- ``created_by`` mirrors core ``UserBasicSerializer`` output.+ ``latest_run_id`` carries just that run's id for the conversation envelope, which needs the id+ to reconnect to sandbox logs but not the full (presigned-log) run payload. ``created_by``+ mirrors core ``UserBasicSerializer`` output."""id: UUID@@ -104,6 +117,7 @@ class TaskDetailDTO:created_at: datetime | None = Noneupdated_at: datetime | None = Nonecreated_by: "TaskUserBasicInfo | None" = None+ latest_run_id: UUID | None = None@dataclass(frozen=True)diff --git a/products/tasks/backend/facade/run_config.py b/products/tasks/backend/facade/run_config.pyindex 17b3edb9fe47..a6b04d670cdc 100644--- a/products/tasks/backend/facade/run_config.py+++ b/products/tasks/backend/facade/run_config.py@@ -14,6 +14,7 @@ from products.tasks.backend.constants import (ALL_INITIAL_PERMISSION_MODE_CHOICES,CODEX_INITIAL_PERMISSION_MODE_CHOICES,INITIAL_PERMISSION_MODE_CHOICES,+ InitialPermissionMode,)from products.tasks.backend.temporal.process_task.utils import (PUBLIC_REASONING_EFFORTS,@@ -32,6 +33,7 @@ __all__ = ["ALL_INITIAL_PERMISSION_MODE_CHOICES","CODEX_INITIAL_PERMISSION_MODE_CHOICES","INITIAL_PERMISSION_MODE_CHOICES",+ "InitialPermissionMode","PUBLIC_REASONING_EFFORTS","GitHubCredentialSource","LLMProvider",diff --git a/products/tasks/backend/facade/warm.py b/products/tasks/backend/facade/warm.pynew file mode 100644index 000000000000..8a24a4f65b49--- /dev/null+++ b/products/tasks/backend/facade/warm.py@@ -0,0 +1,63 @@+"""+Function facade for sandbox warming.++Callers decide when to warm and own their product-specific Task linkage, while+products/tasks owns quota checks, warm-pool capacity, Run creation, and workflow+dispatch. The boundary is function-shaped and returns DTOs, so callers do not+instantiate internal service classes or receive ORM models.+"""++from typing import Any+from uuid import UUID++from posthog.models.team import Team+from posthog.models.user import User++from products.tasks.backend.facade import contracts+from products.tasks.backend.logic.services.warm import SandboxWarmer, WarmResult+from products.tasks.backend.models import Task++__all__ = [+ "enforce_warm_quota",+ "warm_pool_at_capacity",+ "warm_task_run",+]+++def _team_and_user(team_id: int, user_id: int) -> tuple[Team, User]:+ return Team.objects.get(pk=team_id), User.objects.get(pk=user_id)+++def _warm_result_to_dto(result: WarmResult) -> contracts.WarmRunDTO:+ return contracts.WarmRunDTO(+ task_id=result.run.task_id,+ run_id=result.run.id,+ run_status=result.run.status,+ just_created=result.just_created,+ )+++def enforce_warm_quota(origin_product: str, team_id: int, user_id: int) -> None:+ """Raise if the team may not warm a sandbox run for the origin product."""+ team, user = _team_and_user(team_id, user_id)+ SandboxWarmer.enforce_quota(origin_product, team, user)+++def warm_pool_at_capacity(origin_product: str, team_id: int, user_id: int) -> bool:+ """Whether the user or organization already holds the max concurrent warm runs."""+ team, user = _team_and_user(team_id, user_id)+ return SandboxWarmer.at_capacity(origin_product, team, user)+++def warm_task_run(+ task_id: str | UUID,+ team_id: int,+ user_id: int,+ *,+ mode: str = "interactive",+ extra_state: dict[str, Any] | None = None,+) -> contracts.WarmRunDTO:+ """Idempotently ensure a task has a warm run and return the run handle as a DTO."""+ task = Task.objects.select_related("team").get(id=task_id, team_id=team_id)+ user = User.objects.get(pk=user_id)+ return _warm_result_to_dto(SandboxWarmer(task, user=user).warm(mode=mode, extra_state=extra_state))diff --git a/products/tasks/backend/logic/services/warm.py b/products/tasks/backend/logic/services/warm.pyindex 16053cb774c7..0e7fcb74f463 100644--- a/products/tasks/backend/logic/services/warm.py+++ b/products/tasks/backend/logic/services/warm.py@@ -7,9 +7,9 @@ quota gate and a warm-pool concurrency cap — live here so every product warmsone implementation rather than reimplementing provisioning, quota, and idempotency.The trigger (when to warm) and Task ownership (birth + linking to the product's own-entity) stay per-product: ``SandboxWarmer`` operates on an *existing* Task. PostHog AI's-prewarm is the only caller today; the registries below are fail-closed, so a product-must opt in with a quota gate before it can warm.+entity) stay per-product: ``SandboxWarmer`` operates on an *existing* Task behind the+warming facade. The registries below are fail-closed, so a product must opt in with a+quota gate before it can warm."""from collections.abc import Callablediff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 56f0c10cee3f..31b7224c783e 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -495,7 +495,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):"""Create the Task row without an initial run or workflow.For callers that own run creation themselves — e.g. the sandbox warm path- (`products/tasks/backend/services/warm.py`), which creates the first run with its+ (`products/tasks/backend/logic/services/warm.py`), which creates the first run with itsown state. The run `extra_state` assembled by `_build_task` is discarded here."""task, _ = Task._build_task(diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 4f6fdf4ed04a..efaa31692a10 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -15,6 +15,7 @@ from posthog.models.user import Userfrom products.tasks.backend.facade import (api as facade,contracts,+ warm as warm_facade,)from products.tasks.backend.models import SandboxEnvironment, Task, TaskRun@@ -130,6 +131,64 @@ class TestFacadeReadsAndMappers(TestCase):self.assertEqual(facade.get_latest_pr_url_by_task([]), {})+ def test_get_conversation_task_dtos_carries_latest_run_id_not_nested_run(self):+ task = self._make_task(title="Conversation task")+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)+ latest = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)+ other_team = Team.objects.create(organization=self.organization, name="Other team")++ dtos = facade.get_conversation_task_dtos([task.id], self.team.id)++ self.assertEqual(set(dtos.keys()), {task.id})+ dto = dtos[task.id]+ self.assertIsInstance(dto, contracts.TaskDetailDTO)+ self.assertEqual(dto.id, task.id)+ self.assertEqual(dto.title, "Conversation task")+ # The nested run payload stays excluded (no presigned log URLs); only the id is carried.+ self.assertIsNone(dto.latest_run)+ self.assertEqual(dto.latest_run_id, latest.id)+ self.assertEqual(facade.get_conversation_task_dtos([task.id], other_team.id), {})++ def test_get_conversation_task_dtos_latest_run_id_none_without_runs(self):+ task = self._make_task(title="No runs")++ dto = facade.get_conversation_task_dtos([task.id], self.team.id)[task.id]++ self.assertIsNone(dto.latest_run_id)++ def test_get_conversation_task_dtos_is_cheap_for_many_tasks(self):+ tasks = [self._make_task(title=f"task-{i}") for i in range(5)]+ for task in tasks:+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)++ # A single query with the latest-run-id subquery — no per-task run lookup, no N+1.+ with self.assertNumQueries(1):+ dtos = facade.get_conversation_task_dtos([t.id for t in tasks], self.team.id)+ for task in tasks:+ self.assertIsNotNone(dtos[task.id].latest_run_id)++ @patch("products.tasks.backend.logic.services.warm.execute_task_processing_workflow")+ @patch("products.tasks.backend.logic.services.warm.is_team_limited", return_value=False)+ def test_warm_task_run_returns_contract(self, _mock_quota, mock_workflow):+ task = self._make_task(origin_product=Task.OriginProduct.POSTHOG_AI)++ with self.captureOnCommitCallbacks(execute=True):+ dto = warm_facade.warm_task_run(+ task.id,+ self.team.id,+ self.user.id,+ extra_state={"systemPrompt": {"type": "preset"}},+ )++ self.assertIsInstance(dto, contracts.WarmRunDTO)+ self.assertEqual(dto.task_id, task.id)+ self.assertTrue(dto.just_created)++ run = TaskRun.objects.get(id=dto.run_id)+ self.assertEqual(dto.run_status, run.status)+ self.assertEqual(run.state["systemPrompt"], {"type": "preset"})+ mock_workflow.assert_called_once()+def test_stale_queued_and_fail(self):task = self._make_task()fresh = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex c69d90749289..8138cf9d6164 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -53,7 +53,7 @@ export interface TaskRunErrorResponseApi {export type TaskUserBasicInfoApiHedgehogConfig = { [key: string]: unknown } | null/**- * Response shape for a `created_by` user — mirrors core `UserBasicSerializer` output.+ * Response shape for a task creator, mirroring core ``UserBasicSerializer`` output.*/export interface TaskUserBasicInfoApi {id: number@@ -296,143 +296,18 @@ export interface PatchedTaskAutomationWriteApi {enabled?: boolean}-/**- * * `claude` - claude- * * `codex` - codex- */-export type RuntimeAdapterEnumApi = (typeof RuntimeAdapterEnumApi)[keyof typeof RuntimeAdapterEnumApi]--export const RuntimeAdapterEnumApi = {- Claude: 'claude',- Codex: 'codex',-} as const--/**- * * `anthropic` - anthropic- * * `openai` - openai- */-export type TaskRunDetailDTOProviderEnumApi =- (typeof TaskRunDetailDTOProviderEnumApi)[keyof typeof TaskRunDetailDTOProviderEnumApi]--export const TaskRunDetailDTOProviderEnumApi = {- Anthropic: 'anthropic',- Openai: 'openai',-} as const--/**- * * `low` - low- * * `medium` - medium- * * `high` - high- * * `xhigh` - xhigh- * * `max` - max- */-export type ReasoningEffortEnumApi = (typeof ReasoningEffortEnumApi)[keyof typeof ReasoningEffortEnumApi]--export const ReasoningEffortEnumApi = {- Low: 'low',- Medium: 'medium',- High: 'high',- Xhigh: 'xhigh',- Max: 'max',-} as const--export interface TaskRunArtifactResponseApi {- /** Stable identifier for the artifact within this run */- id?: string- /** Artifact file name */- name: string- /** Artifact classification (plan, context, etc.) */- type: string- /** Source of the artifact, such as agent_output or user_attachment */- source?: string- /** Artifact size in bytes */- size?: number- /** Optional MIME type */- content_type?: string- /** S3 object key for the artifact */- storage_path: string- /** Timestamp when the artifact was uploaded */- uploaded_at: string-}--/**- * @nullable- */-export type TaskRunDetailDTOApiOutput = { [key: string]: unknown } | null--export type TaskRunDetailDTOApiState = { [key: string]: unknown }--/**- * Detail response for a task run.- *- * Reads from a frozen ``TaskRunDetailDTO`` produced by the facade mapper (which computes the- * presigned ``log_url`` and parses ``runtime_adapter`` / ``provider`` / ``model`` /- * ``reasoning_effort`` off the run state). ``task`` is the parent task id. Reused as the nested- * ``latest_run`` shape by the task detail response.- */-export interface TaskRunDetailDTOApi {- id: string- /** Parent task id this run belongs to. */- task: string- /** @nullable */- stage: string | null- /** @nullable */- branch: string | null- status: string- environment: string- /** Configured runtime adapter for this run, such as 'claude' or 'codex'.- *- * * `claude` - claude- * * `codex` - codex */- runtime_adapter?: RuntimeAdapterEnumApi | null- /** Configured LLM provider for this run, such as 'anthropic' or 'openai'.- *- * * `anthropic` - anthropic- * * `openai` - openai */- provider?: TaskRunDetailDTOProviderEnumApi | null- /**- * Configured LLM model identifier for this run.- * @nullable- */- model?: string | null- /** Configured reasoning effort for this run when the selected model supports it.- *- * * `low` - low- * * `medium` - medium- * * `high` - high- * * `xhigh` - xhigh- * * `max` - max */- reasoning_effort?: ReasoningEffortEnumApi | null- /**- * Presigned S3 URL for log access (valid for 1 hour).- * @nullable- */- log_url?: string | null- /** @nullable */- error_message: string | null- /** @nullable */- output: TaskRunDetailDTOApiOutput- state: TaskRunDetailDTOApiState- readonly artifacts: readonly TaskRunArtifactResponseApi[]- /** @nullable */- created_at?: string | null- /** @nullable */- updated_at?: string | null- /** @nullable */- completed_at?: string | null-}-/*** @nullable*/export type TaskDetailDTOApiJsonSchema = { [key: string]: unknown } | null/**- * Detail response for a task.+ * Conversation envelope variant: ``latest_run`` is just the latest run's id, not the nested+ * run detail. The frontend only needs the id to reconnect to sandbox logs, and emitting the id+ * avoids presigning a log URL per conversation.*- * Reads from a frozen ``TaskDetailDTO`` produced by the facade. ``github_integration`` /- * ``github_user_integration`` are integration ids, ``signal_report`` is the report id, and- * ``latest_run`` nests the run-detail shape. ``created_by`` mirrors core ``UserBasicSerializer``.+ * Read access here follows the conversation (the share-by-link unit), not per-creator task+ * visibility — write/send stays creator-gated. See ``tasks_facade.get_conversation_task_dtos``.*/export interface TaskDetailDTOApi {id: string@@ -457,8 +332,11 @@ export interface TaskDetailDTOApi {archived: boolean/** @nullable */archived_at: string | null- /** Latest run details for this task */- latest_run?: TaskRunDetailDTOApi | null+ /**+ * Id of the latest TaskRun; null when the task has no runs.+ * @nullable+ */+ readonly latest_run: string | null/** @nullable */created_at?: string | null/** @nullable */@@ -705,6 +583,23 @@ export const ClaudeRuntimeAdapterEnumApi = {Claude: 'claude',} as const+/**+ * * `low` - low+ * * `medium` - medium+ * * `high` - high+ * * `xhigh` - xhigh+ * * `max` - max+ */+export type ReasoningEffortEnumApi = (typeof ReasoningEffortEnumApi)[keyof typeof ReasoningEffortEnumApi]++export const ReasoningEffortEnumApi = {+ Low: 'low',+ Medium: 'medium',+ High: 'high',+ Xhigh: 'xhigh',+ Max: 'max',+} as const+/*** * `default` - default* * `acceptEdits` - acceptEdits@@ -712,10 +607,10 @@ export const ClaudeRuntimeAdapterEnumApi = {* * `bypassPermissions` - bypassPermissions* * `auto` - auto*/-export type ClaudeTaskRunCreateSchemaInitialPermissionModeEnumApi =- (typeof ClaudeTaskRunCreateSchemaInitialPermissionModeEnumApi)[keyof typeof ClaudeTaskRunCreateSchemaInitialPermissionModeEnumApi]+export type InitialPermissionModeEnumApi =+ (typeof InitialPermissionModeEnumApi)[keyof typeof InitialPermissionModeEnumApi]-export const ClaudeTaskRunCreateSchemaInitialPermissionModeEnumApi = {+export const InitialPermissionModeEnumApi = {Default: 'default',AcceptEdits: 'acceptEdits',Plan: 'plan',@@ -784,7 +679,7 @@ export interface ClaudeTaskRunCreateSchemaApi {* * `plan` - plan* * `bypassPermissions` - bypassPermissions* * `auto` - auto */- initial_permission_mode?: ClaudeTaskRunCreateSchemaInitialPermissionModeEnumApi+ initial_permission_mode?: InitialPermissionModeEnumApi}/**@@ -972,6 +867,25 @@ export interface TaskStagedArtifactsFinalizeUploadRequestApi {artifacts: TaskStagedArtifactFinalizeUploadApi[]}+export interface TaskRunArtifactResponseApi {+ /** Stable identifier for the artifact within this run */+ id?: string+ /** Artifact file name */+ name: string+ /** Artifact classification (plan, context, etc.) */+ type: string+ /** Source of the artifact, such as agent_output or user_attachment */+ source?: string+ /** Artifact size in bytes */+ size?: number+ /** Optional MIME type */+ content_type?: string+ /** S3 object key for the artifact */+ storage_path: string+ /** Timestamp when the artifact was uploaded */+ uploaded_at: string+}+export interface TaskStagedArtifactsFinalizeUploadResponseApi {/** Finalized staged artifacts available for attachment to a new run */artifacts: TaskRunArtifactResponseApi[]@@ -1054,6 +968,96 @@ export interface TaskStagedArtifactsPrepareUploadResponseApi {artifacts: TaskStagedArtifactPrepareUploadResponseApi[]}+/**+ * * `claude` - claude+ * * `codex` - codex+ */+export type RuntimeAdapterEnumApi = (typeof RuntimeAdapterEnumApi)[keyof typeof RuntimeAdapterEnumApi]++export const RuntimeAdapterEnumApi = {+ Claude: 'claude',+ Codex: 'codex',+} as const++/**+ * * `anthropic` - anthropic+ * * `openai` - openai+ */+export type TaskRunDetailDTOProviderEnumApi =+ (typeof TaskRunDetailDTOProviderEnumApi)[keyof typeof TaskRunDetailDTOProviderEnumApi]++export const TaskRunDetailDTOProviderEnumApi = {+ Anthropic: 'anthropic',+ Openai: 'openai',+} as const++/**+ * @nullable+ */+export type TaskRunDetailDTOApiOutput = { [key: string]: unknown } | null++export type TaskRunDetailDTOApiState = { [key: string]: unknown }++/**+ * Detail response for a task run.+ *+ * Reads from a frozen ``TaskRunDetailDTO`` produced by the facade mapper (which computes the+ * presigned ``log_url`` and parses ``runtime_adapter`` / ``provider`` / ``model`` /+ * ``reasoning_effort`` off the run state). ``task`` is the parent task id. Reused as the nested+ * ``latest_run`` shape by the task detail response.+ */+export interface TaskRunDetailDTOApi {+ id: string+ /** Parent task id this run belongs to. */+ task: string+ /** @nullable */+ stage: string | null+ /** @nullable */+ branch: string | null+ status: string+ environment: string+ /** Configured runtime adapter for this run, such as 'claude' or 'codex'.+ *+ * * `claude` - claude+ * * `codex` - codex */+ runtime_adapter?: RuntimeAdapterEnumApi | null+ /** Configured LLM provider for this run, such as 'anthropic' or 'openai'.+ *+ * * `anthropic` - anthropic+ * * `openai` - openai */+ provider?: TaskRunDetailDTOProviderEnumApi | null+ /**+ * Configured LLM model identifier for this run.+ * @nullable+ */+ model?: string | null+ /** Configured reasoning effort for this run when the selected model supports it.+ *+ * * `low` - low+ * * `medium` - medium+ * * `high` - high+ * * `xhigh` - xhigh+ * * `max` - max */+ reasoning_effort?: ReasoningEffortEnumApi | null+ /**+ * Presigned S3 URL for log access (valid for 1 hour).+ * @nullable+ */+ log_url?: string | null+ /** @nullable */+ error_message: string | null+ /** @nullable */+ output: TaskRunDetailDTOApiOutput+ state: TaskRunDetailDTOApiState+ readonly artifacts: readonly TaskRunArtifactResponseApi[]+ /** @nullable */+ created_at?: string | null+ /** @nullable */+ updated_at?: string | null+ /** @nullable */+ completed_at?: string | null+}+export interface PaginatedTaskRunDetailDTOListApi {count: number/** @nullable */diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1ff9e117dac6..b48dcf3e8256 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8467,6 +8467,18 @@ export namespace Schemas {resolved_natives: string[];}+ /**+ * * `langgraph` - LangGraph+ * * `sandbox` - Sandbox+ */+ export type AgentRuntimeEnum = typeof AgentRuntimeEnum[keyof typeof AgentRuntimeEnum];+++ export const AgentRuntimeEnum = {+ Langgraph: 'langgraph',+ Sandbox: 'sandbox',+ } as const;+export interface AgentTableHeader {/** Table name. */name: string;@@ -12302,10 +12314,10 @@ export namespace Schemas {* * `bypassPermissions` - bypassPermissions* * `auto` - auto*/- export type ClaudeTaskRunCreateSchemaInitialPermissionModeEnum = typeof ClaudeTaskRunCreateSchemaInitialPermissionModeEnum[keyof typeof ClaudeTaskRunCreateSchemaInitialPermissionModeEnum];+ export type InitialPermissionModeEnum = typeof InitialPermissionModeEnum[keyof typeof InitialPermissionModeEnum];- export const ClaudeTaskRunCreateSchemaInitialPermissionModeEnum = {+ export const InitialPermissionModeEnum = {Default: 'default',AcceptEdits: 'acceptEdits',Plan: 'plan',@@ -12374,7 +12386,7 @@ export namespace Schemas {* * `plan` - plan* * `bypassPermissions` - bypassPermissions* * `auto` - auto */- initial_permission_mode?: ClaudeTaskRunCreateSchemaInitialPermissionModeEnum;+ initial_permission_mode?: InitialPermissionModeEnum;}export type ClickhouseEventProperties = { [key: string]: unknown };@@ -13145,6 +13157,79 @@ export namespace Schemas {Slack: 'slack',} as const;+ /**+ * @nullable+ */+ export type TaskUserBasicInfoHedgehogConfig = { [key: string]: unknown } | null;++ /**+ * Response shape for a task creator, mirroring core ``UserBasicSerializer`` output.+ */+ export interface TaskUserBasicInfo {+ id: number;+ uuid: string;+ distinct_id: string;+ first_name: string;+ last_name: string;+ email: string;+ /** @nullable */+ is_email_verified?: boolean | null;+ /** @nullable */+ hedgehog_config?: TaskUserBasicInfoHedgehogConfig;+ /** @nullable */+ role_at_organization?: string | null;+ }++ /**+ * @nullable+ */+ export type TaskDetailDTOJsonSchema = { [key: string]: unknown } | null;++ /**+ * Conversation envelope variant: ``latest_run`` is just the latest run's id, not the nested+ * run detail. The frontend only needs the id to reconnect to sandbox logs, and emitting the id+ * avoids presigning a log URL per conversation.+ *+ * Read access here follows the conversation (the share-by-link unit), not per-creator task+ * visibility — write/send stays creator-gated. See ``tasks_facade.get_conversation_task_dtos``.+ */+ export interface TaskDetailDTO {+ id: string;+ /** @nullable */+ task_number: number | null;+ slug: string;+ title: string;+ title_manually_set: boolean;+ description: string;+ origin_product: string;+ /** @nullable */+ repository: string | null;+ /** @nullable */+ github_integration: number | null;+ /** @nullable */+ github_user_integration: string | null;+ /** @nullable */+ signal_report: string | null;+ /** @nullable */+ json_schema: TaskDetailDTOJsonSchema;+ internal: boolean;+ archived: boolean;+ /** @nullable */+ archived_at: string | null;+ /**+ * Id of the latest TaskRun; null when the task has no runs.+ * @nullable+ */+ readonly latest_run: string | null;+ /** @nullable */+ created_at?: string | null;+ /** @nullable */+ updated_at?: string | null;+ created_by?: TaskUserBasicInfo | null;+ /** @nullable */+ ci_prompt: string | null;+ }+export interface Conversation {readonly id: string;readonly status: ConversationStatus;@@ -13190,12 +13275,18 @@ 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`.+ *+ * * `langgraph` - LangGraph+ * * `sandbox` - Sandbox */+ readonly agent_runtime: AgentRuntimeEnum;readonly is_sandbox: boolean;/** Return pending approval cards as structured data.** Combines metadata from conversation.approval_decisions with payload from checkpoint* interrupts (single source of truth for payload data). */readonly pending_approvals: readonly ConversationPendingApprovalsItem[];+ readonly task: TaskDetailDTO | null;}export interface ConversationMinimal {@@ -13239,6 +13330,7 @@ export namespace Schemas {* @nullable*/readonly slack_workspace_domain: string | null;+ readonly task: TaskDetailDTO | null;}export interface ConversionGoalSummary {@@ -31076,29 +31168,6 @@ export namespace Schemas {results: Run[];}- /**- * @nullable- */- export type TaskUserBasicInfoHedgehogConfig = { [key: string]: unknown } | null;-- /**- * Response shape for a `created_by` user — mirrors core `UserBasicSerializer` output.- */- export interface TaskUserBasicInfo {- id: number;- uuid: string;- distinct_id: string;- first_name: string;- last_name: string;- email: string;- /** @nullable */- is_email_verified?: boolean | null;- /** @nullable */- hedgehog_config?: TaskUserBasicInfoHedgehogConfig;- /** @nullable */- role_at_organization?: string | null;- }-/*** List response for sandbox environments (subset of fields).*/@@ -32454,6 +32523,15 @@ export namespace Schemas {results: TaskAutomationDTO[];}+ export interface PaginatedTaskDetailDTOList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: TaskDetailDTO[];+ }+/*** * `claude` - claude* * `codex` - codex@@ -32564,61 +32642,6 @@ export namespace Schemas {completed_at?: string | null;}- /**- * @nullable- */- export type TaskDetailDTOJsonSchema = { [key: string]: unknown } | null;-- /**- * Detail response for a task.- *- * Reads from a frozen ``TaskDetailDTO`` produced by the facade. ``github_integration`` /- * ``github_user_integration`` are integration ids, ``signal_report`` is the report id, and- * ``latest_run`` nests the run-detail shape. ``created_by`` mirrors core ``UserBasicSerializer``.- */- export interface TaskDetailDTO {- id: string;- /** @nullable */- task_number: number | null;- slug: string;- title: string;- title_manually_set: boolean;- description: string;- origin_product: string;- /** @nullable */- repository: string | null;- /** @nullable */- github_integration: number | null;- /** @nullable */- github_user_integration: string | null;- /** @nullable */- signal_report: string | null;- /** @nullable */- json_schema: TaskDetailDTOJsonSchema;- internal: boolean;- archived: boolean;- /** @nullable */- archived_at: string | null;- /** Latest run details for this task */- latest_run?: TaskRunDetailDTO | null;- /** @nullable */- created_at?: string | null;- /** @nullable */- updated_at?: string | null;- created_by?: TaskUserBasicInfo | null;- /** @nullable */- ci_prompt: string | null;- }-- export interface PaginatedTaskDetailDTOList {- count: number;- /** @nullable */- next?: string | null;- /** @nullable */- previous?: string | null;- results: TaskDetailDTO[];- }-export interface PaginatedTaskRunDetailDTOList {count: number;/** @nullable */@@ -34460,12 +34483,18 @@ 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`.+ *+ * * `langgraph` - LangGraph+ * * `sandbox` - Sandbox */+ readonly agent_runtime?: AgentRuntimeEnum;readonly is_sandbox?: boolean;/** Return pending approval cards as structured data.** Combines metadata from conversation.approval_decisions with payload from checkpoint* interrupts (single source of truth for payload data). */readonly pending_approvals?: readonly PatchedConversationPendingApprovalsItem[];+ readonly task?: TaskDetailDTO | null;}export interface PatchedCoreEvent {@@ -44912,6 +44941,53 @@ export namespace Schemas {fields: S3PresignedPostFields;}+ /**+ * * `action` - action+ * * `dashboard` - dashboard+ * * `error_tracking_issue` - error_tracking_issue+ * * `evaluation` - evaluation+ * * `event` - event+ * * `insight` - insight+ * * `notebook` - notebook+ * * `text` - text+ */+ export type SandboxAttachedContextItemTypeEnum = typeof SandboxAttachedContextItemTypeEnum[keyof typeof SandboxAttachedContextItemTypeEnum];+++ export const SandboxAttachedContextItemTypeEnum = {+ Action: 'action',+ Dashboard: 'dashboard',+ ErrorTrackingIssue: 'error_tracking_issue',+ Evaluation: 'evaluation',+ Event: 'event',+ Insight: 'insight',+ Notebook: 'notebook',+ Text: 'text',+ } as const;++ /**+ * One typed attachment carried by a sandbox message.+ */+ export interface SandboxAttachedContextItem {+ /** Attachment kind. Entity types carry `id` (+ optional `name`); `text` carries `value`.+ *+ * * `action` - action+ * * `dashboard` - dashboard+ * * `error_tracking_issue` - error_tracking_issue+ * * `evaluation` - evaluation+ * * `event` - event+ * * `insight` - insight+ * * `notebook` - notebook+ * * `text` - text */+ type: SandboxAttachedContextItemTypeEnum;+ /** Entity identifier — integer for `dashboard`/`action`, string short_id/UUID otherwise. Absent for `text`. */+ id?: unknown;+ /** Optional human-readable label rendered in the context block. */+ name?: string;+ /** Free-text content. Only for `text` attachments. */+ value?: string;+ }+/*** Request body for creating or updating a sandbox environment.*/@@ -44945,6 +45021,52 @@ export namespace Schemas {private?: boolean;}+ /**+ * Response for `POST /conversations/{id}/open/` — the IDs the frontend opens SSE against.+ */+ export interface SandboxMessageResponse {+ /** The products/tasks Task backing the conversation. */+ task_id: string;+ /** The Run the frontend opens SSE against. */+ run_id: string;+ /**+ * Echo of the request trace id, if provided.+ * @nullable+ */+ trace_id: string | null;+ /** Current status of the targeted Run (e.g. `queued`, `in_progress`). */+ run_status: string;+ /** True when a new Run was created (first message, terminal resume, or fresh warm); false for an in-progress follow-up or a reused warm Run. */+ just_created_run: boolean;+ }++ /**+ * Request body for `POST /conversations/{id}/open/`. A string `content` processes a turn; a+ * null/absent `content` warms a sandbox that idles awaiting the first message.+ */+ export interface SandboxOpen {+ /**+ * The user's message text. Omit or null to warm a sandbox (boot + idle) ahead of the first message.+ * @maxLength 40000+ * @nullable+ */+ content?: string | null;+ /** Client-generated trace id correlated with the resulting Run's SSE stream. */+ trace_id?: string;+ /** Typed PostHog entities (and free text) attached to this message. */+ attached_context?: SandboxAttachedContextItem[];+ /** Initial permission mode for the sandbox agent session. Defaults to `auto`, which allows safe tool use while preserving explicit confirmations.+ *+ * * `default` - default+ * * `acceptEdits` - acceptEdits+ * * `plan` - plan+ * * `bypassPermissions` - bypassPermissions+ * * `auto` - auto */+ initial_permission_mode?: InitialPermissionModeEnum;+ /** Bind a brand-new sandbox conversation to an existing Task so the first message resumes that Task's run. Honored only when this request creates the conversation row; ignored for an already-existing conversation. */+ task_id?: string;+ }+export interface SavedHeatmapListResponse {results: HeatmapScreenshotResponse[];/** Total number of saved heatmaps matching the filters. */diff --git a/tach.toml b/tach.tomlindex 2a774a8189d7..1050a5e91d6a 100644--- a/tach.toml+++ b/tach.toml@@ -466,6 +466,7 @@ depends_on = ["products.event_definitions","products.ai_observability","products.logs",+ "products.tasks",]layer = "modules"