:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ai): Correct settings links shared by PostHog AI (#74336)
Steven Shultsd943082a1942
diff --git a/ee/hogai/llm.py b/ee/hogai/llm.pyindex 5cfb7baa68dc..3c76ddc0cf2a 100644--- a/ee/hogai/llm.py+++ b/ee/hogai/llm.py@@ -41,7 +41,7 @@ Use Markdown with descriptive anchor text, for example "[Cohorts view](/cohorts)Key URL patterns:- Dashboard: `/dashboard/<id>`, e.g. `/dashboard/12345`- Insights: `/insights/<short_id>`, e.g. `/insights/abc123`-- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`+- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`. Section IDs are a fixed set, so never guess one because it sounds plausible; if you are not certain an ID is real, link `/settings` and name the section in the anchor text. Members and invites are organization-level (`/settings/organization-members`); there is no project members page, and per-project access is `/settings/environment-access-control`.- Data management: `/data-management/events`, `/data-management/properties`- Billing: `/organization/billing`Current time in the project's timezone, {{{project_timezone}}}: {{{project_datetime}}}.diff --git a/ee/hogai/test/test_llm.py b/ee/hogai/test/test_llm.pyindex 72371f43a801..08bee77c2a15 100644--- a/ee/hogai/test/test_llm.py+++ b/ee/hogai/test/test_llm.py@@ -1,16 +1,22 @@+import refrom datetime import datetimefrom functools import cached_property+from pathlib import Pathfrom posthog.test.base import BaseTestfrom unittest.mock import patch+from django.test import SimpleTestCase+import anthropicfrom langchain_anthropic import ChatAnthropicfrom langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessagefrom langchain_core.outputs import ChatGeneration, Generation, LLMResultfrom parameterized import parameterized-from ee.hogai.llm import BILLING_SKIPPED_COUNTER, MaxChatAnthropic, MaxChatOpenAI+from posthog.settings import BASE_DIR++from ee.hogai.llm import BILLING_SKIPPED_COUNTER, PROJECT_ORG_USER_CONTEXT_PROMPT, MaxChatAnthropic, MaxChatOpenAI@patch.dict("os.environ", {"OPENAI_API_KEY": "test-api-key", "ANTHROPIC_API_KEY": "test-api-key"})@@ -541,3 +547,52 @@ class TestMaxChatOpenAI(BaseTest):self.assertIsInstance(ChatAnthropic.__dict__["_async_client"], cached_property)self.assertTrue(callable(ChatAnthropic.__dict__["_client"].func))self.assertTrue(callable(ChatAnthropic.__dict__["_async_client"].func))+++class TestProjectOrgUserContextPrompt(SimpleTestCase):+ """`PROJECT_ORG_USER_CONTEXT_PROMPT` is the only place the assistant learns app URL patterns+ from, and nothing else validates the settings section IDs it names against the real ones. A+ plausible-but-fake ID such as `/settings/project-members` (members live at+ `organization-members`) renders a "Setting not found" page for whoever follows the link."""++ SETTINGS_MAP_PATH = ("frontend", "src", "scenes", "settings", "SettingsMap.tsx")+ SECTION_ID_PATTERN = r"^ id: '([a-z0-9-]+)',$"+ # `canonicalSettingsSection` in settingsSceneLogic.ts rewrites `environment-` to `project-`+ # for every section but these, so these two keep their level prefix in the URL.+ UNRENAMED_SUFFIXES = ("-details", "-danger-zone")++ @cached_property+ def resolvable_section_ids(self) -> set[str]:+ """Section IDs that render a section rather than a not-found page. `settingsLogic`'s+ `sections` selector renames every `environment-` section to `project-`, so the `project-`+ spelling always resolves, while the raw `environment-` spelling only resolves for the+ sections the router rewrites on the way in."""+ settings_map = Path(BASE_DIR, *self.SETTINGS_MAP_PATH)+ declared = re.findall(self.SECTION_ID_PATTERN, settings_map.read_text(), re.MULTILINE)+ if not declared:+ self.fail(f"Could not parse any section IDs out of {settings_map}")+ renamed = {raw.replace("environment-", "project-") for raw in declared}+ rewritten_by_router = {+ raw for raw in declared if raw.startswith("environment-") and not raw.endswith(self.UNRENAMED_SUFFIXES)+ }+ return renamed | rewritten_by_router++ def test_parsed_section_ids_look_sane(self):+ """Guard the guard: if SettingsMap.tsx is reformatted, fail here rather than vacuously passing."""+ self.assertIn("organization-members", self.resolvable_section_ids)+ self.assertIn("environment-replay", self.resolvable_section_ids) # the router rewrites this+ self.assertIn("project-replay", self.resolvable_section_ids) # what `sections` exposes+ self.assertNotIn("project-members", self.resolvable_section_ids)+ # `-details` and `-danger-zone` are not rewritten, so only the `project-` spelling resolves.+ self.assertIn("project-details", self.resolvable_section_ids)+ self.assertNotIn("environment-details", self.resolvable_section_ids)++ def test_settings_urls_in_prompt_resolve_to_real_sections(self):+ referenced = set(re.findall(r"/settings/([a-z0-9-]+)", PROJECT_ORG_USER_CONTEXT_PROMPT))+ self.assertTrue(referenced, "Expected the prompt to give at least one settings URL example")+ self.assertEqual(+ referenced - self.resolvable_section_ids,+ set(),+ "The prompt names settings sections that don't resolve, so the assistant will link users "+ 'to "Setting not found" pages. Valid IDs come from frontend/src/scenes/settings/SettingsMap.tsx.',+ )diff --git a/frontend/src/scenes/settings/settingsSceneLogic.test.ts b/frontend/src/scenes/settings/settingsSceneLogic.test.tsindex 95bad77075d6..2e5f0ab10130 100644--- a/frontend/src/scenes/settings/settingsSceneLogic.test.ts+++ b/frontend/src/scenes/settings/settingsSceneLogic.test.ts@@ -183,6 +183,33 @@ describe('settingsSceneLogic', () => {expect(router.values.hashParams).toHaveProperty('variables')})+ it('redirects the project-members guess to organization members', async () => {+ // Members are organization-level, so `/settings/project-members` is the intuitive wrong+ // guess, and it used to dead-end on "Setting not found".+ router.actions.push('/settings/project-members', {}, { members: true })++ await expectLogic(logic).toMatchValues({+ selectedLevel: 'organization',+ selectedSectionId: 'organization-members',+ })+ expect(router.values.location.pathname).toContain('/settings/organization-members')+ // The redirect keeps hash params, so deep links to a specific setting still scroll to it.+ expect(router.values.hashParams).toHaveProperty('members')+ })++ it('leaves an unmapped section id on the not-found path', async () => {+ // Aliases are added one at a time on purpose. A catch-all redirect for anything unrecognized+ // would shadow the app-level redirects in scenes.ts and would drop the `not_found_shown`+ // report that makes broken settings links visible in the first place.+ router.actions.push('/settings/organization-teapot')++ await expectLogic(logic).toMatchValues({+ selectedSectionId: 'organization-teapot',+ selectedSection: null,+ })+ expect(router.values.location.pathname).toContain('/settings/organization-teapot')+ })+it('does not bounce a level-only URL when already on a section at that level', async () => {router.actions.push('/settings/project-autocapture')await expectLogic(logic).toMatchValues({@@ -200,3 +227,21 @@ describe('settingsSceneLogic', () => {expect(router.values.location.pathname).toMatch(/\/settings\/project$/)})})++describe('settingsSceneLogic on a cold page load', () => {+ // The tests above navigate after mounting, which only covers clicks inside the app. A URL that+ // arrives from outside (pasted, opened in a new tab, followed from an old bookmark) is already+ // set before the logic mounts, and that is the path a broken settings link actually takes.+ it('applies a section alias when the URL is set before the logic mounts', async () => {+ initKeaTests()+ router.actions.push('/settings/project-members')++ const logic = settingsSceneLogic()+ logic.mount()++ await expectLogic(logic).toMatchValues({+ selectedSectionId: 'organization-members',+ })+ expect(router.values.location.pathname).toContain('/settings/organization-members')+ })+})diff --git a/frontend/src/scenes/settings/settingsSceneLogic.ts b/frontend/src/scenes/settings/settingsSceneLogic.tsindex b35f53b19fa6..e847d008e9b6 100644--- a/frontend/src/scenes/settings/settingsSceneLogic.ts+++ b/frontend/src/scenes/settings/settingsSceneLogic.ts@@ -21,12 +21,22 @@ const WEB_ANALYTICS_SETTINGS_SECTION: SettingSectionId = 'project-web-analytics'const WEB_ANALYTICS_AUTHORIZED_URLS_SETTING: SettingId = 'web-analytics-authorized-urls'const LEGACY_TOOLBAR_AUTHORIZED_URLS_SETTING = 'authorized-urls'-const LEGACY_SETTINGS_SECTIONS: Record<string, SettingSectionId> = {+// Section ids that should resolve to a different section than the URL asks for. Two kinds live here:+// sections that were removed or renamed, and ids that were never valid but are the intuitive guess.+// Both would otherwise render "Setting not found". Applied on every `/settings/:section` navigation,+// including a cold page load, so a pasted URL or an old bookmark redirects the same way an in-app+// click does. This is browser routing only; nothing outside the frontend reads this map.+const SETTINGS_SECTION_ALIASES: Record<string, SettingSectionId> = {'environment-llm-analytics': AI_OBSERVABILITY_SETTINGS_SECTION,'project-llm-analytics': AI_OBSERVABILITY_SETTINGS_SECTION,// The dedicated Toolbar section was removed; its authorized-URL config now lives under Web analytics.'environment-toolbar': WEB_ANALYTICS_SETTINGS_SECTION,'project-toolbar': WEB_ANALYTICS_SETTINGS_SECTION,+ // `project-members` is the never-valid kind: members and invites are organization-level, but a+ // project-level id is what people reach for, so it turns up in hand-typed URLs and in links the+ // in-app assistant has suggested. Keep it even once those links age out; it only becomes wrong+ // if members ever become project-scoped.+ 'project-members': 'organization-members',}// Settings that moved to a different section, keyed by setting id. Deep links to the old@@ -55,8 +65,8 @@ const sectionForMovedSetting = (section: string, hashParams: Params): SettingSec}const canonicalSettingsSection = (section: string): string => {- if (LEGACY_SETTINGS_SECTIONS[section]) {- return LEGACY_SETTINGS_SECTIONS[section]+ if (SETTINGS_SECTION_ALIASES[section]) {+ return SETTINGS_SECTION_ALIASES[section]}if (section.startsWith('environment') && !section.endsWith('-details') && !section.endsWith('-danger-zone')) {