Skip to content

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

fix(tasks): restore task pin endpoints (#75212)

Alessandro Pogliaghi3a16dfc0f92c
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 7d20056f36cb..b49f702b0c3f 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -65,6 +65,7 @@ from products.tasks.backend.models import (
Task,
TaskActivity,
TaskAutomation,
+ TaskPin,
TaskRun,
TaskSession,
TaskThreadMessage,
@@ -3761,6 +3762,25 @@ def task_visible(task_id: str | UUID, team_id: int, user_id: int | None, *, for_
return _visible_task_qs(team_id, user_id, for_control=for_control).filter(id=task_id).exists()
+def list_pinned_task_ids(team_id: int, user_id: int) -> list[UUID]:
+ visible_tasks = _visible_task_qs(team_id, user_id).values("id")
+ return list(
+ TaskPin.objects.filter(user_id=user_id, task_id__in=Subquery(visible_tasks))
+ .order_by("-pinned_at")
+ .values_list("task_id", flat=True)
+ )
+
+
+def set_task_pinned(task_id: str | UUID, team_id: int, user_id: int, *, pinned: bool) -> bool | None:
+ if not task_visible(task_id, team_id, user_id):
+ return None
+ if pinned:
+ TaskPin.objects.get_or_create(user_id=user_id, task_id=task_id)
+ else:
+ TaskPin.objects.filter(user_id=user_id, task_id=task_id).delete()
+ return pinned
+
+
async def select_repository_for_message(team_id: int, user_id: int, message: str, *, origin_product: str) -> str | None:
"""Pick the repository a free-form chat message is most likely about.
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 351efefa128e..398351a454b3 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -1611,6 +1611,22 @@ class TaskRepositoriesResponseSerializer(serializers.Serializer):
)
+class PinnedTaskIdsResponseSerializer(serializers.Serializer):
+ task_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ help_text="Visible task IDs pinned by the requester, newest pin first.",
+ )
+
+
+class TaskPinRequestSerializer(serializers.Serializer):
+ pinned = serializers.BooleanField(help_text="Whether the task should be pinned for the requester.")
+
+
+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.")
+
+
class RepositoryReadinessQuerySerializer(serializers.Serializer):
repository = serializers.CharField(required=True, help_text="Repository in org/repo format")
window_days = serializers.IntegerField(required=False, default=7, min_value=1, max_value=30)
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index a2c7be89ab49..4ef422bf8f6e 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -61,6 +61,7 @@ from products.tasks.backend.facade.streams import (
from products.tasks.backend.presentation.serializers import (
CodeInviteRedeemRequestSerializer,
ConnectionTokenResponseSerializer,
+ PinnedTaskIdsResponseSerializer,
RepositoryReadinessQuerySerializer,
RepositoryReadinessResponseSerializer,
SandboxCustomImageBuildSerializer,
@@ -77,6 +78,8 @@ from products.tasks.backend.presentation.serializers import (
TaskAutomationWriteSerializer,
TaskCreateSerializer,
TaskListQuerySerializer,
+ TaskPinRequestSerializer,
+ TaskPinResponseSerializer,
TaskPresenceBeaconRequestSerializer,
TaskRepositoriesResponseSerializer,
TaskRunAppendLogRequestSerializer,
@@ -364,6 +367,30 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
serializer = TaskRepositoriesResponseSerializer({"repositories": repositories})
return Response(serializer.data)
+ @extend_schema(
+ responses={200: PinnedTaskIdsResponseSerializer},
+ summary="List pinned tasks",
+ description="Return the visible tasks pinned by the requester in the current project.",
+ )
+ @action(detail=False, methods=["get"], url_path="pinned", required_scopes=["task:read"])
+ def pinned(self, request, **kwargs):
+ user_id = self._user_id()
+ if user_id is None:
+ raise NotFound()
+ return Response({"task_ids": tasks_facade.list_pinned_task_ids(self.team_id, user_id)})
+
+ @extend_schema(request=TaskPinRequestSerializer, responses={200: TaskPinResponseSerializer})
+ @action(detail=True, methods=["post"], url_path="pin", required_scopes=["task:write"])
+ @validated_request(request_serializer=TaskPinRequestSerializer)
+ def pin(self, request, pk=None, **kwargs):
+ user_id = self._user_id()
+ if user_id is None:
+ raise NotFound()
+ pinned = tasks_facade.set_task_pinned(pk, self.team_id, user_id, pinned=request.validated_data["pinned"])
+ if pinned is None:
+ raise NotFound()
+ return Response({"task_id": pk, "pinned": pinned})
+
@extend_schema(
responses={
200: OpenApiResponse(
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 31c004b616dd..29e501f9ab55 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -65,6 +65,7 @@ from products.tasks.backend.models import (
Task,
TaskArtifact,
TaskAutomation,
+ TaskPin,
TaskRun,
TaskSession,
)
@@ -936,6 +937,67 @@ class TestTaskVisibilityInternalDebugRegionGate(BaseTaskAPITest):
class TestTaskAPI(BaseTaskAPITest):
+ def test_pin_state_is_persisted_per_user(self):
+ task = self.create_task()
+
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/pin/", {"pinned": True}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"task_id": str(task.id), "pinned": True})
+ self.assertTrue(TaskPin.objects.filter(user=self.user, task=task).exists())
+
+ response = self.client.get("/api/projects/@current/tasks/pinned/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"task_ids": [str(task.id)]})
+
+ other_user = self.create_organization_user()
+ self.client.force_authenticate(other_user)
+ response = self.client.get("/api/projects/@current/tasks/pinned/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"task_ids": []})
+
+ def test_setting_pin_state_is_idempotent(self):
+ task = self.create_task()
+ url = f"/api/projects/@current/tasks/{task.id}/pin/"
+
+ self.client.post(url, {"pinned": True}, format="json")
+ self.client.post(url, {"pinned": True}, format="json")
+ self.assertEqual(TaskPin.objects.filter(user=self.user, task=task).count(), 1)
+
+ response = self.client.post(url, {"pinned": False}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertFalse(TaskPin.objects.filter(user=self.user, task=task).exists())
+
+ def test_cannot_pin_invisible_task(self):
+ other_user = self.create_organization_user()
+ task = self.create_task(created_by=other_user)
+
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/pin/", {"pinned": True}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_pins_are_team_scoped_and_hidden_after_task_deletion(self):
+ task = self.create_task()
+ self.client.post(f"/api/projects/@current/tasks/{task.id}/pin/", {"pinned": True}, format="json")
+ task.deleted = True
+ task.save(update_fields=["deleted"])
+
+ response = self.client.get("/api/projects/@current/tasks/pinned/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"task_ids": []})
+
+ other_organization = Organization.objects.create(name="Other Org")
+ other_team = Team.objects.create(organization=other_organization, name="Other Team")
+ other_task = Task.objects.create(
+ team=other_team,
+ created_by=self.user,
+ title="Other team task",
+ description="Not visible here",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{other_task.id}/pin/", {"pinned": True}, format="json"
+ )
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
def test_list_tasks(self):
self.create_task("Task 1")
self.create_task("Task 2")
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 2ef2e7534103..7e594b50d0a8 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1867,6 +1867,18 @@ export interface PatchedTaskWriteApi {
channel?: string | null
}
+export interface TaskPinRequestApi {
+ /** Whether the task should be pinned for the requester. */
+ pinned: boolean
+}
+
+export interface TaskPinResponseApi {
+ /** Task whose pin state was updated. */
+ task_id: string
+ /** Current pin state for the requester. */
+ pinned: boolean
+}
+
/**
* Request body for the presence beacon and beacon-leave endpoints.
*
@@ -3290,6 +3302,11 @@ export interface WizardCloudRunDTOApi {
started_at?: string | null
}
+export interface PinnedTaskIdsResponseApi {
+ /** Visible task IDs pinned by the requester, newest pin first. */
+ task_ids: string[]
+}
+
export interface TaskRepositoriesResponseApi {
/** Distinct repositories in use by non-deleted, non-internal tasks for the current team. */
repositories: string[]
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 73d2cc0ee28d..dca90388ad78 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -46,6 +46,7 @@ import type {
PatchedTaskRunSetOutputRequestApi,
PatchedTaskRunUpdateApi,
PatchedTaskWriteApi,
+ PinnedTaskIdsResponseApi,
RepositoryReadinessResponseApi,
SandboxCustomImageBuildApi,
SandboxCustomImageDTOApi,
@@ -68,6 +69,8 @@ import type {
TaskCreateApi,
TaskDetailDTOApi,
TaskMentionsListParams,
+ TaskPinRequestApi,
+ TaskPinResponseApi,
TaskPresenceBeaconRequestApi,
TaskRepositoriesResponseApi,
TaskRunAppendLogRequestApi,
@@ -1114,6 +1117,27 @@ export const tasksDestroy = async (projectId: string, id: string, options?: Requ
})
}
+export const getTasksPinCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/tasks/${id}/pin/`
+}
+
+/**
+ * API for managing tasks within a project. Tasks represent units of work to be performed by an agent.
+ */
+export const tasksPinCreate = async (
+ projectId: string,
+ id: string,
+ taskPinRequestApi: TaskPinRequestApi,
+ options?: RequestInit
+): Promise<TaskPinResponseApi> => {
+ return apiMutator<TaskPinResponseApi>(getTasksPinCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(taskPinRequestApi),
+ })
+}
+
export const getTasksPresenceCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/tasks/${id}/presence/`
}
@@ -1984,6 +2008,24 @@ export const tasksActiveWizardRunRetrieve = async (
})
}
+export const getTasksPinnedRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/tasks/pinned/`
+}
+
+/**
+ * Return the visible tasks pinned by the requester in the current project.
+ * @summary List pinned tasks
+ */
+export const tasksPinnedRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<PinnedTaskIdsResponseApi> => {
+ return apiMutator<PinnedTaskIdsResponseApi>(getTasksPinnedRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getTasksRepositoriesRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/tasks/repositories/`
}
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 21d2d5d863cc..918eef075705 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -1492,6 +1492,13 @@ 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.'
)
+/**
+ * API for managing tasks within a project. Tasks represent units of work to be performed by an agent.
+ */
+export const TasksPinCreateBody = /* @__PURE__ */ zod.object({
+ pinned: zod.boolean().describe('Whether the task should be pinned for the requester.'),
+})
+
/**
* Idempotent upsert: marks the calling user + `device_id` as actively watching this task for the next ~60 seconds. While at least one device for the user has a non-expired presence row for this task, the push fanout will skip ALL of that user's other registered devices for task notifications — the contract is 'if any device is demonstrably watching, suppress the others'. Clients call this every ~30s while the task screen is foregrounded. `device_id` is the UUID of the caller's UserPushToken row.
* @summary Beacon presence for a device watching this task
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index d9d67d7c76cd..9fb2f449e99d 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -314,6 +314,12 @@ tools:
tasks-partial-update:
operation: tasks_partial_update
enabled: false
+ tasks-pin-create:
+ operation: tasks_pin_create
+ enabled: false
+ tasks-pinned-retrieve:
+ operation: tasks_pinned_retrieve
+ enabled: false
tasks-presence-create:
operation: tasks_presence_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5369f642cfad..54ed78b7c240 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55368,6 +55368,11 @@ export namespace Schemas {
homepage?: PinnedSceneTab | null;
}
+ export interface PinnedTaskIdsResponse {
+ /** Visible task IDs pinned by the requester, newest pin first. */
+ task_ids: string[];
+ }
+
export interface PlainThreadSignalExtra {
status: string | null;
priority: string | null;
@@ -68629,6 +68634,18 @@ export namespace Schemas {
runtime?: RuntimeEnum;
}
+ export interface TaskPinRequest {
+ /** Whether the task should be pinned for the requester. */
+ pinned: boolean;
+ }
+
+ export interface TaskPinResponse {
+ /** Task whose pin state was updated. */
+ task_id: string;
+ /** Current pin state for the requester. */
+ pinned: boolean;
+ }
+
/**
* Request body for the presence beacon and beacon-leave endpoints.
*