Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tasks): hand off a task to a colleague (#84532)

Shy Alter602eae847a0e
diff --git a/products/posthog_ai/backend/message_routing.py b/products/posthog_ai/backend/message_routing.py
index 1ac5ec8c5e1f..d10ac947dab2 100644
--- a/products/posthog_ai/backend/message_routing.py
+++ b/products/posthog_ai/backend/message_routing.py
@@ -34,6 +34,7 @@ from products.posthog_ai.backend.helpers import BaseSandboxService
from products.posthog_ai.backend.models.assistant import Conversation
from products.posthog_ai.backend.run_state import PostHogAIRunState
from products.posthog_ai.backend.services.system_prompt.service import PromptService
+from products.posthog_ai.backend.task_ownership import detach_conversations_for_task_handoff
from products.posthog_ai.backend.wire_types import UnknownFrame, is_user_message_params, parse_log_entry
from products.tasks.backend.facade import (
api as tasks_facade,
@@ -126,6 +127,14 @@ class SandboxSession(BaseSandboxService):
convert_to_acp: bool = False,
repository: str | None = None,
) -> SandboxRouteResult | None:
+ task = self.conversation.task
+ if task is not None and (task.created_by_id != self.conversation.user_id or task.created_by_id != self.user.id):
+ detach_conversations_for_task_handoff(task.id, task.created_by_id)
+ self.conversation.task = None
+ self.conversation.sandbox_task_id = None
+ self.conversation.sandbox_run_id = None
+ raise exceptions.PermissionDenied("This task belongs to another user. Start a new conversation.")
+
initial_permission_mode = self._initial_permission_mode(data.get("initial_permission_mode"))
content = data.get("content")
if not isinstance(content, str) or not content.strip():
diff --git a/products/posthog_ai/backend/task_ownership.py b/products/posthog_ai/backend/task_ownership.py
new file mode 100644
index 000000000000..dc6e81419a6b
--- /dev/null
+++ b/products/posthog_ai/backend/task_ownership.py
@@ -0,0 +1,13 @@
+from uuid import UUID
+
+from django.db.models import Q
+
+from products.posthog_ai.backend.models.assistant import Conversation
+
+
+def detach_conversations_for_task_handoff(task_id: UUID, new_owner_id: int | None) -> int:
+ """Detach conversations that must remain private to a previous task owner."""
+ conversations = Conversation.objects.filter(Q(task_id=task_id) | Q(sandbox_task_id=task_id))
+ if new_owner_id is not None:
+ conversations = conversations.exclude(user_id=new_owner_id)
+ return conversations.update(task=None, sandbox_task_id=None, sandbox_run_id=None)
diff --git a/products/posthog_ai/backend/tests/test_message_routing.py b/products/posthog_ai/backend/tests/test_message_routing.py
index 3a5b74a84a3f..ca10d0a3422e 100644
--- a/products/posthog_ai/backend/tests/test_message_routing.py
+++ b/products/posthog_ai/backend/tests/test_message_routing.py
@@ -1,11 +1,13 @@
from contextlib import contextmanager
+import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from rest_framework import exceptions
from posthog.exceptions import Conflict, QuotaLimitExceeded
+from posthog.models.user import User
from products.posthog_ai.backend.context_wrapper import MAX_ATTACHED_ITEMS, MAX_TEXT_LENGTH
from products.posthog_ai.backend.message_routing import (
@@ -102,6 +104,31 @@ class TestOpenSandboxMessage(APIBaseTest):
# The agent needs write scopes to create insights/dashboards/notebooks.
assert wf_kwargs["posthog_mcp_scopes"] == "full"
+ def test_handoff_detaches_previous_owner_conversation(self):
+ new_owner = User.objects.create_user(
+ first_name="New owner",
+ password="password",
+ )
+ task = Task.objects.create(
+ team=self.team,
+ title="Transferred task",
+ created_by=new_owner,
+ origin_product=Task.OriginProduct.POSTHOG_AI,
+ )
+ self.conversation.task = task
+ self.conversation.sandbox_task_id = task.id
+ self.conversation.sandbox_run_id = task.id
+ self.conversation.save(update_fields=["task", "sandbox_task_id", "sandbox_run_id"])
+
+ with pytest.raises(exceptions.PermissionDenied):
+ self._service().open({"content": "Keep going"})
+
+ self.conversation.refresh_from_db()
+ self.assertIsNone(self.conversation.task_id)
+ self.assertIsNone(self.conversation.sandbox_task_id)
+ self.assertIsNone(self.conversation.sandbox_run_id)
+
def test_first_message_threads_routed_repository(self):
task, _ = self._stub_task()
car, workflow, sysprompt = self._patches(task)
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index de70c18dc1f4..34428707f14a 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -58,8 +58,10 @@ from posthog.dataclasses import frozen
from posthog.event_usage import groups
from posthog.models import Team, User
from posthog.models.integration import Integration
+from posthog.models.oauth import OAuthAccessToken, OAuthRefreshToken
from posthog.utils import absolute_uri
+from products.posthog_ai.backend.task_ownership import detach_conversations_for_task_handoff
from products.tasks.backend.constants import (
AGENT_OTEL_TELEMETRY_STATE_KEY,
AGENT_PEER_MESSAGING_FEATURE_FLAG,
@@ -89,6 +91,8 @@ from products.tasks.backend.logic.services.network_policy import (
)
from products.tasks.backend.mentions import resolve_mentioned_user_ids
from products.tasks.backend.models import (
+ MCP_CREDENTIAL_OWNER_STATE_KEY,
+ TASK_OWNERSHIP_VERSION_STATE_KEY,
Channel,
ChannelContextGeneration,
ChannelFeedMessage,
@@ -106,6 +110,7 @@ from products.tasks.backend.models import (
TaskArtifact,
TaskClientProvenance,
TaskCommentActivity,
+ TaskOwnershipChangedError,
TaskPin,
TaskRun,
TaskSearchDocument,
@@ -275,6 +280,7 @@ __all__ = [
"task_ids_with_pr_url_subquery",
"task_run_has_slack_mapping",
"task_run_is_terminal",
+ "task_run_matches_current_ownership",
"task_runtime",
"task_visible",
"visible_tasks_q",
@@ -2121,6 +2127,7 @@ def delete_sandbox_custom_image(image_id: str | UUID, team_id: int, user_id: int
_PROTECTED_RUN_STATE_KEYS = frozenset(
{
"github_credential_source",
+ TASK_OWNERSHIP_VERSION_STATE_KEY,
"pr_authorship_mode",
"repositories",
"verified_pr_urls",
@@ -2262,6 +2269,14 @@ def task_run_exists(run_id: str | UUID, task_id: str | UUID, team_id: int) -> bo
return False
+def task_run_matches_current_ownership(run_id: str | UUID, task_id: str | UUID, team_id: int) -> bool:
+ try:
+ run = _task_run_queryset().filter(pk=run_id, team_id=team_id, task_id=task_id).first()
+ except (ValueError, TypeError, DjangoValidationError):
+ return False
+ return run is not None and run.matches_task_ownership()
+
+
def task_accessible_for_run_view(
task_id: str | UUID,
team_id: int,
@@ -4123,7 +4138,6 @@ def bootstrap_task_run(
task = _get_task_for_run_control(task_id, team_id, user_id)
if task is None:
return None
-
mode = validated_data.get("mode", "background")
environment = validated_data.get("environment", TaskRun.Environment.LOCAL)
branch = validated_data.get("branch")
@@ -4238,7 +4252,10 @@ def bootstrap_task_run(
logger.info(
"Creating task run for task %s with mode=%s, branch=%s, environment=%s", task.id, mode, branch, environment
)
- run = task.create_run(environment=environment, mode=mode, branch=branch, extra_state=extra_state)
+ try:
+ run = task.create_run(environment=environment, mode=mode, branch=branch, extra_state=extra_state)
+ except TaskOwnershipChangedError:
+ return None
if imported_mcp_servers or relayed_mcp_servers:
update_fields = ["updated_at"]
@@ -4363,12 +4380,14 @@ def start_task_run(
previous_state = dict(run.state or {})
try:
with transaction.atomic():
+ task = Task.objects.select_for_update().get(id=task_id, team_id=team_id)
run = (
TaskRun.objects.select_for_update(of=("self",))
.select_related("task", "task__team", "task__created_by")
- .get(id=run.id)
+ .get(id=run.id, task_id=task.id, team_id=team_id)
)
- task = run.task
+ if not run.matches_task_ownership(task):
+ return "ownership_changed", None
if state_updates:
TaskRun.update_state_atomic(run.id, updates=state_updates)
run.refresh_from_db()
@@ -4401,8 +4420,9 @@ def resume_task_run_in_cloud(
"""Resume a run in a cloud sandbox, terminating any prior workflow.
Returns ``(outcome, run_dto, debug_use_modal)``. ``outcome`` is one of: ``"not_found"``,
- ``"already_active"`` (400), ``"auth_error:<detail>"`` (400, github auth), ``"workflow_failed"``
- (502), or ``"resumed"`` (run_dto set). Mirrors ``TaskRunViewSet.resume_in_cloud``.
+ ``"already_active"`` (400), ``"ownership_changed"`` (400), ``"auth_error:<detail>"``
+ (400, GitHub auth), ``"workflow_failed"`` (502), or ``"resumed"`` (run_dto set).
+ Mirrors ``TaskRunViewSet.resume_in_cloud``.
"""
from products.tasks.backend.facade.streams import reset_task_run_stream # noqa: PLC0415
from products.tasks.backend.redis import run_uses_dedicated_stream # noqa: PLC0415
@@ -4445,11 +4465,14 @@ def resume_task_run_in_cloud(
)
with transaction.atomic():
+ task = Task.objects.select_for_update().get(id=task_id, team_id=team_id)
run = (
TaskRun.objects.select_for_update(of=("self",))
.select_related("task", "task__created_by", "task__github_integration", "task__github_user_integration")
- .get(pk=run.pk)
+ .get(pk=run.pk, task_id=task.id, team_id=team_id)
)
+ if not run.matches_task_ownership(task):
+ return "ownership_changed", None, None
is_cloud_active = run.environment == TaskRun.Environment.CLOUD and run.status in (
TaskRun.Status.QUEUED,
@@ -5295,52 +5318,209 @@ def update_task(
task_id: str | UUID, team_id: int, user_id: int | None, *, validated_data: dict
) -> contracts.TaskDetailDTO | None:
"""Update a task, mirroring ``TaskSerializer.update``. ``None`` if not found/controllable."""
- task = _visible_task_qs(team_id, user_id, for_control=True).filter(id=task_id).first()
- if task is None:
- return None
-
validated_data = dict(validated_data)
# origin_product controls visibility and signal_report is set once.
validated_data.pop("signal_report", None)
validated_data.pop("signal_report_task_relationship", None)
validated_data.pop("origin_product", None)
validated_data.pop("branch", None)
- # Repo is immutable for code-access-exempt tasks; a mutable repo reopens the gate (see task_exempt_from_code_access).
- if task.origin_product in (Task.OriginProduct.SIGNALS_CHAT, Task.OriginProduct.SIGNAL_REPORT):
- validated_data.pop("repository", None)
- validated_data.pop("repositories", None)
- validated_data.pop("github_integration", None)
- validated_data.pop("github_user_integration", None)
- if "repositories" in validated_data:
- repositories = validated_data["repositories"]
- validated_data["repository"] = repositories[0] if repositories else None
- elif "repository" in validated_data:
- if len(task.repositories) <= 1:
- validated_data["repositories"] = [validated_data["repository"]] if validated_data["repository"] else []
- else:
- validated_data.pop("repository")
- if "title" in validated_data and "title_manually_set" not in validated_data:
- validated_data["title_manually_set"] = True
- if "archived" in validated_data and validated_data["archived"] != task.archived:
- validated_data["archived_at"] = django_timezone.now() if validated_data["archived"] else None
-
- logger.info("perform_update called for task %s with validated_data: %s", task.id, validated_data)
- for key, value in validated_data.items():
- setattr(task, key, value)
- task.save()
- logger.info("Task %s updated successfully", task.id)
+
+ with transaction.atomic():
+ task = Task.objects.select_for_update().filter(id=task_id, team_id=team_id, deleted=False).first()
+ if task is None or not Task.objects.filter(id=task.id).filter(task_control_q(user_id)).exists():
+ return None
+
+ # Repo is immutable for code-access-exempt tasks; a mutable repo reopens the gate (see task_exempt_from_code_access).
+ if task.origin_product in (Task.OriginProduct.SIGNALS_CHAT, Task.OriginProduct.SIGNAL_REPORT):
+ validated_data.pop("repository", None)
+ validated_data.pop("repositories", None)
+ validated_data.pop("github_integration", None)
+ validated_data.pop("github_user_integration", None)
+ if "repositories" in validated_data:
+ repositories = validated_data["repositories"]
+ validated_data["repository"] = repositories[0] if repositories else None
+ elif "repository" in validated_data:
+ if len(task.repositories) <= 1:
+ validated_data["repositories"] = [validated_data["repository"]] if validated_data["repository"] else []
+ else:
+ validated_data.pop("repository")
+ if "title" in validated_data and "title_manually_set" not in validated_data:
+ validated_data["title_manually_set"] = True
+ if "archived" in validated_data and validated_data["archived"] != task.archived:
+ validated_data["archived_at"] = django_timezone.now() if validated_data["archived"] else None
+
+ logger.info("perform_update called for task %s with validated_data: %s", task.id, validated_data)
+ for key, value in validated_data.items():
+ setattr(task, key, value)
+ task.save()
+ logger.info("Task %s updated successfully", task.id)
return _task_detail_to_dto(_task_detail_queryset().get(pk=task.pk))
def soft_delete_task(task_id: str | UUID, team_id: int, user_id: int | None) -> bool:
"""Soft-delete a task. Returns whether a task was found/controllable and deleted."""
+ with transaction.atomic():
+ task = Task.objects.select_for_update().filter(id=task_id, team_id=team_id, deleted=False).first()
+ if task is None or not Task.objects.filter(id=task.id).filter(task_control_q(user_id)).exists():
+ return False
+ logger.info("Soft deleting task %s", task.id)
+ task.soft_delete()
+ return True
+
+
+# --- Task handoff (transfer ownership to a colleague) ---
+
+
+class TaskHandoffError(Exception):
+ """A handoff request that reads as a client error rather than a missing task."""
+
+
+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 False
- logger.info("Soft deleting task %s", task.id)
- task.soft_delete()
- return True
+ return None
+ if user_id is None or task.created_by_id != user_id:
+ return None
+ if 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_id
+ actor = User.objects.filter(id=user_id).only("first_name", "email", "distinct_id").first() if user_id else None
+ actor_name = ((actor.first_name.strip() or actor.email) if actor else None) or "Someone"
+ target_name = target.first_name.strip() or target.email
+ with transaction.atomic():
+ locked = 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:
+ return None
+ if locked.created_by_id != previous_owner_id:
+ raise TaskHandoffError("Someone else has already handed this task off. Refresh and try again.")
+ if (
+ TaskRun.objects.filter(task_id=locked.id, team_id=team_id)
+ .exclude(status__in=[TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED])
+ .exists()
+ ):
+ raise TaskHandoffError("Finish or cancel active runs before handing off this task.")
+ if (
+ SandboxSession.objects.for_team(team_id)
+ .filter(
+ task_run__task_id=locked.id,
+ ended_at__isnull=True,
+ ttl_expires_at__gt=django_timezone.now(),
+ )
+ .exists()
+ ):
+ raise TaskHandoffError("Wait for active sandboxes to shut down before handing off this task.")
+
+ bound_tokens = OAuthAccessToken.objects.filter(sandbox_task_id=locked.id)
+ OAuthRefreshToken.objects.filter(access_token__in=bound_tokens).delete()
+ bound_tokens.delete()
+
+ detach_conversations_for_task_handoff(locked.id, target.id)
+
+ channel = locked.channel
+ if 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]
+ 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
+ }
+ locked.state[TASK_OWNERSHIP_VERSION_STATE_KEY] = str(uuid4())
+ locked.save()
+ message = TaskThreadMessage.objects.for_team(team_id).create(
+ team_id=team_id,
+ task_id=locked.id,
+ author_id=user_id,
+ author_kind=TaskThreadMessage.AuthorKind.SYSTEM,
+ event="task_handed_off",
+ 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,
+ },
+ content=f"{actor_name} handed this task off to {target_name}",
+ )
+
+ try:
+ project_thread_message_activity(message)
+ except Exception:
+ logger.exception("Failed to project handoff thread activity", extra={"task_id": str(task_id)})
+ from products.tasks.backend.push_dispatcher import (
+ notify_task_handoff, # noqa: PLC0415 — optional push dep stays off the import path
+ )
+
+ 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),
+ event="task_handed_off",
+ properties={
+ "task_id": str(locked.id),
+ "team_id": locked.team_id,
+ "title": locked.title,
+ "origin_product": locked.origin_product,
+ "repository": locked.repository,
+ "from_user_id": previous_owner_id,
+ "to_user_id": target.id,
+ },
+ groups=groups(team=locked.team),
+ send_feature_flags=True,
+ )
+ except Exception as e:
+ logger.warning("task_handed_off capture_event failed for task %s: %s", locked.id, e)
+
+ return _task_detail_to_dto(_task_detail_queryset().get(pk=locked.pk))
# --- Task staged artifacts (S3 + cache, attached to the next run) ---
@@ -5982,6 +6162,13 @@ def run_task(
return contracts.TaskRunResult(
error=contracts.TaskValidationError(kind="detail", detail="Invalid resume_from_run_id")
)
+ if not previous_run.matches_task_ownership(task):
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(
+ kind="detail",
+ detail="This run belongs to a previous task owner. Start a new run instead.",
+ )
+ )
prev_state = parse_run_state(previous_run.state)
extra_state = extra_state or {}
@@ -6163,18 +6350,15 @@ def run_task(
)
logger.info("Creating task run for task %s with mode=%s, branch=%s", task.id, mode, branch)
- with transaction.atomic():
- task_run = task.create_run(mode=mode, branch=branch, extra_state=extra_state)
- if report_id_for_slot_check is not None:
- # A live run is what marks the report's implementation slot taken, so the slot is only
- # really claimed once this row exists. Inserting first and locking the report second
- # keeps the row lock off `create_run`, which evaluates a feature flag, and still
- # serializes against a concurrent create: that create either takes the report lock
- # first, so this check sees the task it added and rolls the run back, or takes it
- # second, by which point this run is committed and its own count check refuses.
- enforce_report_implementation_rerun_cap(
- team_id=team_id, report_id=report_id_for_slot_check, task_id=str(task.id)
- )
+ try:
+ with transaction.atomic():
+ task_run = task.create_run(mode=mode, branch=branch, extra_state=extra_state)
+ if report_id_for_slot_check is not None:
+ enforce_report_implementation_rerun_cap(
+ team_id=team_id, report_id=report_id_for_slot_check, task_id=str(task.id)
+ )
+ except TaskOwnershipChangedError:
+ return None
if is_pi_task and resume_from_run_id:
task_run.active_task_session = previous_run.active_task_session
task_run.save(update_fields=["active_task_session", "updated_at"])
diff --git a/products/tasks/backend/max_tools.py b/products/tasks/backend/max_tools.py
index 57ebe077ce88..e4ada8eb0ec9 100644
--- a/products/tasks/backend/max_tools.py
+++ b/products/tasks/backend/max_tools.py
@@ -156,7 +156,8 @@ Use this tool when the user wants to:
@transaction.atomic
def get_task_and_create_run():
task = (
- Task.objects.filter(id=task_id, team=self._team, deleted=False)
+ Task.objects.select_for_update(of=("self",))
+ .filter(id=task_id, team=self._team, deleted=False)
.filter(task_control_q(self._user.id))
.first()
)
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index d39ebc458e6f..8977d46078a2 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -64,6 +64,7 @@ MCPBuiltInAgentKey = Literal["support", "scout"]
MCP_BUILT_IN_AGENT_STATE_KEY = "mcp_builtin_agent_key"
MCP_CREDENTIAL_OWNER_STATE_KEY = "mcp_credential_owner_id"
MCP_GATEWAY_SERVER_ALLOWLIST_STATE_KEY = "mcp_gateway_server_ids"
+TASK_OWNERSHIP_VERSION_STATE_KEY = "task_ownership_version"
MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN: dict[str, MCPBuiltInAgentKey] = {
"support_reply": "support",
"signals_scout": "scout",
@@ -76,6 +77,15 @@ def resolve_schema(schema: type[BaseModel] | dict) -> dict:
return schema.model_json_schema()
+def _task_ownership_version(state: dict | None) -> str | None:
+ value = (state or {}).get(TASK_OWNERSHIP_VERSION_STATE_KEY)
+ return value if isinstance(value, str) else None
+
+
+class TaskOwnershipChangedError(RuntimeError):
+ pass
+
+
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"
@@ -518,6 +528,10 @@ class Task(DeletedMetaFields, models.Model):
max_task_number = Task.objects.filter(team=self.team).aggregate(models.Max("task_number"))["task_number__max"]
self.task_number = (max_task_number if max_task_number is not None else -1) + 1
+ @property
+ def ownership_version(self) -> str | None:
+ return _task_ownership_version(self.state)
+
def create_run(
self,
environment: Optional["TaskRun.Environment"] = None,
@@ -525,63 +539,84 @@ class Task(DeletedMetaFields, models.Model):
extra_state: dict | None = None,
branch: str | None = None,
) -> "TaskRun":
- state: dict = {} if self.runtime == Task.Runtime.PI else {"mode": mode}
- if extra_state:
- state.update({k: v for k, v in extra_state.items() if k != "mode"})
- state.setdefault("repositories", self.repositories or ([self.repository] if self.repository else []))
- # A workflow task's later runs (a teammate continuing it) must keep the connector
- # allowlist the workflow selected; without the snapshot the run would mount every
- # installation its owner has (see loop_mcp_installation_allowlist).
- if self.origin_product == Task.OriginProduct.WORKFLOW and "config_snapshot" not in state:
- previous = self.latest_run
- previous_snapshot = previous.state.get("config_snapshot") if previous else None
- if previous_snapshot:
- state["config_snapshot"] = previous_snapshot
- # Pin the stream-routing decision once so every reader/writer agrees for this run's life.
- if "use_dedicated_stream" not in state:
+ expected_created_by_id = self.created_by_id
+ expected_ownership_version = self.ownership_version
+ dedicated_stream = (extra_state or {}).get("use_dedicated_stream")
+ if dedicated_stream is None:
distinct_id = (self.created_by.distinct_id if self.created_by else None) or f"team_{self.team_id}"
- state["use_dedicated_stream"] = evaluate_dedicated_stream_flag(
+ dedicated_stream = evaluate_dedicated_stream_flag(
organization_id=str(self.team.organization_id),
distinct_id=distinct_id,
)
- is_resume = bool((extra_state or {}).get("resume_from_run_id"))
- has_pending = bool(
- (extra_state or {}).get("pending_user_message") or (extra_state or {}).get("pending_user_artifact_ids")
- )
- task_run = TaskRun.objects.create(
- task=self,
- team=self.team,
- status=TaskRun.Status.QUEUED,
- queued_at=django_timezone.now(),
- **({"environment": environment} if environment else {}),
- state=state,
- branch=branch,
- )
- def emit_created_events() -> None:
- task_run.publish_stream_state_event()
- observe_task_run_created(task_run)
- self.capture_event(
- "task_run_created",
- {
- "run_id": str(task_run.id),
- "mode": mode,
- "environment": task_run.environment,
- # The bare `environment` property gets clobbered by the analytics client's
- # deployment-environment super-property, so ship the run's local/cloud value
- # under an unclobbered name too — as TaskRun.capture_event already does.
- "run_environment": task_run.environment,
- "is_resume": is_resume,
- "has_pending_message": has_pending,
- # Loop attribution: this event uses Task.capture_event (not TaskRun's),
- # so carry it from the run state the same way TaskRun.capture_event does.
- "loop_id": state.get("loop_id"),
- "loop_trigger_id": state.get("loop_trigger_id"),
- },
+ with transaction.atomic():
+ task = (
+ Task.objects.select_for_update(of=("self",))
+ .select_related("created_by", "team")
+ .get(id=self.id, team_id=self.team_id)
+ )
+ if task.created_by_id != expected_created_by_id or task.ownership_version != expected_ownership_version:
+ raise TaskOwnershipChangedError("Task ownership changed before the run was created")
+
+ state: dict = {} if task.runtime == Task.Runtime.PI else {"mode": mode}
+ if extra_state:
+ state.update({k: v for k, v in extra_state.items() if k != "mode"})
+ state.setdefault("repositories", task.repositories or ([task.repository] if task.repository else []))
+ # A workflow task's later runs must keep the connector allowlist selected by the workflow.
+ if task.origin_product == Task.OriginProduct.WORKFLOW and "config_snapshot" not in state:
+ previous = task.latest_run
+ previous_snapshot = previous.state.get("config_snapshot") if previous else None
+ if previous_snapshot:
+ state["config_snapshot"] = previous_snapshot
+ if task.ownership_version is not None:
+ state[TASK_OWNERSHIP_VERSION_STATE_KEY] = task.ownership_version
+
+ resume_from_run_id = (extra_state or {}).get("resume_from_run_id")
+ if resume_from_run_id is not None:
+ resume_source = TaskRun.objects.filter(id=resume_from_run_id, task_id=task.id).only("state").first()
+ if resume_source is None or not resume_source.matches_task_ownership(task):
+ raise TaskOwnershipChangedError("The resume source belongs to a previous task owner")
+
+ # Pin the stream-routing decision once so every reader/writer agrees for this run's life.
+ state.setdefault("use_dedicated_stream", dedicated_stream)
+ is_resume = bool(resume_from_run_id)
+ has_pending = bool(
+ (extra_state or {}).get("pending_user_message") or (extra_state or {}).get("pending_user_artifact_ids")
+ )
+ task_run = TaskRun.objects.create(
+ task=task,
+ team=task.team,
+ status=TaskRun.Status.QUEUED,
+ queued_at=django_timezone.now(),
+ **({"environment": environment} if environment else {}),
+ state=state,
+ branch=branch,
)
- execute_after_commit(emit_created_events)
- return task_run
+ def emit_created_events() -> None:
+ task_run.publish_stream_state_event()
+ observe_task_run_created(task_run)
+ task.capture_event(
+ "task_run_created",
+ {
+ "run_id": str(task_run.id),
+ "mode": mode,
+ "environment": task_run.environment,
+ # The bare `environment` property gets clobbered by the analytics client's
+ # deployment-environment super-property, so ship the run's local/cloud value
+ # under an unclobbered name too — as TaskRun.capture_event already does.
+ "run_environment": task_run.environment,
+ "is_resume": is_resume,
+ "has_pending_message": has_pending,
+ # Loop attribution: this event uses Task.capture_event (not TaskRun's),
+ # so carry it from the run state the same way TaskRun.capture_event does.
+ "loop_id": state.get("loop_id"),
+ "loop_trigger_id": state.get("loop_trigger_id"),
+ },
+ )
+
+ execute_after_commit(emit_created_events)
+ return task_run
@property
def slack_notified_pr_url(self) -> str | None:
@@ -2628,6 +2663,14 @@ class TaskRun(models.Model):
self.append_log([event])
self.publish_stream_event(event)
+ @property
+ def ownership_version(self) -> str | None:
+ return _task_ownership_version(self.state)
+
+ def matches_task_ownership(self, task: Task | None = None) -> bool:
+ current_task = task or self.task
+ return self.ownership_version == current_task.ownership_version
+
@property
def is_terminal(self) -> bool:
return self.status in {self.Status.COMPLETED, self.Status.FAILED, self.Status.CANCELLED}
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 34a5d75c5b6f..f915999ff118 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -2267,6 +2267,17 @@ class TaskPinRequestSerializer(serializers.Serializer):
pinned = serializers.BooleanField(help_text="Whether the task should be pinned for the requester.")
+class TaskHandoffRequestSerializer(serializers.Serializer):
+ """Request body for handing a task off to a colleague: they become its owner."""
+
+ user = serializers.IntegerField(
+ min_value=1,
+ help_text=(
+ "ID of the user taking over the task. Must have access to this project and not be the task's current owner."
+ ),
+ )
+
+
class TaskPinResponseSerializer(serializers.Serializer):
task_id = serializers.UUIDField(help_text="Task whose pin state was updated.")
pinned = serializers.BooleanField(help_text="Current pin state for the requester.")
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 2205eca15cb3..1bc9bf74a73a 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -46,7 +46,12 @@ from posthog.api.utils import ServerTimingsGathered
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
from posthog.event_usage import groups
from posthog.models import User
-from posthog.permissions import APIScopePermission, get_authenticator_scoped_team_ids, get_authenticator_scopes
+from posthog.permissions import (
+ APIScopePermission,
+ get_authenticator_scoped_team_ids,
+ get_authenticator_scopes,
+ is_mcp_built_in_agent_oauth_request,
+)
from posthog.rate_limit import CodeInviteThrottle, TaskRunChartRenderThrottle
from posthog.renderers import ServerSentEventRenderer
from posthog.schema_migrations.upgrade import upgrade
@@ -113,6 +118,7 @@ from products.tasks.backend.presentation.serializers import (
TaskCommentsQuerySerializer,
TaskCommentsResponseSerializer,
TaskCreateSerializer,
+ TaskHandoffRequestSerializer,
TaskListQuerySerializer,
TaskPinRequestSerializer,
TaskPinResponseSerializer,
@@ -686,6 +692,40 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
raise NotFound()
return Response({"task_id": pk, "pinned": pinned})
+ @extend_schema(
+ request=TaskHandoffRequestSerializer,
+ responses={
+ 200: TaskSerializer,
+ 403: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="Only a user may hand off a task.",
+ ),
+ },
+ summary="Hand a task off to a colleague",
+ description=(
+ "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."
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="handoff", required_scopes=["task:write"])
+ @validated_request(request_serializer=TaskHandoffRequestSerializer)
+ def handoff(self, request, pk=None, **kwargs):
+ if is_sandbox_oauth_request(request) or is_mcp_built_in_agent_oauth_request(request):
+ raise PermissionDenied("Only a user can hand off a task. Sign in to continue.")
+ user_id = self._user_id()
+ if user_id is None:
+ raise NotFound()
+ try:
+ task = tasks_facade.handoff_task(pk, self.team_id, user_id, target_user_id=request.validated_data["user"])
+ except tasks_facade.TaskHandoffError as e:
+ raise ValidationError({"user": str(e)}) from e
+ if task is None:
+ raise NotFound()
+ return Response(TaskSerializer(task).data)
+
@extend_schema(
responses={
200: OpenApiResponse(
@@ -1121,16 +1161,23 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(tags=["task-runs", "tasks"])
-def is_sandbox_agent_request(request, task_id: str) -> bool:
- """True only for the task-bound sandbox OAuth identity, never a human session or key."""
+def is_sandbox_oauth_request(request) -> bool:
authenticator = request.successful_authenticator
if not isinstance(authenticator, OAuthAccessTokenAuthentication):
return False
- access_token = authenticator.access_token
- application = access_token.application
- if application is None or application.client_id not in SANDBOX_OAUTH_APP_CLIENT_IDS:
- return False
- return access_token.sandbox_task_id == UUID(task_id)
+ application = authenticator.access_token.application
+ return application is not None and application.client_id in SANDBOX_OAUTH_APP_CLIENT_IDS
+
+
+def _sandbox_bound_task_id(request) -> UUID | None:
+ if not is_sandbox_oauth_request(request):
+ return None
+ return request.successful_authenticator.access_token.sandbox_task_id
+
+
+def is_sandbox_agent_request(request, task_id: str) -> bool:
+ """True only for the task-bound sandbox OAuth identity, never a human session or key."""
+ return _sandbox_bound_task_id(request) == UUID(task_id)
class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@@ -1202,6 +1249,13 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
for_control=not is_read_only,
):
raise NotFound("Task not found")
+ run_id = self.kwargs.get("pk")
+ if (
+ not is_read_only
+ and run_id is not None
+ and not tasks_facade.task_run_matches_current_ownership(run_id, task_id, self.team_id)
+ ):
+ raise NotFound("Task run not found")
return task_id
def _get_run_or_404(self, pk) -> tasks_contracts.TaskRunDetailDTO:
@@ -1355,6 +1409,13 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
},
status=status.HTTP_400_BAD_REQUEST,
)
+ if outcome == "ownership_changed":
+ return Response(
+ TaskRunErrorResponseSerializer(
+ {"error": "This run belongs to a previous task owner. Start a new run instead."}
+ ).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
if started_task_id is None:
raise NotFound()
@@ -2666,6 +2727,13 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
TaskRunErrorResponseSerializer({"error": "Run is already active in cloud"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
+ if outcome == "ownership_changed":
+ return Response(
+ TaskRunErrorResponseSerializer(
+ {"error": "This run belongs to a previous task owner. Start a new run instead."}
+ ).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
if outcome.startswith("auth_error:"):
detail = outcome.split(":", 1)[1]
return Response(
@@ -2930,6 +2998,8 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
for_control=not is_read,
):
raise NotFound("Task not found")
+ if not is_read and not tasks_facade.task_run_matches_current_ownership(self._run_id(), task_id, self.team_id):
+ raise NotFound("Task run not found")
return task_id
@validated_request(
diff --git a/products/tasks/backend/push_dispatcher.py b/products/tasks/backend/push_dispatcher.py
index 2c23d0113822..568da315a8b5 100644
--- a/products/tasks/backend/push_dispatcher.py
+++ b/products/tasks/backend/push_dispatcher.py
@@ -37,6 +37,8 @@ from products.tasks.backend.redis import get_tasks_cache
from products.tasks.backend.visibility import task_visibility_q
if TYPE_CHECKING:
+ from uuid import UUID
+
from products.tasks.backend.models import TaskRun, TaskThreadMessage
logger = structlog.get_logger(__name__)
@@ -48,7 +50,7 @@ FEATURE_FLAG_KEY = "posthog-code-mobile-push"
# they should only fire once per run lifetime — anything more is a retry.
# Interactive turn-end can legitimately fire again after the user replies,
# so a short cooldown is enough to absorb rapid duplicate triggers.
-PushKind = Literal["completed", "failed", "cancelled", "awaiting", "turn_completed", "thread_message"]
+PushKind = Literal["completed", "failed", "cancelled", "awaiting", "turn_completed", "thread_message", "handoff"]
_COOLDOWN_SECONDS: dict[PushKind, int] = {
"completed": 600,
"failed": 600,
@@ -56,6 +58,7 @@ _COOLDOWN_SECONDS: dict[PushKind, int] = {
"awaiting": 30,
"turn_completed": 30,
"thread_message": 600,
+ "handoff": 600,
}
@@ -86,6 +89,33 @@ def notify_task_run_turn_completed(task_run: TaskRun) -> None:
_enqueue(task_run, kind="turn_completed", body=f'"{_task_title(task_run)}" finished')
+def notify_task_handoff(task: Task, *, recipient: User, actor: User | None, message_id: UUID) -> None:
+ """Fire a push notification when a task is handed off to ``recipient``.
+
+ The announcement ID separates new handoffs from retries for cooldown purposes.
+ """
+ try:
+ actor_name = ((actor.first_name.strip() or actor.email) if actor else None) or "A colleague"
+ task_title = (task.title or "").strip() or "Untitled task"
+ _enqueue_user(
+ recipient,
+ task=task,
+ kind="handoff",
+ cooldown_subject=f"task_handoff:{message_id}:{recipient.id}",
+ body=f'{actor_name} handed you "{task_title}"',
+ data={"taskId": str(task.id)},
+ )
+ except Exception as exc:
+ PUSH_DISPATCHER_FAILURES_TOTAL.labels(kind="handoff", reason=_failure_reason(exc)).inc()
+ logger.warning(
+ "push_dispatcher.enqueue_failed",
+ task_id=str(task.id),
+ user_id=recipient.id,
+ kind="handoff",
+ exc_info=True,
+ )
+
+
def notify_task_thread_message(message: TaskThreadMessage, mentioned_user_ids: Collection[int]) -> None:
try:
_notify_task_thread_message(message, mentioned_user_ids)
diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.py
index d4099fb7baf3..3b3d5a11da3f 100644
--- a/products/tasks/backend/temporal/oauth.py
+++ b/products/tasks/backend/temporal/oauth.py
@@ -24,7 +24,7 @@ from products.tasks.backend.logic.services.run_actor import (
is_slack_interaction_state,
loop_owner_eligible_for_credentials,
)
-from products.tasks.backend.models import Task
+from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, Task
if TYPE_CHECKING:
from posthog.models.user import User
@@ -162,55 +162,42 @@ def create_oauth_access_token_for_run(
to mint creator credentials for a Slack run by omitting one kwarg. Loop-fired runs
(``loop_id`` in run state) get ``loop:write`` stripped from the granted scopes here.
"""
- actor_user = get_task_run_credential_user(task, state)
- loop_id = (state or {}).get("loop_id")
- if task.origin_product == Task.OriginProduct.WORKFLOW:
- # Workflow-fired runs mirror the loop-run policy below: the owner's eligibility is
- # rechecked and locked at mint time, and automation-editing scopes are stripped.
- # The workflow's snapshotted scope choice additionally caps the request, because a
- # teammate's rerun dispatches with the generic user-run scopes rather than the
- # ones the workflow selected.
- effective_scopes = _workflow_run_scopes(scopes, state)
- credential_owner_id = actor_user.id if actor_user is not None else task.created_by_id
- with transaction.atomic():
- if not loop_owner_eligible_for_credentials(credential_owner_id, task.team):
- raise TaskInvalidStateError(
- f"Workflow task {task.id} credential owner can no longer access its team",
- {"task_id": task.id},
- cause=RuntimeError("workflow credential owner is not an active team member"),
- )
- return create_oauth_access_token(
- task,
- scopes=effective_scopes,
- user=actor_user,
- allow_task_creator_fallback=not is_slack_interaction_state(state),
- loop_id=None,
- )
- if loop_id is None:
- return create_oauth_access_token(
- task,
- scopes=scopes,
- user=actor_user,
- allow_task_creator_fallback=not is_slack_interaction_state(state),
- loop_id=None,
- )
-
- # Loop run: re-verify the credential owner is eligible at mint time, not just at dispatch, and do
- # it atomically. `is_active` on the already-loaded `task.created_by` is stale, so the check reads
- # and locks the owner row (and its membership) freshly, then mints inside the same transaction —
- # a deactivation or membership removal can't commit between the check and token creation, and the
- # async loop cancellation can't revoke a token already handed to the sandbox.
- credential_owner_id = actor_user.id if actor_user is not None else task.created_by_id
with transaction.atomic():
- if not loop_owner_eligible_for_credentials(credential_owner_id, task.team):
+ locked_task = (
+ Task.objects.select_for_update(of=("self",))
+ .select_related("created_by", "team")
+ .get(id=task.id, team_id=task.team_id)
+ )
+ run_ownership_version = (state or {}).get(TASK_OWNERSHIP_VERSION_STATE_KEY)
+ if run_ownership_version != locked_task.ownership_version:
raise TaskInvalidStateError(
- f"Loop task {task.id} credential owner can no longer access its team",
+ f"Task run for {task.id} belongs to a previous task owner",
{"task_id": task.id},
- cause=RuntimeError("loop credential owner is not an active team member"),
+ cause=RuntimeError("task run ownership version is stale"),
)
+
+ actor_user = get_task_run_credential_user(locked_task, state)
+ loop_id = (state or {}).get("loop_id")
+ effective_scopes = scopes
+ credential_owner_kind: str | None = None
+ if locked_task.origin_product == Task.OriginProduct.WORKFLOW:
+ effective_scopes = _workflow_run_scopes(scopes, state)
+ credential_owner_kind = "workflow"
+ elif loop_id is not None:
+ credential_owner_kind = "loop"
+
+ if credential_owner_kind is not None:
+ credential_owner_id = actor_user.id if actor_user is not None else locked_task.created_by_id
+ if not loop_owner_eligible_for_credentials(credential_owner_id, locked_task.team):
+ raise TaskInvalidStateError(
+ f"{credential_owner_kind.capitalize()} task {locked_task.id} credential owner can no longer access its team",
+ {"task_id": locked_task.id},
+ cause=RuntimeError(f"{credential_owner_kind} credential owner is not an active team member"),
+ )
+
return create_oauth_access_token(
- task,
- scopes=scopes,
+ locked_task,
+ scopes=effective_scopes,
user=actor_user,
allow_task_creator_fallback=not is_slack_interaction_state(state),
loop_id=loop_id if isinstance(loop_id, str) else None,
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index 53cd755a179f..7ee212bc7f94 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -834,6 +834,12 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
emit_agent_log(run_id, "debug", "Fetching task details")
task: Task = task_run.task
+ if not task_run.matches_task_ownership(task):
+ raise TaskInvalidStateError(
+ f"TaskRun {run_id} belongs to a previous task owner",
+ {"task_id": str(task.id), "run_id": run_id},
+ cause=RuntimeError(f"TaskRun {run_id} ownership version is stale"),
+ )
if task.runtime == Task.Runtime.PI:
ensure_task_run_session(task_run.id)
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index 8234691f864b..4ebb6cf33805 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -28,6 +28,7 @@ from products.tasks.backend.exceptions import (
OAuthTokenError,
RepositoryCloneError,
SandboxNetworkPolicyError,
+ TaskInvalidStateError,
TaskNotFoundError,
)
from products.tasks.backend.logic.services.agentsh import (
@@ -61,7 +62,7 @@ from products.tasks.backend.logic.services.sandbox_usage import (
measure_sandbox_cpu_usage,
open_sandbox_session,
)
-from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
+from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, SandboxSnapshot, Task, TaskRun
from products.tasks.backend.temporal.metrics import (
StepTimer,
increment_snapshot_restore,
@@ -362,11 +363,19 @@ def _resolve_sandbox_github_token(
def _load_task(ctx: TaskProcessingContext) -> Task:
try:
- return Task.objects.select_related(
+ task = Task.objects.select_related(
"created_by", "github_integration", "github_user_integration", "team", "loop"
).get(id=ctx.task_id)
except Task.DoesNotExist as e:
raise TaskNotFoundError(f"Task {ctx.task_id} not found", {"task_id": ctx.task_id}, cause=e)
+ context_ownership_version = (ctx.state or {}).get(TASK_OWNERSHIP_VERSION_STATE_KEY)
+ if context_ownership_version != task.ownership_version:
+ raise TaskInvalidStateError(
+ f"TaskRun {ctx.run_id} belongs to a previous task owner",
+ {"task_id": ctx.task_id, "run_id": ctx.run_id},
+ cause=RuntimeError(f"TaskRun {ctx.run_id} ownership version is stale"),
+ )
+ return task
def _get_image_source_label(
diff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
index d05433e2f626..7cfaa1fe0fdf 100644
--- a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
@@ -8,7 +8,7 @@ from posthog.temporal.common.utils import asyncify, retry_on_db_connection_drop
from products.tasks.backend.exceptions import CredentialUnavailableError, SandboxNotFoundError, SandboxNotRunningError
from products.tasks.backend.logic.services.sandbox import Sandbox
-from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, Task, TaskRun
from products.tasks.backend.temporal.metrics import increment_credential_refresh
from products.tasks.backend.temporal.observability import log_activity_execution, track_event
from products.tasks.backend.temporal.process_task.sandbox_credentials import (
@@ -89,6 +89,19 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
id=ctx.task_id
)
)
+ context_ownership_version = (ctx.state or {}).get(TASK_OWNERSHIP_VERSION_STATE_KEY)
+ if context_ownership_version != task.ownership_version:
+ logger.info(
+ "sandbox_credentials_refresh_stopped_ownership_changed",
+ sandbox_id=input.sandbox_id,
+ run_id=ctx.run_id,
+ task_id=ctx.task_id,
+ )
+ return RefreshSandboxCredentialsOutput(
+ next_refresh_seconds=DEFAULT_REFRESH_INTERVAL_SECONDS,
+ refreshed_kinds=[],
+ no_credentials_left=True,
+ )
ctx = _with_current_authorship(ctx)
except Task.DoesNotExist:
logger.info(
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
index 7f2c82a0573c..0254328a16c5 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
@@ -24,7 +24,7 @@ from products.tasks.backend.constants import (
vm_sandbox_origin_rollout_percentages,
)
from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyError
-from products.tasks.backend.models import SandboxEnvironment, Task
+from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, SandboxEnvironment, Task
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (
GetTaskProcessingContextInput,
TaskProcessingContext,
@@ -175,6 +175,18 @@ class TestGetTaskProcessingContextActivity:
assert result.repository == "posthog/posthog-js"
assert result.create_pr is True
+ @pytest.mark.django_db(transaction=True)
+ def test_get_task_processing_context_rejects_previous_owner_run(self, activity_environment, test_task):
+ task_run = test_task.create_run()
+ test_task.state = {TASK_OWNERSHIP_VERSION_STATE_KEY: "new-owner"}
+ test_task.save(update_fields=["state", "updated_at"])
+
+ with pytest.raises(TaskInvalidStateError):
+ async_to_sync(activity_environment.run)(
+ get_task_processing_context,
+ GetTaskProcessingContextInput(run_id=str(task_run.id)),
+ )
+
@pytest.mark.django_db(transaction=True)
def test_get_task_processing_context_task_not_found_is_retryable(self, activity_environment):
# A missing TaskRun is treated as a transient (retryable) condition, not a fatal error,
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
index a14352f3c609..6045f8b855ba 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
@@ -12,7 +12,7 @@ from posthog.models.integration import Integration
from products.tasks.backend.exceptions import SandboxExecutionError, SandboxNotFoundError, SandboxNotRunningError
from products.tasks.backend.logic.services.sandbox import ExecutionResult
-from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, Task, TaskRun
from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (
RefreshSandboxCredentialsInput,
refresh_sandbox_credentials,
@@ -66,6 +66,23 @@ class TestRefreshSandboxCredentialsActivity:
assert event_name == "sandbox_credentials_refreshed"
assert track_event.call_args.kwargs["properties"]["refreshed_kinds"] == ["github"]
+ def test_stops_refreshing_after_task_handoff(self, activity_environment, task_context, test_task, sandbox):
+ test_task.state = {TASK_OWNERSHIP_VERSION_STATE_KEY: "new-owner"}
+ test_task.save(update_fields=["state", "updated_at"])
+
+ with patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.Sandbox.get_by_id",
+ return_value=sandbox,
+ ) as get_sandbox:
+ output = async_to_sync(activity_environment.run)(
+ refresh_sandbox_credentials,
+ RefreshSandboxCredentialsInput(context=task_context, sandbox_id="sandbox-abc"),
+ )
+
+ assert output.refreshed_kinds == []
+ assert output.no_credentials_left is True
+ get_sandbox.assert_not_called()
+
def test_promoted_run_refreshes_as_user_not_the_team_installation(
self, activity_environment, task_context, test_task, test_task_run, sandbox
):
diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.py
index 5dcdfb34c038..6ddd11170547 100644
--- a/products/tasks/backend/temporal/tests/test_oauth.py
+++ b/products/tasks/backend/temporal/tests/test_oauth.py
@@ -6,7 +6,7 @@ from posthog.models.user import User
from posthog.temporal.oauth import PosthogMcpScopes
from products.tasks.backend.exceptions import TaskInvalidStateError
-from products.tasks.backend.models import MCPBuiltInAgentKey, Task
+from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, MCPBuiltInAgentKey, Task
from products.tasks.backend.temporal.oauth import create_oauth_access_token, create_oauth_access_token_for_run
@@ -262,6 +262,25 @@ def test_run_token_fails_closed_for_slack_run_with_unresolvable_actor(mock_creat
assert create_oauth_access_token_for_run(task, {}) == "token"
+@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")
+def test_run_token_rejects_previous_task_owner(mock_create: MagicMock) -> None:
+ organization = Organization.objects.create(name="oauth-handoff-org")
+ team = Team.objects.create(organization=organization, name="oauth-handoff-team")
+ creator = User.objects.create(email="[email protected]")
+ task = Task.objects.create(
+ team=team,
+ title="Transferred task",
+ created_by=creator,
+ state={TASK_OWNERSHIP_VERSION_STATE_KEY: "new-owner"},
+ )
+
+ with pytest.raises(TaskInvalidStateError):
+ create_oauth_access_token_for_run(task, {})
+
+ mock_create.assert_not_called()
+
+
@pytest.mark.django_db
@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")
def test_loop_run_fails_closed_when_owner_is_not_a_current_org_member(mock_create: MagicMock) -> None:
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 5c017cbdd710..b95fc4b3b971 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -29,6 +29,7 @@ from rest_framework.test import APIClient
from posthog.models import Integration, Organization, OrganizationMembership, PersonalAPIKey, Team, User
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
from posthog.models.personal_api_key import hash_key_value
+from posthog.models.scoping import team_scope
from posthog.models.user_integration import UserIntegration
from posthog.models.utils import generate_random_token_personal
from posthog.scopes import MCP_BUILT_IN_AGENT_SCOPE
@@ -36,6 +37,7 @@ from posthog.storage import object_storage
from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV
from posthog.utils import absolute_uri
+from products.posthog_ai.backend.models.assistant import Conversation
from products.slack_app.backend.models import SlackThreadTaskMapping
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.repo_selection import RepoSelectionResult
@@ -66,6 +68,7 @@ from products.tasks.backend.logic.stream.redis_stream import (
get_task_run_stream_key,
)
from products.tasks.backend.models import (
+ TASK_OWNERSHIP_VERSION_STATE_KEY,
AgentPeerMessage,
Channel,
CodeInvite,
@@ -235,6 +238,37 @@ class BaseTaskAPITest(TestCase):
self.organization.members.add(user)
return user
+ def _sandbox_oauth_client(
+ self,
+ task_id: uuid.UUID,
+ *,
+ client_id: str = ARRAY_APP_CLIENT_ID_DEV,
+ bound: bool = True,
+ internal_scope: bool = False,
+ ) -> APIClient:
+ application = OAuthApplication.objects.create(
+ name="Task artifact uploader",
+ client_id=client_id,
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ algorithm="RS256",
+ redirect_uris="https://example.com/callback",
+ organization=self.organization,
+ user=self.user,
+ )
+ access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token=f"pha_task_agent_{uuid.uuid4().hex}",
+ expires=django_timezone.now() + timedelta(hours=1),
+ scope=f"task:read task:write{' internal_run:read' if internal_scope else ''}",
+ scoped_teams=[self.team.id],
+ sandbox_task_id=task_id if bound else None,
+ )
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")
+ return client
+
class TestBuiltInAgentTaskAccess(BaseTaskAPITest):
def _built_in_agent_client(self) -> APIClient:
@@ -4972,37 +5006,6 @@ _OTHER_PR_URL = "https://github.com/posthog/posthog-js/pull/2"
class TestTaskRunAPI(BaseTaskAPITest):
- def _sandbox_oauth_client(
- self,
- task_id: uuid.UUID,
- *,
- client_id: str = ARRAY_APP_CLIENT_ID_DEV,
- bound: bool = True,
- internal_scope: bool = False,
- ) -> APIClient:
- application = OAuthApplication.objects.create(
- name="Task artifact uploader",
- client_id=client_id,
- client_type=OAuthApplication.CLIENT_PUBLIC,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- algorithm="RS256",
- redirect_uris="https://example.com/callback",
- organization=self.organization,
- user=self.user,
- )
- access_token = OAuthAccessToken.objects.create(
- user=self.user,
- application=application,
- token=f"pha_task_agent_{uuid.uuid4().hex}",
- expires=django_timezone.now() + timedelta(hours=1),
- scope=f"task:read task:write{' internal_run:read' if internal_scope else ''}",
- scoped_teams=[self.team.id],
- sandbox_task_id=task_id if bound else None,
- )
- client = APIClient()
- client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")
- return client
-
def _create_run_for_origin(self, origin_product: Task.OriginProduct) -> tuple[Task, TaskRun]:
task = Task.objects.create(
team=self.team,
@@ -9242,6 +9245,336 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
)
+class TestTaskHandoffAPI(BaseTaskAPITest):
+ def _handoff_url(self, task: Task) -> str:
+ return f"/api/projects/@current/tasks/{task.id}/handoff/"
+
+ def test_handoff_transfers_ownership_and_posts_thread_announcement(self):
+ recipient = self.create_organization_user("recipient")
+ integration = _grant_user_github_access(self.user)
+ task = self.create_task(created_by=self.user)
+ task.github_user_integration = integration
+ task.save()
+ conversation = Conversation.objects.create(
+ user=self.user,
+ team=self.team,
+ agent_runtime=Conversation.AgentRuntime.SANDBOX,
+ task=task,
+ sandbox_task_id=task.id,
+ sandbox_run_id=uuid.uuid4(),
+ )
+
+ response = self.client.post(self._handoff_url(task), {"user": recipient.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["created_by"]["id"], recipient.id)
+ task.refresh_from_db()
+ self.assertEqual(task.created_by_id, recipient.id)
+ self.assertIsNone(task.github_user_integration_id)
+ self.assertIsInstance((task.state or {}).get(TASK_OWNERSHIP_VERSION_STATE_KEY), str)
+ conversation.refresh_from_db()
+ self.assertIsNone(conversation.task_id)
+ self.assertIsNone(conversation.sandbox_task_id)
+ self.assertIsNone(conversation.sandbox_run_id)
+ with team_scope(self.team.id):
+ announcement = task.thread_messages.get(event="task_handed_off")
+ self.assertEqual(announcement.author_kind, "system")
+ self.assertEqual(announcement.author_id, self.user.id)
+ self.assertEqual(
+ announcement.payload,
+ {
+ "from_user_id": self.user.id,
+ "to_user_id": recipient.id,
+ "from_display_name": "Test",
+ "to_display_name": "Other",
+ },
+ )
+
+ def test_handoff_rejects_nonterminal_runs(self):
+ recipient = self.create_organization_user("recipient")
+ task = self.create_task(created_by=self.user)
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)
+
+ response = self.client.post(self._handoff_url(task), {"user": recipient.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(
+ response.json(),
+ {
+ "type": "validation_error",
+ "code": "invalid_input",
+ "detail": "Finish or cancel active runs before handing off this task.",
+ "attr": "user",
+ },
+ )
+ task.refresh_from_db()
+ self.assertEqual(task.created_by_id, self.user.id)
+
+ def test_handoff_keeps_previous_owner_runs_read_only(self):
+ recipient = self.create_organization_user("recipient")
+ task = self.create_task(created_by=self.user)
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ response = self.client.post(self._handoff_url(task), {"user": recipient.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ recipient_client = APIClient()
+ recipient_client.force_authenticate(recipient)
+ run_url = f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/"
+ self.assertEqual(recipient_client.get(run_url).status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ recipient_client.patch(run_url, {"stage": "build"}, format="json").status_code,
+ status.HTTP_404_NOT_FOUND,
+ )
+ self.assertEqual(
+ recipient_client.post(
+ f"{run_url}living_artifacts/",
+ {"name": "old-run.md", "artifact_type": "document", "content": "old"},
+ format="json",
+ ).status_code,
+ status.HTTP_404_NOT_FOUND,
+ )
+
+ def test_handoff_rejects_open_sandbox_session(self):
+ recipient = self.create_organization_user("recipient")
+ task = self.create_task(created_by=self.user)
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
+ now = django_timezone.now()
+ SandboxSession.objects.unscoped().create(
+ team=self.team,
+ task_run=run,
+ sandbox_id="sandbox-still-closing",
+ cpu_cores=1,
+ memory_gb=1,
+ ttl_seconds=3600,
+ created_at=now,
+ ttl_expires_at=now + timedelta(hours=1),
+ )
+
+ response = self.client.post(self._handoff_url(task), {"user": recipient.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(
+ response.json()["detail"],
+ "Wait for active sandboxes to shut down before handing off this task.",
+ )
+ task.refresh_from_db()
+ self.assertEqual(task.created_by_id, self.user.id)
+
+ def test_handoff_revokes_task_bound_sandbox_oauth_tokens(self):
+ recipient = self.create_organization_user("recipient")
+ task = self.create_task(created_by=self.user)
+ self._sandbox_oauth_client(task.id)
+ access_token = OAuthAccessToken.objects.get(sandbox_task_id=task.id)
+
+ response = self.client.post(self._handoff_url(task), {"user": recipient.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertFalse(OAuthAccessToken.objects.filter(id=access_token.id).exists())
+
+ def test_handoff_rejects_built_in_agent_oauth(self):
+ recipient = self.create_organization_user("recipient")
+ task = self.create_task(created_by=self.user)
+ application = OAuthApplication.objects.create(
+ name="Built-in agent sandbox",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=self.organization,
+ user=self.user,
+ )
+ access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token=f"pha_task_agent_{uuid.uuid4().hex}",
+ expires=django_timezone.now() + timedelta(hours=1),
+ scope=f"task:read task:write {MCP_BUILT_IN_AGENT_SCOPE}",
+ scoped_teams=[self.team.id],
+ )
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")
+
+ response = client.post(self._handoff_url(task), {"user": recipient.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ task.refresh_from_db()
+ self.assertEqual(task.created_by_id, self.user.id)
+
+ def test_handoff_rejects_unbound_legacy_sandbox_oauth(self):
+ recipient = self.create_organization_user("recipient")
+ task = self.create_task(created_by=self.user)
+ client = self._sandbox_oauth_client(task.id, bound=False, internal_scope=True)
+
+ response = client.post(self._handoff_url(task), {"user": recipient.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ task.refresh_from_db()
+ self.assertEqual(task.created_by_id, self.user.id)
+
+ def test_handoff_rejects_task_bound_sandbox_agent_from_another_task(self):
+ recipient = self.create_organization_user("recipient")
+ bound_task = self.create_task(created_by=self.user)
+ task = self.create_task(created_by=self.user)
+ client = self._sandbox_oauth_client(bound_task.id)
+
+ response = client.post(self._handoff_url(task), {"user": recipient.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ task.refresh_from_db()
+ self.assertEqual(task.created_by_id, self.user.id)
+
+ def test_handoff_moves_private_space_task_into_recipient_space(self):
+ recipient = self.create_organization_user("recipient")
+ with team_scope(self.team.id):
+ personal = Channel.objects.create(
+ team=self.team, name="me", channel_type=Channel.ChannelType.PERSONAL, created_by=self.user
+ )
+ task = self.create_task(created_by=self.user)
+ task.channel = personal
+ 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()
+ with team_scope(self.team.id):
+ self.assertIsNotNone(task.channel)
+ self.assertEqual(task.channel.channel_type, Channel.ChannelType.PERSONAL)
+ self.assertEqual(task.channel.created_by_id, recipient.id)
+ # The previous owner loses sight of a private-space task; the recipient can see and drive it.
+ self.assertEqual(
+ self.client.get(f"/api/projects/@current/tasks/{task.id}/").status_code, status.HTTP_404_NOT_FOUND
+ )
+ recipient_client = APIClient()
+ recipient_client.force_authenticate(recipient)
+ self.assertEqual(
+ recipient_client.get(f"/api/projects/@current/tasks/{task.id}/").status_code, status.HTTP_200_OK
+ )
+ self.assertEqual(
+ recipient_client.patch(
+ f"/api/projects/@current/tasks/{task.id}/", {"title": "Taken over"}, format="json"
+ ).status_code,
+ status.HTTP_200_OK,
+ )
+ self.assertEqual(
+ self.client.patch(
+ f"/api/projects/@current/tasks/{task.id}/", {"title": "Still mine"}, format="json"
+ ).status_code,
+ status.HTTP_404_NOT_FOUND,
+ )
+
+ def test_handoff_keeps_task_in_shared_space(self):
+ recipient = self.create_organization_user("recipient")
+ with team_scope(self.team.id):
+ shared = Channel.objects.create(team=self.team, name="general", created_by=self.user)
+ task = self.create_task(created_by=self.user)
+ task.channel = shared
+ 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, shared.id)
+ 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):
+ shared = Channel.objects.create(team=self.team, name="general", created_by=self.user)
+ task = self.create_task(created_by=self.user)
+ task.channel = shared
+ task.save()
+ colleague_client = APIClient()
+ colleague_client.force_authenticate(colleague)
+
+ response = colleague_client.post(self._handoff_url(task), {"user": colleague.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ task.refresh_from_db()
+ self.assertEqual(task.created_by_id, self.user.id)
+
+ @parameterized.expand(
+ [
+ ("unknown_user", 999999, status.HTTP_400_BAD_REQUEST),
+ ("self_handoff", None, status.HTTP_400_BAD_REQUEST),
+ ("missing_user", "missing", status.HTTP_400_BAD_REQUEST),
+ ("non_int_user", "not-a-number", status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_handoff_target_validation(self, _name, user_arg, expected_status):
+ task = self.create_task(created_by=self.user)
+ payload = {} if user_arg == "missing" else {"user": self.user.id if user_arg is None else user_arg}
+
+ response = self.client.post(self._handoff_url(task), payload, format="json")
+
+ self.assertEqual(response.status_code, expected_status)
+ task.refresh_from_db()
+ self.assertEqual(task.created_by_id, self.user.id)
+
+ def test_handoff_rejects_user_outside_the_organization(self):
+ outsider = User.objects.create_user(
+ email=f"outsider-{uuid.uuid4()}@example.com", first_name="Out", password="password"
+ )
+ task = self.create_task(created_by=self.user)
+
+ response = self.client.post(self._handoff_url(task), {"user": outsider.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ task.refresh_from_db()
+ self.assertEqual(task.created_by_id, self.user.id)
+
+ def test_handoff_by_non_owner_of_team_origin_task_returns_404(self):
+ # task_control_q lets any project user DRIVE team-owned system tasks (origin
+ # product fallbacks); handing off is stricter: only the owner can give a task
+ # away, and a task with no owner has nobody who may hand it off.
+ system_task = Task.objects.create(
+ team=self.team,
+ title="Signal brief",
+ origin_product=Task.OriginProduct.SIGNALS_SCOUT,
+ created_by=None,
+ )
+ colleague = self.create_organization_user("colleague")
+
+ response = self.client.post(self._handoff_url(system_task), {"user": colleague.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ system_task.refresh_from_db()
+ self.assertIsNone(system_task.created_by_id)
+
+ def test_handoff_rejects_recipient_without_project_access(self):
+ # Org membership alone isn't project access (private projects under access
+ # control): the recipient must pass the same check that decides what they can
+ # open, otherwise they'd end up owning a task they can't see.
+ recipient = self.create_organization_user("recipient")
+ task = self.create_task(created_by=self.user)
+
+ with patch.object(Team, "all_users_with_access", return_value=User.objects.none()):
+ response = self.client.post(self._handoff_url(task), {"user": recipient.id}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ task.refresh_from_db()
+ self.assertEqual(task.created_by_id, self.user.id)
+
+ def test_handoff_strips_borrowed_mcp_credential_owner(self):
+ recipient = self.create_organization_user("recipient")
+ task = self.create_task(created_by=self.user)
+ task.origin_product = Task.OriginProduct.SIGNALS_SCOUT
+ task.state = {"mcp_builtin_agent": "signals_scout", "mcp_credential_owner_id": self.user.id, "other": 1}
+ 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.assertNotIn("mcp_credential_owner_id", task.state or {})
+ self.assertEqual((task.state or {}).get("other"), 1)
+
+
class TestLivingArtifactChartRequestValidation(SimpleTestCase):
@parameterized.expand(
[
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index 961416eb787e..8c5cfd459b4a 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -1,11 +1,13 @@
import importlib
+import threading
from datetime import timedelta
-from typing import ClassVar
+from typing import Any, ClassVar
from uuid import uuid4
from unittest.mock import MagicMock, patch
-from django.test import TestCase
+from django.db import close_old_connections
+from django.test import TestCase, TransactionTestCase
from django.utils import timezone as django_timezone
from parameterized import parameterized
@@ -20,6 +22,7 @@ from products.tasks.backend.facade import (
warm as warm_facade,
)
from products.tasks.backend.models import (
+ TASK_OWNERSHIP_VERSION_STATE_KEY,
Channel,
SandboxCustomImage,
SandboxEnvironment,
@@ -57,6 +60,142 @@ class TestFacadeImports(TestCase):
self.assertIs(facade.SandboxNetworkAccessLevel, SandboxEnvironment.NetworkAccessLevel)
+class TestTaskHandoffConcurrency(TransactionTestCase):
+ def setUp(self) -> None:
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.owner = User.objects.create_user(email="[email protected]", first_name="Owner", password="password")
+ self.recipient = User.objects.create_user(
+ email="[email protected]", first_name="Recipient", password="password"
+ )
+ self.organization.members.add(self.owner, self.recipient)
+ self.task = Task.objects.create(
+ team=self.team,
+ title="Race task",
+ description="Run later",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ created_by=self.owner,
+ )
+
+ def test_delayed_bootstrap_cannot_create_run_after_handoff(self) -> None:
+ create_reached = threading.Event()
+ handoff_finished = threading.Event()
+ results: list[contracts.TaskRunCreateResult | None] = []
+ errors: list[BaseException] = []
+ original_create_run = Task.create_run
+
+ def delayed_create_run(
+ task: Task,
+ environment: TaskRun.Environment | None = None,
+ mode: str = "background",
+ extra_state: dict | None = None,
+ branch: str | None = None,
+ ) -> TaskRun:
+ create_reached.set()
+ if not handoff_finished.wait(timeout=10):
+ raise TimeoutError("handoff did not finish")
+ return original_create_run(
+ task,
+ environment=environment,
+ mode=mode,
+ extra_state=extra_state,
+ branch=branch,
+ )
+
+ def bootstrap() -> None:
+ close_old_connections()
+ try:
+ results.append(facade.bootstrap_task_run(self.task.id, self.team.id, self.owner.id, validated_data={}))
+ except BaseException as error:
+ errors.append(error)
+ finally:
+ close_old_connections()
+
+ with patch.object(Task, "create_run", new=delayed_create_run):
+ thread = threading.Thread(target=bootstrap)
+ thread.start()
+ self.assertTrue(create_reached.wait(timeout=10))
+ handoff = facade.handoff_task(
+ self.task.id,
+ self.team.id,
+ self.owner.id,
+ target_user_id=self.recipient.id,
+ )
+ handoff_finished.set()
+ thread.join(timeout=10)
+
+ self.assertFalse(thread.is_alive())
+ self.assertEqual(errors, [])
+ self.assertIsNotNone(handoff)
+ self.assertEqual(results, [None])
+ self.assertFalse(TaskRun.objects.filter(task=self.task).exists())
+
+ def test_handoff_waits_for_in_flight_task_update(self) -> None:
+ update_at_save = threading.Event()
+ allow_update_save = threading.Event()
+ update_saved = threading.Event()
+ handoff_finished = threading.Event()
+ errors: list[BaseException] = []
+ original_save = Task.save
+
+ def delayed_save(task: Task, *args: Any, **kwargs: Any) -> None:
+ if task.id == self.task.id and task.title == "Updated title" and not update_saved.is_set():
+ update_at_save.set()
+ if not allow_update_save.wait(timeout=10):
+ raise TimeoutError("update save was not released")
+ result = original_save(task, *args, **kwargs)
+ update_saved.set()
+ return result
+ return original_save(task, *args, **kwargs)
+
+ def update() -> None:
+ close_old_connections()
+ try:
+ facade.update_task(
+ self.task.id,
+ self.team.id,
+ self.owner.id,
+ validated_data={"title": "Updated title"},
+ )
+ except BaseException as error:
+ errors.append(error)
+ finally:
+ close_old_connections()
+
+ def handoff() -> None:
+ close_old_connections()
+ try:
+ facade.handoff_task(
+ self.task.id,
+ self.team.id,
+ self.owner.id,
+ target_user_id=self.recipient.id,
+ )
+ except BaseException as error:
+ errors.append(error)
+ finally:
+ handoff_finished.set()
+ close_old_connections()
+
+ with patch.object(Task, "save", new=delayed_save):
+ update_thread = threading.Thread(target=update)
+ update_thread.start()
+ self.assertTrue(update_at_save.wait(timeout=10))
+ handoff_thread = threading.Thread(target=handoff)
+ handoff_thread.start()
+ self.assertFalse(handoff_finished.wait(timeout=1))
+ allow_update_save.set()
+ update_thread.join(timeout=10)
+ handoff_thread.join(timeout=10)
+
+ self.assertFalse(update_thread.is_alive())
+ self.assertFalse(handoff_thread.is_alive())
+ self.assertEqual(errors, [])
+ self.task.refresh_from_db()
+ self.assertEqual(self.task.title, "Updated title")
+ self.assertEqual(self.task.created_by_id, self.recipient.id)
+
+
class TestFacadeReadsAndMappers(TestCase):
organization: ClassVar[Organization]
team: ClassVar[Team]
@@ -114,6 +253,20 @@ class TestFacadeReadsAndMappers(TestCase):
self.assertIsNone(facade.get_task_run(run.id, team_id=other_team.id))
self.assertIsNone(facade.get_task_run("00000000-0000-0000-0000-000000000000"))
+ def test_resume_in_cloud_rejects_run_from_previous_owner(self):
+ task = self._make_task(state={TASK_OWNERSHIP_VERSION_STATE_KEY: "current-version"})
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED, state={})
+
+ outcome, resumed_run, _ = facade.resume_task_run_in_cloud(
+ run.id,
+ task.id,
+ self.team.id,
+ self.user.id,
+ )
+
+ self.assertEqual(outcome, "ownership_changed")
+ self.assertIsNone(resumed_run)
+
def test_task_exists_and_visibility(self):
task = self._make_task()
self.assertTrue(facade.task_exists(task.id, self.team.id))
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index e2a47821ad13..94be7ebbbed2 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -23,10 +23,12 @@ from posthog.models.user_integration import UserIntegration
from posthog.storage import object_storage
from products.tasks.backend.models import (
+ TASK_OWNERSHIP_VERSION_STATE_KEY,
CodeInvite,
SandboxEnvironment,
SandboxSnapshot,
Task,
+ TaskOwnershipChangedError,
TaskRun,
TaskThreadMessage,
bump_task_activity,
@@ -759,6 +761,48 @@ class TestTaskRun(TestCase):
self.assertNotIn("initial_permission_mode", run.state)
+ def test_create_run_snapshots_task_ownership_version(self):
+ ownership_version = str(uuid.uuid4())
+ self.task.state = {TASK_OWNERSHIP_VERSION_STATE_KEY: ownership_version}
+ self.task.save(update_fields=["state", "updated_at"])
+
+ run = self.task.create_run()
+
+ self.assertEqual(run.ownership_version, ownership_version)
+ self.assertTrue(run.matches_task_ownership(self.task))
+
+ def test_create_run_rejects_stale_task_ownership(self):
+ original_owner = User.objects.create_user(
+ email="[email protected]", first_name="Original", password="password"
+ )
+ new_owner = User.objects.create_user(email="[email protected]", first_name="New", password="password")
+ task = Task.objects.create(
+ team=self.team,
+ title="Owned task",
+ created_by=original_owner,
+ state={TASK_OWNERSHIP_VERSION_STATE_KEY: "old-version"},
+ )
+ Task.objects.filter(id=task.id).update(
+ created_by=new_owner,
+ state={TASK_OWNERSHIP_VERSION_STATE_KEY: "new-version"},
+ )
+
+ with self.assertRaises(TaskOwnershipChangedError):
+ task.create_run()
+
+ self.assertFalse(TaskRun.objects.filter(task=task).exists())
+
+ def test_create_run_rejects_resume_from_previous_owner(self):
+ task = Task.objects.create(
+ team=self.team,
+ title="Transferred task",
+ state={TASK_OWNERSHIP_VERSION_STATE_KEY: "current-version"},
+ )
+ previous_run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED, state={})
+
+ with self.assertRaises(TaskOwnershipChangedError):
+ task.create_run(extra_state={"resume_from_run_id": str(previous_run.id)})
+
@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")
def test_prepare_for_cloud_handoff_clears_stale_sandbox_routing(self, _publish):
run = TaskRun.objects.create(
diff --git a/products/tasks/backend/tests/test_push_dispatcher.py b/products/tasks/backend/tests/test_push_dispatcher.py
index c3b25819e8e7..0e628f0ebff3 100644
--- a/products/tasks/backend/tests/test_push_dispatcher.py
+++ b/products/tasks/backend/tests/test_push_dispatcher.py
@@ -1,3 +1,5 @@
+from uuid import uuid4
+
from unittest.mock import patch
from django.core.cache import cache
@@ -12,6 +14,7 @@ from posthog.tasks.push_notifications import send_user_push
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.push_dispatcher import (
+ notify_task_handoff,
notify_task_run_awaiting_input,
notify_task_run_cancelled,
notify_task_run_completed,
@@ -111,6 +114,16 @@ class TestPushDispatcher(TestCase):
notify_task_run_turn_completed(self.task_run)
self.assertEqual(mock_delay.call_count, 3)
+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
+ def test_handoff_cooldown_distinguishes_announcements(self, mock_delay, _flag):
+ announcement_id = uuid4()
+ with self.captureOnCommitCallbacks(execute=True):
+ notify_task_handoff(self.task, recipient=self.user, actor=self.user, message_id=announcement_id)
+ notify_task_handoff(self.task, recipient=self.user, actor=self.user, message_id=announcement_id)
+ notify_task_handoff(self.task, recipient=self.user, actor=self.user, message_id=uuid4())
+ self.assertEqual(mock_delay.call_count, 2)
+
@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
def test_recipient_without_team_access_is_skipped(self, mock_delay, _flag):
diff --git a/products/tasks/docs/CHANNELS.md b/products/tasks/docs/CHANNELS.md
index f95a4d96abf0..9a9d3e547384 100644
--- a/products/tasks/docs/CHANNELS.md
+++ b/products/tasks/docs/CHANNELS.md
@@ -104,6 +104,20 @@ membership without adding permissions to Task.
- 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
diff --git a/products/tasks/docs/INSTRUMENTATION.md b/products/tasks/docs/INSTRUMENTATION.md
index 3f4e84d91af8..20c6726f6899 100644
--- a/products/tasks/docs/INSTRUMENTATION.md
+++ b/products/tasks/docs/INSTRUMENTATION.md
@@ -66,6 +66,21 @@ Tracked when `Task.soft_delete()` is called. Additional properties:
| ------------------ | ------- | --------------------------- |
| `duration_seconds` | `float` | Seconds since task creation |
+## Facade events
+
+Source: `products/tasks/backend/facade/api.py`
+
+### `task_handed_off`
+
+Tracked when a task controller hands the task off to a colleague (ownership moves
+to the recipient). Captured under the handoff actor's identity rather than the
+recipient's, even though the task's `created_by` has moved by then. Additional properties:
+
+| Property | Type | Description |
+| -------------- | ------ | ------------------------------------ |
+| `from_user_id` | `int?` | User ID of the previous owner |
+| `to_user_id` | `int` | User ID of the recipient (new owner) |
+
## TaskRun Model Events
Source: `products/tasks/backend/models.py`
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index b1a79f565493..ab9a5b938b8d 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -2144,6 +2144,17 @@ export interface TaskCommentDetailApi {
next: string | null
}
+/**
+ * Request body for handing a task off to a colleague: they become its owner.
+ */
+export interface TaskHandoffRequestApi {
+ /**
+ * ID of the user taking over the task. Must have access to this project and not be the task's current owner.
+ * @minimum 1
+ */
+ user: number
+}
+
export interface TaskPinRequestApi {
/** Whether the task should be pinned for the requester. */
pinned: boolean
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 2c4295175e18..2efb175eba8a 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -75,6 +75,7 @@ import type {
TaskCommentsResponseApi,
TaskCreateApi,
TaskDetailDTOApi,
+ TaskHandoffRequestApi,
TaskMentionsListParams,
TaskPinRequestApi,
TaskPinResponseApi,
@@ -1340,6 +1341,28 @@ export const tasksCommentsRetrieve = async (
})
}
+export const getTasksHandoffCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/tasks/${id}/handoff/`
+}
+
+/**
+ * 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.
+ * @summary Hand a task off to a colleague
+ */
+export const tasksHandoffCreate = async (
+ projectId: string,
+ id: string,
+ taskHandoffRequestApi: TaskHandoffRequestApi,
+ options?: RequestInit
+): Promise<TaskDetailDTOApi> => {
+ return apiMutator<TaskDetailDTOApi>(getTasksHandoffCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(taskHandoffRequestApi),
+ })
+}
+
export const getTasksPinCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/tasks/${id}/pin/`
}
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index e15bcce3bab5..8e3f1cdeaa7a 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -1508,6 +1508,22 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod
'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.'
)
+/**
+ * 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.
+ * @summary Hand a task off to a colleague
+ */
+
+export const TasksHandoffCreateBody = /* @__PURE__ */ zod
+ .object({
+ user: zod
+ .number()
+ .min(1)
+ .describe(
+ "ID of the user taking over the task. Must have access to this project and not be the task's current owner."
+ ),
+ })
+ .describe('Request body for handing a task off to a colleague: they become its owner.')
+
/**
* API for managing tasks within a project. Tasks represent units of work to be performed by an agent.
*/
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index 7f027ab0926c..72ddf4bbff74 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -374,6 +374,9 @@ tools:
tasks-destroy:
operation: tasks_destroy
enabled: false
+ tasks-handoff-create:
+ operation: tasks_handoff_create
+ enabled: false
tasks-list:
operation: tasks_list
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2bba8a1c02e7..95548b96a378 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -79398,6 +79398,17 @@ export namespace Schemas {
runtime?: RuntimeEnum;
}
+ /**
+ * Request body for handing a task off to a colleague: they become its owner.
+ */
+ export interface TaskHandoffRequest {
+ /**
+ * ID of the user taking over the task. Must have access to this project and not be the task's current owner.
+ * @minimum 1
+ */
+ user: number;
+ }
+
export interface TaskPinRequest {
/** Whether the task should be pinned for the requester. */
pinned: boolean;