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(desktop): track task comment actions (#80204)

Shy Altere081a9848c55
diff --git a/posthog/api/comments.py b/posthog/api/comments.py
index 6e03116181d4..9237ef4a5a0d 100644
--- a/posthog/api/comments.py
+++ b/posthog/api/comments.py
@@ -21,9 +21,10 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, action
+from posthog.event_usage import groups
from posthog.exceptions import Conflict
from posthog.helpers.slack_thread_mirror import post_comment_to_slack_thread, slack_author_from_user
-from posthog.models import User
+from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.activity_logging.model_activity import get_was_impersonated
from posthog.models.comment import Comment, CommentSlackThread
@@ -121,6 +122,61 @@ class CommentSlackThreadRefSerializer(serializers.Serializer):
url = serializers.CharField(help_text="Deep link that opens the mirrored Slack thread.")
+def _capture_task_comment_action(comment: Comment, mentions: list[int], team: Team) -> None:
+ if (
+ comment.scope not in {"task", "task_artifact", "desktop_canvas"}
+ or not comment.created_by
+ or not comment.created_by.distinct_id
+ ):
+ return
+
+ context = comment.item_context if isinstance(comment.item_context, dict) else {}
+ thread_state = context.get("threadState")
+ if comment.source_comment_id and thread_state == "resolved":
+ action_type = "resolved"
+ elif comment.source_comment_id and thread_state == "open":
+ action_type = "reopened"
+ elif comment.source_comment_id:
+ action_type = "replied"
+ else:
+ action_type = "created"
+
+ anchor = context.get("anchor")
+ anchor_kind = anchor.get("kind") if isinstance(anchor, dict) else None
+ raw_task_id = comment.item_id if comment.scope == "task" else context.get("taskId")
+ properties: dict[str, Any] = {
+ "analytics_version": 1,
+ "action_type": action_type,
+ "scope": comment.scope,
+ "anchor_kind": anchor_kind if anchor_kind in {"text", "region", "document"} else "unknown",
+ "task_id": raw_task_id if isinstance(raw_task_id, str) else None,
+ "item_id": comment.item_id,
+ "thread_id": str(comment.source_comment_id or comment.id),
+ "comment_id": str(comment.id),
+ "is_reply": action_type == "replied",
+ "mention_count": len(mentions),
+ }
+ if action_type in {"created", "replied"}:
+ content_length = len(comment.content or "")
+ properties["content_length_bucket"] = (
+ "0-50" if content_length <= 50 else "51-200" if content_length <= 200 else "201+"
+ )
+ if action_type in {"created", "reopened"}:
+ properties["thread_state"] = "open"
+ elif action_type == "resolved":
+ properties["thread_state"] = "resolved"
+
+ try:
+ posthoganalytics.capture(
+ distinct_id=str(comment.created_by.distinct_id),
+ event="Comment action",
+ properties=properties,
+ groups=groups(team=team),
+ )
+ except Exception:
+ logger.exception("Failed to capture task comment analytics", extra={"comment_id": str(comment.id)})
+
+
def _record_task_comment_activity(
comment: Comment,
mentions: list[int],
@@ -366,10 +422,11 @@ class CommentSerializer(serializers.ModelSerializer):
data["scope"] = root.scope
data["item_id"] = root.item_id
reply_context = data.get("item_context") or {}
+ root_context = root.item_context if isinstance(root.item_context, dict) else {}
# Replies inherit the root's context (anchor, taskId) so filters keep
# working, but a reply's own signal keys must survive the merge.
data["item_context"] = {
- **(root.item_context or {}),
+ **{key: value for key, value in root_context.items() if key != "threadState"},
**({"is_emoji": reply_context["is_emoji"]} if "is_emoji" in reply_context else {}),
**(
{"threadState": reply_context["threadState"]}
@@ -469,6 +526,7 @@ class CommentSerializer(serializers.ModelSerializer):
produce_discussion_mention_events(comment, mentions, slug)
send_mention_notifications(comment, mentions, slug)
_record_task_comment_activity(comment, mentions)
+ _capture_task_comment_action(comment, mentions, self.context["get_team"]())
return comment
diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.py
index b54d3cb16997..02a8941af7e5 100644
--- a/posthog/api/test/test_comments.py
+++ b/posthog/api/test/test_comments.py
@@ -97,6 +97,83 @@ class TestComments(APIBaseTest, QueryMatchingTest):
)
assert [row["id"] for row in with_task.json()["results"]] == [created.json()["id"]]
+ @mock.patch("posthog.api.comments.posthoganalytics.capture")
+ def test_task_comment_actions_track_mentions_without_counting_state_as_replies(self, capture: mock.Mock) -> None:
+ task = self._task_artifact_target()
+ mentioned = User.objects.create_and_join(self.organization, "[email protected]", None)
+ item_context = {
+ "anchor": {"kind": "unsupported"},
+ "taskId": str(task.id),
+ }
+ target = {
+ "scope": "task_artifact",
+ "item_id": "artifact-1",
+ "item_context": item_context,
+ }
+
+ root = self.client.post(
+ f"/api/projects/{self.team.id}/comments",
+ {
+ **target,
+ "content": "A" * 60,
+ "mentions": [mentioned.id],
+ "item_context": {**item_context, "threadState": "resolved"},
+ },
+ )
+ reply = self.client.post(
+ f"/api/projects/{self.team.id}/comments",
+ {**target, "content": "Reply", "source_comment": root.json()["id"]},
+ )
+ resolved = self.client.post(
+ f"/api/projects/{self.team.id}/comments",
+ {
+ **target,
+ "content": "Resolved this thread",
+ "source_comment": root.json()["id"],
+ "item_context": {**item_context, "threadState": "resolved"},
+ },
+ )
+
+ assert root.status_code == status.HTTP_201_CREATED
+ assert reply.status_code == status.HTTP_201_CREATED
+ assert resolved.status_code == status.HTTP_201_CREATED
+ events = [call.kwargs for call in capture.call_args_list if call.kwargs.get("event") == "Comment action"]
+ assert [event["properties"]["action_type"] for event in events] == ["created", "replied", "resolved"]
+ assert events[0]["properties"] == {
+ "analytics_version": 1,
+ "action_type": "created",
+ "scope": "task_artifact",
+ "anchor_kind": "unknown",
+ "task_id": str(task.id),
+ "item_id": "artifact-1",
+ "thread_id": root.json()["id"],
+ "comment_id": root.json()["id"],
+ "is_reply": False,
+ "mention_count": 1,
+ "content_length_bucket": "51-200",
+ "thread_state": "open",
+ }
+ assert events[1]["properties"]["is_reply"] is True
+ assert events[1]["properties"]["mention_count"] == 0
+ assert events[2]["properties"]["is_reply"] is False
+ assert events[2]["properties"]["thread_state"] == "resolved"
+ assert all(event["event"] == "Comment action" for event in events)
+
+ capture.reset_mock()
+ notebook = self.client.post(
+ f"/api/projects/{self.team.id}/comments",
+ {"scope": "Notebook", "content": "Not a task comment"},
+ )
+ assert notebook.status_code == status.HTTP_201_CREATED
+ assert not any(call.kwargs.get("event") == "Comment action" for call in capture.call_args_list)
+
+ capture.side_effect = RuntimeError("Analytics unavailable")
+ saved = self.client.post(
+ f"/api/projects/{self.team.id}/comments",
+ {**target, "content": "Still saved"},
+ )
+ assert saved.status_code == status.HTTP_201_CREATED
+
def test_task_comments_list_artifacts_comments_and_one_comment(self) -> None:
task = self._task_artifact_target()
task_run_model = apps.get_model("tasks", "TaskRun")