: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(canvas): keep a shared canvas commentable (#102677)
posthog[bot]524520ce2b59
diff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex bcbdca451b0e..f97b696850ce 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -228,16 +228,27 @@ def _record_task_comment_activity(def _mentions_allowed_for_comment_target(- *, team_id: int, scope: str, item_id: str | None, item_context: dict | None-) -> bool:+ *, team_id: int, scope: str, item_id: str | None, item_context: dict | None, mentioned_user_ids: list[int]+) -> list[int]:if scope not in DESKTOP_COMMENT_SCOPES:- return True+ return mentioned_user_ids+ if scope == "desktop_canvas":+ if not item_id:+ return []+ from products.canvas.backend.comment_access import visible_canvas_user_ids++ visible_ids = visible_canvas_user_ids(+ team_id=team_id,+ canvas_id=item_id,+ user_ids=mentioned_user_ids,+ )+ return [user_id for user_id in mentioned_user_ids if user_id in visible_ids]task_id = item_id if scope == "task" else (item_context or {}).get("taskId")if not task_id:- return False+ return []from products.tasks.backend.facade.api import task_comment_mentions_allowed # noqa: PLC0415- return task_comment_mentions_allowed(team_id=team_id, task_id=task_id)+ return mentioned_user_ids if task_comment_mentions_allowed(team_id=team_id, task_id=task_id) else []class CommentSerializer(serializers.ModelSerializer):@@ -478,13 +489,13 @@ class CommentSerializer(serializers.ModelSerializer):validated_data["team_id"] = self.context["team_id"]mentions = self._filter_mentions_to_organization(mentions, self.context["get_organization"]().id)- if not _mentions_allowed_for_comment_target(+ mentions = _mentions_allowed_for_comment_target(team_id=self.context["team_id"],scope=validated_data["scope"],item_id=validated_data.get("item_id"),item_context=validated_data.get("item_context"),- ):- mentions = []+ mentioned_user_ids=mentions,+ )# ATOMIC_REQUESTS is off, so wrap the comment insert with the email-outbox write.persist_ctx = transaction.atomic() if validated_data["scope"] == "conversations_ticket" else nullcontext()@@ -511,13 +522,13 @@ class CommentSerializer(serializers.ModelSerializer):request = self.context["request"]mentions = self._filter_mentions_to_organization(mentions, self.context["get_organization"]().id)- if not _mentions_allowed_for_comment_target(+ mentions = _mentions_allowed_for_comment_target(team_id=instance.team_id,scope=validated_data.get("scope", instance.scope),item_id=validated_data.get("item_id", instance.item_id),item_context=validated_data.get("item_context", instance.item_context),- ):- mentions = []+ mentioned_user_ids=mentions,+ )with transaction.atomic():locked_instance = Comment.objects.select_for_update().get(pk=instance.pk)@@ -937,7 +948,9 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVitem_id=item_id,):return queryset.none()- if scope != "task":+ # A canvas thread belongs to the canvas, which `item_id` already selects. Its `taskId`+ # only records which task generated the version the comment was written on.+ if scope == "task_artifact":queryset = queryset.filter(item_context__taskId=str(task_id))elif self.action in ("list", "count"):# Product-owned scopes require their own object-level access checks and mustdiff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.pyindex 2c17d3e346be..63f7d2713286 100644--- a/posthog/api/test/test_comments.py+++ b/posthog/api/test/test_comments.py@@ -590,6 +590,126 @@ class TestComments(APIBaseTest, QueryMatchingTest):payload["item_context"]["taskId"] = str(other_task.id)assert self.client.post(f"/api/projects/{self.team.id}/comments", payload).status_code == 403+ def test_canvas_comments_follow_the_canvas_channel_not_the_task_channel(self) -> None:+ channel_model = apps.get_model("tasks", "Channel")+ task_model = apps.get_model("tasks", "Task")+ canvas_model = apps.get_model("canvas", "Canvas")++ author = User.objects.create_and_join(self.organization, "[email protected]", "password")+ shared = channel_model.objects.unscoped().create(+ team=self.team, name="shared-space", channel_type="public", created_by=author+ )+ author_personal = channel_model.objects.unscoped().create(+ team=self.team, name="me", channel_type="personal", created_by=author+ )+ task = task_model.objects.create(+ team=self.team, title="Build the canvas", created_by=author, channel=author_personal+ )+ canvas = canvas_model.objects.unscoped().create(+ team=self.team,+ channel=shared,+ name="Shared canvas",+ created_by=author,+ generation_task_id=task.id,+ )+ payload = {+ "content": "Nice canvas",+ "scope": "desktop_canvas",+ "item_id": str(canvas.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+ listed = self.client.get(+ f"/api/projects/{self.team.id}/comments?scope=desktop_canvas&item_id={canvas.id}&task_id={task.id}"+ )+ assert [row["id"] for row in listed.json()["results"]] == [created.json()["id"]]++ regenerated_by = task_model.objects.create(+ team=self.team, title="Regenerate the canvas", created_by=author, channel=author_personal+ )+ canvas.generation_task_id = regenerated_by.id+ canvas.save(update_fields=["generation_task_id"])+ relisted = self.client.get(+ f"/api/projects/{self.team.id}/comments?scope=desktop_canvas&item_id={canvas.id}&task_id={regenerated_by.id}"+ )+ assert [row["id"] for row in relisted.json()["results"]] == [created.json()["id"]]++ @mock.patch("posthog.api.comments.send_mention_notifications")+ @mock.patch("posthog.api.comments.produce_discussion_mention_events")+ def test_private_canvas_comments_follow_space_membership(+ self, produce_events: mock.Mock, send_notifications: mock.Mock+ ) -> None:+ channel_model = apps.get_model("tasks", "Channel")+ membership_model = apps.get_model("tasks", "ChannelMembership")+ canvas_model = apps.get_model("canvas", "Canvas")+ invited = User.objects.create_and_join(self.organization, "[email protected]", "password")+ non_member = User.objects.create_and_join(self.organization, "[email protected]", "password")+ channel = channel_model.objects.unscoped().create(+ team=self.team,+ name="private-canvas-space",+ channel_type="private",+ created_by=self.user,+ )+ membership_model.objects.unscoped().bulk_create(+ [+ membership_model(team=self.team, channel=channel, user=self.user),+ membership_model(team=self.team, channel=channel, user=invited),+ ]+ )+ task = self._task_artifact_target(public=False)+ canvas = canvas_model.objects.unscoped().create(+ team=self.team,+ channel=channel,+ name="Private canvas",+ created_by=self.user,+ generation_task_id=task.id,+ )+ payload = {+ "content": "Review this canvas",+ "scope": "desktop_canvas",+ "item_id": str(canvas.id),+ "item_context": {"anchor": {"kind": "document"}, "taskId": str(task.id)},+ "mentions": [invited.id, non_member.id],+ }++ created = self.client.post(f"/api/projects/{self.team.id}/comments", payload)++ assert created.status_code == status.HTTP_201_CREATED+ assert produce_events.call_args.args[1] == [invited.id]+ assert send_notifications.call_args.args[1] == [invited.id]+ activity_model = apps.get_model("tasks", "TaskCommentActivity")+ assert (+ activity_model.objects.unscoped()+ .filter(team=self.team, user=invited, comment_id=created.json()["id"])+ .exists()+ )+ assert (+ not activity_model.objects.unscoped()+ .filter(team=self.team, user=non_member, comment_id=created.json()["id"])+ .exists()+ )++ self.client.force_login(invited)+ assert (+ self.client.post(+ f"/api/projects/{self.team.id}/comments", {**payload, "content": "A member comment", "mentions": []}+ ).status_code+ == status.HTTP_201_CREATED+ )++ self.client.force_login(non_member)+ assert (+ self.client.post(f"/api/projects/{self.team.id}/comments", payload).status_code == status.HTTP_403_FORBIDDEN+ )+ response = self.client.get(+ f"/api/projects/{self.team.id}/comments?scope=desktop_canvas&item_id={canvas.id}&task_id={task.id}"+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["results"] == []+def test_canvas_comments_respect_personal_channel_visibility(self) -> None:task = self._task_artifact_target()other = User.objects.create_and_join(self.organization, "[email protected]", "password")diff --git a/posthog/comment/access.py b/posthog/comment/access.pyindex 61200ca497c9..856141739895 100644--- a/posthog/comment/access.py+++ b/posthog/comment/access.py@@ -4,11 +4,11 @@ from uuid import UUIDdef task_comment_target_is_accessible(*, team_id: int, user_id: int | None, task_id: str | UUID, scope: str, item_id: str | None) -> bool:- from products.tasks.backend.facade.api import (- task_comment_target_is_accessible as task_target_is_accessible, # noqa: PLC0415 # Import lazily because generic comment imports must not load product models.- )-if scope != "desktop_canvas":+ from products.tasks.backend.facade.api import (+ task_comment_target_is_accessible as task_target_is_accessible, # noqa: PLC0415 # Import lazily because generic comment imports must not load product models.+ )+return task_target_is_accessible(team_id=team_id,user_id=user_id,@@ -16,14 +16,6 @@ def task_comment_target_is_accessible(scope=scope,item_id=item_id,)- if not task_target_is_accessible(- team_id=team_id,- user_id=user_id,- task_id=task_id,- scope="task",- item_id=str(task_id),- ):- return Falsetry:parsed_task_id = UUID(str(task_id))diff --git a/products/canvas/backend/comment_access.py b/products/canvas/backend/comment_access.pyindex c2044f3d33a0..bc8267a41b9d 100644--- a/products/canvas/backend/comment_access.py+++ b/products/canvas/backend/comment_access.py@@ -1,3 +1,4 @@+from collections.abc import Iterablefrom uuid import UUIDfrom django.core.exceptions import ValidationError@@ -20,6 +21,29 @@ def canvas_belongs_to_task(*, team_id: int, user_id: int | None, canvas_id: str,return False+def visible_canvas_user_ids(*, team_id: int, canvas_id: str, user_ids: Iterable[int]) -> set[int]:+ candidate_ids = set(user_ids)+ if not candidate_ids:+ return set()+ try:+ canvases = Canvas.objects.for_team(team_id).filter(id=canvas_id, deleted=False, channel__deleted=False)+ if canvases.filter(channel__channel_type="public").exists():+ return candidate_ids+ visible_ids = set(+ canvases.filter(channel__channel_type="personal", channel__created_by_id__in=candidate_ids).values_list(+ "channel__created_by_id", flat=True+ )+ )+ visible_ids.update(+ canvases.filter(+ channel__channel_type="private", channel__memberships__user_id__in=candidate_ids+ ).values_list("channel__memberships__user_id", flat=True)+ )+ return visible_ids+ except (ValueError, ValidationError):+ return set()++def canvas_owner_id(*, team_id: int, canvas_id: str) -> int | None:try:return (diff --git a/products/desktop/packages/core/src/canvas/taskActivity.ts b/products/desktop/packages/core/src/canvas/taskActivity.tsindex 420c41e54724..d06c30bb3c26 100644--- a/products/desktop/packages/core/src/canvas/taskActivity.ts+++ b/products/desktop/packages/core/src/canvas/taskActivity.ts@@ -32,6 +32,18 @@ export interface TaskActivityItem {isUnread: boolean;}+/**+ * The canvas a row is about, or null for a task row. A canvas comment row+ * carries the canvas's name and space but the generating task's id, so links+ * and actions built from `taskId` would name a task that may live in another+ * space, or one the reader can't open.+ */+export function activityCanvasId(item: TaskActivityItem): string | null {+ return item.commentTarget?.scope === "desktop_canvas"+ ? item.commentTarget.itemId+ : null;+}+/** Map activity DTOs (already newest-first from the backend) to feed items. */export function toTaskActivityItems(activity: readonly TaskActivity[],diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanelBody.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanelBody.tsxindex a12d60977c81..17adb7d6d494 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityPanelBody.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityPanelBody.tsx@@ -114,7 +114,9 @@ export function ActivityPanelBody({const body = () => {if (tab === "comments") {- return <TaskCommentsList task={task} timeline={timeline} />;+ return (+ <TaskCommentsList taskId={task.id} task={task} timeline={timeline} />+ );}if (tab === "artifacts") {return (diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityRow.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityRow.test.tsxindex 3cea80ac1aa9..a6ff2ecc743a 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityRow.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityRow.test.tsx@@ -7,6 +7,10 @@ const navigation = vi.hoisted(() => ({toChannelTask: vi.fn(),toTaskDetail: vi.fn(),}));+const links = vi.hoisted(() => ({+ copyCanvasLink: vi.fn(() => Promise.resolve()),+ copyChannelLink: vi.fn(() => Promise.resolve()),+}));vi.mock("@posthog/ui/router/navigationBridge", () => ({navigateToChannelDashboard: navigation.toChannelDashboard,@@ -28,6 +32,12 @@ vi.mock("@posthog/ui/features/canvas/hooks/useFileTaskToChannel", () => ({vi.mock("@posthog/ui/features/browser-tabs/useOpenBrowserTab", () => ({useOpenBrowserTab: () => vi.fn(),}));+vi.mock("@posthog/ui/features/canvas/utils/copyCanvasLink", () => ({+ copyCanvasLink: links.copyCanvasLink,+}));+vi.mock("@posthog/ui/features/canvas/utils/copyChannelLink", () => ({+ copyChannelLink: links.copyChannelLink,+}));import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";import { ActivityRow } from "./ActivityRow";@@ -223,4 +233,29 @@ describe("ActivityRow", () => {intent: "navigate",});});++ it("copies a canvas link, not a task link, for a canvas comment row", () => {+ render(+ <ActivityRow+ item={item({+ channelId: "channel-1",+ commentId: "comment-1",+ commentTarget: { scope: "desktop_canvas", itemId: "canvas-1" },+ })}+ menu={taskMenu()}+ onMarkRead={vi.fn()}+ onActivate={vi.fn()}+ blockedTaskIds={NO_BLOCKED_TASKS}+ />,+ );++ fireEvent.click(screen.getByLabelText("Copy thread link"));++ expect(links.copyCanvasLink).toHaveBeenCalledWith(+ "channel-1",+ "canvas-1",+ "activity",+ );+ expect(links.copyChannelLink).not.toHaveBeenCalled();+ });});diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityRow.tsxindex 535093f044b6..2bc60be2e065 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityRow.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityRow.tsx@@ -5,7 +5,10 @@ import {LinkIcon,QuestionIcon,} from "@phosphor-icons/react";-import type { TaskActivityItem } from "@posthog/core/canvas/taskActivity";+import {+ activityCanvasId,+ type TaskActivityItem,+} from "@posthog/core/canvas/taskActivity";import { Avatar, AvatarFallback, Badge, Button, cn } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import type { UserBasic } from "@posthog/shared/domain-types";@@ -20,6 +23,7 @@ import {TaskRowDropdownMenu,type TaskRowMenuProps,} from "@posthog/ui/features/canvas/components/TaskRowMenu";+import { copyCanvasLink } from "@posthog/ui/features/canvas/utils/copyCanvasLink";import { copyChannelLink } from "@posthog/ui/features/canvas/utils/copyChannelLink";import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";import { track } from "@posthog/ui/shell/analytics";@@ -90,7 +94,16 @@ export function ActivityRow({item.isUnread && !awaitsReply? "bg-primary text-primary-foreground": undefined;+ const canvasId = activityCanvasId(item);const canCopyLink = channelId !== null && !compact;+ const copyLink = (): void => {+ if (channelId === null) return;+ if (canvasId) {+ void copyCanvasLink(channelId, canvasId, "activity");+ } else {+ void copyChannelLink(channelId, "activity", item.taskId);+ }+ };const actionCount = 1 + (item.isUnread ? 1 : 0) + (canCopyLink ? 1 : 0);const openTask = (): void => {track(ANALYTICS_EVENTS.CHANNEL_ACTION, {@@ -195,9 +208,7 @@ export function ActivityRow({variant="default"size="icon-xs"aria-label="Copy thread link"- onClick={() =>- void copyChannelLink(channelId, "activity", item.taskId)- }+ onClick={copyLink}><LinkIcon size={14} /></Button>diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.test.tsxindex 0f27d899cd47..3eb0814fa84f 100644--- a/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.test.tsx@@ -260,7 +260,7 @@ describe("TaskCommentsList", () => {prRun(`https://github.com/acme/repo/pull/${index + 1}`),);- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);const expectedUrls = Array.from({ length: 20 },@@ -294,6 +294,7 @@ describe("TaskCommentsList", () => {render(<TaskCommentsList+ taskId={task.id}task={task}timeline={[]}onlySource={{@@ -355,7 +356,7 @@ describe("TaskCommentsList", () => {}),];- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(screen.getByText("report.md")).toBeTruthy();expect(screen.getByText("“Purpose”")).toBeTruthy();@@ -384,7 +385,9 @@ describe("TaskCommentsList", () => {},] as unknown as ThreadTimelineRow<TaskThreadMessage>[];- render(<TaskCommentsList task={task} timeline={timeline} />);+ render(+ <TaskCommentsList taskId={task.id} task={task} timeline={timeline} />,+ );expect(mocks.queriedTargets.at(-1)).toContainEqual({scope: "desktop_canvas",@@ -396,7 +399,7 @@ describe("TaskCommentsList", () => {// The tab is the one place to see every thread the task produced, so each row// has to say which artifact it came from.it("lists open threads from every artifact, newest first", () => {- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);const newest = screen.getByText("Second thread");const oldest = screen.getByText("Tighten this summary");@@ -411,7 +414,7 @@ describe("TaskCommentsList", () => {});it("opens the artifact a thread belongs to and focuses that thread", () => {- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);openThread("Tighten this summary");@@ -430,7 +433,7 @@ describe("TaskCommentsList", () => {});it("opens an artifact when activity requests its comment thread", () => {- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);act(() => {useCommentNavigationStore@@ -456,7 +459,7 @@ describe("TaskCommentsList", () => {callback(0);return 0;});- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);const thread = screen.getByText("Tighten this summary").closest("[data-comment-thread-id]") as HTMLElement;@@ -505,6 +508,7 @@ describe("TaskCommentsList", () => {render(<TaskCommentsList+ taskId={task.id}task={task}timeline={[]}onlySource={{@@ -534,7 +538,7 @@ describe("TaskCommentsList", () => {// Clicking the same thread twice has to scroll twice, so every request is a// new nonce rather than a no-op set.it("re-requests focus for a thread already focused", () => {- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);openThread("Tighten this summary");const first = useCommentNavigationStore.getState().focusByTask["task-1"];@@ -565,7 +569,7 @@ describe("TaskCommentsList", () => {}),];- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(screen.getByText("Second thread")).toBeTruthy();expect(screen.queryByText("Tighten this summary")).toBeNull();@@ -584,13 +588,13 @@ describe("TaskCommentsList", () => {},});- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(screen.getByText("The highlighted text changed")).toBeTruthy();});it("replies and resolves against the thread's own resource", () => {- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);// Each row builds its mutations from its own target, since the list spans// several resources.@@ -619,7 +623,7 @@ describe("TaskCommentsList", () => {it("narrows to the artifact open in the main pane", () => {mocks.activeArtifactId = "b";- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(screen.getByText("Second thread")).toBeTruthy();expect(screen.queryByText("Tighten this summary")).toBeNull();@@ -639,7 +643,7 @@ describe("TaskCommentsList", () => {mocks.comments = [comment({})];mocks.activeArtifactId = "empty";- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(screen.getByLabelText("Filter by source")).toHaveTextContent("empty.md",@@ -656,7 +660,9 @@ describe("TaskCommentsList", () => {it("follows an active artifact once its run data arrives", () => {mocks.runs = [];mocks.activeArtifactId = "late";- const { rerender } = render(<TaskCommentsList task={task} timeline={[]} />);+ const { rerender } = render(+ <TaskCommentsList taskId={task.id} task={task} timeline={[]} />,+ );expect(screen.getByLabelText("Filter by source")).toHaveTextContent("All sources",@@ -671,7 +677,7 @@ describe("TaskCommentsList", () => {}),]),];- rerender(<TaskCommentsList task={task} timeline={[]} />);+ rerender(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(screen.getByLabelText("Filter by source")).toHaveTextContent("late.md",@@ -680,12 +686,14 @@ describe("TaskCommentsList", () => {it("resumes following the main pane after All sources is selected", () => {mocks.activeArtifactId = "b";- const { rerender } = render(<TaskCommentsList task={task} timeline={[]} />);+ const { rerender } = render(+ <TaskCommentsList taskId={task.id} task={task} timeline={[]} />,+ );fireEvent.click(screen.getByLabelText("Filter by source"));fireEvent.click(screen.getByText(/^All sources/));mocks.activeArtifactId = "a";- rerender(<TaskCommentsList task={task} timeline={[]} />);+ rerender(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(screen.queryByText("Second thread")).toBeNull();expect(screen.getByText("Tighten this summary")).toBeTruthy();@@ -693,12 +701,14 @@ describe("TaskCommentsList", () => {it("stops following the main pane while a specific source is selected", () => {mocks.activeArtifactId = null;- const { rerender } = render(<TaskCommentsList task={task} timeline={[]} />);+ const { rerender } = render(+ <TaskCommentsList taskId={task.id} task={task} timeline={[]} />,+ );fireEvent.click(screen.getByLabelText("Filter by source"));fireEvent.click(screen.getAllByText("report.md").at(-1) as HTMLElement);mocks.activeArtifactId = "b";- rerender(<TaskCommentsList task={task} timeline={[]} />);+ rerender(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(screen.queryByText("Second thread")).toBeNull();expect(screen.getByText("Tighten this summary")).toBeTruthy();@@ -719,7 +729,7 @@ describe("TaskCommentsList", () => {},];- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(screen.getByText("This needs a guard")).toBeTruthy();expect(screen.getByText("Shipping this")).toBeTruthy();@@ -744,7 +754,7 @@ describe("TaskCommentsList", () => {},];- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);fireEvent.click(screen.getByText("View on GitHub"));expect(mocks.openExternalUrl).toHaveBeenCalledWith(@@ -757,7 +767,7 @@ describe("TaskCommentsList", () => {mocks.comments = [];mocks.prReviewThreads = [reviewThread()];- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);openThread("This needs a guard");expect(mocks.openPrInReview).toHaveBeenCalledWith(@@ -775,7 +785,7 @@ describe("TaskCommentsList", () => {mocks.comments = [];mocks.prReviewThreads = [reviewThread()];- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);const thread = screen.getByText("This needs a guard").closest("[data-comment-thread-id]") as HTMLElement;@@ -787,7 +797,7 @@ describe("TaskCommentsList", () => {// Not every comment belongs to a deliverable; some are about the work.it("posts a comment on the task itself without scrolling", async () => {- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);await act(async () => {fireEvent.click(screen.getByText(/Comment on this task/));@@ -825,7 +835,7 @@ describe("TaskCommentsList", () => {),];- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);const queriedTargets = mocks.queriedTargets.at(-1) as Array<{scope: string;@@ -844,7 +854,7 @@ describe("TaskCommentsList", () => {prRun(`https://github.com/acme/repo/pull/${index + 1}`),);- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(mocks.prCommentUrls).toHaveLength(4);expect(mocks.prReviewUrls).toHaveLength(4);@@ -854,7 +864,7 @@ describe("TaskCommentsList", () => {it("shows an empty state pointing at the artifact surfaces", () => {mocks.comments = [];- render(<TaskCommentsList task={task} timeline={[]} />);+ render(<TaskCommentsList taskId={task.id} task={task} timeline={[]} />);expect(screen.getByText("No open comments")).toBeTruthy();});diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsxindex ef3b42b228d0..1606ec5c5558 100644--- a/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskCommentsList.tsx@@ -297,6 +297,7 @@ function PrThreadRow({* it there, which is why no surface carries a thread list of its own.*/export function TaskCommentsList({+ taskId,task,timeline,onlySource,@@ -304,8 +305,9 @@ export function TaskCommentsList({commentVersionLabel,onCanvasCommentOpen,}: {- task: Task;- timeline: ThreadTimelineRow<TaskThreadMessage>[];+ taskId: string;+ task?: Task;+ timeline?: ThreadTimelineRow<TaskThreadMessage>[];/** Restricts the pane to one resource known by its host, without relying on* the task timeline to rediscover it. */onlySource?: CommentSource;@@ -313,16 +315,14 @@ export function TaskCommentsList({commentVersionLabel?: (versionId: string) => string | null;onCanvasCommentOpen?: (versionId: string | null) => void;}) {- const { runs } = useTaskRuns(onlySource ? undefined : task.id);+ const { runs } = useTaskRuns(onlySource ? undefined : taskId);const { members } = useOrgMembers();const openArtifactTab = usePanelLayoutStore((state) => state.openArtifactTab);- const activeArtifactId = useActiveArtifactId(task.id);+ const activeArtifactId = useActiveArtifactId(taskId);const requestCommentFocus = useCommentNavigationStore((state) => state.requestCommentFocus,);- const focus = useCommentNavigationStore(- (state) => state.focusByTask[task.id],- );+ const focus = useCommentNavigationStore((state) => state.focusByTask[taskId]);const resolutionsByTarget = useCommentNavigationStore((state) => state.resolutionsByTarget,);@@ -332,23 +332,23 @@ export function TaskCommentsList({const [draft, setDraft] = useState("");const threadListRef = useRef<HTMLDivElement>(null);const sourceFilterTouched = useRef(false);- const previousTaskId = useRef(task.id);+ const previousTaskId = useRef(taskId);useEffect(() => {- if (previousTaskId.current === task.id) return;- previousTaskId.current = task.id;+ if (previousTaskId.current === taskId) return;+ previousTaskId.current = taskId;sourceFilterTouched.current = false;setSourceFilter(ALL_SOURCES);setDraft("");- }, [task.id]);+ }, [taskId]);const rows = useMemo(- () => buildRows(task, timeline, runs),+ () => (task ? buildRows(task, timeline ?? [], runs) : []),[task, timeline, runs],);const sources = useMemo(- () => (onlySource ? [onlySource] : commentSources(task.id, rows)),- [task.id, rows, onlySource],+ () => (onlySource ? [onlySource] : commentSources(taskId, rows)),+ [taskId, rows, onlySource],);const targets = useMemo(() =>@@ -362,11 +362,11 @@ export function TaskCommentsList({);const singleSourceComments = useCommentsQuery(onlySource?.target ?? null,- task.id,+ taskId,);const taskComments = useCommentsForTargetsQuery(onlySource ? [] : targets,- task.id,+ taskId,{live: true,intervalMs: POLL_INTERVAL_MS,@@ -418,9 +418,9 @@ export function TaskCommentsList({prUrls.length,]);- const taskTarget = useMemo(() => taskCommentTarget(task.id), [task.id]);+ const taskTarget = useMemo(() => taskCommentTarget(taskId), [taskId]);const composerTarget = onlySource?.target ?? taskTarget;- const createComment = useCreateComment(composerTarget, task.id);+ const createComment = useCreateComment(composerTarget, taskId);const threads = useMemo(() => {const reviewByUrl = new Map(prReviews.byUrl);@@ -514,20 +514,20 @@ export function TaskCommentsList({(thread: TaskCommentThread, requestThreadFocus = true) => {const origin = thread.origin;if (origin.kind === "pr-review" || origin.kind === "pr-conversation") {- openPrInReview(task.id, origin.prUrl);+ openPrInReview(taskId, origin.prUrl);if (origin.kind === "pr-review") {// The review pane scrolls by file; a specific comment is as close as it// gets until it grows a per-thread target.useReviewNavigationStore.getState()- .requestScrollToFile(task.id, origin.filePath);+ .requestScrollToFile(taskId, origin.filePath);}return;}const { source, root } = origin;if (source.kind === "canvas") {if (requestThreadFocus) {- requestCommentFocus(task.id, source.target, root.id);+ requestCommentFocus(taskId, source.target, root.id);}if (onCanvasCommentOpen) {onCanvasCommentOpen(@@ -540,16 +540,16 @@ export function TaskCommentsList({}// A thread on the task itself has nowhere else to open because it lives here.if (source.kind === "task" || !source.runId) return;- openArtifactTab(task.id, {+ openArtifactTab(taskId, {runId: source.runId,artifactId: source.target.itemId,name: source.name,});if (requestThreadFocus) {- requestCommentFocus(task.id, source.target, root.id);+ requestCommentFocus(taskId, source.target, root.id);}},- [onCanvasCommentOpen, openArtifactTab, requestCommentFocus, task.id],+ [onCanvasCommentOpen, openArtifactTab, requestCommentFocus, taskId],);// A thread picked on the artifact itself has to surface here, even when a@@ -558,7 +558,7 @@ export function TaskCommentsList({const focusedThreadId = focus?.threadId ?? null;const handledFocusRef = useRef<string | null>(null);useEffect(() => {- const focusKey = focus ? `${task.id}:${focus.nonce}` : null;+ const focusKey = focus ? `${taskId}:${focus.nonce}` : null;if (!focus || handledFocusRef.current === focusKey) return;const focused = threads.find((thread) => thread.id === focus.threadId);// The thread may still be loading, so wait rather than guess its filters.@@ -580,7 +580,7 @@ export function TaskCommentsList({);if (pane && thread) scrollThreadInPane(pane, thread);});- }, [focus, openThread, threads, task.id]);+ }, [focus, openThread, threads, taskId]);// The pulse fades on its own; owning the timer in its own effect keeps it// cleaned up on the next pulse or on unmount, without a stray ref.useEffect(() => {@@ -720,7 +720,7 @@ export function TaskCommentsList({thread={thread}source={thread.origin.source}root={thread.origin.root}- taskId={task.id}+ taskId={taskId}members={members}selected={thread.id === focusedThreadId}pulsing={thread.id === pulseThreadId}@@ -757,7 +757,7 @@ export function TaskCommentsList({mentions,});setDraft("");- requestCommentFocus(task.id, composerTarget, created.id, {+ requestCommentFocus(taskId, composerTarget, created.id, {intent: "focus-only",});}}diff --git a/products/desktop/packages/ui/src/features/canvas/components/activityFeed.test.ts b/products/desktop/packages/ui/src/features/canvas/components/activityFeed.test.tsindex 6fb5cd98776e..ac3d8ae5ab06 100644--- a/products/desktop/packages/ui/src/features/canvas/components/activityFeed.test.ts+++ b/products/desktop/packages/ui/src/features/canvas/components/activityFeed.test.ts@@ -107,8 +107,17 @@ describe("activityFeed", () => {activityAt: "2026-08-25T10:00:00Z",}) as TaskActivityItem;+ const canvasActivity: TaskActivityItem = {+ ...activity("canvas", "task-2"),+ commentTarget: { scope: "desktop_canvas", itemId: "canvas-1" },+ };+const content = deriveActivityFeedContent({- taskItems: [activity("live", "task-1"), activity("gone", "task-2")],+ taskItems: [+ activity("live", "task-1"),+ activity("gone", "task-2"),+ canvasActivity,+ ],reports: [],totalReportCount: 0,mentionsIncluded: true,@@ -117,10 +126,14 @@ describe("activityFeed", () => {archivedTaskIds: new Set(["task-2"]),});- expect(content.feedItems.map((item) => item.id)).toEqual(["task:live"]);+ expect(content.feedItems.map((item) => item.id)).toEqual([+ "task:live",+ "task:canvas",+ ]);expect(content.unreadItems.map((item) => item.id)).toEqual(["live","gone",+ "canvas",]);},);diff --git a/products/desktop/packages/ui/src/features/canvas/components/activityFeed.ts b/products/desktop/packages/ui/src/features/canvas/components/activityFeed.tsindex 447e35c4d028..f90236fe66b2 100644--- a/products/desktop/packages/ui/src/features/canvas/components/activityFeed.ts+++ b/products/desktop/packages/ui/src/features/canvas/components/activityFeed.ts@@ -1,4 +1,7 @@-import type { TaskActivityItem } from "@posthog/core/canvas/taskActivity";+import {+ activityCanvasId,+ type TaskActivityItem,+} from "@posthog/core/canvas/taskActivity";import { formatShortDayLabel, getLocalDayKey } from "@posthog/shared";import type { SignalReport } from "@posthog/shared/types";@@ -51,8 +54,11 @@ export function deriveActivityFeedContent({// Unreads stay whole: this is also what "Mark all as read" acts on, and an// archived task's unread update still counts against the badge.const unreadItems = getUnreadActivityItems(taskItems);+ // A canvas row outlives its generating task: the canvas is still there to+ // open, and the backend keeps counting the row as unread.const shownItems = taskItems.filter(- (item) => !archivedTaskIds.has(item.taskId),+ (item) =>+ activityCanvasId(item) !== null || !archivedTaskIds.has(item.taskId),);const visibleReports = unreadsOnly ? [] : reports;const visibleTaskItems = mentionsIncludeddiff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsxindex c91bf3f60556..dc0a22b35b78 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx@@ -3,23 +3,24 @@ import { fireEvent, render, screen } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";import { CanvasSidePanel } from "./CanvasSidePanel";+const mocks = vi.hoisted(() => ({+ task: undefined as { id: string; title: string } | undefined,+}));+vi.mock("@tanstack/react-query", async (importOriginal) => ({...(await importOriginal<typeof import("@tanstack/react-query")>()),- useQuery: () => ({ data: { id: "task-1", title: "Build canvas" } }),-}));-vi.mock("@posthog/ui/features/canvas/hooks/useThreadConversation", () => ({- useThreadConversation: () => ({ timeline: [{ kind: "message" }] }),+ useQuery: () => ({ data: mocks.task }),}));vi.mock("@posthog/ui/features/canvas/components/TaskCommentsList", () => ({TaskCommentsList: ({- task,+ taskId,onlySource,}: {- task: { id: string };+ taskId: string;onlySource: { target: { itemId: string } };}) => (<div data-testid="task-comments">- {task.id}:{onlySource.target.itemId}+ {taskId}:{onlySource.target.itemId}</div>),}));@@ -32,6 +33,7 @@ vi.mock("@posthog/ui/features/canvas/freeform/FreeformGenerateBar", () => ({describe("CanvasSidePanel", () => {beforeEach(() => {+ mocks.task = { id: "task-1", title: "Build canvas" };useCanvasChatPanelStore.setState({ tab: "chat", collapsed: false });});@@ -87,4 +89,28 @@ describe("CanvasSidePanel", () => {expect(screen.getByText("No run yet")).toBeInTheDocument();}});++ it("opens comments when the generating run is not readable", () => {+ mocks.task = undefined;+ useCanvasChatPanelStore.setState({ tab: "comments", collapsed: false });++ render(+ <CanvasSidePanel+ chatTaskId={null}+ commentTaskId="task-1"+ onMinimize={vi.fn()}+ dashboardId="canvas-1"+ channelId="channel-1"+ channelName="General"+ name="Launch canvas"+ displayedVersionId="version-2"+ commentVersionLabel={(versionId) => versionId}+ onCommentOpen={vi.fn()}+ />,+ );++ expect(screen.getByTestId("task-comments")).toHaveTextContent(+ "task-1:canvas-1",+ );+ });});diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsxindex 3e9845d95051..1bbc750df0b8 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx@@ -13,10 +13,8 @@ import {TooltipContent,TooltipTrigger,} from "@posthog/quill";-import type { Task } from "@posthog/shared/domain-types";import { TaskCommentsList } from "@posthog/ui/features/canvas/components/TaskCommentsList";import { FreeformGenerateBar } from "@posthog/ui/features/canvas/freeform/FreeformGenerateBar";-import { useThreadConversation } from "@posthog/ui/features/canvas/hooks/useThreadConversation";import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";import type { EditorHandle } from "@posthog/ui/features/message-editor/types";import { EmbeddedSessionView } from "@posthog/ui/features/sessions/components/EmbeddedSessionView";@@ -125,7 +123,7 @@ export function CanvasSidePanel({<div className="min-h-0 flex-1">{tab === "comments" && commentTaskId ? (- <CanvasCommentsLoader+ <CanvasCommentstaskId={commentTaskId}dashboardId={dashboardId}name={name}@@ -180,7 +178,7 @@ function CanvasChatLoader({ taskId }: { taskId: string }) {return <EmbeddedSessionView task={task} />;}-function CanvasCommentsLoader({+function CanvasComments({taskId,dashboardId,name,@@ -195,46 +193,9 @@ function CanvasCommentsLoader({commentVersionLabel: (versionId: string) => string | null;onCommentOpen: (versionId: string | null) => void;}) {- const { data: task } = useQuery(taskDetailQuery(taskId));-- if (!task) {- return <LoadingState />;- }-- return (- <CanvasTaskComments- task={task}- dashboardId={dashboardId}- name={name}- displayedVersionId={displayedVersionId}- commentVersionLabel={commentVersionLabel}- onCommentOpen={onCommentOpen}- />- );-}--function CanvasTaskComments({- task,- dashboardId,- name,- displayedVersionId,- commentVersionLabel,- onCommentOpen,-}: {- task: Task;- dashboardId: string;- name: string;- displayedVersionId: string | null;- commentVersionLabel: (versionId: string) => string | null;- onCommentOpen: (versionId: string | null) => void;-}) {- const { timeline } = useThreadConversation(task, {- surface: "activity_panel",- });return (<TaskCommentsList- task={task}- timeline={timeline}+ taskId={taskId}onlySource={{kind: "canvas",name,diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridChatPanel.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridChatPanel.tsxindex 222ec4c2b76a..60163890a2a2 100644--- a/products/desktop/packages/ui/src/features/canvas/grid/GridChatPanel.tsx+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridChatPanel.tsx@@ -7,10 +7,8 @@ import {TabsTrigger,Text,} from "@posthog/quill";-import type { Task } from "@posthog/shared/domain-types";import { TaskCommentsList } from "@posthog/ui/features/canvas/components/TaskCommentsList";import { useGenerateFreeformCanvas } from "@posthog/ui/features/canvas/hooks/useGenerateFreeformCanvas";-import { useThreadConversation } from "@posthog/ui/features/canvas/hooks/useThreadConversation";import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";import { EmbeddedSessionView } from "@posthog/ui/features/sessions/components/EmbeddedSessionView";import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";@@ -183,16 +181,16 @@ function CanvasComments({canvasVersionId: string | null;commentVersionLabel: (versionId: string) => string | null;}) {- const { data: task } = useQuery(taskDetailQuery(taskId));- if (!task) {- return <LoadingState className="flex-1" />;- }return (<div className="min-h-0 flex-1">- <GridCanvasComments- task={task}- canvasId={canvasId}- canvasName={canvasName}+ <TaskCommentsList+ taskId={taskId}+ onlySource={{+ kind: "canvas",+ name: canvasName,+ target: { scope: "desktop_canvas", itemId: canvasId },+ url: null,+ }}canvasVersionId={canvasVersionId}commentVersionLabel={commentVersionLabel}/>@@ -200,39 +198,6 @@ function CanvasComments({);}-// Its own component so useThreadConversation runs only once the task exists.-function GridCanvasComments({- task,- canvasId,- canvasName,- canvasVersionId,- commentVersionLabel,-}: {- task: Task;- canvasId: string;- canvasName: string;- canvasVersionId: string | null;- commentVersionLabel: (versionId: string) => string | null;-}) {- const { timeline } = useThreadConversation(task, {- surface: "activity_panel",- });- return (- <TaskCommentsList- task={task}- timeline={timeline}- onlySource={{- kind: "canvas",- name: canvasName,- target: { scope: "desktop_canvas", itemId: canvasId },- url: null,- }}- canvasVersionId={canvasVersionId}- commentVersionLabel={commentVersionLabel}- />- );-}-// No canvas-wide conversation yet: a one-field composer that starts one.function CanvasChatComposer({canvasId,diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useActivityTaskMenu.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useActivityTaskMenu.test.tsxnew file mode 100644index 000000000000..67aefc9d46d5--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useActivityTaskMenu.test.tsx@@ -0,0 +1,97 @@+import type { TaskActivityItem } from "@posthog/core/canvas/taskActivity";+import { renderHook } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++const hoisted = vi.hoisted(() => ({+ togglePin: vi.fn(() => Promise.resolve()),+ archiveTask: vi.fn(() => Promise.resolve()),+ placeTaskInCommandCenter: vi.fn(),+ placeCanvasInCommandCenter: vi.fn(),+}));++vi.mock("@posthog/ui/features/sidebar/usePinnedTasks", () => ({+ usePinnedTasks: () => ({+ pinnedTaskIds: new Set(["canvas-1"]),+ togglePin: hoisted.togglePin,+ }),+}));++vi.mock("@posthog/ui/features/archive/useArchiveTask", () => ({+ useArchiveTask: () => ({ archiveTask: hoisted.archiveTask }),+}));++vi.mock("@posthog/ui/features/command-center/commandCenterStore", () => ({+ useCommandCenterStore: (+ selector: (state: { cells: (string | null)[] }) => unknown,+ ) => selector({ cells: [null] }),+}));++vi.mock("@posthog/ui/features/command-center/placeTaskInCommandCenter", () => ({+ placeTaskInCommandCenter: hoisted.placeTaskInCommandCenter,+ placeCanvasInCommandCenter: hoisted.placeCanvasInCommandCenter,+}));++import { useActivityTaskMenu } from "./useActivityTaskMenu";++function item(overrides: Partial<TaskActivityItem>): TaskActivityItem {+ return {+ id: "activity-1",+ taskId: "task-1",+ taskTitle: "Say hello",+ channelId: "channel-1",+ channelName: null,+ activityAt: "2026-07-27T10:00:00Z",+ activityKind: "mention",+ snippet: "Hello!",+ author: null,+ messageId: null,+ isUnread: true,+ ...overrides,+ };+}++describe("useActivityTaskMenu", () => {+ it("acts on the canvas, not its generating task, for a canvas comment row", () => {+ const { result } = renderHook(() => useActivityTaskMenu());++ const menu = result.current(+ item({+ taskTitle: "Launch canvas",+ commentId: "comment-1",+ commentTarget: { scope: "desktop_canvas", itemId: "canvas-1" },+ }),+ );++ expect(menu).toMatchObject({+ kind: "canvas",+ id: "canvas-1",+ title: "Launch canvas",+ isPinned: true,+ channelId: "channel-1",+ });+ expect(menu.onArchive).toBeUndefined();+ expect(menu.onFile).toBeUndefined();+ menu.onTogglePin();+ expect(hoisted.togglePin).toHaveBeenCalledWith("canvas-1");+ menu.onAddToCommandCenter?.();+ expect(hoisted.placeCanvasInCommandCenter).toHaveBeenCalledWith(+ "canvas-1",+ "Launch canvas",+ );+ expect(hoisted.placeTaskInCommandCenter).not.toHaveBeenCalled();+ });++ it("keeps the task menu for a task row", () => {+ const { result } = renderHook(() => useActivityTaskMenu());++ const menu = result.current(+ item({+ commentId: "comment-1",+ commentTarget: { scope: "task_artifact", itemId: "artifact-1" },+ }),+ );++ expect(menu).toMatchObject({ kind: "task", id: "task-1" });+ expect(menu.onArchive).toBeDefined();+ });+});diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useActivityTaskMenu.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useActivityTaskMenu.tsindex 1f04986527e3..bcab79597000 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useActivityTaskMenu.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useActivityTaskMenu.ts@@ -1,8 +1,14 @@-import type { TaskActivityItem } from "@posthog/core/canvas/taskActivity";+import {+ activityCanvasId,+ type TaskActivityItem,+} from "@posthog/core/canvas/taskActivity";import { useArchiveTask } from "@posthog/ui/features/archive/useArchiveTask";import type { TaskRowMenuProps } from "@posthog/ui/features/canvas/components/TaskRowMenu";import { useCommandCenterStore } from "@posthog/ui/features/command-center/commandCenterStore";-import { placeTaskInCommandCenter } from "@posthog/ui/features/command-center/placeTaskInCommandCenter";+import {+ placeCanvasInCommandCenter,+ placeTaskInCommandCenter,+} from "@posthog/ui/features/command-center/placeTaskInCommandCenter";import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";import { toast } from "@posthog/ui/primitives/toast";import { useCallback, useEffect, useRef } from "react";@@ -15,6 +21,12 @@ import { useCallback, useEffect, useRef } from "react";* inline editor; hand off and analysis need the task itself, which an activity* row doesn't carry — it holds one update about a task, not the task.*+ * A canvas comment row gets the canvas menu instead. Its `taskId` is the task+ * that generated the canvas, which may sit in another space or be one the+ * reader can't open, so task actions on it would fail or move the wrong item.+ * Filing and deleting a canvas need its own mutations and a confirm, which the+ * feed doesn't carry, so those two stay off here.+ ** Built once for the feed rather than per row: each hook here is a mutation or* a store subscription, and the feed shows a page of rows at a time.*/@@ -35,27 +47,47 @@ export function useActivityTaskMenu(): (});return useCallback(- (item) => ({- kind: "task",- id: item.taskId,- title: item.taskTitle,- isPinned: pinnedTaskIds.has(item.taskId),- // Ticks the space the task is already filed to, inside "File to…".- channelId: item.channelId ?? undefined,- onAddToCommandCenter: cells.includes(item.taskId)- ? undefined- : () => placeTaskInCommandCenter(item.taskId, item.taskTitle),- onTogglePin: () => {- togglePin(item.taskId).catch(() => {- toast.error("Couldn't update pin");- });- },- onArchive: () => {- archiveRef.current({ taskId: item.taskId }).catch(() => {- toast.error("Couldn't archive task");- });- },- }),+ (item) => {+ const canvasId = activityCanvasId(item);+ if (canvasId) {+ return {+ kind: "canvas",+ id: canvasId,+ title: item.taskTitle,+ isPinned: pinnedTaskIds.has(canvasId),+ channelId: item.channelId ?? undefined,+ onAddToCommandCenter: cells.includes(canvasId)+ ? undefined+ : () => placeCanvasInCommandCenter(canvasId, item.taskTitle),+ onTogglePin: () => {+ togglePin(canvasId).catch(() => {+ toast.error("Couldn't update pin");+ });+ },+ };+ }+ return {+ kind: "task",+ id: item.taskId,+ title: item.taskTitle,+ isPinned: pinnedTaskIds.has(item.taskId),+ // Ticks the space the task is already filed to, inside "File to…".+ channelId: item.channelId ?? undefined,+ onAddToCommandCenter: cells.includes(item.taskId)+ ? undefined+ : () => placeTaskInCommandCenter(item.taskId, item.taskTitle),+ onTogglePin: () => {+ togglePin(item.taskId).catch(() => {+ toast.error("Couldn't update pin");+ });+ },+ onArchive: () => {+ archiveRef.current({ taskId: item.taskId }).catch(() => {+ toast.error("Couldn't archive task");+ });+ },+ };+ },[cells, pinnedTaskIds, togglePin],);}diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex ed3949c99bfc..5e20138896a7 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -39,7 +39,7 @@ from django.db.models import (When,)from django.db.models.fields.json import KeyTextTransform, KeyTransform-from django.db.models.functions import Coalesce+from django.db.models.functions import Cast, Coalescefrom django.utils import timezone as django_timezonefrom django.utils.http import content_disposition_header@@ -9657,10 +9657,70 @@ def _task_activity_qs(team_id: int, user_id: int) -> QuerySet[TaskActivity]:return TaskActivity.objects.for_team(team_id).filter(user_id=user_id, task__in=visible_tasks)+def _visible_canvas_comment_ids(team_id: int, user_id: int) -> QuerySet[Canvas, dict[str, str]]:+ return (+ Canvas.objects.for_team(team_id)+ .filter(deleted=False)+ .filter(visible_channels_q(user_id, relation="channel"))+ .annotate(comment_item_id=Cast("id", output_field=CharField()))+ .values("comment_item_id")+ )++def _comment_activity_qs(team_id: int, user_id: int) -> QuerySet[TaskCommentActivity]:visible_tasks = _activity_visible_task_qs(team_id, user_id)- return TaskCommentActivity.objects.for_team(team_id).filter(- user_id=user_id, task__in=visible_tasks, comment__deleted=False+ return (+ TaskCommentActivity.objects.for_team(team_id)+ .filter(user_id=user_id, comment__deleted=False)+ .filter(+ Q(comment__scope="desktop_canvas", comment__item_id__in=_visible_canvas_comment_ids(team_id, user_id))+ | (~Q(comment__scope="desktop_canvas") & Q(task__in=visible_tasks))+ )+ )+++def _visible_canvases_by_id(+ team_id: int, user_id: int, comment_rows: Sequence[TaskCommentActivity]+) -> dict[str, Canvas]:+ canvas_ids: list[UUID] = []+ for row in comment_rows:+ if row.comment.scope != "desktop_canvas":+ continue+ try:+ canvas_ids.append(UUID(row.comment.item_id))+ except ValueError:+ continue+ if not canvas_ids:+ return {}+ canvases = (+ Canvas.objects.for_team(team_id)+ .filter(id__in=canvas_ids, deleted=False)+ .filter(visible_channels_q(user_id, relation="channel"))+ .select_related("channel")+ )+ return {str(canvas.id): canvas for canvas in canvases}+++@frozen+class _ActivityTaskDetails:+ title: str+ channel_id: UUID | None+ channel_name: str | None+++def _activity_task_details(+ row: TaskActivity | TaskCommentActivity, canvases_by_id: dict[str, Canvas]+) -> _ActivityTaskDetails:+ if isinstance(row, TaskCommentActivity) and row.comment.scope == "desktop_canvas" and row.comment.item_id:+ canvas = canvases_by_id.get(row.comment.item_id)+ if canvas is not None:+ return _ActivityTaskDetails(+ title=canvas.name, channel_id=canvas.channel_id, channel_name=canvas.channel.name+ )+ return _ActivityTaskDetails(+ title=row.task.title,+ channel_id=row.task.channel_id,+ channel_name=row.task.channel.name if row.task.channel else None,)@@ -9696,8 +9756,12 @@ def list_task_activity(task_qs = task_qs.filter(cursor)comment_qs = comment_qs.filter(cursor)task_rows = task_qs.select_related("task__channel", "message__author").order_by("-activity_at", "-id")[: limit + 1]- comment_rows = comment_qs.select_related("task__channel", "comment__created_by").order_by("-activity_at", "-id")[- : limit + 1+ comment_rows = list(+ comment_qs.select_related("task__channel", "comment__created_by").order_by("-activity_at", "-id")[: limit + 1]+ )+ canvases_by_id = _visible_canvases_by_id(team_id, user_id, comment_rows)+ comment_rows = [+ row for row in comment_rows if row.comment.scope != "desktop_canvas" or row.comment.item_id in canvases_by_id]activity_rows: list[TaskActivity | TaskCommentActivity] = [*task_rows, *comment_rows]rows: list[TaskActivity | TaskCommentActivity] = sorted(@@ -9714,9 +9778,9 @@ def list_task_activity(contracts.TaskActivityDTO(id=row.id,task_id=row.task_id,- task_title=row.task.title,- channel_id=row.task.channel_id,- channel_name=row.task.channel.name if row.task.channel else None,+ task_title=task_details.title,+ channel_id=task_details.channel_id,+ channel_name=task_details.channel_name,activity_at=row.activity_at,activity_kind=row.kind,snippet=_bounded_activity_snippet(@@ -9736,6 +9800,7 @@ def list_task_activity(is_unread=row.read_at is None,)for row in rows+ for task_details in [_activity_task_details(row, canvases_by_id)]],unread_count=count_unread_task_activity(team_id, user_id),next_before=next_row.activity_at if next_row else None,diff --git a/products/tasks/backend/logic/services/comment_activity.py b/products/tasks/backend/logic/services/comment_activity.pyindex 47c8d45ea5b7..9e3b3641b900 100644--- a/products/tasks/backend/logic/services/comment_activity.py+++ b/products/tasks/backend/logic/services/comment_activity.py@@ -89,7 +89,10 @@ def project_comment_activity(task_id = comment_task_id(comment)if task_id is None:return- task = _notification_tasks(team_id).filter(id=task_id).only("created_by_id").first()+ if comment.scope == "desktop_canvas":+ task = Task.objects.filter(team_id=team_id, id=task_id).only("created_by_id").first()+ else:+ task = _notification_tasks(team_id).filter(id=task_id).only("created_by_id").first()if task is None:return@@ -119,12 +122,26 @@ def project_comment_activity()except (ValueError, DjangoValidationError):pass- owner_id = owner_id or task.created_by_id+ if owner_id is None and comment.scope == "desktop_canvas" and comment.item_id:+ from products.canvas.backend.comment_access import canvas_owner_id++ owner_id = canvas_owner_id(team_id=team_id, canvas_id=comment.item_id)+ if comment.scope != "desktop_canvas":+ owner_id = owner_id or task.created_by_idif owner_id:recipients[owner_id] = TaskCommentActivity.Kind.OWNED_ITEM_COMMENTrecipients.update((user_id, TaskCommentActivity.Kind.MENTION) for user_id in mentioned_user_ids)recipients.pop(comment.created_by_id, None)+ if comment.scope == "desktop_canvas":+ from products.canvas.backend.comment_access import visible_canvas_user_ids++ visible_user_ids = visible_canvas_user_ids(+ team_id=team_id,+ canvas_id=comment.item_id,+ user_ids=recipients,+ )+ recipients = {user_id: kind for user_id, kind in recipients.items() if user_id in visible_user_ids}TaskCommentActivity.record_many(team_id=team_id,task_id=task_id,diff --git a/products/tasks/backend/logic/services/comment_slack_dm.py b/products/tasks/backend/logic/services/comment_slack_dm.pyindex 1cfa6f170f85..5338075aa6c1 100644--- a/products/tasks/backend/logic/services/comment_slack_dm.py+++ b/products/tasks/backend/logic/services/comment_slack_dm.py@@ -15,11 +15,13 @@ from urllib.parse import urlencodefrom uuid import UUIDfrom django.conf import settings+from django.core.exceptions import ValidationErrorimport structlogfrom posthog.comment.access import task_comment_target_is_accessiblefrom posthog.comment.formatting import escape_slack_mrkdwn, rich_content_to_slack_payload+from posthog.dataclasses import frozenfrom posthog.helpers.slack_identity import resolve_slack_userfrom posthog.models.comment import Commentfrom posthog.models.integration import Integration, SlackIntegration@@ -29,6 +31,7 @@ from posthog.models.user import NOTIFICATION_DEFAULTS, Userfrom posthog.models.user_integration import UserIntegrationfrom posthog.user_permissions import UserPermissions+from products.canvas.backend.models import Canvasfrom products.slack_app.backend.feature_flags import is_slack_app_oauth_enabledfrom products.slack_app.backend.services.slack_user_info import lookup_slack_user_id_by_emailfrom products.tasks.backend.models import Task, TaskCommentActivity@@ -47,7 +50,6 @@ _MAX_MENTION_LOOKUPS_PER_SLACK_WORKSPACE = 20_ACCENT = "good"_LOCATIONS: Mapping[str, str] = {- "desktop_canvas": "On a canvas","task_artifact": "On an artifact",}@@ -94,6 +96,9 @@ def send_comment_slack_dms(*, team_id: int, comment_id: UUID, task_id: UUID, rectask = Task.objects.filter(team_id=team_id, id=task_id).only("id", "team_id", "title").first()if task is None:return _skip(comment_id, "task_missing")+ link = _link_target(comment=comment, task=task)+ if link is None:+ return _skip(comment_id, "canvas_missing")team = Team.objects.filter(id=team_id).only("id", "organization_id").first()if team is None:@@ -179,7 +184,7 @@ def send_comment_slack_dms(*, team_id: int, comment_id: UUID, task_id: UUID, recheading, blocks = _message(kind=kind,comment=comment,- task=task,+ link=link,organization_id=team.organization_id,slack_user_id_by_email=_mention_resolver(organization_id=team.organization_id,@@ -366,21 +371,52 @@ def _bridge_url(*, comment: Comment, task: Task) -> str:return f"{settings.SITE_URL}/code/task/{task.id}?{urlencode(params)}"+@frozen+class _LinkTarget:+ title: str+ url: str+++def _link_target(*, comment: Comment, task: Task) -> _LinkTarget | None:+ """The item the heading names and links to.++ A canvas comment links to the canvas, not to the task that generated it. Canvas access follows+ the space the canvas lives in, so a recipient can see the canvas without seeing the task. A task+ link would then name a task they cannot open and leak its title.+ """+ if comment.scope != "desktop_canvas":+ return _LinkTarget(title=task.title or "a task", url=_bridge_url(comment=comment, task=task))+ if not comment.item_id:+ return None+ try:+ canvas = (+ Canvas.objects.for_team(comment.team_id)+ .filter(id=comment.item_id, deleted=False)+ .only("id", "channel_id", "name")+ .first()+ )+ except (ValueError, ValidationError):+ return None+ if canvas is None:+ return None+ return _LinkTarget(+ title=canvas.name or "a canvas", url=f"{settings.SITE_URL}/code/canvas/{canvas.channel_id}/{canvas.id}"+ )++def _message(*,kind: str,comment: Comment,- task: Task,+ link: _LinkTarget,organization_id: str | UUID | None,slack_user_id_by_email: Callable[[str], str | None] | None = None,) -> tuple[str, list[dict]]:- url = _bridge_url(comment=comment, task=task)- title = task.title or "a task"author = _author_name(comment)template = _HEADINGS.get(kind, _HEADINGS[TaskCommentActivity.Kind.MENTION])# A pipe in the title would end the link label early, so it can't survive into the label.- label = escape_slack_mrkdwn(title).replace("|", "-")- heading = template.format(author=f"*{escape_slack_mrkdwn(author)}*", link=f"<{url}|{label}>")+ label = escape_slack_mrkdwn(link.title).replace("|", "-")+ heading = template.format(author=f"*{escape_slack_mrkdwn(author)}*", link=f"<{link.url}|{label}>")body, _ = rich_content_to_slack_payload(comment.rich_content,@@ -393,7 +429,7 @@ def _message(blocks: list[dict] = []if body:blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": body}})- # Three canvases in one task otherwise produce three identical headings.+ # Several artifacts in one task otherwise produce identical headings.location = _LOCATIONS.get(comment.scope)if location:blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": location}]})diff --git a/products/tasks/backend/tests/test_comment_activity.py b/products/tasks/backend/tests/test_comment_activity.pyindex 732def4ac1e7..59ec6f3c4195 100644--- a/products/tasks/backend/tests/test_comment_activity.py+++ b/products/tasks/backend/tests/test_comment_activity.py@@ -7,7 +7,7 @@ from posthog.models.scoping import team_scopefrom products.canvas.backend.models import Canvasfrom products.tasks.backend.facade import api as tasks_facade-from products.tasks.backend.models import Channel, Task, TaskActivity, TaskCommentActivity, TaskRun+from products.tasks.backend.models import Channel, ChannelMembership, Task, TaskActivity, TaskCommentActivity, TaskRunclass CommentActivityTestCase(TestCase):@@ -68,10 +68,37 @@ class TestCommentActivity(CommentActivityTestCase):assert TaskCommentActivity.objects.filter(team=self.team, user=self.author, task=self.task).exists()- def test_canvas_comment_uses_its_generation_task(self):+ @parameterized.expand(+ [+ ("public", Channel.ChannelType.PUBLIC, False, False, True),+ ("private_member", Channel.ChannelType.PRIVATE, True, False, True),+ ("private_non_member", Channel.ChannelType.PRIVATE, False, False, False),+ ("personal_owner", Channel.ChannelType.PERSONAL, False, True, True),+ ("personal_non_owner", Channel.ChannelType.PERSONAL, False, False, False),+ ]+ )+ def test_canvas_comment_activity_follows_canvas_visibility(+ self, _name: str, channel_type: str, invite_author: bool, author_owns_channel: bool, expected: bool+ ) -> None:+ generation_channel = Channel.objects.create(+ team=self.team,+ name="generation",+ channel_type=Channel.ChannelType.PRIVATE,+ created_by=self.peer,+ )+ self.task.channel = generation_channel+ self.task.save(update_fields=["channel"])+ channel = Channel.objects.create(+ team=self.team,+ name="canvas-space",+ channel_type=channel_type,+ created_by=self.author if author_owns_channel else self.peer,+ )+ if invite_author:+ ChannelMembership.objects.create(team=self.team, channel=channel, user=self.author)canvas = Canvas.objects.create(team=self.team,- channel=self.channel,+ channel=channel,name="Launch canvas",created_by=self.peer,generation_task_id=self.task.id,@@ -80,7 +107,30 @@ class TestCommentActivity(CommentActivityTestCase):self._record_activity(comment, [self.author.id])- assert TaskCommentActivity.objects.filter(team=self.team, user=self.author, task=self.task).exists()+ activity = TaskCommentActivity.objects.filter(team=self.team, user=self.author, comment=comment).first()+ assert (activity is not None) is expected+ if expected:+ assert activity is not None+ page = tasks_facade.list_task_activity(self.team.id, self.author.id)+ row = next(row for row in page.results if row.id == activity.id)+ assert row.task_title == canvas.name+ assert row.channel_id == canvas.channel_id+ assert row.channel_name == channel.name++ def test_canvas_comment_resolves_its_owner_when_the_caller_passes_none(self):+ canvas = Canvas.objects.create(+ team=self.team,+ channel=self.channel,+ name="Launch canvas",+ created_by=self.author,+ generation_task_id=self.task.id,+ )+ comment = self._comment(scope="desktop_canvas", item_id=str(canvas.id))++ self._record_activity(comment)++ row = TaskCommentActivity.objects.get(team=self.team, user=self.author, comment=comment)+ assert row.kind == TaskCommentActivity.Kind.OWNED_ITEM_COMMENTdef test_feed_renders_the_comment_author_and_text(self):comment = self._comment()diff --git a/products/tasks/backend/tests/test_comment_slack_dm.py b/products/tasks/backend/tests/test_comment_slack_dm.pyindex dfa26d7a27ef..f5df2b5d64bd 100644--- a/products/tasks/backend/tests/test_comment_slack_dm.py+++ b/products/tasks/backend/tests/test_comment_slack_dm.py@@ -1,5 +1,7 @@from unittest.mock import MagicMock, patch+from django.conf import settings+from parameterized import parameterizedfrom posthog.constants import AvailableFeature@@ -10,7 +12,7 @@ from posthog.models.user_integration import UserIntegrationfrom products.access_control.backend.models.access_control import AccessControlfrom products.canvas.backend.models import Canvasfrom products.tasks.backend.logic.services.comment_slack_dm import send_comment_slack_dms-from products.tasks.backend.models import Channel, TaskCommentActivity+from products.tasks.backend.models import Channel, ChannelMembership, TaskCommentActivityfrom products.tasks.backend.tests.test_comment_activity import CommentActivityTestCaseSLACK_WORKSPACE_ID = "T123"@@ -198,10 +200,25 @@ class TestCommentSlackDm(CommentActivityTestCase):assert self._dm_channels() == []- def test_canvas_comment_dms_a_recipient_who_can_access_its_task(self):+ def test_canvas_comment_dms_a_recipient_who_can_access_its_space(self):+ generation_channel = Channel.objects.create(+ team=self.team,+ name="generation",+ channel_type=Channel.ChannelType.PERSONAL,+ created_by=self.peer,+ )+ self.task.channel = generation_channel+ self.task.save(update_fields=["channel"])+ canvas_channel = Channel.objects.create(+ team=self.team,+ name="canvas-space",+ channel_type=Channel.ChannelType.PRIVATE,+ created_by=self.peer,+ )+ ChannelMembership.objects.create(team=self.team, channel=canvas_channel, user=self.author)canvas = Canvas.objects.create(team=self.team,- channel=self.channel,+ channel=canvas_channel,name="Launch canvas",created_by=self.peer,generation_task_id=self.task.id,@@ -211,10 +228,10 @@ class TestCommentSlackDm(CommentActivityTestCase):self._record_activity(comment, [self.author.id])assert self._dm_channels() == ["U-author"]- assert (- f"/code/task/{self.task.id}?comment={comment.id}&scope=desktop_canvas&item={canvas.id}"- in self._dm_heading()- )+ heading = self._dm_heading()+ assert f"<{settings.SITE_URL}/code/canvas/{canvas_channel.id}/{canvas.id}|Launch canvas>" in heading+ assert self.task.title not in heading+ assert str(self.task.id) not in headingdef test_dm_links_to_the_desktop_task_bridge_anchored_on_the_comment(self):comment = self._comment()