:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): file a workflow-created task in a space (#99007)
Harley Alexanderd99ee0038231
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.tsindex 71799aa5e57d..3c133e3e61e3 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.ts@@ -19,6 +19,7 @@ describe('posthog create task template', () => {skills: ['error-triage', 'db-runbook'],posthog_mcp_scopes: 'full',max_parallel_tasks: 3,+ channel: '0198c9f1-bbbb-0000-0000-000000000001|growth',}// Mirrors the default event in createGlobals; the request must always carry the trigger event.const defaultEventBody = {@@ -81,6 +82,7 @@ describe('posthog create task template', () => {skills: ['error-triage', 'db-runbook'],posthog_mcp_scopes: 'full',max_parallel_tasks: 3,+ channel: '0198c9f1-bbbb-0000-0000-000000000001|growth',event: defaultEventBody,idempotency_key: `${invocation.id}:action_1:0`,})diff --git a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.tsindex f9ac0e8055ff..b9874f969b87 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts@@ -41,6 +41,10 @@ if (not empty(inputs.connectors)) {payload.connectors := inputs.connectors}+if (not empty(inputs.channel)) {+ payload.channel := inputs.channel+}+if (not empty(inputs.skills)) {payload.skills := inputs.skills}@@ -153,6 +157,21 @@ return taskdescription:'New runs are skipped while this many tasks from this workflow are still running. Protects against a burst of trigger events starting too many agents at once. Daily limits on how many tasks a workflow and project can create also apply.',},+ {+ // A space is a Tasks concept the workflow editor has no picker for, so the field is+ // hidden and set by the clients that know about spaces. The display name rides along+ // after a pipe, like the Slack channel picker's "C123|#name": the API keeps the id and+ // the clients read the name back without a second input to keep in step.+ key: 'channel',+ type: 'string',+ label: 'Space',+ secret: false,+ required: false,+ hidden: true,+ templating: false,+ description:+ 'Space the created task is filed into, as its id, optionally followed by "|" and the space name. Leave empty to file the task in no space.',+ },{// Only meaningful on a Slack-triggered workflow; the builder hides it for other// triggers, and the hog code above no-ops when the trigger event isn't a Slack message.diff --git a/nodejs/tests/fixtures/hog-bytecode/c26c0d194134146bbc8d762d2db09e8ccd891f4cb152ecf6da9e73733872359c.json b/nodejs/tests/fixtures/hog-bytecode/c26c0d194134146bbc8d762d2db09e8ccd891f4cb152ecf6da9e73733872359c.jsonnew file mode 100644index 000000000000..12908d0f5ffb--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/c26c0d194134146bbc8d762d2db09e8ccd891f4cb152ecf6da9e73733872359c.json@@ -0,0 +1 @@+["_H",1,52,"apiErrorMessage",1,0,28,36,0,32,"body",45,32,"error",45,47,9,35,36,0,32,"body",45,32,"detail",45,47,6,35,36,0,32,"body",45,38,53,0,32,"prompt",32,"inputs",1,2,2,"empty",1,40,6,32,"Instructions are required",2,"Error",1,49,32,"prompt",32,"prompt",32,"inputs",1,2,32,"event",32,"event",1,1,42,2,32,"title",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"title",32,"title",32,"inputs",1,2,46,32,"model",32,"inputs",1,2,2,"empty",1,5,32,"model",32,"model",32,"inputs",1,3,2,"empty",1,5,3,2,40,40,36,1,32,"model",32,"model",32,"model",32,"inputs",1,3,46,32,"reasoning_effort",32,"model",32,"inputs",1,3,2,"empty",1,5,40,13,36,1,32,"reasoning_effort",32,"reasoning_effort",32,"model",32,"inputs",1,3,46,32,"repository",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"repository",32,"repository",32,"inputs",1,2,46,32,"connectors",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"connectors",32,"connectors",32,"inputs",1,2,46,32,"channel",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"channel",32,"channel",32,"inputs",1,2,46,32,"skills",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"skills",32,"skills",32,"inputs",1,2,46,32,"posthog_mcp_scopes",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"posthog_mcp_scopes",32,"posthog_mcp_scopes",32,"inputs",1,2,46,32,"max_parallel_tasks",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"max_parallel_tasks",32,"max_parallel_tasks",32,"inputs",1,2,46,30,32,"reply_in_slack_thread",32,"inputs",1,2,12,32,"$slack_message_received",32,"event",32,"event",1,2,11,32,"channel",32,"properties",32,"event",1,3,2,"empty",1,5,32,"ts",32,"properties",32,"event",1,3,2,"empty",1,5,3,4,40,102,36,1,32,"slack_context",32,"integration_id",32,"integration_id",32,"properties",32,"event",1,3,32,"channel",32,"channel",32,"properties",32,"event",1,3,32,"thread_ts",32,"thread_ts",32,"properties",32,"event",1,3,47,9,35,32,"ts",32,"properties",32,"event",1,3,32,"message_ts",32,"ts",32,"properties",32,"event",1,3,32,"slack_user_id",32,"user",32,"properties",32,"event",1,3,47,3,35,32,"",32,"slack_team_id",32,"slack_team_id",32,"properties",32,"event",1,3,47,3,35,32,"",32,"is_ext_shared_channel",32,"is_ext_shared_channel",32,"properties",32,"event",1,3,47,2,35,30,42,7,46,36,1,2,"postHogCreateTask",1,33,400,36,2,32,"status",45,14,40,22,32,"Failed to create task (",36,2,32,"status",45,32,"): ",36,2,36,0,54,1,2,"concat",4,2,"Error",1,49,36,2,32,"body",45,36,3,32,"run_id",45,2,"empty",1,5,40,15,36,3,32,"await",32,"max_wait",32,"190m",32,"label",32,"task",42,2,46,36,3,38,35,35,35,35]diff --git a/products/tasks/backend/logic/services/workflow_tasks.py b/products/tasks/backend/logic/services/workflow_tasks.pyindex 72cd323c8df8..b972a27b6b02 100644--- a/products/tasks/backend/logic/services/workflow_tasks.py+++ b/products/tasks/backend/logic/services/workflow_tasks.py@@ -41,7 +41,7 @@ from products.tasks.backend.logic.services.workflow_task_skills import (resolve_attached_skills,)from products.tasks.backend.metrics import observe_workflow_task_create-from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.models import Channel, Task, TaskRunfrom products.tasks.backend.temporal.constants import WORKFLOW_RUN_IDLE_TIMEOUT_SECONDSlogger = structlog.get_logger(__name__)@@ -149,6 +149,7 @@ def create_workflow_task(owner_id: int,prompt: str,title: str | None = None,+ channel_ref: str | None = None,repository: str | None = None,model: str | None = None,reasoning_effort: str | None = None,@@ -180,6 +181,10 @@ def create_workflow_task(latest published version at create time; a name that no longer resolves is dropped ratherthan failing the create, for the same reason a Slack context is.+ `channel_ref` names the space the task is filed into, so a workflow built inside a space+ puts its runs in that space's feed. It is dropped rather than failing the create when it+ names no space the owner can see, for the same reason a Slack context is.+`event` is rendered into the agent's prompt as data. The Slack thread binding decidesthe run's lifetime: a thread-bound run stays live until its inactivity timeout, so itsreply posts and thread replies reach the agent, while a run with no binding ends@@ -352,12 +357,20 @@ def create_workflow_task(# repository runs.extra_run_state["end_run_when_done"] = True+ # Resolved here so the row lock it takes is held until the task is inserted.+ # delete_channel takes the same lock, and only detaches the tasks that already+ # exist, so a space deleted between the resolve and the insert would leave the+ # task filed into a deleted space, which no visibility rule matches: invisible+ # even to its owner.+ channel = _resolve_channel(team.id, owner_id, channel_ref)+task = Task.create_and_run(team=team,title=(title or "").strip() or prompt[:255],description=prompt,origin_product=Task.OriginProduct.WORKFLOW,user_id=owner_id,+ channel=channel,repository=repository,mode="background",# A task with no repository has nothing to open a PR from.@@ -403,6 +416,40 @@ def create_workflow_task(return _task_dto(task, created=True)+def _resolve_channel(team_id: int, owner_id: int, channel_ref: str | None) -> Channel | None:+ """The space the task is filed into, or None to file it in no space.++ The reference is the space id, optionally followed by "|" and its name, so a client can+ read the name back without a second step input to keep in step. Only the id is used here.++ Resolved against what the workflow owner can see, because the run executes as the owner:+ a step input naming a private space the owner is not a member of must not place the task+ there. An id that resolves to nothing only costs the placement: a deleted or renamed space+ must not stop the workflow from running.++ Locks the space row for the rest of the caller's transaction, the same lock+ ``delete_channel`` takes, so the space cannot be deleted between this read and the task+ insert. ``no_key`` keeps the task inserts of other creators in the same space, which take+ a key-share lock on this row for the foreign key check, off that wait.+ """+ if not channel_ref:+ return None+ try:+ channel_id = uuid.UUID(channel_ref.split("|")[0].strip())+ except ValueError:+ logger.warning("workflow_task_channel_malformed", team_id=team_id)+ return None+ channel = (+ Channel.objects.for_team(team_id)+ .select_for_update(no_key=True, of=("self",))+ .filter(Channel.visible_to_q(owner_id), id=channel_id)+ .first()+ )+ if channel is None:+ logger.warning("workflow_task_channel_unresolved", team_id=team_id, channel_id=str(channel_id))+ return channel++def _task_dto(task: Task, *, created: bool) -> contracts.WorkflowTaskDTO:run = task.latest_runreturn contracts.WorkflowTaskDTO(task_id=task.id, run_id=run.id if run is not None else None, created=created)diff --git a/products/tasks/backend/tests/test_workflow_tasks_api.py b/products/tasks/backend/tests/test_workflow_tasks_api.pyindex 70065bf495ad..325691e38ea6 100644--- a/products/tasks/backend/tests/test_workflow_tasks_api.py+++ b/products/tasks/backend/tests/test_workflow_tasks_api.py@@ -20,6 +20,7 @@ from posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models.integration import Integrationfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import OrganizationMembership+from posthog.models.scoping import team_scopefrom posthog.models.team.team import Teamfrom posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV@@ -30,7 +31,7 @@ from products.tasks.backend.logic.services.workflow_tasks import (WORKFLOW_TASK_RATE_CAP_PER_DAY,WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY,)-from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.models import Channel, Task, TaskRunfrom products.tasks.backend.visibility import task_control_q, task_visibility_qfrom products.workflows.backend.api.workflow_tasks import WorkflowTaskCreateSerializerfrom products.workflows.backend.models import HogFlow, TeamWorkflowsConfig@@ -127,6 +128,31 @@ class TestWorkflowTasksAPI(APIBaseTest):assert task.mcp_builtin_agent_key == "workflow"assert task.mcp_gateway_server_allowlist == []+ @parameterized.expand(+ [+ ("bare id", Channel.ChannelType.PUBLIC, "{id}", True),+ ("id with the space name after a pipe", Channel.ChannelType.PUBLIC, "{id}|growth", True),+ ("private space the owner is not in", Channel.ChannelType.PRIVATE, "{id}", False),+ ("space that does not exist", None, "0198c9f1-bbbb-0000-0000-000000000001", False),+ ("not an id at all", None, "growth", False),+ ]+ )+ def test_files_the_task_in_the_named_space_only_when_the_owner_can_see_it(+ self, _name: str, channel_type: str | None, reference: str, expect_filed: bool+ ) -> None:+ with team_scope(self.team.id):+ channel = (+ Channel.objects.create(team=self.team, name="growth", channel_type=channel_type)+ if channel_type is not None+ else None+ )++ response = self._post({"channel": reference.format(id=channel.id) if channel else reference})++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ task = Task.objects.get(id=response.json()["id"])+ assert task.channel_id == (channel.id if channel and expect_filed else None)+@parameterized.expand([("codex", "gpt-5.6-terra", "codex", "openai"),diff --git a/products/workflows/backend/api/workflow_tasks.py b/products/workflows/backend/api/workflow_tasks.pyindex 49343e43bc8f..cd596fadeb21 100644--- a/products/workflows/backend/api/workflow_tasks.py+++ b/products/workflows/backend/api/workflow_tasks.py@@ -98,6 +98,16 @@ class WorkflowTaskCreateSerializer(serializers.Serializer):allow_blank=True,help_text="GitHub repository as organization/repo. Omit for a task with no code access.",)+ channel = serializers.CharField(+ max_length=200,+ required=False,+ allow_blank=True,+ help_text=(+ "Space the task is filed into, as its id, optionally followed by '|' and the space name. "+ "A space the workflow owner cannot see, or one that no longer exists, files the task in no space "+ "rather than failing the create."+ ),+ )model = serializers.CharField(max_length=128, required=False, allow_blank=True, help_text="Model ID from the task model catalogue.")@@ -225,6 +235,7 @@ class WorkflowTaskViewSet(viewsets.GenericViewSet):owner_id=owner_id,prompt=data["prompt"].strip(),title=data.get("title"),+ channel_ref=data.get("channel") or None,repository=data.get("repository") or None,model=data.get("model") or None,reasoning_effort=data.get("reasoning_effort") or None,