:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): add private-by-invitation spaces (backend) (#95752)
Shy Altera8553147831b
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex cfe3dbeb62a0..46f455b34476 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -102,6 +102,7 @@ rules:|ChangeRequest|ChannelContextGeneration|ChannelInstructions+ |ChannelMembership|ChannelStar|ClusteringConfig|ClusteringJob@@ -506,6 +507,7 @@ rules:|ChangeRequest|ChannelContextGeneration|ChannelInstructions+ |ChannelMembership|ChannelStar|ClusteringConfig|ClusteringJobdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 181e1707800e..b7be0d7e3a9f 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -657,6 +657,8 @@ SPECTACULAR_SETTINGS = {# The choices are computed: a subset or union of another definition, a plain# Python enum's values, or a per-widget constant. Converting each producer to# a TextChoices class would delete its entry here.+ "TaskChannelWriteTypeEnum": "products.tasks.backend.facade.enums.CHANNEL_WRITE_TYPE_CHOICES",+ "ChannelTypeEnum": "products.error_tracking.backend.facade.alerts.ALERT_CHANNEL_TYPES","TicketChannelFilterEnum": "products.conversations.backend.api.ticket_filters.TICKET_CHANNEL_FILTER_CHOICES","TicketSlaFilterEnum": "products.conversations.backend.api.ticket_filters.TICKET_SLA_FILTER_CHOICES","TicketSortOrderEnum": "products.conversations.backend.api.ticket_filters.TICKET_SORT_ORDER_CHOICES",diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 2040344582d7..10cb28e6d666 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -1,20 +1,3 @@-"""-Facade API for the tasks product — the data surface other apps may import.--Responsibilities:-- Accept ids / DTOs as input.-- Call into the product's models and logic.-- Convert Django models to DTOs before returning — never return ORM instances.-- Stay thin and stable.--This module is deliberately light: it imports the models and small helpers only. The-heavy behavioral surfaces (sandbox provisioning, warming, the multi-turn agent machinery,-temporal workflows, max tools) live in sibling facade submodules (``sandbox``, ``warm``,-``agents``, ``temporal``, ``max_tools``, ``webhooks``, ``streams``, ``repo_selection``) so a-config-only importer never drags docker/temporalio onto the ``django.setup()`` path.-Functions that bridge to those heavy surfaces import them lazily inside the function body.-"""-import reimport timeimport hashlib@@ -111,6 +94,7 @@ from products.tasks.backend.models import (ChannelContextGeneration,ChannelFeedMessage,ChannelInstructions,+ ChannelMembership,ChannelStar,DesktopBetaTermsAcceptance,InvalidTaskOriginError,@@ -6004,34 +5988,6 @@ class TaskHandoffError(Exception):def handoff_task(task_id: str | UUID, team_id: int, user_id: int | None, *, target_user_id: int) -> contracts.TaskDetailDTO | None:- """Hand ``task_id`` off to ``target_user_id``: they become the task's owner.-- Ownership is what `task_control_q` keys on, so the recipient drives the task- afterwards (steer, archive, forward thread messages), and future runs resolve- GitHub authorship and notification recipients from them. Membership in the- project's organization is required — anything weaker would hand control of a- task to someone who can't see the project.-- Visibility follows the recipient when the task lives in a private space: a- task in the actor's ``#me`` (or a legacy channel-less task) moves into the- recipient's ``#me`` so they can open what's now theirs. Public channels stay- put; both sides keep the shared view.-- Only the owner can hand a task off: ``task_control_q`` also grants control- over team-owned origin products, and giving a task away is stricter than- driving it. The recipient must be an org member with access to this project- (``all_users_with_access`` honors private-project access control), otherwise- they'd end up owning a task they can't open.-- Returns the updated task detail, or ``None`` when the actor can't control the- task or no longer owns it. Raises ``TaskHandoffError`` for invalid targets- (not a member with project access, or the current owner).-- All task runs must be terminal and every sandbox session must be closed- before a handoff. The transfer rotates a server-owned ownership version and- revokes task-bound sandbox OAuth tokens, so old runs cannot execute or refresh- credentials under the recipient's identity.- """task = _visible_task_qs(team_id, user_id, for_control=True).filter(id=task_id).first()if task is None:return None@@ -6039,22 +5995,26 @@ def handoff_task(return Noneif task.created_by_id == target_user_id:raise TaskHandoffError("That person already owns this task.")- target = task.team.all_users_with_access().filter(id=target_user_id).first()- if target is None:- raise TaskHandoffError("Tasks can only be handed off to someone with access to this project.")-previous_owner_id = task.created_by_idactor = User.objects.filter(id=user_id).only("first_name", "email", "distinct_id").first() if user_id else Noneactor_name = ((actor.first_name.strip() or actor.email) if actor else None) or "Someone"- target_name = target.first_name.strip() or target.email+ channel = task.channelwith transaction.atomic():+ if channel is not None and channel.channel_type == Channel.ChannelType.PRIVATE:+ if _locked_visible_channel(channel.id, team_id, user_id, no_key=True) is None:+ return Nonelocked = Task.objects.select_for_update().get(pk=task.pk)- # Under the lock: two concurrent handoffs settle last-writer-loses- # instead of double-announcing and rerouting mid-flight.- if locked.deleted:++ if locked.deleted or locked.channel_id != task.channel_id:return Noneif locked.created_by_id != previous_owner_id:raise TaskHandoffError("Someone else has already handed this task off. Refresh and try again.")+ if not Task.objects.filter(id=locked.id).filter(task_control_q(user_id)).exists():+ return None+ target = locked.team.all_users_with_access().filter(id=target_user_id).first()+ if target is None:+ raise TaskHandoffError("Tasks can only be handed off to someone with access to this project.")+ target_name = target.first_name.strip() or target.emailif (TaskRun.objects.filter(task_id=locked.id, team_id=team_id).exclude(status__in=[TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED])@@ -6080,19 +6040,16 @@ def handoff_task(channel = locked.channelif channel is None or channel.channel_type == Channel.ChannelType.PERSONAL:- # Never widen: a task in one private space moves to the other private- # space rather than becoming visible to the whole project, and a legacy- # channel-less task joins the recipient's #me where they'll find it.locked.channel = _ensure_personal_channel(team_id, target.id)[0]+ elif channel.channel_type == Channel.ChannelType.PRIVATE:+ ChannelMembership.objects.for_team(team_id).get_or_create(+ channel_id=channel.id, user_id=target.id, defaults={"team_id": team_id}+ )locked.created_by = target- # The stored GitHub-user preference names the old owner's installation; the- # recipient picks their own on their next run. Carrying it across would- # defer to user-scoped resolution anyway (it keys on created_by), so clear it.+if locked.github_user_integration_id is not None:locked.github_user_integration = None- # A stamped built-in agent task may borrow its credential owner's MCP Store- # grants. Handing ownership off while keeping that borrow would hand the old- # owner's connected accounts to whoever drives the run now, so drop the borrow.+locked.state = {key: value for key, value in (locked.state or {}).items() if key != MCP_CREDENTIAL_OWNER_STATE_KEY}@@ -6107,8 +6064,6 @@ def handoff_task(payload={"from_user_id": previous_owner_id,"to_user_id": target.id,- # Clients render names straight from the payload (ids alone would need a- # member lookup); both are same-org members, so carrying names is safe."from_display_name": actor_name if user_id is not None else None,"to_display_name": target_name,},@@ -6124,8 +6079,7 @@ def handoff_task()notify_task_handoff(locked, recipient=target, actor=actor, message_id=message.id)- # Task.capture_event would attribute to the new owner (it keys on created_by);- # the actor initiated the handoff, so capture under their identity instead.+try:posthoganalytics.capture(distinct_id=str(actor.distinct_id) if actor is not None and actor.distinct_id else str(locked.team.uuid),@@ -7796,10 +7750,11 @@ def provision_default_channels(team_id: int, user_id: int) -> contracts.Provisiodef list_channels(team_id: int, user_id: int | None) -> list[contracts.ChannelDTO]:- """Every space the requester can see, by name. ``starred`` reflects the requester's- stars. Creates nothing, which is what lets a caller gate on a space existing."""channels = list(- _team_channels(team_id).select_related("created_by").filter(Channel.visible_to_q(user_id)).order_by("name")+ _team_channels(team_id)+ .select_related("created_by")+ .filter(Channel.visible_to_q(user_id))+ .order_by("name", "id"))starred_ids: set = (set(ChannelStar.objects.filter(team_id=team_id, user_id=user_id).values_list("channel_id", flat=True))@@ -7870,6 +7825,92 @@ def resolve_channel(team_id: int, user_id: int | None, *, name: str, star: bool)return _channel_to_dto(channel, starred=starred)+def _channel_member_infos(channel: Channel, team_id: int) -> list[contracts.TaskUserBasicInfo]:+ members = (+ ChannelMembership.objects.for_team(team_id)+ .filter(channel_id=channel.id)+ .select_related("user")+ .order_by("created_at")+ )+ return [info for member in members if (info := _user_basic_info(member.user)) is not None]+++def create_private_channel(+ team_id: int, user_id: int, *, name: str, member_ids: list[int], star: bool+) -> contracts.ChannelDTO | None:+ normalized = normalize_channel_name(name)+ if not normalized or is_reserved_channel_name(normalized):+ return None+ team = Team.objects.get(id=team_id)+ accessible = set(team.all_users_with_access().filter(id__in=member_ids).values_list("id", flat=True))+ target_ids = {user_id, *accessible}+ with transaction.atomic():+ channel = Channel.objects.for_team(team_id).create(+ team_id=team_id,+ name=normalized,+ channel_type=Channel.ChannelType.PRIVATE,+ created_by_id=user_id,+ )+ for member_id in target_ids:+ ChannelMembership.objects.for_team(team_id).create(+ team_id=team_id, channel_id=channel.id, user_id=member_id+ )+ _emit_channel_created(channel, user_id)+ starred = False+ if star:+ _set_channel_star(channel.id, team_id, user_id, starred=True)+ starred = True+ return _channel_to_dto(channel, starred=starred)+++def list_channel_members(+ channel_id: str | UUID, team_id: int, user_id: int | None+) -> list[contracts.TaskUserBasicInfo] | None:+ channel = _visible_channel(channel_id, team_id, user_id)+ if channel is None:+ return None+ return _channel_member_infos(channel, team_id)+++def _reset_channel_memberships(channel: Channel, team_id: int, user_id: int | None) -> None:+ memberships = ChannelMembership.objects.for_team(team_id).filter(channel_id=channel.id)+ memberships.delete()+ if channel.channel_type != Channel.ChannelType.PRIVATE:+ return+ seed_ids = {member_id for member_id in (channel.created_by_id, user_id) if member_id is not None}+ for member_id in seed_ids:+ ChannelMembership.objects.for_team(team_id).create(team_id=team_id, channel_id=channel.id, user_id=member_id)+++def set_channel_members(+ channel_id: str | UUID, team_id: int, user_id: int | None, *, member_ids: list[int]+) -> list[contracts.TaskUserBasicInfo] | str:+ with transaction.atomic():+ channel = _locked_visible_channel(channel_id, team_id, user_id)+ if channel is None:+ return "not_found"+ if channel.channel_type != Channel.ChannelType.PRIVATE:+ return "not_private"++ submitted = {*member_ids}+ accessible = set(channel.team.all_users_with_access().filter(id__in=submitted).values_list("id", flat=True))+ if accessible != submitted:+ return "invalid_member"+ target_ids = set(submitted)+ if channel.created_by_id is not None:+ target_ids.add(channel.created_by_id)+ memberships = ChannelMembership.objects.for_team(team_id).filter(channel_id=channel.id)+ existing = set(memberships.values_list("user_id", flat=True))+ for member_id in target_ids - existing:+ ChannelMembership.objects.for_team(team_id).create(+ team_id=team_id, channel_id=channel.id, user_id=member_id+ )+ to_remove = existing - target_ids+ if to_remove:+ memberships.filter(user_id__in=to_remove).delete()+ return _channel_member_infos(channel, team_id)++def update_channel(channel_id: str | UUID,team_id: int,@@ -7880,67 +7921,63 @@ def update_channel(github_integration: Integration | None = None,repositories: list[str] | None = None,auto_archive_after_days: int | None | _AutoArchiveUnchanged = _AUTO_ARCHIVE_UNCHANGED,+ channel_type: str | None = None,) -> contracts.ChannelDTO | str:- """Update a visible channel."""- channel = Channel.objects.filter(id=channel_id, team_id=team_id, deleted=False).first()- if channel is None:- return "not_found"- if channel.channel_type == Channel.ChannelType.PERSONAL:- if channel.created_by_id != user_id:- return "not_found"- if name is not None:- return "personal"- elif not isinstance(auto_archive_after_days, _AutoArchiveUnchanged) and not can_manage_shared_auto_archive:- return "auto_archive_forbidden"- if name is not None and _is_general_channel(channel):- return "general"- update_fields: list[str] = []- if name is not None:- normalized = normalize_channel_name(name)- if not normalized:- return "invalid_name"- channel.name = normalized- update_fields.append("name")- if repositories is not None:- channel.repositories = repositories- channel.github_integration = github_integration if repositories else None- update_fields.extend(["repositories", "github_integration"])- if not isinstance(auto_archive_after_days, _AutoArchiveUnchanged):- channel.auto_archive_after_days = auto_archive_after_days- update_fields.append("auto_archive_after_days")- if not update_fields:- return _channel_to_dto(channel)try:- channel.save(update_fields=[*update_fields, "updated_at"])+ with transaction.atomic():+ channel = _locked_visible_channel(channel_id, team_id, user_id)+ if channel is None:+ return "not_found"+ if channel.channel_type == Channel.ChannelType.PERSONAL:+ if channel.created_by_id != user_id:+ return "not_found"+ if name is not None or channel_type is not None:+ return "personal"+ elif not isinstance(auto_archive_after_days, _AutoArchiveUnchanged) and not can_manage_shared_auto_archive:+ return "auto_archive_forbidden"+ if (name is not None or channel_type is not None) and _is_general_channel(channel):+ return "general"+ update_fields: list[str] = []+ if channel_type is not None and channel_type != channel.channel_type:+ channel.channel_type = channel_type+ update_fields.append("channel_type")+ _reset_channel_memberships(channel, team_id, user_id)+ if name is not None:+ normalized = normalize_channel_name(name)+ if not normalized:+ return "invalid_name"+ channel.name = normalized+ update_fields.append("name")+ if repositories is not None:+ channel.repositories = repositories+ channel.github_integration = github_integration if repositories else None+ update_fields.extend(["repositories", "github_integration"])+ if not isinstance(auto_archive_after_days, _AutoArchiveUnchanged):+ channel.auto_archive_after_days = auto_archive_after_days+ update_fields.append("auto_archive_after_days")+ if not update_fields:+ return _channel_to_dto(channel)+ channel.save(update_fields=[*update_fields, "updated_at"])+ return _channel_to_dto(channel)except IntegrityError:return "name_taken"- return _channel_to_dto(channel)def delete_channel(channel_id: str | UUID, team_id: int, user_id: int | None) -> str:- """Soft-delete an empty public channel. Archived tasks do not count as content."""- channel = Channel.objects.filter(id=channel_id, team_id=team_id, deleted=False).first()- if channel is None:- return "not_found"- if channel.channel_type == Channel.ChannelType.PERSONAL:- return "personal" if channel.created_by_id == user_id else "not_found"- if _is_general_channel(channel):- return "general"with transaction.atomic():- # Emptiness is checked under a row lock because filing a task takes FOR KEY SHARE on- # its channel: unlocked, a task can land after the check and be orphaned in a channel- # this call goes on to delete.- channel = Channel.objects.select_for_update().filter(id=channel_id, team_id=team_id, deleted=False).first()+ channel = _locked_visible_channel(channel_id, team_id, user_id)if channel is None:return "not_found"+ if channel.channel_type == Channel.ChannelType.PERSONAL:+ return "personal" if channel.created_by_id == user_id else "not_found"+ if _is_general_channel(channel):+ return "general"if (channel.tasks.filter(deleted=False, archived=False).exists()or channel.canvases.filter(deleted=False).exists()):return "not_empty"- # Not filtered on `archived`: flipping that flag leaves the FK untouched, so it takes- # no lock on the channel and can happen after the check above. Task visibility joins- # through the channel, so a task left pointing at a deleted one leaves every list.+channel.tasks.filter(deleted=False).update(channel=None)channel.deleted = Truechannel.save(update_fields=["deleted", "updated_at"])@@ -7984,8 +8021,6 @@ def channel_exists(team_id: int, channel_id: str | UUID, user_id: int | None) ->def _visible_channel(channel_id: str | UUID, team_id: int, user_id: int | None) -> Channel | None:- """A channel the requester may read: any live public channel on the team, or their- own personal channel. ``None`` when it's missing or someone else's personal channel."""return (_team_channels(team_id).select_related("created_by")@@ -7994,6 +8029,18 @@ def _visible_channel(channel_id: str | UUID, team_id: int, user_id: int | None))+def _locked_visible_channel(+ channel_id: str | UUID, team_id: int, user_id: int | None, *, no_key: bool = False+) -> Channel | None:++ channel = (+ Channel.objects.for_team(team_id).select_for_update(no_key=no_key).filter(id=channel_id, deleted=False).first()+ )+ if channel is None:+ return None+ return _visible_channel(channel_id, team_id, user_id)++def list_channel_feed_messages(channel_id: str | UUID, team_id: int, user_id: int | None) -> list[contracts.ChannelFeedMessageDTO] | None:@@ -8020,33 +8067,27 @@ def create_channel_feed_message(payload: dict,created_at: datetime | None = None,) -> contracts.ChannelFeedMessageDTO | None | str:- """Post an announcement into a channel's feed as the requester. ``None`` when the- channel isn't visible; ``"full"`` when the channel's feed is at capacity. The row is- marked human-authored — ``system``/``agent`` kinds are reserved for server-side- writers, so a client can't forge rows other clients render as trusted. ``author``- records the acting user so the client can render "Adam …". ``created_at`` lets a- client order a burst of announcements deterministically (else the server stamps- ``now``)."""- if _visible_channel(channel_id, team_id, user_id) is None:- return None- if (- ChannelFeedMessage.objects.filter(channel_id=channel_id, team_id=team_id, deleted=False).count()- >= CHANNEL_FEED_MAX_MESSAGES- ):- return "full"- fields: dict = {- "team_id": team_id,- "channel_id": channel_id,- "author_id": user_id,- "author_kind": ChannelFeedMessage.AuthorKind.HUMAN,- "event": event,- "payload": payload or {},- }- if created_at is not None:- fields["created_at"] = created_at- message = ChannelFeedMessage.objects.create(**fields)- # Fresh row: author lazy-loads once for the DTO.- return _channel_feed_message_to_dto(message)+ with transaction.atomic():+ if _locked_visible_channel(channel_id, team_id, user_id) is None:+ return None+ if (+ ChannelFeedMessage.objects.filter(channel_id=channel_id, team_id=team_id, deleted=False).count()+ >= CHANNEL_FEED_MAX_MESSAGES+ ):+ return "full"+ fields: dict = {+ "team_id": team_id,+ "channel_id": channel_id,+ "author_id": user_id,+ "author_kind": ChannelFeedMessage.AuthorKind.HUMAN,+ "event": event,+ "payload": payload or {},+ }+ if created_at is not None:+ fields["created_at"] = created_at+ message = ChannelFeedMessage.objects.create(**fields)++ return _channel_feed_message_to_dto(message)def get_channel(channel_id: str | UUID, team_id: int, user_id: int | None) -> contracts.ChannelDTO | None:@@ -8207,19 +8248,12 @@ def publish_channel_instructions(content: str,base_version: int | None = None,) -> contracts.ChannelInstructionsDTO | None:- """Publish a new instructions version, superseding the current latest.-- ``base_version`` guards against lost updates: when the current latest no- longer matches, ``ChannelInstructionsVersionConflictError`` is raised.- ``None`` when the channel isn't visible. Publishing clears the channel's- in-progress context-generation marker.- """- channel = _visible_channel(channel_id, team_id, user_id)- if channel is None:- return None- if len(content.encode("utf-8")) > CHANNEL_INSTRUCTIONS_MAX_BYTES:- raise ChannelInstructionsTooLargeError(max_bytes=CHANNEL_INSTRUCTIONS_MAX_BYTES)with transaction.atomic():+ channel = _locked_visible_channel(channel_id, team_id, user_id)+ if channel is None:+ return None+ if len(content.encode("utf-8")) > CHANNEL_INSTRUCTIONS_MAX_BYTES:+ raise ChannelInstructionsTooLargeError(max_bytes=CHANNEL_INSTRUCTIONS_MAX_BYTES)current_latest = (ChannelInstructions.objects.select_for_update().filter(channel_id=channel.id, deleted=False, is_latest=True)@@ -8234,11 +8268,6 @@ def publish_channel_instructions(if current_latest is not None:ChannelInstructions.objects.filter(pk=current_latest.pk).update(is_latest=False)try:- # Nested savepoint: a lost-update race (the select_for_update above- # locks no row when none exists yet, and a concurrent delete clears- # is_latest without adding a lockable row) makes the insert collide- # with the (channel, version) uniqueness. Rolling back to the- # savepoint keeps this transaction usable so we can read the winner.with transaction.atomic():published = ChannelInstructions.objects.create(team_id=team_id,@@ -8249,25 +8278,22 @@ def publish_channel_instructions(created_by_id=user_id,)except IntegrityError:- # Surface the race as the conflict the view maps to 409, not a 500.latest = (ChannelInstructions.objects.filter(channel_id=channel.id, deleted=False).order_by("-version", "-created_at", "-id").first())raise ChannelInstructionsVersionConflictError(current_version=latest.version if latest is not None else 0)- # Publishing produced a result, so drop the in-progress generation marker.+ChannelContextGeneration.objects.filter(channel_id=channel.id).update(task_id=None)return _instructions_to_dto(published)def delete_channel_instructions(channel_id: str | UUID, team_id: int, user_id: int | None) -> int | None:- """Soft-delete every instructions version. Returns the count, or ``None``- when the channel isn't visible."""- channel = _visible_channel(channel_id, team_id, user_id)- if channel is None:- return Nonewith transaction.atomic():+ channel = _locked_visible_channel(channel_id, team_id, user_id)+ if channel is None:+ return Nonecount = (ChannelInstructions.objects.select_for_update().filter(channel_id=channel.id, deleted=False)@@ -8291,25 +8317,25 @@ def get_channel_context_generation(def set_channel_context_generation(channel_id: str | UUID, team_id: int, user_id: int | None, *, task_id: str | UUID | None) -> str | None | Literal["not_found", "invalid_task"]:- """Set or clear the task associated with the channel's CONTEXT.md generation."""- channel = _visible_channel(channel_id, team_id, user_id)- if channel is None:- return "not_found"- if task_id is not None and not task_exists(task_id, team_id):- return "invalid_task"- ChannelContextGeneration.objects.update_or_create(- channel_id=channel.id, defaults={"team_id": team_id, "task_id": task_id}- )- return str(task_id) if task_id else None+ with transaction.atomic():+ channel = _locked_visible_channel(channel_id, team_id, user_id)+ if channel is None:+ return "not_found"+ if task_id is not None and not task_exists(task_id, team_id):+ return "invalid_task"+ ChannelContextGeneration.objects.update_or_create(+ channel_id=channel.id, defaults={"team_id": team_id, "task_id": task_id}+ )+ return str(task_id) if task_id else Nonedef star_channel(channel_id: str | UUID, team_id: int, user_id: int, *, starred: bool) -> bool:- """Star or unstar a channel for the requesting user. False when the channel isn't visible."""- channel = _visible_channel(channel_id, team_id, user_id)- if channel is None:- return False- _set_channel_star(channel.id, team_id, user_id, starred=starred)- return True+ with transaction.atomic():+ channel = _locked_visible_channel(channel_id, team_id, user_id)+ if channel is None:+ return False+ _set_channel_star(channel.id, team_id, user_id, starred=starred)+ return Truedef _thread_message_to_dto(message: TaskThreadMessage) -> contracts.TaskThreadMessageDTO:diff --git a/products/tasks/backend/facade/enums.py b/products/tasks/backend/facade/enums.pynew file mode 100644index 000000000000..1fe634edbb2d--- /dev/null+++ b/products/tasks/backend/facade/enums.py@@ -0,0 +1 @@+CHANNEL_WRITE_TYPE_CHOICES: list[str] = ["public", "private"]diff --git a/products/tasks/backend/migrations/0118_alter_channel_channel_type_channelmembership.py b/products/tasks/backend/migrations/0118_alter_channel_channel_type_channelmembership.pynew file mode 100644index 000000000000..f76d54aab517--- /dev/null+++ b/products/tasks/backend/migrations/0118_alter_channel_channel_type_channelmembership.py@@ -0,0 +1,80 @@+import uuid++import django.utils.timezone+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1342_drop_cimd_blocklist_table"),+ ("tasks", "0117_task_set_null_cascade_indexes"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AlterField(+ model_name="channel",+ name="channel_type",+ field=models.CharField(+ choices=[+ ("public", "Public"),+ ("personal", "Personal"),+ ("private", "Private"),+ ],+ default="public",+ max_length=16,+ ),+ ),+ migrations.CreateModel(+ name="ChannelMembership",+ fields=[+ (+ "id",+ models.UUIDField(+ default=uuid.uuid4,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),+ (+ "channel",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="memberships",+ to="tasks.channel",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "user",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ],+ options={+ "db_table": "posthog_task_channel_membership",+ "constraints": [+ models.UniqueConstraint(+ fields=("channel", "user"),+ name="task_channel_membership_unique",+ )+ ],+ },+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex 3f19dbad8fb8..855a38050daf 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0117_task_set_null_cascade_indexes+0118_alter_channel_channel_type_channelmembershipdiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 944537ba236f..9646342f28c4 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -169,15 +169,10 @@ class InvalidTaskOriginError(ValueError):class Channel(TeamScopedRootMixin):- """A shared feed of tasks (rendered as "#<name>" in PostHog Desktop). Every task is- owned by the channel it was kicked off in. Each user gets one private "personal"- channel ("#me") per team, and each team gets a public "general" channel, Slack-style.- Listing creates neither; provisioning does. The general channel can't be renamed or- deleted."""-class ChannelType(models.TextChoices):PUBLIC = "public", "Public"PERSONAL = "personal", "Personal"+ PRIVATE = "private", "Private"class SystemRole(models.TextChoices):"""Identifies a channel as one of the two system-provisioned spaces, independent@@ -193,10 +188,6 @@ class Channel(TeamScopedRootMixin):@classmethoddef visible_to_q(cls, user_id: int | None, *, relation: Literal["", "channel", "task__channel"] = "") -> models.Q:- """The channel-visibility rule as a queryset filter: a personal channel is- visible only to its creator. ``relation`` names the join to ``Channel`` when- filtering another model's queryset (e.g. ``"channel"``); empty filters- ``Channel`` rows directly."""prefix = {"": "", "channel": "channel__", "task__channel": "task__channel__"}[relation]visible_q = models.Q(**{f"{prefix}channel_type": cls.ChannelType.PUBLIC})if user_id is not None:@@ -206,6 +197,12 @@ class Channel(TeamScopedRootMixin):f"{prefix}created_by_id": user_id,})+ visible_q |= models.Q(+ **{+ f"{prefix}channel_type": cls.ChannelType.PRIVATE,+ f"{prefix}memberships__user_id": user_id,+ }+ )return models.Q(**{f"{prefix}deleted": False}) & visible_q# nosemgrep: prefer-uuid7-django-pk -- mirrors sibling task models in this app@@ -267,6 +264,22 @@ class Channel(TeamScopedRootMixin):return f"#{self.name}"+class ChannelMembership(TeamScopedRootMixin):+ # nosemgrep: prefer-uuid7-django-pk -- UUIDv4 matches existing task models.+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)+ channel = models.ForeignKey("tasks.Channel", on_delete=models.CASCADE, related_name="memberships")+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)+ created_at = models.DateTimeField(default=django_timezone.now)++ class Meta:+ db_table = "posthog_task_channel_membership"+ constraints = [+ models.UniqueConstraint(fields=["channel", "user"], name="task_channel_membership_unique"),+ ]++@receiver(pre_delete, sender=Integration)def clear_channel_repositories_on_github_integration_delete(sender: type[Integration], instance: Integration, **kwargs: Anydiff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 40828e8ac65a..d6b290e5abd6 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -42,6 +42,7 @@ from products.tasks.backend.facade.contracts import (TaskUserBasicInfo,WizardCloudRunDTO,)+from products.tasks.backend.facade.enums import CHANNEL_WRITE_TYPE_CHOICESfrom products.tasks.backend.facade.model_catalogue import ModelChoicefrom products.tasks.backend.facade.run_config import (ALL_INITIAL_PERMISSION_MODE_CHOICES,@@ -584,13 +585,6 @@ class TaskSerializer(DataclassSerializer):class TaskWriteSerializer(serializers.Serializer):- """Request body for creating or updating a task.-- Field required/default semantics match the ``Task`` model. The view passes- ``validated_data`` (integration/report PK fields already resolved to instances) to the- facade ``create_task`` / ``update_task`` functions.- """-title = serializers.CharField(max_length=255,required=False,@@ -792,10 +786,18 @@ class TaskWriteSerializer(serializers.Serializer):def validate_channel(self, value):request = self.context.get("request")user = getattr(request, "user", None)- if value is not None and (value.deleted or value.channel_type not in {"public", "personal"}):+ user_id = getattr(user, "id", None)+ if value is None:+ return value+ if value.deleted or value.channel_type not in {"public", "personal", "private"}:raise serializers.ValidationError("Space not found")- if value is not None and value.channel_type == "personal" and value.created_by_id != getattr(user, "id", None):+ if value.channel_type == "personal" and value.created_by_id != user_id:raise serializers.ValidationError("Private spaces can only be used by their owner")++ if value.channel_type == "private" and not tasks_facade.channel_exists(+ self.context["team"].id, value.id, user_id+ ):+ raise serializers.ValidationError("Space not found")return valuedef validate_github_integration(self, value):@@ -2173,29 +2175,56 @@ class ChannelDeleteConflictSerializer(serializers.Serializer):detail = serializers.CharField(help_text="Why the space cannot be deleted.")-class ChannelWriteSerializer(serializers.Serializer):- """Request body for creating (resolve-or-create) or renaming a public channel."""+CHANNEL_MEMBERS_MAX = 100++class ChannelWriteSerializer(serializers.Serializer):name = serializers.CharField(- max_length=128, help_text="Channel name, rendered as #<name>. Normalized to lowercase-dashed."+ max_length=128, help_text="Channel name, shown as #<name>. Uses lowercase letters and hyphens.")- star = serializers.BooleanField(+ channel_type = serializers.ChoiceField(+ choices=CHANNEL_WRITE_TYPE_CHOICES,+ default="public",+ help_text=(+ "Use 'public' for access by all project members. Use 'private' for access by channel members only. "+ "Defaults to 'public'. This endpoint cannot create personal #me spaces."+ ),+ )+ member_ids = serializers.ListField(+ child=serializers.IntegerField(),required=False,- default=True,+ default=list,+ max_length=CHANNEL_MEMBERS_MAX,help_text=(- "Star the channel for the requester when this call creates it. "- "Ignored when the channel already exists, which leaves existing stars untouched."+ "User IDs to add to a private channel. The requester is always a member. "+ "The endpoint ignores this field for public channels and skips users without project access."),)+ star = serializers.BooleanField(+ required=False,+ default=True,+ help_text=("Star a new channel for the requester. This field does not change stars on an existing channel."),+ )def validate_name(self, value: str) -> str:- # "general" resolves the team's general space here, so only the personal names are- # refused.if tasks_facade.is_personal_space_name(value):raise serializers.ValidationError("That name is reserved for private spaces. Pick another name.")return value+class ChannelMembersWriteSerializer(serializers.Serializer):+ user_ids = serializers.ListField(+ child=serializers.IntegerField(),+ allow_empty=True,+ max_length=CHANNEL_MEMBERS_MAX,+ help_text=(+ "Required list of member user IDs. This list replaces the current members. "+ "The creator remains a member. Send an empty list to remove all other members. "+ "Each submitted user must have project access."+ ),+ )++class ChannelUpdateSerializer(serializers.Serializer):name = serializers.CharField(max_length=128,@@ -2221,6 +2250,14 @@ class ChannelUpdateSerializer(serializers.Serializer):max_value=365,help_text="Days of inactivity before tasks in this channel are archived. Accepts 1 through 365. Null disables automatic archiving.",)+ channel_type = serializers.ChoiceField(+ choices=CHANNEL_WRITE_TYPE_CHOICES,+ required=False,+ help_text=(+ "Switch a shared space between 'public' and 'private'. Making a space private keeps only the creator "+ "and the requester as members. Making it public removes its member list. Personal #me spaces cannot change."+ ),+ )def validate_name(self, value: str) -> str:if tasks_facade.is_reserved_channel_name(value):diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.pyindex 8e832f1a9cf4..66885cdb05bf 100644--- a/products/tasks/backend/presentation/views/channels_api.py+++ b/products/tasks/backend/presentation/views/channels_api.py@@ -35,6 +35,7 @@ from products.tasks.backend.presentation.serializers import (ChannelFeedMessageWriteSerializer,ChannelInstructionsSerializer,ChannelInstructionsWriteSerializer,+ ChannelMembersWriteSerializer,ChannelSerializer,ChannelStarWriteSerializer,ChannelUpdateSerializer,@@ -53,6 +54,7 @@ from products.tasks.backend.presentation.serializers import (TaskRunErrorResponseSerializer,TaskThreadMessageSerializer,TaskThreadMessageWriteSerializer,+ TaskUserBasicInfoSerializer,TeachingCanvasSerializer,)@@ -81,13 +83,6 @@ PUBLISH_INSTRUCTIONS_SCHEMA_KWARGS: dict[str, Any] = {class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):- """- API for task channels — the shared feeds tasks are kicked off in. The- provision_defaults action get-or-creates the requester's personal "#me" channel and- the team's shared "#general" channel; creation is resolve-or-create by normalized- name so clients can map channel-like surfaces onto backend channels.- """-authentication_classes = [SessionAuthentication,PersonalAPIKeyAuthentication,@@ -99,9 +94,17 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# GET /instructions/ and /context_generation/ are reads; the PUT/PATCH/DELETE# method mappings resolve to their own action names, so they go in the write# bucket by name.- scope_object_read_actions = ["list", "retrieve", "instructions", "instructions_versions", "context_generation"]+ scope_object_read_actions = [+ "list",+ "retrieve",+ "instructions",+ "instructions_versions",+ "context_generation",+ "members",+ ]scope_object_write_actions = ["create",+ "set_members","provision_defaults","onboarding_session","onboarding_session_test",@@ -129,10 +132,11 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):responses={200: OpenApiResponse(response=ChannelSerializer(many=True), description="List of channels")},summary="List channels",description=(- "All live public channels plus the requester's personal #me channel when it exists, "- "sorted by name. Listing does not provision; call provision_defaults to create the "- "default channels. Send `limit` (with `offset`) for one page and a `count`/`next` "- "envelope; without `limit` the response is the full array of channels."+ "List channels the requester can access, sorted by name and ID. "+ "Includes public channels, their personal #me channel, and private channels they belong to. "+ "Call provision_defaults to create missing default channels. "+ "Send limit and offset to get a page with count, next, previous, and results. "+ "Without limit, the response is an array of all accessible channels."),)def list(self, request, *args, **kwargs):@@ -233,23 +237,33 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(request=ChannelWriteSerializer,responses={200: ChannelSerializer},- summary="Resolve or create a public channel",+ summary="Create a channel",description=(- "Returns the existing public channel with the (normalized) name, creating it if needed. "- "A channel created here is starred for the requester unless star is false. "- "The general name returns the team's general space; names that read as a private "- 'space ("me", "personal") are rejected.'+ "Create a channel. Public channels use lowercase names with hyphens. "+ "If a public channel has that name, return it. The name general returns the project's general space. "+ "Private channels always get a new ID, even if another channel has the same name. "+ "The requester and users in member_ids with project access become members. "+ "New channels are starred for the requester unless star is false. "+ 'The names "me" and "personal" are reserved.'),)def create(self, request, **kwargs):serializer = ChannelWriteSerializer(data=request.data)serializer.is_valid(raise_exception=True)- channel = tasks_facade.resolve_channel(- self.team_id,- self._user_id(),- name=serializer.validated_data["name"],- star=serializer.validated_data["star"],- )+ data = serializer.validated_data+ user_id = self._user_id()+ if data["channel_type"] == "private":+ if user_id is None:+ raise PermissionDenied("Creating a private space requires a user.")+ channel = tasks_facade.create_private_channel(+ self.team_id,+ user_id,+ name=data["name"],+ member_ids=data["member_ids"],+ star=data["star"],+ )+ else:+ channel = tasks_facade.resolve_channel(self.team_id, user_id, name=data["name"], star=data["star"])if channel is None:return Response({"detail": "Invalid channel name"}, status=status.HTTP_400_BAD_REQUEST)return Response(ChannelSerializer(channel).data)@@ -257,7 +271,7 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(request=ChannelUpdateSerializer,responses={200: ChannelSerializer},- summary="Rename a public channel",+ summary="Update a channel",)def partial_update(self, request, pk=None, **kwargs):serializer = ChannelUpdateSerializer(data=request.data, context={"team_id": self.team_id}, partial=True)@@ -297,7 +311,7 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):description="The space still contains tasks or canvases.",),},- summary="Delete a public channel",+ summary="Delete a channel",)def destroy(self, request, pk=None, **kwargs):result = tasks_facade.delete_channel(pk, self.team_id, self._user_id())@@ -449,6 +463,51 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise NotFound("Channel not found")return Response(status=status.HTTP_204_NO_CONTENT)+ @extend_schema(+ responses={+ 200: OpenApiResponse(response=TaskUserBasicInfoSerializer(many=True), description="Channel members")+ },+ summary="List a channel's members",+ description=(+ "List the members of a private channel. Return an empty list for public and personal channels. "+ "Return 404 if the requester cannot access the channel."+ ),+ )+ @action(methods=["GET"], detail=True, pagination_class=None)+ def members(self, request, pk=None, **kwargs):+ members = tasks_facade.list_channel_members(pk, self.team_id, self._user_id())+ if members is None:+ raise NotFound("Channel not found")+ return Response(TaskUserBasicInfoSerializer(members, many=True).data)++ @extend_schema(+ request=ChannelMembersWriteSerializer,+ responses={+ 200: OpenApiResponse(response=TaskUserBasicInfoSerializer(many=True), description="Updated members")+ },+ summary="Replace a private channel's members",+ description=(+ "Replace the members of a private channel. Any member can update this list. "+ "The creator remains a member. Return 400 for public and personal channels."+ ),+ )+ @members.mapping.put+ def set_members(self, request, pk=None, **kwargs):+ serializer = ChannelMembersWriteSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ result = tasks_facade.set_channel_members(+ pk, self.team_id, self._user_id(), member_ids=serializer.validated_data["user_ids"]+ )+ if isinstance(result, str):+ if result == "not_found":+ raise NotFound()+ if result == "not_private":+ return Response({"detail": "Only private spaces have members."}, status=status.HTTP_400_BAD_REQUEST)+ return Response(+ {"detail": "Every member must have access to this project."}, status=status.HTTP_400_BAD_REQUEST+ )+ return Response(TaskUserBasicInfoSerializer(result, many=True).data)+class ChannelFeedMessageViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex c9980a1b9960..f010635bee87 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -78,6 +78,7 @@ from products.tasks.backend.models import (TASK_OWNERSHIP_VERSION_STATE_KEY,AgentPeerMessage,Channel,+ ChannelMembership,SandboxCustomImage,SandboxEnvironment,SandboxSession,@@ -10182,6 +10183,32 @@ class TestTaskHandoffAPI(BaseTaskAPITest):for client in (self.client, recipient_client):self.assertEqual(client.get(f"/api/projects/@current/tasks/{task.id}/").status_code, status.HTTP_200_OK)+ def test_handoff_adds_recipient_to_a_private_space(self):+ recipient = self.create_organization_user("recipient")+ private = tasks_facade.create_private_channel(+ self.team.id, self.user.id, name="squad", member_ids=[], star=False+ )+ assert private is not None+ with team_scope(self.team.id):+ channel = Channel.objects.get(id=private.id)+ task = self.create_task(created_by=self.user)+ task.channel = channel+ task.save()++ response = self.client.post(self._handoff_url(task), {"user": recipient.id}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ task.refresh_from_db()+ self.assertEqual(task.channel_id, channel.id)+ self.assertTrue(+ ChannelMembership.objects.unscoped().filter(channel_id=channel.id, user_id=recipient.id).exists()+ )++ recipient_client = APIClient()+ recipient_client.force_authenticate(recipient)+ for client in (self.client, recipient_client):+ self.assertEqual(client.get(f"/api/projects/@current/tasks/{task.id}/").status_code, status.HTTP_200_OK)+def test_handoff_requires_control_of_the_task(self):colleague = self.create_organization_user("colleague")with team_scope(self.team.id):diff --git a/products/tasks/backend/tests/test_channel_membership_concurrency.py b/products/tasks/backend/tests/test_channel_membership_concurrency.pynew file mode 100644index 000000000000..b61afdd3e0cf--- /dev/null+++ b/products/tasks/backend/tests/test_channel_membership_concurrency.py@@ -0,0 +1,166 @@+from collections.abc import Callable+from concurrent.futures import ThreadPoolExecutor+from functools import partial+from queue import Queue+from time import monotonic+from uuid import UUID++from posthog.test.base import NonAtomicBaseTest++from django.db import close_old_connections, connection, transaction++from posthog.models import Team, User+from posthog.models.scoping import team_scope++from products.tasks.backend.facade import api as facade+from products.tasks.backend.models import (+ Channel,+ ChannelContextGeneration,+ ChannelFeedMessage,+ ChannelInstructions,+ ChannelMembership,+ ChannelStar,+ Task,+ TaskThreadMessage,+)+++class TestChannelMembershipConcurrency(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def test_pending_writes_recheck_membership_after_revocation(self) -> None:+ team = self.team+ owner = self.user+ member = User.objects.create(email="[email protected]")+ self.organization.members.add(member)+ for operation, expected in [+ ("update", "not_found"),+ ("delete", "not_found"),+ ("members", "not_found"),+ ("feed", None),+ ("publish_instructions", None),+ ("delete_instructions", None),+ ("context_generation", "not_found"),+ ("star", False),+ ("handoff", None),+ ("handoff_after_move", None),+ ]:+ with self.subTest(operation=operation):+ self._assert_pending_write_rejected(team, owner, member, operation, expected)++ def _assert_pending_write_rejected(+ self, team: Team, owner: User, member: User, operation: str, expected: str | bool | None+ ) -> None:+ with team_scope(team.id):+ channel = facade.create_private_channel(team.id, owner.id, name="squad", member_ids=[member.id], star=False)+ assert channel is not None+ facade.publish_channel_instructions(channel.id, team.id, owner.id, content="Original instructions")++ mutations: dict[str, Callable[[str | UUID, int, int], object]] = {+ "update": partial(facade.update_channel, name="renamed", can_manage_shared_auto_archive=True),+ "delete": facade.delete_channel,+ "members": partial(facade.set_channel_members, member_ids=[member.id]),+ "feed": partial(facade.create_channel_feed_message, event="task_created", payload={}),+ "publish_instructions": partial(facade.publish_channel_instructions, content="Overwritten"),+ "delete_instructions": facade.delete_channel_instructions,+ "context_generation": partial(facade.set_channel_context_generation, task_id=None),+ "star": partial(facade.star_channel, starred=True),+ }+ task = None+ recipient = None+ resource_id = channel.id+ if operation in ("handoff", "handoff_after_move"):+ recipient = User.objects.create(email=f"recipient-{operation}@example.com")+ self.organization.members.add(recipient)+ task = Task.objects.create(+ team=team,+ channel_id=channel.id,+ created_by=member,+ title="Transfer task",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ resource_id = task.id+ mutations[operation] = partial(facade.handoff_task, target_user_id=recipient.id)++ def revoke() -> None:+ if operation == "handoff_after_move":+ assert task is not None+ Task.objects.filter(id=task.id, team_id=team.id).update(channel=None)+ return+ result = facade.set_channel_members(channel.id, team.id, owner.id, member_ids=[])+ self.assertIsInstance(result, list)++ result = self._run_pending_write(+ channel.id, team.id, partial(mutations[operation], resource_id, team.id, member.id), revoke+ )+ self.assertEqual(result, expected)+ if task is not None and recipient is not None:+ task.refresh_from_db()+ self.assertEqual(task.created_by_id, member.id)+ self.assertEqual(task.channel_id, None if operation == "handoff_after_move" else channel.id)+ self.assertFalse(+ ChannelMembership.objects.for_team(team.id).filter(channel_id=channel.id, user_id=recipient.id).exists()+ )+ self.assertFalse(TaskThreadMessage.objects.for_team(team.id).filter(task_id=task.id).exists())++ with team_scope(team.id):+ persisted = Channel.objects.get(id=channel.id)+ self.assertEqual(persisted.name, "squad")+ self.assertFalse(persisted.deleted)+ self.assertEqual(ChannelFeedMessage.objects.filter(channel_id=channel.id).count(), 1)+ self.assertFalse(ChannelContextGeneration.objects.filter(channel_id=channel.id).exists())+ self.assertFalse(ChannelStar.objects.filter(channel_id=channel.id).exists())+ instructions = ChannelInstructions.objects.get(channel_id=channel.id)+ self.assertEqual(instructions.content, "Original instructions")+ self.assertFalse(instructions.deleted)++ def test_pending_membership_replacement_revalidates_project_access(self) -> None:+ candidate = User.objects.create(email="[email protected]")+ self.organization.members.add(candidate)+ with team_scope(self.team.id):+ channel = facade.create_private_channel(self.team.id, self.user.id, name="squad", member_ids=[], star=False)+ assert channel is not None+ result = self._run_pending_write(+ channel.id,+ self.team.id,+ partial(facade.set_channel_members, channel.id, self.team.id, self.user.id, member_ids=[candidate.id]),+ partial(self.organization.members.remove, candidate),+ )+ self.assertEqual(result, "invalid_member")+ self.assertFalse(+ ChannelMembership.objects.for_team(self.team.id)+ .filter(channel_id=channel.id, user_id=candidate.id)+ .exists()+ )++ def _run_pending_write(+ self, channel_id: UUID, team_id: int, mutation: Callable[[], object], change: Callable[[], None]+ ) -> object:+ backend_pid: Queue[int] = Queue()++ def write() -> object:+ close_old_connections()+ try:+ with connection.cursor() as cursor:+ cursor.execute("SET statement_timeout = '10s'")+ cursor.execute("SELECT pg_backend_pid()")+ backend_pid.put(cursor.fetchone()[0])+ with team_scope(team_id):+ return mutation()+ finally:+ close_old_connections()++ with ThreadPoolExecutor(max_workers=1) as executor:+ with transaction.atomic(), team_scope(team_id):+ Channel.objects.for_team(team_id).select_for_update().get(id=channel_id)+ pending = executor.submit(write)+ pid = backend_pid.get(timeout=10)+ deadline = monotonic() + 10+ with connection.cursor() as cursor:+ while not pending.done():+ cursor.execute("SELECT cardinality(pg_blocking_pids(%s)) > 0", [pid])+ if cursor.fetchone()[0]:+ break+ self.assertLess(monotonic(), deadline, "write did not reach the locked channel")+ change()+ return pending.result(timeout=10)diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.pyindex a8eac7708147..1f6ec1df7de5 100644--- a/products/tasks/backend/tests/test_channels_api.py+++ b/products/tasks/backend/tests/test_channels_api.py@@ -17,7 +17,15 @@ from posthog.models.utils import generate_random_token_personalfrom products.tasks.backend.exceptions import ComputeBillingLimitErrorfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.onboarding_canvas import TeachingCanvas-from products.tasks.backend.models import Channel, ChannelFeedMessage, Task, TaskActivity, TaskRun, TaskThreadMessage+from products.tasks.backend.models import (+ Channel,+ ChannelFeedMessage,+ ChannelMembership,+ Task,+ TaskActivity,+ TaskRun,+ TaskThreadMessage,+)from products.tasks.backend.push_dispatcher import (notify_task_run_awaiting_input,notify_task_run_completed,@@ -138,6 +146,8 @@ class ChannelsAPITestCase(TestCase):personal = Channel.objects.unscoped().get(team=self.team, channel_type=Channel.ChannelType.PERSONAL)rename = self.client.patch(f"{self._channels_url()}{personal.id}/", {"name": "not-me"})self.assertEqual(rename.status_code, status.HTTP_403_FORBIDDEN)+ open_up = self.client.patch(f"{self._channels_url()}{personal.id}/", {"channel_type": "public"})+ self.assertEqual(open_up.status_code, status.HTTP_403_FORBIDDEN)delete = self.client.delete(f"{self._channels_url()}{personal.id}/")self.assertEqual(delete.status_code, status.HTTP_403_FORBIDDEN)@@ -362,6 +372,190 @@ class ChannelsAPITestCase(TestCase):listed = other_client.get(self._tasks_url(), {"channel": channel_id}).json()["results"]self.assertEqual([t["id"] for t in listed], [created.json()["id"]])+ def _create_private_channel(self, name: str = "squad", member_ids: list[int] | None = None, client=None) -> dict:+ response = (client or self.client).post(+ self._channels_url(),+ {"name": name, "channel_type": "private", "member_ids": member_ids or []},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.content+ return response.json()++ def _third_member_client(self) -> APIClient:+ third = User.objects.create_user(email="[email protected]", first_name="Cy", password="password")+ self.organization.members.add(third)+ client = APIClient()+ client.force_authenticate(third)+ return client++ def test_private_channel_is_visible_only_to_members(self):+ created = self._create_private_channel()+ channel_id = created["id"]+ self.assertEqual(created["channel_type"], "private")++ self.assertIn(channel_id, [c["id"] for c in self.client.get(self._channels_url()).json()])+ self.assertEqual(self.client.get(f"{self._channels_url()}{channel_id}/").status_code, status.HTTP_200_OK)++ other_client = APIClient()+ other_client.force_authenticate(self.other_user)+ self.assertNotIn(channel_id, [c["id"] for c in other_client.get(self._channels_url()).json()])+ self.assertEqual(+ other_client.get(f"{self._channels_url()}{channel_id}/").status_code, status.HTTP_404_NOT_FOUND+ )++ def test_creating_a_private_channel_seeds_memberships_including_creator(self):+ created = self._create_private_channel(member_ids=[self.other_user.id])+ members = {m["id"] for m in self.client.get(f"{self._channels_url()}{created['id']}/members/").json()}+ self.assertEqual(members, {self.user.id, self.other_user.id})++ def test_task_in_a_private_channel_inherits_its_visibility(self):+ channel_id = self._create_private_channel()["id"]+ created = self.client.post(+ self._tasks_url(),+ {"title": "Secret", "description": "d", "channel": channel_id},+ )+ self.assertEqual(created.status_code, status.HTTP_201_CREATED, created.content)+ task_id = created.json()["id"]++ other_client = APIClient()+ other_client.force_authenticate(self.other_user)+ self.assertEqual(other_client.get(f"{self._tasks_url()}{task_id}/").status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(other_client.get(self._tasks_url(), {"channel": channel_id}).json()["results"], [])++ def test_a_non_member_cannot_create_a_task_in_a_private_channel(self):+ channel_id = self._create_private_channel()["id"]+ other_client = APIClient()+ other_client.force_authenticate(self.other_user)+ response = other_client.post(+ self._tasks_url(),+ {"title": "Sneak in", "description": "d", "channel": channel_id},+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)++ def test_setting_members_adds_and_removes_but_keeps_the_creator(self):+ channel_id = self._create_private_channel(member_ids=[self.other_user.id])["id"]+ members_url = f"{self._channels_url()}{channel_id}/members/"++ response = self.client.put(members_url, {"user_ids": []}, format="json")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual({m["id"] for m in response.json()}, {self.user.id})++ other_client = APIClient()+ other_client.force_authenticate(self.other_user)+ self.assertEqual(+ other_client.get(f"{self._channels_url()}{channel_id}/").status_code, status.HTTP_404_NOT_FOUND+ )++ response = self.client.put(members_url, {"user_ids": [self.other_user.id]}, format="json")+ self.assertEqual({m["id"] for m in response.json()}, {self.user.id, self.other_user.id})++ def test_making_a_private_channel_public_opens_it_and_drops_its_members(self):+ channel_id = self._create_private_channel(member_ids=[self.other_user.id])["id"]++ response = self.client.patch(f"{self._channels_url()}{channel_id}/", {"channel_type": "public"})+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(response.json()["channel_type"], "public")+ self.assertFalse(ChannelMembership.objects.unscoped().filter(channel_id=channel_id).exists())++ third_client = self._third_member_client()+ self.assertIn(channel_id, [c["id"] for c in third_client.get(self._channels_url()).json()])++ def test_making_a_public_channel_private_keeps_only_the_requester_and_creator(self):+ channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]+ other_client = APIClient()+ other_client.force_authenticate(self.other_user)++ response = other_client.patch(f"{self._channels_url()}{channel_id}/", {"channel_type": "private"})+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(response.json()["channel_type"], "private")+ members = {m["id"] for m in other_client.get(f"{self._channels_url()}{channel_id}/members/").json()}+ self.assertEqual(members, {self.user.id, self.other_user.id})++ third_client = self._third_member_client()+ self.assertNotIn(channel_id, [c["id"] for c in third_client.get(self._channels_url()).json()])++ def test_making_a_private_channel_public_rejects_a_taken_name(self):+ self.client.post(self._channels_url(), {"name": "squad"})+ channel_id = self._create_private_channel(name="squad")["id"]++ response = self.client.patch(f"{self._channels_url()}{channel_id}/", {"channel_type": "public"})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)+ self.assertEqual(self.client.get(f"{self._channels_url()}{channel_id}/").json()["channel_type"], "private")++ def test_setting_members_rejects_a_public_channel(self):+ channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]+ response = self.client.put(f"{self._channels_url()}{channel_id}/members/", {"user_ids": []}, format="json")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)++ def test_a_non_member_cannot_reach_the_members_endpoints(self):+ channel_id = self._create_private_channel()["id"]+ other_client = APIClient()+ other_client.force_authenticate(self.other_user)+ members_url = f"{self._channels_url()}{channel_id}/members/"+ self.assertEqual(other_client.get(members_url).status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(+ other_client.put(members_url, {"user_ids": [self.other_user.id]}, format="json").status_code,+ status.HTTP_404_NOT_FOUND,+ )++ def test_setting_members_rejects_a_user_without_project_access(self):+ outsider = User.objects.create_user(email="[email protected]", first_name="Cy", password="password")+ channel_id = self._create_private_channel()["id"]+ response = self.client.put(+ f"{self._channels_url()}{channel_id}/members/", {"user_ids": [outsider.id]}, format="json"+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)+ self.assertFalse(+ ChannelMembership.objects.unscoped().filter(channel_id=channel_id, user_id=outsider.id).exists()+ )++ def test_a_non_member_cannot_patch_or_delete_a_private_channel(self):+ channel_id = self._create_private_channel()["id"]+ other_client = APIClient()+ other_client.force_authenticate(self.other_user)+ self.assertEqual(+ other_client.patch(f"{self._channels_url()}{channel_id}/", {"name": "hijack"}).status_code,+ status.HTTP_404_NOT_FOUND,+ )+ self.assertEqual(+ other_client.delete(f"{self._channels_url()}{channel_id}/").status_code,+ status.HTTP_404_NOT_FOUND,+ )++ listed = {c["id"]: c["name"] for c in self.client.get(self._channels_url()).json()}+ self.assertEqual(listed.get(channel_id), "squad")++ renamed = self.client.patch(f"{self._channels_url()}{channel_id}/", {"name": "squad-2"})+ self.assertEqual(renamed.status_code, status.HTTP_200_OK, renamed.content)++ def test_setting_members_requires_the_user_ids_field(self):+ channel_id = self._create_private_channel(member_ids=[self.other_user.id])["id"]+ members_url = f"{self._channels_url()}{channel_id}/members/"++ self.assertEqual(self.client.put(members_url, {}, format="json").status_code, status.HTTP_400_BAD_REQUEST)++ response = self.client.put(members_url, {"user_ids": []}, format="json")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual({m["id"] for m in response.json()}, {self.user.id})++ def test_members_can_be_managed_after_the_creator_leaves_the_project(self):+ creator = User.objects.create_user(email="[email protected]", first_name="Cara", password="password")+ self.organization.members.add(creator)+ OrganizationMembership.objects.filter(user=creator, organization=self.organization).update(+ level=OrganizationMembership.Level.ADMIN+ )+ creator_client = APIClient()+ creator_client.force_authenticate(creator)+ channel_id = self._create_private_channel(member_ids=[self.user.id], client=creator_client)["id"]++ OrganizationMembership.objects.filter(user=creator, organization=self.organization).delete()++ response = self.client.put(+ f"{self._channels_url()}{channel_id}/members/", {"user_ids": [self.other_user.id]}, format="json"+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual({m["id"] for m in response.json()}, {creator.id, self.other_user.id})+def test_deleting_github_integration_clears_channel_repositories(self):integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})channel = Channel.objects.for_team(self.team.id).create(diff --git a/products/tasks/docs/CHANNELS.md b/products/tasks/docs/CHANNELS.mdindex e41075fa40d8..140fc2faab2a 100644--- a/products/tasks/docs/CHANNELS.md+++ b/products/tasks/docs/CHANNELS.md@@ -1,133 +1,101 @@-# Channels & Threads (PostHog Desktop / Bluebird)--A channel is the backend model for a space. Public spaces are visible to project members.-`#me` is a private space that only its owner can access. A task with a channel inherits-that channel's visibility. Null-channel tasks keep the legacy creator and product-origin-rules until their product adopts spaces.--Each task has one thread. Human messages reach the agent only when the task author-explicitly forwards one.--## Django models--```python-class Channel(models.Model):- class ChannelType(models.TextChoices):- PUBLIC = "public", "Public" # visible to the whole team- PERSONAL = "personal", "Personal" # the user's private "#me" channel-- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)- team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")- name = models.CharField(max_length=128) # rendered as "#<name>"; personal channels are named "me"- channel_type = models.CharField(max_length=16, choices=ChannelType, default=ChannelType.PUBLIC)- created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")- deleted = models.BooleanField(default=False)- created_at = models.DateTimeField(default=django_timezone.now)- updated_at = models.DateTimeField(auto_now=True)-- class Meta:- db_table = "posthog_task_channel"- constraints = [- # public channel names are unique per team (soft-deleted names are reusable)- models.UniqueConstraint(- fields=["team", "name"],- condition=Q(channel_type="public", deleted=False),- name="task_channel_team_name_public_unique",- ),- # exactly one live "#me" channel per user per team- models.UniqueConstraint(- fields=["team", "created_by"],- condition=Q(channel_type="personal", deleted=False),- name="task_channel_team_user_personal_unique",- ),- ]---class Task(...):- # Ordinary user tasks get a channel; legacy and product tasks can remain NULL.- channel = models.ForeignKey(- "tasks.Channel", on_delete=models.SET_NULL, null=True, blank=True, related_name="tasks", db_index=False- )- # + Index(fields=["channel", "-created_at"], name="posthog_task_channel_feed_idx") for the feed---class TaskThreadMessage(models.Model):- """One human message in a task's thread. Threads are human-only side- conversations; a message reaches the agent only when the task author- forwards it (send_to_agent), which stamps the forwarded_* fields."""-- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)- team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")- task = models.ForeignKey("tasks.Task", on_delete=models.CASCADE, related_name="thread_messages")- author = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")- content = models.TextField()- forwarded_to_agent_at = models.DateTimeField(null=True, blank=True)- forwarded_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")- forwarded_run = models.ForeignKey("tasks.TaskRun", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_index=False)- created_at = models.DateTimeField(default=django_timezone.now)-- class Meta:- db_table = "posthog_task_thread_message"- indexes = [models.Index(fields=["task", "created_at"], name="task_thread_msg_task_created")]-```--### Visibility--A task with a channel uses only channel visibility:--- `PUBLIC` is readable by project members.-- `PERSONAL` is readable only by `Channel.created_by` and is shown as a private space.-- Task origin and creator fallbacks never widen a task with a channel.--A null-channel task uses the legacy creator and team-readable origin rules. Thread-messages, runs, artifacts, conversations, and task activity inherit task visibility.-A future selected-member private space can extend `Channel.visible_to_q` with channel-membership without adding permissions to Task.--## API--### `/api/projects/{id}/task_channels/`--- `GET /` — list channels: all live public channels plus the requester's- personal `#me` channel when it exists. Listing does not provision; call- `provision_defaults` to create the default channels. Paging is opt-in:- `?limit=&offset=` returns one page in a `count`/`next`/`previous` envelope,- and a request without `limit` returns every channel as a plain array.-- `POST / {name}` — resolve-or-create a public channel by name- (`get_or_create`, so concurrent creates and name-bridging are race-safe).-- `PATCH /{id}/ {name}` - any project member can rename or configure a public channel. Private `#me` spaces cannot be renamed.-- `DELETE /{id}/` - any project member can delete an empty public channel. Private `#me` and non-empty spaces cannot be deleted.--### Task endpoints--- `TaskCreateSerializer` accepts `channel` (UUID). It must belong to the team. A- private `#me` space is accepted only from its owner.-- Omitting `channel` for an ordinary user task files it into the user's `#me` space.-- A task controller can move a task by updating `channel` to a public or owned private space. Existing callers can still clear `channel` for legacy compatibility.-- `TaskSerializer` / `TaskDetailDTO` emit `channel`.-- `GET /tasks/?channel=<uuid>` filters the list to a channel's feed.-- `POST /tasks/{task_id}/handoff/ {user}`: hand a task off to a colleague. The- requester must own the task; the target must have access to the project and not- be the current owner. Ownership (`created_by`)- moves to the recipient, so they drive the task afterwards and future runs- resolve GitHub authorship and notification recipients from them. A task in a- private `#me` space (or with no channel) moves into the recipient's `#me`, so a- handoff never strands a task the recipient can't open; a task in a shared space- stays there. All task runs must be terminal and every sandbox session must be- closed before a handoff. The handoff rotates the task's server-owned ownership- version, revokes task-bound sandbox OAuth tokens, and makes runs from the old- ownership version read-only. The recipient must start a fresh run. The handoff- also clears the stored GitHub user-integration preference and any borrowed MCP- credential owner, posts a system `task_handed_off` announcement into the task's- thread, and notifies the recipient.--### Canvas endpoints--- Project members can create and read Canvases in public channels.-- Only a Canvas creator can change Canvas metadata or source.-- Any project member can queue a build for the current source version through `publish-current-version`.--Task sandboxes use the authenticated OAuth token user for the creator boundary across public and personal spaces:+# Channels and threads++A channel is the backend model for a space in PostHog Desktop. Tasks in a channel use that channel's access rules.+Each task has one thread. A human message reaches the agent only when the task owner forwards it.++## Models and access++| Channel type | Who can access it | Name rule |+| ------------ | ----------------------------------- | -------------------------------------------------- |+| `public` | Project members | Unique among active public channels in the project |+| `personal` | The creator | One active `#me` channel per user per project |+| `private` | Channel members with project access | Duplicate names are allowed; use the channel ID |++`ChannelMembership` records a private channel's members. Each row has a team, channel, user, and creation time.+The `(channel, user)` pair is unique. Public and personal channels do not use membership rows.+Any private channel member can update the member list. The creator remains a member.++The membership table has no database foreign key constraints on `team` or `user`.+This prevents the migration from locking the shared team and user tables. Django manages these relations and deletion rules.+The `channel` relation has a database foreign key constraint.++`Task.channel` can be null for older tasks and tasks from other products.+These tasks use the existing creator and product access rules.+For tasks with a channel, `Channel.visible_to_q` defines access. Task origin and ownership cannot grant additional access.+Thread messages, runs, artifacts, conversations, and task activity use the task's access rules.++`TaskThreadMessage` stores the task, author, content, and creation time.+When the task owner forwards a message, the row also records the forwarding user, time, and run.++## Channel API++Base path: `/api/projects/{id}/task_channels/`.++| Request | Result |+| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------- |+| `GET /` | List all accessible channels, sorted by name and ID. |+| `POST / {name, channel_type, member_ids, star}` | Create a channel or return an existing public channel with the same name. |+| `PATCH /{id}/ {name, channel_type}` | Rename or switch an accessible public or private channel. Personal and general spaces cannot change. |+| `DELETE /{id}/` | Delete an empty public or private channel. Personal and general spaces cannot be deleted. |+| `GET /{id}/members/` | List private channel members. Return an empty list for public and personal channels. |+| `PUT /{id}/members/ {user_ids}` | Replace a private channel's members. Keep the creator. |++Listing channels does not create them. Call `provision_defaults` to create the default channels.+Send `limit` and `offset` to get one page with `count`, `next`, `previous`, and `results`.+Without `limit`, the response is an array of all accessible channels.++Channel creation defaults to `public`. Public names use lowercase letters and hyphens.+A private channel always gets a new UUID, even if another channel has the same name.+The requester becomes a member. The endpoint adds users from `member_ids` who have project access and skips the others.+A retry creates another private channel.++Membership replacement requires `user_ids`. Each submitted user must have project access.+An empty list removes all members except the creator.+A creator who loses project access remains in the member list but cannot access the channel.+Removing a member leaves their tasks in the channel and removes their access.+The endpoint returns 400 for invalid users or public or personal channels. It returns 404 for inaccessible channels.++A `channel_type` update switches a shared channel between `public` and `private`.+Making a channel private removes every membership row and seeds the creator and the requester.+Making a channel public removes every membership row. The name must be free among active public channels, or the request returns 400.++Channel updates, deletion, membership changes, private channel handoffs, feed posts, instructions, context generation, and stars lock the channel row.+Each write checks access after it acquires the lock. A request from a removed member fails even if it started before removal.+Membership replacement checks project access after it acquires the lock.+Handoff locks the private channel before the task. It fails if the task moved to another channel during the wait.++## Task API++- `TaskCreateSerializer` accepts a channel UUID from the same project. The requester must have access to the channel.+- An ordinary user task without a channel goes into the user's `#me` space.+- A user who controls a task can move it to a public channel, their own `#me` channel, or a private channel they belong to.+- Existing callers can still clear `channel` for compatibility.+- `TaskSerializer` and `TaskDetailDTO` return `channel`.+- `GET /tasks/?channel=<uuid>` lists tasks in a channel.++`POST /tasks/{task_id}/handoff/ {user}` transfers ownership to another project member.+Only the current owner can transfer a task. The recipient must have project access and must differ from the current owner.+All runs must have ended, and all sandbox sessions must be closed.++| Current channel | Channel after handoff |+| ---------------------- | ------------------------------------------------ |+| Personal `#me` or none | The recipient's `#me` channel |+| Private | The same channel; the recipient becomes a member |+| Public | The same channel |++Future runs use the recipient for GitHub authorship and notifications.+Handoff changes the ownership version and revokes sandbox OAuth tokens for the task.+Runs from the previous ownership version become read-only. The recipient must start a new run.+Handoff clears the saved GitHub user integration and MCP credential owner.+It adds a `task_handed_off` message to the thread and notifies the recipient.++## Canvas API++Project members can create and read canvases in public channels.+Only the canvas creator can change its metadata or source.+Any project member can queue a build of the current source through `publish-current-version`.++Task sandboxes use the authenticated OAuth token user to check canvas access:| Canvas space | Token user | Read | Write || ------------ | ----------------------------- | ---- | ----- |@@ -136,41 +104,40 @@ Task sandboxes use the authenticated OAuth token user for the creator boundary a| Personal | Canvas creator | Yes | Yes || Personal | Another user or no token user | No | No |-An exact task-to-Canvas link does not grant additional write access. Canvas creation remains limited to the bound task's space.--### `/api/projects/{id}/tasks/{task_id}/thread_messages/`--- `GET /` — thread messages, ascending `created_at` (paginated).-- `POST / {content}` — add a message as the requester. Anyone who can see the task can post.-- `DELETE /{id}/` — author-only.-- `POST /{id}/send_to_agent/` — task author only. Signals the latest run's- workflow with `[Thread comment from <author>] <content>` via- `signal_task_run_user_message`, then stamps `forwarded_to_agent_at`,- `forwarded_by`, `forwarded_run`. 400 when the task has no signalable run.--## Client (PostHog Desktop, bluebird mode)--- **Channel feed** — the channel view becomes a Slack-like feed: each item is- the kickoff message (author avatar + name + prompt) with a task card- (title, status badge, repo, replies count) underneath. The composer at the- bottom kicks off a task owned by the channel; the author stays in the feed- and the card updates live (poll). The existing tabs (Inbox / Artifacts /- Recents / CONTEXT.md) stay above the feed.-- **Threads** — a collapsible right-side panel shows a task's thread: message- list plus reply composer. Each message row has a hover menu; the task author- gets "Send to agent" there. Forwarded messages show a "Sent to agent" badge.- Opening a thread from a feed card shows the panel next to the feed; opening- a task shows the same panel next to the task detail (collapsible).-- **#me** — the sidebar pins the personal channel (`#me`) above the channel- list; it is each user's private feed.-- **One identity** — the backend `Channel` UUID keys everything: task- ownership, feeds, threads, canvases (`Canvas.channel`), CONTEXT.md- instructions, and per-user stars. (The former desktop-file-system folder- bridge — folders mapped to channels by name — was retired when canvases- became first-class rows; see `products/canvas/`.)--## Out of scope (v1)--- Selected-member private spaces and channel membership.+A task linked to a canvas gains no additional write access.+A sandbox can create a canvas only in its task's space.++## Thread API++Base path: `/api/projects/{id}/tasks/{task_id}/thread_messages/`.++| Request | Result |+| --------------------------- | ------------------------------------------------------------------------ |+| `GET /` | List messages by creation time, oldest first, with pagination. |+| `POST / {content}` | Add a message. Anyone with task access can post. |+| `DELETE /{id}/` | Delete a message. Only its author can delete it. |+| `POST /{id}/send_to_agent/` | Forward a message to the latest run. Only the task owner can forward it. |++Forwarding uses `signal_task_run_user_message` with `[Thread comment from <author>] <content>`.+It records `forwarded_to_agent_at`, `forwarded_by`, and `forwarded_run`.+The endpoint returns 400 if no run can receive the message.++## Desktop client++The channel feed shows each task's initial message and a card with its title, status, repository, and reply count.+The message input creates a task in the channel. The feed updates through polling.+Inbox, Artifacts, Recents, and CONTEXT.md tabs appear above the feed.++A panel beside the feed or task details shows the task's thread and a reply input.+The task owner can select "Send to agent" from a message menu.+Forwarded messages show "Sent to agent". The panel can be collapsed.++The sidebar pins the user's personal `#me` channel above the channel list.+The backend channel UUID identifies the space across tasks, feeds, threads, canvases, instructions, and stars.++## Out of scope++- Per-member roles or permissions.+- Activity log entries for membership changes.+- Push notifications for membership, feed, or thread changes. Clients poll.- Message editing and emoji reactions.-- Real-time push for feed/thread updates (clients poll; SSE can come later).diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 8fde42c2fff6..d5f00e36e89b 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1126,15 +1126,33 @@ export interface PaginatedChannelDTOListApi {}/**- * Request body for creating (resolve-or-create) or renaming a public channel.+ * * `public` - public+ * * `private` - private*/+export type TaskChannelWriteTypeEnumApi = (typeof TaskChannelWriteTypeEnumApi)[keyof typeof TaskChannelWriteTypeEnumApi]++export const TaskChannelWriteTypeEnumApi = {+ Public: 'public',+ Private: 'private',+} as const+export interface ChannelWriteApi {/**- * Channel name, rendered as #<name>. Normalized to lowercase-dashed.+ * Channel name, shown as #<name>. Uses lowercase letters and hyphens.* @maxLength 128*/name: string- /** Star the channel for the requester when this call creates it. Ignored when the channel already exists, which leaves existing stars untouched. */+ /** Use 'public' for access by all project members. Use 'private' for access by channel members only. Defaults to 'public'. This endpoint cannot create personal #me spaces.+ *+ * * `public` - public+ * * `private` - private */+ channel_type?: TaskChannelWriteTypeEnumApi+ /**+ * User IDs to add to a private channel. The requester is always a member. The endpoint ignores this field for public channels and skips users without project access.+ * @maxItems 100+ */+ member_ids?: number[]+ /** Star a new channel for the requester. This field does not change stars on an existing channel. */star?: boolean}@@ -1213,6 +1231,11 @@ export interface PatchedChannelUpdateApi {* @nullable*/auto_archive_after_days?: number | null+ /** Switch a shared space between 'public' and 'private'. Making a space private keeps only the creator and the requester as members. Making it public removes its member list. Personal #me spaces cannot change.+ *+ * * `public` - public+ * * `private` - private */+ channel_type?: TaskChannelWriteTypeEnumApi}export interface ChannelDeleteConflictApi {@@ -1283,6 +1306,14 @@ export interface PaginatedChannelInstructionsDTOListApi {results: ChannelInstructionsDTOApi[]}+export interface ChannelMembersWriteApi {+ /**+ * Required list of member user IDs. This list replaces the current members. The creator remains a member. Send an empty list to remove all other members. Each submitted user must have project access.+ * @maxItems 100+ */+ user_ids: number[]+}+/*** Request body for starring/unstarring a channel for the requesting user.*/@@ -1820,13 +1851,6 @@ export const TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi = {FullAccess: 'full-access',} as const-/**- * Request body for creating or updating a task.- *- * Field required/default semantics match the ``Task`` model. The view passes- * ``validated_data`` (integration/report PK fields already resolved to instances) to the- * facade ``create_task`` / ``update_task`` functions.- */export interface TaskCreateApi {/*** Short human-readable title. Auto-generated from `description` when omitted.@@ -1981,13 +2005,6 @@ export interface TaskCreateApi {runtime?: TaskRuntimeEnumApi}-/**- * Request body for creating or updating a task.- *- * Field required/default semantics match the ``Task`` model. The view passes- * ``validated_data`` (integration/report PK fields already resolved to instances) to the- * facade ``create_task`` / ``update_task`` functions.- */export interface TaskWriteApi {/*** Short human-readable title. Auto-generated from `description` when omitted.@@ -2120,13 +2137,6 @@ export interface TaskWriteApi {channel?: string | null}-/**- * Request body for creating or updating a task.- *- * Field required/default semantics match the ``Task`` model. The view passes- * ``validated_data`` (integration/report PK fields already resolved to instances) to the- * facade ``create_task`` / ``update_task`` functions.- */export interface PatchedTaskWriteApi {/*** Short human-readable title. Auto-generated from `description` when omitted.diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 6546afc37a76..ed1e107c9753 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -15,6 +15,7 @@ import type {ChannelFeedMessageWriteApi,ChannelInstructionsDTOApi,ChannelInstructionsWriteApi,+ ChannelMembersWriteApi,ChannelStarWriteApi,ChannelWriteApi,ConnectionTokenResponseApi,@@ -132,6 +133,7 @@ import type {TaskThreadMessageDTOApi,TaskThreadMessageWriteApi,TaskUsageResponseApi,+ TaskUserBasicInfoApi,TaskWriteApi,TasksAIRunPreferencesApi,TasksCommentsListParams,@@ -784,7 +786,7 @@ export const getTaskChannelsListUrl = (projectId: string, params?: TaskChannelsL}/**- * All live public channels plus the requester's personal #me channel when it exists, sorted by name. Listing does not provision; call provision_defaults to create the default channels. Send `limit` (with `offset`) for one page and a `count`/`next` envelope; without `limit` the response is the full array of channels.+ * List channels the requester can access, sorted by name and ID. Includes public channels, their personal #me channel, and private channels they belong to. Call provision_defaults to create missing default channels. Send limit and offset to get a page with count, next, previous, and results. Without limit, the response is an array of all accessible channels.* @summary List channels*/export const taskChannelsList = async (@@ -803,8 +805,8 @@ export const getTaskChannelsCreateUrl = (projectId: string) => {}/**- * Returns the existing public channel with the (normalized) name, creating it if needed. A channel created here is starred for the requester unless star is false. The general name returns the team's general space; names that read as a private space ("me", "personal") are rejected.- * @summary Resolve or create a public channel+ * Create a channel. Public channels use lowercase names with hyphens. If a public channel has that name, return it. The name general returns the project's general space. Private channels always get a new ID, even if another channel has the same name. The requester and users in member_ids with project access become members. New channels are starred for the requester unless star is false. The names "me" and "personal" are reserved.+ * @summary Create a channel*/export const taskChannelsCreate = async (projectId: string,@@ -884,10 +886,6 @@ export const getTaskChannelsRetrieveUrl = (projectId: string, id: string) => {}/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.* @summary Get a channel*/export const taskChannelsRetrieve = async (@@ -906,11 +904,7 @@ export const getTaskChannelsPartialUpdateUrl = (projectId: string, id: string) =}/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.- * @summary Rename a public channel+ * @summary Update a channel*/export const taskChannelsPartialUpdate = async (projectId: string,@@ -931,11 +925,7 @@ export const getTaskChannelsDestroyUrl = (projectId: string, id: string) => {}/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.- * @summary Delete a public channel+ * @summary Delete a channel*/export const taskChannelsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {return apiMutator<void>(getTaskChannelsDestroyUrl(projectId, id), {@@ -949,10 +939,6 @@ export const getTaskChannelsContextGenerationRetrieveUrl = (projectId: string, i}/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.* @summary Get the channel's CONTEXT.md generation task*/export const taskChannelsContextGenerationRetrieve = async (@@ -971,10 +957,6 @@ export const getTaskChannelsContextGenerationUpdateUrl = (projectId: string, id:}/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.* @summary Set or clear the channel's CONTEXT.md generation task*/export const taskChannelsContextGenerationUpdate = async (@@ -1059,10 +1041,6 @@ export const getTaskChannelsInstructionsDestroyUrl = (projectId: string, id: str}/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.* @summary Delete channel instructions*/export const taskChannelsInstructionsDestroy = async (@@ -1081,10 +1059,6 @@ export const getTaskChannelsInstructionsVersionsRetrieveUrl = (projectId: string}/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.* @summary List channel instruction versions*/export const taskChannelsInstructionsVersionsRetrieve = async (@@ -1101,15 +1075,52 @@ export const taskChannelsInstructionsVersionsRetrieve = async ()}+export const getTaskChannelsMembersRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/task_channels/${id}/members/`+}++/**+ * List the members of a private channel. Return an empty list for public and personal channels. Return 404 if the requester cannot access the channel.+ * @summary List a channel's members+ */+export const taskChannelsMembersRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<TaskUserBasicInfoApi[]> => {+ return apiMutator<TaskUserBasicInfoApi[]>(getTaskChannelsMembersRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getTaskChannelsMembersUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/task_channels/${id}/members/`+}++/**+ * Replace the members of a private channel. Any member can update this list. The creator remains a member. Return 400 for public and personal channels.+ * @summary Replace a private channel's members+ */+export const taskChannelsMembersUpdate = async (+ projectId: string,+ id: string,+ channelMembersWriteApi: ChannelMembersWriteApi,+ options?: RequestInit+): Promise<TaskUserBasicInfoApi[]> => {+ return apiMutator<TaskUserBasicInfoApi[]>(getTaskChannelsMembersUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(channelMembersWriteApi),+ })+}+export const getTaskChannelsStarCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/task_channels/${id}/star/`}/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.* @summary Star or unstar a channel for the requesting user*/export const taskChannelsStarCreate = async (diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex d472d4b7e5cf..01946891a570 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -891,27 +891,40 @@ export const TaskActivityMarkReadCreateBody = /* @__PURE__ */ zod.describe('Request body for clearing the unread flag on specific tasks.')/**- * Returns the existing public channel with the (normalized) name, creating it if needed. A channel created here is starred for the requester unless star is false. The general name returns the team's general space; names that read as a private space ("me", "personal") are rejected.- * @summary Resolve or create a public channel+ * Create a channel. Public channels use lowercase names with hyphens. If a public channel has that name, return it. The name general returns the project's general space. Private channels always get a new ID, even if another channel has the same name. The requester and users in member_ids with project access become members. New channels are starred for the requester unless star is false. The names "me" and "personal" are reserved.+ * @summary Create a channel*/export const taskChannelsCreateBodyNameMax = 128+export const taskChannelsCreateBodyChannelTypeDefault = `public`+export const taskChannelsCreateBodyMemberIdsMax = 100+export const taskChannelsCreateBodyStarDefault = true-export const TaskChannelsCreateBody = /* @__PURE__ */ zod- .object({- name: zod- .string()- .max(taskChannelsCreateBodyNameMax)- .describe('Channel name, rendered as #<name>. Normalized to lowercase-dashed.'),- star: zod- .boolean()- .default(taskChannelsCreateBodyStarDefault)- .describe(- 'Star the channel for the requester when this call creates it. Ignored when the channel already exists, which leaves existing stars untouched.'- ),- })- .describe('Request body for creating (resolve-or-create) or renaming a public channel.')+export const TaskChannelsCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(taskChannelsCreateBodyNameMax)+ .describe('Channel name, shown as #<name>. Uses lowercase letters and hyphens.'),+ channel_type: zod+ .enum(['public', 'private'])+ .describe('\* `public` - public\n\* `private` - private')+ .default(taskChannelsCreateBodyChannelTypeDefault)+ .describe(+ "Use 'public' for access by all project members. Use 'private' for access by channel members only. Defaults to 'public'. This endpoint cannot create personal #me spaces.\n\n\* `public` - public\n\* `private` - private"+ ),+ member_ids: zod+ .array(zod.number())+ .max(taskChannelsCreateBodyMemberIdsMax)+ .optional()+ .describe(+ 'User IDs to add to a private channel. The requester is always a member. The endpoint ignores this field for public channels and skips users without project access.'+ ),+ star: zod+ .boolean()+ .default(taskChannelsCreateBodyStarDefault)+ .describe('Star a new channel for the requester. This field does not change stars on an existing channel.'),+})/*** API for a channel's system-announcement feed — durable "PostHog agent" rows@@ -941,11 +954,7 @@ export const TaskChannelsFeedCreateBody = /* @__PURE__ */ zod.describe("Request body for posting a system announcement into a channel's feed.")/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.- * @summary Rename a public channel+ * @summary Update a channel*/export const taskChannelsPartialUpdateBodyNameMax = 128@@ -978,13 +987,16 @@ export const TaskChannelsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Days of inactivity before tasks in this channel are archived. Accepts 1 through 365. Null disables automatic archiving.'),+ channel_type: zod+ .enum(['public', 'private'])+ .describe('\* `public` - public\n\* `private` - private')+ .optional()+ .describe(+ "Switch a shared space between 'public' and 'private'. Making a space private keeps only the creator and the requester as members. Making it public removes its member list. Personal #me spaces cannot change.\n\n\* `public` - public\n\* `private` - private"+ ),})/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.* @summary Set or clear the channel's CONTEXT.md generation task*/export const TaskChannelsContextGenerationUpdateBody = /* @__PURE__ */ zod@@ -1043,10 +1055,21 @@ export const TaskChannelsInstructionsPartialUpdateBody = /* @__PURE__ */ zod.describe('Request body for publishing a new instructions version.')/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.+ * Replace the members of a private channel. Any member can update this list. The creator remains a member. Return 400 for public and personal channels.+ * @summary Replace a private channel's members+ */+export const taskChannelsMembersUpdateBodyUserIdsMax = 100++export const TaskChannelsMembersUpdateBody = /* @__PURE__ */ zod.object({+ user_ids: zod+ .array(zod.number())+ .max(taskChannelsMembersUpdateBodyUserIdsMax)+ .describe(+ 'Required list of member user IDs. This list replaces the current members. The creator remains a member. Send an empty list to remove all other members. Each submitted user must have project access.'+ ),+})++/*** @summary Star or unstar a channel for the requesting user*/export const TaskChannelsStarCreateBody = /* @__PURE__ */ zod@@ -1142,177 +1165,170 @@ export const tasksCreateBodyPendingUserArtifactIdsItemMax = 128export const tasksCreateBodySignalReportDiscussionQuestionMax = 4000-export const TasksCreateBody = /* @__PURE__ */ zod- .object({- title: zod- .string()- .max(tasksCreateBodyTitleMax)- .optional()- .describe('Short human-readable title. Auto-generated from `description` when omitted.'),- title_manually_set: zod- .boolean()- .optional()- .describe('Whether the title was set by a human (vs auto-generated from the description).'),- description: zod- .string()- .optional()- .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),- origin_product: zod- .enum([- 'onboarding',- 'error_tracking',- 'eval_clusters',- 'user_created',- 'slack',- 'support_queue',- 'session_summaries',- 'posthog_ai',- 'experiments',- 'signal_report',- 'signals_scout',- 'scout_suggestions',- 'support_reply',- 'hogdesk',- 'review_hog',- 'image_builder',- 'loop',- 'mcp_analytics',- 'signals_chat',- 'task_analysis',- 'workflow',- ])- .describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'- )- .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\* `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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'- ),- repository: zod- .string()- .max(tasksCreateBodyRepositoryMax)- .nullish()- .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),- repositories: zod- .array(zod.string().max(tasksCreateBodyRepositoriesItemMax))- .max(tasksCreateBodyRepositoriesMax)- .optional()- .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),- github_integration: zod.number().nullish().describe('GitHub integration for this task.'),- github_user_integration: zod- .uuid()- .nullish()- .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),- signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),- signal_report_task_relationship: zod- .string()- .max(tasksCreateBodySignalReportTaskRelationshipMax)- .optional()- .describe(- "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."- ),- json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),- archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),- ci_prompt: zod- .string()- .nullish()- .describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),- branch: zod- .string()- .max(tasksCreateBodyBranchMax)- .nullish()- .describe(- 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'- ),- runtime_adapter: zod- .union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])- .optional()- .describe(- "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"- ),- model: zod- .string()- .nullish()- .describe(- 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'- ),- reasoning_effort: zod- .union([- zod- .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])- .describe(- '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'- ),- zod.null(),- ])- .optional()- .describe(- 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'- ),- initial_permission_mode: zod- .union([- zod- .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto', 'read-only', 'full-access'])- .describe(- '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'- ),- zod.null(),- ])- .optional()- .describe(- 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'- ),- pending_user_message: zod- .string()- .nullish()- .describe(- 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'- ),- pending_user_artifact_ids: zod- .array(zod.string().max(tasksCreateBodyPendingUserArtifactIdsItemMax))- .optional()- .describe(- "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."- ),- auto_publish: zod- .boolean()- .nullish()- .describe(- "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."- ),- channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),- signal_report_discussion_question: zod- .string()- .max(tasksCreateBodySignalReportDiscussionQuestionMax)- .optional()- .describe(- "Question to forward to the signal report's scout when creating a discussion task. Send an empty string when there is no question. Omit only for older clients that embed the question in the task description. Not persisted on the task."- ),- naming_source: zod- .string()- .optional()- .describe(- 'Text the server generates the title from instead of `description`. Lets a client whose `description` is only an attachment summary (e.g. pasted text stored as a file) supply the real content for naming, so `description` (the prompt passed to the agent) stays unchanged. Not persisted.'- ),- sandbox_environment_id: zod- .uuid()- .nullish()- .describe('Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.'),- custom_image_id: zod- .uuid()- .nullish()- .describe('Custom image selected for matching a pre-warmed cloud run. Not persisted on the task.'),- runtime: zod- .enum(['acp', 'pi'])- .describe('\* `acp` - ACP\n\* `pi` - Pi')- .optional()- .describe(- "Agent protocol and harness used for this task's runs. Defaults to ACP when omitted.\n\n\* `acp` - ACP\n\* `pi` - Pi"- ),- })- .describe(- 'Request body for creating or updating a task.\n\nField required\/default semantics match the ``Task`` model. The view passes\n``validated_data`` (integration\/report PK fields already resolved to instances) to the\nfacade ``create_task`` \/ ``update_task`` functions.'- )+export const TasksCreateBody = /* @__PURE__ */ zod.object({+ title: zod+ .string()+ .max(tasksCreateBodyTitleMax)+ .optional()+ .describe('Short human-readable title. Auto-generated from `description` when omitted.'),+ title_manually_set: zod+ .boolean()+ .optional()+ .describe('Whether the title was set by a human (vs auto-generated from the description).'),+ description: zod+ .string()+ .optional()+ .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),+ origin_product: zod+ .enum([+ 'onboarding',+ 'error_tracking',+ 'eval_clusters',+ 'user_created',+ 'slack',+ 'support_queue',+ 'session_summaries',+ 'posthog_ai',+ 'experiments',+ 'signal_report',+ 'signals_scout',+ 'scout_suggestions',+ 'support_reply',+ 'hogdesk',+ 'review_hog',+ 'image_builder',+ 'loop',+ 'mcp_analytics',+ 'signals_chat',+ 'task_analysis',+ 'workflow',+ ])+ .describe(+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ )+ .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\* `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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ ),+ repository: zod+ .string()+ .max(tasksCreateBodyRepositoryMax)+ .nullish()+ .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),+ repositories: zod+ .array(zod.string().max(tasksCreateBodyRepositoriesItemMax))+ .max(tasksCreateBodyRepositoriesMax)+ .optional()+ .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),+ github_integration: zod.number().nullish().describe('GitHub integration for this task.'),+ github_user_integration: zod+ .uuid()+ .nullish()+ .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),+ signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),+ signal_report_task_relationship: zod+ .string()+ .max(tasksCreateBodySignalReportTaskRelationshipMax)+ .optional()+ .describe(+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."+ ),+ json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),+ archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),+ ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),+ branch: zod+ .string()+ .max(tasksCreateBodyBranchMax)+ .nullish()+ .describe(+ 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'+ ),+ runtime_adapter: zod+ .union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])+ .optional()+ .describe(+ "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"+ ),+ model: zod+ .string()+ .nullish()+ .describe(+ 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'+ ),+ reasoning_effort: zod+ .union([+ zod+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])+ .describe(+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ ),+ initial_permission_mode: zod+ .union([+ zod+ .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto', 'read-only', 'full-access'])+ .describe(+ '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'+ ),+ pending_user_message: zod+ .string()+ .nullish()+ .describe(+ 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'+ ),+ pending_user_artifact_ids: zod+ .array(zod.string().max(tasksCreateBodyPendingUserArtifactIdsItemMax))+ .optional()+ .describe(+ "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."+ ),+ auto_publish: zod+ .boolean()+ .nullish()+ .describe(+ "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."+ ),+ channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),+ signal_report_discussion_question: zod+ .string()+ .max(tasksCreateBodySignalReportDiscussionQuestionMax)+ .optional()+ .describe(+ "Question to forward to the signal report's scout when creating a discussion task. Send an empty string when there is no question. Omit only for older clients that embed the question in the task description. Not persisted on the task."+ ),+ naming_source: zod+ .string()+ .optional()+ .describe(+ 'Text the server generates the title from instead of `description`. Lets a client whose `description` is only an attachment summary (e.g. pasted text stored as a file) supply the real content for naming, so `description` (the prompt passed to the agent) stays unchanged. Not persisted.'+ ),+ sandbox_environment_id: zod+ .uuid()+ .nullish()+ .describe('Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.'),+ custom_image_id: zod+ .uuid()+ .nullish()+ .describe('Custom image selected for matching a pre-warmed cloud run. Not persisted on the task.'),+ runtime: zod+ .enum(['acp', 'pi'])+ .describe('\* `acp` - ACP\n\* `pi` - Pi')+ .optional()+ .describe(+ "Agent protocol and harness used for this task's runs. Defaults to ACP when omitted.\n\n\* `acp` - ACP\n\* `pi` - Pi"+ ),+})/*** API for managing tasks within a project. Tasks represent units of work to be performed by an agent.@@ -1331,149 +1347,142 @@ export const tasksUpdateBodyBranchMax = 255export const tasksUpdateBodyPendingUserArtifactIdsItemMax = 128-export const TasksUpdateBody = /* @__PURE__ */ zod- .object({- title: zod- .string()- .max(tasksUpdateBodyTitleMax)- .optional()- .describe('Short human-readable title. Auto-generated from `description` when omitted.'),- title_manually_set: zod- .boolean()- .optional()- .describe('Whether the title was set by a human (vs auto-generated from the description).'),- description: zod- .string()- .optional()- .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),- origin_product: zod- .enum([- 'onboarding',- 'error_tracking',- 'eval_clusters',- 'user_created',- 'slack',- 'support_queue',- 'session_summaries',- 'posthog_ai',- 'experiments',- 'signal_report',- 'signals_scout',- 'scout_suggestions',- 'support_reply',- 'hogdesk',- 'review_hog',- 'image_builder',- 'loop',- 'mcp_analytics',- 'signals_chat',- 'task_analysis',- 'workflow',- ])- .describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'- )- .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\* `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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'- ),- repository: zod- .string()- .max(tasksUpdateBodyRepositoryMax)- .nullish()- .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),- repositories: zod- .array(zod.string().max(tasksUpdateBodyRepositoriesItemMax))- .max(tasksUpdateBodyRepositoriesMax)- .optional()- .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),- github_integration: zod.number().nullish().describe('GitHub integration for this task.'),- github_user_integration: zod- .uuid()- .nullish()- .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),- signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),- signal_report_task_relationship: zod- .string()- .max(tasksUpdateBodySignalReportTaskRelationshipMax)- .optional()- .describe(- "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."- ),- json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),- archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),- ci_prompt: zod- .string()- .nullish()- .describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),- branch: zod- .string()- .max(tasksUpdateBodyBranchMax)- .nullish()- .describe(- 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'- ),- runtime_adapter: zod- .union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])- .optional()- .describe(- "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"- ),- model: zod- .string()- .nullish()- .describe(- 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'- ),- reasoning_effort: zod- .union([- zod- .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])- .describe(- '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'- ),- zod.null(),- ])- .optional()- .describe(- 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'- ),- initial_permission_mode: zod- .union([- zod- .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto', 'read-only', 'full-access'])- .describe(- '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'- ),- zod.null(),- ])- .optional()- .describe(- 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'- ),- pending_user_message: zod- .string()- .nullish()- .describe(- 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'- ),- pending_user_artifact_ids: zod- .array(zod.string().max(tasksUpdateBodyPendingUserArtifactIdsItemMax))- .optional()- .describe(- "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."- ),- auto_publish: zod- .boolean()- .nullish()- .describe(- "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."- ),- channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),- })- .describe(- 'Request body for creating or updating a task.\n\nField required\/default semantics match the ``Task`` model. The view passes\n``validated_data`` (integration\/report PK fields already resolved to instances) to the\nfacade ``create_task`` \/ ``update_task`` functions.'- )+export const TasksUpdateBody = /* @__PURE__ */ zod.object({+ title: zod+ .string()+ .max(tasksUpdateBodyTitleMax)+ .optional()+ .describe('Short human-readable title. Auto-generated from `description` when omitted.'),+ title_manually_set: zod+ .boolean()+ .optional()+ .describe('Whether the title was set by a human (vs auto-generated from the description).'),+ description: zod+ .string()+ .optional()+ .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),+ origin_product: zod+ .enum([+ 'onboarding',+ 'error_tracking',+ 'eval_clusters',+ 'user_created',+ 'slack',+ 'support_queue',+ 'session_summaries',+ 'posthog_ai',+ 'experiments',+ 'signal_report',+ 'signals_scout',+ 'scout_suggestions',+ 'support_reply',+ 'hogdesk',+ 'review_hog',+ 'image_builder',+ 'loop',+ 'mcp_analytics',+ 'signals_chat',+ 'task_analysis',+ 'workflow',+ ])+ .describe(+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ )+ .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\* `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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ ),+ repository: zod+ .string()+ .max(tasksUpdateBodyRepositoryMax)+ .nullish()+ .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),+ repositories: zod+ .array(zod.string().max(tasksUpdateBodyRepositoriesItemMax))+ .max(tasksUpdateBodyRepositoriesMax)+ .optional()+ .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),+ github_integration: zod.number().nullish().describe('GitHub integration for this task.'),+ github_user_integration: zod+ .uuid()+ .nullish()+ .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),+ signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),+ signal_report_task_relationship: zod+ .string()+ .max(tasksUpdateBodySignalReportTaskRelationshipMax)+ .optional()+ .describe(+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."+ ),+ json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),+ archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),+ ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),+ branch: zod+ .string()+ .max(tasksUpdateBodyBranchMax)+ .nullish()+ .describe(+ 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'+ ),+ runtime_adapter: zod+ .union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])+ .optional()+ .describe(+ "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"+ ),+ model: zod+ .string()+ .nullish()+ .describe(+ 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'+ ),+ reasoning_effort: zod+ .union([+ zod+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])+ .describe(+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ ),+ initial_permission_mode: zod+ .union([+ zod+ .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto', 'read-only', 'full-access'])+ .describe(+ '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'+ ),+ pending_user_message: zod+ .string()+ .nullish()+ .describe(+ 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'+ ),+ pending_user_artifact_ids: zod+ .array(zod.string().max(tasksUpdateBodyPendingUserArtifactIdsItemMax))+ .optional()+ .describe(+ "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."+ ),+ auto_publish: zod+ .boolean()+ .nullish()+ .describe(+ "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."+ ),+ channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),+})/*** API for managing tasks within a project. Tasks represent units of work to be performed by an agent.@@ -1492,149 +1501,142 @@ export const tasksPartialUpdateBodyBranchMax = 255export const tasksPartialUpdateBodyPendingUserArtifactIdsItemMax = 128-export const TasksPartialUpdateBody = /* @__PURE__ */ zod- .object({- title: zod- .string()- .max(tasksPartialUpdateBodyTitleMax)- .optional()- .describe('Short human-readable title. Auto-generated from `description` when omitted.'),- title_manually_set: zod- .boolean()- .optional()- .describe('Whether the title was set by a human (vs auto-generated from the description).'),- description: zod- .string()- .optional()- .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),- origin_product: zod- .enum([- 'onboarding',- 'error_tracking',- 'eval_clusters',- 'user_created',- 'slack',- 'support_queue',- 'session_summaries',- 'posthog_ai',- 'experiments',- 'signal_report',- 'signals_scout',- 'scout_suggestions',- 'support_reply',- 'hogdesk',- 'review_hog',- 'image_builder',- 'loop',- 'mcp_analytics',- 'signals_chat',- 'task_analysis',- 'workflow',- ])- .describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'- )- .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\* `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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'- ),- repository: zod- .string()- .max(tasksPartialUpdateBodyRepositoryMax)- .nullish()- .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),- repositories: zod- .array(zod.string().max(tasksPartialUpdateBodyRepositoriesItemMax))- .max(tasksPartialUpdateBodyRepositoriesMax)- .optional()- .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),- github_integration: zod.number().nullish().describe('GitHub integration for this task.'),- github_user_integration: zod- .uuid()- .nullish()- .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),- signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),- signal_report_task_relationship: zod- .string()- .max(tasksPartialUpdateBodySignalReportTaskRelationshipMax)- .optional()- .describe(- "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."- ),- json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),- archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),- ci_prompt: zod- .string()- .nullish()- .describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),- branch: zod- .string()- .max(tasksPartialUpdateBodyBranchMax)- .nullish()- .describe(- 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'- ),- runtime_adapter: zod- .union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])- .optional()- .describe(- "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"- ),- model: zod- .string()- .nullish()- .describe(- 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'- ),- reasoning_effort: zod- .union([- zod- .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])- .describe(- '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'- ),- zod.null(),- ])- .optional()- .describe(- 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'- ),- initial_permission_mode: zod- .union([- zod- .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto', 'read-only', 'full-access'])- .describe(- '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'- ),- zod.null(),- ])- .optional()- .describe(- 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'- ),- pending_user_message: zod- .string()- .nullish()- .describe(- 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'- ),- pending_user_artifact_ids: zod- .array(zod.string().max(tasksPartialUpdateBodyPendingUserArtifactIdsItemMax))- .optional()- .describe(- "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."- ),- auto_publish: zod- .boolean()- .nullish()- .describe(- "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."- ),- channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),- })- .describe(- 'Request body for creating or updating a task.\n\nField required\/default semantics match the ``Task`` model. The view passes\n``validated_data`` (integration\/report PK fields already resolved to instances) to the\nfacade ``create_task`` \/ ``update_task`` functions.'- )+export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({+ title: zod+ .string()+ .max(tasksPartialUpdateBodyTitleMax)+ .optional()+ .describe('Short human-readable title. Auto-generated from `description` when omitted.'),+ title_manually_set: zod+ .boolean()+ .optional()+ .describe('Whether the title was set by a human (vs auto-generated from the description).'),+ description: zod+ .string()+ .optional()+ .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),+ origin_product: zod+ .enum([+ 'onboarding',+ 'error_tracking',+ 'eval_clusters',+ 'user_created',+ 'slack',+ 'support_queue',+ 'session_summaries',+ 'posthog_ai',+ 'experiments',+ 'signal_report',+ 'signals_scout',+ 'scout_suggestions',+ 'support_reply',+ 'hogdesk',+ 'review_hog',+ 'image_builder',+ 'loop',+ 'mcp_analytics',+ 'signals_chat',+ 'task_analysis',+ 'workflow',+ ])+ .describe(+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ )+ .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\* `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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ ),+ repository: zod+ .string()+ .max(tasksPartialUpdateBodyRepositoryMax)+ .nullish()+ .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),+ repositories: zod+ .array(zod.string().max(tasksPartialUpdateBodyRepositoriesItemMax))+ .max(tasksPartialUpdateBodyRepositoriesMax)+ .optional()+ .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),+ github_integration: zod.number().nullish().describe('GitHub integration for this task.'),+ github_user_integration: zod+ .uuid()+ .nullish()+ .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),+ signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),+ signal_report_task_relationship: zod+ .string()+ .max(tasksPartialUpdateBodySignalReportTaskRelationshipMax)+ .optional()+ .describe(+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."+ ),+ json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),+ archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),+ ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),+ branch: zod+ .string()+ .max(tasksPartialUpdateBodyBranchMax)+ .nullish()+ .describe(+ 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'+ ),+ runtime_adapter: zod+ .union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])+ .optional()+ .describe(+ "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"+ ),+ model: zod+ .string()+ .nullish()+ .describe(+ 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'+ ),+ reasoning_effort: zod+ .union([+ zod+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])+ .describe(+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ ),+ initial_permission_mode: zod+ .union([+ zod+ .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto', 'read-only', 'full-access'])+ .describe(+ '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'+ ),+ pending_user_message: zod+ .string()+ .nullish()+ .describe(+ 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'+ ),+ pending_user_artifact_ids: zod+ .array(zod.string().max(tasksPartialUpdateBodyPendingUserArtifactIdsItemMax))+ .optional()+ .describe(+ "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."+ ),+ auto_publish: zod+ .boolean()+ .nullish()+ .describe(+ "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."+ ),+ channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),+})/*** Transfer ownership of a task to another member of the project: they take over driving it (steering, archiving, running), and future runs resolve GitHub authorship and notification recipients from them. Only the task's current owner can hand it off. Every run must be finished or canceled, and every sandbox must be shut down first. A task in a private space moves into the recipient's private space; a task in a shared space stays there.diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex 1f0cc910201e..1e1f46f8001e 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -21,12 +21,14 @@ tools:annotations:readOnly: falsedestructive: false- idempotent: true- title: Resolve or create a channel+ idempotent: false+ title: Create a channeldescription: >- Resolve-or-create a public channel by name (normalized to lowercase-dashed). Idempotent: returns the- existing channel when one with the name already exists. Use channel-list first when the request names an- existing channel.+ Create a channel. The default `channel_type` is public. Public names use lowercase letters and hyphens. If a+ public channel has that name, return it. Use channel-list to find an existing channel's ID. Set+ `channel_type` to "private" to create a private channel with the requester and the users in `member_ids`.+ Users in `member_ids` must have project access. Private channels always get a new ID, so a retry creates+ another channel.channel-instructions-retrieve:operation: task_channels_instructions_retrieveenabled: true@@ -82,10 +84,10 @@ tools:idempotent: truetitle: List channelsdescription: >- List the project's channels (public channels plus the requester's personal #me channel). Use this to resolve- a channel id from its name before creating or listing canvases or reading instructions. A project can hold- hundreds of channels, so pass `limit` (with `offset`) to read one page: the paged response carries `count`- and `next`, and without `limit` you get every channel in one array.+ List channels the requester can access: public channels, their personal #me channel, and private channels+ they belong to. Use a channel ID to create or list canvases or read instructions. Private channels can have+ the same name, so identify them by ID. Send `limit` and `offset` to get a page with `count`, `next`,+ `previous`, and `results`. Without `limit`, the response is an array of all accessible channels.channel-retrieve:operation: task_channels_retrieveenabled: true@@ -352,6 +354,12 @@ tools:task-channels-instructions-versions-retrieve:operation: task_channels_instructions_versions_retrieveenabled: false+ task-channels-members-retrieve:+ operation: task_channels_members_retrieve+ enabled: false+ task-channels-members-update:+ operation: task_channels_members_update+ enabled: falsetask-channels-onboarding-session-create:operation: task_channels_onboarding_session_createenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 50243512ba37..d81e67b815f8 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1639,15 +1639,15 @@"feature_entitlement": "approvals"},"channel-create": {- "description": "Resolve-or-create a public channel by name (normalized to lowercase-dashed). Idempotent: returns the existing channel when one with the name already exists. Use channel-list first when the request names an existing channel.",+ "description": "Create a channel. The default `channel_type` is public. Public names use lowercase letters and hyphens. If a public channel has that name, return it. Use channel-list to find an existing channel's ID. Set `channel_type` to \"private\" to create a private channel with the requester and the users in `member_ids`. Users in `member_ids` must have project access. Private channels always get a new ID, so a retry creates another channel.","category": "Tasks","feature": "tasks",- "summary": "Resolve or create a channel",- "title": "Resolve or create a channel",+ "summary": "Create a channel",+ "title": "Create a channel","required_scopes": ["task:write"],"annotations": {"destructiveHint": false,- "idempotentHint": true,+ "idempotentHint": false,"openWorldHint": true,"readOnlyHint": false}@@ -1687,7 +1687,7 @@"superseded_by": ["context-wiki-page-update"]},"channel-list": {- "description": "List the project's channels (public channels plus the requester's personal #me channel). Use this to resolve a channel id from its name before creating or listing canvases or reading instructions. A project can hold hundreds of channels, so pass `limit` (with `offset`) to read one page: the paged response carries `count` and `next`, and without `limit` you get every channel in one array.",+ "description": "List channels the requester can access: public channels, their personal #me channel, and private channels they belong to. Use a channel ID to create or list canvases or read instructions. Private channels can have the same name, so identify them by ID. Send `limit` and `offset` to get a page with `count`, `next`, `previous`, and `results`. Without `limit`, the response is an array of all accessible channels.","category": "Tasks","feature": "tasks","summary": "List channels",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 6b15b72cb34e..ac914f68b114 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1654,15 +1654,15 @@"feature_entitlement": "approvals"},"channel-create": {- "description": "Resolve-or-create a public channel by name (normalized to lowercase-dashed). Idempotent: returns the existing channel when one with the name already exists. Use channel-list first when the request names an existing channel.",+ "description": "Create a channel. The default `channel_type` is public. Public names use lowercase letters and hyphens. If a public channel has that name, return it. Use channel-list to find an existing channel's ID. Set `channel_type` to \"private\" to create a private channel with the requester and the users in `member_ids`. Users in `member_ids` must have project access. Private channels always get a new ID, so a retry creates another channel.","category": "Tasks","feature": "tasks",- "summary": "Resolve or create a channel",- "title": "Resolve or create a channel",+ "summary": "Create a channel",+ "title": "Create a channel","required_scopes": ["task:write"],"annotations": {"destructiveHint": false,- "idempotentHint": true,+ "idempotentHint": false,"openWorldHint": true,"readOnlyHint": false}@@ -1702,7 +1702,7 @@"superseded_by": ["context-wiki-page-update"]},"channel-list": {- "description": "List the project's channels (public channels plus the requester's personal #me channel). Use this to resolve a channel id from its name before creating or listing canvases or reading instructions. A project can hold hundreds of channels, so pass `limit` (with `offset`) to read one page: the paged response carries `count` and `next`, and without `limit` you get every channel in one array.",+ "description": "List channels the requester can access: public channels, their personal #me channel, and private channels they belong to. Use a channel ID to create or list canvases or read instructions. Private channels can have the same name, so identify them by ID. Send `limit` and `offset` to get a page with `count`, `next`, `previous`, and `results`. Without `limit`, the response is an array of all accessible channels.","category": "Tasks","feature": "tasks","summary": "List channels",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6d90774ba62b..19c227e6d7fa 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17171,6 +17171,14 @@ export namespace Schemas {base_version?: number | null;}+ export interface ChannelMembersWrite {+ /**+ * Required list of member user IDs. This list replaces the current members. The creator remains a member. Send an empty list to remove all other members. Each submitted user must have project access.+ * @maxItems 100+ */+ user_ids: number[];+ }+/*** Request body for starring/unstarring a channel for the requesting user.*/@@ -17199,15 +17207,34 @@ export namespace Schemas {}/**- * Request body for creating (resolve-or-create) or renaming a public channel.+ * * `public` - public+ * * `private` - private*/+ export type TaskChannelWriteTypeEnum = typeof TaskChannelWriteTypeEnum[keyof typeof TaskChannelWriteTypeEnum];+++ export const TaskChannelWriteTypeEnum = {+ Public: 'public',+ Private: 'private',+ } as const;+export interface ChannelWrite {/**- * Channel name, rendered as #<name>. Normalized to lowercase-dashed.+ * Channel name, shown as #<name>. Uses lowercase letters and hyphens.* @maxLength 128*/name: string;- /** Star the channel for the requester when this call creates it. Ignored when the channel already exists, which leaves existing stars untouched. */+ /** Use 'public' for access by all project members. Use 'private' for access by channel members only. Defaults to 'public'. This endpoint cannot create personal #me spaces.+ *+ * * `public` - public+ * * `private` - private */+ channel_type?: TaskChannelWriteTypeEnum;+ /**+ * User IDs to add to a private channel. The requester is always a member. The endpoint ignores this field for public channels and skips users without project access.+ * @maxItems 100+ */+ member_ids?: number[];+ /** Star a new channel for the requester. This field does not change stars on an existing channel. */star?: boolean;}@@ -61697,6 +61724,11 @@ export namespace Schemas {* @nullable*/auto_archive_after_days?: number | null;+ /** Switch a shared space between 'public' and 'private'. Making a space private keeps only the creator and the requester as members. Making it public removes its member list. Personal #me spaces cannot change.+ *+ * * `public` - public+ * * `private` - private */+ channel_type?: TaskChannelWriteTypeEnum;}export type PatchedClusteringJobEventFiltersItem = { [key: string]: unknown };@@ -68587,13 +68619,6 @@ export namespace Schemas {FullAccess: 'full-access',} as const;- /**- * Request body for creating or updating a task.- *- * Field required/default semantics match the ``Task`` model. The view passes- * ``validated_data`` (integration/report PK fields already resolved to instances) to the- * facade ``create_task`` / ``update_task`` functions.- */export interface PatchedTaskWrite {/*** Short human-readable title. Auto-generated from `description` when omitted.@@ -85278,13 +85303,6 @@ export namespace Schemas {next: string | null;}- /**- * Request body for creating or updating a task.- *- * Field required/default semantics match the ``Task`` model. The view passes- * ``validated_data`` (integration/report PK fields already resolved to instances) to the- * facade ``create_task`` / ``update_task`` functions.- */export interface TaskCreate {/*** Short human-readable title. Auto-generated from `description` when omitted.@@ -86683,13 +86701,6 @@ export namespace Schemas {total_cost_usd: number;}- /**- * Request body for creating or updating a task.- *- * Field required/default semantics match the ``Task`` model. The view passes- * ``validated_data`` (integration/report PK fields already resolved to instances) to the- * facade ``create_task`` / ``update_task`` functions.- */export interface TaskWrite {/*** Short human-readable title. Auto-generated from `description` when omitted.diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 7a71f6c6f868..b4eccfc350f6 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -735,7 +735,7 @@ export const LoopsRunsRetrieveQueryParams = () => zod.object({})/**- * All live public channels plus the requester's personal #me channel when it exists, sorted by name. Listing does not provision; call provision_defaults to create the default channels. Send `limit` (with `offset`) for one page and a `count`/`next` envelope; without `limit` the response is the full array of channels.+ * List channels the requester can access, sorted by name and ID. Includes public channels, their personal #me channel, and private channels they belong to. Call provision_defaults to create missing default channels. Send limit and offset to get a page with count, next, previous, and results. Without limit, the response is an array of all accessible channels.* @summary List channels*/export const TaskChannelsListParams = () => zod.object({@@ -752,8 +752,8 @@ export const TaskChannelsListQueryParams = () => zod.object({})/**- * Returns the existing public channel with the (normalized) name, creating it if needed. A channel created here is starred for the requester unless star is false. The general name returns the team's general space; names that read as a private space ("me", "personal") are rejected.- * @summary Resolve or create a public channel+ * Create a channel. Public channels use lowercase names with hyphens. If a public channel has that name, return it. The name general returns the project's general space. Private channels always get a new ID, even if another channel has the same name. The requester and users in member_ids with project access become members. New channels are starred for the requester unless star is false. The names "me" and "personal" are reserved.+ * @summary Create a channel*/export const TaskChannelsCreateParams = () => zod.object({project_id: zod@@ -765,28 +765,37 @@ export const TaskChannelsCreateParams = () => zod.object({export const taskChannelsCreateBodyNameMax = 128+export const taskChannelsCreateBodyChannelTypeDefault = `public`+export const taskChannelsCreateBodyMemberIdsMax = 100+export const taskChannelsCreateBodyStarDefault = true-export const TaskChannelsCreateBody = () => zod- .object({- name: zod- .string()- .max(taskChannelsCreateBodyNameMax)- .describe('Channel name, rendered as #<name>. Normalized to lowercase-dashed.'),- star: zod- .boolean()- .default(taskChannelsCreateBodyStarDefault)- .describe(- 'Star the channel for the requester when this call creates it. Ignored when the channel already exists, which leaves existing stars untouched.'- ),- })- .describe('Request body for creating (resolve-or-create) or renaming a public channel.')+export const TaskChannelsCreateBody = () => zod.object({+ name: zod+ .string()+ .max(taskChannelsCreateBodyNameMax)+ .describe('Channel name, shown as #<name>. Uses lowercase letters and hyphens.'),+ channel_type: zod+ .enum(['public', 'private'])+ .describe('\* `public` - public\n\* `private` - private')+ .default(taskChannelsCreateBodyChannelTypeDefault)+ .describe(+ "Use 'public' for access by all project members. Use 'private' for access by channel members only. Defaults to 'public'. This endpoint cannot create personal #me spaces.\n\n\* `public` - public\n\* `private` - private"+ ),+ member_ids: zod+ .array(zod.number())+ .max(taskChannelsCreateBodyMemberIdsMax)+ .optional()+ .describe(+ 'User IDs to add to a private channel. The requester is always a member. The endpoint ignores this field for public channels and skips users without project access.'+ ),+ star: zod+ .boolean()+ .default(taskChannelsCreateBodyStarDefault)+ .describe('Star a new channel for the requester. This field does not change stars on an existing channel.'),+})/**- * API for task channels — the shared feeds tasks are kicked off in. The- * provision_defaults action get-or-creates the requester's personal "#me" channel and- * the team's shared "#general" channel; creation is resolve-or-create by normalized- * name so clients can map channel-like surfaces onto backend channels.* @summary Get a channel*/export const TaskChannelsRetrieveParams = () => zod.object({@@ -996,180 +1005,170 @@ export const tasksCreateBodyPendingUserArtifactIdsItemMax = 128export const tasksCreateBodySignalReportDiscussionQuestionMax = 4000-export const TasksCreateBody = () => zod- .object({- title: zod- .string()- .max(tasksCreateBodyTitleMax)- .optional()- .describe('Short human-readable title. Auto-generated from `description` when omitted.'),- title_manually_set: zod- .boolean()- .optional()- .describe('Whether the title was set by a human (vs auto-generated from the description).'),- description: zod- .string()- .optional()- .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),- origin_product: zod- .enum([- 'onboarding',- 'error_tracking',- 'eval_clusters',- 'user_created',- 'slack',- 'support_queue',- 'session_summaries',- 'posthog_ai',- 'experiments',- 'signal_report',- 'signals_scout',- 'scout_suggestions',- 'support_reply',- 'hogdesk',- 'review_hog',- 'image_builder',- 'loop',- 'mcp_analytics',- 'signals_chat',- 'task_analysis',- 'workflow',- ])- .describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'- )- .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\* `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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'- ),- repository: zod- .string()- .max(tasksCreateBodyRepositoryMax)- .nullish()- .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),- repositories: zod- .array(zod.string().max(tasksCreateBodyRepositoriesItemMax))- .max(tasksCreateBodyRepositoriesMax)- .optional()- .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),- github_integration: zod.number().nullish().describe('GitHub integration for this task.'),- github_user_integration: zod- .string()- .nullish()- .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),- signal_report: zod- .string()- .nullish()- .describe('Signal report this task implements, when created from a report.'),- signal_report_task_relationship: zod- .string()- .max(tasksCreateBodySignalReportTaskRelationshipMax)- .optional()- .describe(- "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."- ),- json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),- archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),- ci_prompt: zod- .string()- .nullish()- .describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),- branch: zod- .string()- .max(tasksCreateBodyBranchMax)- .nullish()- .describe(- 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'- ),- runtime_adapter: zod- .union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])- .optional()- .describe(- "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"- ),- model: zod- .string()- .nullish()- .describe(- 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'- ),- reasoning_effort: zod- .union([- zod- .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])- .describe(- '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'- ),- zod.null(),- ])- .optional()- .describe(- 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'- ),- initial_permission_mode: zod- .union([- zod- .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto', 'read-only', 'full-access'])- .describe(- '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'- ),- zod.null(),- ])- .optional()- .describe(- 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'- ),- pending_user_message: zod- .string()- .nullish()- .describe(- 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'- ),- pending_user_artifact_ids: zod- .array(zod.string().max(tasksCreateBodyPendingUserArtifactIdsItemMax))- .optional()- .describe(- "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."- ),- auto_publish: zod- .boolean()- .nullish()- .describe(- "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."- ),- channel: zod.string().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),- signal_report_discussion_question: zod- .string()- .max(tasksCreateBodySignalReportDiscussionQuestionMax)- .optional()- .describe(- "Question to forward to the signal report's scout when creating a discussion task. Send an empty string when there is no question. Omit only for older clients that embed the question in the task description. Not persisted on the task."- ),- naming_source: zod- .string()- .optional()- .describe(- 'Text the server generates the title from instead of `description`. Lets a client whose `description` is only an attachment summary (e.g. pasted text stored as a file) supply the real content for naming, so `description` (the prompt passed to the agent) stays unchanged. Not persisted.'- ),- sandbox_environment_id: zod- .string()- .nullish()- .describe('Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.'),- custom_image_id: zod- .string()- .nullish()- .describe('Custom image selected for matching a pre-warmed cloud run. Not persisted on the task.'),- runtime: zod- .enum(['acp', 'pi'])- .describe('\* `acp` - ACP\n\* `pi` - Pi')- .optional()- .describe(- "Agent protocol and harness used for this task's runs. Defaults to ACP when omitted.\n\n\* `acp` - ACP\n\* `pi` - Pi"- ),- })- .describe(- 'Request body for creating or updating a task.\n\nField required\/default semantics match the ``Task`` model. The view passes\n``validated_data`` (integration\/report PK fields already resolved to instances) to the\nfacade ``create_task`` \/ ``update_task`` functions.'- )+export const TasksCreateBody = () => zod.object({+ title: zod+ .string()+ .max(tasksCreateBodyTitleMax)+ .optional()+ .describe('Short human-readable title. Auto-generated from `description` when omitted.'),+ title_manually_set: zod+ .boolean()+ .optional()+ .describe('Whether the title was set by a human (vs auto-generated from the description).'),+ description: zod+ .string()+ .optional()+ .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),+ origin_product: zod+ .enum([+ 'onboarding',+ 'error_tracking',+ 'eval_clusters',+ 'user_created',+ 'slack',+ 'support_queue',+ 'session_summaries',+ 'posthog_ai',+ 'experiments',+ 'signal_report',+ 'signals_scout',+ 'scout_suggestions',+ 'support_reply',+ 'hogdesk',+ 'review_hog',+ 'image_builder',+ 'loop',+ 'mcp_analytics',+ 'signals_chat',+ 'task_analysis',+ 'workflow',+ ])+ .describe(+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ )+ .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\* `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\* `scout_suggestions` - Signals Scout Suggestions\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\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ ),+ repository: zod+ .string()+ .max(tasksCreateBodyRepositoryMax)+ .nullish()+ .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),+ repositories: zod+ .array(zod.string().max(tasksCreateBodyRepositoriesItemMax))+ .max(tasksCreateBodyRepositoriesMax)+ .optional()+ .describe('GitHub repositories available to this task, each in `organization\/repo` format.'),+ github_integration: zod.number().nullish().describe('GitHub integration for this task.'),+ github_user_integration: zod+ .string()+ .nullish()+ .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),+ signal_report: zod.string().nullish().describe('Signal report this task implements, when created from a report.'),+ signal_report_task_relationship: zod+ .string()+ .max(tasksCreateBodySignalReportTaskRelationshipMax)+ .optional()+ .describe(+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted except labels reserved for server-created tasks ('research', 'repo_selection', 'scout'). Non-implementation labels count toward the report's discussion task limit."+ ),+ json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),+ archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),+ ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),+ branch: zod+ .string()+ .max(tasksCreateBodyBranchMax)+ .nullish()+ .describe(+ 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'+ ),+ runtime_adapter: zod+ .union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])+ .optional()+ .describe(+ "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"+ ),+ model: zod+ .string()+ .nullish()+ .describe(+ 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'+ ),+ reasoning_effort: zod+ .union([+ zod+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])+ .describe(+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ ),+ initial_permission_mode: zod+ .union([+ zod+ .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto', 'read-only', 'full-access'])+ .describe(+ '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'+ ),+ pending_user_message: zod+ .string()+ .nullish()+ .describe(+ 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'+ ),+ pending_user_artifact_ids: zod+ .array(zod.string().max(tasksCreateBodyPendingUserArtifactIdsItemMax))+ .optional()+ .describe(+ "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."+ ),+ auto_publish: zod+ .boolean()+ .nullish()+ .describe(+ "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."+ ),+ channel: zod.string().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),+ signal_report_discussion_question: zod+ .string()+ .max(tasksCreateBodySignalReportDiscussionQuestionMax)+ .optional()+ .describe(+ "Question to forward to the signal report's scout when creating a discussion task. Send an empty string when there is no question. Omit only for older clients that embed the question in the task description. Not persisted on the task."+ ),+ naming_source: zod+ .string()+ .optional()+ .describe(+ 'Text the server generates the title from instead of `description`. Lets a client whose `description` is only an attachment summary (e.g. pasted text stored as a file) supply the real content for naming, so `description` (the prompt passed to the agent) stays unchanged. Not persisted.'+ ),+ sandbox_environment_id: zod+ .string()+ .nullish()+ .describe('Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.'),+ custom_image_id: zod+ .string()+ .nullish()+ .describe('Custom image selected for matching a pre-warmed cloud run. Not persisted on the task.'),+ runtime: zod+ .enum(['acp', 'pi'])+ .describe('\* `acp` - ACP\n\* `pi` - Pi')+ .optional()+ .describe(+ "Agent protocol and harness used for this task's runs. Defaults to ACP when omitted.\n\n\* `acp` - ACP\n\* `pi` - Pi"+ ),+})/*** Retrieve a single task by ID.diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.tsindex f4cb28dff0c8..ff57e3ab0061 100644--- a/services/mcp/src/tools/generated/tasks.ts+++ b/services/mcp/src/tools/generated/tasks.ts@@ -27,6 +27,12 @@ const channelCreate = (): ToolBase<ReturnType<typeof ChannelCreateSchema>, Schemif (params.name !== undefined) {body['name'] = params.name}+ if (params.channel_type !== undefined) {+ body['channel_type'] = params.channel_type+ }+ if (params.member_ids !== undefined) {+ body['member_ids'] = params.member_ids+ }if (params.star !== undefined) {body['star'] = params.star}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/channel-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/channel-create.jsonindex e3e5f789af50..03ca69d1ef06 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/channel-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/channel-create.json@@ -1,15 +1,28 @@{"$schema": "https://json-schema.org/draft/2020-12/schema",- "description": "Request body for creating (resolve-or-create) or renaming a public channel.","properties": {+ "channel_type": {+ "default": "public",+ "description": "Use 'public' for access by all project members. Use 'private' for access by channel members only. Defaults to 'public'. This endpoint cannot create personal #me spaces.\n\n* `public` - public\n* `private` - private",+ "enum": ["public", "private"],+ "type": "string"+ },+ "member_ids": {+ "description": "User IDs to add to a private channel. The requester is always a member. The endpoint ignores this field for public channels and skips users without project access.",+ "items": {+ "type": "number"+ },+ "maxItems": 100,+ "type": "array"+ },"name": {- "description": "Channel name, rendered as #<name>. Normalized to lowercase-dashed.",+ "description": "Channel name, shown as #<name>. Uses lowercase letters and hyphens.","maxLength": 128,"type": "string"},"star": {"default": true,- "description": "Star the channel for the requester when this call creates it. Ignored when the channel already exists, which leaves existing stars untouched.",+ "description": "Star a new channel for the requester. This field does not change stars on an existing channel.","type": "boolean"}},