: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): order task and session lists by last activity (#82781)
Adam Bowkeref0afe4dbf4c
diff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txtindex ac92e62898dc..61135cc4f630 100644--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt@@ -17,6 +17,7 @@ tasks.0079_backfill_task_repositoriesreplay_vision.0073_rebackfill_usage_scanner_idreplay_vision.0070_backfill_usage_scanner_idtasks.0088_backfill_task_search_documents+tasks.0092_backfill_task_last_activity_at# Does run CONCURRENTLY, one index per sourcebatch partition, but from RunPython# (the partition list is only known at runtime), which the type-based check can't see.warehouse_sources_queue.0008_sourcebatch_supersededdiff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex bdbad92cf8aa..43096f266747 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -207,6 +207,8 @@ post_save:products.signals.backend.receivers.tombstone_report_embedding_on_deletpost_save:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_changepost_save:products.slack_app.backend.signals.onboard_slack_inbox_on_installpost_save:products.surveys.backend.models.survey_changed+post_save:products.tasks.backend.models.bump_task_activity_on_run+post_save:products.tasks.backend.models.bump_task_activity_on_thread_messagepost_save:products.tasks.backend.models.project_task_created_activitypost_save:products.tasks.backend.models.track_task_run_completionpost_save:products.tasks.backend.search_index.channel_saveddiff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 25dd9bef57a9..ba5b0b6d1649 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -232,6 +232,12 @@ export interface TaskListOptions {channel?: string;/** Caller-side cap for surfaces that only show the newest few. */limit?: number;+ /**+ * Which end of the list the page is cut from. A surface that asks for a short page and means+ * "what has been happening here" has to say so, or the server hands back the newest-created+ * few and a long-running session never makes the page.+ */+ ordering?: "-last_activity_at" | "-created_at";}export interface TaskSearchResult {@@ -2338,6 +2344,10 @@ export class PostHogAPIClient {params.channel = options.channel;}+ if (options?.ordering) {+ params.ordering = options.ordering;+ }+const data = await this.api.get(`/api/projects/{project_id}/tasks/`, {path: { project_id: teamId.toString() },query: params,diff --git a/products/desktop/packages/api-client/src/task-normalization.ts b/products/desktop/packages/api-client/src/task-normalization.tsindex 83917c1c857c..ba36199bffbe 100644--- a/products/desktop/packages/api-client/src/task-normalization.ts+++ b/products/desktop/packages/api-client/src/task-normalization.ts@@ -31,6 +31,7 @@ type TaskResponseDTO = Partial<channel?: string | null;created_by?: Schemas.UserBasic | null;github_user_integration?: string | null;+ last_activity_at?: string | null;json_schema?: unknown | null;latest_run?: Record<string, unknown> | null;runtime?: unknown;@@ -201,6 +202,7 @@ export function normalizeTaskResponse(description: dto.description ?? "",created_at: dto.created_at ?? "",updated_at: dto.updated_at ?? "",+ last_activity_at: dto.last_activity_at ?? dto.updated_at ?? "",...(dto.created_by === undefined ? {} : { created_by: dto.created_by }),origin_product: dto.origin_product ?? "",...(dto.repository === undefined ? {} : { repository: dto.repository }),diff --git a/products/desktop/packages/core/src/canvas/channelItems.test.ts b/products/desktop/packages/core/src/canvas/channelItems.test.tsindex b47f972a666c..6dfe239ece69 100644--- a/products/desktop/packages/core/src/canvas/channelItems.test.ts+++ b/products/desktop/packages/core/src/canvas/channelItems.test.ts@@ -103,6 +103,33 @@ describe("buildChannelItems", () => {expect(item.title).toBe("Untitled task");});+ it("ranks a session by its activity, not by when its row was last written", () => {+ const items = build({+ feedTasks: [+ task({+ id: "still-running",+ created_at: new Date(1_000).toISOString(),+ updated_at: new Date(1_000).toISOString(),+ last_activity_at: new Date(9_000).toISOString(),+ }),+ task({+ id: "filed-later",+ created_at: new Date(5_000).toISOString(),+ updated_at: new Date(5_000).toISOString(),+ last_activity_at: new Date(5_000).toISOString(),+ }),+ ],+ });+ expect(sortChannelItems(items, "recent").map((i) => i.id)).toEqual([+ "still-running",+ "filed-later",+ ]);+ expect(sortChannelItems(items, "created").map((i) => i.id)).toEqual([+ "filed-later",+ "still-running",+ ]);+ });+it("treats an unparseable updated_at as epoch rather than NaN", () => {const [item] = build({feedTasks: [task({ updated_at: "not a date" })],@@ -190,6 +217,26 @@ describe("buildChannelItems", () => {]);});+ it("marks a session unread from activity its row write time didn't capture", () => {+ const [item] = build({+ feedTasks: [+ task({+ id: "streamed",+ updated_at: new Date(1_000).toISOString(),+ last_activity_at: new Date(3_000).toISOString(),+ }),+ ],+ sessionFacts: {+ needsInputTaskIds: NONE,+ viewedTimestamps: {+ streamed: { lastViewedAt: 2_000, lastActivityAt: null },+ },+ workspaceModeByTaskId: new Map(),+ },+ });+ expect(item.unread).toBe(true);+ });+it("returns everything when the owner is unknown", () => {const items = build({dashboards: [canvas({ createdBy: "Grace Hopper" })],diff --git a/products/desktop/packages/core/src/canvas/channelItems.ts b/products/desktop/packages/core/src/canvas/channelItems.tsindex 690dc40edbf0..141033ba0f18 100644--- a/products/desktop/packages/core/src/canvas/channelItems.ts+++ b/products/desktop/packages/core/src/canvas/channelItems.ts@@ -9,6 +9,7 @@ import type {UserBasic,} from "@posthog/shared/domain-types";import { isTaskUnread, type TaskTimestamp } from "../sidebar/buildSidebarData";+import { taskActivityAt, taskActivityTimestamp } from "../tasks/taskActivity";import type { DashboardRecord } from "./dashboardSchemas";/** Where a session runs. `worktree` is a local checkout, so it reads as local. */@@ -19,6 +20,7 @@ export interface ChannelItemModel {kind: "task" | "canvas";id: string;title: string;+ /** Activity time for the activity-first sort: a session's `last_activity_at`, or a canvas's `updatedAt`. */ts: number;/** When it was first made, for the created-first sort. */createdAt: number;@@ -156,7 +158,7 @@ export function buildChannelItems({kind: "task" as const,id: task.id,title: task.title || "Untitled task",- ts: Date.parse(task.updated_at) || 0,+ ts: taskActivityTimestamp(task, "updated") || 0,createdAt: Date.parse(task.created_at) || 0,pinned: pinnedTaskIds.has(task.id),rawStatus: task.latest_run?.status ?? null,@@ -167,7 +169,7 @@ export function buildChannelItems({source: sourceOf(task),needsInput: sessionFacts.needsInputTaskIds.has(task.id),unread: isTaskUnread(- task.updated_at,+ taskActivityAt(task),sessionFacts.viewedTimestamps[task.id],),authorUser: task.created_by ?? null,diff --git a/products/desktop/packages/core/src/sidebar/buildSidebarData.ts b/products/desktop/packages/core/src/sidebar/buildSidebarData.tsindex dee8cffffaf2..c9f76c9589e9 100644--- a/products/desktop/packages/core/src/sidebar/buildSidebarData.ts+++ b/products/desktop/packages/core/src/sidebar/buildSidebarData.ts@@ -1,5 +1,6 @@import { readPrUrls, type WorkspaceMode } from "@posthog/shared";import type { Task, TaskRunStatus } from "@posthog/shared/domain-types";+import { taskActivityAt } from "../tasks/taskActivity";import { getRepositoryInfo } from "./groupTasks";import type { TaskData, TaskGroup } from "./sidebarData.types";@@ -12,6 +13,7 @@ export interface FullTask {repository?: string | null;created_at: string;updated_at: string;+ last_activity_at?: string | null;origin_product?: string;latest_run?: {status?: TaskRunStatus | null;@@ -27,6 +29,7 @@ export interface SidebarTask {repository?: string | null;created_at: string;updated_at: string;+ last_activity_at?: string | null;origin_product?: string;slack_thread_url?: string;latest_run?: {@@ -70,6 +73,7 @@ export function narrowFullTask(task: FullTask | Task): SidebarTask {repository: task.repository ?? null,created_at: task.created_at,updated_at: task.updated_at,+ last_activity_at: task.last_activity_at ?? null,latest_run: task.latest_run? {status: task.latest_run.status,@@ -160,17 +164,16 @@ export interface DeriveTaskDataContext {}/**- * When a task last moved: the backend's `updated_at`, or local activity where- * that has run ahead of it (the renderer sees a session change before the next- * poll reports it).+ * When a task last moved: the activity time the caller passes (the backend's, via+ * `taskActivityAt`), or local renderer activity where that has run ahead of the next poll.*/export function taskLastActivityAt(- updatedAt: string,+ activityAt: string,timestamp: TaskTimestamp | undefined,): number {- const apiUpdatedAt = new Date(updatedAt).getTime();+ const reportedAt = new Date(activityAt).getTime();const localActivity = timestamp?.lastActivityAt;- return localActivity ? Math.max(apiUpdatedAt, localActivity) : apiUpdatedAt;+ return localActivity ? Math.max(reportedAt, localActivity) : reportedAt;}/**@@ -217,9 +220,10 @@ export function deriveTaskData(ctx: DeriveTaskDataContext,): TaskData {const { session, workspace, timestamp } = ctx;- const lastActivityAt = taskLastActivityAt(task.updated_at, timestamp);+ const activityAt = taskActivityAt(task);+ const lastActivityAt = taskLastActivityAt(activityAt, timestamp);const createdAt = new Date(task.created_at).getTime();- const isUnread = isTaskUnread(task.updated_at, timestamp);+ const isUnread = isTaskUnread(activityAt, timestamp);const cloudPrUrl =readPrUrls(task.latest_run?.output)[0] ??diff --git a/products/desktop/packages/core/src/tasks/taskActivity.test.ts b/products/desktop/packages/core/src/tasks/taskActivity.test.tsindex 35d1eadaffd3..38bbcb51f2f5 100644--- a/products/desktop/packages/core/src/tasks/taskActivity.test.ts+++ b/products/desktop/packages/core/src/tasks/taskActivity.test.ts@@ -51,6 +51,17 @@ describe("taskActivityTimestamp", () => {new Date("2026-01-04T00:00:00Z").getTime(),);});++ it("prefers the backend's activity stamp over the row's write time", () => {+ const task = makeTask({+ updated_at: "2026-01-02T00:00:00Z",+ last_activity_at: "2026-01-09T00:00:00Z",+ });++ expect(taskActivityTimestamp(task, "updated")).toBe(+ new Date("2026-01-09T00:00:00Z").getTime(),+ );+ });});describe("filterAndSortTasks", () => {diff --git a/products/desktop/packages/core/src/tasks/taskActivity.ts b/products/desktop/packages/core/src/tasks/taskActivity.tsindex 50d639e95c31..96077cec8731 100644--- a/products/desktop/packages/core/src/tasks/taskActivity.ts+++ b/products/desktop/packages/core/src/tasks/taskActivity.ts@@ -9,21 +9,42 @@ export interface TaskActivityInput {internal?: boolean;created_at: string;updated_at?: string | null;+ last_activity_at?: string | null;latest_run?: { updated_at: string };}+/**+ * The session's activity time as an ISO string. Prefers `last_activity_at` (the backend's+ * answer, which moves on a thread message or a run starting, streaming, or finishing) and falls+ * back to `updated_at` only for responses that predate the field. Ordering by that fallback+ * comes out in creation order, because `updated_at` moves only when the row itself is written.+ */+export function taskActivityAt(+ task: Pick<+ TaskActivityInput,+ "created_at" | "updated_at" | "last_activity_at"+ >,+): string {+ return task.last_activity_at || task.updated_at || task.created_at;+}+export function taskActivityTimestamp(- task: Pick<TaskActivityInput, "created_at" | "updated_at" | "latest_run">,+ task: Pick<+ TaskActivityInput,+ "created_at" | "updated_at" | "last_activity_at" | "latest_run"+ >,sortMode: TaskActivitySortMode,): number {if (sortMode === "created") {return new Date(task.created_at).getTime();}+ // The run's own timestamp still counts: it is the one activity signal a client talking to a+ // backend without `last_activity_at` can see move during a run.const runUpdatedAt = task.latest_run?.updated_at;return Math.max(runUpdatedAt ? new Date(runUpdatedAt).getTime() : 0,- new Date(task.updated_at ?? task.created_at).getTime(),+ new Date(taskActivityAt(task)).getTime(),);}diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex 414227afb114..737ebacfa62a 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -78,6 +78,11 @@ export interface Task {description: string;created_at: string;updated_at: string;+ /**+ * When something last happened in the session, as opposed to `updated_at` (when the row was+ * last written). The timestamp a "recent activity" sort reads. Empty on older responses.+ */+ last_activity_at?: string;created_by?: UserBasic | null;origin_product: string;repository?: string | null; // Format: "organization/repository" (e.g., "posthog/posthog-js")diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeed.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeed.tsindex 3973ab882615..24e17a67fea6 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeed.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeed.ts@@ -26,7 +26,15 @@ export function useChannelFeed(channelId: string | undefined): {const query = useAuthenticatedQuery<Task[]>(channelFeedQueryKey(channelId),(client) =>- client.getTasks({ channel: channelId }) as unknown as Promise<Task[]>,+ // Order the server page by activity, not creation. The feed is capped+ // server-side, so a long-running but old session would fall off a+ // created-first page before the activity sort could surface it. The rows+ // are still shown oldest-first below; this only decides which tasks make+ // the page.+ client.getTasks({+ channel: channelId,+ ordering: "-last_activity_at",+ }) as unknown as Promise<Task[]>,{enabled: !!channelId,gcTime: SPACE_QUERY_GC_TIME_MS,diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsxindex 4a7422954c97..2c05521f7599 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx@@ -28,8 +28,8 @@ import { useNavigate } from "@tanstack/react-router";import { useMemo } from "react";/**- * A channel's canvases + task feed as merged, newest-first items, plus the row- * actions and the viewer's identity for the recent-list filters.+ * A channel's canvases + task feed as merged items, most recently active first, plus the+ * row actions and the viewer's identity for the recent-list filters.** The channel is looked up in the channels list to establish its identity* (personal vs public). While it's unknown the hook reports loading and yieldsdiff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.tsindex 7d38d935123c..737259b6c594 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts@@ -62,6 +62,10 @@ function spaceTaskPageQuery(return (await client.getTasksPage({channel: spaceId,limit: TREE_FETCH_LIMIT,+ // The tree shows a handful of rows out of a whole space, so which end the server cuts+ // the page from decides what can appear at all: by creation date, a session that has+ // been running since Monday is already off the page before this list sorts anything.+ ordering: "-last_activity_at",})) as SpaceTaskPage;},gcTime: SPACE_QUERY_GC_TIME_MS,@@ -70,7 +74,7 @@ function spaceTaskPageQuery(};}-/** A space's rows: the newest few, and how many sessions it holds in all. */+/** A space's rows: the most recently active few, and how many sessions it holds in all. */export interface SpaceTasks {items: ChannelItemModel[];/** Everything in the space, not just the rows shown. */@@ -118,7 +122,8 @@ function attentionTier(/*** The order a space's rows are cut to five in: pinned sessions, then the rest,- * each run ordered by what it wants from you and still newest first inside that.+ * each run ordered by what it wants from you and still newest-activity first+ * inside that.** Two keys rather than one, because they answer different questions. Pinning is* the reader's own filing and outranks everything, the way it does in the Code@@ -126,8 +131,8 @@ function attentionTier(* behind it: by recency alone the session its dot is counting can sit below the* cut, leaving a marked space that opens onto five quiet rows.*- * Buckets rather than a comparator: the list arrives newest first, and pushing- * in order keeps that inside each run without a second sort key.+ * Buckets rather than a comparator: the page arrives newest-activity first, and+ * pushing in order keeps that inside each run without a second sort key.*/function spaceTreeOrder(items: ChannelItemModel[],@@ -159,7 +164,7 @@ function combineTaskPages(const SPACE_TREE_POLL_INTERVAL_MS = 30_000;/**- * The newest sessions in each of the given spaces, keyed by space id, as the+ * The most recently active sessions in each of the given spaces, keyed by space id, as the* same item model the space's own session list is built from — so a tree row* can wear the status dot and badges those rows do.*@@ -286,8 +291,8 @@ const NO_OVERVIEW: SpaceOverview = { people: [], total: null };* opens over it, so this costs no request of its own.** The people are who has been working here, not a membership list: the backend- * has no such list, and the page is the newest `TREE_FETCH_LIMIT` sessions- * rather than the space's whole history.+ * has no such list, and the page is the `TREE_FETCH_LIMIT` most recently+ * active sessions rather than the space's whole history.** The creator leads, whether or not they appear in that page. They are the one* name the space itself carries, and a group that opened with whoever happened@@ -320,7 +325,7 @@ export function useSpaceOverview(/*** The space's faces, in the order the group stacks them: the creator, then- * whoever ran the sessions, newest first, each person once and no more than+ * whoever ran the sessions, most recently active first, each person once and no more than* `limit` of them.** The creator leads whether or not they ran anything, and is not counted twicediff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useUnreadSessionCount.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useUnreadSessionCount.tsindex 9bc68960e907..3d3642d67d16 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useUnreadSessionCount.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useUnreadSessionCount.ts@@ -3,6 +3,7 @@ import {isTaskUnread,readRunMode,} from "@posthog/core/sidebar/buildSidebarData";+import { taskActivityAt } from "@posthog/core/tasks/taskActivity";import { readPrUrls } from "@posthog/shared";import type { Task } from "@posthog/shared/domain-types";import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";@@ -32,7 +33,7 @@ export function wantsAttention(lastViewedAt: TaskTimestamps,): boolean {const { tone } = taskDot({- isUnread: isTaskUnread(task.updated_at, lastViewedAt[task.id]),+ isUnread: isTaskUnread(taskActivityAt(task), lastViewedAt[task.id]),taskRunStatus: task.latest_run?.status ?? undefined,// A run's mode decides whether its status is a claim about work at all, so// without it the "Pending" rows never count. It rides on the run's state,diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 7e2e72e17827..8b4067e64cf7 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -598,6 +598,7 @@ def _task_detail_to_dto(latest_run=_task_run_detail_to_dto(resolved_latest_run) if resolved_latest_run is not None else None,created_at=task.created_at,updated_at=task.updated_at,+ last_activity_at=task.last_activity_at or task.updated_at,created_by=_user_basic_info(task.created_by if task.created_by_id else None),latest_run_id=latest_run_id,channel=task.channel_id,@@ -4490,11 +4491,23 @@ async def select_repository_for_message(team_id: int, user_id: int, message: str)+#: Orderings the task list accepts, keyed by the value clients send. Both fall back to `-id` so a+#: page boundary can't drop or repeat a row when two tasks share a timestamp. A null+#: `last_activity_at` (rows written outside the ORM) sorts first under `DESC`, which is where a row+#: with no known activity belongs.+TASK_LIST_ORDERINGS: dict[str, tuple[str, ...]] = {+ "-last_activity_at": ("-last_activity_at", "-id"),+ "-created_at": ("-created_at", "-id"),+}+DEFAULT_TASK_LIST_ORDERING = "-created_at"++def _list_tasks_queryset(team_id: int, user_id: int | None, *, filters: dict, bypass_visibility: bool = False) -> QuerySet[Task]:latest_run = TaskRun.objects.filter(task=OuterRef("pk"), team_id=team_id).order_by("-created_at", "-id")- qs = _visible_task_qs(team_id, user_id, bypass_visibility=bypass_visibility).order_by("-created_at", "-id")+ ordering = TASK_LIST_ORDERINGS.get(filters.get("ordering") or "", TASK_LIST_ORDERINGS[DEFAULT_TASK_LIST_ORDERING])+ qs = _visible_task_qs(team_id, user_id, bypass_visibility=bypass_visibility).order_by(*ordering)origin_product = filters.get("origin_product")if origin_product:diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex 2c715e200bee..7ef897f9f45d 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -159,7 +159,8 @@ class TaskDetailDTO:``None``). ``latest_run`` is the most-recent run as a ``TaskRunDetailDTO`` (or ``None``).``latest_run_id`` carries just that run's id for the conversation envelope, which needs the idto reconnect to sandbox logs but not the full (presigned-log) run payload. ``created_by``- mirrors core ``UserBasicSerializer`` output.+ mirrors core ``UserBasicSerializer`` output. ``last_activity_at`` is when something last+ happened in the task, as opposed to ``updated_at``, which is when the row was last written."""id: UUID@@ -183,6 +184,7 @@ class TaskDetailDTO:latest_run: "TaskRunDetailDTO | None" = Nonecreated_at: datetime | None = Noneupdated_at: datetime | None = None+ last_activity_at: datetime | None = Nonecreated_by: "TaskUserBasicInfo | None" = Nonelatest_run_id: UUID | None = Nonechannel: UUID | None = Nonediff --git a/products/tasks/backend/migrations/0091_task_last_activity_at.py b/products/tasks/backend/migrations/0091_task_last_activity_at.pynew file mode 100644index 000000000000..aaba0a76dee5--- /dev/null+++ b/products/tasks/backend/migrations/0091_task_last_activity_at.py@@ -0,0 +1,17 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("tasks", "0090_alter_origin_product_signals_chat")]++ operations = [+ # No default here on purpose: a field default makes Django emit `ADD COLUMN ... DEFAULT`,+ # which stamps every existing row with one migration-time value and leaves the backfill in+ # 0092 nothing to fill. Existing rows land NULL, 0092 seeds them from their real history,+ # and 0093 adds the default for rows created afterwards.+ migrations.AddField(+ model_name="task",+ name="last_activity_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/tasks/backend/migrations/0092_backfill_task_last_activity_at.py b/products/tasks/backend/migrations/0092_backfill_task_last_activity_at.pynew file mode 100644index 000000000000..e043c7c0b372--- /dev/null+++ b/products/tasks/backend/migrations/0092_backfill_task_last_activity_at.py@@ -0,0 +1,58 @@+from django.db import migrations++import structlog++logger = structlog.get_logger(__name__)++BATCH_SIZE = 1_000+LOG_EVERY_BATCHES = 25++# Keyset-paginated over the primary key rather than hunting for the NULLs, so the scan stays+# linear before the new column has an index leading on it. The `IS NULL` guard makes a+# `bin/migrate` retry safe: a task the new signals have already stamped keeps its live value+# instead of being pulled back to this historical estimate.+BACKFILL_SQL = """+UPDATE posthog_task AS t+ SET last_activity_at = GREATEST(+ t.updated_at,+ (SELECT MAX(r.updated_at) FROM posthog_task_run r WHERE r.task_id = t.id)+ )+ WHERE t.id = ANY(%s)+ AND t.last_activity_at IS NULL+"""+++def backfill_last_activity_at(apps, schema_editor):+ """Seed the activity clock from what existing rows already know about themselves.++ The task's own ``updated_at`` and its newest run's ``updated_at`` are the closest thing+ history carries to "when something last happened here", since a run's timestamp moves while+ it streams and the task's does not. Postgres ``GREATEST`` ignores NULLs, so a task with no+ runs falls back to its own ``updated_at``.+ """+ last_id = "00000000-0000-0000-0000-000000000000"+ batches = 0+ with schema_editor.connection.cursor() as cursor:+ while True:+ cursor.execute("SELECT id FROM posthog_task WHERE id > %s ORDER BY id LIMIT %s", [last_id, BATCH_SIZE])+ task_ids = [row[0] for row in cursor.fetchall()]+ if not task_ids:+ logger.info("task_last_activity_backfill_completed", batches=batches)+ return+ last_id = task_ids[-1]+ cursor.execute(BACKFILL_SQL, [task_ids])+ batches += 1+ if batches % LOG_EVERY_BATCHES == 0:+ logger.info("task_last_activity_backfill_progress", batches=batches)+++class Migration(migrations.Migration):+ # Keeps each backfill batch on its own transaction rather than holding one open across the+ # whole historical scan.+ atomic = False++ dependencies = [("tasks", "0091_task_last_activity_at")]++ operations = [+ migrations.RunPython(backfill_last_activity_at, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/tasks/backend/migrations/0093_task_last_activity_default.py b/products/tasks/backend/migrations/0093_task_last_activity_default.pynew file mode 100644index 000000000000..90f62d73fe61--- /dev/null+++ b/products/tasks/backend/migrations/0093_task_last_activity_default.py@@ -0,0 +1,17 @@+from django.db import migrations, models+from django.utils import timezone as django_timezone+++class Migration(migrations.Migration):+ # Adds the Python-level default so rows created after this point are stamped at creation. It+ # changes no stored data and emits no DDL (Django applies `default` in `Model.__init__`, not in+ # the database), so it runs after the 0092 backfill without clobbering the seeded values.+ dependencies = [("tasks", "0092_backfill_task_last_activity_at")]++ operations = [+ migrations.AlterField(+ model_name="task",+ name="last_activity_at",+ field=models.DateTimeField(blank=True, default=django_timezone.now, null=True),+ ),+ ]diff --git a/products/tasks/backend/migrations/0094_task_last_activity_indexes.py b/products/tasks/backend/migrations/0094_task_last_activity_indexes.pynew file mode 100644index 000000000000..d4a4580fe84a--- /dev/null+++ b/products/tasks/backend/migrations/0094_task_last_activity_indexes.py@@ -0,0 +1,20 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [("tasks", "0093_task_last_activity_default")]++ operations = [+ SafeAddIndexConcurrently(+ model_name="task",+ index=models.Index(fields=["team", "-last_activity_at", "-id"], name="posthog_task_team_activity_idx"),+ ),+ SafeAddIndexConcurrently(+ model_name="task",+ index=models.Index(fields=["channel", "-last_activity_at"], name="posthog_task_chan_activity_idx"),+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex d6a516bff6fc..97ec158ac7b2 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0090_alter_origin_product_signals_chat+0094_task_last_activity_indexesdiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 4717a88b473a..5c401be455ba 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -316,6 +316,11 @@ class Task(DeletedMetaFields, models.Model):created_at = models.DateTimeField(default=django_timezone.now)updated_at = models.DateTimeField(auto_now=True)+ # Distinct from `updated_at` (the row's last write): this moves when something happens+ # in the task, so a run can stream for hours without touching `updated_at` yet still sort+ # to the top. Nullable only for rows written outside the ORM; the Django default stamps+ # every other path.+ last_activity_at = models.DateTimeField(default=django_timezone.now, null=True, blank=True)ci_prompt = models.TextField(blank=True,null=True,@@ -343,6 +348,8 @@ class Task(DeletedMetaFields, models.Model):models.Index(fields=["team", "-created_at", "-id"], name="posthog_task_team_created_idx"),models.Index(fields=["team", "created_by", "-created_at", "-id"], name="posthog_task_team_creator_idx"),models.Index(fields=["channel", "-created_at"], name="posthog_task_channel_feed_idx"),+ models.Index(fields=["team", "-last_activity_at", "-id"], name="posthog_task_team_activity_idx"),+ models.Index(fields=["channel", "-last_activity_at"], name="posthog_task_chan_activity_idx"),models.Index(fields=["loop"], name="posthog_task_loop_idx"),]@@ -1360,6 +1367,24 @@ class TaskPin(models.Model):indexes = [models.Index(fields=["user", "-pinned_at"], name="task_pin_user_pinned_idx")]+def bump_task_activity(*, team_id: int, task_id: uuid.UUID | str, at: datetime) -> None:+ """Move a task's activity clock forward to ``at``, newest-wins.++ A guarded ``UPDATE`` rather than a ``save()``: it must not drag ``updated_at`` along+ (that field answers when the task row was last edited), and the ``WHERE`` is what keeps+ a retried Temporal activity or a slow writer from pulling the clock backwards.+ """+ Task.objects.filter(team_id=team_id, id=task_id).filter(+ models.Q(last_activity_at__isnull=True) | models.Q(last_activity_at__lt=at)+ ).update(last_activity_at=at)+++@receiver(post_save, sender=TaskThreadMessage)+def bump_task_activity_on_thread_message(sender, instance: "TaskThreadMessage", created: bool, **kwargs) -> None:+ if created:+ bump_task_activity(team_id=instance.team_id, task_id=instance.task_id, at=instance.created_at)++@receiver(post_save, sender=Task)def project_task_created_activity(sender, instance: Task, created: bool, **kwargs) -> None:"""Seed the creator's activity row. A signal rather than a facade call because tasks are@@ -3306,6 +3331,22 @@ def delete_task_session_object(sender: type[TaskSession], instance: TaskSession,transaction.on_commit(delete_object)+# A write to one of these means the agent did something a reader would call activity. Writes to+# anything else a run carries (branch, model, its sandbox session) are bookkeeping, and bumping+# on them would float an idle session to the top with nothing new to read.+RUN_ACTIVITY_FIELDS = frozenset({"status", "stage", "output", "artifacts", "completed_at", "error_message"})+++@receiver(post_save, sender=TaskRun)+def bump_task_activity_on_run(sender, instance: TaskRun, created: bool, update_fields=None, **kwargs) -> None:+ # A signal rather than calls at each transition because runs are written from the API, the+ # webhook handlers, the sandbox relay, and several Temporal activities, and one path forgetting+ # to bump would silently leave a live session reading as idle.+ if not created and update_fields is not None and not (RUN_ACTIVITY_FIELDS & set(update_fields)):+ return+ bump_task_activity(team_id=instance.team_id, task_id=instance.task_id, at=django_timezone.now())++@receiver(post_save, sender=TaskRun)def track_task_run_completion(sender, instance: TaskRun, created: bool, **kwargs):try:diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 31fd1f28df27..ce68f3e822e4 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -449,6 +449,7 @@ class TaskSerializer(DataclassSerializer):"latest_run","created_at","updated_at",+ "last_activity_at","created_by","ci_prompt","channel",@@ -1531,6 +1532,14 @@ class TaskListQuerySerializer(serializers.Serializer):),)channel = serializers.UUIDField(required=False, help_text="Filter tasks to a channel's feed.")+ ordering = serializers.ChoiceField(+ required=False,+ choices=sorted(tasks_facade.TASK_LIST_ORDERINGS),+ help_text=(+ "Sort order. '-last_activity_at' is newest activity first, where activity means a thread "+ "message or a run starting, streaming, or finishing. Defaults to '-created_at'."+ ),+ )all_team_tasks = serializers.BooleanField(required=False,default=False,diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex cab8283c4ee6..03b0ca735ce4 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -2196,6 +2196,35 @@ class TestTaskAPI(BaseTaskAPITest):response = self.client.get("/api/projects/@current/tasks/?archived=foo")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ @parameterized.expand(+ [+ ("default", "", ["Filed later", "Still running"]),+ ("created", "?ordering=-created_at", ["Filed later", "Still running"]),+ ("activity", "?ordering=-last_activity_at", ["Still running", "Filed later"]),+ ]+ )+ def test_list_tasks_ordering(self, _name, query, expected_titles):+ old = self.create_task("Still running")+ Task.objects.filter(id=old.id).update(+ created_at=django_timezone.now() - timedelta(days=3),+ last_activity_at=django_timezone.now(),+ )+ recent = self.create_task("Filed later")+ Task.objects.filter(id=recent.id).update(+ created_at=django_timezone.now() - timedelta(hours=1),+ last_activity_at=django_timezone.now() - timedelta(hours=1),+ )++ response = self.client.get(f"/api/projects/@current/tasks/{query}")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([task["title"] for task in response.json()["results"]], expected_titles)++ def test_list_tasks_rejects_unknown_ordering(self):+ self.create_task("Task 1")++ response = self.client.get("/api/projects/@current/tasks/?ordering=title")+ 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 = Truediff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex 599015ed646a..4eb332e6902d 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -1,6 +1,7 @@import jsonimport uuidimport secrets+from datetime import UTC, datetimefrom typing import ClassVarfrom unittest.mock import AsyncMock, patch@@ -9,17 +10,31 @@ from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db import IntegrityErrorfrom django.test import TestCase+from django.utils import timezone as django_timezonefrom parameterized import parameterizedfrom posthog.models import Integration, Organization, Teamfrom posthog.models.integration import ERROR_TOKEN_REFRESH_FAILEDfrom posthog.models.organization import OrganizationMembership+from posthog.models.scoping import team_scopefrom posthog.models.user import Userfrom posthog.models.user_integration import UserIntegrationfrom posthog.storage import object_storage-from products.tasks.backend.models import CodeInvite, SandboxEnvironment, SandboxSnapshot, Task, TaskRun+from products.tasks.backend.models import (+ CodeInvite,+ SandboxEnvironment,+ SandboxSnapshot,+ Task,+ TaskRun,+ TaskThreadMessage,+ bump_task_activity,+)++# Far enough back that any bump is unambiguously forward, and stable so a test can assert the+# clock did *not* move.+STALE_ACTIVITY_AT = datetime(2020, 1, 1, tzinfo=UTC)class TestTask(TestCase):@@ -482,6 +497,74 @@ class TestTask(TestCase):self.assertTrue(task.internal)+class TestTaskActivityClock(TestCase):+ organization: ClassVar[Organization]+ team: ClassVar[Team]+ user: ClassVar[User]++ @classmethod+ def setUpTestData(cls):+ cls.organization = Organization.objects.create(name="Test Org")+ cls.team = Team.objects.create(organization=cls.organization, name="Test Team")+ cls.user = User.objects.create_user(email="[email protected]", first_name="Test", password="password")++ def _task(self) -> Task:+ task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ title="Test Task",+ description="Test Description",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ Task.objects.filter(id=task.id).update(last_activity_at=STALE_ACTIVITY_AT, updated_at=STALE_ACTIVITY_AT)+ task.refresh_from_db()+ return task++ def test_thread_message_moves_the_clock_without_touching_updated_at(self):+ task = self._task()++ with team_scope(self.team.id):+ TaskThreadMessage.objects.create(+ team=self.team, task=task, author=self.user, content="Any news?", author_kind="human"+ )++ task.refresh_from_db()+ assert task.last_activity_at is not None+ self.assertGreater(task.last_activity_at, STALE_ACTIVITY_AT)+ self.assertEqual(task.updated_at, STALE_ACTIVITY_AT)++ @parameterized.expand(+ [+ ("status", ["status"], True),+ ("output", ["output"], True),+ ("completed_at", ["completed_at"], True),+ ("bookkeeping", ["active_task_session"], False),+ ("whole row", None, True),+ ]+ )+ def test_run_write_moves_the_clock_only_when_the_run_did_something(self, _name, update_fields, expected_move):+ task = self._task()+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)+ Task.objects.filter(id=task.id).update(last_activity_at=STALE_ACTIVITY_AT)++ run.status = TaskRun.Status.IN_PROGRESS+ run.save(update_fields=update_fields)++ task.refresh_from_db()+ assert task.last_activity_at is not None+ self.assertEqual(task.last_activity_at > STALE_ACTIVITY_AT, expected_move)++ def test_the_clock_never_runs_backwards(self):+ task = self._task()+ latest = django_timezone.now()+ Task.objects.filter(id=task.id).update(last_activity_at=latest)++ bump_task_activity(team_id=self.team.id, task_id=task.id, at=STALE_ACTIVITY_AT)++ task.refresh_from_db()+ self.assertEqual(task.last_activity_at, latest)++class TestTaskSlackPrNotification(TestCase):organization: ClassVar[Organization]team: ClassVar[Team]diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex acfc26fede22..949397b0350e 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1614,6 +1614,8 @@ export interface TaskDetailDTOApi {created_at?: string | null/** @nullable */updated_at?: string | null+ /** @nullable */+ last_activity_at?: string | nullcreated_by?: TaskUserBasicInfoApi | null/** @nullable */ci_prompt: string | null@@ -4334,6 +4336,14 @@ export type TasksListParams = {* @minimum 0*/offset?: number+ /**+ * Sort order. '-last_activity_at' is newest activity first, where activity means a thread message or a run starting, streaming, or finishing. Defaults to '-created_at'.+ *+ * * `-created_at` - -created_at+ * * `-last_activity_at` - -last_activity_at+ * @minLength 1+ */+ ordering?: TasksListOrdering/*** Filter by repository organization* @minLength 1@@ -4388,6 +4398,13 @@ export const TasksListInternal = {All: 'all',} as const+export type TasksListOrdering = (typeof TasksListOrdering)[keyof typeof TasksListOrdering]++export const TasksListOrdering = {+ CreatedAt: '-created_at',+ LastActivityAt: '-last_activity_at',+} as const+export type TasksListStatus = (typeof TasksListStatus)[keyof typeof TasksListStatus]export const TasksListStatus = {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 986b308a9890..42de5720f963 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -53770,6 +53770,8 @@ export namespace Schemas {created_at?: string | null;/** @nullable */updated_at?: string | null;+ /** @nullable */+ last_activity_at?: string | null;created_by?: TaskUserBasicInfo | null;/** @nullable */ci_prompt: string | null;@@ -91878,6 +91880,14 @@ export namespace Schemas {* @minimum 0*/offset?: number;+ /**+ * Sort order. '-last_activity_at' is newest activity first, where activity means a thread message or a run starting, streaming, or finishing. Defaults to '-created_at'.+ *+ * * `-created_at` - -created_at+ * * `-last_activity_at` - -last_activity_at+ * @minLength 1+ */+ ordering?: TasksListOrdering;/*** Filter by repository organization* @minLength 1@@ -91934,6 +91944,14 @@ export namespace Schemas {All: 'all',} as const;+ export type TasksListOrdering = typeof TasksListOrdering[keyof typeof TasksListOrdering];+++ export const TasksListOrdering = {+ CreatedAt: '-created_at',+ LastActivityAt: '-last_activity_at',+ } as const;+export type TasksListStatus = typeof TasksListStatus[keyof typeof TasksListStatus];diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex cc7796e10829..2370d0fa590a 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -894,6 +894,12 @@ export const TasksListQueryParams = /* @__PURE__ */ zod.object({.min(tasksListQueryOffsetMin).default(tasksListQueryOffsetDefault).describe('The initial index from which to return the results.'),+ ordering: zod+ .enum(['-created_at', '-last_activity_at'])+ .optional()+ .describe(+ "Sort order. '-last_activity_at' is newest activity first, where activity means a thread message or a run starting, streaming, or finishing. Defaults to '-created_at'.\n\n\* `-created_at` - -created_at\n\* `-last_activity_at` - -last_activity_at"+ ),organization: zod.string().min(1).optional().describe('Filter by repository organization'),origin_product: zod.string().min(1).optional().describe('Filter by origin product'),repository: zod.string().min(1).optional().describe('Filter by repository name (can include org\/repo format)'),diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.tsindex 19d531c22f51..9cf37ea16e9a 100644--- a/services/mcp/src/tools/generated/tasks.ts+++ b/services/mcp/src/tools/generated/tasks.ts@@ -532,6 +532,7 @@ const tasksList = (): ToolBase<typeof TasksListSchema, WithPostHogUrl<Schemas.Painternal: params.internal,limit: params.limit,offset: params.offset,+ ordering: params.ordering,organization: params.organization,origin_product: params.origin_product,repository: params.repository,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.jsonindex fe1f95e894d2..7c9b20913592 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json@@ -37,6 +37,11 @@"minimum": 0,"type": "number"},+ "ordering": {+ "description": "Sort order. '-last_activity_at' is newest activity first, where activity means a thread message or a run starting, streaming, or finishing. Defaults to '-created_at'.\n\n* `-created_at` - -created_at\n* `-last_activity_at` - -last_activity_at",+ "enum": ["-created_at", "-last_activity_at"],+ "type": "string"+ },"organization": {"description": "Filter by repository organization","minLength": 1,