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(user-interviews): remove the user research product (#109605)

Paul D'Ambra97cd01df38be
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.md
index 6cccf27b515b..c06bbd83e195 100644
--- a/.agents/skills/adding-inbound-webhooks/SKILL.md
+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md
@@ -58,7 +58,7 @@ Reset the process-cached registry and the dedup cache between tests with `reset_
## Add a provider
Create `posthog/ingress/<provider>/` with an `__init__.py` and a `provider.py`.
-Copy `github/` for the full shape, or `vapi/` for a small one.
+Copy `github/` for the full shape, or `pandadoc/` for a small one.
Copy the layout, not the behavior: a provider package holds only what is specific to its third party. A need that a second provider could share becomes a lane, a scheme option or a `WebhookProvider` attribute, the way `retry_status` and `throttle_class` did. A true one-off stays in the provider with a `# One-off:` comment that says why no other provider needs it.
`provider.py` holds three things:
@@ -75,7 +75,7 @@ Copy the layout, not the behavior: a provider package holds only what is specifi
Three exist. Configure one; do not write a fourth without reading [the Schemes section of the package README](../../../posthog/ingress/README.md#schemes).
-- `HmacSha256` (`verify/schemes.py`) — a shared secret over the raw body. Covers hex or base64, an optional prefix, and the `v0:{timestamp}:{body}` input with a replay window that Slack and Customer.io sign. GitHub, Slack, PandaDoc, Vapi and Customer.io all use it.
+- `HmacSha256` (`verify/schemes.py`) — a shared secret over the raw body. Covers hex or base64, an optional prefix, and the `v0:{timestamp}:{body}` input with a replay window that Slack and Customer.io sign. GitHub, Slack, PandaDoc and Customer.io all use it.
- `SnsSignature` (`verify/schemes.py`) — the AWS SNS envelope check plus a topic-ARN allowlist. The RSA work stays with a caller-supplied verifier.
- `BearerJwt` (`verify/jwt.py`) — a `Bearer` token signed as a JWT, checked against the issuer's published JWKS. Its `facts` are the verified claims. The incarnation supplies the JWKS URI, the audience and the issuer allowlist as callables, and caches any discovery it does to find the URI. An endpoint on this scheme sets `throttle_class`, because an unsigned request costs a signing-key lookup.
diff --git a/.agents/skills/routing-outbound-api-calls/SKILL.md b/.agents/skills/routing-outbound-api-calls/SKILL.md
index f5dd8dd47219..40161d92cdf2 100644
--- a/.agents/skills/routing-outbound-api-calls/SKILL.md
+++ b/.agents/skills/routing-outbound-api-calls/SKILL.md
@@ -59,7 +59,7 @@ Copy the closest reference domain for the file layout:
| ------------------------------------ | -------------------------------- |
| Sync, gated, with rate-limit headers | `posthog/egress/github/` |
| Sync, gated, no rate-limit headers | `posthog/egress/firecrawl/` |
-| Record-only, secret identity | `posthog/egress/vapi/` |
+| Record-only, no gate | `posthog/egress/openai_auth/` |
| Async (aiohttp) | `posthog/egress/harmonic/` |
| Vendor SDK | `posthog/egress/slack/client.py` |
diff --git a/.semgrep/rules/devex/prefer-codegen-api-namespaced.yaml b/.semgrep/rules/devex/prefer-codegen-api-namespaced.yaml
index 45b8125fa2b1..757025b043e3 100644
--- a/.semgrep/rules/devex/prefer-codegen-api-namespaced.yaml
+++ b/.semgrep/rules/devex/prefer-codegen-api-namespaced.yaml
@@ -1286,40 +1286,6 @@ rules:
- '**/__mocks__/**'
- '**/mocks/**'
- - id: prefer-codegen-api-namespaced-user_interviews
- message: >-
- Manual `api.<namespace>.<method>(...)` call on a user_interviews namespace. The namespace
- builds its URL in `frontend/src/lib/api.ts`, and this product's generated client
- already covers that URL. Use `products/user_interviews/frontend/generated/api.ts`.
-
- Informational while the backlog is worked down, but a call this pull request adds
- fails the job. `hogli product:maturity --codegen user_interviews` lists the call sites.
-
- Agents: invoke the `adopting-generated-api-types` skill
- (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration
- workflow.
-
- If no generated equivalent is available yet (endpoint missing OpenAPI tags,
- dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-user_interviews`
- above this line - the maturity tooling continues to track tagged sites.
- severity: WARNING
- languages: [typescript, javascript]
- pattern-either:
- - pattern: api.userInterviews.$METHOD(...)
- - pattern: api.userInterviews.$MEMBER.$METHOD(...)
- paths:
- include:
- - '/products/user_interviews/frontend/'
- - '/frontend/src/'
- exclude:
- - '/frontend/src/lib/api.ts'
- - '**/generated/**'
- - '**/*.test.ts'
- - '**/*.test.tsx'
- - '**/*.stories.tsx'
- - '**/__mocks__/**'
- - '**/mocks/**'
-
- id: prefer-codegen-api-namespaced-warehouse_sources
message: >-
Manual `api.<namespace>.<method>(...)` call on a warehouse_sources namespace. The namespace
diff --git a/common/storybook/storybook-timings.json b/common/storybook/storybook-timings.json
index d151daa2815e..45c01f325ab8 100644
--- a/common/storybook/storybook-timings.json
+++ b/common/storybook/storybook-timings.json
@@ -3,10 +3,6 @@
"chromium": 13.862,
"webkit": 3.975
},
- "frontend/src/exporter/stories/ExporterInterview.stories.tsx": {
- "chromium": 29.053,
- "webkit": 1.908
- },
"frontend/src/exporter/stories/ExporterOther.stories.tsx": {
"chromium": 25.232,
"webkit": 4.504
@@ -1343,10 +1339,6 @@
"chromium": 19.529,
"webkit": 3.46
},
- "frontend/src/scenes/user-research/UserInterviews.stories.tsx": {
- "chromium": 14.124,
- "webkit": 3.767
- },
"frontend/src/scenes/web-analytics/CalendarHeatMap/CalendarHeatMap.stories.tsx": {
"chromium": 21.706,
"webkit": 2.758
@@ -1843,14 +1835,6 @@
"chromium": 11.993,
"webkit": 2.61
},
- "products/user_interviews/frontend/InvitePreviewModal.stories.tsx": {
- "chromium": 36.53,
- "webkit": 3.171
- },
- "products/user_interviews/frontend/TranscriptChat.stories.tsx": {
- "chromium": 28.639,
- "webkit": 3.381
- },
"products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx": {
"chromium": 9.533,
"webkit": 2.741
diff --git a/docs/internal/url-routing.md b/docs/internal/url-routing.md
index 9ba81b81b466..fd2417c6ba36 100644
--- a/docs/internal/url-routing.md
+++ b/docs/internal/url-routing.md
@@ -29,13 +29,13 @@ A product declares its root paths in `products/<product>/backend/routes.py`, bes
- `webhook_urlpatterns`, mounted at `webhooks/<product>/`
`<product>` is the product directory name, underscores included.
-Routes in each list are relative to the mount, so `path("vapi_webhook/", ...)` in `products/user_interviews/` serves `/api/user_interviews/vapi_webhook/`.
+Routes in each list are relative to the mount, so `path("pandadoc", ...)` in `products/legal_documents/` serves `/api/legal_documents/pandadoc`.
`posthog/product_urls.py` turns each list into a `path(<prefix>, include(<list>))` mount, and `posthog/urls.py` splices every product's mounts into one slot: after every core `api/` route, and before the `^api.+` fallback and the frontend catch-all.
Precedence stays one list to read, and a product that adds a path does not touch core.
The prefix holds by construction: a route inside the mount cannot address anything outside it, so a product cannot shadow a core route outside its own prefix.
-Inside its prefix, a core route listed above the slot still wins, which is how `api/user_interviews/share/<token>/start_call/` stays in core.
+Inside its prefix, a core route listed above the slot still wins.
`include()` receives the list, not the module, so Django sets no application namespace and `reverse("<name>")` keeps working unchanged.
A routes module that declares any other url patterns list raises `ImproperlyConfigured` when the URL conf loads, rather than having its routes dropped silently. That covers the old flat `urlpatterns` and a near miss such as `webhooks_urlpatterns`, and the error names both valid lists.
diff --git a/ee/hogai/chat_agent/mode_manager.py b/ee/hogai/chat_agent/mode_manager.py
index c23a4e441a52..0ed53a7f7967 100644
--- a/ee/hogai/chat_agent/mode_manager.py
+++ b/ee/hogai/chat_agent/mode_manager.py
@@ -29,18 +29,9 @@ from ee.hogai.core.agent_modes.presets.product_analytics import (
from ee.hogai.core.agent_modes.presets.session_replay import chat_agent_plan_session_replay_agent, session_replay_agent
from ee.hogai.core.agent_modes.presets.sql import chat_agent_plan_sql_agent, sql_agent
from ee.hogai.core.agent_modes.presets.survey import chat_agent_plan_survey_agent, subagent_survey_agent, survey_agent
-from ee.hogai.core.agent_modes.presets.user_interview import (
- chat_agent_plan_user_interview_agent,
- subagent_user_interview_agent,
- user_interview_agent,
-)
from ee.hogai.core.agent_modes.prompt_builder import AgentPromptBuilder
from ee.hogai.core.agent_modes.toolkit import AgentToolkit, AgentToolkitManager
-from ee.hogai.utils.feature_flags import (
- has_customer_analytics_mode_feature_flag,
- has_plan_mode_feature_flag,
- has_user_interview_mode_feature_flag,
-)
+from ee.hogai.utils.feature_flags import has_customer_analytics_mode_feature_flag, has_plan_mode_feature_flag
from ee.hogai.utils.types.base import AssistantState, NodePath
# Execution and plan mode definitions - fictitious modes used to trigger transition in and out of plan mode
@@ -90,10 +81,7 @@ SUBAGENT_CHAT_AGENT_MODE_REGISTRY: dict[AgentMode, AgentModeDefinition] = {
def get_plan_mode_registry(team: Team, user: User) -> dict[AgentMode, AgentModeDefinition]:
- registry = dict(DEFAULT_CHAT_AGENT_PLAN_MODE_REGISTRY)
- if has_user_interview_mode_feature_flag(team, user):
- registry[AgentMode.USER_INTERVIEW] = chat_agent_plan_user_interview_agent
- return registry
+ return dict(DEFAULT_CHAT_AGENT_PLAN_MODE_REGISTRY)
def get_execution_mode_registry(team: Team, user: User) -> dict[AgentMode, AgentModeDefinition]:
@@ -102,8 +90,6 @@ def get_execution_mode_registry(team: Team, user: User) -> dict[AgentMode, Agent
This is the registry that will be available after transitioning out of plan mode.
"""
registry = dict(DEFAULT_CHAT_AGENT_MODE_REGISTRY)
- if has_user_interview_mode_feature_flag(team, user):
- registry[AgentMode.USER_INTERVIEW] = user_interview_agent
if has_customer_analytics_mode_feature_flag(team, user):
registry[AgentMode.CUSTOMER_ANALYTICS] = customer_analytics_agent
return registry
@@ -157,10 +143,7 @@ class ChatAgentModeManager(AgentModeManager):
@property
def _subagent_mode_registry(self) -> dict[AgentMode, AgentModeDefinition]:
- registry = dict(SUBAGENT_CHAT_AGENT_MODE_REGISTRY)
- if has_user_interview_mode_feature_flag(self._team, self._user):
- registry[AgentMode.USER_INTERVIEW] = subagent_user_interview_agent
- return registry
+ return dict(SUBAGENT_CHAT_AGENT_MODE_REGISTRY)
@property
def prompt_builder_class(self) -> type[AgentPromptBuilder]:
diff --git a/ee/hogai/chat_agent/prompts/base.py b/ee/hogai/chat_agent/prompts/base.py
index 5505a48c76d2..08702d891a61 100644
--- a/ee/hogai/chat_agent/prompts/base.py
+++ b/ee/hogai/chat_agent/prompts/base.py
@@ -63,7 +63,6 @@ Created data is used by the user on the PostHog's website to perform business ac
- Feature flags – feature flags that the user creates to control the feature rollout in their product.
- Notebooks – notebooks that the user creates to perform business analysis.
- Error tracking issues – issues that the user creates to track errors in their product.
-- User interview topics – topics that drive AI voice agent interviews with selected users, with questions you author.
- Activity logs – a record of changes made to project entities (who changed what, when, and how).
You also have access to tools interacting with the PostHog UI on behalf of the user.
@@ -214,7 +213,6 @@ PostHog products:
- **Feature flags** – targeting rules, gradual rollouts, kill switches
- **Experiments** – A/B testing and no-code A/B testing with statistical rigor
- **Surveys** – in-app questionnaires, NPS, user feedback collection
-- **User interviews** – AI voice agent interviews with selected users, organized into topics with questions you author
- **LLM observability** – monitor AI/LLM application costs, latency, and quality
- **Data warehouse** – connect external data sources (Stripe, Hubspot, Postgres, etc.) for combined analysis
- **Data pipelines (CDP)** – import data from 20+ sources, transform events in real-time, and export to external destinations
diff --git a/ee/hogai/core/agent_modes/presets/test/test_user_interview_preset.py b/ee/hogai/core/agent_modes/presets/test/test_user_interview_preset.py
deleted file mode 100644
index dba762d153c6..000000000000
--- a/ee/hogai/core/agent_modes/presets/test/test_user_interview_preset.py
+++ /dev/null
@@ -1,59 +0,0 @@
-from unittest import TestCase
-from unittest.mock import MagicMock
-
-from parameterized import parameterized
-
-from posthog.schema import AgentMode
-
-from ..user_interview import (
- ReadOnlyUserInterviewAgentToolkit,
- UserInterviewAgentToolkit,
- chat_agent_plan_user_interview_agent,
- subagent_user_interview_agent,
- user_interview_agent,
-)
-
-
-def _make_toolkit(toolkit_class):
- # The `tools` property only imports and returns classes — it never touches `_team`,
- # `_user`, or `_context_manager`, so mocks are sufficient and keep the test DB-free.
- return toolkit_class(team=MagicMock(), user=MagicMock(), context_manager=MagicMock())
-
-
-class TestUserInterviewAgentToolkit(TestCase):
- def test_toolkit_includes_both_user_interview_tools(self):
- tool_class_names = [tool_class.__name__ for tool_class in _make_toolkit(UserInterviewAgentToolkit).tools]
-
- self.assertIn("CreateUserInterviewTopicTool", tool_class_names)
- self.assertIn("AnalyzeUserInterviewsTool", tool_class_names)
-
- def test_read_only_toolkit_excludes_create_tool(self):
- tool_class_names = [
- tool_class.__name__ for tool_class in _make_toolkit(ReadOnlyUserInterviewAgentToolkit).tools
- ]
-
- self.assertEqual(tool_class_names, ["AnalyzeUserInterviewsTool"])
-
- def test_toolkit_has_trajectory_examples(self):
- examples = UserInterviewAgentToolkit.POSITIVE_TODO_EXAMPLES
- self.assertIsNotNone(examples)
- self.assertGreater(len(examples), 0)
-
- @parameterized.expand(
- [
- ("user_interview_agent", user_interview_agent),
- ("subagent_user_interview_agent", subagent_user_interview_agent),
- ("chat_agent_plan_user_interview_agent", chat_agent_plan_user_interview_agent),
- ]
- )
- def test_mode_definition_uses_user_interview_mode(self, _name, definition):
- self.assertEqual(definition.mode, AgentMode.USER_INTERVIEW)
-
- @parameterized.expand(
- [
- ("subagent_user_interview_agent", subagent_user_interview_agent),
- ("chat_agent_plan_user_interview_agent", chat_agent_plan_user_interview_agent),
- ]
- )
- def test_read_only_variants_use_read_only_toolkit(self, _name, definition):
- self.assertEqual(definition.toolkit_class, ReadOnlyUserInterviewAgentToolkit)
diff --git a/ee/hogai/core/agent_modes/presets/user_interview.py b/ee/hogai/core/agent_modes/presets/user_interview.py
deleted file mode 100644
index a69bb3d54d4f..000000000000
--- a/ee/hogai/core/agent_modes/presets/user_interview.py
+++ /dev/null
@@ -1,130 +0,0 @@
-from dataclasses import replace
-from typing import TYPE_CHECKING
-
-from posthog.schema import AgentMode
-
-from ee.hogai.chat_agent.executables import ChatAgentPlanExecutable, ChatAgentPlanToolsExecutable
-from ee.hogai.core.agent_modes.factory import AgentModeDefinition
-from ee.hogai.core.agent_modes.toolkit import AgentToolkit
-from ee.hogai.tools.todo_write import TodoWriteExample
-
-if TYPE_CHECKING:
- from ee.hogai.tool import MaxTool
-
-
-POSITIVE_EXAMPLE_CREATE_TOPIC_BY_EMAILS = """
-User: Set up an interview about the new dashboard onboarding with [email protected] and [email protected]
-Assistant: I'll create an interview topic about the dashboard onboarding flow targeting those two users.
-*Uses create_user_interview_topic with topic, interviewee_emails, and 3-5 open-ended questions*
-The topic is created — you can send invites from the topic page.
-""".strip()
-
-POSITIVE_EXAMPLE_CREATE_TOPIC_BY_EMAILS_REASONING = """
-The assistant used create_user_interview_topic because:
-1. The user wants live AI voice interviews, not an in-app survey
-2. Participant emails are provided directly, so no cohort/persons lookup is needed
-3. The assistant drafts conversational, open-ended questions in topic order
-""".strip()
-
-POSITIVE_EXAMPLE_CREATE_TOPIC_FROM_COHORT = """
-User: Talk to users in the "Power users" cohort about how they use saved insights
-Assistant: I'll first resolve the cohort to distinct IDs, then create the interview topic.
-*Creates todo list with the following items:*
-1. Search for the "Power users" cohort and resolve its members to distinct IDs
-2. Create the interview topic with those distinct IDs and a question list
-*Uses search with kind: "cohorts" and query: "Power users"*
-After resolving members, the assistant calls create_user_interview_topic with interviewee_distinct_ids.
-""".strip()
-
-POSITIVE_EXAMPLE_CREATE_TOPIC_FROM_COHORT_REASONING = """
-The assistant used the todo list because:
-1. Targeting by cohort needs two steps: resolve the cohort, then create the topic
-2. create_user_interview_topic accepts distinct IDs or emails but does not look up cohorts itself
-3. Breaking it into steps prevents inventing or mis-targeting participants
-""".strip()
-
-POSITIVE_EXAMPLE_ANALYZE_INTERVIEWS = """
-User: What patterns are coming out of our recent user interviews?
-Assistant: I'll analyze the interview summaries for common themes.
-*Uses analyze_user_interviews with an analysis_angle describing the question*
-Here are the themes I found across the interviews: ...
-""".strip()
-
-POSITIVE_EXAMPLE_ANALYZE_INTERVIEWS_REASONING = """
-The assistant used analyze_user_interviews because:
-1. The user wants insights from already-conducted interviews, not to create a new topic
-2. The tool reads existing interview summaries for the team
-3. The analysis_angle steers the LLM toward the user's question
-""".strip()
-
-
-USER_INTERVIEW_MODE_DESCRIPTION = (
- "Specialized mode for setting up and analyzing live AI voice user interviews. "
- "Use this mode when the user wants to interview users, talk to customers, run user research "
- "calls, or analyze interview transcripts. This is NOT a survey mode — interviews are live "
- "voice conversations, not in-app survey widgets."
-)
-
-
-class UserInterviewAgentToolkit(AgentToolkit):
- POSITIVE_TODO_EXAMPLES = [
- TodoWriteExample(
- example=POSITIVE_EXAMPLE_CREATE_TOPIC_BY_EMAILS,
- reasoning=POSITIVE_EXAMPLE_CREATE_TOPIC_BY_EMAILS_REASONING,
- ),
- TodoWriteExample(
- example=POSITIVE_EXAMPLE_CREATE_TOPIC_FROM_COHORT,
- reasoning=POSITIVE_EXAMPLE_CREATE_TOPIC_FROM_COHORT_REASONING,
- ),
- TodoWriteExample(
- example=POSITIVE_EXAMPLE_ANALYZE_INTERVIEWS,
- reasoning=POSITIVE_EXAMPLE_ANALYZE_INTERVIEWS_REASONING,
- ),
- ]
-
- @property
- def tools(self) -> list[type["MaxTool"]]:
- from products.user_interviews.backend.facade.max_tools import (
- AnalyzeUserInterviewsTool,
- CreateUserInterviewTopicTool,
- )
-
- tools: list[type[MaxTool]] = [CreateUserInterviewTopicTool, AnalyzeUserInterviewsTool]
- return tools
-
-
-user_interview_agent = AgentModeDefinition(
- mode=AgentMode.USER_INTERVIEW,
- mode_description=USER_INTERVIEW_MODE_DESCRIPTION,
- toolkit_class=UserInterviewAgentToolkit,
-)
-
-
-class ReadOnlyUserInterviewAgentToolkit(AgentToolkit):
- """User interview toolkit for subagents — only includes AnalyzeUserInterviewsTool (read-only)."""
-
- @property
- def tools(self) -> list[type["MaxTool"]]:
- from products.user_interviews.backend.facade.max_tools import AnalyzeUserInterviewsTool
-
- return [AnalyzeUserInterviewsTool]
-
-
-READ_ONLY_USER_INTERVIEW_MODE_DESCRIPTION = (
- "Specialized mode for analyzing user interviews. Read summaries of past interviews to extract "
- "themes, pain points, and feature requests."
-)
-
-subagent_user_interview_agent = replace(
- user_interview_agent,
- toolkit_class=ReadOnlyUserInterviewAgentToolkit,
- mode_description=READ_ONLY_USER_INTERVIEW_MODE_DESCRIPTION,
-)
-
-chat_agent_plan_user_interview_agent = AgentModeDefinition(
- mode=AgentMode.USER_INTERVIEW,
- mode_description=READ_ONLY_USER_INTERVIEW_MODE_DESCRIPTION,
- toolkit_class=ReadOnlyUserInterviewAgentToolkit,
- node_class=ChatAgentPlanExecutable,
- tools_node_class=ChatAgentPlanToolsExecutable,
-)
diff --git a/ee/hogai/research_agent/prompts/base.py b/ee/hogai/research_agent/prompts/base.py
index c794c8a2f886..cb0f863b568d 100644
--- a/ee/hogai/research_agent/prompts/base.py
+++ b/ee/hogai/research_agent/prompts/base.py
@@ -26,7 +26,6 @@ Created data is used by the user on the PostHog's website to perform business ac
- Feature flags – feature flags that the user creates to control the feature rollout in their product.
- Notebooks – notebooks that the user creates to perform business analysis.
- Error tracking issues – issues that the user creates to track errors in their product.
-- User interview topics – topics that drive AI voice agent interviews with selected users, with questions you author.
Before using a tool, say what you're about to do, in one sentence.
Do not generate any code like Python scripts. Users don't have the ability to run code.
diff --git a/ee/hogai/test/test_tool.py b/ee/hogai/test/test_tool.py
index 51e2fcc6e9c9..14e40b88fb90 100644
--- a/ee/hogai/test/test_tool.py
+++ b/ee/hogai/test/test_tool.py
@@ -465,7 +465,6 @@ class TestToolAccessControlDeclarations(BaseTest):
"execute_sql",
"generate_hogql_query",
"fix_hogql_query",
- "analyze_user_interviews",
"call_mcp_server", # Scoped to user's own MCP installations (team + user filtered) but no protected resources modified
"diagnose_proxy", # Explicit OrganizationMembership.Level >= ADMIN check inside _arun_impl; resource-level RBAC doesn't recognize membership level so we can't use get_required_resource_access here
}
diff --git a/ee/hogai/utils/feature_flags.py b/ee/hogai/utils/feature_flags.py
index fd908b893613..7cacbac50f70 100644
--- a/ee/hogai/utils/feature_flags.py
+++ b/ee/hogai/utils/feature_flags.py
@@ -125,16 +125,6 @@ def has_conversation_task_mirror_feature_flag(team: Team, user: User) -> bool:
)
-def has_user_interview_mode_feature_flag(team: Team, user: User) -> bool:
- return feature_enabled_or_false(
- "user-interviews",
- str(user.distinct_id),
- groups={"organization": str(team.organization_id)},
- group_properties={"organization": {"id": str(team.organization_id)}},
- send_feature_flag_events=False,
- )
-
-
def has_customer_analytics_mode_feature_flag(team: Team, user: User) -> bool:
return feature_enabled_or_false(
"customer-analytics-csp",
diff --git a/ee/tasks/slack.py b/ee/tasks/slack.py
index dcd104643371..763054384608 100644
--- a/ee/tasks/slack.py
+++ b/ee/tasks/slack.py
@@ -51,9 +51,9 @@ def _handle_slack_event(event_payload: Any) -> None:
# First we try and get the sharingconfig for the given link
try:
- sharing_config: SharingConfiguration = SharingConfiguration.objects.get(
- access_token=share_token, enabled=True
- )
+ sharing_config: SharingConfiguration = SharingConfiguration.objects.filter(
+ SharingConfiguration.without_retired_resources_q()
+ ).get(access_token=share_token, enabled=True)
except SharingConfiguration.DoesNotExist:
logger.info("No SharingConfiguration found")
continue
diff --git a/frontend/package.json b/frontend/package.json
index f7c611b6979b..971754b61987 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -152,7 +152,6 @@
"@posthog/products-tasks": "workspace:*",
"@posthog/products-today": "workspace:*",
"@posthog/products-tracing": "workspace:*",
- "@posthog/products-user-interviews": "workspace:*",
"@posthog/products-visual-review": "workspace:*",
"@posthog/products-warehouse-sources": "workspace:*",
"@posthog/products-web-analytics": "workspace:*",
@@ -202,7 +201,6 @@
"@tiptap/react": "3.20.6",
"@tiptap/starter-kit": "3.20.6",
"@tiptap/suggestion": "3.20.6",
- "@vapi-ai/web": "2.5.2",
"@vitejs/plugin-react": "catalog:",
"@xterm/addon-fit": "0.10.0",
"@xterm/addon-webgl": "0.18.0",
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f1ffb24a600e..fe62e609c47b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2308,10 +2308,6 @@ snapshots:
hash: v1.k794b7964.48584f21d48763853573991689622b0af35fac432c0cadaef6a6a75d0f0c9212.6EHjBCMPD2ZHVQrc_tGG8hCLGL8HVk-YRmZDXj3GZHE
components-product-empty-state--transformations-needs-setup--light:
hash: v1.k794b7964.7dc310b2337e6ab0a748d155e418eef0e8cb898b0fd1508da33ca2dfbb9d23f9.jYRYFePNajfiGMNSMsg-iHtcS8Tn0rXmSVvNlPzjH-k
- components-product-empty-state--user-interviews-needs-setup--dark:
- hash: v1.k794b7964.d6755cd66e42f856d03984558b3199db8ffae489ba6724566d055d6ef62e73ca.3zwfUetLHLrs4BwJ5wg7vTTOIhCYTjgI-TKYTTjdFUI
- components-product-empty-state--user-interviews-needs-setup--light:
- hash: v1.k794b7964.77cf80da4377ee0deae418cf8f1539ddeb989182c3e681b873a06bfa2acd52bd.IZPNE4KjQuQ6vL1375iXUtiz_5hLYGT_Ql2MrEh6374
components-product-empty-state--web-scripts-needs-setup--dark:
hash: v1.k794b7964.b8df680b75a655d45a2371155e529b7a46417b8c9bee1c04ee2c9ff2debf7d80.oRFx2ui1Bf2MbcCJ396mUxfFdU4meehkiuB1ZmLb2W4
components-product-empty-state--web-scripts-needs-setup--light:
@@ -3076,38 +3072,6 @@ snapshots:
hash: v1.k794b7964.609d3c94138d98a7d579f4fb3e60317228594cdacc72052b9d2a0a03fef6f914.eVLCswR3cid2OZzFMpI1XCt3F4DN_h8zCQqwfFH9OBE
exporter-funnels--funnel-top-to-bottom-insight-no-results--light:
hash: v1.k794b7964.20a1af37546497f9f358406698065dfce5b088d65d323abccdc72693837416c3.0yAJ8C_91WgHUXp9tIqdjIi42vYEaNUgjZ-R9tKWRFk
- exporter-interview--default--medium--dark:
- hash: v1.k794b7964.f85c9ebce2b0bfec0e0668ba247891cb6c6425fb4c5be6af2f29782050093c8a.14EKIlxKpnZZaO2_oeMezPXUNd-jbC7ZNT1UgtutLS4
- exporter-interview--default--medium--light:
- hash: v1.k794b7964.5b7fc7ec87a216b440e0dbd605022b71078c3d1271af01cabb7c1400963df6c1.RBfD_6elE4F6ctbmCCV-RvblmzS9nkzvoNHMJdLxfEU
- exporter-interview--default--narrow--dark:
- hash: v1.k794b7964.ffadea65bf43fc0e9eab660e4f12ee3ece2dab4500a3a3f3b84f539edfaabdb6.YDF3dLoQivduxH48IE4uRckmm9HlpIu_itxmiE_Vkos
- exporter-interview--default--narrow--light:
- hash: v1.k794b7964.a6f6cc71810fc1567c78ff37eafb61d35c07b29982781a5815c57f0195c44bf5.Gx0JRp35lypF_us2cnDnDkAM8O8y0vNc9oHZkFkMzog
- exporter-interview--default--superwide--dark:
- hash: v1.k794b7964.5785206e6445469e253703e1b18f7c51b3ed33d6d155adcab853cc8246bced8e.E6B8JmOON7UigttZRjQAFSkn2dCTMUfNs1gG1uixxn0
- exporter-interview--default--superwide--light:
- hash: v1.k794b7964.5d2cc8db9e591ccccad39939aae2d9f1824d3793e5698b8983254755ef8878b0.5azHooVZlwfzZ1YNmRSiEHmUV0FP1cNXq4qu9_omYMU
- exporter-interview--default--wide--dark:
- hash: v1.k794b7964.0ca0c7b011d657184f0ff741180fbe1f588341ae73004e575a813c7e881eee87.zpOKfozXHr2-KCE2Kf7oV6nr3VW0GQiHGW-5iXETbGo
- exporter-interview--default--wide--light:
- hash: v1.k794b7964.2c5ccc6dc249ce71afcf3f6d012b37ba996e7acad5378e72393ba5d509a823c0.7pUMxvlEG07gbS6bprMQ1b9dRRyB9vhryowz6CBToM4
- exporter-interview--shared-link--medium--dark:
- hash: v1.k794b7964.d4a84364826ffa625c5483dc8359ab9a8d28a253221f054d40a9170caa843b32.WvjZsrs0qAuVOXprFtsJhx31bU3O2vdhauC8f0PMG8w
- exporter-interview--shared-link--medium--light:
- hash: v1.k794b7964.9f0b6110e71c14fbe0afcf00b3ac2bc1d2988290a3302c2598c3a8a1b4c8cb25.6PuS1H8PjXi-Kqa0iiqIVmhI18D1qtc7Uc0g0y-ZR1k
- exporter-interview--shared-link--narrow--dark:
- hash: v1.k794b7964.5514f2629f499dd342d7d22475c34c7ac391dee83ecfa3a268ba9085269fe7d8.cMKj9f05gHlqi6HQe-cIEGc8QMh6qZVbdWN4S1uIOS0
- exporter-interview--shared-link--narrow--light:
- hash: v1.k794b7964.5867a42a903746bb6ed37c5bdf405b4fc62cd31801ab9cfb70b0b626b8529dce.8Po60C6VFiioe_f9mfouLCyWwAWzf-a40F8l5g5gXik
- exporter-interview--shared-link--superwide--dark:
- hash: v1.k794b7964.66562d7eb7b2e2db226539a65fc7b24b4264de11c1d5d9bece7fcaa44dc255d8.z8BlaOQo9VAvQbbf7FN5A0LQxwruXMUNwXjo-dp38TE
- exporter-interview--shared-link--superwide--light:
- hash: v1.k794b7964.10323a11a1cbad29422007f3be064272de304119f3d287e91872b4ae38b6db5c.-4mP5CkXozGxsFrodhMVfyle7XsOwVIkvOMi9URL1Zk
- exporter-interview--shared-link--wide--dark:
- hash: v1.k794b7964.99032fb79ff715bb7318aa9e56f31db44d175fe53bc6b85fe99033c709051863.-y8Rl-xrI1nzraQqXqIy13zd0NJEm-P5B2PIntpb3sw
- exporter-interview--shared-link--wide--light:
- hash: v1.k794b7964.9c8fe8ac3ec91f347ba6696ab4736880544a462767e545fcb2958511c9157860.Q__2Iemz_j6tHo5-W3Txeddb3M2x31C6WkBjTwcMwIw
exporter-other--adhoc-query-export--dark:
hash: v1.k794b7964.9d483745b16b51f868b86a87a9d2da033441708412476cbf68a133fe75aaa4bb.O33M8wpPOaVMxqQCGjl7Vc6d-2jllnmUyl_2aFKdfBk
exporter-other--adhoc-query-export--light:
@@ -13618,62 +13582,6 @@ snapshots:
hash: v1.k794b7964.b8c44f66626ff2d35a9a566c58337683e9ade9433d135be7f8bb4b17e338aa09.xkwHBWc90Tu3C_N2E-Vtw47FBYj2EOePlemtN4qmwDQ
scenes-app-tracing-tracingimpactcounts--sessions-only--light:
hash: v1.k794b7964.1df982f4a9a5e13533ba18e16809fc68a44c64764aaf3713a8a7e98ab55e9b9b.kL4oa8rGztR7a71LeNRcpjpBpVYvrVTNmouBb4sRErE
- scenes-app-user-interviews-invite-preview-modal--emailable--dark:
- hash: v1.k794b7964.72aefcbed7109d9a1e05f4240c269ce0fa8c6d744f174720aa6fb3cc09d6f624.uCLx-0pStvTD_U6yriY685FeR9zupKQb1RVQL1xcExA
- scenes-app-user-interviews-invite-preview-modal--emailable--light:
- hash: v1.k794b7964.876cb2ded33b5e06d983189db06d4e709c60de43f36f4704f530407e3fe4f190.RhshHujlzz33poPa0Hmom45Vxxnb_xJ9xKR_UPbzk8o
- scenes-app-user-interviews-invite-preview-modal--loading--dark:
- hash: v1.k794b7964.a458b0aa1d5356d554aafade8302946e0206750044af6531f40eba2e0ee002b7.coF7r1Pbx7buAdFsC3Z4CsVQO9UPoPtDXg9i0kbCbfY
- scenes-app-user-interviews-invite-preview-modal--loading--light:
- hash: v1.k794b7964.320ec527145a72ffe5f2c55a15f1b98c814b364dca4f76160d4ba6f4325d6c7b.u50iTSAbyyPjw768_H0H-R75dh0bLlaRYQ8cV8KxkvE
- scenes-app-user-interviews-invite-preview-modal--no-email-address--dark:
- hash: v1.k794b7964.23b3765348da34e8df89ef6f1d30357848b41024a0caee17613a3c6cde7a4534.FiQ-nIk5WOroAQ23_udqsPw2rFfrs2y1xFfsp-kzejk
- scenes-app-user-interviews-invite-preview-modal--no-email-address--light:
- hash: v1.k794b7964.bc71dd4995e91e61e2e01dcc1d3cfb8d53acea3a4afe4817ac6c31458ffa6067.bLVXjgGcq9oRT5kxSzVe1tWaQ3w1zIpJy7Lx8WYMNfU
- scenes-app-user-interviews-transcript-chat--assistant-and-interviewee--dark:
- hash: v1.k794b7964.9b5239a77db2b13851c6729295437797126e5b7d35046c89b656e088976d2c8a.T8hjCkPWnyW1xztj1WIovU8f2WVPgKcyuBwnsmE0X9g
- scenes-app-user-interviews-transcript-chat--assistant-and-interviewee--light:
- hash: v1.k794b7964.758ee11a4cfff5bcf415585c8ca68478e04d96d30b40683ee1f6151f6cb078ee.T5kfQVVz-plBUMN63qssFtRs0-FjZOUwFbkLvadu5io
- scenes-app-user-interviews-transcript-chat--fallback-leading-prose--dark:
- hash: v1.k794b7964.1e8aa367419165cc43f01c9f406f24be46a2c948028e0ab521b524afd224c37c.SWqmwrRSZFMI9K6NN1AvHv9BA9dOWcPfwCB8-Z6GBIw
- scenes-app-user-interviews-transcript-chat--fallback-leading-prose--light:
- hash: v1.k794b7964.200a7e243d51fd181b250342753b668a418100875a47a9fb719a867bb6402acf._WsRFP927_-CXyu4mD8MsLBaJfuT5e_VTzVawReyXHU
- scenes-app-user-interviews-transcript-chat--fallback-no-speaker-markers--dark:
- hash: v1.k794b7964.49a46cac1e6096c4988ef0bc653f1ff057d2f12c1cf41bdce63af3cc5416cff2.VJ9NG6yKRu0S6fd4RaIdS5HCi38OpMC7yjefLGO6PIA
- scenes-app-user-interviews-transcript-chat--fallback-no-speaker-markers--light:
- hash: v1.k794b7964.63b77916a73d0f9828aec9cc86f9f51f4231c32e3deb3746b3af6d2a5fea4765.yR2X9WArparhtdg7NkbCrCbdAEIUqOLozNLVAqYlfJk
- scenes-app-user-interviews-transcript-chat--identifier-only--dark:
- hash: v1.k794b7964.86a2cab439867803e3071766d53c69eea30fe097511999d1eb192e5a58716bbe.8f0ELx8wSfJHSRoIxzY8iVzRZPyYjpIzi2ri0hYrSAk
- scenes-app-user-interviews-transcript-chat--identifier-only--light:
- hash: v1.k794b7964.68464c44ab9bdd021ed0a14afad3edcb5a1f9ade0481bd2dd673aaf089ac6637.1011HGhq4vBWCTtuAELmyI_vkfcC3ZefiJblSte_HMw
- scenes-app-user-interviews-transcript-chat--inline-no-newlines--dark:
- hash: v1.k794b7964.14267ffc2f6e167317b32fed388a0713d647c5f30e6f5c5aed716ba44c0abd68.Qcv7RbyBS39C8JGGGkV22ICdVogp_4UvT4x5INLwl4M
- scenes-app-user-interviews-transcript-chat--inline-no-newlines--light:
- hash: v1.k794b7964.b6501aa2a8f615bc51c1109689322198da4d4aea5d8ae1b6c36f0c6d012a483c.XIiQZWjZ__qhgSwLD5TLT-xa-IZ-jOlUnXxUJnsqebY
- scenes-app-user-interviews-transcript-chat--known-person--dark:
- hash: v1.k794b7964.e347a5c0e32e46e3a5e2b21f01dd14244fcc8f4c8f43a173bb153a144398881b.-d8A4fDnt50nno7OP22CaS3LKMbZ5DMTQcXTiklCSyU
- scenes-app-user-interviews-transcript-chat--known-person--light:
- hash: v1.k794b7964.b7df8d2861e427baa11023fc5966fe8727326d108d1b8714f93f8db521472e33.6dCpLuUhCpTKK988Kj5jqBG39m0EnktsuQctl2UEnGc
- scenes-app-user-interviews-transcript-chat--non-email-identifier--dark:
- hash: v1.k794b7964.3069255c14ed6904259960ce7a29deff04c28c52b0ddbe17628abe005e24d27b.oH7k2GYOq4gIhnc5-n4w64WsuPKaxk8SNoPrf_kawhQ
- scenes-app-user-interviews-transcript-chat--non-email-identifier--light:
- hash: v1.k794b7964.d1f374f2b5394d1e0a61cae09a25e60779e840e9e9c5f27a5c4d9d046088eca0.3MT0wMtejC_PKD3QtKvlD7cM6XYqbSApYZ1Jk9TOtUo
- scenes-app-user-interviews-transcript-chat--speaker-keyword-in-body--dark:
- hash: v1.k794b7964.6c03dfaa7ffb055d6c8ab16377ac2528a91b69b0ad435f8baa57f7f5d42bdad9.8rrcQYqCk7Nf8hpk1hsr1dAeOPB-D_GRWCfj91D_Jck
- scenes-app-user-interviews-transcript-chat--speaker-keyword-in-body--light:
- hash: v1.k794b7964.4b6eb5fca929c448c6556810d53ba83825b54d04b461560723ea65650910ab87.WjvNkmSBcyWaic4Q5xUtYEzaLGdHVsFfy4u_xCNEQ4w
- scenes-app-user-research-topics--search-no-results--dark:
- hash: v1.k794b7964.f917596514ef7327ef276b25147847bb40c4751ea23bc5472d2817ae333f4b08.gX3up_3wMbkCyKHfw6xBEUMhzXaAZLNU-DeFWZQ-m6I
- scenes-app-user-research-topics--search-no-results--light:
- hash: v1.k794b7964.df68cd6d45b2bde2483ca01afef89795a1d3c09b5b552306ddbb7fc7f8648a4c.juGY6xHTE0kx3jJERSXTR2sUs7m5weh_JmiZ8J63uog
- scenes-app-user-research-topics--search-with-results--dark:
- hash: v1.k794b7964.6b4b809c4dcc265d3fd26054001bc2a0ec6c74094d90ca2288a2168a1e648fdc.807rhmRuUxrSKGbJM0fCMHrnv6d-oO66hqP7Wp_sg2k
- scenes-app-user-research-topics--search-with-results--light:
- hash: v1.k794b7964.0f765cd0cb884ffd297295a8d35203bcc28df4f3f06de2a8f2223936d6ebe2dd.UVp7M3TuCHNZywyhXP0cWDYlmdU8jbl_Pbx4bXu4HSU
- scenes-app-user-research-topics--topics-list--dark:
- hash: v1.k794b7964.2be1760894da7958ef5f9376996ae6262c5ab191ec957c533ae74ba4c742aead.dQcZiMIpSCQDJxp76ersiDmELB8efODSyJoZQCWpb8w
- scenes-app-user-research-topics--topics-list--light:
- hash: v1.k794b7964.f1a2f79a98d9a9104868b551164cd1ff8ee03a892af075c495ef6e41229d098e.bFA04K1QUtLmjYG7rmQcIBruv-GuGqTqFlShoEjNfco
scenes-app-visual-review-flakiness--could-not-load--dark:
hash: v1.k794b7964.a885efc43e772acd3c4f772793c1ea66d68aff8db840742efeda0db8d4e0bc81.uOVreOtzrZybXYI515GtfVCcoYT5R1N_lRbvw_qsJ4Y
scenes-app-visual-review-flakiness--could-not-load--light:
diff --git a/frontend/src/exporter/Exporter.tsx b/frontend/src/exporter/Exporter.tsx
index 57816ff5b71f..347b584d2ab9 100644
--- a/frontend/src/exporter/Exporter.tsx
+++ b/frontend/src/exporter/Exporter.tsx
@@ -29,7 +29,6 @@ const LazyHeatmapScene = lazyWithRetry(() => import('./scenes/ExporterHeatmapSce
const LazyInsightScene = lazyWithRetry(() => import('./scenes/ExporterInsightScene'))
const LazyNotebookScene = lazyWithRetry(() => import('./scenes/ExporterNotebookScene'))
const LazyRecordingScene = lazyWithRetry(() => import('./scenes/ExporterRecordingScene'))
-const LazyInterviewScene = lazyWithRetry(() => import('./scenes/ExporterInterviewScene'))
const LazyQueryScene = lazyWithRetry(() => import('./scenes/ExporterQueryScene'))
function ExportedSceneSkeleton(): JSX.Element {
@@ -88,7 +87,6 @@ export function Exporter(props: ExportedData): JSX.Element {
themes,
accessToken,
exportToken,
- interview,
...exportOptions
} = props
const { whitelabel, showInspector = false } = exportOptions
@@ -131,14 +129,6 @@ export function Exporter(props: ExportedData): JSX.Element {
return <ExporterLogin whitelabel={whitelabel} />
}
- if (type === ExportType.Interview && interview) {
- return (
- <Suspense fallback={<ExportedSceneSkeleton />}>
- <LazyInterviewScene interview={interview} accessToken={accessToken} />
- </Suspense>
- )
- }
-
return (
<BindLogic logic={exporterViewLogic} props={props}>
<div
diff --git a/frontend/src/exporter/index.tsx b/frontend/src/exporter/index.tsx
index 724de096c54e..52128c1329c3 100644
--- a/frontend/src/exporter/index.tsx
+++ b/frontend/src/exporter/index.tsx
@@ -5,13 +5,12 @@ import './Exporter.scss'
// before any module that builds a zod schema. See lib/configureZod.
import '../lib/configureZod'
-import { BeforeSendFn, CapturedNetworkRequest, NetworkMetricsConfig } from 'posthog-js'
import { createRoot } from 'react-dom/client'
import { polyfillCountryFlags } from 'lib/countryFlagEmojiPolyfill'
import { Exporter } from '~/exporter/Exporter'
-import { ExportType, ExportedData } from '~/exporter/types'
+import { ExportedData } from '~/exporter/types'
import { initKea } from '~/initKea'
import { loadPostHogJS } from '~/loadPostHogJS'
@@ -21,58 +20,9 @@ const exportedData: ExportedData = window.POSTHOG_EXPORTED_DATA
// Disable tracking for shared dashboards / insights / embeds — those iframes can be embedded on
// our customers' sites, and tracking there would log their visitors to app.posthog.com.
-// The `interview` scene is the exception: it's our own hosted public page, opened by an invitee
-// on a link we sent. We want pageviews + replay to measure the invite-to-call funnel.
-// Require the interview payload to be present — the public `force_type=interview` query param
-// can flip `type` on any shared resource, so checking `type` alone would let anyone enable
-// tracking on a customer dashboard share by appending the parameter.
-const isInterview = exportedData?.type === ExportType.Interview && !!exportedData?.interview
-if (!isInterview) {
- window.JS_POSTHOG_API_KEY = undefined
-}
-
-// The interview URL embeds the SharingConfiguration access token (/interview/<token>/) and the
-// public start_call API path (/api/user_interviews/share/<token>/start_call/) embeds it too.
-// Three hooks redact it everywhere a viewer of analytics, replay, or metrics could otherwise read it:
-// - `before_send` strips URL-shaped event properties ($current_url, $pathname, $referrer, ...)
-// - `maskCapturedNetworkRequestFn` is also the hook posthog-js uses for ALL replay URL
-// surfaces — captured network requests, the rrweb `EventType.Meta` header, `$url_changed`
-// custom events on SPA route transitions, and masked $current_url in captured console events.
-// - `metrics.network.attributes` overrides the `path` attribute posthog-js records on every
-// automatic fetch/XHR duration metric. The default `path` only templates numeric or
-// uuid-like segments to `:id`, and the access token (a `secrets.token_urlsafe` string) does
-// not match that pattern, so without this override the token would reach the Metrics UI.
-// Together they cover every surface where the token could land for a viewer to reuse.
-const INTERVIEW_TOKEN_RE = /\/interview\/[^/?#]+|\/api\/user_interviews\/share\/[^/?#]+/g
-const URL_PROPERTIES = ['$current_url', '$pathname', '$referrer', '$initial_current_url', '$initial_pathname']
-const redactInterviewToken = (value: string): string =>
- value.replace(INTERVIEW_TOKEN_RE, (match) => match.replace(/\/[^/?#]+$/, '/<redacted>'))
-const interviewBeforeSend: BeforeSendFn = (event) => {
- if (event?.properties) {
- for (const key of URL_PROPERTIES) {
- const value = event.properties[key]
- if (typeof value === 'string') {
- event.properties[key] = redactInterviewToken(value)
- }
- }
- }
- return event
-}
-const interviewMaskNetworkRequest = (req: CapturedNetworkRequest): CapturedNetworkRequest => {
- if (req.name) {
- req.name = redactInterviewToken(req.name)
- }
- return req
-}
-const interviewNetworkMetricsAttributes: NonNullable<NetworkMetricsConfig['attributes']> = (request) => ({
- path: redactInterviewToken(new URL(request.url).pathname),
-})
+window.JS_POSTHOG_API_KEY = undefined
-loadPostHogJS({
- beforeSend: isInterview ? interviewBeforeSend : undefined,
- sessionRecording: isInterview ? { maskCapturedNetworkRequestFn: interviewMaskNetworkRequest } : undefined,
- metrics: isInterview ? { network: { attributes: interviewNetworkMetricsAttributes } } : undefined,
-})
+loadPostHogJS()
initKea({ replaceInitialPathInWindow: false })
// On Chrome + Windows, the country flag emojis don't render correctly. This is a polyfill for that.
diff --git a/frontend/src/exporter/scenes/ExporterInterviewScene.tsx b/frontend/src/exporter/scenes/ExporterInterviewScene.tsx
deleted file mode 100644
index fe6c52e96dd3..000000000000
--- a/frontend/src/exporter/scenes/ExporterInterviewScene.tsx
+++ /dev/null
@@ -1,577 +0,0 @@
-import Vapi from '@vapi-ai/web'
-import { memo, type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react'
-
-import * as robotPng from '@posthog/brand/hoggies/png/robot'
-import { LemonButton, LemonInput } from '@posthog/lemon-ui'
-
-import { Logo } from 'lib/brand'
-import { pngHoggie } from 'lib/brand/hoggies'
-import { useHogfetti } from 'lib/components/Hogfetti/Hogfetti'
-import { uuid } from 'lib/utils/dom'
-import { fromParams } from 'lib/utils/url'
-
-import { InterviewExportPayload } from '../types'
-
-const HedgehogRobot = pngHoggie(robotPng)
-
-// Fields a shared-link respondent sends to /start_call/. Empty {} for personalised links.
-interface StartCallBody {
- name?: string
- respondent_key?: string
- distinct_id?: string
- session_id?: string
- _hp?: string
-}
-
-// Stable per-browser id for a shared-link respondent, scoped per share token so two topics in the
-// same browser stay distinct. Persisting it means a refresh mid-call re-attaches to the same
-// respondent instead of creating a duplicate. Best-effort: falls back to an in-memory id if
-// localStorage is unavailable (private mode, blocked storage).
-function getOrCreateRespondentKey(accessToken: string): string {
- const storageKey = `ph-interview-respondent:${accessToken}`
- try {
- const existing = window.localStorage.getItem(storageKey)
- if (existing) {
- return existing
- }
- const created = uuid()
- window.localStorage.setItem(storageKey, created)
- return created
- } catch {
- return uuid()
- }
-}
-
-// Best-effort person/session linkage: whoever built the shared link can append ?distinct_id=…&session_id=…
-// so responses can be tied back to the person/session that triggered the interview. Untrusted.
-function readLinkageFromUrl(): { distinct_id: string; session_id: string } {
- try {
- const params = fromParams()
- return { distinct_id: params.distinct_id ?? '', session_id: params.session_id ?? '' }
- } catch {
- return { distinct_id: '', session_id: '' }
- }
-}
-
-// Vapi surfaces several normal-completion signals through its `error` channel because
-// the underlying Daily.co transport reports the local participant being evicted as
-// an error. Treat these as expected end-of-call events rather than failures.
-const BENIGN_END_OF_CALL_MESSAGES = ['Meeting has ended', 'Meeting ended due to ejection', 'Worker has ended call']
-
-const isBenignEndOfCallError = (message: string): boolean =>
- BENIGN_END_OF_CALL_MESSAGES.some((pattern) => message.includes(pattern))
-
-// Floor for the celebratory end-of-call effect. A 20-second bail-out doesn't
-// deserve confetti — it reads as desperate rather than thankful. Two minutes
-// is the rough point where the interviewee has given enough of a substantive
-// answer that we genuinely want to thank them for the time.
-const HOGFETTI_MIN_CALL_DURATION_MS = 2 * 60 * 1000
-
-type CallState = 'already-replied' | 'idle' | 'loading' | 'connecting' | 'in-call' | 'ended' | 'error'
-
-type ConversationPhase = 'agent-talking' | 'listening' | 'thinking'
-
-const PHASE_LABELS: Record<ConversationPhase, string> = {
- 'agent-talking': '🎤 Talking',
- listening: '👂 Listening',
- thinking: '🧠 Thinking',
-}
-
-interface VapiTranscriptMessage {
- type?: string
- role?: string
- transcriptType?: string
-}
-
-interface StartCallPayload {
- web_call: {
- webCallUrl: string
- id?: string
- artifactPlan?: { videoRecordingEnabled?: boolean }
- }
-}
-
-const CallStatusPanel = memo(function CallStatusPanel({
- state,
- phase,
-}: {
- state: CallState
- phase: ConversationPhase
-}): JSX.Element {
- return (
- <div className="flex-shrink-0 mx-auto md:mx-0 md:w-40">
- <div className="w-40 h-40 mx-auto">
- <HedgehogRobot className="w-full h-full" />
- </div>
- {state === 'in-call' && <p className="text-sm text-muted text-center mt-2">{PHASE_LABELS[phase]}</p>}
- </div>
- )
-})
-
-function PreCallIntro({
- interview,
- name,
- onNameChange,
- honeypotRef,
-}: {
- interview: InterviewExportPayload
- name: string
- onNameChange: (value: string) => void
- honeypotRef: RefObject<HTMLInputElement>
-}): JSX.Element {
- return (
- <>
- <h1 className="text-3xl font-bold mb-4">{interview.shared ? 'Hi there!' : `Hi ${interview.user_name}!`}</h1>
- <p className="text-lg mb-4">
- We're researching <strong>{interview.topic}</strong> and would love to hear your perspective.
- </p>
- <p className="text-muted mb-6">
- This is a 5–10 minute voice conversation with an AI interviewer. Talk like you would to a researcher on
- our team — your feedback helps us build a better product.
- </p>
- {interview.shared && (
- <div className="mb-6">
- <label htmlFor="interview-respondent-name" className="block font-semibold mb-1">
- What's your name?
- </label>
- <LemonInput
- id="interview-respondent-name"
- value={name}
- onChange={onNameChange}
- placeholder="Your name"
- maxLength={200}
- autoFocus
- />
- {/* Honeypot: hidden from real users, tempting to naive bots. Sent as `_hp`; a
- filled value gets the request rejected server-side. */}
- <input
- ref={honeypotRef}
- type="text"
- name="company_website"
- tabIndex={-1}
- autoComplete="off"
- aria-hidden="true"
- className="hidden"
- />
- </div>
- )}
- <div className="bg-accent-highlight border border-accent p-4 rounded mb-6 text-sm">
- <strong>How it works</strong>
- <ol className="list-decimal pl-5 mt-2 space-y-1">
- <li>
- Click <em>Start interview</em> below.
- </li>
- <li>Allow microphone access when prompted.</li>
- <li>Have a casual conversation — the AI will guide you through a few questions.</li>
- <li>You can end the call any time.</li>
- </ol>
- </div>
- </>
- )
-}
-
-function ConnectingPanel(): JSX.Element {
- return (
- <>
- <h2 className="text-2xl font-bold mb-2">Connecting…</h2>
- <p className="text-muted">Hold tight while we connect you to the AI interviewer.</p>
- </>
- )
-}
-
-function LivePanel(): JSX.Element {
- return (
- <>
- <h2 className="text-2xl font-bold mb-2">You're live</h2>
- <p className="text-muted mb-2">Talk as you would to a researcher on our team.</p>
- <p className="text-xs text-muted">
- End the call any time using the button below — the recording will still be saved.
- </p>
- </>
- )
-}
-
-function EndedPanel(): JSX.Element {
- return (
- <>
- <h2 className="text-2xl font-bold mb-2">Thanks for taking the time!</h2>
- <p className="text-muted">
- Your conversation has been recorded — we'll be in touch if we have follow-up questions.
- </p>
- </>
- )
-}
-
-function AlreadyRepliedPanel({ interview }: { interview: InterviewExportPayload }): JSX.Element {
- return (
- <>
- <h2 className="text-2xl font-bold mb-2">Thanks for your response!</h2>
- <p className="text-muted">
- We've already received your interview about <strong>{interview.topic}</strong>. We really appreciate you
- taking the time — your feedback helps us build a better product.
- </p>
- </>
- )
-}
-
-function ErrorPanel({ errorMessage }: { errorMessage: string | null }): JSX.Element {
- return (
- <div className="text-danger">
- <h2 className="text-2xl font-bold mb-2">Something went wrong</h2>
- <p className="mb-2">{errorMessage ?? 'Unknown error.'}</p>
- </div>
- )
-}
-
-function CallActionButton({
- state,
- canStart,
- onStart,
- onStop,
- onRetry,
-}: {
- state: CallState
- canStart: boolean
- onStart: () => void
- onStop: () => void
- onRetry: () => void
-}): JSX.Element | null {
- switch (state) {
- case 'idle':
- return (
- <LemonButton
- type="primary"
- size="large"
- fullWidth
- onClick={onStart}
- disabledReason={canStart ? undefined : 'Enter your name to start'}
- >
- Start interview
- </LemonButton>
- )
- case 'loading':
- return <p>Loading interviewer…</p>
- case 'in-call':
- return (
- <LemonButton type="secondary" onClick={onStop}>
- End interview
- </LemonButton>
- )
- case 'error':
- return (
- <LemonButton type="secondary" onClick={onRetry}>
- Try again
- </LemonButton>
- )
- case 'already-replied':
- case 'connecting':
- case 'ended':
- return null
- }
-}
-
-const CallBodyPanel = memo(function CallBodyPanel({
- state,
- interview,
- errorMessage,
- name,
- onNameChange,
- honeypotRef,
- canStart,
- onStart,
- onStop,
- onRetry,
-}: {
- state: CallState
- interview: InterviewExportPayload
- errorMessage: string | null
- name: string
- onNameChange: (value: string) => void
- honeypotRef: RefObject<HTMLInputElement>
- canStart: boolean
- onStart: () => void
- onStop: () => void
- onRetry: () => void
-}): JSX.Element {
- const isPreCall = state === 'idle' || state === 'loading'
- return (
- <div className="flex-1 min-w-0">
- {state === 'already-replied' && <AlreadyRepliedPanel interview={interview} />}
- {isPreCall && (
- <PreCallIntro interview={interview} name={name} onNameChange={onNameChange} honeypotRef={honeypotRef} />
- )}
- {state === 'connecting' && <ConnectingPanel />}
- {state === 'in-call' && <LivePanel />}
- {state === 'ended' && <EndedPanel />}
- {state === 'error' && <ErrorPanel errorMessage={errorMessage} />}
- <div className="mt-4">
- <CallActionButton
- state={state}
- canStart={canStart}
- onStart={onStart}
- onStop={onStop}
- onRetry={onRetry}
- />
- </div>
- </div>
- )
-})
-
-/**
- * Ask the server to create one Vapi web call when the interviewee clicks Start. The
- * response contains only that call's join payload, never reusable Vapi credentials.
- */
-async function fetchStartCallPayload(accessToken: string, body: StartCallBody): Promise<StartCallPayload> {
- const response = await fetch(`/api/user_interviews/share/${accessToken}/start_call/`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- })
- if (!response.ok) {
- // A shared link is opened by many people at once (e.g. posted in a company Slack), so
- // concurrent respondents can trip the rate limit. Surface a retry-friendly message rather
- // than a raw error — the error panel already offers a "Try again" button.
- if (response.status === 429) {
- throw new Error('A lot of people are starting interviews right now. Please wait a moment and try again.')
- }
- const text = await response.text()
- throw new Error(text || `Server responded ${response.status}`)
- }
- return response.json()
-}
-
-export default function ExporterInterviewScene({
- interview,
- accessToken,
-}: {
- interview: InterviewExportPayload
- accessToken?: string
-}): JSX.Element {
- const [state, setState] = useState<CallState>(interview.already_replied ? 'already-replied' : 'idle')
- // Default to 'thinking' — between connection-up and the agent's first speech-start
- // the assistant is loading its opener, which can take a few seconds. After
- // speech-end transitions us into 'listening', subsequent silent moments correctly
- // read as listening (mic is open), and only the post-user-final gap re-enters thinking.
- const [conversationPhase, setConversationPhase] = useState<ConversationPhase>('thinking')
- const [errorMessage, setErrorMessage] = useState<string | null>(null)
- // Shared links ask each respondent for their name before starting; personalised links already
- // know it. `canStart` gates the button so shared respondents can't start nameless.
- const [respondentName, setRespondentName] = useState<string>('')
- const honeypotRef = useRef<HTMLInputElement>(null)
- const canStart = !interview.shared || respondentName.trim().length > 0
- const vapiRef = useRef<Vapi | null>(null)
- const agentTalkingRef = useRef<boolean>(false)
- const lastPhaseRef = useRef<ConversationPhase>('thinking')
- const isMountedRef = useRef<boolean>(true)
- const callStartedAtRef = useRef<number | null>(null)
- const hogfettiFiredRef = useRef<boolean>(false)
- const { trigger: triggerHogfetti, HogfettiComponent } = useHogfetti({ count: 75, duration: 3000 })
-
- // Reused across a refresh so an interrupted call re-attaches to the same respondent instead of
- // spawning a duplicate. Only meaningful for shared links.
- const respondentKey = useMemo(
- () => (interview.shared && accessToken ? getOrCreateRespondentKey(accessToken) : ''),
- [interview.shared, accessToken]
- )
-
- useEffect(() => {
- document.title = `Interview · ${interview.topic}`
- }, [interview.topic])
-
- // Warn before an accidental refresh/close ends a live call — Vapi's browser call can't be
- // resumed across a page load, so a lost call means starting over.
- useEffect(() => {
- if (state !== 'in-call') {
- return
- }
- const onBeforeUnload = (event: BeforeUnloadEvent): void => {
- event.preventDefault()
- event.returnValue = ''
- }
- window.addEventListener('beforeunload', onBeforeUnload)
- return () => window.removeEventListener('beforeunload', onBeforeUnload)
- }, [state])
-
- useEffect(() => {
- if (state !== 'ended' || hogfettiFiredRef.current) {
- return
- }
- const startedAt = callStartedAtRef.current
- if (startedAt === null) {
- return
- }
- if (Date.now() - startedAt < HOGFETTI_MIN_CALL_DURATION_MS) {
- return
- }
- // Mark as fired before the early returns below so a resize-driven
- // re-run cannot retrigger the celebration. `useHogfetti`'s `trigger`
- // identity changes whenever `dimensions` updates (window resize),
- // and that dep change re-runs this effect while `state === 'ended'`.
- hogfettiFiredRef.current = true
- if (typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) {
- return
- }
- triggerHogfetti()
- }, [state, triggerHogfetti])
-
- useEffect(() => {
- return () => {
- isMountedRef.current = false
- vapiRef.current?.stop()
- vapiRef.current = null
- }
- }, [])
-
- const start = useCallback((): void => {
- if (!accessToken) {
- setErrorMessage('Interview link is missing its access token. Open the URL you were emailed.')
- setState('error')
- return
- }
- vapiRef.current?.stop()
- vapiRef.current = null
- agentTalkingRef.current = false
- lastPhaseRef.current = 'thinking'
- callStartedAtRef.current = null
- hogfettiFiredRef.current = false
- setConversationPhase('thinking')
- setState('loading')
- const body: StartCallBody = {}
- if (interview.shared) {
- const { distinct_id, session_id } = readLinkageFromUrl()
- body.name = respondentName.trim()
- body.respondent_key = respondentKey
- body.distinct_id = distinct_id
- body.session_id = session_id
- body._hp = honeypotRef.current?.value ?? ''
- }
- void (async () => {
- try {
- const startPayload = await fetchStartCallPayload(accessToken, body)
- if (!isMountedRef.current) {
- return
- }
- const vapi = new Vapi('')
- vapiRef.current = vapi
- const setPhase = (next: ConversationPhase): void => {
- if (lastPhaseRef.current === next) {
- return
- }
- lastPhaseRef.current = next
- setConversationPhase(next)
- }
- // Daily.co's normal end-of-call eviction surfaces as an `error` event in the
- // Vapi SDK ("Meeting ended due to ejection: Meeting has ended"), often racing
- // with the `call-end` event. Suppress that race so the error panel doesn't
- // flash as the interview wraps up — but ONLY when the call actually got off
- // the ground. A pre-connection failure that happens to mention "Meeting has
- // ended" (e.g. joining an already-ended room) must still surface as an
- // error so the user gets the retry affordance.
- const callEndedRef = { current: false }
- const callConnectedRef = { current: false }
- vapi.on('call-end', () => {
- callEndedRef.current = true
- setState('ended')
- })
- vapi.on('error', (e: unknown) => {
- const message = e instanceof Error ? e.message : ''
- // call-end already fired — definitely post-end, swallow.
- if (callEndedRef.current) {
- return
- }
- // Benign message + we'd reached in-call → call is ending, swallow.
- // Benign message but never connected → real failure, surface it.
- if (callConnectedRef.current && isBenignEndOfCallError(message)) {
- return
- }
- vapi.stop()
- setErrorMessage(message || 'Vapi reported an error during the call.')
- setState('error')
- })
- vapi.on('speech-start', () => {
- agentTalkingRef.current = true
- setPhase('agent-talking')
- })
- vapi.on('speech-end', () => {
- agentTalkingRef.current = false
- setPhase('listening')
- })
- vapi.on('message', (message: VapiTranscriptMessage) => {
- if (message.type === 'user-interrupted') {
- agentTalkingRef.current = false
- setPhase('listening')
- return
- }
- if (message.type !== 'transcript' || message.role !== 'user') {
- return
- }
- if (agentTalkingRef.current) {
- return
- }
- if (message.transcriptType === 'partial') {
- setPhase('listening')
- } else if (message.transcriptType === 'final') {
- setPhase('thinking')
- }
- })
- setState('connecting')
- await vapi.reconnect(startPayload.web_call)
- if (!isMountedRef.current) {
- vapi.stop()
- return
- }
- // Mark that the call actually connected — gates the benign-error suppression
- // so pre-connection "Meeting has ended" failures still surface to the user.
- callConnectedRef.current = true
- callStartedAtRef.current = Date.now()
- setState((current) => (current === 'connecting' ? 'in-call' : current))
- } catch (e) {
- if (!isMountedRef.current) {
- return
- }
- setErrorMessage(e instanceof Error ? e.message : 'Failed to start interview.')
- setState('error')
- }
- })()
- }, [accessToken, interview.shared, respondentName, respondentKey])
-
- const stop = useCallback((): void => {
- vapiRef.current?.stop()
- setState('ended')
- }, [])
-
- const retry = useCallback((): void => {
- setErrorMessage(null)
- setState('idle')
- }, [])
-
- return (
- <div className="max-w-2xl mx-auto px-4 py-12">
- <HogfettiComponent />
- <div className="mb-8">
- <Logo size="md" />
- </div>
-
- <div className="flex flex-col md:flex-row md:items-start gap-6 md:gap-8 mb-8">
- <CallStatusPanel state={state} phase={conversationPhase} />
- <CallBodyPanel
- state={state}
- interview={interview}
- errorMessage={errorMessage}
- name={respondentName}
- onNameChange={setRespondentName}
- honeypotRef={honeypotRef}
- canStart={canStart}
- onStart={start}
- onStop={stop}
- onRetry={retry}
- />
- </div>
-
- <p className="text-xs text-muted text-center mt-12">
- Your conversation will be transcribed and analyzed to help improve PostHog. We won't share your
- individual responses publicly.
- </p>
- </div>
- )
-}
diff --git a/frontend/src/exporter/stories/ExporterInterview.stories.tsx b/frontend/src/exporter/stories/ExporterInterview.stories.tsx
deleted file mode 100644
index c6696f768e81..000000000000
--- a/frontend/src/exporter/stories/ExporterInterview.stories.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/react'
-import { useEffect } from 'react'
-
-import { ExportType, ExportedData, InterviewExportPayload } from '~/exporter/types'
-
-import { Exporter } from '../Exporter'
-
-const interview: InterviewExportPayload = {
- topic_id: 'topic-123',
- interviewee_identifier: 'interviewee-abc',
- user_name: 'Sam',
- topic: 'how you use dashboards',
- already_replied: false,
- shared: false,
-}
-
-// Non-personalised (shared) link: no known interviewee, so the viewer asks for a name first.
-const sharedInterview: InterviewExportPayload = {
- ...interview,
- interviewee_identifier: '',
- user_name: '',
- shared: true,
-}
-
-type Story = StoryObj<ExportedData>
-const meta: Meta<ExportedData> = {
- title: 'Exporter/Interview',
- component: Exporter,
- args: {
- type: ExportType.Interview,
- whitelabel: false,
- noHeader: false,
- legend: false,
- detailed: false,
- accessToken: 'storybook-access-token',
- interview,
- },
- parameters: {
- layout: 'fullscreen',
- testOptions: {
- snapshotBrowsers: ['chromium'],
- viewportWidths: ['narrow', 'medium', 'wide', 'superwide'],
- },
- mockDate: '2023-02-01',
- viewMode: 'story',
- },
- tags: [],
- render: (props) => {
- useEffect(() => {
- document.body.className = ''
- document.documentElement.className = `export-type-${props.type}`
- }, [props.type])
- return (
- <div className={`storybook-export-type-${props.type} p-4`}>
- <Exporter {...props} />
- </div>
- )
- },
-}
-
-export default meta
-
-export const Default: Story = {}
-
-export const SharedLink: Story = {
- args: {
- interview: sharedInterview,
- },
-}
diff --git a/frontend/src/exporter/types.ts b/frontend/src/exporter/types.ts
index 3da97b15769d..eb7c05f0c2c0 100644
--- a/frontend/src/exporter/types.ts
+++ b/frontend/src/exporter/types.ts
@@ -17,26 +17,6 @@ export enum ExportType {
Scene = 'scene',
Unlock = 'unlock',
Heatmap = 'heatmap',
- Interview = 'interview',
-}
-
-export interface InterviewExportPayload {
- topic_id: string
- interviewee_identifier: string
- user_name: string
- topic: string
- already_replied: boolean
- /**
- * True for a non-personalised (shared) topic link, where every visitor is a new anonymous
- * respondent who self-identifies with a name before starting. False for a personalised
- * per-invitee link (which greets a known `user_name`).
- */
- shared: boolean
- /**
- * NOTE: `agent_context`, `questions`, and the Vapi credentials are intentionally NOT in
- * this payload. They live behind `POST /api/user_interviews/share/<token>/start_call/`
- * so the personalized agent context never lands in the public HTML.
- */
}
export interface ExportedData extends SharingConfigurationSettings {
@@ -78,6 +58,4 @@ export interface ExportedData extends SharingConfigurationSettings {
heatmap_context?: HeatmapExportContext
/** Cohort id+name inlined for shared views, which can't reach /api/cohorts. */
cohorts?: Pick<CohortType, 'id' | 'name'>[]
- /** AI user interview payload — present only for `type === ExportType.Interview`. */
- interview?: InterviewExportPayload
}
diff --git a/frontend/src/layout/navigation-3000/Navigation.tsx b/frontend/src/layout/navigation-3000/Navigation.tsx
index 2b730bdef010..44569e47e5eb 100644
--- a/frontend/src/layout/navigation-3000/Navigation.tsx
+++ b/frontend/src/layout/navigation-3000/Navigation.tsx
@@ -8,7 +8,6 @@ import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableSh
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { cn } from 'lib/utils/css-classes'
import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
-import { useMaxTool } from 'scenes/max/useMaxTool'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene, SceneConfig } from 'scenes/sceneTypes'
@@ -107,16 +106,6 @@ export function Navigation({
}
}, [mainRef, setMainContentRef, setMainContentRect])
- // Register `create_user_interview_topic` globally so Max can create user interview
- // topics from any page (including the homepage), not only from the user-interviews
- // scene. The scene wires its own richer `useMaxTool` for the "New topic" button.
- const userInterviewsEnabled = useFeatureFlag('USER_INTERVIEWS')
- useMaxTool({
- identifier: 'create_user_interview_topic',
- active: userInterviewsEnabled,
- context: {},
- })
-
const noPaddingScene = sceneConfig?.layout === 'app-raw-no-header' || sceneConfig?.layout === 'app-raw'
const todayPhoneBodyClass = todayPhone && mode === 'full'
diff --git a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.stories.tsx b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.stories.tsx
index f15a8cbbb3c9..63a5edda0985 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.stories.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.stories.tsx
@@ -22,7 +22,6 @@ const meta: Meta<(props: StoryProps) => JSX.Element> = {
FEATURE_FLAGS.LIVE_DEBUGGER,
FEATURE_FLAGS.WEB_ANALYTICS_MARKETING,
FEATURE_FLAGS.PRODUCT_TOURS,
- FEATURE_FLAGS.USER_INTERVIEWS,
],
},
render: (props: StoryProps) => {
diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
index 36b426e7cd38..c884181c6ac7 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
@@ -47,7 +47,6 @@ import {
IconMagicWand,
IconMegaphone,
IconMessage,
- IconMicrophone,
IconNotebook,
IconNotification,
IconPencil,
@@ -192,10 +191,6 @@ const iconTypes: Record<FileSystemIconType, { icon: JSX.Element; iconColor?: Fil
icon: <IconSpotlight />,
iconColor: ['var(--color-product-product-tours-light)', 'var(--color-product-product-tours-dark)'],
},
- user_interview: {
- icon: <IconMicrophone />,
- iconColor: ['var(--color-product-user-interviews-light)', 'var(--color-product-user-interviews-dark)'],
- },
home: {
icon: <IconHome />,
},
diff --git a/frontend/src/layout/panel-layout/sidebarProductMeta.ts b/frontend/src/layout/panel-layout/sidebarProductMeta.ts
index d7cabc06c61b..f38db0e8711b 100644
--- a/frontend/src/layout/panel-layout/sidebarProductMeta.ts
+++ b/frontend/src/layout/panel-layout/sidebarProductMeta.ts
@@ -76,7 +76,6 @@ export const SIDEBAR_PRODUCTS_WITHOUT_DOCS = new Set<string>([
'Live Debugger',
'Product tours',
'Pulse',
- 'User research',
'Visual review',
])
@@ -131,7 +130,6 @@ const examples: Record<string, string> = {
Tasks: 'Ask an agent to investigate an issue and prepare a code change.',
Toolbar: 'Inspect elements on your website while setting up tracking.',
Tracing: 'Follow a slow request across services to find the bottleneck.',
- 'User research': 'Run a voice research campaign about a recent product experience.',
'Visual review': 'Review visual changes before they reach users.',
'Web scripts': 'Add a website tag without changing your application code.',
Workflows: 'Send a follow-up when someone completes an onboarding step.',
diff --git a/frontend/src/lib/agentScopes.generated.ts b/frontend/src/lib/agentScopes.generated.ts
index 6d54632deb39..35978112e31b 100644
--- a/frontend/src/lib/agentScopes.generated.ts
+++ b/frontend/src/lib/agentScopes.generated.ts
@@ -147,8 +147,6 @@ export const AGENT_USE_CASE_SCOPES = [
'usage_metric:write',
'user:read',
'user:write',
- 'user_interview:read',
- 'user_interview:write',
'vision_alert:read',
'vision_alert:write',
'visual_review:read',
diff --git a/frontend/src/lib/api-ratchet-baseline.txt b/frontend/src/lib/api-ratchet-baseline.txt
index 9cefc7356721..db9a1613410b 100644
--- a/frontend/src/lib/api-ratchet-baseline.txt
+++ b/frontend/src/lib/api-ratchet-baseline.txt
@@ -247,8 +247,6 @@ task projects/{}/tasks/{}
taskRun projects/{}/tasks/{}/runs/{}
taskRuns projects/{}/tasks/{}/runs
tasks projects/{}/tasks
-userInterview projects/{}/user_interviews/{}
-userInterviews projects/{}/user_interviews
users users
webAnalyticsFilterPreset projects/{}/web_analytics_filter_presets/{}
webAnalyticsFilterPresets projects/{}/web_analytics_filter_presets
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index f4a4e0b5bc4f..362a0f010bd6 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -204,7 +204,6 @@ import {
TeamType,
TwilioPhoneNumberType,
UserBasicType,
- UserInterviewType,
UserType,
WarehouseTableFileUpload,
WebAnalyticsFilterPresetType,
@@ -1203,15 +1202,6 @@ export class ApiRequest {
return this.earlyAccessFeatures(teamId).addPathComponent(id)
}
- // # User interviews
- public userInterviews(teamId?: TeamType['id']): ApiRequest {
- return this.teamProjectDetail(teamId).addPathComponent('user_interviews')
- }
-
- public userInterview(id: UserInterviewType['id'], teamId?: TeamType['id']): ApiRequest {
- return this.userInterviews(teamId).addPathComponent(id)
- }
-
// # Users
public users(email?: string): ApiRequest {
if (email) {
@@ -4977,21 +4967,6 @@ const api = {
},
},
- userInterviews: {
- async list(): Promise<PaginatedResponse<UserInterviewType>> {
- return await new ApiRequest().userInterviews().get()
- },
- async get(id: UserInterviewType['id']): Promise<UserInterviewType> {
- return await new ApiRequest().userInterview(id).get()
- },
- async update(
- id: UserInterviewType['id'],
- data: Pick<UserInterviewType, 'summary'>
- ): Promise<UserInterviewType> {
- return await new ApiRequest().userInterview(id).update({ data })
- },
- },
-
users: {
async list(email?: string): Promise<PaginatedResponse<UserType>> {
return await new ApiRequest().users(email).get()
diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
index 0491c1ea3a1b..db499dee0ab2 100644
--- a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
@@ -45,7 +45,6 @@ import { llmSkillsEmptyState } from 'products/skills/frontend/emptyState/llmSkil
import { subscriptionsEmptyState } from 'products/subscriptions/frontend/emptyState/subscriptionsEmptyState'
import { surveysEmptyState } from 'products/surveys/frontend/emptyState/surveysEmptyState'
import { tracingEmptyState } from 'products/tracing/frontend/emptyState/tracingEmptyState'
-import { userInterviewsEmptyState } from 'products/user_interviews/frontend/emptyState/userInterviewsEmptyState'
import { webVitalsEmptyState } from 'products/web_analytics/frontend/emptyState/webVitalsEmptyState'
import { heatmapsEmptyState } from 'products/web_analytics/frontend/heatmaps/emptyState/heatmapsEmptyState'
import { workflowsEmptyState } from 'products/workflows/frontend/emptyState/workflowsEmptyState'
@@ -189,12 +188,6 @@ export const EndpointsNeedsSetup: ProductEmptyStateStory = productEmptyStateStor
mocks: { get: { '/api/projects/:team_id/endpoints/': [200, emptyEntityList] } },
})
-export const UserInterviewsNeedsSetup: ProductEmptyStateStory = productEmptyStateStory(
- userInterviewsEmptyState,
- 'needs-setup',
- { mocks: { get: { '/api/projects/:team_id/user_interview_topics/': [200, emptyEntityList] } } }
-)
-
export const LinksNeedsSetup: ProductEmptyStateStory = productEmptyStateStory(linksEmptyState, 'needs-setup', {
mocks: { get: { '/api/projects/:team_id/links/': [200, emptyEntityList] } },
})
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index c183b6a88d0f..093d3a80274e 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -571,7 +571,6 @@ export const FEATURE_FLAGS = {
TRAFFIC_TYPE_VIRTUAL_PROPERTIES: 'traffic-type-virtual-properties', // owner: #team-web-analytics
UI_CUSTOMIZATION: 'ui-customization-enabled', // owner: @fercgomes #team-self-driving, gates sidebar/homepage UI customization
UNIFIED_APM_PRODUCT: 'unified-apm-product', // owner: #team-apm (@jonmcwest, @frankh), gates the shared APM product backing logs, tracing, and metrics
- USER_INTERVIEWS: 'user-interviews', // owner: @Twixes @jurajmajerik
UX_HIDE_PROJECT_NOTICE: 'ux-hide-project-notice', // owner: #team-platform-ux, hides the project notice banner across all scenes
UX_REMOVE_SIDEPANEL: 'ux-remove-sidepanel', // owner: #team-surveys
VISION_ENTRYPOINT_ERROR_TRACKING: 'vision-entrypoint-error-tracking', // owner: #team-replay, cross-sell entry point from the error tracking issue recording tab
diff --git a/frontend/src/loadPostHogJS.tsx b/frontend/src/loadPostHogJS.tsx
index 84bacf6ae42b..1f2ceb5f3b9e 100644
--- a/frontend/src/loadPostHogJS.tsx
+++ b/frontend/src/loadPostHogJS.tsx
@@ -1,4 +1,4 @@
-import posthog, { BeforeSendFn, BrowserMetricsConfig, PostHogConfig, SessionRecordingOptions } from 'posthog-js'
+import posthog, { BeforeSendFn, PostHogConfig } from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { isOAuthMode } from 'lib/oauth/oauthClient'
@@ -76,28 +76,7 @@ function writeLastSeenFeatureFlags(lastSeen: LastSeenFeatureFlags): void {
}
}
-export interface LoadPostHogJSOptions {
- /**
- * Hook posthog-js's `before_send` so the caller can mutate or drop events before they leave
- * the browser. Used by the exporter app to redact the SharingConfiguration access token from
- * URL-shaped properties on the interview share page — see `frontend/src/exporter/index.tsx`.
- */
- beforeSend?: BeforeSendFn | BeforeSendFn[]
- /**
- * Extra `session_recording` config merged on top of the defaults — useful for overriding URL
- * / network-payload masking when the page renders sensitive bearer tokens in its own URL.
- */
- sessionRecording?: Partial<SessionRecordingOptions>
- /**
- * Extra `metrics` config merged on top of the defaults. `before_send` and
- * `maskCapturedNetworkRequestFn` do not cover the network metrics channel, so the exporter
- * app uses this to override `network.attributes` and keep the SharingConfiguration access
- * token out of the captured `path`. See `frontend/src/exporter/index.tsx`.
- */
- metrics?: Partial<BrowserMetricsConfig>
-}
-
-export function loadPostHogJS(options: LoadPostHogJSOptions = {}): void {
+export function loadPostHogJS(): void {
if (window.JS_POSTHOG_API_KEY) {
posthog.init(window.JS_POSTHOG_API_KEY, {
opt_out_useragent_filter: window.location.hostname === 'localhost', // we ARE a bot when running in localhost, so we need to enable this opt-out
@@ -127,12 +106,10 @@ export function loadPostHogJS(options: LoadPostHogJSOptions = {}): void {
error_tracking: {
__capturePostHogExceptions: true,
},
- metrics: { network: true, serviceName: 'posthog-app', ...options.metrics },
+ metrics: { network: true, serviceName: 'posthog-app' },
// A page in a frame counts its own pageviews, so its events say so and analysis can filter them.
// `register` would persist the property in storage the main window shares, so it is stamped per event.
- before_send: isEmbeddedPageFrame()
- ? [stampEmbeddedPageFrame, ...(options.beforeSend ? [options.beforeSend].flat() : [])]
- : options.beforeSend,
+ before_send: isEmbeddedPageFrame() ? stampEmbeddedPageFrame : undefined,
loaded: (loadedInstance) => {
if (loadedInstance.sessionRecording) {
loadedInstance.sessionRecording._forceAllowLocalhostNetworkCapture = true
@@ -231,7 +208,6 @@ export function loadPostHogJS(options: LoadPostHogJSOptions = {}): void {
session_recording: {
blockSelector: '.ph-replay-block',
streamNetworkBody: true,
- ...options.sessionRecording,
},
person_profiles: 'always',
// posthog-js patches fetch to add X-POSTHOG-* tracing headers to these hosts. In OAuth
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsx
index 9eadc3a50b5a..c0daab427edd 100644
--- a/frontend/src/productScenes.tsx
+++ b/frontend/src/productScenes.tsx
@@ -183,9 +183,6 @@ export const productScenes: Record<string, () => Promise<any>> = {
import('../../products/tracing/frontend/scenes/TracingRetentionNewScene/TracingRetentionNewScene'),
TracingRetentionDetail: () =>
import('../../products/tracing/frontend/scenes/TracingRetentionDetailScene/TracingRetentionDetailScene'),
- UserInterviews: () => import('../../products/user_interviews/frontend/UserInterviews'),
- UserInterview: () => import('../../products/user_interviews/frontend/UserInterview'),
- UserInterviewResponse: () => import('../../products/user_interviews/frontend/UserInterviewResponse'),
VisualReviewIndex: () => import('../../products/visual_review/frontend/scenes/VisualReviewIndexScene'),
VisualReviewRuns: () => import('../../products/visual_review/frontend/scenes/VisualReviewRunsScene'),
VisualReviewRun: () => import('../../products/visual_review/frontend/scenes/VisualReviewRunScene'),
diff --git a/frontend/src/products.json b/frontend/src/products.json
index 29bc46f51dc2..d6a7cfe5d81d 100644
--- a/frontend/src/products.json
+++ b/frontend/src/products.json
@@ -256,13 +256,6 @@
},
{ "path": "Toolbar", "category": "Tools", "iconType": "toolbar", "type": "toolbar", "intents": ["toolbar"] },
{ "path": "Tracing", "category": "Monitoring", "iconType": "tracing", "type": null, "intents": ["tracing"] },
- {
- "path": "User research",
- "category": "Unreleased",
- "iconType": "user_interview",
- "type": "user_interview",
- "intents": ["user_interviews"]
- },
{
"path": "Visual review",
"category": "Unreleased",
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 901f071904a3..5971f7ef418b 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -294,9 +294,6 @@ export const productRoutes: Record<string, [string, string]> = {
'/tracing/operation': ['TracingOperation', 'tracingOperation'],
'/tracing/retention-rules/new': ['TracingRetentionNew', 'tracingRetentionNew'],
'/tracing/retention-rules/:id': ['TracingRetentionDetail', 'tracingRetentionDetail'],
- '/user_research': ['UserInterviews', 'userInterviews'],
- '/user_research/:topicId/response/:responseId': ['UserInterviewResponse', 'userInterviewResponse'],
- '/user_research/:id': ['UserInterview', 'userInterview'],
'/visual_review': ['VisualReviewIndex', 'visualReviewIndex'],
'/visual_review/settings': ['VisualReviewSettings', 'visualReviewSettings'],
'/visual_review/runs/:runId': ['VisualReviewRun', 'visualReviewRun'],
@@ -506,7 +503,6 @@ export const productRedirects: Record<
combineUrl(urls.skills(), searchParams, hashParams).url,
'/llm-analytics/skills/:name': (params, searchParams, hashParams) =>
combineUrl(urls.skill(params.name), searchParams, hashParams).url,
- '/user_interviews': '/user_research',
}
/** This const is auto-generated, as is the whole file */
@@ -1150,15 +1146,6 @@ export const productConfiguration: Record<string, any> = {
activityScope: 'Tracing',
iconType: 'tracing',
},
- UserInterviews: {
- name: 'User research',
- projectBased: true,
- activityScope: 'UserInterview',
- description: 'Run AI-powered voice research campaigns to gather user insights at scale.',
- iconType: 'user_interview',
- },
- UserInterview: { name: 'Interview topic', projectBased: true, activityScope: 'UserInterview' },
- UserInterviewResponse: { name: 'Interview response', projectBased: true, activityScope: 'UserInterview' },
VisualReviewIndex: {
name: 'Visual review',
description:
@@ -1784,10 +1771,6 @@ export const productUrls = {
}).url,
tracingRetentionNew: (): string => '/tracing/retention-rules/new',
tracingRetentionDetail: (id: string): string => `/tracing/retention-rules/${id}`,
- userInterviews: (): string => '/user_research',
- userInterview: (id: string): string => `/user_research/${id}`,
- userInterviewResponse: (topicId: string, responseId: string): string =>
- `/user_research/${topicId}/response/${responseId}`,
visualReviewRuns: (): string => '/visual_review',
visualReviewSettings: (): string => '/visual_review/settings',
visualReviewRun: (runId: string): string => `/visual_review/runs/${runId}`,
@@ -1937,14 +1920,6 @@ export const fileSystemTypes = {
filterKey: 'task',
flag: FEATURE_FLAGS.TASKS,
},
- user_interview: {
- name: 'User research',
- iconType: 'user_interview',
- href: (ref: string) => urls.userInterview(ref),
- iconColor: ['var(--color-product-user-interviews-light)', 'var(--color-product-user-interviews-dark)'],
- filterKey: 'user_interview',
- flag: FEATURE_FLAGS.USER_INTERVIEWS,
- },
workflows: {
name: 'Workflow',
iconType: 'workflows',
@@ -2189,7 +2164,6 @@ export type ProductTreePath =
| 'Tasks'
| 'Toolbar'
| 'Tracing'
- | 'User research'
| 'Visual review'
| 'Web analytics'
| 'Web scripts'
@@ -2955,22 +2929,6 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
sceneKey: 'Tracing',
sceneKeys: ['Tracing', 'TracingOperation', 'TracingRetentionNew', 'TracingRetentionDetail'],
},
- {
- path: 'User research',
- intents: [ProductKey.USER_INTERVIEWS],
- category: ProductItemCategory.UNRELEASED,
- href: urls.userInterviews(),
- type: 'user_interview',
- flag: FEATURE_FLAGS.USER_INTERVIEWS,
- tags: ['alpha'],
- iconType: 'user_interview',
- iconColor: [
- 'var(--color-product-user-interviews-light)',
- 'var(--color-product-user-interviews-dark)',
- ] as FileSystemIconColor,
- sceneKey: 'UserInterviews',
- sceneKeys: ['UserInterviews', 'UserInterview', 'UserInterviewResponse'],
- },
{
path: 'Visual review',
intents: [ProductKey.VISUAL_REVIEW],
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 8d51dfd2b28a..7323ff53a6fd 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -5047,8 +5047,6 @@
"search_session_recordings",
"create_ai_trace_parser",
"fix_hogql_query",
- "analyze_user_interviews",
- "create_user_interview_topic",
"create_hog_transformation_function",
"create_hog_function_filters",
"create_hog_function_inputs",
@@ -27092,7 +27090,6 @@
"session_profile",
"survey",
"product_tour",
- "user_interview",
"early_access_feature",
"experiment",
"feature_flag",
@@ -40609,7 +40606,6 @@
"toolbar",
"tracing",
"metrics",
- "user_interviews",
"visual_review",
"web_analytics",
"workflows"
diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.ts
index b466b113ead3..83047ae37db3 100644
--- a/frontend/src/queries/schema/schema-assistant-messages.ts
+++ b/frontend/src/queries/schema/schema-assistant-messages.ts
@@ -454,8 +454,6 @@ export type AssistantTool =
| 'search_session_recordings'
| 'create_ai_trace_parser'
| 'fix_hogql_query'
- | 'analyze_user_interviews'
- | 'create_user_interview_topic'
| 'create_hog_transformation_function'
| 'create_hog_function_filters'
| 'create_hog_function_inputs'
@@ -546,6 +544,7 @@ export enum AgentMode {
Flags = 'flags',
AIObservability = 'llm_analytics',
Sandbox = 'sandbox',
+ /** Retired. Kept so stored conversations in this mode still load. */
UserInterview = 'user_interview',
CustomerAnalytics = 'customer_analytics',
}
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 135079266256..30152b5f7e7f 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -5425,7 +5425,6 @@ export type FileSystemIconType =
| 'session_profile'
| 'survey'
| 'product_tour'
- | 'user_interview'
| 'early_access_feature'
| 'experiment'
| 'feature_flag'
@@ -9109,7 +9108,6 @@ export enum ProductKey {
TOOLBAR = 'toolbar',
TRACING = 'tracing',
METRICS = 'metrics',
- USER_INTERVIEWS = 'user_interviews',
VISUAL_REVIEW = 'visual_review',
WEB_ANALYTICS = 'web_analytics',
WORKFLOWS = 'workflows',
diff --git a/frontend/src/scenes/library/libraryLogic.ts b/frontend/src/scenes/library/libraryLogic.ts
index d8097586f7c7..084fd94ef479 100644
--- a/frontend/src/scenes/library/libraryLogic.ts
+++ b/frontend/src/scenes/library/libraryLogic.ts
@@ -19,7 +19,6 @@ const MAX_PAGES_PER_LOAD = 5
const PLURAL_LABELS: Record<string, string> = {
session_recording_playlist: 'Replay playlists',
- user_interview: 'User research',
}
export interface LibraryObjects {
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index 3198051ee9fe..ce6e4afdc566 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -642,34 +642,6 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
return ['Filtering recordings...', widgetDef]
},
},
- analyze_user_interviews: {
- name: 'Analyze user interviews',
- description: 'Analyze user interviews, summarizing pages of feedback, and extracting learnings',
- product: Scene.UserInterviews,
- flag: FEATURE_FLAGS.USER_INTERVIEWS,
- icon: iconForType('user_interview'),
- modes: [AgentMode.UserInterview],
- displayFormatter: (toolCall) => {
- if (toolCall.status === 'completed') {
- return 'Analyzed user interviews'
- }
- return 'Analyzing user interviews...'
- },
- },
- create_user_interview_topic: {
- name: 'Set up user interviews',
- description: 'Set up user interviews — plan a research topic, target participants, and draft questions',
- product: Scene.UserInterviews,
- flag: FEATURE_FLAGS.USER_INTERVIEWS,
- icon: iconForType('user_interview'),
- modes: [AgentMode.UserInterview],
- displayFormatter: (toolCall) => {
- if (toolCall.status === 'completed') {
- return 'Created interview topic'
- }
- return 'Setting up interview topic...'
- },
- },
create_hog_function_filters: {
name: 'Set up function filters',
description: 'Set up function filters for quick pipeline configuration',
@@ -1500,7 +1472,10 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
}
export const MODE_DEFINITIONS: Record<
- Exclude<AgentMode, AgentMode.Plan | AgentMode.Execution | AgentMode.Research | AgentMode.Sandbox>,
+ Exclude<
+ AgentMode,
+ AgentMode.Plan | AgentMode.Execution | AgentMode.Research | AgentMode.Sandbox | AgentMode.UserInterview
+ >,
ModeDefinition
> = {
[AgentMode.ProductAnalytics]: {
@@ -1569,13 +1544,6 @@ export const MODE_DEFINITIONS: Record<
Scene.AIObservabilityUsers,
]),
},
- [AgentMode.UserInterview]: {
- name: 'User interviews',
- description: 'Sets up live AI voice interviews and analyzes interview transcripts.',
- icon: iconForType('user_interview'),
- scenes: new Set([Scene.UserInterviews, Scene.UserInterview, Scene.UserInterviewResponse]),
- flag: 'USER_INTERVIEWS',
- },
[AgentMode.CustomerAnalytics]: {
name: 'Customer analytics',
description:
diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.ts
index ced3f40b9ba3..452d56d12d2d 100644
--- a/frontend/src/scenes/max/maxThreadLogic.test.ts
+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts
@@ -3583,6 +3583,19 @@ describe('maxThreadLogic', () => {
})
})
+ it('setConversation falls back to the default mode for a retired agent mode', async () => {
+ const conversationWithRetiredMode: Conversation = {
+ ...MOCK_CONVERSATION,
+ agent_mode: AgentMode.UserInterview,
+ }
+
+ await expectLogic(logic, () => {
+ logic.actions.setConversation(conversationWithRetiredMode)
+ }).toMatchValues({
+ agentMode: AgentMode.ProductAnalytics,
+ })
+ })
+
it('setConversation does not sync agent mode when locked by user', async () => {
logic.actions.setAgentMode(AgentMode.SQL)
expect(logic.values.agentModeLockedByUser).toBe(true)
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsx
index 3050ea0bb0a4..051b62037289 100644
--- a/frontend/src/scenes/max/maxThreadLogic.tsx
+++ b/frontend/src/scenes/max/maxThreadLogic.tsx
@@ -1730,7 +1730,15 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
}
// Sync agentMode from conversation only if user hasn't manually selected a mode after submission
if (!values.agentModeLockedByUser && conversation?.agent_mode) {
- actions.syncAgentModeFromConversation(conversation.agent_mode as AgentMode)
+ const conversationAgentMode = conversation.agent_mode as AgentMode
+ // Older conversations can store the retired user interview mode, which has no selector
+ // option. Use the default mode, as ee/hogai/chat_agent/mode_manager.py does. Match the
+ // retired mode exactly, because live modes such as Research also have no MODE_DEFINITIONS entry.
+ actions.syncAgentModeFromConversation(
+ conversationAgentMode === AgentMode.UserInterview
+ ? AgentMode.ProductAnalytics
+ : conversationAgentMode
+ )
}
if (conversation?.is_sandbox) {
actions.setIsSandboxMode(true)
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index 4bda534d61ef..404ad4b5905e 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -202,9 +202,6 @@ export enum Scene {
CodeChannelLink = 'CodeChannelLink',
CodeTaskLink = 'CodeTaskLink',
CodeLoopLink = 'CodeLoopLink',
- UserInterview = 'UserInterview',
- UserInterviewResponse = 'UserInterviewResponse',
- UserInterviews = 'UserInterviews',
VercelConnect = 'VercelConnect',
VercelLinkError = 'VercelLinkError',
VerifyEmail = 'VerifyEmail',
diff --git a/frontend/src/scenes/user-research/UserInterviews.stories.tsx b/frontend/src/scenes/user-research/UserInterviews.stories.tsx
deleted file mode 100644
index ceec2253a7df..000000000000
--- a/frontend/src/scenes/user-research/UserInterviews.stories.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-import { MOCK_DEFAULT_BASIC_USER } from '~/lib/api.mock'
-
-import type { Meta, StoryObj } from '@storybook/react'
-import { within } from '@testing-library/dom'
-import userEvent from '@testing-library/user-event'
-
-import { App } from 'scenes/App'
-import { urls } from 'scenes/urls'
-
-import { mswDecorator } from '~/mocks/browser'
-import { toPaginatedResponse } from '~/mocks/handlers'
-
-import type {
- UserInterviewSearchResultApi,
- UserInterviewTopicApi,
-} from '../../../../products/user_interviews/frontend/generated/api.schemas'
-
-const MOCK_TOPICS = [
- {
- id: '01999999-0000-0000-0000-000000000001',
- created_by: MOCK_DEFAULT_BASIC_USER,
- created_at: '2026-05-15T10:00:00Z',
- topic: 'How users discover the MCP integration',
- interviewee_distinct_ids: [],
- agent_context: '',
- questions: ['Why MCP?', 'Web UI experience?', 'What could we improve?'],
- },
- {
- id: '01999999-0000-0000-0000-000000000002',
- created_by: MOCK_DEFAULT_BASIC_USER,
- created_at: '2026-05-12T09:30:00Z',
- topic: 'Trial users that did not convert',
- interviewee_emails: ['[email protected]', '[email protected]'],
- interviewee_distinct_ids: ['distinct-no-email'],
- agent_context: 'Be warm, the trial just ended',
- questions: ['What was missing?', 'What were you hoping for?'],
- },
- {
- id: '01999999-0000-0000-0000-000000000003',
- created_by: MOCK_DEFAULT_BASIC_USER,
- created_at: '2026-05-10T14:00:00Z',
- topic: 'Power users of session replay',
- interviewee_emails: [],
- interviewee_distinct_ids: ['power-user-1', 'power-user-2'],
- agent_context: '',
- questions: ['How did you discover replay?', 'What workflow does it support?'],
- },
-] as unknown as UserInterviewTopicApi[]
-
-const MOCK_SEARCH_RESULTS: UserInterviewSearchResultApi[] = [
- {
- interview_id: 'i-1',
- topic_id: '01999999-0000-0000-0000-000000000001',
- document_type: 'transcript',
- similarity: 0.92,
- interviewee_identifier: '[email protected]',
- content_snippet:
- "I just use the MCP from Claude Code. Honestly I've never opened the PostHog web UI to make a chart — the agent does it faster and I trust it.",
- created_at: '2026-05-12T10:00:00Z',
- },
- {
- interview_id: 'i-2',
- topic_id: '01999999-0000-0000-0000-000000000001',
- document_type: 'summary',
- similarity: 0.84,
- interviewee_identifier: '[email protected]',
- content_snippet:
- 'Heavy MCP user. Prefers conversational queries over clicking through filters. Wants chart-saving via the MCP to be more obvious.',
- created_at: '2026-05-11T09:30:00Z',
- },
- {
- interview_id: 'i-3',
- topic_id: '01999999-0000-0000-0000-000000000001',
- document_type: 'transcript',
- similarity: 0.71,
- interviewee_identifier: '[email protected]',
- content_snippet:
- "Most of my colleagues still use the web UI, but I'm a CLI person. The MCP fits my workflow because I'm already in my terminal all day.",
- created_at: '2026-05-10T16:00:00Z',
- },
-]
-
-type Empty = Record<string, never>
-
-const meta: Meta<Empty> = {
- component: App,
- title: 'Scenes-App/User Research/Topics',
- parameters: {
- layout: 'fullscreen',
- viewMode: 'story',
- mockDate: '2026-05-19',
- pageUrl: urls.userInterviews(),
- testOptions: {
- waitForLoadersToDisappear: true,
- },
- },
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/user_interview_topics/': toPaginatedResponse(MOCK_TOPICS),
- },
- post: {
- '/api/environments/:team_id/user_interviews/search/': MOCK_SEARCH_RESULTS,
- },
- }),
- ],
-}
-export default meta
-type Story = StoryObj<Empty>
-
-async function typeSearch(canvasElement: HTMLElement, query: string): Promise<void> {
- const canvas = within(canvasElement)
- const input = await canvas.findByPlaceholderText(/Search what users said/i)
- await userEvent.type(input, query)
-}
-
-export const TopicsList: Story = {}
-
-export const SearchWithResults: Story = {
- play: async ({ canvasElement }) => {
- await typeSearch(canvasElement, 'how do you use the mcp')
- },
-}
-
-export const SearchNoResults: Story = {
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/user_interview_topics/': toPaginatedResponse(MOCK_TOPICS),
- },
- post: {
- '/api/environments/:team_id/user_interviews/search/': [] as UserInterviewSearchResultApi[],
- },
- }),
- ],
- play: async ({ canvasElement }) => {
- await typeSearch(canvasElement, 'something nobody talked about')
- },
-}
diff --git a/frontend/src/styles/base.scss b/frontend/src/styles/base.scss
index 2431f376555b..26747dafc880 100644
--- a/frontend/src/styles/base.scss
+++ b/frontend/src/styles/base.scss
@@ -366,8 +366,6 @@
--color-product-metrics-dark: rgb(251 146 60);
--color-product-revenue-analytics-light: rgb(52 175 102);
--color-product-revenue-analytics-dark: rgb(54 196 111);
- --color-product-user-interviews-light: rgb(0 140 255);
- --color-product-user-interviews-dark: rgb(77 171 255);
--color-product-dashboards-light: rgb(255 139 7);
--color-product-dashboards-dark: rgb(255 168 71);
--color-product-early-access-features-light: rgb(39 171 151);
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index a4e166564f93..5fc3938f9963 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4996,15 +4996,6 @@ export interface Group {
notebook: string | null
}
-export interface UserInterviewType {
- id: string
- created_by: UserBasicType
- created_at: string
- transcript: string
- summary: string
- interviewee_emails: string[]
-}
-
export enum ExperimentConclusion {
Won = 'won',
Lost = 'lost',
@@ -6107,7 +6098,6 @@ export enum ActivityScope {
DATA_WAREHOUSE_EXPRESSION = 'DataWarehouseExpression',
DATA_WAREHOUSE_SAVED_QUERY = 'DataWarehouseSavedQuery',
DATA_QUALITY_CHECK = 'DataQualityCheck',
- USER_INTERVIEW = 'UserInterview',
TAG = 'Tag',
TAGGED_ITEM = 'TaggedItem',
EVALUATION = 'Evaluation',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f9e78109211c..6d589196ca28 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -857,9 +857,6 @@ importers:
'@posthog/products-tracing':
specifier: workspace:*
version: link:../products/tracing
- '@posthog/products-user-interviews':
- specifier: workspace:*
- version: link:../products/user_interviews
'@posthog/products-visual-review':
specifier: workspace:*
version: link:../products/visual_review
@@ -1007,9 +1004,6 @@ importers:
'@tiptap/suggestion':
specifier: 3.20.6
version: 3.20.6(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
- '@vapi-ai/web':
- specifier: 2.5.2
- version: 2.5.2
'@vitejs/plugin-react':
specifier: 'catalog:'
@@ -5150,48 +5144,7 @@ importers:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
- products/user_interviews:
- dependencies:
- '@posthog/brand':
- specifier: 'catalog:'
- version: 0.12.3([email protected])
- '@posthog/icons':
- specifier: 'catalog:'
- '@storybook/react':
- specifier: 'catalog:'
- '@types/react':
- specifier: 18.3.27
- version: 18.3.27
- clsx:
- specifier: '*'
- version: 1.2.1
- jest:
- specifier: '*'
- kea:
- specifier: 'catalog:'
- version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
- kea-loaders:
- specifier: 'catalog:'
- version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
- kea-router:
- specifier: 'catalog:'
- version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
- posthog-js:
- specifier: 'catalog:'
- version: 1.435.5(@types/[email protected])([email protected])
- react:
- specifier: 18.3.1
- version: 18.3.1
- typescript:
- specifier: 6.0.3
- version: 6.0.3
- devDependencies:
- kea-test-utils:
- specifier: 'catalog:'
- version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ products/user_interviews: {}
products/visual_review:
dependencies:
@@ -7502,10 +7455,6 @@ packages:
resolution: {integrity: sha512-mepCf/e9+SKYy1d02/UkvSy6+6MoyXhVxP8lLDfA7BPE1X1d4dR0sZznmbM8/XVJ1GPM+Svnx7Xj6ZweByWUkw==}
engines: {node: '>17.0.0'}
- '@daily-co/[email protected]':
- resolution: {integrity: sha512-lpl111ZWNTUWDnwYcPuNi9PGJPbLCeCw6LzmEY40nG0hv1jg5JLVW8Rq3Cj/+lOCP6W6h4PXm211ss0FFnxITQ==}
- engines: {node: '>=10.0.0'}
-
'@datadog/[email protected]':
resolution: {integrity: sha512-qX32upm9eqObGVGvqHpjQB2bXVPTX0ccXTW3mUqUWXgJrAKyHtTfo9PqfoXhflYs0WD9el9xl9c0bM1RS4vRmQ==}
engines: {node: '>=16'}
@@ -11836,30 +11785,6 @@ packages:
resolution: {integrity: sha512-y2JVHeQsRADEWRLNXV5uf8BAP5PowYU5IBxsSiJY9WCIDS3/RT98g6fFRURefKn+9Dalmp7X7pcHUX5wW2ljYw==}
hasBin: true
- '@sentry-internal/[email protected]':
- resolution: {integrity: sha512-GnKod+gL/Y+1FUM/RGV8q6le1CoyiGbT40MitEK7eVwWe+bfTRq1gN7ioupyHFMUg1RlQkDQ4/sENmio/uow5A==}
- engines: {node: '>=14.18'}
-
- '@sentry-internal/[email protected]':
- resolution: {integrity: sha512-XQy//NWbL0mLLM5w8wNDWMNpXz39VUyW2397dUrH8++kR63WhUVAvTOtL0o0GMVadSAzl1b08oHP9zSUNFQwcg==}
- engines: {node: '>=14.18'}
-
- '@sentry-internal/[email protected]':
- resolution: {integrity: sha512-P/jGiuR7dRLG9IzD/463fLgiibyYceauav/9prRG0ZxJm1AtuO02OKball2Fs3bbzdzwHCTlcsUuL2ivDF4b5A==}
- engines: {node: '>=14.18'}
-
- '@sentry-internal/[email protected]':
- resolution: {integrity: sha512-+W43Z697EVe/OgpGW07B773sa8xO1UbpnW0Cr+E+3FMDb6ZbXlaBUoagPTUkkQPdwBe35SDh6r8y2M3EOPGbxg==}
- engines: {node: '>=14.18'}
-
- '@sentry/[email protected]':
- resolution: {integrity: sha512-xHuPIEKhx9zw5quWvv4YgZprnwoVMCfxIhmOIf6KJ9iizyUHeUDcKpLS59xERroqwX4RpvK+l/27AZu4zfZlzQ==}
- engines: {node: '>=14.18'}
-
- '@sentry/[email protected]':
- resolution: {integrity: sha512-YlEBwybUcOQ/KjMHDmof1vwweVnBtBxYlQp7DE3fOdtW4pqqdHWTnTntQs4VgYfxzjJYgtkd9LHlGtg8qy+JVQ==}
- engines: {node: '>=14.18'}
-
'@shadcn/[email protected]':
resolution: {integrity: sha512-iKN0NuYe850VDHlxEfvppFrpa7CMV3zArTHusXlaSmeFeQhohGbIqclv6WwPTs/44I8EkXQpcuRt6sXEVKkWqQ==}
peerDependencies:
@@ -13996,10 +13921,6 @@ packages:
'@upsetjs/[email protected]':
resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}
- '@vapi-ai/[email protected]':
- resolution: {integrity: sha512-mT4DjApi0/0+EK77h2xOLq3qVBa7rv3JNQ+gFWuhFE4YdGYxI51+fn8bQI9N535+zU/Z4jFKXotdBHQJ3filHA==}
- engines: {node: '>=18.0.0'}
-
'@vercel/[email protected]':
resolution: {integrity: sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==}
engines: {node: '>= 20'}
@@ -26586,14 +26507,6 @@ snapshots:
'@dagrejs/[email protected]': {}
- '@daily-co/[email protected]':
- dependencies:
- '@babel/runtime': 7.29.7
- '@sentry/browser': 8.55.2
- bowser: 2.11.0
- dequal: 2.0.3
- events: 3.3.0
-
'@datadog/[email protected]':
dependencies:
delay: 5.0.0
@@ -31394,34 +31307,6 @@ snapshots:
'@segment/[email protected]': {}
- '@sentry-internal/[email protected]':
- dependencies:
- '@sentry/core': 8.55.2
-
- '@sentry-internal/[email protected]':
- dependencies:
- '@sentry/core': 8.55.2
-
- '@sentry-internal/[email protected]':
- dependencies:
- '@sentry-internal/replay': 8.55.2
- '@sentry/core': 8.55.2
-
- '@sentry-internal/[email protected]':
- dependencies:
- '@sentry-internal/browser-utils': 8.55.2
- '@sentry/core': 8.55.2
-
- '@sentry/[email protected]':
- dependencies:
- '@sentry-internal/browser-utils': 8.55.2
- '@sentry-internal/feedback': 8.55.2
- '@sentry-internal/replay': 8.55.2
- '@sentry-internal/replay-canvas': 8.55.2
- '@sentry/core': 8.55.2
-
- '@sentry/[email protected]': {}
-
optionalDependencies:
'@types/react': 18.3.27
@@ -33976,11 +33861,6 @@ snapshots:
d3-selection: 3.0.0
d3-transition: 3.0.1([email protected])
- '@vapi-ai/[email protected]':
- dependencies:
- '@daily-co/daily-js': 0.85.0
- events: 3.3.0
-
'@vercel/[email protected]': {}
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index ff03963d01cb..609ec1a88867 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -229,7 +229,7 @@ SHARING_RESOURCE_ACCESS_CHECKS: dict[str, SharingResourceAccessCheck | None] = {
"insight": _require_resource_access("insight", "insight"),
"recording": _require_resource_access("session_recording", "recording"),
"notebook": _require_resource_access("notebook", "notebook"),
- # Materialized by the user-interviews link-generation flow, never via SharingConfigurationViewSet.
+ # The user interviews product is retired. No flow creates these configs, and this viewset never edits them.
"interviewee_context": None,
}
@@ -924,10 +924,11 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
"insight",
"recording",
"notebook",
- "interviewee_context",
- "interviewee_context__topic",
)
- .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now()))
+ .filter(
+ Q(expires_at__isnull=True) | Q(expires_at__gt=now()),
+ SharingConfiguration.without_retired_resources_q(),
+ )
.get(access_token=access_token)
)
except SharingConfiguration.DoesNotExist:
@@ -1354,47 +1355,6 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
"themes": get_themes_for_team(resource.team),
}
)
- elif isinstance(resource, SharingConfiguration) and resource.interviewee_context:
- from products.user_interviews.backend.facade.api import (
- has_replied,
- is_shared_interviewee_context,
- parse_interviewee_identifier,
- )
-
- ic = resource.interviewee_context
- topic = ic.topic
- asset_title = topic.topic or "User interview"
- asset_description = "PostHog AI user interview"
- # A shared link's IntervieweeContext carries a sentinel identifier: every visitor is a new
- # anonymous respondent, so there's no fixed name and no "already replied" gate — the
- # viewer prompts for a name before starting.
- shared = is_shared_interviewee_context(ic.interviewee_identifier)
- if shared:
- user_name = ""
- already_replied = False
- else:
- user_name = parse_interviewee_identifier(ic.interviewee_identifier).display_name
- already_replied = has_replied(
- team_id=topic.team_id,
- topic_id=topic.id,
- interviewee_identifier=ic.interviewee_identifier,
- )
- # Keep agent_context, questions, and Vapi credentials OUT of the public HTML —
- # the recipient would otherwise see their own internal-notes context in view-source.
- # The exporter scene fetches those server-side via /start_call/ when the user clicks Start.
- exported_data.update(
- {
- "type": "interview",
- "interview": {
- "topic_id": str(topic.id),
- "interviewee_identifier": "" if shared else ic.interviewee_identifier,
- "user_name": user_name,
- "topic": topic.topic,
- "already_replied": already_replied,
- "shared": shared,
- },
- }
- )
elif isinstance(resource, SharingConfiguration) and resource.recording:
asset_title = "Session Recording"
recording_data = SessionRecordingSerializer(resource.recording, context=context).data
diff --git a/posthog/api/test/test_product_urls.py b/posthog/api/test/test_product_urls.py
index cc9dfbde6dea..967bf262d2cf 100644
--- a/posthog/api/test/test_product_urls.py
+++ b/posthog/api/test/test_product_urls.py
@@ -47,7 +47,6 @@ class TestProductRootRoutes(SimpleTestCase):
class TestProductRootRoutesInTheUrlConf(SimpleTestCase):
@parameterized.expand(
[
- ("a path a product declares", "/api/user_interviews/vapi_webhook/", "user_interviews_vapi_webhook"),
("a path without a trailing slash", "/api/legal_documents/pandadoc", "legal_document_pandadoc_webhook"),
("a list a product includes", "/api/customer_analytics/external/account", "external-account"),
]
diff --git a/posthog/api/test/test_sharing_access_token_security.py b/posthog/api/test/test_sharing_access_token_security.py
index ced1e82e0acb..141016359b41 100644
--- a/posthog/api/test/test_sharing_access_token_security.py
+++ b/posthog/api/test/test_sharing_access_token_security.py
@@ -17,6 +17,7 @@ from posthog.models.sharing_configuration import SharingConfiguration
from products.dashboards.backend.models.dashboard import Dashboard
from products.product_analytics.backend.facade.models import Insight
+from products.user_interviews.backend.models import IntervieweeContext, UserInterviewTopic
class SharingAccessTokenSecurityTest(APIBaseTest):
@@ -489,6 +490,27 @@ class SharingAccessTokenSecurityTest(APIBaseTest):
sharing_config = SharingConfiguration.objects.create(team=self.team, dashboard=self.dashboard, enabled=True)
return insight, sharing_config
+ def test_sharing_access_token_of_retired_user_interview_is_rejected(self):
+ topic = UserInterviewTopic.objects.create(team=self.team, topic="Onboarding")
+ interviewee_context = IntervieweeContext.objects.create(
+ team=self.team, topic=topic, interviewee_identifier="[email protected]", agent_context="context"
+ )
+ team_config = SharingConfiguration.objects.create(team=self.team, enabled=True)
+ interview_config = SharingConfiguration.objects.create(
+ team=self.team, interviewee_context=interviewee_context, enabled=True
+ )
+
+ team_wide_url = f"/api/projects/{self.team.id}/data_color_themes/"
+ response = self.client.get(team_wide_url, cast(Any, {"sharing_access_token": team_config.access_token}))
+ assert response.status_code == 200, response.content
+
+ response = self.client.get(team_wide_url, cast(Any, {"sharing_access_token": interview_config.access_token}))
+ assert response.status_code == 403, response.content
+ assert response.json()["detail"] == "Sharing access token is invalid."
+
+ response = self.client.get(f"/shared/{interview_config.access_token}")
+ assert response.status_code == 404
+
def test_sharing_access_token_rejected_when_organization_disallows_public_sharing(self):
"""
Regression test for the org-level public sharing kill switch.
diff --git a/posthog/auth.py b/posthog/auth.py
index 7dcdca9397a0..af2f0c24e7b0 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -839,9 +839,9 @@ class SharingAccessTokenAuthentication(ActivityCredentialMixin, authentication.B
if request.method not in ["GET", "HEAD"]:
raise AuthenticationFailed(detail="Sharing access token can only be used for GET requests.")
try:
- sharing_configuration = SharingConfiguration.objects.filter(SharingConfiguration.tokens_active_q()).get(
- access_token=sharing_access_token
- )
+ sharing_configuration = SharingConfiguration.objects.filter(
+ SharingConfiguration.tokens_active_q(), SharingConfiguration.without_retired_resources_q()
+ ).get(access_token=sharing_access_token)
# If password is required, don't authenticate via direct access_token
# Let the view handle showing the unlock page
@@ -897,7 +897,8 @@ class SharingPasswordProtectedAuthentication(ActivityCredentialMixin, authentica
SharePassword.objects.select_related("sharing_configuration")
.filter(
models.Q(sharing_configuration__expires_at__isnull=True)
- | models.Q(sharing_configuration__expires_at__gt=timezone.now())
+ | models.Q(sharing_configuration__expires_at__gt=timezone.now()),
+ SharingConfiguration.without_retired_resources_q(prefix="sharing_configuration__"),
)
.get(
id=payload["share_password_id"],
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 36b729cedb5b..d5aebba23adf 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -87,7 +87,6 @@ class Product(StrEnum):
SQL_EDITOR = "sql_editor"
SURVEYS = "surveys"
TRACING = "tracing"
- USER_INTERVIEWS = "user_interviews"
WAREHOUSE = "warehouse"
WEB_ANALYTICS = "web_analytics"
WORKFLOWS = "workflows"
diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.py
index 1e1f81a7f535..d886579a94ec 100644
--- a/posthog/csp_middleware.py
+++ b/posthog/csp_middleware.py
@@ -76,12 +76,11 @@ REPLAY_PLAYER_FRAME_PATH = "/replay_player_frame/index.html"
#
# The list follows `posthog/urls.py`. The Contour ingress keeps a similar list in
# `charts/argocd/contour-ingress/values/values.{dev,prod-us,prod-eu}.yaml`, which omits
-# `/interview/` and the bare `/exporter`. Sync to the URL patterns, not to that list.
+# the bare `/exporter`. Sync to the URL patterns, not to that list.
EMBEDDABLE_PATH_PREFIXES = (
"/shared_dashboard/",
"/shared/",
"/embedded/",
- "/interview/",
"/exporter/",
"/external_surveys/",
)
diff --git a/posthog/egress/README.md b/posthog/egress/README.md
index ec84bede6d11..4d735a080ac6 100644
--- a/posthog/egress/README.md
+++ b/posthog/egress/README.md
@@ -135,7 +135,7 @@ The weekly Salesforce sweep allows 24 company lookups in flight; each outbound r
`transport/transport.py` holds three bases:
- **`EgressClient`**: gate, request, record, for a sync domain with a budget. A subclass sets `observability`, draws from its budget in `_consume`, and names its `EgressBudgetExhausted` subclass.
-- **`RecordedEgressClient`**: request and record with no gate, for an API that publishes no request limit a rate budget can model. `slack/` and `vapi/` use it.
+- **`RecordedEgressClient`**: request and record with no gate, for an API that publishes no request limit a rate budget can model. `slack/` and `openai_auth/` use it.
- **`AsyncEgressClient`**: the gated algorithm over aiohttp. `harmonic/` uses it.
A domain exposes a `<domain>_request` helper over its client, and may add a typed client for the few endpoints its callers use (see `firecrawl/client.py`).
@@ -154,7 +154,7 @@ It is **never** a PostHog DB row id (`Integration.id`).
Several PostHog integration rows can point at the same installation (multiple projects, one org), and GitHub gives that installation one shared budget: key a gauge by the row and one real budget splits into N flip-flopping series; key by the installation and you get one true series.
Per-caller attribution is the `source` label's job, not the identity's.
-An identity that must not reach a metric label in plain form, such as a token, is hashed first (see `browserless/` and `vapi/`).
+An identity that must not reach a metric label in plain form, such as a token, is hashed first (see `browserless/`).
A caller with no identity in scope passes no scope: it records the counter only and skips both the limiter and the gauges.
## Shared mechanisms
diff --git a/posthog/egress/test/test_vapi_transport.py b/posthog/egress/test/test_vapi_transport.py
deleted file mode 100644
index bc31ac194133..000000000000
--- a/posthog/egress/test/test_vapi_transport.py
+++ /dev/null
@@ -1,58 +0,0 @@
-from unittest.mock import patch
-
-from django.test import SimpleTestCase
-
-import requests
-from prometheus_client import REGISTRY
-
-from posthog.egress.observability.observability import scope_fingerprint
-from posthog.egress.vapi.transport import vapi_request
-
-
-def _request_count(scope: str, status_code: str = "201") -> float:
- labels = {
- "scope": scope,
- "method": "POST",
- "endpoint": "/call/web",
- "status_code": status_code,
- "source": "user_interviews",
- }
- return REGISTRY.get_sample_value("vapi_api_requests_total", labels) or 0
-
-
-class TestVapiTransport(SimpleTestCase):
- def test_request_keeps_the_token_in_the_header_and_out_of_the_metric_scope(self) -> None:
- response = requests.Response()
- response.status_code = 201
- fingerprint = scope_fingerprint("pk_test")
- before = _request_count(fingerprint)
-
- with patch("requests.request", return_value=response) as request:
- vapi_request(
- "POST",
- "https://api.vapi.ai/call/web",
- api_token="pk_test",
- source="user_interviews",
- endpoint="/call/web",
- json={"assistantId": "assistant"},
- )
-
- assert request.call_args.kwargs["headers"]["Authorization"] == "Bearer pk_test"
- assert _request_count(fingerprint) == before + 1
- assert _request_count("pk_test") == 0
-
- def test_a_request_that_raises_is_recorded_and_re_raised(self) -> None:
- fingerprint = scope_fingerprint("pk_test")
- before = _request_count(fingerprint, "exception")
-
- with patch("requests.request", side_effect=requests.ConnectionError("down")):
- with self.assertRaises(requests.ConnectionError):
- vapi_request(
- "POST",
- "https://api.vapi.ai/call/web",
- api_token="pk_test",
- source="user_interviews",
- endpoint="/call/web",
- )
-
- assert _request_count(fingerprint, "exception") == before + 1
diff --git a/posthog/egress/vapi/README.md b/posthog/egress/vapi/README.md
deleted file mode 100644
index da3f299cc55a..000000000000
--- a/posthog/egress/vapi/README.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# Vapi egress
-
-## Identity
-
-A 16-character SHA-256 fingerprint of the API token, so the token never reaches a metric label.
-
-## Budget
-
-None: Vapi calls are recorded, never gated (`RecordedEgressClient`).
-Vapi's docs state no REST request limit.
-The limit they describe is [concurrent call slots](https://docs.vapi.ai/calls/call-concurrency), which a request-rate budget cannot model.
-Add a gate only if Vapi publishes a request limit or starts billing per API call.
-
-## Lanes and callers
-
-No lanes, because nothing is gated.
-The user interviews web call creation (`products/user_interviews/backend/presentation/webhooks.py`) is the caller.
-It maps Vapi's own 429 to a retryable `VapiWebCallError`.
-
-## Rate-limit headers
-
-Vapi returns none, so the domain declares no gauges.
-The counter is `vapi_api_requests_total`, labeled `scope, method, endpoint, status_code, source`.
-
-## Auth
-
-`VAPI_PUBLIC_KEY`, sent as a bearer token.
-
-## Sources
-
-- [Call concurrency](https://docs.vapi.ai/calls/call-concurrency): concurrent call slots. Vapi's docs state no REST request limit.
diff --git a/posthog/egress/vapi/__init__.py b/posthog/egress/vapi/__init__.py
deleted file mode 100644
index fdc32504893c..000000000000
--- a/posthog/egress/vapi/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from posthog.egress.vapi.transport import vapi_request
-
-__all__ = ["vapi_request"]
diff --git a/posthog/egress/vapi/observability.py b/posthog/egress/vapi/observability.py
deleted file mode 100644
index 38aee66d4e98..000000000000
--- a/posthog/egress/vapi/observability.py
+++ /dev/null
@@ -1,18 +0,0 @@
-"""Vapi outbound API request telemetry.
-
-Vapi returns no rate-limit headers, so this domain declares no gauges.
-"""
-
-from prometheus_client import Counter
-
-from posthog.egress.observability.observability import EgressMetrics, EgressObservability
-
-vapi_egress = EgressObservability(
- EgressMetrics(
- request_counter=Counter(
- "vapi_api_requests",
- "Outbound Vapi API requests.",
- labelnames=["scope", "method", "endpoint", "status_code", "source"],
- ),
- )
-)
diff --git a/posthog/egress/vapi/transport.py b/posthog/egress/vapi/transport.py
deleted file mode 100644
index a14fa411c042..000000000000
--- a/posthog/egress/vapi/transport.py
+++ /dev/null
@@ -1,48 +0,0 @@
-"""Recorded transport for calls to the Vapi API.
-
-Vapi documents no REST request limit. The limit it does enforce is concurrent call slots, which a
-request-rate budget cannot model, so these calls are recorded but not gated. The caller maps Vapi's
-own 429 to a retryable error.
-"""
-
-from typing import Any
-
-import requests
-
-from posthog.egress.observability.observability import scope_fingerprint
-from posthog.egress.transport.transport import RecordedEgressClient
-from posthog.egress.vapi.observability import vapi_egress
-
-
-class VapiClient(RecordedEgressClient):
- observability = vapi_egress
-
- def _standard_headers(self) -> dict[str, str]:
- return {"Accept": "application/json", "Content-Type": "application/json"}
-
-
-_vapi_client = VapiClient()
-
-
-def vapi_request(
- method: str,
- url: str,
- *,
- api_token: str,
- source: str,
- endpoint: str,
- timeout: float | tuple[float, float] | None = None,
- session: requests.Session | None = None,
- **kwargs: Any,
-) -> requests.Response:
- return _vapi_client.request(
- method,
- url,
- source=source,
- headers={"Authorization": f"Bearer {api_token}"},
- scope=scope_fingerprint(api_token),
- endpoint=endpoint,
- timeout=timeout,
- session=session,
- **kwargs,
- )
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 01d22f6ab26e..ea1226585431 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -73,7 +73,6 @@ Three duties fall on the incarnation rather than on `BearerJwt`, and none is enf
| `slack` | `/api/conversations/v1/slack/interactivity` | `supporthog_interactivity` | `conversations_slack_interactivity` | `products/conversations/backend/webhook_consumers.py` |
| `teams` | `/api/conversations/v1/teams/events` | `supporthog` | `conversations_teams` | `products/conversations/backend/webhook_consumers.py` |
| `pandadoc` | `/api/legal_documents/pandadoc` | `default` | `legal_documents_signatures` | `products/legal_documents/backend/webhook_consumers.py` |
-| `vapi` | `/api/user_interviews/vapi_webhook/` | `default` | `user_interviews_vapi` | `products/user_interviews/backend/webhook_consumers.py` |
| `mailgun` | `/api/conversations/v1/email/inbound` | `inbound` | `conversations_email_inbound` | `products/conversations/backend/webhook_consumers.py` |
| `mailgun` | `/api/conversations/v1/email/outbound` | `outbound` | `conversations_email_outbound` | `products/conversations/backend/webhook_consumers.py` |
| `mailgun` | `/api/conversations/v1/email/capture` | `capture` | `conversations_email_capture` | `products/conversations/backend/webhook_consumers.py` |
@@ -86,7 +85,7 @@ The customer-facing GitHub App is shared across products, so its two endpoints a
Every other endpoint is declared by the product that registered the App, in its own `routes.py`.
The Vercel Marketplace App is registered by `ee/`, which is not a product, so its route is declared in `ee/urls.py` and its consumer module is named in `posthog/ingress/dispatch/loading.py` rather than discovered.
-The Vapi endpoint is the only one that caps request volume: its provider sets `throttle_class` to a per-IP throttle, because the endpoint is public and Vapi's egress is shared across tenants.
+The Teams endpoint is the only one that caps request volume: its provider sets `throttle_class`, because the endpoint is public and an unsigned request costs a signing-key lookup.
## Non-goals
@@ -238,7 +237,7 @@ A need that a second provider could share becomes shared code: a lane in `views.
A true one-off stays in the provider, marked with a `# One-off:` comment that says why no other provider needs it.
Tracing and metrics in a provider package fail CI unless marked, see "Shared mechanisms" in [the egress README](../egress/README.md#shared-mechanisms).
-Add a `<provider>/` subpackage with a `provider.py` holding three things (see `github/` for the full shape, `vapi/` for a small one):
+Add a `<provider>/` subpackage with a `provider.py` holding three things (see `github/` for the full shape, `pandadoc/` for a small one):
- `SPECS` — one `ProviderSpec` per app, naming the event types the app is subscribed to. The registry validates consumers against these.
- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success, with a short body naming the reason on the two rejections. The 500 suits an endpoint whose secret is always set, because an unconfigured one is then an operator fault; an endpoint that a deployment may legitimately never configure, such as Slack, Mailgun and Teams on a self-hosted instance, sets `unconfigured_status = 403` instead, or the URL answers a server error to every anonymous probe. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well, and so does one that must not tell an unauthenticated caller whether the secret is merely unset. The unconfigured case of an incarnation that answers a 4xx is logged as a warning rather than an error, because an endpoint that an operator may never configure sees probes of a public URL. Four more attributes are optional: `parse()`, which decodes the body, `throttle_class`, which caps request volume, `retry_status`, which a provider that redelivers on a non-2xx sets so an unaccepted delivery is not receipted, and `reports_unconfigured`, which also sends a missing secret to error tracking. That last one is off by default, because an endpoint that answers an unconfigured request like an unknown route lets an unauthenticated prober fill error tracking from the outside; turn it on where the deliveries are lost while the secret is unset and nothing else would notice. See [The lanes one request runs through](#the-lanes-one-request-runs-through).
diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.py
index 33209e765e3b..e9af5e50c133 100644
--- a/posthog/ingress/providers.py
+++ b/posthog/ingress/providers.py
@@ -28,7 +28,6 @@ _INCARNATION_MODULES = (
"posthog.ingress.teams.provider",
"posthog.ingress.pandadoc.provider",
"posthog.ingress.mailgun.provider",
- "posthog.ingress.vapi.provider",
"posthog.ingress.sns.provider",
"posthog.ingress.vercel.provider",
)
@@ -83,8 +82,8 @@ class WebhookProvider(ABC):
"""One provider app: how a delivery is verified, and how it is read.
The status codes are attributes rather than view arguments because they are part of the
- provider's own protocol: PandaDoc answers 404 on a bad signature by design, and Vapi
- answers 401. Everything else is a 202 transport receipt.
+ provider's own protocol: PandaDoc answers 404 on a bad signature by design. Everything else
+ is a 202 transport receipt.
"""
provider: str = ""
diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.py
index 16e7025090f5..e7ca91486d3e 100644
--- a/posthog/ingress/test/test_verify.py
+++ b/posthog/ingress/test/test_verify.py
@@ -188,12 +188,12 @@ class TestHmacSha256(SimpleTestCase):
def test_signature_pattern_rejects_before_the_digest_runs(self) -> None:
scheme = HmacSha256(
secret_getter=lambda: SECRET,
- signature_header="X-Vapi-Signature",
+ signature_header="X-Signature",
signature_pattern=re.compile(r"^[0-9a-f]{64}$"),
)
with patch("hmac.digest") as digest:
self.assertEqual(
- scheme.verify(body=BODY, headers={"X-Vapi-Signature": "NOT-A-HEX-DIGEST"}).outcome,
+ scheme.verify(body=BODY, headers={"X-Signature": "NOT-A-HEX-DIGEST"}).outcome,
VerificationOutcome.INVALID,
)
digest.assert_not_called()
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
index 019219068055..0590c464ec1d 100644
--- a/posthog/ingress/test/test_views.py
+++ b/posthog/ingress/test/test_views.py
@@ -1,3 +1,4 @@
+import re
import hmac
import json
import importlib
@@ -38,8 +39,7 @@ from posthog.ingress.pandadoc.provider import build_pandadoc_provider
from posthog.ingress.providers import _INCARNATION_MODULES, InvalidPayload, WebhookProvider
from posthog.ingress.slack.provider import build_slack_provider
from posthog.ingress.test import LOCMEM_CACHES
-from posthog.ingress.vapi.provider import VapiProvider
-from posthog.ingress.verify.schemes import Verification, VerificationOutcome
+from posthog.ingress.verify.schemes import HmacSha256, SignatureScheme, Verification, VerificationOutcome
from posthog.ingress.views import build_webhook_view
from posthog.regions import SECONDARY_REGION_DOMAIN
@@ -117,6 +117,18 @@ class _ThrottledGitHubProvider(GitHubProvider):
throttle_class = _StubThrottle
+class _PatternCheckedGitHubProvider(GitHubProvider):
+ # Stands in for a provider whose signature has one fixed shape, so a header of any other
+ # shape fails before the body is read.
+ def scheme(self) -> SignatureScheme:
+ return HmacSha256(
+ secret_getter=lambda: SECRET,
+ signature_header="X-Hub-Signature-256",
+ prefix="sha256=",
+ signature_pattern=re.compile(r"^sha256=[0-9a-f]{64}$"),
+ )
+
+
class _ScopedThrottleGitHubProvider(GitHubProvider):
throttle_class = ScopedRateThrottle
@@ -227,27 +239,21 @@ class TestWebhookView(SimpleTestCase):
@parameterized.expand(
[
("missing_header", {}, False),
- ("empty_header", {"X-Vapi-Signature": ""}, False),
- ("malformed_header", {"X-Vapi-Signature": "not-a-digest"}, False),
- ("well_formed_but_wrong_digest", {"X-Vapi-Signature": "0" * 64}, True),
+ ("empty_header", {"X-Hub-Signature-256": ""}, False),
+ ("malformed_header", {"X-Hub-Signature-256": "not-a-digest"}, False),
+ ("well_formed_but_wrong_digest", {"X-Hub-Signature-256": "sha256=" + "0" * 64}, True),
]
)
- @override_settings(VAPI_WEBHOOK_SECRET=SECRET)
def test_a_signature_header_that_cannot_pass_is_refused_before_the_body_is_read(
self, _name: str, headers: dict[str, str], reads_body: bool
) -> None:
- request = self.factory.post(
- "/webhooks/vapi/",
- data=json.dumps({"message": {"type": "status-update"}}).encode(),
- content_type="application/json",
- headers=headers,
- )
+ request = self._post(json.dumps({"action": "opened"}).encode(), {**headers, "X-GitHub-Event": "issues"})
with patch.object(HttpRequest, "body", new_callable=PropertyMock, return_value=b"{}") as body:
- response = build_webhook_view(VapiProvider())(request)
+ response = build_webhook_view(_PatternCheckedGitHubProvider("posthog"))(request)
# Same answer either way, so only the body read separates the two paths.
- self.assertEqual(response.status_code, 401)
+ self.assertEqual(response.status_code, 403)
self.assertEqual(response.content, b"Invalid signature")
self.assertEqual(body.called, reads_body)
self.dispatcher.dispatch.assert_not_called()
diff --git a/posthog/ingress/vapi/README.md b/posthog/ingress/vapi/README.md
deleted file mode 100644
index 4a0fa174a272..000000000000
--- a/posthog/ingress/vapi/README.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# Vapi
-
-Deliveries from the Vapi voice agent.
-
-## Headers
-
-- `X-Vapi-Signature` carries the signature.
-
-Vapi sends no delivery header and no timestamp header.
-
-## Signature scheme
-
-HMAC-SHA256 over the raw body, hex encoded, with no prefix.
-There is no replay window, because there is no timestamp to check.
-A signature that is not 64 lowercase hex characters is rejected before the HMAC runs, which keeps a casual probe off the digest path.
-
-## Delivery id and event type
-
-Vapi sends no delivery id, so dedup is skipped.
-The call id is the only stable id in the payload, and it repeats across the status update and the end-of-call report.
-It therefore cannot key dedup: a mark set by the first message would swallow the second.
-The call id goes into the delivery context as `call_id`, and the consumer stays idempotent on it.
-The event type is `message.type`.
-
-## Apps and secrets
-
-One app, `default`.
-The secret is the Django setting `VAPI_WEBHOOK_SECRET`.
-
-## Quirks
-
-A bad signature answers 401 and an unconfigured instance answers 503.
-The public interview surface already relies on both codes.
-
-A delivery a consumer did not accept answers 500 rather than the 202 receipt, because Vapi sends the delivery again after a 5xx.
-The report is the only copy of an interview, so losing it to a receipt costs the transcript.
-
-The provider sets `throttle_class` to `VapiWebhookIPThrottle`, a per-IP cap of 1200/minute from `posthog/rate_limit.py`.
-The endpoint is public and unauthenticated, so the cap bounds how much HMAC-verification CPU and structured-log volume one source can drive.
-Vapi's egress is shared across all tenants, so the bucket sits well above legitimate aggregate volume: a busy interview hour must not bleed onto a normal one.
-The refusal is the shared lane's 429 with a `Retry-After`.
-
-## Consumers
-
-One consumer, `user_interviews_vapi`, declared in `products/user_interviews/backend/webhook_consumers.py`.
-
-It enqueues a Celery task and returns, so the request does not wait on persistence.
-The enqueue is the only work on the request path, so a failure there is what the 500 above answers.
-The task persists the end-of-call report and retries a transient database error, so a lost connection does not lose the transcript.
-It acknowledges late, so a worker that dies mid-task gives the report back to the broker.
-The handler is idempotent on the call id, which is what makes both the retry and the redelivery safe.
diff --git a/posthog/ingress/vapi/__init__.py b/posthog/ingress/vapi/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/ingress/vapi/provider.py b/posthog/ingress/vapi/provider.py
deleted file mode 100644
index 4666bf17aa99..000000000000
--- a/posthog/ingress/vapi/provider.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""Vapi voice-agent webhooks.
-
-An unconfigured instance answers 503 and a bad signature 401, both of which the public
-interview surface already relies on.
-"""
-
-import re
-from collections.abc import Mapping, Sequence
-from typing import Any
-
-from django.conf import settings
-from django.http import HttpRequest
-from django.utils import timezone
-
-from posthog.ingress.contracts import ProviderSpec, WebhookDelivery
-from posthog.ingress.providers import WebhookProvider
-from posthog.ingress.verify.schemes import HmacSha256, SignatureScheme
-from posthog.rate_limit import VapiWebhookIPThrottle
-
-VAPI_EVENT_TYPES = frozenset({"status-update", "end-of-call-report"})
-
-# Vapi's HMAC-SHA256 hex digest is exactly 64 lowercase hex chars. Rejecting other shapes
-# before the HMAC keeps casual probes off the digest path and out of the diagnostic logs.
-VAPI_SIGNATURE_PATTERN = re.compile(r"^[0-9a-f]{64}$")
-
-SPECS = (ProviderSpec(provider="vapi", app="default", event_types=VAPI_EVENT_TYPES),)
-
-
-def _vapi_secret() -> str | None:
- return getattr(settings, "VAPI_WEBHOOK_SECRET", "") or None
-
-
-class VapiProvider(WebhookProvider):
- provider = "vapi"
- app = "default"
- invalid_signature_status = 401
- unconfigured_status = 503
- # Vapi sends the delivery again after a 5xx, and its report is the only copy: nothing else
- # replays an interview. The consumer hands the report to a queue and does no other work, so a
- # consumer failure means the report reached no queue at all, and a receipt would drop it.
- retry_status = 500
- # The endpoint is public and unauthenticated, so the per-IP cap bounds how much
- # HMAC-verification CPU and structured-log volume one source can drive.
- throttle_class = VapiWebhookIPThrottle
-
- def __init__(self) -> None:
- self._scheme = HmacSha256(
- secret_getter=_vapi_secret,
- signature_header="X-Vapi-Signature",
- signature_pattern=VAPI_SIGNATURE_PATTERN,
- )
-
- def scheme(self) -> SignatureScheme:
- return self._scheme
-
- def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
- if not isinstance(payload, Mapping):
- return ()
- message = payload.get("message")
- message = message if isinstance(message, Mapping) else {}
- call = message.get("call")
- call = call if isinstance(call, Mapping) else {}
- call_id = call.get("id")
- context = {"call_id": str(call_id)} if isinstance(call_id, str) and call_id else {}
- return (
- WebhookDelivery(
- provider=self.provider,
- app=self.app,
- # The call id is the only stable id Vapi sends, and it repeats across the
- # status update and the end-of-call report, so it cannot key dedup. The
- # consumer stays idempotent on it instead.
- delivery_id=None,
- event_type=str(message.get("type", "")),
- payload=payload,
- received_at=timezone.now(),
- context=context,
- ),
- )
-
-
-def build_vapi_provider() -> VapiProvider:
- return VapiProvider()
diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.py
index fad61fbac132..5b4a69252bdb 100644
--- a/posthog/ingress/verify/schemes.py
+++ b/posthog/ingress/verify/schemes.py
@@ -134,7 +134,7 @@ class HmacSignature:
timestamp_header: str | None = None
timestamp_max_age_seconds: int = 300
timestamp_max_future_seconds: int = 300
- # Cheap shape gate run before the HMAC, so a probe cannot drive digest CPU (Vapi).
+ # Cheap shape gate run before the HMAC, so a probe cannot drive digest CPU.
signature_pattern: re.Pattern[str] | None = None
def _timestamp_is_fresh(self, timestamp: str) -> bool:
diff --git a/posthog/models/sharing_configuration.py b/posthog/models/sharing_configuration.py
index c49ae4d8a02f..a0051c584f96 100644
--- a/posthog/models/sharing_configuration.py
+++ b/posthog/models/sharing_configuration.py
@@ -108,6 +108,13 @@ class SharingConfiguration(models.Model):
for a resource and ignores grace-period duplicates."""
return models.Q(enabled=True) & (models.Q(expires_at__isnull=True) | models.Q(expires_at__gt=timezone.now()))
+ @classmethod
+ def without_retired_resources_q(cls, prefix: str = "") -> models.Q:
+ """Excludes configs that share a resource of a retired product, so their tokens authenticate
+ nothing and resolve like an unknown token. Every access token lookup must apply it. Pass
+ ``prefix`` (for example ``"sharing_configuration__"``) when filtering a related model."""
+ return models.Q(**{f"{prefix}interviewee_context__isnull": True})
+
@classmethod
def queryset_active_for_resource(cls, **resource_lookup: Any) -> models.QuerySet["SharingConfiguration"]:
return cls.objects.filter(**resource_lookup, expires_at__isnull=True).order_by("-created_at")
@@ -156,8 +163,7 @@ class SharingConfiguration(models.Model):
def _lock_resource_for_rotation(self) -> None:
# Resolve each parent model from its own FK instead of importing it. This keeps the module
- # free of product imports (``user_interviews`` only exposes its webhooks via tach's
- # ``[[interfaces]]``).
+ # free of product imports.
for field_name in ("dashboard", "insight", "notebook", "recording", "interviewee_context"):
fk_value = getattr(self, f"{field_name}_id")
if not fk_value:
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 98505b88b358..a55f471baff1 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -389,20 +389,6 @@ class LeakedKeyReportThrottle(IPThrottle):
rate = "10/minute"
-class VapiWebhookIPThrottle(IPThrottle):
- """Per-IP cap on the public Vapi webhook endpoint, run by the ingress throttle lane.
-
- Vapi calls us a small handful of times per interview (status-update + end-of-call-report),
- but its egress is shared across all of our tenants, so the bucket has to be generous enough
- that a noisy concurrent interview hour doesn't bleed onto a normal one. 1200/min is well
- above legitimate aggregate volume while still stopping a persistent attacker from driving
- HMAC-verification CPU or structured-log volume from a single IP.
- """
-
- scope = "user_interviews_vapi_webhook_ip"
- rate = "1200/minute"
-
-
class SignupEmailPrecheckThrottle(IPThrottle):
"""
Rate limit signup email precheck requests by IP.
@@ -1773,28 +1759,6 @@ class AlertLLMSimulationDailyThrottle(_AlertLLMSimulationThrottle):
rate = "200/day"
-class UserInterviewInviteThrottle(PersonalApiKeyOrUserRateThrottle):
- # Cap how often a team can fire the user-interview send_invites action.
- #
- # The content (subject + intro) and the recipient list are both
- # user-controlled, so without a limit a member could use the action as a
- # PostHog-branded spam relay by rotating the topic's interviewee_emails and
- # re-sending. Idempotency only stops re-sending to the *same*
- # SharingConfiguration, not sending to fresh addresses.
- #
- # Keyed per team (not per personal API key, not per topic) so neither
- # rotating topics nor minting extra API keys bypasses the limit. Extends
- # PersonalApiKeyOrUserRateThrottle so every authenticated caller is covered
- # (PATs, OAuth bearer tokens, and session-cookie UI users alike).
- scope = "user_interview_invite"
- rate = "10/minute"
-
- def get_cache_key(self, request, view):
- team_id = self.safely_get_team_id_from_view(view)
- if team_id:
- return self.cache_format % {"scope": self.scope, "ident": f"team_{team_id}"}
-
-
class _OrganizationInviteRateThrottleBase(PersonalApiKeyOrUserRateThrottle):
# Cap how many organization invites a single organization can create in a
# given window. A malicious member can otherwise use the invite flow to
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 17a7569f2fb8..1f78428da272 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -470,8 +470,6 @@ class AssistantTool(StrEnum):
SEARCH_SESSION_RECORDINGS = "search_session_recordings"
CREATE_AI_TRACE_PARSER = "create_ai_trace_parser"
FIX_HOGQL_QUERY = "fix_hogql_query"
- ANALYZE_USER_INTERVIEWS = "analyze_user_interviews"
- CREATE_USER_INTERVIEW_TOPIC = "create_user_interview_topic"
CREATE_HOG_TRANSFORMATION_FUNCTION = "create_hog_transformation_function"
CREATE_HOG_FUNCTION_FILTERS = "create_hog_function_filters"
CREATE_HOG_FUNCTION_INPUTS = "create_hog_function_inputs"
@@ -1386,7 +1384,6 @@ class FileSystemIconType(StrEnum):
SESSION_PROFILE = "session_profile"
SURVEY = "survey"
PRODUCT_TOUR = "product_tour"
- USER_INTERVIEW = "user_interview"
EARLY_ACCESS_FEATURE = "early_access_feature"
EXPERIMENT = "experiment"
FEATURE_FLAG = "feature_flag"
@@ -2503,7 +2500,6 @@ class ProductKey(StrEnum):
TOOLBAR = "toolbar"
TRACING = "tracing"
METRICS = "metrics"
- USER_INTERVIEWS = "user_interviews"
VISUAL_REVIEW = "visual_review"
WEB_ANALYTICS = "web_analytics"
WORKFLOWS = "workflows"
diff --git a/posthog/scopes.py b/posthog/scopes.py
index ad1717c98d0a..daab6abdb1c1 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -138,7 +138,7 @@ APIScopeObject = Literal[
"uploaded_media",
"usage_metric",
"user",
- "user_interview", # Alpha product — access gated by feature flag at the MCP/API layer rather than by hiding the scope.
+ "user_interview", # Endpoints are gone; kept advertised until desktop OAuth clients stop requesting it.
"vision_action", # Endpoints are gone; kept advertised until desktop OAuth clients stop requesting it.
"vision_alert",
"visual_review",
diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.py
index 82730400150b..6253c3d42231 100644
--- a/posthog/settings/__init__.py
+++ b/posthog/settings/__init__.py
@@ -94,11 +94,6 @@ SLACK_WORKFLOW_TRIGGERS_ENABLED: bool = get_from_env("SLACK_WORKFLOW_TRIGGERS_EN
# firehose, and this is the only thing admitting it.
GITHUB_WORKFLOW_TRIGGERS_ENABLED: bool = get_from_env("GITHUB_WORKFLOW_TRIGGERS_ENABLED", False, type_cast=str_to_bool)
-# Vapi voice-AI integration (used by user_interviews to host public interview pages).
-VAPI_PUBLIC_KEY: str = os.getenv("VAPI_PUBLIC_KEY", "")
-VAPI_ASSISTANT_ID: str = os.getenv("VAPI_ASSISTANT_ID", "")
-VAPI_WEBHOOK_SECRET: str = os.getenv("VAPI_WEBHOOK_SECRET", "")
-
if DEBUG:
JS_URL: str = os.getenv("JS_URL", "http://localhost:8234").rstrip("/")
else:
diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
index 653b176ac6bf..433f7682fa6c 100644
--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
@@ -366,7 +366,6 @@ products/tasks/backend/tests/test_repository_readiness.py::TestClassifyRepositor
products/tasks/backend/tests/test_repository_readiness.py::TestSelectCandidatePaths
products/tasks/backend/tests/test_repository_readiness.py::TestShouldScanPath
products/tasks/backend/tests/test_webhooks.py::TestAccountType
-products/user_interviews/backend/test_facade.py::TestParseIntervieweeIdentifier
products/warehouse_sources/backend/tests/api/test_external_data_source.py::TestGetOAuthIntegrationKinds
products/warehouse_sources/backend/tests/api/test_external_data_source.py::TestSensitiveFieldClassification
products/web_analytics/backend/hogql_queries/test/test_custom_bot_definitions.py::TestPatternsCompile
diff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.py
index 2a695214f69e..563f1af1031d 100644
--- a/posthog/test/test_csp_middleware.py
+++ b/posthog/test/test_csp_middleware.py
@@ -460,7 +460,6 @@ class TestAppCspHeaderName(SimpleTestCase):
("shared_dashboard", "/shared_dashboard/abc123"),
("shared", "/shared/abc123"),
("embedded", "/embedded/abc123"),
- ("interview", "/interview/abc123"),
("exporter_with_token", "/exporter/abc123"),
("exporter_render", "/exporter"),
("render_query", "/render_query"),
diff --git a/posthog/urls.py b/posthog/urls.py
index 8ff80224d8f8..1c02a2b75d15 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -74,7 +74,6 @@ from products.streamlit_apps.backend.presentation.bridge_views import StreamlitB
from products.surveys.backend.api.survey import public_survey_page
from products.tasks.backend.facade.agent_proxy import agent_proxy_callback
from products.tasks.backend.presentation.views.gateway_generation_requests import gateway_generation_request
-from products.user_interviews.backend.presentation.webhooks import start_call as user_interviews_start_call
from products.warehouse_sources.backend.presentation.views.public_source_configs import PublicSourceConfigViewSet
from products.workflows.backend.presentation.views import hog_flow, hog_flow_template
@@ -149,11 +148,6 @@ urlpatterns = [
name="user_signal_autonomy",
),
path("api/projects/<int:team_id>/messaging/customerio/webhook/", csrf_exempt(CustomerIOWebhookView.as_view())),
- path(
- "api/user_interviews/share/<str:access_token>/start_call/",
- csrf_exempt(user_interviews_start_call),
- name="user_interviews_start_call",
- ),
path("api/sdk_health/", sdk_health),
# Conversations serves its widget and channel API from backend/api/, which its routes module
# may not import (import-linter contract "routes must only import presentation"), so the mount
@@ -307,10 +301,6 @@ urlpatterns = [
"embedded/<str:access_token>",
sharing.SharingViewerPageViewSet.as_view({"get": "retrieve"}),
),
- path(
- "interview/<str:access_token>",
- sharing.SharingViewerPageViewSet.as_view({"get": "retrieve"}),
- ),
path("render_query", render_query, name="render_query"),
path("exporter", sharing.SharingViewerPageViewSet.as_view({"get": "retrieve"})),
path(
diff --git a/products/legal_documents/frontend/generated/api.schemas.ts b/products/legal_documents/frontend/generated/api.schemas.ts
index e65dffadc39a..a8227b62523c 100644
--- a/products/legal_documents/frontend/generated/api.schemas.ts
+++ b/products/legal_documents/frontend/generated/api.schemas.ts
@@ -39,10 +39,9 @@ export interface PaginatedLegalDocumentDTOListApi {
* * `BAA` - BAA
* * `DPA` - DPA
*/
-export type CreateLegalDocumentDocumentTypeEnumApi =
- (typeof CreateLegalDocumentDocumentTypeEnumApi)[keyof typeof CreateLegalDocumentDocumentTypeEnumApi]
+export type DocumentTypeEnumApi = (typeof DocumentTypeEnumApi)[keyof typeof DocumentTypeEnumApi]
-export const CreateLegalDocumentDocumentTypeEnumApi = {
+export const DocumentTypeEnumApi = {
Baa: 'BAA',
Dpa: 'DPA',
} as const
@@ -57,7 +56,7 @@ export interface CreateLegalDocumentApi {
*
* * `BAA` - BAA
* * `DPA` - DPA */
- document_type: CreateLegalDocumentDocumentTypeEnumApi
+ document_type: DocumentTypeEnumApi
/**
* The customer legal entity entering the agreement (PandaDoc's Client.Company).
* @maxLength 255
diff --git a/products/ruff.toml b/products/ruff.toml
index 08836e8cf2cd..7c7049502378 100644
--- a/products/ruff.toml
+++ b/products/ruff.toml
@@ -121,7 +121,6 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]
"surveys/**" = ["PLC0415"]
"tasks/**" = ["PLC0415"]
"tracing/**" = ["PLC0415"]
-"user_interviews/**" = ["PLC0415"]
"visual_review/**" = ["PLC0415"]
"warehouse_sources/**" = ["PLC0415"]
"web_analytics/**" = ["PLC0415"]
diff --git a/products/user_interviews/backend/classification.py b/products/user_interviews/backend/classification.py
deleted file mode 100644
index 83ee19d25958..000000000000
--- a/products/user_interviews/backend/classification.py
+++ /dev/null
@@ -1,33 +0,0 @@
-import re
-
-from .models import UserInterviewClassification
-
-# Vapi voice-interview transcripts are newline-delimited `AI:` / `User:` turns. Keep the
-# speaker vocabulary in sync with frontend/parseTranscript.ts (TURN_SPLIT_RE) — both sides
-# parse the same Vapi format independently.
-_USER_TURN_RE = re.compile(
- r"(?:^|\n)\s*(?:User|Interviewee):\s+(.+?)(?=\n\s*(?:AI|Assistant|Interviewer|User|Interviewee):|$)",
- re.IGNORECASE | re.DOTALL,
-)
-_AI_TURN_RE = re.compile(r"(?:^|\n)\s*(?:AI|Assistant|Interviewer):\s+", re.IGNORECASE)
-
-
-def _user_turns(transcript: str) -> list[str]:
- return [t.strip() for t in _USER_TURN_RE.findall(transcript) if t.strip()]
-
-
-def derive_auto_classifications(transcript: str) -> list[str]:
- """Derive the mechanical classifications for a Vapi voice-interview transcript.
-
- Only `abandoned` is auto-derived — when the AI spoke but the interviewee never
- meaningfully did. `off-topic` needs human judgement and is never auto-set.
-
- Only the `AI:` / `User:` turn format (Vapi) is recognised. Transcripts in other formats
- (e.g. the audio-upload path's `#### Speaker N` headings) have no parseable turns, so we
- return no classifications rather than mislabel them `abandoned`.
- """
- if _user_turns(transcript):
- return []
- # No interviewee turns. Only call it `abandoned` when the AI clearly spoke (a real
- # voice interview the interviewee dropped); an unrecognised format gets left untagged.
- return [UserInterviewClassification.ABANDONED] if _AI_TURN_RE.search(transcript) else []
diff --git a/products/user_interviews/backend/facade/__init__.py b/products/user_interviews/backend/facade/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/user_interviews/backend/facade/api.py b/products/user_interviews/backend/facade/api.py
deleted file mode 100644
index e19b1b86dc7d..000000000000
--- a/products/user_interviews/backend/facade/api.py
+++ /dev/null
@@ -1,117 +0,0 @@
-"""
-Facade API for user_interviews.
-
-The primary facade module for data capabilities. Other facade submodules
-(max_tools.py) expose wiring; external code must import only from backend/facade/.
-
-Responsibilities:
-- Accept primitives / contracts as input
-- Call domain logic / ORM
-- Return contracts (no ORM instances)
-- Remain thin and stable
-
-Do NOT:
-- Import DRF, serializers, or HTTP concerns
-- Return ORM instances or QuerySets
-"""
-
-from uuid import UUID
-
-import structlog
-
-from posthog.ingress.contracts import WebhookDelivery
-
-from products.user_interviews.backend import logic
-from products.user_interviews.backend.classification import derive_auto_classifications
-from products.user_interviews.backend.facade.contracts import IntervieweeIdentity
-
-logger = structlog.get_logger(__name__)
-
-__all__ = [
- "SHARED_INTERVIEWEE_IDENTIFIER",
- "IntervieweeIdentity",
- "accept_vapi_event",
- "derive_auto_classifications",
- "has_replied",
- "is_shared_interviewee_context",
- "parse_interviewee_identifier",
- "valid_distinct_id",
- "valid_session_id",
-]
-
-SHARED_INTERVIEWEE_IDENTIFIER = logic.SHARED_INTERVIEWEE_IDENTIFIER
-
-
-def is_shared_interviewee_context(interviewee_identifier: str) -> bool:
- return logic.is_shared_interviewee_context(interviewee_identifier)
-
-
-def valid_distinct_id(value: object) -> str:
- return logic.valid_distinct_id(value)
-
-
-def valid_session_id(value: object) -> str:
- return logic.valid_session_id(value)
-
-
-def parse_interviewee_identifier(identifier: str) -> IntervieweeIdentity:
- return logic.parse_interviewee_identifier(identifier)
-
-
-def has_replied(*, team_id: int, topic_id: UUID, interviewee_identifier: str) -> bool:
- return logic.has_replied(
- team_id=team_id,
- topic_id=topic_id,
- interviewee_identifier=interviewee_identifier,
- )
-
-
-def accept_vapi_event(delivery: WebhookDelivery) -> None:
- """Resolve the share this delivery belongs to, and hand the work to a queue.
-
- The token is resolved here, in the request, because the answer expires: a share that the
- team disables, or a token that leaves its rotation grace period, while the work waits in
- the queue would make the worker find nothing and drop a report the endpoint has already
- accepted. So does the share row itself, which the cleanup command deletes once the token is
- past its grace period. What crosses the broker is the team, the topic and the interviewee
- context the share names, and nothing removes those with the share.
-
- A token nothing answers enqueues nothing. ingress ignores what a consumer returns, so there
- is no status to refuse the delivery with, and queueing work for a share nobody can name only
- moves the dead end into a worker. A database failure raises instead, which costs the request
- its receipt and makes Vapi send the report again.
- """
- # Deferred: keeps the Celery app off the facade import path.
- from products.user_interviews.backend.tasks.tasks import handle_vapi_webhook # noqa: PLC0415
-
- call_id = delivery.context.get("call_id")
- access_token = logic.vapi_access_token(delivery.payload)
- if not access_token:
- logger.warning(
- "user_interviews_vapi_webhook_missing_access_token",
- event_type=delivery.event_type,
- call_id=call_id,
- )
- return
-
- share = logic.vapi_share_identity(access_token)
- if share is None:
- logger.warning(
- "user_interviews_vapi_webhook_unknown_access_token",
- event_type=delivery.event_type,
- call_id=call_id,
- )
- return
-
- handle_vapi_webhook.delay(
- payload=dict(delivery.payload),
- event_type=delivery.event_type,
- team_id=share.team_id,
- topic_id=share.topic_id,
- interviewee_context_id=share.interviewee_context_id,
- interviewee_identifier=share.interviewee_identifier,
- # The lifecycle analytics events are timestamped with this, not with the moment the worker
- # runs, so a delayed or retried task cannot report a call as started after it ended. Sent
- # as a string because the broker carries JSON, which has no datetime.
- received_at=delivery.received_at.isoformat(),
- )
diff --git a/products/user_interviews/backend/facade/contracts.py b/products/user_interviews/backend/facade/contracts.py
deleted file mode 100644
index 8eee778b6217..000000000000
--- a/products/user_interviews/backend/facade/contracts.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from pydantic.dataclasses import dataclass
-
-
-@dataclass(frozen=True)
-class IntervieweeIdentity:
- """Parsed interviewee identifier — display name plus optional email.
-
- `email` is None when the identifier was a PostHog distinct_id rather than an
- email address.
- """
-
- display_name: str
- email: str | None
diff --git a/products/user_interviews/backend/facade/enums.py b/products/user_interviews/backend/facade/enums.py
deleted file mode 100644
index 8db692ede489..000000000000
--- a/products/user_interviews/backend/facade/enums.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from posthog.enums import LabeledStrEnum
-
-
-# Each label repeats its value, because the API documents these choices as plain values.
-class UserInterviewSearchDocumentType(LabeledStrEnum):
- TRANSCRIPT = "transcript", "transcript"
- SUMMARY = "summary", "summary"
diff --git a/products/user_interviews/backend/facade/max_tools.py b/products/user_interviews/backend/facade/max_tools.py
deleted file mode 100644
index 9544f8334772..000000000000
--- a/products/user_interviews/backend/facade/max_tools.py
+++ /dev/null
@@ -1,15 +0,0 @@
-"""
-Facade re-export of the product's MaxTool classes for the AI agent toolkits.
-
-Kept out of api.py so light consumers (e.g. sharing) don't pull the LLM tool
-stack, and because api.py sits on max_tools' own import chain
-(max_tools -> invite_email -> logic -> facade.contracts), so re-exporting
-from there would create a circular import.
-"""
-
-from products.user_interviews.backend.max_tools import AnalyzeUserInterviewsTool, CreateUserInterviewTopicTool
-
-__all__ = [
- "AnalyzeUserInterviewsTool",
- "CreateUserInterviewTopicTool",
-]
diff --git a/products/user_interviews/backend/invite_email.py b/products/user_interviews/backend/invite_email.py
deleted file mode 100644
index 87bcf64218c0..000000000000
--- a/products/user_interviews/backend/invite_email.py
+++ /dev/null
@@ -1,141 +0,0 @@
-from typing import Any
-
-from django.conf import settings
-from django.template.loader import get_template
-
-from rest_framework import serializers
-
-from posthog.email import inline_css
-from posthog.helpers.email_utils import (
- contains_bare_domain,
- sanitize_display_name,
- sanitize_message_body,
- validate_display_name,
- validate_message_body,
-)
-from posthog.utils import absolute_uri
-
-from .logic import parse_interviewee_identifier
-from .models import UserInterviewTopic
-
-INVITE_EMAIL_TEMPLATE = "email/interview_invite.html"
-PREVIEW_PLACEHOLDER_PATH = "/interview/preview"
-
-# Interview invite copy is stricter than org-invite copy: we reject bare domains (on top of the
-# URL-scheme / bracket / control-char checks the shared validators already enforce) because there's
-# no legitimate reason to link out from a research invite, and mail clients auto-link bare domains —
-# a phishing vector in a PostHog-branded email.
-_INVITE_DOMAIN_ERROR = "Links and domain names aren't allowed in interview invite copy."
-
-
-def validate_invite_subject(value: str | None) -> str | None:
- validated = validate_display_name(value)
- if contains_bare_domain(validated):
- raise serializers.ValidationError(_INVITE_DOMAIN_ERROR, code="invalid_domain")
- return validated
-
-
-def validate_invite_message(value: str | None) -> str | None:
- validated = validate_message_body(value)
- if contains_bare_domain(validated):
- raise serializers.ValidationError(_INVITE_DOMAIN_ERROR, code="invalid_domain")
- return validated
-
-
-def build_invite_email_context(
- *,
- topic: UserInterviewTopic,
- user_name: str,
- interview_url: str,
- subject_override: str = "",
-) -> dict[str, Any]:
- """Resolve the subject + template context for a topic's invite email, personalized for one
- recipient. Shared by the send path and the (side-effect-free) preview path so both render
- identically. Re-sanitizes the stored subject/message at render time (defense-in-depth): a stale
- or pre-validation value degrades to the default rather than emitting anything unsafe.
- """
- topic_label = topic.topic or "a quick research interview"
- default_subject = f"Got 5 minutes to talk about {topic_label}?"
- log_context = {"feature": "user_interview_invite", "topic_id": str(topic.id)}
- subject = sanitize_display_name(
- subject_override or topic.invite_subject,
- fallback=default_subject,
- context={**log_context, "field": "subject"},
- )
- invite_message = sanitize_message_body(
- topic.invite_message,
- fallback="",
- context={**log_context, "field": "invite_message"},
- )
- return {
- "subject": subject,
- "template_context": {
- "user_name": user_name,
- "topic": topic_label,
- "interview_url": interview_url,
- "invite_message": invite_message,
- "site_url": settings.SITE_URL,
- },
- }
-
-
-def render_invite_email_html(
- *,
- topic: UserInterviewTopic,
- user_name: str,
- interview_url: str,
- subject_override: str = "",
-) -> dict[str, str]:
- """Render the invite email to CSS-inlined HTML without sending. Renders a fixed template file
- with autoescaped context — user content never reaches the template engine as a template.
- """
- built = build_invite_email_context(
- topic=topic,
- user_name=user_name,
- interview_url=interview_url,
- subject_override=subject_override,
- )
- html = inline_css(get_template(INVITE_EMAIL_TEMPLATE).render(built["template_context"]))
- return {"subject": built["subject"], "html": html}
-
-
-def _targeted_identifiers(topic: UserInterviewTopic) -> list[str]:
- return [
- raw.strip()
- for raw in [*(topic.interviewee_emails or []), *(topic.interviewee_distinct_ids or [])]
- if raw and raw.strip()
- ]
-
-
-def resolve_invite_preview(
- *,
- topic: UserInterviewTopic,
- interviewee_identifier: str = "",
-) -> dict[str, Any] | None:
- """Render an invite-email preview for one targeted interviewee. Defaults to the first targeted
- interviewee when none is given. Returns None when the topic targets nobody, or when a specific
- interviewee_identifier is given that the topic does not target.
-
- Read-only and never exposes a live interview link: the previewed body always shows an illustrative
- placeholder URL. The real per-recipient share token is minted only when invites are actually sent,
- so a read-scoped caller can't harvest working interview links through the preview.
- """
- targets = _targeted_identifiers(topic)
- requested = (interviewee_identifier or "").strip()
- identifier = requested or (targets[0] if targets else "")
- if not identifier or (requested and requested not in targets):
- return None
-
- identity = parse_interviewee_identifier(identifier)
- interview_url = absolute_uri(PREVIEW_PLACEHOLDER_PATH)
- rendered = render_invite_email_html(topic=topic, user_name=identity.display_name, interview_url=interview_url)
- return {
- "interviewee_identifier": identifier,
- "user_name": identity.display_name,
- "email": identity.email,
- "subject": rendered["subject"],
- "html": rendered["html"],
- "interview_url": interview_url,
- "emailable": identity.email is not None,
- "is_preview_link": True,
- }
diff --git a/products/user_interviews/backend/logic.py b/products/user_interviews/backend/logic.py
deleted file mode 100644
index 663827112d5b..000000000000
--- a/products/user_interviews/backend/logic.py
+++ /dev/null
@@ -1,287 +0,0 @@
-"""Business logic for user_interviews.
-
-Holds the parsing rules and ORM queries that back the facade. The facade
-(`facade/api.py`) stays thin and delegates here; tests and other internal
-modules within this product may call these helpers directly, but external
-products must keep going through the facade.
-"""
-
-import re
-import uuid
-from collections.abc import Mapping
-from typing import Any
-from uuid import UUID, uuid4
-
-import structlog
-
-from posthog.dataclasses import frozen
-from posthog.ingress.dispatch.database import bounded_statement_timeout
-from posthog.models.sharing_configuration import SharingConfiguration
-from posthog.models.team import Team
-from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
-
-from products.ai_observability.backend.prompt_references import resolve_prompt_references
-from products.user_interviews.backend.facade.contracts import IntervieweeIdentity
-from products.user_interviews.backend.models import (
- EmailWithDisplayNameValidator,
- UserInterview,
- UserInterviewClassification,
-)
-
-logger = structlog.get_logger(__name__)
-
-# distinct_id rules ported from rust/capture (`CAPTURE_V1_DISTINCT_ID_MAX_SIZE` and
-# `ILLEGAL_DISTINCT_IDS` in v1/analytics/constants.rs). On the shared interview link these are
-# best-effort person/session linkage hints from an untrusted public page, so an invalid value is
-# dropped (ignored), never a reason to reject the interview.
-DISTINCT_ID_MAX_CHARS = 200
-ILLEGAL_DISTINCT_IDS = frozenset(
- {
- "0",
- "00000000-0000-0000-0000-000000000000",
- "[object object]",
- "anonymous",
- "anonymous-user",
- "backend",
- "distinct_id",
- "distinctid",
- "email",
- "false",
- "guest",
- "id",
- "nan",
- "none",
- "not_authenticated",
- "null",
- "system",
- "true",
- "undefined",
- "user",
- }
-)
-
-
-def valid_distinct_id(value: object) -> str:
- """Return a usable distinct_id, or "" if it fails the canonical capture rules (empty, longer
- than the 200-char limit, or a known-bad sentinel). Dropped, not rejected — it's a linkage hint.
- A too-long id is dropped rather than truncated: a truncated distinct_id would never match a real
- person, so keeping it would be misleading."""
- if not value:
- return ""
- candidate = str(value).strip()
- if not candidate or len(candidate) > DISTINCT_ID_MAX_CHARS or candidate.lower() in ILLEGAL_DISTINCT_IDS:
- return ""
- return candidate
-
-
-def valid_session_id(value: object) -> str:
- """Return the session_id only if it's a valid UUIDv7 (PostHog session IDs are UUIDv7), else "".
- Dropped, not rejected — it's a best-effort linkage hint."""
- if not value:
- return ""
- candidate = str(value).strip()
- try:
- return candidate if uuid.UUID(candidate).version == 7 else ""
- except ValueError:
- return ""
-
-
-# A shared (non-personalised) interview link is modelled as an IntervieweeContext carrying this
-# reserved identifier — the same machinery as a per-invitee link (and the test/dogfood link), but
-# the token belongs to the whole topic and every visitor is a new anonymous respondent. Using a
-# sentinel row (rather than a new field, or a new FK on the main-app SharingConfiguration) keeps this
-# experiment's blast radius entirely inside the user_interviews product.
-SHARED_INTERVIEWEE_IDENTIFIER = "__posthog_shared_link__"
-
-
-def is_shared_interviewee_context(interviewee_identifier: str) -> bool:
- """Whether an IntervieweeContext identifier marks the topic's shared (anonymous) link."""
- return interviewee_identifier == SHARED_INTERVIEWEE_IDENTIFIER
-
-
-# Max lengths for the self-reported fields a shared-link respondent sends to start_call. These
-# are echoed into Vapi metadata and persisted on the UserInterview, so cap them defensively.
-RESPONDENT_NAME_MAX_CHARS = 200
-RESPONDENT_KEY_MAX_CHARS = 64
-
-# Every shared-link response is stored under an identifier carrying this prefix. It can NEVER equal a
-# personalised interviewee's identifier (an email or distinct_id), so an anonymous respondent can
-# neither be attributed to nor lock out a targeted invitee.
-SHARED_RESPONDENT_IDENTIFIER_PREFIX = "shared:"
-
-
-def clean_field(value: Any, max_chars: int) -> str:
- return str(value).strip()[:max_chars] if value else ""
-
-
-def shared_interviewee_identifier(respondent_key: str) -> str:
- """Namespaced, non-authoritative identity for a shared-link respondent.
-
- Keyed on the stable per-browser ``respondent_key`` so a refreshed respondent keeps one identity;
- falls back to a random id when no key was supplied so rows stay distinct. Deliberately independent
- of any self-reported name or untrusted ``distinct_id`` — those never determine attribution."""
- return f"{SHARED_RESPONDENT_IDENTIFIER_PREFIX}{respondent_key or uuid4().hex}"
-
-
-def resolve_share(access_token: str) -> SharingConfiguration | None:
- """Resolve a share token to its `SharingConfiguration`, with the rows the public interview
- page reads off it already joined.
-
- Uses the same enabled/expiry predicate as `SharingViewerPageViewSet.get_object()`, so a
- rotated token past its grace period is dead here exactly when it is dead on the public viewer.
- """
- try:
- return (
- SharingConfiguration.objects.select_related(
- "team",
- "team__organization",
- "interviewee_context",
- "interviewee_context__topic",
- )
- .filter(SharingConfiguration.tokens_active_q())
- .get(access_token=access_token)
- )
- except SharingConfiguration.DoesNotExist:
- return None
-
-
-def vapi_access_token(payload: Mapping[str, Any]) -> str:
- """The share token Vapi echoes back from the metadata `start_call` set on the call.
-
- Vapi surfaces that metadata in two places on the Call object: `call.metadata` for some
- message types, and nested under `call.assistantOverrides.metadata` on others. Empirically
- the end-of-call report comes through with the nested form, so both are read.
- """
- message: dict[str, Any] = payload.get("message") or {}
- call: dict[str, Any] = message.get("call") or {}
- overrides_metadata: dict[str, Any] = (call.get("assistantOverrides") or {}).get("metadata") or {}
- top_metadata: dict[str, Any] = call.get("metadata") or {}
- token = (
- top_metadata.get("sharing_access_token")
- or top_metadata.get("access_token")
- or overrides_metadata.get("sharing_access_token")
- or overrides_metadata.get("access_token")
- )
- return str(token) if token else ""
-
-
-# The token lookup runs inside the ingress request budget, so it is capped rather than left to
-# stall the delivery on a slow shared connection pool. See posthog/ingress/README.md, "The
-# delivery budget".
-SHARE_LOOKUP_TIMEOUT_MS = 1_000
-
-
-@frozen
-class VapiShareIdentity:
- """What a queued Vapi report needs from the share the delivery arrived on.
-
- The share row is not durable. `cleanup_expired_sharing_configs` deletes every configuration
- that is past its `expires_at`, so a token rotated during a call can lose its row while the
- report still waits in the queue or between retries. Nothing deletes the team, the topic or
- the interviewee context with it, so these ids still say where the report belongs.
-
- The ids are strings because the broker carries JSON, which has no UUID.
- """
-
- team_id: int
- topic_id: str
- interviewee_context_id: str
- interviewee_identifier: str
-
-
-def vapi_share_identity(access_token: str) -> VapiShareIdentity | None:
- """The identity behind a Vapi delivery's token, or None when no interview share answers it.
-
- Asks the same enabled/expiry question as `resolve_share`, and reads only the ids and the
- identifier a worker needs, because the caller hands the answer to a queue rather than to a
- page.
- """
- with bounded_statement_timeout(SHARE_LOOKUP_TIMEOUT_MS, models=[SharingConfiguration]):
- identity = (
- SharingConfiguration.objects.filter(SharingConfiguration.tokens_active_q())
- .filter(access_token=access_token, interviewee_context__isnull=False)
- .values_list(
- "team_id",
- "interviewee_context__topic_id",
- "interviewee_context_id",
- "interviewee_context__interviewee_identifier",
- )
- .first()
- )
- if identity is None:
- return None
- team_id, topic_id, interviewee_context_id, interviewee_identifier = identity
- return VapiShareIdentity(
- team_id=team_id,
- topic_id=str(topic_id),
- interviewee_context_id=str(interviewee_context_id),
- interviewee_identifier=interviewee_identifier,
- )
-
-
-def parse_interviewee_identifier(identifier: str) -> IntervieweeIdentity:
- """Split an interviewee identifier into a display name and (optional) email.
-
- Accepts the same display-name format the topic validator accepts —
- ``"Display Name <email@host>"`` — falling back to a best-effort
- title-cased local-part for raw emails and the identifier as-is for
- distinct IDs.
- """
- identifier = identifier.strip()
- display_match = re.match(EmailWithDisplayNameValidator.display_name_regex, identifier)
- if display_match:
- return IntervieweeIdentity(
- display_name=display_match.group(1).strip(),
- email=display_match.group(2).strip(),
- )
- if "@" in identifier:
- local_part = identifier.split("@", 1)[0]
- return IntervieweeIdentity(
- display_name=local_part.replace(".", " ").replace("_", " ").strip().title() or identifier,
- email=identifier,
- )
- return IntervieweeIdentity(display_name=identifier, email=None)
-
-
-def has_replied(*, team_id: int, topic_id: UUID, interviewee_identifier: str) -> bool:
- """Whether a personalised (invited) interviewee has already completed an interview for this topic.
-
- Abandoned interviews don't count: an accidental refresh mid-call leaves an abandoned
- partial behind, and treating that as "replied" would lock the interviewee out of ever
- finishing. Only a non-abandoned response gates the personalised link.
-
- Shared-link responses never count: they carry a `respondent_key` and a namespaced
- `interviewee_identifier`, so this filter is defense-in-depth against a shared respondent
- (whose distinct_id is untrusted) ever being able to mark a targeted invitee as replied.
- """
- return (
- UserInterview.objects.filter(
- team_id=team_id,
- topic_id=topic_id,
- interviewee_identifier=interviewee_identifier,
- respondent_key="",
- )
- .exclude(classifications__contains=[UserInterviewClassification.ABANDONED])
- .exists()
- )
-
-
-def resolve_first_message_template(team: Team, prompt_name: str, default: str) -> str:
- """Return the team's managed first-message prompt, or `default`.
-
- Splices in any referenced partials so a raw reference tag never reaches the
- voice agent. Falls back to `default` on a lookup failure, an absent or empty
- managed prompt, or an unresolvable reference.
- """
- try:
- cached = get_prompt_by_name_from_cache(team, prompt_name)
- except Exception as err:
- logger.warning("user_interviews_first_message_prompt_lookup_failed", team_id=team.id, error=str(err))
- return default
- if cached is not None:
- template = cached.get("prompt")
- if isinstance(template, str) and template.strip():
- resolved = resolve_prompt_references(team, template)
- if resolved is not None:
- return resolved
- return default
diff --git a/products/user_interviews/backend/max_tools.py b/products/user_interviews/backend/max_tools.py
deleted file mode 100644
index c73f4de60e02..000000000000
--- a/products/user_interviews/backend/max_tools.py
+++ /dev/null
@@ -1,330 +0,0 @@
-from textwrap import dedent
-from typing import Any
-
-from django.conf import settings
-from django.core.exceptions import ValidationError as DjangoValidationError
-
-import posthoganalytics
-from posthoganalytics.ai.openai import OpenAI
-from pydantic import BaseModel, ConfigDict, Field
-from rest_framework.serializers import ValidationError as DRFValidationError
-
-from posthog.exceptions_capture import capture_exception
-from posthog.scopes import APIScopeObject
-
-from products.access_control.backend.facade.user_access_control import AccessControlLevel
-
-from ee.hogai.tool import MaxTool
-
-from .invite_email import validate_invite_message, validate_invite_subject
-from .models import EmailWithDisplayNameValidator, UserInterview, UserInterviewTopic
-
-
-def _topic_url(topic_id: str) -> str:
- return f"/user_research/{topic_id}"
-
-
-class AnalyzeUserInterviewsArgs(BaseModel):
- analysis_angle: str = Field(
- description="How to analyze the interviews based on user's question (e.g. 'Find common pain points', 'Identify feature requests', etc.)"
- )
-
-
-class AnalyzeUserInterviewsTool(MaxTool):
- name: str = "analyze_user_interviews"
- description: str = "Analyze all user interviews from a specific angle to find patterns and insights"
- context_prompt_template: str = "Since the user is currently on the user interviews page, you should lean towards the `analyze_user_interviews` when it comes to any questions about users or customers."
- args_schema: type[BaseModel] = AnalyzeUserInterviewsArgs
-
- def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
- return [("user_interview", "viewer")]
-
- def _run_impl(self, analysis_angle: str) -> tuple[str, Any]:
- # Get all interviews for the current team
- interviews = UserInterview.objects.filter(team=self._team).order_by("-created_at")
-
- if not interviews:
- return "No user interviews found to analyze.", None
-
- # Prepare interview summaries for analysis
- interview_summaries = []
- for interview in interviews:
- if interview.summary:
- interview_summaries.append(f"Interview from {interview.created_at}:\n{interview.summary}\n")
-
- if not interview_summaries:
- return "No interview summaries found to analyze.", None
-
- interview_summaries_text = "\n\n".join(interview_summaries)
-
- # Use GPT to analyze the summaries
- analysis_response = OpenAI(
- posthog_client=posthoganalytics.default_client, base_url=settings.OPENAI_BASE_URL
- ).responses.create(
- model="gpt-4.1-mini",
- posthog_privacy_mode=True,
- posthog_distinct_id=self._user.distinct_id,
- posthog_properties={
- "ai_product": "user_interviews",
- "ai_feature": "analyze-interviews",
- "team_id": self._team.id,
- },
- input=[
- {
- "role": "system",
- "content": """
-You are an expert product manager analyzing user interviews. Your task is to analyze multiple interview summaries and provide insights based on the requested analysis angle.
-Focus on finding patterns, common themes, and actionable insights.
-""".strip(),
- },
- {
- "role": "user",
- "content": f"""
-Please analyze these user interview summaries from the following angle:
-{analysis_angle}
-
-<interview_summaries>
-{interview_summaries_text}
-</interview_summaries>
-
-Provide a structured analysis with clear sections and bullet points where appropriate. Keep it very concise though. Avoid fluff, just give the facts to answer the question.
-""".strip(),
- },
- ],
- )
-
- return analysis_response.output_text, None
-
-
-CREATE_USER_INTERVIEW_TOPIC_DESCRIPTION = dedent("""
- Create a user research interview topic — a planned voice-AI interview campaign.
-
- # When to use
- - The user wants to set up or run user interviews, user research, customer research,
- or "talk to users" about a feature, product area, or hypothesis.
- - The user asks to plan, schedule, draft, or kick off user interviews.
-
- # What this creates
- A `UserInterviewTopic` containing who to talk to (`interviewee_emails` and/or
- `interviewee_distinct_ids`), the research topic, optional context for the AI voice
- agent, and the ordered list of questions it should work through. After creation, the
- user can generate per-interviewee public links from the topic page and email invites
- to participants. The voice agent handles the live call.
-
- # Required information
- - `topic`: short statement of what to learn (e.g. "the new dashboard onboarding flow").
- - At least one of `interviewee_emails` OR `interviewee_distinct_ids` must be non-empty.
- Emails are preferred when known — invites can be sent automatically. PostHog distinct
- IDs work too but cannot receive email invites until an email is added.
- - `questions`: 3-6 focused, open-ended questions in the order the agent should ask
- them. Keep them conversational and avoid leading or yes/no phrasings.
-
- # Optional
- - `agent_context`: extra background for the voice agent — tone, what the product
- does, what NOT to ask about, who the interviewer "is" representing. Becomes part
- of the agent's system prompt for every call on this topic.
-
- # Important
- - This is NOT a survey. Do NOT use `create_survey` when the user asks for an
- interview, research call, or "talk to users" — those are live AI voice
- conversations, not in-app survey widgets.
- - This is NOT a session recording filter. Do NOT redirect to session recordings
- or replays when the user wants to interview people.
- - Do not invent emails or distinct IDs. If the user has not provided participants
- and you cannot derive them from the available cohort/persons tools, ask the user.
- """).strip()
-
-
-class CreateUserInterviewTopicArgs(BaseModel):
- model_config = ConfigDict(extra="ignore")
-
- topic: str = Field(
- description=(
- "Short statement of what you want to learn from the interviews — the product "
- "area, feature, or hypothesis being researched."
- ),
- )
- interviewee_emails: list[str] = Field(
- default_factory=list,
- description=(
- "Email addresses of people to interview. Accepts plain `email@host` or the "
- "`Display Name <email@host>` form. May be combined with `interviewee_distinct_ids` "
- "but at least one of the two lists must be non-empty."
- ),
- )
- interviewee_distinct_ids: list[str] = Field(
- default_factory=list,
- description=(
- "PostHog distinct IDs of people to interview. May be combined with "
- "`interviewee_emails`, but at least one of the two lists must be non-empty. "
- "Distinct-ID-only interviewees cannot receive email invites until they are "
- "given an email address."
- ),
- )
- questions: list[str] = Field(
- default_factory=list,
- description=(
- "Ordered list of questions the AI voice agent should work through during the "
- "interview. Keep questions open-ended, conversational, and focused on the topic."
- ),
- )
- agent_context: str = Field(
- default="",
- description=(
- "Optional extra context for the voice agent — background on the product, "
- "tone, or constraints. Becomes part of the agent's system prompt for every "
- "call on this topic. Leave empty if no extra context is needed."
- ),
- )
- invite_subject: str = Field(
- default="",
- description=(
- "Optional subject line for the invitation email. Plain text only — must not contain URLs, "
- "angle brackets, or line breaks. The email template handles personalization, so do not add "
- "placeholders. Leave empty to use the default subject."
- ),
- )
- invite_message: str = Field(
- default="",
- description=(
- "Optional intro message shown in the invitation email body, above the interview link. Plain "
- "prose only (line breaks allowed) — must not contain URLs or angle brackets. Leave empty to "
- "use the default copy."
- ),
- )
-
-
-class CreateUserInterviewTopicTool(MaxTool):
- name: str = "create_user_interview_topic"
- description: str = CREATE_USER_INTERVIEW_TOPIC_DESCRIPTION
- context_prompt_template: str = (
- "When the user explicitly wants to interview users, talk to users live, or run "
- "user research calls, prefer `create_user_interview_topic`. For passive, in-app "
- "feedback (e.g. NPS, opinion polls, ratings), `create_survey` is still the right "
- "choice."
- )
- args_schema: type[BaseModel] = CreateUserInterviewTopicArgs
-
- def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
- return [("user_interview", "editor")]
-
- async def _arun_impl(
- self,
- topic: str = "",
- interviewee_emails: list[str] | None = None,
- interviewee_distinct_ids: list[str] | None = None,
- questions: list[str] | None = None,
- agent_context: str = "",
- invite_subject: str = "",
- invite_message: str = "",
- ) -> tuple[str, dict[str, Any]]:
- emails = [e.strip() for e in (interviewee_emails or []) if e and e.strip()]
- distinct_ids = [d.strip() for d in (interviewee_distinct_ids or []) if d and d.strip()]
- questions = [q.strip() for q in (questions or []) if q and q.strip()]
- topic = (topic or "").strip()
-
- if not topic:
- return "Topic is required.", {
- "error": "validation_failed",
- "error_message": "Topic must be a non-empty string describing what you want to learn.",
- }
-
- if not emails and not distinct_ids:
- return (
- "At least one interviewee email or PostHog distinct ID must be provided.",
- {
- "error": "validation_failed",
- "error_message": (
- "Provide at least one entry in `interviewee_emails` or "
- "`interviewee_distinct_ids` so we know who to interview."
- ),
- },
- )
-
- if not questions:
- return (
- "At least one interview question is required.",
- {
- "error": "validation_failed",
- "error_message": (
- "Provide at least one question in `questions`. "
- "The AI voice agent needs questions to ask during the interview."
- ),
- },
- )
-
- validator = EmailWithDisplayNameValidator()
- invalid_emails: list[str] = []
- for email in emails:
- try:
- validator(email)
- except DjangoValidationError:
- invalid_emails.append(email)
- if invalid_emails:
- return (
- f"Invalid email address(es): {', '.join(invalid_emails)}",
- {
- "error": "validation_failed",
- "error_message": (
- "These values are not valid email addresses: "
- + ", ".join(invalid_emails)
- + ". Use plain `email@host` or `Display Name <email@host>`."
- ),
- },
- )
-
- try:
- invite_subject = validate_invite_subject(invite_subject or "") or ""
- invite_message = validate_invite_message(invite_message or "") or ""
- except DRFValidationError as e:
- return (
- "The invite subject or message contains disallowed content.",
- {
- "error": "validation_failed",
- "error_message": (
- "The invite subject or message was rejected (URLs, angle brackets, and control "
- f"characters are not allowed): {e.detail}"
- ),
- },
- )
-
- try:
- created_topic = await UserInterviewTopic.objects.acreate(
- team=self._team,
- created_by=self._user,
- topic=topic,
- interviewee_emails=emails,
- interviewee_distinct_ids=distinct_ids,
- questions=questions,
- agent_context=agent_context or "",
- invite_subject=invite_subject,
- invite_message=invite_message,
- )
- except Exception as e:
- capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})
- return f"Failed to create interview topic: {str(e)}", {
- "error": "creation_failed",
- "error_message": str(e),
- }
-
- topic_id = str(created_topic.id)
- topic_url = _topic_url(topic_id)
- targeting_summary_parts = []
- if emails:
- targeting_summary_parts.append(f"{len(emails)} email{'s' if len(emails) != 1 else ''}")
- if distinct_ids:
- targeting_summary_parts.append(f"{len(distinct_ids)} distinct ID{'s' if len(distinct_ids) != 1 else ''}")
- targeting_summary = " + ".join(targeting_summary_parts) or "no interviewees"
-
- message = (
- f"Created interview topic '{topic}' targeting {targeting_summary} with "
- f"{len(questions)} question{'s' if len(questions) != 1 else ''}. "
- f"[Open topic]({topic_url}) to generate links or send invites."
- )
- return message, {
- "topic_id": topic_id,
- "topic": created_topic.topic,
- "interviewee_email_count": len(emails),
- "interviewee_distinct_id_count": len(distinct_ids),
- "question_count": len(questions),
- }
diff --git a/products/user_interviews/backend/models.py b/products/user_interviews/backend/models.py
index 730f46d395c3..ab34d7955655 100644
--- a/products/user_interviews/backend/models.py
+++ b/products/user_interviews/backend/models.py
@@ -29,6 +29,9 @@ class UserInterviewClassification(models.TextChoices):
class UserInterview(UUIDTModel, CreatedMetaFields):
+ """The user interviews product is retired. The model stays so that Django keeps cascading
+ team and user deletes into its table. A later migration removes the model and drops the table."""
+
team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="+")
interviewee_emails = ArrayField(
models.CharField(max_length=254, validators=[EmailWithDisplayNameValidator()]), default=list
@@ -75,6 +78,9 @@ class UserInterview(UUIDTModel, CreatedMetaFields):
class UserInterviewTopic(UUIDTModel, CreatedMetaFields):
+ """The user interviews product is retired. The model stays so that Django keeps cascading
+ team and user deletes into its table. A later migration removes the model and drops the table."""
+
team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="+")
interviewee_emails = ArrayField(
models.CharField(max_length=254, validators=[EmailWithDisplayNameValidator()]),
@@ -101,6 +107,9 @@ class UserInterviewTopic(UUIDTModel, CreatedMetaFields):
class IntervieweeContext(UUIDTModel, CreatedMetaFields):
+ """The user interviews product is retired. The model stays so that Django keeps cascading
+ team and user deletes into its table. A later migration removes the model and drops the table."""
+
team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="+")
topic = models.ForeignKey(
UserInterviewTopic,
diff --git a/products/user_interviews/backend/presentation/__init__.py b/products/user_interviews/backend/presentation/__init__.py
deleted file mode 100644
index 483733a933b4..000000000000
--- a/products/user_interviews/backend/presentation/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""User interviews presentation layer modules."""
diff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.py
deleted file mode 100644
index 2e614d2ab286..000000000000
--- a/products/user_interviews/backend/presentation/views.py
+++ /dev/null
@@ -1,1627 +0,0 @@
-import re
-import json
-from functools import cache, cached_property
-from typing import TYPE_CHECKING, Any, cast
-from uuid import uuid4
-
-from django.conf import settings
-from django.core.exceptions import ValidationError as DjangoValidationError
-from django.core.files import File
-from django.db import models, transaction
-from django.db.models import QuerySet
-from django.utils import timezone
-from django.utils.text import slugify
-
-import structlog
-import django_filters
-import posthoganalytics
-import posthoganalytics.ai.openai
-from django_filters.rest_framework import DjangoFilterBackend
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiResponse, extend_schema
-from posthoganalytics.ai.openai import OpenAI
-from rest_framework import filters, response, serializers, status, viewsets
-from rest_framework.decorators import action
-from rest_framework.exceptions import ValidationError
-from rest_framework.parsers import JSONParser, MultiPartParser
-from rest_framework.request import Request
-from rest_framework_csv import renderers as csvrenderers
-
-from posthog.schema import EmbeddingModelName
-
-from posthog.hogql import ast
-from posthog.hogql.query import execute_hogql_query
-
-from posthog.api.embedding_worker import generate_embedding
-from posthog.api.mixins import ValidatedRequest, validated_request
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.shared import UserBasicSerializer
-from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
-from posthog.email import EmailMessage, is_email_available
-from posthog.models.sharing_configuration import SharingConfiguration
-from posthog.models.team import Team
-from posthog.models.user import User
-from posthog.permissions import PostHogFeatureFlagPermission
-from posthog.rate_limit import UserInterviewInviteThrottle
-from posthog.security.spreadsheet_safety import sanitize_formula_injection
-from posthog.utils import absolute_uri
-
-from ..facade.api import SHARED_INTERVIEWEE_IDENTIFIER, derive_auto_classifications, parse_interviewee_identifier
-from ..facade.enums import UserInterviewSearchDocumentType
-from ..invite_email import (
- build_invite_email_context,
- resolve_invite_preview,
- validate_invite_message,
- validate_invite_subject,
-)
-from ..models import (
- EmailWithDisplayNameValidator,
- IntervieweeContext,
- UserInterview,
- UserInterviewClassification,
- UserInterviewTopic,
-)
-
-logger = structlog.get_logger(__name__)
-
-if TYPE_CHECKING:
- from elevenlabs import ElevenLabs
-
-
-@cache
-def _get_elevenlabs_client() -> "ElevenLabs":
- # Deferred import + cached instance: the elevenlabs SDK is slow to import and
- # only the audio transcription path needs it, not every process that loads this module.
- from elevenlabs import ElevenLabs
-
- return ElevenLabs()
-
-
-class _InterviewLinksCSVRenderer(csvrenderers.CSVRenderer):
- """Lock the CSV column order for interview-links exports."""
-
- header = ["interviewee_identifier", "interviewee_email", "user_name", "interview_url"]
-
-
-class UserInterviewSerializer(serializers.ModelSerializer):
- created_by = UserBasicSerializer(read_only=True)
- audio = serializers.FileField(write_only=True)
- classifications = serializers.ListField(
- child=serializers.ChoiceField(choices=UserInterviewClassification.choices),
- required=False,
- help_text=(
- "Searchable classifications on the response. `abandoned` is auto-derived from the transcript when "
- "the interview is recorded; `off-topic` is set manually. Sending `classifications` on an update "
- "replaces the whole list — pass the full desired set, not a delta."
- ),
- )
-
- class Meta:
- model = UserInterview
- fields = (
- "id",
- "created_by",
- "created_at",
- "interviewee_emails",
- "interviewee_identifier",
- "topic",
- "transcript",
- "summary",
- "classifications",
- "audio",
- )
- read_only_fields = ("id", "created_by", "created_at", "interviewee_identifier", "topic", "transcript")
-
- def create(self, validated_data: dict) -> UserInterview:
- request = self.context["request"]
- validated_data["created_by"] = request.user
- validated_data["team_id"] = self.context["team_id"]
- audio = validated_data.pop("audio")
- validated_data["transcript"] = self._transcribe_audio(audio, validated_data["interviewee_emails"])
- validated_data["summary"] = self._summarize_transcript(validated_data["transcript"])
- validated_data["classifications"] = derive_auto_classifications(validated_data["transcript"])
- return super().create(validated_data)
-
- def _transcribe_audio(self, audio: File, interviewee_emails: list[str]) -> str:
- transcript = _get_elevenlabs_client().speech_to_text.convert(
- model_id="scribe_v1",
- file=audio,
- num_speakers=10, # Maximum number of speakers, not expected one
- diarize=True,
- tag_audio_events=False,
- additional_formats=json.dumps( # type: ignore
- [
- {
- "format": "txt",
- "include_timestamps": False,
- "segment_on_silence_longer_than_s": 10,
- }
- ]
- ),
- )
-
- transcript_text = transcript.additional_formats[0].content.strip() # type: ignore
-
- speaker_mapping = self._attempt_to_map_speaker_names(transcript_text, interviewee_emails)
- if speaker_mapping:
- for speaker_marker, speaker_name in speaker_mapping.items():
- transcript_text = transcript_text.replace(speaker_marker, speaker_name)
- formatted_transcript_text = re.sub(r"\[(.+)\]", "#### \\1", transcript_text)
- else:
- # Always fall back to formatting speaker numbers if we can't map names
- formatted_transcript_text = re.sub(r"\[speaker_(\d+)\]", "#### Speaker \\1", transcript_text)
-
- return formatted_transcript_text
-
- def _attempt_to_map_speaker_names(self, transcript: str, interviewee_emails: list[str]) -> dict[str, str] | None:
- participant_emails_joined = "\n".join(f"- {email}" for email in interviewee_emails)
- assignment_response = OpenAI(
- posthog_client=posthoganalytics.default_client, base_url=settings.OPENAI_BASE_URL
- ).responses.create(
- model="gpt-4.1-mini",
- posthog_trace_id=self._ai_trace_id,
- posthog_privacy_mode=True,
- posthog_distinct_id=self.context["request"].user.distinct_id,
- posthog_properties={
- "ai_product": "user_interviews",
- "ai_feature": "map-speakers",
- "team_id": self.context["request"].user.current_team_id,
- },
- input=[
- {
- "role": "system",
- "content": """
-Your task is to map speakers in a transcript to the actual names of the people who spoke. Each speaker is identified by a number.
-Use clues such as who the speaker is calling out (e.g. they wouldn't greet themselves) or what they're talking about (e.g. how they use company names).
-
-Your output should be a JSON mapping between "speaker_<n>" and "<speaker name>".
-
-<handling_ambiguity>
-- Use just the person's display name if available, otherwise use their email. If two people with the same full name are present, include their email to disambiguate.
-- Likely many of the participants have spoken, but not necessarily all of them.
-- Keep in mind it's possible there were additional unexpected participants (though not that likely).
-- The transcript is not going to be perfect, so some names in the transcript may be slightly mangled compared to display names in participant emails.
- E.g. the transcript may contain that an interviewer greeted "Jon", but if the participant emails only have a "John", it's safe to assume that the interviewer was talking to John.
-- If most of the speakers are entirely obvious, but only a small subset isn't, mark the unidentified speakers' names as "Unknown #1 (<candidate_1> or <candidate_2>)" etc. Don't leave any speaker unmarked.
- If however you cannot infer a reliable mapping for most speakers (the transcript has no useful information or is too chaotic), return simply: null.
-</handling_ambiguity>
-
-<example>
-As an example, for transcript:
-
-<participant_emails>
-- Michael F. Doe <[email protected]>
-- Steve Jobs <[email protected]>
-</participant_emails>
-<transcript>
-[speaker_0]
-Hi Michael! How big is your company?
-
-[speaker_1]
-Hey! We're about 200 people.
-
-[speaker_0]
-That's great!
-</transcript>
-
-Your output should be:
-
-{
-"speaker_0": "Steve Jobs",
-"speaker_1": "Michael F. Doe"
-}
-</example>
-
-<output_format>
-Output must always be valid JSON - either an object or null.
-</output_format>
-""".strip(),
- },
- {
- "role": "user",
- "content": f"""
-Map the speakers in the following transcript:
-
-<participant_emails>
-{participant_emails_joined}
-</participant_emails>
-
-<transcript>
-{transcript}
-</transcript>
-""".strip(),
- },
- ],
- )
- try:
- return json.loads(assignment_response.output_text)
- except json.JSONDecodeError as e:
- posthoganalytics.capture_exception(e)
- return None
-
- def _summarize_transcript(self, transcript: str) -> str:
- summary_response = OpenAI(posthog_client=posthoganalytics.default_client).responses.create(
- model="gpt-4.1-mini",
- posthog_trace_id=self._ai_trace_id,
- posthog_privacy_mode=True,
- posthog_distinct_id=self.context["request"].user.distinct_id,
- posthog_properties={
- "ai_product": "user_interviews",
- "ai_feature": "summarize-transcript",
- "team_id": self.context["request"].user.current_team_id,
- },
- input=[
- {
- "role": "system",
- "content": """
-You are an expert product manager, and your sole task is to summarizes user interviews ran by our team.
-""".strip(),
- },
- {
- "role": "user",
- "content": f"""
-I interviewed a user to gather insights about our product. The goal is to capture the customer's feedback, experiences, and suggestions in a detailed and organized manner.
-The notes should be comprehensive but focused, allowing for the detailed documentation of both qualitative insights and actionable items.
-Pull out direct quotes and figures whenever relevant.
-
-Because no better transcript is available, you should still do your best to summarize the interview.
-
-<summary_format>
-## User background
-
-Capture relevant details about the user, including their role, experience, and how they interact with your product or service.
-Note down here any existing solutions or workarounds they use.
-
-## Current product usage
-
-Document how the user is currently using the product, including frequency of use, key features used, and any specific use cases.
-
-## Positive feedback and pain points
-
-Summarize the positive feedback the user provided, as well as any pain points or challenges they are experiencing with the product.
-
-## Impact of the product
-
-Record the impact the product has had on the user's work or life, including any improvements or changes it has enabled.
-
-## Next steps and follow-up
-
-Record the agreed-upon next steps, including any additional actions that need to be taken, follow-up tasks, and who is responsible for them.
-</summary_format>
-
-<transcript>
-{transcript}
-</transcript>
-""".strip(),
- },
- ],
- )
- return summary_response.output_text
-
- @cached_property
- def _ai_trace_id(self) -> str:
- return str(uuid4())
-
-
-SEARCH_EMBEDDING_MODEL = EmbeddingModelName.TEXT_EMBEDDING_3_LARGE_3072.value
-SEARCH_CONTENT_SNIPPET_LIMIT = 500
-SEARCH_MAX_LIMIT = 50
-SEARCH_DEFAULT_LIMIT = 10
-# Pathological-size guard for topic_id-scoped searches — a topic with more than this many
-# interviews ships a giant IN list to ClickHouse. Realistic topics are tiny (<100); the
-# cap exists to keep the worst case bounded.
-SEARCH_TOPIC_INTERVIEW_CAP = 1000
-
-
-class UserInterviewSearchRequestSerializer(serializers.Serializer):
- query = serializers.CharField(
- max_length=2000,
- help_text="Natural-language query to match semantically against interview transcripts and summaries.",
- )
- document_types = serializers.ListField(
- child=serializers.ChoiceField(choices=UserInterviewSearchDocumentType.choices),
- required=False,
- allow_empty=False,
- min_length=1,
- help_text=(
- "Which document types to search across. Omit to default to both "
- "`transcript` and `summary`. Pass a non-empty subset to restrict the search."
- ),
- )
- topic_id = serializers.UUIDField(
- required=False,
- allow_null=True,
- help_text="Optional. Restrict results to interviews belonging to a specific UserInterviewTopic.",
- )
- classifications = serializers.ListField(
- child=serializers.ChoiceField(choices=UserInterviewClassification.choices),
- required=False,
- allow_empty=False,
- min_length=1,
- help_text=(
- "Optional. Restrict results to interviews carrying any of these classifications (OR). "
- "Combines with `topic_id` as AND."
- ),
- )
- limit = serializers.IntegerField(
- required=False,
- min_value=1,
- max_value=SEARCH_MAX_LIMIT,
- help_text=(
- f"Maximum number of matches to return (1-{SEARCH_MAX_LIMIT}). "
- f"Defaults to {SEARCH_DEFAULT_LIMIT}. Two matches per interview are possible — "
- "one for the transcript, one for the summary."
- ),
- )
-
-
-class UserInterviewSearchResultSerializer(serializers.Serializer):
- interview_id = serializers.UUIDField(help_text="ID of the matched UserInterview.")
- document_type = serializers.ChoiceField(
- choices=UserInterviewSearchDocumentType.choices,
- help_text="Which document type matched — `transcript` is the raw conversation, `summary` is the AI-generated abstract.",
- )
- similarity = serializers.FloatField(
- help_text="Cosine similarity in [0, 1]; higher is closer to the query. Computed as `1 - cosineDistance`.",
- )
- content_snippet = serializers.CharField(
- help_text=f"Excerpt of the matched document (first {SEARCH_CONTENT_SNIPPET_LIMIT} characters).",
- )
- interviewee_identifier = serializers.CharField(
- help_text="Email or PostHog distinct ID of the interviewee.",
- )
- topic_id = serializers.UUIDField(
- allow_null=True,
- help_text="ID of the UserInterviewTopic the interview was conducted for, or null if detached.",
- )
- created_at = serializers.DateTimeField(help_text="When the interview row was created.")
-
-
-class UserInterviewFilterSet(django_filters.FilterSet):
- classifications = django_filters.CharFilter(
- method="filter_classifications",
- help_text=(
- "Comma-separated classifications; returns responses carrying any of them (OR). "
- "Valid values: abandoned, off-topic."
- ),
- )
-
- class Meta:
- model = UserInterview
- fields = ["topic"]
-
- def filter_classifications(self, queryset: Any, name: str, value: str) -> Any:
- wanted = [t.strip() for t in value.split(",") if t.strip()]
- if not wanted:
- return queryset
- unknown = [c for c in wanted if c not in UserInterviewClassification.values]
- if unknown:
- valid = ", ".join(UserInterviewClassification.values)
- raise ValidationError(
- {"classifications": f"Unknown classification(s): {', '.join(unknown)}. Valid values: {valid}."}
- )
- return queryset.filter(classifications__overlap=wanted)
-
-
-class UserInterviewViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
- scope_object = "user_interview"
- queryset = UserInterview.objects.order_by("-created_at").select_related("created_by").all()
- serializer_class = UserInterviewSerializer
- parser_classes = [MultiPartParser, JSONParser]
- posthog_feature_flag = "user-interviews"
- permission_classes = [PostHogFeatureFlagPermission]
- filter_backends = [DjangoFilterBackend]
- filterset_class = UserInterviewFilterSet
-
- @validated_request(
- request_serializer=UserInterviewSearchRequestSerializer,
- responses={
- 200: OpenApiResponse(
- response=UserInterviewSearchResultSerializer(many=True),
- description="Matches ranked by cosine similarity (descending).",
- ),
- },
- summary="Search interview responses by semantic similarity",
- description=(
- "Embed `query` with the same model used to index interview transcripts and summaries, "
- "then return the top matches by cosine distance. Each match is a single (interview, "
- "document_type) pair — an interview can appear up to twice if both its transcript and "
- "summary score above other interviews. Useful for surfacing relevant interview snippets "
- "in natural language, without exact keyword matches."
- ),
- )
- @action(
- detail=False,
- methods=["post"],
- url_path="search",
- pagination_class=None,
- parser_classes=[JSONParser],
- required_scopes=["user_interview:read"],
- )
- def search(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> response.Response:
- body = request.validated_data
- query_str: str = body["query"]
- document_types: list[str] = body.get("document_types") or UserInterviewSearchDocumentType.values
- topic_id = body.get("topic_id")
- classifications: list[str] = body.get("classifications") or []
- limit: int = body.get("limit") or SEARCH_DEFAULT_LIMIT
-
- # When a topic_id or classifications filter is requested, resolve it via the current
- # Postgres linkage rather than the embedding-time `metadata.topic_id` — UserInterview.topic
- # is nullable with on_delete=SET_NULL, so historical metadata can name a topic the
- # row no longer belongs to, and classifications are mutated post-embedding.
- scoped_document_ids: list[str] | None = None
- if topic_id is not None or classifications:
- scoped_qs = UserInterview.objects.filter(team_id=self.team_id)
- if topic_id is not None:
- scoped_qs = scoped_qs.filter(topic_id=topic_id)
- if classifications:
- scoped_qs = scoped_qs.filter(classifications__overlap=classifications)
- scoped_ids_qs = scoped_qs.order_by("id").values_list("id", flat=True)[: SEARCH_TOPIC_INTERVIEW_CAP + 1]
- scoped_document_ids = [str(pk) for pk in scoped_ids_qs]
- if not scoped_document_ids:
- return response.Response(UserInterviewSearchResultSerializer([], many=True).data)
- if len(scoped_document_ids) > SEARCH_TOPIC_INTERVIEW_CAP:
- logger.warning(
- "user_interviews_search_topic_scope_capped",
- team_id=self.team_id,
- topic_id=str(topic_id) if topic_id is not None else None,
- classifications=classifications or None,
- cap=SEARCH_TOPIC_INTERVIEW_CAP,
- )
- scoped_document_ids = scoped_document_ids[:SEARCH_TOPIC_INTERVIEW_CAP]
-
- try:
- embedding_response = generate_embedding(self.team, query_str, model=SEARCH_EMBEDDING_MODEL)
- except Exception:
- logger.exception(
- "user_interviews_search_embedding_failed",
- team_id=self.team_id,
- query_length=len(query_str),
- )
- return response.Response(
- {"detail": "Embedding service is currently unavailable. Please retry shortly."},
- status=status.HTTP_502_BAD_GATEWAY,
- )
- query_vector = embedding_response.embedding
-
- where_clauses = [
- "model_name = {model_name}",
- "product = {product}",
- "team_id = {team_id}",
- "document_type IN {document_types}",
- ]
- placeholders: dict[str, ast.Expr] = {
- "embedding": ast.Constant(value=query_vector),
- "model_name": ast.Constant(value=SEARCH_EMBEDDING_MODEL),
- "product": ast.Constant(value=Product.USER_INTERVIEWS.value),
- "team_id": ast.Constant(value=self.team_id),
- "document_types": ast.Constant(value=document_types),
- "limit": ast.Constant(value=limit),
- }
- if scoped_document_ids is not None:
- where_clauses.append("document_id IN {scoped_document_ids}")
- placeholders["scoped_document_ids"] = ast.Constant(value=scoped_document_ids)
-
- # The embedding row is used only for ranking and routing. The snippet itself is
- # built from the current Postgres UserInterview field so edits/deletions to the
- # source content are reflected immediately — otherwise an embedding written before
- # an edit would leak the previous text via the search endpoint.
- hogql_query = f"""
- SELECT
- document_id,
- document_type,
- cosineDistance(embedding, {{embedding}}) AS distance
- FROM document_embeddings
- WHERE {" AND ".join(where_clauses)}
- ORDER BY distance ASC
- LIMIT {{limit}}
- """
-
- tag_queries(product=Product.USER_INTERVIEWS, feature=Feature.SEMANTIC_SEARCH)
- query_result = execute_hogql_query(
- query=hogql_query,
- team=self.team,
- placeholders=placeholders,
- )
-
- rows = query_result.results or []
- document_ids = {row[0] for row in rows}
- interviews_by_id = {
- str(i.id): i
- for i in UserInterview.objects.filter(team_id=self.team_id, id__in=document_ids).only(
- "id", "interviewee_identifier", "topic_id", "created_at", "transcript", "summary"
- )
- }
-
- results: list[dict[str, Any]] = []
- for document_id, document_type, distance in rows:
- interview = interviews_by_id.get(document_id)
- if interview is None:
- continue
- live_content = interview.transcript if document_type == "transcript" else interview.summary
- results.append(
- {
- "interview_id": interview.id,
- "document_type": document_type,
- "similarity": min(1.0, max(0.0, 1.0 - float(distance))),
- "content_snippet": (live_content or "")[:SEARCH_CONTENT_SNIPPET_LIMIT],
- "interviewee_identifier": interview.interviewee_identifier,
- "topic_id": interview.topic_id,
- "created_at": interview.created_at,
- }
- )
-
- return response.Response(UserInterviewSearchResultSerializer(results, many=True).data)
-
-
-# The shared-link sentinel and the `shared:` respondent namespace are internal markers that back a
-# topic's non-personalised link. A user-supplied interviewee identifier equal to one — or in the
-# `shared:` namespace — would collide on the unique (topic, interviewee_identifier) constraint and
-# silently merge with, or revoke, the topic's shared link. Reject them at every input boundary;
-# internal creation of the sentinel goes through the ORM directly, bypassing these serializers.
-_RESERVED_SHARED_IDENTIFIER_PREFIX = "shared:"
-
-
-def _reject_reserved_identifier(value: str) -> None:
- if value == SHARED_INTERVIEWEE_IDENTIFIER or value.startswith(_RESERVED_SHARED_IDENTIFIER_PREFIX):
- raise serializers.ValidationError(
- "This identifier is reserved for shared interview links and can't be assigned to an interviewee."
- )
-
-
-class UserInterviewTopicSerializer(serializers.ModelSerializer):
- created_by = UserBasicSerializer(read_only=True)
- interviewee_emails = serializers.ListField(
- child=serializers.CharField(max_length=254, validators=[EmailWithDisplayNameValidator()]),
- required=False,
- help_text="Email addresses of people to interview. May be combined with interviewee_distinct_ids.",
- )
- interviewee_distinct_ids = serializers.ListField(
- child=serializers.CharField(max_length=400),
- required=False,
- help_text="PostHog distinct IDs of people to interview. May be combined with interviewee_emails.",
- )
- topic = serializers.CharField(
- help_text="The product, feature, or idea you want to ask interviewees about.",
- )
- agent_context = serializers.CharField(
- required=False,
- allow_blank=True,
- help_text="Optional additional system prompt for the voice agent — extra background, tone, or constraints.",
- )
- questions = serializers.ListField(
- child=serializers.CharField(),
- required=False,
- help_text="Ordered list of questions the voice agent should work through during the interview.",
- )
- invite_subject = serializers.CharField(
- required=False,
- allow_blank=True,
- max_length=255,
- help_text=(
- "Subject line for the invitation email. Plain text only — URLs, angle brackets, and control "
- "characters are rejected. Leave blank to use the default subject. Personalization is handled by "
- "the email template, so do not include placeholders."
- ),
- )
- invite_message = serializers.CharField(
- required=False,
- allow_blank=True,
- max_length=1000,
- help_text=(
- "Intro message shown in the invitation email body, above the interview link. Plain prose only — "
- "URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank "
- "to use the default copy."
- ),
- )
-
- class Meta:
- model = UserInterviewTopic
- fields = (
- "id",
- "created_by",
- "created_at",
- "interviewee_emails",
- "interviewee_distinct_ids",
- "topic",
- "agent_context",
- "questions",
- "invite_subject",
- "invite_message",
- )
- read_only_fields = ("id", "created_by", "created_at")
-
- def validate_invite_subject(self, value: str | None) -> str | None:
- return validate_invite_subject(value)
-
- def validate_invite_message(self, value: str | None) -> str | None:
- return validate_invite_message(value)
-
- def validate_interviewee_distinct_ids(self, value: list[str]) -> list[str]:
- for identifier in value:
- _reject_reserved_identifier(identifier)
- return value
-
- # A topic needs no targeted interviewees to be valid: a non-personalised (shared) link is created
- # for a zero-target topic — the whole point for reaching anonymous visitors we have no contact
- # details for. The personalised flows (generate_links / send_invites) still guard the empty case
- # with their own errors where they actually need targets.
-
- def create(self, validated_data: dict) -> UserInterviewTopic:
- request = self.context["request"]
- team = self.context["get_team"]()
- return UserInterviewTopic.objects.create(
- team=team,
- created_by=request.user,
- **validated_data,
- )
-
- def update(self, instance: UserInterviewTopic, validated_data: dict) -> UserInterviewTopic:
- old_emails = set(instance.interviewee_emails or [])
- old_distinct_ids = set(instance.interviewee_distinct_ids or [])
- # Atomic so the topic save and the share-revoke commit together. Without this,
- # a crash between the two writes would leave an interviewee removed from targeting
- # but still able to open their existing public interview link.
- with transaction.atomic():
- topic = super().update(instance, validated_data)
- new_emails = set(topic.interviewee_emails or [])
- new_distinct_ids = set(topic.interviewee_distinct_ids or [])
- removed = (old_emails - new_emails) | (old_distinct_ids - new_distinct_ids)
- _disable_shares_for_identifiers(topic=topic, identifiers=sorted(removed))
- return topic
-
-
-def _parse_identifier(identifier: str) -> tuple[str, str | None]:
- """Tuple-shaped shim around the facade's identifier parser for legacy internal callers."""
- identity = parse_interviewee_identifier(identifier)
- return identity.display_name, identity.email
-
-
-def _merge_agent_context(topic_context: str, personal_context: str) -> str:
- parts = [p.strip() for p in (topic_context, personal_context) if p and p.strip()]
- return "\n\n".join(parts)
-
-
-class LatestTestInterviewSerializer(serializers.Serializer):
- completed_at = serializers.DateTimeField(
- help_text="When the test interview was completed.",
- )
- transcript = serializers.CharField(
- allow_blank=True,
- help_text="Full transcript of the test call, if Vapi delivered one. May be empty.",
- )
- summary = serializers.CharField(
- allow_blank=True,
- help_text="AI-generated summary of the test call, if Vapi delivered one. May be empty.",
- )
-
-
-class TestInterviewLinkSerializer(serializers.Serializer):
- interview_url = serializers.URLField(
- help_text=(
- "Public, unauthenticated URL the topic author opens to dogfood the voice "
- "interview themselves — does not count against the targeted interviewees."
- ),
- )
- latest_test_interview = LatestTestInterviewSerializer(
- allow_null=True,
- help_text="Most recent test interview completed by the topic author, or null if none yet.",
- )
-
-
-class InterviewLinkSerializer(serializers.Serializer):
- interviewee_identifier = serializers.CharField(
- max_length=400,
- help_text="The original identifier (email or distinct ID) from the topic targeting.",
- )
- user_name = serializers.CharField(
- help_text="Best-effort display name derived from the identifier, used to greet the interviewee.",
- )
- interview_url = serializers.URLField(
- help_text="Public, unauthenticated URL the interviewee opens to start the call. Backed by a SharingConfiguration access token.",
- )
- agent_context = serializers.CharField(
- help_text="The merged topic + per-interviewee context the voice agent will see during the call.",
- )
-
-
-class SharedInterviewLinkSerializer(serializers.Serializer):
- interview_url = serializers.URLField(
- help_text=(
- "Public, unauthenticated URL any respondent can open to start a new interview for this "
- "topic. Backed by a topic-level SharingConfiguration access token — not tied to any "
- "specific interviewee. Each visit is a new anonymous respondent who self-identifies with "
- "a name; `distinct_id` and `session_id` query params on the URL are captured as "
- "best-effort person/session linkage."
- ),
- )
-
-
-def _get_or_create_active_share(*, team: Team, **resource: Any) -> SharingConfiguration:
- """Get the active (enabled, unexpired) SharingConfiguration for a user-interviews resource,
- creating one if none exists. `resource` is the single FK kwarg identifying what's shared —
- always `interviewee_context=` today (a real invitee, the caller's test link, or the topic's
- shared-link sentinel). Callers own the surrounding transaction/locking."""
- sharing_config = (
- SharingConfiguration.objects.filter(team=team, enabled=True, **resource)
- .filter(models.Q(expires_at__isnull=True) | models.Q(expires_at__gt=timezone.now()))
- .order_by("-created_at")
- .first()
- )
- if sharing_config is None:
- sharing_config = SharingConfiguration.objects.create(team=team, enabled=True, **resource)
- return sharing_config
-
-
-def _ensure_shared_link_for_topic(*, topic: UserInterviewTopic, team: Team, created_by: User) -> SharingConfiguration:
- """Get-or-create the topic's single shared (non-personalised) interview link.
-
- Modelled exactly like the per-caller test link — an IntervieweeContext plus an enabled
- SharingConfiguration — but keyed on a reserved sentinel identifier so the token belongs to the
- whole topic: every visitor is a new anonymous respondent. No new model and no main-app schema
- change; the unique (topic, interviewee_identifier) constraint guarantees one shared link per
- topic and coalesces concurrent creates.
- """
- with transaction.atomic():
- ic, _ = IntervieweeContext.objects.select_for_update().get_or_create(
- team=team,
- topic=topic,
- interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER,
- defaults={"agent_context": "", "created_by": created_by},
- )
- return _get_or_create_active_share(team=team, interviewee_context=ic)
-
-
-def _disable_shared_link_for_topic(*, topic: UserInterviewTopic, team: Team) -> None:
- """Revoke the topic's shared (non-personalised) interview link so an already-distributed URL stops
- working. Disables every enabled SharingConfiguration on the topic's shared-link sentinel context —
- mirrors `_disable_shares_for_identifiers` for the personalised links. A later `shared_link` POST
- mints a fresh token (rotation)."""
- SharingConfiguration.objects.filter(
- team=team,
- interviewee_context__topic=topic,
- interviewee_context__interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER,
- enabled=True,
- ).update(enabled=False)
-
-
-def _dogfood_identifier(caller: User) -> str:
- """Identifier for the calling user's personal dogfood interviewee context.
-
- Prefers the user's email so the existing identifier-parsing surfaces a friendly
- display name in the assistant greeting; falls back to their distinct_id so a
- user without a real email still gets a working test link.
- """
- return caller.email or str(caller.distinct_id)
-
-
-def _ensure_dogfood_context(
- *, topic: UserInterviewTopic, team: Team, caller: User
-) -> tuple[IntervieweeContext, SharingConfiguration]:
- """Idempotently get-or-create the calling user's `IntervieweeContext` +
- enabled `SharingConfiguration` for a topic. The IC is keyed on the caller's
- own identifier so each team member gets their own dogfood link — we never
- mint a public share token in someone else's name.
-
- Wrapped in `transaction.atomic` + `select_for_update` on the IC row so two
- concurrent calls don't race into duplicate enabled SharingConfigurations
- for the same (caller, topic).
- """
- identifier = _dogfood_identifier(caller)
- with transaction.atomic():
- ic, _ = IntervieweeContext.objects.select_for_update().get_or_create(
- team=team,
- topic=topic,
- interviewee_identifier=identifier,
- defaults={
- "agent_context": "",
- "created_by": caller,
- },
- )
- sharing_config = _get_or_create_active_share(team=team, interviewee_context=ic)
- return ic, sharing_config
-
-
-def _materialize_links_for_topic(*, topic: UserInterviewTopic, team: Any, created_by: Any) -> list[dict[str, Any]]:
- """Get-or-create an `IntervieweeContext` and enabled `SharingConfiguration` for every
- targeted identifier on the topic. Returns one row per identifier with the resolved
- objects attached so callers (link-listing, invite-sending) can fan out without re-querying.
-
- Race-safe: concurrent calls for the same (topic, identifier) rely on the
- `unique_interviewee_per_topic` constraint (Paul's migration 0003) to coalesce. The
- `SharingConfiguration` lookup is best-effort and may transiently produce two configs
- on a tight race — that's acceptable since both are valid and one wins the next call.
- """
- identifiers: list[str] = []
- seen: set[str] = set()
- for raw in [*(topic.interviewee_emails or []), *(topic.interviewee_distinct_ids or [])]:
- if raw and raw not in seen:
- identifiers.append(raw)
- seen.add(raw)
-
- if not identifiers:
- return []
-
- results: list[dict[str, Any]] = []
- for identifier in identifiers:
- ic, _ = IntervieweeContext.objects.get_or_create(
- team=team,
- topic=topic,
- interviewee_identifier=identifier,
- defaults={"agent_context": "", "created_by": created_by},
- )
-
- sharing_config = _get_or_create_active_share(team=team, interviewee_context=ic)
-
- user_name, email = _parse_identifier(identifier)
- results.append(
- {
- "identifier": identifier,
- "user_name": user_name,
- "email": email,
- "interview_url": absolute_uri(f"/interview/{sharing_config.access_token}"),
- "agent_context": _merge_agent_context(topic.agent_context or "", ic.agent_context or ""),
- "interviewee_context": ic,
- "sharing_configuration": sharing_config,
- }
- )
- return results
-
-
-class InterviewInviteResultSerializer(serializers.Serializer):
- interviewee_identifier = serializers.CharField(
- help_text="The original identifier (email or distinct ID) from the topic targeting.",
- )
- email = serializers.EmailField(
- required=False,
- allow_null=True,
- help_text="Email used for delivery. Null when the identifier was not an email (e.g., a distinct ID).",
- )
- interview_url = serializers.URLField(
- help_text="The personalized public interview URL embedded in the email body.",
- )
- sent = serializers.BooleanField(
- help_text="True if an email was queued for delivery. False when the recipient was skipped — see `reason`.",
- )
- reason = serializers.CharField(
- required=False,
- allow_blank=True,
- help_text=(
- "Why the email was skipped (e.g., `not_an_email`, `duplicate_recipient`, `already_sent`). "
- "Empty when sent=true."
- ),
- )
-
-
-# Mirrors the column max_length on UserInterviewTopic.interviewee_emails — anything longer
-# would pass request validation and then fail at INSERT time with a 500. Keep in sync.
-EMAIL_IDENTIFIER_MAX_LENGTH = 254
-DISTINCT_ID_IDENTIFIER_MAX_LENGTH = 400
-
-
-def _identifier_is_email(identifier: str) -> bool:
- try:
- EmailWithDisplayNameValidator()(identifier)
- except DjangoValidationError:
- return False
- return True
-
-
-class IntervieweeIdentifierRequestSerializer(serializers.Serializer):
- identifier = serializers.CharField(
- max_length=DISTINCT_ID_IDENTIFIER_MAX_LENGTH,
- help_text=(
- "Email address or PostHog distinct ID for the interviewee. Email-shaped values "
- "(including the `Display Name <email@host>` form) are routed to `interviewee_emails`; "
- "everything else lands in `interviewee_distinct_ids`."
- ),
- )
-
- def validate_identifier(self, value: str) -> str:
- _reject_reserved_identifier(value)
- if _identifier_is_email(value) and len(value) > EMAIL_IDENTIFIER_MAX_LENGTH:
- raise serializers.ValidationError(
- f"Email identifiers must be {EMAIL_IDENTIFIER_MAX_LENGTH} characters or fewer."
- )
- return value
-
-
-def _disable_shares_for_identifiers(*, topic: UserInterviewTopic, identifiers: list[str]) -> None:
- """Disable any active SharingConfiguration tied to the given identifiers on a topic.
-
- Used by remove_interviewee, and by topic partial_update when identifiers are dropped
- from the targeting arrays — so a person removed via either path can no longer open
- their existing public interview link.
- """
- if not identifiers:
- return
- SharingConfiguration.objects.filter(
- team_id=topic.team_id,
- interviewee_context__topic=topic,
- interviewee_context__interviewee_identifier__in=identifiers,
- enabled=True,
- ).update(enabled=False)
-
-
-MAX_INVITE_RECIPIENTS_PER_SEND = 500
-
-
-class SendInvitesRequestSerializer(serializers.Serializer):
- subject = serializers.CharField(
- required=False,
- max_length=200,
- help_text=(
- "Override the email subject line for this send. Plain text only — URLs, angle brackets, and "
- "control characters are rejected. Falls back to the topic's saved subject, then a default."
- ),
- )
- reply_to = serializers.EmailField(
- required=False,
- help_text="Email address replies should go to. Defaults to the topic creator's email if blank.",
- )
- send_async = serializers.BooleanField(
- required=False,
- default=True,
- help_text="If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately.",
- )
-
- def validate_subject(self, value: str | None) -> str | None:
- return validate_invite_subject(value)
-
-
-class PreviewInviteRequestSerializer(serializers.Serializer):
- interviewee_identifier = serializers.CharField(
- required=False,
- allow_blank=True,
- max_length=400,
- help_text=(
- "Which targeted interviewee to render the preview for (an email or PostHog distinct ID "
- "already on the topic). Leave blank to preview for the first targeted interviewee."
- ),
- )
-
-
-class PreviewInviteResultSerializer(serializers.Serializer):
- interviewee_identifier = serializers.CharField(
- help_text="The identifier (email or distinct ID) the preview was rendered for.",
- )
- user_name = serializers.CharField(
- help_text="The display name used in the email greeting, derived from the identifier.",
- )
- email = serializers.EmailField(
- allow_null=True,
- help_text="The email address the invite would be sent to. Null for distinct-ID-only interviewees.",
- )
- subject = serializers.CharField(
- help_text="The rendered subject line (saved topic subject, sanitized, or the default).",
- )
- html = serializers.CharField(
- help_text="The fully rendered, CSS-inlined HTML body of the invite email. Safe to display in a sandboxed iframe.",
- )
- interview_url = serializers.URLField(
- help_text=(
- "An illustrative placeholder interview link shown in the previewed email body. The preview "
- "never exposes a real per-recipient share token — that link is minted only when invites are sent."
- ),
- )
- emailable = serializers.BooleanField(
- help_text="True if this interviewee has an email address and could actually receive the invite.",
- )
- is_preview_link = serializers.BooleanField(
- help_text="Always true — the previewed interview_url is an illustrative placeholder, never a live link.",
- )
-
-
-class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
- """Planned user interview topics: who we want to target and what we want to ask about."""
-
- scope_object = "user_interview"
- # Treat the custom @action endpoints as writes so personal API keys with
- # `user_interview:write` can hit them. Without this override, APIScopePermission
- # can't map a custom action name to a scope and rejects the request with
- # "This action does not support personal API key access".
- scope_object_write_actions = [
- "create",
- "update",
- "partial_update",
- "patch",
- "destroy",
- "generate_links",
- "shared_link",
- "links_csv",
- "send_invites",
- "add_interviewee",
- "remove_interviewee",
- "test_link",
- ]
- # preview_invite is a POST (body carries the identifier, keeping emails out of query-string logs)
- # but renders read-only with no side effects, so it maps to the read scope. Keep the default read
- # actions (list/retrieve) — this list REPLACES the default, so omitting them would drop read-scope
- # access for token-authenticated list/retrieve.
- scope_object_read_actions = [
- "list",
- "retrieve",
- "preview_invite",
- ]
- queryset = UserInterviewTopic.objects.select_related("created_by").all()
- serializer_class = UserInterviewTopicSerializer
- filter_backends = [filters.SearchFilter]
- search_fields = ["topic"]
- posthog_feature_flag = "user-interviews"
- permission_classes = [PostHogFeatureFlagPermission]
-
- @extend_schema(
- request=None,
- responses={200: OpenApiResponse(response=InterviewLinkSerializer(many=True))},
- description=(
- "Generate one public interview link per targeted interviewee. "
- "Materializes an IntervieweeContext row for every identifier on the topic "
- "(without overwriting existing per-person context), and an enabled "
- "SharingConfiguration with a unique access token. The URL resolves to the "
- "public interview viewer with no PostHog auth required."
- ),
- )
- @action(detail=True, methods=["post"], url_path="generate_links")
- def generate_links(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
- topic = self.get_object()
- results = _materialize_links_for_topic(topic=topic, team=self.team, created_by=request.user)
-
- if not results:
- return response.Response(
- {
- "error": (
- "Topic has no interviewee_emails or interviewee_distinct_ids set. "
- "Add them before generating links."
- )
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- payload = [
- {
- "interviewee_identifier": r["identifier"],
- "user_name": r["user_name"],
- "interview_url": r["interview_url"],
- "agent_context": r["agent_context"],
- }
- for r in results
- ]
- return response.Response(InterviewLinkSerializer(payload, many=True).data)
-
- @extend_schema(
- methods=["POST"],
- request=None,
- responses={200: OpenApiResponse(response=SharedInterviewLinkSerializer)},
- description=(
- "Get-or-create a single non-personalised (shared) interview link for this topic. Unlike "
- "generate_links, the returned URL is not tied to a specific interviewee — every visitor "
- "becomes a new anonymous respondent who self-identifies with a name. Idempotent: repeated "
- "calls return the same active link. `distinct_id` and `session_id` query params appended "
- "to the URL are captured as best-effort person/session linkage."
- ),
- )
- @extend_schema(
- methods=["DELETE"],
- request=None,
- responses={204: OpenApiResponse(description="Shared link revoked; the already-distributed URL stops working.")},
- description=(
- "Revoke this topic's shared (non-personalised) interview link so an already-distributed URL "
- "can no longer start interviews. Idempotent — a no-op when no active shared link exists. A "
- "subsequent shared_link POST mints a fresh link (rotation)."
- ),
- )
- @action(detail=True, methods=["post", "delete"], url_path="shared_link")
- def shared_link(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
- topic = self.get_object()
- if request.method == "DELETE":
- _disable_shared_link_for_topic(topic=topic, team=self.team)
- return response.Response(status=status.HTTP_204_NO_CONTENT)
- sharing_config = _ensure_shared_link_for_topic(topic=topic, team=self.team, created_by=cast(User, request.user))
- payload = {"interview_url": absolute_uri(f"/interview/{sharing_config.access_token}")}
- return response.Response(SharedInterviewLinkSerializer(payload).data)
-
- @extend_schema(
- request=None,
- responses={
- (200, "text/csv"): OpenApiResponse(
- response=OpenApiTypes.BINARY,
- description=(
- "CSV with columns: interviewee_identifier, interviewee_email, user_name, interview_url. "
- "One row per targeted interviewee."
- ),
- )
- },
- description=(
- "Same materialization as generate_links, returned as a downloadable CSV. "
- "Intended for users who want to mail-merge the per-person interview links "
- "into their own email tooling."
- ),
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="links_csv",
- renderer_classes=[_InterviewLinksCSVRenderer],
- )
- def links_csv(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
- topic = self.get_object()
- results = _materialize_links_for_topic(topic=topic, team=self.team, created_by=request.user)
-
- if not results:
- raise ValidationError(
- {
- "error": (
- "Topic has no interviewee_emails or interviewee_distinct_ids set. "
- "Add them before generating links."
- )
- }
- )
-
- rows = [
- {
- "interviewee_identifier": sanitize_formula_injection(r["identifier"]),
- "interviewee_email": sanitize_formula_injection(r["email"] or ""),
- "user_name": sanitize_formula_injection(r["user_name"]),
- "interview_url": sanitize_formula_injection(r["interview_url"]),
- }
- for r in results
- ]
- filename = f"{slugify(topic.topic or 'user-interview')}-links.csv"
- return response.Response(
- rows,
- headers={"Content-Disposition": f'attachment; filename="{filename}"'},
- )
-
- @extend_schema(
- request=SendInvitesRequestSerializer,
- responses={200: OpenApiResponse(response=InterviewInviteResultSerializer(many=True))},
- description=(
- "Generate (if needed) and email a personalized public interview link to every "
- "targeted interviewee on this topic whose identifier is an email address. "
- "Distinct-ID-only interviewees are skipped and surfaced in the response. "
- "Each invite is keyed on the underlying SharingConfiguration so re-runs after "
- "token rotation produce a fresh send."
- ),
- )
- @action(detail=True, methods=["post"], url_path="send_invites", throttle_classes=[UserInterviewInviteThrottle])
- def send_invites(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
- if not is_email_available():
- return response.Response(
- {"error": "Email is not configured for this PostHog instance."},
- status=status.HTTP_503_SERVICE_UNAVAILABLE,
- )
-
- params = SendInvitesRequestSerializer(data=request.data)
- params.is_valid(raise_exception=True)
-
- topic = self.get_object()
- # Enforce the cap on targeted identifiers BEFORE materializing share links, so an oversized
- # topic is rejected without first minting an IntervieweeContext + SharingConfiguration for
- # every target. dict.fromkeys dedups while preserving order, matching _materialize_links_for_topic.
- targeted_identifiers = list(
- dict.fromkeys(
- raw for raw in [*(topic.interviewee_emails or []), *(topic.interviewee_distinct_ids or [])] if raw
- )
- )
- if not targeted_identifiers:
- return response.Response(
- {
- "error": (
- "Topic has no interviewee_emails or interviewee_distinct_ids set. "
- "Add them before sending invites."
- )
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
- if len(targeted_identifiers) > MAX_INVITE_RECIPIENTS_PER_SEND:
- return response.Response(
- {
- "error": (
- f"Topic targets {len(targeted_identifiers)} interviewees, more than the per-send limit of "
- f"{MAX_INVITE_RECIPIENTS_PER_SEND}. Split the targeting across multiple topics."
- )
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- links = _materialize_links_for_topic(topic=topic, team=self.team, created_by=request.user)
-
- subject_override = params.validated_data.get("subject") or ""
- reply_to = params.validated_data.get("reply_to")
- if not reply_to and topic.created_by_id and topic.created_by and topic.created_by.email:
- reply_to = topic.created_by.email
- send_async = params.validated_data["send_async"]
-
- results: list[dict[str, Any]] = []
- seen_emails: set[str] = set()
- for link in links:
- base = {
- "interviewee_identifier": link["identifier"],
- "email": link["email"],
- "interview_url": link["interview_url"],
- }
- if not link["email"]:
- results.append({**base, "sent": False, "reason": "not_an_email"})
- continue
-
- # Collapse display-name aliases that resolve to the same mailbox (e.g.
- # "A1 <x@host>" and "A2 <x@host>") so one mailbox can't be invited repeatedly.
- email_key = link["email"].strip().lower()
- if email_key in seen_emails:
- results.append({**base, "sent": False, "reason": "duplicate_recipient"})
- continue
- seen_emails.add(email_key)
-
- built = build_invite_email_context(
- topic=topic,
- user_name=link["user_name"],
- interview_url=link["interview_url"],
- subject_override=subject_override,
- )
- campaign_key = f"interview_invite_{link['sharing_configuration'].id}"
- try:
- message = EmailMessage(
- campaign_key=campaign_key,
- template_name="interview_invite",
- subject=built["subject"],
- template_context=built["template_context"],
- reply_to=reply_to,
- )
- message.add_recipient(email=link["email"], name=link["user_name"])
- message.send(send_async=send_async)
- results.append({**base, "sent": True, "reason": ""})
- except Exception as e: # noqa: BLE001 — surface per-recipient failures without aborting the batch
- posthoganalytics.capture_exception(e)
- results.append({**base, "sent": False, "reason": f"error:{type(e).__name__}"})
-
- return response.Response(InterviewInviteResultSerializer(results, many=True).data)
-
- @extend_schema(
- request=PreviewInviteRequestSerializer,
- responses={200: OpenApiResponse(response=PreviewInviteResultSerializer)},
- description=(
- "Render the invite email exactly as a specific targeted interviewee would receive it — "
- "personalized subject and body — without sending anything and without creating or reading "
- "any share links. Pass `interviewee_identifier` to preview for a particular person, or omit "
- "it to preview for the first targeted interviewee. The body always shows an illustrative "
- "placeholder link (`is_preview_link: true`), never a live interview URL."
- ),
- )
- @action(detail=True, methods=["post"], url_path="preview_invite")
- def preview_invite(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
- params = PreviewInviteRequestSerializer(data=request.data)
- params.is_valid(raise_exception=True)
-
- topic = self.get_object()
- payload = resolve_invite_preview(
- topic=topic,
- interviewee_identifier=params.validated_data.get("interviewee_identifier") or "",
- )
- if payload is None:
- return response.Response(
- {
- "error": (
- "Topic has no targeted interviewees, or the given interviewee_identifier is not "
- "one of this topic's interviewee_emails / interviewee_distinct_ids."
- )
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
- return response.Response(PreviewInviteResultSerializer(payload).data)
-
- @extend_schema(
- request=None,
- responses={200: OpenApiResponse(response=TestInterviewLinkSerializer)},
- description=(
- "Return the calling user's personal dogfood interview link for this topic, "
- "plus the latest test interview they have recorded against it. Lazily "
- "get-or-creates a per-caller IntervieweeContext + enabled SharingConfiguration "
- "the first time it's called, then returns the same stable URL on subsequent "
- "calls. The caller's identifier is intentionally not added to the topic's "
- "targeting arrays — each user dogfoods under their own row, so test calls "
- "never mint a public share token on someone else's behalf."
- ),
- )
- @action(detail=True, methods=["get"], url_path="test_link")
- def test_link(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
- topic = self.get_object()
- ic, sharing_config = _ensure_dogfood_context(
- topic=topic,
- team=self.team,
- caller=cast(User, request.user),
- )
-
- latest = (
- UserInterview.objects.filter(
- team_id=self.team_id,
- topic_id=topic.id,
- interviewee_identifier=ic.interviewee_identifier,
- )
- .order_by("-created_at")
- .only("created_at", "transcript", "summary")
- .first()
- )
- latest_payload: dict[str, Any] | None = None
- if latest is not None:
- latest_payload = {
- "completed_at": latest.created_at,
- "transcript": latest.transcript or "",
- "summary": latest.summary or "",
- }
-
- payload = {
- "interview_url": absolute_uri(f"/interview/{sharing_config.access_token}"),
- "latest_test_interview": latest_payload,
- }
- return response.Response(TestInterviewLinkSerializer(payload).data)
-
- @extend_schema(
- request=IntervieweeIdentifierRequestSerializer,
- responses={200: OpenApiResponse(response=UserInterviewTopicSerializer)},
- description=(
- "Add a single interviewee to this topic. Email-shaped identifiers (including the "
- "`Display Name <email@host>` form) are appended to `interviewee_emails`; everything "
- "else is appended to `interviewee_distinct_ids`. Idempotent — adding an identifier "
- "that's already present leaves the topic unchanged. Returns the updated topic."
- ),
- )
- @action(detail=True, methods=["post"], url_path="add_interviewee")
- def add_interviewee(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
- params = IntervieweeIdentifierRequestSerializer(data=request.data)
- params.is_valid(raise_exception=True)
- identifier = params.validated_data["identifier"]
-
- self.get_object()
- with transaction.atomic():
- topic = self.get_queryset().select_for_update(of=("self",)).get(pk=kwargs[self.lookup_field])
- emails = list(topic.interviewee_emails or [])
- distinct_ids = list(topic.interviewee_distinct_ids or [])
- changed = False
- if _identifier_is_email(identifier):
- if identifier not in emails:
- emails.append(identifier)
- changed = True
- elif identifier not in distinct_ids:
- distinct_ids.append(identifier)
- changed = True
-
- if changed:
- topic.interviewee_emails = emails
- topic.interviewee_distinct_ids = distinct_ids
- topic.save(update_fields=["interviewee_emails", "interviewee_distinct_ids"])
-
- serializer = UserInterviewTopicSerializer(topic, context=self.get_serializer_context())
- return response.Response(serializer.data)
-
- @extend_schema(
- request=IntervieweeIdentifierRequestSerializer,
- responses={200: OpenApiResponse(response=UserInterviewTopicSerializer)},
- description=(
- "Remove an interviewee from this topic. Drops the identifier from both "
- "`interviewee_emails` and `interviewee_distinct_ids`, and disables any active "
- "SharingConfiguration linked to an IntervieweeContext for that identifier on this "
- "topic so the removed person can no longer open their interview link. Idempotent — "
- "removing an identifier that isn't present is a no-op. Returns the updated topic."
- ),
- )
- @action(detail=True, methods=["post"], url_path="remove_interviewee")
- def remove_interviewee(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
- params = IntervieweeIdentifierRequestSerializer(data=request.data)
- params.is_valid(raise_exception=True)
- identifier = params.validated_data["identifier"]
-
- self.get_object()
- with transaction.atomic():
- topic = self.get_queryset().select_for_update(of=("self",)).get(pk=kwargs[self.lookup_field])
- new_emails = [e for e in (topic.interviewee_emails or []) if e != identifier]
- new_distinct_ids = [d for d in (topic.interviewee_distinct_ids or []) if d != identifier]
-
- if new_emails != list(topic.interviewee_emails or []) or new_distinct_ids != list(
- topic.interviewee_distinct_ids or []
- ):
- topic.interviewee_emails = new_emails
- topic.interviewee_distinct_ids = new_distinct_ids
- topic.save(update_fields=["interviewee_emails", "interviewee_distinct_ids"])
-
- _disable_shares_for_identifiers(topic=topic, identifiers=[identifier])
-
- serializer = UserInterviewTopicSerializer(topic, context=self.get_serializer_context())
- return response.Response(serializer.data)
-
-
-class IntervieweeContextSerializer(serializers.ModelSerializer):
- created_by = UserBasicSerializer(read_only=True)
- interviewee_identifier = serializers.CharField(
- max_length=400,
- help_text="Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids.",
- )
- agent_context = serializers.CharField(
- max_length=10000,
- help_text="Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'.",
- )
-
- class Meta:
- model = IntervieweeContext
- fields = (
- "id",
- "created_by",
- "created_at",
- "interviewee_identifier",
- "agent_context",
- )
- read_only_fields = ("id", "created_by", "created_at")
-
- def validate_interviewee_identifier(self, value: str) -> str:
- _reject_reserved_identifier(value)
- return value
-
- def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
- topic_id = self.context["topic_id"]
- team = self.context["get_team"]()
-
- if not UserInterviewTopic.objects.filter(id=topic_id, team_id=team.id).exists():
- raise serializers.ValidationError({"topic": "Topic not found in this project."})
-
- interviewee_identifier = attrs.get("interviewee_identifier")
- if interviewee_identifier is not None:
- conflicts = IntervieweeContext.objects.filter(
- topic_id=topic_id, interviewee_identifier=interviewee_identifier
- )
- if self.instance is not None:
- conflicts = conflicts.exclude(pk=self.instance.pk)
- if conflicts.exists():
- raise serializers.ValidationError(
- {
- "interviewee_identifier": "A context row for this interviewee already exists on this topic. Update the existing row instead of creating a new one."
- }
- )
- return attrs
-
- def create(self, validated_data: dict[str, Any]) -> IntervieweeContext:
- request = self.context["request"]
- team = self.context["get_team"]()
- topic_id = self.context["topic_id"]
- return IntervieweeContext.objects.create(
- team=team,
- topic_id=topic_id,
- created_by=request.user,
- **validated_data,
- )
-
-
-BULK_INTERVIEWEE_CONTEXT_MAX_ITEMS = 500
-
-
-class BulkIntervieweeContextItemSerializer(serializers.Serializer):
- interviewee_identifier = serializers.CharField(
- max_length=400,
- help_text="Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids.",
- )
- agent_context = serializers.CharField(
- max_length=10000,
- help_text="Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'.",
- )
-
- def validate_interviewee_identifier(self, value: str) -> str:
- _reject_reserved_identifier(value)
- return value
-
-
-class BulkIntervieweeContextRequestSerializer(serializers.Serializer):
- items = BulkIntervieweeContextItemSerializer(
- many=True,
- allow_empty=False,
- help_text=(
- "List of interviewee context rows to create. Each item has an `interviewee_identifier` and an "
- f"`agent_context`. At most {BULK_INTERVIEWEE_CONTEXT_MAX_ITEMS} items per request."
- ),
- )
-
- def validate_items(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]:
- if len(value) > BULK_INTERVIEWEE_CONTEXT_MAX_ITEMS:
- raise serializers.ValidationError(
- f"Cannot create more than {BULK_INTERVIEWEE_CONTEXT_MAX_ITEMS} interviewee contexts in one request."
- )
- identifiers = [item["interviewee_identifier"] for item in value]
- if len(set(identifiers)) != len(identifiers):
- raise serializers.ValidationError("Duplicate interviewee_identifier values within items.")
- return value
-
-
-class BulkIntervieweeContextResponseSerializer(serializers.Serializer):
- inserted_count = serializers.IntegerField(help_text="Number of rows inserted by this request.")
- skipped_count = serializers.IntegerField(
- help_text="Number of items skipped because a row for that (topic, interviewee_identifier) already existed."
- )
- skipped_identifiers = serializers.ListField(
- child=serializers.CharField(),
- help_text="Identifiers from the request whose rows were skipped because a row for that (topic, interviewee_identifier) already existed.",
- )
-
-
-class IntervieweeContextViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
- """Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier)."""
-
- scope_object = "user_interview"
- # Treat the custom @action endpoints as writes so personal API keys with
- # `user_interview:write` can hit them. Without this override, APIScopePermission
- # can't map a custom action name to a scope and rejects the request with
- # "This action does not support personal API key access".
- scope_object_write_actions = [
- "create",
- "update",
- "partial_update",
- "destroy",
- "bulk_create",
- ]
- serializer_class = IntervieweeContextSerializer
- queryset = IntervieweeContext.objects.select_related("created_by").all()
- posthog_feature_flag = "user-interviews"
- permission_classes = [PostHogFeatureFlagPermission]
-
- def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
- # Hide the shared-link sentinel row — it's an internal marker, not a real interviewee.
- return queryset.filter(
- topic_id=self.parents_query_dict["topic_id"],
- team_id=self.parents_query_dict["team_id"],
- ).exclude(interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER)
-
- def get_serializer_context(self) -> dict[str, Any]:
- return {**super().get_serializer_context(), "topic_id": self.parents_query_dict["topic_id"]}
-
- @extend_schema(
- request=BulkIntervieweeContextRequestSerializer,
- responses={200: OpenApiResponse(response=BulkIntervieweeContextResponseSerializer)},
- description=(
- f"Create up to {BULK_INTERVIEWEE_CONTEXT_MAX_ITEMS} interviewee context rows for a topic in a single "
- "request. Rows whose (topic, interviewee_identifier) already exists are skipped — the response surfaces "
- "an `inserted_count`, a `skipped_count`, and the `skipped_identifiers` so the caller can reconcile. "
- "Items must have unique `interviewee_identifier` values within the batch."
- ),
- )
- @action(detail=False, methods=["post"], url_path="bulk", pagination_class=None)
- def bulk_create(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
- topic_id = self.parents_query_dict["topic_id"]
- team_id = self.parents_query_dict["team_id"]
-
- topic = UserInterviewTopic.objects.filter(id=topic_id, team_id=team_id).first()
- if topic is None:
- return response.Response(
- {"error": "Topic not found in this project."},
- status=status.HTTP_404_NOT_FOUND,
- )
- self.check_object_permissions(request, topic)
-
- payload = BulkIntervieweeContextRequestSerializer(data=request.data)
- payload.is_valid(raise_exception=True)
- items: list[dict[str, Any]] = payload.validated_data["items"]
-
- identifiers = [item["interviewee_identifier"] for item in items]
- existing = set(
- IntervieweeContext.objects.filter(
- topic_id=topic_id,
- interviewee_identifier__in=identifiers,
- ).values_list("interviewee_identifier", flat=True)
- )
-
- new_rows = [
- IntervieweeContext(
- team_id=team_id,
- topic_id=topic_id,
- created_by=cast(User, request.user),
- interviewee_identifier=item["interviewee_identifier"],
- agent_context=item["agent_context"],
- )
- for item in items
- if item["interviewee_identifier"] not in existing
- ]
-
- inserted = IntervieweeContext.objects.bulk_create(new_rows, ignore_conflicts=True)
-
- response_payload = {
- "inserted_count": len(inserted),
- "skipped_count": len(existing) + (len(new_rows) - len(inserted)),
- "skipped_identifiers": sorted(existing),
- }
- return response.Response(BulkIntervieweeContextResponseSerializer(response_payload).data)
diff --git a/products/user_interviews/backend/presentation/webhooks.py b/products/user_interviews/backend/presentation/webhooks.py
deleted file mode 100644
index 379e033e739d..000000000000
--- a/products/user_interviews/backend/presentation/webhooks.py
+++ /dev/null
@@ -1,392 +0,0 @@
-"""Public, unauthenticated endpoints for the user_interviews product.
-
-Two surfaces live here, both keyed on a SharingConfiguration access token:
-
-* ``start_call`` — called by the public interview page when the recipient clicks
- Start. Creates one Vapi web call server-side and returns only its join payload.
-* ``vapi_webhook`` — the endpoint Vapi calls during and after a call. The throttle,
- verification and fan-out are the ingress vapi incarnation's, and the consumer it
- dispatches to lives in ``backend/webhook_consumers.py``.
-"""
-
-import json
-import string
-import hashlib
-from typing import Any
-
-from django.conf import settings
-
-import requests
-import structlog
-from rest_framework import status
-from rest_framework.decorators import api_view, authentication_classes, permission_classes, throttle_classes
-from rest_framework.permissions import AllowAny
-from rest_framework.request import Request
-from rest_framework.response import Response
-from rest_framework.throttling import SimpleRateThrottle
-
-from posthog.constants import AvailableFeature
-from posthog.egress.vapi import vapi_request
-from posthog.ingress.vapi.provider import build_vapi_provider
-from posthog.ingress.views import build_webhook_view
-from posthog.models.sharing_configuration import SharingConfiguration
-from posthog.models.team import Team
-from posthog.rate_limit import IPThrottle
-
-from ..facade.api import is_shared_interviewee_context, valid_distinct_id, valid_session_id
-from ..logic import (
- RESPONDENT_KEY_MAX_CHARS,
- RESPONDENT_NAME_MAX_CHARS,
- clean_field,
- resolve_first_message_template,
- resolve_share,
- shared_interviewee_identifier,
-)
-
-logger = structlog.get_logger(__name__)
-
-
-class _RateLimitMetricsMixin(SimpleRateThrottle):
- """Mixin that emits `rate_limit_exceeded_total` whenever the throttle it's mixed into rejects
- a request. Mixed *ahead* of the concrete throttle base (`IPThrottle` or `SimpleRateThrottle`)
- so `super().allow_request()` runs the real throttle logic, then this records the rejection.
-
- Kept product-local (not folded into the base `IPThrottle`) on purpose: tweaking the base would
- cascade into unrelated products that subclass it. One mixin serves both the IP-keyed and the
- token/respondent-keyed throttles here — `IPThrottle` is itself a `SimpleRateThrottle`, so the MRO
- resolves `super()` to whichever concrete base each throttle names.
- """
-
- def allow_request(self, request: Request, view: Any) -> bool:
- from posthog.rate_limit import RATE_LIMIT_EXCEEDED_COUNTER, get_route_from_path
-
- allowed = super().allow_request(request, view)
- if not allowed:
- route = get_route_from_path(getattr(request, "path", None))
- RATE_LIMIT_EXCEEDED_COUNTER.labels(team_id="", scope=self.scope, path=route, route=route).inc()
- return bool(allowed)
-
-
-class InterviewStartCallIPThrottle(_RateLimitMetricsMixin, IPThrottle):
- """Per-IP cap on `start_call`. The endpoint is `AllowAny`, so without this any caller can spin DB
- queries on share-token lookups indefinitely. This cap's real job is bounding cross-token probing
- from one IP — per-token abuse is bounded by the token burst (120/min) + sustained (600/hour)
- buckets. It sits above the token burst on purpose: a shared link's headline use case is many
- people behind one corporate NAT / mobile CGNAT egress IP opening the same link, so a tight per-IP
- cap would 429 legitimate concurrent respondents who share an egress. 200/min clears the token
- burst (so the token bucket, not the IP, governs a single link's concurrency) while still stopping
- a single IP from probing many tokens."""
-
- scope = "user_interviews_start_call_ip"
- rate = "200/minute"
-
-
-class InterviewStartCallTokenThrottle(_RateLimitMetricsMixin):
- """Sustained per-share-token ceiling on `start_call`. One token maps to either a single invited
- person (personalised link) or many self-serve respondents (a shared topic link), so this is a
- generous *sustained* bucket. On its own it would still let the whole hour's budget be spent in a
- burst — the per-IP cap doesn't bind a caller spread across many IPs, and the respondent throttle
- keys on a client-supplied respondent_key an attacker can rotate — so the companion
- `InterviewStartCallTokenBurstThrottle` adds a short-window per-token cap. Keying on the token (not
- IP) means an attacker rotating IPs still can't drain a guessed token faster than these two allow."""
-
- scope = "user_interviews_start_call_token"
- rate = "600/hour"
-
- def get_cache_key(self, request: Request, view: Any) -> str | None:
- resolver_match = getattr(request, "resolver_match", None)
- token = resolver_match.kwargs.get("access_token") if resolver_match else None
- if not token:
- return None
- return self.cache_format % {"scope": self.scope, "ident": token}
-
-
-class InterviewStartCallTokenBurstThrottle(InterviewStartCallTokenThrottle):
- """Short-window per-share-token burst cap. Bounds the *instantaneous* rate a single token can be
- driven at — regardless of how many IPs or rotated respondent_keys a caller uses — so the sustained
- hourly budget can't be dumped in seconds. Recovers within the minute, and 120/min sits well above
- the realistic concurrent-Start volume for a shared link at this stage, so legitimate respondents
- aren't throttled. Reuses the parent's token-keyed cache key under its own scope."""
-
- scope = "user_interviews_start_call_token_burst"
- rate = "120/minute"
-
-
-class InterviewStartCallRespondentThrottle(_RateLimitMetricsMixin):
- """Per-respondent burst on `start_call`, mirroring the support widget's `WidgetUserBurstThrottle`.
- Keys on the client-generated `respondent_key` (a random per-browser id a shared-link visitor
- sends) so one respondent hammering Start is bounded without penalising the next visitor sharing
- the same token. Falls back to IP when no key is present (personalised links, which don't send one)
- — so a personalised interviewee's effective per-IP ceiling is this 30/min (the lower of this and
- the 200/min IP throttle), which is still far above one person clicking Start."""
-
- scope = "user_interviews_start_call_respondent"
- rate = "30/minute"
-
- def get_cache_key(self, request: Request, view: Any) -> str | None:
- respondent_key = request.data.get("respondent_key") if isinstance(request.data, dict) else None
- if respondent_key:
- ident = hashlib.sha256(str(respondent_key).encode()).hexdigest()
- else:
- ident = self.get_ident(request)
- return self.cache_format % {"scope": self.scope, "ident": ident}
-
-
-def _public_sharing_disabled_for_org(sharing_config: SharingConfiguration) -> bool:
- """Mirror of `SharingViewerPageViewSet.retrieve()`'s org-level kill switch."""
- organization = sharing_config.team.organization
- return (
- organization.is_feature_available(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS)
- and not organization.allow_publicly_shared_resources
- )
-
-
-_TOPIC_MAX_CHARS = 200
-
-FIRST_MESSAGE_PROMPT_NAME = "user_interviews_vapi_first_message"
-
-DEFAULT_FIRST_MESSAGE_TEMPLATE = (
- "Hey $user_name! Thanks for making time — I know you're busy. "
- "I'm here to learn how you actually use $topic_text in the wild. "
- "Mind if I ask a few questions? Should take about 5-10 minutes."
-)
-
-_FIRST_MESSAGE_MAX_CHARS = 1000
-
-
-def _normalise_topic(topic_text: str) -> str:
- return " ".join(topic_text.split())[:_TOPIC_MAX_CHARS]
-
-
-def _resolve_first_message_template(team: Team) -> str:
- return resolve_first_message_template(team, FIRST_MESSAGE_PROMPT_NAME, DEFAULT_FIRST_MESSAGE_TEMPLATE)
-
-
-def _build_first_message(
- template: str,
- *,
- user_name: str,
- topic_text: str,
- team_id: int | None = None,
-) -> str:
- name_part = user_name.strip() or "there"
- topic_part = _normalise_topic(topic_text) or "your experience"
- try:
- rendered = string.Template(template).substitute(user_name=name_part, topic_text=topic_part)
- except (KeyError, ValueError):
- logger.warning(
- "user_interviews_first_message_template_invalid",
- team_id=team_id,
- template_prefix=template[:60],
- )
- rendered = string.Template(DEFAULT_FIRST_MESSAGE_TEMPLATE).substitute(
- user_name=name_part, topic_text=topic_part
- )
- if len(rendered) > _FIRST_MESSAGE_MAX_CHARS:
- logger.warning(
- "user_interviews_first_message_too_long",
- team_id=team_id,
- rendered_chars=len(rendered),
- limit=_FIRST_MESSAGE_MAX_CHARS,
- )
- rendered = string.Template(DEFAULT_FIRST_MESSAGE_TEMPLATE).substitute(
- user_name=name_part, topic_text=topic_part
- )
- return rendered[:_FIRST_MESSAGE_MAX_CHARS]
-
-
-VAPI_WEB_CALL_URL = "https://api.vapi.ai/call/web"
-
-
-class VapiWebCallError(Exception):
- def __init__(self, message: str, status_code: int = status.HTTP_502_BAD_GATEWAY) -> None:
- super().__init__(message)
- self.status_code = status_code
-
-
-def _create_vapi_web_call(assistant_overrides: dict[str, Any]) -> dict[str, Any]:
- try:
- response = vapi_request(
- "POST",
- VAPI_WEB_CALL_URL,
- api_token=settings.VAPI_PUBLIC_KEY,
- source="user_interviews",
- endpoint="/call/web",
- timeout=(3.05, 15),
- json={
- "assistantId": settings.VAPI_ASSISTANT_ID,
- "assistantOverrides": assistant_overrides,
- "roomDeleteOnUserLeaveEnabled": True,
- },
- )
- except requests.RequestException as error:
- raise VapiWebCallError("Could not connect to Vapi.") from error
-
- if response.status_code == status.HTTP_429_TOO_MANY_REQUESTS:
- raise VapiWebCallError("Vapi is temporarily rate limited.", status.HTTP_429_TOO_MANY_REQUESTS)
- if not 200 <= response.status_code < 300:
- raise VapiWebCallError(f"Vapi rejected web call creation with status {response.status_code}.")
-
- try:
- payload = response.json()
- except ValueError as error:
- raise VapiWebCallError("Vapi returned an invalid web call response.") from error
- if not isinstance(payload, dict):
- raise VapiWebCallError("Vapi returned an invalid web call response.")
-
- transport = payload.get("transport")
- transport_url = transport.get("callUrl") if isinstance(transport, dict) else None
- web_call_url = payload.get("webCallUrl") or transport_url
- if not isinstance(web_call_url, str) or not web_call_url:
- raise VapiWebCallError("Vapi returned a web call without a join URL.")
-
- web_call: dict[str, Any] = {"webCallUrl": web_call_url}
- call_id = payload.get("id")
- if isinstance(call_id, str):
- web_call["id"] = call_id
- artifact_plan = payload.get("artifactPlan")
- if isinstance(artifact_plan, dict):
- web_call["artifactPlan"] = {"videoRecordingEnabled": bool(artifact_plan.get("videoRecordingEnabled", False))}
- return web_call
-
-
-@api_view(["POST"])
-@authentication_classes([])
-@permission_classes([AllowAny])
-@throttle_classes(
- [
- InterviewStartCallIPThrottle,
- InterviewStartCallRespondentThrottle,
- InterviewStartCallTokenBurstThrottle,
- InterviewStartCallTokenThrottle,
- ]
-)
-def start_call(request: Request, access_token: str) -> Response:
- """Create a Vapi web call and return its join payload for a public interview share.
-
- Handles both share types the token can resolve to:
- * a personalised (per-invitee) share — greets the named invitee, merges their per-person
- ``agent_context``;
- * a non-personalised (shared) topic share — every visitor is a new anonymous respondent who
- self-identifies with a name; ``distinct_id``/``session_id`` query params are carried through
- as best-effort person/session linkage, and a client ``respondent_key`` lets a refreshed call
- re-attach to the same respondent.
-
- The ``agent_context`` (which may include internal CRM notes about a personalised invitee) and
- reusable Vapi credentials stay server-side. The browser receives only a single call's join
- payload after the existing start-call throttles have accepted the request.
- """
- from .views import _merge_agent_context, _parse_identifier
-
- if not settings.VAPI_PUBLIC_KEY or not settings.VAPI_ASSISTANT_ID:
- logger.warning("user_interviews_start_call_misconfigured")
- return Response(
- {"error": "Vapi is not configured on this PostHog instance."},
- status=status.HTTP_503_SERVICE_UNAVAILABLE,
- )
-
- body = request.data if isinstance(request.data, dict) else {}
- # Honeypot: a hidden field real users never fill, but naive bots do. Present on the shared-link
- # name form; reject silently-ish with a 400 so a bot can't spin up calls. Log it so a bot wave —
- # or a false positive dropping a real respondent — is visible rather than a silent black hole.
- if body.get("_hp"):
- logger.warning(
- "user_interviews_start_call_honeypot_tripped",
- access_token_suffix=access_token[-6:] if access_token else None,
- )
- return Response({"error": "invalid request"}, status=status.HTTP_400_BAD_REQUEST)
-
- sharing_config = resolve_share(access_token)
- if sharing_config is None or sharing_config.interviewee_context is None:
- logger.warning("user_interviews_start_call_unknown_access_token")
- return Response({"error": "unknown access_token"}, status=status.HTTP_404_NOT_FOUND)
- if _public_sharing_disabled_for_org(sharing_config):
- # Match the public viewer's behavior: return 404 so the kill switch is opaque to
- # link recipients (doesn't reveal whether the token is real, just disabled).
- logger.info(
- "user_interviews_start_call_sharing_disabled",
- team_id=sharing_config.team_id,
- )
- return Response({"error": "unknown access_token"}, status=status.HTTP_404_NOT_FOUND)
-
- ic = sharing_config.interviewee_context
- topic = ic.topic
- if is_shared_interviewee_context(ic.interviewee_identifier):
- respondent_name = clean_field(body.get("name"), RESPONDENT_NAME_MAX_CHARS)
- if not respondent_name:
- return Response({"error": "name is required"}, status=status.HTTP_400_BAD_REQUEST)
- respondent_key = clean_field(body.get("respondent_key"), RESPONDENT_KEY_MAX_CHARS)
- user_name = respondent_name or "there"
- agent_context = topic.agent_context or ""
- # The response is stored under a namespaced identifier that can never collide with a targeted
- # invitee's. The distinct_id from the URL is best-effort, UNTRUSTED linkage carried in its own
- # metadata field — never folded into the identifier, so it can't forge attribution or lock a
- # targeted person out.
- metadata: dict[str, str] = {
- "topic_id": str(topic.id),
- "interviewee_identifier": shared_interviewee_identifier(respondent_key),
- "sharing_access_token": access_token,
- "shared": "true",
- "respondent_name": respondent_name,
- "respondent_key": respondent_key,
- "distinct_id": valid_distinct_id(body.get("distinct_id")),
- # session_id isn't persisted in the DB — it rides on the lifecycle PostHog event (as
- # $session_id, which associates the interview with the session recording). Validated
- # here at the trust boundary; invalid values are dropped, not rejected.
- "session_id": valid_session_id(body.get("session_id")),
- }
- else:
- user_name, _ = _parse_identifier(ic.interviewee_identifier)
- agent_context = _merge_agent_context(topic.agent_context or "", ic.agent_context or "")
- metadata = {
- "topic_id": str(topic.id),
- "interviewee_identifier": ic.interviewee_identifier,
- "sharing_access_token": access_token,
- }
-
- first_message_template = _resolve_first_message_template(sharing_config.team)
- first_message = _build_first_message(
- first_message_template,
- user_name=user_name,
- topic_text=topic.topic or "",
- team_id=sharing_config.team_id,
- )
-
- assistant_overrides: dict[str, Any] = {
- "firstMessage": first_message,
- # Scope server messages to just the lifecycle hooks we act on. Default Vapi
- # config sends ~10 message types that we'd otherwise ignore.
- "serverMessages": ["status-update", "end-of-call-report"],
- "variableValues": {
- "userName": user_name,
- "topic": topic.topic or "",
- "agent_context": agent_context,
- "questions": json.dumps(topic.questions or []),
- },
- "metadata": metadata,
- }
- try:
- web_call = _create_vapi_web_call(assistant_overrides)
- except VapiWebCallError as error:
- logger.exception(
- "user_interviews_vapi_web_call_creation_failed",
- team_id=sharing_config.team_id,
- topic_id=str(topic.id),
- status_code=error.status_code,
- )
- return Response({"error": str(error)}, status=error.status_code)
-
- logger.info(
- "user_interviews_start_call_issued",
- team_id=sharing_config.team_id,
- topic_id=str(topic.id),
- shared=is_shared_interviewee_context(ic.interviewee_identifier),
- call_id=web_call.get("id"),
- )
- return Response({"web_call": web_call})
-
-
-# Built once per process: the provider holds a secret getter, and reads the secret per request.
-# The per-IP cap rides on the provider's `throttle_class`, so the throttle, the 429 and its
-# `Retry-After` are the ingress lane's, the same as every other provider that caps.
-vapi_webhook = build_webhook_view(build_vapi_provider())
diff --git a/products/user_interviews/backend/routes.py b/products/user_interviews/backend/routes.py
deleted file mode 100644
index 2382b9e687be..000000000000
--- a/products/user_interviews/backend/routes.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from django.urls import URLPattern, path
-
-from posthog.api.routing import RouterRegistry
-
-from products.user_interviews.backend.presentation.views import (
- IntervieweeContextViewSet,
- UserInterviewTopicViewSet,
- UserInterviewViewSet,
-)
-from products.user_interviews.backend.presentation.webhooks import vapi_webhook
-
-api_urlpatterns: list[URLPattern] = [
- path(
- "vapi_webhook/",
- vapi_webhook,
- name="user_interviews_vapi_webhook",
- ),
-]
-
-
-def register_routes(routers: RouterRegistry) -> None:
- routers.projects.register(r"user_interviews", UserInterviewViewSet, "project_user_interviews", ["team_id"])
- user_interview_topics_router = routers.projects.register(
- r"user_interview_topics", UserInterviewTopicViewSet, "project_user_interview_topics", ["team_id"]
- )
- user_interview_topics_router.register(
- r"interviewees",
- IntervieweeContextViewSet,
- "project_user_interview_topic_interviewees",
- ["team_id", "topic_id"],
- )
diff --git a/products/user_interviews/backend/tasks/__init__.py b/products/user_interviews/backend/tasks/__init__.py
deleted file mode 100644
index 3375607ab701..000000000000
--- a/products/user_interviews/backend/tasks/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-# Re-exported so Celery autodiscovery registers the task when it imports `<app>.tasks`.
-from products.user_interviews.backend.tasks.tasks import handle_vapi_webhook # noqa: F401
diff --git a/products/user_interviews/backend/tasks/tasks.py b/products/user_interviews/backend/tasks/tasks.py
deleted file mode 100644
index f4b48be2b610..000000000000
--- a/products/user_interviews/backend/tasks/tasks.py
+++ /dev/null
@@ -1,89 +0,0 @@
-"""Celery tasks for user_interviews.
-
-``handle_vapi_webhook`` is the durable side of the inbound Vapi webhook. Ingress answers the
-request with a transport receipt that never reflects consumer work, so Vapi does not resend
-when persistence fails. The retry therefore has to live in something that outlives the request.
-"""
-
-from typing import Any
-
-from django.db import InterfaceError, OperationalError
-
-import structlog
-from celery import Task, shared_task
-
-logger = structlog.get_logger(__name__)
-
-
-def _call_id(payload: dict[str, Any]) -> str | None:
- call: dict[str, Any] = (payload.get("message") or {}).get("call") or {}
- return call.get("id")
-
-
-@shared_task(
- bind=True,
- name="products.user_interviews.backend.tasks.handle_vapi_webhook",
- ignore_result=True,
- # autoretry_for is load-bearing: bare max_retries without it is silently inert.
- autoretry_for=(OperationalError, InterfaceError),
- # Sized for a database outage, which lasts minutes to hours, while the default backoff is
- # spent in a few seconds. Vapi holds its receipt by the time the task runs and nothing else
- # replays an interview, so every attempt this policy does not make is a report lost. Each
- # attempt waits twice as long as the one before it, capped at ten minutes, which spans about
- # two and a half hours over all the attempts. Jitter spreads the workers that failed at the
- # same moment, and halves that span on average.
- retry_backoff=10,
- retry_backoff_max=600,
- retry_jitter=True,
- max_retries=20,
- # The report is the only copy of the interview, and by the time the task runs Vapi already
- # holds its receipt. A worker that dies after reserving the message would drop the report with
- # the default early acknowledgement, so the message is acknowledged after the run instead and
- # given back to the broker when the worker is lost. The handler is idempotent on the call id,
- # so the redelivered message creates nothing a second time.
- acks_late=True,
- reject_on_worker_lost=True,
-)
-def handle_vapi_webhook(
- self: Task,
- payload: dict[str, Any],
- event_type: str,
- team_id: int,
- topic_id: str,
- interviewee_context_id: str,
- interviewee_identifier: str,
- received_at: str | None = None,
-) -> None:
- """Store one verified Vapi delivery, outside the request that accepted it.
-
- ``received_at`` is the ISO time the endpoint received the delivery, and it timestamps the
- lifecycle analytics events. It has a default so that a message queued without it still runs;
- those events then carry the worker's clock instead.
- """
- from products.user_interviews.backend import ( # noqa: PLC0415 - keeps posthog.schema and the embedding worker off the task module's import path
- vapi_events,
- )
-
- try:
- vapi_events.handle_vapi_webhook_delivery(
- payload,
- event_type,
- team_id=team_id,
- topic_id=topic_id,
- interviewee_context_id=interviewee_context_id,
- interviewee_identifier=interviewee_identifier,
- received_at=received_at,
- )
- except (OperationalError, InterfaceError):
- # autoretry_for re-raises the original error once the retries run out, which reads like any
- # other failed attempt. The last attempt says that the report is now lost, and names the
- # call so the interview can be traced in Vapi.
- if self.request.retries >= self.max_retries:
- logger.exception(
- "user_interviews_vapi_webhook_retries_exhausted",
- event_type=event_type,
- call_id=_call_id(payload),
- team_id=team_id,
- topic_id=topic_id,
- )
- raise
diff --git a/products/user_interviews/backend/test_classification.py b/products/user_interviews/backend/test_classification.py
deleted file mode 100644
index 4b25c7180fae..000000000000
--- a/products/user_interviews/backend/test_classification.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from django.test import SimpleTestCase
-
-from parameterized import parameterized
-
-from products.user_interviews.backend.classification import derive_auto_classifications
-from products.user_interviews.backend.models import UserInterviewClassification
-
-
-class TestDeriveAutoClassifications(SimpleTestCase):
- @parameterized.expand(
- [
- ("empty transcript has no parseable turns", "", []),
- ("ai only, no user turn", "AI: Hi there, are you free?\n", [UserInterviewClassification.ABANDONED]),
- ("ai only multi line", "AI: Hi.\nAI: Still there?\n", [UserInterviewClassification.ABANDONED]),
- ("blank user turn is not a real turn", "AI: Hello.\nUser: \n", [UserInterviewClassification.ABANDONED]),
- (
- "lowercase ai-only prefix still abandoned",
- "ai: are you there?\n",
- [UserInterviewClassification.ABANDONED],
- ),
- ("a real exchange is not auto-classified", "AI: How was onboarding?\nUser: Fine, no complaints.", []),
- (
- "unrecognised speaker-heading format is left untagged, not abandoned",
- "#### Speaker 1\nThanks for joining today.\n#### Speaker 2\nHappy to help, this product changed how we work.",
- [],
- ),
- ]
- )
- def test_derive_auto_classifications(self, _name: str, transcript: str, expected: list[str]):
- assert derive_auto_classifications(transcript) == expected
diff --git a/products/user_interviews/backend/test_dogfood_interview_link.py b/products/user_interviews/backend/test_dogfood_interview_link.py
deleted file mode 100644
index fdbc3faf254b..000000000000
--- a/products/user_interviews/backend/test_dogfood_interview_link.py
+++ /dev/null
@@ -1,126 +0,0 @@
-from posthog.test.base import APIBaseTest
-from unittest.mock import patch
-
-from parameterized import parameterized
-from rest_framework import status
-
-from posthog.models.sharing_configuration import SharingConfiguration
-
-from products.user_interviews.backend.models import IntervieweeContext, UserInterview, UserInterviewTopic
-
-
-class _FeatureFlagEnabledMixin(APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- patcher = patch("posthoganalytics.feature_enabled", return_value=True)
- patcher.start()
- self.addCleanup(patcher.stop)
-
-
-class TestDogfoodInterviewLink(_FeatureFlagEnabledMixin):
- def _topics_url(self) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/"
-
- def _test_link_url(self, topic_id: str) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/test_link/"
-
- def _create_topic(self) -> UserInterviewTopic:
- response = self.client.post(
- self._topics_url(),
- {
- "topic": "Session replay adoption",
- "interviewee_emails": ["[email protected]"],
- "interviewee_distinct_ids": [],
- "questions": ["What blocks adoption?"],
- },
- format="json",
- )
- assert response.status_code == status.HTTP_201_CREATED, response.content
- return UserInterviewTopic.objects.get(team=self.team, id=response.json()["id"])
-
- def test_topic_creation_does_not_eagerly_seed_dogfood_context(self) -> None:
- topic = self._create_topic()
- assert not IntervieweeContext.objects.filter(team=self.team, topic=topic).exists()
-
- def test_test_link_materializes_caller_context_and_share(self) -> None:
- topic = self._create_topic()
-
- response = self.client.get(self._test_link_url(str(topic.id)))
-
- assert response.status_code == status.HTTP_200_OK, response.content
- ic = IntervieweeContext.objects.get(team=self.team, topic=topic, interviewee_identifier=self.user.email)
- assert ic.created_by_id == self.user.id
- assert SharingConfiguration.objects.filter(team=self.team, interviewee_context=ic, enabled=True).exists()
-
- def test_test_link_is_idempotent(self) -> None:
- topic = self._create_topic()
- first = self.client.get(self._test_link_url(str(topic.id))).json()
- second = self.client.get(self._test_link_url(str(topic.id))).json()
- assert first["interview_url"] == second["interview_url"]
- assert (
- IntervieweeContext.objects.filter(
- team=self.team, topic=topic, interviewee_identifier=self.user.email
- ).count()
- == 1
- )
- assert (
- SharingConfiguration.objects.filter(
- team=self.team,
- interviewee_context__topic=topic,
- interviewee_context__interviewee_identifier=self.user.email,
- ).count()
- == 1
- )
-
- def test_each_caller_gets_their_own_dogfood_context(self) -> None:
- topic = self._create_topic()
- first_response = self.client.get(self._test_link_url(str(topic.id))).json()
-
- other_user = self._create_user("[email protected]")
- self.client.force_login(other_user)
- second_response = self.client.get(self._test_link_url(str(topic.id))).json()
-
- assert first_response["interview_url"] != second_response["interview_url"]
- identifiers = set(
- IntervieweeContext.objects.filter(team=self.team, topic=topic).values_list(
- "interviewee_identifier", flat=True
- )
- )
- assert identifiers == {self.user.email, other_user.email}
-
- @parameterized.expand(
- [
- ("no_interview", None, None, None),
- ("transcript_only", "hello", "", "hello"),
- ("summary_only", "", "said hello", ""),
- ("both", "hello", "said hello", "hello"),
- ]
- )
- def test_test_link_surfaces_latest_test_interview(
- self,
- _name: str,
- transcript: str | None,
- summary: str | None,
- expected_transcript: str | None,
- ) -> None:
- topic = self._create_topic()
- # First call materializes the dogfood context so we have an identifier to attach an interview to.
- self.client.get(self._test_link_url(str(topic.id)))
- if transcript is not None:
- UserInterview.objects.create(
- team=self.team,
- created_by=self.user,
- topic=topic,
- interviewee_identifier=self.user.email,
- transcript=transcript,
- summary=summary or "",
- )
-
- latest = self.client.get(self._test_link_url(str(topic.id))).json()["latest_test_interview"]
-
- if transcript is None:
- assert latest is None
- else:
- assert latest is not None
- assert latest["transcript"] == expected_transcript
- assert latest["summary"] == (summary or "")
diff --git a/products/user_interviews/backend/test_facade.py b/products/user_interviews/backend/test_facade.py
deleted file mode 100644
index 6b72b9adf8e8..000000000000
--- a/products/user_interviews/backend/test_facade.py
+++ /dev/null
@@ -1,118 +0,0 @@
-from posthog.test.base import APIBaseTest
-
-from django.test import SimpleTestCase
-
-from parameterized import parameterized
-
-from products.user_interviews.backend.facade.api import has_replied, parse_interviewee_identifier
-from products.user_interviews.backend.facade.contracts import IntervieweeIdentity
-from products.user_interviews.backend.logic import valid_distinct_id, valid_session_id
-from products.user_interviews.backend.models import UserInterview, UserInterviewClassification, UserInterviewTopic
-
-
-class TestParseIntervieweeIdentifier(APIBaseTest):
- @parameterized.expand(
- [
- ("display+email", "Alex Smith <[email protected]>", "Alex Smith", "[email protected]"),
- ("display+email_whitespace", " Alex <[email protected]> ", "Alex", "[email protected]"),
- ("plain_email", "[email protected]", "Alex Smith", "[email protected]"),
- ("plain_email_with_underscores", "[email protected]", "Alex Smith", "[email protected]"),
- ("distinct_id", "user_abc_123", "user_abc_123", None),
- ]
- )
- def test_parses_identifier(self, _: str, identifier: str, expected_name: str, expected_email: str | None) -> None:
- assert parse_interviewee_identifier(identifier) == IntervieweeIdentity(
- display_name=expected_name, email=expected_email
- )
-
-
-class TestLinkageValidation(SimpleTestCase):
- # A UUIDv7 (version nibble 7); a UUIDv4 for the wrong-version case.
- _V7 = "018f0b7a-0000-7000-8000-000000000000"
- _V4 = "018f0b7a-0000-4000-8000-000000000000"
-
- @parameterized.expand(
- [
- ("uuid_v7", _V7, _V7),
- ("uuid_v7_trimmed", f" {_V7} ", _V7),
- ("uuid_v4_wrong_version", _V4, ""),
- ("not_a_uuid", "session-123", ""),
- ("empty", "", ""),
- ("none", None, ""),
- ]
- )
- def test_valid_session_id(self, _name: str, value: object, expected: str) -> None:
- assert valid_session_id(value) == expected
-
- @parameterized.expand(
- [
- ("normal", "user_42", "user_42"),
- ("trimmed", " user_42 ", "user_42"),
- ("illegal_sentinel", "anonymous", ""),
- ("illegal_case_insensitive", "ANONYMOUS", ""),
- ("illegal_after_trim", " guest ", ""),
- ("all_zero_uuid", "00000000-0000-0000-0000-000000000000", ""),
- ("empty", "", ""),
- ("none", None, ""),
- ("too_long", "x" * 201, ""),
- ("max_length_ok", "x" * 200, "x" * 200),
- ]
- )
- def test_valid_distinct_id(self, _name: str, value: object, expected: str) -> None:
- assert valid_distinct_id(value) == expected
-
-
-class TestHasReplied(APIBaseTest):
- def _create_topic(self) -> UserInterviewTopic:
- return UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic="MCP usage",
- )
-
- def test_false_when_no_reply(self) -> None:
- topic = self._create_topic()
- assert not has_replied(team_id=self.team.id, topic_id=topic.id, interviewee_identifier="[email protected]")
-
- def test_true_when_reply_exists(self) -> None:
- topic = self._create_topic()
- UserInterview.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- interviewee_identifier="[email protected]",
- transcript="hi",
- summary="hi",
- topic=topic,
- )
- assert has_replied(team_id=self.team.id, topic_id=topic.id, interviewee_identifier="[email protected]")
-
- def test_abandoned_reply_does_not_count(self) -> None:
- # An accidental refresh mid-call leaves an abandoned partial behind. Treating that as
- # "replied" would lock the interviewee out of ever finishing — so it must not count.
- topic = self._create_topic()
- UserInterview.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- interviewee_identifier="[email protected]",
- transcript="",
- topic=topic,
- classifications=[UserInterviewClassification.ABANDONED],
- )
- assert not has_replied(team_id=self.team.id, topic_id=topic.id, interviewee_identifier="[email protected]")
-
- def test_scoped_by_team(self) -> None:
- topic = self._create_topic()
- other_team = self.organization.teams.create(name="other team")
- UserInterview.objects.create(
- team=topic.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- interviewee_identifier="[email protected]",
- transcript="hi",
- summary="hi",
- topic=topic,
- )
- assert not has_replied(team_id=other_team.id, topic_id=topic.id, interviewee_identifier="[email protected]")
diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.py
deleted file mode 100644
index 4a1340fa1df3..000000000000
--- a/products/user_interviews/backend/test_interview_sharing.py
+++ /dev/null
@@ -1,1625 +0,0 @@
-import io
-import csv
-import hmac
-import json
-import hashlib
-import datetime
-from collections.abc import Callable
-from typing import Any
-
-import unittest
-import time_machine
-from posthog.test.base import APIBaseTest
-from unittest.mock import Mock, patch
-
-from django.core.cache import cache
-from django.db import InterfaceError, OperationalError, connection
-from django.db.models import QuerySet
-from django.template.loader import get_template
-from django.test import SimpleTestCase, override_settings
-from django.test.utils import CaptureQueriesContext
-from django.utils import timezone
-
-import kombu.exceptions
-from parameterized import parameterized
-from rest_framework import status
-from rest_framework.exceptions import PermissionDenied
-
-from posthog.api.sharing import check_can_access_sharing_configuration
-from posthog.api.test.test_sharing import mock_exporter_template
-from posthog.models.sharing_configuration import SharingConfiguration
-from posthog.rate_limit import VapiWebhookIPThrottle
-
-from products.user_interviews.backend.models import IntervieweeContext, UserInterview, UserInterviewTopic
-from products.user_interviews.backend.presentation.webhooks import (
- DEFAULT_FIRST_MESSAGE_TEMPLATE,
- FIRST_MESSAGE_PROMPT_NAME,
- _build_first_message,
- _create_vapi_web_call,
- _resolve_first_message_template,
-)
-from products.user_interviews.backend.tasks.tasks import handle_vapi_webhook
-from products.user_interviews.backend.vapi_events import EMBEDDING_CONTENT_MAX_BYTES
-
-
-def _mock_web_call(assistant_overrides: dict[str, Any]) -> dict[str, Any]:
- return {"webCallUrl": "https://daily.example/call", "id": "call_test"}
-
-
-class TestCreateVapiWebCall(SimpleTestCase):
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- @patch("products.user_interviews.backend.presentation.webhooks.vapi_request")
- def test_creates_call_server_side_and_returns_only_join_fields(self, mock_request: Mock) -> None:
- response = Mock(status_code=201)
- response.json.return_value = {
- "id": "call_123",
- "webCallUrl": "https://daily.example/call",
- "assistant": {"id": "asst_test", "secret": "not-for-browser"},
- "artifactPlan": {"videoRecordingEnabled": False},
- }
- mock_request.return_value = response
- overrides = {"metadata": {"sharing_access_token": "share-token"}}
-
- web_call = _create_vapi_web_call(overrides)
-
- assert web_call == {
- "id": "call_123",
- "webCallUrl": "https://daily.example/call",
- "artifactPlan": {"videoRecordingEnabled": False},
- }
- assert mock_request.call_args.kwargs["api_token"] == "pk_test"
- assert mock_request.call_args.kwargs["json"] == {
- "assistantId": "asst_test",
- "assistantOverrides": overrides,
- "roomDeleteOnUserLeaveEnabled": True,
- }
-
-
-class _FeatureFlagEnabledMixin(APIBaseTest):
- """Auto-mock `posthoganalytics.feature_enabled` so flag-gated viewsets accept calls in tests."""
-
- def setUp(self) -> None:
- super().setUp()
- patcher = patch("posthoganalytics.feature_enabled", return_value=True)
- patcher.start()
- self.addCleanup(patcher.stop)
-
-
-class TestGenerateInterviewLinks(_FeatureFlagEnabledMixin):
- def _create_topic(self, **overrides) -> UserInterviewTopic:
- defaults: dict = {
- "team": self.team,
- "created_by": self.user,
- "interviewee_emails": ["Alex <[email protected]>", "[email protected]"],
- "interviewee_distinct_ids": ["distinct-abc"],
- "topic": "Session replay adoption",
- "agent_context": "Researching adoption of session replay",
- "questions": ["What blocks adoption?"],
- }
- defaults.update(overrides)
- return UserInterviewTopic.objects.create(**defaults)
-
- def _generate_links_url(self, topic_id: str) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/generate_links/"
-
- def test_generate_links_materializes_contexts_and_sharing_configs(self):
- topic = self._create_topic()
-
- response = self.client.post(self._generate_links_url(str(topic.id)))
-
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- body = response.json()
- identifiers = sorted(link["interviewee_identifier"] for link in body)
- self.assertEqual(
- identifiers,
- sorted(["Alex <[email protected]>", "[email protected]", "distinct-abc"]),
- )
-
- for link in body:
- self.assertTrue(link["interview_url"].endswith(link["interview_url"].rsplit("/", 1)[-1]))
- self.assertIn("/interview/", link["interview_url"])
-
- self.assertEqual(IntervieweeContext.objects.filter(topic=topic).count(), 3)
- self.assertEqual(
- SharingConfiguration.objects.filter(team=self.team, interviewee_context__topic=topic, enabled=True).count(),
- 3,
- )
-
- def test_generate_links_is_idempotent(self):
- topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])
- first = self.client.post(self._generate_links_url(str(topic.id))).json()
- second = self.client.post(self._generate_links_url(str(topic.id))).json()
- self.assertEqual(first[0]["interview_url"], second[0]["interview_url"])
- self.assertEqual(IntervieweeContext.objects.filter(topic=topic).count(), 1)
- self.assertEqual(SharingConfiguration.objects.filter(interviewee_context__topic=topic).count(), 1)
-
- def test_generate_links_preserves_existing_personal_context(self):
- topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])
- IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="[email protected]",
- agent_context="heavy user, churned last quarter",
- created_by=self.user,
- )
- response = self.client.post(self._generate_links_url(str(topic.id)))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- link = response.json()[0]
- self.assertIn("heavy user, churned last quarter", link["agent_context"])
- self.assertIn("Researching adoption of session replay", link["agent_context"])
-
- def test_generate_links_rejects_topic_with_no_identifiers(self):
- topic = self._create_topic(interviewee_emails=[], interviewee_distinct_ids=[])
- response = self.client.post(self._generate_links_url(str(topic.id)))
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-
- def _generate_links_csv_url(self, topic_id: str) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/links_csv/"
-
- def test_generate_links_csv_returns_csv_with_expected_columns_and_rows(self):
- topic = self._create_topic()
-
- response = self.client.post(self._generate_links_csv_url(str(topic.id)))
-
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- self.assertTrue(response["Content-Type"].startswith("text/csv"))
- self.assertIn("attachment", response["Content-Disposition"])
- self.assertIn(".csv", response["Content-Disposition"])
-
- reader = csv.DictReader(io.StringIO(response.content.decode("utf-8")))
- self.assertEqual(
- reader.fieldnames,
- ["interviewee_identifier", "interviewee_email", "user_name", "interview_url"],
- )
- rows = list(reader)
- # One row per targeted interviewee (3 in the default _create_topic).
- self.assertEqual(len(rows), 3)
- # Email column is empty for distinct-id-only rows; URL column always populated.
- for row in rows:
- self.assertIn("/interview/", row["interview_url"])
-
- def test_generate_links_csv_rejects_topic_with_no_identifiers(self):
- topic = self._create_topic(interviewee_emails=[], interviewee_distinct_ids=[])
- response = self.client.post(self._generate_links_csv_url(str(topic.id)))
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-
- def test_generate_links_csv_sanitizes_formula_injection_without_breaking_emails(self):
- topic = self._create_topic(
- interviewee_emails=["[email protected]"],
- # Deliberately craft a malicious distinct ID starting with `=` — must be quoted.
- interviewee_distinct_ids=["=cmd|/c calc!A1"],
- )
- response = self.client.post(self._generate_links_csv_url(str(topic.id)))
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
-
- body = response.content.decode("utf-8")
- # Plain email is untouched (first char is a letter, not a formula trigger).
- self.assertIn("[email protected]", body)
- self.assertNotIn("'[email protected]", body)
- # Formula-injection identifier is prefixed with a single quote.
- self.assertIn("'=cmd|/c calc!A1", body)
-
- def test_generate_links_csv_is_idempotent_with_existing_links(self):
- topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])
- # Materialize via the JSON endpoint first; the CSV endpoint must return the same access token.
- json_body = self.client.post(self._generate_links_url(str(topic.id))).json()
- expected_url = json_body[0]["interview_url"]
-
- csv_response = self.client.post(self._generate_links_csv_url(str(topic.id)))
- self.assertEqual(csv_response.status_code, status.HTTP_200_OK)
- self.assertIn(expected_url, csv_response.content.decode("utf-8"))
- self.assertEqual(SharingConfiguration.objects.filter(interviewee_context__topic=topic).count(), 1)
-
-
-class TestUserInterviewTopicCreate(_FeatureFlagEnabledMixin):
- def _url(self) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/"
-
- @parameterized.expand(
- [
- ("no_targeting", {}),
- ("empty_lists", {"interviewee_emails": [], "interviewee_distinct_ids": []}),
- ]
- )
- def test_accepts_topic_without_identifiers(self, _name: str, targeting: dict[str, Any]):
- # A zero-target topic is valid — it backs a non-personalised (shared) link for anonymous
- # visitors we have no contact details for. Targets can be added later for personalised links.
- payload = {"topic": "Why people churn", **targeting}
- response = self.client.post(self._url(), data=payload, format="json")
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
-
- @parameterized.expand(
- [
- ("emails_only", {"interviewee_emails": ["[email protected]"]}),
- ("distinct_ids_only", {"interviewee_distinct_ids": ["distinct-abc"]}),
- (
- "both",
- {"interviewee_emails": ["[email protected]"], "interviewee_distinct_ids": ["distinct-abc"]},
- ),
- ]
- )
- def test_accepts_topic_with_identifiers(self, _name: str, targeting: dict[str, Any]):
- payload = {"topic": "Why people churn", **targeting}
- response = self.client.post(self._url(), data=payload, format="json")
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
-
-
-class TestUserInterviewTopicEdit(_FeatureFlagEnabledMixin):
- def _topic(self, **overrides) -> UserInterviewTopic:
- defaults: dict = {
- "team": self.team,
- "created_by": self.user,
- "interviewee_emails": ["[email protected]"],
- "interviewee_distinct_ids": ["distinct-abc"],
- "topic": "Adoption",
- "agent_context": "ctx",
- "questions": ["q1"],
- }
- defaults.update(overrides)
- return UserInterviewTopic.objects.create(**defaults)
-
- def _detail_url(self, topic_id: str) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/"
-
- def _add_url(self, topic_id: str) -> str:
- return f"{self._detail_url(topic_id)}add_interviewee/"
-
- def _remove_url(self, topic_id: str) -> str:
- return f"{self._detail_url(topic_id)}remove_interviewee/"
-
- @parameterized.expand(
- [
- ("plain_email", "[email protected]", "interviewee_emails"),
- ("display_name_email", "Jordan Doe <[email protected]>", "interviewee_emails"),
- ("distinct_id", "distinct-xyz", "interviewee_distinct_ids"),
- ]
- )
- def test_add_interviewee_routes_to_correct_array(self, _name: str, identifier: str, expected_field: str):
- topic = self._topic()
- response = self.client.post(self._add_url(str(topic.id)), data={"identifier": identifier}, format="json")
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- topic.refresh_from_db()
- assert identifier in getattr(topic, expected_field), (identifier, expected_field, response.json())
-
- def test_add_interviewee_is_idempotent(self):
- topic = self._topic(interviewee_emails=[])
- first = self.client.post(self._add_url(str(topic.id)), data={"identifier": "[email protected]"}, format="json")
- second = self.client.post(self._add_url(str(topic.id)), data={"identifier": "[email protected]"}, format="json")
- self.assertEqual(first.status_code, status.HTTP_200_OK, first.content)
- self.assertEqual(second.status_code, status.HTTP_200_OK, second.content)
- topic.refresh_from_db()
- assert topic.interviewee_emails == ["[email protected]"], topic.interviewee_emails
-
- def test_remove_interviewee_drops_from_both_arrays(self):
- topic = self._topic(
- interviewee_emails=["[email protected]", "[email protected]"],
- interviewee_distinct_ids=["distinct-abc"],
- )
- response = self.client.post(
- self._remove_url(str(topic.id)), data={"identifier": "[email protected]"}, format="json"
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- topic.refresh_from_db()
- assert topic.interviewee_emails == ["[email protected]"], topic.interviewee_emails
- assert topic.interviewee_distinct_ids == ["distinct-abc"], topic.interviewee_distinct_ids
-
- def test_remove_interviewee_disables_active_sharing_configurations(self):
- topic = self._topic()
- ic = IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="[email protected]",
- agent_context="",
- created_by=self.user,
- )
- share = SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)
- self.client.post(self._remove_url(str(topic.id)), data={"identifier": "[email protected]"}, format="json")
- share.refresh_from_db()
- assert share.enabled is False
-
- def test_remove_interviewee_is_noop_for_unknown_identifier(self):
- topic = self._topic()
- response = self.client.post(
- self._remove_url(str(topic.id)), data={"identifier": "[email protected]"}, format="json"
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- topic.refresh_from_db()
- assert topic.interviewee_emails == ["[email protected]"], topic.interviewee_emails
-
- def test_partial_update_changes_topic_text(self):
- topic = self._topic()
- response = self.client.patch(self._detail_url(str(topic.id)), data={"topic": "New angle"}, format="json")
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- topic.refresh_from_db()
- assert topic.topic == "New angle"
-
- def test_partial_update_can_clear_all_targeting_for_shared_only_topic(self):
- # Zero-target topics are valid — a shared (non-personalised) link needs no pre-seeded
- # interviewees — so clearing all targeting must be allowed, not rejected.
- topic = self._topic()
- response = self.client.patch(
- self._detail_url(str(topic.id)),
- data={"interviewee_emails": [], "interviewee_distinct_ids": []},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- topic.refresh_from_db()
- assert topic.interviewee_emails == []
- assert topic.interviewee_distinct_ids == []
-
- def test_partial_update_revokes_shares_for_removed_identifiers(self):
- topic = self._topic(interviewee_emails=["[email protected]", "[email protected]"])
- ic = IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="[email protected]",
- agent_context="",
- created_by=self.user,
- )
- share = SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)
- response = self.client.patch(
- self._detail_url(str(topic.id)),
- data={"interviewee_emails": ["[email protected]"]},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- share.refresh_from_db()
- assert share.enabled is False
-
- def test_remove_interviewee_revokes_shares_even_when_identifier_already_absent(self):
- topic = self._topic(interviewee_emails=["[email protected]"])
- ic = IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="[email protected]",
- agent_context="",
- created_by=self.user,
- )
- share = SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)
- response = self.client.post(
- self._remove_url(str(topic.id)), data={"identifier": "[email protected]"}, format="json"
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- share.refresh_from_db()
- assert share.enabled is False
-
- def test_add_interviewee_rejects_overlong_email_identifier(self):
- topic = self._topic()
- long_email = "a" * 250 + "@example.com"
- assert len(long_email) > 254
- response = self.client.post(self._add_url(str(topic.id)), data={"identifier": long_email}, format="json")
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-
-
-class TestInterviewPublicViewer(APIBaseTest):
- def _create_share(self) -> SharingConfiguration:
- topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic="Session replay adoption",
- agent_context="adoption research",
- questions=["q1"],
- )
- ic = IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="[email protected]",
- agent_context="heavy user",
- created_by=self.user,
- )
- return SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- @mock_exporter_template
- def test_public_viewer_renders_interview_payload_without_agent_context(self):
- share = self._create_share()
- self.client.logout()
- response = self.client.get(f"/interview/{share.access_token}")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- body = response.content.decode()
- # The exporter payload is JSON-encoded inside a JSON script tag, so escaped keys appear.
- # We render: type=interview, topic name, access token. We do NOT render the agent
- # context, the questions, or the Vapi credentials — those live behind /start_call/.
- self.assertIn("interview", body)
- self.assertIn(share.access_token, body)
- self.assertIn("Session replay adoption", body)
- self.assertNotIn("heavy user", body)
- self.assertNotIn("adoption research", body)
- self.assertNotIn("pk_test", body)
- self.assertNotIn("asst_test", body)
-
- def test_public_viewer_rejects_disabled_share(self):
- share = self._create_share()
- share.enabled = False
- share.save()
- self.client.logout()
- response = self.client.get(f"/interview/{share.access_token}")
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
-
-class TestBuildFirstMessage(unittest.TestCase):
- @parameterized.expand(
- [
- ("simple_name_and_topic", "Paul", "taxonomic filter search", ["Hey Paul!", "taxonomic filter search"]),
- ("dotted_local_part", "Cory S", "session replay adoption", ["Hey Cory S!", "session replay adoption"]),
- (
- "name_with_trailing_topic_whitespace",
- "Kim",
- " feature flag rollout ",
- ["Hey Kim!", "feature flag rollout"],
- ),
- ]
- )
- def test_includes_name_and_topic(self, _label: str, user_name: str, topic_text: str, expected_fragments: list[str]):
- message = _build_first_message(DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name=user_name, topic_text=topic_text)
- for fragment in expected_fragments:
- assert fragment in message
-
- @parameterized.expand([("empty", ""), ("whitespace_only", " ")])
- def test_falls_back_to_generic_topic_when_topic_empty(self, _label: str, topic_text: str):
- message = _build_first_message(DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name="Sam", topic_text=topic_text)
- assert "Hey Sam!" in message
- assert "your experience" in message
-
- @parameterized.expand([("empty", ""), ("whitespace_only", " ")])
- def test_falls_back_to_generic_greeting_when_user_name_empty(self, _label: str, user_name: str):
- message = _build_first_message(
- DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name=user_name, topic_text="checkout funnel"
- )
- assert "Hey there!" in message
- assert "Hey !" not in message
-
- def test_collapses_internal_whitespace_in_topic(self):
- message = _build_first_message(
- DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name="Sam", topic_text="multi\nline\n\ttopic"
- )
- assert "multi line topic" in message
- assert "\n" not in message
-
- def test_truncates_very_long_topic(self):
- long_topic = "x" * 500
- message = _build_first_message(DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name="Sam", topic_text=long_topic)
- assert "x" * 200 in message
- assert "x" * 201 not in message
-
- def test_uses_custom_template_when_provided(self):
- custom = "Hi $user_name, today's topic: $topic_text."
- message = _build_first_message(custom, user_name="Paul", topic_text="onboarding")
- assert message == "Hi Paul, today's topic: onboarding."
-
- def test_falls_back_to_default_when_custom_template_missing_placeholder(self):
- broken = "Hi $nonsense, today is $missing_field."
- message = _build_first_message(broken, user_name="Paul", topic_text="onboarding")
- assert "Hey Paul!" in message
- assert "onboarding" in message
-
- def test_format_spec_in_template_is_treated_as_literal_text(self):
- # string.Template has no format-spec syntax, so an attacker cannot use
- # `{user_name:>10000000000}` to allocate gigabytes — `:` is just a character.
- attempted = "Hi $user_name, padded: {user_name:>10000000000}"
- message = _build_first_message(attempted, user_name="Paul", topic_text="onboarding")
- assert "Hi Paul" in message
- assert len(message) <= 1000
-
- def test_falls_back_to_default_when_rendered_message_exceeds_cap(self):
- huge = "Hi $user_name! " + ("x" * 2000)
- message = _build_first_message(huge, user_name="Paul", topic_text="onboarding")
- assert "Hey Paul!" in message
- assert "onboarding" in message
- assert len(message) <= 1000
-
- def test_return_value_is_always_bounded_even_with_long_user_name(self):
- message = _build_first_message(DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name="x" * 5000, topic_text="onboarding")
- assert len(message) <= 1000
-
-
-class TestResolveFirstMessageTemplate(APIBaseTest):
- def test_returns_default_when_no_prompt_configured(self):
- template = _resolve_first_message_template(self.team)
- assert template == DEFAULT_FIRST_MESSAGE_TEMPLATE
-
- def test_returns_team_override_when_prompt_published(self):
- from products.ai_observability.backend.models.llm_prompt import LLMPrompt
-
- LLMPrompt.objects.create(
- team=self.team,
- name=FIRST_MESSAGE_PROMPT_NAME,
- prompt="Hey $user_name! Quick chat about $topic_text?",
- version=1,
- is_latest=True,
- created_by=self.user,
- )
- template = _resolve_first_message_template(self.team)
- assert template == "Hey $user_name! Quick chat about $topic_text?"
-
- def test_returns_default_when_published_prompt_is_empty(self):
- from products.ai_observability.backend.models.llm_prompt import LLMPrompt
-
- LLMPrompt.objects.create(
- team=self.team,
- name=FIRST_MESSAGE_PROMPT_NAME,
- prompt=" ",
- version=1,
- is_latest=True,
- created_by=self.user,
- )
- template = _resolve_first_message_template(self.team)
- assert template == DEFAULT_FIRST_MESSAGE_TEMPLATE
-
-
-class TestInterviewStartCall(APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- patcher = patch(
- "products.user_interviews.backend.presentation.webhooks._create_vapi_web_call",
- side_effect=_mock_web_call,
- )
- self.create_vapi_web_call = patcher.start()
- self.addCleanup(patcher.stop)
-
- def _create_share(self) -> SharingConfiguration:
- topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic="Replay adoption",
- agent_context="adoption research",
- questions=["What blocks you?"],
- )
- ic = IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="[email protected]",
- agent_context="heavy user, churned last quarter",
- created_by=self.user,
- )
- return SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_returns_merged_assistant_overrides(self):
- share = self._create_share()
- self.client.logout()
- response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- body = response.json()
- self.assertEqual(body, {"web_call": {"webCallUrl": "https://daily.example/call", "id": "call_test"}})
- overrides = self.create_vapi_web_call.call_args.args[0]
- # Merged agent_context combines topic-level and per-person notes.
- self.assertIn("adoption research", overrides["variableValues"]["agent_context"])
- self.assertIn("heavy user, churned last quarter", overrides["variableValues"]["agent_context"])
- self.assertEqual(overrides["metadata"]["sharing_access_token"], share.access_token)
- self.assertEqual(overrides["metadata"]["interviewee_identifier"], "[email protected]")
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_returns_scoped_server_messages(self):
- share = self._create_share()
- self.client.logout()
- response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- overrides = self.create_vapi_web_call.call_args.args[0]
- # Scoped to the two lifecycle events we act on — keeps Vapi from sending
- # speech-update / conversation-update / etc that we'd just ignore.
- self.assertEqual(overrides["serverMessages"], ["status-update", "end-of-call-report"])
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_returns_personalised_first_message(self):
- share = self._create_share()
- self.client.logout()
- response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
- assert response.status_code == status.HTTP_200_OK, response.content
- first_message = self.create_vapi_web_call.call_args.args[0]["firstMessage"]
- assert "Hey Alex!" in first_message
- assert "Replay adoption" in first_message
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_rejects_disabled_share(self):
- share = self._create_share()
- share.enabled = False
- share.save()
- self.client.logout()
- response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
- @override_settings(VAPI_PUBLIC_KEY="", VAPI_ASSISTANT_ID="")
- def test_503_when_vapi_unconfigured(self):
- share = self._create_share()
- self.client.logout()
- response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
- self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_returns_questions_as_json_not_python_repr(self):
- share = self._create_share()
- self.client.logout()
- self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
- questions_raw = self.create_vapi_web_call.call_args.args[0]["variableValues"]["questions"]
- # The Vapi assistant prompt receives this string verbatim; it must parse as JSON,
- # not Python repr (which would be `['What blocks you?']` with single quotes).
- self.assertEqual(json.loads(questions_raw), ["What blocks you?"])
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_rejects_when_org_disables_public_sharing(self):
- share = self._create_share()
- org = share.team.organization
- # Pretend the org has the enterprise security feature and has disabled public shares.
- org.available_product_features = [{"key": "organization_security_settings", "name": "Org security"}]
- org.allow_publicly_shared_resources = False
- org.save()
- self.client.logout()
- response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
- @time_machine.travel("2026-05-14 12:00:00", tick=False)
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_rejects_expired_rotated_token(self):
- # Simulate the post-grace-period state of a rotated SharingConfiguration:
- # `expires_at` in the past, still `enabled=True`. The public viewer 404s on these,
- # and start_call must do the same — otherwise the rotated token is still valid here.
- share = self._create_share()
- share.expires_at = timezone.now() - datetime.timedelta(minutes=1)
- share.save()
- self.client.logout()
- response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
-
-class TestVapiWebhook(APIBaseTest):
- def _create_share(self) -> SharingConfiguration:
- topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic="Replay adoption",
- agent_context="ctx",
- questions=[],
- )
- ic = IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="[email protected]",
- agent_context="",
- created_by=self.user,
- )
- return SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)
-
- def _end_of_call_payload(
- self, access_token: str | None, call_id: str = "call_abc", metadata_path: str = "top"
- ) -> dict:
- # Vapi can surface our `assistant_overrides.metadata` either at `call.metadata`
- # (top-level) or `call.assistantOverrides.metadata` (nested). The handler must
- # find it in either path; parameterised tests cover both.
- if metadata_path == "nested":
- call: dict[str, Any] = {
- "id": call_id,
- "assistantOverrides": {"metadata": {"sharing_access_token": access_token}},
- "duration": 120,
- }
- else:
- call = {
- "id": call_id,
- "metadata": {"sharing_access_token": access_token},
- "duration": 120,
- }
- return {
- "message": {
- "type": "end-of-call-report",
- "call": call,
- "transcript": "Hi! ...",
- "summary": "User talked about replay.",
- "recording": {"url": "https://vapi.example/recording.mp3"},
- }
- }
-
- def _signed_post(self, secret: str, payload: dict) -> Any:
- body = json.dumps(payload)
- signature = hmac.new(secret.encode(), body.encode(), hashlib.sha256).hexdigest()
- return self.client.post(
- "/api/user_interviews/vapi_webhook/",
- data=body,
- content_type="application/json",
- HTTP_X_VAPI_SIGNATURE=signature,
- )
-
- @parameterized.expand([("top",), ("nested",)])
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_webhook_creates_user_interview(self, metadata_path: str):
- share = self._create_share()
- self.client.logout()
- response = self._signed_post(
- "topsecret",
- self._end_of_call_payload(share.access_token, metadata_path=metadata_path),
- )
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
- interview = UserInterview.objects.get(team=self.team)
- assert share.interviewee_context is not None
- self.assertEqual(interview.topic, share.interviewee_context.topic)
- self.assertEqual(interview.interviewee_identifier, "[email protected]")
- self.assertEqual(interview.recording_url, "https://vapi.example/recording.mp3")
- self.assertEqual(interview.transcript, "Hi! ...")
-
- @time_machine.travel("2026-05-14 12:00:00", tick=False)
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.tasks.tasks.handle_vapi_webhook.delay")
- def test_webhook_hands_the_report_to_a_task(self, mock_delay):
- share = self._create_share()
- self.client.logout()
- payload = self._end_of_call_payload(share.access_token)
- response = self._signed_post("topsecret", payload)
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
- assert share.interviewee_context is not None
- mock_delay.assert_called_once_with(
- payload=payload,
- event_type="end-of-call-report",
- team_id=self.team.pk,
- topic_id=str(share.interviewee_context.topic_id),
- interviewee_context_id=str(share.interviewee_context_id),
- interviewee_identifier="[email protected]",
- received_at=timezone.now().isoformat(),
- )
- self.assertEqual(UserInterview.objects.count(), 0)
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_webhook_serializes_persistence_per_call_id(self):
- # No unique constraint keeps a call to one row, so two runs that overlap have to queue
- # behind an advisory lock on the call id instead of both passing the existence check.
- share = self._create_share()
- self.client.logout()
- with CaptureQueriesContext(connection) as queries:
- response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token, call_id="call_xyz"))
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
-
- statements = [query["sql"] for query in queries.captured_queries]
- locks = [index for index, sql in enumerate(statements) if "pg_advisory_xact_lock" in sql]
- inserts = [index for index, sql in enumerate(statements) if "INSERT INTO" in sql and "userinterview" in sql]
- self.assertEqual(len(locks), 1)
- self.assertIn(f"user_interviews_vapi_call:{self.team.id}:call_xyz", statements[locks[0]])
- self.assertTrue(inserts)
- self.assertLess(locks[0], inserts[0])
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
- @patch("products.user_interviews.backend.tasks.tasks.handle_vapi_webhook.delay")
- def test_lifecycle_event_carries_the_delivery_time_not_the_run_time(self, mock_delay, mock_scoped_capture):
- mock_capture = mock_scoped_capture.return_value.__enter__.return_value
- share = self._create_share()
- self.client.logout()
- received_at = datetime.datetime(2026, 5, 14, 12, 0, tzinfo=datetime.UTC)
- with time_machine.travel(received_at, tick=False) as clock:
- accepted = self._signed_post(
- "topsecret",
- {
- "message": {
- "type": "status-update",
- "status": "in-progress",
- "call": {"id": "call_xyz", "metadata": {"sharing_access_token": share.access_token}},
- }
- },
- )
- self.assertEqual(accepted.status_code, status.HTTP_202_ACCEPTED, accepted.content)
- clock.move_to(received_at + datetime.timedelta(minutes=10))
- handle_vapi_webhook(**mock_delay.call_args.kwargs)
-
- mock_capture.assert_called_once()
- self.assertEqual(mock_capture.call_args.kwargs["timestamp"], received_at.isoformat())
-
- @parameterized.expand(
- [
- ("share_disabled", lambda shares: shares.update(enabled=False)),
- (
- "token_past_its_grace_period",
- lambda shares: shares.update(expires_at=timezone.now() - datetime.timedelta(minutes=1)),
- ),
- ("share_row_deleted", lambda shares: shares.delete()),
- ]
- )
- @time_machine.travel("2026-05-14 12:00:00", tick=False)
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.tasks.tasks.handle_vapi_webhook.delay")
- def test_report_is_stored_when_the_share_stops_answering_after_the_endpoint_accepted_it(
- self, _name: str, revoke: Callable[[QuerySet[SharingConfiguration]], Any], mock_delay
- ):
- share = self._create_share()
- self.client.logout()
- accepted = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
- self.assertEqual(accepted.status_code, status.HTTP_202_ACCEPTED, accepted.content)
-
- # revoke is a callable so the expiry it writes is computed here, under the frozen clock
- # above, instead of at parameterized.expand's module-import time. Deleting the row is what
- # cleanup_expired_sharing_configs does to a share once its token is past the grace period.
- revoke(SharingConfiguration.objects.filter(pk=share.pk, team_id=self.team.pk))
- handle_vapi_webhook(**mock_delay.call_args.kwargs)
-
- self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)
-
- def test_report_task_survives_a_database_error_and_a_lost_worker(self):
- # Both settings are silently inert when missing: max_retries without autoretry_for never
- # retries, and the default early acknowledgement drops the report when the worker dies.
- self.assertEqual(handle_vapi_webhook.autoretry_for, (OperationalError, InterfaceError))
- self.assertTrue(handle_vapi_webhook.acks_late)
- self.assertTrue(handle_vapi_webhook.reject_on_worker_lost)
- # The default backoff spends every attempt within seconds, which is shorter than any
- # database outage worth retrying through, and Vapi never resends the report.
- window_seconds = sum(
- min(handle_vapi_webhook.retry_backoff * 2**attempt, handle_vapi_webhook.retry_backoff_max)
- for attempt in range(handle_vapi_webhook.max_retries)
- )
- self.assertGreater(window_seconds, 60 * 60)
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.tasks.tasks.handle_vapi_webhook.delay")
- def test_webhook_asks_for_a_resend_when_the_report_reaches_no_queue(self, mock_delay):
- share = self._create_share()
- self.client.logout()
- payload = self._end_of_call_payload(share.access_token)
-
- mock_delay.side_effect = kombu.exceptions.OperationalError("broker unreachable")
- refused = self._signed_post("topsecret", payload)
- self.assertEqual(refused.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR, refused.content)
- self.assertEqual(UserInterview.objects.count(), 0)
-
- mock_delay.side_effect = lambda **kwargs: handle_vapi_webhook(**kwargs)
- resent = self._signed_post("topsecret", payload)
- self.assertEqual(resent.status_code, status.HTTP_202_ACCEPTED, resent.content)
- self.assertEqual(UserInterview.objects.count(), 1)
-
- @parameterized.expand(
- [
- ("under_the_rate", 0, status.HTTP_202_ACCEPTED),
- ("over_the_rate", 1, status.HTTP_429_TOO_MANY_REQUESTS),
- ]
- )
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch.object(VapiWebhookIPThrottle, "rate", "1/minute")
- def test_webhook_caps_deliveries_from_one_ip(self, _name: str, already_spent: int, expected_status: int):
- # The cap is the provider's `throttle_class`, so this also pins that the ingress lane
- # actually runs it: a provider that dropped the attribute would answer 202 to both.
- cache.clear()
- share = self._create_share()
- self.client.logout()
- for _ in range(already_spent):
- self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
-
- response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
-
- self.assertEqual(response.status_code, expected_status, response.content)
- if expected_status == status.HTTP_429_TOO_MANY_REQUESTS:
- self.assertGreater(int(response.headers["Retry-After"]), 0)
- else:
- self.assertNotIn("Retry-After", response.headers)
-
- @override_settings(VAPI_WEBHOOK_SECRET="")
- def test_webhook_fails_closed_when_secret_unset(self):
- share = self._create_share()
- self.client.logout()
- response = self.client.post(
- "/api/user_interviews/vapi_webhook/",
- data=self._end_of_call_payload(share.access_token),
- content_type="application/json",
- )
- self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
- self.assertEqual(UserInterview.objects.count(), 0)
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.tasks.tasks.handle_vapi_webhook.delay")
- def test_webhook_rejects_unknown_token(self, mock_delay):
- self.client.logout()
- response = self._signed_post("topsecret", self._end_of_call_payload("does-not-exist"))
- # The receipt is the transport's, so an unknown token is only observable as nothing stored.
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
- self.assertEqual(UserInterview.objects.count(), 0)
- mock_delay.assert_not_called()
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_webhook_requires_valid_signature(self):
- share = self._create_share()
- self.client.logout()
- response = self.client.post(
- "/api/user_interviews/vapi_webhook/",
- data=self._end_of_call_payload(share.access_token),
- content_type="application/json",
- HTTP_X_VAPI_SIGNATURE="a" * 64, # right shape, wrong value
- )
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
-
- @parameterized.expand(
- [
- ("missing", None),
- ("empty", ""),
- ("too_short", "abc"),
- ("non_hex", "z" * 64),
- ("uppercase", "A" * 64),
- ]
- )
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_webhook_rejects_malformed_signature_pre_hmac(self, _name: str, value: Any):
- share = self._create_share()
- self.client.logout()
- kwargs: dict[str, Any] = {
- "data": self._end_of_call_payload(share.access_token),
- "content_type": "application/json",
- }
- if value is not None:
- kwargs["HTTP_X_VAPI_SIGNATURE"] = value
- response = self.client.post("/api/user_interviews/vapi_webhook/", **kwargs)
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_webhook_ignores_unknown_message_types(self):
- self.client.logout()
- response = self._signed_post("topsecret", {"message": {"type": "speech-update"}})
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
- self.assertEqual(UserInterview.objects.count(), 0)
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
- def test_webhook_status_update_in_progress_captures_started_event(self, mock_scoped_capture):
- mock_capture = mock_scoped_capture.return_value.__enter__.return_value
- share = self._create_share()
- self.client.logout()
- response = self._signed_post(
- "topsecret",
- {
- "message": {
- "type": "status-update",
- "status": "in-progress",
- "call": {"id": "call_xyz", "metadata": {"sharing_access_token": share.access_token}},
- }
- },
- )
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
- mock_capture.assert_called_once()
- kwargs = mock_capture.call_args.kwargs
- self.assertEqual(kwargs["event"], "user_interview_conversation_started")
- # distinct_id is intentionally an opaque interviewee_context UUID — not the
- # email — so these feature-usage events don't create person profiles for the
- # third-party interviewees.
- assert share.interviewee_context is not None
- self.assertEqual(kwargs["distinct_id"], f"user_interview:{share.interviewee_context.id}")
- self.assertNotIn("[email protected]", kwargs["distinct_id"])
- self.assertEqual(kwargs["properties"]["call_id"], "call_xyz")
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
- def test_webhook_status_update_duplicate_in_progress_emits_same_insert_id(self, mock_scoped_capture):
- # Vapi re-fires `status-update / in-progress` on transient drops + warm-transfer flows.
- # We tag every started event with `$insert_id` = "user_interview_conversation_started:<call_id>"
- # so PostHog dedupes the second delivery at ingest. Both captures fire here (we don't
- # de-dup client-side); the contract is that they share an insert_id.
- mock_capture = mock_scoped_capture.return_value.__enter__.return_value
- share = self._create_share()
- self.client.logout()
- payload = {
- "message": {
- "type": "status-update",
- "status": "in-progress",
- "call": {"id": "call_xyz", "metadata": {"sharing_access_token": share.access_token}},
- }
- }
- self._signed_post("topsecret", payload)
- self._signed_post("topsecret", payload)
- self.assertEqual(mock_capture.call_count, 2)
- for call in mock_capture.call_args_list:
- self.assertEqual(call.kwargs["properties"]["$insert_id"], "user_interview_conversation_started:call_xyz")
-
- @parameterized.expand([("ringing",), ("ended",), ("queued",), ("forwarding",), ("scheduled",)])
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
- def test_webhook_status_update_other_statuses_do_not_capture(self, call_status: str, mock_scoped_capture):
- mock_capture = mock_scoped_capture.return_value.__enter__.return_value
- share = self._create_share()
- self.client.logout()
- response = self._signed_post(
- "topsecret",
- {
- "message": {
- "type": "status-update",
- "status": call_status,
- "call": {"id": "call_xyz", "metadata": {"sharing_access_token": share.access_token}},
- }
- },
- )
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
- mock_capture.assert_not_called()
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
- def test_webhook_end_of_call_report_captures_ended_event(self, mock_scoped_capture):
- mock_capture = mock_scoped_capture.return_value.__enter__.return_value
- share = self._create_share()
- self.client.logout()
- response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
- mock_capture.assert_called_once()
- kwargs = mock_capture.call_args.kwargs
- self.assertEqual(kwargs["event"], "user_interview_conversation_ended")
- assert share.interviewee_context is not None
- self.assertEqual(kwargs["distinct_id"], f"user_interview:{share.interviewee_context.id}")
- self.assertNotIn("[email protected]", kwargs["distinct_id"])
- self.assertTrue(kwargs["properties"]["had_transcript"])
- self.assertTrue(kwargs["properties"]["had_summary"])
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_webhook_is_idempotent_on_call_id(self):
- share = self._create_share()
- self.client.logout()
- payload = self._end_of_call_payload(share.access_token, call_id="call_xyz")
- first = self._signed_post("topsecret", payload)
- self.assertEqual(first.status_code, status.HTTP_202_ACCEPTED)
- stored_id = UserInterview.objects.get(team=self.team).id
- second = self._signed_post("topsecret", payload)
- self.assertEqual(second.status_code, status.HTTP_202_ACCEPTED)
- # The row the second delivery must not duplicate or replace.
- self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)
- self.assertEqual(UserInterview.objects.get(team=self.team).id, stored_id)
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.emit_embedding_request")
- def test_webhook_emits_transcript_and_summary_embeddings(self, mock_emit):
- share = self._create_share()
- self.client.logout()
- with self.captureOnCommitCallbacks(execute=True):
- response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
-
- interview = UserInterview.objects.get(team=self.team)
- assert share.interviewee_context is not None
- topic = share.interviewee_context.topic
-
- emitted = {kwargs["document_type"]: kwargs for _, kwargs in mock_emit.call_args_list}
- self.assertEqual(set(emitted), {"transcript", "summary"})
-
- for document_type, expected_content in (("transcript", "Hi! ..."), ("summary", "User talked about replay.")):
- kwargs = emitted[document_type]
- self.assertEqual(kwargs["content"], expected_content)
- self.assertEqual(kwargs["team_id"], self.team.id)
- self.assertEqual(kwargs["product"], "user_interviews")
- self.assertEqual(kwargs["rendering"], "plain")
- self.assertEqual(kwargs["document_id"], str(interview.id))
- self.assertEqual(kwargs["models"], ["text-embedding-3-small-1536", "text-embedding-3-large-3072"])
- self.assertEqual(
- kwargs["metadata"],
- {"topic_id": str(topic.id), "interviewee_identifier": "[email protected]"},
- )
-
- @parameterized.expand(
- [
- ("transcript_only", "Hi! ...", "", {"transcript"}),
- ("summary_only", "", "User talked about replay.", {"summary"}),
- ("both_empty", "", "", set()),
- ]
- )
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.emit_embedding_request")
- def test_webhook_skips_empty_content(self, _name, transcript, summary, expected_types, mock_emit):
- share = self._create_share()
- self.client.logout()
- payload = self._end_of_call_payload(share.access_token)
- payload["message"]["transcript"] = transcript
- payload["message"]["summary"] = summary
-
- with self.captureOnCommitCallbacks(execute=True):
- response = self._signed_post("topsecret", payload)
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
-
- emitted_types = {kwargs["document_type"] for _, kwargs in mock_emit.call_args_list}
- self.assertEqual(emitted_types, expected_types)
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.emit_embedding_request")
- def test_webhook_does_not_re_emit_on_duplicate(self, mock_emit):
- share = self._create_share()
- self.client.logout()
- payload = self._end_of_call_payload(share.access_token, call_id="call_dup")
-
- with self.captureOnCommitCallbacks(execute=True):
- self._signed_post("topsecret", payload)
- first_emitted_types = {kwargs["document_type"] for _, kwargs in mock_emit.call_args_list}
- self.assertEqual(first_emitted_types, {"transcript", "summary"})
- first_call_count = mock_emit.call_count
-
- with self.captureOnCommitCallbacks(execute=True):
- self._signed_post("topsecret", payload)
- self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)
- self.assertEqual(mock_emit.call_count, first_call_count)
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch(
- "products.user_interviews.backend.vapi_events.emit_embedding_request",
- side_effect=RuntimeError("kafka down"),
- )
- def test_webhook_succeeds_when_embedding_emit_fails(self, _mock_emit):
- share = self._create_share()
- self.client.logout()
- with self.captureOnCommitCallbacks(execute=True):
- response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
- self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)
-
- @parameterized.expand(
- [
- ("transcript_only", True, False),
- ("summary_only", False, True),
- ("both", True, True),
- ]
- )
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.emit_embedding_request")
- def test_webhook_truncates_oversized_content_before_emit(
- self, _name, oversize_transcript, oversize_summary, mock_emit
- ):
- share = self._create_share()
- self.client.logout()
- payload = self._end_of_call_payload(share.access_token)
- original_transcript = payload["message"]["transcript"]
- original_summary = payload["message"]["summary"]
- if oversize_transcript:
- payload["message"]["transcript"] = "a" * (EMBEDDING_CONTENT_MAX_BYTES + 1000)
- if oversize_summary:
- payload["message"]["summary"] = "b" * (EMBEDDING_CONTENT_MAX_BYTES + 500)
-
- with self.captureOnCommitCallbacks(execute=True):
- response = self._signed_post("topsecret", payload)
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
-
- emitted = {kwargs["document_type"]: kwargs for _, kwargs in mock_emit.call_args_list}
-
- for document_type, was_oversized, original in (
- ("transcript", oversize_transcript, original_transcript),
- ("summary", oversize_summary, original_summary),
- ):
- content_bytes = emitted[document_type]["content"].encode("utf-8")
- if was_oversized:
- self.assertEqual(len(content_bytes), EMBEDDING_CONTENT_MAX_BYTES)
- else:
- self.assertEqual(emitted[document_type]["content"], original)
-
-
-class TestSendInterviewInvites(_FeatureFlagEnabledMixin):
- def _create_topic(self, **overrides) -> UserInterviewTopic:
- defaults: dict = {
- "team": self.team,
- "created_by": self.user,
- "interviewee_emails": ["Alex <[email protected]>", "[email protected]"],
- "interviewee_distinct_ids": ["distinct-no-email"],
- "topic": "Session replay adoption",
- "agent_context": "ctx",
- "questions": ["q1"],
- }
- defaults.update(overrides)
- return UserInterviewTopic.objects.create(**defaults)
-
- def _url(self, topic_id: str) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/send_invites/"
-
- def test_send_invites_emails_only_email_identifiers(self):
- topic = self._create_topic()
-
- with (
- patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,
- patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
- ):
- mock_message = mock_message_cls.return_value
- response = self.client.post(self._url(str(topic.id)), data={"send_async": False}, format="json")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- results = response.json()
- sent = sorted(r["interviewee_identifier"] for r in results if r["sent"])
- skipped = [r for r in results if not r["sent"]]
- self.assertEqual(sent, sorted(["Alex <[email protected]>", "[email protected]"]))
- self.assertEqual(len(skipped), 1)
- self.assertEqual(skipped[0]["interviewee_identifier"], "distinct-no-email")
- self.assertEqual(skipped[0]["reason"], "not_an_email")
-
- # Two EmailMessage instances built, each with one recipient, sent synchronously.
- self.assertEqual(mock_message_cls.call_count, 2)
- self.assertEqual(mock_message.add_recipient.call_count, 2)
- mock_message.send.assert_called_with(send_async=False)
-
- def test_send_invites_defaults_subject_and_reply_to(self):
- topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])
-
- with (
- patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,
- patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
- ):
- self.client.post(self._url(str(topic.id)), data={}, format="json")
-
- kwargs = mock_message_cls.call_args.kwargs
- self.assertIn("Session replay adoption", kwargs["subject"])
- self.assertEqual(kwargs["reply_to"], self.user.email)
- self.assertEqual(kwargs["template_name"], "interview_invite")
- self.assertEqual(kwargs["template_context"]["user_name"], "Alex")
- self.assertIn("/interview/", kwargs["template_context"]["interview_url"])
-
- def test_send_invites_uses_explicit_subject_and_reply_to(self):
- topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])
-
- with (
- patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,
- patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
- ):
- self.client.post(
- self._url(str(topic.id)),
- data={"subject": "Hey, can we chat?", "reply_to": "[email protected]"},
- format="json",
- )
-
- kwargs = mock_message_cls.call_args.kwargs
- self.assertEqual(kwargs["subject"], "Hey, can we chat?")
- self.assertEqual(kwargs["reply_to"], "[email protected]")
-
- def test_send_invites_503_when_email_disabled(self):
- topic = self._create_topic()
- with patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=False):
- response = self.client.post(self._url(str(topic.id)), data={}, format="json")
- self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
-
- def test_send_invites_400_when_topic_has_no_identifiers(self):
- topic = self._create_topic(interviewee_emails=[], interviewee_distinct_ids=[])
- with patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True):
- response = self.client.post(self._url(str(topic.id)), data={}, format="json")
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-
- def test_send_invites_marks_per_recipient_failures(self):
- topic = self._create_topic(
- interviewee_emails=["[email protected]", "[email protected]"], interviewee_distinct_ids=[]
- )
-
- class FlakyEmail:
- """Stand-in for EmailMessage that raises on send for one specific recipient."""
-
- def __init__(self, **_kwargs):
- self.recipient_email = None
-
- def add_recipient(self, email, name=None, distinct_id=None):
- self.recipient_email = email
-
- def send(self, send_async=True):
- if self.recipient_email == "[email protected]":
- raise RuntimeError("smtp down")
-
- with (
- patch("products.user_interviews.backend.presentation.views.EmailMessage", FlakyEmail),
- patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
- ):
- response = self.client.post(self._url(str(topic.id)), data={"send_async": False}, format="json")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- by_id = {r["interviewee_identifier"]: r for r in response.json()}
- self.assertTrue(by_id["[email protected]"]["sent"])
- self.assertFalse(by_id["[email protected]"]["sent"])
- self.assertTrue(by_id["[email protected]"]["reason"].startswith("error:"))
-
- def test_send_invites_uses_stored_topic_subject_and_message(self):
- topic = self._create_topic(
- interviewee_emails=["[email protected]"],
- interviewee_distinct_ids=[],
- invite_subject="Quick chat about replay?",
- invite_message="Hey!\nWe'd love your thoughts.",
- )
-
- with (
- patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,
- patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
- ):
- self.client.post(self._url(str(topic.id)), data={}, format="json")
-
- kwargs = mock_message_cls.call_args.kwargs
- assert kwargs["subject"] == "Quick chat about replay?"
- assert kwargs["template_context"]["invite_message"] == "Hey!\nWe'd love your thoughts."
-
- def test_send_invites_request_subject_overrides_stored(self):
- topic = self._create_topic(
- interviewee_emails=["[email protected]"],
- interviewee_distinct_ids=[],
- invite_subject="Stored subject?",
- )
-
- with (
- patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,
- patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
- ):
- self.client.post(self._url(str(topic.id)), data={"subject": "Override subject?"}, format="json")
-
- assert mock_message_cls.call_args.kwargs["subject"] == "Override subject?"
-
- def test_send_invites_sanitizes_unsafe_stored_values_at_send_time(self):
- # Defense-in-depth: values written straight to the DB (bypassing serializer validation)
- # must still degrade to safe defaults at send time rather than reaching the email.
- topic = self._create_topic(
- interviewee_emails=["[email protected]"],
- interviewee_distinct_ids=[],
- invite_subject="http://evil.com",
- invite_message="<b>click www.evil.com</b>",
- )
-
- with (
- patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,
- patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
- ):
- self.client.post(self._url(str(topic.id)), data={}, format="json")
-
- kwargs = mock_message_cls.call_args.kwargs
- assert kwargs["subject"] == "Got 5 minutes to talk about Session replay adoption?"
- assert "evil.com" not in kwargs["subject"]
- assert kwargs["template_context"]["invite_message"] == ""
-
- def test_send_invites_rejects_over_recipient_cap(self):
- topic = self._create_topic(
- interviewee_emails=["[email protected]", "[email protected]"], interviewee_distinct_ids=[]
- )
-
- with (
- patch("products.user_interviews.backend.presentation.views.MAX_INVITE_RECIPIENTS_PER_SEND", 1),
- patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
- ):
- response = self.client.post(self._url(str(topic.id)), data={}, format="json")
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
- assert "per-send limit" in response.json()["error"]
-
- def test_send_invites_collapses_aliases_to_one_mailbox(self):
- topic = self._create_topic(
- interviewee_emails=["A1 <[email protected]>", "A2 <[email protected]>", "[email protected]"],
- interviewee_distinct_ids=[],
- )
-
- with (
- patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,
- patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
- ):
- response = self.client.post(self._url(str(topic.id)), data={"send_async": False}, format="json")
-
- assert response.status_code == status.HTTP_200_OK, response.content
- results = response.json()
- sent = [r for r in results if r["sent"]]
- duplicates = [r for r in results if r.get("reason") == "duplicate_recipient"]
- assert len(sent) == 1
- assert len(duplicates) == 2
- assert mock_message_cls.call_count == 1
-
- @parameterized.expand(
- [
- ("url", "chat about http://evil.com"),
- ("brackets", "chat <b>now</b>"),
- ("newline", "line one\nline two"),
- ]
- )
- def test_send_invites_rejects_unsafe_subject_override(self, _name: str, subject: str):
- topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])
- with patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True):
- response = self.client.post(self._url(str(topic.id)), data={"subject": subject}, format="json")
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
- assert response.json()["attr"] == "subject"
-
-
-class TestInviteFieldValidation(_FeatureFlagEnabledMixin):
- def _url(self) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/"
-
- UNSAFE_SUBJECTS = [
- ("url_scheme", "Visit http://evil.com"),
- ("www_prefix", "go to www.evil.com now"),
- ("bare_domain", "thoughts on acme.com?"),
- ("angle_brackets", "Hi <b>there</b>"),
- ("newline", "line one\nline two"),
- ("null_byte", "subject\x00"),
- ("zero_width", "sub​ject"),
- ("fullwidth_url", "http://evil.example"),
- ]
- UNSAFE_MESSAGES = [
- ("url_scheme", "click http://evil.com"),
- ("javascript_scheme", "click javascript:alert(1)"),
- ("www_prefix", "see www.evil.com"),
- ("bare_domain", "head to acme.com to learn more"),
- ("angle_brackets", "<script>alert(1)</script>"),
- ("null_byte", "body\x00here"),
- ("bidi_override", "body‮here"),
- ("fullwidth_url", "http://evil.example"),
- ]
-
- @parameterized.expand(UNSAFE_SUBJECTS)
- def test_create_rejects_unsafe_subject(self, _name: str, subject: str):
- payload = {"topic": "t", "interviewee_emails": ["[email protected]"], "invite_subject": subject}
- response = self.client.post(self._url(), data=payload, format="json")
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
- assert response.json()["attr"] == "invite_subject"
-
- @parameterized.expand(UNSAFE_MESSAGES)
- def test_create_rejects_unsafe_message(self, _name: str, message: str):
- payload = {"topic": "t", "interviewee_emails": ["[email protected]"], "invite_message": message}
- response = self.client.post(self._url(), data=payload, format="json")
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
- assert response.json()["attr"] == "invite_message"
-
- @parameterized.expand(
- [
- ("plain_subject_and_message", "Got a sec to chat?", "Hi there,\nThanks for being a user."),
- ("multiline_no_links", "Quick question", "have you seen the new onboarding flow?\nKeen to hear your take."),
- ("blank_values", "", ""),
- ]
- )
- def test_create_accepts_safe_values(self, _name: str, subject: str, message: str):
- payload = {
- "topic": "t",
- "interviewee_emails": ["[email protected]"],
- "invite_subject": subject,
- "invite_message": message,
- }
- response = self.client.post(self._url(), data=payload, format="json")
- assert response.status_code == status.HTTP_201_CREATED, response.content
- topic = UserInterviewTopic.objects.get(id=response.json()["id"], team=self.team)
- assert topic.invite_subject == subject
- assert topic.invite_message == message
-
- def test_partial_update_rejects_unsafe_subject(self):
- topic = UserInterviewTopic.objects.create(
- team=self.team, created_by=self.user, interviewee_emails=["[email protected]"], topic="t"
- )
- response = self.client.patch(
- f"{self._url()}{topic.id}/", data={"invite_subject": "go to www.evil.com"}, format="json"
- )
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
- topic.refresh_from_db()
- assert topic.invite_subject == ""
-
-
-class TestInterviewInviteTemplateRendering(unittest.TestCase):
- def _render(self, **context: Any) -> str:
- ctx: dict[str, Any] = {
- "user_name": "Alex",
- "topic": "Session replay",
- "interview_url": "https://app.posthog.com/interview/abc",
- "site_url": "https://app.posthog.com",
- }
- ctx.update(context)
- return get_template("email/interview_invite.html").render(ctx)
-
- def test_hostile_message_is_escaped_not_live_markup(self):
- html = self._render(invite_message='<script>alert("xss")</script>\nstay safe')
- assert "&lt;script&gt;" in html
- assert "<script>" not in html
- assert "stay safe" in html
-
- def test_multiline_message_renders_line_breaks(self):
- html = self._render(invite_message="Line one\nLine two")
- assert "Line one<br>" in html
- assert "Line two" in html
-
- def test_blank_message_falls_back_to_default_copy(self):
- html = self._render(invite_message="")
- assert "AI interviewer" in html
-
-
-class TestPreviewInterviewInvite(_FeatureFlagEnabledMixin):
- def _create_topic(self, **overrides) -> UserInterviewTopic:
- defaults: dict = {
- "team": self.team,
- "created_by": self.user,
- "interviewee_emails": ["Alex <[email protected]>"],
- "interviewee_distinct_ids": [],
- "topic": "Session replay adoption",
- "questions": ["q1"],
- }
- defaults.update(overrides)
- return UserInterviewTopic.objects.create(**defaults)
-
- def _url(self, topic_id: str) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/preview_invite/"
-
- def test_preview_renders_subject_and_html_for_default_identifier(self):
- topic = self._create_topic(invite_subject="Quick chat about replay?", invite_message="Hey,\nGot a sec?")
- response = self.client.post(self._url(str(topic.id)), data={}, format="json")
- assert response.status_code == status.HTTP_200_OK, response.content
- body = response.json()
- assert body["interviewee_identifier"] == "Alex <[email protected]>"
- assert body["user_name"] == "Alex"
- assert body["email"] == "[email protected]"
- assert body["subject"] == "Quick chat about replay?"
- assert body["emailable"] is True
- assert "Got a sec?" in body["html"]
-
- @parameterized.expand(
- [
- ("blank_message", ""),
- ("unsafe_stored_brackets", "<script>alert(1)</script>"),
- ]
- )
- def test_preview_falls_back_to_default_copy(self, _name: str, invite_message: str):
- topic = self._create_topic(invite_message=invite_message)
- body = self.client.post(self._url(str(topic.id)), data={}, format="json").json()
- assert "AI interviewer" in body["html"]
- assert "<script>" not in body["html"]
- assert body["subject"] == "Got 5 minutes to talk about Session replay adoption?"
-
- def test_preview_for_distinct_id_only_identifier_is_not_emailable(self):
- topic = self._create_topic(interviewee_emails=[], interviewee_distinct_ids=["distinct-123"])
- body = self.client.post(
- self._url(str(topic.id)), data={"interviewee_identifier": "distinct-123"}, format="json"
- ).json()
- assert body["interviewee_identifier"] == "distinct-123"
- assert body["email"] is None
- assert body["emailable"] is False
-
- def test_preview_creates_no_share_rows_and_uses_placeholder_link(self):
- topic = self._create_topic()
- before_ic = IntervieweeContext.objects.count()
- before_sc = SharingConfiguration.objects.count()
- body = self.client.post(self._url(str(topic.id)), data={}, format="json").json()
- assert body["is_preview_link"] is True
- assert "/interview/preview" in body["interview_url"]
- assert IntervieweeContext.objects.count() == before_ic
- assert SharingConfiguration.objects.count() == before_sc
-
- def test_preview_never_exposes_live_share_token(self):
- # A read-scoped preview must not leak a working interview link even when one exists.
- topic = self._create_topic()
- ic = IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="Alex <[email protected]>",
- agent_context="",
- created_by=self.user,
- )
- share = SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)
- body = self.client.post(self._url(str(topic.id)), data={}, format="json").json()
- assert share.access_token not in body["interview_url"]
- assert "/interview/preview" in body["interview_url"]
- assert body["is_preview_link"] is True
-
- def test_preview_400_when_topic_has_no_identifiers(self):
- topic = self._create_topic(interviewee_emails=[], interviewee_distinct_ids=[])
- response = self.client.post(self._url(str(topic.id)), data={}, format="json")
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
-
- def test_preview_400_for_non_targeted_identifier(self):
- topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])
- response = self.client.post(
- self._url(str(topic.id)), data={"interviewee_identifier": "[email protected]"}, format="json"
- )
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
-
-
-class TestSharingConfigurationCanAccess(APIBaseTest):
- def test_can_access_interviewee_context(self):
- topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic="t",
- )
- ic = IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="[email protected]",
- agent_context="",
- created_by=self.user,
- )
- share = SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)
- self.assertTrue(share.can_access_object(ic))
-
- def test_interviewee_context_config_fails_closed_through_sharing_gate(self):
- topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic="t",
- )
- ic = IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="[email protected]",
- agent_context="",
- created_by=self.user,
- )
- share = SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)
-
- request = Mock(method="PATCH", data={"enabled": True})
- request.user = self.user
- view = Mock(team=self.team)
-
- with self.assertRaises(PermissionDenied) as caught:
- check_can_access_sharing_configuration(view, request, share)
-
- assert "cannot be shared through this endpoint" in str(caught.exception)
diff --git a/products/user_interviews/backend/test_interviewee_context_bulk_create.py b/products/user_interviews/backend/test_interviewee_context_bulk_create.py
deleted file mode 100644
index 60bbf9123667..000000000000
--- a/products/user_interviews/backend/test_interviewee_context_bulk_create.py
+++ /dev/null
@@ -1,149 +0,0 @@
-from typing import Any
-from uuid import uuid4
-
-from posthog.test.base import APIBaseTest
-from unittest.mock import patch
-
-from parameterized import parameterized
-from rest_framework import status
-
-from products.user_interviews.backend.models import IntervieweeContext, UserInterviewTopic
-from products.user_interviews.backend.presentation.views import BULK_INTERVIEWEE_CONTEXT_MAX_ITEMS
-
-
-class _FeatureFlagEnabledMixin(APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- patcher = patch("posthoganalytics.feature_enabled", return_value=True)
- patcher.start()
- self.addCleanup(patcher.stop)
-
-
-class TestIntervieweeContextBulkCreate(_FeatureFlagEnabledMixin):
- def _create_topic(self, **overrides: Any) -> UserInterviewTopic:
- defaults: dict = {
- "team": self.team,
- "created_by": self.user,
- "interviewee_emails": [],
- "interviewee_distinct_ids": [],
- "topic": "MCP-only insight creators",
- }
- defaults.update(overrides)
- return UserInterviewTopic.objects.create(**defaults)
-
- def _bulk_url(self, topic_id: str) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/interviewees/bulk/"
-
- def _item(self, identifier: str, context: str = "ctx") -> dict[str, str]:
- return {"interviewee_identifier": identifier, "agent_context": context}
-
- def test_bulk_create_inserts_all_new_rows(self):
- topic = self._create_topic()
- items = [self._item(f"user{i}@example.com", f"context {i}") for i in range(3)]
-
- response = self.client.post(self._bulk_url(str(topic.id)), {"items": items}, format="json")
-
- assert response.status_code == status.HTTP_200_OK, response.content
- assert response.json() == {
- "inserted_count": 3,
- "skipped_count": 0,
- "skipped_identifiers": [],
- }
- assert IntervieweeContext.objects.filter(topic=topic).count() == 3
-
- def test_bulk_create_skips_existing_rows(self):
- topic = self._create_topic()
- IntervieweeContext.objects.create(
- team=self.team,
- topic=topic,
- interviewee_identifier="[email protected]",
- agent_context="existing context",
- created_by=self.user,
- )
- items = [
- self._item("[email protected]", "would-be-overwritten"),
- self._item("[email protected]", "new context"),
- ]
-
- response = self.client.post(self._bulk_url(str(topic.id)), {"items": items}, format="json")
-
- assert response.status_code == status.HTTP_200_OK, response.content
- assert response.json() == {
- "inserted_count": 1,
- "skipped_count": 1,
- "skipped_identifiers": ["[email protected]"],
- }
- existing = IntervieweeContext.objects.get(topic=topic, interviewee_identifier="[email protected]")
- assert existing.agent_context == "existing context"
- assert IntervieweeContext.objects.filter(topic=topic).count() == 2
-
- def test_bulk_create_rejects_unknown_topic(self):
- response = self.client.post(self._bulk_url(str(uuid4())), {"items": [self._item("[email protected]")]}, format="json")
-
- assert response.status_code == status.HTTP_404_NOT_FOUND, response.content
-
- def test_bulk_create_rejects_topic_belonging_to_another_team(self):
- other_team = self.organization.teams.create(name="other-team")
- other_topic = UserInterviewTopic.objects.create(
- team=other_team,
- created_by=self.user,
- topic="other team topic",
- )
-
- response = self.client.post(
- self._bulk_url(str(other_topic.id)),
- {"items": [self._item("[email protected]")]},
- format="json",
- )
-
- assert response.status_code == status.HTTP_404_NOT_FOUND, response.content
- assert IntervieweeContext.objects.filter(topic=other_topic).count() == 0
-
- @parameterized.expand(
- [
- ("empty_items", {"items": []}),
- ("missing_items", {}),
- ("missing_identifier", {"items": [{"agent_context": "x"}]}),
- ("missing_context", {"items": [{"interviewee_identifier": "[email protected]"}]}),
- (
- "duplicate_identifiers_in_batch",
- {"items": [{"interviewee_identifier": "[email protected]", "agent_context": "x"}] * 2},
- ),
- (
- "identifier_too_long",
- {"items": [{"interviewee_identifier": "a" * 401, "agent_context": "x"}]},
- ),
- (
- "context_too_long",
- {"items": [{"interviewee_identifier": "[email protected]", "agent_context": "x" * 10_001}]},
- ),
- ]
- )
- def test_bulk_create_validation_errors(self, _name: str, body: dict[str, Any]):
- topic = self._create_topic()
-
- response = self.client.post(self._bulk_url(str(topic.id)), body, format="json")
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
- assert IntervieweeContext.objects.filter(topic=topic).count() == 0
-
- def test_bulk_create_rejects_oversized_batch(self):
- topic = self._create_topic()
- items = [self._item(f"u{i}@example.com") for i in range(BULK_INTERVIEWEE_CONTEXT_MAX_ITEMS + 1)]
-
- response = self.client.post(self._bulk_url(str(topic.id)), {"items": items}, format="json")
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
- assert IntervieweeContext.objects.filter(topic=topic).count() == 0
-
- def test_bulk_create_accepts_max_size_batch(self):
- topic = self._create_topic()
- items = [self._item(f"u{i}@example.com") for i in range(BULK_INTERVIEWEE_CONTEXT_MAX_ITEMS)]
-
- response = self.client.post(self._bulk_url(str(topic.id)), {"items": items}, format="json")
-
- assert response.status_code == status.HTTP_200_OK, response.content
- body = response.json()
- assert body["inserted_count"] == BULK_INTERVIEWEE_CONTEXT_MAX_ITEMS
- assert body["skipped_count"] == 0
- assert IntervieweeContext.objects.filter(topic=topic).count() == BULK_INTERVIEWEE_CONTEXT_MAX_ITEMS
diff --git a/products/user_interviews/backend/test_max_tools.py b/products/user_interviews/backend/test_max_tools.py
deleted file mode 100644
index 13eb8c0a5916..000000000000
--- a/products/user_interviews/backend/test_max_tools.py
+++ /dev/null
@@ -1,179 +0,0 @@
-import pytest
-from posthog.test.base import BaseTest
-
-from asgiref.sync import sync_to_async
-from langchain_core.runnables import RunnableConfig
-from parameterized import parameterized
-
-from products.user_interviews.backend.models import UserInterviewTopic
-
-from .max_tools import CreateUserInterviewTopicTool
-
-
-class TestCreateUserInterviewTopicTool(BaseTest):
- def setUp(self):
- super().setUp()
- self._config: RunnableConfig = {
- "configurable": {
- "team": self.team,
- "user": self.user,
- },
- }
-
- def _tool(self) -> CreateUserInterviewTopicTool:
- return CreateUserInterviewTopicTool(team=self.team, user=self.user, config=self._config)
-
- @pytest.mark.django_db
- @pytest.mark.asyncio
- async def test_arun_impl_success_with_emails(self):
- tool = self._tool()
-
- content, artifact = await tool._arun_impl(
- topic="Onboarding experience",
- interviewee_emails=["[email protected]", "Sam <[email protected]>"],
- questions=[
- "What were you hoping to achieve when you signed up?",
- "Where did you get stuck during onboarding?",
- "What would have made the first 5 minutes easier?",
- ],
- agent_context="Focus on emotional friction, not feature requests.",
- )
-
- assert "Created interview topic" in content
- assert artifact["topic"] == "Onboarding experience"
- assert artifact["interviewee_email_count"] == 2
- assert artifact["interviewee_distinct_id_count"] == 0
- assert artifact["question_count"] == 3
-
- topic = await sync_to_async(
- lambda: UserInterviewTopic.objects.select_related("team", "created_by").get(
- team=self.team, id=artifact["topic_id"]
- )
- )()
- assert topic.team == self.team
- assert topic.created_by == self.user
- assert topic.interviewee_emails == ["[email protected]", "Sam <[email protected]>"]
- assert topic.interviewee_distinct_ids == []
- assert len(topic.questions) == 3
- assert topic.agent_context == "Focus on emotional friction, not feature requests."
-
- @pytest.mark.django_db
- @pytest.mark.asyncio
- async def test_arun_impl_success_with_distinct_ids_only(self):
- tool = self._tool()
-
- content, artifact = await tool._arun_impl(
- topic="Power user dashboard usage",
- interviewee_distinct_ids=["user_123", "user_456"],
- questions=["How do you currently use dashboards?"],
- )
-
- assert "Created interview topic" in content
- assert artifact["interviewee_email_count"] == 0
- assert artifact["interviewee_distinct_id_count"] == 2
-
- @pytest.mark.django_db
- @pytest.mark.asyncio
- @parameterized.expand(
- [
- (
- "empty_topic",
- {"topic": " ", "interviewee_emails": ["[email protected]"]},
- "topic is required",
- ),
- (
- "no_interviewees",
- {"topic": "Some topic", "interviewee_emails": [], "interviewee_distinct_ids": []},
- "interviewee",
- ),
- (
- "invalid_emails",
- {
- "topic": "Some topic",
- "interviewee_emails": ["not-an-email", "also bad"],
- "questions": ["A question?"],
- },
- "not-an-email",
- ),
- (
- "no_questions",
- {"topic": "Some topic", "interviewee_emails": ["[email protected]"], "questions": []},
- "question",
- ),
- ]
- )
- async def test_arun_impl_rejects_invalid_input(self, _name, kwargs, expected_content_fragment):
- tool = self._tool()
-
- content, artifact = await tool._arun_impl(**kwargs)
-
- assert artifact["error"] == "validation_failed"
- assert expected_content_fragment in content.lower()
- assert not await sync_to_async(UserInterviewTopic.objects.filter(team=self.team).exists)()
-
- @pytest.mark.django_db
- @pytest.mark.asyncio
- async def test_arun_impl_strips_blank_entries(self):
- tool = self._tool()
-
- content, artifact = await tool._arun_impl(
- topic="Some topic",
- interviewee_emails=["[email protected]", " ", ""],
- interviewee_distinct_ids=["", "user_1"],
- questions=["A real question?", " ", ""],
- )
-
- assert artifact["interviewee_email_count"] == 1
- assert artifact["interviewee_distinct_id_count"] == 1
- assert artifact["question_count"] == 1
-
- topic = await sync_to_async(lambda: UserInterviewTopic.objects.get(team=self.team, id=artifact["topic_id"]))()
- assert topic.interviewee_emails == ["[email protected]"]
- assert topic.interviewee_distinct_ids == ["user_1"]
- assert topic.questions == ["A real question?"]
-
- @pytest.mark.django_db
- @pytest.mark.asyncio
- async def test_arun_impl_persists_safe_invite_fields(self):
- tool = self._tool()
-
- content, artifact = await tool._arun_impl(
- topic="Some topic",
- interviewee_emails=["[email protected]"],
- questions=["A real question?"],
- invite_subject="Got a sec to chat?",
- invite_message="Hi Alex,\nWe'd love your thoughts.",
- )
-
- assert "Created interview topic" in content
- topic = await sync_to_async(lambda: UserInterviewTopic.objects.get(team=self.team, id=artifact["topic_id"]))()
- assert topic.invite_subject == "Got a sec to chat?"
- assert topic.invite_message == "Hi Alex,\nWe'd love your thoughts."
-
- @pytest.mark.django_db
- @pytest.mark.asyncio
- @parameterized.expand(
- [
- ("subject_with_url", {"invite_subject": "see http://evil.com"}),
- ("subject_with_brackets", {"invite_subject": "<b>hi</b>"}),
- ("subject_with_newline", {"invite_subject": "line one\nline two"}),
- ("message_with_www", {"invite_message": "go to www.evil.com"}),
- ("message_with_bare_domain", {"invite_message": "head to acme.com to learn more"}),
- ("subject_with_bare_domain", {"invite_subject": "thoughts on acme.com?"}),
- ("message_with_javascript", {"invite_message": "click javascript:alert(1)"}),
- ("message_with_brackets", {"invite_message": "<script>alert(1)</script>"}),
- ]
- )
- async def test_arun_impl_rejects_unsafe_invite_fields(self, _name, invite_kwargs):
- tool = self._tool()
-
- content, artifact = await tool._arun_impl(
- topic="Some topic",
- interviewee_emails=["[email protected]"],
- questions=["A real question?"],
- **invite_kwargs,
- )
-
- assert artifact["error"] == "validation_failed"
- assert "invite" in content.lower()
- assert not await sync_to_async(UserInterviewTopic.objects.filter(team=self.team).exists)()
diff --git a/products/user_interviews/backend/test_search.py b/products/user_interviews/backend/test_search.py
deleted file mode 100644
index 82e58ed0b65a..000000000000
--- a/products/user_interviews/backend/test_search.py
+++ /dev/null
@@ -1,349 +0,0 @@
-from typing import Any
-
-from posthog.test.base import APIBaseTest
-from unittest.mock import MagicMock, patch
-
-from parameterized import parameterized
-from rest_framework import status
-
-from products.user_interviews.backend.models import UserInterview, UserInterviewTopic
-
-
-class _FeatureFlagEnabledMixin(APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- patcher = patch("posthoganalytics.feature_enabled", return_value=True)
- patcher.start()
- self.addCleanup(patcher.stop)
-
-
-class TestUserInterviewSearch(_FeatureFlagEnabledMixin):
- def setUp(self) -> None:
- super().setUp()
- self.topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic="Replay adoption",
- agent_context="ctx",
- questions=[],
- )
- self.interview_a = UserInterview.objects.create(
- team=self.team,
- topic=self.topic,
- interviewee_identifier="[email protected]",
- interviewee_emails=["[email protected]"],
- transcript="alex talked about session replay buffering",
- summary="alex finds session replay slow on long sessions",
- created_by=self.user,
- )
- self.interview_b = UserInterview.objects.create(
- team=self.team,
- topic=self.topic,
- interviewee_identifier="[email protected]",
- interviewee_emails=["[email protected]"],
- transcript="bob loves heatmaps but ignores replays",
- summary="bob uses heatmaps daily",
- created_by=self.user,
- )
-
- def _url(self) -> str:
- return f"/api/environments/{self.team.id}/user_interviews/search/"
-
- def _embedding_response(self) -> MagicMock:
- resp = MagicMock()
- resp.embedding = [0.0] * 3072
- resp.tokens_used = 4
- resp.did_truncate = False
- return resp
-
- def _hogql_rows(self, rows: list[tuple[Any, ...]]) -> MagicMock:
- result = MagicMock()
- result.results = rows
- return result
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_returns_ranked_matches(self, mock_embed, mock_hogql):
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows(
- [
- (str(self.interview_a.id), "transcript", 0.12),
- (str(self.interview_a.id), "summary", 0.22),
- (str(self.interview_b.id), "transcript", 0.48),
- ]
- )
-
- response = self.client.post(self._url(), {"query": "is session replay slow?"}, content_type="application/json")
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
-
- body = response.json()
- self.assertEqual(len(body), 3)
- self.assertEqual(body[0]["interview_id"], str(self.interview_a.id))
- self.assertEqual(body[0]["document_type"], "transcript")
- self.assertAlmostEqual(body[0]["similarity"], 0.88, places=5)
- self.assertEqual(body[0]["content_snippet"], "alex talked about session replay buffering")
- self.assertEqual(body[0]["interviewee_identifier"], "[email protected]")
- self.assertEqual(body[0]["topic_id"], str(self.topic.id))
- self.assertGreater(body[0]["similarity"], body[2]["similarity"])
-
- mock_embed.assert_called_once()
- embed_args, embed_kwargs = mock_embed.call_args
- self.assertEqual(embed_args[0], self.team)
- self.assertEqual(embed_args[1], "is session replay slow?")
- self.assertEqual(embed_kwargs["model"], "text-embedding-3-large-3072")
-
- @parameterized.expand(
- [
- ("distance_above_one_clamps_to_zero", 1.4, 0.0),
- ("negative_distance_clamps_to_one", -0.01, 1.0),
- ]
- )
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_clamps_similarity_to_unit_interval(self, _name, distance, expected, mock_embed, mock_hogql):
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows([(str(self.interview_a.id), "transcript", distance)])
- response = self.client.post(self._url(), {"query": "x"}, content_type="application/json")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()[0]["similarity"], expected)
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_snippet_reflects_current_postgres_content(self, mock_embed, mock_hogql):
- """The snippet must come from the live UserInterview row, not the embedding row's
- snapshot — otherwise editing or trimming a transcript leaves stale content visible
- through the search endpoint until the embedding ages out."""
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows([(str(self.interview_a.id), "transcript", 0.1)])
-
- self.interview_a.transcript = "alex's edited transcript: replay is faster now"
- self.interview_a.save(update_fields=["transcript"])
-
- response = self.client.post(self._url(), {"query": "x"}, content_type="application/json")
- self.assertEqual(response.json()[0]["content_snippet"], "alex's edited transcript: replay is faster now")
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_truncates_long_content_snippet(self, mock_embed, mock_hogql):
- mock_embed.return_value = self._embedding_response()
- self.interview_a.transcript = "x" * 1000
- self.interview_a.save(update_fields=["transcript"])
- mock_hogql.return_value = self._hogql_rows([(str(self.interview_a.id), "transcript", 0.1)])
- response = self.client.post(self._url(), {"query": "x"}, content_type="application/json")
- self.assertEqual(len(response.json()[0]["content_snippet"]), 500)
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_skips_rows_for_deleted_interviews(self, mock_embed, mock_hogql):
- mock_embed.return_value = self._embedding_response()
- ghost_id = "00000000-0000-0000-0000-000000000000"
- mock_hogql.return_value = self._hogql_rows(
- [
- (str(self.interview_a.id), "transcript", 0.1),
- (ghost_id, "transcript", 0.2),
- ]
- )
- response = self.client.post(self._url(), {"query": "x"}, content_type="application/json")
- body = response.json()
- self.assertEqual(len(body), 1)
- self.assertEqual(body[0]["interview_id"], str(self.interview_a.id))
-
- @parameterized.expand(
- [
- ("transcript_only", ["transcript"], {"transcript"}),
- ("summary_only", ["summary"], {"summary"}),
- ("both_explicit", ["transcript", "summary"], {"transcript", "summary"}),
- ]
- )
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_forwards_document_types_filter(
- self, _name, document_types, expected_in_placeholders, mock_embed, mock_hogql
- ):
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows([])
-
- self.client.post(
- self._url(),
- {"query": "x", "document_types": document_types},
- content_type="application/json",
- )
-
- mock_hogql.assert_called_once()
- placeholders = mock_hogql.call_args.kwargs["placeholders"]
- self.assertEqual(set(placeholders["document_types"].value), expected_in_placeholders)
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_resolves_topic_id_via_current_postgres_linkage(self, mock_embed, mock_hogql):
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows([])
-
- self.client.post(
- self._url(),
- {"query": "x", "topic_id": str(self.topic.id)},
- content_type="application/json",
- )
-
- placeholders = mock_hogql.call_args.kwargs["placeholders"]
- # Both seeded interviews are currently linked to the topic; the search WHERE clause
- # is built from that *current* linkage, not from the embedding-time metadata snapshot.
- self.assertEqual(
- set(placeholders["scoped_document_ids"].value),
- {str(self.interview_a.id), str(self.interview_b.id)},
- )
- hogql_query = mock_hogql.call_args.kwargs["query"]
- self.assertIn("document_id IN {scoped_document_ids}", hogql_query)
- self.assertNotIn("JSONExtractString(metadata, 'topic_id')", hogql_query)
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_excludes_interviews_detached_from_topic(self, mock_embed, mock_hogql):
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows([])
- # Detach interview_b from the topic — its embedding row still names topic in metadata,
- # but the Postgres linkage is gone, so it must NOT appear in the scoped id set.
- self.interview_b.topic = None
- self.interview_b.save(update_fields=["topic"])
-
- self.client.post(
- self._url(),
- {"query": "x", "topic_id": str(self.topic.id)},
- content_type="application/json",
- )
-
- placeholders = mock_hogql.call_args.kwargs["placeholders"]
- self.assertEqual(set(placeholders["scoped_document_ids"].value), {str(self.interview_a.id)})
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_short_circuits_when_topic_has_no_interviews(self, mock_embed, mock_hogql):
- mock_embed.return_value = self._embedding_response()
- # No call to HogQL should happen when the topic resolves to zero interview IDs.
- empty_topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic="No interviews yet",
- agent_context="",
- questions=[],
- )
-
- response = self.client.post(
- self._url(),
- {"query": "x", "topic_id": str(empty_topic.id)},
- content_type="application/json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json(), [])
- mock_hogql.assert_not_called()
- mock_embed.assert_not_called()
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_defaults_to_both_document_types_when_unset(self, mock_embed, mock_hogql):
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows([])
-
- self.client.post(self._url(), {"query": "x"}, content_type="application/json")
-
- placeholders = mock_hogql.call_args.kwargs["placeholders"]
- self.assertEqual(set(placeholders["document_types"].value), {"transcript", "summary"})
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_enforces_default_limit_when_omitted(self, mock_embed, mock_hogql):
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows([])
-
- self.client.post(self._url(), {"query": "x"}, content_type="application/json")
-
- placeholders = mock_hogql.call_args.kwargs["placeholders"]
- self.assertEqual(placeholders["limit"].value, 10)
-
- @parameterized.expand(
- [
- ("missing_query", {}),
- ("query_above_max_length", {"query": "x" * 2001}),
- ("limit_above_max", {"query": "x", "limit": 51}),
- ("invalid_document_type", {"query": "x", "document_types": ["nonsense"]}),
- ("empty_document_types_list", {"query": "x", "document_types": []}),
- ]
- )
- def test_search_rejects_invalid_request(self, _name, payload):
- response = self.client.post(self._url(), payload, content_type="application/json")
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-
- def test_search_action_declares_read_scope(self):
- from products.user_interviews.backend.presentation.views import UserInterviewViewSet
-
- self.assertEqual(UserInterviewViewSet.search.kwargs["required_scopes"], ["user_interview:read"])
-
- @patch("products.user_interviews.backend.presentation.views.tag_queries")
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_tags_clickhouse_query_for_attribution(self, mock_embed, mock_hogql, mock_tag):
- from posthog.clickhouse.query_tagging import Feature, Product
-
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows([])
-
- self.client.post(self._url(), {"query": "x"}, content_type="application/json")
-
- mock_tag.assert_called_once_with(product=Product.USER_INTERVIEWS, feature=Feature.SEMANTIC_SEARCH)
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch(
- "products.user_interviews.backend.presentation.views.generate_embedding",
- side_effect=RuntimeError("embedding service down"),
- )
- def test_search_returns_502_when_embedding_service_fails(self, _mock_embed, mock_hogql):
- response = self.client.post(self._url(), {"query": "x"}, content_type="application/json")
- self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)
- self.assertIn("Embedding service", response.json()["detail"])
- mock_hogql.assert_not_called()
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_caps_scoped_document_ids_for_pathological_topic_size(self, mock_embed, mock_hogql):
- from products.user_interviews.backend.presentation.views import SEARCH_TOPIC_INTERVIEW_CAP
-
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows([])
- # Create enough interviews to exceed the cap. Generate them in a single batch.
- UserInterview.objects.bulk_create(
- [
- UserInterview(
- team=self.team,
- topic=self.topic,
- interviewee_identifier=f"person-{i}@example.com",
- interviewee_emails=[f"person-{i}@example.com"],
- transcript="t",
- summary="s",
- created_by=self.user,
- )
- for i in range(SEARCH_TOPIC_INTERVIEW_CAP + 5)
- ]
- )
-
- self.client.post(
- self._url(),
- {"query": "x", "topic_id": str(self.topic.id)},
- content_type="application/json",
- )
-
- placeholders = mock_hogql.call_args.kwargs["placeholders"]
- self.assertEqual(len(placeholders["scoped_document_ids"].value), SEARCH_TOPIC_INTERVIEW_CAP)
-
- @patch("products.user_interviews.backend.presentation.views.execute_hogql_query")
- @patch("products.user_interviews.backend.presentation.views.generate_embedding")
- def test_search_does_not_leak_across_teams(self, mock_embed, mock_hogql):
- mock_embed.return_value = self._embedding_response()
- mock_hogql.return_value = self._hogql_rows([])
-
- self.client.post(self._url(), {"query": "x"}, content_type="application/json")
-
- placeholders = mock_hogql.call_args.kwargs["placeholders"]
- self.assertEqual(placeholders["team_id"].value, self.team.id)
diff --git a/products/user_interviews/backend/test_shared_interview_link.py b/products/user_interviews/backend/test_shared_interview_link.py
deleted file mode 100644
index 4c62641285f4..000000000000
--- a/products/user_interviews/backend/test_shared_interview_link.py
+++ /dev/null
@@ -1,471 +0,0 @@
-import hmac
-import json
-import hashlib
-from typing import Any
-
-from posthog.test.base import APIBaseTest
-from unittest.mock import patch
-
-from django.test import override_settings
-
-from parameterized import parameterized
-from rest_framework import status
-
-from posthog.api.test.test_sharing import mock_exporter_template
-from posthog.models.sharing_configuration import SharingConfiguration
-from posthog.models.user import User
-
-from products.user_interviews.backend.facade.api import SHARED_INTERVIEWEE_IDENTIFIER, has_replied
-from products.user_interviews.backend.models import (
- IntervieweeContext,
- UserInterview,
- UserInterviewClassification,
- UserInterviewTopic,
-)
-
-
-def _mock_web_call(assistant_overrides: dict[str, Any]) -> dict[str, Any]:
- return {"webCallUrl": "https://daily.example/call", "id": "call_test"}
-
-
-def _make_shared_config(*, team: Any, topic: UserInterviewTopic, created_by: User) -> SharingConfiguration:
- """Build a shared link the way the product does — a sentinel IntervieweeContext plus a
- SharingConfiguration on it (no new model / no main-app FK)."""
- ic = IntervieweeContext.objects.create(
- team=team,
- topic=topic,
- interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER,
- agent_context="",
- created_by=created_by,
- )
- return SharingConfiguration.objects.create(team=team, interviewee_context=ic, enabled=True)
-
-
-class _FeatureFlagEnabledMixin(APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- patcher = patch("posthoganalytics.feature_enabled", return_value=True)
- patcher.start()
- self.addCleanup(patcher.stop)
-
-
-class TestGenerateSharedLink(_FeatureFlagEnabledMixin):
- def _topic(self) -> UserInterviewTopic:
- return UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=[],
- interviewee_distinct_ids=[],
- topic="Alternatives and comparisons",
- questions=["What were you comparing us against?"],
- )
-
- def _url(self, topic_id: str) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/shared_link/"
-
- def test_creates_shared_link_via_sentinel_context(self) -> None:
- topic = self._topic()
- response = self.client.post(self._url(str(topic.id)))
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
-
- # Modelled as a sentinel IntervieweeContext (no new model / no main-app FK).
- ic = IntervieweeContext.objects.get(
- team=self.team, topic=topic, interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER
- )
- config = SharingConfiguration.objects.get(team=self.team, interviewee_context=ic, enabled=True)
- assert config.access_token is not None
- assert config.access_token in response.json()["interview_url"]
-
- def test_is_idempotent(self) -> None:
- topic = self._topic()
- first = self.client.post(self._url(str(topic.id))).json()
- second = self.client.post(self._url(str(topic.id))).json()
- assert first["interview_url"] == second["interview_url"]
- assert (
- IntervieweeContext.objects.filter(topic=topic, interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER).count()
- == 1
- )
- assert (
- SharingConfiguration.objects.filter(
- interviewee_context__topic=topic,
- interviewee_context__interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER,
- enabled=True,
- ).count()
- == 1
- )
-
- def test_shared_link_works_without_any_targeted_interviewees(self) -> None:
- # Unlike generate_links (which needs emails/distinct_ids), a shared link is for a topic with
- # no pre-seeded targets — this is the whole point for anonymous blog visitors.
- topic = self._topic()
- assert not topic.interviewee_emails and not topic.interviewee_distinct_ids
- response = self.client.post(self._url(str(topic.id)))
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
-
-
-class TestReservedIdentifierRejected(_FeatureFlagEnabledMixin):
- # A user-supplied identifier equal to the shared-link sentinel (or in the `shared:` namespace)
- # would collide on the unique (topic, interviewee_identifier) constraint and silently merge with
- # or revoke the topic's shared link, so it's rejected at every input boundary.
- def _topics_url(self) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/"
-
- @parameterized.expand([("sentinel", SHARED_INTERVIEWEE_IDENTIFIER), ("shared_namespace", "shared:abc123")])
- def test_topic_create_rejects_reserved_distinct_id(self, _name: str, identifier: str) -> None:
- response = self.client.post(
- self._topics_url(),
- data={"topic": "Why people churn", "interviewee_distinct_ids": [identifier]},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
-
- @parameterized.expand([("sentinel", SHARED_INTERVIEWEE_IDENTIFIER), ("shared_namespace", "shared:abc123")])
- def test_add_interviewee_rejects_reserved_identifier(self, _name: str, identifier: str) -> None:
- topic = UserInterviewTopic.objects.create(team=self.team, created_by=self.user, topic="Why people churn")
- response = self.client.post(
- f"{self._topics_url()}{topic.id}/add_interviewee/",
- data={"identifier": identifier},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
-
-
-class TestRevokeSharedLink(_FeatureFlagEnabledMixin):
- def _topic(self) -> UserInterviewTopic:
- return UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- topic="Alternatives and comparisons",
- questions=[],
- )
-
- def _url(self, topic_id: str) -> str:
- return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/shared_link/"
-
- def _start_call_url(self, token: str) -> str:
- return f"/api/user_interviews/share/{token}/start_call/"
-
- def _token(self, body: dict) -> str:
- return body["interview_url"].rstrip("/").rsplit("/", 1)[-1]
-
- def _enabled_shared_count(self, topic: UserInterviewTopic) -> int:
- return SharingConfiguration.objects.filter(
- interviewee_context__topic=topic,
- interviewee_context__interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER,
- enabled=True,
- ).count()
-
- @patch(
- "products.user_interviews.backend.presentation.webhooks._create_vapi_web_call",
- side_effect=_mock_web_call,
- )
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_delete_revokes_link_and_post_mints_a_fresh_one(self, _create_vapi_web_call) -> None:
- topic = self._topic()
- token1 = self._token(self.client.post(self._url(str(topic.id))).json())
- assert self._enabled_shared_count(topic) == 1
-
- assert self.client.delete(self._url(str(topic.id))).status_code == status.HTTP_204_NO_CONTENT
- assert self._enabled_shared_count(topic) == 0
-
- token2 = self._token(self.client.post(self._url(str(topic.id))).json())
- assert token2 != token1
- assert self._enabled_shared_count(topic) == 1
-
- # The revoked URL can no longer start a call; the freshly minted one can.
- self.client.logout()
- revoked = self.client.post(self._start_call_url(token1), data={"name": "Robin"}, format="json")
- assert revoked.status_code == status.HTTP_404_NOT_FOUND
- fresh = self.client.post(self._start_call_url(token2), data={"name": "Robin"}, format="json")
- assert fresh.status_code == status.HTTP_200_OK
-
-
-class TestSharedInterviewPublicViewer(APIBaseTest):
- def _shared_config(self) -> SharingConfiguration:
- topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- topic="Alternatives and comparisons",
- agent_context="internal only",
- questions=["q1"],
- )
- return _make_shared_config(team=self.team, topic=topic, created_by=self.user)
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- @mock_exporter_template
- def test_public_viewer_marks_payload_shared_and_not_already_replied(self) -> None:
- config = self._shared_config()
- self.client.logout()
- response = self.client.get(f"/interview/{config.access_token}")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- body = response.content.decode()
- self.assertIn("interview", body)
- self.assertIn(config.access_token, body)
- self.assertIn("Alternatives and comparisons", body)
- # agent_context and Vapi creds stay off the HTML, same as the personalised viewer.
- self.assertNotIn("internal only", body)
- self.assertNotIn("pk_test", body)
-
-
-class TestSharedStartCall(APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- patcher = patch(
- "products.user_interviews.backend.presentation.webhooks._create_vapi_web_call",
- side_effect=_mock_web_call,
- )
- self.create_vapi_web_call = patcher.start()
- self.addCleanup(patcher.stop)
-
- def _shared_config(self) -> SharingConfiguration:
- topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- topic="Alternatives and comparisons",
- agent_context="topic ctx",
- questions=["What were you comparing?"],
- )
- return _make_shared_config(team=self.team, topic=topic, created_by=self.user)
-
- def _url(self, token: str | None) -> str:
- return f"/api/user_interviews/share/{token}/start_call/"
-
- _SESSION_ID_V7 = "018f0b7a-0000-7000-8000-000000000000"
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_carries_respondent_name_and_valid_linkage_into_metadata(self) -> None:
- config = self._shared_config()
- self.client.logout()
- response = self.client.post(
- self._url(config.access_token),
- data={
- "name": "Robin",
- "respondent_key": "resp-123",
- "distinct_id": "person-abc",
- "session_id": self._SESSION_ID_V7,
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- metadata = self.create_vapi_web_call.call_args.args[0]["metadata"]
- assert metadata["shared"] == "true"
- assert metadata["respondent_name"] == "Robin"
- # The identifier is namespaced on the respondent_key, never the provided distinct_id — so a
- # respondent can't attribute themselves to a targeted invitee. The distinct_id rides in its
- # own field as best-effort, untrusted linkage.
- assert metadata["interviewee_identifier"] == "shared:resp-123"
- assert metadata["distinct_id"] == "person-abc"
- assert metadata["session_id"] == self._SESSION_ID_V7
- assert metadata["sharing_access_token"] == config.access_token
- # The self-reported name greets the respondent.
- assert "Robin" in self.create_vapi_web_call.call_args.args[0]["firstMessage"]
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_drops_invalid_linkage_but_still_starts(self) -> None:
- # Invalid linkage is a reason to ignore the hint, not to reject the interview: a non-UUIDv7
- # session_id and an illegal distinct_id ("anonymous") are dropped, and the call still starts.
- config = self._shared_config()
- self.client.logout()
- response = self.client.post(
- self._url(config.access_token),
- data={"name": "Robin", "distinct_id": "anonymous", "session_id": "not-a-uuid"},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- metadata = self.create_vapi_web_call.call_args.args[0]["metadata"]
- assert metadata["session_id"] == ""
- # Illegal distinct_id is dropped from the linkage field; the identifier is still a namespaced
- # shared marker (never the self-reported name), so same-named respondents can't collide.
- assert metadata["distinct_id"] == ""
- assert metadata["interviewee_identifier"].startswith("shared:")
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_missing_name_is_rejected(self) -> None:
- config = self._shared_config()
- self.client.logout()
- response = self.client.post(
- self._url(config.access_token),
- data={"respondent_key": "resp-123"},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- assert response.json() == {"error": "name is required"}
-
- @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
- def test_honeypot_filled_is_rejected(self) -> None:
- config = self._shared_config()
- self.client.logout()
- response = self.client.post(
- self._url(config.access_token),
- data={"name": "Robin", "_hp": "http://spam.example"},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-
-
-class TestSharedVapiWebhook(APIBaseTest):
- def _shared_config(self) -> SharingConfiguration:
- topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- topic="Alternatives and comparisons",
- questions=[],
- )
- return _make_shared_config(team=self.team, topic=topic, created_by=self.user)
-
- def _payload(
- self, token: str | None, *, call_id: str, respondent_key: str, transcript: str, name: str = "Robin"
- ) -> dict:
- return {
- "message": {
- "type": "end-of-call-report",
- "call": {
- "id": call_id,
- "metadata": {
- "sharing_access_token": token,
- "shared": "true",
- "respondent_name": name,
- "respondent_key": respondent_key,
- # start_call namespaces the identifier on respondent_key and keeps the untrusted
- # distinct_id in its own field.
- "interviewee_identifier": f"shared:{respondent_key}",
- "distinct_id": "person-abc",
- "session_id": "018f0b7a-0000-7000-8000-000000000000",
- },
- },
- "transcript": transcript,
- "summary": "",
- }
- }
-
- def _signed_post(self, secret: str, payload: dict) -> Any:
- body = json.dumps(payload)
- signature = hmac.new(secret.encode(), body.encode(), hashlib.sha256).hexdigest()
- return self.client.post(
- "/api/user_interviews/vapi_webhook/",
- data=body,
- content_type="application/json",
- HTTP_X_VAPI_SIGNATURE=signature,
- )
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_persists_respondent_and_linkage_for_topic_share(self) -> None:
- config = self._shared_config()
- self.client.logout()
- response = self._signed_post(
- "topsecret",
- self._payload(config.access_token, call_id="call_1", respondent_key="resp-1", transcript="a real answer"),
- )
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
- interview = UserInterview.objects.get(team=self.team)
- assert config.interviewee_context is not None
- assert interview.topic_id == config.interviewee_context.topic_id
- assert interview.respondent_name == "Robin"
- # The identifier is namespaced on respondent_key; the untrusted distinct_id is stored in its
- # own column, never as the identifier.
- assert interview.interviewee_identifier == "shared:resp-1"
- assert interview.distinct_id == "person-abc"
- assert interview.interviewee_emails == []
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
- def test_session_id_rides_on_the_lifecycle_event(self, mock_scoped_capture) -> None:
- # session_id isn't persisted on the model — it's attached to the conversation event as
- # $session_id so the interview associates with the session recording.
- mock_capture = mock_scoped_capture.return_value.__enter__.return_value
- config = self._shared_config()
- self.client.logout()
- response = self._signed_post(
- "topsecret",
- self._payload(config.access_token, call_id="call_s", respondent_key="resp-s", transcript="hi"),
- )
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
- ended = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "user_interview_conversation_ended"]
- assert ended, "expected a conversation_ended event"
- assert ended[0].kwargs["properties"]["$session_id"] == "018f0b7a-0000-7000-8000-000000000000"
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_shared_response_cannot_impersonate_or_lock_out_a_targeted_invitee(self) -> None:
- # A shared respondent forges a targeted invitee's identifier as their linkage. It must not
- # become the stored identifier (no forged attribution) and must not gate the invitee's
- # personalised link (no lockout) — the core IDOR the namespaced identity prevents.
- topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic="Alternatives and comparisons",
- questions=[],
- )
- config = _make_shared_config(team=self.team, topic=topic, created_by=self.user)
- payload = self._payload(
- config.access_token, call_id="call_x", respondent_key="attacker", transcript="a full answer"
- )
- # Forge the target's identifier in both the echoed identifier and the linkage field.
- payload["message"]["call"]["metadata"]["interviewee_identifier"] = "[email protected]"
- payload["message"]["call"]["metadata"]["distinct_id"] = "[email protected]"
- self.client.logout()
- response = self._signed_post("topsecret", payload)
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
-
- interview = UserInterview.objects.get(team=self.team)
- # Stored under a namespaced shared identity, never the targeted invitee's; the forged linkage
- # is kept only in the untrusted distinct_id field.
- assert interview.interviewee_identifier == "shared:attacker"
- assert interview.distinct_id == "[email protected]"
- # The targeted invitee's personalised link is NOT marked replied.
- assert not has_replied(team_id=self.team.id, topic_id=topic.id, interviewee_identifier="[email protected]")
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_completed_response_supersedes_abandoned_partial_from_a_refresh(self) -> None:
- config = self._shared_config()
- assert config.interviewee_context is not None
- topic = config.interviewee_context.topic
- # Simulate the abandoned partial an accidental refresh leaves behind: an AI-only transcript
- # (the respondent never spoke), which is what auto-derives as abandoned and is safe to collapse.
- abandoned = UserInterview.objects.create(
- team=self.team,
- created_by=self.user,
- topic=topic,
- interviewee_identifier="shared:resp-1",
- respondent_key="resp-1",
- transcript="AI: Hey! Thanks for making time. Ready to start?",
- classifications=[UserInterviewClassification.ABANDONED],
- )
- self.client.logout()
- response = self._signed_post(
- "topsecret",
- self._payload(config.access_token, call_id="call_2", respondent_key="resp-1", transcript="a full answer"),
- )
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
- # The abandoned partial is gone; only the completed response remains for this respondent.
- assert not UserInterview.objects.filter(pk=abandoned.pk).exists()
- remaining = UserInterview.objects.filter(team=self.team, respondent_key="resp-1")
- assert remaining.count() == 1
- assert remaining.first().transcript == "a full answer" # type: ignore[union-attr]
-
- @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_manually_tagged_real_response_is_not_collapsed(self) -> None:
- # A real response a curator re-tagged `abandoned` (it contains interviewee turns) must survive
- # the collapse — the delete re-derives from the transcript, so only genuine AI-only partials go.
- # `abandoned` is user-mutable, so trusting the stored label would permanently delete real data.
- config = self._shared_config()
- assert config.interviewee_context is not None
- topic = config.interviewee_context.topic
- real = UserInterview.objects.create(
- team=self.team,
- created_by=self.user,
- topic=topic,
- interviewee_identifier="shared:resp-9",
- respondent_key="resp-9",
- transcript="AI: How do you use this?\nUser: Every day — it's core to my workflow.",
- classifications=[UserInterviewClassification.ABANDONED],
- )
- self.client.logout()
- response = self._signed_post(
- "topsecret",
- self._payload(config.access_token, call_id="call_9", respondent_key="resp-9", transcript="a full answer"),
- )
- self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
- # The mislabeled real response is preserved (it has interviewee turns, so it doesn't re-derive
- # as abandoned); only genuine AI-only partials are collapsed.
- assert UserInterview.objects.filter(pk=real.pk).exists()
diff --git a/products/user_interviews/backend/test_user_interviews_list.py b/products/user_interviews/backend/test_user_interviews_list.py
deleted file mode 100644
index 84f31b8e2de1..000000000000
--- a/products/user_interviews/backend/test_user_interviews_list.py
+++ /dev/null
@@ -1,160 +0,0 @@
-from posthog.test.base import APIBaseTest
-from unittest.mock import patch
-
-from parameterized import parameterized
-from rest_framework import status
-
-from posthog.models.team import Team
-
-from products.user_interviews.backend.models import UserInterview, UserInterviewTopic
-
-
-class TestUserInterviewsListFilters(APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- patcher = patch("posthoganalytics.feature_enabled", return_value=True)
- patcher.start()
- self.addCleanup(patcher.stop)
-
- def _list_url(self, team: Team | None = None) -> str:
- return f"/api/environments/{(team or self.team).id}/user_interviews/"
-
- def _create_topic(self, topic_text: str, team: Team | None = None) -> UserInterviewTopic:
- return UserInterviewTopic.objects.create(
- team=team or self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic=topic_text,
- )
-
- def _create_interview(
- self,
- *,
- topic: UserInterviewTopic | None,
- summary: str,
- team: Team | None = None,
- classifications: list[str] | None = None,
- ) -> UserInterview:
- return UserInterview.objects.create(
- team=team or self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- transcript="Hello world",
- summary=summary,
- topic=topic,
- classifications=classifications or [],
- )
-
- @parameterized.expand(
- [
- ("no filter returns all interviews", None, {"A1", "A2", "B1", "orphan"}),
- ("topic A filter narrows to that topic", "topic_a", {"A1", "A2"}),
- ("topic B filter narrows to that topic", "topic_b", {"B1"}),
- ("topic with zero interviews returns empty set", "topic_c", set()),
- ]
- )
- def test_topic_filter(self, _name: str, filter_topic_key: str | None, expected_summaries: set[str]) -> None:
- topic_a = self._create_topic("Topic A")
- topic_b = self._create_topic("Topic B")
- topic_c = self._create_topic("Topic C")
- self._create_interview(topic=topic_a, summary="A1")
- self._create_interview(topic=topic_a, summary="A2")
- self._create_interview(topic=topic_b, summary="B1")
- self._create_interview(topic=None, summary="orphan")
-
- params = (
- {}
- if filter_topic_key is None
- else {"topic": str({"topic_a": topic_a.id, "topic_b": topic_b.id, "topic_c": topic_c.id}[filter_topic_key])}
- )
- response = self.client.get(self._list_url(), params)
-
- assert response.status_code == status.HTTP_200_OK, response.content
- summaries = {row["summary"] for row in response.json()["results"]}
- assert summaries == expected_summaries
-
- def test_list_does_not_leak_interviews_across_teams(self) -> None:
- other_team = Team.objects.create(organization=self.organization, name="other team")
- other_topic = self._create_topic("Other team topic", team=other_team)
- self._create_interview(topic=other_topic, summary="other-team-secret", team=other_team)
- own_topic = self._create_topic("Own topic")
- self._create_interview(topic=own_topic, summary="own-team-summary")
-
- plain_list = self.client.get(self._list_url())
- assert plain_list.status_code == status.HTTP_200_OK, plain_list.content
- summaries = {row["summary"] for row in plain_list.json()["results"]}
- assert summaries == {"own-team-summary"}
-
- filtered_by_other_team_topic = self.client.get(self._list_url(), {"topic": str(other_topic.id)})
- assert filtered_by_other_team_topic.status_code == status.HTTP_200_OK, filtered_by_other_team_topic.content
- assert filtered_by_other_team_topic.json()["results"] == []
-
- @parameterized.expand(
- [
- ("no classification filter returns all", None, {"abandoned-one", "off-topic-one", "unclassified"}),
- ("single classification", "abandoned", {"abandoned-one"}),
- ("multiple classifications are OR", "abandoned,off-topic", {"abandoned-one", "off-topic-one"}),
- ("classification with no matches", "off-topic", {"off-topic-one"}),
- ]
- )
- def test_classifications_filter(
- self, _name: str, classifications_param: str | None, expected_summaries: set[str]
- ) -> None:
- topic = self._create_topic("Classified topic")
- self._create_interview(topic=topic, summary="abandoned-one", classifications=["abandoned"])
- self._create_interview(topic=topic, summary="off-topic-one", classifications=["off-topic"])
- self._create_interview(topic=topic, summary="unclassified", classifications=[])
-
- params = {} if classifications_param is None else {"classifications": classifications_param}
- response = self.client.get(self._list_url(), params)
-
- assert response.status_code == status.HTTP_200_OK, response.content
- summaries = {row["summary"] for row in response.json()["results"]}
- assert summaries == expected_summaries
-
- def test_list_rejects_unknown_classification(self) -> None:
- topic = self._create_topic("Classified topic")
- self._create_interview(topic=topic, summary="abandoned-one", classifications=["abandoned"])
-
- response = self.client.get(self._list_url(), {"classifications": "abandoned,bogus"})
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
-
- def test_partial_update_replaces_classifications(self) -> None:
- topic = self._create_topic("Classified topic")
- interview = self._create_interview(topic=topic, summary="resp", classifications=["abandoned"])
-
- response = self.client.patch(
- f"{self._list_url()}{interview.id}/",
- {"classifications": ["off-topic"]},
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK, response.content
- assert set(response.json()["classifications"]) == {"off-topic"}
- interview.refresh_from_db()
- assert set(interview.classifications) == {"off-topic"}
-
- def test_partial_update_rejects_unknown_classification(self) -> None:
- topic = self._create_topic("Classified topic")
- interview = self._create_interview(topic=topic, summary="resp", classifications=[])
-
- response = self.client.patch(
- f"{self._list_url()}{interview.id}/",
- {"classifications": ["bogus"]},
- format="json",
- )
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
-
- def test_retrieve_returns_full_transcript_and_summary(self) -> None:
- topic = self._create_topic("Topic A")
- interview = self._create_interview(topic=topic, summary="Full summary text")
-
- response = self.client.get(f"{self._list_url()}{interview.id}/")
-
- assert response.status_code == status.HTTP_200_OK, response.content
- body = response.json()
- assert body["summary"] == "Full summary text"
- assert body["transcript"] == "Hello world"
- assert body["topic"] == str(topic.id)
diff --git a/products/user_interviews/backend/test_vapi_task.py b/products/user_interviews/backend/test_vapi_task.py
deleted file mode 100644
index 0cebc71d186e..000000000000
--- a/products/user_interviews/backend/test_vapi_task.py
+++ /dev/null
@@ -1,120 +0,0 @@
-from typing import Any
-
-from posthog.test.base import APIBaseTest
-
-from django.db import InterfaceError, OperationalError, connection
-from django.test.utils import CaptureQueriesContext
-
-from parameterized import parameterized
-
-from posthog.celery import app as celery_app
-
-from products.user_interviews.backend.models import IntervieweeContext, UserInterview, UserInterviewTopic
-from products.user_interviews.backend.tasks.tasks import handle_vapi_webhook
-
-TASK_NAME = "products.user_interviews.backend.tasks.handle_vapi_webhook"
-
-
-class TestVapiWebhookTask(APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- self.topic = UserInterviewTopic.objects.create(
- team=self.team,
- created_by=self.user,
- interviewee_emails=["[email protected]"],
- topic="Replay adoption",
- agent_context="ctx",
- questions=[],
- )
- self.interviewee_context = IntervieweeContext.objects.create(
- team=self.team,
- topic=self.topic,
- interviewee_identifier="[email protected]",
- agent_context="",
- created_by=self.user,
- )
-
- def _report(self, call_id: str = "call_abc") -> dict[str, Any]:
- return {
- "message": {
- "type": "end-of-call-report",
- "call": {"id": call_id, "duration": 120},
- "transcript": "Hi! ...",
- "summary": "User talked about replay.",
- "recording": {"url": "https://vapi.example/recording.mp3"},
- }
- }
-
- def _run(self, payload: dict[str, Any]) -> None:
- handle_vapi_webhook(
- payload=payload,
- event_type="end-of-call-report",
- team_id=self.team.pk,
- topic_id=str(self.topic.pk),
- interviewee_context_id=str(self.interviewee_context.pk),
- interviewee_identifier="[email protected]",
- received_at="2026-05-14T12:00:00+00:00",
- )
-
- def test_task_is_registered_under_the_name_a_publisher_sends(self):
- # The name is the contract between the web pod that publishes and the worker that runs the
- # task. A worker that does not know the name drops the message, and Vapi never resends.
- self.assertIn(TASK_NAME, celery_app.tasks)
-
- def test_task_survives_a_database_error_and_a_lost_worker(self):
- # Both settings are silently inert when missing: max_retries without autoretry_for never
- # retries, and the default early acknowledgement drops the report when the worker dies.
- self.assertEqual(handle_vapi_webhook.autoretry_for, (OperationalError, InterfaceError))
- self.assertTrue(handle_vapi_webhook.acks_late)
- self.assertTrue(handle_vapi_webhook.reject_on_worker_lost)
- # The default backoff spends every attempt within seconds, which is shorter than any
- # database outage worth retrying through, and Vapi never resends the report.
- window_seconds = sum(
- min(handle_vapi_webhook.retry_backoff * 2**attempt, handle_vapi_webhook.retry_backoff_max)
- for attempt in range(handle_vapi_webhook.max_retries)
- )
- self.assertGreater(window_seconds, 60 * 60)
-
- @parameterized.expand([("null_message", {"message": None}), ("null_call", {"message": {"call": None}})])
- def test_task_survives_a_null_message_or_call(self, _name: str, payload: dict[str, Any]) -> None:
- # A JSON null where the message or call object goes must not raise: an AttributeError is
- # outside the task's retry list. Without a call id there is no idempotency either, so the
- # report must not become a blank interview on every redelivery.
- self._run(payload)
-
- self.assertFalse(UserInterview.objects.filter(team=self.team).exists())
-
- def test_task_stores_the_report(self):
- self._run(self._report())
-
- interview = UserInterview.objects.get(team=self.team)
- self.assertEqual(interview.topic, self.topic)
- self.assertEqual(interview.interviewee_identifier, "[email protected]")
- self.assertEqual(interview.transcript, "Hi! ...")
- self.assertEqual(interview.recording_url, "https://vapi.example/recording.mp3")
- # The report can wait in the queue through an outage, so the interview keeps the time the
- # endpoint accepted it rather than the time the worker got to it.
- self.assertEqual(interview.created_at.isoformat(), "2026-05-14T12:00:00+00:00")
-
- def test_task_serializes_persistence_per_call_id(self):
- # No unique constraint keeps a call to one row, so two runs that overlap have to queue
- # behind an advisory lock on the call id instead of both passing the existence check.
- with CaptureQueriesContext(connection) as queries:
- self._run(self._report(call_id="call_xyz"))
-
- statements = [query["sql"] for query in queries.captured_queries]
- locks = [index for index, sql in enumerate(statements) if "pg_advisory_xact_lock" in sql]
- inserts = [index for index, sql in enumerate(statements) if "INSERT INTO" in sql and "userinterview" in sql]
- self.assertEqual(len(locks), 1)
- self.assertIn(f"user_interviews_vapi_call:{self.team.id}:call_xyz", statements[locks[0]])
- self.assertTrue(inserts)
- self.assertLess(locks[0], inserts[0])
-
- def test_a_second_run_of_the_same_call_stores_nothing(self):
- # The task acknowledges late and retries a transient database error, so one call can
- # reach two runs.
- payload = self._report()
- self._run(payload)
- self._run(payload)
-
- self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)
diff --git a/products/user_interviews/backend/vapi_events.py b/products/user_interviews/backend/vapi_events.py
deleted file mode 100644
index 69848b8bd77a..000000000000
--- a/products/user_interviews/backend/vapi_events.py
+++ /dev/null
@@ -1,390 +0,0 @@
-"""User interviews' handling of the inbound Vapi webhook.
-
-``handle_vapi_webhook_delivery`` runs in the Celery task that the ingress vapi consumer
-enqueues through ``facade.api.accept_vapi_event``. It persists a UserInterview row attributed
-to the topic creator, idempotent on ``call.id``.
-"""
-
-from collections.abc import Mapping
-from datetime import datetime
-from typing import Any
-
-from django.db import connection, transaction
-
-import structlog
-
-from posthog.schema import EmbeddingModelName
-
-from posthog.api.embedding_worker import emit_embedding_request
-from posthog.event_usage import groups
-from posthog.models.team import Team
-from posthog.ph_client import ph_scoped_capture
-
-from products.user_interviews.backend.classification import derive_auto_classifications
-from products.user_interviews.backend.logic import (
- RESPONDENT_KEY_MAX_CHARS,
- RESPONDENT_NAME_MAX_CHARS,
- clean_field,
- is_shared_interviewee_context,
- shared_interviewee_identifier,
- valid_distinct_id,
- valid_session_id,
-)
-from products.user_interviews.backend.models import UserInterview, UserInterviewClassification, UserInterviewTopic
-
-logger = structlog.get_logger(__name__)
-
-_EMBEDDING_MODELS = [m.value for m in EmbeddingModelName]
-
-# TODO: figure out a better story for transcripts that exceed our Kafka envelope
-# than head-truncation. Options: (a) chunk + emit multiple documents per type, or
-# (b) push large content to object storage and embed a reference. Truncation is a
-# stop-gap so a 90-minute interview doesn't silently lose its embeddings entirely.
-EMBEDDING_CONTENT_MAX_BYTES = 750_000
-
-
-def _emit_interview_embeddings(interview: UserInterview, topic: UserInterviewTopic) -> None:
- """Emit transcript and summary as two separate embedding documents so each can be
- searched independently. Failures are logged but never propagated: Vapi retries are
- idempotent on call.id, so a re-delivery would skip creation and never re-emit —
- making a thrown exception here strictly worse than a degraded but acknowledged row."""
- metadata = {
- "topic_id": str(topic.id),
- "interviewee_identifier": interview.interviewee_identifier,
- }
- for document_type, content in (("transcript", interview.transcript), ("summary", interview.summary)):
- if not content or not content.strip():
- continue
- content_bytes = content.encode("utf-8")
- if len(content_bytes) > EMBEDDING_CONTENT_MAX_BYTES:
- logger.warning(
- "user_interviews_embedding_content_truncated",
- team_id=interview.team_id,
- interview_id=str(interview.id),
- document_type=document_type,
- original_bytes=len(content_bytes),
- truncated_to_bytes=EMBEDDING_CONTENT_MAX_BYTES,
- )
- content = content_bytes[:EMBEDDING_CONTENT_MAX_BYTES].decode("utf-8", errors="ignore")
- try:
- emit_embedding_request(
- content=content,
- team_id=interview.team_id,
- product="user_interviews",
- document_type=document_type,
- rendering="plain",
- document_id=str(interview.id),
- models=_EMBEDDING_MODELS,
- metadata=metadata,
- )
- except Exception:
- logger.exception(
- "user_interviews_embedding_emit_failed",
- team_id=interview.team_id,
- interview_id=str(interview.id),
- document_type=document_type,
- )
-
-
-def _collapse_abandoned_partials(*, team: Team, topic: UserInterviewTopic, respondent_key: str, keep_pk: Any) -> None:
- """Delete the abandoned partial an accidental mid-call refresh leaves behind, when the same
- respondent (same ``respondent_key``) comes back and finishes — so the topic shows one response
- per respondent instead of a junk trail.
-
- Deletes only rows that STILL auto-derive as ``abandoned`` from their own transcript, rather than
- trusting the stored label. ``abandoned`` is user-mutable (writable via the update API and the MCP
- tool), so a real response a curator manually re-tagged ``abandoned`` would otherwise be
- permanently, unrecoverably deleted here. Re-deriving keeps this a cleanup of genuine AI-only
- partials and never touches a row that contains real interviewee content.
- """
- candidates = (
- UserInterview.objects.filter(
- team=team,
- topic=topic,
- respondent_key=respondent_key,
- classifications__contains=[UserInterviewClassification.ABANDONED],
- )
- .exclude(pk=keep_pk)
- .only("id", "transcript")
- )
- stale_pks = [
- c.pk for c in candidates if UserInterviewClassification.ABANDONED in derive_auto_classifications(c.transcript)
- ]
- if not stale_pks:
- return
- deleted_count, _ = UserInterview.objects.filter(
- team=team,
- topic=topic,
- respondent_key=respondent_key,
- pk__in=stale_pks,
- ).delete()
- logger.info(
- "user_interviews_collapsed_abandoned_partials",
- team_id=team.id,
- topic_id=str(topic.id),
- deleted_count=deleted_count,
- )
-
-
-def _lock_call(team_id: int, call_id: str) -> None:
- """Hold the sole right to store this call's report until the transaction ends.
-
- Nothing in the schema stops a second row for one call. Vapi resends a report whose receipt it
- lost, the endpoint asks for a resend when the enqueue fails, and the task is acknowledged after
- the run, so two runs for one call can be in flight together. Without this lock both pass the
- existence check and both insert, which gives the topic two interviews for one call and emits
- the embeddings twice. The run that loses waits here until the winner commits, and its next read
- then sees the row.
- """
- with connection.cursor() as cursor:
- cursor.execute(
- "SELECT pg_advisory_xact_lock(hashtext(%s))",
- [f"user_interviews_vapi_call:{team_id}:{call_id}"],
- )
-
-
-def _capture_user_interview_event(
- event: str,
- *,
- team: Team,
- topic_id: str,
- interviewee_context_id: str,
- call_id: str | None,
- received_at: str | None,
- session_id: str = "",
- extra_properties: dict[str, Any] | None = None,
-) -> None:
- """Fire a PostHog event for a user-interview lifecycle moment (conversation started/ended).
- Failures never propagate — analytics never blocks a webhook delivery.
-
- Vapi emits `status-update` per state transition and may re-fire `in-progress` after
- transient drops or warm-transfer flows, and end-of-call-report can be retried by Vapi
- until we ack. Set `$insert_id` to `<event>:<call_id>` so PostHog dedupes the second
- delivery at ingest — funnels see one start and one end per call.
-
- The event carries the moment the endpoint received the delivery, not the moment this ran. The
- worker runs after the request, and later again on a retry, so the run time would put
- "conversation started" after "conversation ended" for the same call.
-
- When a shared-link respondent supplied a valid session_id, it's attached as `$session_id` so
- the event (and thus the interview) associates with that session recording — this is how the
- session is linked without a dedicated DB column.
-
- The `distinct_id` is intentionally an opaque per-share UUID — *not* the interviewee's
- email/distinct_id — so these feature-usage events never create person profiles for the
- third-party interviewees themselves. The events report on the user_interviews feature, not
- the people being interviewed."""
- properties: dict[str, Any] = {
- "topic_id": topic_id,
- "team_id": team.id,
- "call_id": call_id,
- }
- if session_id:
- properties["$session_id"] = session_id
- if call_id:
- properties["$insert_id"] = f"{event}:{call_id}"
- if extra_properties:
- properties.update(extra_properties)
- try:
- # This runs in the Celery task, where the global client's background flush may never run
- # before the worker exits, so the event is lost without a word. The scoped client flushes
- # when the context exits. A run emits at most one event, so the client is opened once.
- with ph_scoped_capture() as capture:
- capture(
- distinct_id=f"user_interview:{interviewee_context_id}",
- event=event,
- properties=properties,
- timestamp=received_at,
- groups=groups(organization=team.organization, team=team),
- )
- except Exception:
- logger.exception(
- "user_interviews_event_capture_failed",
- event=event,
- team_id=team.id,
- call_id=call_id,
- )
-
-
-def _backdate_to_receipt(interview: UserInterview, received_at: str | None) -> None:
- """Stamp the interview with the time the endpoint accepted the report, not the worker's."""
- if not received_at:
- return
- try:
- accepted_at = datetime.fromisoformat(received_at)
- except ValueError:
- return
- # created_at is auto_now_add, so the row must be updated after the insert.
- UserInterview.objects.filter(pk=interview.pk).update(created_at=accepted_at)
- interview.created_at = accepted_at
-
-
-def handle_vapi_webhook_delivery(
- payload: Mapping[str, Any],
- event_type: str,
- *,
- team_id: int,
- topic_id: str,
- interviewee_context_id: str,
- interviewee_identifier: str,
- received_at: str | None,
-) -> None:
- """Act on one verified Vapi delivery: the lifecycle event, and the end-of-call report.
-
- The share is not read here. ``accept_vapi_event`` resolved the token in the request, before
- the endpoint accepted the delivery, and took out of the share everything this needs. The
- share row does not survive the wait: the team can disable it, its token can leave the
- rotation grace period, and ``cleanup_expired_sharing_configs`` then deletes the row itself.
- Each of those would turn an accepted report into nothing. The topic and the interviewee
- context the share names outlive it.
-
- Idempotent on ``call.id`` (stored in ``call_metadata.id``). Vapi repeats that id across the
- status update and the end-of-call report, so ingress cannot dedup on it and this does
- instead: a repeat delivery of a report already stored creates nothing. The idempotency also
- covers the Celery retry that persistence rides on, and an advisory lock holds it when two of
- those runs overlap.
- """
- message: dict[str, Any] = payload.get("message") or {}
- call: dict[str, Any] = message.get("call") or {}
- # Vapi can surface our `assistant_overrides.metadata` (set in `start_call`) in two
- # places on the Call object: `call.metadata` for some message types, and nested under
- # `call.assistantOverrides.metadata` on others. Empirically end-of-call-report comes
- # through with the nested form, so try both.
- overrides_metadata: dict[str, Any] = (call.get("assistantOverrides") or {}).get("metadata") or {}
- top_metadata: dict[str, Any] = call.get("metadata") or {}
- # Shared-link respondent fields (set in start_call's metadata, echoed back by Vapi). Merge with
- # top-level precedence, mirroring how the access token is resolved when the delivery arrives.
- merged_metadata: dict[str, Any] = {**overrides_metadata, **top_metadata}
- call_id = call.get("id")
- if event_type == "end-of-call-report" and not call_id:
- # The call id is what makes a report idempotent, so a report without one would create a
- # blank interview on every redelivery.
- logger.warning("user_interviews_vapi_webhook_missing_call_id", team_id=team_id, topic_id=topic_id)
- return
-
- topic = (
- UserInterviewTopic.objects.select_related("team", "team__organization", "created_by")
- .filter(team_id=team_id, id=topic_id)
- .first()
- )
- if topic is None:
- # The team deleted the topic while the report waited in the queue, so there is nothing
- # left to file the report under. Say so, because the alternative reads like a delivery
- # that never arrived.
- logger.warning(
- "user_interviews_vapi_webhook_topic_gone",
- team_id=team_id,
- topic_id=topic_id,
- call_id=call_id,
- )
- return
-
- if event_type == "status-update":
- # Lifecycle ping. We only act on `in-progress` (call started) — the `ended` status
- # is followed by a separate `end-of-call-report` with the full transcript, so we
- # capture the ended event from that branch where we already have the interview row.
- call_status = message.get("status")
- if call_status == "in-progress":
- _capture_user_interview_event(
- "user_interview_conversation_started",
- team=topic.team,
- topic_id=topic_id,
- interviewee_context_id=interviewee_context_id,
- call_id=call_id,
- received_at=received_at,
- session_id=valid_session_id(merged_metadata.get("session_id")),
- )
- logger.info(
- "user_interviews_vapi_webhook_status_update",
- call_status=call_status,
- call_id=call_id,
- )
- return
-
- # The consumer registers for status-update and end-of-call-report only, so the registry
- # drops every other message type before this runs and the rest is the end-of-call report.
- recording_url = (message.get("recording") or {}).get("url", "") or message.get("recordingUrl", "") or ""
- transcript = message.get("transcript", "") or ""
- classifications = derive_auto_classifications(transcript)
-
- if is_shared_interviewee_context(interviewee_identifier):
- respondent_name = clean_field(merged_metadata.get("respondent_name"), RESPONDENT_NAME_MAX_CHARS)
- respondent_key = clean_field(merged_metadata.get("respondent_key"), RESPONDENT_KEY_MAX_CHARS)
- # Recompute the identifier from respondent_key rather than trusting the echoed metadata, so it
- # is always a namespaced shared marker and can never be steered onto a targeted invitee.
- stored_identifier = shared_interviewee_identifier(respondent_key)
- interviewee_emails = []
- # Best-effort, untrusted person linkage. Re-validated here (defense in depth) and stored in its
- # own column — never as the interviewee_identifier, so it can't forge attribution.
- distinct_id = valid_distinct_id(merged_metadata.get("distinct_id"))
- # session_id isn't persisted — it rides on the lifecycle event below. Re-validated here
- # (defense in depth) so only a well-formed UUIDv7 reaches the event.
- session_id = valid_session_id(merged_metadata.get("session_id"))
- else:
- stored_identifier = interviewee_identifier
- interviewee_emails = [stored_identifier] if "@" in stored_identifier else []
- respondent_name = respondent_key = ""
- distinct_id = ""
- session_id = ""
-
- with transaction.atomic():
- if call_id:
- _lock_call(team_id, call_id)
- existing = UserInterview.objects.filter(team_id=team_id, call_metadata__id=call_id).first()
- if existing is not None:
- logger.info(
- "user_interviews_vapi_webhook_duplicate",
- team_id=team_id,
- interview_id=str(existing.id),
- call_id=call_id,
- )
- return
- interview = UserInterview.objects.create(
- team=topic.team,
- topic=topic,
- interviewee_identifier=stored_identifier,
- interviewee_emails=interviewee_emails,
- respondent_name=respondent_name,
- respondent_key=respondent_key,
- distinct_id=distinct_id,
- transcript=transcript,
- summary=message.get("summary", "") or "",
- recording_url=recording_url,
- call_metadata=call,
- created_by=topic.created_by,
- classifications=classifications,
- )
- _backdate_to_receipt(interview, received_at)
- # Collapse the abandoned partial an accidental refresh leaves behind: when a shared-link
- # respondent comes back (same respondent_key) and finishes, drop their earlier abandoned
- # rows so the topic shows one response per respondent instead of a junk trail.
- if respondent_key and UserInterviewClassification.ABANDONED not in classifications:
- _collapse_abandoned_partials(
- team=topic.team,
- topic=topic,
- respondent_key=respondent_key,
- keep_pk=interview.pk,
- )
- transaction.on_commit(lambda: _emit_interview_embeddings(interview, topic))
-
- _capture_user_interview_event(
- "user_interview_conversation_ended",
- team=topic.team,
- topic_id=topic_id,
- interviewee_context_id=interviewee_context_id,
- call_id=call_id,
- received_at=received_at,
- session_id=session_id,
- extra_properties={
- "interview_id": str(interview.id),
- "had_transcript": bool(interview.transcript),
- "had_summary": bool(interview.summary),
- },
- )
-
- logger.info(
- "user_interviews_vapi_webhook_stored",
- team_id=team_id,
- topic_id=topic_id,
- interview_id=str(interview.id),
- )
diff --git a/products/user_interviews/backend/webhook_consumers.py b/products/user_interviews/backend/webhook_consumers.py
deleted file mode 100644
index 666028d95bf4..000000000000
--- a/products/user_interviews/backend/webhook_consumers.py
+++ /dev/null
@@ -1,23 +0,0 @@
-"""User interviews' consumer on the Vapi endpoint."""
-
-from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery
-from posthog.ingress.vapi.provider import VAPI_EVENT_TYPES
-
-
-def _queue_interview_storage(delivery: WebhookDelivery) -> None:
- from products.user_interviews.backend.facade.api import ( # noqa: PLC0415 - keeps the product's models and the Celery app off the registry's import path
- accept_vapi_event,
- )
-
- accept_vapi_event(delivery)
-
-
-WEBHOOK_CONSUMERS = (
- WebhookConsumer(
- name="user_interviews_vapi",
- provider="vapi",
- app="default",
- event_types=VAPI_EVENT_TYPES,
- handler=_queue_interview_storage,
- ),
-)
diff --git a/products/user_interviews/frontend/InterviewLinkCopyButton.tsx b/products/user_interviews/frontend/InterviewLinkCopyButton.tsx
deleted file mode 100644
index 6c506b31ee07..000000000000
--- a/products/user_interviews/frontend/InterviewLinkCopyButton.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useValues } from 'kea'
-
-import { IconCopy } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
-
-import { copyToClipboard } from 'lib/utils/copyToClipboard'
-
-import { userInterviewLogic } from './userInterviewLogic'
-
-export function InterviewLinkCopyButton({ identifier, topicId }: { identifier: string; topicId: string }): JSX.Element {
- const { linkForIdentifier, linksLoading, linksLoadFailed } = useValues(userInterviewLogic({ id: topicId }))
- const interviewUrl = linkForIdentifier(identifier)
-
- const handleCopy = (e: React.MouseEvent): void => {
- e.preventDefault()
- e.stopPropagation()
- if (!interviewUrl) {
- return
- }
- void copyToClipboard(interviewUrl, 'interview link')
- }
-
- const disabledReason = interviewUrl
- ? undefined
- : linksLoadFailed
- ? "Couldn't generate link — refresh to retry"
- : linksLoading
- ? 'Generating link…'
- : 'No link available'
-
- return (
- <LemonButton
- type="tertiary"
- size="xsmall"
- icon={<IconCopy />}
- onClick={handleCopy}
- disabledReason={disabledReason}
- tooltip="Copy interview link"
- />
- )
-}
diff --git a/products/user_interviews/frontend/InvitePreviewModal.stories.tsx b/products/user_interviews/frontend/InvitePreviewModal.stories.tsx
deleted file mode 100644
index 18437fe49d03..000000000000
--- a/products/user_interviews/frontend/InvitePreviewModal.stories.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/react'
-
-import type { PreviewInviteResultApi } from './generated/api.schemas'
-import { InvitePreviewModal } from './UserInterview'
-
-const meta: Meta<typeof InvitePreviewModal> = {
- title: 'Scenes-App/User Interviews/Invite Preview Modal',
- component: InvitePreviewModal,
- parameters: {
- layout: 'fullscreen',
- testOptions: {
- waitForSelector: '.LemonModal',
- waitForLoadersToDisappear: false,
- },
- },
-}
-export default meta
-
-type Story = StoryObj<typeof InvitePreviewModal>
-
-const emailHtml = `<!DOCTYPE html>
-<html>
-<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif; color: #2d2d2d; max-width: 560px; margin: 0 auto; padding: 24px;">
- <h1 style="font-size: 22px; margin-bottom: 24px;">Got 5 minutes to chat?</h1>
- <p>Hey Alex,</p>
- <p>We're researching <strong>creating insights with the MCP integration</strong> and your perspective would be really valuable. Got 5&ndash;10 minutes for a quick voice conversation?</p>
- <p>It's a casual call with an AI interviewer &mdash; not a sales call, just research. You can do it whenever's convenient in the next few days.</p>
- <p style="text-align: center; margin: 32px 0;">
- <a href="#" target="_blank" style="background: #1d4aff; color: #ffffff; padding: 12px 24px; border-radius: 6px; text-decoration: none; font-weight: 600;">Start the interview</a>
- </p>
- <p style="font-size: 12px; color: #888;">Or paste this link into your browser: <a href="#">https://us.posthog.com/interview/preview</a></p>
- <p>Thanks!<br />The PostHog team</p>
-</body>
-</html>`
-
-const emailablePreview: PreviewInviteResultApi = {
- interviewee_identifier: '[email protected]',
- user_name: 'Alex',
- email: '[email protected]',
- subject: 'Got 5 minutes to talk about creating insights with the MCP integration?',
- html: emailHtml,
- interview_url: 'https://us.posthog.com/interview/preview',
- emailable: true,
- is_preview_link: true,
-}
-
-export const Emailable: Story = {
- args: {
- isOpen: true,
- onClose: () => {},
- preview: emailablePreview,
- loading: false,
- },
-}
-
-export const Loading: Story = {
- args: {
- isOpen: true,
- onClose: () => {},
- preview: null,
- loading: true,
- },
-}
-
-export const NoEmailAddress: Story = {
- args: {
- isOpen: true,
- onClose: () => {},
- preview: {
- ...emailablePreview,
- interviewee_identifier: 'distinct_id_abc123',
- user_name: 'distinct_id_abc123',
- email: null,
- emailable: false,
- },
- loading: false,
- },
-}
diff --git a/products/user_interviews/frontend/TranscriptChat.stories.tsx b/products/user_interviews/frontend/TranscriptChat.stories.tsx
deleted file mode 100644
index ad2b3a11f35a..000000000000
--- a/products/user_interviews/frontend/TranscriptChat.stories.tsx
+++ /dev/null
@@ -1,122 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/react'
-
-import { PersonType } from '~/types'
-
-import { TranscriptChat } from './TranscriptChat'
-
-const meta: Meta<typeof TranscriptChat> = {
- title: 'Scenes-App/User Interviews/Transcript Chat',
- component: TranscriptChat,
-}
-export default meta
-
-type Story = StoryObj<typeof TranscriptChat>
-
-const fakePerson: PersonType = {
- id: '1',
- uuid: '00000000-0000-0000-0000-000000000000',
- distinct_ids: ['[email protected]'],
- properties: {
- name: 'Alex Example',
- email: '[email protected]',
- },
- created_at: '2024-01-15T12:00:00Z',
- is_identified: true,
-}
-
-const multiTurnTranscript = [
- 'AI: Thanks for making the time. Mind if I ask a few questions about your workflow? Should take about five minutes.',
- 'User: Yep, go ahead.',
- "AI: I see you've created a bunch of insights in the last month through the MCP integration but never via the web UI. Do you ever use the web UI at all?",
- 'User: Honestly, just the MCP integration for me. I do most of my work inside another tool and pull data in from there.',
- 'AI: That makes sense. Walk me through the most recent thing you were trying to figure out.',
- 'User: I was trying to figure out the install rate on iOS, because it matters a lot for our product right now.',
- 'AI: Why reach for MCP for that instead of opening the dashboard yourself?',
- 'User: Having one tool that can synthesize across platforms is really valuable. I would not know where to look in the UI on my own.',
-].join('\n')
-
-const inlineNoNewlinesTranscript =
- 'AI: Hey there, thanks for joining. Could you describe a typical week for you? User: Sure, mostly product work. AI: Where do you feel the most friction? User: Honestly, switching between tools — every context switch costs me momentum.'
-
-const speakerKeywordInBodyTranscript =
- 'AI: When you say the User: experience felt slow, do you mean the loading time or the time-to-first-interaction?\nUser: The loading time.\nAI: Got it.'
-
-const namedSpeakerTranscript = `Assistant: Welcome. Before we dive in, could you tell me what brought you to the product?
-Interviewee: A friend recommended it. We needed a way to track usage without piecing things together ourselves.
-Assistant: And what does success look like for your team in the next quarter?
-Interviewee: Cutting the time it takes to answer a "did this feature move the needle" question from days to minutes.`
-
-const noSpeakerTranscript = `This transcript did not include any speaker labels — perhaps because the
-transcription provider could not segment speakers. The fallback renderer
-should still show this content as plain markdown so nothing is lost.
-
-- It may even contain markdown lists.
-- Or **bold text**.`
-
-const leadingProseTranscript = `Interview started 2026-05-29 with Alex Example.
-AI: Thanks for joining. Walk me through your last week.
-User: Mostly product work — Monday dashboards, Tuesday writing, Thursday customer calls.`
-
-export const KnownPerson: Story = {
- args: {
- transcript: multiTurnTranscript,
- person: fakePerson,
- identifier: '[email protected]',
- },
-}
-
-export const IdentifierOnly: Story = {
- args: {
- transcript: multiTurnTranscript,
- person: null,
- identifier: '[email protected]',
- },
-}
-
-export const InlineNoNewlines: Story = {
- args: {
- transcript: inlineNoNewlinesTranscript,
- person: fakePerson,
- identifier: '[email protected]',
- },
-}
-
-export const SpeakerKeywordInBody: Story = {
- args: {
- transcript: speakerKeywordInBodyTranscript,
- person: fakePerson,
- identifier: '[email protected]',
- },
-}
-
-export const AssistantAndInterviewee: Story = {
- args: {
- transcript: namedSpeakerTranscript,
- person: fakePerson,
- identifier: '[email protected]',
- },
-}
-
-export const FallbackNoSpeakerMarkers: Story = {
- args: {
- transcript: noSpeakerTranscript,
- person: null,
- identifier: 'unknown',
- },
-}
-
-export const FallbackLeadingProse: Story = {
- args: {
- transcript: leadingProseTranscript,
- person: fakePerson,
- identifier: '[email protected]',
- },
-}
-
-export const NonEmailIdentifier: Story = {
- args: {
- transcript: multiTurnTranscript,
- person: null,
- identifier: 'distinct_id_abc123',
- },
-}
diff --git a/products/user_interviews/frontend/TranscriptChat.test.tsx b/products/user_interviews/frontend/TranscriptChat.test.tsx
deleted file mode 100644
index d0ef6a6e2688..000000000000
--- a/products/user_interviews/frontend/TranscriptChat.test.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import { ParsedTranscript, parseTranscript } from './parseTranscript'
-
-const EMPTY: ParsedTranscript = { leadingText: '', turns: [] }
-
-describe('parseTranscript', () => {
- describe.each<[string, string, ParsedTranscript]>([
- ['empty string', '', EMPTY],
- ['no speaker markers falls through to empty', 'Just some prose without any labels at all.', EMPTY],
- [
- 'single AI turn',
- 'AI: Hello there.',
- { leadingText: '', turns: [{ speaker: 'ai', name: 'AI', text: 'Hello there.' }] },
- ],
- [
- 'multi-turn newline-delimited (Vapi format)',
- 'AI: Hi.\nUser: Hello.\nAI: How are you?',
- {
- leadingText: '',
- turns: [
- { speaker: 'ai', name: 'AI', text: 'Hi.' },
- { speaker: 'user', name: 'User', text: 'Hello.' },
- { speaker: 'ai', name: 'AI', text: 'How are you?' },
- ],
- },
- ],
- [
- 'trailing newline at end of transcript is tolerated',
- 'AI: Hi.\nUser: Hello.\n',
- {
- leadingText: '',
- turns: [
- { speaker: 'ai', name: 'AI', text: 'Hi.' },
- { speaker: 'user', name: 'User', text: 'Hello.' },
- ],
- },
- ],
- [
- 'assistant and interviewee aliases',
- 'Assistant: Welcome.\nInterviewee: Thanks.',
- {
- leadingText: '',
- turns: [
- { speaker: 'ai', name: 'Assistant', text: 'Welcome.' },
- { speaker: 'user', name: 'Interviewee', text: 'Thanks.' },
- ],
- },
- ],
- [
- 'colons in turn body do not split',
- 'AI: Pick a number: any number.\nUser: Five.',
- {
- leadingText: '',
- turns: [
- { speaker: 'ai', name: 'AI', text: 'Pick a number: any number.' },
- { speaker: 'user', name: 'User', text: 'Five.' },
- ],
- },
- ],
- [
- 'speaker keyword mid-turn-body does not split',
- 'AI: How did the User: experience feel?\nUser: Good.',
- {
- leadingText: '',
- turns: [
- { speaker: 'ai', name: 'AI', text: 'How did the User: experience feel?' },
- { speaker: 'user', name: 'User', text: 'Good.' },
- ],
- },
- ],
- [
- 'lowercase prefixes are accepted',
- 'ai: Hello.\nuser: Hi.',
- {
- leadingText: '',
- turns: [
- { speaker: 'ai', name: 'ai', text: 'Hello.' },
- { speaker: 'user', name: 'user', text: 'Hi.' },
- ],
- },
- ],
- [
- 'inline turns on a single line yield one degraded turn (no newline delimiter present)',
- 'AI: Hey, Chris. User: Yep. Go ahead.',
- {
- leadingText: '',
- turns: [{ speaker: 'ai', name: 'AI', text: 'Hey, Chris. User: Yep. Go ahead.' }],
- },
- ],
- [
- 'leading prose before first speaker prefix is reported (caller falls back to markdown)',
- 'Interview started 2026-05-29.\nAI: Hi.\nUser: Hello.',
- {
- leadingText: 'Interview started 2026-05-29.',
- turns: [
- { speaker: 'ai', name: 'AI', text: 'Hi.' },
- { speaker: 'user', name: 'User', text: 'Hello.' },
- ],
- },
- ],
- ])('case: %s', (_label, input, expected) => {
- it('parses into the expected shape', () => {
- expect(parseTranscript(input)).toEqual(expected)
- })
- })
-})
diff --git a/products/user_interviews/frontend/TranscriptChat.tsx b/products/user_interviews/frontend/TranscriptChat.tsx
deleted file mode 100644
index f6d932b6148e..000000000000
--- a/products/user_interviews/frontend/TranscriptChat.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-import clsx from 'clsx'
-
-import * as robotPng from '@posthog/brand/hoggies/png/robot'
-
-import { pngHoggie } from 'lib/brand/hoggies'
-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
-
-import { PersonType } from '~/types'
-
-import { PersonIcon } from 'products/persons/frontend/components/PersonDisplay'
-import { asDisplay } from 'products/persons/frontend/person-utils'
-
-import { TranscriptTurn, parseTranscript } from './parseTranscript'
-
-const HedgehogRobot = pngHoggie(robotPng)
-
-interface TranscriptChatProps {
- transcript: string
- person: PersonType | null
- identifier: string
-}
-
-export function TranscriptChat({ transcript, person, identifier }: TranscriptChatProps): JSX.Element {
- const { leadingText, turns } = parseTranscript(transcript)
-
- if (turns.length === 0 || leadingText) {
- return (
- <div data-attr="transcript-chat" data-parsed="false">
- <LemonMarkdown className="text-sm leading-relaxed">{transcript}</LemonMarkdown>
- </div>
- )
- }
-
- return (
- <div data-attr="transcript-chat" data-parsed="true" className="flex flex-col gap-3">
- {turns.map((turn, index) => (
- <TranscriptBubble key={index} turn={turn} person={person} identifier={identifier} />
- ))}
- </div>
- )
-}
-
-interface TranscriptBubbleProps {
- turn: TranscriptTurn
- person: PersonType | null
- identifier: string
-}
-
-function TranscriptBubble({ turn, person, identifier }: TranscriptBubbleProps): JSX.Element {
- const isUser = turn.speaker === 'user'
- return (
- <div className={clsx('flex items-start gap-2', isUser ? 'flex-row-reverse' : 'flex-row')}>
- <div className="shrink-0">
- <TranscriptAvatar turn={turn} person={person} identifier={identifier} />
- </div>
- <div
- className={clsx(
- 'rounded-lg border px-3 py-2 max-w-[85%] min-w-0',
- isUser ? 'bg-accent-highlight-secondary' : 'bg-surface-primary'
- )}
- >
- <div className="text-xs font-semibold mb-1 text-muted">{labelFor(turn, person, identifier)}</div>
- <LemonMarkdown className="text-sm">{turn.text}</LemonMarkdown>
- </div>
- </div>
- )
-}
-
-function TranscriptAvatar({ turn, person, identifier }: TranscriptBubbleProps): JSX.Element {
- if (turn.speaker === 'ai') {
- return (
- <span
- className="inline-flex items-center justify-center w-8 h-8 rounded-full bg-surface-tertiary overflow-hidden"
- title={turn.name}
- >
- <HedgehogRobot className="w-8 h-8 object-cover" />
- </span>
- )
- }
-
- if (turn.speaker === 'user') {
- return <PersonIcon person={effectivePerson(person, identifier)} size="md" />
- }
-
- return <PersonIcon displayName={turn.name} size="md" />
-}
-
-function labelFor(turn: TranscriptTurn, person: PersonType | null, identifier: string): string {
- if (turn.speaker === 'user') {
- return asDisplay(effectivePerson(person, identifier))
- }
- return turn.name
-}
-
-function effectivePerson(person: PersonType | null, identifier: string): PersonType {
- return person ?? { distinct_ids: [identifier], properties: {} }
-}
diff --git a/products/user_interviews/frontend/UserInterview.tsx b/products/user_interviews/frontend/UserInterview.tsx
deleted file mode 100644
index a02081686fe8..000000000000
--- a/products/user_interviews/frontend/UserInterview.tsx
+++ /dev/null
@@ -1,489 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import {
- IconArrowLeft,
- IconCheck,
- IconChevronRight,
- IconClock,
- IconCopy,
- IconDownload,
- IconEye,
- IconFlask,
-} from '@posthog/icons'
-import { LemonButton, LemonModal, LemonSkeleton, LemonTag, LemonWidget } from '@posthog/lemon-ui'
-
-import { NotFound } from 'lib/components/NotFound'
-import { dayjs } from 'lib/dayjs'
-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
-import { Link } from 'lib/lemon-ui/Link'
-import { copyToClipboard } from 'lib/utils/copyToClipboard'
-import { SceneExport } from 'scenes/sceneTypes'
-import { urls } from 'scenes/urls'
-
-import { SceneContent } from '~/layout/scenes/components/SceneContent'
-
-import type { PreviewInviteResultApi, TestInterviewLinkApi, UserInterviewTopicApi } from './generated/api.schemas'
-import { InterviewLinkCopyButton } from './InterviewLinkCopyButton'
-import { UserInterviewLogicProps, userInterviewLogic } from './userInterviewLogic'
-
-export const scene: SceneExport<UserInterviewLogicProps> = {
- component: UserInterview,
- logic: userInterviewLogic,
- paramsToProps: ({ params: { id } }) => ({ id }),
-}
-
-function targetingLabel(topic: UserInterviewTopicApi): string {
- const emailCount = topic.interviewee_emails?.length || 0
- const distinctIdCount = topic.interviewee_distinct_ids?.length || 0
- const parts: string[] = []
- if (emailCount > 0) {
- parts.push(`${emailCount} email${emailCount !== 1 ? 's' : ''}`)
- }
- if (distinctIdCount > 0) {
- parts.push(`${distinctIdCount} ID${distinctIdCount !== 1 ? 's' : ''}`)
- }
- return parts.length > 0 ? parts.join(' + ') : 'Not set'
-}
-
-export function UserInterview({ id }: UserInterviewLogicProps): JSX.Element {
- const {
- topic,
- topicLoading,
- interviewees,
- intervieweesLoading,
- respondedIdentifiers,
- respondedCount,
- totalTargeted,
- responseRate,
- linksCsvExporting,
- sharedLinkLoading,
- testLink,
- testLinkLoading,
- previewInviteIdentifier,
- invitePreview,
- invitePreviewLoading,
- } = useValues(userInterviewLogic)
- const { exportLinksCsv, copySharedLink, loadTestLink, openInvitePreview, closeInvitePreview } =
- useActions(userInterviewLogic)
-
- if (topicLoading && !topic) {
- return (
- <SceneContent>
- <div className="space-y-4">
- <LemonSkeleton.Text className="h-8 w-[60%]" />
- <LemonSkeleton.Text className="h-4 w-[40%]" />
- <div className="grid grid-cols-2 gap-3 @2xl:grid-cols-4">
- <LemonSkeleton className="h-24" />
- <LemonSkeleton className="h-24" />
- <LemonSkeleton className="h-24" />
- <LemonSkeleton className="h-24" />
- </div>
- </div>
- </SceneContent>
- )
- }
-
- if (!topic) {
- return <NotFound object="interview topic" />
- }
-
- const pendingCount = totalTargeted - respondedCount
- const questionCount = topic.questions?.length || 0
- const allIdentifiers = [...(topic.interviewee_emails || []), ...(topic.interviewee_distinct_ids || [])]
- // Responded interviewees first (grouped together), awaiting ones below — stable within each group.
- const orderedIdentifiers = [...allIdentifiers].sort(
- (a, b) => Number(respondedIdentifiers.has(b)) - Number(respondedIdentifiers.has(a))
- )
-
- return (
- <SceneContent>
- {/* Header */}
- <div className="flex items-start justify-between mb-4 gap-4">
- <div>
- <LemonButton
- type="tertiary"
- size="small"
- icon={<IconArrowLeft />}
- to={urls.userInterviews()}
- className="mb-1 -ml-2"
- >
- All topics
- </LemonButton>
- <h1 className="text-2xl font-bold mb-1">{topic.topic}</h1>
- {topic.agent_context && <p className="text-muted mb-0 text-sm">{topic.agent_context}</p>}
- </div>
- <div className="shrink-0 flex items-center gap-2">
- <LemonButton
- type="secondary"
- icon={<IconCopy />}
- onClick={copySharedLink}
- loading={sharedLinkLoading}
- data-attr="copy-shared-interview-link"
- tooltip="Copy one shared link anyone can open — each visitor becomes a new anonymous respondent. No interviewee targeting needed."
- >
- Copy shared link
- </LemonButton>
- <LemonButton
- type="secondary"
- icon={<IconDownload />}
- onClick={exportLinksCsv}
- loading={linksCsvExporting}
- disabledReason={
- totalTargeted === 0 ? 'Add interviewees to the topic before exporting links' : undefined
- }
- data-attr="export-interview-links-csv"
- tooltip="Download a CSV with each interviewee's personal interview link, for use in your own email tooling"
- >
- Export links (CSV)
- </LemonButton>
- </div>
- </div>
-
- <div className="grid grid-cols-1 gap-4 @container @4xl:grid-cols-3">
- {/* Left column */}
- <div className="col-span-2 flex flex-col gap-4">
- {/* Stats cards */}
- <div className="grid grid-cols-2 gap-3 @2xl:grid-cols-4">
- {/* Response rate — hero card */}
- <div className="col-span-2 rounded-lg border-2 border-success bg-success-highlight p-4 flex items-center justify-between">
- <div>
- <div className="text-xs font-semibold uppercase text-success tracking-wide">
- Response rate
- </div>
- <div className="text-3xl font-bold text-success mt-1">{responseRate}%</div>
- <div className="text-sm text-muted mt-0.5">
- {respondedCount} of {totalTargeted} responded
- </div>
- </div>
- <div className="text-5xl font-bold text-success opacity-20">{respondedCount}</div>
- </div>
-
- <StatCard label="Awaiting response" value={pendingCount} color="warning" />
- <StatCard label="Questions" value={questionCount} color="muted" />
- </div>
-
- <TestInterviewWidget
- testLink={testLink}
- testLinkLoading={testLinkLoading}
- onRefresh={loadTestLink}
- />
-
- {/* Targeted people list */}
- <LemonWidget title={`People (${allIdentifiers.length})`}>
- <div className="divide-y">
- {intervieweesLoading && interviewees.length === 0 && allIdentifiers.length === 0 ? (
- <div className="p-4 space-y-3">
- <LemonSkeleton.Text className="h-4 w-[60%]" />
- <LemonSkeleton.Text className="h-4 w-[40%]" />
- <LemonSkeleton.Text className="h-4 w-[50%]" />
- </div>
- ) : allIdentifiers.length === 0 ? (
- <div className="p-4 text-muted text-center">
- No people targeted yet. Use PostHog AI to set up targeting and generate interview
- links.
- </div>
- ) : (
- orderedIdentifiers.map((identifier) => (
- <PersonRow
- key={identifier}
- identifier={identifier}
- topicId={id}
- hasResponded={respondedIdentifiers.has(identifier)}
- onPreview={() => openInvitePreview(identifier)}
- previewLoading={previewInviteIdentifier === identifier && invitePreviewLoading}
- />
- ))
- )}
- </div>
- </LemonWidget>
- </div>
-
- {/* Right column — topic metadata */}
- <div className="col-span-1 flex flex-col gap-4">
- <LemonWidget title="Details">
- <div className="p-3 space-y-3">
- <DetailRow label="Targeting" value={targetingLabel(topic)} />
- <DetailRow label="Created" value={topic.created_at.split('T')[0]} />
- <DetailRow
- label="Owner"
- value={topic.created_by?.first_name || topic.created_by?.email || '—'}
- />
- </div>
- </LemonWidget>
-
- {questionCount > 0 && (
- <LemonWidget title="Interview questions">
- <div className="p-3">
- <LemonMarkdown>
- {(topic.questions || []).map((q, i) => `${i + 1}. ${q}`).join('\n')}
- </LemonMarkdown>
- </div>
- </LemonWidget>
- )}
-
- {topic.agent_context && (
- <LemonWidget title="Agent context">
- <div className="p-3">
- <p className="text-sm mb-0">{topic.agent_context}</p>
- </div>
- </LemonWidget>
- )}
- </div>
- </div>
-
- <InvitePreviewModal
- isOpen={previewInviteIdentifier !== null}
- onClose={closeInvitePreview}
- preview={invitePreview}
- loading={invitePreviewLoading}
- />
- </SceneContent>
- )
-}
-
-export function InvitePreviewModal({
- isOpen,
- onClose,
- preview,
- loading,
-}: {
- isOpen: boolean
- onClose: () => void
- preview: PreviewInviteResultApi | null
- loading: boolean
-}): JSX.Element {
- return (
- <LemonModal isOpen={isOpen} onClose={onClose} title="Invite email preview" width="90vw">
- {/* Gate on `loading` alone (not `loading && !preview`): while a newly opened person's
- preview loads, kea-loaders still holds the previous person's value, so keying off
- `loading` shows the skeleton instead of the stale email. */}
- {loading ? (
- <div className="space-y-3 h-[70vh]">
- <LemonSkeleton.Text className="h-4 w-[50%]" />
- <LemonSkeleton className="h-[60vh]" />
- </div>
- ) : preview ? (
- <div className="flex flex-col gap-3">
- <div className="flex flex-col gap-1">
- <div className="text-xs font-semibold uppercase text-muted tracking-wide">Subject</div>
- <div className="text-sm font-medium">{preview.subject}</div>
- <div className="text-sm text-muted">
- To {preview.user_name}
- {preview.email ? ` <${preview.email}>` : ''}
- </div>
- <div className="flex items-center gap-2 flex-wrap">
- {!preview.emailable && <LemonTag type="warning">No email address — can't be sent</LemonTag>}
- {preview.is_preview_link && (
- <LemonTag type="default">Link is a placeholder until invites are sent</LemonTag>
- )}
- </div>
- </div>
- <iframe
- srcDoc={preview.html}
- sandbox=""
- title="Invite email preview"
- className="w-full h-[70vh] border rounded"
- />
- </div>
- ) : (
- <div className="text-muted h-[70vh]">Couldn't load the preview. Try again.</div>
- )}
- </LemonModal>
- )
-}
-
-function StatCard({
- label,
- value,
- color,
-}: {
- label: string
- value: number
- color: 'success' | 'warning' | 'primary' | 'muted' | 'danger'
-}): JSX.Element {
- const borderColor = {
- success: 'border-success',
- warning: 'border-warning',
- primary: 'border-primary',
- muted: 'border-border',
- danger: 'border-danger',
- }[color]
- const textColor = {
- success: 'text-success',
- warning: 'text-warning',
- primary: 'text-primary',
- muted: 'text-muted',
- danger: 'text-danger',
- }[color]
-
- return (
- <div className={`rounded-lg border-2 ${borderColor} bg-bg-light p-3`}>
- <div className={`text-2xl font-bold ${textColor}`}>{value}</div>
- <div className="text-xs text-muted font-medium mt-0.5">{label}</div>
- </div>
- )
-}
-
-function DetailRow({ label, value }: { label: string; value: string }): JSX.Element {
- return (
- <div className="flex justify-between">
- <span className="text-muted text-sm">{label}</span>
- <span className="text-sm font-medium">{value}</span>
- </div>
- )
-}
-
-function TestInterviewWidget({
- testLink,
- testLinkLoading,
- onRefresh,
-}: {
- testLink: TestInterviewLinkApi | null
- testLinkLoading: boolean
- onRefresh: () => void
-}): JSX.Element {
- const interviewUrl = testLink?.interview_url
- const latest = testLink?.latest_test_interview ?? null
-
- const handleCopy = (): void => {
- if (interviewUrl) {
- void copyToClipboard(interviewUrl, 'test interview link')
- }
- }
-
- return (
- <LemonWidget
- title={
- <span className="flex items-center gap-2">
- <IconFlask />
- <span>Test interview</span>
- <LemonTag type="warning">No real user needed</LemonTag>
- </span>
- }
- >
- <div className="p-3 space-y-3">
- <p className="text-muted text-sm mb-0">
- Open this link to try the AI voice interview yourself — your test calls are kept separate from the
- targeted interviewees and the most recent one appears below.
- </p>
- {testLinkLoading && !testLink ? (
- <LemonSkeleton.Text className="h-4 w-[80%]" />
- ) : interviewUrl ? (
- <div className="flex items-center gap-2">
- <Link to={interviewUrl} target="_blank" className="text-sm font-mono break-all">
- {interviewUrl}
- </Link>
- <LemonButton
- type="tertiary"
- size="xsmall"
- icon={<IconCopy />}
- onClick={handleCopy}
- tooltip="Copy test interview link"
- />
- <LemonButton
- type="tertiary"
- size="xsmall"
- onClick={onRefresh}
- loading={testLinkLoading}
- tooltip="Refresh test interview state"
- >
- Refresh
- </LemonButton>
- </div>
- ) : (
- <p className="text-danger text-sm mb-0">Couldn't load the test link. Try refreshing the page.</p>
- )}
- <div>
- <div className="text-xs font-semibold uppercase text-muted tracking-wide mb-1">
- Latest test transcript
- </div>
- {latest ? (
- <div className="text-sm space-y-2">
- <div className="text-muted">
- Recorded {dayjs(latest.completed_at).format('MMM D, YYYY [at] HH:mm')}
- </div>
- {latest.summary ? (
- <div>
- <div className="text-xs font-semibold uppercase text-muted tracking-wide mb-1">
- Summary
- </div>
- <LemonMarkdown>{latest.summary}</LemonMarkdown>
- </div>
- ) : null}
- {latest.transcript ? (
- <details>
- <summary className="cursor-pointer text-xs uppercase text-muted tracking-wide">
- Full transcript
- </summary>
- <pre className="text-xs whitespace-pre-wrap mt-2">{latest.transcript}</pre>
- </details>
- ) : null}
- {!latest.summary && !latest.transcript ? (
- <div className="text-muted">
- The most recent test call completed but no transcript or summary was delivered.
- </div>
- ) : null}
- </div>
- ) : (
- <div className="text-sm text-muted">No test call has completed yet for this topic.</div>
- )}
- </div>
- </div>
- </LemonWidget>
- )
-}
-
-function PersonRow({
- identifier,
- topicId,
- hasResponded,
- onPreview,
- previewLoading,
-}: {
- identifier: string
- topicId: string
- hasResponded: boolean
- onPreview: () => void
- previewLoading: boolean
-}): JSX.Element {
- return (
- <Link
- to={urls.userInterviewResponse(topicId, encodeURIComponent(identifier))}
- className="block no-underline text-current"
- >
- <div className="p-3 hover:bg-bg-light transition-colors">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <div className="font-medium text-sm">{identifier}</div>
- </div>
- <div className="flex items-center gap-2">
- <LemonButton
- type="tertiary"
- size="xsmall"
- icon={<IconEye />}
- loading={previewLoading}
- onClick={(e) => {
- e.preventDefault()
- e.stopPropagation()
- onPreview()
- }}
- data-attr="user-interview-preview-invite"
- tooltip="Preview the invite email this person would receive"
- />
- <InterviewLinkCopyButton identifier={identifier} topicId={topicId} />
- {hasResponded ? (
- <LemonTag type="success" icon={<IconCheck />}>
- Responded
- </LemonTag>
- ) : (
- <LemonTag type="default" icon={<IconClock />}>
- Awaiting
- </LemonTag>
- )}
- <IconChevronRight className="text-muted" />
- </div>
- </div>
- </div>
- </Link>
- )
-}
diff --git a/products/user_interviews/frontend/UserInterviewResponse.tsx b/products/user_interviews/frontend/UserInterviewResponse.tsx
deleted file mode 100644
index f2214cea086d..000000000000
--- a/products/user_interviews/frontend/UserInterviewResponse.tsx
+++ /dev/null
@@ -1,237 +0,0 @@
-import { useValues } from 'kea'
-import { useEffect, useState } from 'react'
-
-import { IconArrowLeft, IconCalendar, IconPerson, IconSend, IconShare } from '@posthog/icons'
-import { LemonButton, LemonSkeleton, LemonTag, LemonWidget } from '@posthog/lemon-ui'
-
-import api from 'lib/api'
-import { NotFound } from 'lib/components/NotFound'
-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
-import { Link } from 'lib/lemon-ui/Link'
-import { SceneExport } from 'scenes/sceneTypes'
-import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
-
-import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { PersonType } from '~/types'
-
-import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplay'
-
-import { userInterviewTopicsRetrieve, userInterviewTopicsIntervieweesList, userInterviewsList } from './generated/api'
-import type { UserInterviewTopicApi, IntervieweeContextApi, UserInterviewApi } from './generated/api.schemas'
-import { InterviewLinkCopyButton } from './InterviewLinkCopyButton'
-import { TranscriptChat } from './TranscriptChat'
-import { userInterviewLogic } from './userInterviewLogic'
-
-export interface UserInterviewResponseProps {
- topicId: string
- responseId: string
-}
-
-export const scene: SceneExport<UserInterviewResponseProps> = {
- component: UserInterviewResponse,
- paramsToProps: ({ params: { topicId, responseId } }) => ({ topicId, responseId }),
-}
-
-export function UserInterviewResponse({ topicId, responseId }: UserInterviewResponseProps): JSX.Element {
- const identifier = decodeURIComponent(responseId)
- const { linkForIdentifier, linksLoading, linksLoadFailed } = useValues(userInterviewLogic({ id: topicId }))
- const interviewUrl = linkForIdentifier(identifier)
- const [loading, setLoading] = useState(true)
- const [topic, setTopic] = useState<UserInterviewTopicApi | null>(null)
- const [intervieweeContext, setIntervieweeContext] = useState<IntervieweeContextApi | null>(null)
- const [interview, setInterview] = useState<UserInterviewApi | null>(null)
- const [person, setPerson] = useState<PersonType | null>(null)
-
- useEffect(() => {
- const projectId = String(teamLogic.values.currentTeamId)
-
- async function load(): Promise<void> {
- setLoading(true)
- try {
- const [topicData, intervieweesData, interviewsData] = await Promise.all([
- userInterviewTopicsRetrieve(projectId, topicId),
- userInterviewTopicsIntervieweesList(projectId, topicId),
- userInterviewsList(projectId),
- ])
- setTopic(topicData)
- const ctx = intervieweesData.results.find((c) => c.interviewee_identifier === identifier)
- setIntervieweeContext(ctx || null)
- const matchingInterviews = interviewsData.results.filter(
- (i) => i.topic === topicId && i.interviewee_identifier === identifier
- )
- // Prefer the interview that has a transcript
- const matchingInterview = matchingInterviews.find((i) => i.transcript) || matchingInterviews[0] || null
- setInterview(matchingInterview)
-
- // Look up person by email/distinct_id
- try {
- const personResponse = await api.persons.list({ search: identifier })
- if (personResponse.results.length > 0) {
- setPerson(personResponse.results[0])
- }
- } catch {
- // Person lookup is best-effort
- }
- } catch {
- setTopic(null)
- } finally {
- setLoading(false)
- }
- }
-
- void load()
- }, [topicId, identifier])
-
- if (loading) {
- return (
- <SceneContent>
- <div className="space-y-4">
- <LemonSkeleton.Text className="h-8 w-[40%]" />
- <LemonSkeleton.Text className="h-4 w-[30%]" />
- <LemonSkeleton className="h-48" />
- </div>
- </SceneContent>
- )
- }
-
- if (!topic) {
- return <NotFound object="interview response" />
- }
-
- const hasResponse = !!(interview?.transcript || interview?.summary)
- const displayName = person?.properties?.name || person?.properties?.email || person?.name || identifier
-
- return (
- <SceneContent>
- <LemonButton
- type="tertiary"
- size="small"
- icon={<IconArrowLeft />}
- to={urls.userInterview(topicId)}
- className="mb-1 -ml-2"
- >
- All responses
- </LemonButton>
- <SceneTitleSection name={displayName} description={topic.topic} resourceType={{ type: 'user_interview' }} />
-
- <div className="grid grid-cols-1 gap-4 @container @4xl:grid-cols-3">
- {/* Left column — transcript + summary */}
- <div className="col-span-2 flex flex-col gap-4">
- {interview?.summary && (
- <LemonWidget title="Summary">
- <div className="p-4">
- <LemonMarkdown className="text-sm">{interview.summary}</LemonMarkdown>
- </div>
- </LemonWidget>
- )}
-
- <LemonWidget title="Transcript">
- {interview?.transcript ? (
- <div className="p-4">
- <TranscriptChat
- transcript={interview.transcript}
- person={person}
- identifier={identifier}
- />
- </div>
- ) : (
- <div className="p-4 text-muted text-center">
- No transcript available yet. The interview may not have been completed.
- </div>
- )}
- </LemonWidget>
- </div>
-
- {/* Right column — metadata */}
- <div className="col-span-1 flex flex-col gap-4">
- {/* Person card */}
- <LemonWidget title="Person">
- <div className="p-4 space-y-3">
- {person ? (
- <>
- <PersonDisplay person={person} withIcon />
- <div className="space-y-2 mt-2">
- {person.properties?.email && (
- <div className="flex items-center gap-2">
- <IconSend className="text-muted shrink-0" />
- <span className="text-sm">{person.properties.email}</span>
- </div>
- )}
- {person.created_at && (
- <div className="flex items-center gap-2">
- <IconCalendar className="text-muted shrink-0" />
- <span className="text-sm">
- First seen {person.created_at.split('T')[0]}
- </span>
- </div>
- )}
- </div>
- </>
- ) : (
- <div className="flex items-center gap-2">
- <IconPerson className="text-muted" />
- <span className="font-medium">{identifier}</span>
- </div>
- )}
- <div className="space-y-1">
- <div className="flex items-center gap-2">
- <IconShare className="text-muted shrink-0" />
- <span className="text-sm">Interview link</span>
- <InterviewLinkCopyButton identifier={identifier} topicId={topicId} />
- </div>
- {interviewUrl ? (
- <Link
- to={interviewUrl}
- target="_blank"
- className="block text-xs font-mono break-all pl-6"
- >
- {interviewUrl}
- </Link>
- ) : (
- <span className="block text-xs text-muted pl-6">
- {linksLoadFailed
- ? "Couldn't generate link — refresh to retry"
- : linksLoading
- ? 'Generating link…'
- : 'No link available'}
- </span>
- )}
- </div>
- <div>
- <LemonTag type={hasResponse ? 'success' : 'default'}>
- {hasResponse ? 'Responded' : 'Awaiting response'}
- </LemonTag>
- </div>
- </div>
- </LemonWidget>
-
- {intervieweeContext && (
- <LemonWidget title="Interviewee context">
- <div className="p-4">
- <p className="text-sm mb-0">{intervieweeContext.agent_context}</p>
- </div>
- </LemonWidget>
- )}
-
- <LemonWidget title="Topic details">
- <div className="p-4 space-y-2">
- <DetailRow label="Topic" value={topic.topic} />
- <DetailRow label="Created" value={topic.created_at.split('T')[0]} />
- </div>
- </LemonWidget>
- </div>
- </div>
- </SceneContent>
- )
-}
-
-function DetailRow({ label, value }: { label: string; value: string }): JSX.Element {
- return (
- <div className="flex justify-between gap-2">
- <span className="text-muted text-sm shrink-0">{label}</span>
- <span className="text-sm font-medium text-right">{value}</span>
- </div>
- )
-}
diff --git a/products/user_interviews/frontend/UserInterviews.tsx b/products/user_interviews/frontend/UserInterviews.tsx
deleted file mode 100644
index 0e4f17e80d67..000000000000
--- a/products/user_interviews/frontend/UserInterviews.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { IconSearch, IconSparkles } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'
-
-import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
-import { cn } from 'lib/utils/css-classes'
-import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
-import { useMaxTool } from 'scenes/max/useMaxTool'
-import { sceneConfigurations } from 'scenes/scenes'
-import { Scene, SceneExport } from 'scenes/sceneTypes'
-import { urls } from 'scenes/urls'
-
-import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { ProductKey } from '~/queries/schema/schema-general'
-
-import { userInterviewsEmptyState } from './emptyState/userInterviewsEmptyState'
-import type { UserInterviewSearchResultApi, UserInterviewTopicApi } from './generated/api.schemas'
-import { NEW_TOPIC_PROMPT, NEW_TOPIC_SUGGESTIONS } from './newTopicMaxTool'
-import { userInterviewsLogic } from './userInterviewsLogic'
-
-export const scene: SceneExport = {
- component: UserInterviews,
- logic: userInterviewsLogic,
- productKey: ProductKey.USER_INTERVIEWS,
- emptyState: userInterviewsEmptyState,
-}
-
-function targetingLabel(topic: UserInterviewTopicApi): string {
- const emailCount = topic.interviewee_emails?.length || 0
- const distinctIdCount = topic.interviewee_distinct_ids?.length || 0
- const parts: string[] = []
- if (emailCount > 0) {
- parts.push(`${emailCount} email${emailCount !== 1 ? 's' : ''}`)
- }
- if (distinctIdCount > 0) {
- parts.push(`${distinctIdCount} ID${distinctIdCount !== 1 ? 's' : ''}`)
- }
- return parts.length > 0 ? parts.join(' + ') : 'Not set'
-}
-
-function SearchResultCard({ result }: { result: UserInterviewSearchResultApi }): JSX.Element {
- const target = result.topic_id
- ? urls.userInterviewResponse(result.topic_id, encodeURIComponent(result.interviewee_identifier))
- : null
- const card = (
- <div className="border rounded p-3 hover:bg-accent-highlight-secondary">
- <div className="flex items-center gap-2 mb-1 text-sm">
- <LemonTag type="muted">{result.document_type}</LemonTag>
- <span className="text-muted">{Math.round(result.similarity * 100)}% match</span>
- <span className="text-muted">·</span>
- <span>{result.interviewee_identifier}</span>
- </div>
- <p className="text-sm">{result.content_snippet}</p>
- </div>
- )
- return target ? (
- <Link to={target} className="block">
- {card}
- </Link>
- ) : (
- card
- )
-}
-
-function SearchResults({
- results,
- loading,
-}: {
- results: UserInterviewSearchResultApi[]
- loading: boolean
-}): JSX.Element {
- if (results.length === 0) {
- return <p className="text-muted">{loading ? 'Searching…' : 'No matching responses yet.'}</p>
- }
- return (
- <div className={cn('flex flex-col gap-2 transition-opacity', loading && 'opacity-50')}>
- {results.map((r) => (
- <SearchResultCard key={`${r.interview_id}-${r.document_type}`} result={r} />
- ))}
- </div>
- )
-}
-
-export function UserInterviews(): JSX.Element {
- const { topics, topicsLoading, searchQuery, searchResults, searchResultsLoading } = useValues(userInterviewsLogic)
- const { isMaxAvailable } = useValues(maxGlobalLogic)
- const { setSearchQuery } = useActions(userInterviewsLogic)
- const hasSearch = searchQuery.trim().length > 0
-
- const { openMax } = useMaxTool({
- identifier: 'create_user_interview_topic',
- context: {},
- initialMaxPrompt: NEW_TOPIC_PROMPT,
- suggestions: NEW_TOPIC_SUGGESTIONS,
- // `openMax` is null only when the tool is inactive, so the button's disabledReason
- // needs this to fire on an instance without PostHog AI.
- active: isMaxAvailable,
- })
-
- return (
- <SceneContent>
- <SceneTitleSection
- name={sceneConfigurations[Scene.UserInterviews].name}
- description="Run AI-powered voice research campaigns. Target an audience, set a topic, and let the AI handle the interviews."
- resourceType={{
- type: sceneConfigurations[Scene.UserInterviews].iconType || 'default_icon_type',
- }}
- actions={
- <LemonButton
- type="primary"
- icon={<IconSparkles />}
- data-attr="new-topic"
- onClick={() => openMax?.()}
- disabledReason={openMax ? undefined : 'PostHog AI is unavailable here'}
- >
- New topic
- </LemonButton>
- }
- />
- <LemonInput
- type="search"
- prefix={<IconSearch />}
- placeholder="Search what users said across all interviews — e.g. 'problems with the taxonomic filter'"
- value={searchQuery}
- onChange={setSearchQuery}
- allowClear
- fullWidth
- data-attr="user-interviews-search"
- />
- {hasSearch ? (
- <SearchResults results={searchResults} loading={searchResultsLoading} />
- ) : (
- <LemonTable
- loading={topicsLoading}
- columns={[
- {
- title: 'Topic',
- key: 'topic',
- render: (_, row: UserInterviewTopicApi) => (
- <LemonTableLink title={row.topic} to={urls.userInterview(row.id)} />
- ),
- },
- {
- title: 'Targeting',
- key: 'targeting',
- render: (_, row: UserInterviewTopicApi) => (
- <span className="text-sm">{targetingLabel(row)}</span>
- ),
- },
- {
- title: 'Questions',
- key: 'questions',
- width: 100,
- render: (_, row: UserInterviewTopicApi) => {
- const count = row.questions?.length || 0
- return (
- <span className="text-muted">
- {count} question{count !== 1 ? 's' : ''}
- </span>
- )
- },
- },
- {
- title: 'Created',
- key: 'created_at',
- render: (_, row: UserInterviewTopicApi) => (
- <span className="text-muted whitespace-nowrap">{row.created_at?.split('T')[0]}</span>
- ),
- sorter: (a, b) => (a.created_at || '').localeCompare(b.created_at || ''),
- },
- {
- title: 'Created by',
- key: 'created_by',
- render: (_, row: UserInterviewTopicApi) => (
- <span>{row.created_by?.first_name || row.created_by?.email || '—'}</span>
- ),
- },
- ]}
- dataSource={topics}
- rowKey="id"
- loadingSkeletonRows={5}
- emptyState="No topics yet. Click 'New topic' to get started with PostHog AI."
- />
- )}
- </SceneContent>
- )
-}
diff --git a/products/user_interviews/frontend/emptyState/NewTopicButton.tsx b/products/user_interviews/frontend/emptyState/NewTopicButton.tsx
deleted file mode 100644
index 2de048904457..000000000000
--- a/products/user_interviews/frontend/emptyState/NewTopicButton.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useValues } from 'kea'
-
-import { IconSparkles } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
-
-import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
-import { useMaxTool } from 'scenes/max/useMaxTool'
-
-import { NEW_TOPIC_PROMPT, NEW_TOPIC_SUGGESTIONS } from '../newTopicMaxTool'
-
-/** The empty state's primary action: the same Max-driven topic creation as the scene's "New topic" button. */
-export function NewTopicButton(): JSX.Element {
- const { isMaxAvailable } = useValues(maxGlobalLogic)
- const { openMax } = useMaxTool({
- identifier: 'create_user_interview_topic',
- context: {},
- initialMaxPrompt: NEW_TOPIC_PROMPT,
- suggestions: NEW_TOPIC_SUGGESTIONS,
- // `openMax` is null only when the tool is inactive, so without this the button stays
- // enabled on an instance without PostHog AI and opens a panel saying it isn't set up.
- active: isMaxAvailable,
- })
-
- return (
- <LemonButton
- type="primary"
- icon={<IconSparkles />}
- className="self-start"
- data-attr="user-research-empty-state-new-topic"
- onClick={() => openMax?.()}
- disabledReason={openMax ? undefined : 'PostHog AI is unavailable here'}
- >
- Create your first topic
- </LemonButton>
- )
-}
diff --git a/products/user_interviews/frontend/emptyState/UserInterviewPreview.scss b/products/user_interviews/frontend/emptyState/UserInterviewPreview.scss
deleted file mode 100644
index 6de318a9bbf4..000000000000
--- a/products/user_interviews/frontend/emptyState/UserInterviewPreview.scss
+++ /dev/null
@@ -1,318 +0,0 @@
-@import '../../../../frontend/src/lib/components/ProductEmptyState/previewMixins';
-
-.ResearchPreview {
- --research-preview-accent: var(--empty-state-accent, var(--color-primary-500));
- --research-preview-alt: var(--color-text-tertiary);
-
- display: flex;
- flex-direction: column;
- gap: 0.75rem;
-
- // Hidden topic state. Direct children of .ResearchPreview so `:checked ~` reaches all cards.
- &__radio {
- position: absolute;
- width: 0;
- height: 0;
- pointer-events: none;
- opacity: 0;
- }
-
- &__panel,
- &__interview,
- &__spark {
- overflow: hidden;
- background: var(--color-bg-surface-primary);
- border: 1px solid var(--color-border-primary);
- border-radius: var(--radius);
- }
-
- // Topic variants are stacked on one grid cell and crossfaded, so switching topics
- // never changes any element's size (no layout shift).
- &__swap {
- display: grid;
- }
-
- &__swap > * {
- grid-area: 1 / 1;
- min-width: 0;
- }
-
- &__on-a,
- &__on-b {
- @include preview-swap-hidden;
- }
-
- &__head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 0.5rem 0.75rem;
- border-bottom: 1px solid var(--color-border-primary);
- }
-
- &__title {
- font-size: 0.75rem;
- font-weight: 600;
- }
-
- &__rows {
- display: flex;
- flex-direction: column;
- padding: 0.25rem 0.5rem;
- }
-
- &__row {
- display: grid;
- grid-template-columns: auto 1fr auto auto;
- gap: 0.5rem;
- align-items: center;
- padding: 0.4375rem 0.5rem;
- cursor: pointer;
- user-select: none;
- border: 1px solid transparent;
- border-radius: var(--radius);
- transition:
- background-color 150ms ease,
- border-color 150ms ease;
- }
-
- &__row:hover {
- background: var(--color-bg-fill-highlight-50);
- }
-
- // Radio dots make the rows read as selectable.
- &__vradio {
- position: relative;
- flex-shrink: 0;
- width: 12px;
- height: 12px;
- border: 1.5px solid var(--research-preview-accent);
- border-radius: 50%;
-
- &::after {
- position: absolute;
- inset: 2px;
- content: '';
- background: var(--research-preview-accent);
- border-radius: 50%;
- transition: transform 150ms ease;
- transform: scale(0);
- }
- }
-
- &__topic {
- overflow: hidden;
- font-size: 0.75rem;
- font-weight: 600;
- color: var(--color-text-primary);
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- &__targeting {
- font-size: 0.625rem;
- color: var(--color-text-tertiary);
- }
-
- &__questions {
- min-width: 4.5rem;
- font-size: 0.625rem;
- color: var(--color-text-secondary);
- text-align: right;
- }
-
- &__hint {
- padding: 0 0.75rem 0.5rem;
- font-size: 0.6875rem;
- color: var(--color-text-tertiary);
- }
-
- // The live interview card the selected topic drives.
- &__interview-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 0.5rem 0.75rem;
- border-bottom: 1px solid var(--color-border-primary);
- }
-
- &__live {
- display: inline-flex;
- gap: 0.25rem;
- align-items: center;
- font-size: 0.6875rem;
- font-weight: 600;
- color: var(--color-green-500);
- }
-
- &__live-dot {
- width: 6px;
- height: 6px;
- background: var(--color-green-500);
- border-radius: 50%;
- animation: ResearchPreview__pulse 1.8s ease-in-out infinite;
- }
-
- &__who {
- font-family: var(--font-mono);
- font-size: 0.625rem;
- color: var(--color-text-tertiary);
- text-align: right;
- }
-
- &__transcript {
- display: flex;
- flex-direction: column;
- gap: 0.5rem;
- padding: 0.75rem 0.875rem;
- }
-
- &__msg {
- display: flex;
- flex-direction: column;
- gap: 0.1875rem;
- max-width: 88%;
- }
-
- &__msg--user {
- align-self: flex-end;
- text-align: right;
- }
-
- &__speaker {
- font-size: 0.5625rem;
- font-weight: 700;
- color: var(--color-text-tertiary);
- text-transform: uppercase;
- letter-spacing: 0.03em;
- }
-
- &__bubble {
- padding: 0.375rem 0.5625rem;
- font-size: 0.6875rem;
- line-height: 1.35;
- text-align: left;
- border-radius: var(--radius);
- }
-
- &__bubble--ai {
- color: var(--color-text-primary);
- background: var(--color-bg-surface-secondary);
- border: 1px solid var(--color-border-primary);
- }
-
- &__bubble--user {
- color: var(--color-text-primary);
- background: color-mix(in oklab, var(--research-preview-accent) 10%, transparent);
- border: 1px solid color-mix(in oklab, var(--research-preview-accent) 30%, transparent);
- }
-
- // Responses stat card for the selected topic.
- &__spark {
- padding: 0.75rem 0.875rem 0.875rem;
- }
-
- &__spark-note {
- font-size: 0.6875rem;
- font-weight: 400;
- color: var(--color-text-tertiary);
- }
-
- &__spark-chart {
- margin-top: 0.5rem;
- }
-
- &__spark-g {
- transition: opacity 250ms ease;
- }
-
- &__spark-area {
- fill: color-mix(in oklab, var(--research-preview-accent) 13%, transparent);
- stroke: none;
- }
-
- &__spark-line {
- fill: none;
- stroke: color-mix(in oklab, var(--research-preview-accent) 32%, transparent);
- stroke-width: 2;
- }
-
- // The moving bit: a short bright segment cycling along the line.
- &__spark-trace {
- fill: none;
- stroke: var(--research-preview-accent);
- stroke-dasharray: 16 84;
- stroke-linecap: round;
- stroke-width: 2;
- animation: ResearchPreview__trace 3.2s linear infinite;
- }
-
- @include preview-sparkline;
-}
-
-// Selected topic, driven purely by the hidden radios.
-
-#research-preview-a:checked ~ * .ResearchPreview__on-a,
-#research-preview-b:checked ~ * .ResearchPreview__on-b {
- @include preview-swap-visible;
-}
-
-#research-preview-a:checked ~ .ResearchPreview__panel .ResearchPreview__row--a,
-#research-preview-b:checked ~ .ResearchPreview__panel .ResearchPreview__row--b {
- background: color-mix(in oklab, var(--research-preview-accent) 8%, transparent);
- border-color: color-mix(in oklab, var(--research-preview-accent) 40%, transparent);
-}
-
-#research-preview-a:checked ~ .ResearchPreview__panel .ResearchPreview__vradio--a::after,
-#research-preview-b:checked ~ .ResearchPreview__panel .ResearchPreview__vradio--b::after {
- transform: scale(1);
-}
-
-// The radios stay keyboard-focusable while visually hidden, so the topic row they
-// label needs a visible focus indicator (WCAG 2.4.7).
-#research-preview-a:focus-visible ~ .ResearchPreview__panel .ResearchPreview__row--a,
-#research-preview-b:focus-visible ~ .ResearchPreview__panel .ResearchPreview__row--b {
- outline: 2px solid var(--research-preview-accent);
- outline-offset: 1px;
-}
-
-// Nudge attention at the unselected topic's radio until it's been picked.
-.ResearchPreview:not(.ResearchPreview--static)
- #research-preview-b:not(:checked)
- ~ .ResearchPreview__panel
- .ResearchPreview__vradio--b {
- animation: ResearchPreview__nudge 2.4s ease-in-out infinite;
-}
-
-@keyframes ResearchPreview__nudge {
- 0%,
- 100% {
- box-shadow: 0 0 0 0 color-mix(in oklab, var(--research-preview-accent) 45%, transparent);
- }
-
- 50% {
- box-shadow: 0 0 0 4px color-mix(in oklab, var(--research-preview-accent) 20%, transparent);
- }
-}
-
-@keyframes ResearchPreview__pulse {
- 0%,
- 100% {
- opacity: 1;
- }
-
- 50% {
- opacity: 0.35;
- }
-}
-
-// pathLength is normalized to 100, so the dash offset loops cleanly regardless of length.
-@keyframes ResearchPreview__trace {
- to {
- stroke-dashoffset: -100;
- }
-}
-
-// Storybook snapshots and reduced motion drop all ambient motion; picking a topic
-// still works (transitions only).
-@include preview-motion-guards('ResearchPreview');
diff --git a/products/user_interviews/frontend/emptyState/UserInterviewPreview.tsx b/products/user_interviews/frontend/emptyState/UserInterviewPreview.tsx
deleted file mode 100644
index 39c48abb0024..000000000000
--- a/products/user_interviews/frontend/emptyState/UserInterviewPreview.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-import './UserInterviewPreview.scss'
-
-import { LemonTag } from 'lib/lemon-ui/LemonTag'
-import { cn } from 'lib/utils/css-classes'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
-
-// Hand-authored rising response series for the stat card sparkline, one per topic.
-const LINE_A = 'M 0 34 L 10 32 L 20 32.6 L 30 29 L 40 29.8 L 50 26 L 60 26.8 L 70 22.5 L 80 21 L 90 17.5 L 100 15'
-const LINE_B = 'M 0 35 L 10 34 L 20 34.4 L 30 32 L 40 32.6 L 50 30 L 60 30.6 L 70 28 L 80 27 L 90 24.5 L 100 23'
-
-function areaPath(line: string): string {
- return `${line} L 100 40 L 0 40 Z`
-}
-
-/**
- * Example-data preview for the user research empty state: the topic list wired to a
- * live interview transcript and a responses stat card, so picking a topic swaps which
- * interview and response count show. The whole interaction is two hidden radios
- * driving `:checked ~` styles - no timers or state, per the preview rules in the
- * `building-product-empty-states` skill. Topic variants are stacked in `__swap` grids
- * and crossfaded, so switching never changes the layout's size.
- */
-export function UserInterviewPreview(): JSX.Element {
- const isStatic = inStorybook() || inStorybookTestRunner()
-
- return (
- <div className={cn('ResearchPreview', isStatic && 'ResearchPreview--static')}>
- {/* Topic selection, before all three cards so `:checked ~` can style them. */}
- <input
- type="radio"
- name="research-preview-topic"
- id="research-preview-a"
- defaultChecked
- className="ResearchPreview__radio"
- />
- <input
- type="radio"
- name="research-preview-topic"
- id="research-preview-b"
- className="ResearchPreview__radio"
- />
-
- <div className="ResearchPreview__panel">
- <div className="ResearchPreview__head">
- <span className="ResearchPreview__title">Research topics</span>
- <LemonTag size="small">example data</LemonTag>
- </div>
-
- <div className="ResearchPreview__rows">
- <label htmlFor="research-preview-a" className="ResearchPreview__row ResearchPreview__row--a">
- <span className="ResearchPreview__vradio ResearchPreview__vradio--a" aria-hidden="true" />
- <span className="ResearchPreview__topic">Onboarding friction</span>
- <span className="ResearchPreview__targeting">12 emails + 4 IDs</span>
- <span className="ResearchPreview__questions">5 questions</span>
- </label>
- <label htmlFor="research-preview-b" className="ResearchPreview__row ResearchPreview__row--b">
- <span className="ResearchPreview__vradio ResearchPreview__vradio--b" aria-hidden="true" />
- <span className="ResearchPreview__topic">Churn reasons</span>
- <span className="ResearchPreview__targeting">26 emails</span>
- <span className="ResearchPreview__questions">4 questions</span>
- </label>
- </div>
-
- <div className="ResearchPreview__hint">Pick a topic to read one of its interviews.</div>
- </div>
-
- <div className="ResearchPreview__interview">
- <div className="ResearchPreview__interview-head">
- <span className="ResearchPreview__live">
- <span className="ResearchPreview__live-dot" aria-hidden="true" />
- Interview in progress
- </span>
- <span className="ResearchPreview__swap ResearchPreview__who">
- <span className="ResearchPreview__on-a">[email protected]</span>
- <span className="ResearchPreview__on-b">[email protected]</span>
- </span>
- </div>
-
- <div className="ResearchPreview__transcript">
- <div className="ResearchPreview__msg ResearchPreview__msg--ai">
- <span className="ResearchPreview__speaker">AI interviewer</span>
- <span className="ResearchPreview__swap ResearchPreview__bubble ResearchPreview__bubble--ai">
- <span className="ResearchPreview__on-a">
- What slowed you down when you first set up tracking?
- </span>
- <span className="ResearchPreview__on-b">What made you decide to cancel your plan?</span>
- </span>
- </div>
- <div className="ResearchPreview__msg ResearchPreview__msg--user">
- <span className="ResearchPreview__speaker">Participant</span>
- <span className="ResearchPreview__swap ResearchPreview__bubble ResearchPreview__bubble--user">
- <span className="ResearchPreview__on-a">
- I couldn't tell which steps were required, so I skipped the install and got stuck.
- </span>
- <span className="ResearchPreview__on-b">
- Nothing was wrong. We only needed it for one launch, and the project ended.
- </span>
- </span>
- </div>
- </div>
- </div>
-
- <div className="ResearchPreview__spark">
- <div className="ResearchPreview__spark-head">
- <span className="ResearchPreview__swap ResearchPreview__spark-title">
- <span className="ResearchPreview__on-a">Responses · Onboarding friction</span>
- <span className="ResearchPreview__on-b">Responses · Churn reasons</span>
- </span>
- <LemonTag size="small">example data</LemonTag>
- </div>
-
- <div className="ResearchPreview__spark-value">
- <span className="ResearchPreview__swap">
- <span className="ResearchPreview__on-a">18</span>
- <span className="ResearchPreview__on-b">11</span>
- </span>
- <span className="ResearchPreview__spark-note">completed interviews</span>
- </div>
-
- <div className="ResearchPreview__spark-chart">
- <svg
- className="ResearchPreview__spark-svg"
- viewBox="0 0 100 40"
- preserveAspectRatio="none"
- aria-hidden="true"
- >
- <g className="ResearchPreview__spark-g ResearchPreview__on-a">
- <path className="ResearchPreview__spark-area" d={areaPath(LINE_A)} />
- <path
- className="ResearchPreview__spark-line"
- d={LINE_A}
- vectorEffect="non-scaling-stroke"
- />
- <path
- className="ResearchPreview__spark-trace"
- d={LINE_A}
- pathLength={100}
- vectorEffect="non-scaling-stroke"
- />
- </g>
- <g className="ResearchPreview__spark-g ResearchPreview__on-b">
- <path className="ResearchPreview__spark-area" d={areaPath(LINE_B)} />
- <path
- className="ResearchPreview__spark-line"
- d={LINE_B}
- vectorEffect="non-scaling-stroke"
- />
- <path
- className="ResearchPreview__spark-trace"
- d={LINE_B}
- pathLength={100}
- vectorEffect="non-scaling-stroke"
- />
- </g>
- </svg>
- </div>
- </div>
- </div>
- )
-}
diff --git a/products/user_interviews/frontend/emptyState/userInterviewsEmptyState.tsx b/products/user_interviews/frontend/emptyState/userInterviewsEmptyState.tsx
deleted file mode 100644
index 4b1ee6dee0a8..000000000000
--- a/products/user_interviews/frontend/emptyState/userInterviewsEmptyState.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import * as reporterPng from '@posthog/brand/hoggies/png/reporter'
-import { IconMicrophone } from '@posthog/icons'
-
-import { pngHoggie } from 'lib/brand/hoggies'
-import type { SceneProductEmptyState } from 'lib/components/ProductEmptyState/types'
-import { FEATURE_FLAGS } from 'lib/constants'
-
-import { ProductKey } from '~/queries/schema/schema-general'
-
-import { NewTopicButton } from './NewTopicButton'
-import { UserInterviewPreview } from './UserInterviewPreview'
-import { userInterviewsSetupLogic } from './userInterviewsSetupLogic'
-
-const HedgehogReporter = pngHoggie(reporterPng)
-
-export const userInterviewsEmptyState: SceneProductEmptyState = {
- statusLogic: userInterviewsSetupLogic,
- // The whole product is behind this flag (nav-gated); flag-off users never reach the scene.
- featureFlag: FEATURE_FLAGS.USER_INTERVIEWS,
- config: {
- productKey: ProductKey.USER_INTERVIEWS,
- productName: 'User research',
- icon: <IconMicrophone />,
- accentColor: 'var(--color-product-user-interviews-light)',
- accentColorDark: 'var(--color-product-user-interviews-dark)',
- hedgehog: HedgehogReporter,
- text: {
- 'needs-setup': {
- headline: 'Run user interviews without booking a single call',
- lead: 'Create a research topic with the questions you want answered and the users to ask. An AI voice agent runs each interview, and transcripts and summaries land here as responses come in. You can then search across every response for what users said about any subject.',
- },
- },
- PrimaryAction: NewTopicButton,
- skippable: false,
- previewLabel: 'Your research, once responses arrive',
- Preview: UserInterviewPreview,
- },
-}
diff --git a/products/user_interviews/frontend/emptyState/userInterviewsSetupLogic.test.ts b/products/user_interviews/frontend/emptyState/userInterviewsSetupLogic.test.ts
deleted file mode 100644
index 61b2e6d1c8c1..000000000000
--- a/products/user_interviews/frontend/emptyState/userInterviewsSetupLogic.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
-
-import { ProductKey } from '~/queries/schema/schema-general'
-import { initKeaTests } from '~/test/init'
-
-import { userInterviewTopicsList, userInterviewsList } from 'products/user_interviews/frontend/generated/api'
-
-import { userInterviewsSetupLogic } from './userInterviewsSetupLogic'
-
-jest.mock('products/user_interviews/frontend/generated/api', () => ({
- userInterviewTopicsList: jest.fn(),
- userInterviewsList: jest.fn(),
-}))
-
-const mockUserInterviewTopicsList = userInterviewTopicsList as jest.MockedFunction<typeof userInterviewTopicsList>
-const mockUserInterviewsList = userInterviewsList as jest.MockedFunction<typeof userInterviewsList>
-
-// Guards the connect + mapping into the app-wide setup-status layer: if either
-// breaks, the scene empty-state gate strands on its spinner or shows the wrong surface.
-describe('userInterviewsSetupLogic', () => {
- beforeEach(() => {
- jest.clearAllMocks()
- initKeaTests()
- })
-
- // Responses outlive their topic, so the count is the sum of topics and interviews.
- it.each([
- [0, 0, 'needs-setup'],
- [1, 0, 'has-data'],
- [17, 0, 'has-data'],
- [0, 4, 'has-data'],
- ])('pushes %i topics and %i interviews as status %s', async (topics, interviews, expected) => {
- mockUserInterviewTopicsList.mockResolvedValue({ count: topics, next: null, previous: null, results: [] })
- mockUserInterviewsList.mockResolvedValue({ count: interviews, next: null, previous: null, results: [] })
- const logic = userInterviewsSetupLogic()
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- expect(productSetupStatusLogic({ productKey: ProductKey.USER_INTERVIEWS }).values.status).toBe(expected)
- })
-
- it('fails open to unknown when the count query fails before any answer', async () => {
- mockUserInterviewTopicsList.mockRejectedValue(new Error('network down'))
- mockUserInterviewsList.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })
- const logic = userInterviewsSetupLogic()
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- expect(productSetupStatusLogic({ productKey: ProductKey.USER_INTERVIEWS }).values.status).toBe('unknown')
- })
-})
diff --git a/products/user_interviews/frontend/emptyState/userInterviewsSetupLogic.ts b/products/user_interviews/frontend/emptyState/userInterviewsSetupLogic.ts
deleted file mode 100644
index 7abcf4f3682c..000000000000
--- a/products/user_interviews/frontend/emptyState/userInterviewsSetupLogic.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
-import { loaders } from 'kea-loaders'
-
-import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
-import type { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'
-import { teamLogic } from 'scenes/teamLogic'
-
-import { ProductKey } from '~/queries/schema/schema-general'
-
-import { userInterviewTopicsList, userInterviewsList } from 'products/user_interviews/frontend/generated/api'
-
-const POLL_INTERVAL_MS = 20000
-// The poll exists to catch a topic created by PostHog AI while this screen is up. Roughly ten
-// minutes of checks covers that; past it, a remount re-arms the poll. Without a cap, leaving
-// the tab open issues a request every 20 seconds indefinitely, and a failing endpoint turns
-// into an endless retry underneath a scene that already loads its own topics.
-const POLL_MAX_TICKS = 30
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface userInterviewsSetupLogicValues {
- setupStatus: ProductSetupStatus // productSetupStatusLogic
- currentProjectId: number | string // teamLogic
- topicCount: number | null
- topicCountLoading: boolean
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface userInterviewsSetupLogicActions {
- setDetectedStatus: (status: ProductSetupStatus) => {
- status: ProductSetupStatus
- } // productSetupStatusLogic
- loadTopicCount: (_: void) => void
- loadTopicCountFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadTopicCountSuccess: (
- topicCount: number,
- payload?: void
- ) => {
- topicCount: number
- payload?: void
- }
-}
-
-export type userInterviewsSetupLogicType = MakeLogicType<
- userInterviewsSetupLogicValues,
- userInterviewsSetupLogicActions
->
-
-/**
- * Setup detection for the user research empty state. User research is a
- * creation-first product, so "set up" simply means the project has at least one
- * research topic or interview response - no event or traffic signal involved.
- * Re-checks on every mount (the scene gate mounts it), which covers returning
- * after creating a topic.
- */
-export const userInterviewsSetupLogic = kea<userInterviewsSetupLogicType>([
- path(['products', 'user_interviews', 'frontend', 'emptyState', 'userInterviewsSetupLogic']),
- connect(() => ({
- actions: [productSetupStatusLogic({ productKey: ProductKey.USER_INTERVIEWS }), ['setDetectedStatus']],
- values: [
- productSetupStatusLogic({ productKey: ProductKey.USER_INTERVIEWS }),
- ['status as setupStatus'],
- teamLogic,
- ['currentProjectId'],
- ],
- })),
- loaders(({ values }) => ({
- topicCount: [
- null as number | null,
- {
- loadTopicCount: async (_: void, breakpoint): Promise<number> => {
- // Responses outlive their topic: deleting a topic nulls the link rather than
- // cascading, and audio uploads never get one. Counting topics alone would hide
- // a project's responses behind the setup screen, and the scene's search box is
- // the only place to reach them.
- const [topics, interviews] = await Promise.all([
- userInterviewTopicsList(String(values.currentProjectId), { limit: 1 }),
- userInterviewsList(String(values.currentProjectId), { limit: 1 }),
- ])
- breakpoint()
- return topics.count + interviews.count
- },
- },
- ],
- })),
- listeners(({ actions, cache, values }) => ({
- loadTopicCountSuccess: () => {
- const hasData = (values.topicCount ?? 0) > 0
- if (hasData) {
- cache.disposables.dispose('poll')
- }
- actions.setDetectedStatus(hasData ? 'has-data' : 'needs-setup')
- },
- loadTopicCountFailure: () => {
- // Never strand the gate on its spinner: if nothing has answered yet, fail
- // open to the real scene. Don't downgrade an existing answer on a blip.
- if (values.setupStatus === 'loading') {
- actions.setDetectedStatus('unknown')
- }
- // The scene loads its own topics, so retrying a broken endpoint here buys nothing.
- cache.disposables.dispose('poll')
- },
- })),
- afterMount(({ actions, cache }) => {
- actions.loadTopicCount()
- // Topics are created by PostHog AI in the side panel while the gate stays on
- // screen, so poll until one lands rather than waiting for a remount.
- cache.disposables.add(() => {
- let ticks = 0
- const interval = setInterval(() => {
- ticks += 1
- if (ticks > POLL_MAX_TICKS) {
- cache.disposables.dispose('poll')
- return
- }
- actions.loadTopicCount()
- }, POLL_INTERVAL_MS)
- return () => clearInterval(interval)
- }, 'poll')
- }),
-])
diff --git a/products/user_interviews/frontend/generated/api.schemas.ts b/products/user_interviews/frontend/generated/api.schemas.ts
deleted file mode 100644
index 78915d92c56a..000000000000
--- a/products/user_interviews/frontend/generated/api.schemas.ts
+++ /dev/null
@@ -1,484 +0,0 @@
-/**
- * Auto-generated from the Django backend OpenAPI schema.
- * To modify these types, update the Django serializers or views, then run:
- * hogli build:openapi
- * Questions or issues? #team-devex on Slack
- *
- * PostHog API - generated
- * OpenAPI spec version: 1.0.0
- */
-/**
- * * `engineering` - Engineering
- * * `data` - Data
- * * `product` - Product Management
- * * `founder` - Founder
- * * `leadership` - Leadership
- * * `marketing` - Marketing
- * * `sales` - Sales / Success
- * * `student` - Student
- * * `other` - Other
- */
-export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
-
-export const RoleAtOrganizationEnumApi = {
- Engineering: 'engineering',
- Data: 'data',
- Product: 'product',
- Founder: 'founder',
- Leadership: 'leadership',
- Marketing: 'marketing',
- Sales: 'sales',
- Student: 'student',
- Other: 'other',
-} as const
-
-export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
-
-export const BlankEnumApi = {
- '': '',
-} as const
-
-/**
- * @nullable
- */
-export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null
-
-export interface UserBasicApi {
- readonly id: number
- readonly uuid: string
- /**
- * @maxLength 200
- * @nullable
- */
- distinct_id?: string | null
- /** @maxLength 150 */
- first_name?: string
- /** @maxLength 150 */
- last_name?: string
- /** @maxLength 254 */
- email: string
- /** @nullable */
- is_email_verified?: boolean | null
- /** @nullable */
- readonly hedgehog_config: UserBasicApiHedgehogConfig
- role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
-}
-
-export interface UserInterviewTopicApi {
- readonly id: string
- readonly created_by: UserBasicApi
- readonly created_at: string
- /**
- * Email addresses of people to interview. May be combined with interviewee_distinct_ids.
- * @items.maxLength 254
- */
- interviewee_emails?: string[]
- /**
- * PostHog distinct IDs of people to interview. May be combined with interviewee_emails.
- * @items.maxLength 400
- */
- interviewee_distinct_ids?: string[]
- /** The product, feature, or idea you want to ask interviewees about. */
- topic: string
- /** Optional additional system prompt for the voice agent — extra background, tone, or constraints. */
- agent_context?: string
- /** Ordered list of questions the voice agent should work through during the interview. */
- questions?: string[]
- /**
- * Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.
- * @maxLength 255
- */
- invite_subject?: string
- /**
- * Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.
- * @maxLength 1000
- */
- invite_message?: string
-}
-
-export interface PaginatedUserInterviewTopicListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: UserInterviewTopicApi[]
-}
-
-export interface PatchedUserInterviewTopicApi {
- readonly id?: string
- readonly created_by?: UserBasicApi
- readonly created_at?: string
- /**
- * Email addresses of people to interview. May be combined with interviewee_distinct_ids.
- * @items.maxLength 254
- */
- interviewee_emails?: string[]
- /**
- * PostHog distinct IDs of people to interview. May be combined with interviewee_emails.
- * @items.maxLength 400
- */
- interviewee_distinct_ids?: string[]
- /** The product, feature, or idea you want to ask interviewees about. */
- topic?: string
- /** Optional additional system prompt for the voice agent — extra background, tone, or constraints. */
- agent_context?: string
- /** Ordered list of questions the voice agent should work through during the interview. */
- questions?: string[]
- /**
- * Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.
- * @maxLength 255
- */
- invite_subject?: string
- /**
- * Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.
- * @maxLength 1000
- */
- invite_message?: string
-}
-
-export interface IntervieweeIdentifierRequestApi {
- /**
- * Email address or PostHog distinct ID for the interviewee. Email-shaped values (including the `Display Name <email@host>` form) are routed to `interviewee_emails`; everything else lands in `interviewee_distinct_ids`.
- * @maxLength 400
- */
- identifier: string
-}
-
-export interface InterviewLinkApi {
- /**
- * The original identifier (email or distinct ID) from the topic targeting.
- * @maxLength 400
- */
- interviewee_identifier: string
- /** Best-effort display name derived from the identifier, used to greet the interviewee. */
- user_name: string
- /** Public, unauthenticated URL the interviewee opens to start the call. Backed by a SharingConfiguration access token. */
- interview_url: string
- /** The merged topic + per-interviewee context the voice agent will see during the call. */
- agent_context: string
-}
-
-export interface PaginatedInterviewLinkListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: InterviewLinkApi[]
-}
-
-export interface PreviewInviteRequestApi {
- /**
- * Which targeted interviewee to render the preview for (an email or PostHog distinct ID already on the topic). Leave blank to preview for the first targeted interviewee.
- * @maxLength 400
- */
- interviewee_identifier?: string
-}
-
-export interface PreviewInviteResultApi {
- /** The identifier (email or distinct ID) the preview was rendered for. */
- interviewee_identifier: string
- /** The display name used in the email greeting, derived from the identifier. */
- user_name: string
- /**
- * The email address the invite would be sent to. Null for distinct-ID-only interviewees.
- * @nullable
- */
- email: string | null
- /** The rendered subject line (saved topic subject, sanitized, or the default). */
- subject: string
- /** The fully rendered, CSS-inlined HTML body of the invite email. Safe to display in a sandboxed iframe. */
- html: string
- /** An illustrative placeholder interview link shown in the previewed email body. The preview never exposes a real per-recipient share token — that link is minted only when invites are sent. */
- interview_url: string
- /** True if this interviewee has an email address and could actually receive the invite. */
- emailable: boolean
- /** Always true — the previewed interview_url is an illustrative placeholder, never a live link. */
- is_preview_link: boolean
-}
-
-export interface SendInvitesRequestApi {
- /**
- * Override the email subject line for this send. Plain text only — URLs, angle brackets, and control characters are rejected. Falls back to the topic's saved subject, then a default.
- * @maxLength 200
- */
- subject?: string
- /** Email address replies should go to. Defaults to the topic creator's email if blank. */
- reply_to?: string
- /** If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately. */
- send_async?: boolean
-}
-
-export interface InterviewInviteResultApi {
- /** The original identifier (email or distinct ID) from the topic targeting. */
- interviewee_identifier: string
- /**
- * Email used for delivery. Null when the identifier was not an email (e.g., a distinct ID).
- * @nullable
- */
- email?: string | null
- /** The personalized public interview URL embedded in the email body. */
- interview_url: string
- /** True if an email was queued for delivery. False when the recipient was skipped — see `reason`. */
- sent: boolean
- /** Why the email was skipped (e.g., `not_an_email`, `duplicate_recipient`, `already_sent`). Empty when sent=true. */
- reason?: string
-}
-
-export interface PaginatedInterviewInviteResultListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: InterviewInviteResultApi[]
-}
-
-export interface SharedInterviewLinkApi {
- /** Public, unauthenticated URL any respondent can open to start a new interview for this topic. Backed by a topic-level SharingConfiguration access token — not tied to any specific interviewee. Each visit is a new anonymous respondent who self-identifies with a name; `distinct_id` and `session_id` query params on the URL are captured as best-effort person/session linkage. */
- interview_url: string
-}
-
-export interface LatestTestInterviewApi {
- /** When the test interview was completed. */
- completed_at: string
- /** Full transcript of the test call, if Vapi delivered one. May be empty. */
- transcript: string
- /** AI-generated summary of the test call, if Vapi delivered one. May be empty. */
- summary: string
-}
-
-export interface TestInterviewLinkApi {
- /** Public, unauthenticated URL the topic author opens to dogfood the voice interview themselves — does not count against the targeted interviewees. */
- interview_url: string
- /** Most recent test interview completed by the topic author, or null if none yet. */
- latest_test_interview: LatestTestInterviewApi | null
-}
-
-export interface IntervieweeContextApi {
- readonly id: string
- readonly created_by: UserBasicApi
- readonly created_at: string
- /**
- * Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids.
- * @maxLength 400
- */
- interviewee_identifier: string
- /**
- * Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'.
- * @maxLength 10000
- */
- agent_context: string
-}
-
-export interface PaginatedIntervieweeContextListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: IntervieweeContextApi[]
-}
-
-export interface PatchedIntervieweeContextApi {
- readonly id?: string
- readonly created_by?: UserBasicApi
- readonly created_at?: string
- /**
- * Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids.
- * @maxLength 400
- */
- interviewee_identifier?: string
- /**
- * Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'.
- * @maxLength 10000
- */
- agent_context?: string
-}
-
-export interface BulkIntervieweeContextItemApi {
- /**
- * Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids.
- * @maxLength 400
- */
- interviewee_identifier: string
- /**
- * Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'.
- * @maxLength 10000
- */
- agent_context: string
-}
-
-export interface BulkIntervieweeContextRequestApi {
- /** List of interviewee context rows to create. Each item has an `interviewee_identifier` and an `agent_context`. At most 500 items per request. */
- items: BulkIntervieweeContextItemApi[]
-}
-
-export interface BulkIntervieweeContextResponseApi {
- /** Number of rows inserted by this request. */
- inserted_count: number
- /** Number of items skipped because a row for that (topic, interviewee_identifier) already existed. */
- skipped_count: number
- /** Identifiers from the request whose rows were skipped because a row for that (topic, interviewee_identifier) already existed. */
- skipped_identifiers: string[]
-}
-
-/**
- * * `abandoned` - Abandoned
- * * `off-topic` - Off-topic
- */
-export type UserInterviewClassificationEnumApi =
- (typeof UserInterviewClassificationEnumApi)[keyof typeof UserInterviewClassificationEnumApi]
-
-export const UserInterviewClassificationEnumApi = {
- Abandoned: 'abandoned',
- OffTopic: 'off-topic',
-} as const
-
-export interface UserInterviewApi {
- readonly id: string
- readonly created_by: UserBasicApi
- readonly created_at: string
- /** @items.maxLength 254 */
- interviewee_emails?: string[]
- readonly interviewee_identifier: string
- /** @nullable */
- readonly topic: string | null
- readonly transcript: string
- summary?: string
- /** Searchable classifications on the response. `abandoned` is auto-derived from the transcript when the interview is recorded; `off-topic` is set manually. Sending `classifications` on an update replaces the whole list — pass the full desired set, not a delta. */
- classifications?: UserInterviewClassificationEnumApi[]
- audio: string
-}
-
-export interface PaginatedUserInterviewListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: UserInterviewApi[]
-}
-
-export interface PatchedUserInterviewApi {
- readonly id?: string
- readonly created_by?: UserBasicApi
- readonly created_at?: string
- /** @items.maxLength 254 */
- interviewee_emails?: string[]
- readonly interviewee_identifier?: string
- /** @nullable */
- readonly topic?: string | null
- readonly transcript?: string
- summary?: string
- /** Searchable classifications on the response. `abandoned` is auto-derived from the transcript when the interview is recorded; `off-topic` is set manually. Sending `classifications` on an update replaces the whole list — pass the full desired set, not a delta. */
- classifications?: UserInterviewClassificationEnumApi[]
- audio?: string
-}
-
-/**
- * * `transcript` - transcript
- * * `summary` - summary
- */
-export type UserInterviewSearchDocumentTypeEnumApi =
- (typeof UserInterviewSearchDocumentTypeEnumApi)[keyof typeof UserInterviewSearchDocumentTypeEnumApi]
-
-export const UserInterviewSearchDocumentTypeEnumApi = {
- Transcript: 'transcript',
- Summary: 'summary',
-} as const
-
-export interface UserInterviewSearchRequestApi {
- /**
- * Natural-language query to match semantically against interview transcripts and summaries.
- * @maxLength 2000
- */
- query: string
- /**
- * Which document types to search across. Omit to default to both `transcript` and `summary`. Pass a non-empty subset to restrict the search.
- * @minItems 1
- */
- document_types?: UserInterviewSearchDocumentTypeEnumApi[]
- /**
- * Optional. Restrict results to interviews belonging to a specific UserInterviewTopic.
- * @nullable
- */
- topic_id?: string | null
- /**
- * Optional. Restrict results to interviews carrying any of these classifications (OR). Combines with `topic_id` as AND.
- * @minItems 1
- */
- classifications?: UserInterviewClassificationEnumApi[]
- /**
- * Maximum number of matches to return (1-50). Defaults to 10. Two matches per interview are possible — one for the transcript, one for the summary.
- * @minimum 1
- * @maximum 50
- */
- limit?: number
-}
-
-export interface UserInterviewSearchResultApi {
- /** ID of the matched UserInterview. */
- interview_id: string
- /** Which document type matched — `transcript` is the raw conversation, `summary` is the AI-generated abstract.
- *
- * * `transcript` - transcript
- * * `summary` - summary */
- document_type: UserInterviewSearchDocumentTypeEnumApi
- /** Cosine similarity in [0, 1]; higher is closer to the query. Computed as `1 - cosineDistance`. */
- similarity: number
- /** Excerpt of the matched document (first 500 characters). */
- content_snippet: string
- /** Email or PostHog distinct ID of the interviewee. */
- interviewee_identifier: string
- /**
- * ID of the UserInterviewTopic the interview was conducted for, or null if detached.
- * @nullable
- */
- topic_id: string | null
- /** When the interview row was created. */
- created_at: string
-}
-
-export type UserInterviewTopicsListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * The initial index from which to return the results.
- */
- offset?: number
- /**
- * A search term.
- */
- search?: string
-}
-
-export type UserInterviewTopicsIntervieweesListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * The initial index from which to return the results.
- */
- offset?: number
-}
-
-export type UserInterviewsListParams = {
- /**
- * Comma-separated classifications; returns responses carrying any of them (OR). Valid values: abandoned, off-topic.
- */
- classifications?: string
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * The initial index from which to return the results.
- */
- offset?: number
- topic?: string
-}
diff --git a/products/user_interviews/frontend/generated/api.ts b/products/user_interviews/frontend/generated/api.ts
deleted file mode 100644
index adc39cbfdf2a..000000000000
--- a/products/user_interviews/frontend/generated/api.ts
+++ /dev/null
@@ -1,688 +0,0 @@
-import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
-/**
- * Auto-generated from the Django backend OpenAPI schema.
- * To modify these types, update the Django serializers or views, then run:
- * hogli build:openapi
- * Questions or issues? #team-devex on Slack
- *
- * PostHog API - generated
- * OpenAPI spec version: 1.0.0
- */
-import type {
- BulkIntervieweeContextRequestApi,
- BulkIntervieweeContextResponseApi,
- IntervieweeContextApi,
- IntervieweeIdentifierRequestApi,
- PaginatedInterviewInviteResultListApi,
- PaginatedInterviewLinkListApi,
- PaginatedIntervieweeContextListApi,
- PaginatedUserInterviewListApi,
- PaginatedUserInterviewTopicListApi,
- PatchedIntervieweeContextApi,
- PatchedUserInterviewApi,
- PatchedUserInterviewTopicApi,
- PreviewInviteRequestApi,
- PreviewInviteResultApi,
- SendInvitesRequestApi,
- SharedInterviewLinkApi,
- TestInterviewLinkApi,
- UserInterviewApi,
- UserInterviewSearchRequestApi,
- UserInterviewSearchResultApi,
- UserInterviewTopicApi,
- UserInterviewTopicsIntervieweesListParams,
- UserInterviewTopicsListParams,
- UserInterviewsListParams,
-} from './api.schemas'
-
-// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
-type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
-
-type WritableKeys<T> = {
- [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
-}[keyof T]
-
-type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
-type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
-
-type Writable<T> = Pick<T, WritableKeys<T>>
-type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
- ? {
- [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
- }
- : DistributeReadOnlyOverUnions<T>
-
-export const getUserInterviewTopicsListUrl = (projectId: string, params?: UserInterviewTopicsListParams) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/user_interview_topics/?${stringifiedParams}`
- : `/api/projects/${projectId}/user_interview_topics/`
-}
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const userInterviewTopicsList = async (
- projectId: string,
- params?: UserInterviewTopicsListParams,
- options?: RequestInit
-): Promise<PaginatedUserInterviewTopicListApi> => {
- return apiMutator<PaginatedUserInterviewTopicListApi>(getUserInterviewTopicsListUrl(projectId, params), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getUserInterviewTopicsCreateUrl = (projectId: string) => {
- return `/api/projects/${projectId}/user_interview_topics/`
-}
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const userInterviewTopicsCreate = async (
- projectId: string,
- userInterviewTopicApi: NonReadonly<UserInterviewTopicApi>,
- options?: RequestInit
-): Promise<UserInterviewTopicApi> => {
- return apiMutator<UserInterviewTopicApi>(getUserInterviewTopicsCreateUrl(projectId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(userInterviewTopicApi),
- })
-}
-
-export const getUserInterviewTopicsRetrieveUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/`
-}
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const userInterviewTopicsRetrieve = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<UserInterviewTopicApi> => {
- return apiMutator<UserInterviewTopicApi>(getUserInterviewTopicsRetrieveUrl(projectId, id), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getUserInterviewTopicsUpdateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/`
-}
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const userInterviewTopicsUpdate = async (
- projectId: string,
- id: string,
- userInterviewTopicApi: NonReadonly<UserInterviewTopicApi>,
- options?: RequestInit
-): Promise<UserInterviewTopicApi> => {
- return apiMutator<UserInterviewTopicApi>(getUserInterviewTopicsUpdateUrl(projectId, id), {
- ...options,
- method: 'PUT',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(userInterviewTopicApi),
- })
-}
-
-export const getUserInterviewTopicsPartialUpdateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/`
-}
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const userInterviewTopicsPartialUpdate = async (
- projectId: string,
- id: string,
- patchedUserInterviewTopicApi?: NonReadonly<PatchedUserInterviewTopicApi>,
- options?: RequestInit
-): Promise<UserInterviewTopicApi> => {
- return apiMutator<UserInterviewTopicApi>(getUserInterviewTopicsPartialUpdateUrl(projectId, id), {
- ...options,
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedUserInterviewTopicApi),
- })
-}
-
-export const getUserInterviewTopicsDestroyUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/`
-}
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const userInterviewTopicsDestroy = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getUserInterviewTopicsDestroyUrl(projectId, id), {
- ...options,
- method: 'DELETE',
- })
-}
-
-export const getUserInterviewTopicsAddIntervieweeCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/add_interviewee/`
-}
-
-/**
- * Add a single interviewee to this topic. Email-shaped identifiers (including the `Display Name <email@host>` form) are appended to `interviewee_emails`; everything else is appended to `interviewee_distinct_ids`. Idempotent — adding an identifier that's already present leaves the topic unchanged. Returns the updated topic.
- */
-export const userInterviewTopicsAddIntervieweeCreate = async (
- projectId: string,
- id: string,
- intervieweeIdentifierRequestApi: IntervieweeIdentifierRequestApi,
- options?: RequestInit
-): Promise<UserInterviewTopicApi> => {
- return apiMutator<UserInterviewTopicApi>(getUserInterviewTopicsAddIntervieweeCreateUrl(projectId, id), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(intervieweeIdentifierRequestApi),
- })
-}
-
-export const getUserInterviewTopicsGenerateLinksCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/generate_links/`
-}
-
-/**
- * Generate one public interview link per targeted interviewee. Materializes an IntervieweeContext row for every identifier on the topic (without overwriting existing per-person context), and an enabled SharingConfiguration with a unique access token. The URL resolves to the public interview viewer with no PostHog auth required.
- */
-export const userInterviewTopicsGenerateLinksCreate = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<PaginatedInterviewLinkListApi> => {
- return apiMutator<PaginatedInterviewLinkListApi>(getUserInterviewTopicsGenerateLinksCreateUrl(projectId, id), {
- ...options,
- method: 'POST',
- })
-}
-
-export const getUserInterviewTopicsLinksCsvCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/links_csv/`
-}
-
-/**
- * Same materialization as generate_links, returned as a downloadable CSV. Intended for users who want to mail-merge the per-person interview links into their own email tooling.
- */
-export const userInterviewTopicsLinksCsvCreate = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<Blob> => {
- return apiMutator<Blob>(getUserInterviewTopicsLinksCsvCreateUrl(projectId, id), {
- ...options,
- method: 'POST',
- })
-}
-
-export const getUserInterviewTopicsPreviewInviteCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/preview_invite/`
-}
-
-/**
- * Render the invite email exactly as a specific targeted interviewee would receive it — personalized subject and body — without sending anything and without creating or reading any share links. Pass `interviewee_identifier` to preview for a particular person, or omit it to preview for the first targeted interviewee. The body always shows an illustrative placeholder link (`is_preview_link: true`), never a live interview URL.
- */
-export const userInterviewTopicsPreviewInviteCreate = async (
- projectId: string,
- id: string,
- previewInviteRequestApi?: PreviewInviteRequestApi,
- options?: RequestInit
-): Promise<PreviewInviteResultApi> => {
- return apiMutator<PreviewInviteResultApi>(getUserInterviewTopicsPreviewInviteCreateUrl(projectId, id), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(previewInviteRequestApi),
- })
-}
-
-export const getUserInterviewTopicsRemoveIntervieweeCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/remove_interviewee/`
-}
-
-/**
- * Remove an interviewee from this topic. Drops the identifier from both `interviewee_emails` and `interviewee_distinct_ids`, and disables any active SharingConfiguration linked to an IntervieweeContext for that identifier on this topic so the removed person can no longer open their interview link. Idempotent — removing an identifier that isn't present is a no-op. Returns the updated topic.
- */
-export const userInterviewTopicsRemoveIntervieweeCreate = async (
- projectId: string,
- id: string,
- intervieweeIdentifierRequestApi: IntervieweeIdentifierRequestApi,
- options?: RequestInit
-): Promise<UserInterviewTopicApi> => {
- return apiMutator<UserInterviewTopicApi>(getUserInterviewTopicsRemoveIntervieweeCreateUrl(projectId, id), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(intervieweeIdentifierRequestApi),
- })
-}
-
-export const getUserInterviewTopicsSendInvitesCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/send_invites/`
-}
-
-/**
- * Generate (if needed) and email a personalized public interview link to every targeted interviewee on this topic whose identifier is an email address. Distinct-ID-only interviewees are skipped and surfaced in the response. Each invite is keyed on the underlying SharingConfiguration so re-runs after token rotation produce a fresh send.
- */
-export const userInterviewTopicsSendInvitesCreate = async (
- projectId: string,
- id: string,
- sendInvitesRequestApi?: SendInvitesRequestApi,
- options?: RequestInit
-): Promise<PaginatedInterviewInviteResultListApi> => {
- return apiMutator<PaginatedInterviewInviteResultListApi>(
- getUserInterviewTopicsSendInvitesCreateUrl(projectId, id),
- {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(sendInvitesRequestApi),
- }
- )
-}
-
-export const getUserInterviewTopicsSharedLinkCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/shared_link/`
-}
-
-/**
- * Get-or-create a single non-personalised (shared) interview link for this topic. Unlike generate_links, the returned URL is not tied to a specific interviewee — every visitor becomes a new anonymous respondent who self-identifies with a name. Idempotent: repeated calls return the same active link. `distinct_id` and `session_id` query params appended to the URL are captured as best-effort person/session linkage.
- */
-export const userInterviewTopicsSharedLinkCreate = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<SharedInterviewLinkApi> => {
- return apiMutator<SharedInterviewLinkApi>(getUserInterviewTopicsSharedLinkCreateUrl(projectId, id), {
- ...options,
- method: 'POST',
- })
-}
-
-export const getUserInterviewTopicsSharedLinkDestroyUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/shared_link/`
-}
-
-/**
- * Revoke this topic's shared (non-personalised) interview link so an already-distributed URL can no longer start interviews. Idempotent — a no-op when no active shared link exists. A subsequent shared_link POST mints a fresh link (rotation).
- */
-export const userInterviewTopicsSharedLinkDestroy = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getUserInterviewTopicsSharedLinkDestroyUrl(projectId, id), {
- ...options,
- method: 'DELETE',
- })
-}
-
-export const getUserInterviewTopicsTestLinkRetrieveUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${id}/test_link/`
-}
-
-/**
- * Return the calling user's personal dogfood interview link for this topic, plus the latest test interview they have recorded against it. Lazily get-or-creates a per-caller IntervieweeContext + enabled SharingConfiguration the first time it's called, then returns the same stable URL on subsequent calls. The caller's identifier is intentionally not added to the topic's targeting arrays — each user dogfoods under their own row, so test calls never mint a public share token on someone else's behalf.
- */
-export const userInterviewTopicsTestLinkRetrieve = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<TestInterviewLinkApi> => {
- return apiMutator<TestInterviewLinkApi>(getUserInterviewTopicsTestLinkRetrieveUrl(projectId, id), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getUserInterviewTopicsIntervieweesListUrl = (
- projectId: string,
- topicId: string,
- params?: UserInterviewTopicsIntervieweesListParams
-) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/user_interview_topics/${topicId}/interviewees/?${stringifiedParams}`
- : `/api/projects/${projectId}/user_interview_topics/${topicId}/interviewees/`
-}
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const userInterviewTopicsIntervieweesList = async (
- projectId: string,
- topicId: string,
- params?: UserInterviewTopicsIntervieweesListParams,
- options?: RequestInit
-): Promise<PaginatedIntervieweeContextListApi> => {
- return apiMutator<PaginatedIntervieweeContextListApi>(
- getUserInterviewTopicsIntervieweesListUrl(projectId, topicId, params),
- {
- ...options,
- method: 'GET',
- }
- )
-}
-
-export const getUserInterviewTopicsIntervieweesCreateUrl = (projectId: string, topicId: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${topicId}/interviewees/`
-}
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const userInterviewTopicsIntervieweesCreate = async (
- projectId: string,
- topicId: string,
- intervieweeContextApi: NonReadonly<IntervieweeContextApi>,
- options?: RequestInit
-): Promise<IntervieweeContextApi> => {
- return apiMutator<IntervieweeContextApi>(getUserInterviewTopicsIntervieweesCreateUrl(projectId, topicId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(intervieweeContextApi),
- })
-}
-
-export const getUserInterviewTopicsIntervieweesRetrieveUrl = (projectId: string, topicId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${topicId}/interviewees/${id}/`
-}
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const userInterviewTopicsIntervieweesRetrieve = async (
- projectId: string,
- topicId: string,
- id: string,
- options?: RequestInit
-): Promise<IntervieweeContextApi> => {
- return apiMutator<IntervieweeContextApi>(getUserInterviewTopicsIntervieweesRetrieveUrl(projectId, topicId, id), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getUserInterviewTopicsIntervieweesUpdateUrl = (projectId: string, topicId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${topicId}/interviewees/${id}/`
-}
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const userInterviewTopicsIntervieweesUpdate = async (
- projectId: string,
- topicId: string,
- id: string,
- intervieweeContextApi: NonReadonly<IntervieweeContextApi>,
- options?: RequestInit
-): Promise<IntervieweeContextApi> => {
- return apiMutator<IntervieweeContextApi>(getUserInterviewTopicsIntervieweesUpdateUrl(projectId, topicId, id), {
- ...options,
- method: 'PUT',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(intervieweeContextApi),
- })
-}
-
-export const getUserInterviewTopicsIntervieweesPartialUpdateUrl = (projectId: string, topicId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${topicId}/interviewees/${id}/`
-}
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const userInterviewTopicsIntervieweesPartialUpdate = async (
- projectId: string,
- topicId: string,
- id: string,
- patchedIntervieweeContextApi?: NonReadonly<PatchedIntervieweeContextApi>,
- options?: RequestInit
-): Promise<IntervieweeContextApi> => {
- return apiMutator<IntervieweeContextApi>(
- getUserInterviewTopicsIntervieweesPartialUpdateUrl(projectId, topicId, id),
- {
- ...options,
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedIntervieweeContextApi),
- }
- )
-}
-
-export const getUserInterviewTopicsIntervieweesDestroyUrl = (projectId: string, topicId: string, id: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${topicId}/interviewees/${id}/`
-}
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const userInterviewTopicsIntervieweesDestroy = async (
- projectId: string,
- topicId: string,
- id: string,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getUserInterviewTopicsIntervieweesDestroyUrl(projectId, topicId, id), {
- ...options,
- method: 'DELETE',
- })
-}
-
-export const getUserInterviewTopicsIntervieweesBulkCreateUrl = (projectId: string, topicId: string) => {
- return `/api/projects/${projectId}/user_interview_topics/${topicId}/interviewees/bulk/`
-}
-
-/**
- * Create up to 500 interviewee context rows for a topic in a single request. Rows whose (topic, interviewee_identifier) already exists are skipped — the response surfaces an `inserted_count`, a `skipped_count`, and the `skipped_identifiers` so the caller can reconcile. Items must have unique `interviewee_identifier` values within the batch.
- */
-export const userInterviewTopicsIntervieweesBulkCreate = async (
- projectId: string,
- topicId: string,
- bulkIntervieweeContextRequestApi: BulkIntervieweeContextRequestApi,
- options?: RequestInit
-): Promise<BulkIntervieweeContextResponseApi> => {
- return apiMutator<BulkIntervieweeContextResponseApi>(
- getUserInterviewTopicsIntervieweesBulkCreateUrl(projectId, topicId),
- {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(bulkIntervieweeContextRequestApi),
- }
- )
-}
-
-export const getUserInterviewsListUrl = (projectId: string, params?: UserInterviewsListParams) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/user_interviews/?${stringifiedParams}`
- : `/api/projects/${projectId}/user_interviews/`
-}
-
-export const userInterviewsList = async (
- projectId: string,
- params?: UserInterviewsListParams,
- options?: RequestInit
-): Promise<PaginatedUserInterviewListApi> => {
- return apiMutator<PaginatedUserInterviewListApi>(getUserInterviewsListUrl(projectId, params), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getUserInterviewsCreateUrl = (projectId: string) => {
- return `/api/projects/${projectId}/user_interviews/`
-}
-
-export const userInterviewsCreate = async (
- projectId: string,
- userInterviewApi: NonReadonly<UserInterviewApi>,
- options?: RequestInit
-): Promise<UserInterviewApi> => {
- const formData = new FormData()
- if (userInterviewApi.interviewee_emails !== undefined) {
- userInterviewApi.interviewee_emails.forEach((value) => formData.append(`interviewee_emails`, value))
- }
- if (userInterviewApi.summary !== undefined) {
- formData.append(`summary`, userInterviewApi.summary)
- }
- if (userInterviewApi.classifications !== undefined) {
- userInterviewApi.classifications.forEach((value) => formData.append(`classifications`, value))
- }
- formData.append(`audio`, userInterviewApi.audio)
-
- return apiMutator<UserInterviewApi>(getUserInterviewsCreateUrl(projectId), {
- ...options,
- method: 'POST',
- body: formData,
- })
-}
-
-export const getUserInterviewsRetrieveUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interviews/${id}/`
-}
-
-export const userInterviewsRetrieve = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<UserInterviewApi> => {
- return apiMutator<UserInterviewApi>(getUserInterviewsRetrieveUrl(projectId, id), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getUserInterviewsUpdateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interviews/${id}/`
-}
-
-export const userInterviewsUpdate = async (
- projectId: string,
- id: string,
- userInterviewApi: NonReadonly<UserInterviewApi>,
- options?: RequestInit
-): Promise<UserInterviewApi> => {
- const formData = new FormData()
- if (userInterviewApi.interviewee_emails !== undefined) {
- userInterviewApi.interviewee_emails.forEach((value) => formData.append(`interviewee_emails`, value))
- }
- if (userInterviewApi.summary !== undefined) {
- formData.append(`summary`, userInterviewApi.summary)
- }
- if (userInterviewApi.classifications !== undefined) {
- userInterviewApi.classifications.forEach((value) => formData.append(`classifications`, value))
- }
- formData.append(`audio`, userInterviewApi.audio)
-
- return apiMutator<UserInterviewApi>(getUserInterviewsUpdateUrl(projectId, id), {
- ...options,
- method: 'PUT',
- body: formData,
- })
-}
-
-export const getUserInterviewsPartialUpdateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interviews/${id}/`
-}
-
-export const userInterviewsPartialUpdate = async (
- projectId: string,
- id: string,
- patchedUserInterviewApi?: NonReadonly<PatchedUserInterviewApi>,
- options?: RequestInit
-): Promise<UserInterviewApi> => {
- const formData = new FormData()
- if (patchedUserInterviewApi?.interviewee_emails !== undefined) {
- patchedUserInterviewApi?.interviewee_emails.forEach((value) => formData.append(`interviewee_emails`, value))
- }
- if (patchedUserInterviewApi?.summary !== undefined) {
- formData.append(`summary`, patchedUserInterviewApi.summary)
- }
- if (patchedUserInterviewApi?.classifications !== undefined) {
- patchedUserInterviewApi?.classifications.forEach((value) => formData.append(`classifications`, value))
- }
- if (patchedUserInterviewApi?.audio !== undefined) {
- formData.append(`audio`, patchedUserInterviewApi.audio)
- }
-
- return apiMutator<UserInterviewApi>(getUserInterviewsPartialUpdateUrl(projectId, id), {
- ...options,
- method: 'PATCH',
- body: formData,
- })
-}
-
-export const getUserInterviewsDestroyUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/user_interviews/${id}/`
-}
-
-export const userInterviewsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getUserInterviewsDestroyUrl(projectId, id), {
- ...options,
- method: 'DELETE',
- })
-}
-
-export const getUserInterviewsSearchCreateUrl = (projectId: string) => {
- return `/api/projects/${projectId}/user_interviews/search/`
-}
-
-/**
- * Embed `query` with the same model used to index interview transcripts and summaries, then return the top matches by cosine distance. Each match is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and summary score above other interviews. Useful for surfacing relevant interview snippets in natural language, without exact keyword matches.
- * @summary Search interview responses by semantic similarity
- */
-export const userInterviewsSearchCreate = async (
- projectId: string,
- userInterviewSearchRequestApi: UserInterviewSearchRequestApi,
- options?: RequestInit
-): Promise<UserInterviewSearchResultApi[]> => {
- return apiMutator<UserInterviewSearchResultApi[]>(getUserInterviewsSearchCreateUrl(projectId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(userInterviewSearchRequestApi),
- })
-}
diff --git a/products/user_interviews/frontend/generated/api.zod.ts b/products/user_interviews/frontend/generated/api.zod.ts
deleted file mode 100644
index cb821140cdb9..000000000000
--- a/products/user_interviews/frontend/generated/api.zod.ts
+++ /dev/null
@@ -1,396 +0,0 @@
-/**
- * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
- * To modify these schemas, update the Django serializers or views, then run:
- * hogli build:openapi
- * Questions or issues? #team-devex on Slack
- *
- * PostHog API - generated
- * OpenAPI spec version: 1.0.0
- */
-import * as zod from 'zod'
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const userInterviewTopicsCreateBodyIntervieweeEmailsItemMax = 254
-
-export const userInterviewTopicsCreateBodyIntervieweeDistinctIdsItemMax = 400
-
-export const userInterviewTopicsCreateBodyInviteSubjectMax = 255
-
-export const userInterviewTopicsCreateBodyInviteMessageMax = 1000
-
-export const UserInterviewTopicsCreateBody = /* @__PURE__ */ zod.object({
- interviewee_emails: zod
- .array(zod.string().max(userInterviewTopicsCreateBodyIntervieweeEmailsItemMax))
- .optional()
- .describe('Email addresses of people to interview. May be combined with interviewee_distinct_ids.'),
- interviewee_distinct_ids: zod
- .array(zod.string().max(userInterviewTopicsCreateBodyIntervieweeDistinctIdsItemMax))
- .optional()
- .describe('PostHog distinct IDs of people to interview. May be combined with interviewee_emails.'),
- topic: zod.string().describe('The product, feature, or idea you want to ask interviewees about.'),
- agent_context: zod
- .string()
- .optional()
- .describe('Optional additional system prompt for the voice agent — extra background, tone, or constraints.'),
- questions: zod
- .array(zod.string())
- .optional()
- .describe('Ordered list of questions the voice agent should work through during the interview.'),
- invite_subject: zod
- .string()
- .max(userInterviewTopicsCreateBodyInviteSubjectMax)
- .optional()
- .describe(
- 'Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.'
- ),
- invite_message: zod
- .string()
- .max(userInterviewTopicsCreateBodyInviteMessageMax)
- .optional()
- .describe(
- 'Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.'
- ),
-})
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const userInterviewTopicsUpdateBodyIntervieweeEmailsItemMax = 254
-
-export const userInterviewTopicsUpdateBodyIntervieweeDistinctIdsItemMax = 400
-
-export const userInterviewTopicsUpdateBodyInviteSubjectMax = 255
-
-export const userInterviewTopicsUpdateBodyInviteMessageMax = 1000
-
-export const UserInterviewTopicsUpdateBody = /* @__PURE__ */ zod.object({
- interviewee_emails: zod
- .array(zod.string().max(userInterviewTopicsUpdateBodyIntervieweeEmailsItemMax))
- .optional()
- .describe('Email addresses of people to interview. May be combined with interviewee_distinct_ids.'),
- interviewee_distinct_ids: zod
- .array(zod.string().max(userInterviewTopicsUpdateBodyIntervieweeDistinctIdsItemMax))
- .optional()
- .describe('PostHog distinct IDs of people to interview. May be combined with interviewee_emails.'),
- topic: zod.string().describe('The product, feature, or idea you want to ask interviewees about.'),
- agent_context: zod
- .string()
- .optional()
- .describe('Optional additional system prompt for the voice agent — extra background, tone, or constraints.'),
- questions: zod
- .array(zod.string())
- .optional()
- .describe('Ordered list of questions the voice agent should work through during the interview.'),
- invite_subject: zod
- .string()
- .max(userInterviewTopicsUpdateBodyInviteSubjectMax)
- .optional()
- .describe(
- 'Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.'
- ),
- invite_message: zod
- .string()
- .max(userInterviewTopicsUpdateBodyInviteMessageMax)
- .optional()
- .describe(
- 'Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.'
- ),
-})
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const userInterviewTopicsPartialUpdateBodyIntervieweeEmailsItemMax = 254
-
-export const userInterviewTopicsPartialUpdateBodyIntervieweeDistinctIdsItemMax = 400
-
-export const userInterviewTopicsPartialUpdateBodyInviteSubjectMax = 255
-
-export const userInterviewTopicsPartialUpdateBodyInviteMessageMax = 1000
-
-export const UserInterviewTopicsPartialUpdateBody = /* @__PURE__ */ zod.object({
- interviewee_emails: zod
- .array(zod.string().max(userInterviewTopicsPartialUpdateBodyIntervieweeEmailsItemMax))
- .optional()
- .describe('Email addresses of people to interview. May be combined with interviewee_distinct_ids.'),
- interviewee_distinct_ids: zod
- .array(zod.string().max(userInterviewTopicsPartialUpdateBodyIntervieweeDistinctIdsItemMax))
- .optional()
- .describe('PostHog distinct IDs of people to interview. May be combined with interviewee_emails.'),
- topic: zod.string().optional().describe('The product, feature, or idea you want to ask interviewees about.'),
- agent_context: zod
- .string()
- .optional()
- .describe('Optional additional system prompt for the voice agent — extra background, tone, or constraints.'),
- questions: zod
- .array(zod.string())
- .optional()
- .describe('Ordered list of questions the voice agent should work through during the interview.'),
- invite_subject: zod
- .string()
- .max(userInterviewTopicsPartialUpdateBodyInviteSubjectMax)
- .optional()
- .describe(
- 'Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.'
- ),
- invite_message: zod
- .string()
- .max(userInterviewTopicsPartialUpdateBodyInviteMessageMax)
- .optional()
- .describe(
- 'Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.'
- ),
-})
-
-/**
- * Add a single interviewee to this topic. Email-shaped identifiers (including the `Display Name <email@host>` form) are appended to `interviewee_emails`; everything else is appended to `interviewee_distinct_ids`. Idempotent — adding an identifier that's already present leaves the topic unchanged. Returns the updated topic.
- */
-export const userInterviewTopicsAddIntervieweeCreateBodyIdentifierMax = 400
-
-export const UserInterviewTopicsAddIntervieweeCreateBody = /* @__PURE__ */ zod.object({
- identifier: zod
- .string()
- .max(userInterviewTopicsAddIntervieweeCreateBodyIdentifierMax)
- .describe(
- 'Email address or PostHog distinct ID for the interviewee. Email-shaped values (including the `Display Name <email@host>` form) are routed to `interviewee_emails`; everything else lands in `interviewee_distinct_ids`.'
- ),
-})
-
-/**
- * Render the invite email exactly as a specific targeted interviewee would receive it — personalized subject and body — without sending anything and without creating or reading any share links. Pass `interviewee_identifier` to preview for a particular person, or omit it to preview for the first targeted interviewee. The body always shows an illustrative placeholder link (`is_preview_link: true`), never a live interview URL.
- */
-export const userInterviewTopicsPreviewInviteCreateBodyIntervieweeIdentifierMax = 400
-
-export const UserInterviewTopicsPreviewInviteCreateBody = /* @__PURE__ */ zod.object({
- interviewee_identifier: zod
- .string()
- .max(userInterviewTopicsPreviewInviteCreateBodyIntervieweeIdentifierMax)
- .optional()
- .describe(
- 'Which targeted interviewee to render the preview for (an email or PostHog distinct ID already on the topic). Leave blank to preview for the first targeted interviewee.'
- ),
-})
-
-/**
- * Remove an interviewee from this topic. Drops the identifier from both `interviewee_emails` and `interviewee_distinct_ids`, and disables any active SharingConfiguration linked to an IntervieweeContext for that identifier on this topic so the removed person can no longer open their interview link. Idempotent — removing an identifier that isn't present is a no-op. Returns the updated topic.
- */
-export const userInterviewTopicsRemoveIntervieweeCreateBodyIdentifierMax = 400
-
-export const UserInterviewTopicsRemoveIntervieweeCreateBody = /* @__PURE__ */ zod.object({
- identifier: zod
- .string()
- .max(userInterviewTopicsRemoveIntervieweeCreateBodyIdentifierMax)
- .describe(
- 'Email address or PostHog distinct ID for the interviewee. Email-shaped values (including the `Display Name <email@host>` form) are routed to `interviewee_emails`; everything else lands in `interviewee_distinct_ids`.'
- ),
-})
-
-/**
- * Generate (if needed) and email a personalized public interview link to every targeted interviewee on this topic whose identifier is an email address. Distinct-ID-only interviewees are skipped and surfaced in the response. Each invite is keyed on the underlying SharingConfiguration so re-runs after token rotation produce a fresh send.
- */
-export const userInterviewTopicsSendInvitesCreateBodySubjectMax = 200
-
-export const userInterviewTopicsSendInvitesCreateBodySendAsyncDefault = true
-
-export const UserInterviewTopicsSendInvitesCreateBody = /* @__PURE__ */ zod.object({
- subject: zod
- .string()
- .max(userInterviewTopicsSendInvitesCreateBodySubjectMax)
- .optional()
- .describe(
- "Override the email subject line for this send. Plain text only — URLs, angle brackets, and control characters are rejected. Falls back to the topic's saved subject, then a default."
- ),
- reply_to: zod
- .email()
- .optional()
- .describe("Email address replies should go to. Defaults to the topic creator's email if blank."),
- send_async: zod
- .boolean()
- .default(userInterviewTopicsSendInvitesCreateBodySendAsyncDefault)
- .describe(
- 'If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately.'
- ),
-})
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const userInterviewTopicsIntervieweesCreateBodyIntervieweeIdentifierMax = 400
-
-export const userInterviewTopicsIntervieweesCreateBodyAgentContextMax = 10000
-
-export const UserInterviewTopicsIntervieweesCreateBody = /* @__PURE__ */ zod.object({
- interviewee_identifier: zod
- .string()
- .max(userInterviewTopicsIntervieweesCreateBodyIntervieweeIdentifierMax)
- .describe(
- "Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids."
- ),
- agent_context: zod
- .string()
- .max(userInterviewTopicsIntervieweesCreateBodyAgentContextMax)
- .describe(
- "Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'."
- ),
-})
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const userInterviewTopicsIntervieweesUpdateBodyIntervieweeIdentifierMax = 400
-
-export const userInterviewTopicsIntervieweesUpdateBodyAgentContextMax = 10000
-
-export const UserInterviewTopicsIntervieweesUpdateBody = /* @__PURE__ */ zod.object({
- interviewee_identifier: zod
- .string()
- .max(userInterviewTopicsIntervieweesUpdateBodyIntervieweeIdentifierMax)
- .describe(
- "Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids."
- ),
- agent_context: zod
- .string()
- .max(userInterviewTopicsIntervieweesUpdateBodyAgentContextMax)
- .describe(
- "Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'."
- ),
-})
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const userInterviewTopicsIntervieweesPartialUpdateBodyIntervieweeIdentifierMax = 400
-
-export const userInterviewTopicsIntervieweesPartialUpdateBodyAgentContextMax = 10000
-
-export const UserInterviewTopicsIntervieweesPartialUpdateBody = /* @__PURE__ */ zod.object({
- interviewee_identifier: zod
- .string()
- .max(userInterviewTopicsIntervieweesPartialUpdateBodyIntervieweeIdentifierMax)
- .optional()
- .describe(
- "Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids."
- ),
- agent_context: zod
- .string()
- .max(userInterviewTopicsIntervieweesPartialUpdateBodyAgentContextMax)
- .optional()
- .describe(
- "Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'."
- ),
-})
-
-/**
- * Create up to 500 interviewee context rows for a topic in a single request. Rows whose (topic, interviewee_identifier) already exists are skipped — the response surfaces an `inserted_count`, a `skipped_count`, and the `skipped_identifiers` so the caller can reconcile. Items must have unique `interviewee_identifier` values within the batch.
- */
-export const userInterviewTopicsIntervieweesBulkCreateBodyItemsItemIntervieweeIdentifierMax = 400
-
-export const userInterviewTopicsIntervieweesBulkCreateBodyItemsItemAgentContextMax = 10000
-
-export const UserInterviewTopicsIntervieweesBulkCreateBody = /* @__PURE__ */ zod.object({
- items: zod
- .array(
- zod.object({
- interviewee_identifier: zod
- .string()
- .max(userInterviewTopicsIntervieweesBulkCreateBodyItemsItemIntervieweeIdentifierMax)
- .describe(
- "Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids."
- ),
- agent_context: zod
- .string()
- .max(userInterviewTopicsIntervieweesBulkCreateBodyItemsItemAgentContextMax)
- .describe(
- "Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'."
- ),
- })
- )
- .describe(
- 'List of interviewee context rows to create. Each item has an `interviewee_identifier` and an `agent_context`. At most 500 items per request.'
- ),
-})
-
-export const userInterviewsCreateBodyIntervieweeEmailsItemMax = 254
-
-export const UserInterviewsCreateBody = /* @__PURE__ */ zod.object({
- interviewee_emails: zod.array(zod.string().max(userInterviewsCreateBodyIntervieweeEmailsItemMax)).optional(),
- summary: zod.string().optional(),
- classifications: zod
- .array(zod.enum(['abandoned', 'off-topic']).describe('\* `abandoned` - Abandoned\n\* `off-topic` - Off-topic'))
- .optional()
- .describe(
- 'Searchable classifications on the response. `abandoned` is auto-derived from the transcript when the interview is recorded; `off-topic` is set manually. Sending `classifications` on an update replaces the whole list — pass the full desired set, not a delta.'
- ),
- audio: zod.url(),
-})
-
-export const userInterviewsUpdateBodyIntervieweeEmailsItemMax = 254
-
-export const UserInterviewsUpdateBody = /* @__PURE__ */ zod.object({
- interviewee_emails: zod.array(zod.string().max(userInterviewsUpdateBodyIntervieweeEmailsItemMax)).optional(),
- summary: zod.string().optional(),
- classifications: zod
- .array(zod.enum(['abandoned', 'off-topic']).describe('\* `abandoned` - Abandoned\n\* `off-topic` - Off-topic'))
- .optional()
- .describe(
- 'Searchable classifications on the response. `abandoned` is auto-derived from the transcript when the interview is recorded; `off-topic` is set manually. Sending `classifications` on an update replaces the whole list — pass the full desired set, not a delta.'
- ),
- audio: zod.url(),
-})
-
-export const userInterviewsPartialUpdateBodyIntervieweeEmailsItemMax = 254
-
-export const UserInterviewsPartialUpdateBody = /* @__PURE__ */ zod.object({
- interviewee_emails: zod.array(zod.string().max(userInterviewsPartialUpdateBodyIntervieweeEmailsItemMax)).optional(),
- summary: zod.string().optional(),
- classifications: zod
- .array(zod.enum(['abandoned', 'off-topic']).describe('\* `abandoned` - Abandoned\n\* `off-topic` - Off-topic'))
- .optional()
- .describe(
- 'Searchable classifications on the response. `abandoned` is auto-derived from the transcript when the interview is recorded; `off-topic` is set manually. Sending `classifications` on an update replaces the whole list — pass the full desired set, not a delta.'
- ),
- audio: zod.url().optional(),
-})
-
-/**
- * Embed `query` with the same model used to index interview transcripts and summaries, then return the top matches by cosine distance. Each match is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and summary score above other interviews. Useful for surfacing relevant interview snippets in natural language, without exact keyword matches.
- * @summary Search interview responses by semantic similarity
- */
-export const userInterviewsSearchCreateBodyQueryMax = 2000
-
-export const userInterviewsSearchCreateBodyLimitMax = 50
-
-export const UserInterviewsSearchCreateBody = /* @__PURE__ */ zod.object({
- query: zod
- .string()
- .max(userInterviewsSearchCreateBodyQueryMax)
- .describe('Natural-language query to match semantically against interview transcripts and summaries.'),
- document_types: zod
- .array(zod.enum(['transcript', 'summary']).describe('\* `transcript` - transcript\n\* `summary` - summary'))
- .min(1)
- .optional()
- .describe(
- 'Which document types to search across. Omit to default to both `transcript` and `summary`. Pass a non-empty subset to restrict the search.'
- ),
- topic_id: zod
- .uuid()
- .nullish()
- .describe('Optional. Restrict results to interviews belonging to a specific UserInterviewTopic.'),
- classifications: zod
- .array(zod.enum(['abandoned', 'off-topic']).describe('\* `abandoned` - Abandoned\n\* `off-topic` - Off-topic'))
- .min(1)
- .optional()
- .describe(
- 'Optional. Restrict results to interviews carrying any of these classifications (OR). Combines with `topic_id` as AND.'
- ),
- limit: zod
- .number()
- .min(1)
- .max(userInterviewsSearchCreateBodyLimitMax)
- .optional()
- .describe(
- 'Maximum number of matches to return (1-50). Defaults to 10. Two matches per interview are possible — one for the transcript, one for the summary.'
- ),
-})
diff --git a/products/user_interviews/frontend/newTopicMaxTool.ts b/products/user_interviews/frontend/newTopicMaxTool.ts
deleted file mode 100644
index f113aaf9b904..000000000000
--- a/products/user_interviews/frontend/newTopicMaxTool.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-// Shared by the scene's "New topic" button and the empty state's primary action,
-// so both open PostHog AI armed the same way.
-export const NEW_TOPIC_PROMPT = `!I want to set up a new user research topic. Help me work through:
-1. What I want to learn — the feature, behavior, or question to research.
-2. Who to interview — let me give you emails or distinct IDs, or help me pick from a cohort.
-3. The interview questions — 3-6 open-ended, conversational prompts in a sensible order.
-Then create the topic using the create_user_interview_topic tool. Don't try to send emails or generate links yourself — once the topic exists I'll do that from the topic page.`
-
-export const NEW_TOPIC_SUGGESTIONS = [
- 'Interview recent signups about their onboarding experience',
- 'Talk to power users about what they wish the product did better',
- 'Interview customers who churned in the last 30 days',
- 'Research how teams are using dashboards day-to-day',
-]
diff --git a/products/user_interviews/frontend/parseTranscript.ts b/products/user_interviews/frontend/parseTranscript.ts
deleted file mode 100644
index 16b675b64951..000000000000
--- a/products/user_interviews/frontend/parseTranscript.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-export type TranscriptTurnSpeaker = 'ai' | 'user' | 'other'
-
-export interface TranscriptTurn {
- speaker: TranscriptTurnSpeaker
- name: string
- text: string
-}
-
-export interface ParsedTranscript {
- leadingText: string
- turns: TranscriptTurn[]
-}
-
-const TURN_SPLIT_RE = /(?:^|\n)\s*(AI|Assistant|Interviewer|User|Interviewee):\s+/i
-
-const AI_SPEAKER_RE = /^(AI|Assistant|Interviewer)$/i
-const USER_SPEAKER_RE = /^(User|Interviewee)$/i
-
-export function parseTranscript(transcript: string): ParsedTranscript {
- if (!transcript) {
- return { leadingText: '', turns: [] }
- }
- const parts = transcript.split(TURN_SPLIT_RE)
- if (parts.length < 3) {
- return { leadingText: '', turns: [] }
- }
-
- const turns: TranscriptTurn[] = []
- for (let i = 1; i < parts.length; i += 2) {
- const name = parts[i]
- const text = (parts[i + 1] ?? '').trim()
- if (!text) {
- continue
- }
- const speaker: TranscriptTurnSpeaker = AI_SPEAKER_RE.test(name)
- ? 'ai'
- : USER_SPEAKER_RE.test(name)
- ? 'user'
- : 'other'
- turns.push({ speaker, name, text })
- }
- return { leadingText: (parts[0] ?? '').trim(), turns }
-}
diff --git a/products/user_interviews/frontend/userInterviewLogic.ts b/products/user_interviews/frontend/userInterviewLogic.ts
deleted file mode 100644
index 67719550c21b..000000000000
--- a/products/user_interviews/frontend/userInterviewLogic.ts
+++ /dev/null
@@ -1,444 +0,0 @@
-import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-
-import { lemonToast } from '@posthog/lemon-ui'
-
-import api from 'lib/api'
-import { copyToClipboard } from 'lib/utils/copyToClipboard'
-import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
-
-import { Breadcrumb } from '~/types'
-
-import {
- getUserInterviewTopicsLinksCsvCreateUrl,
- userInterviewTopicsGenerateLinksCreate,
- userInterviewTopicsIntervieweesList,
- userInterviewTopicsPreviewInviteCreate,
- userInterviewTopicsRetrieve,
- userInterviewTopicsSharedLinkCreate,
- userInterviewTopicsTestLinkRetrieve,
- userInterviewsList,
-} from './generated/api'
-import { UserInterviewClassificationEnumApi } from './generated/api.schemas'
-import type {
- IntervieweeContextApi,
- InterviewLinkApi,
- PreviewInviteResultApi,
- TestInterviewLinkApi,
- UserInterviewApi,
- UserInterviewTopicApi,
-} from './generated/api.schemas'
-
-export interface UserInterviewLogicProps {
- id: string
-}
-
-function unwrapPaginatedOrArray<T>(response: T[] | { results?: T[] }): T[] {
- if (Array.isArray(response)) {
- return response
- }
- return response.results ?? []
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface userInterviewLogicValues {
- breadcrumbs: Breadcrumb[]
- interviewees: IntervieweeContextApi[]
- intervieweesLoading: boolean
- interviews: UserInterviewApi[]
- interviewsLoading: boolean
- invitePreview: PreviewInviteResultApi | null
- invitePreviewLoading: boolean
- linkByIdentifier: Record<string, string>
- linkForIdentifier: (identifier: string) => string | undefined
- links: InterviewLinkApi[]
- linksCsvExporting: boolean
- linksLoadFailed: boolean
- linksLoading: boolean
- previewInviteIdentifier: string | null
- respondedCount: number
- respondedIdentifiers: Set<string>
- responseRate: number
- sharedLinkLoading: boolean
- testLink: TestInterviewLinkApi | null
- testLinkLoading: boolean
- topic: UserInterviewTopicApi | null
- topicInterviews: UserInterviewApi[]
- topicLoading: boolean
- totalTargeted: number
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface userInterviewLogicActions {
- closeInvitePreview: () => {
- value: true
- }
- copySharedLink: () => {
- value: true
- }
- copySharedLinkDone: () => {
- value: true
- }
- exportLinksCsv: () => {
- value: true
- }
- exportLinksCsvDone: () => {
- value: true
- }
- loadInterviewees: () => any
- loadIntervieweesFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadIntervieweesSuccess: (
- interviewees: IntervieweeContextApi[],
- payload?: any
- ) => {
- interviewees: IntervieweeContextApi[]
- payload?: any
- }
- loadInterviews: () => any
- loadInterviewsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadInterviewsSuccess: (
- interviews: UserInterviewApi[],
- payload?: any
- ) => {
- interviews: UserInterviewApi[]
- payload?: any
- }
- loadInvitePreview: (identifier: string) => string
- loadInvitePreviewFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadInvitePreviewSuccess: (
- invitePreview: PreviewInviteResultApi,
- payload?: string
- ) => {
- invitePreview: PreviewInviteResultApi
- payload?: string
- }
- loadLinks: () => any
- loadLinksFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadLinksSuccess: (
- links: InterviewLinkApi[],
- payload?: any
- ) => {
- links: InterviewLinkApi[]
- payload?: any
- }
- loadTestLink: () => any
- loadTestLinkFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadTestLinkSuccess: (
- testLink: TestInterviewLinkApi,
- payload?: any
- ) => {
- testLink: TestInterviewLinkApi
- payload?: any
- }
- loadTopic: () => any
- loadTopicFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadTopicSuccess: (
- topic: UserInterviewTopicApi | null,
- payload?: any
- ) => {
- topic: UserInterviewTopicApi | null
- payload?: any
- }
- openInvitePreview: (identifier: string) => {
- identifier: string
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface userInterviewLogicMeta {
- key: string
- __keaTypeGenInternalSelectorTypes: {
- topicInterviews: (interviews: UserInterviewApi[]) => UserInterviewApi[]
- linkByIdentifier: (links: InterviewLinkApi[]) => Record<string, string>
- linkForIdentifier: (linkByIdentifier: Record<string, string>) => (identifier: string) => string | undefined
- respondedIdentifiers: (topicInterviews: UserInterviewApi[]) => Set<string>
- respondedCount: (topic: UserInterviewTopicApi | null, respondedIdentifiers: Set<string>) => number
- totalTargeted: (topic: UserInterviewTopicApi | null) => number
- responseRate: (respondedCount: number, totalTargeted: number) => number
- breadcrumbs: (topic: UserInterviewTopicApi | null) => Breadcrumb[]
- }
-}
-
-export type userInterviewLogicType = MakeLogicType<
- userInterviewLogicValues,
- userInterviewLogicActions,
- UserInterviewLogicProps,
- userInterviewLogicMeta
->
-
-export const userInterviewLogic = kea<userInterviewLogicType>([
- path(['products', 'user_interviews', 'frontend', 'userInterviewLogic']),
- props({} as UserInterviewLogicProps),
- key((props) => props.id),
- loaders(({ props }) => ({
- topic: {
- __default: null as UserInterviewTopicApi | null,
- loadTopic: async () => {
- const projectId = String(teamLogic.values.currentTeamId)
- try {
- return await userInterviewTopicsRetrieve(projectId, props.id)
- } catch {
- return null
- }
- },
- },
- interviewees: {
- __default: [] as IntervieweeContextApi[],
- loadInterviewees: async () => {
- const projectId = String(teamLogic.values.currentTeamId)
- try {
- const response = await userInterviewTopicsIntervieweesList(projectId, props.id)
- return response.results
- } catch {
- return []
- }
- },
- },
- interviews: {
- __default: [] as UserInterviewApi[],
- loadInterviews: async () => {
- const projectId = String(teamLogic.values.currentTeamId)
- try {
- const response = await userInterviewsList(projectId)
- return response.results
- } catch {
- return []
- }
- },
- },
- links: {
- __default: [] as InterviewLinkApi[],
- loadLinks: async (): Promise<InterviewLinkApi[]> => {
- const projectId = String(teamLogic.values.currentTeamId)
- const response = (await userInterviewTopicsGenerateLinksCreate(projectId, props.id)) as unknown as
- | InterviewLinkApi[]
- | { results?: InterviewLinkApi[] }
- return unwrapPaginatedOrArray(response)
- },
- },
- testLink: {
- __default: null as TestInterviewLinkApi | null,
- loadTestLink: async (): Promise<TestInterviewLinkApi> => {
- const projectId = String(teamLogic.values.currentTeamId)
- return await userInterviewTopicsTestLinkRetrieve(projectId, props.id)
- },
- },
- invitePreview: {
- __default: null as PreviewInviteResultApi | null,
- loadInvitePreview: async (identifier: string): Promise<PreviewInviteResultApi> => {
- const projectId = String(teamLogic.values.currentTeamId)
- return await userInterviewTopicsPreviewInviteCreate(projectId, props.id, {
- interviewee_identifier: identifier,
- })
- },
- },
- })),
- actions({
- exportLinksCsv: true,
- exportLinksCsvDone: true,
- copySharedLink: true,
- copySharedLinkDone: true,
- openInvitePreview: (identifier: string) => ({ identifier }),
- closeInvitePreview: true,
- }),
- reducers({
- sharedLinkLoading: [
- false,
- {
- copySharedLink: () => true,
- copySharedLinkDone: () => false,
- },
- ],
- linksLoadFailed: [
- false,
- {
- loadLinks: () => false,
- loadLinksFailure: () => true,
- },
- ],
- linksCsvExporting: [
- false,
- {
- exportLinksCsv: () => true,
- exportLinksCsvDone: () => false,
- },
- ],
- previewInviteIdentifier: [
- null as string | null,
- {
- openInvitePreview: (_, { identifier }) => identifier,
- closeInvitePreview: () => null,
- },
- ],
- }),
- listeners(({ props, values, actions }) => ({
- openInvitePreview: ({ identifier }) => {
- actions.loadInvitePreview(identifier)
- },
- loadTopicSuccess: ({ topic }) => {
- // generate_links 400s for a zero-target topic (now valid — a shared-only link needs no
- // targeted interviewees), so only materialise personalised links once we know the topic
- // has some. Avoids a guaranteed-failing POST and a misleading "couldn't generate link"
- // state on the shared-only flow.
- const hasTargets =
- (topic?.interviewee_emails?.length || 0) + (topic?.interviewee_distinct_ids?.length || 0) > 0
- if (hasTargets) {
- actions.loadLinks()
- }
- },
- copySharedLink: async () => {
- const projectId = String(teamLogic.values.currentTeamId)
- try {
- // Idempotent get-or-create — returns the topic's single shared link.
- const { interview_url } = await userInterviewTopicsSharedLinkCreate(projectId, props.id)
- await copyToClipboard(interview_url, 'shared interview link')
- } catch {
- lemonToast.error('Could not generate the shared interview link')
- } finally {
- actions.copySharedLinkDone()
- }
- },
- exportLinksCsv: async () => {
- const projectId = String(teamLogic.values.currentTeamId)
- try {
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
- const response = await api.createResponse(getUserInterviewTopicsLinksCsvCreateUrl(projectId, props.id))
- if (!response.ok) {
- throw new Error(`Export failed (${response.status})`)
- }
- const blob = await response.blob()
- const filename = `${(values.topic?.topic || 'user-interview')
- .replace(/[^\w-]+/g, '-')
- .toLowerCase()}-links.csv`
- const url = URL.createObjectURL(blob)
- const anchor = document.createElement('a')
- anchor.href = url
- anchor.download = filename
- document.body.appendChild(anchor)
- anchor.click()
- document.body.removeChild(anchor)
- URL.revokeObjectURL(url)
- } catch {
- lemonToast.error('Could not export interview links as CSV')
- } finally {
- actions.exportLinksCsvDone()
- }
- },
- })),
- selectors(({ props }) => ({
- topicInterviews: [
- (s) => [s.interviews],
- (interviews: UserInterviewApi[]): UserInterviewApi[] => interviews.filter((i) => i.topic === props.id),
- ],
- linkByIdentifier: [
- (s) => [s.links],
- (links: InterviewLinkApi[]): Record<string, string> =>
- Object.fromEntries(links.map((link) => [link.interviewee_identifier, link.interview_url])),
- ],
- linkForIdentifier: [
- (s) => [s.linkByIdentifier],
- (linkByIdentifier: Record<string, string>): ((identifier: string) => string | undefined) =>
- (identifier: string) =>
- linkByIdentifier[identifier],
- ],
- respondedIdentifiers: [
- (s) => [s.topicInterviews],
- (interviews: UserInterviewApi[]): Set<string> => {
- const responded = new Set<string>()
- for (const interview of interviews) {
- // Mirror the backend `has_replied` rule: an abandoned partial (e.g. a mid-call
- // refresh) is not a reply, so it must not mark the invitee responded — otherwise
- // the topic page and the public link disagree on who still needs chasing.
- if (interview.classifications?.includes(UserInterviewClassificationEnumApi.Abandoned)) {
- continue
- }
- if (interview.transcript || interview.summary) {
- if (interview.interviewee_identifier) {
- responded.add(interview.interviewee_identifier)
- }
- }
- }
- return responded
- },
- ],
- respondedCount: [
- (s) => [s.topic, s.respondedIdentifiers],
- (topic: UserInterviewTopicApi | null, respondedIdentifiers: Set<string>): number => {
- const allTargeted = [...(topic?.interviewee_emails || []), ...(topic?.interviewee_distinct_ids || [])]
- return allTargeted.filter((id) => respondedIdentifiers.has(id)).length
- },
- ],
- totalTargeted: [
- (s) => [s.topic],
- (topic: UserInterviewTopicApi | null): number =>
- (topic?.interviewee_emails?.length || 0) + (topic?.interviewee_distinct_ids?.length || 0),
- ],
- responseRate: [
- (s) => [s.respondedCount, s.totalTargeted],
- (respondedCount: number, totalTargeted: number): number =>
- totalTargeted > 0 ? Math.round((respondedCount / totalTargeted) * 100) : 0,
- ],
- breadcrumbs: [
- (s) => [s.topic],
- (topic: UserInterviewTopicApi | null): Breadcrumb[] => [
- {
- key: 'UserInterviews',
- name: 'User research',
- path: urls.userInterviews(),
- iconType: 'user_interview',
- },
- {
- key: props.id,
- name: topic?.topic || props.id,
- path: urls.userInterview(props.id),
- iconType: 'user_interview',
- },
- ],
- ],
- })),
- afterMount(({ actions }) => {
- actions.loadTopic()
- actions.loadInterviewees()
- actions.loadInterviews()
- // loadLinks is fired from loadTopicSuccess only when the topic has targeted interviewees —
- // generate_links 400s for the zero-target (shared-only) topics this now supports.
- actions.loadTestLink()
- }),
-])
diff --git a/products/user_interviews/frontend/userInterviewsLogic.ts b/products/user_interviews/frontend/userInterviewsLogic.ts
deleted file mode 100644
index 48c84e7d9269..000000000000
--- a/products/user_interviews/frontend/userInterviewsLogic.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-
-import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
-
-import { Breadcrumb } from '~/types'
-
-import { userInterviewTopicsList, userInterviewsSearchCreate } from './generated/api'
-import type { UserInterviewSearchResultApi, UserInterviewTopicApi } from './generated/api.schemas'
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface userInterviewsLogicValues {
- breadcrumbs: Breadcrumb[]
- searchQuery: string
- searchResults: UserInterviewSearchResultApi[]
- searchResultsLoading: boolean
- topics: UserInterviewTopicApi[]
- topicsLoading: boolean
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface userInterviewsLogicActions {
- loadSearchResults: (_: unknown) => unknown
- loadSearchResultsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadSearchResultsSuccess: (
- searchResults: UserInterviewSearchResultApi[],
- payload?: unknown
- ) => {
- searchResults: UserInterviewSearchResultApi[]
- payload?: unknown
- }
- loadTopics: () => any
- loadTopicsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadTopicsSuccess: (
- topics: UserInterviewTopicApi[],
- payload?: any
- ) => {
- topics: UserInterviewTopicApi[]
- payload?: any
- }
- setSearchQuery: (searchQuery: string) => {
- searchQuery: string
- }
-}
-
-export type userInterviewsLogicType = MakeLogicType<userInterviewsLogicValues, userInterviewsLogicActions>
-
-export const userInterviewsLogic = kea<userInterviewsLogicType>([
- path(['products', 'user_interviews', 'frontend', 'userInterviewsLogic']),
- actions({
- setSearchQuery: (searchQuery: string) => ({ searchQuery }),
- }),
- reducers({
- searchQuery: [
- '' as string,
- {
- setSearchQuery: (_, { searchQuery }) => searchQuery,
- },
- ],
- }),
- loaders(({ values }) => ({
- topics: {
- __default: [] as UserInterviewTopicApi[],
- loadTopics: async () => {
- const projectId = String(teamLogic.values.currentTeamId)
- const response = await userInterviewTopicsList(projectId)
- return response.results
- },
- },
- searchResults: {
- __default: [] as UserInterviewSearchResultApi[],
- loadSearchResults: async (_: unknown, breakpoint) => {
- await breakpoint(300)
- const query = values.searchQuery.trim()
- if (!query) {
- return []
- }
- const projectId = String(teamLogic.values.currentTeamId)
- const results = await userInterviewsSearchCreate(projectId, { query })
- breakpoint()
- return results
- },
- },
- })),
- listeners(({ actions }) => ({
- setSearchQuery: () => {
- actions.loadSearchResults(null)
- },
- })),
- selectors({
- breadcrumbs: [
- () => [],
- (): Breadcrumb[] => [
- {
- key: 'UserInterviews',
- name: 'User research',
- path: urls.userInterviews(),
- iconType: 'user_interview',
- },
- ],
- ],
- }),
- afterMount(({ actions }) => {
- actions.loadTopics()
- }),
-])
diff --git a/products/user_interviews/manifest.tsx b/products/user_interviews/manifest.tsx
deleted file mode 100644
index 93c631fa2724..000000000000
--- a/products/user_interviews/manifest.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { FEATURE_FLAGS } from 'lib/constants'
-import { urls } from 'scenes/urls'
-
-import { ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'
-
-import { FileSystemIconColor, ProductManifest } from '../../frontend/src/types'
-
-export const manifest: ProductManifest = {
- name: 'User research',
- scenes: {
- UserInterviews: {
- name: 'User research',
- import: () => import('./frontend/UserInterviews'),
- projectBased: true,
- activityScope: 'UserInterview',
- description: 'Run AI-powered voice research campaigns to gather user insights at scale.',
- iconType: 'user_interview',
- },
- UserInterview: {
- name: 'Interview topic',
- import: () => import('./frontend/UserInterview'),
- projectBased: true,
- activityScope: 'UserInterview',
- },
- UserInterviewResponse: {
- name: 'Interview response',
- import: () => import('./frontend/UserInterviewResponse'),
- projectBased: true,
- activityScope: 'UserInterview',
- },
- },
- routes: {
- // nosemgrep: frontend-route-hyphen -- shipped app URL, existing links point here
- '/user_research': ['UserInterviews', 'userInterviews'],
- // nosemgrep: frontend-route-hyphen -- shipped app URL, existing links point here
- '/user_research/:topicId/response/:responseId': ['UserInterviewResponse', 'userInterviewResponse'],
- // nosemgrep: frontend-route-hyphen -- shipped app URL, existing links point here
- '/user_research/:id': ['UserInterview', 'userInterview'],
- },
- redirects: {
- '/user_interviews': '/user_research',
- },
- urls: {
- userInterviews: (): string => '/user_research',
- userInterview: (id: string): string => `/user_research/${id}`,
- userInterviewResponse: (topicId: string, responseId: string): string =>
- `/user_research/${topicId}/response/${responseId}`,
- },
- fileSystemTypes: {
- user_interview: {
- name: 'User research',
- iconType: 'user_interview',
- href: (ref: string) => urls.userInterview(ref),
- iconColor: ['var(--color-product-user-interviews-light)', 'var(--color-product-user-interviews-dark)'],
- filterKey: 'user_interview',
- flag: FEATURE_FLAGS.USER_INTERVIEWS,
- },
- },
- treeItemsProducts: [
- {
- path: 'User research',
- intents: [ProductKey.USER_INTERVIEWS],
- category: ProductItemCategory.UNRELEASED,
- href: urls.userInterviews(),
- type: 'user_interview',
- flag: FEATURE_FLAGS.USER_INTERVIEWS,
- tags: ['alpha'],
- iconType: 'user_interview',
- iconColor: [
- 'var(--color-product-user-interviews-light)',
- 'var(--color-product-user-interviews-dark)',
- ] as FileSystemIconColor,
- sceneKey: 'UserInterviews',
- },
- ],
-}
diff --git a/products/user_interviews/mcp/apps/InviteEmailPreviewView.tsx b/products/user_interviews/mcp/apps/InviteEmailPreviewView.tsx
deleted file mode 100644
index 0b7dde752cbe..000000000000
--- a/products/user_interviews/mcp/apps/InviteEmailPreviewView.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import type { ReactElement } from 'react'
-
-import { Badge, Card, CardContent, CardHeader, CardTitle } from '@posthog/quill'
-
-export interface InviteEmailPreviewData {
- interviewee_identifier: string
- user_name: string
- email?: string | null
- subject: string
- html: string
- interview_url: string
- emailable: boolean
- is_preview_link: boolean
- _posthogUrl?: string
-}
-
-export interface InviteEmailPreviewViewProps {
- data: InviteEmailPreviewData
-}
-
-export function InviteEmailPreviewView({ data }: InviteEmailPreviewViewProps): ReactElement {
- return (
- <Card>
- <CardHeader>
- <CardTitle>{data.subject}</CardTitle>
- <div className="flex flex-col gap-1">
- <span className="text-sm text-muted-foreground">
- To {data.user_name}
- {data.email ? ` <${data.email}>` : ''}
- </span>
- <div className="flex items-center gap-2 flex-wrap">
- {!data.emailable && <Badge variant="warning">No email address — can&apos;t be sent</Badge>}
- {data.is_preview_link && <Badge>Link is a placeholder until invites are sent</Badge>}
- </div>
- </div>
- </CardHeader>
- <CardContent>
- {/* The HTML is server-rendered and sanitized at the source; render it isolated in a
- sandboxed iframe (no scripts, no same-origin) as an extra layer of safety. */}
- <iframe
- srcDoc={data.html}
- sandbox=""
- title="Invite email preview"
- className="w-full border-0"
- style={{ height: '70vh' }}
- />
- </CardContent>
- </Card>
- )
-}
diff --git a/products/user_interviews/mcp/apps/index.ts b/products/user_interviews/mcp/apps/index.ts
deleted file mode 100644
index e684c91f0ec2..000000000000
--- a/products/user_interviews/mcp/apps/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export {
- InviteEmailPreviewView,
- type InviteEmailPreviewData,
- type InviteEmailPreviewViewProps,
-} from './InviteEmailPreviewView'
diff --git a/products/user_interviews/mcp/tools.yaml b/products/user_interviews/mcp/tools.yaml
deleted file mode 100644
index fc1429be8eac..000000000000
--- a/products/user_interviews/mcp/tools.yaml
+++ /dev/null
@@ -1,406 +0,0 @@
-# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.
-# The tool list and operation IDs are kept in sync automatically:
-# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
-#
-# To enable a tool, set enabled: true and add required scopes + annotations.
-# All other fields (title, description, enrich_url, etc.) are yours to configure.
-category: User interview topics
-feature: user_interviews
-url_prefix: /user_interviews
-ui_apps:
- invite-email-preview:
- type: detail
- view_prop: data
-tools:
- user-interview-topics-add-interviewee:
- operation: user_interview_topics_add_interviewee_create
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: true
- title: Add an interviewee to a topic
- description: >
- Append a single interviewee identifier to a user interview topic. Email-shaped identifiers (including the
- `Display Name <email@host>` form) go to `interviewee_emails`; everything else goes to
- `interviewee_distinct_ids`. Idempotent — adding an identifier that is already present leaves the topic
- unchanged. Returns the updated topic.
- include_params:
- - identifier
- feature_flag: user-interviews
- user-interview-topics-create:
- operation: user_interview_topics_create
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: false
- title: Create user interview topic
- description: >
- Plan a user interview by recording who you want to target and what product or idea you want to ask them
- about. `topic` is the free-text description of the question or product area. Targets are specified as a
- combination of `interviewee_emails` (list of email addresses) and `interviewee_distinct_ids` (list of
- PostHog distinct IDs) — at least one of the two must be provided. To target a cohort, resolve cohort members
- to emails/distinct_ids in the calling agent first (see the planning-voice-agent-user-interviews skill) and
- pass them explicitly here — topics snapshot their audience at creation time. Pass `agent_context` (free
- text) to give the voice agent extra background or instructions, and `questions` (list of strings) for the
- ordered set of questions the agent should work through.
- include_params:
- - interviewee_emails
- - interviewee_distinct_ids
- - topic
- - agent_context
- - questions
- - invite_subject
- - invite_message
- feature_flag: user-interviews
- user-interview-topics-destroy:
- operation: user_interview_topics_destroy
- enabled: false
- user-interview-topics-generate-links:
- operation: user_interview_topics_generate_links_create
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: true
- title: Generate public interview links for a topic
- description: >
- Generate one public, unauthenticated interview link per targeted interviewee on a user interview topic. For
- each identifier in the topic's `interviewee_emails` and `interviewee_distinct_ids`, materializes (or reuses)
- an IntervieweeContext row and an enabled SharingConfiguration, and returns the merged voice-agent context
- alongside the URL the interviewee should open. The URL hosts the call publicly — no PostHog login required.
- Calling this multiple times is safe: existing share links are reused.
- feature_flag: user-interviews
- user-interview-topics-interviewees-bulk-create:
- operation: user_interview_topics_interviewees_bulk_create
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: false
- title: Create many per-interviewee context rows at once
- description: >
- Create up to 500 per-interviewee context rows for a topic in a single request. Each item is
- (interviewee_identifier, agent_context). Rows whose (topic, interviewee_identifier) already exists are
- skipped — the response surfaces `inserted_count`, `skipped_count`, and `skipped_identifiers` so the caller
- can reconcile. Items must have unique `interviewee_identifier` values within the batch. Prefer this over
- `user-interview-topics-interviewees-create` when adding many rows.
- include_params:
- - items
- feature_flag: user-interviews
- user-interview-topics-interviewees-create:
- operation: user_interview_topics_interviewees_create
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: false
- title: Add per-interviewee context to a topic
- description: >
- Attach extra context for a single interviewee on a user interview topic. Use this to give the voice agent
- background it should know about this specific person — e.g. "uses the replay product but has never used
- summarization". `interviewee_identifier` is the email or PostHog distinct ID matching one of the entries in
- the parent topic's targeting fields. `agent_context` is free text. At most one row per (topic,
- interviewee_identifier) — calling create twice for the same pair will conflict. Prefer
- `user-interview-topics-interviewees-bulk-create` when adding many rows at once.
- include_params:
- - interviewee_identifier
- - agent_context
- feature_flag: user-interviews
- user-interview-topics-interviewees-destroy:
- operation: user_interview_topics_interviewees_destroy
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: true
- idempotent: true
- title: Delete a per-interviewee context row
- description: >
- Remove the extra context attached to a single interviewee on a user interview topic. Only deletes the
- `IntervieweeContext` row — does not change the topic's targeting (`interviewee_emails` /
- `interviewee_distinct_ids`). Use `user-interview-topics-remove-interviewee` if you want to drop the
- interviewee from targeting as well.
- feature_flag: user-interviews
- user-interview-topics-interviewees-list:
- operation: user_interview_topics_interviewees_list
- enabled: true
- scopes:
- - user_interview:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- list: true
- title: List per-interviewee contexts for a topic
- description: >
- List the per-interviewee context rows attached to a single user interview topic. Each row is
- (interviewee_identifier, agent_context). Use this to see who has extra context attached before adding more.
- feature_flag: user-interviews
- user-interview-topics-interviewees-partial-update:
- operation: user_interview_topics_interviewees_partial_update
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: true
- title: Update a per-interviewee context row
- description: >
- Update the `agent_context` field on a per-interviewee context row. Pass only the fields you want to change.
- Does not modify the topic's targeting; use `user-interview-topics-add-interviewee` /
- `user-interview-topics-remove-interviewee` for that.
- include_params:
- - agent_context
- feature_flag: user-interviews
- user-interview-topics-interviewees-retrieve:
- operation: user_interview_topics_interviewees_retrieve
- enabled: false
- user-interview-topics-interviewees-update:
- operation: user_interview_topics_interviewees_update
- enabled: false
- user-interview-topics-links-csv:
- operation: user_interview_topics_links_csv_create
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: true
- title: Export interview links for a topic as CSV
- description: >
- Same materialization as `user-interview-topics-generate-links` but returns the per-interviewee links as a
- downloadable CSV with columns `interviewee_identifier`, `interviewee_email`, `user_name`, `interview_url`.
- Use this when the human plans to mail-merge the links into their own email tooling rather than letting
- PostHog send the invites.
- feature_flag: user-interviews
- user-interview-topics-list:
- operation: user_interview_topics_list
- enabled: true
- scopes:
- - user_interview:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- list: true
- title: List user interview topics
- description: >
- List planned user interview topics in the current project, newest first. Each result includes the topic,
- targeting (interviewee_emails, interviewee_distinct_ids), and the voice agent setup (agent_context,
- questions). Supports `search` for substring match against the topic, and `limit`/`offset` for pagination.
- feature_flag: user-interviews
- user-interview-topics-partial-update:
- operation: user_interview_topics_partial_update
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: true
- title: Update a user interview topic
- description: >
- Update fields on a user interview topic. Pass only the fields you want to change. For incremental edits to
- targeting, prefer `user-interview-topics-add-interviewee` and `user-interview-topics-remove-interviewee` —
- sending `interviewee_emails` or `interviewee_distinct_ids` here replaces the entire array.
- include_params:
- - topic
- - agent_context
- - questions
- - interviewee_emails
- - interviewee_distinct_ids
- - invite_subject
- - invite_message
- feature_flag: user-interviews
- user-interview-topics-preview-invite:
- operation: user_interview_topics_preview_invite_create
- enabled: true
- scopes:
- - user_interview:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- title: Preview the invite email for a targeted interviewee
- description: >
- Render the invitation email exactly as a specific targeted interviewee would receive it — the personalized
- subject and HTML body — without sending anything and without creating any share links. Pass
- interviewee_identifier (an email or distinct ID already on the topic) to preview for a particular person, or
- omit it to preview for the first targeted interviewee. The response includes the rendered subject and html,
- the recipient, whether they are emailable, and whether the embedded link is a placeholder.
- include_params:
- - interviewee_identifier
- ui_app: invite-email-preview
- feature_flag: user-interviews
- user-interview-topics-preview-invite-create:
- operation: user_interview_topics_preview_invite_create
- enabled: false
- user-interview-topics-remove-interviewee:
- operation: user_interview_topics_remove_interviewee_create
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: true
- idempotent: true
- title: Remove an interviewee from a topic
- description: >
- Remove an interviewee identifier from a topic's targeting. Drops the identifier from both
- `interviewee_emails` and `interviewee_distinct_ids`, and disables any active SharingConfiguration tied to
- that interviewee on this topic so the removed person can no longer open their interview link. Idempotent —
- removing an identifier that isn't present is a no-op. Returns the updated topic.
- include_params:
- - identifier
- feature_flag: user-interviews
- user-interview-topics-retrieve:
- operation: user_interview_topics_retrieve
- enabled: true
- scopes:
- - user_interview:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- title: Get user interview topic
- description: >
- Retrieve a single user interview topic by ID, including its full targeting (`interviewee_emails`,
- `interviewee_distinct_ids`), voice agent setup (`agent_context`, `questions`), and metadata. Use this to
- list the current interviewees on a topic before adding, editing, or removing them.
- feature_flag: user-interviews
- user-interview-topics-send-invites:
- operation: user_interview_topics_send_invites_create
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: true
- title: Email interview invites to every targeted interviewee
- description: >
- Generate (if not yet created) and email a personalized public interview link to every targeted interviewee
- on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a
- button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in
- the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per
- share via the messaging system's idempotency record, and a token rotation produces a fresh send key. Email
- delivery is intentionally capped at 500 recipients per send (and rate-limited per team). For larger
- audiences, don't loop this — use user-interview-topics-generate-links (or the links CSV export) to get one
- public link per interviewee and mail-merge them through your own email tooling instead.
- include_params:
- - subject
- - reply_to
- - send_async
- feature_flag: user-interviews
- user-interview-topics-shared-link-create:
- operation: user_interview_topics_shared_link_create
- enabled: false
- user-interview-topics-shared-link-destroy:
- operation: user_interview_topics_shared_link_destroy
- enabled: false
- user-interview-topics-test-link-retrieve:
- operation: user_interview_topics_test_link_retrieve
- enabled: false
- user-interview-topics-update:
- operation: user_interview_topics_update
- enabled: false
- user-interviews-create:
- operation: user_interviews_create
- enabled: false
- user-interviews-destroy:
- operation: user_interviews_destroy
- enabled: false
- user-interviews-list:
- operation: user_interviews_list
- enabled: true
- scopes:
- - user_interview:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- list: true
- title: List user interview responses
- description: >
- List completed user interview responses in the current project, newest first. Each row includes the
- interviewee email(s) and identifier, the linked `topic` UUID (set when the interview came in via a topic's
- shared link), and the AI-generated `transcript` and `summary` fields. Pass `topic` with a topic UUID to
- scope to a single research topic — use this to answer questions like "do I have any responses on my X topic
- yet?". Use `limit`/`offset` for pagination. `transcript` and `summary` can be long; when listing, prefer
- skimming the response shapes and then call `user-interviews-retrieve` for the full text of a specific
- interview. Pass `classifications` (comma-separated; any of `abandoned`, `off-topic`) to return only
- responses carrying any of those classifications — e.g. `classifications=abandoned` to find drop-offs.
- feature_flag: user-interviews
- user-interviews-partial-update:
- operation: user_interviews_partial_update
- enabled: true
- scopes:
- - user_interview:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: true
- title: Set classifications on an interview response
- description: >
- Replace the searchable `classifications` on a single interview response. The valid classifications are
- `abandoned` and `off-topic`. `abandoned` is auto-derived from the transcript when the response is recorded;
- use this to correct it or to apply `off-topic`, which is never auto-set. Sending `classifications` replaces
- the entire list — pass the full desired set, not a delta, so include the auto-derived `abandoned` if you
- want to keep it. Filter by these later via the `classifications` parameter on `user-interviews-list` and
- `user-interviews-search`.
- include_params:
- - classifications
- feature_flag: user-interviews
- user-interviews-retrieve:
- operation: user_interviews_retrieve
- enabled: true
- scopes:
- - user_interview:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- title: Retrieve a user interview response
- description: >
- Fetch a single completed user interview response by id, including the full AI-generated `transcript` and
- `summary`. Use after `user-interviews-list` has narrowed down to a specific interview — for example, to read
- what a particular interviewee said about a research topic.
- feature_flag: user-interviews
- user-interviews-search:
- operation: user_interviews_search_create
- enabled: true
- scopes:
- - user_interview:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- title: Semantic search across interview responses
- description: >
- Search recorded user interviews by meaning, not keywords. Embeds the natural-language `query` with the same
- model used to index transcripts and summaries, then returns the top matches by cosine similarity. Each match
- is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and
- summary score above other interviews. Use `document_types` to restrict to just `transcript` or just
- `summary`. Filter by `topic_id` to scope the search to a single interview topic. `limit` caps the number of
- returned matches (1-50, default 10). Filter by `classifications` (any of `abandoned`, `off-topic`) to
- restrict the search to responses carrying those; combines with `topic_id` as AND. Useful for surfacing
- relevant excerpts when the caller has a research question rather than a known string to grep for.
- feature_flag: user-interviews
- user-interviews-update:
- operation: user_interviews_update
- enabled: false
diff --git a/products/user_interviews/package.json b/products/user_interviews/package.json
index 1ba8b1a6b873..bb67e6641585 100644
--- a/products/user_interviews/package.json
+++ b/products/user_interviews/package.json
@@ -1,25 +1,6 @@
{
"name": "@posthog/products-user-interviews",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"
- },
- "dependencies": {
- "kea": "catalog:",
- "kea-loaders": "catalog:",
- "kea-router": "catalog:",
- "posthog-js": "catalog:"
- },
- "devDependencies": {
- "kea-test-utils": "catalog:"
- },
- "peerDependencies": {
- "@posthog/brand": "catalog:",
- "@posthog/icons": "catalog:",
- "@storybook/react": "catalog:",
- "@types/react": "*",
- "clsx": "*",
- "jest": "*",
- "react": "*",
- "typescript": "catalog:*"
+ "backend:test": "echo 'vestigial app — no tests'"
}
}
diff --git a/products/user_interviews/skills/planning-voice-agent-user-interviews/SKILL.md b/products/user_interviews/skills/planning-voice-agent-user-interviews/SKILL.md
deleted file mode 100644
index 18968f712ed2..000000000000
--- a/products/user_interviews/skills/planning-voice-agent-user-interviews/SKILL.md
+++ /dev/null
@@ -1,235 +0,0 @@
----
-name: planning-voice-agent-user-interviews
-description: 'Plan a round of user interviews conducted by PostHog''s AI voice agent (a "robo interviewer") — the automated voice-agent interview product. Captures a UserInterviewTopic (who to target, what to ask, framing context, question list) and calls user-interview-topics-create. ONLY trigger when the user clearly wants an AI voice agent to actually run the interview calls (e.g. "set up robo user interviews", "have the voice agent interview these users"). Do NOT trigger for ordinary user research that does not involve the voice agent — finding or shortlisting users to talk to ("who''d be a good fit to interview about Y"), planning questions for a human-run interview, or analysing feedback are audience discovery, handled with normal data queries, not this skill. Also do NOT trigger for uploading a recorded interview audio file or browsing topics with user-interview-topics-list. When intent is ambiguous, first confirm what kind of research it is and whether they want an AI voice agent to conduct it (see Step 0).'
----
-
-# Planning voice-agent user interviews
-
-Use this skill **only** when someone wants PostHog's AI voice agent — a "robo interviewer" — to actually conduct a round of user interview calls for them. The plan is captured as a `UserInterviewTopic` that the voice agent later runs through, calling each targeted person and working through the questions.
-
-This is a specific product, not a generic research helper. If the user only wants to _find_ or _shortlist_ people to interview, plan questions for an interview a human will run, or analyse feedback they already have, this is **not** the right skill — handle that as ordinary audience discovery / data work (see `querying-posthog-data`) and, at most, mention that the voice-agent option exists.
-
-## Step 0: Confirm this is the voice-agent flow
-
-Before doing anything else, make sure the user actually wants the AI voice agent to run the interviews. Many requests that mention "interviewing users" are really about discovering _who_ to talk to, not about handing the conversation to a robot.
-
-- If the user explicitly asked for the voice agent / robo interviews / automated calls, proceed to Step 1.
-- If they only asked to find or rank users to interview (e.g. "who'd be a good fit to interview about the inbox?"), treat it as audience discovery: answer it with normal queries and **do not** create a topic. You may add a one-line offer afterwards, e.g. _"If you want, I can set these up as automated interviews run by PostHog's AI voice agent — want me to do that?"_
-- If intent is ambiguous, ask first, e.g. _"Quick check on what you're after: what kind of user research is this, and do you want PostHog's AI voice agent to actually run the interviews (it calls people and works through your questions)? Or did you just want me to find the right users to talk to?"_
-
-Only continue past this step once the user has confirmed they want the voice agent to conduct the interviews.
-
-## What a complete topic needs
-
-Before calling `user-interview-topics-create`, gather these:
-
-1. **Who to interview** — at least one of:
- - `interviewee_emails` — list of email addresses
- - `interviewee_distinct_ids` — list of PostHog distinct IDs
-2. **What to ask about** — `topic` (required free text)
-3. **How the agent should frame the conversation** — optional `agent_context` (extra system prompt)
-4. **The questions to work through** — optional ordered `questions` list
-
-Topics snapshot their audience at create time — there is no live cohort link. If the user names a cohort, you (the agent) resolve cohort members to emails/distinct_ids before calling `user-interview-topics-create`. See Step 2 for the resolution flow and the 500-member cap UX.
-
-The API rejects topics with no targeting, so `interviewee_emails` and/or `interviewee_distinct_ids` must end up non-empty.
-
-## Step 1: Clarify intent
-
-If the request is vague, ask:
-
-- **Which feature or behavior?** "checkout" might be the button click, the page view, or the payment submission — narrow it down to one event.
-- **What do you want to learn?** Why they bounced? What confused them? What alternatives they tried? The goal shapes both the audience and the questions.
-- **Which kind of users?** Heavy users (what works), drop-offs (what blocks adoption), at-risk users (what breaks retention), or a mix.
-
-Skip these questions only when the user has already answered them.
-
-## Step 2: Pick the audience
-
-Map what the user said to one of these paths:
-
-- **They named a cohort** ("our power users", "trial signups last week") — use `cohorts-list` (or a `system.cohorts` SQL search) to find the cohort, confirm the match, then resolve cohort members to emails/distinct_ids (see "Resolving a cohort" below).
-- **They described the kind of person but no cohort exists** — offer to either create the cohort first (`cohorts-create`), then resolve it, or fall back to finding people by behavior (see below).
-- **They gave email addresses or distinct IDs** — accept them directly. Skip the cohort lookup.
-- **They described a behavior, not a cohort** ("users who tried checkout but didn't finish", "people who used to use dark mode and stopped") — find them by querying their events (see below).
-- **They were vague** ("a few customers", "some power users") — ask which they prefer:
- - Pick an existing cohort → `cohorts-list`
- - Look up specific persons by name or email → `persons-list` with a search query
- - Find users by behavior → see below
- - Paste a list of email addresses
-
-Each email passes through DRF email validation (display-name format `Paul D'Ambra <[email protected]>` is accepted alongside plain `[email protected]`).
-
-### Resolving a cohort
-
-Topics snapshot their audience at create time. When the user picks a cohort, you must materialize the member list into `interviewee_emails` (and `interviewee_distinct_ids` for members without emails) before creating the topic.
-
-1. **Count the cohort first.** Cheap query, decides the next step:
-
- ```sql
- SELECT count() FROM persons WHERE id IN COHORT <cohort_id>
- ```
-
-2. **If the cohort has 500 or fewer members**, fetch their emails:
-
- ```sql
- SELECT properties.email AS email
- FROM persons
- WHERE id IN COHORT <cohort_id> AND properties.email IS NOT NULL
- LIMIT 500
- ```
-
- Put each row into `interviewee_emails`. Dedupe.
-
- Cohort members without an email property aren't included by default — the `persons.id` column is the person UUID, not the SDK distinct_id, so it can't be used as an `interviewee_distinct_id` without a `pdi.distinct_id` join. If you specifically need to reach members who only exist as distinct IDs, ask the user first, then do the join explicitly.
-
-3. **If the cohort has more than 500 members**, stop and ask the user. Do not silently truncate, sample, or fall back to a different cohort — the user needs to choose. Surface:
- - The cohort name and count (e.g. "PostHog Team has 28,563 members — over the 500 cap.")
- - Why the cap exists ("we snapshot the audience at create time, and 500 is an agent-side guardrail to keep one interview campaign manageable — the backend itself does not cap the array length")
- - Their options:
- - **Narrow the cohort** — describe the subset they actually want (e.g. "engineers only", "active in the last 30 days"). You can offer to write a more specific HogQL filter or create a new, smaller cohort via `cohorts-create`.
- - **Sample randomly** — confirm a count (e.g. 200) and use `ORDER BY rand() LIMIT <n>` on the cohort query. Make the randomness explicit so they know they're not getting the "top" members.
- - **Paste a curated list** — they take over and provide emails directly.
-
- Pick the path with them, then re-run the resolution. Never proceed without an explicit decision.
-
-4. **Tell the user what you resolved.** After resolution, confirm before creating: "Cohort 'X' has N members, resolved to E emails and D distinct IDs (snapshot — won't update if the cohort changes later)." This makes the snapshot semantics visible.
-
-### Finding users by behavior
-
-When the user describes who they want to talk to in behavioral terms, find them in the project's own data:
-
-1. **Find the right event.** Call `read-data-schema` to list events that actually exist in the project. Don't guess event names from training data — PostHog event taxonomies are bespoke. Match the user's description to one or two candidate events; if multiple plausible matches exist, list them and ask which behavior they care about.
-2. **Query for users.** Call `execute-sql` with HogQL. Filter by the chosen event over the last 60 days and group per person with `coalesce(person.properties.email, distinct_id) AS id` — this keeps both kinds of rows in a single query: people with an email group under it (directly usable as `interviewee_emails`), while emailless people fall back to their own `distinct_id` (for `interviewee_distinct_ids`) instead of collapsing into one junk `None` bucket that would sort to the top under `ORDER BY count() DESC` and eat a slot of the sample. The selected `email` column tells you which is which when routing (see below). The aggregates in each template (`event_count`, `last_seen`, `days_since_last_seen`) are what feed Step 5's per-interviewee context. Replace `<event_name>` with the chosen event:
- - **Heavy users** — `SELECT coalesce(person.properties.email, distinct_id) AS id, person.properties.email AS email, count() AS event_count, max(timestamp) AS last_seen, dateDiff('day', max(timestamp), now()) AS days_since_last_seen FROM events WHERE event = '<event_name>' AND timestamp > now() - INTERVAL 60 DAY GROUP BY id, email HAVING count() >= 5 ORDER BY count() DESC LIMIT 20`
- - **Drop-offs** (tried once or twice and never came back) — `SELECT coalesce(person.properties.email, distinct_id) AS id, person.properties.email AS email, count() AS event_count, max(timestamp) AS last_seen, dateDiff('day', max(timestamp), now()) AS days_since_last_seen FROM events WHERE event = '<event_name>' AND timestamp > now() - INTERVAL 60 DAY GROUP BY id, email HAVING count() <= 2 AND dateDiff('day', max(timestamp), now()) > 14 ORDER BY count() ASC LIMIT 20`
- - **At-risk** (was active, now dormant) — `SELECT coalesce(person.properties.email, distinct_id) AS id, person.properties.email AS email, count() AS event_count, max(timestamp) AS last_seen, dateDiff('day', max(timestamp), now()) AS days_since_last_seen FROM events WHERE event = '<event_name>' AND timestamp > now() - INTERVAL 60 DAY GROUP BY id, email HAVING count() >= 3 AND dateDiff('day', max(timestamp), now()) > 14 ORDER BY days_since_last_seen DESC LIMIT 20`
-3. **Build a balanced sample.** Unless the user asked for one specific segment, mixing 5 heavy users + 3 drop-offs + 2 at-risk users yields the most actionable interviews: you learn what works, what blocks adoption, and what breaks retention. Adjust counts to match what the user actually wants.
-
-Route each row by its `email` column: rows where `email` is non-null go into `interviewee_emails`, and rows where `email` is null (so `id` holds the `distinct_id`) go into `interviewee_distinct_ids` — both can be set on the same topic. Keep `event_count` and `days_since_last_seen` per person so Step 5 can synthesise context like "used checkout 47 times in last 60 days; last seen 2 days ago".
-
-## Step 3: Capture the topic
-
-`topic` is one or two sentences describing what the interview is about. Infer from context where possible — don't ask the user to repeat themselves.
-
-Example: "ask trial users why they didn't convert" → `topic: "Why trial users didn't convert in the first 14 days"`.
-
-## Step 4: Prepare the voice agent
-
-Two fields shape what the agent actually does on the call. **Always ask about both before creating the topic.**
-
-### Always ask: what questions do they want to ask?
-
-`questions` is an ordered list the agent works through. Anchors, not a script — the agent will adapt phrasing. Keep them open-ended:
-
-- ✅ "What made you decide to try PostHog?"
-- ❌ "Did you like PostHog?"
-
-If the user already listed questions in their original request, use those and confirm. Otherwise, ask explicitly: _"What questions do you want the agent to ask?"_
-
-If the user can't think of any, suggest 3–5 open-ended questions drawn from the `topic` and offer them for review before creating.
-
-The field is technically optional in the API, but don't skip it silently — an interview with no questions is rarely useful.
-
-Question templates by research goal:
-
-- **Why users dropped off / churned**:
- - "Tell me about the last time you tried [feature] — what were you trying to do?"
- - "Walk me through what happened step-by-step."
- - "What did you expect vs what actually happened?"
- - "What made you stop or decide not to continue?"
- - "What would need to change for you to use [feature] regularly?"
-- **Why heavy users love a feature**:
- - "Tell me about how you use [feature] — what problem does it solve for you?"
- - "Walk me through your typical workflow."
- - "What would you do if [feature] didn't exist?"
- - "What almost made you not use it when you first tried?"
- - "What's one thing you wish it did differently?"
-- **Why someone hasn't tried a feature yet**:
- - "Have you noticed [feature] in the product?"
- - "What's stopped you from trying it?"
- - "What would have to be true for it to be worth trying?"
-
-### Always offer: extra context to guide the interview
-
-`agent_context` is optional, but a few sentences here make the conversation dramatically better. Always offer the user the chance to provide it, e.g.:
-
-> _"Want to give the agent any extra context? Things like tone, what to avoid, or background on the interviewee help guide the conversation. It's optional."_
-
-Useful kinds of context:
-
-- **Tone**: "warm and conversational", "skip pleasantries — this is a 10-minute call"
-- **Constraints**: "don't promise feature delivery", "do not discuss pricing"
-- **Background the agent should know**: "the user just churned from the Scale plan; be empathetic", "this person tried PostHog 6 months ago and bounced"
-- **Persona**: "you are Sam, a PostHog product researcher"
-
-If the user declines, that's fine — leave `agent_context` empty and continue.
-
-## Calling user-interview-topics-create
-
-Once you have the pieces:
-
-```json
-{
- "topic": "Why trial users churned in week 2",
- "interviewee_emails": ["[email protected]", "[email protected]"],
- "interviewee_distinct_ids": ["distinct-id-with-no-email"],
- "agent_context": "Be warm. The interviewee just churned — don't pitch.",
- "questions": [
- "What were you hoping PostHog would help with?",
- "Where did you get stuck?",
- "What would have made you stay?"
- ]
-}
-```
-
-After creation, capture the returned topic ID — you'll need it for Step 5 and for handing off to the voice agent.
-
-## Step 5: Optionally attach per-interviewee context
-
-The topic-level `agent_context` applies to every interviewee. If the user knows something specific about individual interviewees that should shape that one conversation, attach it as a per-interviewee row via `user-interview-topics-interviewees-create`. This is optional — most topics won't need it.
-
-Each row pairs an `interviewee_identifier` (must match one of the emails or distinct IDs in the parent topic's targeting) with an `agent_context` string. At most one row per (topic, interviewee). A user can have zero rows.
-
-Good per-interviewee context looks like:
-
-- "uses the replay product but has never used summarization"
-- "churned from Scale plan last month — be empathetic, don't pitch"
-- "founder, very technical, skip basic product explanations"
-
-After Step 4 succeeds, ask the user: _"Want to add per-interviewee context? Useful when individual people have very different backgrounds. You can either dictate the rows or paste a CSV."_
-
-If you found the audience via behavioral query in Step 2, you already have per-person context (usage counts, dormancy windows). Use it: e.g. `"used checkout 47 times in last 60 days; last seen 2 days ago"` for heavy users, `"tried checkout once 18 days ago, never returned"` for drop-offs.
-
-### Accepting CSV input
-
-If the user pastes a CSV, expect two columns: `identifier,context`. Either with or without a header row. Examples:
-
-```csv
[email protected],uses replay but never summarization
[email protected],founder; very technical; skip product basics
-```
-
-Or with a header:
-
-```csv
-identifier,context
-abc-distinct-id-1,churned from Scale last month — be empathetic
-```
-
-Parse the CSV, then create the rows with the captured `topic_id`. For more than a couple of rows, prefer `user-interview-topics-interviewees-bulk-create` — it takes an `items` array of `(interviewee_identifier, agent_context)` and creates up to 500 rows in one request, reporting `inserted_count`, `skipped_count`, and `skipped_identifiers` for pairs that already exist. Fall back to `user-interview-topics-interviewees-create` for a single row. Skip blank lines. Quote-escape commas inside the context cell — standard CSV rules.
-
-If a row's identifier isn't present in the parent topic's `interviewee_emails` or `interviewee_distinct_ids`, warn the user before creating — the voice agent looks up context by exact string match, so a mismatched identifier just gets ignored at runtime.
-
-## Edge cases
-
-- **No users match the behavioral query.** Possible reasons: the event isn't firing, the date range is too narrow, or no users have email addresses captured as person properties. Offer to widen the date range, try a different event, or fall back to cohorts / explicit emails.
-- **Users matched but few have emails.** PostHog stores whatever the SDK captures. If only a handful of matching users have email addresses on their person profile, surface the count and ask: take the smaller sample, fall back to `interviewee_distinct_ids` (the agent can still reach them via in-app delivery), or skip the behavioral query and let the user paste emails directly.
-- **Ambiguous event name.** If `read-data-schema` returns multiple candidates (e.g. `checkout_started`, `checkout_completed`, `checkout_abandoned`), list them with counts and let the user pick the behavior they want to understand. Don't pick silently.
-- **User asks to interview only drop-offs (or only one segment).** That works, but flag the tradeoff: interviewing only drop-offs tells you what's broken without telling you what works. Recommend including 2–3 successful users for contrast unless the user has a reason for the narrower sample.
-
-## What this skill is not for
-
-- **Uploading a recorded interview** — that's the separate `UserInterview` model (`user_interviews_create` with an audio file). Different flow, different model.
-- **Listing existing topics** — `user-interview-topics-list` handles that directly with `search`, `limit`, and `offset`. No skill needed.
-- **Analyzing transcripts after the interview** — out of scope here; that lives with the recorded `UserInterview` flow.
diff --git a/products/user_interviews/tsconfig.json b/products/user_interviews/tsconfig.json
deleted file mode 100644
index fe425d6fcba8..000000000000
--- a/products/user_interviews/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "extends": "../../tsconfig.json",
- "compilerOptions": {
- "composite": true
- }
-}
diff --git a/pyproject.toml b/pyproject.toml
index 3c088214a963..c3e1d9f46366 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -634,13 +634,6 @@ ignore_imports = [
# Saved-views ModelViewSet needs the model class for its serializer; same accepted pattern as
# logs' views_api. TODO: route through facade with the broader presentation cleanup.
"products.tracing.backend.presentation.views_api -> products.tracing.backend.models",
- "products.user_interviews.backend.presentation.views -> products.user_interviews.backend.models",
- "products.user_interviews.backend.presentation.views -> products.user_interviews.backend.invite_email",
- # The public interview view still resolves a share token itself and reads the team, the
- # interviewee context and the topic off the ORM rows, so it takes the share lookup and the
- # respondent-field helpers from logic directly. A facade read would have to hand back the
- # SharingConfiguration, which §5 forbids.
- "products.user_interviews.backend.presentation.webhooks -> products.user_interviews.backend.logic",
# logs presentation isolation (temporary): the moved viewsets still reach in-product
# internals directly. Removed by the follow-up that thins each viewset to go through
# the facade.
diff --git a/services/mcp/README.md b/services/mcp/README.md
index fda02c72d20f..3f4a3611de04 100644
--- a/services/mcp/README.md
+++ b/services/mcp/README.md
@@ -273,7 +273,6 @@ Available features:
| `surveys` | [Surveys](https://posthog.com/docs/surveys) |
| `tasks` | [Tasks](https://posthog.com/docs/posthog-desktop/tasks) |
| `tracing` | Tracing |
-| `user_interviews` | User interview topics |
| `visual_review` | Visual review |
| `warehouse_sources` | Warehouse sources |
| `web_analytics` | [Web analytics](https://posthog.com/docs/web-analytics) |
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index d6ca20f80e4a..e133c32d79ce 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -12737,291 +12737,6 @@
"readOnlyHint": false
}
},
- "user-interview-topics-add-interviewee": {
- "description": "Append a single interviewee identifier to a user interview topic. Email-shaped identifiers (including the `Display Name <email@host>` form) go to `interviewee_emails`; everything else goes to `interviewee_distinct_ids`. Idempotent — adding an identifier that is already present leaves the topic unchanged. Returns the updated topic.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Add an interviewee to a topic",
- "title": "Add an interviewee to a topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-create": {
- "description": "Plan a user interview by recording who you want to target and what product or idea you want to ask them about. `topic` is the free-text description of the question or product area. Targets are specified as a combination of `interviewee_emails` (list of email addresses) and `interviewee_distinct_ids` (list of PostHog distinct IDs) — at least one of the two must be provided. To target a cohort, resolve cohort members to emails/distinct_ids in the calling agent first (see the planning-voice-agent-user-interviews skill) and pass them explicitly here — topics snapshot their audience at creation time. Pass `agent_context` (free text) to give the voice agent extra background or instructions, and `questions` (list of strings) for the ordered set of questions the agent should work through.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Create user interview topic",
- "title": "Create user interview topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": false,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-generate-links": {
- "description": "Generate one public, unauthenticated interview link per targeted interviewee on a user interview topic. For each identifier in the topic's `interviewee_emails` and `interviewee_distinct_ids`, materializes (or reuses) an IntervieweeContext row and an enabled SharingConfiguration, and returns the merged voice-agent context alongside the URL the interviewee should open. The URL hosts the call publicly — no PostHog login required. Calling this multiple times is safe: existing share links are reused.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Generate public interview links for a topic",
- "title": "Generate public interview links for a topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-interviewees-bulk-create": {
- "description": "Create up to 500 per-interviewee context rows for a topic in a single request. Each item is (interviewee_identifier, agent_context). Rows whose (topic, interviewee_identifier) already exists are skipped — the response surfaces `inserted_count`, `skipped_count`, and `skipped_identifiers` so the caller can reconcile. Items must have unique `interviewee_identifier` values within the batch. Prefer this over `user-interview-topics-interviewees-create` when adding many rows.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Create many per-interviewee context rows at once",
- "title": "Create many per-interviewee context rows at once",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": false,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-interviewees-create": {
- "description": "Attach extra context for a single interviewee on a user interview topic. Use this to give the voice agent background it should know about this specific person — e.g. \"uses the replay product but has never used summarization\". `interviewee_identifier` is the email or PostHog distinct ID matching one of the entries in the parent topic's targeting fields. `agent_context` is free text. At most one row per (topic, interviewee_identifier) — calling create twice for the same pair will conflict. Prefer `user-interview-topics-interviewees-bulk-create` when adding many rows at once.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Add per-interviewee context to a topic",
- "title": "Add per-interviewee context to a topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": false,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-interviewees-destroy": {
- "description": "Remove the extra context attached to a single interviewee on a user interview topic. Only deletes the `IntervieweeContext` row — does not change the topic's targeting (`interviewee_emails` / `interviewee_distinct_ids`). Use `user-interview-topics-remove-interviewee` if you want to drop the interviewee from targeting as well.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Delete a per-interviewee context row",
- "title": "Delete a per-interviewee context row",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": true,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-interviewees-list": {
- "description": "List the per-interviewee context rows attached to a single user interview topic. Each row is (interviewee_identifier, agent_context). Use this to see who has extra context attached before adding more.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "List per-interviewee contexts for a topic",
- "title": "List per-interviewee contexts for a topic",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-interviewees-partial-update": {
- "description": "Update the `agent_context` field on a per-interviewee context row. Pass only the fields you want to change. Does not modify the topic's targeting; use `user-interview-topics-add-interviewee` / `user-interview-topics-remove-interviewee` for that.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Update a per-interviewee context row",
- "title": "Update a per-interviewee context row",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-links-csv": {
- "description": "Same materialization as `user-interview-topics-generate-links` but returns the per-interviewee links as a downloadable CSV with columns `interviewee_identifier`, `interviewee_email`, `user_name`, `interview_url`. Use this when the human plans to mail-merge the links into their own email tooling rather than letting PostHog send the invites.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Export interview links for a topic as CSV",
- "title": "Export interview links for a topic as CSV",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-list": {
- "description": "List planned user interview topics in the current project, newest first. Each result includes the topic, targeting (interviewee_emails, interviewee_distinct_ids), and the voice agent setup (agent_context, questions). Supports `search` for substring match against the topic, and `limit`/`offset` for pagination.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "List user interview topics",
- "title": "List user interview topics",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-partial-update": {
- "description": "Update fields on a user interview topic. Pass only the fields you want to change. For incremental edits to targeting, prefer `user-interview-topics-add-interviewee` and `user-interview-topics-remove-interviewee` — sending `interviewee_emails` or `interviewee_distinct_ids` here replaces the entire array.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Update a user interview topic",
- "title": "Update a user interview topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-preview-invite": {
- "description": "Render the invitation email exactly as a specific targeted interviewee would receive it — the personalized subject and HTML body — without sending anything and without creating any share links. Pass interviewee_identifier (an email or distinct ID already on the topic) to preview for a particular person, or omit it to preview for the first targeted interviewee. The response includes the rendered subject and html, the recipient, whether they are emailable, and whether the embedded link is a placeholder.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Preview the invite email for a targeted interviewee",
- "title": "Preview the invite email for a targeted interviewee",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-remove-interviewee": {
- "description": "Remove an interviewee identifier from a topic's targeting. Drops the identifier from both `interviewee_emails` and `interviewee_distinct_ids`, and disables any active SharingConfiguration tied to that interviewee on this topic so the removed person can no longer open their interview link. Idempotent — removing an identifier that isn't present is a no-op. Returns the updated topic.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Remove an interviewee from a topic",
- "title": "Remove an interviewee from a topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": true,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-retrieve": {
- "description": "Retrieve a single user interview topic by ID, including its full targeting (`interviewee_emails`, `interviewee_distinct_ids`), voice agent setup (`agent_context`, `questions`), and metadata. Use this to list the current interviewees on a topic before adding, editing, or removing them.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Get user interview topic",
- "title": "Get user interview topic",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-send-invites": {
- "description": "Generate (if not yet created) and email a personalized public interview link to every targeted interviewee on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per share via the messaging system's idempotency record, and a token rotation produces a fresh send key. Email delivery is intentionally capped at 500 recipients per send (and rate-limited per team). For larger audiences, don't loop this — use user-interview-topics-generate-links (or the links CSV export) to get one public link per interviewee and mail-merge them through your own email tooling instead.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Email interview invites to every targeted interviewee",
- "title": "Email interview invites to every targeted interviewee",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interviews-list": {
- "description": "List completed user interview responses in the current project, newest first. Each row includes the interviewee email(s) and identifier, the linked `topic` UUID (set when the interview came in via a topic's shared link), and the AI-generated `transcript` and `summary` fields. Pass `topic` with a topic UUID to scope to a single research topic — use this to answer questions like \"do I have any responses on my X topic yet?\". Use `limit`/`offset` for pagination. `transcript` and `summary` can be long; when listing, prefer skimming the response shapes and then call `user-interviews-retrieve` for the full text of a specific interview. Pass `classifications` (comma-separated; any of `abandoned`, `off-topic`) to return only responses carrying any of those classifications — e.g. `classifications=abandoned` to find drop-offs.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "List user interview responses",
- "title": "List user interview responses",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interviews-partial-update": {
- "description": "Replace the searchable `classifications` on a single interview response. The valid classifications are `abandoned` and `off-topic`. `abandoned` is auto-derived from the transcript when the response is recorded; use this to correct it or to apply `off-topic`, which is never auto-set. Sending `classifications` replaces the entire list — pass the full desired set, not a delta, so include the auto-derived `abandoned` if you want to keep it. Filter by these later via the `classifications` parameter on `user-interviews-list` and `user-interviews-search`.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Set classifications on an interview response",
- "title": "Set classifications on an interview response",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interviews-retrieve": {
- "description": "Fetch a single completed user interview response by id, including the full AI-generated `transcript` and `summary`. Use after `user-interviews-list` has narrowed down to a specific interview — for example, to read what a particular interviewee said about a research topic.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Retrieve a user interview response",
- "title": "Retrieve a user interview response",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interviews-search": {
- "description": "Search recorded user interviews by meaning, not keywords. Embeds the natural-language `query` with the same model used to index transcripts and summaries, then returns the top matches by cosine similarity. Each match is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and summary score above other interviews. Use `document_types` to restrict to just `transcript` or just `summary`. Filter by `topic_id` to scope the search to a single interview topic. `limit` caps the number of returned matches (1-50, default 10). Filter by `classifications` (any of `abandoned`, `off-topic`) to restrict the search to responses carrying those; combines with `topic_id` as AND. Useful for surfacing relevant excerpts when the caller has a research question rather than a known string to grep for.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Semantic search across interview responses",
- "title": "Semantic search across interview responses",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
"user-settings-update": {
"description": "Update the authenticated user's profile and settings using PATCH semantics — only the fields included in the request body are changed. Pass `@me` as the UUID; non-staff callers may only update their own account. Use `user-get` first to inspect current settings. `notification_settings` merges key-by-key; changing `email` triggers a verification flow; changing `password` also requires `current_password`. Always confirm changes with the user before applying.",
"category": "Core",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 42c9a6ea0042..510c5420b268 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -13415,291 +13415,6 @@
"readOnlyHint": false
}
},
- "user-interview-topics-add-interviewee": {
- "description": "Append a single interviewee identifier to a user interview topic. Email-shaped identifiers (including the `Display Name <email@host>` form) go to `interviewee_emails`; everything else goes to `interviewee_distinct_ids`. Idempotent — adding an identifier that is already present leaves the topic unchanged. Returns the updated topic.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Add an interviewee to a topic",
- "title": "Add an interviewee to a topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-create": {
- "description": "Plan a user interview by recording who you want to target and what product or idea you want to ask them about. `topic` is the free-text description of the question or product area. Targets are specified as a combination of `interviewee_emails` (list of email addresses) and `interviewee_distinct_ids` (list of PostHog distinct IDs) — at least one of the two must be provided. To target a cohort, resolve cohort members to emails/distinct_ids in the calling agent first (see the planning-voice-agent-user-interviews skill) and pass them explicitly here — topics snapshot their audience at creation time. Pass `agent_context` (free text) to give the voice agent extra background or instructions, and `questions` (list of strings) for the ordered set of questions the agent should work through.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Create user interview topic",
- "title": "Create user interview topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": false,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-generate-links": {
- "description": "Generate one public, unauthenticated interview link per targeted interviewee on a user interview topic. For each identifier in the topic's `interviewee_emails` and `interviewee_distinct_ids`, materializes (or reuses) an IntervieweeContext row and an enabled SharingConfiguration, and returns the merged voice-agent context alongside the URL the interviewee should open. The URL hosts the call publicly — no PostHog login required. Calling this multiple times is safe: existing share links are reused.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Generate public interview links for a topic",
- "title": "Generate public interview links for a topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-interviewees-bulk-create": {
- "description": "Create up to 500 per-interviewee context rows for a topic in a single request. Each item is (interviewee_identifier, agent_context). Rows whose (topic, interviewee_identifier) already exists are skipped — the response surfaces `inserted_count`, `skipped_count`, and `skipped_identifiers` so the caller can reconcile. Items must have unique `interviewee_identifier` values within the batch. Prefer this over `user-interview-topics-interviewees-create` when adding many rows.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Create many per-interviewee context rows at once",
- "title": "Create many per-interviewee context rows at once",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": false,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-interviewees-create": {
- "description": "Attach extra context for a single interviewee on a user interview topic. Use this to give the voice agent background it should know about this specific person — e.g. \"uses the replay product but has never used summarization\". `interviewee_identifier` is the email or PostHog distinct ID matching one of the entries in the parent topic's targeting fields. `agent_context` is free text. At most one row per (topic, interviewee_identifier) — calling create twice for the same pair will conflict. Prefer `user-interview-topics-interviewees-bulk-create` when adding many rows at once.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Add per-interviewee context to a topic",
- "title": "Add per-interviewee context to a topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": false,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-interviewees-destroy": {
- "description": "Remove the extra context attached to a single interviewee on a user interview topic. Only deletes the `IntervieweeContext` row — does not change the topic's targeting (`interviewee_emails` / `interviewee_distinct_ids`). Use `user-interview-topics-remove-interviewee` if you want to drop the interviewee from targeting as well.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Delete a per-interviewee context row",
- "title": "Delete a per-interviewee context row",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": true,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-interviewees-list": {
- "description": "List the per-interviewee context rows attached to a single user interview topic. Each row is (interviewee_identifier, agent_context). Use this to see who has extra context attached before adding more.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "List per-interviewee contexts for a topic",
- "title": "List per-interviewee contexts for a topic",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-interviewees-partial-update": {
- "description": "Update the `agent_context` field on a per-interviewee context row. Pass only the fields you want to change. Does not modify the topic's targeting; use `user-interview-topics-add-interviewee` / `user-interview-topics-remove-interviewee` for that.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Update a per-interviewee context row",
- "title": "Update a per-interviewee context row",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-links-csv": {
- "description": "Same materialization as `user-interview-topics-generate-links` but returns the per-interviewee links as a downloadable CSV with columns `interviewee_identifier`, `interviewee_email`, `user_name`, `interview_url`. Use this when the human plans to mail-merge the links into their own email tooling rather than letting PostHog send the invites.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Export interview links for a topic as CSV",
- "title": "Export interview links for a topic as CSV",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-list": {
- "description": "List planned user interview topics in the current project, newest first. Each result includes the topic, targeting (interviewee_emails, interviewee_distinct_ids), and the voice agent setup (agent_context, questions). Supports `search` for substring match against the topic, and `limit`/`offset` for pagination.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "List user interview topics",
- "title": "List user interview topics",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-partial-update": {
- "description": "Update fields on a user interview topic. Pass only the fields you want to change. For incremental edits to targeting, prefer `user-interview-topics-add-interviewee` and `user-interview-topics-remove-interviewee` — sending `interviewee_emails` or `interviewee_distinct_ids` here replaces the entire array.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Update a user interview topic",
- "title": "Update a user interview topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-preview-invite": {
- "description": "Render the invitation email exactly as a specific targeted interviewee would receive it — the personalized subject and HTML body — without sending anything and without creating any share links. Pass interviewee_identifier (an email or distinct ID already on the topic) to preview for a particular person, or omit it to preview for the first targeted interviewee. The response includes the rendered subject and html, the recipient, whether they are emailable, and whether the embedded link is a placeholder.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Preview the invite email for a targeted interviewee",
- "title": "Preview the invite email for a targeted interviewee",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-remove-interviewee": {
- "description": "Remove an interviewee identifier from a topic's targeting. Drops the identifier from both `interviewee_emails` and `interviewee_distinct_ids`, and disables any active SharingConfiguration tied to that interviewee on this topic so the removed person can no longer open their interview link. Idempotent — removing an identifier that isn't present is a no-op. Returns the updated topic.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Remove an interviewee from a topic",
- "title": "Remove an interviewee from a topic",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": true,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-retrieve": {
- "description": "Retrieve a single user interview topic by ID, including its full targeting (`interviewee_emails`, `interviewee_distinct_ids`), voice agent setup (`agent_context`, `questions`), and metadata. Use this to list the current interviewees on a topic before adding, editing, or removing them.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Get user interview topic",
- "title": "Get user interview topic",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interview-topics-send-invites": {
- "description": "Generate (if not yet created) and email a personalized public interview link to every targeted interviewee on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per share via the messaging system's idempotency record, and a token rotation produces a fresh send key. Email delivery is intentionally capped at 500 recipients per send (and rate-limited per team). For larger audiences, don't loop this — use user-interview-topics-generate-links (or the links CSV export) to get one public link per interviewee and mail-merge them through your own email tooling instead.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Email interview invites to every targeted interviewee",
- "title": "Email interview invites to every targeted interviewee",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interviews-list": {
- "description": "List completed user interview responses in the current project, newest first. Each row includes the interviewee email(s) and identifier, the linked `topic` UUID (set when the interview came in via a topic's shared link), and the AI-generated `transcript` and `summary` fields. Pass `topic` with a topic UUID to scope to a single research topic — use this to answer questions like \"do I have any responses on my X topic yet?\". Use `limit`/`offset` for pagination. `transcript` and `summary` can be long; when listing, prefer skimming the response shapes and then call `user-interviews-retrieve` for the full text of a specific interview. Pass `classifications` (comma-separated; any of `abandoned`, `off-topic`) to return only responses carrying any of those classifications — e.g. `classifications=abandoned` to find drop-offs.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "List user interview responses",
- "title": "List user interview responses",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interviews-partial-update": {
- "description": "Replace the searchable `classifications` on a single interview response. The valid classifications are `abandoned` and `off-topic`. `abandoned` is auto-derived from the transcript when the response is recorded; use this to correct it or to apply `off-topic`, which is never auto-set. Sending `classifications` replaces the entire list — pass the full desired set, not a delta, so include the auto-derived `abandoned` if you want to keep it. Filter by these later via the `classifications` parameter on `user-interviews-list` and `user-interviews-search`.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Set classifications on an interview response",
- "title": "Set classifications on an interview response",
- "required_scopes": ["user_interview:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "feature_flag": "user-interviews"
- },
- "user-interviews-retrieve": {
- "description": "Fetch a single completed user interview response by id, including the full AI-generated `transcript` and `summary`. Use after `user-interviews-list` has narrowed down to a specific interview — for example, to read what a particular interviewee said about a research topic.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Retrieve a user interview response",
- "title": "Retrieve a user interview response",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
- "user-interviews-search": {
- "description": "Search recorded user interviews by meaning, not keywords. Embeds the natural-language `query` with the same model used to index transcripts and summaries, then returns the top matches by cosine similarity. Each match is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and summary score above other interviews. Use `document_types` to restrict to just `transcript` or just `summary`. Filter by `topic_id` to scope the search to a single interview topic. `limit` caps the number of returned matches (1-50, default 10). Filter by `classifications` (any of `abandoned`, `off-topic`) to restrict the search to responses carrying those; combines with `topic_id` as AND. Useful for surfacing relevant excerpts when the caller has a research question rather than a known string to grep for.",
- "category": "User interview topics",
- "feature": "user_interviews",
- "summary": "Semantic search across interview responses",
- "title": "Semantic search across interview responses",
- "required_scopes": ["user_interview:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- },
- "feature_flag": "user-interviews"
- },
"user-settings-update": {
"description": "Update the authenticated user's profile and settings using PATCH semantics — only the fields included in the request body are changed. Pass `@me` as the UUID; non-staff callers may only update their own account. Use `user-get` first to inspect current settings. `notification_settings` merges key-by-key; changing `email` triggers a verification flow; changing `password` also requires `current_password`. Always confirm changes with the user before applying.",
"category": "Core",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 50b5dd930157..8d4871007ae7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18594,33 +18594,6 @@ export namespace Schemas {
errors: BulkDeleteErrorItem[];
}
- export interface BulkIntervieweeContextItem {
- /**
- * Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids.
- * @maxLength 400
- */
- interviewee_identifier: string;
- /**
- * Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'.
- * @maxLength 10000
- */
- agent_context: string;
- }
-
- export interface BulkIntervieweeContextRequest {
- /** List of interviewee context rows to create. Each item has an `interviewee_identifier` and an `agent_context`. At most 500 items per request. */
- items: BulkIntervieweeContextItem[];
- }
-
- export interface BulkIntervieweeContextResponse {
- /** Number of rows inserted by this request. */
- inserted_count: number;
- /** Number of items skipped because a row for that (topic, interviewee_identifier) already existed. */
- skipped_count: number;
- /** Identifiers from the request whose rows were skipped because a row for that (topic, interviewee_identifier) already existed. */
- skipped_identifiers: string[];
- }
-
export interface BulkKeysRequest {
/** Feature flag IDs to look up keys for. Strings of digits are also accepted; any other value is reported in the response `warning` field and otherwise ignored. */
ids?: unknown[];
@@ -25238,10 +25211,10 @@ export namespace Schemas {
* * `BAA` - BAA
* * `DPA` - DPA
*/
- export type CreateLegalDocumentDocumentTypeEnum = typeof CreateLegalDocumentDocumentTypeEnum[keyof typeof CreateLegalDocumentDocumentTypeEnum];
+ export type DocumentTypeEnum = typeof DocumentTypeEnum[keyof typeof DocumentTypeEnum];
- export const CreateLegalDocumentDocumentTypeEnum = {
+ export const DocumentTypeEnum = {
Baa: 'BAA',
Dpa: 'DPA',
} as const;
@@ -25256,7 +25229,7 @@ export namespace Schemas {
*
* * `BAA` - BAA
* * `DPA` - DPA */
- document_type: CreateLegalDocumentDocumentTypeEnum;
+ document_type: DocumentTypeEnum;
/**
* The customer legal entity entering the agreement (PandaDoc's Client.Company).
* @maxLength 255
@@ -57342,60 +57315,6 @@ export namespace Schemas {
Number60: 60,
} as const;
- export interface InterviewInviteResult {
- /** The original identifier (email or distinct ID) from the topic targeting. */
- interviewee_identifier: string;
- /**
- * Email used for delivery. Null when the identifier was not an email (e.g., a distinct ID).
- * @nullable
- */
- email?: string | null;
- /** The personalized public interview URL embedded in the email body. */
- interview_url: string;
- /** True if an email was queued for delivery. False when the recipient was skipped — see `reason`. */
- sent: boolean;
- /** Why the email was skipped (e.g., `not_an_email`, `duplicate_recipient`, `already_sent`). Empty when sent=true. */
- reason?: string;
- }
-
- export interface InterviewLink {
- /**
- * The original identifier (email or distinct ID) from the topic targeting.
- * @maxLength 400
- */
- interviewee_identifier: string;
- /** Best-effort display name derived from the identifier, used to greet the interviewee. */
- user_name: string;
- /** Public, unauthenticated URL the interviewee opens to start the call. Backed by a SharingConfiguration access token. */
- interview_url: string;
- /** The merged topic + per-interviewee context the voice agent will see during the call. */
- agent_context: string;
- }
-
- export interface IntervieweeContext {
- readonly id: string;
- readonly created_by: UserBasic;
- readonly created_at: string;
- /**
- * Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids.
- * @maxLength 400
- */
- interviewee_identifier: string;
- /**
- * Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'.
- * @maxLength 10000
- */
- agent_context: string;
- }
-
- export interface IntervieweeIdentifierRequest {
- /**
- * Email address or PostHog distinct ID for the interviewee. Email-shaped values (including the `Display Name <email@host>` form) are routed to `interviewee_emails`; everything else lands in `interviewee_distinct_ids`.
- * @maxLength 400
- */
- identifier: string;
- }
-
/**
* How one mailbox provider treated this project's email, from AWS SES's own delivery data.
*/
@@ -58740,15 +58659,6 @@ export namespace Schemas {
Never: 'never',
} as const;
- export interface LatestTestInterview {
- /** When the test interview was completed. */
- completed_at: string;
- /** Full transcript of the test call, if Vapi delivered one. May be empty. */
- transcript: string;
- /** AI-generated summary of the test call, if Vapi delivered one. May be empty. */
- summary: string;
- }
-
/**
* * `preserve` - preserve
* * `two_column` - two_column
@@ -67501,33 +67411,6 @@ export namespace Schemas {
results: IntegrationConfig[];
}
- export interface PaginatedInterviewInviteResultList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: InterviewInviteResult[];
- }
-
- export interface PaginatedInterviewLinkList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: InterviewLink[];
- }
-
- export interface PaginatedIntervieweeContextList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: IntervieweeContext[];
- }
-
export interface PaginatedKnowledgeGapSuggestionList {
count: number;
/** @nullable */
@@ -72781,84 +72664,6 @@ export namespace Schemas {
results: UserGitHubIntegrationListResponse[];
}
- /**
- * * `abandoned` - Abandoned
- * * `off-topic` - Off-topic
- */
- export type UserInterviewClassificationEnum = typeof UserInterviewClassificationEnum[keyof typeof UserInterviewClassificationEnum];
-
-
- export const UserInterviewClassificationEnum = {
- Abandoned: 'abandoned',
- OffTopic: 'off-topic',
- } as const;
-
- export interface UserInterview {
- readonly id: string;
- readonly created_by: UserBasic;
- readonly created_at: string;
- /** @items.maxLength 254 */
- interviewee_emails?: string[];
- readonly interviewee_identifier: string;
- /** @nullable */
- readonly topic: string | null;
- readonly transcript: string;
- summary?: string;
- /** Searchable classifications on the response. `abandoned` is auto-derived from the transcript when the interview is recorded; `off-topic` is set manually. Sending `classifications` on an update replaces the whole list — pass the full desired set, not a delta. */
- classifications?: UserInterviewClassificationEnum[];
- audio: string;
- }
-
- export interface PaginatedUserInterviewList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: UserInterview[];
- }
-
- export interface UserInterviewTopic {
- readonly id: string;
- readonly created_by: UserBasic;
- readonly created_at: string;
- /**
- * Email addresses of people to interview. May be combined with interviewee_distinct_ids.
- * @items.maxLength 254
- */
- interviewee_emails?: string[];
- /**
- * PostHog distinct IDs of people to interview. May be combined with interviewee_emails.
- * @items.maxLength 400
- */
- interviewee_distinct_ids?: string[];
- /** The product, feature, or idea you want to ask interviewees about. */
- topic: string;
- /** Optional additional system prompt for the voice agent — extra background, tone, or constraints. */
- agent_context?: string;
- /** Ordered list of questions the voice agent should work through during the interview. */
- questions?: string[];
- /**
- * Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.
- * @maxLength 255
- */
- invite_subject?: string;
- /**
- * Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.
- * @maxLength 1000
- */
- invite_message?: string;
- }
-
- export interface PaginatedUserInterviewTopicList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: UserInterviewTopic[];
- }
-
/**
* * `disabled` - disabled
* * `toolbar` - toolbar
@@ -77935,22 +77740,6 @@ export namespace Schemas {
readonly installation_status?: InstallationStatusEnum | null;
}
- export interface PatchedIntervieweeContext {
- readonly id?: string;
- readonly created_by?: UserBasic;
- readonly created_at?: string;
- /**
- * Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids.
- * @maxLength 400
- */
- interviewee_identifier?: string;
- /**
- * Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'.
- * @maxLength 10000
- */
- agent_context?: string;
- }
-
export interface PatchedJsSnippetVersion {
/**
* Version pin: null for latest, "1.358.0" for exact, "1" for major, "1.358" for minor
@@ -82706,54 +82495,6 @@ export namespace Schemas {
custom_facets?: UserFacetSettingsEntry[];
}
- export interface PatchedUserInterview {
- readonly id?: string;
- readonly created_by?: UserBasic;
- readonly created_at?: string;
- /** @items.maxLength 254 */
- interviewee_emails?: string[];
- readonly interviewee_identifier?: string;
- /** @nullable */
- readonly topic?: string | null;
- readonly transcript?: string;
- summary?: string;
- /** Searchable classifications on the response. `abandoned` is auto-derived from the transcript when the interview is recorded; `off-topic` is set manually. Sending `classifications` on an update replaces the whole list — pass the full desired set, not a delta. */
- classifications?: UserInterviewClassificationEnum[];
- audio?: string;
- }
-
- export interface PatchedUserInterviewTopic {
- readonly id?: string;
- readonly created_by?: UserBasic;
- readonly created_at?: string;
- /**
- * Email addresses of people to interview. May be combined with interviewee_distinct_ids.
- * @items.maxLength 254
- */
- interviewee_emails?: string[];
- /**
- * PostHog distinct IDs of people to interview. May be combined with interviewee_emails.
- * @items.maxLength 400
- */
- interviewee_distinct_ids?: string[];
- /** The product, feature, or idea you want to ask interviewees about. */
- topic?: string;
- /** Optional additional system prompt for the voice agent — extra background, tone, or constraints. */
- agent_context?: string;
- /** Ordered list of questions the voice agent should work through during the interview. */
- questions?: string[];
- /**
- * Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.
- * @maxLength 255
- */
- invite_subject?: string;
- /**
- * Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.
- * @maxLength 1000
- */
- invite_message?: string;
- }
-
export interface PatchedUserProductList {
readonly id?: string;
readonly product_path?: string;
@@ -83891,36 +83632,6 @@ export namespace Schemas {
preferences_url: string;
}
- export interface PreviewInviteRequest {
- /**
- * Which targeted interviewee to render the preview for (an email or PostHog distinct ID already on the topic). Leave blank to preview for the first targeted interviewee.
- * @maxLength 400
- */
- interviewee_identifier?: string;
- }
-
- export interface PreviewInviteResult {
- /** The identifier (email or distinct ID) the preview was rendered for. */
- interviewee_identifier: string;
- /** The display name used in the email greeting, derived from the identifier. */
- user_name: string;
- /**
- * The email address the invite would be sent to. Null for distinct-ID-only interviewees.
- * @nullable
- */
- email: string | null;
- /** The rendered subject line (saved topic subject, sanitized, or the default). */
- subject: string;
- /** The fully rendered, CSS-inlined HTML body of the invite email. Safe to display in a sandboxed iframe. */
- html: string;
- /** An illustrative placeholder interview link shown in the previewed email body. The preview never exposes a real per-recipient share token — that link is minted only when invites are sent. */
- interview_url: string;
- /** True if this interviewee has an email address and could actually receive the invite. */
- emailable: boolean;
- /** Always true — the previewed interview_url is an illustrative placeholder, never a live link. */
- is_preview_link: boolean;
- }
-
export interface PreviewPathCleaningSuggestionResponse {
/** Up to 20 before/after pairs for sampled paths the suggested rules would rewrite. */
examples: PathCleaningPreviewExample[];
@@ -94995,18 +94706,6 @@ export namespace Schemas {
channel_id: string;
}
- export interface SendInvitesRequest {
- /**
- * Override the email subject line for this send. Plain text only — URLs, angle brackets, and control characters are rejected. Falls back to the topic's saved subject, then a default.
- * @maxLength 200
- */
- subject?: string;
- /** Email address replies should go to. Defaults to the topic creator's email if blank. */
- reply_to?: string;
- /** If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately. */
- send_async?: boolean;
- }
-
/**
* * `positive` - positive
* * `negative` - negative
@@ -95197,11 +94896,6 @@ export namespace Schemas {
readonly is_active: boolean;
}
- export interface SharedInterviewLink {
- /** Public, unauthenticated URL any respondent can open to start a new interview for this topic. Backed by a topic-level SharingConfiguration access token — not tied to any specific interviewee. Each visit is a new anonymous respondent who self-identifies with a name; `distinct_id` and `session_id` query params on the URL are captured as best-effort person/session linkage. */
- interview_url: string;
- }
-
/**
* Mixin for serializers to add user access control fields
*/
@@ -105532,13 +105226,6 @@ export namespace Schemas {
message?: string;
}
- export interface TestInterviewLink {
- /** Public, unauthenticated URL the topic author opens to dogfood the voice interview themselves — does not count against the targeted interviewees. */
- interview_url: string;
- /** Most recent test interview completed by the topic author, or null if none yet. */
- latest_test_interview: LatestTestInterview | null;
- }
-
export interface TextReprMetadata {
event_type?: string;
event_id?: string;
@@ -106316,70 +106003,6 @@ export namespace Schemas {
github_login: string | null;
}
- /**
- * * `transcript` - transcript
- * * `summary` - summary
- */
- export type UserInterviewSearchDocumentTypeEnum = typeof UserInterviewSearchDocumentTypeEnum[keyof typeof UserInterviewSearchDocumentTypeEnum];
-
-
- export const UserInterviewSearchDocumentTypeEnum = {
- Transcript: 'transcript',
- Summary: 'summary',
- } as const;
-
- export interface UserInterviewSearchRequest {
- /**
- * Natural-language query to match semantically against interview transcripts and summaries.
- * @maxLength 2000
- */
- query: string;
- /**
- * Which document types to search across. Omit to default to both `transcript` and `summary`. Pass a non-empty subset to restrict the search.
- * @minItems 1
- */
- document_types?: UserInterviewSearchDocumentTypeEnum[];
- /**
- * Optional. Restrict results to interviews belonging to a specific UserInterviewTopic.
- * @nullable
- */
- topic_id?: string | null;
- /**
- * Optional. Restrict results to interviews carrying any of these classifications (OR). Combines with `topic_id` as AND.
- * @minItems 1
- */
- classifications?: UserInterviewClassificationEnum[];
- /**
- * Maximum number of matches to return (1-50). Defaults to 10. Two matches per interview are possible — one for the transcript, one for the summary.
- * @minimum 1
- * @maximum 50
- */
- limit?: number;
- }
-
- export interface UserInterviewSearchResult {
- /** ID of the matched UserInterview. */
- interview_id: string;
- /** Which document type matched — `transcript` is the raw conversation, `summary` is the AI-generated abstract.
- *
- * * `transcript` - transcript
- * * `summary` - summary */
- document_type: UserInterviewSearchDocumentTypeEnum;
- /** Cosine similarity in [0, 1]; higher is closer to the query. Computed as `1 - cosineDistance`. */
- similarity: number;
- /** Excerpt of the matched document (first 500 characters). */
- content_snippet: string;
- /** Email or PostHog distinct ID of the interviewee. */
- interviewee_identifier: string;
- /**
- * ID of the UserInterviewTopic the interview was conducted for, or null if detached.
- * @nullable
- */
- topic_id: string | null;
- /** When the interview row was created. */
- created_at: string;
- }
-
/**
* * `ios` - iOS
* * `android` - Android
@@ -124002,48 +123625,6 @@ export namespace Schemas {
export type UploadedMediaCreate201 = { [key: string]: unknown };
- export type UserInterviewTopicsListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- /**
- * A search term.
- */
- search?: string;
- };
-
- export type UserInterviewTopicsIntervieweesListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- };
-
- export type UserInterviewsListParams = {
- /**
- * Comma-separated classifications; returns responses carrying any of them (OR). Valid values: abandoned, off-topic.
- */
- classifications?: string;
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- topic?: string;
- };
-
export type UserProductListListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/user_interviews/api.ts b/services/mcp/src/generated/user_interviews/api.ts
deleted file mode 100644
index 685e4aa4605f..000000000000
--- a/services/mcp/src/generated/user_interviews/api.ts
+++ /dev/null
@@ -1,510 +0,0 @@
-/**
- * Auto-generated from the Django backend OpenAPI schema.
- * MCP service uses these Zod schemas for generated tool handlers.
- * To regenerate: hogli build:openapi
- *
- * PostHog API - MCP 19 enabled ops
- * OpenAPI spec version: 1.0.0
- */
-import * as zod from 'zod'
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const UserInterviewTopicsListParams = () => zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const UserInterviewTopicsListQueryParams = () => zod.object({
- limit: zod.number().optional().describe('Number of results to return per page.'),
- offset: zod.number().optional().describe('The initial index from which to return the results.'),
- search: zod.string().optional().describe('A search term.'),
-})
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const UserInterviewTopicsCreateParams = () => zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const userInterviewTopicsCreateBodyIntervieweeEmailsItemMax = 254
-
-export const userInterviewTopicsCreateBodyIntervieweeDistinctIdsItemMax = 400
-
-export const userInterviewTopicsCreateBodyInviteSubjectMax = 255
-
-export const userInterviewTopicsCreateBodyInviteMessageMax = 1000
-
-export const UserInterviewTopicsCreateBody = () => zod.object({
- interviewee_emails: zod
- .array(zod.string().max(userInterviewTopicsCreateBodyIntervieweeEmailsItemMax))
- .optional()
- .describe('Email addresses of people to interview. May be combined with interviewee_distinct_ids.'),
- interviewee_distinct_ids: zod
- .array(zod.string().max(userInterviewTopicsCreateBodyIntervieweeDistinctIdsItemMax))
- .optional()
- .describe('PostHog distinct IDs of people to interview. May be combined with interviewee_emails.'),
- topic: zod.string().describe('The product, feature, or idea you want to ask interviewees about.'),
- agent_context: zod
- .string()
- .optional()
- .describe('Optional additional system prompt for the voice agent — extra background, tone, or constraints.'),
- questions: zod
- .array(zod.string())
- .optional()
- .describe('Ordered list of questions the voice agent should work through during the interview.'),
- invite_subject: zod
- .string()
- .max(userInterviewTopicsCreateBodyInviteSubjectMax)
- .optional()
- .describe(
- 'Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.'
- ),
- invite_message: zod
- .string()
- .max(userInterviewTopicsCreateBodyInviteMessageMax)
- .optional()
- .describe(
- 'Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.'
- ),
-})
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const UserInterviewTopicsRetrieveParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this user interview topic.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-/**
- * Planned user interview topics: who we want to target and what we want to ask about.
- */
-export const UserInterviewTopicsPartialUpdateParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this user interview topic.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const userInterviewTopicsPartialUpdateBodyIntervieweeEmailsItemMax = 254
-
-export const userInterviewTopicsPartialUpdateBodyIntervieweeDistinctIdsItemMax = 400
-
-export const userInterviewTopicsPartialUpdateBodyInviteSubjectMax = 255
-
-export const userInterviewTopicsPartialUpdateBodyInviteMessageMax = 1000
-
-export const UserInterviewTopicsPartialUpdateBody = () => zod.object({
- interviewee_emails: zod
- .array(zod.string().max(userInterviewTopicsPartialUpdateBodyIntervieweeEmailsItemMax))
- .optional()
- .describe('Email addresses of people to interview. May be combined with interviewee_distinct_ids.'),
- interviewee_distinct_ids: zod
- .array(zod.string().max(userInterviewTopicsPartialUpdateBodyIntervieweeDistinctIdsItemMax))
- .optional()
- .describe('PostHog distinct IDs of people to interview. May be combined with interviewee_emails.'),
- topic: zod.string().optional().describe('The product, feature, or idea you want to ask interviewees about.'),
- agent_context: zod
- .string()
- .optional()
- .describe('Optional additional system prompt for the voice agent — extra background, tone, or constraints.'),
- questions: zod
- .array(zod.string())
- .optional()
- .describe('Ordered list of questions the voice agent should work through during the interview.'),
- invite_subject: zod
- .string()
- .max(userInterviewTopicsPartialUpdateBodyInviteSubjectMax)
- .optional()
- .describe(
- 'Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.'
- ),
- invite_message: zod
- .string()
- .max(userInterviewTopicsPartialUpdateBodyInviteMessageMax)
- .optional()
- .describe(
- 'Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.'
- ),
-})
-
-/**
- * Add a single interviewee to this topic. Email-shaped identifiers (including the `Display Name <email@host>` form) are appended to `interviewee_emails`; everything else is appended to `interviewee_distinct_ids`. Idempotent — adding an identifier that's already present leaves the topic unchanged. Returns the updated topic.
- */
-export const UserInterviewTopicsAddIntervieweeCreateParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this user interview topic.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const userInterviewTopicsAddIntervieweeCreateBodyIdentifierMax = 400
-
-export const UserInterviewTopicsAddIntervieweeCreateBody = () => zod.object({
- identifier: zod
- .string()
- .max(userInterviewTopicsAddIntervieweeCreateBodyIdentifierMax)
- .describe(
- 'Email address or PostHog distinct ID for the interviewee. Email-shaped values (including the `Display Name <email@host>` form) are routed to `interviewee_emails`; everything else lands in `interviewee_distinct_ids`.'
- ),
-})
-
-/**
- * Generate one public interview link per targeted interviewee. Materializes an IntervieweeContext row for every identifier on the topic (without overwriting existing per-person context), and an enabled SharingConfiguration with a unique access token. The URL resolves to the public interview viewer with no PostHog auth required.
- */
-export const UserInterviewTopicsGenerateLinksCreateParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this user interview topic.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-/**
- * Same materialization as generate_links, returned as a downloadable CSV. Intended for users who want to mail-merge the per-person interview links into their own email tooling.
- */
-export const UserInterviewTopicsLinksCsvCreateParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this user interview topic.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-/**
- * Render the invite email exactly as a specific targeted interviewee would receive it — personalized subject and body — without sending anything and without creating or reading any share links. Pass `interviewee_identifier` to preview for a particular person, or omit it to preview for the first targeted interviewee. The body always shows an illustrative placeholder link (`is_preview_link: true`), never a live interview URL.
- */
-export const UserInterviewTopicsPreviewInviteCreateParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this user interview topic.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const userInterviewTopicsPreviewInviteCreateBodyIntervieweeIdentifierMax = 400
-
-export const UserInterviewTopicsPreviewInviteCreateBody = () => zod.object({
- interviewee_identifier: zod
- .string()
- .max(userInterviewTopicsPreviewInviteCreateBodyIntervieweeIdentifierMax)
- .optional()
- .describe(
- 'Which targeted interviewee to render the preview for (an email or PostHog distinct ID already on the topic). Leave blank to preview for the first targeted interviewee.'
- ),
-})
-
-/**
- * Remove an interviewee from this topic. Drops the identifier from both `interviewee_emails` and `interviewee_distinct_ids`, and disables any active SharingConfiguration linked to an IntervieweeContext for that identifier on this topic so the removed person can no longer open their interview link. Idempotent — removing an identifier that isn't present is a no-op. Returns the updated topic.
- */
-export const UserInterviewTopicsRemoveIntervieweeCreateParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this user interview topic.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const userInterviewTopicsRemoveIntervieweeCreateBodyIdentifierMax = 400
-
-export const UserInterviewTopicsRemoveIntervieweeCreateBody = () => zod.object({
- identifier: zod
- .string()
- .max(userInterviewTopicsRemoveIntervieweeCreateBodyIdentifierMax)
- .describe(
- 'Email address or PostHog distinct ID for the interviewee. Email-shaped values (including the `Display Name <email@host>` form) are routed to `interviewee_emails`; everything else lands in `interviewee_distinct_ids`.'
- ),
-})
-
-/**
- * Generate (if needed) and email a personalized public interview link to every targeted interviewee on this topic whose identifier is an email address. Distinct-ID-only interviewees are skipped and surfaced in the response. Each invite is keyed on the underlying SharingConfiguration so re-runs after token rotation produce a fresh send.
- */
-export const UserInterviewTopicsSendInvitesCreateParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this user interview topic.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const userInterviewTopicsSendInvitesCreateBodySubjectMax = 200
-
-export const userInterviewTopicsSendInvitesCreateBodySendAsyncDefault = true
-
-export const UserInterviewTopicsSendInvitesCreateBody = () => zod.object({
- subject: zod
- .string()
- .max(userInterviewTopicsSendInvitesCreateBodySubjectMax)
- .optional()
- .describe(
- "Override the email subject line for this send. Plain text only — URLs, angle brackets, and control characters are rejected. Falls back to the topic's saved subject, then a default."
- ),
- reply_to: zod
- .email()
- .optional()
- .describe("Email address replies should go to. Defaults to the topic creator's email if blank."),
- send_async: zod
- .boolean()
- .default(userInterviewTopicsSendInvitesCreateBodySendAsyncDefault)
- .describe(
- 'If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately.'
- ),
-})
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const UserInterviewTopicsIntervieweesListParams = () => zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
- topic_id: zod.string(),
-})
-
-export const UserInterviewTopicsIntervieweesListQueryParams = () => zod.object({
- limit: zod.number().optional().describe('Number of results to return per page.'),
- offset: zod.number().optional().describe('The initial index from which to return the results.'),
-})
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const UserInterviewTopicsIntervieweesCreateParams = () => zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
- topic_id: zod.string(),
-})
-
-export const userInterviewTopicsIntervieweesCreateBodyIntervieweeIdentifierMax = 400
-
-export const userInterviewTopicsIntervieweesCreateBodyAgentContextMax = 10000
-
-export const UserInterviewTopicsIntervieweesCreateBody = () => zod.object({
- interviewee_identifier: zod
- .string()
- .max(userInterviewTopicsIntervieweesCreateBodyIntervieweeIdentifierMax)
- .describe(
- "Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids."
- ),
- agent_context: zod
- .string()
- .max(userInterviewTopicsIntervieweesCreateBodyAgentContextMax)
- .describe(
- "Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'."
- ),
-})
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const UserInterviewTopicsIntervieweesPartialUpdateParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this interviewee context.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
- topic_id: zod.string(),
-})
-
-export const userInterviewTopicsIntervieweesPartialUpdateBodyIntervieweeIdentifierMax = 400
-
-export const userInterviewTopicsIntervieweesPartialUpdateBodyAgentContextMax = 10000
-
-export const UserInterviewTopicsIntervieweesPartialUpdateBody = () => zod.object({
- interviewee_identifier: zod
- .string()
- .max(userInterviewTopicsIntervieweesPartialUpdateBodyIntervieweeIdentifierMax)
- .optional()
- .describe(
- "Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids."
- ),
- agent_context: zod
- .string()
- .max(userInterviewTopicsIntervieweesPartialUpdateBodyAgentContextMax)
- .optional()
- .describe(
- "Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'."
- ),
-})
-
-/**
- * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).
- */
-export const UserInterviewTopicsIntervieweesDestroyParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this interviewee context.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
- topic_id: zod.string(),
-})
-
-/**
- * Create up to 500 interviewee context rows for a topic in a single request. Rows whose (topic, interviewee_identifier) already exists are skipped — the response surfaces an `inserted_count`, a `skipped_count`, and the `skipped_identifiers` so the caller can reconcile. Items must have unique `interviewee_identifier` values within the batch.
- */
-export const UserInterviewTopicsIntervieweesBulkCreateParams = () => zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
- topic_id: zod.string(),
-})
-
-export const userInterviewTopicsIntervieweesBulkCreateBodyItemsItemIntervieweeIdentifierMax = 400
-
-export const userInterviewTopicsIntervieweesBulkCreateBodyItemsItemAgentContextMax = 10000
-
-export const UserInterviewTopicsIntervieweesBulkCreateBody = () => zod.object({
- items: zod
- .array(
- zod.object({
- interviewee_identifier: zod
- .string()
- .max(userInterviewTopicsIntervieweesBulkCreateBodyItemsItemIntervieweeIdentifierMax)
- .describe(
- "Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids."
- ),
- agent_context: zod
- .string()
- .max(userInterviewTopicsIntervieweesBulkCreateBodyItemsItemAgentContextMax)
- .describe(
- "Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'."
- ),
- })
- )
- .describe(
- 'List of interviewee context rows to create. Each item has an `interviewee_identifier` and an `agent_context`. At most 500 items per request.'
- ),
-})
-
-export const UserInterviewsListParams = () => zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const UserInterviewsListQueryParams = () => zod.object({
- classifications: zod
- .string()
- .optional()
- .describe(
- 'Comma-separated classifications; returns responses carrying any of them (OR). Valid values: abandoned, off-topic.'
- ),
- limit: zod.number().optional().describe('Number of results to return per page.'),
- offset: zod.number().optional().describe('The initial index from which to return the results.'),
- topic: zod.string().optional(),
-})
-
-export const UserInterviewsRetrieveParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this user interview.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const UserInterviewsPartialUpdateParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this user interview.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const userInterviewsPartialUpdateBodyIntervieweeEmailsItemMax = 254
-
-export const UserInterviewsPartialUpdateBody = () => zod.object({
- interviewee_emails: zod.array(zod.string().max(userInterviewsPartialUpdateBodyIntervieweeEmailsItemMax)).optional(),
- summary: zod.string().optional(),
- classifications: zod
- .array(zod.enum(['abandoned', 'off-topic']).describe('\* `abandoned` - Abandoned\n\* `off-topic` - Off-topic'))
- .optional()
- .describe(
- 'Searchable classifications on the response. `abandoned` is auto-derived from the transcript when the interview is recorded; `off-topic` is set manually. Sending `classifications` on an update replaces the whole list — pass the full desired set, not a delta.'
- ),
- audio: zod.url().optional(),
-})
-
-/**
- * Embed `query` with the same model used to index interview transcripts and summaries, then return the top matches by cosine distance. Each match is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and summary score above other interviews. Useful for surfacing relevant interview snippets in natural language, without exact keyword matches.
- * @summary Search interview responses by semantic similarity
- */
-export const UserInterviewsSearchCreateParams = () => zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const userInterviewsSearchCreateBodyQueryMax = 2000
-
-export const userInterviewsSearchCreateBodyLimitMax = 50
-
-export const UserInterviewsSearchCreateBody = () => zod.object({
- query: zod
- .string()
- .max(userInterviewsSearchCreateBodyQueryMax)
- .describe('Natural-language query to match semantically against interview transcripts and summaries.'),
- document_types: zod
- .array(zod.enum(['transcript', 'summary']).describe('\* `transcript` - transcript\n\* `summary` - summary'))
- .min(1)
- .optional()
- .describe(
- 'Which document types to search across. Omit to default to both `transcript` and `summary`. Pass a non-empty subset to restrict the search.'
- ),
- topic_id: zod
- .string()
- .nullish()
- .describe('Optional. Restrict results to interviews belonging to a specific UserInterviewTopic.'),
- classifications: zod
- .array(zod.enum(['abandoned', 'off-topic']).describe('\* `abandoned` - Abandoned\n\* `off-topic` - Off-topic'))
- .min(1)
- .optional()
- .describe(
- 'Optional. Restrict results to interviews carrying any of these classifications (OR). Combines with `topic_id` as AND.'
- ),
- limit: zod
- .number()
- .min(1)
- .max(userInterviewsSearchCreateBodyLimitMax)
- .optional()
- .describe(
- 'Maximum number of matches to return (1-50). Defaults to 10. Two matches per interview are possible — one for the transcript, one for the summary.'
- ),
-})
diff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.ts
index d9b3282ea0c6..74bfd9d1873c 100644
--- a/services/mcp/src/resources/ui-apps.generated.ts
+++ b/services/mcp/src/resources/ui-apps.generated.ts
@@ -17,7 +17,6 @@ export const FEATURE_FLAG_LIST_RESOURCE_URI = 'ui://posthog/feature-flag-list.ht
export const FEATURE_FLAG_TESTING_RESOURCE_URI = 'ui://posthog/feature-flag-testing.html'
export const INLINE_SCAN_RESOURCE_URI = 'ui://posthog/inline-scan.html'
export const INSIGHT_ACTORS_RESOURCE_URI = 'ui://posthog/insight-actors.html'
-export const INVITE_EMAIL_PREVIEW_RESOURCE_URI = 'ui://posthog/invite-email-preview.html'
export const LLM_COSTS_RESOURCE_URI = 'ui://posthog/llm-costs.html'
export const LOOPS_REVIEW_RESOURCE_URI = 'ui://posthog/loops-review.html'
export const QUERY_RESULTS_RESOURCE_URI = 'ui://posthog/query-results.html'
@@ -52,7 +51,6 @@ export type UiAppKey =
| 'feature-flag-testing'
| 'inline-scan'
| 'insight-actors'
- | 'invite-email-preview'
| 'llm-costs'
| 'loops-review'
| 'query-results'
@@ -87,7 +85,6 @@ export const URI_MAP: Record<UiAppKey, string> = {
'feature-flag-testing': FEATURE_FLAG_TESTING_RESOURCE_URI,
'inline-scan': INLINE_SCAN_RESOURCE_URI,
'insight-actors': INSIGHT_ACTORS_RESOURCE_URI,
- 'invite-email-preview': INVITE_EMAIL_PREVIEW_RESOURCE_URI,
'llm-costs': LLM_COSTS_RESOURCE_URI,
'loops-review': LOOPS_REVIEW_RESOURCE_URI,
'query-results': QUERY_RESULTS_RESOURCE_URI,
@@ -126,7 +123,6 @@ export const DISPATCHABLE_APP_KEYS: UiAppKey[] = [
'feature-flag-testing',
'inline-scan',
'insight-actors',
- 'invite-email-preview',
'llm-costs',
'query-results',
'session-recording',
@@ -250,12 +246,6 @@ export const UI_APPS: Array<{
description: 'Insight Actors detail view',
appDir: 'generated/insight-actors',
},
- {
- name: 'PostHog Invite Email Preview',
- uri: INVITE_EMAIL_PREVIEW_RESOURCE_URI,
- description: 'Invite Email Preview detail view',
- appDir: 'generated/invite-email-preview',
- },
{
name: 'PostHog Llm Costs',
uri: LLM_COSTS_RESOURCE_URI,
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index 28f2c9b21113..c60149579581 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -63,7 +63,6 @@ import { GENERATED_TOOLS as surveys } from './surveys'
import { GENERATED_TOOLS as tasks } from './tasks'
import { GENERATED_TOOLS as today } from './today'
import { GENERATED_TOOLS as tracing } from './tracing'
-import { GENERATED_TOOLS as user_interviews } from './user_interviews'
import { GENERATED_TOOLS as visual_review } from './visual_review'
import { GENERATED_TOOLS as warehouse_sources } from './warehouse_sources'
import { GENERATED_TOOLS as web_analytics } from './web_analytics'
@@ -132,7 +131,6 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =
...tasks,
...today,
...tracing,
- ...user_interviews,
...visual_review,
...warehouse_sources,
...web_analytics,
diff --git a/services/mcp/src/tools/generated/user_interviews.ts b/services/mcp/src/tools/generated/user_interviews.ts
deleted file mode 100644
index 5b711c784699..000000000000
--- a/services/mcp/src/tools/generated/user_interviews.ts
+++ /dev/null
@@ -1,609 +0,0 @@
-// AUTO-GENERATED from products/user_interviews/mcp/tools.yaml + OpenAPI — do not edit
-import { z } from 'zod'
-
-import type { Schemas } from '@/api/generated'
-import * as orvalSchemas from '@/generated/user_interviews/api'
-import { withUiApp } from '@/resources/ui-apps'
-import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
-import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
-
-const UserInterviewTopicsAddIntervieweeSchema = () => {
- const UserInterviewTopicsAddIntervieweeCreateBody = orvalSchemas.UserInterviewTopicsAddIntervieweeCreateBody()
- const UserInterviewTopicsAddIntervieweeCreateParams = orvalSchemas.UserInterviewTopicsAddIntervieweeCreateParams()
- return UserInterviewTopicsAddIntervieweeCreateParams.omit({ project_id: true }).extend(
- UserInterviewTopicsAddIntervieweeCreateBody.shape
- )
-}
-
-const userInterviewTopicsAddInterviewee = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsAddIntervieweeSchema>,
- Schemas.UserInterviewTopic
-> => ({
- name: 'user-interview-topics-add-interviewee',
- schema: UserInterviewTopicsAddIntervieweeSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewTopicsAddIntervieweeSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.identifier !== undefined) {
- body['identifier'] = params.identifier
- }
- const result = await context.api.request<Schemas.UserInterviewTopic>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/add_interviewee/`,
- body,
- })
- return result
- },
-})
-
-const UserInterviewTopicsCreateSchema = () => {
- const UserInterviewTopicsCreateBody = orvalSchemas.UserInterviewTopicsCreateBody()
- return UserInterviewTopicsCreateBody
-}
-
-const userInterviewTopicsCreate = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsCreateSchema>,
- Schemas.UserInterviewTopic
-> => ({
- name: 'user-interview-topics-create',
- schema: UserInterviewTopicsCreateSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewTopicsCreateSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.interviewee_emails !== undefined) {
- body['interviewee_emails'] = params.interviewee_emails
- }
- if (params.interviewee_distinct_ids !== undefined) {
- body['interviewee_distinct_ids'] = params.interviewee_distinct_ids
- }
- if (params.topic !== undefined) {
- body['topic'] = params.topic
- }
- if (params.agent_context !== undefined) {
- body['agent_context'] = params.agent_context
- }
- if (params.questions !== undefined) {
- body['questions'] = params.questions
- }
- if (params.invite_subject !== undefined) {
- body['invite_subject'] = params.invite_subject
- }
- if (params.invite_message !== undefined) {
- body['invite_message'] = params.invite_message
- }
- const result = await context.api.request<Schemas.UserInterviewTopic>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/`,
- body,
- })
- return result
- },
-})
-
-const UserInterviewTopicsGenerateLinksSchema = () => {
- const UserInterviewTopicsGenerateLinksCreateParams = orvalSchemas.UserInterviewTopicsGenerateLinksCreateParams()
- return UserInterviewTopicsGenerateLinksCreateParams.omit({ project_id: true })
-}
-
-const userInterviewTopicsGenerateLinks = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsGenerateLinksSchema>,
- Schemas.PaginatedInterviewLinkList
-> => ({
- name: 'user-interview-topics-generate-links',
- schema: UserInterviewTopicsGenerateLinksSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewTopicsGenerateLinksSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedInterviewLinkList>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/generate_links/`,
- })
- return result
- },
-})
-
-const UserInterviewTopicsIntervieweesBulkCreateSchema = () => {
- const UserInterviewTopicsIntervieweesBulkCreateBody = orvalSchemas.UserInterviewTopicsIntervieweesBulkCreateBody()
- const UserInterviewTopicsIntervieweesBulkCreateParams =
- orvalSchemas.UserInterviewTopicsIntervieweesBulkCreateParams()
- return UserInterviewTopicsIntervieweesBulkCreateParams.omit({ project_id: true }).extend(
- UserInterviewTopicsIntervieweesBulkCreateBody.shape
- )
-}
-
-const userInterviewTopicsIntervieweesBulkCreate = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsIntervieweesBulkCreateSchema>,
- Schemas.BulkIntervieweeContextResponse
-> => ({
- name: 'user-interview-topics-interviewees-bulk-create',
- schema: UserInterviewTopicsIntervieweesBulkCreateSchema(),
- handler: async (
- context: Context,
- params: z.infer<ReturnType<typeof UserInterviewTopicsIntervieweesBulkCreateSchema>>
- ) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.items !== undefined) {
- body['items'] = params.items
- }
- const result = await context.api.request<Schemas.BulkIntervieweeContextResponse>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.topic_id))}/interviewees/bulk/`,
- body,
- })
- return result
- },
-})
-
-const UserInterviewTopicsIntervieweesCreateSchema = () => {
- const UserInterviewTopicsIntervieweesCreateBody = orvalSchemas.UserInterviewTopicsIntervieweesCreateBody()
- const UserInterviewTopicsIntervieweesCreateParams = orvalSchemas.UserInterviewTopicsIntervieweesCreateParams()
- return UserInterviewTopicsIntervieweesCreateParams.omit({ project_id: true }).extend(
- UserInterviewTopicsIntervieweesCreateBody.shape
- )
-}
-
-const userInterviewTopicsIntervieweesCreate = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsIntervieweesCreateSchema>,
- Schemas.IntervieweeContext
-> => ({
- name: 'user-interview-topics-interviewees-create',
- schema: UserInterviewTopicsIntervieweesCreateSchema(),
- handler: async (
- context: Context,
- params: z.infer<ReturnType<typeof UserInterviewTopicsIntervieweesCreateSchema>>
- ) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.interviewee_identifier !== undefined) {
- body['interviewee_identifier'] = params.interviewee_identifier
- }
- if (params.agent_context !== undefined) {
- body['agent_context'] = params.agent_context
- }
- const result = await context.api.request<Schemas.IntervieweeContext>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.topic_id))}/interviewees/`,
- body,
- })
- return result
- },
-})
-
-const UserInterviewTopicsIntervieweesDestroySchema = () => {
- const UserInterviewTopicsIntervieweesDestroyParams = orvalSchemas.UserInterviewTopicsIntervieweesDestroyParams()
- return UserInterviewTopicsIntervieweesDestroyParams.omit({ project_id: true })
-}
-
-const userInterviewTopicsIntervieweesDestroy = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsIntervieweesDestroySchema>,
- unknown
-> => ({
- name: 'user-interview-topics-interviewees-destroy',
- schema: UserInterviewTopicsIntervieweesDestroySchema(),
- handler: async (
- context: Context,
- params: z.infer<ReturnType<typeof UserInterviewTopicsIntervieweesDestroySchema>>
- ) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<unknown>({
- method: 'DELETE',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.topic_id))}/interviewees/${encodeURIComponent(String(params.id))}/`,
- })
- return result
- },
-})
-
-const UserInterviewTopicsIntervieweesListSchema = () => {
- const UserInterviewTopicsIntervieweesListParams = orvalSchemas.UserInterviewTopicsIntervieweesListParams()
- const UserInterviewTopicsIntervieweesListQueryParams = orvalSchemas.UserInterviewTopicsIntervieweesListQueryParams()
- return UserInterviewTopicsIntervieweesListParams.omit({ project_id: true }).extend(
- UserInterviewTopicsIntervieweesListQueryParams.shape
- )
-}
-
-const userInterviewTopicsIntervieweesList = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsIntervieweesListSchema>,
- WithPostHogUrl<Schemas.PaginatedIntervieweeContextList>
-> => ({
- name: 'user-interview-topics-interviewees-list',
- schema: UserInterviewTopicsIntervieweesListSchema(),
- handler: async (
- context: Context,
- params: z.infer<ReturnType<typeof UserInterviewTopicsIntervieweesListSchema>>
- ) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedIntervieweeContextList>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.topic_id))}/interviewees/`,
- query: {
- limit: params.limit,
- offset: params.offset,
- },
- })
- return await withPostHogUrl(context, result, '/user_interviews')
- },
-})
-
-const UserInterviewTopicsIntervieweesPartialUpdateSchema = () => {
- const UserInterviewTopicsIntervieweesPartialUpdateBody =
- orvalSchemas.UserInterviewTopicsIntervieweesPartialUpdateBody()
- const UserInterviewTopicsIntervieweesPartialUpdateParams =
- orvalSchemas.UserInterviewTopicsIntervieweesPartialUpdateParams()
- return UserInterviewTopicsIntervieweesPartialUpdateParams.omit({ project_id: true }).extend(
- UserInterviewTopicsIntervieweesPartialUpdateBody.omit({ interviewee_identifier: true }).shape
- )
-}
-
-const userInterviewTopicsIntervieweesPartialUpdate = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsIntervieweesPartialUpdateSchema>,
- Schemas.IntervieweeContext
-> => ({
- name: 'user-interview-topics-interviewees-partial-update',
- schema: UserInterviewTopicsIntervieweesPartialUpdateSchema(),
- handler: async (
- context: Context,
- params: z.infer<ReturnType<typeof UserInterviewTopicsIntervieweesPartialUpdateSchema>>
- ) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.agent_context !== undefined) {
- body['agent_context'] = params.agent_context
- }
- const result = await context.api.request<Schemas.IntervieweeContext>({
- method: 'PATCH',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.topic_id))}/interviewees/${encodeURIComponent(String(params.id))}/`,
- body,
- })
- return result
- },
-})
-
-const UserInterviewTopicsLinksCsvSchema = () => {
- const UserInterviewTopicsLinksCsvCreateParams = orvalSchemas.UserInterviewTopicsLinksCsvCreateParams()
- return UserInterviewTopicsLinksCsvCreateParams.omit({ project_id: true })
-}
-
-const userInterviewTopicsLinksCsv = (): ToolBase<ReturnType<typeof UserInterviewTopicsLinksCsvSchema>, unknown> => ({
- name: 'user-interview-topics-links-csv',
- schema: UserInterviewTopicsLinksCsvSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewTopicsLinksCsvSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<unknown>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/links_csv/`,
- })
- return result
- },
-})
-
-const UserInterviewTopicsListSchema = () => {
- const UserInterviewTopicsListQueryParams = orvalSchemas.UserInterviewTopicsListQueryParams()
- return UserInterviewTopicsListQueryParams
-}
-
-const userInterviewTopicsList = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsListSchema>,
- WithPostHogUrl<Schemas.PaginatedUserInterviewTopicList>
-> => ({
- name: 'user-interview-topics-list',
- schema: UserInterviewTopicsListSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewTopicsListSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedUserInterviewTopicList>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/`,
- query: {
- limit: params.limit,
- offset: params.offset,
- search: params.search,
- },
- })
- return await withPostHogUrl(context, result, '/user_interviews')
- },
-})
-
-const UserInterviewTopicsPartialUpdateSchema = () => {
- const UserInterviewTopicsPartialUpdateBody = orvalSchemas.UserInterviewTopicsPartialUpdateBody()
- const UserInterviewTopicsPartialUpdateParams = orvalSchemas.UserInterviewTopicsPartialUpdateParams()
- return UserInterviewTopicsPartialUpdateParams.omit({ project_id: true }).extend(
- UserInterviewTopicsPartialUpdateBody.shape
- )
-}
-
-const userInterviewTopicsPartialUpdate = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsPartialUpdateSchema>,
- Schemas.UserInterviewTopic
-> => ({
- name: 'user-interview-topics-partial-update',
- schema: UserInterviewTopicsPartialUpdateSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewTopicsPartialUpdateSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.interviewee_emails !== undefined) {
- body['interviewee_emails'] = params.interviewee_emails
- }
- if (params.interviewee_distinct_ids !== undefined) {
- body['interviewee_distinct_ids'] = params.interviewee_distinct_ids
- }
- if (params.topic !== undefined) {
- body['topic'] = params.topic
- }
- if (params.agent_context !== undefined) {
- body['agent_context'] = params.agent_context
- }
- if (params.questions !== undefined) {
- body['questions'] = params.questions
- }
- if (params.invite_subject !== undefined) {
- body['invite_subject'] = params.invite_subject
- }
- if (params.invite_message !== undefined) {
- body['invite_message'] = params.invite_message
- }
- const result = await context.api.request<Schemas.UserInterviewTopic>({
- method: 'PATCH',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/`,
- body,
- })
- return result
- },
-})
-
-const UserInterviewTopicsPreviewInviteSchema = () => {
- const UserInterviewTopicsPreviewInviteCreateBody = orvalSchemas.UserInterviewTopicsPreviewInviteCreateBody()
- const UserInterviewTopicsPreviewInviteCreateParams = orvalSchemas.UserInterviewTopicsPreviewInviteCreateParams()
- return UserInterviewTopicsPreviewInviteCreateParams.omit({ project_id: true }).extend(
- UserInterviewTopicsPreviewInviteCreateBody.shape
- )
-}
-
-const userInterviewTopicsPreviewInvite = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsPreviewInviteSchema>,
- Schemas.PreviewInviteResult
-> =>
- withUiApp('invite-email-preview', {
- name: 'user-interview-topics-preview-invite',
- schema: UserInterviewTopicsPreviewInviteSchema(),
- handler: async (
- context: Context,
- params: z.infer<ReturnType<typeof UserInterviewTopicsPreviewInviteSchema>>
- ) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.interviewee_identifier !== undefined) {
- body['interviewee_identifier'] = params.interviewee_identifier
- }
- const result = await context.api.request<Schemas.PreviewInviteResult>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/preview_invite/`,
- body,
- })
- return result
- },
- })
-
-const UserInterviewTopicsRemoveIntervieweeSchema = () => {
- const UserInterviewTopicsRemoveIntervieweeCreateBody = orvalSchemas.UserInterviewTopicsRemoveIntervieweeCreateBody()
- const UserInterviewTopicsRemoveIntervieweeCreateParams =
- orvalSchemas.UserInterviewTopicsRemoveIntervieweeCreateParams()
- return UserInterviewTopicsRemoveIntervieweeCreateParams.omit({ project_id: true }).extend(
- UserInterviewTopicsRemoveIntervieweeCreateBody.shape
- )
-}
-
-const userInterviewTopicsRemoveInterviewee = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsRemoveIntervieweeSchema>,
- Schemas.UserInterviewTopic
-> => ({
- name: 'user-interview-topics-remove-interviewee',
- schema: UserInterviewTopicsRemoveIntervieweeSchema(),
- handler: async (
- context: Context,
- params: z.infer<ReturnType<typeof UserInterviewTopicsRemoveIntervieweeSchema>>
- ) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.identifier !== undefined) {
- body['identifier'] = params.identifier
- }
- const result = await context.api.request<Schemas.UserInterviewTopic>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/remove_interviewee/`,
- body,
- })
- return result
- },
-})
-
-const UserInterviewTopicsRetrieveSchema = () => {
- const UserInterviewTopicsRetrieveParams = orvalSchemas.UserInterviewTopicsRetrieveParams()
- return UserInterviewTopicsRetrieveParams.omit({ project_id: true })
-}
-
-const userInterviewTopicsRetrieve = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsRetrieveSchema>,
- Schemas.UserInterviewTopic
-> => ({
- name: 'user-interview-topics-retrieve',
- schema: UserInterviewTopicsRetrieveSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewTopicsRetrieveSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.UserInterviewTopic>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/`,
- })
- return result
- },
-})
-
-const UserInterviewTopicsSendInvitesSchema = () => {
- const UserInterviewTopicsSendInvitesCreateBody = orvalSchemas.UserInterviewTopicsSendInvitesCreateBody()
- const UserInterviewTopicsSendInvitesCreateParams = orvalSchemas.UserInterviewTopicsSendInvitesCreateParams()
- return UserInterviewTopicsSendInvitesCreateParams.omit({ project_id: true }).extend(
- UserInterviewTopicsSendInvitesCreateBody.shape
- )
-}
-
-const userInterviewTopicsSendInvites = (): ToolBase<
- ReturnType<typeof UserInterviewTopicsSendInvitesSchema>,
- Schemas.PaginatedInterviewInviteResultList
-> => ({
- name: 'user-interview-topics-send-invites',
- schema: UserInterviewTopicsSendInvitesSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewTopicsSendInvitesSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.subject !== undefined) {
- body['subject'] = params.subject
- }
- if (params.reply_to !== undefined) {
- body['reply_to'] = params.reply_to
- }
- if (params.send_async !== undefined) {
- body['send_async'] = params.send_async
- }
- const result = await context.api.request<Schemas.PaginatedInterviewInviteResultList>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/send_invites/`,
- body,
- })
- return result
- },
-})
-
-const UserInterviewsListSchema = () => {
- const UserInterviewsListQueryParams = orvalSchemas.UserInterviewsListQueryParams()
- return UserInterviewsListQueryParams
-}
-
-const userInterviewsList = (): ToolBase<
- ReturnType<typeof UserInterviewsListSchema>,
- WithPostHogUrl<Schemas.PaginatedUserInterviewList>
-> => ({
- name: 'user-interviews-list',
- schema: UserInterviewsListSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewsListSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedUserInterviewList>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interviews/`,
- query: {
- classifications: params.classifications,
- limit: params.limit,
- offset: params.offset,
- topic: params.topic,
- },
- })
- return await withPostHogUrl(context, result, '/user_interviews')
- },
-})
-
-const UserInterviewsPartialUpdateSchema = () => {
- const UserInterviewsPartialUpdateBody = orvalSchemas.UserInterviewsPartialUpdateBody()
- const UserInterviewsPartialUpdateParams = orvalSchemas.UserInterviewsPartialUpdateParams()
- return UserInterviewsPartialUpdateParams.omit({ project_id: true }).extend(
- UserInterviewsPartialUpdateBody.omit({ interviewee_emails: true, summary: true, audio: true }).shape
- )
-}
-
-const userInterviewsPartialUpdate = (): ToolBase<
- ReturnType<typeof UserInterviewsPartialUpdateSchema>,
- Schemas.UserInterview
-> => ({
- name: 'user-interviews-partial-update',
- schema: UserInterviewsPartialUpdateSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewsPartialUpdateSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.classifications !== undefined) {
- body['classifications'] = params.classifications
- }
- const result = await context.api.request<Schemas.UserInterview>({
- method: 'PATCH',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interviews/${encodeURIComponent(String(params.id))}/`,
- body,
- })
- return result
- },
-})
-
-const UserInterviewsRetrieveSchema = () => {
- const UserInterviewsRetrieveParams = orvalSchemas.UserInterviewsRetrieveParams()
- return UserInterviewsRetrieveParams.omit({ project_id: true })
-}
-
-const userInterviewsRetrieve = (): ToolBase<
- ReturnType<typeof UserInterviewsRetrieveSchema>,
- Schemas.UserInterview
-> => ({
- name: 'user-interviews-retrieve',
- schema: UserInterviewsRetrieveSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewsRetrieveSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.UserInterview>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interviews/${encodeURIComponent(String(params.id))}/`,
- })
- return result
- },
-})
-
-const UserInterviewsSearchSchema = () => {
- const UserInterviewsSearchCreateBody = orvalSchemas.UserInterviewsSearchCreateBody()
- return UserInterviewsSearchCreateBody
-}
-
-const userInterviewsSearch = (): ToolBase<
- ReturnType<typeof UserInterviewsSearchSchema>,
- Schemas.UserInterviewSearchResult[]
-> => ({
- name: 'user-interviews-search',
- schema: UserInterviewsSearchSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UserInterviewsSearchSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.query !== undefined) {
- body['query'] = params.query
- }
- if (params.document_types !== undefined) {
- body['document_types'] = params.document_types
- }
- if (params.topic_id !== undefined) {
- body['topic_id'] = params.topic_id
- }
- if (params.classifications !== undefined) {
- body['classifications'] = params.classifications
- }
- if (params.limit !== undefined) {
- body['limit'] = params.limit
- }
- const result = await context.api.request<Schemas.UserInterviewSearchResult[]>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interviews/search/`,
- body,
- })
- return result
- },
-})
-
-export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
- 'user-interview-topics-add-interviewee': userInterviewTopicsAddInterviewee,
- 'user-interview-topics-create': userInterviewTopicsCreate,
- 'user-interview-topics-generate-links': userInterviewTopicsGenerateLinks,
- 'user-interview-topics-interviewees-bulk-create': userInterviewTopicsIntervieweesBulkCreate,
- 'user-interview-topics-interviewees-create': userInterviewTopicsIntervieweesCreate,
- 'user-interview-topics-interviewees-destroy': userInterviewTopicsIntervieweesDestroy,
- 'user-interview-topics-interviewees-list': userInterviewTopicsIntervieweesList,
- 'user-interview-topics-interviewees-partial-update': userInterviewTopicsIntervieweesPartialUpdate,
- 'user-interview-topics-links-csv': userInterviewTopicsLinksCsv,
- 'user-interview-topics-list': userInterviewTopicsList,
- 'user-interview-topics-partial-update': userInterviewTopicsPartialUpdate,
- 'user-interview-topics-preview-invite': userInterviewTopicsPreviewInvite,
- 'user-interview-topics-remove-interviewee': userInterviewTopicsRemoveInterviewee,
- 'user-interview-topics-retrieve': userInterviewTopicsRetrieve,
- 'user-interview-topics-send-invites': userInterviewTopicsSendInvites,
- 'user-interviews-list': userInterviewsList,
- 'user-interviews-partial-update': userInterviewsPartialUpdate,
- 'user-interviews-retrieve': userInterviewsRetrieve,
- 'user-interviews-search': userInterviewsSearch,
-}
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index 88e1000313bb..6ac2e6114911 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -1769,21 +1769,6 @@
"params": [],
"scope": "project"
},
- "userInterview": {
- "template": "/user_research/{id}",
- "params": ["id"],
- "scope": "project"
- },
- "userInterviewResponse": {
- "template": "/user_research/{topicId}/response/{responseId}",
- "params": ["topicId", "responseId"],
- "scope": "project"
- },
- "userInterviews": {
- "template": "/user_research",
- "params": [],
- "scope": "project"
- },
"variable": {
"template": "/data-management/variables/{id}",
"params": ["id"],
diff --git a/services/mcp/src/ui-apps/apps/generated/invite-email-preview.tsx b/services/mcp/src/ui-apps/apps/generated/invite-email-preview.tsx
deleted file mode 100644
index a3584bd8298c..000000000000
--- a/services/mcp/src/ui-apps/apps/generated/invite-email-preview.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-// AUTO-GENERATED by generate-ui-apps.ts — do not edit
-import '../../styles/tailwind.css'
-
-import { createRoot } from 'react-dom/client'
-
-import { type InviteEmailPreviewData, InviteEmailPreviewView } from 'products/user_interviews/mcp/apps'
-
-import { AppWrapper } from '../../components/AppWrapper'
-
-function InviteEmailPreviewApp(): JSX.Element {
- return (
- <AppWrapper<InviteEmailPreviewData> appName="PostHog Invite Email Preview">
- {({ data }) => <InviteEmailPreviewView data={data!} />}
- </AppWrapper>
- )
-}
-
-const container = document.getElementById('root')
-if (container) {
- createRoot(container).render(<InviteEmailPreviewApp />)
-}
diff --git a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
index 8f52b3e8bb1f..f15a975581b5 100644
--- a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
+++ b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
@@ -47,7 +47,6 @@ import {
type SurveyStatsData,
} from 'products/surveys/mcp/apps'
import { TraceSpanListView, TraceSpanView, type TraceSpanData, type TraceSpanListData } from 'products/tracing/mcp/apps'
-import { InviteEmailPreviewView, type InviteEmailPreviewData } from 'products/user_interviews/mcp/apps'
import {
EmailTemplateView,
WorkflowListView,
@@ -433,7 +432,6 @@ export const RENDER_DISPATCH: Partial<Record<UiAppKey, (props: RenderDispatchPro
'insight-actors': ({ data, openLink }) => (
<InsightActorsView data={data as InsightActorsData} openLink={openLink} />
),
- 'invite-email-preview': ({ data }) => <InviteEmailPreviewView data={data as InviteEmailPreviewData} />,
'llm-costs': ({ data }) => <LLMCostsView data={data as LLMCostsData} />,
'query-results': ({ data }) => <Component data={data} />,
'session-recording': ({ data }) => <SessionRecordingView recording={data as SessionRecordingData} />,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index f842f6c1bd12..9b80b23645cd 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/scout-trials\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/views\n/views/new\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/scout-trials\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/verify_email\n/views\n/views/new\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 07cb9d7e7ec1..78d35ee6b7fd 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -1039,7 +1039,6 @@ describe('Tool Filtering - Feature Flags', () => {
'llm-analytics-datasets',
'tracing',
'visual-review',
- 'user-interviews',
'customer-analytics-csp',
'customer-analytics-feature-requests',
'customer-analytics-customer-tasks',
@@ -1077,7 +1076,7 @@ describe('Tool Filtering - Feature Flags', () => {
'today-rail-nav',
])
)
- expect(flags).toHaveLength(39)
+ expect(flags).toHaveLength(38)
})
it('every loops tool is gated on the loops flag', () => {
diff --git a/tach.toml b/tach.toml
index 17e32aee185d..74cc95e14567 100644
--- a/tach.toml
+++ b/tach.toml
@@ -73,7 +73,6 @@ depends_on = [
"products.surveys",
"products.tasks",
"products.business_knowledge",
- "products.user_interviews",
"products.warehouse_sources",
"products.exports",
"products.workflows",
@@ -142,7 +141,6 @@ depends_on = [
"products.tasks",
"products.today",
"products.tracing",
- "products.user_interviews",
"products.visual_review",
"products.mcp_analytics",
"products.mcp_registry",
@@ -1066,12 +1064,10 @@ depends_on = [
layer = "modules"
[[modules]]
+# Retired product. The app keeps its models and migration history so that Django keeps
+# cascading deletes into its tables until a later migration drops them.
path = "products.user_interviews"
-depends_on = [
- "ee",
- "posthog",
- "products.ai_observability", "products.access_control",
-]
+depends_on = ["posthog"]
layer = "modules"
[[modules]]
@@ -1137,7 +1133,7 @@ expose = [
"backend\\.routes.*",
]
from = [
- "products\\.(autoresearch|batch_exports|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|managed_warehouse|mcp_analytics|mcp_store|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|user_interviews|visual_review|warehouse_sources|workflows)",
+ "products\\.(autoresearch|batch_exports|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|managed_warehouse|mcp_analytics|mcp_store|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|visual_review|warehouse_sources|workflows)",
]
# TODO: Experiments-specific temporary interface
@@ -1187,16 +1183,6 @@ from = [
"products.experiments",
]
-# user_interviews exposes Vapi webhook handlers that are routed directly from posthog/urls.py.
-
-[[interfaces]]
-expose = [
- "backend\\.presentation\\.webhooks.*",
-]
-from = [
- "products.user_interviews",
-]
-
# streamlit_apps exposes the HogQL bridge view, routed directly from posthog/urls.py.
[[interfaces]]