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): add space auto-archive policies (#90643)

Dylan Martin8421bd65ace2
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 201ede0d2a50..1174d966eae9 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -118,6 +118,7 @@ from products.tasks.backend.facade.tasks import (
reconcile_loop_trigger_schedules_task,
refresh_dev_stack_image_task,
refresh_stale_sandbox_custom_images_task,
+ sweep_inactive_tasks_task,
sweep_loop_task_retention_task,
)
from products.warehouse_sources.backend.facade.tasks import sweep_stopped_schema_syncs
@@ -362,6 +363,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="sweep loop task retention",
)
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="15"),
+ sweep_inactive_tasks_task.s(),
+ name="archive inactive tasks",
+ )
+
# Loop trigger schedule reconciliation - every 10 minutes, re-syncs schedules
# stranded pending/failed by a transient Temporal outage during create/edit.
add_periodic_task_with_expiry(
diff --git a/products/tasks/backend/access.py b/products/tasks/backend/access.py
index 3166cfbacc17..82b20fe103c3 100644
--- a/products/tasks/backend/access.py
+++ b/products/tasks/backend/access.py
@@ -1,6 +1,8 @@
from enum import StrEnum
from typing import TYPE_CHECKING
+from django.conf import settings
+
from posthog.cloud_utils import get_cached_instance_license
from posthog.models.user import User
from posthog.ph_client import feature_enabled_or_false, get_feature_flag_or_none
@@ -55,6 +57,10 @@ def get_desktop_access_decision(user: User, organization: "Organization") -> Des
if not user or not user.is_authenticated or not user.distinct_id:
raise DesktopAccessResolutionError("Authentication is required to evaluate Desktop access")
+ if settings.DEBUG:
+ observe_desktop_access_decision(outcome="override")
+ return DesktopAccessDecision.ALLOWED
+
organization_id = str(organization.id)
groups = {"organization": organization_id}
group_properties = {"organization": {"id": organization_id}}
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 9cd3095f402b..0a7f42d73b1e 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -165,6 +165,13 @@ WIZARD_CLOUD_RUN_RUNTIME_ADAPTER = "claude"
WIZARD_CLOUD_RUN_MODEL = "claude-sonnet-5"
WIZARD_CLOUD_RUN_AI_STAGE = "wizard_pr_agent"
+
+class _AutoArchiveUnchanged:
+ pass
+
+
+_AUTO_ARCHIVE_UNCHANGED = _AutoArchiveUnchanged()
+
__all__ = [
"SandboxNetworkAccessLevel",
"SandboxSnapshotStatus",
@@ -7439,6 +7446,7 @@ def _channel_to_dto(channel: Channel, *, starred: bool = False) -> contracts.Cha
system_role=channel.system_role,
github_integration=channel.github_integration_id,
repositories=channel.repositories,
+ auto_archive_after_days=channel.auto_archive_after_days,
created_at=channel.created_at,
created_by=_user_basic_info(channel.created_by if channel.created_by_id else None),
starred=starred,
@@ -7667,9 +7675,11 @@ def update_channel(
team_id: int,
user_id: int | None,
*,
+ can_manage_shared_auto_archive: bool,
name: str | None = None,
github_integration: Integration | None = None,
repositories: list[str] | None = None,
+ auto_archive_after_days: int | None | _AutoArchiveUnchanged = _AUTO_ARCHIVE_UNCHANGED,
) -> contracts.ChannelDTO | str:
"""Update a visible channel."""
channel = Channel.objects.filter(id=channel_id, team_id=team_id, deleted=False).first()
@@ -7680,6 +7690,8 @@ def update_channel(
return "not_found"
if name is not None:
return "personal"
+ elif not isinstance(auto_archive_after_days, _AutoArchiveUnchanged) and not can_manage_shared_auto_archive:
+ return "auto_archive_forbidden"
if name is not None and _is_general_channel(channel):
return "general"
update_fields: list[str] = []
@@ -7693,6 +7705,9 @@ def update_channel(
channel.repositories = repositories
channel.github_integration = github_integration if repositories else None
update_fields.extend(["repositories", "github_integration"])
+ if not isinstance(auto_archive_after_days, _AutoArchiveUnchanged):
+ channel.auto_archive_after_days = auto_archive_after_days
+ update_fields.append("auto_archive_after_days")
if not update_fields:
return _channel_to_dto(channel)
try:
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 8353106014a0..042eea0c2b6d 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -211,6 +211,7 @@ class ChannelDTO:
channel_type: str
github_integration: int | None
repositories: list[str]
+ auto_archive_after_days: int | None
created_at: datetime
created_by: "TaskUserBasicInfo | None" = None
starred: bool = False
diff --git a/products/tasks/backend/facade/tasks.py b/products/tasks/backend/facade/tasks.py
index ea0589364f4d..f873b3723eae 100644
--- a/products/tasks/backend/facade/tasks.py
+++ b/products/tasks/backend/facade/tasks.py
@@ -10,8 +10,9 @@ from celery import shared_task
from products.tasks.backend.loop_reconciliation import reconcile_loop_trigger_schedules_task
from products.tasks.backend.loop_retention import sweep_loop_task_retention_task
+from products.tasks.backend.task_auto_archive import sweep_inactive_tasks_task
-__all__ = ["reconcile_loop_trigger_schedules_task", "sweep_loop_task_retention_task"]
+__all__ = ["reconcile_loop_trigger_schedules_task", "sweep_inactive_tasks_task", "sweep_loop_task_retention_task"]
logger = logging.getLogger(__name__)
diff --git a/products/tasks/backend/migrations/0108_channel_auto_archive_after_days.py b/products/tasks/backend/migrations/0108_channel_auto_archive_after_days.py
new file mode 100644
index 000000000000..3784335522dc
--- /dev/null
+++ b/products/tasks/backend/migrations/0108_channel_auto_archive_after_days.py
@@ -0,0 +1,19 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("tasks", "0107_remove_code_invites_from_state")]
+
+ operations = [
+ migrations.AddField(
+ model_name="channel",
+ name="auto_archive_after_days",
+ field=models.PositiveSmallIntegerField(
+ blank=True,
+ help_text=(
+ "Archive inactive tasks in this channel after this many days. Null disables automatic archiving."
+ ),
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index fc041ae0ed81..4cb3616d51c0 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0107_remove_code_invites_from_state
+0108_channel_auto_archive_after_days
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 1529edb59162..5f77113eeb0c 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -226,6 +226,11 @@ class Channel(TeamScopedRootMixin):
blank=True,
help_text="GitHub repositories inherited by new tasks in this channel",
)
+ auto_archive_after_days = models.PositiveSmallIntegerField(
+ null=True,
+ blank=True,
+ help_text="Archive inactive tasks in this channel after this many days. Null disables automatic archiving.",
+ )
deleted = models.BooleanField(default=False)
created_at = models.DateTimeField(default=django_timezone.now)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index e74807130dd6..826a10b23730 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -2034,6 +2034,7 @@ class ChannelSerializer(DataclassSerializer):
"channel_type",
"github_integration",
"repositories",
+ "auto_archive_after_days",
"created_at",
"created_by",
"starred",
@@ -2158,6 +2159,13 @@ class ChannelUpdateSerializer(serializers.Serializer):
max_length=10,
help_text="GitHub repositories inherited by new tasks in this channel.",
)
+ auto_archive_after_days = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=1,
+ max_value=365,
+ help_text="Days of inactivity before tasks in this channel are archived. Accepts 1 through 365. Null disables automatic archiving.",
+ )
def validate_name(self, value: str) -> str:
if tasks_facade.is_reserved_channel_name(value):
diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.py
index da90d6f50210..c4b1653363fd 100644
--- a/products/tasks/backend/presentation/views/channels_api.py
+++ b/products/tasks/backend/presentation/views/channels_api.py
@@ -14,6 +14,7 @@ from rest_framework.response import Response
from posthog.api.mixins import validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
+from posthog.models import OrganizationMembership
from posthog.models.user import User
from posthog.permissions import APIScopePermission
@@ -244,13 +245,24 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def partial_update(self, request, pk=None, **kwargs):
serializer = ChannelUpdateSerializer(data=request.data, context={"team_id": self.team_id}, partial=True)
serializer.is_valid(raise_exception=True)
- result = tasks_facade.update_channel(pk, self.team_id, self._user_id(), **serializer.validated_data)
+ membership_level = self.user_permissions.current_team.effective_membership_level
+ result = tasks_facade.update_channel(
+ pk,
+ self.team_id,
+ self._user_id(),
+ can_manage_shared_auto_archive=(
+ membership_level is not None and membership_level >= OrganizationMembership.Level.ADMIN
+ ),
+ **serializer.validated_data,
+ )
if result == "not_found":
raise NotFound()
if result == "personal":
raise PermissionDenied("Personal channels cannot be renamed")
if result == "general":
raise PermissionDenied("The general space can't be renamed")
+ if result == "auto_archive_forbidden":
+ raise PermissionDenied("Only project admins can change automatic archiving for shared spaces")
if result == "invalid_name":
return Response({"detail": "Invalid channel name"}, status=status.HTTP_400_BAD_REQUEST)
if result == "name_taken":
diff --git a/products/tasks/backend/task_auto_archive.py b/products/tasks/backend/task_auto_archive.py
new file mode 100644
index 000000000000..8747241c5137
--- /dev/null
+++ b/products/tasks/backend/task_auto_archive.py
@@ -0,0 +1,106 @@
+from datetime import datetime, timedelta
+from uuid import UUID
+
+from django.db import OperationalError, ProgrammingError
+from django.db.models import Exists, OuterRef, QuerySet
+from django.utils import timezone as django_timezone
+
+import structlog
+import psycopg.errors
+from celery import shared_task
+from celery.exceptions import SoftTimeLimitExceeded
+
+from posthog.exceptions_capture import capture_exception
+from posthog.scoping_audit import skip_team_scope_audit
+
+from products.tasks.backend.models import Channel, Task, TaskPin, TaskPresence, TaskRun
+
+logger = structlog.get_logger(__name__)
+
+AUTO_ARCHIVE_SWEEP_LIMIT = 5_000
+_NON_TERMINAL_RUN_STATUSES = (
+ TaskRun.Status.NOT_STARTED,
+ TaskRun.Status.QUEUED,
+ TaskRun.Status.IN_PROGRESS,
+)
+
+
+def _archivable_tasks(*, channel_id: UUID, team_id: int, cutoff: datetime, now: datetime) -> QuerySet[Task]:
+ active_run = TaskRun.objects.filter( # nosemgrep: celery-task-team-scope-audit
+ task_id=OuterRef("pk"), team_id=team_id, status__in=_NON_TERMINAL_RUN_STATUSES
+ )
+ pin = TaskPin.objects.filter(
+ task_id=OuterRef("pk"),
+ task__team_id=team_id,
+ )
+ active_presence = TaskPresence.objects.for_team(team_id).filter(task_id=OuterRef("pk"), expires_at__gt=now)
+ return (
+ Task.objects.filter( # nosemgrep: celery-task-team-scope-audit
+ channel_id=channel_id,
+ team_id=team_id,
+ archived=False,
+ deleted=False,
+ internal=False,
+ last_activity_at__lt=cutoff,
+ )
+ .filter(~Exists(active_run))
+ .filter(~Exists(pin))
+ .filter(~Exists(active_presence))
+ )
+
+
+def sweep_inactive_tasks(*, at: datetime | None = None, limit: int = AUTO_ARCHIVE_SWEEP_LIMIT) -> int:
+ now = at or django_timezone.now()
+ archived_count = 0
+ policies = (
+ Channel.objects.unscoped()
+ .filter(deleted=False, auto_archive_after_days__isnull=False)
+ .values_list("id", "team_id", "auto_archive_after_days")
+ .iterator(chunk_size=500)
+ )
+
+ for channel_id, team_id, inactivity_days in policies:
+ if inactivity_days is None:
+ continue
+ remaining = limit - archived_count
+ if remaining <= 0:
+ break
+ cutoff = now - timedelta(days=inactivity_days)
+ task_ids = list(
+ _archivable_tasks(channel_id=channel_id, team_id=team_id, cutoff=cutoff, now=now)
+ .order_by("last_activity_at")
+ .values_list("id", flat=True)[:remaining]
+ )
+ if not task_ids:
+ continue
+ archived_count += (
+ _archivable_tasks(channel_id=channel_id, team_id=team_id, cutoff=cutoff, now=now)
+ .filter(id__in=task_ids)
+ .update(archived=True, archived_at=now)
+ )
+
+ return archived_count
+
+
+@shared_task(ignore_result=True, soft_time_limit=110, time_limit=170)
+@skip_team_scope_audit
+def sweep_inactive_tasks_task() -> None:
+ try:
+ archived_count = sweep_inactive_tasks()
+ except SoftTimeLimitExceeded:
+ raise
+ except ProgrammingError as exc:
+ if isinstance(exc.__cause__, psycopg.errors.UndefinedTable | psycopg.errors.UndefinedColumn):
+ logger.debug("task_auto_archive.sweep_missing_schema", exception=exc)
+ return
+ capture_exception(exc)
+ logger.exception("task_auto_archive.sweep_failed")
+ return
+ except OperationalError as exc:
+ logger.warning("task_auto_archive.sweep_transient_db_error", error=str(exc))
+ return
+ except Exception as exc:
+ capture_exception(exc)
+ logger.exception("task_auto_archive.sweep_failed")
+ return
+ logger.info("task_auto_archive.swept", archived_count=archived_count)
diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.py
index 3ce4aabaf48f..d90c94c1b8e6 100644
--- a/products/tasks/backend/tests/test_channels_api.py
+++ b/products/tasks/backend/tests/test_channels_api.py
@@ -405,6 +405,60 @@ class ChannelsAPITestCase(TestCase):
self.assertEqual(renamed.status_code, status.HTTP_200_OK, renamed.content)
self.assertEqual(Channel.objects.unscoped().get(id=channel_id).name, "renamed")
+ def test_project_admin_can_configure_shared_space_auto_archive(self):
+ channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]
+ other_client = APIClient()
+ other_client.force_authenticate(self.other_user)
+
+ configured = other_client.patch(
+ f"{self._channels_url()}{channel_id}/", {"auto_archive_after_days": 45}, format="json"
+ )
+
+ self.assertEqual(configured.status_code, status.HTTP_200_OK, configured.content)
+ self.assertEqual(configured.json()["auto_archive_after_days"], 45)
+ listed = self.client.get(self._channels_url())
+ self.assertEqual(listed.json()[0]["auto_archive_after_days"], 45)
+
+ for invalid_days in (0, 366):
+ invalid = self.client.patch(
+ f"{self._channels_url()}{channel_id}/",
+ {"auto_archive_after_days": invalid_days},
+ format="json",
+ )
+ self.assertEqual(invalid.status_code, status.HTTP_400_BAD_REQUEST, invalid.content)
+ self.assertEqual(Channel.objects.unscoped().get(id=channel_id).auto_archive_after_days, 45)
+
+ disabled = self.client.patch(
+ f"{self._channels_url()}{channel_id}/", {"auto_archive_after_days": None}, format="json"
+ )
+ self.assertEqual(disabled.status_code, status.HTTP_200_OK, disabled.content)
+ self.assertIsNone(disabled.json()["auto_archive_after_days"])
+
+ def test_project_member_can_only_configure_their_personal_space_auto_archive(self):
+ OrganizationMembership.objects.filter(user=self.other_user, organization=self.organization).update(
+ level=OrganizationMembership.Level.MEMBER
+ )
+ shared_channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]
+ other_client = APIClient()
+ other_client.force_authenticate(self.other_user)
+ personal_channel_id = next(
+ channel["id"]
+ for channel in self._provision(other_client)["channels"]
+ if channel["channel_type"] == "personal"
+ )
+
+ shared = other_client.patch(
+ f"{self._channels_url()}{shared_channel_id}/", {"auto_archive_after_days": 1}, format="json"
+ )
+ personal = other_client.patch(
+ f"{self._channels_url()}{personal_channel_id}/", {"auto_archive_after_days": 1}, format="json"
+ )
+
+ self.assertEqual(shared.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(personal.status_code, status.HTTP_200_OK, personal.content)
+ self.assertIsNone(Channel.objects.unscoped().get(id=shared_channel_id).auto_archive_after_days)
+ self.assertEqual(personal.json()["auto_archive_after_days"], 1)
+
def test_public_channel_task_is_readable_but_not_controllable_by_teammates(self):
channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]
created = self.client.post(
diff --git a/products/tasks/backend/tests/test_desktop_access.py b/products/tasks/backend/tests/test_desktop_access.py
index b17f3648c39b..6403568665fd 100644
--- a/products/tasks/backend/tests/test_desktop_access.py
+++ b/products/tasks/backend/tests/test_desktop_access.py
@@ -2,6 +2,7 @@ from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache
+from django.test import override_settings
from parameterized import parameterized
from rest_framework import status
@@ -30,6 +31,15 @@ class TestDesktopAccessPolicy(APIBaseTest):
self.feature_flag_patcher.stop()
super().tearDown()
+ @override_settings(DEBUG=True)
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_debug_mode_allows_access_without_external_resolution(self, mock_funding) -> None:
+ decision = get_desktop_access_decision(self.user, self.organization)
+
+ self.assertTrue(decision.allowed)
+ self.mock_feature_flag.assert_not_called()
+ mock_funding.assert_not_called()
+
@parameterized.expand(
[
("normal", None, PrepaidCreditState.NONE, True, None),
diff --git a/products/tasks/backend/tests/test_task_auto_archive.py b/products/tasks/backend/tests/test_task_auto_archive.py
new file mode 100644
index 000000000000..2ef8ce37d187
--- /dev/null
+++ b/products/tasks/backend/tests/test_task_auto_archive.py
@@ -0,0 +1,124 @@
+from datetime import timedelta
+
+from django.test import TestCase
+from django.utils import timezone as django_timezone
+
+from posthog.models import Organization, Team, User, UserPushToken
+
+from products.tasks.backend.models import Channel, Task, TaskPin, TaskPresence, TaskRun
+from products.tasks.backend.task_auto_archive import sweep_inactive_tasks
+
+
+class TestTaskAutoArchive(TestCase):
+ def setUp(self) -> None:
+ organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=organization, name="Test Team")
+ self.user = User.objects.create_user(email="[email protected]", first_name="Author", password="password")
+ self.now = django_timezone.now()
+
+ def _channel(self, *, name: str, inactivity_days: int | None) -> Channel:
+ return Channel.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ created_by=self.user,
+ name=name,
+ auto_archive_after_days=inactivity_days,
+ )
+
+ def _task(self, *, channel: Channel, age_days: int) -> Task:
+ task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ channel=channel,
+ title="Test task",
+ description="Test description",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ Task.objects.filter(id=task.id).update(last_activity_at=self.now - timedelta(days=age_days))
+ task.refresh_from_db()
+ return task
+
+ def test_sweep_uses_each_space_threshold(self) -> None:
+ enabled = self._channel(name="enabled", inactivity_days=3)
+ disabled = self._channel(name="disabled", inactivity_days=None)
+ stale = self._task(channel=enabled, age_days=4)
+ recent = self._task(channel=enabled, age_days=2)
+ disabled_stale = self._task(channel=disabled, age_days=30)
+
+ self.assertEqual(sweep_inactive_tasks(at=self.now), 1)
+
+ stale.refresh_from_db()
+ recent.refresh_from_db()
+ disabled_stale.refresh_from_db()
+ self.assertTrue(stale.archived)
+ self.assertEqual(stale.archived_at, self.now)
+ self.assertFalse(recent.archived)
+ self.assertFalse(disabled_stale.archived)
+
+ def test_sweep_keeps_active_and_pinned_tasks(self) -> None:
+ channel = self._channel(name="protected", inactivity_days=1)
+ active = self._task(channel=channel, age_days=3)
+ pinned = self._task(channel=channel, age_days=3)
+ TaskRun.objects.create(task=active, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ Task.objects.filter(id=active.id).update(last_activity_at=self.now - timedelta(days=3))
+ TaskPin.objects.create(user=self.user, task=pinned)
+
+ self.assertEqual(sweep_inactive_tasks(at=self.now), 0)
+
+ active.refresh_from_db()
+ pinned.refresh_from_db()
+ self.assertFalse(active.archived)
+ self.assertFalse(pinned.archived)
+
+ def test_sweep_keeps_task_with_active_presence(self) -> None:
+ channel = self._channel(name="protected", inactivity_days=1)
+ viewed = self._task(channel=channel, age_days=3)
+ no_longer_viewed = self._task(channel=channel, age_days=3)
+ push_token = UserPushToken.objects.create(
+ user=self.user,
+ token="ExponentPushToken[auto-archive-test]",
+ platform=UserPushToken.Platform.IOS,
+ )
+ TaskPresence.objects.unscoped().create(
+ team=self.team,
+ task=viewed,
+ user=self.user,
+ push_token=push_token,
+ expires_at=self.now + timedelta(minutes=1),
+ )
+ TaskPresence.objects.unscoped().create(
+ team=self.team,
+ task=no_longer_viewed,
+ user=self.user,
+ push_token=push_token,
+ expires_at=self.now - timedelta(minutes=1),
+ )
+
+ self.assertEqual(sweep_inactive_tasks(at=self.now), 1)
+
+ viewed.refresh_from_db()
+ no_longer_viewed.refresh_from_db()
+ self.assertFalse(viewed.archived)
+ self.assertTrue(no_longer_viewed.archived)
+
+ def test_sweep_scopes_protection_checks_to_the_task_team(self) -> None:
+ other_team = Team.objects.create(organization=self.team.organization, name="Other Team")
+ channel = self._channel(name="scoped", inactivity_days=1)
+ stale = self._task(channel=channel, age_days=3)
+ push_token = UserPushToken.objects.create(
+ user=self.user,
+ token="ExponentPushToken[other-team-auto-archive-test]",
+ platform=UserPushToken.Platform.IOS,
+ )
+ TaskRun.objects.create(task=stale, team=other_team, status=TaskRun.Status.IN_PROGRESS)
+ TaskPresence.objects.for_team(other_team.id).create(
+ team=other_team,
+ task=stale,
+ user=self.user,
+ push_token=push_token,
+ expires_at=self.now + timedelta(minutes=1),
+ )
+
+ self.assertEqual(sweep_inactive_tasks(at=self.now), 1)
+
+ stale.refresh_from_db()
+ self.assertTrue(stale.archived)
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index e5a3d85db0f6..8d760d3c8416 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1103,6 +1103,8 @@ export interface ChannelDTOApi {
/** @nullable */
github_integration: number | null
repositories: string[]
+ /** @nullable */
+ auto_archive_after_days: number | null
created_at: string
created_by?: TaskUserBasicInfoApi | null
starred?: boolean
@@ -1203,6 +1205,13 @@ export interface PatchedChannelUpdateApi {
* @items.maxLength 255
*/
repositories?: string[]
+ /**
+ * Days of inactivity before tasks in this channel are archived. Accepts 1 through 365. Null disables automatic archiving.
+ * @minimum 1
+ * @maximum 365
+ * @nullable
+ */
+ auto_archive_after_days?: number | null
}
export interface ChannelDeleteConflictApi {
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index b8ed65b373ec..9c73aaec79f8 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -953,6 +953,8 @@ export const taskChannelsPartialUpdateBodyRepositoriesItemMax = 255
export const taskChannelsPartialUpdateBodyRepositoriesMax = 10
+export const taskChannelsPartialUpdateBodyAutoArchiveAfterDaysMax = 365
+
export const TaskChannelsPartialUpdateBody = /* @__PURE__ */ zod.object({
name: zod
.string()
@@ -968,6 +970,14 @@ export const TaskChannelsPartialUpdateBody = /* @__PURE__ */ zod.object({
.max(taskChannelsPartialUpdateBodyRepositoriesMax)
.optional()
.describe('GitHub repositories inherited by new tasks in this channel.'),
+ auto_archive_after_days: zod
+ .number()
+ .min(1)
+ .max(taskChannelsPartialUpdateBodyAutoArchiveAfterDaysMax)
+ .nullish()
+ .describe(
+ 'Days of inactivity before tasks in this channel are archived. Accepts 1 through 365. Null disables automatic archiving.'
+ ),
})
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 99d272594a3c..3f1e6ea09b48 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17087,6 +17087,8 @@ export namespace Schemas {
/** @nullable */
github_integration: number | null;
repositories: string[];
+ /** @nullable */
+ auto_archive_after_days: number | null;
created_at: string;
created_by?: TaskUserBasicInfo | null;
starred?: boolean;
@@ -60151,6 +60153,13 @@ export namespace Schemas {
* @items.maxLength 255
*/
repositories?: string[];
+ /**
+ * Days of inactivity before tasks in this channel are archived. Accepts 1 through 365. Null disables automatic archiving.
+ * @minimum 1
+ * @maximum 365
+ * @nullable
+ */
+ auto_archive_after_days?: number | null;
}
export interface PatchedClusteringJob {