: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): add undo and home tab toggle for feature tips (#130721)
Vojta Bartošc8e28500fb49
diff --git a/products/slack_app/backend/logic/feature_tips/interactivity.py b/products/slack_app/backend/logic/feature_tips/interactivity.pyindex c1d1f81ad7c9..1f34cd8c2b30 100644--- a/products/slack_app/backend/logic/feature_tips/interactivity.py+++ b/products/slack_app/backend/logic/feature_tips/interactivity.py@@ -20,14 +20,22 @@ from products.slack_app.backend.logic.feature_tips.offer import (FEATURE_TIP_CTA_ACTION_ID,FEATURE_TIP_DISMISS_ACTION_ID,FEATURE_TIP_OPT_OUT_ACTION_ID,+ FEATURE_TIP_UNDO_OPT_OUT_ACTION_ID,+)+from products.slack_app.backend.logic.feature_tips.state import (+ FeatureTipsState,+ TipRecord,+ set_tips_enabled,+ update_state,)-from products.slack_app.backend.logic.feature_tips.state import FeatureTipsState, TipRecord, update_statefrom products.slack_app.backend.services.inbox_interactivity import post_response_url+from products.slack_app.backend.services.slack_messages import section_blockfrom products.slack_app.backend.services.workspace_integrations import get_workspace_integrationlogger = structlog.get_logger(__name__)-TIPS_OFF_TEXT = "👋 Got it. I won't show you more tips."+TIPS_OFF_TEXT = "👋 Got it. I won't show you more tips. You can turn them on again in the Home tab."+TIPS_ON_AGAIN_TEXT = "💡 Tips are on again."@frozen@@ -63,6 +71,17 @@ def feature_tip_integration_hint(payload: dict[str, Any]) -> int | None:return _integration_id(found.value) if found is not None else None+def _tips_off_blocks(value: dict[str, Any]) -> list[dict[str, Any]]:+ undo = {+ "type": "button",+ "action_id": FEATURE_TIP_UNDO_OPT_OUT_ACTION_ID,+ "text": {"type": "plain_text", "text": "Undo"},+ # The same value as the tip, so the cross-region router finds the region that owns the click.+ "value": json.dumps(value),+ }+ return [section_block(TIPS_OFF_TEXT), {"type": "actions", "elements": [undo]}]++def handle_feature_tip_action(payload: dict[str, Any]) -> HttpResponse:response_url = payload.get("response_url", "")found = _tip_action(payload)@@ -80,6 +99,17 @@ def handle_feature_tip_action(payload: dict[str, Any]) -> HttpResponse:feature = SlackFeature(value["feature"])action_id = found.action_id+ if action_id == FEATURE_TIP_UNDO_OPT_OUT_ACTION_ID:+ set_tips_enabled(integration.integration_id, slack_user_id, True)+ post_response_url(response_url, {"replace_original": True, "text": TIPS_ON_AGAIN_TEXT})+ capture_slack_event(+ integration,+ "slack app feature tips turned on",+ slack_user_id=slack_user_id,+ feature=feature.value,+ source="undo",+ )+ return HttpResponse(status=200)tip = CATALOG[feature]runs_action = action_id == FEATURE_TIP_CTA_ACTION_ID and tip.has_actionnow = timezone.now()@@ -107,7 +137,10 @@ def handle_feature_tip_action(payload: dict[str, Any]) -> HttpResponse:post_response_url(response_url, {"delete_original": True})elif action_id == FEATURE_TIP_OPT_OUT_ACTION_ID:event = "slack app feature tips turned off"- post_response_url(response_url, {"replace_original": True, "text": TIPS_OFF_TEXT})+ post_response_url(+ response_url,+ {"replace_original": True, "text": TIPS_OFF_TEXT, "blocks": _tips_off_blocks(found.value)},+ )else:event = "slack app feature tip dismissed"post_response_url(response_url, {"delete_original": True})diff --git a/products/slack_app/backend/logic/feature_tips/offer.py b/products/slack_app/backend/logic/feature_tips/offer.pyindex 5be6769542b8..6c89c3557281 100644--- a/products/slack_app/backend/logic/feature_tips/offer.py+++ b/products/slack_app/backend/logic/feature_tips/offer.py@@ -30,7 +30,7 @@ from products.slack_app.backend.logic.feature_tips.features import SlackFeaturefrom products.slack_app.backend.logic.feature_tips.picker import choose_tipfrom products.slack_app.backend.logic.feature_tips.state import FeatureTipsState, mark_shown, parse_statefrom products.slack_app.backend.models import SlackSettings, SlackThreadTaskMapping-from products.slack_app.backend.services.slack_messages import post_slack_ephemeral, section_block+from products.slack_app.backend.services.slack_messages import context_block, post_slack_ephemeral, section_blockfrom products.slack_app.backend.services.slack_settings import parse_onboardingfrom products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration@@ -46,8 +46,14 @@ TIP_INTERVAL = timedelta(hours=24)FEATURE_TIP_CTA_ACTION_ID = "slack_app_feature_tip_cta"FEATURE_TIP_DISMISS_ACTION_ID = "slack_app_feature_tip_dismiss"FEATURE_TIP_OPT_OUT_ACTION_ID = "slack_app_feature_tip_opt_out"+FEATURE_TIP_UNDO_OPT_OUT_ACTION_ID = "slack_app_feature_tip_undo_opt_out"FEATURE_TIP_ACTION_IDS = frozenset(- {FEATURE_TIP_CTA_ACTION_ID, FEATURE_TIP_DISMISS_ACTION_ID, FEATURE_TIP_OPT_OUT_ACTION_ID}+ {+ FEATURE_TIP_CTA_ACTION_ID,+ FEATURE_TIP_DISMISS_ACTION_ID,+ FEATURE_TIP_OPT_OUT_ACTION_ID,+ FEATURE_TIP_UNDO_OPT_OUT_ACTION_ID,+ })@@ -120,8 +126,8 @@ def offer_feature_tip(request: TipRequest) -> SlackFeature | None:channel=request.channel,user=request.slack_user_id,thread_ts=request.thread_ts,- text=f"💡 Tip: {tip.title}. {body}",- blocks=tip_blocks(integration.id, tip, reservation.ctx, body),+ text=f"💡 PostHog tip: {tip.title}. {body}",+ blocks=tip_blocks(integration.id, tip, reservation.ctx, body, contextual=choice.source == "contextual"),)except Exception:logger.warning("slack_app_feature_tip_post_failed", feature=choice.feature, exc_info=True)@@ -252,7 +258,9 @@ def _button(action_id: str, label: str, value: str, **extra: str) -> dict[str, A}-def tip_blocks(integration_id: int, tip: TipFeature, ctx: TipContext, body: str) -> list[dict[str, Any]]:+def tip_blocks(+ integration_id: int, tip: TipFeature, ctx: TipContext, body: str, *, contextual: bool = False+) -> list[dict[str, Any]]:# The integration id lets the cross-region interactivity router find the region that owns the click.value = json.dumps({"integration_id": integration_id, "feature": tip.feature.value})buttons: list[dict[str, Any]] = []@@ -262,7 +270,13 @@ def tip_blocks(integration_id: int, tip: TipFeature, ctx: TipContext, body: str)buttons.append(_button(FEATURE_TIP_CTA_ACTION_ID, cta.label, value, **extra))buttons.append(_button(FEATURE_TIP_DISMISS_ACTION_ID, "Not now", value))buttons.append(_button(FEATURE_TIP_OPT_OUT_ACTION_ID, "Don't show tips", value))+ # Without a name, a reader can take the tip for a promotion from Slack itself.+ home_tab = f"<{ctx.app_home_url}|Home tab>" if ctx.app_home_url else "Home tab"+ note = f"Turn tips on or off in the {home_tab}."+ if contextual:+ note = f"I picked this tip from what you asked. {note}"return [- section_block(f"💡 *Tip: {tip.title}*\n{tip.emoji} {body}"),+ section_block(f"💡 *PostHog tip: {tip.title}*\n{tip.emoji} {body}"),{"type": "actions", "elements": buttons},+ context_block(note),]diff --git a/products/slack_app/backend/logic/feature_tips/picker.py b/products/slack_app/backend/logic/feature_tips/picker.pyindex 6ecc05bb6b9d..35ceca908bbb 100644--- a/products/slack_app/backend/logic/feature_tips/picker.py+++ b/products/slack_app/backend/logic/feature_tips/picker.py@@ -1,13 +1,15 @@"""Which feature a tip promotes, when more than one is a candidate.Jev, a System One decision model, reads the person's message and picks the feature that fits it,-or ``none``. Below the confidence threshold, on ``none``, or on any failure, the candidate with-the lowest rank wins. A tip does not have to match the message, so the model only orders the-candidates and never decides whether a tip goes out.+or ``none``. Below the confidence threshold or on ``none``, the message fits no candidate, so a+random candidate wins, weighted toward the lower ranks, and the same tip does not lead every time.+On any failure, the candidate with the lowest rank wins. A tip does not have to match the message,+so the model only orders the candidates and never decides whether a tip goes out."""from __future__ import annotations+import randomfrom collections.abc import Sequencefrom typing import Literal@@ -57,7 +59,7 @@ class FeatureTipVerdict:@frozenclass TipChoice:feature: SlackFeature- source: Literal["contextual", "ranked"]+ source: Literal["contextual", "ranked", "random"]confidence: float | None = None@@ -128,8 +130,11 @@ def choose_tip(by_value = {tip.feature.value: tip for tip in candidates}if verdict is not None and verdict.choice in by_value and verdict.confidence >= FEATURE_TIP_MIN_CONFIDENCE:return TipChoice(feature=by_value[verdict.choice].feature, source="contextual", confidence=verdict.confidence)- return TipChoice(- feature=ranked.feature,- source="ranked",- confidence=verdict.confidence if verdict is not None else None,- )+ if verdict is None:+ return TipChoice(feature=ranked.feature, source="ranked")+ return TipChoice(feature=_weighted_random(candidates).feature, source="random", confidence=verdict.confidence)+++def _weighted_random(candidates: Sequence[TipFeature]) -> TipFeature:+ ordered = sorted(candidates, key=lambda tip: tip.rank)+ return random.choices(ordered, weights=[1 / (position + 1) for position in range(len(ordered))])[0]diff --git a/products/slack_app/backend/logic/feature_tips/state.py b/products/slack_app/backend/logic/feature_tips/state.pyindex 0edb5ed29c3b..e19e31fe2b30 100644--- a/products/slack_app/backend/logic/feature_tips/state.py+++ b/products/slack_app/backend/logic/feature_tips/state.py@@ -110,6 +110,13 @@ def record_feature_used(slack_workspace_id: str, slack_user_id: str | None, featlogger.warning("slack_app_feature_tips_record_used_failed", feature=feature, exc_info=True)+def set_tips_enabled(slack_workspace_id: str, slack_user_id: str, enabled: bool) -> None:+ def change(state: FeatureTipsState) -> None:+ state.opted_out_at = None if enabled else (state.opted_out_at or timezone.now())++ update_state(slack_workspace_id, slack_user_id, change)++def mark_shown(slack_workspace_id: str, slack_user_id: str, feature: str, source: TipSource) -> None:def change(state: FeatureTipsState) -> None:record_shown(state, feature, source, timezone.now())diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex 40792e5a92dc..fce221bb9136 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -35,7 +35,7 @@ from posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.feature_flags import is_slack_app_byos_enabled, is_slack_app_oauth_enabledfrom products.slack_app.backend.logic.feature_tips.features import SlackFeature-from products.slack_app.backend.logic.feature_tips.state import record_feature_used+from products.slack_app.backend.logic.feature_tips.state import get_state, record_feature_used, set_tips_enabledfrom products.slack_app.backend.logic.interview_recruitment import INVITE_MESSAGE, book_button, invite_sectionfrom products.slack_app.backend.models import ChannelWelcomeMode, SlackSettings, ThreadJoinMode, UntaggedFollowupModefrom products.slack_app.backend.services.integration_resolver import load_integrations, resolve_from_candidates@@ -116,6 +116,7 @@ ACTION_SET_UNTAGGED_FOLLOWUP_MODE = "slack_app_home:set_untagged_followup_mode"ACTION_SET_UNTAGGED_QUESTION_MODE = "slack_app_home:set_untagged_question_mode"ACTION_SET_CHANNEL_WELCOME_MODE = "slack_app_home:set_channel_welcome_mode"ACTION_SET_AUTO_MODEL_CHOICE = "slack_app_home:set_auto_model_choice"+ACTION_SET_FEATURE_TIPS = "slack_app_home:set_feature_tips"# URL buttons: Slack opens the link itself and posts a block_actions payload we# only ack — the ids exist so the clicks still reach the usage-analytics capture.ACTION_GITHUB_SETTINGS = "slack_app_home:github_settings"@@ -145,6 +146,7 @@ HOME_ACTION_IDS: frozenset[str] = frozenset(ACTION_SET_UNTAGGED_QUESTION_MODE,ACTION_SET_CHANNEL_WELCOME_MODE,ACTION_SET_AUTO_MODEL_CHOICE,+ ACTION_SET_FEATURE_TIPS,ACTION_GITHUB_SETTINGS,ACTION_CONNECT_ACCOUNT,}@@ -469,6 +471,7 @@ def render_home_view(auto_model_choice: bool | None = None,own_plan: OwnPlanState | None = None,thread_join_mode: ThreadJoinMode | None = None,+ feature_tips_enabled: bool | None = None,has_project_access: bool = True,account_settings_url: str | None = None,interview_invite: dict | None = None,@@ -536,6 +539,11 @@ def render_home_view(blocks.append({"type": "divider"})blocks.extend(_channel_welcome_section_blocks(channel_welcome_mode))+ # Section 5a — feature tips: the only way back for a reader who turned them off.+ if feature_tips_enabled is not None:+ blocks.append({"type": "divider"})+ blocks.extend(_feature_tips_section_blocks(feature_tips_enabled))+# Section 6 — linked accounts: PostHog and GitHub side by side, shown# before Tasks so the connect prompts are visible while the Tasks list# is still empty. The PostHog half is flag-gated.@@ -957,6 +965,7 @@ def _personal_section_blocks(run_defaults: RunDefaultsState) -> list[dict]:AUTO_MODEL_CHOICE_VALUE = "on"+FEATURE_TIPS_VALUE = "on"def _auto_model_choice_blocks(enabled: bool) -> list[dict]:@@ -992,6 +1001,21 @@ def _auto_model_choice_blocks(enabled: bool) -> list[dict]:]+def _feature_tips_section_blocks(enabled: bool) -> list[dict]:+ option = {+ "text": {"type": "mrkdwn", "text": "*Show tips*"},+ "description": {"type": "mrkdwn", "text": "At most one tip a day, under an answer. Only you see it."},+ "value": FEATURE_TIPS_VALUE,+ }+ checkbox: dict[str, Any] = {"type": "checkboxes", "action_id": ACTION_SET_FEATURE_TIPS, "options": [option]}+ if enabled:+ checkbox["initial_options"] = [option]+ return [+ _section_title("💡 Tips", "Short tips about PostHog features you have not used yet."),+ {"type": "actions", "elements": [checkbox]},+ ]++def _own_plan_blocks(state: OwnPlanState) -> list[dict]:"""The prompt to connect a ChatGPT plan, for a viewer who has not connected one."""text = f"<{state.settings_url}|Connect your ChatGPT plan> in PostHog to use it for Codex tasks you start here."@@ -1851,6 +1875,18 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpResporepublish()return HttpResponse(status=200)+ if action_id == ACTION_SET_FEATURE_TIPS:+ enabled = any(option.get("value") == FEATURE_TIPS_VALUE for option in action.get("selected_options") or [])+ set_tips_enabled(integration.integration_id, slack_user_id, enabled)+ capture_slack_event(+ integration,+ "slack app feature tips turned on" if enabled else "slack app feature tips turned off",+ slack_user_id=slack_user_id,+ source="home",+ )+ republish()+ return HttpResponse(status=200)+if action_id == ACTION_SET_CHANNEL_WELCOME_MODE:slack = SlackIntegration(integration)if not _is_admin(slack, integration, slack_user_id):@@ -2316,6 +2352,7 @@ def _build_home_view(),own_plan=own_plan,thread_join_mode=(resolve_thread_join_mode(integration, slack_user_id) if home_user is not None else None),+ feature_tips_enabled=get_state(integration.integration_id, slack_user_id).opted_out_at is None,has_project_access=bool(accessible),# The same settings page the GitHub card deep-links to.account_settings_url=github_state.settings_url,diff --git a/products/slack_app/backend/tests/logic/test_feature_tips.py b/products/slack_app/backend/tests/logic/test_feature_tips.pyindex 9a96b8e839eb..827c933c2eee 100644--- a/products/slack_app/backend/tests/logic/test_feature_tips.py+++ b/products/slack_app/backend/tests/logic/test_feature_tips.py@@ -204,16 +204,16 @@ class TestChooseTip(SimpleTestCase):),("low confidence",- ChoiceAnswer(choice="code_change_pr", confidence=0.3, probabilities={}),- "subscription",- "ranked",+ ChoiceAnswer(choice="subscription", confidence=0.3, probabilities={}),+ "code_change_pr",+ "random",),- ("no match", ChoiceAnswer(choice="none", confidence=0.95, probabilities={}), "subscription", "ranked"),+ ("no match", ChoiceAnswer(choice="none", confidence=0.95, probabilities={}), "code_change_pr", "random"),("not a candidate",ChoiceAnswer(choice="mcp_tool", confidence=0.95, probabilities={}),- "subscription",- "ranked",+ "code_change_pr",+ "random",),("refusal", RefusalAnswer(), "subscription", "ranked"),]@@ -223,7 +223,11 @@ class TestChooseTip(SimpleTestCase):client.decide.return_value = SystemOneResult(model="jev", answers={picker.FEATURE_TIP_QUESTION_ID: answer}, input_tokens=None)- with patch.object(picker, "build_system_one_client", return_value=client):+ with (+ patch.object(picker, "build_system_one_client", return_value=client),+ # A random pick takes the last candidate, so it can not pass by matching the ranked one.+ patch.object(picker.random, "choices", side_effect=lambda population, weights: [population[-1]]),+ ):choice = picker.choose_tip(self.candidates, "fix the checkout error", team_id=1, distinct_id=None)assert choice is not None@@ -287,6 +291,15 @@ class TestFeatureTipClicks:assert get_state(WORKSPACE, SLACK_USER).opted_out_at is not None+ def test_undo_turns_tips_on_again(self):+ self._click(offer.FEATURE_TIP_OPT_OUT_ACTION_ID, SlackFeature.SUBSCRIPTION.value)+ confirmation = self.respond.call_args.args[1]+ assert offer.FEATURE_TIP_UNDO_OPT_OUT_ACTION_ID in json.dumps(confirmation["blocks"])++ self._click(offer.FEATURE_TIP_UNDO_OPT_OUT_ACTION_ID, SlackFeature.SUBSCRIPTION.value)++ assert get_state(WORKSPACE, SLACK_USER).opted_out_at is None+def test_a_click_from_another_workspace_changes_nothing(self):self._click(offer.FEATURE_TIP_OPT_OUT_ACTION_ID, SlackFeature.SUBSCRIPTION.value, slack_team_id="T_OTHER")diff --git a/products/slack_app/backend/tests/services/test_slack_app_home.py b/products/slack_app/backend/tests/services/test_slack_app_home.pyindex b0c65899d371..e7d9f227f822 100644--- a/products/slack_app/backend/tests/services/test_slack_app_home.py+++ b/products/slack_app/backend/tests/services/test_slack_app_home.py@@ -27,6 +27,7 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.models.user_integration import UserIntegration+from products.slack_app.backend.logic.feature_tips.state import get_state, set_tips_enabledfrom products.slack_app.backend.models import (ChannelWelcomeMode,SlackSettings,@@ -42,6 +43,7 @@ from products.slack_app.backend.services.slack_app_home import (ACTION_RESET_PROJECT_PERSONAL,ACTION_SET_AUTO_MODEL_CHOICE,ACTION_SET_CHANNEL_WELCOME_MODE,+ ACTION_SET_FEATURE_TIPS,ACTION_SET_PROJECT_WORKSPACE,ACTION_SET_THREAD_JOIN_MODE,ACTION_SET_UNTAGGED_FOLLOWUP_MODE,@@ -52,6 +54,7 @@ from products.slack_app.backend.services.slack_app_home import (AUTO_MODEL_CHOICE_VALUE,BLOCK_TASKS_CONTROLS,EDIT_MODAL_PERSONAL_CALLBACK_ID,+ FEATURE_TIPS_VALUE,HOME_ACTION_IDS,MODAL_ACTION_MODEL,MODAL_ACTION_REASONING_EFFORT,@@ -481,6 +484,7 @@ class TestRenderHomeView:auto_model_choice=auto_model_choice,own_plan=OwnPlanState(connected=True, settings_url="https://app.example.com/settings"),thread_join_mode=ThreadJoinMode.ASK_PER_THREAD,+ feature_tips_enabled=auto_model_choice,)@pytest.mark.parametrize(@@ -621,6 +625,25 @@ class TestAutoModelChoiceToggle:assert mock_slack_client.views_publish.called+class TestFeatureTipsToggle:+ @pytest.mark.parametrize("checked", [True, False])+ def test_toggle_is_stored_for_the_clicking_user(self, slack_integration, mock_slack_client, checked):+ set_tips_enabled(SLACK_WORKSPACE_ID, "U001", not checked)+ selected = [{"value": FEATURE_TIPS_VALUE}] if checked else []+ action = {"action_id": ACTION_SET_FEATURE_TIPS, "selected_options": selected}+ payload = {+ "type": "block_actions",+ "team": {"id": SLACK_WORKSPACE_ID},+ "user": {"id": "U001"},+ "actions": [action],+ }+ with patch("products.slack_app.backend.services.slack_app_home.is_slack_workspace_admin", return_value=False):+ handle_ai_preferences_block_action(payload, action)++ assert (get_state(SLACK_WORKSPACE_ID, "U001").opted_out_at is None) is checked+ assert mock_slack_client.views_publish.called++class TestChannelWelcomePicker:def test_card_is_hidden_from_non_admins(self):view = render_home_view(is_admin=False, channel_welcome_mode=ChannelWelcomeMode.CHANNEL)