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): show who worked in each space on the spaces index (#110058)

Shy Alter9980207216c1
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 941657157737..bb8a3d7bd2c5 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -29,6 +29,7 @@ from django.db.models import (
F,
Func,
IntegerField,
+ Max,
Min,
Model,
OuterRef,
@@ -9601,6 +9602,49 @@ def list_channels(team_id: int, user_id: int | None) -> list[contracts.ChannelDT
return [_channel_to_dto(channel, starred=channel.id in starred_ids) for channel in channels]
+def list_channel_contributors(team_id: int, user_id: int | None) -> list[contracts.ChannelContributorsDTO]:
+ """The people who own a task or a canvas in each channel the requester can see.
+
+ Archived tasks count, because their owners still worked in the channel. Deleted tasks
+ and canvases do not. A channel with no owner has no entry."""
+ channel_ids = list(_team_channels(team_id).filter(Channel.visible_to_q(user_id)).values_list("id", flat=True))
+ if not channel_ids:
+ return []
+ task_rows = (
+ Task.objects.filter(
+ task_visibility_q(user_id),
+ team_id=team_id,
+ channel_id__in=channel_ids,
+ deleted=False,
+ internal=False,
+ created_by_id__isnull=False,
+ )
+ .values("channel_id", "created_by_id")
+ .annotate(last_active=Max(Coalesce("last_activity_at", "created_at")))
+ )
+ canvas_rows = (
+ Canvas.objects.for_team(team_id)
+ .filter(channel_id__in=channel_ids, deleted=False, created_by_id__isnull=False)
+ .values("channel_id", "created_by_id")
+ .annotate(last_active=Max("updated_at"))
+ )
+ last_active: dict[UUID, dict[int, datetime]] = {}
+ for row in [*task_rows, *canvas_rows]:
+ per_channel = last_active.setdefault(row["channel_id"], {})
+ previous = per_channel.get(row["created_by_id"])
+ if previous is None or row["last_active"] > previous:
+ per_channel[row["created_by_id"]] = row["last_active"]
+ user_ids = {owner_id for owners in last_active.values() for owner_id in owners}
+ users = {user.id: user for user in User.objects.filter(id__in=user_ids)}
+ contributors: list[contracts.ChannelContributorsDTO] = []
+ for channel_id, owners in last_active.items():
+ ranked = sorted(owners.items(), key=lambda owner: (-owner[1].timestamp(), owner[0]))
+ people = [info for owner_id, _ in ranked if (info := _user_basic_info(users.get(owner_id))) is not None]
+ if people:
+ contributors.append(contracts.ChannelContributorsDTO(channel=channel_id, people=people))
+ return contributors
+
+
def _emit_channel_created(channel: Channel, user_id: int | None) -> None:
"""Announce a newly-created public channel in its own feed as a system row
("Ann created this context"). Server-emitted so the announcement appears no
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index a0ebe20d9c23..3ff2dc0df3c4 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -269,6 +269,14 @@ class ChannelDTO:
system_role: str | None = None
+@dataclass(frozen=True)
+class ChannelContributorsDTO:
+ """The people who own at least one task or canvas in a channel, most recently active first."""
+
+ channel: UUID
+ people: list["TaskUserBasicInfo"]
+
+
@dataclass(frozen=True)
class ProvisionedChannelsDTO:
channels: list[ChannelDTO]
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 391812a85d50..b777b1561048 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -30,6 +30,7 @@ from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.api import CHANNEL_INSTRUCTIONS_MAX_BYTES
from products.tasks.backend.facade.client_provenance import is_api_key_request, is_sandbox_oauth_request
from products.tasks.backend.facade.contracts import (
+ ChannelContributorsDTO,
ChannelDTO,
ChannelFeedMessageDTO,
ChannelInstructionsDTO,
@@ -2436,6 +2437,23 @@ class ChannelSerializer(DataclassSerializer):
]
+class ChannelContributorsSerializer(DataclassSerializer):
+ """The people who own at least one task or canvas in a channel."""
+
+ channel = serializers.UUIDField(help_text="The channel these people worked in.")
+ people = TaskUserBasicInfoSerializer(
+ many=True,
+ help_text=(
+ "Everyone who owns at least one task or canvas in the channel, most recently active first. "
+ "Deleted tasks and canvases do not count."
+ ),
+ )
+
+ class Meta:
+ dataclass = ChannelContributorsDTO
+ fields = ["channel", "people"]
+
+
class OnboardingSessionSerializer(serializers.Serializer):
"""The first-run session that was started for the requester."""
diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.py
index f5cd80d9e20b..2ddf02ab3d9b 100644
--- a/products/tasks/backend/presentation/views/channels_api.py
+++ b/products/tasks/backend/presentation/views/channels_api.py
@@ -31,6 +31,7 @@ from products.tasks.backend.facade.onboarding import (
from products.tasks.backend.facade.onboarding_canvas import ensure_teaching_canvas
from products.tasks.backend.presentation.serializers import (
ChannelContextGenerationSerializer,
+ ChannelContributorsSerializer,
ChannelDeleteConflictSerializer,
ChannelFeedMessageSerializer,
ChannelFeedMessageWriteSerializer,
@@ -104,6 +105,7 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"instructions_versions",
"context_generation",
"members",
+ "contributors",
]
scope_object_write_actions = [
"create",
@@ -151,6 +153,24 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(ChannelSerializer(channels, many=True).data)
return paginator.get_paginated_response(ChannelSerializer(page, many=True).data)
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=ChannelContributorsSerializer(many=True),
+ description="The task and canvas owners of each channel",
+ )
+ },
+ summary="List who worked in each channel",
+ description=(
+ "For each channel the requester can access, list the people who own at least one task or canvas "
+ "in it, most recently active first. Channels with no owners are left out."
+ ),
+ )
+ @action(methods=["GET"], detail=False, pagination_class=None)
+ def contributors(self, request: Request, **kwargs) -> Response:
+ contributors = tasks_facade.list_channel_contributors(self.team_id, self._user_id())
+ return Response(ChannelContributorsSerializer(contributors, many=True).data)
+
@extend_schema(
request=None,
responses={
diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.py
index f78b5def98d7..06df2fd06d31 100644
--- a/products/tasks/backend/tests/test_channels_api.py
+++ b/products/tasks/backend/tests/test_channels_api.py
@@ -16,6 +16,7 @@ from posthog.models.personal_api_key import hash_key_value
from posthog.models.scoping import team_scope
from posthog.models.utils import generate_random_token_personal
+from products.canvas.backend.models import Canvas
from products.tasks.backend.exceptions import ComputeBillingLimitError
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.onboarding_canvas import TeachingCanvas
@@ -566,6 +567,45 @@ class ChannelsAPITestCase(TestCase):
self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
self.assertEqual({m["id"] for m in response.json()}, {creator.id, self.other_user.id})
+ def test_contributors_list_task_and_canvas_owners_in_visible_channels(self):
+ public_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]
+ private_id = self._create_private_channel()["id"]
+ third = User.objects.create_user(email="[email protected]", first_name="Cy", password="password")
+ now = django_timezone.now()
+
+ def task(channel_id: str, owner: User, minutes_ago: int, **extra) -> None:
+ Task.objects.create(
+ team=self.team,
+ created_by=owner,
+ channel_id=channel_id,
+ title="t",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ last_activity_at=now - timedelta(minutes=minutes_ago),
+ **extra,
+ )
+
+ task(public_id, self.user, 30)
+ task(public_id, self.user, 90, archived=True)
+ task(public_id, third, 5, deleted=True)
+ task(private_id, self.user, 1)
+ with team_scope(self.team.id):
+ Canvas.objects.create(team=self.team, channel_id=public_id, name="Board", created_by=self.other_user)
+ Canvas.objects.create(team=self.team, channel_id=public_id, name="Gone", created_by=third, deleted=True)
+
+ response = self.client.get(f"{self._channels_url()}contributors/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertEqual(
+ {row["channel"]: [person["id"] for person in row["people"]] for row in response.json()},
+ {public_id: [self.other_user.id, self.user.id], private_id: [self.user.id]},
+ )
+
+ other_client = APIClient()
+ other_client.force_authenticate(self.other_user)
+ self.assertEqual(
+ [row["channel"] for row in other_client.get(f"{self._channels_url()}contributors/").json()], [public_id]
+ )
+
def test_deleting_github_integration_clears_channel_repositories(self):
integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})
channel = Channel.objects.for_team(self.team.id).create(
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 6a580ac67488..caa425ddf956 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1455,6 +1455,16 @@ export interface ChannelStarWriteApi {
starred: boolean
}
+/**
+ * The people who own at least one task or canvas in a channel.
+ */
+export interface ChannelContributorsDTOApi {
+ /** The channel these people worked in. */
+ channel: string
+ /** Everyone who owns at least one task or canvas in the channel, most recently active first. Deleted tasks and canvases do not count. */
+ people: TaskUserBasicInfoApi[]
+}
+
/**
* The first-run session that was started for the requester.
*/
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index dbe60ccb82f2..ac4d812c0c2a 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -10,6 +10,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
ChannelContextGenerationApi,
+ ChannelContributorsDTOApi,
ChannelDTOApi,
ChannelFeedMessageDTOApi,
ChannelFeedMessageWriteApi,
@@ -1190,6 +1191,24 @@ export const taskChannelsStarCreate = async (
})
}
+export const getTaskChannelsContributorsRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/task_channels/contributors/`
+}
+
+/**
+ * For each channel the requester can access, list the people who own at least one task or canvas in it, most recently active first. Channels with no owners are left out.
+ * @summary List who worked in each channel
+ */
+export const taskChannelsContributorsRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<ChannelContributorsDTOApi[]> => {
+ return apiMutator<ChannelContributorsDTOApi[]>(getTaskChannelsContributorsRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getTaskChannelsOnboardingSessionCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/task_channels/onboarding_session/`
}
diff --git a/products/tasks/frontend/spaces/SpacesIndexRow.tsx b/products/tasks/frontend/spaces/SpacesIndexRow.tsx
index 7ae2a888aa47..984e2d291683 100644
--- a/products/tasks/frontend/spaces/SpacesIndexRow.tsx
+++ b/products/tasks/frontend/spaces/SpacesIndexRow.tsx
@@ -10,14 +10,20 @@ import { TodaySpaceGlyph } from '~/layout/today/TodaySpaceGlyph'
import { isLockedSpace, spaceLabel } from '~/layout/today/todaySpacesLogic'
import { ChannelDTOApi } from '../generated/api.schemas'
+import { SPACE_PRESENCE_LIMIT } from './spacePresence'
+import { SpacePresenceAvatars } from './SpacePresenceAvatars'
import { spacesSceneLogic } from './spacesSceneLogic'
+import { taskUserName } from './TaskUserAvatar'
export function SpacesIndexRow({ space }: { space: ChannelDTOApi }): JSX.Element {
- const { pendingSpaceIds } = useValues(spacesSceneLogic)
+ const { pendingSpaceIds, contributors, spacePresence } = useValues(spacesSceneLogic)
const { toggleStar } = useActions(spacesSceneLogic)
const personal = space.system_role === 'personal'
const starLabel = space.starred ? 'Unstar space' : 'Star space'
const saving = pendingSpaceIds.includes(space.id)
+ const people = contributors?.[space.id] ?? []
+ const shown = people.slice(0, SPACE_PRESENCE_LIMIT)
+ const hidden = people.slice(SPACE_PRESENCE_LIMIT)
return (
<div className="relative flex min-w-0 items-center">
@@ -35,6 +41,28 @@ export function SpacesIndexRow({ space }: { space: ChannelDTOApi }): JSX.Element
<Text render={<span />} size="xs" variant="muted" className="min-w-0 flex-1 truncate">
{space.repositories.join(', ')}
</Text>
+ {shown.length > 0 && (
+ <span className="flex shrink-0 items-center gap-1" data-attr="today-spaces-index-people">
+ <SpacePresenceAvatars
+ presence={{ people: shown, liveUuids: spacePresence[space.id]?.liveUuids ?? [] }}
+ />
+ {hidden.length > 0 && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ className="text-xs text-muted-foreground tabular-nums"
+ aria-label={hidden.map(taskUserName).join(', ')}
+ />
+ }
+ >
+ +{hidden.length}
+ </TooltipTrigger>
+ <TooltipContent>{hidden.map(taskUserName).join(', ')}</TooltipContent>
+ </Tooltip>
+ )}
+ </span>
+ )}
</Button>
{!personal && (
<div className="absolute right-1 flex">
diff --git a/products/tasks/frontend/spaces/spacesSceneLogic.ts b/products/tasks/frontend/spaces/spacesSceneLogic.ts
index a3dd0eddbd66..909abe45424a 100644
--- a/products/tasks/frontend/spaces/spacesSceneLogic.ts
+++ b/products/tasks/frontend/spaces/spacesSceneLogic.ts
@@ -1,12 +1,16 @@
-import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
import { Scene } from 'scenes/sceneTypes'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { starredSpaces, todaySpacesLogic } from '~/layout/today/todaySpacesLogic'
import { Breadcrumb } from '~/types'
-import { ChannelDTOApi } from '../generated/api.schemas'
+import { taskChannelsContributorsRetrieve } from '../generated/api'
+import { ChannelDTOApi, TaskUserBasicInfoApi } from '../generated/api.schemas'
+import { SpacePresence } from './spacePresence'
export interface SpacesIndexLists {
starred: ChannelDTOApi[]
@@ -23,11 +27,15 @@ export function spacesIndexLists(spaces: ChannelDTOApi[], search: string): Space
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface spacesSceneLogicValues {
+ currentTeamId: number | null // teamLogic
pendingSpaceIds: string[] // todaySpacesLogic
sortedSpaces: ChannelDTOApi[] // todaySpacesLogic
+ spacePresence: Record<string, SpacePresence> // todaySpacesLogic
spacesLoading: boolean // todaySpacesLogic
spacesUnavailable: boolean // todaySpacesLogic
breadcrumbs: Breadcrumb[]
+ contributors: Record<string, TaskUserBasicInfoApi[]> | null
+ contributorsLoading: boolean
lists: SpacesIndexLists
search: string
}
@@ -42,6 +50,25 @@ export interface spacesSceneLogicActions {
spaceId: string
starred: boolean
} // todaySpacesLogic
+ loadContributors: () => any
+ loadContributorsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadContributorsSuccess: (
+ contributors: {
+ [k: string]: TaskUserBasicInfoApi[]
+ } | null,
+ payload?: any
+ ) => {
+ contributors: {
+ [k: string]: TaskUserBasicInfoApi[]
+ } | null
+ payload?: any
+ }
setSearch: (search: string) => {
search: string
}
@@ -64,7 +91,12 @@ export type spacesSceneLogicType = MakeLogicType<
export const spacesSceneLogic = kea<spacesSceneLogicType>([
path(['products', 'tasks', 'spaces', 'spacesSceneLogic']),
connect(() => ({
- values: [todaySpacesLogic, ['sortedSpaces', 'spacesLoading', 'spacesUnavailable', 'pendingSpaceIds']],
+ values: [
+ todaySpacesLogic,
+ ['sortedSpaces', 'spacesLoading', 'spacesUnavailable', 'pendingSpaceIds', 'spacePresence'],
+ teamLogic,
+ ['currentTeamId'],
+ ],
actions: [todaySpacesLogic, ['loadSpaces', 'toggleStar']],
})),
actions({
@@ -73,6 +105,20 @@ export const spacesSceneLogic = kea<spacesSceneLogicType>([
reducers({
search: ['', { setSearch: (_, { search }) => search }],
}),
+ loaders(({ values }) => ({
+ contributors: [
+ null as Record<string, TaskUserBasicInfoApi[]> | null,
+ {
+ loadContributors: async () => {
+ if (!values.currentTeamId) {
+ return null
+ }
+ const rows = await taskChannelsContributorsRetrieve(String(values.currentTeamId))
+ return Object.fromEntries(rows.map((row) => [row.channel, row.people]))
+ },
+ },
+ ],
+ })),
selectors({
lists: [
(s) => [s.sortedSpaces, s.search],
@@ -83,4 +129,7 @@ export const spacesSceneLogic = kea<spacesSceneLogicType>([
(): Breadcrumb[] => [{ key: Scene.TaskSpaces, name: 'Spaces', path: urls.taskSpaces(), iconType: 'task' }],
],
}),
+ afterMount(({ actions }) => {
+ actions.loadContributors()
+ }),
])
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index 4207a6cf25f8..a842b967f760 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -391,6 +391,9 @@ tools:
task-channels-context-generation-update:
operation: task_channels_context_generation_update
enabled: false
+ task-channels-contributors-retrieve:
+ operation: task_channels_contributors_retrieve
+ enabled: false
task-channels-destroy:
operation: task_channels_destroy
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 09d56ba85ae8..64fe401211a7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21332,6 +21332,16 @@ export namespace Schemas {
role_at_organization?: string | null;
}
+ /**
+ * The people who own at least one task or canvas in a channel.
+ */
+ export interface ChannelContributorsDTO {
+ /** The channel these people worked in. */
+ channel: string;
+ /** Everyone who owns at least one task or canvas in the channel, most recently active first. Deleted tasks and canvases do not count. */
+ people: TaskUserBasicInfo[];
+ }
+
/**
* * `personal` - Personal
* * `general` - General