:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): add server-side archived flag to tasks (#59292)
Dylan Martin1eaf7724eb53
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.pyindex 3b9940b3ed0f..5affe337d8c9 100644--- a/products/tasks/backend/api.py+++ b/products/tasks/backend/api.py@@ -445,6 +445,14 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):else:qs = qs.filter(internal=False)+ archived_param = getattr(self.request, "validated_query_data", {}).get("archived")+ if archived_param == "true":+ qs = qs.filter(archived=True)+ elif archived_param == "all":+ pass+ else:+ qs = qs.filter(archived=False)+# select_related to avoid N+1 on created_by (UserBasicSerializer), team (slug property),# and GitHub integrations returned on task rows.qs = qs.select_related("created_by", "team", "github_integration", "github_user_integration").prefetch_related(diff --git a/products/tasks/backend/migrations/0032_task_archived_archived_at.py b/products/tasks/backend/migrations/0032_task_archived_archived_at.pynew file mode 100644index 000000000000..eda69e7db23a--- /dev/null+++ b/products/tasks/backend/migrations/0032_task_archived_archived_at.py@@ -0,0 +1,26 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("tasks", "0031_task_github_user_integration"),+ ]++ operations = [+ migrations.AddField(+ model_name="task",+ name="archived",+ field=models.BooleanField(+ default=False,+ help_text=(+ "If true, the task is hidden from default list responses. Used by PostHog Code clients "+ "to share archive state across desktop and mobile."+ ),+ ),+ ),+ migrations.AddField(+ model_name="task",+ name="archived_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/tasks/backend/migrations/0033_task_archived_idx.py b/products/tasks/backend/migrations/0033_task_archived_idx.pynew file mode 100644index 000000000000..d803e4d6ef32--- /dev/null+++ b/products/tasks/backend/migrations/0033_task_archived_idx.py@@ -0,0 +1,17 @@+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations, models+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("tasks", "0032_task_archived_archived_at"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="task",+ index=models.Index(fields=["archived"], name="posthog_task_archived_idx"),+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex fcd88617af3a..18161e199045 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0031_task_github_user_integration+0033_task_archived_idxdiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex eee4a3b6916d..107d8dd006eb 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -120,6 +120,15 @@ class Task(DeletedMetaFields, models.Model):help_text="If true, this task is for internal use and should not be exposed to end users.",)+ archived = models.BooleanField(+ default=False,+ help_text=(+ "If true, the task is hidden from default list responses. Used by PostHog Code clients "+ "to share archive state across desktop and mobile."+ ),+ )+ archived_at = models.DateTimeField(null=True, blank=True)+created_at = models.DateTimeField(default=django_timezone.now)updated_at = models.DateTimeField(auto_now=True)ci_prompt = models.TextField(@@ -133,6 +142,7 @@ class Task(DeletedMetaFields, models.Model):managed = Trueindexes = [models.Index(fields=["signal_report"], name="posthog_task_signal_report_idx"),+ models.Index(fields=["archived"], name="posthog_task_archived_idx"),]def __str__(self):diff --git a/products/tasks/backend/serializers.py b/products/tasks/backend/serializers.pyindex ae32f8184b46..f7cf62f3afd6 100644--- a/products/tasks/backend/serializers.py+++ b/products/tasks/backend/serializers.py@@ -127,6 +127,8 @@ class TaskSerializer(serializers.ModelSerializer):"signal_report_task_relationship","json_schema","internal",+ "archived",+ "archived_at","latest_run","created_at","updated_at",@@ -137,6 +139,7 @@ class TaskSerializer(serializers.ModelSerializer):"id","task_number","slug",+ "archived_at","created_at","updated_at","created_by",@@ -266,6 +269,8 @@ class TaskSerializer(serializers.ModelSerializer):validated_data.pop("origin_product", None)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"] != instance.archived:+ validated_data["archived_at"] = timezone.now() if validated_data["archived"] else Nonereturn super().update(instance, validated_data)@@ -850,6 +855,14 @@ class TaskListQuerySerializer(serializers.Serializer):required=False,help_text="When true, list internal tasks instead of user-facing ones. Honored in debug environments or for staff users; ignored for non-staff users in production. Defaults to excluding internal tasks.",)+ archived = serializers.ChoiceField(+ required=False,+ choices=["true", "false", "all"],+ help_text=(+ "Filter by archived state. Defaults to excluding archived tasks. Use 'true' to list only "+ "archived tasks, 'false' for the default, or 'all' to include both."+ ),+ )class TaskRepositoriesResponseSerializer(serializers.Serializer):diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 02263057ac9c..74a022bd888a 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -786,6 +786,115 @@ class TestTaskAPI(BaseTaskAPITest):self.assertTrue(task.deleted)self.assertIsNotNone(task.deleted_at)+ @parameterized.expand(+ [+ # (archived_param, expected_titles)+ ("default_excludes_archived", None, {"Active"}),+ ("archived_true_returns_only_archived", "true", {"Archived"}),+ ("archived_all_returns_both", "all", {"Active", "Archived"}),+ ("archived_false_returns_only_active", "false", {"Active"}),+ ]+ )+ def test_list_tasks_archived_filter(self, _name, archived_param, expected_titles):+ active_task = self.create_task("Active")+ archived_task = self.create_task("Archived")+ archived_task.archived = True+ archived_task.archived_at = django_timezone.now()+ archived_task.save(update_fields=["archived", "archived_at"])++ url = "/api/projects/@current/tasks/"+ if archived_param is not None:+ url = f"{url}?archived={archived_param}"+ response = self.client.get(url)+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ results = response.json()["results"]+ titles = {task["title"] for task in results}+ self.assertEqual(titles, expected_titles)+ # The expected set drives which task UUIDs we expect to come back.+ expected_ids: set[str] = set()+ if "Active" in expected_titles:+ expected_ids.add(str(active_task.id))+ if "Archived" in expected_titles:+ expected_ids.add(str(archived_task.id))+ self.assertEqual({task["id"] for task in results}, expected_ids)++ def test_list_tasks_rejects_invalid_archived_value(self):+ self.create_task("Active")++ response = self.client.get("/api/projects/@current/tasks/?archived=foo")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_retrieve_archived_task_still_works(self):+ task = self.create_task("Archived")+ task.archived = True+ task.archived_at = django_timezone.now()+ task.save(update_fields=["archived", "archived_at"])++ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertTrue(data["archived"])+ self.assertIsNotNone(data["archived_at"])++ def test_patch_archived_true_stamps_archived_at(self):+ task = self.create_task("Mine")+ self.assertFalse(task.archived)+ self.assertIsNone(task.archived_at)++ response = self.client.patch(+ f"/api/projects/@current/tasks/{task.id}/",+ {"archived": True},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertTrue(data["archived"])+ self.assertIsNotNone(data["archived_at"])++ task.refresh_from_db()+ self.assertTrue(task.archived)+ self.assertIsNotNone(task.archived_at)++ def test_patch_archived_false_clears_archived_at(self):+ task = self.create_task("Mine")+ task.archived = True+ task.archived_at = django_timezone.now()+ task.save(update_fields=["archived", "archived_at"])++ response = self.client.patch(+ f"/api/projects/@current/tasks/{task.id}/",+ {"archived": False},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertFalse(data["archived"])+ self.assertIsNone(data["archived_at"])++ task.refresh_from_db()+ self.assertFalse(task.archived)+ self.assertIsNone(task.archived_at)++ def test_patch_archived_idempotent_preserves_archived_at(self):+ task = self.create_task("Mine")+ original_archived_at = django_timezone.now() - timedelta(days=1)+ task.archived = True+ task.archived_at = original_archived_at+ task.save(update_fields=["archived", "archived_at"])++ response = self.client.patch(+ f"/api/projects/@current/tasks/{task.id}/",+ {"archived": True},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ task.refresh_from_db()+ self.assertTrue(task.archived)+ # archived_at should not be re-stamped because the value did not transition.+ self.assertEqual(task.archived_at, original_archived_at)+@patch("products.tasks.backend.api.execute_task_processing_workflow")def test_run_endpoint_triggers_workflow(self, mock_workflow):task = self.create_task()diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 6af41799cf96..c9dffe19eb29 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -261,6 +261,10 @@ export interface TaskApi {json_schema?: unknown/** If true, this task is for internal use and should not be exposed to end users. */internal?: boolean+ /** If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile. */+ archived?: boolean+ /** @nullable */+ readonly archived_at: string | null/*** Latest run details for this task* @nullable@@ -323,6 +327,10 @@ export interface PatchedTaskApi {json_schema?: unknown/** If true, this task is for internal use and should not be exposed to end users. */internal?: boolean+ /** If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile. */+ archived?: boolean+ /** @nullable */+ readonly archived_at?: string | null/*** Latest run details for this task* @nullable@@ -1475,6 +1483,15 @@ export type TaskAutomationsListParams = {export type TasksListParams = {/**+ * Filter by archived state. Defaults to excluding archived tasks. Use 'true' to list only archived tasks, 'false' for the default, or 'all' to include both.++* `true` - true+* `false` - false+* `all` - all+ * @minLength 1+ */+ archived?: TasksListArchived+ /*** Filter by creator user ID*/created_by?: number@@ -1528,6 +1545,14 @@ export type TasksListParams = {status?: TasksListStatus}+export type TasksListArchived = (typeof TasksListArchived)[keyof typeof TasksListArchived]++export const TasksListArchived = {+ True: 'true',+ False: 'false',+ All: 'all',+} as const+export type TasksListStatus = (typeof TasksListStatus)[keyof typeof TasksListStatus]export const TasksListStatus = {diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 1c35d2eaf08b..fbaacd0a0be4 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -122,6 +122,12 @@ export const TasksCreateBody = /* @__PURE__ */ zod.object({.boolean().optional().describe('If true, this task is for internal use and should not be exposed to end users.'),+ archived: zod+ .boolean()+ .optional()+ .describe(+ 'If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile.'+ ),ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),})@@ -170,6 +176,12 @@ export const TasksUpdateBody = /* @__PURE__ */ zod.object({.boolean().optional().describe('If true, this task is for internal use and should not be exposed to end users.'),+ archived: zod+ .boolean()+ .optional()+ .describe(+ 'If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile.'+ ),ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),})@@ -218,6 +230,12 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({.boolean().optional().describe('If true, this task is for internal use and should not be exposed to end users.'),+ archived: zod+ .boolean()+ .optional()+ .describe(+ 'If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile.'+ ),ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 772ff089175c..e786a1a3810b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24665,6 +24665,10 @@ export namespace Schemas {json_schema?: unknown;/** If true, this task is for internal use and should not be exposed to end users. */internal?: boolean;+ /** If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile. */+ archived?: boolean;+ /** @nullable */+ readonly archived_at: string | null;/*** Latest run details for this task* @nullable@@ -30557,6 +30561,10 @@ export namespace Schemas {json_schema?: unknown;/** If true, this task is for internal use and should not be exposed to end users. */internal?: boolean;+ /** If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile. */+ archived?: boolean;+ /** @nullable */+ readonly archived_at?: string | null;/*** Latest run details for this task* @nullable@@ -45186,6 +45194,15 @@ export namespace Schemas {};export type TasksListParams = {+ /**+ * Filter by archived state. Defaults to excluding archived tasks. Use 'true' to list only archived tasks, 'false' for the default, or 'all' to include both.++ * `true` - true+ * `false` - false+ * `all` - all+ * @minLength 1+ */+ archived?: TasksListArchived;/*** Filter by creator user ID*/@@ -45240,6 +45257,15 @@ export namespace Schemas {status?: TasksListStatus;};+ export type TasksListArchived = typeof TasksListArchived[keyof typeof TasksListArchived];+++ export const TasksListArchived = {+ True: 'true',+ False: 'false',+ All: 'all',+ } as const;+export type TasksListStatus = typeof TasksListStatus[keyof typeof TasksListStatus];