: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
chore(frontend): add code-inspector-plugin for click-to-source in dev (#115215)
Adam Leith54d286494b16
diff --git a/.env.local.example b/.env.local.exampleindex 24fe906a0a2d..3050c9ef93a4 100644--- a/.env.local.example+++ b/.env.local.example@@ -34,6 +34,12 @@# start to apply.# POSTHOG_DEV_SANDBOX=0+# Click-to-source: hold Option+Shift (Alt+Shift) and click an element to open it in+# your editor. Off by default, because its local server on port 5678 has no auth.+# See "Opening a component's source from the browser" in developing-locally.md.+# DEV_CODE_INSPECTOR=1+# CODE_EDITOR=cursor+# Use your own API keys instead of 1Password# OPENAI_API_KEY=sk-...diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.mdindex b8d4068fbc7c..62f554be9a28 100644--- a/docs/published/handbook/engineering/developing-locally.md+++ b/docs/published/handbook/engineering/developing-locally.md@@ -411,6 +411,16 @@ The PostHog repository includes [VS Code launch options for debugging](https://g> **Note:** You can debug all services using the main "PostHog" launch option. If you are running most services with `hogli start` and only want to debug one (e.g. the backend), use `hogli dev:setup` to exclude that service so it doesn't conflict with the VS Code debugger.+## Extra: Opening a component's source from the browser++You can hold `Option+Shift` (macOS) or `Alt+Shift` (Windows and Linux) and click an element in the app. Your editor then opens the file and line that renders it. [code-inspector-plugin](https://github.com/zh-lx/code-inspector) adds this feature. It runs only with the Vite dev server, so production builds do not include it.++The feature is off by default. To turn it on, add `DEV_CODE_INSPECTOR=1` to your `.env.local` and restart `hogli start`. The Vite dev server and Django both read this value.++The click sends a request to a local server on port 5678. This server has no authentication and accepts requests from all interfaces and all origins. While it runs, another page in your browser or another device on your network can make your editor open a file in the repo. Turn the feature off when you do not use it, and do not turn it on for a devbox.++The plugin finds your editor from the running processes. If the wrong editor opens, set `CODE_EDITOR` in `.env.local`, for example `CODE_EDITOR=cursor`. If another process uses port 5678, the plugin moves to the next free port and the click does nothing.+## Extra: Debugging the backend in PyCharmWith PyCharm's built in support for Django, it's fairly easy to setup debugging in the backend. This is especially useful when you want to trace and debug a network request made from the client all the way back to the server. You can set breakpoints and step through code to see exactly what the backend is doing with your request.diff --git a/frontend/package.json b/frontend/package.jsonindex 97eb6679c3c5..cc0e20c95b96 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -342,6 +342,7 @@"@types/zxcvbn": "^4.4.0","ajv": "^8.20.0","caniuse-lite": "^1.0.30001689",+ "code-inspector-plugin": "2.0.9","concurrently": "catalog:","esbuild-visualizer": "^0.6.0","fake-indexeddb": "^6.0.1",diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex bdceba8560e1..17cc859caa92 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -15,9 +15,22 @@ import { zodJitlessPlugin } from './plugins/vite-zod-jitless-plugin'// https://vitejs.dev/config/export default defineConfig(({ mode }) => {const isDev = mode === 'development'+ // Opt-in because the plugin's server listens on all interfaces with no auth. Set DEV_CODE_INSPECTOR=1 in .env.local.+ const codeInspectorEnabled = ['1', 'true'].includes(process.env.DEV_CODE_INSPECTOR?.toLowerCase() ?? '')return {plugins: [+ // Dev server only: hold Option+Shift (Alt+Shift) and click an element to open its source in your editor.+ // The plugin must come before react(). CSPMiddleware admits port 5678 when DEV_CODE_INSPECTOR is set, so keep the two in sync.+ codeInspectorEnabled &&+ import('code-inspector-plugin').then(({ codeInspectorPlugin }) =>+ codeInspectorPlugin({+ bundler: 'vite',+ port: 5678,+ pathType: 'relative',+ injectTo: resolve(__dirname, 'src/index.tsx'),+ })+ ),react(),tailwindcss(),// We delete and copy the HTML files for developmentdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex bf95d04cf8d5..2efffa3067a8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1422,6 +1422,9 @@ importers:caniuse-lite:specifier: ^1.0.30001689version: 1.0.30001690+ code-inspector-plugin:+ specifier: 2.0.9+ version: 2.0.9concurrently:specifier: 'catalog:'version: 5.3.0@@ -7325,6 +7328,7 @@ packages:'@cloudflare/[email protected]':resolution: {integrity: sha512-nTuEiuLv+YoLrGfftdlBJB3nJJELT/9VVuBlF2JDpnv3uAOCXaZcniP+K5C9Mcg0xSopvFLAL45Q7Hco1hHOLQ==}+ deprecated: '@cloudflare/vitest-pool-workers has been renamed to @cloudflare/vitest-plugin. This package will not receive future updates.'peerDependencies:'@vitest/runner': ^4.1.0'@vitest/snapshot': ^4.1.0@@ -7366,6 +7370,35 @@ packages:'@cloudflare/[email protected]':resolution: {integrity: sha512-Yz90KXPZBB9K/AhsnLaA321s5+i5ZpWZRFbcGx9dWjyknQJXPAS1pK5CJSFEedwY6zoEr1cf2SkpBATL1idsWA==}+ '@code-inspector/[email protected]':+ resolution: {integrity: sha512-7WkUlXfpwM95+KY5ra3KyivQGy0fUBq9dFcoI481LJKKnZNzwRW6kUkQF2hVP7zTj8TDy5esCMw8YuOwI8HhsQ==}+ peerDependencies:+ '@anthropic-ai/claude-agent-sdk': ^0.2.29+ '@openai/codex-sdk': ^0.106.0+ '@opencode-ai/sdk': ^1.2.24+ peerDependenciesMeta:+ '@anthropic-ai/claude-agent-sdk':+ optional: true+ '@openai/codex-sdk':+ optional: true+ '@opencode-ai/sdk':+ optional: true++ '@code-inspector/[email protected]':+ resolution: {integrity: sha512-uiddojMyD4HUtJ8pVq4/Iu0AgILaRZoe/zXJUK2ibqWdP6XtjIWCTLfvDL8IO9tOOxuEi+0SsRwr/Y8CEN5sTQ==}++ '@code-inspector/[email protected]':+ resolution: {integrity: sha512-HGb8oHXEj2fGnD5AtdUzFhMXkuRAXenKT1iCV53B8gFgiV5ddSrln+/mPQZt3v3FTu3TyQNd3aaHtPpSW+B0vg==}++ '@code-inspector/[email protected]':+ resolution: {integrity: sha512-uNTPCkDxS+4htXOKTJf+yEjYqKDFLIczILQ41dMqD5z9rbSDJkU/bvMs+8RcGUks0f7cB+TtRQyQCfwoFW1atA==}++ '@code-inspector/[email protected]':+ resolution: {integrity: sha512-XXwb3Cyz70Y8OqP7H7umKVM1RrfmWtKBZ7JrrtlwraEaRRefo70+guuQZr6vuNm8lOT2VHgsG1bH9wqs7WrrXw==}++ '@code-inspector/[email protected]':+ resolution: {integrity: sha512-sauXo+GD6QIlqSymNtDTQOyrQid8er71Kr3Jh07viUKd1+U10//EML/tb/IpOzutwauizJeQslKqAvDV+Nqc9w==}+'@commander-js/[email protected]':resolution: {integrity: sha512-hIn0ncNaJRLkZrxBIp5AsW/eXEHNKYQBh0aPdoUqNgD+Io3NIykQqpKFyKcuasZhicGaEZJX/JBSIkZ4e5x8Dg==}peerDependencies:@@ -15063,6 +15096,10 @@ packages:resolution: {integrity: sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==}engines: {node: '>=8'}+ resolution: {integrity: sha512-diHzdDKxcU+bAsUboHLPEDQiw0qEe0qd7SYUn3HgcFlWgbDcfLGswOHYeGrHKzG9z6UYf01d9VFMfZxPM1xZSg==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}engines: {node: '>=10'}@@ -15207,6 +15244,9 @@ packages:resolution: {integrity: sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==}engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'}+ resolution: {integrity: sha512-0CApBNHqPTrcbOL/1n4JJS0Wy0CGYTRmJVWY8qI0wkYmmeT/LhaQZ1EIGQNuHLepZn4SA/XWd+4No+8gshpRNA==}+resolution: {integrity: sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==}@@ -18587,6 +18627,9 @@ packages:resolution: {integrity: sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==}+ resolution: {integrity: sha512-MqkYz5/dYDtBkvcDmz6tr2uFWU8AqRnrI+kLwcVmV83QZ/uhN0yns9GUQyLZJ5CJ5pglm8xko65JGcyzyI3dBQ==}+resolution: {integrity: sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==}@@ -19645,6 +19688,9 @@ packages:resolution: {integrity: sha512-RM5oyBy45cLEoHqCeh+MNuFAxO0vTFBLskvQbOKnEE7YTTSN4tbN8QWDIPQ6L+WvKsB/qLEGpYe2ZZ9d4W9OIQ==}engines: {node: '>=8'}+ resolution: {integrity: sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg==}+resolution: {integrity: sha512-sfpTbrT35429cs0RE8Yb9avGX9BiRRvpV7aweQsghKTjtrVZP3jBrKOPItWXAqHb8doyh3SkuGuUVBLgig1SRg==}engines: {node: '>=16'}@@ -23317,6 +23363,7 @@ packages:resolution: {integrity: sha512-GQINDTb/ocyz4acQj3GXAe0wipYxws6L+9ouqaq10KlInTk9DGvW9TJd0pYa/Xu3cppNnZuB4T/sBuSXpcN2ng==}+ deprecated: v1 is no longer supported, please upgrade.resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==}@@ -26390,6 +26437,77 @@ snapshots:'@cloudflare/[email protected]': {}+ '@code-inspector/[email protected]':+ dependencies:+ '@vue/compiler-dom': 3.5.32+ chalk: 4.1.2+ launch-ide: 1.4.10+ portfinder: 1.0.38+ ws: 8.20.1+ optionalDependencies:+ node-pty: 1.1.0+ transitivePeerDependencies:+ - bufferutil+ - supports-color+ - utf-8-validate++ '@code-inspector/[email protected]':+ dependencies:+ '@code-inspector/core': 2.0.9+ transitivePeerDependencies:+ - '@anthropic-ai/claude-agent-sdk'+ - '@openai/codex-sdk'+ - '@opencode-ai/sdk'+ - bufferutil+ - supports-color+ - utf-8-validate++ '@code-inspector/[email protected]':+ dependencies:+ '@code-inspector/core': 2.0.9+ transitivePeerDependencies:+ - '@anthropic-ai/claude-agent-sdk'+ - '@openai/codex-sdk'+ - '@opencode-ai/sdk'+ - bufferutil+ - supports-color+ - utf-8-validate++ '@code-inspector/[email protected]':+ dependencies:+ '@code-inspector/core': 2.0.9+ '@code-inspector/webpack': 2.0.9+ transitivePeerDependencies:+ - '@anthropic-ai/claude-agent-sdk'+ - '@openai/codex-sdk'+ - '@opencode-ai/sdk'+ - bufferutil+ - supports-color+ - utf-8-validate++ '@code-inspector/[email protected]':+ dependencies:+ '@code-inspector/core': 2.0.9+ chalk: 4.1.1+ transitivePeerDependencies:+ - '@anthropic-ai/claude-agent-sdk'+ - '@openai/codex-sdk'+ - '@opencode-ai/sdk'+ - bufferutil+ - supports-color+ - utf-8-validate++ '@code-inspector/[email protected]':+ dependencies:+ '@code-inspector/core': 2.0.9+ transitivePeerDependencies:+ - '@anthropic-ai/claude-agent-sdk'+ - '@openai/codex-sdk'+ - '@opencode-ai/sdk'+ - bufferutil+ - supports-color+ - utf-8-validate+'@commander-js/[email protected]([email protected])':dependencies:commander: 14.0.3@@ -35263,6 +35381,11 @@ snapshots:ansi-styles: 4.3.0supports-color: 7.2.0+ dependencies:+ ansi-styles: 4.3.0+ supports-color: 7.2.0+dependencies:ansi-styles: 4.3.0@@ -35407,6 +35530,23 @@ snapshots:+ dependencies:+ '@code-inspector/core': 2.0.9+ '@code-inspector/esbuild': 2.0.9+ '@code-inspector/mako': 2.0.9+ '@code-inspector/turbopack': 2.0.9+ '@code-inspector/vite': 2.0.9+ '@code-inspector/webpack': 2.0.9+ chalk: 4.1.1+ transitivePeerDependencies:+ - '@anthropic-ai/claude-agent-sdk'+ - '@openai/codex-sdk'+ - '@opencode-ai/sdk'+ - bufferutil+ - supports-color+ - utf-8-validate+@@ -40267,6 +40407,11 @@ snapshots:+ dependencies:+ chalk: 4.1.2+ dotenv: 16.6.1+@@ -41619,6 +41764,11 @@ snapshots:dependencies:process-on-spawn: 1.0.0+ dependencies:+ node-addon-api: 7.1.1+ optional: true+dependencies:bindings: 1.5.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 6c3eb563d916..e3e2307ce833 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -150,6 +150,8 @@ allowBuilds:'@datadog/pprof': falseffmpeg-static: falsefree-email-domains: false+ # Optional dependency of code-inspector-plugin, used only by its AI terminal, which we do not enable.+ node-pty: falsepuppeteer: falsecatalog:diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pyindex 43b42c02e3d4..e20eef82e211 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -305,6 +305,10 @@ class CSPMiddleware:resource_url = "https://*.dev.posthog.dev"connect_debug_url = "ws://localhost:8234" if settings.DEBUG or settings.TEST else ""+ if settings.DEBUG and settings.DEV_CODE_INSPECTOR:+ # Port 5678 is the opt-in code-inspector-plugin server in frontend/vite.config.mts. The+ # click-to-source request goes to it, and the policy refuses that request without this source.+ connect_debug_url += " http://localhost:5678"object_storage_source = object_storage_upload_source()# The image exporter renders replay exports in the bare /exporter document, and a frame of# that render calls eval. 'report-sample' puts the first 40 characters of the evaluateddiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 27cf2dec104c..be857bf2232b 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1073,6 +1073,9 @@ ALLOW_DEV_LOGIN = get_from_env("ALLOW_DEV_LOGIN", False, type_cast=str_to_bool)# shows the full value of the seeded dev personal API key in the UI (also requires DEBUG)ALLOW_DEV_API_KEY_REVEAL = get_from_env("ALLOW_DEV_API_KEY_REVEAL", False, type_cast=str_to_bool)+# admits the click-to-source server of frontend/vite.config.mts in the dev CSP (also requires DEBUG)+DEV_CODE_INSPECTOR = get_from_env("DEV_CODE_INSPECTOR", False, type_cast=str_to_bool)+##### Random/temporary# Everything that is supposed to be removed eventuallydiff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.pyindex f682688635d8..f269d7b186de 100644--- a/posthog/test/test_csp_middleware.py+++ b/posthog/test/test_csp_middleware.py@@ -115,6 +115,21 @@ class TestCSPMiddleware(APIBaseTest):).split()assert {"http://localhost:8234", "https://frontend--devbox--jane.coder.example.com"} <= set(script_src)+ @parameterized.expand(+ [+ ("opted_in", True, True),+ ("not_opted_in", False, False),+ ]+ )+ def test_dev_policy_admits_the_code_inspector_only_when_opted_in(self, _name, opted_in, expected):+ # The inspector server answers any origin, so the policy must not reach it unless the engineer asked for it.+ with override_settings(DEBUG=True, DEV_CODE_INSPECTOR=opted_in):+ response = self.client.get("/")+ connect_src = next(+ part for part in response["Content-Security-Policy"].split("; ") if part.startswith("connect-src ")+ ).split()+ assert ("http://localhost:5678" in connect_src) is expected+def test_replay_player_frame_serves_the_mount_node_without_a_session(self):# Shared recordings render the player for logged-out viewers.self.client.logout()diff --git a/turbo.json b/turbo.jsonindex 8c6d6f4d4b2a..8cc340da99ce 100644--- a/turbo.json+++ b/turbo.json@@ -117,7 +117,16 @@"dependsOn": ["^build"],"persistent": true,"cache": false,- "passThroughEnv": ["SKIP_TYPEGEN", "COREPACK_ENABLE_DOWNLOAD_PROMPT", "SSL_CERT_FILE", "JS_URL"]+ // Turbo strips undeclared env vars, so an opt-in set in .env.local never reaches vite.config.mts+ // unless it is listed here. DEV_CODE_INSPECTOR loads the click-to-source plugin, and CODE_EDITOR picks the editor it opens.+ "passThroughEnv": [+ "SKIP_TYPEGEN",+ "COREPACK_ENABLE_DOWNLOAD_PROMPT",+ "SSL_CERT_FILE",+ "JS_URL",+ "DEV_CODE_INSPECTOR",+ "CODE_EDITOR"+ ]},"dev": {"dependsOn": ["^build"],