: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(signals): autostart reviewer-less reports and default inbox scope (#68844)
Joshua Snyderdc08ee38561c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 66d74b117588..137efcea3870 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5863,7 +5863,7 @@ snapshots:scenes-app-inbox-pullrequestdiffview--truncated--light:hash: v1.k794b7964.c8211a05cd4404a003460d2c4abe79fb078edd5c7801422dbb3a5c55cc50f6a1.R85Q2EEe3EteBgaslGBlB4Vp7AdPgMstb0whb50OXycscenes-app-inbox-scene--empty--dark:- hash: v1.k794b7964.59cfa41575869858a73b2a7ce71fd5a95d5185d418ac0b755ff2e45c6fdf20b5.nNFglXwlzwm71vGR0-QAnNDIYdInXgSzT_k2pie3NT8+ hash: v1.k794b7964.0aafc7b733bbc111b069cec4a54d0aefb3178d313438f1ead34e674c90b25e3e.-QT6yl-ujsJL_nvqzzk-gZTwKMv0AREbT4tHngwBB-Qscenes-app-inbox-scene--empty--light:hash: v1.k794b7964.9ac628482107f92f19d4440301e8dad66f38a9df250d5321f6544733a697e2b6.XhpQBR1sBJS3CaCwS02LNxOUFfI6NqlI6BG3vvWWIp8scenes-app-inbox-scene--inbox--dark:diff --git a/frontend/src/scenes/inbox/logics/inboxFiltersLogic.ts b/frontend/src/scenes/inbox/logics/inboxFiltersLogic.tsindex 0d8f43f22a88..498d560a21ad 100644--- a/frontend/src/scenes/inbox/logics/inboxFiltersLogic.ts+++ b/frontend/src/scenes/inbox/logics/inboxFiltersLogic.ts@@ -53,6 +53,9 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([actions({setScope: (scope: InboxScope) => ({ scope }),+ // Auto-select a default scope (e.g. Entire project when the user has no assigned reports)+ // without marking it as an explicit user choice, so a later real choice still wins and persists.+ applyDefaultScope: (scope: InboxScope) => ({ scope }),setSearchQuery: (searchQuery: string) => ({ searchQuery }),setSort: (field: InboxSortField, direction: InboxSortDirection) => ({ field, direction }),toggleSourceProduct: (source: string) => ({ source }),@@ -89,6 +92,16 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([{ persist: true },{setScope: (_, { scope }) => scope,+ applyDefaultScope: (_, { scope }) => scope,+ },+ ],+ // Whether the user has explicitly picked a scope. Once true, the empty-inbox auto-default+ // no longer fires, so a deliberate choice of "For you" is respected even with zero reports.+ hasUserChosenScope: [+ false,+ { persist: true },+ {+ setScope: () => true,},],// Not persisted – matches desktop (searchQuery is excluded from `partialize`).diff --git a/frontend/src/scenes/inbox/logics/reportListLogic.test.ts b/frontend/src/scenes/inbox/logics/reportListLogic.test.tsnew file mode 100644index 000000000000..266b00f4262b--- /dev/null+++ b/frontend/src/scenes/inbox/logics/reportListLogic.test.ts@@ -0,0 +1,33 @@+import { INBOX_SCOPE_ENTIRE_PROJECT, INBOX_SCOPE_FOR_YOU, InboxFlatListTabKey, InboxScope } from '../types'+import { shouldDefaultToEntireProject } from './reportListLogic'++describe('shouldDefaultToEntireProject', () => {+ const base = {+ tabKey: 'pulls' as InboxFlatListTabKey,+ scope: INBOX_SCOPE_FOR_YOU as InboxScope,+ hasUserChosenScope: false,+ hasResolvedUser: true,+ count: 0 as number | null,+ }++ it('switches to Entire project when a fresh user has zero assigned PRs', () => {+ expect(shouldDefaultToEntireProject(base)).toBe(true)+ })++ it.each<[string, Partial<typeof base>]>([+ // The user has PRs assigned – keep them on For you.+ ['user has assigned PRs', { count: 3 }],+ // The user deliberately picked a scope – never override it, even with zero PRs.+ ['user chose their scope', { hasUserChosenScope: true }],+ // Only the Pull requests tab (their assigned PRs) drives the default.+ ['not the pulls tab', { tabKey: 'reports' as InboxFlatListTabKey }],+ // Already off For you – nothing to default.+ ['already entire project', { scope: INBOX_SCOPE_ENTIRE_PROJECT as InboxScope }],+ // Count for For-you scope is only meaningful once the user's uuid has resolved.+ ['user not resolved yet', { hasResolvedUser: false }],+ // Count request in flight / failed (null) is not treated as "zero".+ ['count not loaded', { count: null }],+ ])('stays put when %s', (_label, override) => {+ expect(shouldDefaultToEntireProject({ ...base, ...override })).toBe(false)+ })+})diff --git a/frontend/src/scenes/inbox/logics/reportListLogic.ts b/frontend/src/scenes/inbox/logics/reportListLogic.tsindex dfb41259b90c..6f048be25b2d 100644--- a/frontend/src/scenes/inbox/logics/reportListLogic.ts+++ b/frontend/src/scenes/inbox/logics/reportListLogic.ts@@ -7,7 +7,14 @@ import api, { CountedPaginatedResponse } from 'lib/api'import { userLogic } from 'scenes/userLogic'import { captureInboxReportAction } from '../inboxAnalytics'-import { ACTIONABLE_ACTIONABILITY_VALUES, INBOX_SCOPE_FOR_YOU, InboxFlatListTabKey, SignalReport } from '../types'+import {+ ACTIONABLE_ACTIONABILITY_VALUES,+ INBOX_SCOPE_ENTIRE_PROJECT,+ INBOX_SCOPE_FOR_YOU,+ InboxFlatListTabKey,+ InboxScope,+ SignalReport,+} from '../types'import { DismissalReasonValue } from '../utils/dismissalReasons'import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'import { buildSignalReportListOrdering, inboxFiltersLogic } from './inboxFiltersLogic'@@ -45,6 +52,29 @@ function teammateUuidFromScope(scope: string): string | undefined {return scope.startsWith('teammate:') ? scope.slice('teammate:'.length).trim() || undefined : undefined}+/**+ * Whether to auto-switch the reviewer scope to Entire project on first load. True only for the+ * Pull requests tab when the user is still on the (default) For-you scope, hasn't chosen a scope+ * themselves, has resolved to a real user, and has zero PRs suggested to them — so a user with+ * nothing assigned doesn't land on an empty view. Pure so the branching is unit-testable without+ * mounting the logic.+ */+export function shouldDefaultToEntireProject(input: {+ tabKey: InboxFlatListTabKey+ scope: InboxScope+ hasUserChosenScope: boolean+ hasResolvedUser: boolean+ count: number | null+}): boolean {+ return (+ input.tabKey === 'pulls' &&+ input.scope === INBOX_SCOPE_FOR_YOU &&+ !input.hasUserChosenScope &&+ input.hasResolvedUser &&+ input.count === 0+ )+}+/*** Keyed per-tab report list. Mounted once per flat tab (pulls / reports / not-actionable),* each with its own fixed `listParams`, so every tab is its own filtered request with its@@ -62,13 +92,29 @@ export const reportListLogic = kea<reportListLogicType>([connect(() => ({values: [inboxFiltersLogic,- ['scope', 'searchQuery', 'sortField', 'sortDirection', 'sourceProductFilter', 'priorityFilter'],+ [+ 'scope',+ 'hasUserChosenScope',+ 'searchQuery',+ 'sortField',+ 'sortDirection',+ 'sourceProductFilter',+ 'priorityFilter',+ ],userLogic,['user'],],actions: [inboxFiltersLogic,- ['setSearchQuery', 'setSort', 'toggleSourceProduct', 'togglePriority', 'setScope', 'clearFilters'],+ [+ 'setSearchQuery',+ 'setSort',+ 'toggleSourceProduct',+ 'togglePriority',+ 'setScope',+ 'applyDefaultScope',+ 'clearFilters',+ ],],})),@@ -167,7 +213,24 @@ export const reportListLogic = kea<reportListLogicType>([isLoaded: [(s) => [s.reportsResponse], (reportsResponse): boolean => reportsResponse !== null],}),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, props }) => ({+ // First For-you count for the Pull requests tab: if the user has no PRs suggested to them,+ // default to Entire project so they don't land on an empty view. Only when they haven't+ // picked a scope themselves, and only once the user's uuid has resolved (so the count is+ // genuinely theirs, not an unfiltered project-wide count).+ loadCountSuccess: () => {+ if (+ shouldDefaultToEntireProject({+ tabKey: props.tabKey,+ scope: values.scope,+ hasUserChosenScope: values.hasUserChosenScope,+ hasResolvedUser: !!values.user?.uuid,+ count: values.count,+ })+ ) {+ actions.applyDefaultScope(INBOX_SCOPE_ENTIRE_PROJECT)+ }+ },ensureLoaded: () => {if (values.reportsResponse === null && !values.reportsResponseLoading) {actions.loadReports()@@ -193,6 +256,7 @@ export const reportListLogic = kea<reportListLogicType>([toggleSourceProduct: () => actions.refresh(),togglePriority: () => actions.refresh(),setScope: () => actions.refresh(),+ applyDefaultScope: () => actions.refresh(),clearFilters: () => actions.refresh(),// For-you scope needs the current user's uuid; reload once it resolves.[userLogic.actionTypes.loadUserSuccess]: () => {diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex 45adb285c377..a94764da4879 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -9,11 +9,13 @@ import structlogfrom pydantic import BaseModel, ValidationErrorfrom posthog.models import Team, User+from posthog.models.organization import OrganizationMembershipfrom posthog.sync import database_sync_to_asyncfrom products.signals.backend.models import (SignalReport,SignalReportArtefact,+ SignalSourceConfig,SignalTeamConfig,SignalUserAutonomyConfig,)@@ -62,6 +64,17 @@ def _effective_threshold(config: SignalUserAutonomyConfig | None, team_default_preturn Priority(config.autostart_priority) if config and config.autostart_priority else team_default_priority+def _report_meets_team_autostart_threshold(report_priority: Priority, team_default_priority: Priority) -> bool:+ """Whether the report's priority is at or above the team's default autostart threshold.++ Gates the reviewer-less fallback so a team that set ``default_autostart_priority`` (e.g. P2)+ doesn't get autonomous PRs for lower-priority reports. Lower rank = higher priority; the team+ default is P4 ("all priorities") when the team has no config row, so the gate is a no-op then.+ Per-user autostart priorities are intentionally not consulted — the fallback has no named user.+ """+ return _priority_rank(report_priority) <= _priority_rank(team_default_priority)++def _build_autostart_task_description(*, report_id: str, summary: str, repository: str, priority: PriorityAssessment | None) -> str:@@ -214,6 +227,61 @@ def _resolve_autostart_assignee(return None+def _resolve_autostart_fallback_user(team_id: int) -> User | None:+ """Assignee for an actionable report whose suggested reviewers don't resolve to a member.++ Suggested reviewers are advisory — a report can be immediately actionable with a clear fix+ even when none of its suggested reviewers have linked a GitHub account (or it has none at all).+ Rather than drop the auto-start, run the implementation task under the human who turned signals+ on for this team. Enabling a signal source is the team's opt-in to the signals product, of which+ autonomous PRs are a part, so attributing the task to that member is within the team's consent.++ Resolution, restricted at every tier to *active* org members (still in the org and not+ deactivated) — the task mints a PostHog OAuth token as this user, so a departed or disabled+ account can't run it:++ 1. The earliest active member who enabled a ``SignalSourceConfig`` for this team (ordered by+ the source's creation time) — who first turned signals on.+ 2. If none (sources enabled by a system path leave ``created_by`` null), the organization's+ owner, then an admin — the accountable human for an org that is clearly running signals.+ 3. Otherwise ``None`` — no eligible human, so nothing auto-starts.++ Deterministic within each tier so concurrent evaluations pick the same user.+ """+ org_id = Team.objects.filter(id=team_id).values_list("organization_id", flat=True).first()+ if org_id is None:+ return None++ active_member_ids = OrganizationMembership.objects.filter(organization_id=org_id, user__is_active=True).values_list(+ "user_id", flat=True+ )++ # Tier 1: the earliest active member who enabled a signal source for this team.+ enabler_id = (+ SignalSourceConfig.objects.filter(team_id=team_id, created_by_id__in=active_member_ids)+ .order_by("created_at")+ .values_list("created_by_id", flat=True)+ .first()+ )+ if enabler_id is not None:+ return User.objects.filter(id=enabler_id).first()++ # Tier 2: no active enabler — fall back to the org's owner, then an admin (highest level first).+ fallback_id = (+ OrganizationMembership.objects.filter(+ organization_id=org_id,+ user__is_active=True,+ level__gte=OrganizationMembership.Level.ADMIN,+ )+ .order_by("-level", "user_id")+ .values_list("user_id", flat=True)+ .first()+ )+ if fallback_id is not None:+ return User.objects.filter(id=fallback_id).first()+ return None++def _resolve_triggering_user(team_id: int,user_id: int,@@ -260,12 +328,20 @@ async def maybe_autostart_implementation_task(Idempotent: skipped if an implementation task already started for the report(a `SignalReportTask` implementation gate row), if the report is not immediately- actionable, if it's already addressed, if priority is missing, if there are no- suggested reviewers, or if no reviewer qualifies. The- "already started" check is enforced atomically under a row lock in+ actionable, if it's already addressed, or if priority is missing. The "already+ started" check is enforced atomically under a row lock in`_create_implementation_task_if_absent`, so concurrent evaluations(reviewer-edit hook, pipeline, custom agent) can't double-start.+ Suggested reviewers no longer gate the pipeline path: an immediately-actionable report+ whose reviewers don't resolve to a connected-GitHub member (or has none) still auto-starts+ under the member who enabled signals for the team (see `_resolve_autostart_fallback_user`),+ provided the report meets the team's ``default_autostart_priority``, so a clear fix isn't+ dropped just because nobody linked GitHub. It's skipped when the report is below that team+ threshold or no such member exists. The user-triggered path (a reviewer edit) still runs+ strictly as the editing user and never falls back, so it can't act under another member's+ identity.+Both the agentic signals pipeline (``temporal/agentic/report.py``) and thecustom agent activity (``temporal/custom_agent.py``) call this after persistingtheir report and artefacts. Callers should wrap this in try/except so an@@ -287,8 +363,6 @@ async def maybe_autostart_implementation_task(skip_reason = "report already addressed"elif priority is None:skip_reason = "no priority assessment"- elif not reviewers_content:- skip_reason = "no suggested reviewers"if skip_reason is not None:logger.info("signals auto-start skipped", report_id=report_id, team_id=team_id, reason=skip_reason)return@@ -308,12 +382,17 @@ async def maybe_autostart_implementation_task(task_user = await database_sync_to_async(_resolve_autostart_assignee, thread_sensitive=False)(team_id, priority.priority, reviewers_content, team_default_priority)+ if task_user is None and _report_meets_team_autostart_threshold(priority.priority, team_default_priority):+ # No suggested reviewer resolved to a connected-GitHub member, but the report meets the+ # team's default autostart priority, so run it under the member who enabled signals for+ # the team rather than dropping the PR.+ task_user = await database_sync_to_async(_resolve_autostart_fallback_user, thread_sensitive=False)(team_id)if task_user is None:logger.info("signals auto-start skipped",report_id=report_id,team_id=team_id,- reason="no reviewer meets the autonomy priority threshold",+ reason="no autostart runner: no reviewer met threshold, and no enabling member for a report at/above the team autostart priority",)return@@ -437,15 +516,11 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)priority = await _latest_artefact_as(report_id, SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT, PriorityAssessment)+ # Empty / unresolved reviewers no longer short-circuit here: `maybe_autostart_implementation_task`+ # falls back to the member who enabled signals for the team (for the system/scout path, gated by+ # the team autostart priority), while a user-edited list still runs strictly as the editing user+ # via `triggering_user_id` below.reviewers_content, editor_user_id = await _latest_reviewers_content(report_id)- if not reviewers_content:- logger.info(- "signals auto-start re-eval skipped",- report_id=report_id,- team_id=team_id,- reason="no suggested reviewers",- )- returnawait maybe_autostart_implementation_task(team_id=team_id,diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.pyindex 1242658a57e3..32af119b0b64 100644--- a/products/signals/backend/test/test_auto_start.py+++ b/products/signals/backend/test/test_auto_start.py@@ -13,13 +13,16 @@ from posthog.models.organization import OrganizationMembershipfrom products.signals.backend.auto_start import (ReviewerContent,_create_implementation_task_if_absent,+ _report_meets_team_autostart_threshold,_resolve_autostart_assignee,+ _resolve_autostart_fallback_user,_resolve_triggering_user,)from products.signals.backend.models import (SignalReport,SignalReportArtefact,SignalReportTask,+ SignalSourceConfig,SignalUserAutonomyConfig,)from products.signals.backend.report_generation.research import Priority@@ -84,6 +87,88 @@ def test_resolve_autostart_assignee(assert assignee is None+ ("report_priority", "team_default_priority", "expected"),+ [+ (Priority.P0, Priority.P2, True), # above the team threshold → fallback may fire+ (Priority.P2, Priority.P2, True), # at the team threshold → fallback may fire+ (Priority.P3, Priority.P2, False), # below a stricter team threshold → gated out+ (Priority.P4, Priority.P4, True), # default "all priorities" admits the lowest priority+ ],+)+def test_report_meets_team_autostart_threshold(report_priority, team_default_priority, expected):+ # Guards the reviewer-less fallback against auto-opening PRs for reports below the team's+ # configured default_autostart_priority (per-user priorities are intentionally ignored here).+ assert _report_meets_team_autostart_threshold(report_priority, team_default_priority) is expected+++def test_resolve_autostart_fallback_user_prefers_earliest_active_enabler(organization, team):+ # Tier 1: run under the earliest active member who turned a signal source on. A departed /+ # deactivated enabler is skipped even though they enabled a source first (the task mints an+ # OAuth token as this user, so a disabled account can't run it).+ departed = User.objects.create(email="[email protected]", is_active=False)+ OrganizationMembership.objects.create(user=departed, organization=organization)+ active_early = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(user=active_early, organization=organization)+ active_late = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(user=active_late, organization=organization)++ # Creation order fixes created_at ordering: departed first, then the two active members.+ SignalSourceConfig.objects.create(+ team=team, source_product="error_tracking", source_type="issue_created", created_by=departed+ )+ SignalSourceConfig.objects.create(+ team=team, source_product="error_tracking", source_type="issue_reopened", created_by=active_early+ )+ SignalSourceConfig.objects.create(+ team=team, source_product="error_tracking", source_type="issue_spiking", created_by=active_late+ )++ resolved = _resolve_autostart_fallback_user(team_id=team.id)++ assert resolved is not None+ assert resolved.id == active_early.id+++def test_resolve_autostart_fallback_user_falls_back_to_org_owner(organization, team):+ # Tier 2: sources enabled by a system path leave created_by null, so there's no enabler to run+ # as. Attribute to the org owner, ahead of an admin, and never a plain member.+ SignalSourceConfig.objects.create(+ team=team, source_product="error_tracking", source_type="issue_created", created_by=None+ )+ member = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(+ user=member, organization=organization, level=OrganizationMembership.Level.MEMBER+ )+ admin = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(+ user=admin, organization=organization, level=OrganizationMembership.Level.ADMIN+ )+ owner = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(+ user=owner, organization=organization, level=OrganizationMembership.Level.OWNER+ )++ resolved = _resolve_autostart_fallback_user(team_id=team.id)++ assert resolved is not None+ assert resolved.id == owner.id+++def test_resolve_autostart_fallback_user_returns_none_without_enabler_or_admin(organization, team):+ # Tier 3 (fail-closed): a plain member with no enabled source and no elevated role is not an+ # eligible runner, so nothing auto-starts rather than picking an arbitrary member.+ member = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(+ user=member, organization=organization, level=OrganizationMembership.Level.MEMBER+ )++ assert _resolve_autostart_fallback_user(team_id=team.id) is None++@pytest.mark.django_db@pytest.mark.parametrize(("autostart_priority", "report_priority", "expect_user"),