Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: ms polls for shared channels (#64529)

Alex V3784b982e14c
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 35189b110224..845eb1e39e28 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -165,6 +165,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"EvaluationConfig",
"RemoteConfig",
"TeamConversationsSlackConfig",
+ "TeamConversationsTeamsChannelSync",
"TeamCustomerAnalyticsConfig",
"TeamDefaultEvaluationContext",
"TeamDataWarehouseConfig",
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 1e975e21790a..e37e8e6a5586 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -69,7 +69,11 @@ from posthog.tasks.team_llm_gateway_policy import refresh_expiring_llm_gateway_p
from posthog.tasks.team_metadata import cleanup_stale_expiry_tracking_task, refresh_expiring_team_metadata_cache_entries
from posthog.utils import get_crontab, get_instance_region
-from products.conversations.backend.tasks import flush_pending_email_replies, wake_snoozed_tickets
+from products.conversations.backend.tasks import (
+ flush_pending_email_replies,
+ poll_teams_shared_channels,
+ wake_snoozed_tickets,
+)
from products.data_modeling.backend.tasks.cleanup_test_saved_queries import cleanup_expired_test_saved_queries
from products.data_warehouse.backend.tasks import send_external_data_failure_digest_catchup
from products.endpoints.backend.tasks import deactivate_stale_materializations
@@ -671,6 +675,15 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
flush_pending_email_replies.s(),
name="flush pending conversation email replies",
)
+
+ # Pull ambient messages from MS Teams shared channels (which never push them
+ # over the bot webhook) into the ticket pipeline via Graph messages/delta.
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="*"),
+ poll_teams_shared_channels.s(),
+ name="poll teams shared channels",
+ )
# Delete expired Streamlit bridge OAuth tokens.
sender.add_periodic_task(
# Hourly because tokens have a 1-hour TTL and every connect_info
diff --git a/products/conversations/backend/api/teams_channels.py b/products/conversations/backend/api/teams_channels.py
index 95e8190adaf5..2d95525c55e3 100644
--- a/products/conversations/backend/api/teams_channels.py
+++ b/products/conversations/backend/api/teams_channels.py
@@ -104,7 +104,14 @@ class TeamsChannelsView(APIView):
data = resp.json()
channels = [
- {"id": c.get("id"), "name": c.get("displayName")}
+ {
+ "id": c.get("id"),
+ "name": c.get("displayName"),
+ # "standard" | "shared" | "private" — drives shared-channel
+ # polling and the picker badge. Absent fields are treated as
+ # standard downstream.
+ "membership_type": c.get("membershipType"),
+ }
for c in data.get("value", [])
if c.get("id") and c.get("displayName")
]
@@ -384,6 +391,10 @@ class TeamsSelectChannelView(APIView):
"team_name": teams_team_name,
"channel_id": teams_channel_id,
"channel_name": teams_channel_name,
+ # "standard" | "shared" | "private". Shared/private channels never
+ # push ambient messages over the bot webhook, so the per-minute
+ # poller pulls them from Graph; standard channels stay webhook-only.
+ "membership_type": channel_match.get("membershipType"),
}
# Remove existing entry with same channel_id (if any)
teams_channels = [c for c in teams_channels if c.get("channel_id") != teams_channel_id]
diff --git a/products/conversations/backend/api/teams_oauth.py b/products/conversations/backend/api/teams_oauth.py
index 24d9d7867fb1..11dfdc4536c2 100644
--- a/products/conversations/backend/api/teams_oauth.py
+++ b/products/conversations/backend/api/teams_oauth.py
@@ -35,7 +35,11 @@ TEAMS_OAUTH_SCOPES = (
"Team.ReadBasic.All Channel.ReadBasic.All TeamsAppInstallation.ReadWriteForTeam "
# User.ReadBasic.All is needed to resolve a Teams user's email via
# GET /users/{aadObjectId} — User.Read alone only grants /me.
- "User.ReadBasic.All offline_access openid profile"
+ "User.ReadBasic.All "
+ # ChannelMessage.Read.All (delegated) lets the shared-channel poller read
+ # channel messages via Graph's messages/delta as the connecting admin.
+ # Must stay in sync with support_teams.GRAPH_REFRESH_SCOPES.
+ "ChannelMessage.Read.All offline_access openid profile"
)
AZURE_AD_AUTHORIZE_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
AZURE_AD_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
diff --git a/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py b/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py
new file mode 100644
index 000000000000..dc6b40ca5501
--- /dev/null
+++ b/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py
@@ -0,0 +1,276 @@
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.conversations.backend.models import (
+ TeamConversationsTeamsChannelSync,
+ TeamConversationsTeamsConfig,
+ Ticket,
+)
+from products.conversations.backend.support_teams import store_teams_service_url
+from products.conversations.backend.tasks import poll_team_shared_channels, poll_teams_shared_channels
+from products.conversations.backend.teams import graph_message_to_activity
+
+TRUSTED_SERVICE_URL = "https://smba.trafficmanager.net/teams"
+
+CHANNEL_ID = "19:[email protected]"
+TEAMS_TEAM_ID = "teams-group-1"
+
+
+def _graph_message(
+ *,
+ msg_id: str = "m1",
+ message_type: str = "message",
+ content: str = "<p>hello support</p>",
+ user_id: str | None = "aad-user-1",
+ deleted: bool = False,
+ reply_to_id: str | None = None,
+) -> dict[str, Any]:
+ msg: dict[str, Any] = {
+ "id": msg_id,
+ "messageType": message_type,
+ "createdDateTime": "2024-01-01T12:00:00Z",
+ "body": {"contentType": "html", "content": content},
+ }
+ if deleted:
+ msg["deletedDateTime"] = "2024-01-02T00:00:00Z"
+ if reply_to_id:
+ msg["replyToId"] = reply_to_id
+ if user_id is not None:
+ msg["from"] = {"user": {"id": user_id, "displayName": "Alice"}}
+ else:
+ msg["from"] = {"application": {"id": "app-1", "displayName": "SupportHog"}}
+ return msg
+
+
+def _resp(status_code: int = 200, json_data: dict | None = None) -> MagicMock:
+ resp = MagicMock()
+ resp.status_code = status_code
+ resp.json.return_value = json_data or {}
+ return resp
+
+
+def _channel_verify_resp() -> MagicMock:
+ """Graph GET /teams/{id}/channels/{id} confirming membershipType=shared."""
+ return _resp(json_data={"id": CHANNEL_ID, "membershipType": "shared"})
+
+
+class TestGraphMessageToActivity(BaseTest):
+ @parameterized.expand(
+ [
+ ("normal_message", _graph_message(), True),
+ ("deleted_message", _graph_message(deleted=True), False),
+ ("system_event", _graph_message(message_type="systemEventMessage"), False),
+ ("app_authored", _graph_message(user_id=None), False),
+ ("empty_body", _graph_message(content=" "), False),
+ ("reply", _graph_message(reply_to_id="root-1"), False),
+ ]
+ )
+ def test_mapping(self, _name: str, msg: dict, should_map: bool) -> None:
+ activity = graph_message_to_activity(msg, CHANNEL_ID, "https://smba.trafficmanager.net/teams/")
+ if not should_map:
+ self.assertIsNone(activity)
+ return
+ assert activity is not None
+ self.assertEqual(activity["id"], "m1")
+ self.assertEqual(activity["from"]["aadObjectId"], "aad-user-1")
+ self.assertEqual(activity["conversation"]["id"], f"{CHANNEL_ID};messageid=m1")
+ self.assertEqual(activity["channelData"]["channel"]["id"], CHANNEL_ID)
+
+
+@patch("products.conversations.backend.teams.resolve_teams_user", return_value={"name": "Alice", "email": None})
+@patch("products.conversations.backend.tasks.get_graph_token", return_value="graph-token")
+class TestPollSharedChannel(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.conversations_settings = {
+ "teams_enabled": True,
+ "teams_channels": [
+ {
+ "team_id": TEAMS_TEAM_ID,
+ "team_name": "Group",
+ "channel_id": CHANNEL_ID,
+ "channel_name": "shared",
+ "membership_type": "shared",
+ },
+ ],
+ }
+ self.team.save()
+ TeamConversationsTeamsConfig.objects.update_or_create(
+ team=self.team,
+ defaults={
+ "teams_tenant_id": "tenant-abc",
+ "teams_graph_access_token": "graph-tok",
+ "teams_graph_refresh_token": "graph-ref",
+ },
+ )
+
+ def _sync(self) -> TeamConversationsTeamsChannelSync:
+ return TeamConversationsTeamsChannelSync.objects.for_team(self.team.id).get(channel_id=CHANNEL_ID)
+
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_first_run_primes_without_creating_tickets(self, mock_get: MagicMock, *_: Any) -> None:
+ mock_get.side_effect = [
+ _channel_verify_resp(),
+ _resp(json_data={"value": [_graph_message()], "@odata.deltaLink": "DELTA1"}),
+ ]
+
+ poll_team_shared_channels(self.team.id)
+
+ self.assertEqual(Ticket.objects.filter(team=self.team).count(), 0)
+ sync = self._sync()
+ self.assertTrue(sync.primed)
+ self.assertEqual(sync.delta_link, "DELTA1")
+
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_second_run_creates_one_ticket_and_is_idempotent(self, mock_get: MagicMock, *_: Any) -> None:
+ # Prime (first call = verify, second = delta).
+ mock_get.side_effect = [
+ _channel_verify_resp(),
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA1"}),
+ ]
+ poll_team_shared_channels(self.team.id)
+ self.assertEqual(Ticket.objects.filter(team=self.team).count(), 0)
+
+ # New message after priming -> exactly one ticket. No verify on second run.
+ mock_get.side_effect = None
+ mock_get.return_value = _resp(json_data={"value": [_graph_message(msg_id="m2")], "@odata.deltaLink": "DELTA2"})
+ poll_team_shared_channels(self.team.id)
+ self.assertEqual(Ticket.objects.filter(team=self.team).count(), 1)
+ self.assertEqual(self._sync().delta_link, "DELTA2")
+
+ # Same message re-delivered -> no duplicate ticket.
+ mock_get.return_value = _resp(json_data={"value": [_graph_message(msg_id="m2")], "@odata.deltaLink": "DELTA3"})
+ poll_team_shared_channels(self.team.id)
+ self.assertEqual(Ticket.objects.filter(team=self.team).count(), 1)
+
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_polled_ticket_uses_service_url_from_config(self, mock_get: MagicMock, *_: Any) -> None:
+ TeamConversationsTeamsConfig.objects.filter(team=self.team).update(teams_service_url=TRUSTED_SERVICE_URL)
+ mock_get.side_effect = [
+ _channel_verify_resp(),
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA1"}),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ mock_get.side_effect = None
+ mock_get.return_value = _resp(json_data={"value": [_graph_message(msg_id="m2")], "@odata.deltaLink": "DELTA2"})
+ poll_team_shared_channels(self.team.id)
+
+ ticket = Ticket.objects.filter(team=self.team).get()
+ self.assertEqual(ticket.teams_service_url, TRUSTED_SERVICE_URL)
+
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_pagination_follows_next_link(self, mock_get: MagicMock, *_: Any) -> None:
+ # Prime first (verify + delta).
+ mock_get.side_effect = [
+ _channel_verify_resp(),
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA1"}),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ mock_get.side_effect = [
+ _resp(json_data={"value": [_graph_message(msg_id="p1")], "@odata.nextLink": "NEXT1"}),
+ _resp(json_data={"value": [_graph_message(msg_id="p2")], "@odata.deltaLink": "DELTA_FINAL"}),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ self.assertEqual(Ticket.objects.filter(team=self.team).count(), 2)
+ self.assertEqual(self._sync().delta_link, "DELTA_FINAL")
+
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_410_resets_state_for_reprime(self, mock_get: MagicMock, *_: Any) -> None:
+ mock_get.side_effect = [
+ _channel_verify_resp(),
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA1"}),
+ ]
+ poll_team_shared_channels(self.team.id)
+ self.assertTrue(self._sync().primed)
+
+ mock_get.side_effect = None
+ mock_get.return_value = _resp(status_code=410)
+ poll_team_shared_channels(self.team.id)
+
+ sync = self._sync()
+ self.assertFalse(sync.primed)
+ self.assertIsNone(sync.delta_link)
+
+ @parameterized.expand([("payment", 402), ("forbidden", 403), ("throttled", 429)])
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_error_statuses_skip_without_crashing(
+ self, _name: str, status_code: int, mock_get: MagicMock, *_: Any
+ ) -> None:
+ mock_get.side_effect = [
+ _channel_verify_resp(),
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA1"}),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ mock_get.side_effect = None
+ mock_get.return_value = _resp(status_code=status_code)
+ # Should not raise.
+ poll_team_shared_channels(self.team.id)
+ self.assertEqual(Ticket.objects.filter(team=self.team).count(), 0)
+
+
+class TestStoreTeamsServiceUrl(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.config, _ = TeamConversationsTeamsConfig.objects.update_or_create(
+ team=self.team, defaults={"teams_tenant_id": "tenant-abc", "teams_service_url": None}
+ )
+
+ @patch("products.conversations.backend.support_teams.is_trusted_teams_service_url", return_value=True)
+ def test_persists_trusted_url_and_strips_trailing_slash(self, _trusted: MagicMock) -> None:
+ store_teams_service_url("tenant-abc", TRUSTED_SERVICE_URL + "/")
+ self.config.refresh_from_db()
+ self.assertEqual(self.config.teams_service_url, TRUSTED_SERVICE_URL)
+
+ @patch("products.conversations.backend.support_teams.is_trusted_teams_service_url", return_value=False)
+ def test_skips_untrusted_url(self, _trusted: MagicMock) -> None:
+ store_teams_service_url("tenant-abc", "https://evil.example.com")
+ self.config.refresh_from_db()
+ self.assertIsNone(self.config.teams_service_url)
+
+ @patch("products.conversations.backend.support_teams.is_trusted_teams_service_url", return_value=True)
+ def test_noop_for_unknown_tenant(self, _trusted: MagicMock) -> None:
+ store_teams_service_url("tenant-zzz", TRUSTED_SERVICE_URL)
+ self.config.refresh_from_db()
+ self.assertIsNone(self.config.teams_service_url)
+
+
+@patch("products.conversations.backend.tasks.poll_team_shared_channels.delay")
+class TestPollFanout(BaseTest):
+ def test_fans_out_only_teams_with_shared_channels(self, mock_delay: MagicMock) -> None:
+ # Team with a shared channel -> fanned out.
+ self.team.conversations_settings = {
+ "teams_enabled": True,
+ "teams_channels": [{"channel_id": CHANNEL_ID, "team_id": TEAMS_TEAM_ID, "membership_type": "shared"}],
+ }
+ self.team.save()
+ TeamConversationsTeamsConfig.objects.update_or_create(
+ team=self.team,
+ defaults={"teams_tenant_id": "tenant-abc", "teams_graph_access_token": "graph-tok"},
+ )
+
+ poll_teams_shared_channels()
+
+ mock_delay.assert_called_once_with(self.team.id)
+
+ def test_skips_team_with_only_standard_channels(self, mock_delay: MagicMock) -> None:
+ self.team.conversations_settings = {
+ "teams_enabled": True,
+ "teams_channels": [{"channel_id": CHANNEL_ID, "team_id": TEAMS_TEAM_ID, "membership_type": "standard"}],
+ }
+ self.team.save()
+ TeamConversationsTeamsConfig.objects.update_or_create(
+ team=self.team,
+ defaults={"teams_tenant_id": "tenant-abc", "teams_graph_access_token": "graph-tok"},
+ )
+
+ poll_teams_shared_channels()
+
+ mock_delay.assert_not_called()
diff --git a/products/conversations/backend/migrations/0038_teamconversationsteamsconfig_teams_service_url_and_more.py b/products/conversations/backend/migrations/0038_teamconversationsteamsconfig_teams_service_url_and_more.py
new file mode 100644
index 000000000000..6803ae16263f
--- /dev/null
+++ b/products/conversations/backend/migrations/0038_teamconversationsteamsconfig_teams_service_url_and_more.py
@@ -0,0 +1,57 @@
+# Generated by Django 5.2.14 on 2026-06-18 13:16
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("conversations", "0037_emailoutboxmessage"),
+ ("posthog", "1226_identityproviderconfig_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="teamconversationsteamsconfig",
+ name="teams_service_url",
+ field=models.CharField(blank=True, max_length=512, null=True),
+ ),
+ migrations.CreateModel(
+ name="TeamConversationsTeamsChannelSync",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("teams_team_id", models.CharField(max_length=255)),
+ ("channel_id", models.CharField(max_length=255)),
+ ("delta_link", models.TextField(blank=True, null=True)),
+ ("primed", models.BooleanField(default=False)),
+ ("last_polled_at", models.DateTimeField(blank=True, null=True)),
+ ("last_message_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_conversations_teams_channel_sync",
+ "indexes": [models.Index(fields=["team"], name="conv_teams_chan_sync_team_idx")],
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team", "channel_id"),
+ name="unique_teams_channel_sync_per_team",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txt
index 972dba1501fe..aa32bf37cec9 100644
--- a/products/conversations/backend/migrations/max_migration.txt
+++ b/products/conversations/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0037_emailoutboxmessage
+0038_teamconversationsteamsconfig_teams_service_url_and_more
diff --git a/products/conversations/backend/models/__init__.py b/products/conversations/backend/models/__init__.py
index 8bf5316afee8..5dba61014c8a 100644
--- a/products/conversations/backend/models/__init__.py
+++ b/products/conversations/backend/models/__init__.py
@@ -6,6 +6,7 @@ from .github_comment_mapping import GithubCommentMapping
from .restore_token import ConversationRestoreToken
from .team_conversations_email_config import EmailChannel
from .team_conversations_slack_config import TeamConversationsSlackConfig
+from .team_conversations_teams_channel_sync import TeamConversationsTeamsChannelSync
from .team_conversations_teams_config import TeamConversationsTeamsConfig
from .ticket import Ticket
from .ticket_view import TicketView
@@ -22,6 +23,7 @@ __all__ = [
"RuleType",
"Status",
"TeamConversationsSlackConfig",
+ "TeamConversationsTeamsChannelSync",
"TeamConversationsTeamsConfig",
"Ticket",
"TicketAssignment",
diff --git a/products/conversations/backend/models/team_conversations_teams_channel_sync.py b/products/conversations/backend/models/team_conversations_teams_channel_sync.py
new file mode 100644
index 000000000000..71b3e39f152c
--- /dev/null
+++ b/products/conversations/backend/models/team_conversations_teams_channel_sync.py
@@ -0,0 +1,43 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+
+class TeamConversationsTeamsChannelSync(TeamScopedRootMixin, UUIDModel):
+ """Per-channel Microsoft Graph delta-sync state for shared-channel polling.
+
+ Shared (and private) Teams channels never push ambient messages over the bot
+ webhook, so we pull them from Graph's per-channel ``messages/delta`` endpoint
+ on a schedule. This row tracks where each channel's delta cursor is so each
+ poll only fetches messages posted since the last run.
+
+ Kept out of ``Team.conversations_settings`` so the every-minute poller's cursor
+ writes don't contend with the settings blob and survive channel add/remove.
+ """
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
+ teams_team_id = models.CharField(max_length=255)
+ channel_id = models.CharField(max_length=255)
+
+ # Opaque Graph @odata.deltaLink for the next poll. Null until first primed.
+ delta_link = models.TextField(null=True, blank=True)
+ # Once True, the initial walk-to-deltaLink has completed and we ingest new
+ # messages. The priming pass itself creates no tickets (no history dump).
+ primed = models.BooleanField(default=False)
+
+ last_polled_at = models.DateTimeField(null=True, blank=True)
+ last_message_at = models.DateTimeField(null=True, blank=True)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ app_label = "conversations"
+ db_table = "posthog_conversations_teams_channel_sync"
+ constraints = [
+ models.UniqueConstraint(fields=["team", "channel_id"], name="unique_teams_channel_sync_per_team"),
+ ]
+ indexes = [
+ models.Index(fields=["team"], name="conv_teams_chan_sync_team_idx"),
+ ]
diff --git a/products/conversations/backend/models/team_conversations_teams_config.py b/products/conversations/backend/models/team_conversations_teams_config.py
index 81bfc8e6c328..a76125c21764 100644
--- a/products/conversations/backend/models/team_conversations_teams_config.py
+++ b/products/conversations/backend/models/team_conversations_teams_config.py
@@ -17,6 +17,11 @@ class TeamConversationsTeamsConfig(models.Model):
teams_graph_refresh_token = EncryptedTextField(max_length=4000, null=True, blank=True)
teams_token_expires_at = models.DateTimeField(null=True, blank=True)
+ # Tenant's Bot Framework serviceUrl, captured from inbound webhook activities.
+ # The shared-channel poller has no inbound activity of its own, so it reuses
+ # this to post confirmation cards and route agent replies for polled tickets.
+ teams_service_url = models.CharField(max_length=512, null=True, blank=True)
+
class Meta:
app_label = "conversations"
db_table = "posthog_conversations_teams_config"
diff --git a/products/conversations/backend/support_teams.py b/products/conversations/backend/support_teams.py
index 3b4386d3c954..ed7cf5f2be50 100644
--- a/products/conversations/backend/support_teams.py
+++ b/products/conversations/backend/support_teams.py
@@ -70,7 +70,13 @@ JWT_CLOCK_TOLERANCE_SECONDS = 5 * 60
# to avoid Azure AD scope-mismatch errors. TeamsAppInstallation.ReadWriteForTeam
# is deliberately omitted here — that's requested at authorize time but we don't
# need it on refresh for Graph user/channel reads.
-GRAPH_REFRESH_SCOPES = "Team.ReadBasic.All Channel.ReadBasic.All User.ReadBasic.All offline_access openid profile"
+#
+# ChannelMessage.Read.All (delegated) powers the shared-channel message poller:
+# shared/private channels never push ambient messages over the bot webhook, so we
+# pull them from Graph's per-channel messages/delta as the connecting admin.
+GRAPH_REFRESH_SCOPES = (
+ "Team.ReadBasic.All Channel.ReadBasic.All User.ReadBasic.All ChannelMessage.Read.All offline_access openid profile"
+)
def get_teams_instance_settings() -> dict:
@@ -429,6 +435,25 @@ def get_graph_token(team: Team) -> str:
pass
+def store_teams_service_url(tenant_id: str, service_url: str) -> None:
+ """Persist the tenant's Bot Framework serviceUrl on its Teams config.
+
+ The shared-channel poller pulls messages from Graph and has no inbound
+ activity to read serviceUrl from, so it reuses this value — captured here
+ from any inbound webhook activity (install welcome, help command, mention,
+ or channel message) — to post confirmation cards and route agent replies.
+
+ Writes only when the value changes (≈once per tenant) and is a no-op for
+ tenants without a config row (e.g. AppSource validators pre-OAuth).
+ """
+ service_url = (service_url or "").rstrip("/")
+ if not tenant_id or not service_url or not is_trusted_teams_service_url(service_url):
+ return
+ TeamConversationsTeamsConfig.objects.filter(teams_tenant_id=tenant_id).exclude(
+ teams_service_url=service_url
+ ).update(teams_service_url=service_url)
+
+
def save_teams_token(
*,
team: Team,
diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.py
index 5a11f5f31879..8a7fb309dc68 100644
--- a/products/conversations/backend/tasks.py
+++ b/products/conversations/backend/tasks.py
@@ -1,7 +1,7 @@
"""Celery tasks for the conversations product."""
import html as html_mod
-from datetime import timedelta
+from datetime import datetime, timedelta
from email.utils import formataddr
from typing import Any, cast
from urllib.parse import quote, urlparse
@@ -43,9 +43,10 @@ from products.conversations.backend.models import (
EmailOutboxMessage,
GithubCommentMapping,
TeamConversationsSlackConfig,
+ TeamConversationsTeamsChannelSync,
TeamConversationsTeamsConfig,
)
-from products.conversations.backend.models.constants import Status
+from products.conversations.backend.models.constants import ChannelDetail, Status
from products.conversations.backend.models.ticket import Ticket
from products.conversations.backend.slack import (
get_slack_client,
@@ -59,11 +60,16 @@ from products.conversations.backend.slack import (
from products.conversations.backend.support_teams import (
get_bot_framework_token,
get_bot_from_id,
+ get_graph_token,
invalidate_bot_framework_token,
is_trusted_teams_service_url,
+ store_teams_service_url,
)
from products.conversations.backend.teams import (
+ GRAPH_API_BASE,
_is_bot_mention,
+ create_or_update_teams_ticket,
+ graph_message_to_activity,
handle_teams_mention,
handle_teams_message,
post_help_card,
@@ -684,6 +690,15 @@ def send_teams_help(self, activity: dict[str, Any], reply: bool = False) -> None
``reply=True`` lands the card as a thread reply (response to a "Hi"/"Help"
command); ``reply=False`` is the proactive welcome on install.
"""
+ # Capture the tenant's serviceUrl as early as install — this is often the
+ # only inbound activity a pure-ambient shared-channel tenant ever sends, and
+ # the poller needs it to post confirmation cards / sync agent replies.
+ tenant_id = ((activity.get("channelData") or {}).get("tenant") or {}).get("id") or ""
+ try:
+ store_teams_service_url(tenant_id, activity.get("serviceUrl") or "")
+ except Exception:
+ pass
+
try:
ok = post_help_card(
activity,
@@ -721,6 +736,14 @@ def process_teams_event(activity: dict[str, Any], tenant_id: str, activity_id: s
logger.info("supporthog_teams_not_configured", team_id=team.id, tenant_id=tenant_id)
return
+ # Capture the tenant's Bot Framework serviceUrl from any inbound activity so
+ # the shared-channel poller (which has no inbound activity) can post
+ # confirmation cards and route agent replies for polled tickets.
+ try:
+ store_teams_service_url(tenant_id, activity.get("serviceUrl") or "")
+ except Exception:
+ logger.warning("store_teams_service_url_failed", team_id=team.id, tenant_id=tenant_id)
+
try:
if _is_bot_mention(activity):
handle_teams_mention(activity, team, tenant_id)
@@ -805,6 +828,251 @@ def post_reply_to_teams(
raise cast(Any, post_reply_to_teams).retry(exc=e)
+def _shared_channel_entries(support_settings: dict) -> list[dict]:
+ """Configured channels flagged as shared (the only ones the poller pulls)."""
+ entries = support_settings.get("teams_channels")
+ if not isinstance(entries, list):
+ return []
+ return [e for e in entries if isinstance(e, dict) and e.get("membership_type") == "shared"]
+
+
+def _parse_graph_datetime(value: str | None) -> datetime | None:
+ if not value:
+ return None
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except (ValueError, AttributeError, TypeError):
+ return None
+
+
+# Bound the work per invocation so priming a long-lived channel (the first delta
+# walk returns the channel's full history before the deltaLink) can't hammer Graph
+# in a single run. Remaining pages resume on subsequent every-minute runs.
+TEAMS_DELTA_MAX_PAGES_PER_RUN = 20
+TEAMS_DELTA_REQUEST_TIMEOUT_SECONDS = 30
+
+
+def _poll_one_shared_channel(
+ *,
+ team: Team,
+ tenant_id: str,
+ token: str,
+ teams_team_id: str,
+ channel_id: str,
+ service_url: str,
+) -> None:
+ """Pull new top-level messages for one shared channel via Graph messages/delta.
+
+ First run for a channel primes the delta cursor without ingesting (no history
+ dump); subsequent runs map each new root message onto the existing ticket path.
+ Idempotency is handled by ``create_or_update_teams_ticket`` (dedup on
+ channel + normalized conversation id), so re-delivering a message is a no-op.
+ """
+ sync, created = TeamConversationsTeamsChannelSync.objects.for_team(team.id).get_or_create(
+ channel_id=channel_id,
+ defaults={"team": team, "teams_team_id": teams_team_id},
+ )
+
+ # On first encounter, verify via Graph that the channel is actually shared.
+ # conversations_settings is client-mutable, so we don't trust its
+ # membership_type — we confirm from the authoritative source before polling.
+ if created:
+ ch_resp = requests.get(
+ f"{GRAPH_API_BASE}/teams/{teams_team_id}/channels/{channel_id}",
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TEAMS_DELTA_REQUEST_TIMEOUT_SECONDS,
+ )
+ if ch_resp.status_code != 200 or ch_resp.json().get("membershipType") != "shared":
+ logger.warning(
+ "poll_teams_shared_channel_not_shared",
+ team_id=team.id,
+ channel_id=channel_id,
+ status=ch_resp.status_code,
+ )
+ sync.delete()
+ return
+
+ url: str | None = sync.delta_link or (
+ f"{GRAPH_API_BASE}/teams/{teams_team_id}/channels/{channel_id}/messages/delta"
+ )
+ headers = {"Authorization": f"Bearer {token}"}
+
+ new_delta_link: str | None = None
+ latest_message_at: datetime | None = None
+ pages = 0
+
+ while url and pages < TEAMS_DELTA_MAX_PAGES_PER_RUN:
+ pages += 1
+ resp = requests.get(url, headers=headers, timeout=TEAMS_DELTA_REQUEST_TIMEOUT_SECONDS)
+
+ if resp.status_code == 410:
+ # Delta token expired/invalid: reset and re-prime on the next run.
+ sync.delta_link = None
+ sync.primed = False
+ sync.last_polled_at = timezone.now()
+ sync.save(update_fields=["delta_link", "primed", "last_polled_at", "updated_at"])
+ logger.info("poll_teams_shared_channel_resync", team_id=team.id, channel_id=channel_id)
+ return
+ if resp.status_code == 429:
+ logger.warning("poll_teams_shared_channel_throttled", team_id=team.id, channel_id=channel_id)
+ return
+ if resp.status_code in (401, 402, 403):
+ # 401: token rejected (next run refreshes if stale). 402: metered/payment
+ # gate. 403: lost channel membership / missing scope. Skip, don't crash.
+ logger.warning(
+ "poll_teams_shared_channel_denied",
+ team_id=team.id,
+ channel_id=channel_id,
+ status=resp.status_code,
+ )
+ return
+ if resp.status_code != 200:
+ logger.warning(
+ "poll_teams_shared_channel_error",
+ team_id=team.id,
+ channel_id=channel_id,
+ status=resp.status_code,
+ )
+ return
+
+ data = resp.json()
+ messages = data.get("value") or []
+
+ if sync.primed:
+ for msg in messages:
+ msg_created = _parse_graph_datetime(msg.get("createdDateTime"))
+ if msg_created and (latest_message_at is None or msg_created > latest_message_at):
+ latest_message_at = msg_created
+ activity = graph_message_to_activity(msg, channel_id, service_url)
+ if activity is None:
+ continue
+ try:
+ create_or_update_teams_ticket(
+ team=team,
+ activity=activity,
+ tenant_id=tenant_id,
+ is_thread_reply=False,
+ channel_detail=ChannelDetail.TEAMS_CHANNEL_MESSAGE,
+ )
+ except Exception:
+ logger.exception(
+ "poll_teams_shared_channel_ingest_failed",
+ team_id=team.id,
+ channel_id=channel_id,
+ )
+
+ delta_link = data.get("@odata.deltaLink")
+ next_link = data.get("@odata.nextLink")
+ if delta_link:
+ new_delta_link = delta_link
+ url = None
+ else:
+ url = next_link
+
+ update_fields = ["last_polled_at", "updated_at"]
+ sync.last_polled_at = timezone.now()
+
+ if new_delta_link:
+ sync.delta_link = new_delta_link
+ update_fields.append("delta_link")
+ if not sync.primed:
+ sync.primed = True
+ update_fields.append("primed")
+ elif url:
+ # Hit the per-run page budget mid-walk; resume from this nextLink next run.
+ sync.delta_link = url
+ update_fields.append("delta_link")
+
+ if latest_message_at and (sync.last_message_at is None or latest_message_at > sync.last_message_at):
+ sync.last_message_at = latest_message_at
+ update_fields.append("last_message_at")
+
+ sync.save(update_fields=update_fields)
+
+
+@shared_task(ignore_result=True)
+@skip_team_scope_audit
+def poll_team_shared_channels(team_id: int) -> None:
+ """Poll every configured shared channel for one team."""
+ team = Team.objects.filter(id=team_id).first()
+ if not team:
+ return
+
+ support_settings = team.conversations_settings or {}
+ if not support_settings.get("teams_enabled"):
+ return
+
+ shared_channels = _shared_channel_entries(support_settings)
+ if not shared_channels:
+ return
+
+ config = TeamConversationsTeamsConfig.objects.filter(team=team).first()
+ tenant_id = config.teams_tenant_id if config else None
+ if not tenant_id:
+ logger.warning("poll_teams_shared_channels_no_tenant", team_id=team_id)
+ return
+
+ try:
+ token = get_graph_token(team)
+ except ValueError:
+ logger.warning("poll_teams_shared_channels_no_token", team_id=team_id)
+ return
+
+ # serviceUrl is captured from inbound webhook activities (install/mention).
+ # Empty until then: polled tickets still get created, but confirmation cards
+ # and agent-reply sync stay dormant until the first inbound activity fills it.
+ service_url = (config.teams_service_url or "") if config else ""
+
+ for entry in shared_channels:
+ channel_id = entry.get("channel_id")
+ teams_team_id = entry.get("team_id")
+ if not channel_id or not teams_team_id:
+ continue
+ try:
+ _poll_one_shared_channel(
+ team=team,
+ tenant_id=tenant_id,
+ token=token,
+ teams_team_id=teams_team_id,
+ channel_id=channel_id,
+ service_url=service_url,
+ )
+ except requests.RequestException:
+ logger.warning("poll_teams_shared_channel_network_error", team_id=team_id, channel_id=channel_id)
+ except Exception:
+ logger.exception("poll_teams_shared_channel_unexpected", team_id=team_id, channel_id=channel_id)
+
+
+@shared_task(ignore_result=True)
+@skip_team_scope_audit
+def poll_teams_shared_channels() -> None:
+ """Fan out per-team shared-channel polling.
+
+ Shared/private Teams channels never push ambient (non-@mention) messages over
+ the bot webhook, so we pull them from Graph on a schedule. One subtask per team
+ keeps a slow or rate-limited tenant from blocking the others.
+ """
+ configs = (
+ TeamConversationsTeamsConfig.objects.filter(teams_graph_access_token__isnull=False)
+ .select_related("team")
+ .only("team__id", "team__conversations_settings", "teams_tenant_id")
+ )
+
+ team_ids: list[int] = []
+ for config in configs:
+ support_settings = config.team.conversations_settings or {}
+ if not support_settings.get("teams_enabled"):
+ continue
+ if _shared_channel_entries(support_settings):
+ team_ids.append(config.team_id)
+
+ for team_id in team_ids:
+ poll_team_shared_channels.delay(team_id)
+
+ if team_ids:
+ logger.info("poll_teams_shared_channels_fanout", team_count=len(team_ids))
+
+
WAKE_SNOOZE_BATCH_SIZE = 100
diff --git a/products/conversations/backend/teams.py b/products/conversations/backend/teams.py
index 46cb0b2b18d6..932956edc62d 100644
--- a/products/conversations/backend/teams.py
+++ b/products/conversations/backend/teams.py
@@ -705,3 +705,55 @@ def handle_teams_mention(activity: dict, team: Team, tenant_id: str) -> None:
is_thread_reply=existing,
channel_detail=ChannelDetail.TEAMS_BOT_MENTION,
)
+
+
+def graph_message_to_activity(msg: dict, channel_id: str, service_url: str) -> dict | None:
+ """Map a Microsoft Graph ``chatMessage`` (from channel ``messages/delta``) to the
+ Bot Framework activity shape that ``create_or_update_teams_ticket`` consumes.
+
+ Returns ``None`` for anything we don't ingest as a top-level support message:
+ non-message types (system events), deletions, replies, empty bodies, and
+ system/bot/app-authored posts (no ``from.user``). The mapped activity uses the
+ canonical ``"<channelId>;messageid=<msgId>"`` conversation id so a later webhook
+ reply on the same thread dedupes onto the same ticket.
+ """
+ # Only real user messages: skip systemEventMessage, typing, etc.
+ if msg.get("messageType") != "message":
+ return None
+ if msg.get("deletedDateTime"):
+ return None
+ # Channel messages/delta returns root messages only; guard defensively in case
+ # a reply ever shows up (reply sync is out of v1 scope).
+ if msg.get("replyToId"):
+ return None
+
+ body = msg.get("body") or {}
+ content = body.get("content") or ""
+ if not content.strip():
+ return None
+
+ # System/bot/app posts (incl. our own confirmation cards) carry from.application
+ # or from.device, never from.user — skip them so we never self-ingest.
+ from_field = msg.get("from") or {}
+ user = from_field.get("user") or {}
+ aad_object_id = user.get("id")
+ if not aad_object_id:
+ return None
+
+ msg_id = msg.get("id")
+ if not msg_id:
+ return None
+
+ return {
+ "id": msg_id,
+ "type": "message",
+ "text": content,
+ "from": {
+ "id": aad_object_id,
+ "aadObjectId": aad_object_id,
+ "name": user.get("displayName") or "",
+ },
+ "conversation": {"id": f"{channel_id};messageid={msg_id}"},
+ "channelData": {"channel": {"id": channel_id}},
+ "serviceUrl": service_url,
+ }
diff --git a/products/conversations/frontend/scenes/settings/TeamsSection.tsx b/products/conversations/frontend/scenes/settings/TeamsSection.tsx
index 2224117a50ad..5aff9a4c80a6 100644
--- a/products/conversations/frontend/scenes/settings/TeamsSection.tsx
+++ b/products/conversations/frontend/scenes/settings/TeamsSection.tsx
@@ -2,7 +2,16 @@ import { useActions, useValues } from 'kea'
import { useState } from 'react'
import { IconTrash } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonCard, LemonDivider, LemonSelect, LemonTag, Link } from '@posthog/lemon-ui'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonCard,
+ LemonDivider,
+ LemonSelect,
+ LemonTag,
+ Link,
+ Tooltip,
+} from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { OrganizationMembershipLevel } from 'lib/constants'
@@ -34,18 +43,34 @@ export function TeamsSection(): JSX.Element {
}
interface TeamsChannelRowProps {
- pair: { team_id: string; team_name?: string | null; channel_id: string; channel_name?: string | null }
+ pair: {
+ team_id: string
+ team_name?: string | null
+ channel_id: string
+ channel_name?: string | null
+ membership_type?: string | null
+ }
onRemove: () => void
isLoading: boolean
adminRestrictionReason: string | null
}
function TeamsChannelRow({ pair, onRemove, isLoading, adminRestrictionReason }: TeamsChannelRowProps): JSX.Element {
+ const isShared = pair.membership_type === 'shared'
return (
<div className="flex items-center justify-between gap-2 py-2 px-3 border rounded">
<div className="flex-1 min-w-0">
<div className="font-medium truncate">{pair.team_name || pair.team_id}</div>
- <div className="text-xs text-muted-alt truncate">#{pair.channel_name || pair.channel_id}</div>
+ <div className="flex items-center gap-2">
+ <div className="text-xs text-muted-alt truncate">#{pair.channel_name || pair.channel_id}</div>
+ {isShared && (
+ <Tooltip title="Shared channels don't push messages to bots, so PostHog polls them via Microsoft Graph every minute to pick up new messages.">
+ <LemonTag type="completion" size="small">
+ Shared · polled
+ </LemonTag>
+ </Tooltip>
+ )}
+ </div>
</div>
<LemonButton
icon={<IconTrash />}
@@ -178,10 +203,12 @@ function AddTeamsChannelRow({ adminRestrictionReason }: AddTeamsChannelRowProps)
value={null}
options={[
{ value: null, label: 'Select channel...' },
- ...selectedTeamChannels.map((c: { id: string; name: string }) => ({
- value: c.id,
- label: `#${c.name}`,
- })),
+ ...selectedTeamChannels.map(
+ (c: { id: string; name: string; membership_type?: string | null }) => ({
+ value: c.id,
+ label: c.membership_type === 'shared' ? `#${c.name} (shared)` : `#${c.name}`,
+ })
+ ),
]}
onChange={handleChannelSelect}
loading={teamsChannelsLoading || !!teamsChannelPairLoading}
diff --git a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
index a5335287bdf9..43ea5bc43df6 100644
--- a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
+++ b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
@@ -78,7 +78,10 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
addTeamsChannelPair: (teamId: string, channelId: string) => ({ teamId, channelId }),
removeTeamsChannelPair: (channelId: string) => ({ channelId }),
setTeamsChannelPairLoading: (channelId: string | null) => ({ channelId }),
- cacheTeamsChannelsForTeam: (teamId: string, channels: { id: string; name: string }[]) => ({ teamId, channels }),
+ cacheTeamsChannelsForTeam: (
+ teamId: string,
+ channels: { id: string; name: string; membership_type?: string | null }[]
+ ) => ({ teamId, channels }),
// Email channel settings (multi-config)
loadEmailConfigs: true,
loadEmailConfigsDone: (configs: EmailConfigStatus[]) => ({ configs }),
@@ -251,7 +254,7 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
},
],
teamsChannelsCache: [
- {} as Record<string, { id: string; name: string }[]>,
+ {} as Record<string, { id: string; name: string; membership_type?: string | null }[]>,
{
cacheTeamsChannelsForTeam: (state, { teamId, channels }) => ({ ...state, [teamId]: channels }),
disconnectTeams: () => ({}),
@@ -357,7 +360,7 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
},
],
teamsChannels: [
- [] as { id: string; name: string }[],
+ [] as { id: string; name: string; membership_type?: string | null }[],
{
loadTeamsChannelsForTeam: async ({ teamId }: { teamId: string }) => {
try {
@@ -453,7 +456,13 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
(s) => [s.currentTeam],
(
currentTeam
- ): { team_id: string; team_name?: string | null; channel_id: string; channel_name?: string | null }[] => {
+ ): {
+ team_id: string
+ team_name?: string | null
+ channel_id: string
+ channel_name?: string | null
+ membership_type?: string | null
+ }[] => {
const cs = currentTeam?.conversations_settings
if (Array.isArray(cs?.teams_channels) && cs.teams_channels.length > 0) {
return cs.teams_channels