: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(slack_app): add workspace activity stats to the App Home tab (#77244)
Vojta Bartošb47128011372
diff --git a/products/slack_app/backend/migrations/0012_slackthreadtaskmapping_workspace_created_idx.py b/products/slack_app/backend/migrations/0012_slackthreadtaskmapping_workspace_created_idx.pynew file mode 100644index 000000000000..745282a3cde4--- /dev/null+++ b/products/slack_app/backend/migrations/0012_slackthreadtaskmapping_workspace_created_idx.py@@ -0,0 +1,24 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ # CONCURRENTLY so the build takes no ACCESS EXCLUSIVE lock on the mapping table.+ # Concurrent builds can't run in a transaction, so this migration is non-atomic.+ atomic = False++ dependencies = [+ ("slack_app", "0011_slacksettings_permission_modes"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="slackthreadtaskmapping",+ index=models.Index(+ fields=["slack_workspace_id", "created_at"],+ include=["team_id"],+ name="slack_thr_map_ws_created_idx",+ ),+ ),+ ]diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txtindex ab1715c8d09d..93c987dfd4df 100644--- a/products/slack_app/backend/migrations/max_migration.txt+++ b/products/slack_app/backend/migrations/max_migration.txt@@ -1 +1 @@-0011_slacksettings_permission_modes+0012_slackthreadtaskmapping_workspace_created_idxdiff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.pyindex a627abe762ce..b490d9674ddc 100644--- a/products/slack_app/backend/models.py+++ b/products/slack_app/backend/models.py@@ -47,6 +47,17 @@ class SlackThreadTaskMapping(UUIDModel):name="uniq_slack_thread_task_mapping",)]+ indexes = [+ # Serves the workspace-wide activity aggregates on the App Home tab, which scan a+ # whole workspace over a date window rather than a single thread. `team_id` rides+ # along as an INCLUDE column so the accessible-projects filter is evaluated off the+ # index instead of a heap fetch per candidate row.+ models.Index(+ fields=["slack_workspace_id", "created_at"],+ include=["team_id"],+ name="slack_thr_map_ws_created_idx",+ ),+ ]class SlackUserProfileCache(UUIDModel):diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex 12f0e2ca6dae..cfef901cb703 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -15,8 +15,8 @@ in `products/slack_app/backend/api.py` are the ones that actually callfrom __future__ import annotations-from collections.abc import Mapping-from dataclasses import dataclass+from collections.abc import Iterable, Mapping+from dataclasses import dataclass, replacefrom datetime import datetime, timedeltafrom typing import Any, Literal@@ -32,6 +32,19 @@ from posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.feature_flags import is_slack_app_home_enabled, is_slack_app_oauth_enabledfrom products.slack_app.backend.models import SlackSettings, SlackUserProfileCache+from products.slack_app.backend.services.slack_app_home_stats import (+ DEFAULT_STATS_WINDOW_DAYS,+ OUTCOME_CANCELLED,+ OUTCOME_DONE,+ OUTCOME_FAILED,+ OUTCOME_RUNNING,+ STATS_MAX_TASKS,+ STATS_WINDOW_OPTIONS,+ ModelUsage,+ StatsState,+ build_stats_state,+ coerce_window_days,+)from products.slack_app.backend.services.slack_settings import (AIPreferences,build_ai_preferences_payload,@@ -61,12 +74,15 @@ ACTION_TASKS_REFRESH = "slack_app_home:tasks_refresh"# can't share one id — they both carry the target page as `value`.ACTION_TASKS_PAGE_PREV = "slack_app_home:tasks_page_prev"ACTION_TASKS_PAGE_NEXT = "slack_app_home:tasks_page_next"+ACTION_STATS_WINDOW = "slack_app_home:stats_window"+ACTION_STATS_REFRESH = "slack_app_home:stats_refresh"# Single block_id for the whole controls row. Block Kit only persists# state in `view.state.values` under blocks that carry a `block_id`, so# both the repo and the status dropdowns live under the same key here and# the handler can read them back on each pick.BLOCK_TASKS_CONTROLS = "block_tasks_controls"+BLOCK_STATS_CONTROLS = "block_stats_controls"# Sentinel value the "All …" options carry — Slack rejects empty `value`# strings, so the resolver treats this as "no filter".@@ -326,6 +342,35 @@ class TasksState:return self.page + 1 < self.total_pages+@dataclass(frozen=True)+class HomeViewState:+ """The Home tab's control settings, as they stood when the user clicked.++ Slack holds no server-side state for a published Home tab; each `block_actions`+ payload instead carries the whole view's inputs. Reading them into one object means+ an action on any card republishes the others exactly as they were, instead of+ resetting them to their defaults.+ """++ selected_repo: str | None = None+ selected_status: str | None = None+ tasks_page: int = 0+ stats_window_days: int = DEFAULT_STATS_WINDOW_DAYS+ stats_force_refresh: bool = False++ @classmethod+ def from_payload(cls, payload: dict) -> HomeViewState:+ # Block Kit only persists state under blocks carrying a `block_id`, so each+ # card's controls row shares one key. Absent blocks (a card the viewer doesn't+ # get) simply fall back to defaults.+ values = (payload.get("view") or {}).get("state", {}).get("values", {}) or {}+ return cls(+ selected_repo=_selected_value(values, BLOCK_TASKS_CONTROLS, ACTION_TASKS_FILTER_REPO),+ selected_status=_selected_value(values, BLOCK_TASKS_CONTROLS, ACTION_TASKS_FILTER_STATUS),+ stats_window_days=coerce_window_days(_selected_value(values, BLOCK_STATS_CONTROLS, ACTION_STATS_WINDOW)),+ )++@dataclass(frozen=True)class AccountState:"""Inputs the renderer needs to draw the optional account-link card.@@ -349,6 +394,7 @@ def render_home_view(account_state: AccountState | None = None,project_state: ProjectState | None = None,tasks_state: TasksState | None = None,+ stats_state: StatsState | None = None,) -> dict:"""Render the Block Kit payload for `views.publish` on the App Home tab."""@@ -357,13 +403,20 @@ def render_home_view(blocks.extend(_header_blocks())- # Section 1 — project routing. Personal pick on top; admins get an+ # Section 1 — workspace activity: aggregates across everyone's Slack-started work,+ # rather than the calling user's own. Admin-only, and first because it's the reason+ # an admin opens the tab at all — the settings below are set once and rarely revisited.+ if stats_state is not None:+ blocks.append({"type": "divider"})+ blocks.extend(_stats_section_blocks(stats_state))++ # Section 2 — project routing. Personal pick on top; admins get an# editable workspace default below, others see it as read-only context.if project_state and project_state.has_anything_to_show:blocks.append({"type": "divider"})blocks.extend(_project_section_blocks(project_state, is_admin=is_admin))- # Section 2 — AI model settings: which model handles those mentions.+ # Section 3 — AI model settings: which model handles those mentions.# Headline shows the effective triple (and its source); personal /# workspace controls underneath mirror the project routing layout.blocks.append({"type": "divider"})@@ -371,13 +424,13 @@ def render_home_view(blocks.extend(_personal_section_blocks(user_row))blocks.extend(_workspace_section_blocks(workspace_row, is_admin=is_admin))- # Section 3 — account linking: shown before Tasks so the connect+ # Section 4 — account linking: shown before Tasks so the connect# prompt is visible while the Tasks list is still empty. Flag-gated.if account_state and account_state.enabled:blocks.append({"type": "divider"})blocks.extend(_account_section_blocks(account_state))- # Section 4 — your tasks: a quiet list of tasks the calling user+ # Section 5 — your tasks: a quiet list of tasks the calling user# started via @PostHog mentions, so they can see status without# the bot pinging the activity feed for every transition.if tasks_state is not None:@@ -402,6 +455,60 @@ def _subsection_label(text: str) -> dict:return {"type": "context", "elements": [{"type": "mrkdwn", "text": f"*{text}*"}]}+def _refreshed_at_blocks(epoch: int) -> list[dict]:+ """ "Last refreshed" line, rendered in the viewer's own timezone by Slack.++ Empty when the card has never been resolved, so callers can `extend` unconditionally.+ """+ if not epoch:+ return []+ return [+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": f"_Last refreshed <!date^{epoch}^{{date_short_pretty}} at {{time}}|just now>_",+ }+ ],+ }+ ]+++def _static_select(+ *,+ action_id: str,+ placeholder: str,+ pairs: Iterable[tuple[str, str]],+ selected: str | None = None,+) -> dict[str, Any]:+ """A `static_select` built from `(value, label)` pairs.++ `selected` is honoured only when it matches one of the pairs, so a stale value from a+ cached view can't produce an `initial_option` Slack rejects.+ """+ options = [{"text": {"type": "plain_text", "text": label, "emoji": True}, "value": value} for value, label in pairs]+ element: dict[str, Any] = {+ "type": "static_select",+ "action_id": action_id,+ "placeholder": {"type": "plain_text", "text": placeholder},+ "options": options,+ }+ initial = next((o for o in options if o["value"] == selected), None)+ if initial:+ element["initial_option"] = initial+ return element+++def _provider_for_runtime_adapter(runtime_adapter: str | None) -> str:+ """The gateway `owned_by` a runtime adapter implies — the inverse of+ `_PROVIDER_TO_RUNTIME_ADAPTER`, so the two can't drift when an adapter is added."""+ for provider, adapter in _PROVIDER_TO_RUNTIME_ADAPTER.items():+ if adapter == runtime_adapter:+ return provider+ return "anthropic"++def _header_blocks() -> list[dict]:return [_section_title(@@ -675,21 +782,7 @@ def _tasks_section_blocks(state: TasksState) -> list[dict]:if state.has_any_tasks:blocks.append(_tasks_controls_block(state))- if state.refreshed_at_epoch:- blocks.append(- {- "type": "context",- "elements": [- {- "type": "mrkdwn",- "text": (- f"_Last refreshed <!date^{state.refreshed_at_epoch}"- "^{date_short_pretty} at {time}|just now>_"- ),- }- ],- }- )+ blocks.extend(_refreshed_at_blocks(state.refreshed_at_epoch))if not state.items:empty_text = (@@ -836,10 +929,252 @@ def _tasks_controls_block(state: TasksState) -> dict:return {"type": "actions", "block_id": BLOCK_TASKS_CONTROLS, "elements": elements}+# Display caps for the stats card. These live with the renderer rather than the resolver+# because they describe what gets drawn, not what the workspace did.+#+# Charts are drawn as text. Block Kit does have a native `data_visualization` block, but+# `views.publish` rejects it on the App Home surface with "Unsupported block type" — note+# that `blocks.validate` accepts it, so the schema check is not proof a surface takes it.+_STATS_MAX_BREAKDOWN_ROWS = 6+# Breakdown labels and bars share a half-width column, so both are tighter than the+# full-width sparkline row above them.+_STATS_COLUMN_LABEL_CHARS = 14+_STATS_BAR_WIDTH = 8+# Slack renders `section.fields` in two columns and rejects more than 10 cells.+_STATS_MAX_FIELDS = 10++# Eight levels of block-fill, so a sparkline reads as a shape rather than a row of dots.+_SPARK_LEVELS = "▁▂▃▄▅▆▇█"++_OUTCOME_EMOJI: dict[str, str] = {+ OUTCOME_DONE: "🦔",+ OUTCOME_FAILED: "❌",+ OUTCOME_CANCELLED: "🚫",+ OUTCOME_RUNNING: "🔄",+}+++def _stats_section_blocks(state: StatsState) -> list[dict]:+ """Render the workspace-activity card: a KPI grid, two text charts, a leaderboard."""+ blocks: list[dict] = [+ _section_title(+ "📊 Workspace activity",+ "What your team shipped with @PostHog. Only workspace admins see this.",+ ),+ _stats_controls_block(state),+ ]++ if not state.has_data:+ blocks.append(+ {+ "type": "section",+ "text": {"type": "mrkdwn", "text": "_Nobody has started a task from Slack in this window._"},+ }+ )+ return blocks++ blocks.append(_stats_headline_block(state))+ blocks.extend(+ block+ for block in (+ _stats_outcomes_block(state),+ _stats_trend_block(state),+ _stats_breakdowns_block(state),+ )+ if block+ )+ blocks.extend(_stats_footnote_blocks(state))+ return blocks+++def _stats_controls_block(state: StatsState) -> dict:+ return {+ "type": "actions",+ "block_id": BLOCK_STATS_CONTROLS,+ "elements": [+ _static_select(+ action_id=ACTION_STATS_WINDOW,+ placeholder="Pick a window",+ pairs=((str(days), label) for days, label in STATS_WINDOW_OPTIONS),+ selected=str(state.window_days),+ ),+ {+ "type": "button",+ "action_id": ACTION_STATS_REFRESH,+ "value": str(state.window_days),+ "text": {"type": "plain_text", "text": "Refresh", "emoji": True},+ },+ ],+ }+++def _stats_headline_block(state: StatsState) -> dict:+ merge_rate = state.merge_rate_percent+ cells = [+ ("Tasks", str(state.tasks_started)),+ ("Opened a PR", str(state.tasks_with_pr)),+ ("Merged", str(state.tasks_merged)),+ ("Merge rate", "—" if merge_rate is None else f"{merge_rate}%"),+ ("Median run", _format_duration(state.median_cycle_seconds)),+ ("People", str(state.active_people)),+ ]+ # `fields` lays out in two columns, so six KPIs cost three rows instead of the six+ # lines a stack of sections would take. Slack caps this at 10 cells.+ return {+ "type": "section",+ "fields": [{"type": "mrkdwn", "text": f"*{label}*\n{value}"} for label, value in cells[:_STATS_MAX_FIELDS]],+ }+++def _format_duration(seconds: int | None) -> str:+ """Compact wall-clock label — `45s`, `12m`, `2h 5m`, `3d`."""+ if seconds is None:+ return "—"+ if seconds < 60:+ return f"{seconds}s"+ minutes = seconds // 60+ if minutes < 60:+ return f"{minutes}m"+ hours, mins = divmod(minutes, 60)+ if hours < 24:+ return f"{hours}h {mins}m" if mins else f"{hours}h"+ return f"{hours // 24}d"+++def _stats_outcomes_block(state: StatsState) -> dict | None:+ """Outcome split as a muted text line — it's the least interesting of the four+ breakdowns, and giving up its chart keeps the card inside Slack's per-surface+ data-visualization budget."""+ if not state.outcomes:+ return None+ parts = [f"{_OUTCOME_EMOJI.get(s.label, '')} {s.value} {s.label.lower()}".strip() for s in state.outcomes]+ return {"type": "context", "elements": [{"type": "mrkdwn", "text": " · ".join(parts)}]}+++def _stats_trend_block(state: StatsState) -> dict | None:+ """PRs opened vs merged per bucket, as two sparklines on one line.++ Skipped when the window produced no PRs — a flat line of minima is noise.+ """+ buckets = state.trend+ if not buckets or not state.tasks_with_pr:+ return None++ # One shared peak so the two lines are read against each other, not each rescaled.+ peak = max(max(b.opened, b.merged) for b in buckets)+ opened = _sparkline([b.opened for b in buckets], peak)+ merged = _sparkline([b.merged for b in buckets], peak)+ span = f"{buckets[0].label} → {buckets[-1].label}"+ return {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": f"*PRs* `{opened}` opened · `{merged}` merged _{span}_",+ }+ ],+ }+++def _stats_breakdowns_block(state: StatsState) -> dict | None:+ """Models and people side by side.++ `section.fields` is Block Kit's only two-column layout, so the two breakdowns share+ one block instead of stacking. Each column is fenced: the counts only line up under a+ monospace font, and proportional text leaves them ragged.+ """+ columns = [column for column in (_stats_models_column(state), _stats_people_column(state)) if column]+ if not columns:+ return None+ return {"type": "section", "fields": [{"type": "mrkdwn", "text": column} for column in columns]}+++def _stats_models_column(state: StatsState) -> str | None:+ """Share of runs per model, with the long tail folded into "Other"."""+ if not state.models:+ return None++ fits = len(state.models) <= _STATS_MAX_BREAKDOWN_ROWS+ head = state.models if fits else state.models[: _STATS_MAX_BREAKDOWN_ROWS - 1]+ tail = () if fits else state.models[_STATS_MAX_BREAKDOWN_ROWS - 1 :]++ rows = [(_stats_model_label(usage), usage.value) for usage in head if usage.value > 0]+ other = sum(usage.value for usage in tail)+ if other > 0:+ rows.append(("Other", other))+ if not rows:+ return None++ peak = max(value for _, value in rows)+ width = max(len(label) for label, _ in rows)+ lines = "\n".join(f"{label:<{width}} {_bar(value, peak)} {value:>3}" for label, value in rows)+ return f"*Models*\n```\n{lines}\n```"+++def _stats_people_column(state: StatsState) -> str | None:+ """Leaderboard as text: who started how many, and how many of those merged."""+ people = state.people[:_STATS_MAX_BREAKDOWN_ROWS]+ if not people:+ return None++ names = [_truncate(person.name, _STATS_COLUMN_LABEL_CHARS) for person in people]+ width = max(len(name) for name in names)+ lines = "\n".join(f"{name:<{width}} {person.tasks:>3} {person.merged:>4}" for name, person in zip(names, people))+ return f"*Most active* _tasks · merged_\n```\n{lines}\n```"+++def _truncate(text: str, limit: int) -> str:+ return text if len(text) <= limit else text[: limit - 1] + "…"+++def _sparkline(values: list[int], peak: int) -> str:+ """Render counts as block-fill characters, scaled against `peak`."""+ if peak <= 0:+ return _SPARK_LEVELS[0] * len(values)+ top = len(_SPARK_LEVELS) - 1+ return "".join(_SPARK_LEVELS[min(top, value * top // peak)] for value in values)+++def _bar(value: int, peak: int, width: int = _STATS_BAR_WIDTH) -> str:+ """Fixed-width bar. Any non-zero value keeps at least one filled cell, so a small+ count reads as present rather than absent."""+ if peak <= 0 or value <= 0:+ return "░" * width+ filled = min(width, max(1, round(value * width / peak)))+ return "█" * filled + "░" * (width - filled)+++def _stats_model_label(usage: ModelUsage) -> str:+ """Display label for a model, truncated so the bar column stays aligned."""+ label = _format_model_id(usage.model, owned_by=_provider_for_runtime_adapter(usage.runtime_adapter))+ return _truncate(label, _STATS_COLUMN_LABEL_CHARS)+++def _stats_footnote_blocks(state: StatsState) -> list[dict]:+ blocks: list[dict] = []+ if state.truncated:+ blocks.append(+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": (+ f"_Counting the {STATS_MAX_TASKS} most recent tasks — "+ "older activity in this window is excluded._"+ ),+ }+ ],+ }+ )+ blocks.extend(_refreshed_at_blocks(state.refreshed_at_epoch))+ return blocks++def _row_summary(row: SlackSettings | None) -> str:if not row or not row.runtime_adapter or not row.model:return "_(none)_"- owned_by = "openai" if row.runtime_adapter == "codex" else "anthropic"+ owned_by = _provider_for_runtime_adapter(row.runtime_adapter)parts = [f"*Model:* {_format_model_id(row.model, owned_by=owned_by)}",f"*Runtime:* {_label(row.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}",@@ -1042,9 +1377,11 @@ def handle_app_home_opened(event: dict, slack_team_id: str) -> None:slack = SlackIntegration(integration)is_admin = _is_admin(slack, integration, slack_user_id)+ accessible = _accessible_integrations(integration, slack_user_id)account_state = _resolve_account_state(integration, slack_user_id)- project_state = _resolve_project_state(integration, slack_user_id)- tasks_state = _resolve_tasks_state(integration, slack_user_id)+ project_state = _resolve_project_state(integration, slack_user_id, accessible=accessible)+ tasks_state = _resolve_tasks_state(integration, slack_user_id, accessible=accessible)+ stats_state = _resolve_stats_state(integration, accessible=accessible, is_admin=is_admin)view = render_home_view(effective=effective,@@ -1054,6 +1391,7 @@ def handle_app_home_opened(event: dict, slack_team_id: str) -> None:account_state=account_state,project_state=project_state,tasks_state=tasks_state,+ stats_state=stats_state,)try:slack.client.views_publish(user_id=slack_user_id, view=view)@@ -1083,6 +1421,14 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpRespoif not is_slack_app_home_enabled(integration):return HttpResponse(status=200)+ # The Home tab keeps no server-side view state — every payload carries the whole+ # view's inputs instead. Read them all back once so any action republishes with the+ # controls the user had dialled in, rather than resetting its neighbours' cards.+ view_state = HomeViewState.from_payload(payload)++ def republish(state: HomeViewState = view_state) -> None:+ _republish_home(integration, slack_user_id, view_state=state)+if action_id == ACTION_EDIT_PERSONAL and trigger_id:_open_edit_modal(integration, slack_user_id, scope="personal", trigger_id=trigger_id)return HttpResponse(status=200)@@ -1097,17 +1443,17 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpRespoif action_id == ACTION_RESET_PERSONAL:_clear_personal_override(integration, slack_user_id)- _republish_home(integration, slack_user_id)+ republish()return HttpResponse(status=200)if action_id == ACTION_SET_PROJECT_PERSONAL:_apply_project_pick(integration, slack_user_id=slack_user_id, action=action, scope="personal")- _republish_home(integration, slack_user_id)+ republish()return HttpResponse(status=200)if action_id == ACTION_RESET_PROJECT_PERSONAL:_clear_project_personal(integration, slack_user_id)- _republish_home(integration, slack_user_id)+ republish()return HttpResponse(status=200)if action_id == ACTION_SET_PROJECT_WORKSPACE:@@ -1116,7 +1462,7 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpRespo_post_ephemeral_admin_only(slack, payload)return HttpResponse(status=200)_apply_project_pick(integration, slack_user_id=None, action=action, scope="workspace")- _republish_home(integration, slack_user_id)+ republish()return HttpResponse(status=200)if action_id == ACTION_UNLINK_ACCOUNT:@@ -1125,7 +1471,7 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpRespo# cached view shouldn't be allowed to drive deletes.if is_slack_app_oauth_enabled(integration, integration.integration_id):_unlink_user_account(integration, slack_user_id)- _republish_home(integration, slack_user_id)+ republish()return HttpResponse(status=200)if action_id in (@@ -1135,7 +1481,6 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpRespoACTION_TASKS_PAGE_PREV,ACTION_TASKS_PAGE_NEXT,):- selected_repo, selected_status = _read_tasks_filters_from_payload(payload)# Filter changes snap back to page 0; Refresh / Prev / Next carry the# target page as the button value so the Home tab stays stateless.if action_id in (ACTION_TASKS_REFRESH, ACTION_TASKS_PAGE_PREV, ACTION_TASKS_PAGE_NEXT):@@ -1145,13 +1490,13 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpRespopage = 0else:page = 0- _republish_home(- integration,- slack_user_id,- selected_repo=selected_repo,- selected_status=selected_status,- page=page,- )+ republish(replace(view_state, tasks_page=page))+ return HttpResponse(status=200)++ if action_id in (ACTION_STATS_WINDOW, ACTION_STATS_REFRESH):+ # The window pick already rode in on the view state; only Refresh additionally+ # needs to bypass the aggregate cache.+ republish(replace(view_state, stats_force_refresh=action_id == ACTION_STATS_REFRESH))return HttpResponse(status=200)if action_id in (MODAL_ACTION_RUNTIME_ADAPTER, MODAL_ACTION_MODEL):@@ -1395,22 +1740,30 @@ def _republish_home(integration: Integration,slack_user_id: str,*,- selected_repo: str | None = None,- selected_status: str | None = None,- page: int = 0,+ view_state: HomeViewState | None = None,) -> None:+ view_state = view_state or HomeViewState()user_row, workspace_row = _load_rows(integration, slack_user_id)effective = resolve_ai_preferences(integration, slack_user_id)slack = SlackIntegration(integration)is_admin = _is_admin(slack, integration, slack_user_id)+ accessible = _accessible_integrations(integration, slack_user_id)account_state = _resolve_account_state(integration, slack_user_id)- project_state = _resolve_project_state(integration, slack_user_id)+ project_state = _resolve_project_state(integration, slack_user_id, accessible=accessible)tasks_state = _resolve_tasks_state(integration,slack_user_id,- selected_repo=selected_repo,- selected_status=selected_status,- page=page,+ accessible=accessible,+ selected_repo=view_state.selected_repo,+ selected_status=view_state.selected_status,+ page=view_state.tasks_page,+ )+ stats_state = _resolve_stats_state(+ integration,+ accessible=accessible,+ is_admin=is_admin,+ window_days=view_state.stats_window_days,+ force_refresh=view_state.stats_force_refresh,)view = render_home_view(effective=effective,@@ -1420,6 +1773,7 @@ def _republish_home(account_state=account_state,project_state=project_state,tasks_state=tasks_state,+ stats_state=stats_state,)try:slack.client.views_publish(user_id=slack_user_id, view=view)@@ -1439,6 +1793,7 @@ def _resolve_tasks_state(integration: Integration,slack_user_id: str,*,+ accessible: list[Integration],selected_repo: str | None = None,selected_status: str | None = None,page: int = 0,@@ -1473,12 +1828,7 @@ def _resolve_tasks_state(if not mappings:return TasksState()- candidates = list(- Integration.objects.filter(kind="slack", integration_id=slack_team_id)- .select_related("team", "team__organization")- .order_by("id")- )- accessible_team_ids = {c.team_id for c in _filter_accessible_integrations(integration, slack_user_id, candidates)}+ accessible_team_ids = {c.team_id for c in accessible}if not accessible_team_ids:return TasksState()@@ -1582,22 +1932,6 @@ def _format_relative(when: datetime | None, *, now: datetime) -> str:return when.strftime("%b %d")-def _read_tasks_filters_from_payload(payload: dict) -> tuple[str | None, str | None]:- """Pull current filter selections off the Home tab view state.-- The Home tab is stateless — each pick triggers a `block_actions` payload- that carries the *whole* view's input state, so the handler can re-publish- honouring whatever the user has dialled in. Block Kit only persists- state under blocks that carry a `block_id`, so the controls row uses- a single fixed `BLOCK_TASKS_CONTROLS` key for every select inside it.- """- values = (payload.get("view") or {}).get("state", {}).get("values", {}) or {}- controls = values.get(BLOCK_TASKS_CONTROLS, {})- repo = (controls.get(ACTION_TASKS_FILTER_REPO, {}).get("selected_option") or {}).get("value")- status = (controls.get(ACTION_TASKS_FILTER_STATUS, {}).get("selected_option") or {}).get("value")- return repo, status--def _resolve_account_state(integration: Integration, slack_user_id: str) -> AccountState:slack_team_id = integration.integration_idif not is_slack_app_oauth_enabled(integration, slack_team_id):@@ -1630,17 +1964,72 @@ def _resolve_account_state(integration: Integration, slack_user_id: str) -> Accoreturn AccountState(enabled=True, linked_email=None, link_url=link_url)-def _resolve_project_state(integration: Integration, slack_user_id: str) -> ProjectState:- candidates = list(- Integration.objects.filter(kind="slack", integration_id=integration.integration_id)+def _workspace_integrations(slack_team_id: str) -> list[Integration]:+ """Every PostHog project this Slack workspace is connected to."""+ return list(+ Integration.objects.filter(kind="slack", integration_id=slack_team_id).select_related("team", "team__organization").order_by("id"))+++def _accessible_integrations(integration: Integration, slack_user_id: str) -> list[Integration]:+ """The workspace's projects this Slack user can actually reach in PostHog.++ Resolved once per publish and handed to every card: it costs a `UserPermissions`+ build plus three queries, and all three cards want the same answer. It is also the+ authorization boundary for the whole tab, so it should have exactly one definition.+ """+ return _filter_accessible_integrations(+ integration, slack_user_id, _workspace_integrations(integration.integration_id)+ )+++def _resolve_stats_state(+ integration: Integration,+ *,+ accessible: list[Integration],+ is_admin: bool,+ window_days: int = DEFAULT_STATS_WINDOW_DAYS,+ force_refresh: bool = False,+) -> StatsState | None:+ """Workspace activity aggregates, or None when the card shouldn't render at all.++ Admin-only, and rides the same `slack-app-home` gate as the rest of the tab — the+ callers already returned early when that flag is off.++ Scoped to the projects this admin can already reach: being a Slack workspace admin+ says nothing about PostHog org membership, so the card must never widen what its+ viewer could otherwise see.+ """+ if not is_admin:+ return None++ accessible_team_ids = {c.team_id for c in accessible}+ if not accessible_team_ids:+ return None++ try:+ return build_stats_state(+ slack_workspace_id=integration.integration_id,+ accessible_team_ids=accessible_team_ids,+ window_days=window_days,+ force_refresh=force_refresh,+ )+ except Exception:+ # The card is supplementary — a failed aggregate shouldn't cost the user their+ # settings and task list too.+ logger.exception("slack_app_home_stats_resolve_failed", integration_id=integration.id)+ return None+++def _resolve_project_state(+ integration: Integration, slack_user_id: str, *, accessible: list[Integration]+) -> ProjectState:+ candidates = _workspace_integrations(integration.integration_id)if not candidates:return ProjectState()- accessible = _filter_accessible_integrations(integration, slack_user_id, candidates)-user_row = (SlackSettings.objects.filter(slack_workspace_id=integration.integration_id,diff --git a/products/slack_app/backend/services/slack_app_home_stats.py b/products/slack_app/backend/services/slack_app_home_stats.pynew file mode 100644index 000000000000..989b544ade91--- /dev/null+++ b/products/slack_app/backend/services/slack_app_home_stats.py@@ -0,0 +1,397 @@+"""Workspace activity aggregates behind the App Home stats card.++This module is deliberately free of Block Kit: it answers "what did this workspace ship+with @PostHog over the last N days" and returns plain dataclasses. The renderer in+`slack_app_home.py` decides how much of that fits into Slack's chart and table limits,+because caps like the 12 pie segments and 20-character labels are presentation+constraints rather than facts about the data.++Two caps are the exception and live here, because they change what gets *computed* rather+than what gets drawn: `MAX_TREND_POINTS` picks daily-vs-weekly bucketing, and+`_MAX_PEOPLE_ROWS` bounds the leaderboard so the cached aggregate stays small.++Everything is scoped to the tasks a Slack workspace started *and* the caller can already+see: the mapping query filters on `team_id__in=accessible_team_ids`, which the caller+derives from the same accessible-integration check the rest of the Home tab uses. A Slack+workspace admin is not automatically a PostHog org member, so the aggregates must never+widen what the viewer could otherwise reach.+"""++from __future__ import annotations++from collections import defaultdict+from collections.abc import Iterable, Mapping+from dataclasses import dataclass+from datetime import date, datetime, timedelta+from statistics import median+from typing import Any++from django.core.cache import cache+from django.utils import timezone as django_timezone++import structlog++from products.slack_app.backend.models import SlackThreadTaskMapping, SlackUserProfileCache++logger = structlog.get_logger(__name__)++# Window choices offered by the card's picker, in render order.+STATS_WINDOW_OPTIONS: tuple[tuple[int, str], ...] = (+ (7, "Last 7 days"),+ (30, "Last 30 days"),+ (90, "Last 90 days"),+)+DEFAULT_STATS_WINDOW_DAYS = 30+_VALID_WINDOW_DAYS = frozenset(days for days, _ in STATS_WINDOW_OPTIONS)++# Aggregation happens in Python over fetched rows rather than in SQL, so the row set is+# bounded. Hitting the cap is surfaced in the UI instead of silently under-reporting.+STATS_MAX_TASKS = 2000++# The Home tab republishes on open and on every interaction, all inside Slack's 3s SLA,+# so the same aggregate is recomputed far more often than the underlying data changes.+_STATS_CACHE_TTL_SECONDS = 300++# Slack rejects a chart series carrying more than 20 points. The trend is bucketed by day+# while a window fits under that, and by week beyond it, so the cap is enforced where the+# buckets are chosen rather than by truncating a too-long series at render time.+MAX_TREND_POINTS = 20++# The leaderboard is a top-N, not a directory — bounding it here also keeps the cached+# aggregate small on workspaces with hundreds of people.+_MAX_PEOPLE_ROWS = 20++# Display order for the outcome breakdown, and the labels the renderer decorates.+OUTCOME_DONE = "Done"+OUTCOME_FAILED = "Failed"+OUTCOME_CANCELLED = "Cancelled"+OUTCOME_RUNNING = "In progress"+_OUTCOME_ORDER: tuple[str, ...] = (OUTCOME_DONE, OUTCOME_FAILED, OUTCOME_CANCELLED, OUTCOME_RUNNING)++# Terminal run statuses get their own bucket; everything else — including a task with no+# run row yet — is still in flight.+_TERMINAL_OUTCOMES: dict[str, str] = {+ "completed": OUTCOME_DONE,+ "failed": OUTCOME_FAILED,+ "cancelled": OUTCOME_CANCELLED,+}+++@dataclass(frozen=True)+class Slice:+ """One labelled count — an outcome bucket or a model's share of runs."""++ label: str+ value: int+++@dataclass(frozen=True)+class ModelUsage:+ """How many runs a given pinned model handled.++ Carries the raw model id and its runtime so the renderer can format a display label+ without guessing the provider.+ """++ model: str+ runtime_adapter: str | None+ value: int+++@dataclass(frozen=True)+class TrendBucket:+ """PRs opened and merged within one day or week of the window."""++ label: str+ opened: int+ merged: int+++@dataclass(frozen=True)+class PersonRow:+ """One row of the most-active-people table."""++ name: str+ tasks: int+ merged: int+++@dataclass(frozen=True)+class StatsState:+ """Everything the stats card renders, already aggregated.++ ``tasks_with_pr`` and ``tasks_merged`` are both counted off each task's latest+ *PR-bearing* run, so they describe the same runs and the merge rate between them+ cannot exceed 100%.+ """++ window_days: int = DEFAULT_STATS_WINDOW_DAYS+ tasks_started: int = 0+ tasks_with_pr: int = 0+ tasks_merged: int = 0+ # Everyone who started something, not just the leaderboard's top rows.+ active_people: int = 0+ # Median wall-clock of runs that finished successfully. Failed and cancelled runs are+ # excluded — they stop at an arbitrary point and would drag the figure toward noise.+ median_cycle_seconds: int | None = None+ outcomes: tuple[Slice, ...] = ()+ trend: tuple[TrendBucket, ...] = ()+ models: tuple[ModelUsage, ...] = ()+ people: tuple[PersonRow, ...] = ()+ truncated: bool = False+ refreshed_at_epoch: int = 0++ @property+ def has_data(self) -> bool:+ return self.tasks_started > 0++ @property+ def merge_rate_percent(self) -> int | None:+ """Merged as a percentage of tasks that opened a PR. None when nothing opened one."""+ if not self.tasks_with_pr:+ return None+ return round(self.tasks_merged * 100 / self.tasks_with_pr)+++def coerce_window_days(raw: str | int | None) -> int:+ """Clamp an untrusted window value from a Slack payload to one we offer."""+ try:+ days = int(raw) # type: ignore[arg-type]+ except (TypeError, ValueError):+ return DEFAULT_STATS_WINDOW_DAYS+ return days if days in _VALID_WINDOW_DAYS else DEFAULT_STATS_WINDOW_DAYS+++def build_stats_state(+ *,+ slack_workspace_id: str,+ accessible_team_ids: Iterable[int],+ window_days: int = DEFAULT_STATS_WINDOW_DAYS,+ force_refresh: bool = False,+) -> StatsState:+ """Aggregate Slack-started task activity for a workspace over the given window.++ Cached for `_STATS_CACHE_TTL_SECONDS`; the card's Refresh button bypasses the cache.+ """+ team_ids = sorted(set(accessible_team_ids))+ window_days = coerce_window_days(window_days)+ if not slack_workspace_id or not team_ids:+ return StatsState(window_days=window_days)++ cache_key = _cache_key(slack_workspace_id, team_ids, window_days)+ cached = _cache_get(cache_key) if not force_refresh else None+ if cached is not None:+ return cached++ state = _compute_stats_state(+ slack_workspace_id=slack_workspace_id,+ team_ids=team_ids,+ window_days=window_days,+ )+ _cache_set(cache_key, state)+ return state+++def _cache_key(slack_workspace_id: str, team_ids: list[int], window_days: int) -> str:+ teams = ",".join(str(t) for t in team_ids)+ return f"slack_app_home_stats:{slack_workspace_id}:{window_days}:{teams}"+++def _cache_get(cache_key: str) -> StatsState | None:+ # A cache backend outage should slow the Home tab down, not make the card vanish, so+ # both sides of the cache swallow their errors.+ try:+ cached = cache.get(cache_key)+ except Exception:+ logger.warning("slack_app_home_stats_cache_read_failed", cache_key=cache_key)+ return None+ return cached if isinstance(cached, StatsState) else None+++def _cache_set(cache_key: str, state: StatsState) -> None:+ try:+ cache.set(cache_key, state, _STATS_CACHE_TTL_SECONDS)+ except Exception:+ logger.warning("slack_app_home_stats_cache_write_failed", cache_key=cache_key)+++def _compute_stats_state(*, slack_workspace_id: str, team_ids: list[int], window_days: int) -> StatsState:+ # Deferred to keep the tasks facade off this module's import path, matching how the+ # rest of the Home tab reaches it.+ from products.tasks.backend.facade import api as tasks_facade # noqa: PLC0415++ now = django_timezone.now()+ refreshed_at_epoch = int(now.timestamp())+ cutoff = now - timedelta(days=window_days)++ # One extra row tells us the cap was hit without a second COUNT query.+ rows = list(+ SlackThreadTaskMapping.objects.filter(+ slack_workspace_id=slack_workspace_id,+ team_id__in=team_ids,+ created_at__gte=cutoff,+ )+ .order_by("-created_at")+ .values("task_id", "mentioning_slack_user_id", "created_at")[: STATS_MAX_TASKS + 1]+ )+ truncated = len(rows) > STATS_MAX_TASKS+ rows = rows[:STATS_MAX_TASKS]+ if not rows:+ return StatsState(window_days=window_days, refreshed_at_epoch=refreshed_at_epoch)++ # A task is mapped once per thread, but dedupe anyway so a task can't be double-counted.+ first_row_by_task: dict[str, Mapping[str, Any]] = {}+ for row in rows:+ first_row_by_task.setdefault(str(row["task_id"]), row)++ task_ids = list(first_row_by_task)+ runs_by_task = tasks_facade.get_latest_run_by_task(task_ids)+ # `get_latest_pr_url_by_task` and `get_merged_pr_task_ids` resolve the same run for a+ # given task, so "opened a PR" and "merged" always describe one run. The latest run+ # overall — which carries the status and model — may well be a later, PR-less one.+ pr_urls_by_task = tasks_facade.get_latest_pr_url_by_task(task_ids)+ merged_task_ids = tasks_facade.get_merged_pr_task_ids(task_ids)++ outcome_counts: dict[str, int] = defaultdict(int)+ model_counts: dict[tuple[str, str | None], int] = defaultdict(int)+ tasks_by_person: dict[str, int] = defaultdict(int)+ merged_by_person: dict[str, int] = defaultdict(int)+ opened_by_bucket: dict[date, int] = defaultdict(int)+ merged_by_bucket: dict[date, int] = defaultdict(int)+ cycle_seconds: list[int] = []+ tasks_with_pr = 0++ bucket_by_week = window_days > MAX_TREND_POINTS++ for task_id, mapping_row in first_row_by_task.items():+ run = runs_by_task.get(task_id)+ person = mapping_row["mentioning_slack_user_id"] or ""+ bucket = _bucket_start(mapping_row["created_at"], by_week=bucket_by_week)++ outcome_counts[_outcome_label(run.status if run else None)] += 1++ if run is not None:+ model = (run.state or {}).get("model")+ if model:+ model_counts[(str(model), (run.state or {}).get("runtime_adapter"))] += 1+ if run.status == "completed" and run.completed_at and run.created_at:+ elapsed = int((run.completed_at - run.created_at).total_seconds())+ if elapsed >= 0:+ cycle_seconds.append(elapsed)++ tasks_by_person[person] += 1++ if task_id in pr_urls_by_task:+ tasks_with_pr += 1+ opened_by_bucket[bucket] += 1+ if task_id in merged_task_ids:+ merged_by_bucket[bucket] += 1+ merged_by_person[person] += 1++ return StatsState(+ window_days=window_days,+ tasks_started=len(first_row_by_task),+ tasks_with_pr=tasks_with_pr,+ tasks_merged=len(merged_task_ids),+ active_people=len(tasks_by_person),+ median_cycle_seconds=int(median(cycle_seconds)) if cycle_seconds else None,+ outcomes=tuple(+ Slice(label=label, value=outcome_counts[label]) for label in _OUTCOME_ORDER if outcome_counts.get(label)+ ),+ trend=_build_trend(+ opened_by_bucket,+ merged_by_bucket,+ now=now,+ window_days=window_days,+ by_week=bucket_by_week,+ ),+ models=tuple(+ ModelUsage(model=model, runtime_adapter=runtime_adapter, value=count)+ for (model, runtime_adapter), count in sorted(model_counts.items(), key=lambda kv: (-kv[1], kv[0][0]))+ ),+ people=_build_people(tasks_by_person, merged_by_person, slack_workspace_id),+ truncated=truncated,+ refreshed_at_epoch=refreshed_at_epoch,+ )+++def _outcome_label(status: str | None) -> str:+ """Map a run status onto a card bucket.++ A task with no run yet, and any status we don't recognise, counts as in flight —+ every task started in the window has to land in exactly one bucket for the outcome+ counts to add up to the headline total.+ """+ return _TERMINAL_OUTCOMES.get(status or "", OUTCOME_RUNNING)+++def _bucket_start(when: datetime, *, by_week: bool) -> date:+ """The day, or the Monday of the week, a task belongs to."""+ day = when.date()+ return day - timedelta(days=day.weekday()) if by_week else day+++def _build_trend(+ opened_by_bucket: dict[date, int],+ merged_by_bucket: dict[date, int],+ *,+ now: datetime,+ window_days: int,+ by_week: bool,+) -> tuple[TrendBucket, ...]:+ """Every bucket in the window, including empty ones.++ Slack requires each series to carry a point for every axis category, so gaps have to+ be materialised as zeroes rather than skipped.+ """+ end = _bucket_start(now, by_week=by_week)+ start = _bucket_start(now - timedelta(days=window_days - 1), by_week=by_week)+ step = timedelta(days=7 if by_week else 1)++ buckets: list[TrendBucket] = []+ current = start+ while current <= end:+ buckets.append(+ TrendBucket(+ label=current.strftime("%b %d"),+ opened=opened_by_bucket.get(current, 0),+ merged=merged_by_bucket.get(current, 0),+ )+ )+ current += step+ return tuple(buckets)+++def _build_people(+ tasks_by_person: dict[str, int],+ merged_by_person: dict[str, int],+ slack_workspace_id: str,+) -> tuple[PersonRow, ...]:+ """The leaderboard, resolved to human names where the profile cache knows them."""+ if not tasks_by_person:+ return ()++ ranked = sorted(tasks_by_person.items(), key=lambda kv: (-kv[1], kv[0]))[:_MAX_PEOPLE_ROWS]+ slack_user_ids = [slack_user_id for slack_user_id, _ in ranked if slack_user_id]++ # The cache is per-integration and a workspace can be connected to several projects,+ # so match on the workspace and keep the first profile found for each Slack user.+ # Name precedence matches `slack_messages`, so one person reads the same on the+ # leaderboard as in forwarded thread context.+ names: dict[str, str] = {}+ for profile in SlackUserProfileCache.objects.filter(+ integration__integration_id=slack_workspace_id,+ slack_user_id__in=slack_user_ids,+ ).values("slack_user_id", "real_name", "display_name"):+ name = profile["display_name"] or profile["real_name"]+ if name:+ names.setdefault(profile["slack_user_id"], name)++ return tuple(+ PersonRow(+ name=names.get(slack_user_id) or slack_user_id or "Unknown",+ tasks=task_count,+ merged=merged_by_person.get(slack_user_id, 0),+ )+ for slack_user_id, task_count in ranked+ )diff --git a/products/slack_app/backend/tests/services/test_slack_app_home_stats.py b/products/slack_app/backend/tests/services/test_slack_app_home_stats.pynew file mode 100644index 000000000000..6de5ee7d670a--- /dev/null+++ b/products/slack_app/backend/tests/services/test_slack_app_home_stats.py@@ -0,0 +1,495 @@+from __future__ import annotations++import re+from datetime import timedelta++import pytest+from unittest.mock import MagicMock, patch++from django.apps import apps+from django.core.cache import cache+from django.utils import timezone++from posthog.models.integration import Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team++from products.slack_app.backend.models import SlackThreadTaskMapping, SlackUserProfileCache+from products.slack_app.backend.services.slack_app_home import handle_app_home_opened, render_home_view+from products.slack_app.backend.services.slack_app_home_stats import (+ DEFAULT_STATS_WINDOW_DAYS,+ ModelUsage,+ PersonRow,+ StatsState,+ TrendBucket,+ build_stats_state,+ coerce_window_days,+)+from products.slack_app.backend.services.slack_settings import AIPreferences++WORKSPACE = "T_STATS"+SLACK_USER = "U_ADMIN"++# Slack's documented Block Kit caps. Exceeding any of them makes `views.publish` fail with+# `invalid_blocks`, which takes down the whole Home tab and not just this card.+MAX_MODEL_ROWS = 6+MAX_CHART_POINTS = 20+MAX_LABEL_CHARS = 14+MAX_SECTION_FIELDS = 10++[email protected](autouse=True)+def _clear_stats_cache():+ cache.clear()+ yield+ cache.clear()+++def slack_integration(db):+ organization = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=organization, name="Team")+ return Integration.objects.create(+ team=team,+ kind="slack",+ integration_id=WORKSPACE,+ sensitive_config={"access_token": "xoxb"},+ )+++def mock_slack_client():+ fake_client = MagicMock()+ with patch("products.slack_app.backend.services.slack_app_home.SlackIntegration") as cls:+ instance = MagicMock()+ instance.client = fake_client+ cls.return_value = instance+ yield fake_client+++def flag_on():+ with patch(+ "products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled",+ return_value=True,+ ):+ yield+++def admin_user():+ with patch(+ "products.slack_app.backend.services.slack_app_home.is_slack_workspace_admin",+ return_value=True,+ ):+ yield+++def _mk_task_with_run(+ *,+ team,+ integration,+ slack_user_id: str = SLACK_USER,+ channel: str = "C1",+ thread_ts: str = "1.1",+ status: str = "completed",+ pr_url: str | None = None,+ pr_merged: bool = False,+ model: str | None = "claude-opus-5",+ created_at=None,+) -> SlackThreadTaskMapping:+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")++ task = Task.objects.create(team=team, title="t")+ output: dict = {}+ if pr_url:+ output["pr_url"] = pr_url+ output["pr_merged"] = pr_merged+ state = {"model": model, "runtime_adapter": "claude"} if model else {}+ task_run = TaskRun.objects.create(team=team, task=task, status=status, output=output, state=state)++ mapping = SlackThreadTaskMapping.objects.create(+ team=team,+ integration=integration,+ slack_workspace_id=WORKSPACE,+ channel=channel,+ thread_ts=thread_ts,+ task=task,+ task_run=task_run,+ mentioning_slack_user_id=slack_user_id,+ )+ if created_at is not None:+ # `created_at` is auto_now_add, so backdating has to bypass the model save.+ SlackThreadTaskMapping.objects.filter(pk=mapping.pk).update(created_at=created_at)+ mapping.refresh_from_db()+ return mapping+++def _blocks_of_type(view: dict, block_type: str) -> list[dict]:+ return [b for b in view["blocks"] if b["type"] == block_type]+++def _fields_blocks(view: dict) -> list[dict]:+ return [b for b in view["blocks"] if b["type"] == "section" and "fields" in b]+++def _kpi_grid(view: dict) -> dict:+ return next(b for b in _fields_blocks(view) if any(f["text"].startswith("*Tasks*") for f in b["fields"]))+++def _breakdowns_block(view: dict) -> dict:+ return next(b for b in _fields_blocks(view) if any(f["text"].startswith("*Models*") for f in b["fields"]))+++def _column(view: dict, heading: str) -> str:+ return next(f["text"] for b in _fields_blocks(view) for f in b["fields"] if f["text"].startswith(heading))+++def _render(state: StatsState | None) -> dict:+ return render_home_view(+ effective=AIPreferences(),+ user_row=None,+ workspace_row=None,+ is_admin=True,+ stats_state=state,+ )+++class TestWindowCoercion:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("7", 7),+ ("30", 30),+ ("90", 90),+ (90, 90),+ ("99999", DEFAULT_STATS_WINDOW_DAYS),+ ("-1", DEFAULT_STATS_WINDOW_DAYS),+ ("nonsense", DEFAULT_STATS_WINDOW_DAYS),+ (None, DEFAULT_STATS_WINDOW_DAYS),+ ],+ )+ def test_untrusted_window_is_clamped_to_an_offered_option(self, raw, expected):+ assert coerce_window_days(raw) == expected+++class TestStatsCardRendering:+ def test_card_omitted_when_state_is_none(self):+ view = _render(None)+ assert "Workspace activity" not in str(view)++ def test_empty_window_renders_controls_without_charts(self):+ view = _render(StatsState(window_days=30))+ assert "Workspace activity" in str(view)+ # An empty window has nothing to plot and nobody to list.+ assert "*Models*" not in str(view)+ assert "*Most active*" not in str(view)++ def test_model_bars_fold_the_tail_without_losing_counts(self):+ models = tuple(ModelUsage(model=f"model-{i}", runtime_adapter="claude", value=20 - i) for i in range(15))+ view = _render(StatsState(tasks_started=100, models=models))++ column = _column(view, "*Models*")+ lines = [line for line in column.splitlines() if line and not line.startswith(("*", "`"))]++ assert len(lines) <= MAX_MODEL_ROWS+ assert lines[-1].startswith("Other")+ # The folded tail carries the models that didn't get their own row.+ counted = sum(int(line.rsplit(" ", 1)[-1]) for line in lines)+ assert counted == sum(m.value for m in models)++ def test_card_sits_below_the_welcome_and_above_the_settings(self):+ view = _render(StatsState(tasks_started=1))+ rendered = [str(block) for block in view["blocks"]]++ welcome_at = next(i for i, b in enumerate(rendered) if "Welcome to PostHog" in b)+ stats_at = next(i for i, b in enumerate(rendered) if "Workspace activity" in b)+ model_at = next(i for i, b in enumerate(rendered) if "AI model" in b)++ # An admin opens the tab for the activity; routing and model are set once and+ # rarely revisited, so they must not push it below the fold.+ assert welcome_at < stats_at < model_at++ def test_headline_renders_as_a_two_column_field_grid(self):+ view = _render(+ StatsState(+ tasks_started=24,+ tasks_with_pr=18,+ tasks_merged=11,+ active_people=5,+ median_cycle_seconds=840,+ )+ )+ grid = _kpi_grid(view)++ # Slack lays `fields` out in two columns and rejects more than 10 cells; a stack of+ # sections instead would cost one full-width row per KPI.+ assert len(grid["fields"]) <= MAX_SECTION_FIELDS+ rendered = [f["text"] for f in grid["fields"]]+ assert "*Tasks*\n24" in rendered+ assert "*Merge rate*\n61%" in rendered+ assert "*Median run*\n14m" in rendered+ assert "*People*\n5" in rendered++ @pytest.mark.parametrize(+ "seconds, expected",+ [+ (None, "—"),+ (45, "45s"),+ (840, "14m"),+ (3600, "1h"),+ (7500, "2h 5m"),+ (259200, "3d"),+ ],+ )+ def test_durations_render_compactly(self, seconds, expected):+ view = _render(StatsState(tasks_started=1, median_cycle_seconds=seconds))+ assert f"*Median run*\n{expected}" in [f["text"] for f in _kpi_grid(view)["fields"]]++ def test_long_model_ids_are_truncated_to_the_label_cap(self):+ view = _render(+ StatsState(+ tasks_started=1,+ models=(+ ModelUsage(+ model="anthropic/claude-sonnet-4-5-with-an-absurdly-long-name",+ runtime_adapter="claude",+ value=1,+ ),+ ),+ )+ )+ labels = [+ line.split(" ")[0]+ for line in _column(view, "*Models*").splitlines()+ if line and not line.startswith(("*", "`"))+ ]+ # A long label would push the bar column out of alignment inside the fenced block.+ assert all(len(label) <= MAX_LABEL_CHARS for label in labels)++ def test_trend_sparklines_scale_both_series_against_one_peak(self):+ trend = (+ TrendBucket(label="Jul 07", opened=8, merged=0),+ TrendBucket(label="Jul 14", opened=0, merged=4),+ )+ view = _render(StatsState(tasks_started=12, tasks_with_pr=8, trend=trend))++ text = next(b["elements"][0]["text"] for b in view["blocks"] if b["type"] == "context" and "*PRs*" in str(b))+ opened, merged = re.findall(r"`([^`]+)`", text)++ assert len(opened) == len(merged) == len(trend)+ # Shared peak: merged's 4 must read as half of opened's 8, not as its own maximum.+ assert opened[0] == "█" and merged[0] == "▁"+ assert merged[1] < opened[0]+ assert "Jul 07 → Jul 14" in text++ def test_trend_omitted_when_the_window_produced_no_prs(self):+ trend = (TrendBucket(label="Jul 07", opened=0, merged=0),)+ view = _render(StatsState(tasks_started=3, tasks_with_pr=0, trend=trend))+ assert not [b for b in view["blocks"] if b["type"] == "context" and "*PRs*" in str(b)]++ def test_models_and_people_render_as_two_columns_of_one_block(self):+ view = _render(+ StatsState(+ tasks_started=9,+ models=(ModelUsage(model="claude-opus-5", runtime_adapter="claude", value=9),),+ people=(PersonRow(name="Vojta", tasks=9, merged=6), PersonRow(name="Anna", tasks=4, merged=1)),+ )+ )++ # `section.fields` is the only two-column layout Block Kit offers, so both+ # breakdowns have to share one block to sit side by side.+ block = _breakdowns_block(view)+ columns = [f["text"] for f in block["fields"]]++ assert len(columns) == 2+ assert columns[0].startswith("*Models*")+ assert columns[1].startswith("*Most active*")+ assert "Vojta" in columns[1] and "Anna" in columns[1]++ def test_leaderboard_columns_stay_aligned_under_a_long_name(self):+ people = (PersonRow(name="A", tasks=9, merged=6), PersonRow(name="Bartholomew Wigglesworth", tasks=4, merged=1))+ view = _render(StatsState(tasks_started=13, people=people))++ column = _column(view, "*Most active*")+ rows = [line for line in column.splitlines() if line and not line.startswith(("*", "`"))]++ # Names are padded to a common width inside the fenced block, so the count+ # columns line up rather than drifting with each name's length.+ assert len({len(row) for row in rows}) == 1+++class TestResolveStatsState:+ def test_counts_prs_and_merges_off_the_same_tasks(self, slack_integration):+ team = slack_integration.team+ _mk_task_with_run(team=team, integration=slack_integration, thread_ts="1.1", pr_url="u/1", pr_merged=True)+ _mk_task_with_run(team=team, integration=slack_integration, thread_ts="1.2", pr_url="u/2", pr_merged=False)+ _mk_task_with_run(team=team, integration=slack_integration, thread_ts="1.3", pr_url=None)++ state = build_stats_state(slack_workspace_id=WORKSPACE, accessible_team_ids={team.id})++ assert state.tasks_started == 3+ assert state.tasks_with_pr == 2+ assert state.tasks_merged == 1+ assert state.merge_rate_percent == 50++ def test_merge_rate_survives_a_later_run_that_produced_no_pr(self, slack_integration):+ team = slack_integration.team+ TaskRun = apps.get_model("tasks", "TaskRun")+ mapping = _mk_task_with_run(+ team=team, integration=slack_integration, pr_url="u/1", pr_merged=True, status="completed"+ )+ # A follow-up run on the same task that never opened a PR. Counting "opened a PR"+ # off the latest run of any kind would drop this task from the denominator while+ # the merge helper still counts it, pushing the rate above 100%.+ TaskRun.objects.create(team=team, task=mapping.task, status="failed", output={}, state={})++ state = build_stats_state(slack_workspace_id=WORKSPACE, accessible_team_ids={team.id})++ assert state.tasks_with_pr == 1+ assert state.tasks_merged == 1+ assert state.merge_rate_percent == 100++ def test_median_run_time_ignores_runs_that_did_not_complete(self, slack_integration):+ team = slack_integration.team+ TaskRun = apps.get_model("tasks", "TaskRun")+ # Completed runs of 10 and 30 minutes, plus a failed one that ran for a week. The+ # failed run stopped at an arbitrary point, so letting it in would swamp the median.+ for index, (status, minutes) in enumerate([("completed", 10), ("completed", 30), ("failed", 10080)]):+ mapping = _mk_task_with_run(team=team, integration=slack_integration, thread_ts=f"1.{index}", status=status)+ TaskRun.objects.filter(pk=mapping.task_run_id).update(+ completed_at=mapping.task_run.created_at + timedelta(minutes=minutes)+ )++ state = build_stats_state(slack_workspace_id=WORKSPACE, accessible_team_ids={team.id})++ assert state.median_cycle_seconds == 20 * 60++ def test_active_people_counts_everyone_not_just_the_leaderboard(self, slack_integration):+ team = slack_integration.team+ for index in range(3):+ _mk_task_with_run(+ team=team,+ integration=slack_integration,+ thread_ts=f"1.{index}",+ slack_user_id=f"U_PERSON_{index}",+ )++ state = build_stats_state(slack_workspace_id=WORKSPACE, accessible_team_ids={team.id})++ assert state.active_people == 3++ def test_model_usage_is_aggregated_from_the_latest_run_state(self, slack_integration):+ team = slack_integration.team+ for index, model in enumerate(["claude-opus-5", "claude-opus-5", "gpt-5-codex"]):+ _mk_task_with_run(team=team, integration=slack_integration, thread_ts=f"1.{index}", model=model)++ state = build_stats_state(slack_workspace_id=WORKSPACE, accessible_team_ids={team.id})++ assert [(usage.model, usage.value) for usage in state.models] == [+ ("claude-opus-5", 2),+ ("gpt-5-codex", 1),+ ]++ def test_merge_rate_is_none_when_nothing_opened_a_pr(self, slack_integration):+ team = slack_integration.team+ _mk_task_with_run(team=team, integration=slack_integration, pr_url=None)++ state = build_stats_state(slack_workspace_id=WORKSPACE, accessible_team_ids={team.id})++ assert state.tasks_with_pr == 0+ assert state.merge_rate_percent is None++ def test_excludes_tasks_from_teams_the_viewer_cannot_access(self, slack_integration):+ other_org = Organization.objects.create(name="Other org")+ other_team = Team.objects.create(organization=other_org, name="Other team")+ other_integration = Integration.objects.create(+ team=other_team,+ kind="slack",+ integration_id=WORKSPACE,+ sensitive_config={"access_token": "xoxb"},+ )+ _mk_task_with_run(team=slack_integration.team, integration=slack_integration, thread_ts="1.1")+ _mk_task_with_run(team=other_team, integration=other_integration, thread_ts="2.1", channel="C2")++ state = build_stats_state(+ slack_workspace_id=WORKSPACE,+ accessible_team_ids={slack_integration.team_id},+ )++ assert state.tasks_started == 1++ def test_excludes_activity_older_than_the_window(self, slack_integration):+ team = slack_integration.team+ _mk_task_with_run(team=team, integration=slack_integration, thread_ts="1.1")+ _mk_task_with_run(+ team=team,+ integration=slack_integration,+ thread_ts="1.2",+ created_at=timezone.now() - timedelta(days=45),+ )++ state = build_stats_state(slack_workspace_id=WORKSPACE, accessible_team_ids={team.id}, window_days=30)++ assert state.tasks_started == 1++ def test_every_started_task_lands_in_exactly_one_outcome_bucket(self, slack_integration):+ team = slack_integration.team+ for index, status in enumerate(["completed", "failed", "cancelled", "in_progress", "queued"]):+ _mk_task_with_run(team=team, integration=slack_integration, thread_ts=f"1.{index}", status=status)++ state = build_stats_state(slack_workspace_id=WORKSPACE, accessible_team_ids={team.id})++ assert sum(outcome.value for outcome in state.outcomes) == state.tasks_started++ @pytest.mark.parametrize("window_days", [7, 30, 90])+ def test_trend_buckets_stay_within_the_chart_point_cap(self, slack_integration, window_days):+ team = slack_integration.team+ _mk_task_with_run(team=team, integration=slack_integration, pr_url="u/1", pr_merged=True)++ state = build_stats_state(+ slack_workspace_id=WORKSPACE,+ accessible_team_ids={team.id},+ window_days=window_days,+ )++ assert 0 < len(state.trend) <= MAX_CHART_POINTS++ def test_leaderboard_resolves_slack_ids_to_cached_names(self, slack_integration):+ team = slack_integration.team+ SlackUserProfileCache.objects.create(+ integration=slack_integration,+ slack_user_id=SLACK_USER,+ real_name="Vojta Bartos",+ )+ _mk_task_with_run(team=team, integration=slack_integration, thread_ts="1.1", pr_url="u/1", pr_merged=True)+ _mk_task_with_run(team=team, integration=slack_integration, thread_ts="1.2", slack_user_id="U_UNKNOWN")++ state = build_stats_state(slack_workspace_id=WORKSPACE, accessible_team_ids={team.id})++ by_name = {person.name: person for person in state.people}+ assert by_name["Vojta Bartos"].tasks == 1+ assert by_name["Vojta Bartos"].merged == 1+ # No cached profile — falling back to the raw id beats dropping the row.+ assert by_name["U_UNKNOWN"].tasks == 1++ def test_no_accessible_teams_yields_an_empty_card(self, slack_integration):+ _mk_task_with_run(team=slack_integration.team, integration=slack_integration)++ state = build_stats_state(slack_workspace_id=WORKSPACE, accessible_team_ids=set())++ assert not state.has_data+++class TestStatsCardGating:+ @pytest.mark.parametrize("is_admin, expected_visible", [(True, True), (False, False)])+ def test_card_is_admin_only(self, slack_integration, mock_slack_client, flag_on, is_admin, expected_visible):+ with patch(+ "products.slack_app.backend.services.slack_app_home.is_slack_workspace_admin",+ return_value=is_admin,+ ):+ handle_app_home_opened({"user": SLACK_USER}, WORKSPACE)++ view = mock_slack_client.views_publish.call_args.kwargs["view"]+ assert ("Workspace activity" in str(view)) is expected_visible