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.

fix(tasks): allow flagged users to analyze public tasks (#87668)

Shy Alter103ecc6cd5b1
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
index fb6549fbc540..7881890be2b2 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
@@ -843,6 +843,7 @@ const FeedItem = memo(function FeedItem({
id: task.id,
title: task.title,
isPinned: taskData?.isPinned ?? false,
+ task,
channelId: task.channel ?? undefined,
onAddToCommandCenter: commandCenterCells.includes(task.id)
? undefined
@@ -860,6 +861,7 @@ const FeedItem = memo(function FeedItem({
archiveTaskFromFeed,
beginTitleEdit,
canStop,
+ task,
commandCenterCells,
task.channel,
task.id,
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
index 9773aa64ed7b..e2c3e00bd7ae 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
@@ -1,5 +1,6 @@
import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
import { formatRelativeTimeShort } from "@posthog/shared";
+import type { Task } from "@posthog/shared/domain-types";
import { CANVAS_DRAG_TYPE } from "@posthog/ui/features/canvas/canvasDrag";
import type { TaskStatusInput } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";
import {
@@ -19,6 +20,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
status: null as TaskStatusInput | null,
currentUserId: 999 as number | undefined,
+ analysis: {
+ canAnalyze: false,
+ isPending: false,
+ run: vi.fn(),
+ },
}));
vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({
useCurrentUser: () => ({ data: { id: mocks.currentUserId } }),
@@ -37,6 +43,12 @@ vi.mock("@posthog/ui/features/canvas/hooks/useFileTaskToChannel", () => ({
vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
useFeatureFlag: () => true,
}));
+vi.mock(
+ "@posthog/ui/features/task-detail/components/TaskAnalysisButton",
+ () => ({
+ useTaskAnalysis: () => mocks.analysis,
+ }),
+);
// The handoff dialog is tested on its own; here it only opens.
vi.mock(
"@posthog/ui/features/task-detail/components/HandoffTaskDialog",
@@ -103,6 +115,7 @@ function renderRow(model: ChannelItemModel) {
beforeEach(() => {
mocks.status = null;
+ mocks.analysis = { canAnalyze: false, isPending: false, run: vi.fn() };
useSidebarStore.setState({ listItemMetadataFields: [] });
usePendingCanvasDeleteStore.setState({ pending: {} });
useTaskSelectionStore.setState({
@@ -389,6 +402,38 @@ describe("ChannelItemRow", () => {
}
});
+ it("offers Run analysis for a task with a terminal run", () => {
+ const run = vi.fn();
+ mocks.analysis = { canAnalyze: true, isPending: false, run };
+ const task = {
+ id: "task-1",
+ task_number: 1,
+ slug: "task-1",
+ title: "Investigate signup drop-off",
+ description: "",
+ created_at: "2026-07-16T12:00:00.000Z",
+ updated_at: "2026-07-16T12:00:00.000Z",
+ origin_product: "user_created",
+ latest_run: { id: "run-1", status: "completed" },
+ } as Task;
+
+ renderInList(
+ <ChannelItemRow
+ actions={actions}
+ isActive={false}
+ item={item({ task })}
+ />,
+ );
+ fireEvent.contextMenu(screen.getByText("Investigate signup drop-off"));
+
+ const analysisItem = screen.getByRole("menuitem", {
+ name: "Run analysis",
+ });
+ expect(analysisItem).not.toBeNull();
+ fireEvent.click(analysisItem);
+ expect(run).toHaveBeenCalledOnce();
+ });
+
it("offers Hand off… only to the task's owner", async () => {
// The API 404s a non-owner's handoff, so the menu must not offer it to one.
const ownerItem = item({
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
index e76e493f417b..8df9e7e82cc4 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
@@ -343,6 +343,7 @@ export function ChannelItemRow({
id: item.id,
title: item.title,
isPinned: item.pinned,
+ task: item.task ?? undefined,
channelId,
onAddToCommandCenter,
onRename,
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
index 070bdb1ca7b2..7a2bb010eae8 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
@@ -489,6 +489,7 @@ const SpaceTaskRow = memo(function SpaceTaskRow({
id: item.id,
title: item.title,
isPinned: item.pinned,
+ task: item.task ?? undefined,
// Ticks the space the session is already in, inside "File to…".
channelId: spaceId,
onAddToCommandCenter: actions.commandCenterAssigner(item.id),
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
index e98e70c398a7..5940f5553a4c 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
@@ -3,6 +3,7 @@ import {
CaretRightIcon,
DotsThreeIcon,
FolderSimpleIcon,
+ MagnifyingGlassIcon,
PencilSimpleIcon,
PushPinIcon,
PushPinSlashIcon,
@@ -28,16 +29,24 @@ import {
DropdownMenuTrigger,
} from "@posthog/quill";
import { PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";
+import type { Task } from "@posthog/shared/domain-types";
import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";
import { useFileTaskToChannel } from "@posthog/ui/features/canvas/hooks/useFileTaskToChannel";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import type { SidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";
+import { useTaskAnalysis } from "@posthog/ui/features/task-detail/components/TaskAnalysisButton";
import {
type MenuFlyoutItem,
MenuSubFlyout,
SearchableMenuFlyout,
} from "@posthog/ui/primitives/SearchableMenuFlyout";
-import { type ComponentType, type ReactNode, useMemo, useState } from "react";
+import {
+ type ComponentType,
+ type ReactElement,
+ type ReactNode,
+ useMemo,
+ useState,
+} from "react";
/**
* What a row's menu can do. The row owns the handlers because they're the same
@@ -53,6 +62,7 @@ export interface TaskRowMenuProps {
id: string;
title: string;
isPinned: boolean;
+ task?: Task;
/** The channel this task is already filed to, ticked in "File to…". */
channelId?: string;
/** Absent when the command centre is full, which disables the item. */
@@ -95,6 +105,24 @@ const DROPDOWN_PARTS: MenuParts = {
SubTrigger: DropdownMenuSubTrigger,
};
+function TaskAnalysisMenuItem({
+ Item,
+ task,
+}: {
+ Item: MenuParts["Item"];
+ task: Task;
+}): ReactElement | null {
+ const { canAnalyze, isPending, run } = useTaskAnalysis(task);
+ if (!canAnalyze) return null;
+
+ return (
+ <Item disabled={isPending} onClick={run}>
+ <MagnifyingGlassIcon size={14} />
+ {isPending ? "Analyzing…" : "Run analysis"}
+ </Item>
+ );
+}
+
/**
* The row's actions, in the order the native menu used: the edits, then the
* places a task can be sent, then the destructive one last.
@@ -114,6 +142,7 @@ function TaskRowMenuItems({
import.meta.env.DEV,
);
const isTask = menu.kind === "task";
+ const analysisTask = isTask && menu.task?.latest_run ? menu.task : null;
const { channels } = useChannels({ enabled: bluebirdEnabled && isTask });
const fileToChannel = useFileTaskToChannel();
@@ -140,6 +169,7 @@ function TaskRowMenuItems({
Rename
</Item>
)}
+ {analysisTask && <TaskAnalysisMenuItem Item={Item} task={analysisTask} />}
{menu.onStop && (
<Item onClick={menu.onStop}>
<StopCircle size={14} />
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskAnalysisButton.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskAnalysisButton.tsx
index c585d3dc50b6..bf342c00b19b 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskAnalysisButton.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskAnalysisButton.tsx
@@ -7,6 +7,7 @@ import {
import type { Task } from "@posthog/shared/domain-types";
import { toastError } from "@posthog/ui/features/notifications/errorDetails";
import { toast } from "@posthog/ui/primitives/toast";
+import type { ReactElement } from "react";
import { useAuthenticatedMutation } from "../../../hooks/useAuthenticatedMutation";
import { navigateToTaskDetail } from "../../../router/navigationBridge";
import { track } from "../../../shell/analytics";
@@ -17,11 +18,15 @@ interface AnalyzeResult {
created: boolean;
}
-export function TaskAnalysisButton({ task }: { task: Task }) {
+export interface TaskAnalysisControls {
+ canAnalyze: boolean;
+ isPending: boolean;
+ run: () => void;
+}
+
+export function useTaskAnalysis(task: Task): TaskAnalysisControls {
const enabled = useFeatureFlag(TASK_ANALYSIS_FLAG) || import.meta.env.DEV;
const runId = task.latest_run?.id;
- const isAnalyzableOrigin = task.origin_product !== "task_analysis";
-
const mutation = useAuthenticatedMutation<AnalyzeResult, Error, void>(
(client) => {
if (!runId) throw new Error("This task has no run to analyze yet.");
@@ -47,21 +52,33 @@ export function TaskAnalysisButton({ task }: { task: Task }) {
},
);
- if (
- !enabled ||
- !runId ||
- !isAnalyzableOrigin ||
- !isTerminalStatus(task.latest_run?.status)
- )
- return null;
+ return {
+ canAnalyze:
+ enabled &&
+ !!runId &&
+ task.origin_product !== "task_analysis" &&
+ isTerminalStatus(task.latest_run?.status),
+ isPending: mutation.isPending,
+ run: () => mutation.mutate(),
+ };
+}
+
+export function TaskAnalysisButton({
+ task,
+}: {
+ task: Task;
+}): ReactElement | null {
+ const { canAnalyze, isPending, run } = useTaskAnalysis(task);
+
+ if (!canAnalyze) return null;
return (
<Button
size="sm"
variant="outline"
- onClick={() => mutation.mutate()}
- loading={mutation.isPending}
- disabled={mutation.isPending}
+ onClick={run}
+ loading={isPending}
+ disabled={isPending}
>
Run analysis
</Button>
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 65ab57149746..87f51729a49f 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -1242,10 +1242,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def _is_sandbox_agent_request(self, task_id: str) -> bool:
return is_sandbox_agent_request(self.request, task_id)
- # Actions that only read run state. Everything else mutates or drives the
- # run, so it requires task control (not just visibility): public-channel
- # visibility lets teammates watch a run, never command it. connection_token
- # is a GET but mints a write-capable token, so it is deliberately absent.
+ # Actions that only read run state. The visibility-only exception creates a
+ # separate analysis task without driving the target run. Other actions
+ # require task control (not just visibility): public-channel visibility lets
+ # teammates watch a run, never command it. connection_token is a GET but
+ # mints a write-capable token, so it is deliberately absent.
_READ_ONLY_ACTIONS = (
"list",
"retrieve",
@@ -1258,6 +1259,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"artifacts_download",
"artifacts_download_by_id",
)
+ _VISIBILITY_ONLY_ACTIONS = ("analyze",)
def _one_shot_analysis_response(self, task_id: str) -> Response | None:
"""Refuse to add runs to a server-created analysis task; see the facade reader."""
@@ -1272,6 +1274,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Gate access to the parent task, including exact task-bound sandbox access."""
task_id = self._task_id()
is_read_only = self.action in self._READ_ONLY_ACTIONS
+ is_visibility_only = self.action in self._VISIBILITY_ONLY_ACTIONS
bypass_visibility = self._is_sandbox_agent_request(task_id) or (
is_read_only and _can_bypass_visibility(self.request, self.team_id)
)
@@ -1280,7 +1283,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
self.team_id,
self._user_id(),
bypass_visibility=bypass_visibility,
- for_control=not is_read_only,
+ for_control=not (is_read_only or is_visibility_only),
):
raise NotFound("Task not found")
run_id = self.kwargs.get("pk")
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 5f430b30b68a..e923545fb9e1 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -13461,6 +13461,35 @@ class TestTaskRunAnalyzeAPI(BaseTaskAPITest):
mock_dispatch.assert_called_once()
self.assertEqual(run.state["pending_dispatch"]["posthog_mcp_scopes"], "read_only")
+ def test_flagged_user_can_analyze_a_teammate_public_task(self):
+ teammate = self.create_organization_user("teammate")
+ channel = Channel.objects.unscoped().create(
+ team=self.team,
+ name="shared-analysis",
+ created_by=teammate,
+ )
+ task = Task.objects.create(
+ team=self.team,
+ created_by=teammate,
+ channel=channel,
+ title="Teammate task",
+ description="Inspect it",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ )
+
+ read_p, write_p, tag_p, dispatch_p = self._patch_boundaries()
+ with read_p, write_p, tag_p, dispatch_p:
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/analyze/")
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertTrue(response.json()["created"])
+ self.assertEqual(Task.objects.filter(origin_product=Task.OriginProduct.TASK_ANALYSIS).count(), 1)
+
def test_analyze_is_idempotent_per_run(self):
read_p, write_p, tag_p, dispatch_p = self._patch_boundaries()
with read_p, write_p, tag_p, dispatch_p: