: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
fix(business-knowledge): remember earlier playground messages (#114049)
Alex V8eeb3cb7ef4d
diff --git a/products/business_knowledge/backend/migrations/0022_playground_chat_sandbox_task.py b/products/business_knowledge/backend/migrations/0022_playground_chat_sandbox_task.pynew file mode 100644index 000000000000..db493bfa8bd2--- /dev/null+++ b/products/business_knowledge/backend/migrations/0022_playground_chat_sandbox_task.py@@ -0,0 +1,24 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("business_knowledge", "0021_teambusinessknowledgeconfig_github_repos"),+ ]++ operations = [+ migrations.AddField(+ model_name="playgroundchat",+ name="task_id",+ field=models.UUIDField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="playgroundturn",+ name="run_id",+ field=models.UUIDField(blank=True, null=True),+ ),+ migrations.RemoveConstraint(+ model_name="playgroundturn",+ name="bk_pg_turn_task_id",+ ),+ ]diff --git a/products/business_knowledge/backend/migrations/max_migration.txt b/products/business_knowledge/backend/migrations/max_migration.txtindex 388458427ef5..ccdc8236269b 100644--- a/products/business_knowledge/backend/migrations/max_migration.txt+++ b/products/business_knowledge/backend/migrations/max_migration.txt@@ -1 +1 @@-0021_teambusinessknowledgeconfig_github_repos+0022_playground_chat_sandbox_taskdiff --git a/products/business_knowledge/backend/models/playground_chat.py b/products/business_knowledge/backend/models/playground_chat.pyindex 0db01a7c8919..d8fbbc61f8cf 100644--- a/products/business_knowledge/backend/models/playground_chat.py+++ b/products/business_knowledge/backend/models/playground_chat.py@@ -5,7 +5,7 @@ from posthog.models.utils import UUIDModelclass PlaygroundChat(TeamScopedRootMixin, UUIDModel):- """A playground thread owned by one person. Each question is its own sandbox run."""+ """A playground thread owned by one person. The chat is one sandbox task. Each question is a run on that task."""team = models.ForeignKey("posthog.Team",@@ -23,6 +23,8 @@ class PlaygroundChat(TeamScopedRootMixin, UUIDModel):related_name="+",)title = models.CharField(max_length=255, blank=True, default="")+ # Null until the first question. Later questions resume this task.+ task_id = models.UUIDField(null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)diff --git a/products/business_knowledge/backend/models/playground_turn.py b/products/business_knowledge/backend/models/playground_turn.pyindex 489e2d157b5d..0a00d06bbb78 100644--- a/products/business_knowledge/backend/models/playground_turn.py+++ b/products/business_knowledge/backend/models/playground_turn.py@@ -5,7 +5,7 @@ from posthog.models.utils import UUIDModelclass PlaygroundTurn(TeamScopedRootMixin, UUIDModel):- """One question in a playground chat, pointing at a sandbox task."""+ """One question in a playground chat. `run_id` is the run that answered it."""team = models.ForeignKey("posthog.Team",@@ -18,13 +18,14 @@ class PlaygroundTurn(TeamScopedRootMixin, UUIDModel):chat = models.ForeignKey("business_knowledge.PlaygroundChat", on_delete=models.CASCADE, related_name="turns")question = models.TextField()task_id = models.UUIDField()+ # A null id reads the task's latest run, so a follow-up records the current run before starting another.+ run_id = models.UUIDField(null=True, blank=True)position = models.PositiveIntegerField()created_at = models.DateTimeField(auto_now_add=True)class Meta:constraints = [models.UniqueConstraint(fields=["chat", "position"], name="bk_pg_turn_chat_pos"),- models.UniqueConstraint(fields=["task_id"], name="bk_pg_turn_task_id"),]def __str__(self) -> str:diff --git a/products/business_knowledge/backend/playground.py b/products/business_knowledge/backend/playground.pyindex 90ad01a957ea..cbe94e430aed 100644--- a/products/business_knowledge/backend/playground.py+++ b/products/business_knowledge/backend/playground.py@@ -2,11 +2,14 @@ from __future__ import annotationsfrom collections.abc import Iterablefrom typing import Any+from uuid import UUID++from django.db import transactionfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from products.tasks.backend.facade.contracts import CreatedTaskDTO+from products.tasks.backend.facade.contracts import CreatedTaskDTO, TaskRunDTOfrom .models import PlaygroundChat, PlaygroundTurnfrom .sandbox import (@@ -18,6 +21,7 @@ from .sandbox import (load_sandbox_run,lock_owner_admission,open_sandbox_task_ids,+ resume_sandbox_run,start_sandbox_run,)@@ -64,7 +68,12 @@ def serialize_playground_chat(*, chat: PlaygroundChat, user_id: int) -> dict[strdef serialize_playground_turn(turn: PlaygroundTurn, *, user_id: int) -> dict[str, Any]:- run = load_sandbox_run(task_id=str(turn.task_id), team_id=turn.team_id, user_id=user_id)+ run = load_sandbox_run(+ task_id=str(turn.task_id),+ team_id=turn.team_id,+ user_id=user_id,+ run_id=None if turn.run_id is None else str(turn.run_id),+ )return {"id": turn.id,"question": turn.question,@@ -89,25 +98,65 @@ def ask_playground_chat(*, chat: PlaygroundChat, team: Team, user_id: int, questraise SandboxRunLimitReached()def record_turn(created: CreatedTaskDTO) -> None:+ run = created.latest_run+ if run is None:+ raise RuntimeError("Sandbox task was created without a run")last = PlaygroundTurn.objects.filter(chat=chat).order_by("-position").values_list("position", flat=True).first()PlaygroundTurn.objects.create(team_id=chat.team_id,chat=chat,question=question,task_id=created.task_id,+ run_id=run.id,position=0 if last is None else last + 1,)+ update_fields = ["updated_at"]+ if chat.task_id != created.task_id:+ chat.task_id = created.task_id+ update_fields.append("task_id")if not chat.title:chat.title = _title_for(question)- chat.save(update_fields=["title", "updated_at"])- else:- chat.save(update_fields=["updated_at"])+ update_fields.append("title")+ chat.save(update_fields=update_fields)- start_sandbox_run(- team=team,- user_id=user_id,- question=question,- admit=admit_one_run_per_chat,- on_admitted=record_turn,- )+ def remember_current_run(previous: TaskRunDTO) -> None:+ PlaygroundTurn.objects.filter(chat=chat, task_id=previous.task_id, run_id__isnull=True).update(+ run_id=previous.id+ )++ def task_for_next_run() -> UUID | None:+ chat.refresh_from_db(fields=["task_id", "title"])+ latest_task_id = (+ PlaygroundTurn.objects.filter(chat=chat).order_by("-position").values_list("task_id", flat=True).first()+ )+ # An older process can append a turn on a new task and leave chat.task_id behind.+ if latest_task_id is not None and latest_task_id != chat.task_id:+ chat.task_id = latest_task_id+ chat.save(update_fields=["task_id", "updated_at"])+ return chat.task_id++ def already_admitted() -> None:+ return++ with transaction.atomic():+ admit_one_run_per_chat()+ task_id = task_for_next_run()+ if task_id is None:+ start_sandbox_run(+ team=team,+ user_id=user_id,+ question=question,+ admit=already_admitted,+ on_admitted=record_turn,+ )+ else:+ resume_sandbox_run(+ team=team,+ user_id=user_id,+ task_id=task_id,+ question=question,+ admit=already_admitted,+ on_admitted=record_turn,+ before_create=remember_current_run,+ )return serialize_playground_chat(chat=chat, user_id=user_id)diff --git a/products/business_knowledge/backend/sandbox.py b/products/business_knowledge/backend/sandbox.pyindex b3bee57417b5..378931992d3a 100644--- a/products/business_knowledge/backend/sandbox.py+++ b/products/business_knowledge/backend/sandbox.py@@ -76,6 +76,14 @@ BK_HIDDEN_TOOLS = ["task-context-wiki-page-retrieve",]_RECOGNIZED_TOOLS = BK_DISPLAY_TOOLS | {DOCS_SEARCH_TOOL}+# A follow-up run is a new process. These pins live on the previous run, not on the task.+_RESUMED_RUN_STATE_KEYS = (+ "mcp_exclude_tools",+ "config_snapshot",+ "model",+ "runtime_adapter",+ "sandbox_environment_id",+)# Exact single-exec form. A later mention of the tool name inside the command is not a call._CALL_COMMAND = re.compile(r"^call (\S+)(?:\s|$)")@@ -290,6 +298,93 @@ def start_sandbox_run(return created+def resume_sandbox_run(+ *,+ team: Team,+ user_id: int,+ task_id: UUID,+ question: str,+ admit: Callable[[], None] | None = None,+ on_admitted: Callable[[CreatedTaskDTO], None] | None = None,+ before_create: Callable[[TaskRunDTO], None] | None = None,+) -> CreatedTaskDTO:+ """Admit the run, then resume `task_id` with `question` as the next user message.++ The agent server restores the previous session from `resume_from_run_id` and sends+ `pending_user_message` itself. Background mode does not forward that message again.+ """+ with transaction.atomic():+ if admit is None:+ _admit_one_run_per_owner(team.id, user_id)+ else:+ admit()+ previous = tasks_facade.get_owner_origin_latest_run(+ task_id=task_id,+ team_id=team.id,+ created_by_id=user_id,+ origin_product=tasks_facade.TaskOriginProduct.BUSINESS_KNOWLEDGE,+ )+ if previous is None:+ raise RuntimeError("Playground chat has no sandbox run to resume")+ if not previous.is_terminal:+ raise SandboxRunInProgress()+ # A turn with no run id reads the task's latest run. Record the current run before+ # another one exists, or that turn starts showing the new answer.+ if before_create is not None:+ before_create(previous)+ run = tasks_facade.create_run(+ task_id,+ mode="background",+ acting_user_id=user_id,+ extra_state=_resumed_run_state(question=question, previous=previous, user_id=user_id),+ )+ created = CreatedTaskDTO(task_id=run.task_id, team_id=run.team_id, latest_run=run)+ if on_admitted is not None:+ on_admitted(created)+ _dispatch_sandbox_run(run, user_id)+ return created+++def _resumed_run_state(*, question: str, previous: TaskRunDTO, user_id: int) -> dict[str, Any]:+ state: dict[str, Any] = {+ "resume_from_run_id": str(previous.id),+ "pending_user_message": question,+ # A lost workflow start leaves the run queued. The reconciler reads this blob to start it again.+ "pending_dispatch": {+ "create_pr": False,+ "posthog_mcp_scopes": BK_MCP_SCOPES,+ "user_id": user_id,+ "slack_thread_context": None,+ "workflow_id_prefix": None,+ },+ }+ state.update(tasks_facade.get_resume_snapshot_carry_state(previous.state))+ for key in _RESUMED_RUN_STATE_KEYS:+ value = previous.state.get(key)+ if isinstance(value, list):+ state[key] = list(value)+ elif isinstance(value, dict):+ state[key] = dict(value)+ elif value is not None:+ state[key] = value+ return state+++def _dispatch_sandbox_run(run: TaskRunDTO, user_id: int) -> None:+ from products.tasks.backend.facade.temporal import ( # noqa: PLC0415 — keeps the heavy dep off the import path+ dispatch_task_processing_workflow,+ )++ dispatch_task_processing_workflow(+ task_id=str(run.task_id),+ run_id=str(run.id),+ team_id=run.team_id,+ user_id=user_id,+ create_pr=False,+ posthog_mcp_scopes=BK_MCP_SCOPES,+ )++def describe_sandbox_run(run: TaskRunDTO, activity: SandboxActivity) -> dict[str, Any]:status = run.statusreply = None@@ -324,14 +419,20 @@ def describe_sandbox_run(run: TaskRunDTO, activity: SandboxActivity) -> dict[str}-def load_sandbox_run(*, task_id: str, team_id: int, user_id: int) -> dict[str, Any] | None:- """Owner-scoped read, then logs. A task that fails the identity check never has its log opened."""- run = tasks_facade.get_owner_origin_latest_run(- task_id=task_id,- team_id=team_id,- created_by_id=user_id,- origin_product=tasks_facade.TaskOriginProduct.BUSINESS_KNOWLEDGE,- )+def load_sandbox_run(*, task_id: str, team_id: int, user_id: int, run_id: str | None = None) -> dict[str, Any] | None:+ """Owner-scoped read, then logs. A task that fails the identity check never has its log opened.++ Pass `run_id` when the task has more than one run. A null `run_id` means the task has a single run.+ """+ if run_id is not None:+ run = _run_for_turn(run_id=run_id, task_id=task_id, team_id=team_id, user_id=user_id)+ else:+ run = tasks_facade.get_owner_origin_latest_run(+ task_id=task_id,+ team_id=team_id,+ created_by_id=user_id,+ origin_product=tasks_facade.TaskOriginProduct.BUSINESS_KNOWLEDGE,+ )if run is None:return Noneif _is_open(run):@@ -348,6 +449,20 @@ def sandbox_activity_for_run(*, run_id: UUID, task_id: UUID, team_id: int) -> Sareturn parse_sandbox_log(logs)+def _run_for_turn(*, run_id: str, task_id: str, team_id: int, user_id: int) -> TaskRunDTO | None:+ try:+ parsed_run_id = UUID(str(run_id))+ expected_task_id = UUID(str(task_id))+ except (ValueError, TypeError):+ return None+ run = tasks_facade.get_task_run(parsed_run_id, team_id=team_id)+ if run is None or run.created_by_id != user_id or run.task_id != expected_task_id:+ return None+ if run.task_origin_product != tasks_facade.TaskOriginProduct.BUSINESS_KNOWLEDGE:+ return None+ return run++def _is_open(run: TaskRunDTO) -> bool:return run.status in (tasks_facade.TaskRunStatus.NOT_STARTED,diff --git a/products/business_knowledge/backend/tests/test_playground.py b/products/business_knowledge/backend/tests/test_playground.pyindex 05c1b50651cd..eb219fa25200 100644--- a/products/business_knowledge/backend/tests/test_playground.py+++ b/products/business_knowledge/backend/tests/test_playground.py@@ -79,6 +79,7 @@ class TestPlaygroundChatAPI(APIBaseTest):blocked = self.client.post(f"{self.url}{first['id']}/ask/", {"question": "And after 30 days?"}, format="json")assert blocked.status_code == status.HTTP_409_CONFLICTassert PlaygroundTurn.objects.unscoped().filter(chat_id=first["id"]).count() == 1+ assert TaskRun.objects.filter(task_id=started.json()["turns"][0]["task_id"]).count() == 1untitled = self._create_chat()second = self._create_chat()@@ -137,6 +138,10 @@ class TestPlaygroundChatAPI(APIBaseTest):assert listed.json()[0]["id"] == chat["id"]still_readable = self.client.get(f"{self.url}{chat['id']}/")assert still_readable.status_code == status.HTTP_200_OK+ PlaygroundTurn.objects.unscoped().filter(chat_id=chat["id"]).update(run_id=None)+ legacy = self.client.get(f"{self.url}{chat['id']}/")+ assert legacy.status_code == status.HTTP_200_OK+ assert legacy.json()["turns"][0]["run"]["reply"] == "Yes, within 30 days."blocked = self.client.post(f"{self.url}{chat['id']}/ask/", {"question": "Another question"}, format="json")assert blocked.status_code == status.HTTP_403_FORBIDDEN@@ -162,6 +167,113 @@ class TestPlaygroundChatAPI(APIBaseTest):assert not Task.objects.filter(origin_product=Task.OriginProduct.BUSINESS_KNOWLEDGE).exists()assert PlaygroundTurn.objects.unscoped().count() == 0+ def test_follow_up_resumes_the_same_sandbox(self, _ff, _workflow) -> None:+ chat = self._create_chat()+ asked = self.client.post(f"{self.url}{chat['id']}/ask/", {"question": "Can I get a refund?"}, format="json")+ assert asked.status_code == status.HTTP_201_CREATED, asked.content+ first_turn = asked.json()["turns"][0]+ first_run = TaskRun.objects.get(id=first_turn["run"]["run_id"])+ first_run.status = TaskRun.Status.COMPLETED+ first_run.output = {"reply": "Yes, within 30 days.", "sources": []}+ first_run.save(update_fields=["status", "output"])+ description = Task.objects.get(id=first_turn["task_id"]).description++ follow_up = self.client.post(f"{self.url}{chat['id']}/ask/", {"question": "And after 30 days?"}, format="json")+ assert follow_up.status_code == status.HTTP_201_CREATED, follow_up.content+ body = follow_up.json()+ assert len(body["turns"]) == 2+ assert body["turns"][0]["task_id"] == body["turns"][1]["task_id"] == first_turn["task_id"]+ assert body["turns"][0]["run"]["status"] == "completed"+ assert body["turns"][0]["run"]["reply"] == "Yes, within 30 days."+ assert body["turns"][1]["question"] == "And after 30 days?"+ assert body["turns"][1]["run"]["status"] == "running"+ assert body["turns"][1]["run"]["reply"] is None++ successor = TaskRun.objects.get(id=body["turns"][1]["run"]["run_id"])+ assert successor.id != first_run.id+ assert successor.task_id == first_run.task_id+ assert successor.state["resume_from_run_id"] == str(first_run.id)+ assert successor.state["pending_user_message"] == "And after 30 days?"+ assert successor.state["mcp_exclude_tools"] == first_run.state["mcp_exclude_tools"]+ assert successor.state["config_snapshot"] == first_run.state["config_snapshot"]+ assert successor.state["model"] == first_run.state["model"]+ assert successor.state["runtime_adapter"] == first_run.state["runtime_adapter"]+ assert successor.state.get("sandbox_environment_id") == first_run.state.get("sandbox_environment_id")+ assert (+ successor.state["pending_dispatch"]["posthog_mcp_scopes"]+ == first_run.state["pending_dispatch"]["posthog_mcp_scopes"]+ )+ assert Task.objects.filter(origin_product=Task.OriginProduct.BUSINESS_KNOWLEDGE).count() == 1+ task = Task.objects.get(id=first_run.task_id)+ assert task.description == description+ assert "And after 30 days?" not in task.description++ reloaded = self.client.get(f"{self.url}{chat['id']}/")+ assert reloaded.status_code == status.HTTP_200_OK+ loaded = reloaded.json()["turns"]+ assert loaded[0]["run"]["reply"] == "Yes, within 30 days."+ assert loaded[0]["run"]["run_id"] == str(first_run.id)+ assert loaded[1]["run"]["run_id"] == str(successor.id)+ assert loaded[1]["run"]["status"] == "running"++ def test_follow_up_resumes_a_later_turn_on_another_task(self, _ff, _workflow) -> None:+ chat = self._create_chat()+ asked = self.client.post(f"{self.url}{chat['id']}/ask/", {"question": "Can I get a refund?"}, format="json")+ assert asked.status_code == status.HTTP_201_CREATED, asked.content+ first_task_id = asked.json()["turns"][0]["task_id"]+ TaskRun.objects.filter(task_id=first_task_id).update(+ status=TaskRun.Status.COMPLETED, output={"reply": "Yes, within 30 days.", "sources": []}+ )+ other = self.client.post(+ f"/api/projects/{self.team.id}/business_knowledge/sandbox/",+ {"question": "Where is the policy?"},+ format="json",+ )+ assert other.status_code == status.HTTP_201_CREATED, other.content+ other_task_id = other.json()["task_id"]+ other_run_id = other.json()["run_id"]+ TaskRun.objects.filter(id=other_run_id).update(+ status=TaskRun.Status.COMPLETED, output={"reply": "In the handbook.", "sources": []}+ )+ PlaygroundTurn.objects.unscoped().create(+ team_id=self.team.id,+ chat_id=chat["id"],+ question="Where is the policy?",+ task_id=other_task_id,+ run_id=other_run_id,+ position=1,+ )++ follow_up = self.client.post(f"{self.url}{chat['id']}/ask/", {"question": "And after 30 days?"}, format="json")+ assert follow_up.status_code == status.HTTP_201_CREATED, follow_up.content+ body = follow_up.json()+ assert body["turns"][0]["task_id"] == first_task_id+ assert body["turns"][1]["run"]["reply"] == "In the handbook."+ assert body["turns"][2]["task_id"] == other_task_id+ successor = TaskRun.objects.get(id=body["turns"][2]["run"]["run_id"])+ assert str(successor.task_id) == other_task_id+ assert successor.state["resume_from_run_id"] == other_run_id+ assert str(PlaygroundChat.objects.unscoped().get(id=chat["id"]).task_id) == other_task_id++ def test_follow_up_keeps_an_unpinned_earlier_answer(self, _ff, _workflow) -> None:+ chat = self._create_chat()+ asked = self.client.post(f"{self.url}{chat['id']}/ask/", {"question": "Can I get a refund?"}, format="json")+ assert asked.status_code == status.HTTP_201_CREATED, asked.content+ first_run_id = asked.json()["turns"][0]["run"]["run_id"]+ TaskRun.objects.filter(id=first_run_id).update(+ status=TaskRun.Status.COMPLETED, output={"reply": "Yes, within 30 days.", "sources": []}+ )+ PlaygroundTurn.objects.unscoped().filter(chat_id=chat["id"]).update(run_id=None)++ follow_up = self.client.post(f"{self.url}{chat['id']}/ask/", {"question": "And after 30 days?"}, format="json")+ assert follow_up.status_code == status.HTTP_201_CREATED, follow_up.content+ reloaded = self.client.get(f"{self.url}{chat['id']}/")+ turns = reloaded.json()["turns"]+ assert turns[0]["run"]["run_id"] == first_run_id+ assert turns[0]["run"]["reply"] == "Yes, within 30 days."+ assert turns[1]["run"]["run_id"] != first_run_id+ assert turns[1]["run"]["status"] == "running"+def test_blank_ask_is_rejected(self, _ff, _workflow) -> None:chat = self._create_chat()response = self.client.post(f"{self.url}{chat['id']}/ask/", {"question": " "}, format="json")diff --git a/products/business_knowledge/backend/tests/test_sandbox.py b/products/business_knowledge/backend/tests/test_sandbox.pyindex 749552bb56ce..2541246b7d25 100644--- a/products/business_knowledge/backend/tests/test_sandbox.py+++ b/products/business_knowledge/backend/tests/test_sandbox.py@@ -403,6 +403,19 @@ class TestSandboxAPI(APIBaseTest):assert first["searches"] == second["searches"]assert len(second["searches"]) == 1+ def test_a_finished_run_starts_a_new_sandbox(self, _ff, _workflow) -> None:+ started = self.client.post(self.url, {"question": "Can I get a refund?"}, format="json")+ assert started.status_code == status.HTTP_201_CREATED, started.content+ TaskRun.objects.filter(id=started.json()["run_id"]).update(+ status=TaskRun.Status.COMPLETED, output={"reply": "Yes, within 30 days.", "sources": []}+ )+ again = self.client.post(self.url, {"question": "And after 30 days?"}, format="json")+ assert again.status_code == status.HTTP_201_CREATED, again.content+ assert again.json()["task_id"] != started.json()["task_id"]+ second = TaskRun.objects.get(id=again.json()["run_id"])+ assert "resume_from_run_id" not in second.state+ assert Task.objects.filter(origin_product=Task.OriginProduct.BUSINESS_KNOWLEDGE).count() == 2+def test_blank_question_is_rejected(self, _ff, _workflow) -> None:response = self.client.post(self.url, {"question": " "}, format="json")assert response.status_code == status.HTTP_400_BAD_REQUEST