: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): queue slack messages per conversation behind feature flag (#68894)
Vojta Bartoša46bf7ba4c87
diff --git a/posthog/temporal/ai/__init__.py b/posthog/temporal/ai/__init__.pyindex 720d3a9122dc..45f107b263a1 100644--- a/posthog/temporal/ai/__init__.py+++ b/posthog/temporal/ai/__init__.py@@ -15,6 +15,7 @@ from posthog.temporal.ai.slack_app.posthog_code_slack_interactivity import (from posthog.temporal.ai.slack_app.posthog_code_slack_mention import PostHogCodeSlackMentionWorkflowfrom posthog.temporal.ai.slack_app.posthog_code_slack_mention_command import PostHogCodeSlackMentionCommandWorkflowfrom posthog.temporal.ai.slack_app.posthog_slack_inbox_onboarding import PostHogSlackInboxOnboardingWorkflow+from posthog.temporal.ai.slack_app.slack_app_mention import SlackAppMentionWorkflowfrom .llm_traces_summaries.summarize_traces import (SummarizeLLMTracesInputs,@@ -35,6 +36,7 @@ from .sync_vectors import (# workflows.POSTHOG_CODE_SLACK_WORKFLOWS = [PostHogCodeSlackMentionWorkflow,+ SlackAppMentionWorkflow,PostHogCodeSlackMentionCommandWorkflow,PostHogCodeSlackTerminateTaskWorkflow,PostHogSlackInboxOnboardingWorkflow,diff --git a/posthog/temporal/ai/slack_app/__init__.py b/posthog/temporal/ai/slack_app/__init__.pyindex 456852b300f6..220a81131850 100644--- a/posthog/temporal/ai/slack_app/__init__.py+++ b/posthog/temporal/ai/slack_app/__init__.py@@ -23,6 +23,8 @@ from posthog.temporal.ai.slack_app.activities import (forward_posthog_code_followup_activity,handle_posthog_code_rules_command_activity,handle_posthog_code_slack_mention_command_activity,+ mark_slack_app_message_processing_activity,+ mark_slack_app_message_queued_activity,post_posthog_code_authorship_timeout_activity,post_posthog_code_internal_error_activity,post_posthog_code_no_repos_activity,@@ -34,12 +36,16 @@ from posthog.temporal.ai.slack_app.activities import (run_posthog_slack_inbox_onboarding_activity,)from posthog.temporal.ai.slack_app.types import (+ SLACK_APP_PROCESSING_REACTION,+ SLACK_APP_QUEUED_REACTION,PostHogCodeRepoCascadeOutcome,PostHogCodeRulesCommandResult,PostHogCodeSlackMentionCommandResult,PostHogCodeSlackMentionCommandWorkflowInputs,PostHogCodeSlackMentionWorkflowInputs,PostHogSlackInboxOnboardingInputs,+ SlackAppMentionWorkflowInputs,+ SlackAppMessageReactionInput,SlackRepoSelectionOutcome,)@@ -64,13 +70,18 @@ SLACK_APP_ACTIVITIES = [handle_posthog_code_rules_command_activity,create_posthog_code_routing_rule_activity,handle_posthog_code_slack_mention_command_activity,+ mark_slack_app_message_processing_activity,+ mark_slack_app_message_queued_activity,run_posthog_slack_inbox_onboarding_activity,]__all__ = ["CLASSIFIER_THREAD_HISTORY_MESSAGES",+ "SlackAppMessageReactionInput","POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE","POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE",+ "SLACK_APP_PROCESSING_REACTION",+ "SLACK_APP_QUEUED_REACTION","PostHogCodeRepoCascadeOutcome","PostHogCodeRulesCommandResult","PostHogCodeSlackMentionCommandResult",@@ -78,6 +89,7 @@ __all__ = ["PostHogCodeSlackMentionWorkflowInputs","PostHogSlackInboxOnboardingInputs","SLACK_APP_ACTIVITIES",+ "SlackAppMentionWorkflowInputs","SlackRepoSelectionOutcome","block_posthog_code_task_if_no_personal_github_activity","cascade_posthog_code_repository_activity",@@ -93,6 +105,8 @@ __all__ = ["forward_posthog_code_followup_activity","handle_posthog_code_rules_command_activity","handle_posthog_code_slack_mention_command_activity",+ "mark_slack_app_message_processing_activity",+ "mark_slack_app_message_queued_activity","post_posthog_code_authorship_timeout_activity","post_posthog_code_internal_error_activity","post_posthog_code_no_repos_activity",diff --git a/posthog/temporal/ai/slack_app/activities/__init__.py b/posthog/temporal/ai/slack_app/activities/__init__.pyindex 02dc8ba6b76c..60e9bb59c368 100644--- a/posthog/temporal/ai/slack_app/activities/__init__.py+++ b/posthog/temporal/ai/slack_app/activities/__init__.py@@ -10,6 +10,8 @@ from posthog.temporal.ai.slack_app.activities.messaging import (POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE,POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,block_posthog_code_task_if_no_personal_github_activity,+ mark_slack_app_message_processing_activity,+ mark_slack_app_message_queued_activity,post_posthog_code_authorship_timeout_activity,post_posthog_code_internal_error_activity,post_posthog_code_no_repos_activity,@@ -60,6 +62,8 @@ __all__ = ["forward_posthog_code_followup_activity","handle_posthog_code_rules_command_activity","handle_posthog_code_slack_mention_command_activity",+ "mark_slack_app_message_processing_activity",+ "mark_slack_app_message_queued_activity","post_posthog_code_authorship_timeout_activity","post_posthog_code_internal_error_activity","post_posthog_code_no_repos_activity",diff --git a/posthog/temporal/ai/slack_app/activities/messaging.py b/posthog/temporal/ai/slack_app/activities/messaging.pyindex ef571b9d3b53..69e824b703fd 100644--- a/posthog/temporal/ai/slack_app/activities/messaging.py+++ b/posthog/temporal/ai/slack_app/activities/messaging.py@@ -1,15 +1,20 @@import json-from typing import TYPE_CHECKING, Any+from typing import Anyimport structlogfrom temporalio import activity-from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs, coerce_mention_workflow_inputs+from posthog.models.integration import Integration, SlackIntegration+from posthog.temporal.ai.slack_app.helpers import safe_react, swap_reaction+from posthog.temporal.ai.slack_app.types import (+ SLACK_APP_PROCESSING_REACTION,+ SLACK_APP_QUEUED_REACTION,+ PostHogCodeSlackMentionWorkflowInputs,+ SlackAppMessageReactionInput,+ coerce_mention_workflow_inputs,+)from posthog.temporal.common.utils import close_db_connections-if TYPE_CHECKING:- from posthog.models.integration import SlackIntegration-logger = structlog.get_logger(__name__)POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE = (@@ -26,8 +31,6 @@ POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE = "Select the repository for this rdef post_posthog_code_no_repos_activity(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:- from posthog.models.integration import Integration, SlackIntegration-inputs = coerce_mention_workflow_inputs(inputs)integration = Integration.objects.select_related("team", "team__organization").get(id=inputs.integration_id,@@ -68,8 +71,6 @@ def post_posthog_code_repo_picker_activity(downstream external-select handler. New workflows go through the patched callsite at the workflow body and pass ``user_id`` as the final positional arg."""- from posthog.models.integration import Integration, SlackIntegration-inputs = coerce_mention_workflow_inputs(inputs)if user_id is None:logger.warning(@@ -167,7 +168,6 @@ def block_posthog_code_task_if_no_personal_github_activity("""from django.conf import settings- from posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.user_integration import UserIntegrationfrom products.slack_app.backend.feature_flags import is_slack_app_bot_prs_enabled@@ -219,7 +219,6 @@ def resolve_posthog_code_authorship_activity("""Gate PR authorship for a repo-bound task: returns "proceed", "awaiting_confirmation", or "blocked"."""from django.conf import settings- from posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.user_integration import UserIntegrationfrom products.slack_app.backend.feature_flags import is_slack_app_bot_prs_enabled@@ -329,8 +328,6 @@ def resolve_posthog_code_authorship_activity(def post_posthog_code_authorship_timeout_activity(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:- from posthog.models.integration import Integration, SlackIntegration-from products.slack_app.backend.models import SlackThreadTaskMappinginputs = coerce_mention_workflow_inputs(inputs)@@ -360,8 +357,6 @@ def post_posthog_code_authorship_timeout_activity(def post_posthog_code_picker_timeout_activity(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:- from posthog.models.integration import Integration, SlackIntegration-from products.slack_app.backend.api import _clear_pending_repo_pickerfrom products.slack_app.backend.models import SlackThreadTaskMapping@@ -403,8 +398,6 @@ def post_posthog_code_picker_timeout_activity(def post_posthog_code_internal_error_activity(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:- from posthog.models.integration import Integration, SlackIntegration-from products.slack_app.backend.api import _clear_pending_repo_pickerinputs = coerce_mention_workflow_inputs(inputs)@@ -428,3 +421,56 @@ def post_posthog_code_internal_error_activity(thread_ts=thread_ts,text="Sorry, I hit an internal error while processing that request. Please try again.",)+++@close_db_connections+def mark_slack_app_message_processing_activity(input: SlackAppMessageReactionInput) -> None:+ """Swap the queued :hourglass: reaction for :eyes: when the conversation+ queue starts processing a message.++ Purely cosmetic UX feedback: never raises, so a Slack hiccup can't stall+ the conversation queue behind retries of a reaction.+ """+ try:+ integration = Integration.objects.get(+ id=input.integration_id,+ kind="slack",+ integration_id=input.slack_team_id,+ )+ slack = SlackIntegration(integration)+ swap_reaction(+ slack.client, input.channel, input.message_ts, SLACK_APP_QUEUED_REACTION, SLACK_APP_PROCESSING_REACTION+ )+ except Exception as e:+ logger.warning(+ "slack_app_processing_reaction_failed",+ channel=input.channel,+ message_ts=input.message_ts,+ error=str(e),+ )+++@close_db_connections+def mark_slack_app_message_queued_activity(input: SlackAppMessageReactionInput) -> None:+ """React :hourglass: on a message that entered the conversation queue+ behind another message. Messages processed immediately never get it.++ Best-effort like the processing swap above: never raises.+ """+ try:+ integration = Integration.objects.get(+ id=input.integration_id,+ kind="slack",+ integration_id=input.slack_team_id,+ )+ slack = SlackIntegration(integration)+ safe_react(slack.client, input.channel, input.message_ts, SLACK_APP_QUEUED_REACTION)+ except Exception as e:+ logger.warning(+ "slack_app_queued_reaction_failed",+ channel=input.channel,+ message_ts=input.message_ts,+ error=str(e),+ )diff --git a/posthog/temporal/ai/slack_app/helpers.py b/posthog/temporal/ai/slack_app/helpers.pyindex 3f5606961a07..cc347ce33f3a 100644--- a/posthog/temporal/ai/slack_app/helpers.py+++ b/posthog/temporal/ai/slack_app/helpers.py@@ -62,3 +62,12 @@ def safe_react(client: Any, channel: str, timestamp: str, name: str) -> None:passelse:raise+++def swap_reaction(client: Any, channel: str, timestamp: str, remove: str, add: str) -> None:+ """Replace one reaction with another; a missing old reaction is a no-op."""+ try:+ client.reactions_remove(channel=channel, timestamp=timestamp, name=remove)+ except Exception:+ pass+ safe_react(client, channel, timestamp, add)diff --git a/posthog/temporal/ai/slack_app/slack_app_mention.py b/posthog/temporal/ai/slack_app/slack_app_mention.pynew file mode 100644index 000000000000..7aaca3ea49c0--- /dev/null+++ b/posthog/temporal/ai/slack_app/slack_app_mention.py@@ -0,0 +1,202 @@+# Workflows in this module run on the max-ai temporal task queue.+import json+from datetime import timedelta+from typing import Any++from temporalio import exceptions, workflow+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy++from posthog.temporal.ai.slack_app import (+ derive_mention_workflow_id,+ mark_slack_app_message_processing_activity,+ mark_slack_app_message_queued_activity,+)+from posthog.temporal.ai.slack_app.posthog_code_slack_mention import PostHogCodeSlackMentionWorkflow+from posthog.temporal.ai.slack_app.types import (+ PostHogCodeSlackMentionWorkflowInputs,+ SlackAppMentionWorkflowInputs,+ SlackAppMessageReactionInput,+)+from posthog.temporal.common.base import PostHogWorkflow++SLACK_APP_MENTION_IDLE_TIMEOUT_SECONDS = 30+# Dedup keys carried across continue_as_new. Bounded so the carry-over payload+# stays small; old keys only matter for Slack retries, which arrive within+# minutes of the original event.+SLACK_APP_MENTION_MAX_PROCESSED_KEYS = 200+++def derive_slack_app_mention_workflow_id(inputs: PostHogCodeSlackMentionWorkflowInputs) -> str | None:+ """Conversation-scoped workflow ID: one per thread (or DM thread).++ Anchored on the thread root ts — the same anchor the rest of the pipeline+ uses — so every message in a conversation resolves to the same workflow.+ Returns None when the event lacks a channel or ts; callers fall back to+ the per-message workflow.+ """+ event = inputs.event+ channel = event.get("channel")+ anchor = event.get("thread_ts") or event.get("ts")+ if not channel or not anchor:+ return None+ return f"slack-app-mention-{inputs.slack_team_id}:{channel}:{anchor}"++[email protected](name="slack-app-mention")+class SlackAppMentionWorkflow(PostHogWorkflow):+ """Per-conversation queue over the per-message mention workflow.++ Standalone ``PostHogCodeSlackMentionWorkflow`` executions race when+ several messages land in one thread. This workflow serializes them: the+ webhook signal-with-starts one instance per conversation, messages queue+ up as ``new_message`` signals, and the loop runs each one as a child+ ``PostHogCodeSlackMentionWorkflow`` — under the same per-message workflow+ ID the flag-off dispatch would use — awaiting its completion before+ starting the next. Interactive signals (repo picker, authorship+ confirmation) never touch this workflow: the child bakes its own ID into+ the prompts it posts, so the interactivity webhook signals the child+ directly, exactly as in the standalone shape. After the idle timeout with+ an empty queue the workflow completes; the next message simply starts a+ fresh instance, which finds the conversation's task via+ ``SlackThreadTaskMapping`` and continues in followup mode.++ The FIFO and dedup guarantees are scoped to one instance: the queue and+ the seen-key set die when the workflow completes, and a fresh instance+ starts empty. Ordering still holds across the boundary — a fresh instance+ only ever starts after the previous one finished with an empty queue —+ but a Slack event retry arriving after the idle window is no longer+ deduped and gets processed again.+ """++ def __init__(self) -> None:+ self._queue: list[PostHogCodeSlackMentionWorkflowInputs] = []+ self._processing = False+ # Dedup for Slack event redeliveries: signals have no server-side+ # dedup the way per-message workflow IDs did. A dict, not a set, so+ # iteration order stays deterministic for the continue_as_new carry-over.+ self._seen_keys: dict[str, None] = {}++ @workflow.signal+ async def new_message(self, message: PostHogCodeSlackMentionWorkflowInputs) -> None:+ # The per-message workflow ID doubles as the message's identity, so the+ # dedup rule stays single-sourced with derive_mention_workflow_id.+ key = derive_mention_workflow_id(message)+ if key in self._seen_keys:+ return+ self._seen_keys[key] = None+ # Only a message that waits behind another gets the queued reaction.+ will_wait = self._processing or bool(self._queue)+ self._queue.append(message)+ if will_wait:+ await self._react(message, mark_slack_app_message_queued_activity)++ @staticmethod+ def parse_inputs(inputs: list[str]) -> SlackAppMentionWorkflowInputs:+ loaded = json.loads(inputs[0])+ loaded["pending_messages"] = [+ PostHogCodeSlackMentionWorkflowInputs(**message) for message in loaded.get("pending_messages", [])+ ]+ return SlackAppMentionWorkflowInputs(**loaded)++ async def _react(self, message: PostHogCodeSlackMentionWorkflowInputs, reaction_activity: Any) -> None:+ """Run one of the reaction activities for a mention or DM. Untagged+ thread followups get no reactions — they were never addressed to the+ bot, and most are dropped by the chitchat classifier.+ """+ channel = message.event.get("channel")+ message_ts = message.event.get("ts")+ if message.untagged_followup or not channel or not message_ts:+ return+ try:+ await workflow.execute_activity(+ reaction_activity,+ SlackAppMessageReactionInput(+ integration_id=message.integration_id,+ slack_team_id=message.slack_team_id,+ channel=channel,+ message_ts=message_ts,+ ),+ start_to_close_timeout=timedelta(seconds=10),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except exceptions.ActivityError:+ # The activity swallows Slack errors itself; this only fires on a+ # timeout. Cosmetic either way — never stall the queue for it.+ workflow.logger.warning("slack_app_reaction_activity_failed")++ async def _process(self, message: PostHogCodeSlackMentionWorkflowInputs) -> None:+ """Run one message to completion as a child workflow.++ The child ID is the per-message workflow ID — the same execution the+ flag-off dispatch would create, so debug tooling that resolves+ ``slack_mention_workflow_id`` finds a real run either way.+ ALLOW_DUPLICATE mirrors the standalone dispatch's reuse policy for+ retries that outlive this instance's dedup keys.+ """+ try:+ # The default parent close policy (terminate) is deliberate: an+ # operator killing this queue means "stop this conversation", so+ # the in-flight child goes down with it. Normal exits (idle+ # return, continue_as_new) never have a child in flight — the+ # serial await completes it first.+ await workflow.execute_child_workflow(+ PostHogCodeSlackMentionWorkflow.run,+ message,+ id=derive_mention_workflow_id(message),+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ )+ except exceptions.WorkflowAlreadyStartedError:+ # A standalone execution for this exact message is already+ # running (dispatched pre-flag, retried post-flag). It owns the+ # work; skip.+ workflow.logger.info("slack_app_mention_child_already_running")+ except exceptions.ChildWorkflowError:+ # The child posts its own internal-error replies and is not+ # expected to fail; this backstop keeps one poisoned message from+ # wedging the conversation's queue.+ workflow.logger.exception("slack_app_mention_child_failed")++ @workflow.run+ async def run(self, inputs: SlackAppMentionWorkflowInputs) -> None:+ for key in inputs.processed_event_keys:+ self._seen_keys[key] = None+ for message in inputs.pending_messages:+ self._seen_keys.setdefault(derive_mention_workflow_id(message), None)+ self._queue.append(message)++ while True:+ try:+ await workflow.wait_condition(+ lambda: bool(self._queue),+ timeout=timedelta(seconds=SLACK_APP_MENTION_IDLE_TIMEOUT_SECONDS),+ )+ except TimeoutError:+ # Idle exit. Drain in-flight signal handlers and re-check: a+ # message landing between the timeout and the return must not+ # be dropped. A signal racing the completion command makes the+ # server fail the workflow task and replay, landing here again+ # with the queue non-empty. Once the workflow has fully closed,+ # the webhook's signal-with-start spawns a fresh instance.+ await workflow.wait_condition(workflow.all_handlers_finished)+ if self._queue:+ continue+ return++ message = self._queue.pop(0)+ self._processing = True+ await self._react(message, mark_slack_app_message_processing_activity)+ await self._process(message)+ self._processing = False++ # A long-lived conversation would eventually hit Temporal's history+ # cap, so restart the run with fresh history, carrying over the+ # waiting messages and recent dedup keys. Handlers are drained+ # first so a message mid-signal isn't lost from the queue snapshot.+ if workflow.info().is_continue_as_new_suggested():+ await workflow.wait_condition(workflow.all_handlers_finished)+ workflow.continue_as_new(+ SlackAppMentionWorkflowInputs(+ pending_messages=list(self._queue),+ processed_event_keys=list(self._seen_keys)[-SLACK_APP_MENTION_MAX_PROCESSED_KEYS:],+ )+ )diff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.pyindex f0fc204f44f8..27b0885ab112 100644--- a/posthog/temporal/ai/slack_app/types.py+++ b/posthog/temporal/ai/slack_app/types.py@@ -5,9 +5,11 @@ package can take the inputs dataclass as their typed signature withoutcreating an import cycle with the workflow modules."""-from dataclasses import dataclass, fields+from dataclasses import dataclass, field, fieldsfrom typing import Any, Literal+from pydantic import BaseModel+@dataclassclass PostHogSlackInboxOnboardingInputs:@@ -68,6 +70,43 @@ def coerce_mention_workflow_inputs(inputs: object) -> PostHogCodeSlackMentionWor)+@dataclass+class SlackAppMentionWorkflowInputs:+ """Conversation-level inputs for the per-thread queue workflow.++ One workflow instance covers one Slack conversation (channel thread or DM+ thread), identified entirely by its workflow ID; individual messages+ arrive as ``new_message`` signals carrying+ ``PostHogCodeSlackMentionWorkflowInputs``. These fields exist only to+ carry state across ``continue_as_new`` — fresh starts leave them empty.+ """++ pending_messages: list[PostHogCodeSlackMentionWorkflowInputs] = field(default_factory=list)+ processed_event_keys: list[str] = field(default_factory=list)+++# The queue reaction contract: the queue workflow adds the queued reaction to+# a message that has to wait behind another, then swaps it for the processing+# one when the message's turn starts. A message processed immediately gets+# only the processing reaction. Both activities must agree, so the names live+# here rather than as literals at each call site.+SLACK_APP_QUEUED_REACTION = "hourglass"+SLACK_APP_PROCESSING_REACTION = "eyes"+++class SlackAppMessageReactionInput(BaseModel):+ """Single-argument input for the queue-reaction activities.++ New Slack-app activities take one pydantic model instead of positional+ arguments so the payload can grow fields without signature churn.+ """++ integration_id: int+ slack_team_id: str+ channel: str+ message_ts: str++@dataclassclass PostHogCodeSlackMentionCommandWorkflowInputs:event: dict[str, Any]diff --git a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.pynew file mode 100644index 000000000000..185c0d6283aa--- /dev/null+++ b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py@@ -0,0 +1,421 @@+import os+import uuid+import asyncio+from typing import Any, Literal++import pytest++from temporalio import activity+from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.temporal.ai.slack_app import derive_mention_workflow_id+from posthog.temporal.ai.slack_app.posthog_code_slack_mention import PostHogCodeSlackMentionWorkflow+from posthog.temporal.ai.slack_app.slack_app_mention import SlackAppMentionWorkflow+from posthog.temporal.ai.slack_app.types import (+ PostHogCodeRepoCascadeOutcome,+ PostHogCodeSlackMentionWorkflowInputs,+ SlackAppMentionWorkflowInputs,+ SlackAppMessageReactionInput,+ SlackRepoSelectionOutcome,+)+++def _message(+ ts: str,+ *,+ event_id: str | None = None,+ untagged: bool = False,+) -> PostHogCodeSlackMentionWorkflowInputs:+ return PostHogCodeSlackMentionWorkflowInputs(+ event={"channel": "C1", "ts": ts, "thread_ts": "100.0", "user": "U1", "text": "fix the bug"},+ integration_id=1,+ slack_team_id="T1",+ slack_event_id=event_id,+ user_id=42,+ untagged_followup=untagged,+ )+++class _Recorder:+ def __init__(self) -> None:+ # (ts, repository) per create-task call, in execution order.+ self.created: list[tuple[str, str | None]] = []+ # ts per hourglass reaction (message queued behind another), in execution order.+ self.queued_marked: list[str] = []+ # ts per hourglass->eyes reaction swap, in execution order.+ self.processing_marked: list[str] = []+ # ts per forwarded followup, in execution order.+ self.forwarded: list[str] = []+ # ts -> forward result; missing means False (no existing task, fall through to new-task path).+ self.forward_results: dict[str, bool] = {}+ # ts -> cascade mode; missing means "auto" with a fixed repository.+ self.cascade_modes: dict[str, Literal["auto", "no_repo", "agent_needed", "needs_user_github"]] = {}+ # ts -> gate the create-task fake blocks on, to hold a message mid-processing.+ self.create_gates: dict[str, asyncio.Event] = {}+ self.create_reached: dict[str, asyncio.Event] = {}+ self.picker_posted = asyncio.Event()+ self.picker_workflow_id: str | None = None+++def _fake_activities(rec: _Recorder) -> list:+ @activity.defn(name="enforce_posthog_code_billing_quota_activity")+ async def quota(+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str, slack_user_id: str+ ) -> bool:+ return False++ @activity.defn(name="classify_untagged_followup_activity")+ async def classify_followup(+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+ event_text: str,+ ) -> bool:+ return True++ @activity.defn(name="forward_posthog_code_followup_activity")+ async def forward(+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+ event_text: str,+ user_message_ts: str | None,+ ) -> bool:+ ts = inputs.event["ts"]+ if rec.forward_results.get(ts, False):+ rec.forwarded.append(ts)+ return True+ return False++ @activity.defn(name="collect_posthog_code_thread_messages_activity")+ async def collect(+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str+ ) -> list[dict[str, str]]:+ return [{"user": "U1", "text": inputs.event["text"]}]++ @activity.defn(name="cascade_posthog_code_repository_activity")+ async def cascade(+ inputs: PostHogCodeSlackMentionWorkflowInputs, event_text: str, user_id: int | None = None+ ) -> PostHogCodeRepoCascadeOutcome:+ mode = rec.cascade_modes.get(inputs.event["ts"], "auto")+ repository = "org/auto-repo" if mode == "auto" else None+ return PostHogCodeRepoCascadeOutcome(mode=mode, repository=repository, reason="test")++ @activity.defn(name="classify_posthog_code_task_needs_repo_activity")+ async def needs_repo(event_text: str, thread_messages: list[dict[str, str]]) -> bool:+ return True++ @activity.defn(name="discover_posthog_code_repository_via_agent_activity")+ async def discover(+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ channel: str,+ event: dict[str, Any],+ thread_messages: list[dict[str, str]],+ user_id: int,+ ) -> SlackRepoSelectionOutcome:+ return SlackRepoSelectionOutcome(status="failed", repository=None, reason="agent crashed")++ @activity.defn(name="post_posthog_code_repo_picker_activity")+ async def post_picker(+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+ event: dict[str, Any],+ workflow_id: str,+ guidance: str,+ allow_no_repo: bool,+ user_id: int | None = None,+ ) -> None:+ rec.picker_workflow_id = workflow_id+ rec.picker_posted.set()++ @activity.defn(name="resolve_posthog_code_authorship_activity")+ async def resolve_authorship(+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+ user_id: int,+ workflow_id: str,+ repository: str,+ ) -> str:+ return "proceed"++ @activity.defn(name="block_posthog_code_task_if_no_personal_github_activity")+ async def block_github(+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ channel: str,+ thread_ts: str,+ user_id: int,+ allow_bot_prs: bool = False,+ ) -> bool:+ return False++ @activity.defn(name="create_posthog_code_task_for_repo_activity")+ async def create_task(+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+ user_id: int,+ event: dict[str, Any],+ thread_messages: list[dict[str, str]],+ repository: str | None,+ repo_research_task_id: str | None = None,+ repo_research_run_id: str | None = None,+ ) -> None:+ ts = inputs.event["ts"]+ reached = rec.create_reached.get(ts)+ if reached:+ reached.set()+ gate = rec.create_gates.get(ts)+ if gate:+ await gate.wait()+ rec.created.append((ts, repository))++ @activity.defn(name="post_posthog_code_picker_timeout_activity")+ async def picker_timeout(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:+ return None++ @activity.defn(name="post_posthog_code_authorship_timeout_activity")+ async def authorship_timeout(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:+ return None++ @activity.defn(name="post_posthog_code_internal_error_activity")+ async def internal_error(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:+ return None++ @activity.defn(name="resolve_posthog_code_slack_user_activity")+ async def resolve_user(+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str, slack_user_id: str+ ) -> int | None:+ return 42++ @activity.defn(name="mark_slack_app_message_processing_activity")+ async def mark_processing(input: SlackAppMessageReactionInput) -> None:+ rec.processing_marked.append(input.message_ts)++ @activity.defn(name="mark_slack_app_message_queued_activity")+ async def mark_queued(input: SlackAppMessageReactionInput) -> None:+ rec.queued_marked.append(input.message_ts)++ return [+ mark_processing,+ mark_queued,+ quota,+ classify_followup,+ forward,+ collect,+ cascade,+ needs_repo,+ discover,+ post_picker,+ resolve_authorship,+ block_github,+ create_task,+ picker_timeout,+ authorship_timeout,+ internal_error,+ resolve_user,+ ]+++async def _signal_with_start(env, task_queue: str, workflow_id: str, message: PostHogCodeSlackMentionWorkflowInputs):+ """Mirror the production dispatch shape from api._start_mention_workflow."""+ return await env.client.start_workflow(+ SlackAppMentionWorkflow.run,+ SlackAppMentionWorkflowInputs(),+ id=workflow_id,+ task_queue=task_queue,+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ start_signal="new_message",+ start_signal_args=[message],+ )+++class _Harness:+ """One time-skipping environment + worker per test.++ Time only skips while the test awaits the workflow result, so the idle+ timer (and the 15-minute picker timer) stay parked while the test delivers+ signals in real time — no sleeps, no timer races.+ """++ def __init__(self, rec: _Recorder) -> None:+ self.rec = rec+ self.task_queue = str(uuid.uuid4())++ async def __aenter__(self):+ # Escape hatch for networks where the SDK's temporal.download fetch is+ # blocked: point at a pre-downloaded temporal-test-server binary (from+ # the temporalio/sdk-java GitHub releases). Unset, the SDK downloads+ # and caches the binary itself.+ self._env_cm = await WorkflowEnvironment.start_time_skipping(+ test_server_existing_path=os.environ.get("TEMPORAL_TEST_SERVER_PATH")+ )+ self.env = await self._env_cm.__aenter__()+ self._worker_cm = Worker(+ self.env.client,+ task_queue=self.task_queue,+ workflows=[SlackAppMentionWorkflow, PostHogCodeSlackMentionWorkflow],+ activities=_fake_activities(self.rec),+ workflow_runner=UnsandboxedWorkflowRunner(),+ )+ await self._worker_cm.__aenter__()+ return self++ async def __aexit__(self, *exc_info):+ await self._worker_cm.__aexit__(*exc_info)+ await self._env_cm.__aexit__(*exc_info)+++async def test_queued_messages_process_serially_in_arrival_order():+ rec = _Recorder()+ first, second, third = _message("1.1"), _message("1.2"), _message("1.3")+ rec.create_reached["1.1"] = asyncio.Event()+ rec.create_gates["1.1"] = asyncio.Event()++ async with _Harness(rec) as h:+ handle = await _signal_with_start(h.env, h.task_queue, f"wf-{uuid.uuid4()}", first)+ # Hold the first message inside its create-task activity, queue two+ # more behind it, then release. FIFO must be preserved.+ await asyncio.wait_for(rec.create_reached["1.1"].wait(), timeout=30)+ await handle.signal(SlackAppMentionWorkflow.new_message, second)+ await handle.signal(SlackAppMentionWorkflow.new_message, third)+ rec.create_gates["1.1"].set()+ await asyncio.wait_for(handle.result(), timeout=30)++ assert rec.created == [("1.1", "org/auto-repo"), ("1.2", "org/auto-repo"), ("1.3", "org/auto-repo")]+ # Only the messages that waited behind another get the hourglass; the+ # first one went straight to processing.+ assert rec.queued_marked == ["1.2", "1.3"]+ # Every mention gets eyes as it leaves the queue.+ assert rec.processing_marked == ["1.1", "1.2", "1.3"]+++async def test_signal_with_start_on_running_workflow_signals_same_run():+ rec = _Recorder()+ first, second = _message("1.1"), _message("1.2")+ rec.create_reached["1.1"] = asyncio.Event()+ rec.create_gates["1.1"] = asyncio.Event()++ async with _Harness(rec) as h:+ workflow_id = f"wf-{uuid.uuid4()}"+ handle = await _signal_with_start(h.env, h.task_queue, workflow_id, first)+ # Issue a second signal-with-start (the exact production dispatch call)+ # while the first run is mid-message. It must NOT start a second+ # execution — the server delivers the signal to the running one.+ await asyncio.wait_for(rec.create_reached["1.1"].wait(), timeout=30)+ handle_two = await _signal_with_start(h.env, h.task_queue, workflow_id, second)+ rec.create_gates["1.1"].set()+ await asyncio.wait_for(handle.result(), timeout=30)+ assert handle_two.first_execution_run_id == handle.first_execution_run_id++ assert rec.created == [("1.1", "org/auto-repo"), ("1.2", "org/auto-repo")]+++async def test_duplicate_slack_event_id_is_processed_once():+ rec = _Recorder()+ message = _message("1.1", event_id="Ev123")++ async with _Harness(rec) as h:+ handle = await _signal_with_start(h.env, h.task_queue, f"wf-{uuid.uuid4()}", message)+ await handle.signal(SlackAppMentionWorkflow.new_message, message)+ await asyncio.wait_for(handle.result(), timeout=30)++ assert rec.created == [("1.1", "org/auto-repo")]+++async def test_untagged_followup_forwards_without_task_creation_or_reactions():+ rec = _Recorder()+ rec.forward_results["1.1"] = True++ async with _Harness(rec) as h:+ handle = await _signal_with_start(h.env, h.task_queue, f"wf-{uuid.uuid4()}", _message("1.1", untagged=True))+ await asyncio.wait_for(handle.result(), timeout=30)++ assert rec.forwarded == ["1.1"]+ assert rec.created == []+ # Untagged followups were never addressed to the bot: no reactions.+ assert rec.queued_marked == []+ assert rec.processing_marked == []+++async def test_idle_exit_then_signal_with_start_processes_in_fresh_run():+ rec = _Recorder()+ workflow_id = f"wf-{uuid.uuid4()}"++ async with _Harness(rec) as h:+ handle = await _signal_with_start(h.env, h.task_queue, workflow_id, _message("1.1"))+ await asyncio.wait_for(handle.result(), timeout=30)+ # First run has idled out and completed; the production dispatch shape+ # must start a fresh run under the same conversation ID.+ handle_two = await _signal_with_start(h.env, h.task_queue, workflow_id, _message("2.1"))+ await asyncio.wait_for(handle_two.result(), timeout=30)+ assert handle_two.result_run_id != handle.result_run_id++ assert rec.created == [("1.1", "org/auto-repo"), ("2.1", "org/auto-repo")]+ # Both messages opened their own idle conversation and processed+ # immediately — neither ever waited, so neither got the hourglass.+ assert rec.queued_marked == []+++async def test_repo_picker_signal_resolves_and_queue_continues():+ rec = _Recorder()+ rec.cascade_modes["1.1"] = "agent_needed"++ first = _message("1.1")+ async with _Harness(rec) as h:+ workflow_id = f"wf-{uuid.uuid4()}"+ handle = await _signal_with_start(h.env, h.task_queue, workflow_id, first)+ # First message falls through discovery to the picker and blocks the+ # queue; a second message queues up behind it in the meantime.+ await asyncio.wait_for(rec.picker_posted.wait(), timeout=30)+ await handle.signal(SlackAppMentionWorkflow.new_message, _message("1.2"))++ # The picker message must carry the child's per-message workflow ID —+ # it is what the interactivity webhook uses to route the click back as+ # a signal, straight to the child that is waiting on it.+ assert rec.picker_workflow_id is not None+ assert rec.picker_workflow_id == derive_mention_workflow_id(first)+ child_handle = h.env.client.get_workflow_handle(rec.picker_workflow_id)+ await child_handle.signal("repo_selected", "org/picked")+ await asyncio.wait_for(handle.result(), timeout=30)++ assert rec.created == [("1.1", "org/picked"), ("1.2", "org/auto-repo")]+++async def test_continue_as_new_carry_over_processes_pending_and_dedups_seen():+ rec = _Recorder()+ pending = _message("1.1", event_id="Ev-pending")+ already_seen = _message("1.2", event_id="Ev-seen")++ async with _Harness(rec) as h:+ # Start with post-continue_as_new-shaped inputs: one carried pending+ # message and one already-processed key.+ handle = await h.env.client.start_workflow(+ SlackAppMentionWorkflow.run,+ SlackAppMentionWorkflowInputs(+ pending_messages=[pending],+ processed_event_keys=[derive_mention_workflow_id(already_seen)],+ ),+ id=f"wf-{uuid.uuid4()}",+ task_queue=h.task_queue,+ )+ await handle.signal(SlackAppMentionWorkflow.new_message, already_seen)+ await asyncio.wait_for(handle.result(), timeout=30)++ assert rec.created == [("1.1", "org/auto-repo")]diff --git a/posthog/temporal/tests/ai/test_block_missing_user_github.py b/posthog/temporal/tests/ai/test_block_missing_user_github.pyindex 7897598acba0..f18274c8a558 100644--- a/posthog/temporal/tests/ai/test_block_missing_user_github.py+++ b/posthog/temporal/tests/ai/test_block_missing_user_github.py@@ -30,7 +30,7 @@ class TestBlockPostHogCodeTaskIfNoPersonalGitHub(TestCase):self.user = User.objects.create(email="[email protected]")self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_returns_true_and_posts_block_when_user_has_no_personal_github(self, mock_slack_cls):mock_slack = MagicMock()mock_slack_cls.return_value = mock_slack@@ -51,7 +51,7 @@ class TestBlockPostHogCodeTaskIfNoPersonalGitHub(TestCase):assert button["text"]["text"] == "Connect GitHub"assert button["url"].endswith(f"/project/{self.team.id}/settings/user-personal-integrations")- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_returns_false_and_posts_nothing_when_user_has_personal_github(self, mock_slack_cls):UserIntegration.objects.create(user=self.user,@@ -70,7 +70,7 @@ class TestBlockPostHogCodeTaskIfNoPersonalGitHub(TestCase):assert blocked is Falsemock_slack.client.chat_postMessage.assert_not_called()- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_only_github_kind_counts_as_personal_integration(self, mock_slack_cls):UserIntegration.objects.create(user=self.user,@@ -97,7 +97,7 @@ class TestBlockPostHogCodeTaskIfNoPersonalGitHub(TestCase):])@patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled")- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_allow_bot_prs_gates_on_flag_and_team_install(self, _name, flag_on, has_team_install, expect_blocked, mock_slack_cls, mock_flag):@@ -119,7 +119,7 @@ class TestBlockPostHogCodeTaskIfNoPersonalGitHub(TestCase):assert blocked is expect_blockedassert mock_slack.client.chat_postMessage.called is expect_blocked- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_another_users_github_integration_does_not_count(self, mock_slack_cls):other_user = User.objects.create(email="[email protected]")UserIntegration.objects.create(diff --git a/posthog/temporal/tests/ai/test_resolve_authorship.py b/posthog/temporal/tests/ai/test_resolve_authorship.pyindex 9af7ba8aa1ba..3a95d8ae1d3a 100644--- a/posthog/temporal/tests/ai/test_resolve_authorship.py+++ b/posthog/temporal/tests/ai/test_resolve_authorship.py@@ -61,7 +61,7 @@ class TestResolvePostHogCodeAuthorship(TestCase):)@patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True)- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_personal_github_with_repo_access_proceeds_and_posts_nothing(self, mock_slack_cls, _mock_flag):self._add_personal_github(repos=["posthog/target-repo"])mock_slack = MagicMock()@@ -77,7 +77,7 @@ class TestResolvePostHogCodeAuthorship(TestCase):("expired_refresh_token_flag_on", ["posthog/target-repo"], 1, True, "awaiting_confirmation"),])- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_unusable_personal_github_never_proceeds(self, _name, repos, refresh_token_expires_at, flag_on, expected_status, mock_slack_cls):@@ -93,7 +93,7 @@ class TestResolvePostHogCodeAuthorship(TestCase):assert "can't author PRs in `posthog/target-repo`" in kwargs["text"]@patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_no_personal_flag_off_blocks_with_single_button(self, mock_slack_cls, _mock_flag):self._add_team_github()mock_slack = MagicMock()@@ -109,7 +109,7 @@ class TestResolvePostHogCodeAuthorship(TestCase):assert "action_id" not in elements[0]@patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True)- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_no_personal_flag_on_with_team_install_awaits_confirmation(self, mock_slack_cls, _mock_flag):self._add_team_github()mock_slack = MagicMock()@@ -130,7 +130,7 @@ class TestResolvePostHogCodeAuthorship(TestCase):assert kwargs["metadata"]["event_payload"]["workflow_id"] == "wf-123"@patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True)- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_no_personal_flag_on_without_team_install_blocks(self, mock_slack_cls, _mock_flag):mock_slack = MagicMock()mock_slack_cls.return_value = mock_slack@@ -145,7 +145,7 @@ class TestResolvePostHogCodeAuthorship(TestCase):])@patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True)- @patch("posthog.models.integration.SlackIntegration")+ @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")def test_non_github_personal_integration_does_not_count(self, _name, kind, mock_slack_cls, _mock_flag):UserIntegration.objects.create(user=self.user, kind=kind, integration_id="x", config={}, sensitive_config={})self._add_team_github()diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex e73227e47204..a09614ce79ae 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -40,6 +40,7 @@ from posthog.models.user_integration import UserGitHubIntegration, UserIntegratifrom posthog.temporal.ai.slack_app import (PostHogCodeSlackMentionCommandWorkflowInputs,PostHogCodeSlackMentionWorkflowInputs,+ SlackAppMentionWorkflowInputs,derive_mention_workflow_id,)from posthog.temporal.ai.slack_app.posthog_code_slack_interactivity import (@@ -48,6 +49,10 @@ from posthog.temporal.ai.slack_app.posthog_code_slack_interactivity import ()from posthog.temporal.ai.slack_app.posthog_code_slack_mention import PostHogCodeSlackMentionWorkflowfrom posthog.temporal.ai.slack_app.posthog_code_slack_mention_command import PostHogCodeSlackMentionCommandWorkflow+from posthog.temporal.ai.slack_app.slack_app_mention import (+ SlackAppMentionWorkflow,+ derive_slack_app_mention_workflow_id,+)from posthog.temporal.common.client import sync_connectfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import get_instance_region@@ -57,6 +62,7 @@ from products.slack_app.backend.feature_flags import (is_slack_app_assistant_enabled,is_slack_app_bot_prs_enabled,is_slack_app_oauth_enabled,+ is_slack_app_queue_workflow_enabled,is_slack_app_untagged_thread_followups_enabled,)from products.slack_app.backend.models import SlackChannel, SlackThreadTaskMapping@@ -1435,7 +1441,16 @@ def _start_posthog_code_workflow(event: dict,event_id: str | None,workflow_id: str | None = None,+ start_signal: str | None = None,+ start_signal_args: list[Any] | None = None,) -> None:+ """Start a Slack-app workflow, optionally as a signal-with-start.++ With ``start_signal`` set the operation is atomic on the server: a running+ execution gets the signal, a finished (or never-started) one is started+ with the signal as its first event — how the queue workflow guarantees a+ message lands exactly once in its conversation's queue.+ """if workflow_id is None:fallback = event_id if event_id else f"{event.get('channel', '')}:{event.get('ts', '')}"workflow_id = f"{id_prefix}-{slack_team_id}:{fallback}"@@ -1448,6 +1463,9 @@ def _start_posthog_code_workflow(task_queue=settings.TASKS_TASK_QUEUE,id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ # None / [] match the SDK defaults, so a plain start stays a plain start.+ start_signal=start_signal,+ start_signal_args=start_signal_args or [],))@@ -2444,6 +2462,22 @@ def _start_mention_workflow(untagged_followup=untagged_followup,is_ext_shared_channel=is_ext_shared_channel,)+ # Deriving the ID is free, the flag evaluation is remote — check in that+ # order. Events without channel/ts fall back to the per-message workflow.+ queue_workflow_id = derive_slack_app_mention_workflow_id(workflow_inputs)+ if queue_workflow_id is not None and is_slack_app_queue_workflow_enabled(integration, slack_team_id):+ _start_posthog_code_workflow(+ SlackAppMentionWorkflow,+ SlackAppMentionWorkflowInputs(),+ id_prefix="slack-app-mention",+ slack_team_id=slack_team_id,+ event=event,+ event_id=event_id,+ workflow_id=queue_workflow_id,+ start_signal="new_message",+ start_signal_args=[workflow_inputs],+ )+ return ROUTE_HANDLED_LOCALLY# Use derive_mention_workflow_id as the single source of truth: the workflow persists the same# value as slack_mention_workflow_id, so dispatch and the debug-tool Temporal link stay consistent_start_posthog_code_workflow(diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.pyindex d4f3a7c81210..a609e61db48d 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -35,6 +35,7 @@ SLACK_APP_ASSISTANT_FLAG = "slack-app-assistant"SLACK_APP_BOT_PRS_FLAG = "slack-app-bot-prs"SLACK_APP_LIVING_ARTIFACTS_FLAG = "slack-app-living-artifacts"SLACK_APP_CANVAS_FILE_ARTIFACTS_FLAG = "slack-app-canvas-file-artifacts"+SLACK_APP_QUEUE_WORKFLOW_FLAG = "slack-app-queue-workflow"UNTAGGED_THREAD_FOLLOWUPS_FLAG = "posthog-slack-app-untagged-thread-followups"@@ -187,6 +188,31 @@ def is_slack_app_untagged_thread_followups_enabled(integration: Integration, slareturn False+def is_slack_app_queue_workflow_enabled(integration: Integration, slack_team_id: str) -> bool:+ """Gate for the per-conversation queue workflow: when on, mention/followup/DM+ dispatch signal-with-starts one ``SlackAppMentionWorkflow`` per thread that+ processes messages serially, instead of one workflow per message. Keyed on+ the Slack workspace + PostHog org."""+ try:+ return bool(+ posthoganalytics.feature_enabled(+ SLACK_APP_QUEUE_WORKFLOW_FLAG,+ f"slack_workspace:{slack_team_id}",+ groups={"organization": str(integration.team.organization_id)},+ person_properties=_region_properties(),+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.exception(+ "slack_app_queue_workflow_flag_check_failed",+ slack_team_id=slack_team_id,+ integration_id=integration.id,+ )+ return False++def is_slack_app_bot_prs_enabled(team: Team) -> bool:organization_id = str(team.organization_id)project_id = str(team.id)diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.pyindex f3baf258671c..952e99e462b2 100644--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py@@ -1253,3 +1253,77 @@ class TestAssistantInstallWelcome(TestCase):with enabled_p, slack as slack_cls:slack_cls.return_value.client.chat_postMessage.side_effect = Exception("slack down")send_assistant_install_welcome(self.integration) # must not raise+++class TestQueueWorkflowDispatch(TestCase):+ def setUp(self):+ from django.utils import timezone++ from posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES++ cache.clear()+ self.factory = RequestFactory()+ self.organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.user = User.objects.create(email="[email protected]", distinct_id="queue-user-1")+ OrganizationMembership.objects.create(organization=self.organization, user=self.user)+ self.user.current_organization = self.organization+ self.user.current_team = self.team+ self.user.save()+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T12345",+ config={"scope": ",".join(sorted(REQUIRED_SLACK_SCOPES))},+ sensitive_config={"access_token": "xoxb-posthog-code-test"},+ )+ SlackUserProfileCache.objects.create(+ integration=self.integration,+ slack_user_id="U123",+ email="[email protected]",+ display_name="Dev",+ real_name="Dev User",+ refreshed_at=timezone.now(),+ )++ @parameterized.expand(+ [+ ("top_level_mention_anchors_on_ts", None, "1234.5678"),+ ("threaded_mention_anchors_on_thread_root", "1000.0001", "1000.0001"),+ ]+ )+ @patch("products.slack_app.backend.api.SlackIntegration")+ @patch("products.slack_app.backend.api.is_slack_app_queue_workflow_enabled", return_value=True)+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")+ def test_flag_on_signal_with_starts_conversation_workflow(+ self, _name, thread_ts, expected_anchor, mock_sync_connect, mock_asyncio_run, mock_flag, mock_slack+ ):+ # With the flag on, every message in a conversation must land in ONE+ # per-thread workflow via signal-with-start — the conversation ID+ # anchors on the thread root so followups reach the same instance.+ from posthog.temporal.ai.slack_app.slack_app_mention import SlackAppMentionWorkflow++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ mock_slack.return_value.missing_scopes.return_value = set()+ event = {"type": "app_mention", "channel": "C001", "user": "U123", "ts": "1234.5678"}+ if thread_ts:+ event["thread_ts"] = thread_ts+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")++ result = route_posthog_code_event_to_relevant_region(request, event, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ mock_sync_connect.return_value.start_workflow.assert_called_once()+ call = mock_sync_connect.return_value.start_workflow.call_args+ assert call.args[0] == SlackAppMentionWorkflow.run+ assert call.kwargs["id"] == f"slack-app-mention-T12345:C001:{expected_anchor}"+ assert call.kwargs["start_signal"] == "new_message"+ message = call.kwargs["start_signal_args"][0]+ assert message.user_id == self.user.id+ assert message.event["ts"] == "1234.5678"+ # Dispatch adds no reaction — the queue workflow reacts only on+ # messages that actually wait behind another one.+ mock_slack.return_value.client.reactions_add.assert_not_called()