Skip to content

: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.

feat(tasks): make posthog_ai tasks user-authorable (#112412)

Alessandro Pogliaghi39a074610323
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 13566342f97f..2522e336ae67 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -5871,7 +5871,7 @@ def _resolve_cloud_pr_authorship_mode(
task.save(update_fields=["github_user_integration", "updated_at"])
return PrAuthorshipMode.USER, None
- if _ensure_task_team_github_integration(task):
+ if _ensure_task_team_github_integration(task) or task.origin_product == Task.OriginProduct.POSTHOG_AI:
return PrAuthorshipMode.BOT, None
return None, contracts.TaskRunValidationError(
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 283a61faa07e..30763493102c 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -864,6 +864,20 @@ class Task(Taggable, DeletedMetaFields, models.Model):
# Later runs keep the image the task was first provisioned with.
if carry_sandbox_template and previous_state.get("sandbox_template"):
state["sandbox_template"] = previous_state["sandbox_template"]
+ if task.origin_product == Task.OriginProduct.POSTHOG_AI and "pr_authorship_mode" not in state:
+ from products.tasks.backend.temporal.process_task.utils import (
+ PrAuthorshipMode,
+ resolve_user_github_integration_for_task,
+ user_github_integration_is_usable,
+ )
+
+ state["pr_authorship_mode"] = (
+ PrAuthorshipMode.USER.value
+ if user_github_integration_is_usable(
+ resolve_user_github_integration_for_task(task, allow_refresh=False)
+ )
+ else PrAuthorshipMode.BOT.value
+ )
# Every run creation flows through here, so this is where team/user default AI run
# preferences apply when the caller didn't pin a runtime selection.
task._apply_ai_run_defaults(state, acting_user_id)
@@ -1165,10 +1179,10 @@ class Task(Taggable, DeletedMetaFields, models.Model):
parse_requested_sandbox_template(sandbox_template) if sandbox_template is not None else None
)
from products.tasks.backend.temporal.process_task.utils import (
+ USER_AUTHORABLE_ORIGIN_PRODUCTS,
PrAuthorshipMode,
RunSource,
apply_runtime_adapter_run_state,
- get_pr_authorship_mode,
resolve_user_github_integration_for_task,
user_github_integration_is_usable,
)
@@ -1200,11 +1214,8 @@ class Task(Taggable, DeletedMetaFields, models.Model):
github_integration=github_integration,
runtime=runtime,
)
- authorship_mode = get_pr_authorship_mode(
- task_stub,
- {"run_source": RunSource.SIGNAL_REPORT.value}
- if origin_product == Task.OriginProduct.SIGNAL_REPORT
- else None,
+ authorship_mode = (
+ PrAuthorshipMode.USER if origin_product in USER_AUTHORABLE_ORIGIN_PRODUCTS else PrAuthorshipMode.BOT
)
if not github_resolution_allowed:
pass
@@ -1294,7 +1305,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
if origin_product == Task.OriginProduct.SIGNAL_REPORT:
extra_state["run_source"] = RunSource.SIGNAL_REPORT.value
extra_state["pr_authorship_mode"] = PrAuthorshipMode.BOT.value
- elif origin_product in (Task.OriginProduct.USER_CREATED, Task.OriginProduct.SLACK):
+ elif origin_product in USER_AUTHORABLE_ORIGIN_PRODUCTS:
extra_state["pr_authorship_mode"] = (
PrAuthorshipMode.USER.value if github_user_integration is not None else PrAuthorshipMode.BOT.value
)
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index 4d8794850510..48b51eecb76b 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -749,9 +749,10 @@ class TestGetGitIdentityEnvVars(TestCase):
"GIT_COMMITTER_EMAIL": "[email protected]",
}
- def test_user_created_with_explicit_bot_mode_returns_empty(self) -> None:
+ @parameterized.expand([(Task.OriginProduct.USER_CREATED,), (Task.OriginProduct.POSTHOG_AI,)])
+ def test_user_authorable_origin_with_explicit_bot_mode_returns_empty(self, origin_product: str) -> None:
user = self._make_user()
- task = self._make_task(Task.OriginProduct.USER_CREATED, user=user)
+ task = self._make_task(origin_product, user=user)
assert get_git_identity_env_vars(task, {"pr_authorship_mode": "bot"}) == {}
def test_non_user_created_with_explicit_user_mode_returns_user_identity(self) -> None:
@@ -790,6 +791,11 @@ class TestGetGitIdentityEnvVars(TestCase):
"GIT_COMMITTER_EMAIL": "[email protected]",
}
+ def test_posthog_ai_without_marker_returns_empty(self) -> None:
+ user = self._make_user()
+ task = self._make_task(Task.OriginProduct.POSTHOG_AI, user=user)
+ assert get_git_identity_env_vars(task) == {}
+
def test_user_created_without_user_returns_empty(self) -> None:
task = self._make_task(Task.OriginProduct.USER_CREATED, user=None)
assert get_git_identity_env_vars(task) == {}
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index eeaeed464d2d..e1b4a4365756 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -107,7 +107,7 @@ def mcp_scopes_for_run_source(run_source: RunSource | None) -> Literal["read_onl
# Origins whose runs are meant to carry a human git identity; everything else is bot-authored.
-USER_AUTHORABLE_ORIGIN_PRODUCTS: tuple[str, ...] = ("user_created", "slack")
+USER_AUTHORABLE_ORIGIN_PRODUCTS: tuple[str, ...] = ("user_created", "slack", "posthog_ai")
class RuntimeAdapter(StrEnum):
@@ -1561,7 +1561,7 @@ def get_pr_authorship_mode(task: Task, state: dict[str, Any] | None = None) -> P
if run_state.pr_authorship_mode is not None:
return run_state.pr_authorship_mode
- if task.origin_product == TaskModel.OriginProduct.SIGNAL_REPORT:
+ if task.origin_product in (TaskModel.OriginProduct.SIGNAL_REPORT, TaskModel.OriginProduct.POSTHOG_AI):
return PrAuthorshipMode.BOT
return PrAuthorshipMode.USER if task.origin_product in USER_AUTHORABLE_ORIGIN_PRODUCTS else PrAuthorshipMode.BOT
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 63e938092e68..492b691ffdcd 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -4717,22 +4717,38 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(get_cached_github_user_token(str(task_run.id)), "ghu_test_token")
mock_workflow.assert_not_called()
+ @parameterized.expand(
+ [
+ ("user_created_requests_user", Task.OriginProduct.USER_CREATED, {"pr_authorship_mode": "user"}, None),
+ ("posthog_ai_requests_user", Task.OriginProduct.POSTHOG_AI, {"pr_authorship_mode": "user"}, "bot"),
+ ("posthog_ai_requests_nothing", Task.OriginProduct.POSTHOG_AI, {}, "bot"),
+ ]
+ )
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
- def test_create_run_endpoint_rejects_user_authorship_without_github_identity_when_no_repo(self, mock_workflow):
+ def test_create_run_endpoint_user_authorship_without_github_identity_when_no_repo(
+ self, _name, origin_product, authorship_request, expected_mode, mock_workflow
+ ):
task = self.create_task()
+ task.origin_product = origin_product
+ task.save(update_fields=["origin_product"])
response = self.client.post(
f"/api/projects/@current/tasks/{task.id}/runs/",
{
"environment": "cloud",
- "pr_authorship_mode": "user",
"run_source": "manual",
+ **authorship_request,
},
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(response.json()["code"], "github_authorization_required")
+ if expected_mode is None:
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], "github_authorization_required")
+ else:
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ task_run = TaskRun.objects.get(id=response.json()["id"])
+ self.assertEqual(task_run.state["pr_authorship_mode"], expected_mode)
mock_workflow.assert_not_called()
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index 2a53bd75bc57..ee1e2c29e031 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -668,6 +668,44 @@ class TestTask(TestCase):
self.assertEqual(task.github_user_integration, user_integration)
mock_execute_workflow.assert_called_once()
+ @parameterized.expand(
+ [
+ ("connected_creator", True, "user"),
+ ("creator_without_personal_github", False, "bot"),
+ ]
+ )
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_and_run_posthog_ai_authorship_follows_the_creators_personal_github(
+ self, _name, connected, expected_mode, mock_execute_workflow
+ ):
+ user = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(user=user, organization=self.organization)
+ user_integration = (
+ UserIntegration.objects.create(
+ user=user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id="install-1",
+ config={},
+ sensitive_config={"user_access_token": "at", "user_refresh_token": "rt"},
+ )
+ if connected
+ else None
+ )
+
+ with self.captureOnCommitCallbacks(execute=True):
+ task = Task.create_and_run(
+ team=self.team,
+ title="PostHog AI",
+ description="Repo-less",
+ origin_product=Task.OriginProduct.POSTHOG_AI,
+ user_id=user.id,
+ )
+
+ self.assertIsNone(task.github_integration)
+ self.assertEqual(task.github_user_integration, user_integration)
+ state = TaskRun.objects.get(id=mock_execute_workflow.call_args.kwargs["run_id"]).state
+ self.assertEqual(state["pr_authorship_mode"], expected_mode)
+
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_and_run_signal_report_raises_when_no_integration_anywhere(self, mock_execute_workflow):
user = User.objects.create(email="[email protected]")
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index 86a83402a02a..6cc6dddd3218 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -15,6 +15,7 @@ from temporalio.service import RPCError, RPCStatusCode
from posthog.exceptions import QuotaLimitExceeded
from posthog.models import Integration, User
+from posthog.models.user_integration import UserIntegration
from products.tasks.backend.facade import (
access as tasks_access,
@@ -393,6 +394,42 @@ class TestWarmTaskSandbox(APIBaseTest):
assert task.repository is None
assert task.github_integration_id == integration_id
+ @parameterized.expand(
+ [
+ ("posthog_ai_connected", Task.OriginProduct.POSTHOG_AI, True, "user"),
+ ("posthog_ai_without_personal_github", Task.OriginProduct.POSTHOG_AI, False, "bot"),
+ ]
+ )
+ def test_repo_less_warm_stamps_authorship_from_the_creators_personal_github(
+ self, _name, origin_product, connected, expected_mode
+ ):
+ user_integration = (
+ UserIntegration.objects.create(
+ user=self.user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id="install-1",
+ config={},
+ sensitive_config={"user_access_token": "at", "user_refresh_token": "rt"},
+ )
+ if connected
+ else None
+ )
+
+ def fake_warm(self_warmer, **kwargs):
+ run = self_warmer.task.create_run(
+ mode="interactive", extra_state={**kwargs["extra_state"], "await_user_message": True}
+ )
+ return WarmResult(run=run, just_created=True)
+
+ with patch(f"{WARM_SRC}.warm", autospec=True, side_effect=fake_warm):
+ result = self._warm(repository=None, github_integration_id=None, branch=None, origin_product=origin_product)
+
+ assert result is not None
+ task = Task.objects.get(id=result.task_id)
+ assert task.github_integration_id is None
+ assert task.github_user_integration == user_integration
+ assert TaskRun.objects.get(id=result.run_id).state["pr_authorship_mode"] == expected_mode
+
@parameterized.expand(
[
("entitled_caller_carries_the_team_credential", True),