: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(tasks): re-gate cloud task execution on desktop access (#82993)
Charles Vien92acee33c583
diff --git a/products/mcp_analytics/frontend/tool-quality/CreateFixTaskButton.tsx b/products/mcp_analytics/frontend/tool-quality/CreateFixTaskButton.tsxindex d1b69626db23..c62aefc535fa 100644--- a/products/mcp_analytics/frontend/tool-quality/CreateFixTaskButton.tsx+++ b/products/mcp_analytics/frontend/tool-quality/CreateFixTaskButton.tsx@@ -31,7 +31,6 @@ export function CreateFixTaskButton({size={size}icon={<IconWrench />}tooltip="Create a task and start a fix agent on it"- // Without a repository the agent has no codebase to fix, so a task must not start.disabledReason={githubIntegrations.length === 0? 'Connect the GitHub integration (Settings → Integrations) to give the fix agent a repository'diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.pyindex 1d1c869ae188..728768f302b2 100644--- a/products/signals/backend/routes.py+++ b/products/signals/backend/routes.py@@ -1,6 +1,7 @@from posthog.api.routing import RouterRegistryimport products.signals.backend.views as signals+from products.signals.backend.scout_chat import SignalScoutChatTaskViewSetfrom products.signals.backend.scout_harness.views import (SignalProjectProfileViewSet,SignalScoutConfigViewSet,@@ -67,4 +68,13 @@ def register_routes(routers: RouterRegistry) -> None:"project_signals_scout_members",["team_id"],)+ # Scout chat kickoff: server-minted tasks with the reserved SIGNALS_CHAT origin, so the+ # generally-available Inbox chat CTAs work without the Desktop waitlist that gates the+ # generic task run endpoints.+ routers.projects.register(+ r"signals/scout/chat_tasks",+ SignalScoutChatTaskViewSet,+ "project_signals_scout_chat_tasks",+ ["team_id"],+ )routers.projects.register(r"signals/scout", SignalScoutViewSet, "project_signals_scout", ["team_id"])diff --git a/products/signals/backend/scout_chat.py b/products/signals/backend/scout_chat.pynew file mode 100644index 000000000000..de2f9af49598--- /dev/null+++ b/products/signals/backend/scout_chat.py@@ -0,0 +1,163 @@+"""Server-minted scout chat tasks.++The Inbox scout surfaces ("Suggest a scout", fleet overview, recent signals) kick off a cloud+Task the user then chats with. The prompt templates and the task dispatch live here, server-side,+because the run endpoints gate arbitrary tasks on PostHog Desktop access: scout chat is entitled+through the generally-available Inbox instead, and the reserved ``SIGNALS_CHAT`` origin this+endpoint stamps is what proves that entitlement to the gate (the tasks write serializer rejects+the origin from API callers). See ``task_exempt_from_code_access`` in the tasks facade.+"""++import time++from django.core.cache import cache++from drf_spectacular.utils import OpenApiResponse+from rest_framework import exceptions, serializers, status, viewsets+from rest_framework.authentication import SessionAuthentication+from rest_framework.permissions import IsAuthenticated+from rest_framework.response import Response+from rest_framework.throttling import UserRateThrottle++from posthog.api.mixins import validated_request+from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication+from posthog.permissions import APIScopePermission++from products.signals.backend.models import SignalScoutConfig+from products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.facade.access import usage_limit_response++SCOUT_AUTHOR_PROMPT = """I'd like to make a new scout for this PostHog project.++Use the authoring-scouts skill from the PostHog MCP to guide creating a new signals scout.++First, take a quick scan of this PostHog project to ground your suggestions: skim its events, insights, dashboards, recently emitted signals, and the existing scout fleet so you understand what this product is and where automated monitoring would add value.++Then ask me what sort of scout I'd like to make, and offer a few concrete suggestions tailored to what you found (for example specific funnels, error or latency spikes, churn or activation signals, or revenue metrics worth watching) – and call out gaps the current fleet doesn't already cover. Once I pick a direction, walk me through authoring the scout end to end.++If the skill is unavailable, fall back to the signals-scout MCP tools directly (config list to see the existing fleet) plus the read-data and insight tools to scan the project."""++SCOUT_FLEET_OVERVIEW_PROMPT = """How is my scout fleet performing?++Use the exploring-scouts skill from the PostHog MCP to survey the signals scout fleet on this project and give me a high-level overview:++- The fleet: which scouts exist, enabled vs disabled, and their cadences+- Recent run health: success rate, failures and timeouts, anything stuck+- Output: which scouts emitted signals recently, emit rate, signal-to-noise+- Memory: notable scratchpad entries the fleet has learned+- Recommendations: anything misconfigured, noisy, or worth tuning++Lead with a short overall verdict, then per-scout notes only where something is notable. If the skill is unavailable, fall back to the signals-scout MCP tools directly (config list, runs list, scratchpad search)."""++SCOUT_RECENT_SIGNALS_PROMPT = """What signals have my scouts emitted recently?++Use the exploring-scouts skill from the PostHog MCP to pull the most recent scout runs that emitted findings and walk me through the signals:++- What each signal says, in plain language+- Which scout emitted it, when, and its severity/confidence where available+- Whether it looks genuinely actionable or like noise++Group by scout, newest first. Close with a short note on overall signal quality and any scouts that look noisy or suspiciously silent. If the skill is unavailable, fall back to the signals-scout MCP tools directly (runs list with emitted filter, run emissions)."""++SCOUT_CHAT_TEMPLATES: dict[str, tuple[str, str]] = {+ "author_scout": ("Suggest a scout", SCOUT_AUTHOR_PROMPT),+ "fleet_overview": ("How is my scout troop performing?", SCOUT_FLEET_OVERVIEW_PROMPT),+ "recent_signals": ("What signals were emitted recently?", SCOUT_RECENT_SIGNALS_PROMPT),+}+SCOUT_CHAT_DAILY_ATTEMPT_CAP = 15+++class ScoutChatBurstRateThrottle(UserRateThrottle):+ scope = "signals_scout_chat_burst"+ rate = "2/hour"+++class ScoutChatSustainedRateThrottle(UserRateThrottle):+ scope = "signals_scout_chat_day"+ rate = "5/day"+++class ScoutChatTaskCreateSerializer(serializers.Serializer):+ chat_type = serializers.ChoiceField(+ choices=sorted(SCOUT_CHAT_TEMPLATES),+ help_text=(+ "Which scout chat to start: `author_scout` (guided scout authoring), `fleet_overview` "+ "(health of the scout fleet), or `recent_signals` (walk through recently emitted "+ "signals). The prompt template is owned server-side."+ ),+ )+++class ScoutChatTaskSerializer(serializers.Serializer):+ task_id = serializers.UUIDField(help_text="The created chat task. Open it on the task detail page to continue.")+++class SignalScoutChatTaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """Kick off a scout chat task from one of the fixed Inbox templates.++ Creates a repo-less interactive cloud task with the reserved ``SIGNALS_CHAT`` origin and+ starts its run, mirroring what the Inbox previously did client-side through the generic+ task endpoints.+ """++ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]+ permission_classes = [IsAuthenticated, APIScopePermission]+ scope_object = "task"+ serializer_class = ScoutChatTaskSerializer+ pagination_class = None+ throttle_classes = [ScoutChatBurstRateThrottle, ScoutChatSustainedRateThrottle]+ # No model backs this endpoint; a queryset is still required by the team/org viewset mixin+ # and `create` never reads it.+ queryset = SignalScoutConfig.objects.unscoped()++ @validated_request(+ request_serializer=ScoutChatTaskCreateSerializer,+ responses={+ 201: OpenApiResponse(response=ScoutChatTaskSerializer, description="Chat task created and run started"),+ 403: OpenApiResponse(description="Organization has not approved AI data processing"),+ 429: OpenApiResponse(description="Team is over its posthog_code usage limit"),+ },+ summary="Start a scout chat task",+ description=(+ "Create and run a cloud task for one of the fixed scout chat templates (suggest a "+ "scout, fleet overview, recent signals). The prompt is server-owned; the response "+ "carries the task id to navigate to."+ ),+ )+ def create(self, request, **kwargs):+ if self.team.organization.is_ai_data_processing_approved is not True:+ return Response(+ {"error": "Enable AI data processing for this organization to start a scout chat."},+ status=status.HTTP_403_FORBIDDEN,+ )++ if limit_response := usage_limit_response(request.user, self.team_id):+ return limit_response++ window = int(time.time()) // 86400+ key = f"signals_scout_chat_attempts:{request.user.id}:{window}"+ cache.add(key, 0, timeout=86400)+ try:+ attempts = cache.incr(key)+ except ValueError:+ attempts = 1+ if attempts > SCOUT_CHAT_DAILY_ATTEMPT_CAP:+ raise exceptions.Throttled(detail="You've reached today's limit for scout chats. Try again tomorrow.")++ title, prompt = SCOUT_CHAT_TEMPLATES[request.validated_data["chat_type"]]+ # Repo-less on purpose: these chats read PostHog data over MCP and never touch code.+ # create_pr=False marks the session non-PR-opening, and the pending user message is+ # self-delivered by the agent server on boot so the interactive run has a first turn.+ created = tasks_facade.create_and_run_task(+ team=self.team,+ title=title,+ description=prompt,+ origin_product=tasks_facade.TaskOriginProduct.SIGNALS_CHAT,+ user_id=request.user.id,+ repository=None,+ create_pr=False,+ mode="interactive",+ pending_user_message=prompt,+ )+ return Response(ScoutChatTaskSerializer({"task_id": created.task_id}).data, status=status.HTTP_201_CREATED)diff --git a/products/signals/backend/test/test_scout_chat_api.py b/products/signals/backend/test/test_scout_chat_api.pynew file mode 100644index 000000000000..ab4d900de0dc--- /dev/null+++ b/products/signals/backend/test/test_scout_chat_api.py@@ -0,0 +1,84 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status++from products.signals.backend.scout_chat import SCOUT_CHAT_TEMPLATES+from products.tasks.backend.logic.services.code_usage_gate import CodeUsageStatus # tach-ignore+from products.tasks.backend.models import Task, TaskRun # tach-ignore+++class TestScoutChatTaskAPI(APIBaseTest):+ @patch("posthoganalytics.feature_enabled", return_value=False)+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_starts_chat_task_without_desktop_access(self, mock_workflow, _mock_flag):+ # Scout chat is entitled through the generally-available Inbox: it must work with the+ # Desktop `tasks` flag off, where running the same prompt through the generic task+ # endpoints 403s. The reserved origin the server stamps is what the run gate trusts.+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.post(+ f"/api/projects/{self.team.id}/signals/scout/chat_tasks/",+ {"chat_type": "fleet_overview"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ task = Task.objects.get(id=response.json()["task_id"])+ title, prompt = SCOUT_CHAT_TEMPLATES["fleet_overview"]+ self.assertEqual(task.origin_product, Task.OriginProduct.SIGNALS_CHAT)+ self.assertEqual(task.title, title)+ self.assertEqual(task.description, prompt)+ self.assertIsNone(task.repository)+ self.assertIsNone(task.github_integration)+ self.assertIsNone(task.github_user_integration)+ run = TaskRun.objects.get(task=task)+ self.assertEqual(run.state.get("pending_user_message"), prompt)+ mock_workflow.assert_called_once()++ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_over_limit_team_gets_429_and_no_task(self, mock_workflow, mock_gate):+ mock_gate.return_value = CodeUsageStatus(+ is_rate_limited=True, limit_type="burst", reset_at="2026-06-09T00:00:00Z", is_pro=False+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/signals/scout/chat_tasks/",+ {"chat_type": "recent_signals"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertEqual(response.json()["code"], "usage_limit_exceeded")+ self.assertFalse(Task.objects.filter(origin_product=Task.OriginProduct.SIGNALS_CHAT).exists())+ mock_workflow.assert_not_called()++ @patch("products.signals.backend.scout_chat.SCOUT_CHAT_DAILY_ATTEMPT_CAP", 0)+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_daily_attempt_cap_creates_no_task(self, mock_workflow):+ response = self.client.post(+ f"/api/projects/{self.team.id}/signals/scout/chat_tasks/",+ {"chat_type": "recent_signals"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertFalse(Task.objects.filter(origin_product=Task.OriginProduct.SIGNALS_CHAT).exists())+ mock_workflow.assert_not_called()++ @parameterized.expand([("declined", False), ("undecided", None)])+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_ai_consent_not_approved_gets_403_and_no_task(self, _name, approval, mock_workflow):+ self.organization.is_ai_data_processing_approved = approval+ self.organization.save()++ response = self.client.post(+ f"/api/projects/{self.team.id}/signals/scout/chat_tasks/",+ {"chat_type": "fleet_overview"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertFalse(Task.objects.filter(origin_product=Task.OriginProduct.SIGNALS_CHAT).exists())+ mock_workflow.assert_not_called()diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 6e3429dde2d6..3ff059c45e4f 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -2074,6 +2074,33 @@ export interface SignalScoutCreateResponseApi {config: SignalScoutConfigApi}+/**+ * * `author_scout` - author_scout+ * * `fleet_overview` - fleet_overview+ * * `recent_signals` - recent_signals+ */+export type ChatTypeEnumApi = (typeof ChatTypeEnumApi)[keyof typeof ChatTypeEnumApi]++export const ChatTypeEnumApi = {+ AuthorScout: 'author_scout',+ FleetOverview: 'fleet_overview',+ RecentSignals: 'recent_signals',+} as const++export interface ScoutChatTaskCreateApi {+ /** Which scout chat to start: `author_scout` (guided scout authoring), `fleet_overview` (health of the scout fleet), or `recent_signals` (walk through recently emitted signals). The prompt template is owned server-side.+ *+ * * `author_scout` - author_scout+ * * `fleet_overview` - fleet_overview+ * * `recent_signals` - recent_signals */+ chat_type: ChatTypeEnumApi+}++export interface ScoutChatTaskApi {+ /** The created chat task. Open it on the task detail page to continue. */+ task_id: string+}+/*** Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.* @nullablediff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex f82f5360d3a6..17ae5bb0d7b7 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -41,6 +41,8 @@ import type {RecordStructuredOutputResponseApi,RememberRequestApi,ReportSignalsResponseApi,+ ScoutChatTaskApi,+ ScoutChatTaskCreateApi,ScoutEmissionReportLinkApi,ScoutMemberApi,ScoutMetadataApi,@@ -719,6 +721,27 @@ export const signalsScoutCreate = async (})}+export const getSignalsScoutChatTasksCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/scout/chat_tasks/`+}++/**+ * Create and run a cloud task for one of the fixed scout chat templates (suggest a scout, fleet overview, recent signals). The prompt is server-owned; the response carries the task id to navigate to.+ * @summary Start a scout chat task+ */+export const signalsScoutChatTasksCreate = async (+ projectId: string,+ scoutChatTaskCreateApi: ScoutChatTaskCreateApi,+ options?: RequestInit+): Promise<ScoutChatTaskApi> => {+ return apiMutator<ScoutChatTaskApi>(getSignalsScoutChatTasksCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(scoutChatTaskCreateApi),+ })+}+export const getSignalsScoutConfigListUrl = (projectId: string, params?: SignalsScoutConfigListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 301aa0296294..6ad92e2d8ce2 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -482,6 +482,21 @@ export const SignalsScoutCreateBody = /* @__PURE__ */ zod}).describe('Create a runnable custom scout and its config in one atomic request.')+/**+ * Create and run a cloud task for one of the fixed scout chat templates (suggest a scout, fleet overview, recent signals). The prompt is server-owned; the response carries the task id to navigate to.+ * @summary Start a scout chat task+ */+export const SignalsScoutChatTasksCreateBody = /* @__PURE__ */ zod.object({+ chat_type: zod+ .enum(['author_scout', 'fleet_overview', 'recent_signals'])+ .describe(+ '\* `author_scout` - author_scout\n\* `fleet_overview` - fleet_overview\n\* `recent_signals` - recent_signals'+ )+ .describe(+ 'Which scout chat to start: `author_scout` (guided scout authoring), `fleet_overview` (health of the scout fleet), or `recent_signals` (walk through recently emitted signals). The prompt template is owned server-side.\n\n\* `author_scout` - author_scout\n\* `fleet_overview` - fleet_overview\n\* `recent_signals` - recent_signals'+ ),+})+/*** Register the config for a `signals-scout-*` skill immediately, without waiting for the coordinator to auto-register it. The same call can optionally set `run_interval_minutes`, a cron `run_cron_schedule`, `enabled`, `emit`, `network_access`, and output destinations. The skill must already exist on this project. Upsert: if a config already exists for the skill, the provided fields are applied to it.* @summary Create a scout configdiff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.test.tsxindex efdee8f07d7a..56b48866e063 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.test.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.test.tsx@@ -5,7 +5,6 @@ import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { SCOUT_AUTHOR_PROMPT } from '../../../utils/scoutRunsWindow'import { ScoutCreateButton } from './ScoutCreateButton'import { ScoutSuggestButton } from './ScoutSuggestButton'@@ -28,10 +27,10 @@ const mockGetAccessControlDisabledReason = getAccessControlDisabledReason as jes>describe('scout creation buttons', () => {- let createdTaskDescriptions: string[]+ let startedChatTypes: string[]beforeEach(() => {- createdTaskDescriptions = []+ startedChatTypes = []mockGetAccessControlDisabledReason.mockReturnValue(null)useMocks({get: {@@ -46,15 +45,13 @@ describe('scout creation buttons', () => {runs_remaining_today: null,},},- '/api/projects/:team/tasks/repositories/': { repositories: [] },},post: {- '/api/projects/:team/tasks/': async ({ request }) => {- const body = (await request.json()) as { description: string }- createdTaskDescriptions.push(body.description)- return [201, { id: 'task-1' }]+ '/api/projects/:team/signals/scout/chat_tasks/': async ({ request }) => {+ const body = (await request.json()) as { chat_type: string }+ startedChatTypes.push(body.chat_type)+ return [201, { task_id: 'task-1' }]},- '/api/projects/:team/tasks/:id/run/': { id: 'task-1' },},})initKeaTests()@@ -71,7 +68,7 @@ describe('scout creation buttons', () => {expect(await findByText('Manual scout form')).toBeTruthy()expect(await findByText('signals-scout-daily-digest')).toBeTruthy()- expect(createdTaskDescriptions).toEqual([])+ expect(startedChatTypes).toEqual([])})it('starts the authoring task from the suggest button', async () => {@@ -79,7 +76,7 @@ describe('scout creation buttons', () => {fireEvent.click(getByText('Suggest a scout'))- await waitFor(() => expect(createdTaskDescriptions).toEqual([SCOUT_AUTHOR_PROMPT]))+ await waitFor(() => expect(startedChatTypes).toEqual(['author_scout']))expect(queryByText('Manual scout form')).toBeNull()})@@ -94,6 +91,6 @@ describe('scout creation buttons', () => {expect(button?.getAttribute('aria-disabled')).toBe('true')fireEvent.click(button!)- expect(createdTaskDescriptions).toEqual([])+ expect(startedChatTypes).toEqual([])})})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestButton.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestButton.tsxindex f5fcbc7b2bc6..59a18e24b14c 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestButton.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestButton.tsx@@ -8,7 +8,6 @@ import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { AccessControlLevel, AccessControlResourceType } from '~/types'import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'-import { SCOUT_AUTHOR_PROMPT } from '../../../utils/scoutRunsWindow'export interface ScoutSuggestButtonProps {children?: React.ReactNode@@ -27,9 +26,9 @@ export function ScoutSuggestButton({'data-attr': dataAttr,}: ScoutSuggestButtonProps): JSX.Element {const { startScoutChatTask } = useActions(scoutFleetLogic)- const { runningChatPrompt, aiConsentDisabledReason } = useValues(scoutFleetLogic)- const isStarting = runningChatPrompt === SCOUT_AUTHOR_PROMPT- const anotherTaskIsStarting = runningChatPrompt !== null && !isStarting+ const { runningChatType, aiConsentDisabledReason } = useValues(scoutFleetLogic)+ const isStarting = runningChatType === 'author_scout'+ const anotherTaskIsStarting = runningChatType !== null && !isStartingconst creationDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.LlmSkill,AccessControlLevel.Editor@@ -46,7 +45,7 @@ export function ScoutSuggestButton({? 'Starting another task…': (creationDisabledReason ?? aiConsentDisabledReason ?? undefined)}- onClick={() => startScoutChatTask(SCOUT_AUTHOR_PROMPT, 'scout authoring task', 'Suggest a scout')}+ onClick={() => startScoutChatTask('author_scout', 'scout authoring task')}className={className}data-attr={dataAttr}>diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsxindex e25d6fc2afa2..8fdb1341d15a 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsx@@ -11,14 +11,10 @@ import { pluralize } from 'lib/utils/strings'import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'import { captureScoutAction, captureScoutFleetViewed } from '../../../inboxAnalytics'+import type { ScoutChatType } from '../../../inboxAnalytics'import { inboxSceneLogic } from '../../../inboxSceneLogic'import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'-import {- FleetSummary,- SCOUT_FLEET_OVERVIEW_PROMPT,- SCOUT_RECENT_SIGNALS_PROMPT,- SCOUT_RUNS_PER_SCOUT_LABEL,-} from '../../../utils/scoutRunsWindow'+import { FleetSummary, SCOUT_RUNS_PER_SCOUT_LABEL } from '../../../utils/scoutRunsWindow'import { agentSetupModalLogic } from '../../shell/agentSetupModalLogic'import { FleetFindingsCallout } from './FleetFindingsCallout'import { FleetMemoryCallout } from './FleetMemoryCallout'@@ -241,8 +237,8 @@ function ScoutsFleetList(): JSX.Element {<div className="flex items-center gap-2 flex-wrap"><ScoutCreateButton type="secondary" size="xsmall" onCreated={() => loadScoutConfigs()} /><ScoutSuggestButton type="secondary" size="xsmall" />- <ScoutChatCta label="How is my scout troop performing?" prompt={SCOUT_FLEET_OVERVIEW_PROMPT} />- <ScoutChatCta label="What signals were emitted recently?" prompt={SCOUT_RECENT_SIGNALS_PROMPT} />+ <ScoutChatCta label="How is my scout troop performing?" chatType="fleet_overview" />+ <ScoutChatCta label="What signals were emitted recently?" chatType="recent_signals" /><span className="flex-1" />{scoutTagOptions.length > 0 ? (<div className="flex items-center gap-2">@@ -314,11 +310,19 @@ function ScoutsFleetList(): JSX.Element {* question, then navigates to it – same one-click shape as the inbox* discuss / create-PR flows.*/-function ScoutChatCta({ label, prompt, icon }: { label: string; prompt: string; icon?: JSX.Element }): JSX.Element {+function ScoutChatCta({+ label,+ chatType,+ icon,+}: {+ label: string+ chatType: ScoutChatType+ icon?: JSX.Element+}): JSX.Element {const { startScoutChatTask } = useActions(scoutFleetLogic)- const { runningChatPrompt, aiConsentDisabledReason } = useValues(scoutFleetLogic)- const isRunning = runningChatPrompt === prompt- const anyRunning = runningChatPrompt !== null+ const { runningChatType, aiConsentDisabledReason } = useValues(scoutFleetLogic)+ const isRunning = runningChatType === chatType+ const anyRunning = runningChatType !== nullreturn (<LemonButtontype="secondary"@@ -326,7 +330,7 @@ function ScoutChatCta({ label, prompt, icon }: { label: string; prompt: string;icon={icon ?? <IconSparkles />}loading={isRunning}disabledReason={anyRunning ? 'Starting a task…' : (aiConsentDisabledReason ?? undefined)}- onClick={() => startScoutChatTask(prompt, label, label)}+ onClick={() => startScoutChatTask(chatType, label)}>{label}</LemonButton>diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.tsindex 73d33ecc70b8..42ad5f53e54b 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts@@ -3,24 +3,23 @@ import { MOCK_DEFAULT_ORGANIZATION, MOCK_TEAM_ID } from 'lib/api.mock'import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'-import api from 'lib/api'import { organizationLogic } from 'scenes/organizationLogic'import { teamLogic } from 'scenes/teamLogic'import { initKeaTests } from '~/test/init'import {+ signalsScoutChatTasksCreate,signalsScoutConfigList,signalsScoutConfigUpdate,signalsScoutMetadataGet,} from 'products/signals/frontend/generated/api'import type { SignalScoutConfigApi } from 'products/signals/frontend/generated/api.schemas'-import { RunSourceEnumApi, TaskExecutionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'-import { SCOUT_AUTHOR_PROMPT } from '../utils/scoutRunsWindow'import { scoutFleetLogic } from './scoutFleetLogic'jest.mock('products/signals/frontend/generated/api', () => ({+ signalsScoutChatTasksCreate: jest.fn(),signalsScoutConfigDestroy: jest.fn(),signalsScoutConfigList: jest.fn(),signalsScoutConfigUpdate: jest.fn(),@@ -28,6 +27,9 @@ jest.mock('products/signals/frontend/generated/api', () => ({signalsScoutRunsFindingsSummary: jest.fn(),}))+const mockSignalsScoutChatTasksCreate = signalsScoutChatTasksCreate as jest.MockedFunction<+ typeof signalsScoutChatTasksCreate+>const mockSignalsScoutConfigList = signalsScoutConfigList as jest.MockedFunction<typeof signalsScoutConfigList>const mockSignalsScoutConfigUpdate = signalsScoutConfigUpdate as jest.MockedFunction<typeof signalsScoutConfigUpdate>const mockSignalsScoutMetadataGet = signalsScoutMetadataGet as jest.MockedFunction<typeof signalsScoutMetadataGet>@@ -70,6 +72,7 @@ describe('scoutFleetLogic', () => {beforeEach(async () => {initKeaTests()+ mockSignalsScoutChatTasksCreate.mockReset()mockSignalsScoutConfigList.mockReset().mockResolvedValue([])mockSignalsScoutConfigUpdate.mockReset()mockSignalsScoutMetadataGet.mockReset().mockResolvedValue({@@ -210,24 +213,16 @@ describe('scoutFleetLogic', () => {expect(logic.values.updatingScoutIds).toEqual([])})- it('runs the task it creates, rather than leaving the user on an unstarted one', async () => {- const repositories = jest.spyOn(api.tasks, 'repositories')- const create = jest.spyOn(api.tasks, 'create').mockResolvedValue({ id: 'task-1' } as any)- const run = jest.spyOn(api.tasks, 'run').mockResolvedValue({ id: 'task-1' } as any)+ it('starts the chat task server-side and navigates to it', async () => {+ mockSignalsScoutChatTasksCreate.mockResolvedValue({ task_id: 'task-1' })- logic.actions.startScoutChatTask(SCOUT_AUTHOR_PROMPT, 'scout authoring task', 'Suggest a scout')- await expectLogic(logic).toFinishAllListeners()+ logic.actions.startScoutChatTask('author_scout', 'scout authoring task')+ await expectLogic(logic).toDispatchActions(['startScoutChatTaskSuccess'])- expect(run).toHaveBeenCalledWith('task-1', {- run_source: RunSourceEnumApi.Manual,- mode: TaskExecutionModeEnumApi.Interactive,- // Without the prompt as the first turn, an interactive run boots the agent idle.- pending_user_message: SCOUT_AUTHOR_PROMPT,+ expect(mockSignalsScoutChatTasksCreate).toHaveBeenCalledWith(String(MOCK_TEAM_ID), {+ chat_type: 'author_scout',})expect(router.values.location.pathname).toContain('task-1')- // Pinning a repo would make the run clone it in full, and these prompts never touch code.- expect(repositories).not.toHaveBeenCalled()- expect(create).toHaveBeenCalledWith(expect.not.objectContaining({ repository: expect.anything() }))})it('starts nothing when the organization has not approved AI data processing', async () => {@@ -235,25 +230,21 @@ describe('scoutFleetLogic', () => {...MOCK_DEFAULT_ORGANIZATION,is_ai_data_processing_approved: false,})- const create = jest.spyOn(api.tasks, 'create').mockResolvedValue({ id: 'task-3' } as any)- const run = jest.spyOn(api.tasks, 'run').mockResolvedValue({ id: 'task-3' } as any)- logic.actions.startScoutChatTask(SCOUT_AUTHOR_PROMPT, 'scout authoring task', 'Suggest a scout')+ logic.actions.startScoutChatTask('author_scout', 'scout authoring task')await expectLogic(logic).toDispatchActions(['startScoutChatTaskFailure'])- // The tasks run endpoint has no consent check of its own, so dropping the guard here would+ // The endpoint enforces no consent check of its own, so dropping the guard here would// start an agent sandbox for an organization that declined AI data processing.- expect(create).not.toHaveBeenCalled()- expect(run).not.toHaveBeenCalled()+ expect(mockSignalsScoutChatTasksCreate).not.toHaveBeenCalled()})- it('still opens the task when kicking off its run fails', async () => {- jest.spyOn(api.tasks, 'create').mockResolvedValue({ id: 'task-2' } as any)- jest.spyOn(api.tasks, 'run').mockRejectedValue(new Error('over the usage limit'))+ it('resets the in-flight chat type when the kickoff fails', async () => {+ mockSignalsScoutChatTasksCreate.mockRejectedValue(new Error('over the usage limit'))- logic.actions.startScoutChatTask(SCOUT_AUTHOR_PROMPT, 'scout authoring task', 'Suggest a scout')- await expectLogic(logic).toDispatchActions(['startScoutChatTaskSuccess'])+ logic.actions.startScoutChatTask('author_scout', 'scout authoring task')+ await expectLogic(logic).toDispatchActions(['startScoutChatTaskFailure'])- expect(router.values.location.pathname).toContain('task-2')+ expect(logic.values.runningChatType).toBeNull()})})diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.tsindex 19fc1da5d710..c9dc56a9c759 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts@@ -4,14 +4,13 @@ import { router } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'import { dayjs } from 'lib/dayjs'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { OriginProduct } from 'products/posthog_ai/frontend/types/taskTypes'import {+ signalsScoutChatTasksCreate,signalsScoutConfigDestroy,signalsScoutConfigList,signalsScoutConfigUpdate,@@ -27,7 +26,6 @@ import type {SignalScoutConfigApi,} from 'products/signals/frontend/generated/api.schemas'import { llmSkillsNameArchiveCreate } from 'products/skills/frontend/generated/api'-import { RunSourceEnumApi, TaskExecutionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'import {captureScoutAction,@@ -44,9 +42,6 @@ import {isSettledRun,prettifyScoutSkillName,reconcileById,- SCOUT_AUTHOR_PROMPT,- SCOUT_FLEET_OVERVIEW_PROMPT,- SCOUT_RECENT_SIGNALS_PROMPT,SCOUT_RUNS_PER_SCOUT,SCOUT_RUNS_WINDOW_HOURS,ScoutRollup,@@ -58,13 +53,6 @@ import type { ScoutTagOption } from '../utils/scoutTags'type SignalScoutConfig = SignalScoutConfigApitype SignalScoutConfigUpdate = PatchedSignalScoutConfigUpdateApi-// Which CTA a chat task came from, keyed off the templated prompt so the callers stay untouched.-const SCOUT_CHAT_TYPES: Record<string, ScoutChatType> = {- [SCOUT_AUTHOR_PROMPT]: 'author_scout',- [SCOUT_FLEET_OVERVIEW_PROMPT]: 'fleet_overview',- [SCOUT_RECENT_SIGNALS_PROMPT]: 'recent_signals',-}-/*** One `Scout config changed` per field the request carried. A schedule switch patches both* `run_interval_minutes` and `run_cron_schedule` at once, and collapsing those into a single event@@ -122,7 +110,7 @@ export interface scoutFleetLogicValues {hideDisabled: booleanlastRunAt: string | nullrollups: Map<string, ScoutRollup>- runningChatPrompt: string | null+ runningChatType: ScoutChatType | nullrunsWindow: {complete: booleanruns: SignalScoutRunSummary[]@@ -255,12 +243,10 @@ export interface scoutFleetLogicActions {value: true}startScoutChatTask: (- prompt: string,- taskLabel: string,- fallbackTitle: string+ chatType: ScoutChatType,+ taskLabel: string) => {- fallbackTitle: string- prompt: string+ chatType: ScoutChatTypetaskLabel: string}startScoutChatTaskFailure: () => {@@ -357,10 +343,9 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([// (which only reads configs) doesn't trigger the paginated runs-window polling.startRunsPolling: true,stopRunsPolling: true,- startScoutChatTask: (prompt: string, taskLabel: string, fallbackTitle: string) => ({- prompt,+ startScoutChatTask: (chatType: ScoutChatType, taskLabel: string) => ({+ chatType,taskLabel,- fallbackTitle,}),startScoutChatTaskSuccess: true,startScoutChatTaskFailure: true,@@ -495,12 +480,12 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([})),reducers({- // Tracks which CTA's chat-task kickoff is mid-flight, keyed by its prompt, so only the+ // Tracks which CTA's chat-task kickoff is mid-flight, keyed by its chat type, so only the// pressed chip spins (the others merely disable). A shared boolean spun all three at once.- runningChatPrompt: [- null as string | null,+ runningChatType: [+ null as ScoutChatType | null,{- startScoutChatTask: (_, { prompt }) => prompt,+ startScoutChatTask: (_, { chatType }) => chatType,startScoutChatTaskSuccess: () => null,startScoutChatTaskFailure: () => null,},@@ -826,50 +811,29 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([actions.deleteScoutFinished(configId)}},- startScoutChatTask: async ({ prompt, fallbackTitle, taskLabel }) => {- // Task-kickoff, mirroring inboxTaskKickoffLogic: create an auto-mode cloud- // task from a templated prompt, then navigate to it. Not a live chat.+ startScoutChatTask: async ({ chatType, taskLabel }) => {+ // Task-kickoff, mirroring inboxTaskKickoffLogic: start a cloud task from a fixed+ // template, then navigate to it. Not a live chat.// The CTAs carry this as a `disabledReason`; this backstops the paths that don't go- // through a button press, since the run endpoint enforces no consent of its own.+ // through a button press, since the endpoint enforces no consent of its own.if (values.aiConsentDisabledReason) {lemonToast.error(values.aiConsentDisabledReason)actions.startScoutChatTaskFailure()return}- const chatType = SCOUT_CHAT_TYPES[prompt]- if (chatType) {- captureScoutChatStarted({ chatType, surface: 'fleet_list' })+ captureScoutChatStarted({ chatType, surface: 'fleet_list' })+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ actions.startScoutChatTaskFailure()+ return}try {- // Deliberately repo-less: these prompts read PostHog data over MCP and never touch- // code, while `tasks/repositories/` would hand back whichever repo sorts first across- // the team's visible tasks. A SIGNAL_REPORT task clones with full history (for git- // blame), so pinning an arbitrary repo would clone it in full for nothing.- const task = await api.tasks.create({- title: fallbackTitle,- description: prompt,- origin_product: OriginProduct.SIGNAL_REPORT,- })- // Creating the task alone lands the user on a "This task hasn't been run yet" screen,- // so kick off the run too (same as inboxTaskKickoffLogic). Interactive, not background:- // the agent-server only relays approval prompts to the client on non-background runs.- try {- await api.tasks.run(task.id, {- run_source: RunSourceEnumApi.Manual,- mode: TaskExecutionModeEnumApi.Interactive,- // The agent-server self-delivers `pending_user_message` from run state on boot,- // and interactive runs skip the workflow's forwarding path. Nothing falls back to- // the task description on the ACP runtime, so without this the sandbox boots with- // no first turn and the run just idles.- pending_user_message: prompt,- })- } catch (error: any) {- // The task exists and its page has a Run button, so strand nobody — say what- // failed and still navigate there.- lemonToast.error(error?.detail || error?.message || `Failed to run ${taskLabel}`)- }+ // The server owns the prompt template, creates the task repo-less with the+ // reserved signals_chat origin (which exempts it from the Desktop access gate+ // on the task run endpoints) and starts its interactive run in one call.+ const task = await signalsScoutChatTasksCreate(String(teamId), { chat_type: chatType })actions.startScoutChatTaskSuccess()- router.actions.push(urls.taskDetail(task.id))+ router.actions.push(urls.taskDetail(task.task_id))} catch (error: any) {lemonToast.error(error?.detail || error?.message || `Failed to start ${taskLabel}`)actions.startScoutChatTaskFailure()diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.tsindex dd7468749551..83570069b07c 100644--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts@@ -571,39 +571,8 @@ export function sortConfigsForDisplay(configs: SignalScoutConfig[]): SignalScout})}-// ── Templated chat-task prompts (ported from desktop scoutPrompts.ts) ─────────--export const SCOUT_AUTHOR_PROMPT = `I'd like to make a new scout for this PostHog project.--Use the authoring-scouts skill from the PostHog MCP to guide creating a new signals scout.--First, take a quick scan of this PostHog project to ground your suggestions: skim its events, insights, dashboards, recently emitted signals, and the existing scout fleet so you understand what this product is and where automated monitoring would add value.--Then ask me what sort of scout I'd like to make, and offer a few concrete suggestions tailored to what you found (for example specific funnels, error or latency spikes, churn or activation signals, or revenue metrics worth watching) – and call out gaps the current fleet doesn't already cover. Once I pick a direction, walk me through authoring the scout end to end.--If the skill is unavailable, fall back to the signals-scout MCP tools directly (config list to see the existing fleet) plus the read-data and insight tools to scan the project.`--export const SCOUT_FLEET_OVERVIEW_PROMPT = `How is my scout fleet performing?--Use the exploring-scouts skill from the PostHog MCP to survey the signals scout fleet on this project and give me a high-level overview:--- The fleet: which scouts exist, enabled vs disabled, and their cadences-- Recent run health: success rate, failures and timeouts, anything stuck-- Output: which scouts emitted signals recently, emit rate, signal-to-noise-- Memory: notable scratchpad entries the fleet has learned-- Recommendations: anything misconfigured, noisy, or worth tuning--Lead with a short overall verdict, then per-scout notes only where something is notable. If the skill is unavailable, fall back to the signals-scout MCP tools directly (config list, runs list, scratchpad search).`--export const SCOUT_RECENT_SIGNALS_PROMPT = `What signals have my scouts emitted recently?--Use the exploring-scouts skill from the PostHog MCP to pull the most recent scout runs that emitted findings and walk me through the signals:--- What each signal says, in plain language-- Which scout emitted it, when, and its severity/confidence where available-- Whether it looks genuinely actionable or like noise--Group by scout, newest first. Close with a short note on overall signal quality and any scouts that look noisy or suspiciously silent. If the skill is unavailable, fall back to the signals-scout MCP tools directly (runs list with emitted filter, run emissions).`+// The fixed chat-task prompt templates live server-side in+// products/signals/backend/scout_chat.py, keyed by `chat_type`./** Per-scout variant of the templated questions, scoped to one skill. */export function buildScoutCheckinPrompt(skillName: string, displayName: string): string {diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex 5d328e6d9b71..0b7f5114c33a 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -873,6 +873,9 @@ tools:signals-reports-viewed-create:operation: signals_reports_viewed_createenabled: false+ signals-scout-chat-tasks-create:+ operation: signals_scout_chat_tasks_create+ enabled: falsesignals-scout-config-create:operation: signals_scout_config_createenabled: truediff --git a/products/tasks/backend/access.py b/products/tasks/backend/access.pyindex 9a28568e575a..3d054a3ff0c9 100644--- a/products/tasks/backend/access.py+++ b/products/tasks/backend/access.py@@ -42,7 +42,7 @@ def has_tasks_access(user: User) -> bool:def has_loops_access(user: User, team: "Team | None" = None) -> bool:"""Loops sits behind its own `loops` flag (see docs/LOOPS.md Rollout).- Not layered on `has_tasks_access` any more: `tasks` gates the Desktop waitlist, and the- backend no longer enforces that on task execution — only the Desktop client's own UI reads it.+ Independent of `has_tasks_access`: `tasks` gates the Desktop waitlist that user-triggered cloud+ runs require (see code_access_required_response), while Loops gates on its own flag instead."""return _is_flag_enabled("loops", user, team)diff --git a/products/tasks/backend/automation_service.py b/products/tasks/backend/automation_service.pyindex c51bc4fcd832..04f65e8d2448 100644--- a/products/tasks/backend/automation_service.py+++ b/products/tasks/backend/automation_service.py@@ -1,6 +1,7 @@import loggingfrom django.conf import settings+from django.core.exceptions import PermissionDeniedfrom django.db import transactionfrom temporalio.client import Schedule, ScheduleActionStartWorkflow, ScheduleSpec, ScheduleState@@ -15,6 +16,7 @@ from posthog.temporal.common.schedule import (update_schedule,)+from .access import has_tasks_accessfrom .models import Task, TaskAutomation, TaskRunlogger = logging.getLogger(__name__)@@ -61,6 +63,16 @@ def delete_automation_schedule(automation: TaskAutomation) -> None:def run_task_automation(automation_id: str, trigger_workflow_id: str | None = None) -> tuple[Task, TaskRun]:automation_id = str(automation_id)++ # Scheduled fires bypass the HTTP gate, so re-check the creator (fail closed if deleted) before+ # the run transaction, recording the reason to last_error instead of rolling it back.+ automation = TaskAutomation.objects.select_related("task", "task__created_by").get(id=automation_id)+ creator = automation.task.created_by+ if creator is None or not has_tasks_access(creator):+ automation.last_error = "PostHog Desktop access is required to run task automations"+ automation.save(update_fields=["last_error", "updated_at"])+ raise PermissionDenied("PostHog Desktop access is required to run task automations")+with transaction.atomic():automation = TaskAutomation.objects.select_for_update(of=("self",)).select_related("task").get(id=automation_id)task = automation.taskdiff --git a/products/tasks/backend/facade/access.py b/products/tasks/backend/facade/access.pyindex 7d334f647571..1db19bff6be1 100644--- a/products/tasks/backend/facade/access.py+++ b/products/tasks/backend/facade/access.py@@ -1,18 +1,23 @@"""Facade re-exports for tasks access / usage gating.-``has_tasks_access`` reports Desktop waitlist access (the `tasks` flag or a redeemed invite) so-clients can gate their own UI — the backend does not enforce it on task execution.+``has_tasks_access`` reports Desktop waitlist access (the `tasks` flag or a redeemed invite).``has_loops_access`` gates Loops on its own `loops` flag (see docs/LOOPS.md Rollout).-``usage_limit_response`` provides the HTTP-layer 429 that meters cloud execution paths.-Presentation imports it from here rather than reaching the internal ``access`` /-``logic.services.code_usage_gate`` modules directly.+``code_access_required_response`` provides the HTTP-layer 403 that gates user-triggered cloud+execution on Desktop access; ``usage_limit_response`` provides the HTTP-layer 429 that meters+cloud execution paths. Presentation imports them from here rather than reaching the internal+``access`` / ``logic.services.code_usage_gate`` modules directly."""from products.tasks.backend.access import has_loops_access, has_tasks_access-from products.tasks.backend.logic.services.code_usage_gate import compute_quota_limit_response, usage_limit_response+from products.tasks.backend.logic.services.code_usage_gate import (+ code_access_required_response,+ compute_quota_limit_response,+ usage_limit_response,+)__all__ = [+ "code_access_required_response","compute_quota_limit_response","has_loops_access","has_tasks_access",diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 30f39c5bd0b0..f61b7a909426 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -256,6 +256,7 @@ __all__ = ["start_task_run","task_accessible_for_run_view","task_channel_id",+ "task_exempt_from_code_access","task_exists","task_ids_with_pr_url_subquery","task_run_has_slack_mapping",@@ -768,6 +769,48 @@ def task_owned_by_user(task_id: str | UUID, team_id: int, user_id: int) -> bool:return Task.objects.filter(id=task_id, team_id=team_id, created_by_id=user_id).exists()+def task_exempt_from_code_access(task_id: str | UUID, team_id: int) -> bool:+ """Whether this task's cloud runs are entitled outside PostHog Desktop.++ The run/command endpoints gate on Desktop access (``code_access_required_response``) but+ also serve the generally-available Inbox, whose tasks must run without the waitlist. Only+ server-verifiable Inbox shapes qualify:++ - ``SIGNAL_REPORT`` linked to a report in this team and repo-less (Inbox "Discuss").+ Reports are minted by scouts and the link is team-scoped by the write serializer, so a+ caller can't forge one. Acting on a report is entitled through self-driving+ (`product-autonomy`). Repository-backed report tasks require Desktop access.+ - ``SIGNALS_CHAT`` (Inbox scout chat), reserved for server-side creation by the signals+ scout-chat endpoint; the write serializer rejects it from API callers. Only while+ repo-less: chat tasks are minted without repositories, and attaching one via update+ would turn the exemption into ungated cloud code work.++ A bare ``SIGNAL_REPORT`` origin without a report link deliberately does not qualify:+ ``origin_product`` is client input, so an FK-less claim would be a one-field waitlist+ bypass. The report's own team is re-checked here even though the write serializer+ already enforces it, so a future write path can't silently widen the exemption.+ """+ return Task.objects.filter(+ Q(+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ signal_report__team_id=team_id,+ repository__isnull=True,+ repositories=[],+ github_integration__isnull=True,+ github_user_integration__isnull=True,+ )+ | Q(+ origin_product=Task.OriginProduct.SIGNALS_CHAT,+ repository__isnull=True,+ repositories=[],+ github_integration__isnull=True,+ github_user_integration__isnull=True,+ ),+ id=task_id,+ team_id=team_id,+ ).exists()++def count_in_progress_runs_for_github_integration(team_id: int, integration_id: int) -> int:"""In-progress runs whose task uses this team GitHub integration.@@ -4693,7 +4736,14 @@ def create_task(pending_user_artifact_ids = validated_data.pop("pending_user_artifact_ids", None) or []warm_auto_publish = validated_data.pop("auto_publish", None)channel = validated_data.get("channel")- if channel is not None and "repositories" not in validated_data and "repository" not in validated_data:+ if (+ channel is not None+ and "repositories" not in validated_data+ and "repository" not in validated_data+ # A signal_report task's repo must come from the report (resolved below), never a+ # channel-carried one, or the code-access exemption runs against an attacker-picked repo.+ and validated_data["origin_product"] != Task.OriginProduct.SIGNAL_REPORT+ ):validated_data["repositories"] = channel.repositoriesvalidated_data["github_integration"] = channel.github_integrationif "repositories" in validated_data:@@ -4799,11 +4849,6 @@ def create_task(# Popped so it isn't forwarded to the model; the link itself is recorded by record_report_task below.signal_report_task_relationship = validated_data.pop("signal_report_task_relationship", None)- if not validated_data.get("github_integration"):- default_integration = Integration.objects.filter(team=team, kind="github").first()- if default_integration:- validated_data["github_integration"] = default_integration-# Inbox "Create PR" / "Discuss" don't pre-select a repo, so resolve one here rather than# creating a report-linked task that can never open a PR.signal_report = validated_data.get("signal_report")@@ -4837,6 +4882,11 @@ def create_task(if resolved_repository:validated_data["repository"] = resolved_repository+ if validated_data.get("repository") and not validated_data.get("github_integration"):+ default_integration = Integration.objects.filter(team=team, kind="github").first()+ if default_integration:+ validated_data["github_integration"] = default_integration+if (validated_data.get("repository")and validated_data.get("origin_product", Task.OriginProduct.USER_CREATED) == Task.OriginProduct.USER_CREATED@@ -4913,6 +4963,12 @@ def update_task(validated_data.pop("signal_report_task_relationship", None)validated_data.pop("origin_product", None)validated_data.pop("branch", None)+ # Repo is immutable for code-access-exempt tasks; a mutable repo reopens the gate (see task_exempt_from_code_access).+ if task.origin_product in (Task.OriginProduct.SIGNALS_CHAT, Task.OriginProduct.SIGNAL_REPORT):+ validated_data.pop("repository", None)+ validated_data.pop("repositories", None)+ validated_data.pop("github_integration", None)+ validated_data.pop("github_user_integration", None)if "repositories" in validated_data:repositories = validated_data["repositories"]validated_data["repository"] = repositories[0] if repositories else Nonediff --git a/products/tasks/backend/logic/services/code_usage_gate.py b/products/tasks/backend/logic/services/code_usage_gate.pyindex 4d9185cf4e91..94997b46ee3f 100644--- a/products/tasks/backend/logic/services/code_usage_gate.py+++ b/products/tasks/backend/logic/services/code_usage_gate.py@@ -1,6 +1,6 @@import loggingfrom dataclasses import dataclass-from typing import Any+from typing import TYPE_CHECKING, Anyfrom django.conf import settings@@ -9,9 +9,13 @@ from rest_framework import statusfrom rest_framework.response import Responsefrom posthog.models import OAuthAccessToken++if TYPE_CHECKING:+ from posthog.models import Userfrom posthog.temporal.oauth import create_oauth_access_token_for_userfrom posthog.utils import get_instance_region+from products.tasks.backend.access import has_tasks_accessfrom products.tasks.backend.logic.services.compute_quota import (COMPUTE_QUOTA_DENIAL_CODE,ORGANIZATION_DEACTIVATED_DENIAL_CODE,@@ -164,14 +168,37 @@ def compute_quota_limit_response(reason: str = COMPUTE_QUOTA_DENIAL_CODE) -> Res)+def code_access_required_response(user: "User") -> Response | None:+ """Return a 403 when the user lacks PostHog Desktop access, else None.++ The entitlement gate for user-triggered cloud execution: usage-based billing alone+ doesn't control cost for credit-funded teams (startup-program credits cover the meter),+ so cloud runs additionally require the Desktop waitlist (the `tasks` flag or a redeemed+ invite). Endpoints serving generally-available Inbox surfaces skip this for tasks whose+ Inbox entitlement is server-verifiable — see ``task_exempt_from_code_access``.+ """+ if has_tasks_access(user):+ return None+ return Response(+ TaskRunErrorResponseSerializer(+ {+ "type": "permission_denied",+ "code": "code_access_required",+ "error": "PostHog Desktop access is required to run tasks in the cloud.",+ }+ ).data,+ status=status.HTTP_403_FORBIDDEN,+ )++def usage_limit_response(user, team_id: int) -> Response | None:"""Return a 429 when the team is over its PostHog Desktop usage limit, else None.- Since Desktop moved to usage-based billing, this is the whole cost control on cloud runs —- no waitlist check is involved. Fails open when the gateway can't be reached, so every check- is counted by outcome (`checked_allowed` / `checked_blocked` / `fail_open`) and a degraded- gateway silently removing the backstop is visible, not just logged. Deactivated organizations- are blocked locally first, so that block holds even when the gateway check fails open.+ The cost backstop on cloud runs, applied on top of the entitlement gate above. Fails+ open when the gateway can't be reached, so every check is counted by outcome+ (`checked_allowed` / `checked_blocked` / `fail_open`) and a degraded gateway silently+ removing the backstop is visible, not just logged. Deactivated organizations are blocked+ locally first, so that block holds even when the gateway check fails open."""if organization_deactivated(team_id):observe_code_usage_gate_check(outcome="org_deactivated")diff --git a/products/tasks/backend/migrations/0090_alter_origin_product_signals_chat.py b/products/tasks/backend/migrations/0090_alter_origin_product_signals_chat.pynew file mode 100644index 000000000000..f80a90ac45f0--- /dev/null+++ b/products/tasks/backend/migrations/0090_alter_origin_product_signals_chat.py@@ -0,0 +1,101 @@+# Generated by Django 5.2.14++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("tasks", "0089_taskrun_queued_at"),+ ]++ operations = [+ migrations.AlterField(+ model_name="loop",+ name="origin_product",+ field=models.CharField(+ choices=[+ ("onboarding", "Onboarding"),+ ("error_tracking", "Error Tracking"),+ ("eval_clusters", "Eval Clusters"),+ ("user_created", "User Created"),+ ("automation", "Automation"),+ ("slack", "Slack"),+ ("support_queue", "Support Queue"),+ ("session_summaries", "Session Summaries"),+ ("posthog_ai", "PostHog AI"),+ ("experiments", "Experiments"),+ ("signal_report", "Signal Report"),+ ("signals_scout", "Signals Scout"),+ ("support_reply", "Support Reply"),+ ("hogdesk", "HogDesk"),+ ("review_hog", "ReviewHog"),+ ("image_builder", "Image Builder"),+ ("loop", "Loop"),+ ("mcp_analytics", "MCP Analytics"),+ ("signals_chat", "Signals Chat"),+ ],+ default="user_created",+ help_text="Which product or flow created this loop.",+ max_length=32,+ ),+ ),+ migrations.AlterField(+ model_name="sandboxsession",+ name="origin_product",+ field=models.CharField(+ blank=True,+ choices=[+ ("onboarding", "Onboarding"),+ ("error_tracking", "Error Tracking"),+ ("eval_clusters", "Eval Clusters"),+ ("user_created", "User Created"),+ ("automation", "Automation"),+ ("slack", "Slack"),+ ("support_queue", "Support Queue"),+ ("session_summaries", "Session Summaries"),+ ("posthog_ai", "PostHog AI"),+ ("experiments", "Experiments"),+ ("signal_report", "Signal Report"),+ ("signals_scout", "Signals Scout"),+ ("support_reply", "Support Reply"),+ ("hogdesk", "HogDesk"),+ ("review_hog", "ReviewHog"),+ ("image_builder", "Image Builder"),+ ("loop", "Loop"),+ ("mcp_analytics", "MCP Analytics"),+ ("signals_chat", "Signals Chat"),+ ],+ help_text="Task origin at provision time, denormalized for per-origin aggregation",+ max_length=20,+ null=True,+ ),+ ),+ migrations.AlterField(+ model_name="task",+ name="origin_product",+ field=models.CharField(+ choices=[+ ("onboarding", "Onboarding"),+ ("error_tracking", "Error Tracking"),+ ("eval_clusters", "Eval Clusters"),+ ("user_created", "User Created"),+ ("automation", "Automation"),+ ("slack", "Slack"),+ ("support_queue", "Support Queue"),+ ("session_summaries", "Session Summaries"),+ ("posthog_ai", "PostHog AI"),+ ("experiments", "Experiments"),+ ("signal_report", "Signal Report"),+ ("signals_scout", "Signals Scout"),+ ("support_reply", "Support Reply"),+ ("hogdesk", "HogDesk"),+ ("review_hog", "ReviewHog"),+ ("image_builder", "Image Builder"),+ ("loop", "Loop"),+ ("mcp_analytics", "MCP Analytics"),+ ("signals_chat", "Signals Chat"),+ ],+ max_length=20,+ ),+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex 78d36976b40e..d6a516bff6fc 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0089_taskrun_queued_at+0090_alter_origin_product_signals_chatdiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex da5b11c112d4..4717a88b473a 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -203,6 +203,10 @@ class Task(DeletedMetaFields, models.Model):LOOP = "loop", "Loop"# "Create fix task" on the MCP analytics tool-quality failure drill-down.MCP_ANALYTICS = "mcp_analytics", "MCP Analytics"+ # Inbox scout-chat kickoffs ("Suggest a scout", fleet overview, recent signals),+ # minted server-side by products/signals so the origin proves the run is entitled+ # through the generally-available Inbox rather than PostHog Desktop.+ SIGNALS_CHAT = "signals_chat", "Signals Chat"# nosemgrep: prefer-uuid7-django-pk -- TODO: migrate to uuid7 or clarify intentid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)@@ -651,12 +655,14 @@ class Task(DeletedMetaFields, models.Model):user_github_integration_is_usable,)- github_integration = (- Integration.objects.filter(team=team, kind="github")- .exclude(errors=ERROR_TOKEN_REFRESH_FAILED)- .exclude(config__has_key=INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY)- .first()- )+ github_integration = None+ if repository or origin_product not in (Task.OriginProduct.SIGNALS_CHAT, Task.OriginProduct.SIGNAL_REPORT):+ github_integration = (+ Integration.objects.filter(team=team, kind="github")+ .exclude(errors=ERROR_TOKEN_REFRESH_FAILED)+ .exclude(config__has_key=INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY)+ .first()+ )github_user_integration = Nonetask_stub = Task(team=team,diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex f597a1b6cd5f..d689d69d3181 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -686,6 +686,9 @@ class TaskWriteSerializer(serializers.Serializer):# forged origin would be free model access. Only create_wizard_cloud_run sets it,# behind its own rate limits and daily cap.tasks_facade.TaskOriginProduct.ONBOARDING,+ # Exempt from the Desktop code-access gate on run endpoints, so a forged origin+ # would bypass the waitlist. Only the signals scout-chat endpoint sets it.+ tasks_facade.TaskOriginProduct.SIGNALS_CHAT,}if value in reserved_origins:raise serializers.ValidationError(f"origin_product '{value}' is reserved for server-created tasks")@@ -771,6 +774,13 @@ class TaskWriteSerializer(serializers.Serializer):raise serializers.ValidationError({"github_user_integration": "Signal report tasks use the team GitHub integration."})+ # Repo is server-resolved for these code-access-exempt tasks; a client-set repo bypasses the gate.+ if attrs.get("origin_product") == tasks_facade.TaskOriginProduct.SIGNAL_REPORT and (+ attrs.get("repository") or attrs.get("repositories")+ ):+ raise serializers.ValidationError(+ {"repository": "Signal report tasks resolve their repository server-side."}+ )return attrsdiff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 5f7261f71b3b..41cdf45f0900 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -58,7 +58,11 @@ from products.tasks.backend.facade import (cancellation as tasks_cancellation,contracts as tasks_contracts,)-from products.tasks.backend.facade.access import compute_quota_limit_response, usage_limit_response+from products.tasks.backend.facade.access import (+ code_access_required_response,+ compute_quota_limit_response,+ usage_limit_response,+)from products.tasks.backend.facade.client_provenance import get_task_client_provenancefrom products.tasks.backend.facade.compute_quota import ComputeBillingLimitExceededfrom products.tasks.backend.facade.metrics import (@@ -837,7 +841,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):responses={200: OpenApiResponse(response=TaskSerializer, description="Task with updated latest run"),400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid task run payload"),- 403: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Pi cloud runtime is disabled"),+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="PostHog Desktop access is required, or Pi cloud runtime is disabled",+ ),404: OpenApiResponse(description="Task not found"),429: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"@@ -857,10 +864,13 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):) == tasks_facade.TaskRuntime.PI and not tasks_facade.pi_cloud_runtime_enabled(self.team, request.user):return _pi_cloud_runtime_disabled_response()- # Usage limits only, no `has_tasks_access` check: that gate is the Desktop waitlist (the- # `tasks` flag or a redeemed invite), and this is the endpoint the generally-available Inbox- # runs tasks through (report "Create PR" / "Discuss", scout chat). Waitlisting a released- # surface would 403 it; cost is covered by usage-based billing.+ # The generally-available Inbox runs tasks through this endpoint too (report "Create PR" /+ # "Discuss", scout chat), so the Desktop waitlist gate applies only to tasks whose Inbox+ # entitlement the server can't verify — see task_exempt_from_code_access.+ if not tasks_facade.task_exempt_from_code_access(pk, self.team_id) and (+ access_response := code_access_required_response(request.user)+ ):+ return access_responseif limit_response := usage_limit_response(request.user, self.team_id):return limit_response@@ -898,6 +908,9 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):response=WarmTaskResponseSerializer,description="Warm Run provisioned (`task_id`/`run_id` to activate on submit), or an empty body when the feature is off, capped, or the integration didn't resolve.",),+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer, description="PostHog Desktop access is required"+ ),429: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"),@@ -918,6 +931,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if not self._warm_enabled():return Response(status=status.HTTP_200_OK)+ # Warming is a Desktop-composer feature with no Inbox caller, so no exemption applies.+ if access_response := code_access_required_response(request.user):+ return access_response+user_id = self._user_id()if user_id is None:return Response(status=status.HTTP_200_OK)@@ -1046,17 +1063,42 @@ class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise NotFound()return Response(TaskAutomationSerializer(automation).data)- @extend_schema(request=TaskAutomationWriteSerializer, responses={201: TaskAutomationSerializer})+ @extend_schema(+ request=TaskAutomationWriteSerializer,+ responses={+ 201: TaskAutomationSerializer,+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="PostHog Desktop access is required",+ ),+ },+ )def create(self, request, **kwargs):+ # Automations schedule cloud runs, so creating one needs the same Desktop access as+ # running a task. No Inbox surface creates automations, so no exemption applies.+ if access_response := code_access_required_response(request.user):+ return access_responseserializer = self._write_serializer(request.data)automation = tasks_facade.create_task_automation(self.team_id, getattr(request.user, "id", None), **self._facade_kwargs(serializer.validated_data))return Response(TaskAutomationSerializer(automation).data, status=status.HTTP_201_CREATED)- @extend_schema(request=TaskAutomationWriteSerializer, responses={200: TaskAutomationSerializer})+ @extend_schema(+ request=TaskAutomationWriteSerializer,+ responses={+ 200: TaskAutomationSerializer,+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="PostHog Desktop access is required",+ ),+ },+ )def partial_update(self, request, pk=None, **kwargs):serializer = self._write_serializer(request.data, partial=True)+ if serializer.validated_data.get("enabled") is True:+ if access_response := code_access_required_response(request.user):+ return access_responseautomation = tasks_facade.update_task_automation(pk, self.team_id, getattr(request.user, "id", None), **self._facade_kwargs(serializer.validated_data))@@ -1070,9 +1112,20 @@ class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise NotFound()return Response(status=status.HTTP_204_NO_CONTENT)- @extend_schema(request=None, responses={200: TaskAutomationSerializer})+ @extend_schema(+ request=None,+ responses={+ 200: TaskAutomationSerializer,+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="PostHog Desktop access is required",+ ),+ },+ )@action(detail=True, methods=["post"], url_path="run", required_scopes=["task:write"])def run(self, request, pk=None, **kwargs):+ if access_response := code_access_required_response(request.user):+ return access_responseautomation = tasks_facade.run_task_automation_now(pk, self.team_id, getattr(request.user, "id", None))if automation is None:raise NotFound()@@ -1209,7 +1262,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):responses={201: OpenApiResponse(response=TaskRunDetailSerializer, description="Created task run"),400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid task run payload"),- 403: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Pi cloud runtime is disabled"),+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="PostHog Desktop access is required, or Pi cloud runtime is disabled",+ ),429: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"),@@ -1228,6 +1284,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):task_id, self.team_id, self._user_id(), for_control=True) == tasks_facade.TaskRuntime.PI and not tasks_facade.pi_cloud_runtime_enabled(self.team, request.user):return _pi_cloud_runtime_disabled_response()+ if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (+ access_response := code_access_required_response(request.user)+ ):+ return access_responseif limit_response := usage_limit_response(request.user, self.team_id):return limit_response@@ -1245,7 +1305,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):responses={200: OpenApiResponse(response=TaskSerializer, description="Task with updated latest run"),400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid start payload"),- 403: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Pi cloud runtime is disabled"),+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="PostHog Desktop access is required, or Pi cloud runtime is disabled",+ ),404: OpenApiResponse(description="Task run not found"),429: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"@@ -1282,7 +1345,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):status=status.HTTP_400_BAD_REQUEST,)- # Backstop: don't launch the cloud workflow for an over-limit team.+ # Backstop: don't launch the cloud workflow without Desktop access or for an over-limit team.+ if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (+ access_response := code_access_required_response(request.user)+ ):+ return access_responseif limit_response := usage_limit_response(request.user, self.team_id):return limit_response@@ -1970,7 +2037,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):response=ConnectionTokenResponseSerializer,description="Connection token for direct sandbox connection",),+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer, description="PostHog Desktop access is required"+ ),404: OpenApiResponse(description="Task run not found"),+ 429: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="Organization reached its PostHog Desktop usage limit",+ ),},summary="Get sandbox connection token",description="Generate a JWT token for direct connection to the sandbox. Valid for 24 hours.",@@ -1983,6 +2057,12 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)def connection_token(self, request, pk=None, **kwargs):task_id = self._ensure_task_accessible()+ if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (+ access_response := code_access_required_response(request.user)+ ):+ return access_response+ if limit_response := usage_limit_response(request.user, self.team_id):+ return limit_responseuser = request.usertoken = tasks_facade.create_task_run_connection_token(pk, task_id, self.team_id, user_id=user.id, distinct_id=user.distinct_id@@ -2031,6 +2111,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):response=TaskRunErrorResponseSerializer,description="Invalid command or no active sandbox",),+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="PostHog Desktop access is required to message this run's agent",+ ),404: OpenApiResponse(description="Task run not found"),429: OpenApiResponse(response=TaskRunErrorResponseSerializer,@@ -2076,9 +2160,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):params = request.validated_data.get("params")if method == "user_message":- # No `has_tasks_access` check, for the same reason as `TaskViewSet.run`:- # the Inbox starts interactive runs and drops the user straight into this composer, so- # "Discuss" would 403 on its first reply if this required Code access.+ # The Inbox starts interactive runs and drops the user straight into this composer,+ # so "Discuss" and scout chat replies must not require Desktop access. Their tasks+ # are server-verifiable Inbox shapes (task_exempt_from_code_access); everything else+ # is a Desktop conversation and follows the same gate as TaskViewSet.run.+ if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (+ access_response := code_access_required_response(request.user)+ ):+ return access_responsecommand_params = dict(params or {})artifact_ids = command_params.pop("artifact_ids", [])if artifact_ids:@@ -2139,6 +2228,28 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):response_payload["id"] = request_idreturn Response(TaskRunCommandResponseSerializer(response_payload).data)+ if method == "pi/rpc":+ inner_command = params.get("command") if isinstance(params, dict) else None+ inner_type = inner_command.get("type") if isinstance(inner_command, dict) else None+ if (+ inner_type+ not in {+ "abort",+ "abort_bash",+ "get_available_models",+ "get_available_thinking_levels",+ "get_commands",+ "get_entries",+ "get_session_stats",+ "get_state",+ "mcp_permission_response",+ "permission_response",+ }+ and not tasks_facade.task_exempt_from_code_access(task_id, self.team_id)+ and (access_response := code_access_required_response(request.user))+ ):+ return access_response+connection = tasks_facade.get_task_run_sandbox_connection(pk, task_id, self.team_id, user_id=request.user.id, distinct_id=request.user.distinct_id)@@ -2400,7 +2511,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Run already active or workflow failed"),- 403: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Pi cloud runtime is disabled"),+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="PostHog Desktop access is required, or Pi cloud runtime is disabled",+ ),429: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"),@@ -2424,6 +2538,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return _pi_cloud_runtime_disabled_response()# Resume also runs in cloud: gate before handoff.+ if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (+ access_response := code_access_required_response(request.user)+ ):+ return access_responseif limit_response := usage_limit_response(request.user, self.team_id):return limit_responsediff --git a/products/tasks/backend/temporal/automation/activities.py b/products/tasks/backend/temporal/automation/activities.pyindex 2e20e34f4f81..8fb2285f0e26 100644--- a/products/tasks/backend/temporal/automation/activities.py+++ b/products/tasks/backend/temporal/automation/activities.py@@ -1,4 +1,7 @@+from django.core.exceptions import PermissionDenied+from temporalio import activity+from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import asyncify@@ -8,4 +11,7 @@ from posthog.temporal.common.utils import asyncifydef run_task_automation_activity(automation_id: str) -> None:from ...automation_service import run_task_automation- run_task_automation(automation_id, trigger_workflow_id=activity.info().workflow_id)+ try:+ run_task_automation(automation_id, trigger_workflow_id=activity.info().workflow_id)+ except PermissionDenied as e:+ raise ApplicationError(str(e), type="AutomationAccessRevoked", non_retryable=True) from ediff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 55e5fca32144..0f62bfda8985 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -265,6 +265,9 @@ def _resolve_sandbox_github_token()return github_token+ if not has_repo and task.origin_product in (Task.OriginProduct.SIGNALS_CHAT, Task.OriginProduct.SIGNAL_REPORT):+ return ""+should_inject_github_token = ctx.has_github_credentials and (has_repo or ctx.github_user_integration_id is not None or ctx.github_integration_id is not None)diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 9492dbea9d94..bbda25f6998e 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -41,6 +41,7 @@ from products.tasks.backend.facade.run_config import TaskArtifactAdapter, TaskArfrom products.tasks.backend.logic.services.code_usage_gate import (CodeUsageStatus,_gateway_usage_url,+ code_access_required_response,get_posthog_code_usage,usage_limit_response,)@@ -148,7 +149,16 @@ _DISCUSS_PROMPT = ()+OVER_LIMIT = CodeUsageStatus(+ is_rate_limited=True,+ limit_type="burst",+ reset_at="2026-06-09T00:00:00Z",+ is_pro=False,+)++class BaseTaskAPITest(TestCase):+ OVER_LIMIT: ClassVar[CodeUsageStatus] = OVER_LIMITorganization: ClassVar[Organization]team: ClassVar[Team]user: ClassVar[User]@@ -400,6 +410,44 @@ class TestTaskCreatorScoping(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["id"], str(task.id))+ def test_retrieve_signals_chat_task_owned_by_another_user_returns_404(self):+ other_user = self.create_organization_user("chat-owner")+ task = Task.objects.create(+ team=self.team,+ created_by=other_user,+ title="Scout chat",+ description="How is my scout fleet performing?",+ origin_product=Task.OriginProduct.SIGNALS_CHAT,+ )++ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_only_creator_can_create_run_for_signals_chat_task(self):+ other_user = self.create_organization_user("chat-owner")+ task = Task.objects.create(+ team=self.team,+ created_by=other_user,+ title="Scout chat",+ description="How is my scout fleet performing?",+ origin_product=Task.OriginProduct.SIGNALS_CHAT,+ )++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/",+ {"environment": "cloud"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ self.client.force_authenticate(other_user)+ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/",+ {"environment": "cloud"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+def test_list_signal_report_tasks_hidden_by_default(self):# Signal-report tasks are always created with internal=True, so the# default list still hides them. The retrieve-by-ID path (and the@@ -1633,6 +1681,7 @@ class TestTaskAPI(BaseTaskAPITest):(Task.OriginProduct.SIGNALS_SCOUT,),(Task.OriginProduct.SUPPORT_REPLY,),(Task.OriginProduct.ONBOARDING,),+ (Task.OriginProduct.SIGNALS_CHAT,),])def test_create_task_rejects_server_created_origin(self, origin_product: Task.OriginProduct):@@ -3845,7 +3894,10 @@ class TestTaskAPI(BaseTaskAPITest):mock_workflow.assert_not_called()@override_settings(DEBUG=False)- @patch("products.tasks.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)+ @patch(+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",+ side_effect=lambda flag, *_args, **_kwargs: flag == "tasks",+ )@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_run_endpoint_resume_rejects_inherited_gated_model(self, mock_workflow, mock_feature_enabled):# A resume omits `model`, so the serializer sees None and passes. The inherited@@ -4577,8 +4629,7 @@ class TestTaskAutomationAPI(BaseTaskAPITest):mock_sync_schedule.assert_called_once_with(automation)@patch("products.tasks.backend.automation_service.sync_automation_schedule")- def test_create_automation_without_code_access(self, mock_sync_schedule):- # `tasks` gates the Desktop client's UI, not the API.+ def test_create_automation_requires_code_access(self, mock_sync_schedule):self.set_tasks_feature_flag(False)response = self.client.post(@@ -4593,9 +4644,10 @@ class TestTaskAutomationAPI(BaseTaskAPITest):format="json",)- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- self.assertTrue(TaskAutomation.objects.exists())- mock_sync_schedule.assert_called_once()+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+ self.assertFalse(TaskAutomation.objects.exists())+ mock_sync_schedule.assert_not_called()def test_list_automations(self):automation = self.create_automation()@@ -4723,7 +4775,24 @@ class TestTaskAutomationAPI(BaseTaskAPITest):mock_sync_schedule.assert_called_once_with(automation)@patch("products.tasks.backend.automation_service.sync_automation_schedule")- def test_enable_automation_without_code_access(self, mock_sync_schedule):+ def test_update_automation_without_enabling_needs_no_code_access(self, _mock_sync_schedule):+ # The gate only guards turning an automation on; editing or disabling one must stay+ # possible for users without Desktop access, or they couldn't stop their own schedules.+ automation = self.create_automation()+ self.set_tasks_feature_flag(False)++ response = self.client.patch(+ f"/api/projects/@current/task_automations/{automation.id}/",+ {"cron_expression": "30 14 * * *"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ automation.refresh_from_db()+ self.assertEqual(automation.cron_expression, "30 14 * * *")++ @patch("products.tasks.backend.automation_service.sync_automation_schedule")+ def test_enable_automation_requires_code_access(self, mock_sync_schedule):automation = self.create_automation()automation.enabled = Falseautomation.save(update_fields=["enabled", "updated_at"])@@ -4735,10 +4804,11 @@ class TestTaskAutomationAPI(BaseTaskAPITest):format="json",)- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")automation.refresh_from_db()- self.assertTrue(automation.enabled)- mock_sync_schedule.assert_called_once()+ self.assertFalse(automation.enabled)+ mock_sync_schedule.assert_not_called()@patch("products.tasks.backend.facade.api._sync_automation_schedule")def test_update_automation_rolls_back_automation_when_task_update_fails(self, mock_sync_schedule):@@ -4779,14 +4849,15 @@ class TestTaskAutomationAPI(BaseTaskAPITest):mock_run_task_automation.assert_called_once_with(str(automation.id))@patch("products.tasks.backend.automation_service.run_task_automation")- def test_run_without_code_access(self, mock_run_task_automation):+ def test_run_requires_code_access(self, mock_run_task_automation):self.set_tasks_feature_flag(False)automation = self.create_automation()response = self.client.post(f"/api/projects/@current/task_automations/{automation.id}/run/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- mock_run_task_automation.assert_called_once_with(str(automation.id))+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+ mock_run_task_automation.assert_not_called()_PR_URL = "https://github.com/posthog/posthog-js/pull/1"@@ -7586,6 +7657,29 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(decoded["user_id"], self.user.id)self.assertIn("exp", decoded)+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")+ def test_connection_token_requires_code_access(self, mock_usage):+ self.set_tasks_feature_flag(False)+ task = self.create_task()+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)++ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/connection_token/")++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+ mock_usage.assert_not_called()++ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")+ def test_connection_token_keeps_usage_backstop(self, mock_usage):+ mock_usage.return_value = self.OVER_LIMIT+ task = self.create_task()+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)++ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/connection_token/")++ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertEqual(response.json()["code"], "usage_limit_exceeded")+@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_connection_token_has_correct_expiry(self):reset_sandbox_jwt_key_cache()@@ -9510,9 +9604,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):)@patch("products.tasks.backend.temporal.client.signal_task_followup_message")- def test_command_user_message_without_code_access_still_sends(self, mock_signal_followup):- # The Inbox drops users straight into this composer after starting an interactive run,- # so replying must not require Desktop waitlist access.+ def test_command_user_message_requires_code_access(self, mock_signal_followup):self.set_tasks_feature_flag(False)task = self.create_task()run = self._create_run_with_sandbox(task)@@ -9523,6 +9615,83 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):format="json",)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+ mock_signal_followup.assert_not_called()++ @parameterized.expand([("prompt",), ("steer",), ("follow_up",), ("bash",), ("compact",), ("set_model",)])+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")+ def test_command_pi_rpc_execution_requires_code_access(self, inner_type, mock_post):+ self.set_tasks_feature_flag(False)+ task = self.create_task(runtime=Task.Runtime.PI)+ run = self._create_run_with_sandbox(task)++ response = self.client.post(+ self._command_url(task, run),+ {+ "jsonrpc": "2.0",+ "method": "pi/rpc",+ "id": "p1",+ "params": {"command": {"id": "p1", "type": inner_type, "message": "go"}},+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+ mock_post.assert_not_called()++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")+ def test_command_pi_rpc_control_command_skips_code_access(self, mock_post):+ reset_sandbox_jwt_key_cache()+ self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "id": "c1", "result": {}})+ self.set_tasks_feature_flag(False)+ task = self.create_task(runtime=Task.Runtime.PI)+ run = self._create_run_with_sandbox(task)++ response = self.client.post(+ self._command_url(task, run),+ {+ "jsonrpc": "2.0",+ "method": "pi/rpc",+ "id": "c1",+ "params": {"command": {"id": "c1", "type": "permission_response", "approved": True}},+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_post.assert_called_once()++ @parameterized.expand(+ [+ ("signal_report_with_report", Task.OriginProduct.SIGNAL_REPORT),+ ("signals_chat", Task.OriginProduct.SIGNALS_CHAT),+ ]+ )+ @patch("products.tasks.backend.temporal.client.signal_task_followup_message")+ def test_command_user_message_on_inbox_task_needs_no_code_access(self, _name, origin, mock_signal_followup):+ # The Inbox starts interactive runs and drops the user straight into this composer, so+ # replying on its tasks (report Discuss / scout chat) must not require Desktop access.+ from products.signals.backend.models import SignalReport++ self.set_tasks_feature_flag(False)+ task = self.create_task()+ task.origin_product = origin+ task.github_integration = None+ task.github_user_integration = None+ if origin == Task.OriginProduct.SIGNAL_REPORT:+ task.signal_report = SignalReport.objects.create(team=self.team)+ task.save()+ run = self._create_run_with_sandbox(task)++ response = self.client.post(+ self._command_url(task, run),+ self._make_user_message(),+ format="json",+ )+self.assertEqual(response.status_code, status.HTTP_200_OK)mock_signal_followup.assert_called_once()@@ -11057,13 +11226,6 @@ class TestSandboxEnvironmentAPI(BaseTaskAPITest):class TestCloudUsageGate(BaseTaskAPITest):- OVER_LIMIT: ClassVar[CodeUsageStatus] = CodeUsageStatus(- is_rate_limited=True,- limit_type="burst",- reset_at="2026-06-09T00:00:00Z",- is_pro=False,- )-def _cloud_run(self, task, status_value=TaskRun.Status.QUEUED):return TaskRun.objects.create(task=task,@@ -11074,7 +11236,7 @@ class TestCloudUsageGate(BaseTaskAPITest):@patch("products.tasks.backend.facade.api.warm_task_sandbox")@patch("products.tasks.backend.presentation.views.api.TaskViewSet._warm_enabled", return_value=True)- def test_warm_without_code_access_still_provisions(self, _mock_warm_enabled, mock_warm):+ def test_warm_without_code_access_returns_403_before_provisioning(self, _mock_warm_enabled, mock_warm):self.set_tasks_feature_flag(False)response = self.client.post(@@ -11083,7 +11245,9 @@ class TestCloudUsageGate(BaseTaskAPITest):format="json",)- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+ mock_warm.assert_not_called()@patch("products.tasks.backend.facade.api.warm_task_sandbox")@patch("products.tasks.backend.presentation.views.api.TaskViewSet._warm_enabled", return_value=True)@@ -11139,12 +11303,19 @@ class TestCloudUsageGate(BaseTaskAPITest):assert mock_feature_enabled.call_args.args[0] == "tasks-kimi-k3"assert not Task.objects.filter(title="Gated").exists()+ def _inbox_task(self, origin: Task.OriginProduct) -> Task:+ from products.signals.backend.models import SignalReport++ task = self.create_task()+ task.origin_product = origin+ if origin == Task.OriginProduct.SIGNAL_REPORT:+ task.signal_report = SignalReport.objects.create(team=self.team)+ task.save()+ return task+@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")- def test_run_without_code_access_still_runs(self, mock_gate, mock_workflow):- # The generally-available Inbox runs report and scout tasks through this endpoint, so the- # Desktop waitlist (`tasks` flag) must not gate it.- mock_gate.return_value = None+ def test_run_without_code_access_returns_403_before_usage_check(self, mock_gate, mock_workflow):self.set_tasks_feature_flag(False)task = self.create_task()@@ -11154,9 +11325,31 @@ class TestCloudUsageGate(BaseTaskAPITest):format="json",)- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertTrue(TaskRun.objects.filter(task=task).exists())- mock_workflow.assert_called_once()+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+ self.assertFalse(TaskRun.objects.filter(task=task).exists())+ mock_gate.assert_not_called()+ mock_workflow.assert_not_called()++ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")+ def test_run_forged_signal_report_origin_without_report_still_403s(self, mock_gate, mock_workflow):+ # `origin_product` is client input on task create, so an FK-less signal_report claim+ # must not bypass the waitlist — only a real team-scoped report link exempts a task.+ self.set_tasks_feature_flag(False)+ task = self.create_task()+ task.origin_product = Task.OriginProduct.SIGNAL_REPORT+ task.save()++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/run/",+ {"mode": "background"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+ mock_workflow.assert_not_called()@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")def test_run_for_any_deactivated_org_returns_429_without_gateway_check(self, mock_gate):@@ -11208,9 +11401,7 @@ class TestCloudUsageGate(BaseTaskAPITest):self.assertFalse(TaskRun.objects.filter(task=task).exists())@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")- def test_create_cloud_run_without_code_access_still_runs(self, mock_gate):- # Desktop is usage-billed, so cloud runs are metered rather than waitlist-gated.- mock_gate.return_value = None+ def test_create_cloud_run_without_code_access_returns_403(self, mock_gate):self.set_tasks_feature_flag(False)task = self.create_task()@@ -11220,9 +11411,196 @@ class TestCloudUsageGate(BaseTaskAPITest):format="json",)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+ self.assertFalse(TaskRun.objects.filter(task=task).exists())+ mock_gate.assert_not_called()++ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage", return_value=None)+ def test_create_cloud_run_on_inbox_task_needs_no_code_access(self, _mock_gate):+ self.set_tasks_feature_flag(False)+ task = self._inbox_task(Task.OriginProduct.SIGNALS_CHAT)++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/",+ {"environment": "cloud"},+ format="json",+ )+self.assertEqual(response.status_code, status.HTTP_201_CREATED)self.assertTrue(TaskRun.objects.filter(task=task).exists())+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage", return_value=None)+ def test_start_on_inbox_task_needs_no_code_access(self, _mock_gate, mock_workflow):+ self.set_tasks_feature_flag(False)+ task = self._inbox_task(Task.OriginProduct.SIGNALS_CHAT)+ run = self._cloud_run(task)++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/start/",+ {},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_workflow.assert_called_once()++ @patch("products.tasks.backend.temporal.client.resume_task_in_cloud_workflow")+ @patch("products.tasks.backend.facade.streams.reset_task_run_stream", return_value=True)+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage", return_value=None)+ def test_resume_in_cloud_on_inbox_task_needs_no_code_access(self, _mock_gate, _mock_reset, mock_resume):+ self.set_tasks_feature_flag(False)+ task = self._inbox_task(Task.OriginProduct.SIGNALS_CHAT)+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ environment=TaskRun.Environment.LOCAL,+ status=TaskRun.Status.COMPLETED,+ state={"pr_authorship_mode": "bot"},+ )++ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/resume_in_cloud/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_resume.assert_called_once()++ def test_exemption_ignores_cross_team_report_link(self):+ # The write serializer blocks cross-team report links, so forge one at the ORM level:+ # the exemption query must re-check the report's team rather than trust the FK alone.+ from products.signals.backend.models import SignalReport++ other_team = Team.objects.create(organization=self.organization, name="Other Team")+ task = self.create_task()+ task.origin_product = Task.OriginProduct.SIGNAL_REPORT+ task.signal_report = SignalReport.objects.create(team=other_team)+ task.save()++ self.assertFalse(tasks_facade.task_exempt_from_code_access(task.id, self.team.id))++ @parameterized.expand(+ [+ ("legacy_repository", "repository", "posthog/posthog"),+ ("repositories_list", "repositories", ["posthog/posthog"]),+ ]+ )+ def test_exemption_drops_for_signals_chat_task_with_repository(self, _name, field, value):+ task = self._inbox_task(Task.OriginProduct.SIGNALS_CHAT)+ self.assertTrue(tasks_facade.task_exempt_from_code_access(task.id, self.team.id))++ setattr(task, field, value)+ task.save()++ self.assertFalse(tasks_facade.task_exempt_from_code_access(task.id, self.team.id))++ def test_exemption_drops_for_signal_report_task_with_repository(self):+ task = self._inbox_task(Task.OriginProduct.SIGNAL_REPORT)+ self.assertTrue(tasks_facade.task_exempt_from_code_access(task.id, self.team.id))++ task.repository = "posthog/posthog"+ task.save()++ self.assertFalse(tasks_facade.task_exempt_from_code_access(task.id, self.team.id))++ def test_create_signal_report_task_ignores_channel_repository(self):+ from products.signals.backend.models import SignalReport+ from products.tasks.backend.models import Channel++ report = SignalReport.objects.create(team=self.team)+ channel = Channel.objects.unscoped().create(team=self.team, name="ch", repositories=["attacker/repo"])+ with (+ patch("products.signals.backend.facade.api.persisted_repo_selection", return_value=None),+ patch("products.tasks.backend.logic.repo_selection.cascade.cascade_select_repository", return_value=None),+ ):+ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "Forged",+ "description": "Forged",+ "origin_product": Task.OriginProduct.SIGNAL_REPORT,+ "signal_report": str(report.id),+ "channel": str(channel.id),+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ task = Task.objects.get(id=response.json()["id"])+ self.assertIsNone(task.repository)+ self.assertNotIn("attacker/repo", task.repositories)++ def test_create_signal_report_task_rejects_client_repository(self):+ from products.signals.backend.models import SignalReport++ report = SignalReport.objects.create(team=self.team)+ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "Forged",+ "description": "Forged",+ "origin_product": Task.OriginProduct.SIGNAL_REPORT,+ "signal_report": str(report.id),+ "repository": "posthog/posthog",+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "repository")+ self.assertFalse(Task.objects.filter(title="Forged").exists())++ def test_update_cannot_attach_repository_to_signals_chat_task(self):+ task = self._inbox_task(Task.OriginProduct.SIGNALS_CHAT)++ response = self.client.patch(+ f"/api/projects/@current/tasks/{task.id}/",+ {"repository": "posthog/posthog"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ task.refresh_from_db()+ self.assertIsNone(task.repository)+ self.assertEqual(task.repositories, [])+ self.assertTrue(tasks_facade.task_exempt_from_code_access(task.id, self.team.id))++ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")+ def test_start_without_code_access_returns_403(self, mock_gate):+ self.set_tasks_feature_flag(False)+ task = self.create_task()+ run = self._cloud_run(task)++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/start/",+ {},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+ run.refresh_from_db()+ self.assertEqual(run.status, TaskRun.Status.QUEUED)++ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")+ def test_resume_in_cloud_without_code_access_returns_403(self, mock_gate):+ self.set_tasks_feature_flag(False)+ task = self.create_task()+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ environment=TaskRun.Environment.LOCAL,+ status=TaskRun.Status.COMPLETED,+ )++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/resume_in_cloud/",+ {},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["code"], "code_access_required")+@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")def test_create_local_run_is_not_gated(self, mock_gate):mock_gate.return_value = self.OVER_LIMIT@@ -11298,13 +11676,31 @@ class TestCloudUsageGate(BaseTaskAPITest):self.assertTrue(TaskRun.objects.filter(task=task).exists())mock_workflow.assert_called_once()+ @parameterized.expand(+ [+ ("signal_report_under_limit", Task.OriginProduct.SIGNAL_REPORT, None, status.HTTP_200_OK),+ (+ "signal_report_over_limit",+ Task.OriginProduct.SIGNAL_REPORT,+ OVER_LIMIT,+ status.HTTP_429_TOO_MANY_REQUESTS,+ ),+ ("signals_chat_under_limit", Task.OriginProduct.SIGNALS_CHAT, None, status.HTTP_200_OK),+ ("signals_chat_over_limit", Task.OriginProduct.SIGNALS_CHAT, OVER_LIMIT, status.HTTP_429_TOO_MANY_REQUESTS),+ ]+ )+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")- def test_run_without_code_access_keeps_usage_backstop(self, mock_gate):- # Usage limits are the only cost backstop left on this endpoint, so they have to fire- # with the `tasks` flag off.+ def test_run_inbox_task_bypasses_code_access_but_keeps_usage_backstop(+ self, _name, origin, gate_return, expected_status, mock_gate, _mock_workflow+ ):+ # Inbox tasks (report "Create PR" / "Discuss", scout chat) are entitled through+ # self-driving, not PostHog Desktop, so they run with the `tasks` flag off — where a+ # plain task 403s (see test_run_without_code_access_returns_403_before_usage_check).+ # The usage cost-backstop must still fire on the entitlement-bypassed path.self.set_tasks_feature_flag(False)- mock_gate.return_value = self.OVER_LIMIT- task = self.create_task()+ mock_gate.return_value = gate_return+ task = self._inbox_task(origin)response = self.client.post(f"/api/projects/@current/tasks/{task.id}/run/",@@ -11312,8 +11708,9 @@ class TestCloudUsageGate(BaseTaskAPITest):format="json",)- self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)- self.assertFalse(TaskRun.objects.filter(task=task).exists())+ self.assertEqual(response.status_code, expected_status)+ mock_gate.assert_called_once()+ self.assertEqual(TaskRun.objects.filter(task=task).exists(), expected_status == status.HTTP_200_OK)class TestGetPosthogCodeUsage(TestCase):@@ -11406,6 +11803,14 @@ class TestUsageLimitResponse(TestCase):self.assertEqual(response.data["code"], "usage_limit_exceeded")self.assertEqual(response.data["limit_type"], "burst")+ @patch("products.tasks.backend.logic.services.code_usage_gate.has_tasks_access", return_value=False)+ def test_code_access_required_response_is_structured(self, _mock_access):+ response = code_access_required_response(MagicMock())++ assert response is not None+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.data["code"], "code_access_required")+def _make_custom_image(*, team: Team, user: User, **kwargs) -> SandboxCustomImage:image = SandboxCustomImage(team=team, created_by=user, **kwargs)diff --git a/products/tasks/backend/tests/test_automation_service.py b/products/tasks/backend/tests/test_automation_service.pyindex 8c9aee4daac2..a0978474bbdc 100644--- a/products/tasks/backend/tests/test_automation_service.py+++ b/products/tasks/backend/tests/test_automation_service.py@@ -1,5 +1,6 @@from unittest.mock import patch+from django.core.exceptions import PermissionDeniedfrom django.test import TestCasefrom posthog.models import Organization, Team, User@@ -13,6 +14,9 @@ class TestAutomationService(TestCase):self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")self.user = User.objects.create_user(email="[email protected]", first_name="Test", password="password")+ access_patcher = patch("products.tasks.backend.automation_service.has_tasks_access", return_value=True)+ access_patcher.start()+ self.addCleanup(access_patcher.stop)def create_automation(self) -> TaskAutomation:task = Task.objects.create(@@ -98,6 +102,33 @@ class TestAutomationService(TestCase):self.assertEqual(TaskRun.objects.filter(task=first_task).count(), 2)self.assertEqual(mock_execute_workflow.call_count, 2)+ @patch("products.tasks.backend.automation_service.has_tasks_access", return_value=False)+ @patch("products.tasks.backend.automation_service.execute_task_processing_workflow_for_automation")+ def test_run_task_automation_requires_code_access(self, mock_execute_workflow, _mock_access):+ automation = self.create_automation()++ with self.assertRaises(PermissionDenied):+ run_task_automation(str(automation.id))++ self.assertFalse(TaskRun.objects.filter(task=automation.task).exists())+ mock_execute_workflow.assert_not_called()+ automation.refresh_from_db()+ self.assertIsNotNone(automation.last_error)++ @patch("products.tasks.backend.automation_service.execute_task_processing_workflow_for_automation")+ def test_run_task_automation_fails_closed_without_creator(self, mock_execute_workflow):+ # created_by is SET_NULL on user deletion; with no user there is no entitlement and+ # no way to mint the run's sandbox OAuth token, so the fire must stop, not skip the check.+ automation = self.create_automation()+ automation.task.created_by = None+ automation.task.save(update_fields=["created_by", "updated_at"])++ with self.assertRaises(PermissionDenied):+ run_task_automation(str(automation.id))++ self.assertFalse(TaskRun.objects.filter(task=automation.task).exists())+ mock_execute_workflow.assert_not_called()+def test_automation_last_run_properties_come_from_last_task_run(self):automation = self.create_automation()task_run = automation.task.create_run(mode="background", extra_state={"automation_id": str(automation.id)})diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.pyindex 4c58e2441881..96ff8e24a843 100644--- a/products/tasks/backend/tests/test_warm_facade.py+++ b/products/tasks/backend/tests/test_warm_facade.py@@ -53,6 +53,12 @@ class TestWarmTaskSandbox(APIBaseTest):def setUp(self) -> None:super().setUp()self.integration = Integration.objects.create(team=self.team, kind="github", config={})+ # The warm endpoint gates on Desktop access; these tests cover warm forwarding, not the gate.+ access_patcher = patch(+ "products.tasks.backend.logic.services.code_usage_gate.has_tasks_access", return_value=True+ )+ access_patcher.start()+ self.addCleanup(access_patcher.stop)def _warm(self, **overrides):kwargs: dict[str, Any] = {diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 1b1145532852..77b010023de4 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1648,6 +1648,7 @@ export interface PaginatedTaskDetailDTOListApi {* * `image_builder` - Image Builder* * `loop` - Loop* * `mcp_analytics` - MCP Analytics+ * * `signals_chat` - Signals Chat*/export type OriginProductEnumApi = (typeof OriginProductEnumApi)[keyof typeof OriginProductEnumApi]@@ -1670,6 +1671,7 @@ export const OriginProductEnumApi = {ImageBuilder: 'image_builder',Loop: 'loop',McpAnalytics: 'mcp_analytics',+ SignalsChat: 'signals_chat',} as const/**@@ -1708,7 +1710,8 @@ export interface TaskCreateApi {* * `review_hog` - ReviewHog* * `image_builder` - Image Builder* * `loop` - Loop- * * `mcp_analytics` - MCP Analytics */+ * * `mcp_analytics` - MCP Analytics+ * * `signals_chat` - Signals Chat */origin_product?: OriginProductEnumApi/*** Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).@@ -1851,7 +1854,8 @@ export interface TaskWriteApi {* * `review_hog` - ReviewHog* * `image_builder` - Image Builder* * `loop` - Loop- * * `mcp_analytics` - MCP Analytics */+ * * `mcp_analytics` - MCP Analytics+ * * `signals_chat` - Signals Chat */origin_product?: OriginProductEnumApi/*** Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).@@ -1979,7 +1983,8 @@ export interface PatchedTaskWriteApi {* * `review_hog` - ReviewHog* * `image_builder` - Image Builder* * `loop` - Loop- * * `mcp_analytics` - MCP Analytics */+ * * `mcp_analytics` - MCP Analytics+ * * `signals_chat` - Signals Chat */origin_product?: OriginProductEnumApi/*** Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex fbb886104741..0f6a51c1ed24 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -1205,13 +1205,14 @@ export const TasksCreateBody = /* @__PURE__ */ zod'image_builder','loop','mcp_analytics',+ 'signals_chat',]).describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat').optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'),repository: zod.string()@@ -1369,13 +1370,14 @@ export const TasksUpdateBody = /* @__PURE__ */ zod'image_builder','loop','mcp_analytics',+ 'signals_chat',]).describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat').optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'),repository: zod.string()@@ -1518,13 +1520,14 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod'image_builder','loop','mcp_analytics',+ 'signals_chat',]).describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat').optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'),repository: zod.string()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9122a04de761..ad84cac24fb5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -15425,6 +15425,20 @@ export namespace Schemas {star?: boolean;}+ /**+ * * `author_scout` - author_scout+ * * `fleet_overview` - fleet_overview+ * * `recent_signals` - recent_signals+ */+ export type ChatTypeEnum = typeof ChatTypeEnum[keyof typeof ChatTypeEnum];+++ export const ChatTypeEnum = {+ AuthorScout: 'author_scout',+ FleetOverview: 'fleet_overview',+ RecentSignals: 'recent_signals',+ } as const;+export interface CheckDatabaseNameResponse {name: string;available: boolean;@@ -47620,6 +47634,7 @@ export namespace Schemas {* * `image_builder` - Image Builder* * `loop` - Loop* * `mcp_analytics` - MCP Analytics+ * * `signals_chat` - Signals Chat*/export type OriginProductEnum = typeof OriginProductEnum[keyof typeof OriginProductEnum];@@ -47643,6 +47658,7 @@ export namespace Schemas {ImageBuilder: 'image_builder',Loop: 'loop',McpAnalytics: 'mcp_analytics',+ SignalsChat: 'signals_chat',} as const;/**@@ -60723,7 +60739,8 @@ export namespace Schemas {* * `review_hog` - ReviewHog* * `image_builder` - Image Builder* * `loop` - Loop- * * `mcp_analytics` - MCP Analytics */+ * * `mcp_analytics` - MCP Analytics+ * * `signals_chat` - Signals Chat */origin_product?: OriginProductEnum;/*** Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).@@ -69138,6 +69155,20 @@ export namespace Schemas {base_version?: number;}+ export interface ScoutChatTask {+ /** The created chat task. Open it on the task detail page to continue. */+ task_id: string;+ }++ export interface ScoutChatTaskCreate {+ /** Which scout chat to start: `author_scout` (guided scout authoring), `fleet_overview` (health of the scout fleet), or `recent_signals` (walk through recently emitted signals). The prompt template is owned server-side.+ *+ * * `author_scout` - author_scout+ * * `fleet_overview` - fleet_overview+ * * `recent_signals` - recent_signals */+ chat_type: ChatTypeEnum;+ }+/*** * `no_output` - No output* * `ignored` - Ignored@@ -76334,7 +76365,8 @@ export namespace Schemas {* * `review_hog` - ReviewHog* * `image_builder` - Image Builder* * `loop` - Loop- * * `mcp_analytics` - MCP Analytics */+ * * `mcp_analytics` - MCP Analytics+ * * `signals_chat` - Signals Chat */origin_product?: OriginProductEnum;/*** Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).@@ -77488,7 +77520,8 @@ export namespace Schemas {* * `review_hog` - ReviewHog* * `image_builder` - Image Builder* * `loop` - Loop- * * `mcp_analytics` - MCP Analytics */+ * * `mcp_analytics` - MCP Analytics+ * * `signals_chat` - Signals Chat */origin_product?: OriginProductEnum;/*** Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 616dbb937907..cc7796e10829 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -972,13 +972,14 @@ export const TasksCreateBody = /* @__PURE__ */ zod'image_builder','loop','mcp_analytics',+ 'signals_chat',]).describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat').optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'),repository: zod.string()