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.

fix(hobby): use local sdk assets for self-capture (#104587)

Paul D'Ambra931b76b4de82
diff --git a/frontend/src/lib/utils/getAppContext.ts b/frontend/src/lib/utils/getAppContext.ts
index 41ae67a0b42f..502f010e1bed 100644
--- a/frontend/src/lib/utils/getAppContext.ts
+++ b/frontend/src/lib/utils/getAppContext.ts
@@ -86,3 +86,5 @@ export function getCurrentOrganizationId(): OrganizationType['id'] {
}
export const isUserLoggedIn = (): boolean => !getAppContext()?.anonymous
+
+export const isHobbyDeployment = (): boolean => getAppContext()?.run_mode === 'HOBBY'
diff --git a/frontend/src/loadPostHogJS.test.ts b/frontend/src/loadPostHogJS.test.ts
index 0264e8c6da8a..4fb3dcaa28aa 100644
--- a/frontend/src/loadPostHogJS.test.ts
+++ b/frontend/src/loadPostHogJS.test.ts
@@ -1,6 +1,8 @@
import posthog from 'posthog-js'
import { sampleOnProperty } from 'posthog-js/lib/src/extensions/sampling'
+import { AppContext } from '~/types'
+
import { LastSeenFeatureFlags, isInDeferredInitSample, loadPostHogJS, withLastSeenFeatureFlags } from './loadPostHogJS'
describe('loadPostHogJS', () => {
@@ -77,4 +79,43 @@ describe('loadPostHogJS', () => {
)
})
})
+
+ it.each([
+ ['hobby with self-capture', { run_mode: 'HOBBY' }, true, false],
+ ['hobby with Cloud assets', { run_mode: 'HOBBY' }, false, undefined],
+ ['US cloud', { run_mode: 'US' }, false, undefined],
+ ['EU cloud', { run_mode: 'EU' }, false, undefined],
+ ['cloud development', { run_mode: 'DEV' }, false, undefined],
+ ['local development', { run_mode: 'LOCAL' }, false, undefined],
+ ['E2E', { run_mode: 'E2E' }, false, undefined],
+ ['older app context', {}, false, undefined],
+ ['missing app context', undefined, false, undefined],
+ ] as const)('selects script versioning for %s', (_, context, selfCapture, expected) => {
+ const original = {
+ key: window.JS_POSTHOG_API_KEY,
+ host: window.JS_POSTHOG_HOST,
+ selfCapture: window.JS_POSTHOG_SELF_CAPTURE,
+ context: window.POSTHOG_APP_CONTEXT,
+ }
+ window.JS_POSTHOG_API_KEY = 'phc_example'
+ window.JS_POSTHOG_HOST = window.location.origin
+ window.JS_POSTHOG_SELF_CAPTURE = selfCapture
+ window.POSTHOG_APP_CONTEXT = context as AppContext | undefined
+ jest.mocked(posthog.get_session_id).mockReturnValue('example-session')
+ jest.mocked(posthog.init).mockClear()
+ try {
+ loadPostHogJS()
+ const config = jest.mocked(posthog.init).mock.calls[0][1]
+ if (expected === undefined) {
+ expect(config).not.toHaveProperty('strict_script_versioning')
+ } else {
+ expect(config).toHaveProperty('strict_script_versioning', expected)
+ }
+ } finally {
+ window.JS_POSTHOG_API_KEY = original.key
+ window.JS_POSTHOG_HOST = original.host
+ window.JS_POSTHOG_SELF_CAPTURE = original.selfCapture
+ window.POSTHOG_APP_CONTEXT = original.context
+ }
+ })
})
diff --git a/frontend/src/loadPostHogJS.tsx b/frontend/src/loadPostHogJS.tsx
index c044dc3a2700..84bacf6ae42b 100644
--- a/frontend/src/loadPostHogJS.tsx
+++ b/frontend/src/loadPostHogJS.tsx
@@ -4,7 +4,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { isOAuthMode } from 'lib/oauth/oauthClient'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { isEmbeddedPageFrame } from 'lib/utils/embeddedPageFrame'
-import { getAppContext } from 'lib/utils/getAppContext'
+import { getAppContext, isHobbyDeployment } from 'lib/utils/getAppContext'
import { startDetachedElementTracking } from './detachedElementTracker'
@@ -104,6 +104,10 @@ export function loadPostHogJS(options: LoadPostHogJSOptions = {}): void {
api_host: window.JS_POSTHOG_HOST,
ui_host: window.JS_POSTHOG_UI_HOST,
defaults: SDK_DEFAULTS_DATE,
+ // Hobby static files use /static/<asset>.js, without a version directory.
+ ...(isHobbyDeployment() && window.JS_POSTHOG_SELF_CAPTURE
+ ? { strict_script_versioning: false as const }
+ : {}),
persistence: 'localStorage+cookie',
cookie_persisted_properties: [
'prod_interest', // posthog.com sets these based on what docs were browsed
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 717242eebb39..a4e166564f93 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5226,6 +5226,7 @@ export interface TiledIconModuleProps {
export type EventOrPropType = EventDefinition & PropertyDefinition
export interface AppContext {
+ run_mode?: 'US' | 'EU' | 'DEV' | 'E2E' | 'LOCAL' | 'HOBBY'
current_user: UserType | null
current_project: ProjectType | null
current_team: TeamType | TeamPublicType | null
diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.py
index 10d67bdc13d1..50edf53bc442 100644
--- a/posthog/test/test_get_context_for_template.py
+++ b/posthog/test/test_get_context_for_template.py
@@ -29,7 +29,10 @@ STABLE_CHUNKS = StableChunks(
class TestGetContextForTemplate(APIBaseTest):
def test_get_context_for_template(self):
- with self.settings(STRIPE_PUBLIC_KEY=None, PERSISTED_FEATURE_FLAGS=["the_persisted_flags"]):
+ with (
+ self.settings(STRIPE_PUBLIC_KEY=None, PERSISTED_FEATURE_FLAGS=["the_persisted_flags"]),
+ mock.patch("posthog.settings.CLOUD_DEPLOYMENT", "LOCAL"),
+ ):
actual = get_context_for_template(
"layout",
MagicMock(),
@@ -45,13 +48,35 @@ class TestGetContextForTemplate(APIBaseTest):
"js_posthog_host": "",
"js_url": "http://localhost:8234",
"opt_out_capture": False,
- "posthog_app_context": {"persisted_feature_flags": ["the_persisted_flags"], "anonymous": False},
+ "posthog_app_context": {
+ "persisted_feature_flags": ["the_persisted_flags"],
+ "anonymous": False,
+ "run_mode": "LOCAL",
+ },
"posthog_bootstrap": {},
"posthog_js_uuid_version": "v7",
"region": None,
"self_capture": True,
}
+ @parameterized.expand(
+ [
+ ("hobby", None, False, "HOBBY"),
+ ("local", None, True, "LOCAL"),
+ ("cloud_us", "US", False, "US"),
+ ("cloud_eu", "EU", False, "EU"),
+ ("cloud_dev", "DEV", False, "DEV"),
+ ("e2e", "E2E", False, "E2E"),
+ ]
+ )
+ def test_exposes_run_mode(self, _name, deployment, debug, expected):
+ with (
+ mock.patch("posthog.settings.CLOUD_DEPLOYMENT", deployment),
+ mock.patch("posthog.settings.DEBUG", debug),
+ ):
+ actual = get_context_for_template("layout", MagicMock())
+ assert actual["posthog_app_context"]["run_mode"] == expected
+
def test_picks_up_stripe_public_key_from_environment(self):
with self.settings(STRIPE_PUBLIC_KEY="pk_test_12345"):
actual = get_context_for_template(
diff --git a/posthog/utils.py b/posthog/utils.py
index 29235e167e32..dadccf16c90d 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -58,6 +58,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.git import get_git_branch, get_git_commit_short
from posthog.metrics import KLUDGES_COUNTER
from posthog.redis import get_client
+from posthog.run_mode import run_mode
from posthog.security.url_validation import has_ambiguous_authority
from posthog.stable_chunks import persist_stable_chunks_choice, stable_chunks_for_request
@@ -576,6 +577,7 @@ def _build_template_context(
posthoganalytics.feature_flag_definitions(), settings.PERSISTED_FEATURE_FLAGS
),
"anonymous": not request.user or not request.user.is_authenticated,
+ "run_mode": run_mode().value,
}
posthog_bootstrap: dict[str, Any] = {}