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: Debug UI/logic for agentic runs from Slack (#60458)

Alex Lebedev6b3f849647fe
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 68804d0321d7..59cf4b1e4f05 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5005,8 +5005,8 @@ const api = {
async repositories(): Promise<{ repositories: string[] }> {
return await new ApiRequest().tasks().withAction('repositories').get()
},
- async get(id: Task['id']): Promise<Task> {
- return await new ApiRequest().task(id).get()
+ async get(id: Task['id'], params: Record<string, any> = {}): Promise<Task> {
+ return await new ApiRequest().task(id).withQueryString(params).get()
},
async create(data: TaskUpsertProps): Promise<Task> {
return await new ApiRequest().tasks().create({ data })
@@ -5024,11 +5024,11 @@ const api = {
return await new ApiRequest().task(id).withAction('run').create()
},
runs: {
- async list(taskId: Task['id']): Promise<PaginatedResponse<TaskRun>> {
- return await new ApiRequest().taskRuns(taskId).get()
+ async list(taskId: Task['id'], params: Record<string, any> = {}): Promise<PaginatedResponse<TaskRun>> {
+ return await new ApiRequest().taskRuns(taskId).withQueryString(params).get()
},
- async get(taskId: Task['id'], runId: TaskRun['id']): Promise<TaskRun> {
- return await new ApiRequest().taskRun(taskId, runId).get()
+ async get(taskId: Task['id'], runId: TaskRun['id'], params: Record<string, any> = {}): Promise<TaskRun> {
+ return await new ApiRequest().taskRun(taskId, runId).withQueryString(params).get()
},
async getLogs(taskId: Task['id'], runId: TaskRun['id']): Promise<string> {
const run = await new ApiRequest().taskRun(taskId, runId).get()
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 05a381313a5a..ffb0720a8099 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -137,6 +137,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
SessionGroupSummary: () => import('../../products/session_summaries/frontend/SessionGroupSummaryScene'),
TaskTracker: () => import('../../products/tasks/frontend/TaskTracker'),
TaskDetail: () => import('../../products/tasks/frontend/TaskDetailScene'),
+ SlackTaskContext: () => import('../../products/tasks/frontend/SlackTaskContextScene'),
Tracing: () => import('../../products/tracing/frontend/TracingScene'),
UserInterviews: () => import('../../products/user_interviews/frontend/UserInterviews'),
UserInterview: () => import('../../products/user_interviews/frontend/UserInterview'),
@@ -261,6 +262,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/session-summaries/:sessionGroupId': ['SessionGroupSummary', 'sessionGroupSummary'],
'/tasks': ['TaskTracker', 'taskTracker'],
'/tasks/:taskId': ['TaskDetail', 'taskDetail'],
+ '/slack-task-context': ['SlackTaskContext', 'slackTaskContext'],
'/tracing': ['Tracing', 'tracing'],
'/user_research': ['UserInterviews', 'userInterviews'],
'/user_research/:topicId/response/:responseId': ['UserInterviewResponse', 'userInterviewResponse'],
@@ -743,6 +745,7 @@ export const productConfiguration: Record<string, any> = {
iconType: 'task',
},
TaskDetail: { name: 'Task', projectBased: true, activityScope: 'TaskDetail' },
+ SlackTaskContext: { name: 'Slack task context', projectBased: true },
Toolbar: {
name: 'Toolbar',
projectBased: true,
@@ -1171,6 +1174,7 @@ export const productUrls = {
`/surveys/guided/${id}${template ? `?template=${encodeURIComponent(template)}` : ''}`,
taskTracker: (): string => '/tasks',
taskDetail: (taskId: string | number): string => `/tasks/${taskId}`,
+ slackTaskContext: (): string => '/slack-task-context',
toolbarLaunch: (): string => '/toolbar',
tracing: (): string => '/tracing',
userInterviews: (): string => '/user_research',
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index e7fb1f994c9d..22ccbf3db763 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -208,6 +208,7 @@ export enum Scene {
NewAction = 'NewAction',
TaskDetail = 'TaskDetail',
TaskTracker = 'TaskTracker',
+ SlackTaskContext = 'SlackTaskContext',
OrganizationDeactivated = 'OrganizationDeactivated',
OrganizationPendingDeletion = 'OrganizationPendingDeletion',
CustomerJourneyTemplates = 'CustomerJourneyTemplates',
diff --git a/posthog/clickhouse/test/test_dmat_dictionary.py b/posthog/clickhouse/test/test_dmat_dictionary.py
index fa1716f6b02a..e5a9d9caef52 100644
--- a/posthog/clickhouse/test/test_dmat_dictionary.py
+++ b/posthog/clickhouse/test/test_dmat_dictionary.py
@@ -13,6 +13,8 @@ dict round-trip the mutation builder relies on.
import uuid
+import pytest
+
from posthog.clickhouse.client import sync_execute
from posthog.models.dmat_slot_assignments.sql import (
DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME,
@@ -21,6 +23,10 @@ from posthog.models.dmat_slot_assignments.sql import (
TRUNCATE_DMAT_SLOT_ASSIGNMENTS_SQL,
)
+# django_db_setup (posthog/conftest.py) creates the ClickHouse test DB; without
+# this marker the file never triggers it when sharded onto a runner alone.
+pytestmark = pytest.mark.django_db
+
def _populate(rows: list[tuple[int, int, str]]) -> None:
sync_execute(TRUNCATE_DMAT_SLOT_ASSIGNMENTS_SQL())
diff --git a/posthog/temporal/ai/posthog_code_slack_mention.py b/posthog/temporal/ai/posthog_code_slack_mention.py
index c09fe99039c0..9f5cfde03936 100644
--- a/posthog/temporal/ai/posthog_code_slack_mention.py
+++ b/posthog/temporal/ai/posthog_code_slack_mention.py
@@ -23,7 +23,7 @@ from products.slack_app.backend.slack_thread import (
ack_emoji_for,
stale_ack_emojis_for,
)
-from products.tasks.backend.models import Task
+from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.repo_selection import (
RepoSelectionRejectedError,
RepoSelectionUnavailableError,
@@ -168,6 +168,18 @@ class PostHogCodeSlackMentionWorkflowInputs:
event: dict[str, Any]
integration_id: int
slack_team_id: str
+ # Event that dispatched the workflow
+ slack_event_id: str | None = None
+
+
+def derive_mention_workflow_id(inputs: "PostHogCodeSlackMentionWorkflowInputs") -> str:
+ """Construct the dispatch workflow id from webhook inputs."""
+ event = inputs.event
+ if inputs.slack_event_id:
+ suffix = inputs.slack_event_id
+ else:
+ suffix = f"{event.get('channel', '')}:{event.get('ts', '')}"
+ return f"posthog-code-mention-{inputs.slack_team_id}:{suffix}"
@dataclass
@@ -202,11 +214,16 @@ class SlackRepoSelectionOutcome:
`found` → use `repository`. `no_match` → no plausible candidate, create a
no-repo task. `failed` → agent crashed/timed out/hallucinated, fall back to
the interactive repo picker so the user can resolve manually.
+
+ `repo_research_task_id`/`repo_research_run_id` point at the internal sandbox
+ run the repo discovery agent spun up to make this call.
"""
status: Literal["found", "no_match", "failed"]
repository: str | None
reason: str
+ repo_research_task_id: str | None = None
+ repo_research_run_id: str | None = None
@dataclass
@@ -356,6 +373,9 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
# once all pre-rollout workflows have drained — they live at most
# ~25 minutes (activity timeouts + picker wait).
repository: str | None
+ # Set only on the ambiguous path that runs the discovery sandbox
+ repo_research_task_id: str | None = None
+ repo_research_run_id: str | None = None
if workflow.patched("posthog-code-repo-discovery-agent-2026-05"):
cascade = await _execute_posthog_code_activity(
cascade_posthog_code_repository_activity,
@@ -387,6 +407,8 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
thread_messages,
user_id,
)
+ repo_research_task_id = outcome.repo_research_task_id
+ repo_research_run_id = outcome.repo_research_run_id
if outcome.status == "found":
repository = outcome.repository
@@ -514,6 +536,8 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
event,
thread_messages,
repository,
+ repo_research_task_id,
+ repo_research_run_id,
)
except Exception as exc:
workflow.logger.exception(
@@ -760,6 +784,13 @@ async def discover_posthog_code_repository_via_agent_activity(
# selector. The selector is domain-agnostic; the caller serializes.
context_block = "\n".join(f"{msg['user']}: {msg['text']}" for msg in thread_messages)
+ # Captured even when select_repository later raises
+ research_ids: dict[str, str] = {}
+
+ def _capture_research_session(task_id: str, run_id: str) -> None:
+ research_ids["task_id"] = task_id
+ research_ids["run_id"] = run_id
+
try:
async with Heartbeater():
result = await select_repository(
@@ -767,6 +798,7 @@ async def discover_posthog_code_repository_via_agent_activity(
user_id=user_id,
context=context_block,
origin_product=Task.OriginProduct.SLACK,
+ on_research_session=_capture_research_session,
)
except RepoSelectionRejectedError as exc:
logger.warning(
@@ -780,6 +812,8 @@ async def discover_posthog_code_repository_via_agent_activity(
repository=None,
# Don't echo `exc.returned_repository` — it's raw LLM output and reaches Slack mrkdwn.
reason="Agent returned an unrecognized repository.",
+ repo_research_task_id=research_ids.get("task_id"),
+ repo_research_run_id=research_ids.get("run_id"),
)
except RepoSelectionUnavailableError as exc:
logger.warning(
@@ -791,6 +825,8 @@ async def discover_posthog_code_repository_via_agent_activity(
status="failed",
repository=None,
reason=f"Repo selection unavailable: {exc.reason}",
+ repo_research_task_id=research_ids.get("task_id"),
+ repo_research_run_id=research_ids.get("run_id"),
)
except Exception as exc:
logger.exception(
@@ -802,6 +838,8 @@ async def discover_posthog_code_repository_via_agent_activity(
status="failed",
repository=None,
reason=f"Agent failed: {type(exc).__name__}",
+ repo_research_task_id=research_ids.get("task_id"),
+ repo_research_run_id=research_ids.get("run_id"),
)
if result.repository is None:
@@ -809,11 +847,15 @@ async def discover_posthog_code_repository_via_agent_activity(
status="no_match",
repository=None,
reason=result.reason,
+ repo_research_task_id=research_ids.get("task_id"),
+ repo_research_run_id=research_ids.get("run_id"),
)
return SlackRepoSelectionOutcome(
status="found",
repository=result.repository,
reason=result.reason,
+ repo_research_task_id=research_ids.get("task_id"),
+ repo_research_run_id=research_ids.get("run_id"),
)
@@ -998,6 +1040,8 @@ def create_posthog_code_task_for_repo_activity(
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:
integration = Integration.objects.select_related("team", "team__organization").get(
id=inputs.integration_id,
@@ -1109,6 +1153,20 @@ def create_posthog_code_task_for_repo_activity(
"mentioning_slack_user_id": slack_user_id,
},
)
+ # Track the workflow to link Temporal jobs to Slack threads
+ state_updates: dict[str, str] = {"slack_mention_workflow_id": derive_mention_workflow_id(inputs)}
+ if repo_research_task_id and repo_research_run_id:
+ state_updates["repo_research_task_id"] = repo_research_task_id
+ state_updates["repo_research_run_id"] = repo_research_run_id
+ try:
+ TaskRun.update_state_atomic(task_run.id, updates=state_updates)
+ except Exception:
+ logger.exception(
+ "posthog_code_persist_mention_workflow_id_failed",
+ task_run_id=str(task_run.id),
+ channel=channel,
+ thread_ts=thread_ts,
+ )
# 3. Now start the workflow
if task and task_run:
@@ -1378,6 +1436,7 @@ def _resume_task_with_new_run(
extra_state["pending_user_message"] = initial_prompt_override
if user_message_ts:
extra_state["pending_user_message_ts"] = user_message_ts
+ extra_state["slack_mention_workflow_id"] = derive_mention_workflow_id(inputs)
try:
new_run = mapping.task.create_run(mode="interactive", extra_state=extra_state)
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 43a114eb7eb4..3a03ee62e443 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -38,6 +38,7 @@ from posthog.temporal.ai.posthog_code_slack_interactivity import (
from posthog.temporal.ai.posthog_code_slack_mention import (
PostHogCodeSlackMentionWorkflow,
PostHogCodeSlackMentionWorkflowInputs,
+ derive_mention_workflow_id,
)
from posthog.temporal.ai.posthog_code_slack_mention_command import (
PostHogCodeSlackMentionCommandWorkflow,
@@ -432,9 +433,9 @@ def resolve_slack_user(
)
return None
- if get_instance_region() == "DEV":
- # Dev region override for testing on any workspace (for Slack review team)
- slack_email = "[email protected]"
+ if settings.DEBUG:
+ # When running locally - match the local user
+ slack_email = "[email protected]"
# Trust model: Slack signature validation proves the payload is authentic.
# The email comes from Slack's `users.info` API via `users:read.email` scope, not from
@@ -1321,9 +1322,11 @@ def _start_posthog_code_workflow(
slack_team_id: str,
event: dict,
event_id: str | None,
+ workflow_id: str | None = None,
) -> None:
- fallback = event_id if event_id else f"{event.get('channel', '')}:{event.get('ts', '')}"
- workflow_id = f"{id_prefix}-{slack_team_id}:{fallback}"
+ 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}"
client = sync_connect()
asyncio.run(
client.start_workflow(
@@ -1441,17 +1444,22 @@ def _start_command_workflow(
def _start_mention_workflow(event: dict, integration: Integration, slack_team_id: str, event_id: str | None) -> str:
if _resolve_pending_repo_picker_from_followup(event, integration):
return ROUTE_HANDLED_LOCALLY
+ workflow_inputs = PostHogCodeSlackMentionWorkflowInputs(
+ event=event,
+ integration_id=integration.id,
+ slack_team_id=slack_team_id,
+ slack_event_id=event_id,
+ )
+ # 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(
PostHogCodeSlackMentionWorkflow,
- PostHogCodeSlackMentionWorkflowInputs(
- event=event,
- integration_id=integration.id,
- slack_team_id=slack_team_id,
- ),
+ workflow_inputs,
id_prefix="posthog-code-mention",
slack_team_id=slack_team_id,
event=event,
event_id=event_id,
+ workflow_id=derive_mention_workflow_id(workflow_inputs),
)
return ROUTE_HANDLED_LOCALLY
diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.py
index 804e375ba7b9..608ed438d8bc 100644
--- a/products/slack_app/backend/tests/test_followup_forwarding.py
+++ b/products/slack_app/backend/tests/test_followup_forwarding.py
@@ -181,6 +181,10 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert task.latest_run.state["interaction_origin"] == "slack"
assert task.latest_run.state["pr_authorship_mode"] == "bot"
+ # Mention-dispatch debug pointer persisted on the new run.
+ # No explicit envelope event_id → falls back to "<channel>:<ts>".
+ assert task.latest_run.state["slack_mention_workflow_id"] == "posthog-code-mention-T_SLACK:C123:1234.5678"
+
mock_execute_workflow.assert_called_once()
call_kwargs = mock_execute_workflow.call_args.kwargs
assert call_kwargs["task_id"] == str(task.id)
@@ -194,6 +198,93 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert mapping.task_id == task.id
assert mapping.task_run_id == task.latest_run.id
+ @patch("posthog.temporal.ai.posthog_code_slack_mention.execute_task_processing_workflow")
+ @patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")
+ def test_persists_explicit_event_id_in_workflow_id(self, mock_slack_cls, mock_execute_workflow):
+ mock_slack_instance = MagicMock()
+ mock_slack_instance.client.chat_getPermalink.return_value = {
+ "ok": True,
+ "permalink": "https://slack.example.com/thread",
+ }
+ mock_slack_cls.return_value = mock_slack_instance
+
+ inputs = PostHogCodeSlackMentionWorkflowInputs(
+ event={"channel": "C123", "ts": "1234.5678", "user": "U_ALICE", "text": "<@BOT> hi"},
+ integration_id=self.integration.id,
+ slack_team_id="T_SLACK",
+ slack_event_id="Ev01234567",
+ )
+ create_posthog_code_task_for_repo_activity(
+ inputs,
+ "C123",
+ "1234.5678",
+ "U_ALICE",
+ self.user.id,
+ inputs.event,
+ [{"user": "U_ALICE", "text": "hi"}],
+ None,
+ )
+
+ task = self.Task.objects.get(team=self.team)
+ assert task.latest_run.state["slack_mention_workflow_id"] == "posthog-code-mention-T_SLACK:Ev01234567"
+
+ @patch("posthog.temporal.ai.posthog_code_slack_mention.execute_task_processing_workflow")
+ @patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")
+ def test_persists_repo_research_ids_when_provided(self, mock_slack_cls, mock_execute_workflow):
+ mock_slack_instance = MagicMock()
+ mock_slack_instance.client.chat_getPermalink.return_value = {
+ "ok": True,
+ "permalink": "https://slack.example.com/thread",
+ }
+ mock_slack_cls.return_value = mock_slack_instance
+
+ inputs = _make_inputs(self.integration.id)
+ create_posthog_code_task_for_repo_activity(
+ inputs,
+ "C123",
+ "1234.5678",
+ "U_ALICE",
+ self.user.id,
+ inputs.event,
+ [{"user": "U_ALICE", "text": "investigate the flaky checkout test"}],
+ None,
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ )
+
+ task = self.Task.objects.get(team=self.team)
+ state = task.latest_run.state
+ assert state["repo_research_task_id"] == "11111111-1111-1111-1111-111111111111"
+ assert state["repo_research_run_id"] == "22222222-2222-2222-2222-222222222222"
+
+ @patch("posthog.temporal.ai.posthog_code_slack_mention.execute_task_processing_workflow")
+ @patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")
+ def test_no_repo_research_ids_when_not_provided(self, mock_slack_cls, mock_execute_workflow):
+ # The unambiguous path (explicit mention / cascade auto) never runs the
+ # discovery sandbox, so the keys must be absent rather than null.
+ mock_slack_instance = MagicMock()
+ mock_slack_instance.client.chat_getPermalink.return_value = {
+ "ok": True,
+ "permalink": "https://slack.example.com/thread",
+ }
+ mock_slack_cls.return_value = mock_slack_instance
+
+ inputs = _make_inputs(self.integration.id)
+ create_posthog_code_task_for_repo_activity(
+ inputs,
+ "C123",
+ "1234.5678",
+ "U_ALICE",
+ self.user.id,
+ inputs.event,
+ [{"user": "U_ALICE", "text": "just answer this, no repo needed"}],
+ None,
+ )
+
+ task = self.Task.objects.get(team=self.team)
+ assert "repo_research_task_id" not in task.latest_run.state
+ assert "repo_research_run_id" not in task.latest_run.state
+
@patch("posthog.temporal.ai.posthog_code_slack_mention.execute_task_processing_workflow")
@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")
def test_no_repo_task_falls_back_to_team_github_integration(self, mock_slack_cls, mock_execute_workflow):
@@ -544,6 +635,9 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
assert new_run.state.get("pending_user_message_ts") == "1234.5679"
assert new_run.state.get("initial_prompt_override") == "do something"
+ # Resume path also annotates the new run with the mention-dispatch pointer.
+ assert new_run.state.get("slack_mention_workflow_id") == "posthog-code-mention-T_SLACK:C123:1234.5678"
+
mock_slack_instance.client.reactions_add.assert_called_once_with(
channel="C123", timestamp="1234.5679", name="eyes"
)
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
index 1a5e01aafcc5..3745eb061667 100644
--- a/products/tasks/backend/api.py
+++ b/products/tasks/backend/api.py
@@ -1,4 +1,5 @@
import os
+import re
import json
import uuid
import asyncio
@@ -7,6 +8,7 @@ import builtins
from collections.abc import AsyncGenerator
from datetime import datetime, timedelta
from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
from django.conf import settings
from django.core.cache import cache
@@ -40,6 +42,8 @@ from posthog.rate_limit import CodeInviteThrottle
from posthog.renderers import ServerSentEventRenderer
from posthog.storage import object_storage
+from products.slack_app.backend.models import SlackThreadTaskMapping
+
from ee.hogai.utils.aio import async_to_sync
from .access import has_tasks_access
@@ -67,6 +71,8 @@ from .serializers import (
RepositoryReadinessResponseSerializer,
SandboxEnvironmentListSerializer,
SandboxEnvironmentSerializer,
+ SlackThreadContextQuerySerializer,
+ SlackThreadContextResponseSerializer,
TaskAutomationSerializer,
TaskListQuerySerializer,
TaskPresenceBeaconRequestSerializer,
@@ -208,6 +214,12 @@ def _resolve_cloud_pr_authorship_mode(
TASK_RUN_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES = 64 * 1024
+def _is_internal_debug_team(team_id: int | None) -> bool:
+ if settings.DEBUG and not settings.TEST:
+ return team_id == 1
+ return team_id == 2 and settings.CLOUD_DEPLOYMENT == "US"
+
+
def task_visibility_q(user_id: int | None) -> Q:
"""Filter for tasks visible to the given user.
@@ -240,6 +252,71 @@ class TasksAccessPermission(BasePermission):
return has_tasks_access(request.user)
+def _parse_slack_thread_url(url: str) -> tuple[str, str] | None:
+ """Parse a Slack permalink into `(channel, thread_ts)`"""
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ return None
+ match = re.search(r"/archives/(?P<channel>[A-Z0-9]+)/p(?P<ts>\d+)", parsed.path)
+ if not match:
+ return None
+ channel = match.group("channel")
+ # Reply permalinks put the parent thread_ts in the query string; that wins over the in-path ts.
+ thread_ts_from_query = parse_qs(parsed.query).get("thread_ts", [None])[0]
+ if thread_ts_from_query:
+ return channel, thread_ts_from_query
+ raw_ts = match.group("ts")
+ if len(raw_ts) < 7:
+ return None
+ return channel, f"{raw_ts[:-6]}.{raw_ts[-6:]}"
+
+
+def _temporal_workflow_url(workflow_id: str | None) -> str | None:
+ if not workflow_id:
+ return None
+ base = getattr(settings, "TEMPORAL_UI_HOST", None)
+ namespace = getattr(settings, "TEMPORAL_NAMESPACE", None)
+ if not base or not namespace:
+ return None
+ return f"{base.rstrip('/')}/namespaces/{namespace}/workflows/{workflow_id}"
+
+
+def _slack_repo_research_payload(
+ request, team_id: int, state: dict[str, Any], repo_research_runs_by_id: dict[str, TaskRun]
+) -> dict[str, Any] | None:
+ """Build the repo-research block for a run, or None when the mention wasn't ambiguous."""
+ research_task_id = state.get("repo_research_task_id")
+ research_run_id = state.get("repo_research_run_id")
+ if not research_task_id or not research_run_id:
+ return None
+ research_run = repo_research_runs_by_id.get(research_run_id)
+ sandbox_url = None
+ log_url = None
+ run_status = None
+ if research_run is not None:
+ sandbox_url = (research_run.state if isinstance(research_run.state, dict) else {}).get("sandbox_url")
+ run_status = research_run.status
+ try:
+ log_url = object_storage.get_presigned_url(research_run.log_url, expiration=3600)
+ except Exception:
+ logger.exception("slack_thread_context_research_log_presign_failed", extra={"run_id": research_run_id})
+ log_url = None
+ workflow_id = TaskRun.get_workflow_id(research_task_id, research_run_id)
+ return {
+ "task_id": research_task_id,
+ "run_id": research_run_id,
+ "status": run_status,
+ "task_processing_workflow_id": workflow_id,
+ "task_processing_workflow_url": _temporal_workflow_url(workflow_id),
+ "sandbox_url": sandbox_url,
+ "task_view_url": request.build_absolute_uri(
+ f"/project/{team_id}/tasks/{research_task_id}?runId={research_run_id}&ph_debug=true"
+ ),
+ "log_url": log_url,
+ }
+
+
@extend_schema(tags=["tasks"])
class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""
@@ -385,12 +462,148 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
return Response(result)
- def safely_get_queryset(self, queryset):
- qs = (
- queryset.filter(team=self.team, deleted=False)
- .filter(task_visibility_q(getattr(self.request.user, "id", None)))
- .order_by("-created_at")
+ @validated_request(
+ query_serializer=SlackThreadContextQuerySerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=SlackThreadContextResponseSerializer,
+ description="Task, runs, and Temporal workflow handles for the Slack thread.",
+ ),
+ 400: OpenApiResponse(description="Malformed Slack URL or unparseable thread identifiers."),
+ 403: OpenApiResponse(description="Endpoint is gated to PostHog-internal debugging."),
+ 404: OpenApiResponse(description="No SlackThreadTaskMapping exists for the parsed (channel, thread_ts)."),
+ },
+ summary="Resolve a Slack thread to its task, runs, and Temporal workflows",
+ description=(
+ "PostHog-internal debug tool. Resolves a Slack permalink to the linked task, its runs, "
+ "the task-processing and mention-dispatch Temporal workflow ids/URLs, and presigned log URLs."
+ ),
+ )
+ @action(
+ detail=False,
+ methods=["get"],
+ url_path="slack_thread_context",
+ required_scopes=["task:read"],
+ pagination_class=None,
+ filter_backends=[],
+ )
+ def slack_thread_context(self, request, **kwargs):
+ if not _is_internal_debug_team(self.team_id):
+ return Response(
+ {"detail": "slack-thread-context is restricted to PostHog-internal debugging."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ # 1. Get Slack URL from the request URL
+ url = request.validated_query_data["url"]
+ parsed = _parse_slack_thread_url(url)
+ if parsed is None:
+ return Response(
+ {"detail": "Could not parse channel/thread_ts from the provided Slack URL.", "url": url},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ channel, thread_ts = parsed
+ # 2. Find related tasks
+ mapping = (
+ SlackThreadTaskMapping.objects.select_related("task", "task__created_by")
+ .filter(channel=channel, thread_ts=thread_ts)
+ .first()
)
+ if mapping is None:
+ return Response(
+ {
+ "detail": "no_mapping",
+ "thread": {
+ "url": url,
+ "channel": channel,
+ "thread_ts": thread_ts,
+ "slack_workspace_id": None,
+ "mentioning_slack_user_id": None,
+ },
+ },
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ task = mapping.task
+ # 3. Find runs for the task
+ runs = list(TaskRun.objects.filter(task=task).order_by("created_at", "id"))
+ # Include repo discovery runs, if present
+ repo_research_run_ids = [
+ rid
+ for run in runs
+ if (rid := (run.state if isinstance(run.state, dict) else {}).get("repo_research_run_id"))
+ ]
+ repo_research_runs_by_id: dict[str, TaskRun] = (
+ {str(r.id): r for r in TaskRun.objects.filter(team=task.team, id__in=repo_research_run_ids)}
+ if repo_research_run_ids
+ else {}
+ )
+ # `?ph_debug=true` allows to check tasks of all team members through /tasks/<id>
+ task_url = request.build_absolute_uri(f"/project/{task.team_id}/tasks/{task.id}?ph_debug=true")
+ run_payloads: list[dict[str, Any]] = []
+ # 4. Find workflows for the runs
+ for run in runs:
+ state = run.state if isinstance(run.state, dict) else {}
+ output = run.output if isinstance(run.output, dict) else {}
+ task_processing_workflow_id = TaskRun.get_workflow_id(task.id, run.id)
+ mention_workflow_id = state.get("slack_mention_workflow_id")
+ try:
+ presigned_log_url = object_storage.get_presigned_url(run.log_url, expiration=3600)
+ except Exception:
+ logger.exception("slack_thread_context_log_presign_failed", extra={"run_id": str(run.id)})
+ presigned_log_url = None
+ run_payloads.append(
+ {
+ "id": str(run.id),
+ "status": run.status,
+ "created_at": run.created_at,
+ "completed_at": run.completed_at,
+ "sandbox_url": state.get("sandbox_url"),
+ "pr_url": output.get("pr_url"),
+ "error_message": run.error_message,
+ "task_processing_workflow_id": task_processing_workflow_id,
+ "task_processing_workflow_url": _temporal_workflow_url(task_processing_workflow_id),
+ "mention_workflow_id": mention_workflow_id,
+ "mention_workflow_url": _temporal_workflow_url(mention_workflow_id),
+ "task_view_url": request.build_absolute_uri(
+ f"/project/{task.team_id}/tasks/{task.id}?runId={run.id}&ph_debug=true"
+ ),
+ "log_url": presigned_log_url,
+ "repo_research": _slack_repo_research_payload(
+ request, task.team_id, state, repo_research_runs_by_id
+ ),
+ }
+ )
+ payload = {
+ "thread": {
+ "url": url,
+ "channel": channel,
+ "thread_ts": thread_ts,
+ "slack_workspace_id": mapping.slack_workspace_id,
+ "mentioning_slack_user_id": mapping.mentioning_slack_user_id,
+ },
+ "task": {
+ "id": str(task.id),
+ "team_id": task.team_id,
+ "title": task.title,
+ "repository": task.repository,
+ "origin_product": task.origin_product,
+ "created_at": task.created_at,
+ "url": task_url,
+ },
+ "runs": run_payloads,
+ }
+ serializer = SlackThreadContextResponseSerializer(payload)
+ return Response(serializer.data)
+
+ def safely_get_queryset(self, queryset):
+ qs = queryset.filter(team=self.team, deleted=False)
+ # `?ph_debug=true` allows to check tasks of all team members through /tasks/<id>
+ if not (
+ _is_internal_debug_team(self.team_id)
+ and self.action == "retrieve"
+ and self.request.query_params.get("ph_debug") == "true"
+ ):
+ qs = qs.filter(task_visibility_q(getattr(self.request.user, "id", None)))
+ qs = qs.order_by("-created_at")
params = self.request.query_params if hasattr(self, "request") else {}
@@ -1361,12 +1574,17 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if not task_id:
raise NotFound("Task ID is required")
- task_visible = (
- Task.objects.filter(id=task_id, team=self.team)
- .filter(task_visibility_q(getattr(self.request.user, "id", None)))
- .exists()
+ task_filter = Task.objects.filter(id=task_id, team=self.team)
+ # `?ph_debug=true` allows to check tasks of all team members through /tasks/<id>.
+ # Allowlist read-only actions only — connection_token is a GET but mints a write-capable token.
+ is_internal_debug_read = (
+ _is_internal_debug_team(self.team_id)
+ and self.action in ("list", "retrieve", "logs", "session_logs", "stream")
+ and self.request.query_params.get("ph_debug") == "true"
)
- if not task_visible:
+ if not is_internal_debug_read:
+ task_filter = task_filter.filter(task_visibility_q(getattr(self.request.user, "id", None)))
+ if not task_filter.exists():
raise NotFound("Task not found")
return queryset.filter(team=self.team, task_id=task_id)
diff --git a/products/tasks/backend/repo_selection/agent.py b/products/tasks/backend/repo_selection/agent.py
index 1345988cc248..5b94a6ef215a 100644
--- a/products/tasks/backend/repo_selection/agent.py
+++ b/products/tasks/backend/repo_selection/agent.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import json
import logging
+from collections.abc import Callable
from typing import TYPE_CHECKING
from pydantic import BaseModel, Field
@@ -304,6 +305,7 @@ async def select_repository(
sandbox_environment_id: str | None = None,
verbose: bool = False,
output_fn: OutputFn = None,
+ on_research_session: Callable[[str, str], None] | None = None,
) -> RepoSelectionResult:
"""Select the most relevant repository for a free-form request context.
@@ -373,6 +375,9 @@ async def select_repository(
origin_product=origin_product,
internal=True,
)
+ # Track repo discovery execution (for example, for Slack)
+ if on_research_session is not None:
+ on_research_session(str(session.task.id), str(session.task_run.id))
try:
if result.repository is not None:
result.repository = result.repository.strip().lower()
diff --git a/products/tasks/backend/serializers.py b/products/tasks/backend/serializers.py
index faeb028e8bac..da5e04c19326 100644
--- a/products/tasks/backend/serializers.py
+++ b/products/tasks/backend/serializers.py
@@ -1695,3 +1695,147 @@ class TaskPresenceBeaconRequestSerializer(serializers.Serializer):
device_id = serializers.UUIDField(
help_text="UUID of the caller's UserPushToken (returned by `/api/users/@me/push_tokens/` on register).",
)
+
+
+class SlackThreadContextQuerySerializer(serializers.Serializer):
+ """Query params for the slack-thread debug endpoint."""
+
+ url = serializers.URLField(
+ help_text=(
+ "Full Slack permalink to any message in the thread (e.g. "
+ "https://posthog.slack.com/archives/C…/p1779956938619299). Replies inside the "
+ "thread are accepted too — the `thread_ts` query param (when present) takes "
+ "precedence over the in-path message ts."
+ ),
+ )
+
+
+class SlackThreadContextThreadSerializer(serializers.Serializer):
+ """Slack-side identifiers and the mapping metadata for a thread → task lookup."""
+
+ url = serializers.CharField(help_text="Echoed input URL.")
+ channel = serializers.CharField(help_text="Slack channel id parsed from the URL (e.g. C0ACRAMJUAG).")
+ thread_ts = serializers.CharField(help_text="Slack thread_ts (e.g. 1779956938.619299).")
+ slack_workspace_id = serializers.CharField(
+ allow_null=True,
+ help_text="Slack workspace id (e.g. T…). Null when no mapping exists yet.",
+ )
+ mentioning_slack_user_id = serializers.CharField(
+ allow_null=True,
+ help_text="The Slack user who triggered the task. Null when no mapping exists yet.",
+ )
+
+
+class SlackThreadContextTaskSerializer(serializers.Serializer):
+ """The PostHog Task linked to the Slack thread."""
+
+ id = serializers.CharField(help_text="UUID of the Task row.")
+ team_id = serializers.IntegerField(help_text="Team that owns the task.")
+ title = serializers.CharField(help_text="Task title (typically the first ~255 chars of the Slack ask).")
+ repository = serializers.CharField(
+ allow_null=True,
+ help_text="Resolved repository in `org/repo` form, or null if the run started without a repo.",
+ )
+ origin_product = serializers.CharField(help_text="`Task.OriginProduct` (`slack` for slack-originated tasks).")
+ created_at = serializers.DateTimeField(help_text="When the task was created (server-side timestamp).")
+ url = serializers.CharField(help_text="Absolute URL to the task detail page in the PostHog app.")
+
+
+class SlackThreadContextRepoResearchSerializer(serializers.Serializer):
+ """The internal sandbox run the discovery agent used to pick this run's repo.
+
+ Only present when the originating mention was ambiguous (multiple candidate
+ repos, no explicit mention) — that's the only path that spins up a research
+ sandbox. Null otherwise.
+ """
+
+ task_id = serializers.CharField(help_text="UUID of the internal repo-research Task.")
+ run_id = serializers.CharField(help_text="UUID of the internal repo-research TaskRun.")
+ status = serializers.CharField(
+ allow_null=True,
+ help_text="Research run status, or null if the run row could not be loaded.",
+ )
+ task_processing_workflow_id = serializers.CharField(
+ help_text="Temporal workflow id for the research sandbox run (`task-processing-<task_id>-<run_id>`).",
+ )
+ task_processing_workflow_url = serializers.CharField(
+ allow_null=True,
+ help_text="Full Temporal Web UI URL for the research workflow; null when `TEMPORAL_UI_HOST` is unset.",
+ )
+ sandbox_url = serializers.CharField(
+ allow_null=True,
+ help_text="Live sandbox tunnel URL for the research run, when one was attached.",
+ )
+ task_view_url = serializers.CharField(
+ help_text="Absolute URL to the research task detail page (carries `?ph_debug=true`).",
+ )
+ log_url = serializers.CharField(
+ allow_null=True,
+ help_text="Presigned S3 URL for the research run's JSONL log transcript (valid ~1 hour).",
+ )
+
+
+class SlackThreadContextRunSerializer(serializers.Serializer):
+ """One TaskRun and its associated Temporal workflow handles."""
+
+ id = serializers.CharField(help_text="UUID of the TaskRun row.")
+ status = serializers.CharField(help_text="Run status (queued/in_progress/completed/failed/…).")
+ created_at = serializers.DateTimeField(help_text="When the run was created.")
+ completed_at = serializers.DateTimeField(
+ allow_null=True,
+ help_text="When the run reached a terminal state, or null while still running.",
+ )
+ sandbox_url = serializers.CharField(
+ allow_null=True,
+ help_text="Live sandbox tunnel URL, when one was attached.",
+ )
+ pr_url = serializers.CharField(
+ allow_null=True,
+ help_text="PR URL produced by the run, when one was opened.",
+ )
+ error_message = serializers.CharField(
+ allow_null=True,
+ help_text="Error captured on terminal failure, or null on success.",
+ )
+ task_processing_workflow_id = serializers.CharField(
+ help_text="Temporal workflow id for the sandbox/agent run (`task-processing-<task_id>-<run_id>`).",
+ )
+ task_processing_workflow_url = serializers.CharField(
+ allow_null=True,
+ help_text="Full Temporal Web UI URL for the task-processing workflow; null when `TEMPORAL_UI_HOST` is unset.",
+ )
+ mention_workflow_id = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Temporal workflow id of the Slack mention that dispatched this run "
+ "(`posthog-code-mention-<workspace>:<event_id_or_channel:ts>`). Null for runs "
+ "created before this field was persisted."
+ ),
+ )
+ mention_workflow_url = serializers.CharField(
+ allow_null=True,
+ help_text="Full Temporal Web UI URL for the mention dispatch workflow; null when unavailable.",
+ )
+ task_view_url = serializers.CharField(help_text="Absolute URL to the task detail page focused on this run.")
+ log_url = serializers.CharField(
+ allow_null=True,
+ help_text="Presigned S3 URL for the run's full JSONL log transcript (valid ~1 hour).",
+ )
+ repo_research = SlackThreadContextRepoResearchSerializer(
+ allow_null=True,
+ help_text="The discovery-agent sandbox that picked this run's repo, when the mention was ambiguous.",
+ )
+
+
+class SlackThreadContextResponseSerializer(serializers.Serializer):
+ """Top-level response for the slack-thread debug endpoint."""
+
+ thread = SlackThreadContextThreadSerializer(help_text="Slack-side identifiers and the mapping metadata.")
+ task = SlackThreadContextTaskSerializer(
+ allow_null=True,
+ help_text="Linked PostHog Task. Null when no mapping was found for the thread.",
+ )
+ runs = SlackThreadContextRunSerializer(
+ many=True,
+ help_text="All runs on the task, oldest first. Empty when no mapping was found.",
+ )
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 67007da65743..27261fcc115e 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -11,6 +11,7 @@ from urllib.parse import quote
from unittest.mock import AsyncMock, MagicMock, patch
+from django.conf import settings
from django.http import StreamingHttpResponse
from django.test import TestCase, override_settings
from django.utils import timezone as django_timezone
@@ -504,6 +505,186 @@ class TestTaskCreatorScoping(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+@override_settings(CLOUD_DEPLOYMENT="US")
+class TestTaskVisibilityInternalDebugTeamBypass(BaseTaskAPITest):
+ """When the gate (`_is_internal_debug_team`) fires, PostHog employees can
+ read any teammate's task/run by ID — but the bypass is deliberately narrow:
+ only the `retrieve` action on TaskViewSet and read-only actions on
+ TaskRunViewSet. List views, write actions, and other teams remain
+ creator-scoped. The unaffected cases live in `TestTaskCreatorScoping`
+ above; the deployment-region requirement is covered by
+ `TestTaskVisibilityInternalDebugRegionGate`."""
+
+ def setUp(self):
+ super().setUp()
+ # Production checks `team_id == 2 AND CLOUD_DEPLOYMENT == "US"`; tests
+ # can't easily force the row id, so substitute the test team's id and
+ # keep the deployment-region clause intact so off-US tests still flip.
+ self._bypass_patch = patch(
+ "products.tasks.backend.api._is_internal_debug_team",
+ side_effect=lambda team_id: team_id == self.team.id and settings.CLOUD_DEPLOYMENT == "US",
+ )
+ self._bypass_patch.start()
+
+ def tearDown(self):
+ self._bypass_patch.stop()
+ super().tearDown()
+
+ def test_retrieve_other_user_task_succeeds(self):
+ other_user = self.create_organization_user("teammate")
+ task = self.create_task(created_by=other_user)
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/?ph_debug=true")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["id"], str(task.id))
+
+ def test_retrieve_other_user_task_without_ph_debug_still_404s(self):
+ # The whole point of the param-gated bypass — even on the internal team
+ # in US-prod, default behavior matches every other team.
+ other_user = self.create_organization_user("teammate")
+ task = self.create_task(created_by=other_user)
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_list_still_excludes_other_user_tasks(self):
+ # The bypass is scoped to `retrieve` — list still filters by creator even
+ # with `?ph_debug=true`.
+ other_user = self.create_organization_user("teammate")
+ mine = self.create_task("Mine", created_by=self.user)
+ theirs = self.create_task("Theirs", created_by=other_user)
+
+ response = self.client.get("/api/projects/@current/tasks/?ph_debug=true")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ ids = {item["id"] for item in response.json()["results"]}
+ assert str(mine.id) in ids
+ assert str(theirs.id) not in ids
+
+ def test_repositories_still_excludes_other_user_repos(self):
+ other_user = self.create_organization_user("teammate")
+ theirs = self.create_task("Theirs", created_by=other_user)
+ theirs.repository = "team/repo"
+ theirs.save(update_fields=["repository"])
+
+ response = self.client.get("/api/projects/@current/tasks/repositories/?ph_debug=true")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["repositories"], [])
+
+ def test_list_runs_for_other_user_task_succeeds(self):
+ other_user = self.create_organization_user("teammate")
+ task = self.create_task(created_by=other_user)
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/?ph_debug=true")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ ids = {item["id"] for item in response.json()["results"]}
+ self.assertEqual(ids, {str(run.id)})
+
+ def test_list_runs_for_other_user_task_without_ph_debug_still_404s(self):
+ other_user = self.create_organization_user("teammate")
+ task = self.create_task(created_by=other_user)
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_retrieve_other_user_run_succeeds(self):
+ other_user = self.create_organization_user("teammate")
+ task = self.create_task(created_by=other_user)
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/?ph_debug=true")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["id"], str(run.id))
+
+ def test_connection_token_on_other_user_run_still_404s_with_ph_debug(self):
+ # connection_token is a GET but mints a write-capable sandbox JWT — the
+ # read-only debug bypass must NOT expose it for another user's run.
+ other_user = self.create_organization_user("teammate")
+ task = self.create_task(created_by=other_user)
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ response = self.client.get(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/connection_token/?ph_debug=true"
+ )
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ def test_write_action_on_other_user_task_still_returns_404(self, _mock_workflow):
+ # POST /tasks/<id>/run/ is a write — bypass must NOT fire even when the
+ # `?ph_debug=true` opt-in is set; that param is read-only.
+ other_user = self.create_organization_user("teammate")
+ task = self.create_task(created_by=other_user)
+
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/run/?ph_debug=true")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_create_run_on_other_user_task_still_returns_404(self):
+ # POST /tasks/<id>/runs/ is a write — bypass must NOT fire even with the
+ # opt-in.
+ other_user = self.create_organization_user("teammate")
+ task = self.create_task(created_by=other_user)
+
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/runs/?ph_debug=true",
+ {"environment": "cloud"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+
+class TestTaskVisibilityInternalDebugRegionGate(BaseTaskAPITest):
+ """The internal-debug bypass keys on team-id 2 — but that's only meaningful in
+ the US-prod DB. On EU prod, self-hosted, and dev, team-id 2 belongs to some
+ unrelated organization. The gate must require `CLOUD_DEPLOYMENT == "US"` to
+ avoid silently granting cross-creator visibility there."""
+
+ def setUp(self):
+ super().setUp()
+ # Same shape as `TestTaskVisibilityInternalDebugTeamBypass.setUp` — the
+ # `team.id` match would pass on its own, leaving `CLOUD_DEPLOYMENT` as
+ # the only thing each test varies.
+ self._bypass_patch = patch(
+ "products.tasks.backend.api._is_internal_debug_team",
+ side_effect=lambda team_id: team_id == self.team.id and settings.CLOUD_DEPLOYMENT == "US",
+ )
+ self._bypass_patch.start()
+
+ def tearDown(self):
+ self._bypass_patch.stop()
+ super().tearDown()
+
+ @parameterized.expand(
+ [
+ ("eu_prod", "EU"),
+ ("self_hosted_or_dev", None),
+ ]
+ )
+ def test_retrieve_other_user_task_still_blocked_off_us(self, _name: str, deployment: str | None) -> None:
+ # Sending the FE opt-in must NOT unlock the bypass off-US: the deployment
+ # guard fires before the param is even considered.
+ other_user = self.create_organization_user("teammate")
+ task = self.create_task(created_by=other_user)
+
+ with override_settings(CLOUD_DEPLOYMENT=deployment):
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/?ph_debug=true")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ @parameterized.expand(
+ [
+ ("eu_prod", "EU"),
+ ("self_hosted_or_dev", None),
+ ]
+ )
+ def test_slack_thread_context_403_off_us(self, _name: str, deployment: str | None) -> None:
+ with override_settings(CLOUD_DEPLOYMENT=deployment):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/tasks/slack_thread_context/"
+ "?url=https%3A%2F%2Fposthog.slack.com%2Farchives%2FC0%2Fp1779956938619299"
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+
class TestTaskAPI(BaseTaskAPITest):
def test_list_tasks(self):
self.create_task("Task 1")
diff --git a/products/tasks/backend/tests/test_slack_thread_context.py b/products/tasks/backend/tests/test_slack_thread_context.py
new file mode 100644
index 000000000000..de1abc4e2c9d
--- /dev/null
+++ b/products/tasks/backend/tests/test_slack_thread_context.py
@@ -0,0 +1,313 @@
+from typing import ClassVar
+from urllib.parse import quote
+
+from unittest.mock import patch
+
+from django.conf import settings
+from django.test import TestCase, override_settings
+
+from rest_framework import status
+from rest_framework.test import APIClient
+
+from posthog.models import Integration, Organization, OrganizationMembership, Team, User
+
+from products.slack_app.backend.models import SlackThreadTaskMapping
+from products.tasks.backend.models import Task, TaskRun
+
+
+class _SlackThreadContextBase(TestCase):
+ organization: ClassVar[Organization]
+ team: ClassVar[Team]
+ user: ClassVar[User]
+
+ @classmethod
+ def setUpTestData(cls):
+ cls.organization = Organization.objects.create(name="Test Org")
+ cls.team = Team.objects.create(organization=cls.organization, name="Test Team")
+ cls.user = User.objects.create_user(email="[email protected]", first_name="Alice", password="password")
+ cls.organization.members.add(cls.user)
+ OrganizationMembership.objects.filter(user=cls.user, organization=cls.organization).update(
+ level=OrganizationMembership.Level.ADMIN
+ )
+
+ def setUp(self):
+ self.client = APIClient()
+ self.client.force_authenticate(self.user)
+ self._flag_patcher = patch(
+ "posthoganalytics.feature_enabled", side_effect=lambda flag, *a, **k: flag == "tasks"
+ )
+ self._flag_patcher.start()
+ # Production gate is `team_id == 2 AND CLOUD_DEPLOYMENT == "US"`; tests
+ # can't easily force the test row to id 2, so substitute self.team.id
+ # for the constant while keeping the deployment clause intact.
+ self._gate_patcher = patch(
+ "products.tasks.backend.api._is_internal_debug_team",
+ side_effect=lambda team_id: team_id == self.team.id and settings.CLOUD_DEPLOYMENT == "US",
+ )
+ self._gate_patcher.start()
+
+ def tearDown(self):
+ self._gate_patcher.stop()
+ self._flag_patcher.stop()
+ super().tearDown()
+
+
+@override_settings(CLOUD_DEPLOYMENT="US")
+class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
+ def _url(self, slack_url: str | None = None) -> str:
+ suffix = f"?url={quote(slack_url, safe='')}" if slack_url else ""
+ return f"/api/projects/{self.team.id}/tasks/slack_thread_context/{suffix}"
+
+ def _create_fixture(
+ self,
+ *,
+ slack_mention_workflow_id: str | None = "posthog-code-mention-T_SLACK:Ev01",
+ ) -> tuple[Task, TaskRun, SlackThreadTaskMapping]:
+ integration = Integration.objects.create(
+ team=self.team, kind="slack-posthog-code", integration_id="T_SLACK", config={}
+ )
+ task = Task.objects.create(
+ team=self.team,
+ title="Investigate flaky test",
+ description="From slack thread",
+ origin_product=Task.OriginProduct.SLACK,
+ created_by=self.user,
+ repository=None,
+ )
+ run_state: dict[str, object] = {"sandbox_url": "https://sandbox.example/abc"}
+ if slack_mention_workflow_id is not None:
+ run_state["slack_mention_workflow_id"] = slack_mention_workflow_id
+ run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ state=run_state,
+ output={"pr_url": "https://github.com/posthog/posthog/pull/1"},
+ )
+ mapping = SlackThreadTaskMapping.objects.create(
+ team=self.team,
+ integration=integration,
+ slack_workspace_id="T_SLACK",
+ channel="C0ACRAMJUAG",
+ thread_ts="1779956938.619299",
+ task=task,
+ task_run=run,
+ mentioning_slack_user_id="U_ANDY",
+ )
+ return task, run, mapping
+
+ def test_non_internal_team_is_forbidden(self):
+ # Override the base-class gate patcher so this call lands on the
+ # "not the internal team" branch of `_is_internal_debug_team`.
+ with patch("products.tasks.backend.api._is_internal_debug_team", return_value=False):
+ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_malformed_url_returns_400(self):
+ response = self.client.get(self._url("https://posthog.slack.com/not/a/permalink"))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_missing_url_returns_400(self):
+ # validated_request raises a validation error → 400 from drf
+ response = self.client.get(self._url(None))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_no_mapping_returns_404(self):
+ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ body = response.json()
+ assert body["detail"] == "no_mapping"
+ assert body["thread"]["channel"] == "C0ACRAMJUAG"
+ assert body["thread"]["thread_ts"] == "1779956938.619299"
+
+ def test_happy_path_returns_task_and_runs(self):
+ task, run, mapping = self._create_fixture()
+ with patch(
+ "products.tasks.backend.api.object_storage.get_presigned_url",
+ return_value="https://s3.example/presigned",
+ ):
+ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert body["thread"]["channel"] == "C0ACRAMJUAG"
+ assert body["thread"]["thread_ts"] == "1779956938.619299"
+ assert body["thread"]["slack_workspace_id"] == "T_SLACK"
+ assert body["thread"]["mentioning_slack_user_id"] == "U_ANDY"
+
+ assert body["task"]["id"] == str(task.id)
+ assert body["task"]["team_id"] == self.team.id
+ assert body["task"]["title"] == "Investigate flaky test"
+ assert body["task"]["repository"] is None
+ assert body["task"]["origin_product"] == Task.OriginProduct.SLACK
+ # Links carry `?ph_debug=true` so reviewers don't lose the cross-creator
+ # bypass when they click through to the regular task UI.
+ assert body["task"]["url"].endswith(f"/project/{self.team.id}/tasks/{task.id}?ph_debug=true")
+
+ assert len(body["runs"]) == 1
+ run_payload = body["runs"][0]
+ assert run_payload["id"] == str(run.id)
+ assert run_payload["sandbox_url"] == "https://sandbox.example/abc"
+ assert run_payload["pr_url"] == "https://github.com/posthog/posthog/pull/1"
+ assert run_payload["task_processing_workflow_id"] == f"task-processing-{task.id}-{run.id}"
+ assert run_payload["mention_workflow_id"] == "posthog-code-mention-T_SLACK:Ev01"
+ assert run_payload["task_view_url"].endswith(
+ f"/project/{self.team.id}/tasks/{task.id}?runId={run.id}&ph_debug=true"
+ )
+ assert run_payload["log_url"] == "https://s3.example/presigned"
+
+ def test_log_presign_failure_returns_200_with_null_log_url(self):
+ # Presign failures must degrade to a null log_url, not 500.
+ self._create_fixture()
+ with patch(
+ "products.tasks.backend.api.object_storage.get_presigned_url",
+ side_effect=Exception("boto signing error"),
+ ):
+ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["runs"][0]["log_url"] is None
+
+ def test_reply_url_uses_thread_ts_query_param(self):
+ self._create_fixture()
+ reply_url = (
+ "https://posthog.slack.com/archives/C0ACRAMJUAG/p1779957091477899"
+ "?thread_ts=1779956938.619299&cid=C0ACRAMJUAG"
+ )
+ with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ response = self.client.get(self._url(reply_url))
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ # The reply's in-path ts (1779957091.477899) must NOT win — the thread_ts query
+ # param identifies the originating thread that has the mapping.
+ assert body["thread"]["thread_ts"] == "1779956938.619299"
+
+ def test_multiple_runs_returned_oldest_first(self):
+ task, first_run, _ = self._create_fixture()
+ # A second run on the same task — resume after follow-up.
+ second_run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ state={
+ "resume_from_run_id": str(first_run.id),
+ "slack_mention_workflow_id": "posthog-code-mention-T_SLACK:Ev02",
+ },
+ )
+ with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ run_ids = [r["id"] for r in body["runs"]]
+ assert run_ids == [str(first_run.id), str(second_run.id)]
+ assert body["runs"][1]["mention_workflow_id"] == "posthog-code-mention-T_SLACK:Ev02"
+
+ @override_settings(TEMPORAL_UI_HOST="")
+ def test_temporal_url_null_when_ui_host_unset(self):
+ self._create_fixture()
+ with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ run_payload = body["runs"][0]
+ assert run_payload["task_processing_workflow_url"] is None
+ assert run_payload["mention_workflow_url"] is None
+
+ @override_settings(TEMPORAL_UI_HOST="https://temporal.example.com", TEMPORAL_NAMESPACE="prod")
+ def test_temporal_url_includes_workflow_id_when_configured(self):
+ task, run, _ = self._create_fixture()
+ with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ run_payload = body["runs"][0]
+ assert run_payload["task_processing_workflow_url"] == (
+ f"https://temporal.example.com/namespaces/prod/workflows/task-processing-{task.id}-{run.id}"
+ )
+ assert run_payload["mention_workflow_url"] == (
+ "https://temporal.example.com/namespaces/prod/workflows/posthog-code-mention-T_SLACK:Ev01"
+ )
+
+ def test_mention_workflow_id_null_for_old_runs(self):
+ self._create_fixture(slack_mention_workflow_id=None)
+ with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["runs"][0]["mention_workflow_id"] is None
+ assert body["runs"][0]["mention_workflow_url"] is None
+
+ def test_repo_research_null_for_unambiguous_run(self):
+ # The default fixture run has no repo_research_* state — it should report null.
+ self._create_fixture()
+ with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["runs"][0]["repo_research"] is None
+
+ def test_repo_research_surfaced_for_ambiguous_run(self):
+ task, run, _ = self._create_fixture()
+ # The discovery sandbox is a separate internal task/run on the same team.
+ research_task = Task.objects.create(
+ team=self.team,
+ title="[sandbox_prompt:repo_selection] pick a repo",
+ description="repo research",
+ origin_product=Task.OriginProduct.SLACK,
+ created_by=self.user,
+ repository="PostHog/.github",
+ internal=True,
+ )
+ research_run = TaskRun.objects.create(
+ task=research_task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ state={"sandbox_url": "https://sandbox.example/research"},
+ )
+ run.state = {
+ **run.state,
+ "repo_research_task_id": str(research_task.id),
+ "repo_research_run_id": str(research_run.id),
+ }
+ run.save(update_fields=["state"])
+
+ with override_settings(TEMPORAL_UI_HOST="https://temporal.example.com", TEMPORAL_NAMESPACE="prod"):
+ with patch(
+ "products.tasks.backend.api.object_storage.get_presigned_url",
+ return_value="https://s3.example/research-log",
+ ):
+ response = self.client.get(
+ self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299")
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ research = response.json()["runs"][0]["repo_research"]
+ assert research is not None
+ assert research["task_id"] == str(research_task.id)
+ assert research["run_id"] == str(research_run.id)
+ assert research["status"] == TaskRun.Status.COMPLETED
+ assert research["sandbox_url"] == "https://sandbox.example/research"
+ assert research["task_processing_workflow_id"] == f"task-processing-{research_task.id}-{research_run.id}"
+ assert research["task_processing_workflow_url"] == (
+ f"https://temporal.example.com/namespaces/prod/workflows/task-processing-{research_task.id}-{research_run.id}"
+ )
+ assert research["task_view_url"].endswith(
+ f"/project/{self.team.id}/tasks/{research_task.id}?runId={research_run.id}&ph_debug=true"
+ )
+ assert research["log_url"] == "https://s3.example/research-log"
+
+ def test_repo_research_handles_missing_research_run_row(self):
+ # If the research run row is gone, still surface the ids/workflow without crashing.
+ task, run, _ = self._create_fixture()
+ run.state = {
+ **run.state,
+ "repo_research_task_id": "11111111-1111-1111-1111-111111111111",
+ "repo_research_run_id": "22222222-2222-2222-2222-222222222222",
+ }
+ run.save(update_fields=["state"])
+ with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
+ assert response.status_code == status.HTTP_200_OK
+ research = response.json()["runs"][0]["repo_research"]
+ assert research is not None
+ assert research["run_id"] == "22222222-2222-2222-2222-222222222222"
+ assert research["status"] is None
+ assert research["sandbox_url"] is None
+ assert research["log_url"] is None
diff --git a/products/tasks/frontend/SlackTaskContextScene.tsx b/products/tasks/frontend/SlackTaskContextScene.tsx
new file mode 100644
index 000000000000..369f6c7a51c5
--- /dev/null
+++ b/products/tasks/frontend/SlackTaskContextScene.tsx
@@ -0,0 +1,353 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonDivider, LemonInput, LemonTag, Spinner } from '@posthog/lemon-ui'
+
+import { CodeSnippet } from 'lib/components/CodeSnippet'
+import { Link } from 'lib/lemon-ui/Link'
+import { SceneExport } from 'scenes/sceneTypes'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { SlackThreadContextRepoResearchApi, SlackThreadContextRunApi } from './generated/api.schemas'
+import { slackTaskContextSceneLogic } from './logics/slackTaskContextSceneLogic'
+
+export const scene: SceneExport = {
+ component: SlackTaskContextScene,
+ logic: slackTaskContextSceneLogic,
+}
+
+export function SlackTaskContextScene(): JSX.Element {
+ const { url, result, resultLoading, submissionError, canSubmit } = useValues(slackTaskContextSceneLogic)
+ const { setUrl, loadResult, clearResult } = useActions(slackTaskContextSceneLogic)
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="Slack task context"
+ description="Look up the PostHog Task, runs, and Temporal workflows linked to a Slack thread. Restricted to PostHog-internal debugging (team 2)."
+ resourceType={{ type: 'task' }}
+ />
+
+ <LemonBanner type="info">
+ Paste any Slack permalink from inside the thread (parent message or reply). Reply URLs that carry{' '}
+ <code>?thread_ts=…</code> resolve to the originating thread. Log URLs expire after ~1 hour.
+ </LemonBanner>
+
+ <div className="flex items-end gap-2">
+ <LemonInput
+ placeholder="https://posthog.slack.com/archives/C…/p1779956938619299"
+ value={url}
+ onChange={setUrl}
+ onPressEnter={() => {
+ if (canSubmit) {
+ loadResult()
+ }
+ }}
+ className="flex-1"
+ autoFocus
+ />
+ <LemonButton
+ type="primary"
+ loading={resultLoading}
+ disabledReason={
+ url.trim().length === 0 ? 'Enter a Slack thread URL' : resultLoading ? 'Loading…' : null
+ }
+ onClick={() => loadResult()}
+ >
+ Look up
+ </LemonButton>
+ {(result || submissionError) && !resultLoading ? (
+ <LemonButton type="secondary" onClick={() => clearResult()}>
+ Clear
+ </LemonButton>
+ ) : null}
+ </div>
+
+ {submissionError ? (
+ <LemonBanner type="error">
+ {submissionError.status === 403
+ ? 'This endpoint is restricted to PostHog-internal debugging (team 2).'
+ : submissionError.status === 404
+ ? 'No Slack → task mapping found for that thread.'
+ : submissionError.detail || 'Request failed.'}
+ </LemonBanner>
+ ) : null}
+
+ {resultLoading ? (
+ <div className="flex items-center gap-2 text-muted">
+ <Spinner /> Looking up the thread…
+ </div>
+ ) : null}
+
+ {result ? <SlackTaskContextResult result={result} /> : null}
+ </SceneContent>
+ )
+}
+
+function SlackTaskContextResult({
+ result,
+}: {
+ result: NonNullable<ReturnType<typeof useValues<typeof slackTaskContextSceneLogic>>['result']>
+}): JSX.Element {
+ const { thread, task, runs } = result
+ return (
+ <div className="space-y-4">
+ <section>
+ <h3 className="mb-2">Thread</h3>
+ <KeyValueGrid
+ rows={[
+ ['Channel', thread.channel],
+ ['Thread ts', thread.thread_ts],
+ ['Workspace', thread.slack_workspace_id ?? '—'],
+ ['Mentioning user', thread.mentioning_slack_user_id ?? '—'],
+ [
+ 'Slack URL',
+ <Link key="slack-url" to={thread.url} target="_blank">
+ {thread.url}
+ </Link>,
+ ],
+ ]}
+ />
+ </section>
+
+ <LemonDivider />
+
+ {task ? (
+ <section>
+ <h3 className="mb-2">Task</h3>
+ <KeyValueGrid
+ rows={[
+ ['Title', task.title],
+ ['Task ID', <CodeSnippet key="task-id">{task.id}</CodeSnippet>],
+ ['Repository', task.repository ?? <em key="empty">empty (no repo)</em>],
+ ['Origin', task.origin_product],
+ ['Team ID', String(task.team_id)],
+ [
+ 'Open in PostHog',
+ <Link key="task-url" to={task.url}>
+ {task.url}
+ </Link>,
+ ],
+ ]}
+ />
+ </section>
+ ) : (
+ <LemonBanner type="warning">No task is linked to this thread.</LemonBanner>
+ )}
+
+ <LemonDivider />
+
+ <section>
+ <h3 className="mb-2">Runs ({runs.length})</h3>
+ {runs.length === 0 ? (
+ <div className="text-muted">No runs yet.</div>
+ ) : (
+ <div className="space-y-4">
+ {runs.map((run, idx) => (
+ <SlackTaskContextRunCard key={run.id} run={run} index={idx + 1} />
+ ))}
+ </div>
+ )}
+ </section>
+ </div>
+ )
+}
+
+function SlackTaskContextRunCard({ run, index }: { run: SlackThreadContextRunApi; index: number }): JSX.Element {
+ return (
+ <div className="border rounded p-3">
+ <div className="flex items-center justify-between mb-2">
+ <h4 className="m-0">
+ Run #{index} <LemonTag size="small">{run.status}</LemonTag>
+ </h4>
+ <span className="text-muted text-sm">{run.created_at}</span>
+ </div>
+ <KeyValueGrid
+ rows={[
+ ['Run ID', <CodeSnippet key="run-id">{run.id}</CodeSnippet>],
+ [
+ 'Open in PostHog',
+ <Link key="task-view" to={run.task_view_url}>
+ {run.task_view_url}
+ </Link>,
+ ],
+ [
+ 'Task-processing workflow',
+ <WorkflowLink
+ key="task-processing-wf"
+ id={run.task_processing_workflow_id}
+ url={run.task_processing_workflow_url}
+ />,
+ ],
+ [
+ 'Mention workflow',
+ run.mention_workflow_id ? (
+ <WorkflowLink
+ key="mention-wf"
+ id={run.mention_workflow_id}
+ url={run.mention_workflow_url}
+ />
+ ) : (
+ <span key="empty" className="text-muted">
+ Not recorded (run created before this field was persisted).
+ </span>
+ ),
+ ],
+ [
+ 'Sandbox',
+ run.sandbox_url ? (
+ <Link key="sandbox" to={run.sandbox_url} target="_blank">
+ {run.sandbox_url}
+ </Link>
+ ) : (
+ <span key="empty" className="text-muted">
+ —
+ </span>
+ ),
+ ],
+ [
+ 'PR',
+ run.pr_url ? (
+ <Link key="pr" to={run.pr_url} target="_blank">
+ {run.pr_url}
+ </Link>
+ ) : (
+ <span key="empty" className="text-muted">
+ —
+ </span>
+ ),
+ ],
+ [
+ 'Logs (presigned, ~1h)',
+ run.log_url ? (
+ <Link key="log" to={run.log_url} target="_blank">
+ Download JSONL
+ </Link>
+ ) : (
+ <span key="empty" className="text-muted">
+ —
+ </span>
+ ),
+ ],
+ [
+ 'Error',
+ run.error_message ? (
+ <code key="err">{run.error_message}</code>
+ ) : (
+ <span key="empty" className="text-muted">
+ —
+ </span>
+ ),
+ ],
+ [
+ 'Completed at',
+ run.completed_at ?? (
+ <span key="empty" className="text-muted">
+ — (still running)
+ </span>
+ ),
+ ],
+ ]}
+ />
+ {run.repo_research ? <RepoResearchBlock research={run.repo_research} /> : null}
+ </div>
+ )
+}
+
+function RepoResearchBlock({ research }: { research: SlackThreadContextRepoResearchApi }): JSX.Element {
+ return (
+ <div className="mt-3 pl-3 border-l-2">
+ <div className="text-muted font-semibold mb-1">
+ Repo research sandbox <LemonTag size="small">{research.status ?? 'unknown'}</LemonTag>
+ </div>
+ <p className="text-muted text-xs mb-2">
+ This run started from an ambiguous mention, so the discovery agent ran a sandbox to pick the repo.
+ </p>
+ <KeyValueGrid
+ rows={[
+ ['Research run ID', <CodeSnippet key="rr-id">{research.run_id}</CodeSnippet>],
+ [
+ 'Open in PostHog',
+ <Link key="rr-view" to={research.task_view_url}>
+ {research.task_view_url}
+ </Link>,
+ ],
+ [
+ 'Research workflow',
+ <WorkflowLink
+ key="rr-wf"
+ id={research.task_processing_workflow_id}
+ url={research.task_processing_workflow_url}
+ />,
+ ],
+ [
+ 'Sandbox',
+ research.sandbox_url ? (
+ <Link key="rr-sandbox" to={research.sandbox_url} target="_blank">
+ {research.sandbox_url}
+ </Link>
+ ) : (
+ <span key="empty" className="text-muted">
+ —
+ </span>
+ ),
+ ],
+ [
+ 'Logs (presigned, ~1h)',
+ research.log_url ? (
+ <Link key="rr-log" to={research.log_url} target="_blank">
+ Download JSONL
+ </Link>
+ ) : (
+ <span key="empty" className="text-muted">
+ —
+ </span>
+ ),
+ ],
+ ]}
+ />
+ </div>
+ )
+}
+
+function WorkflowLink({ id, url }: { id: string; url: string | null }): JSX.Element {
+ if (url) {
+ return (
+ <Link to={url} target="_blank">
+ {id}
+ </Link>
+ )
+ }
+ return (
+ <span>
+ <code>{id}</code>{' '}
+ <span className="text-muted text-xs">
+ (TEMPORAL_UI_HOST not configured — search Temporal UI by workflow id)
+ </span>
+ </span>
+ )
+}
+
+function KeyValueGrid({ rows }: { rows: Array<[string, React.ReactNode]> }): JSX.Element {
+ return (
+ <div className="grid grid-cols-[180px_1fr] gap-y-1 gap-x-3">
+ {rows.map(([label, value]) => (
+ <ContextRow key={label} label={label}>
+ {value}
+ </ContextRow>
+ ))}
+ </div>
+ )
+}
+
+function ContextRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {
+ return (
+ <>
+ <div className="text-muted font-semibold">{label}</div>
+ <div className="break-all">{children}</div>
+ </>
+ )
+}
+
+export default SlackTaskContextScene
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 7d8bb9a2756f..a0b6b3f5f205 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1442,6 +1442,159 @@ export interface RepositoryReadinessResponseApi {
scan?: ScanEvidenceApi
}
+/**
+ * Slack-side identifiers and the mapping metadata for a thread → task lookup.
+ */
+export interface SlackThreadContextThreadApi {
+ /** Echoed input URL. */
+ url: string
+ /** Slack channel id parsed from the URL (e.g. C0ACRAMJUAG). */
+ channel: string
+ /** Slack thread_ts (e.g. 1779956938.619299). */
+ thread_ts: string
+ /**
+ * Slack workspace id (e.g. T…). Null when no mapping exists yet.
+ * @nullable
+ */
+ slack_workspace_id: string | null
+ /**
+ * The Slack user who triggered the task. Null when no mapping exists yet.
+ * @nullable
+ */
+ mentioning_slack_user_id: string | null
+}
+
+/**
+ * The PostHog Task linked to the Slack thread.
+ */
+export interface SlackThreadContextTaskApi {
+ /** UUID of the Task row. */
+ id: string
+ /** Team that owns the task. */
+ team_id: number
+ /** Task title (typically the first ~255 chars of the Slack ask). */
+ title: string
+ /**
+ * Resolved repository in `org/repo` form, or null if the run started without a repo.
+ * @nullable
+ */
+ repository: string | null
+ /** `Task.OriginProduct` (`slack` for slack-originated tasks). */
+ origin_product: string
+ /** When the task was created (server-side timestamp). */
+ created_at: string
+ /** Absolute URL to the task detail page in the PostHog app. */
+ url: string
+}
+
+/**
+ * The internal sandbox run the discovery agent used to pick this run's repo.
+
+Only present when the originating mention was ambiguous (multiple candidate
+repos, no explicit mention) — that's the only path that spins up a research
+sandbox. Null otherwise.
+ */
+export interface SlackThreadContextRepoResearchApi {
+ /** UUID of the internal repo-research Task. */
+ task_id: string
+ /** UUID of the internal repo-research TaskRun. */
+ run_id: string
+ /**
+ * Research run status, or null if the run row could not be loaded.
+ * @nullable
+ */
+ status: string | null
+ /** Temporal workflow id for the research sandbox run (`task-processing-<task_id>-<run_id>`). */
+ task_processing_workflow_id: string
+ /**
+ * Full Temporal Web UI URL for the research workflow; null when `TEMPORAL_UI_HOST` is unset.
+ * @nullable
+ */
+ task_processing_workflow_url: string | null
+ /**
+ * Live sandbox tunnel URL for the research run, when one was attached.
+ * @nullable
+ */
+ sandbox_url: string | null
+ /** Absolute URL to the research task detail page (carries `?ph_debug=true`). */
+ task_view_url: string
+ /**
+ * Presigned S3 URL for the research run's JSONL log transcript (valid ~1 hour).
+ * @nullable
+ */
+ log_url: string | null
+}
+
+/**
+ * One TaskRun and its associated Temporal workflow handles.
+ */
+export interface SlackThreadContextRunApi {
+ /** UUID of the TaskRun row. */
+ id: string
+ /** Run status (queued/in_progress/completed/failed/…). */
+ status: string
+ /** When the run was created. */
+ created_at: string
+ /**
+ * When the run reached a terminal state, or null while still running.
+ * @nullable
+ */
+ completed_at: string | null
+ /**
+ * Live sandbox tunnel URL, when one was attached.
+ * @nullable
+ */
+ sandbox_url: string | null
+ /**
+ * PR URL produced by the run, when one was opened.
+ * @nullable
+ */
+ pr_url: string | null
+ /**
+ * Error captured on terminal failure, or null on success.
+ * @nullable
+ */
+ error_message: string | null
+ /** Temporal workflow id for the sandbox/agent run (`task-processing-<task_id>-<run_id>`). */
+ task_processing_workflow_id: string
+ /**
+ * Full Temporal Web UI URL for the task-processing workflow; null when `TEMPORAL_UI_HOST` is unset.
+ * @nullable
+ */
+ task_processing_workflow_url: string | null
+ /**
+ * Temporal workflow id of the Slack mention that dispatched this run (`posthog-code-mention-<workspace>:<event_id_or_channel:ts>`). Null for runs created before this field was persisted.
+ * @nullable
+ */
+ mention_workflow_id: string | null
+ /**
+ * Full Temporal Web UI URL for the mention dispatch workflow; null when unavailable.
+ * @nullable
+ */
+ mention_workflow_url: string | null
+ /** Absolute URL to the task detail page focused on this run. */
+ task_view_url: string
+ /**
+ * Presigned S3 URL for the run's full JSONL log transcript (valid ~1 hour).
+ * @nullable
+ */
+ log_url: string | null
+ /** The discovery-agent sandbox that picked this run's repo, when the mention was ambiguous. */
+ repo_research: SlackThreadContextRepoResearchApi | null
+}
+
+/**
+ * Top-level response for the slack-thread debug endpoint.
+ */
+export interface SlackThreadContextResponseApi {
+ /** Slack-side identifiers and the mapping metadata. */
+ thread: SlackThreadContextThreadApi
+ /** Linked PostHog Task. Null when no mapping was found for the thread. */
+ task: SlackThreadContextTaskApi | null
+ /** All runs on the task, oldest first. Empty when no mapping was found. */
+ runs: SlackThreadContextRunApi[]
+}
+
export interface TaskSummariesRequestApi {
/**
* Task IDs to fetch summaries for (max 5000). Response is paginated; follow the `next` cursor to retrieve all results.
@@ -1632,6 +1785,14 @@ export type TasksRepositoryReadinessRetrieveParams = {
window_days?: number
}
+export type TasksSlackThreadContextRetrieveParams = {
+ /**
+ * Full Slack permalink to any message in the thread (e.g. https://posthog.slack.com/archives/C…/p1779956938619299). Replies inside the thread are accepted too — the `thread_ts` query param (when present) takes precedence over the in-path message ts.
+ * @minLength 1
+ */
+ url: string
+}
+
export type TasksSummariesCreateParams = {
/**
* Page size for the paginated response.
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 40193b02eb39..1ed7344b02f7 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -22,6 +22,7 @@ import type {
RepositoryReadinessResponseApi,
SandboxEnvironmentApi,
SandboxListParams,
+ SlackThreadContextResponseApi,
TaskApi,
TaskAutomationApi,
TaskAutomationsListParams,
@@ -53,6 +54,7 @@ import type {
TasksRepositoryReadinessRetrieveParams,
TasksRunsListParams,
TasksRunsSessionLogsRetrieveParams,
+ TasksSlackThreadContextRetrieveParams,
TasksSummariesCreateParams,
} from './api.schemas'
@@ -913,6 +915,40 @@ export const tasksRepositoryReadinessRetrieve = async (
})
}
+export const getTasksSlackThreadContextRetrieveUrl = (
+ projectId: string,
+ params: TasksSlackThreadContextRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/tasks/slack_thread_context/?${stringifiedParams}`
+ : `/api/projects/${projectId}/tasks/slack_thread_context/`
+}
+
+/**
+ * PostHog-internal debug tool. Resolves a Slack permalink to the linked task, its runs, the task-processing and mention-dispatch Temporal workflow ids/URLs, and presigned log URLs.
+ * @summary Resolve a Slack thread to its task, runs, and Temporal workflows
+ */
+export const tasksSlackThreadContextRetrieve = async (
+ projectId: string,
+ params: TasksSlackThreadContextRetrieveParams,
+ options?: RequestInit
+): Promise<SlackThreadContextResponseApi> => {
+ return apiMutator<SlackThreadContextResponseApi>(getTasksSlackThreadContextRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getTasksSummariesCreateUrl = (projectId: string, params?: TasksSummariesCreateParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/tasks/frontend/lib/ph-debug.ts b/products/tasks/frontend/lib/ph-debug.ts
new file mode 100644
index 000000000000..6f70b0764108
--- /dev/null
+++ b/products/tasks/frontend/lib/ph-debug.ts
@@ -0,0 +1,24 @@
+import { router } from 'kea-router'
+
+/**
+ * Read the `?ph_debug=true` opt-in from the current URL. When set, the backend
+ * relaxes the per-creator visibility filter on read-only task/run lookups for
+ * PostHog-internal debugging (US-prod team only).
+ *
+ * Use `phDebugQueryParams()` with API helpers that take a params object
+ * (`api.tasks.get`, `api.tasks.runs.get`, …) — they pipe it through
+ * `withQueryString`. Use `phDebugQuerySuffix()` when building a request URL by
+ * hand (e.g. the `/logs/` proxy endpoint that `loadLogs` consumes).
+ */
+function isPhDebugSet(): boolean {
+ const value = router.values.searchParams?.ph_debug
+ return value === 'true' || value === true
+}
+
+export function phDebugQueryParams(): { ph_debug?: 'true' } {
+ return isPhDebugSet() ? { ph_debug: 'true' } : {}
+}
+
+export function phDebugQuerySuffix(): '' | '?ph_debug=true' {
+ return isPhDebugSet() ? '?ph_debug=true' : ''
+}
diff --git a/products/tasks/frontend/logics/slackTaskContextSceneLogic.test.ts b/products/tasks/frontend/logics/slackTaskContextSceneLogic.test.ts
new file mode 100644
index 000000000000..56100baf64b4
--- /dev/null
+++ b/products/tasks/frontend/logics/slackTaskContextSceneLogic.test.ts
@@ -0,0 +1,105 @@
+import { MOCK_TEAM_ID } from 'lib/api.mock'
+
+import { initKeaTests } from '~/test/init'
+
+import { SlackThreadContextResponseApi } from '../generated/api.schemas'
+import { slackTaskContextSceneLogic } from './slackTaskContextSceneLogic'
+
+jest.mock('products/tasks/frontend/generated/api', () => ({
+ tasksSlackThreadContextRetrieve: jest.fn(),
+}))
+
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const generatedApi = require('products/tasks/frontend/generated/api')
+
+const mockResponse: SlackThreadContextResponseApi = {
+ thread: {
+ url: 'https://posthog.slack.com/archives/C0/p1779956938619299',
+ channel: 'C0',
+ thread_ts: '1779956938.619299',
+ slack_workspace_id: 'T_SLACK',
+ mentioning_slack_user_id: 'U_ANDY',
+ },
+ task: {
+ id: 'task-1',
+ team_id: 2,
+ title: 'Investigate flaky test',
+ repository: null,
+ origin_product: 'slack',
+ created_at: '2026-05-28T08:30:00Z',
+ url: 'http://testserver/project/2/tasks/task-1',
+ },
+ runs: [],
+}
+
+describe('slackTaskContextSceneLogic', () => {
+ let logic: ReturnType<typeof slackTaskContextSceneLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = slackTaskContextSceneLogic()
+ logic.mount()
+ ;(generatedApi.tasksSlackThreadContextRetrieve as jest.Mock).mockReset()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it('refuses to submit when url is empty', async () => {
+ await logic.asyncActions.loadResult()
+ expect(generatedApi.tasksSlackThreadContextRetrieve).not.toHaveBeenCalled()
+ expect(logic.values.submissionError?.detail).toBe('Enter a Slack thread URL.')
+ expect(logic.values.result).toBeNull()
+ })
+
+ it('loads a result when the API call succeeds', async () => {
+ ;(generatedApi.tasksSlackThreadContextRetrieve as jest.Mock).mockResolvedValueOnce(mockResponse)
+ logic.actions.setUrl('https://posthog.slack.com/archives/C0/p1779956938619299')
+
+ await logic.asyncActions.loadResult()
+
+ expect(generatedApi.tasksSlackThreadContextRetrieve).toHaveBeenCalledWith(String(MOCK_TEAM_ID), {
+ url: 'https://posthog.slack.com/archives/C0/p1779956938619299',
+ })
+ expect(logic.values.result).toEqual(mockResponse)
+ expect(logic.values.submissionError).toBeNull()
+ })
+
+ it('surfaces a 403 error from the backend', async () => {
+ ;(generatedApi.tasksSlackThreadContextRetrieve as jest.Mock).mockRejectedValueOnce({
+ status: 403,
+ data: { detail: 'Forbidden' },
+ })
+ logic.actions.setUrl('https://posthog.slack.com/archives/C0/p1779956938619299')
+
+ await logic.asyncActions.loadResult()
+
+ expect(logic.values.result).toBeNull()
+ expect(logic.values.submissionError).toEqual({ status: 403, detail: 'Forbidden' })
+ })
+
+ it('surfaces a 404 error from the backend', async () => {
+ ;(generatedApi.tasksSlackThreadContextRetrieve as jest.Mock).mockRejectedValueOnce({
+ status: 404,
+ data: { detail: 'no_mapping' },
+ })
+ logic.actions.setUrl('https://posthog.slack.com/archives/C0/p1779956938619299')
+
+ await logic.asyncActions.loadResult()
+
+ expect(logic.values.submissionError).toEqual({ status: 404, detail: 'no_mapping' })
+ })
+
+ it('clears state on clearResult', async () => {
+ ;(generatedApi.tasksSlackThreadContextRetrieve as jest.Mock).mockResolvedValueOnce(mockResponse)
+ logic.actions.setUrl('https://posthog.slack.com/archives/C0/p1779956938619299')
+ await logic.asyncActions.loadResult()
+ expect(logic.values.result).toEqual(mockResponse)
+
+ logic.actions.clearResult()
+ expect(logic.values.url).toBe('')
+ expect(logic.values.result).toBeNull()
+ expect(logic.values.submissionError).toBeNull()
+ })
+})
diff --git a/products/tasks/frontend/logics/slackTaskContextSceneLogic.ts b/products/tasks/frontend/logics/slackTaskContextSceneLogic.ts
new file mode 100644
index 000000000000..ea0500fef243
--- /dev/null
+++ b/products/tasks/frontend/logics/slackTaskContextSceneLogic.ts
@@ -0,0 +1,82 @@
+import { actions, kea, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { tasksSlackThreadContextRetrieve } from 'products/tasks/frontend/generated/api'
+import { SlackThreadContextResponseApi } from 'products/tasks/frontend/generated/api.schemas'
+
+import type { slackTaskContextSceneLogicType } from './slackTaskContextSceneLogicType'
+
+export type SlackTaskContextSubmissionError = {
+ status: number | null
+ detail: string
+}
+
+export const slackTaskContextSceneLogic = kea<slackTaskContextSceneLogicType>([
+ path(['products', 'tasks', 'frontend', 'logics', 'slackTaskContextSceneLogic']),
+
+ actions({
+ setUrl: (url: string) => ({ url }),
+ clearResult: true,
+ setSubmissionError: (error: SlackTaskContextSubmissionError | null) => ({ error }),
+ }),
+
+ reducers({
+ url: [
+ '' as string,
+ {
+ setUrl: (_, { url }) => url,
+ clearResult: () => '',
+ },
+ ],
+ submissionError: [
+ null as SlackTaskContextSubmissionError | null,
+ {
+ setSubmissionError: (_, { error }) => error,
+ setUrl: () => null,
+ clearResult: () => null,
+ },
+ ],
+ }),
+
+ loaders(({ values, actions }) => ({
+ result: [
+ null as SlackThreadContextResponseApi | null,
+ {
+ loadResult: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (teamId == null) {
+ actions.setSubmissionError({ status: null, detail: 'No active team.' })
+ return null
+ }
+ const trimmed = values.url.trim()
+ if (!trimmed) {
+ actions.setSubmissionError({ status: null, detail: 'Enter a Slack thread URL.' })
+ return null
+ }
+ actions.setSubmissionError(null)
+ try {
+ return await tasksSlackThreadContextRetrieve(String(teamId), { url: trimmed })
+ } catch (e: any) {
+ const status: number | null =
+ typeof e?.status === 'number'
+ ? e.status
+ : typeof e?.response?.status === 'number'
+ ? e.response.status
+ : null
+ const detail: string =
+ e?.data?.detail ?? e?.response?.data?.detail ?? e?.message ?? 'Request failed.'
+ actions.setSubmissionError({ status, detail })
+ return null
+ }
+ },
+ clearResult: () => null,
+ },
+ ],
+ })),
+
+ selectors({
+ canSubmit: [(s) => [s.url, s.resultLoading], (url, loading): boolean => url.trim().length > 0 && !loading],
+ }),
+])
diff --git a/products/tasks/frontend/logics/taskDetailSceneLogic.ts b/products/tasks/frontend/logics/taskDetailSceneLogic.ts
index f4a2810adddf..6649c752ac2b 100644
--- a/products/tasks/frontend/logics/taskDetailSceneLogic.ts
+++ b/products/tasks/frontend/logics/taskDetailSceneLogic.ts
@@ -16,10 +16,12 @@ import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import api from 'lib/api'
+import { isUUIDLike } from 'lib/utils'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { LogEntry, parseLogEvent } from '../lib/parse-logs'
+import { phDebugQueryParams, phDebugQuerySuffix } from '../lib/ph-debug'
import { TaskRun, TaskRunStatus } from '../types'
import type { taskDetailSceneLogicType } from './taskDetailSceneLogicType'
import { TaskLogicProps, taskLogic } from './taskLogic'
@@ -222,7 +224,7 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
[] as TaskRun[],
{
loadRuns: async () => {
- const response = await api.tasks.runs.list(props.taskId)
+ const response = await api.tasks.runs.list(props.taskId, phDebugQueryParams())
return response.results
},
},
@@ -234,10 +236,10 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
if (!values.selectedRunId) {
return null
}
- const run = await api.tasks.runs.get(props.taskId, values.selectedRunId)
+ const run = await api.tasks.runs.get(props.taskId, values.selectedRunId, phDebugQueryParams())
// Use proxy endpoint to avoid CORS issues with direct S3 access
actions.loadLogs({
- url: `/api/projects/${values.currentProjectId}/tasks/${props.taskId}/runs/${values.selectedRunId}/logs/`,
+ url: `/api/projects/${values.currentProjectId}/tasks/${props.taskId}/runs/${values.selectedRunId}/logs/${phDebugQuerySuffix()}`,
})
return run
},
@@ -536,7 +538,7 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
return
}
const runIdFromUrl = searchParams.runId
- if (runIdFromUrl && runIdFromUrl !== values.selectedRunId) {
+ if (runIdFromUrl && isUUIDLike(runIdFromUrl) && runIdFromUrl !== values.selectedRunId) {
actions.setSelectedRunId(runIdFromUrl, props.taskId)
}
},
diff --git a/products/tasks/frontend/logics/taskLogic.ts b/products/tasks/frontend/logics/taskLogic.ts
index 156ed1a4c3cf..b55423e195ea 100644
--- a/products/tasks/frontend/logics/taskLogic.ts
+++ b/products/tasks/frontend/logics/taskLogic.ts
@@ -6,6 +6,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { phDebugQueryParams } from '../lib/ph-debug'
import { Task, type TaskUpsertProps } from '../types'
import type { taskLogicType } from './taskLogicType'
import { tasksLogic } from './tasksLogic'
@@ -23,7 +24,7 @@ export const taskLogic = kea<taskLogicType>([
null as Task | null,
{
loadTask: async () => {
- return await api.tasks.get(props.taskId)
+ return await api.tasks.get(props.taskId, phDebugQueryParams())
},
runTask: async () => {
const response = await api.tasks.run(props.taskId)
diff --git a/products/tasks/manifest.tsx b/products/tasks/manifest.tsx
index 1bb3c620628d..d22afcf4a815 100644
--- a/products/tasks/manifest.tsx
+++ b/products/tasks/manifest.tsx
@@ -20,15 +20,23 @@ export const manifest: ProductManifest = {
projectBased: true,
activityScope: 'TaskDetail',
},
+ // Hidden internal debug scene. No nav entry — reachable only by typing the URL.
+ SlackTaskContext: {
+ name: 'Slack task context',
+ import: () => import('./frontend/SlackTaskContextScene'),
+ projectBased: true,
+ },
},
routes: {
'/tasks': ['TaskTracker', 'taskTracker'],
'/tasks/:taskId': ['TaskDetail', 'taskDetail'],
+ '/slack-task-context': ['SlackTaskContext', 'slackTaskContext'],
},
redirects: {},
urls: {
taskTracker: (): string => '/tasks',
taskDetail: (taskId: string | number): string => `/tasks/${taskId}`,
+ slackTaskContext: (): string => '/slack-task-context',
},
fileSystemTypes: {
task: {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7ec56f1d1660..a96580f57136 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -36369,6 +36369,159 @@ export namespace Schemas {
has_more?: boolean;
}
+ /**
+ * The internal sandbox run the discovery agent used to pick this run's repo.
+
+ Only present when the originating mention was ambiguous (multiple candidate
+ repos, no explicit mention) — that's the only path that spins up a research
+ sandbox. Null otherwise.
+ */
+ export interface SlackThreadContextRepoResearch {
+ /** UUID of the internal repo-research Task. */
+ task_id: string;
+ /** UUID of the internal repo-research TaskRun. */
+ run_id: string;
+ /**
+ * Research run status, or null if the run row could not be loaded.
+ * @nullable
+ */
+ status: string | null;
+ /** Temporal workflow id for the research sandbox run (`task-processing-<task_id>-<run_id>`). */
+ task_processing_workflow_id: string;
+ /**
+ * Full Temporal Web UI URL for the research workflow; null when `TEMPORAL_UI_HOST` is unset.
+ * @nullable
+ */
+ task_processing_workflow_url: string | null;
+ /**
+ * Live sandbox tunnel URL for the research run, when one was attached.
+ * @nullable
+ */
+ sandbox_url: string | null;
+ /** Absolute URL to the research task detail page (carries `?ph_debug=true`). */
+ task_view_url: string;
+ /**
+ * Presigned S3 URL for the research run's JSONL log transcript (valid ~1 hour).
+ * @nullable
+ */
+ log_url: string | null;
+ }
+
+ /**
+ * Slack-side identifiers and the mapping metadata for a thread → task lookup.
+ */
+ export interface SlackThreadContextThread {
+ /** Echoed input URL. */
+ url: string;
+ /** Slack channel id parsed from the URL (e.g. C0ACRAMJUAG). */
+ channel: string;
+ /** Slack thread_ts (e.g. 1779956938.619299). */
+ thread_ts: string;
+ /**
+ * Slack workspace id (e.g. T…). Null when no mapping exists yet.
+ * @nullable
+ */
+ slack_workspace_id: string | null;
+ /**
+ * The Slack user who triggered the task. Null when no mapping exists yet.
+ * @nullable
+ */
+ mentioning_slack_user_id: string | null;
+ }
+
+ /**
+ * The PostHog Task linked to the Slack thread.
+ */
+ export interface SlackThreadContextTask {
+ /** UUID of the Task row. */
+ id: string;
+ /** Team that owns the task. */
+ team_id: number;
+ /** Task title (typically the first ~255 chars of the Slack ask). */
+ title: string;
+ /**
+ * Resolved repository in `org/repo` form, or null if the run started without a repo.
+ * @nullable
+ */
+ repository: string | null;
+ /** `Task.OriginProduct` (`slack` for slack-originated tasks). */
+ origin_product: string;
+ /** When the task was created (server-side timestamp). */
+ created_at: string;
+ /** Absolute URL to the task detail page in the PostHog app. */
+ url: string;
+ }
+
+ /**
+ * One TaskRun and its associated Temporal workflow handles.
+ */
+ export interface SlackThreadContextRun {
+ /** UUID of the TaskRun row. */
+ id: string;
+ /** Run status (queued/in_progress/completed/failed/…). */
+ status: string;
+ /** When the run was created. */
+ created_at: string;
+ /**
+ * When the run reached a terminal state, or null while still running.
+ * @nullable
+ */
+ completed_at: string | null;
+ /**
+ * Live sandbox tunnel URL, when one was attached.
+ * @nullable
+ */
+ sandbox_url: string | null;
+ /**
+ * PR URL produced by the run, when one was opened.
+ * @nullable
+ */
+ pr_url: string | null;
+ /**
+ * Error captured on terminal failure, or null on success.
+ * @nullable
+ */
+ error_message: string | null;
+ /** Temporal workflow id for the sandbox/agent run (`task-processing-<task_id>-<run_id>`). */
+ task_processing_workflow_id: string;
+ /**
+ * Full Temporal Web UI URL for the task-processing workflow; null when `TEMPORAL_UI_HOST` is unset.
+ * @nullable
+ */
+ task_processing_workflow_url: string | null;
+ /**
+ * Temporal workflow id of the Slack mention that dispatched this run (`posthog-code-mention-<workspace>:<event_id_or_channel:ts>`). Null for runs created before this field was persisted.
+ * @nullable
+ */
+ mention_workflow_id: string | null;
+ /**
+ * Full Temporal Web UI URL for the mention dispatch workflow; null when unavailable.
+ * @nullable
+ */
+ mention_workflow_url: string | null;
+ /** Absolute URL to the task detail page focused on this run. */
+ task_view_url: string;
+ /**
+ * Presigned S3 URL for the run's full JSONL log transcript (valid ~1 hour).
+ * @nullable
+ */
+ log_url: string | null;
+ /** The discovery-agent sandbox that picked this run's repo, when the mention was ambiguous. */
+ repo_research: SlackThreadContextRepoResearch | null;
+ }
+
+ /**
+ * Top-level response for the slack-thread debug endpoint.
+ */
+ export interface SlackThreadContextResponse {
+ /** Slack-side identifiers and the mapping metadata. */
+ thread: SlackThreadContextThread;
+ /** Linked PostHog Task. Null when no mapping was found for the thread. */
+ task: SlackThreadContextTask | null;
+ /** All runs on the task, oldest first. Empty when no mapping was found. */
+ runs: SlackThreadContextRun[];
+ }
+
/**
* * `none` - none
* `auto` - auto
@@ -47467,6 +47620,14 @@ export namespace Schemas {
window_days?: number;
};
+ export type TasksSlackThreadContextRetrieveParams = {
+ /**
+ * Full Slack permalink to any message in the thread (e.g. https://posthog.slack.com/archives/C…/p1779956938619299). Replies inside the thread are accepted too — the `thread_ts` query param (when present) takes precedence over the in-path message ts.
+ * @minLength 1
+ */
+ url: string;
+ };
+
export type TasksSummariesCreateParams = {
/**
* Page size for the paginated response.