: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(tasks): add task_preview and task_browser comment scopes (#107424)
Shy Alter3518f5ff9f23
diff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex f97b696850ce..980f9299aea8 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -432,7 +432,7 @@ class CommentSerializer(serializers.ModelSerializer):target_scope = data.get("scope", instance.scope if instance else None)target_item_id = data.get("item_id", instance.item_id if instance else None)target_context = data.get("item_context", instance.item_context if instance else None) or {}- if target_scope in {"task", "task_artifact", "desktop_canvas"}:+ if target_scope in DESKTOP_COMMENT_SCOPES:task_id = target_item_id if target_scope == "task" else target_context.get("taskId")if not task_comment_target_is_accessible(team_id=self.context["get_team"]().id,@@ -581,7 +581,8 @@ class CommentListQueryParamsSerializer(serializers.Serializer):required=False, help_text="Filter by the numeric ID of the user who wrote the comment.")task_id = serializers.UUIDField(- required=False, help_text="Owning task for task, task_artifact, and desktop_canvas comment scopes."+ required=False,+ help_text="Owning task for task, task_artifact, task_preview, task_browser, and desktop_canvas comment scopes.",)search = serializers.CharField(required=False, help_text="Full-text search within comment content.")source_comment = serializers.CharField(required=False, help_text="Filter replies to a specific parent comment.")@@ -863,7 +864,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVcomment = Comment.objects.filter(team_id=self.team_id, pk=pk).first()except (ValueError, django_exceptions.ValidationError):return- if comment is None or comment.scope not in {"task", "task_artifact", "desktop_canvas"}:+ if comment is None or comment.scope not in DESKTOP_COMMENT_SCOPES:returnitem_context = comment.item_context if isinstance(comment.item_context, dict) else {}task_id = comment.item_id if comment.scope == "task" else item_context.get("taskId")@@ -880,7 +881,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVlookup_url_kwarg = self.lookup_url_kwarg or self.lookup_fieldlookup_value = self.kwargs[lookup_url_kwarg]comment = get_object_or_404(queryset, **{self.lookup_field: lookup_value})- if comment.scope in {"task", "task_artifact", "desktop_canvas"}:+ if comment.scope in DESKTOP_COMMENT_SCOPES:task_id = comment.item_id if comment.scope == "task" else (comment.item_context or {}).get("taskId")if not task_comment_target_is_accessible(team_id=self.team_id,@@ -937,7 +938,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVqueryset = queryset.filter(scope=scope)if scope in TICKET_COMMENT_SCOPES:queryset = self._filter_ticket_scoped_queryset(queryset, params.get("item_id"))- elif scope in {"task", "task_artifact", "desktop_canvas"}:+ elif scope in DESKTOP_COMMENT_SCOPES:task_id = params.get("task_id")item_id = params.get("item_id")if not task_comment_target_is_accessible(@@ -955,7 +956,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVelif self.action in ("list", "count"):# Product-owned scopes require their own object-level access checks and must# never leak through an unscoped generic comments query.- queryset = queryset.exclude(scope__in=[*TICKET_COMMENT_SCOPES, "task", "task_artifact", "desktop_canvas"])+ queryset = queryset.exclude(scope__in=[*TICKET_COMMENT_SCOPES, *DESKTOP_COMMENT_SCOPES])else:self._require_ticket_viewer_access_for_pk()self._require_task_comment_viewer_access_for_pk()diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.pyindex 63f7d2713286..dee7c8a5c696 100644--- a/posthog/api/test/test_comments.py+++ b/posthog/api/test/test_comments.py@@ -76,26 +76,56 @@ class TestComments(APIBaseTest, QueryMatchingTest):)return task- def test_task_artifact_comments_require_a_visible_owning_task(self) -> None:+ @parameterized.expand([("task_artifact",), ("task_preview",), ("task_browser",)])+ def test_task_comments_require_a_visible_owning_task(self, scope: str) -> None:task = self._task_artifact_target()+ item_id = {+ "task_artifact": "artifact-1",+ "task_preview": f"{task.id}:3000",+ "task_browser": f"{task.id}:browser",+ }[scope]payload: dict[str, Any] = {"content": "Review this",- "scope": "task_artifact",- "item_id": "artifact-1",+ "scope": scope,+ "item_id": item_id,"item_context": {"anchor": {"kind": "document"}, "taskId": str(task.id)},}created = self.client.post(f"/api/projects/{self.team.id}/comments", payload)assert created.status_code == status.HTTP_201_CREATED- without_task = self.client.get(f"/api/projects/{self.team.id}/comments?scope=task_artifact&item_id=artifact-1")+ without_task = self.client.get(f"/api/projects/{self.team.id}/comments?scope={scope}&item_id={item_id}")assert without_task.json()["results"] == []- unscoped = self.client.get(f"/api/projects/{self.team.id}/comments?item_id=artifact-1")+ unscoped = self.client.get(f"/api/projects/{self.team.id}/comments?item_id={item_id}")assert unscoped.json()["results"] == []with_task = self.client.get(- f"/api/projects/{self.team.id}/comments?scope=task_artifact&item_id=artifact-1&task_id={task.id}"+ f"/api/projects/{self.team.id}/comments?scope={scope}&item_id={item_id}&task_id={task.id}")assert [row["id"] for row in with_task.json()["results"]] == [created.json()["id"]]+ @parameterized.expand(+ [+ ("preview_on_another_task", "task_preview", "{other}:3000"),+ ("preview_without_port", "task_preview", "{task}"),+ ("preview_with_bad_port", "task_preview", "{task}:http"),+ ("browser_on_another_task", "task_browser", "{other}:browser"),+ ("browser_without_suffix", "task_browser", "{task}"),+ ("browser_with_a_port", "task_browser", "{task}:3000"),+ ]+ )+ def test_task_comment_item_must_belong_to_the_task(self, _name: str, scope: str, item_template: str) -> None:+ task = self._task_artifact_target()+ other = self._task_artifact_target()+ response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {+ "content": "Review this",+ "scope": scope,+ "item_id": item_template.format(task=task.id, other=other.id),+ "item_context": {"anchor": {"kind": "document"}, "taskId": str(task.id)},+ },+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN+@mock.patch("posthog.api.comments.send_mention_notifications")@mock.patch("posthog.api.comments.produce_discussion_mention_events")@mock.patch("posthog.tasks.email.send_discussions_mentioned.delay")@@ -303,6 +333,57 @@ class TestComments(APIBaseTest, QueryMatchingTest):assert detail.json()["comments"][0]["canvas_version_id"] == "version-2"assert detail.json()["next"] is None+ @parameterized.expand(+ [+ ("preview", "task_preview", "{task}:3000", {"kind": "document"}, "preview", "Preview of port 3000"),+ (+ "browser_page",+ "task_browser",+ "{task}:browser",+ {"kind": "document", "origin": "https://example.com", "path": "/pricing"},+ "browser",+ "https://example.com/pricing",+ ),+ (+ "browser_page_with_a_huge_path",+ "task_browser",+ "{task}:browser",+ {"kind": "document", "origin": "https://example.com", "path": "/" + "a" * 5000},+ "browser",+ ("https://example.com/" + "a" * 5000)[:500],+ ),+ (+ "browser_without_page",+ "task_browser",+ "{task}:browser",+ {"kind": "document"},+ "browser",+ "In-app browser",+ ),+ ]+ )+ def test_task_comments_list_preview_and_browser_targets(+ self, _name: str, scope: str, item_template: str, anchor: dict, expected_type: str, expected_name: str+ ) -> None:+ task = self._task_artifact_target()+ item_id = item_template.format(task=task.id)+ root = Comment.objects.create(+ team=self.team,+ created_by=self.user,+ scope=scope,+ item_id=item_id,+ item_context={"taskId": str(task.id), "anchor": anchor},+ content="Check this",+ )+ client = self._sandbox_task_comment_client(task.id)++ comments = client.get(f"/api/projects/{self.team.id}/tasks/{task.id}/comments/")++ assert comments.status_code == status.HTTP_200_OK+ assert [(row["id"], row["target"]) for row in comments.json()["comments"]] == [+ (str(root.id), {"id": item_id, "type": expected_type, "name": expected_name})+ ]+def test_task_comment_retrieval_tolerates_malformed_stored_context(self) -> None:task = self._task_artifact_target()root = Comment.objects.create(diff --git a/posthog/models/comment/utils.py b/posthog/models/comment/utils.pyindex 9664cd9f4afe..69e2553f3055 100644--- a/posthog/models/comment/utils.py+++ b/posthog/models/comment/utils.py@@ -14,7 +14,7 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)-DESKTOP_COMMENT_SCOPES = frozenset({"task", "task_artifact", "desktop_canvas"})+DESKTOP_COMMENT_SCOPES = frozenset({"task", "task_artifact", "task_preview", "task_browser", "desktop_canvas"})SCOPE_TO_SOURCE_TYPE: dict[str, str] = {"Replay": "replay",diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 6e7cfe5a7e28..69ba7b42fb9c 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1855,7 +1855,7 @@ export type CommentsListParams = {*/source_comment?: string/**- * Owning task for task, task_artifact, and desktop_canvas comment scopes.+ * Owning task for task, task_artifact, task_preview, task_browser, and desktop_canvas comment scopes.*/task_id?: string}diff --git a/products/tasks/backend/logic/services/comment_activity.py b/products/tasks/backend/logic/services/comment_activity.pyindex 9e3b3641b900..b658c55320a3 100644--- a/products/tasks/backend/logic/services/comment_activity.py+++ b/products/tasks/backend/logic/services/comment_activity.py@@ -9,13 +9,17 @@ from django.db.models import Qimport structlogfrom posthog.models import Comment+from posthog.models.comment.utils import DESKTOP_COMMENT_SCOPESfrom products.tasks.backend.models import Channel, Task, TaskArtifact, TaskCommentActivity, TaskRunfrom products.tasks.backend.visibility import task_visibility_qlogger = structlog.get_logger(__name__)-COMMENT_ACTIVITY_SCOPES = frozenset({"task", "task_artifact", "desktop_canvas"})++def is_task_preview_item(task_id: UUID, item_id: str) -> bool:+ prefix, _, port = item_id.rpartition(":")+ return prefix == str(task_id) and port.isascii() and port.isdigit() and 0 < int(port) <= 65535def _visible_tasks(team_id: int, user_id: int | None):@@ -31,10 +35,14 @@ def target_is_accessible(return Falsetask = _visible_tasks(team_id, user_id).filter(id=parsed_task_id).first()- if task is None or not item_id or scope not in COMMENT_ACTIVITY_SCOPES:+ if task is None or not item_id or scope not in DESKTOP_COMMENT_SCOPES:return Falseif scope == "task":return str(task.id) == str(item_id)+ if scope == "task_browser":+ return str(item_id) == f"{task.id}:browser"+ if scope == "task_preview":+ return is_task_preview_item(task.id, item_id)if scope != "task_artifact":return False@@ -63,7 +71,7 @@ def notifications_allowed(*, team_id: int, task_id: str | UUID) -> bool:def comment_task_id(comment: Comment) -> UUID | None:- if comment.scope not in COMMENT_ACTIVITY_SCOPES:+ if comment.scope not in DESKTOP_COMMENT_SCOPES:return Noneraw_task_id = comment.item_id if comment.scope == "task" else (comment.item_context or {}).get("taskId")if not isinstance(raw_task_id, str):diff --git a/products/tasks/backend/logic/services/comment_slack_dm.py b/products/tasks/backend/logic/services/comment_slack_dm.pyindex 1b7e158de7de..7287533ec940 100644--- a/products/tasks/backend/logic/services/comment_slack_dm.py+++ b/products/tasks/backend/logic/services/comment_slack_dm.py@@ -52,6 +52,8 @@ _ACCENT = "good"_LOCATIONS: Mapping[str, str] = {"task_artifact": "On an artifact",+ "task_preview": "On a preview",+ "task_browser": "On a web page",}_HEADINGS: Mapping[str, str] = {diff --git a/products/tasks/backend/logic/services/task_comments.py b/products/tasks/backend/logic/services/task_comments.pyindex 9cda97ad9d64..e9cc07b6fc91 100644--- a/products/tasks/backend/logic/services/task_comments.py+++ b/products/tasks/backend/logic/services/task_comments.py@@ -6,6 +6,7 @@ from uuid import UUIDfrom django.db.models import Count, Q, QuerySetfrom posthog.models import Comment+from posthog.models.comment.utils import DESKTOP_COMMENT_SCOPESfrom products.tasks.backend.facade import contractsfrom products.tasks.backend.models import TaskArtifact, TaskRun, TaskThreadMessage@@ -18,6 +19,7 @@ LIST_CONTENT_BYTES = 1024SELECTED_TEXT_BYTES = 1024DETAIL_CONTENT_BUDGET_BYTES = 64 * 1024ANCHOR_QUOTE_BYTES = 4096+TASK_ITEM_COMMENT_SCOPES = sorted(DESKTOP_COMMENT_SCOPES - {"task"})class InvalidTaskCommentCursor(ValueError):@@ -117,7 +119,7 @@ def _comments(team_id: int, task_id: UUID) -> QuerySet[Comment]:Comment.objects.filter(team_id=team_id, deleted=False).filter(Q(scope="task", item_id=task_id_string)- | Q(scope__in=["task_artifact", "desktop_canvas"], item_context__taskId=task_id_string)+ | Q(scope__in=TASK_ITEM_COMMENT_SCOPES, item_context__taskId=task_id_string)).filter(Q(item_context__isnull=True) | ~Q(item_context__has_key="is_emoji") | Q(item_context__is_emoji=False)))@@ -144,6 +146,19 @@ def _canvas_names(*, team_id: int, task_id: UUID, canvas_ids: Sequence[str]) ->return names+_MAX_BROWSER_TARGET_NAME_CHARS = 500+++def _browser_target_name(comment: Comment) -> str:+ anchor = _item_context(comment).get("anchor")+ origin = anchor.get("origin") if isinstance(anchor, dict) else None+ if not isinstance(origin, str) or not origin:+ return "In-app browser"+ path = anchor.get("path") if isinstance(anchor, dict) else None+ name = f"{origin}{path}" if isinstance(path, str) else origin+ return name[:_MAX_BROWSER_TARGET_NAME_CHARS]++def _target(comment: Comment, target_names: dict[tuple[str, str], str]) -> contracts.TaskCommentTargetDTO:if comment.scope == "task":return contracts.TaskCommentTargetDTO(id=str(comment.item_id), type="task", name="This task")@@ -152,6 +167,13 @@ def _target(comment: Comment, target_names: dict[tuple[str, str], str]) -> contrreturn contracts.TaskCommentTargetDTO(id=item_id, type="artifact", name=target_names.get(("artifact", item_id), item_id or "Artifact"))+ if comment.scope == "task_preview":+ port = item_id.rpartition(":")[2]+ return contracts.TaskCommentTargetDTO(+ id=item_id, type="preview", name=f"Preview of port {port}" if port.isdigit() else "Preview"+ )+ if comment.scope == "task_browser":+ return contracts.TaskCommentTargetDTO(id=item_id, type="browser", name=_browser_target_name(comment))return contracts.TaskCommentTargetDTO(id=item_id, type="canvas", name=target_names.get(("canvas", item_id), item_id or "Canvas"))diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 5913c11baba2..6ba62319e5ca 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -3070,13 +3070,15 @@ class TaskCommentDetailQuerySerializer(serializers.Serializer):class TaskCommentTargetSerializer(serializers.Serializer):id = serializers.CharField(help_text="Stable target id.")- type = serializers.CharField(help_text="Target type: task, artifact, or canvas.")+ type = serializers.CharField(help_text="Target type: task, artifact, canvas, preview, or browser.")name = serializers.CharField(help_text="Display name of the comment target.")class TaskCommentSummarySerializer(serializers.Serializer):id = serializers.UUIDField(help_text="Root comment id.")- target = TaskCommentTargetSerializer(help_text="Task, artifact, or canvas receiving the comment.")+ target = TaskCommentTargetSerializer(+ help_text="Task, artifact, canvas, preview, or in-app browser page receiving the comment."+ )content = serializers.CharField(help_text="Bounded excerpt of the root comment body.")content_truncated = serializers.BooleanField(help_text="Whether the root comment body has more content.")selected_text = serializers.CharField(allow_null=True, help_text="Text selected when the comment was created.")@@ -3119,7 +3121,9 @@ class TaskCommentEntrySerializer(serializers.Serializer):class TaskCommentDetailSerializer(serializers.Serializer):id = serializers.UUIDField(help_text="Root comment id.")- target = TaskCommentTargetSerializer(help_text="Task, artifact, or canvas receiving the comment.")+ target = TaskCommentTargetSerializer(+ help_text="Task, artifact, canvas, preview, or in-app browser page receiving the comment."+ )resolved = serializers.BooleanField(help_text="Whether the comment is resolved.")comments = TaskCommentEntrySerializer(many=True, help_text="Comments in this page, oldest first.")next = serializers.CharField(allow_null=True, help_text="Opaque cursor for the next page, or null.")diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex dd198839cee8..c242b337af7b 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -2584,7 +2584,7 @@ export interface TaskArtifactsResponseApi {export interface TaskCommentTargetApi {/** Stable target id. */id: string- /** Target type: task, artifact, or canvas. */+ /** Target type: task, artifact, canvas, preview, or browser. */type: string/** Display name of the comment target. */name: string@@ -2593,7 +2593,7 @@ export interface TaskCommentTargetApi {export interface TaskCommentSummaryApi {/** Root comment id. */id: string- /** Task, artifact, or canvas receiving the comment. */+ /** Task, artifact, canvas, preview, or in-app browser page receiving the comment. */target: TaskCommentTargetApi/** Bounded excerpt of the root comment body. */content: string@@ -2698,7 +2698,7 @@ export interface TaskCommentEntryApi {export interface TaskCommentDetailApi {/** Root comment id. */id: string- /** Task, artifact, or canvas receiving the comment. */+ /** Task, artifact, canvas, preview, or in-app browser page receiving the comment. */target: TaskCommentTargetApi/** Whether the comment is resolved. */resolved: booleandiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 688cffd4e980..4497cb55fcbb 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -97576,7 +97576,7 @@ export namespace Schemas {export interface TaskCommentTarget {/** Stable target id. */id: string;- /** Target type: task, artifact, or canvas. */+ /** Target type: task, artifact, canvas, preview, or browser. */type: string;/** Display name of the comment target. */name: string;@@ -97613,7 +97613,7 @@ export namespace Schemas {export interface TaskCommentDetail {/** Root comment id. */id: string;- /** Task, artifact, or canvas receiving the comment. */+ /** Task, artifact, canvas, preview, or in-app browser page receiving the comment. */target: TaskCommentTarget;/** Whether the comment is resolved. */resolved: boolean;@@ -97629,7 +97629,7 @@ export namespace Schemas {export interface TaskCommentSummary {/** Root comment id. */id: string;- /** Task, artifact, or canvas receiving the comment. */+ /** Task, artifact, canvas, preview, or in-app browser page receiving the comment. */target: TaskCommentTarget;/** Bounded excerpt of the root comment body. */content: string;@@ -108127,7 +108127,7 @@ export namespace Schemas {*/source_comment?: string;/**- * Owning task for task, task_artifact, and desktop_canvas comment scopes.+ * Owning task for task, task_artifact, task_preview, task_browser, and desktop_canvas comment scopes.*/task_id?: string;};diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.tsindex a9f036996573..5c6c1690c78e 100644--- a/services/mcp/src/generated/platform_features/api.ts+++ b/services/mcp/src/generated/platform_features/api.ts@@ -409,7 +409,9 @@ export const CommentsListQueryParams = () => zod.object({task_id: zod.string().optional()- .describe('Owning task for task, task_artifact, and desktop_canvas comment scopes.'),+ .describe(+ 'Owning task for task, task_artifact, task_preview, task_browser, and desktop_canvas comment scopes.'+ ),})/**diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.jsonindex 39ad8658debf..a843aa4ebd85 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.json@@ -40,7 +40,7 @@"type": "string"},"task_id": {- "description": "Owning task for task, task_artifact, and desktop_canvas comment scopes.",+ "description": "Owning task for task, task_artifact, task_preview, task_browser, and desktop_canvas comment scopes.","type": "string"}},