: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
feat(tasks): show cited posthog objects as their real pages in artifacts (#110601)
Shy Alter698bd6583291
diff --git a/frontend/src/layout/navigation-3000/Navigation.tsx b/frontend/src/layout/navigation-3000/Navigation.tsxindex f4b27bd7d5e5..d0754c051b8a 100644--- a/frontend/src/layout/navigation-3000/Navigation.tsx+++ b/frontend/src/layout/navigation-3000/Navigation.tsx@@ -134,7 +134,17 @@ export function Navigation({}>{showMinimalNavigation && <MinimalNavigation />}- <main className={mode === 'zen' ? 'p-4' : undefined}>{children}</main>+ <main+ className={+ mode === 'zen'+ ? 'p-4'+ : mode === 'embedded'+ ? '@container/main-content min-h-screen p-4'+ : undefined+ }+ >+ {children}+ </main></div>)}diff --git a/frontend/src/layout/navigation-3000/navigationLogic.tsx b/frontend/src/layout/navigation-3000/navigationLogic.tsxindex 43ae74565e08..d1a5a3399409 100644--- a/frontend/src/layout/navigation-3000/navigationLogic.tsx+++ b/frontend/src/layout/navigation-3000/navigationLogic.tsx@@ -5,6 +5,7 @@ import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { isEmbeddedPageFrame } from 'lib/utils/embeddedPageFrame'import { onboardingVariantChrome, resolveOnboardingFlowVariant } from 'scenes/onboarding/onboardingVariants'import { organizationLogic } from 'scenes/organizationLogic'import { sceneLogic } from 'scenes/sceneLogic'@@ -13,7 +14,7 @@ import { Scene } from 'scenes/sceneTypes'import type { SceneConfig } from '../../scenes/sceneTypes'import { navigationLogic } from '../navigation/navigationLogic'-export type Navigation3000Mode = 'none' | 'minimal' | 'zen' | 'full'+export type Navigation3000Mode = 'none' | 'minimal' | 'zen' | 'embedded' | 'full'export type ZenModeTrigger = 'shortcut' | 'account_menu' | 'help_menu' | 'exit_button' | 'url'@@ -120,6 +121,10 @@ export const navigation3000Logic = kea<navigation3000LogicType>([activeSceneId: string | null,featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): Navigation3000Mode => {+ // An embedded page frame sits inside another app page, so it shows the scene alone.+ if (isEmbeddedPageFrame()) {+ return 'embedded'+ }if (zenMode) {return 'zen'}diff --git a/frontend/src/lib/utils/embeddedPageFrame.ts b/frontend/src/lib/utils/embeddedPageFrame.tsnew file mode 100644index 000000000000..0a1998e47526--- /dev/null+++ b/frontend/src/lib/utils/embeddedPageFrame.ts@@ -0,0 +1,19 @@+/** The name of a frame that shows an app page inside another app page, such as a cited object in a task. */+export const EMBEDDED_PAGE_FRAME_NAME = 'posthog-embedded-page'++/**+ * True when this document is an app page inside an embedded page frame, so it renders without the app's+ * navigation. The frame name stays when the page navigates inside the frame. The origin check makes sure+ * only the app itself can turn the mode on.+ */+export function isEmbeddedPageFrame(): boolean {+ if (typeof window === 'undefined' || window.name !== EMBEDDED_PAGE_FRAME_NAME || window.parent === window) {+ return false+ }+ try {+ return window.parent.location.origin === window.location.origin+ } catch {+ // A cross-origin parent throws on any read of its location.+ return false+ }+}diff --git a/frontend/src/loadPostHogJS.tsx b/frontend/src/loadPostHogJS.tsxindex 07e5659e0ea9..c044dc3a2700 100644--- a/frontend/src/loadPostHogJS.tsx+++ b/frontend/src/loadPostHogJS.tsx@@ -3,6 +3,7 @@ import posthog, { BeforeSendFn, BrowserMetricsConfig, PostHogConfig, SessionRecoimport { 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 { startDetachedElementTracking } from './detachedElementTracker'@@ -54,6 +55,10 @@ export function withLastSeenFeatureFlags(return { ...bootstrap, featureFlags: { ...lastSeen.featureFlags, ...bootstrap.featureFlags } }}+// pinned: analytics property name. Insights filter the framed pages by it.+const stampEmbeddedPageFrame: BeforeSendFn = (event) =>+ event && { ...event, properties: { ...event.properties, embedded_page_frame: true } }+function readLastSeenFeatureFlags(): LastSeenFeatureFlags | null {try {const stored = window.localStorage.getItem(LAST_SEEN_FEATURE_FLAGS_KEY)@@ -119,7 +124,11 @@ export function loadPostHogJS(options: LoadPostHogJSOptions = {}): void {__capturePostHogExceptions: true,},metrics: { network: true, serviceName: 'posthog-app', ...options.metrics },- before_send: options.beforeSend,+ // 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,loaded: (loadedInstance) => {if (loadedInstance.sessionRecording) {loadedInstance.sessionRecording._forceAllowLocalhostNetworkCapture = truediff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsxindex bd96c75f29c5..e1fe39cea206 100644--- a/frontend/src/scenes/AuthenticatedShell.tsx+++ b/frontend/src/scenes/AuthenticatedShell.tsx@@ -9,6 +9,7 @@ import { ToastCloseButton } from 'lib/lemon-ui/LemonToast/LemonToast'import { apiStatusLogic } from 'lib/logic/apiStatusLogic'import { eventIngestionRestrictionLogic } from 'lib/logic/eventIngestionRestrictionLogic'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { isEmbeddedPageFrame } from 'lib/utils/embeddedPageFrame'import { lazyWithRetry } from 'lib/utils/retryImport'import { WizardHandoffDialog } from 'scenes/onboarding/shared/wizard-sync/WizardHandoffDialog'import { WizardSyncDebugPanel } from 'scenes/onboarding/shared/wizard-sync/WizardSyncDebugPanel'@@ -43,6 +44,28 @@ export default function AuthenticatedShell({ children }: { children: React.Reactconst { featureFlags } = useValues(featureFlagLogic)const { isDarkModeOn } = useValues(themeLogic)const runSyncEnabled = featureFlags[FEATURE_FLAGS.WIZARD_RUN_SYNC] === 'wizard-run'+ const toasts = (+ <ToastContainer+ autoClose={6000}+ transition={Slide}+ closeButton={<ToastCloseButton />}+ position="bottom-right"+ theme={isDarkModeOn ? 'dark' : 'light'}+ />+ )++ // The page around the frame already has the command palette, shortcuts and floating buttons.+ if (isEmbeddedPageFrame()) {+ return (+ <>+ <div className="contents isolate">+ <Navigation sceneConfig={sceneConfig}>{children}</Navigation>+ <GlobalModals />+ </div>+ {toasts}+ </>+ )+ }return (<>@@ -71,13 +94,7 @@ export default function AuthenticatedShell({ children }: { children: React.React<div data-attr="experiments-freeze-exposure-aa-test-variant" className="hidden" />)}</div>- <ToastContainer- autoClose={6000}- transition={Slide}- closeButton={<ToastCloseButton />}- position="bottom-right"- theme={isDarkModeOn ? 'dark' : 'light'}- />+ {toasts}</>)}diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pyindex ff5953c690a1..1e1f81a7f535 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -307,7 +307,10 @@ class CSPMiddleware:# Enforced for every viewer, flag or not, because this directive is what admits these# origins: a frame-ancestors directive makes browsers ignore X-Frame-Options, which# names only our own origin.- frame_ancestors = f"frame-ancestors {' '.join(app_frame_ancestor_sources())}"+ # `'self'` lets the app show one of its own pages in a frame, such as a PostHog object+ # cited in a task's Artifacts tab. It stays out of app_frame_ancestor_sources(), because+ # the canvas sandbox document on the user-content origin shares that list.+ frame_ancestors = f"frame-ancestors 'self' {' '.join(app_frame_ancestor_sources())}"js_url = urlsplit(settings.JS_URL)bundle_origin = f"{js_url.scheme}://{js_url.netloc}" if js_url.scheme and js_url.netloc else ""if settings.DEBUG or settings.TEST:diff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.pyindex e0b670af33a8..2a695214f69e 100644--- a/posthog/test/test_csp_middleware.py+++ b/posthog/test/test_csp_middleware.py@@ -190,7 +190,7 @@ class TestCSPMiddleware(APIBaseTest):# Framing is enforced ahead of the flag because it is what lets posthog.com frame the app.# The enforced list has to be the one the reported policy names, or the two drift apart.enforced = response["Content-Security-Policy"]- assert enforced.startswith("frame-ancestors https://posthog.com")+ assert enforced.startswith("frame-ancestors 'self' https://posthog.com")assert "default-src" not in enforcedassert enforced in reporteddiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsxindex 8994a9be02a1..111f66fa3117 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx@@ -11,7 +11,6 @@ import { SceneLayout } from '~/layout/scenes/SceneLayout'import { TodayShell } from '~/layout/today/TodayShell'import { todayShellLogic } from '~/layout/today/todayShellLogic'import { mswDecorator } from '~/mocks/browser'-import TRENDS_LINE_INSIGHT from '~/mocks/fixtures/api/projects/team_id/insights/trendsLine.json'import type { MockSignature } from '~/mocks/utils'import type {@@ -203,7 +202,7 @@ const WALKTHROUGH_WEBM_BASE64 =function objectReference(id: string,name: string,- objectKind: 'insight' | 'dashboard' | 'flag' | 'experiment' | 'cohort' | 'survey',+ objectKind: string,objectId: string,uploadedAt: string): TaskRunArtifactResponseApi {@@ -231,21 +230,10 @@ const OBJECT_REFERENCES = [objectReference('phref_experiment', 'Plan picker layout test', 'experiment', '12', '2026-09-28T18:09:00Z'),objectReference('phref_cohort', 'Trial starters on laptops', 'cohort', '3', '2026-09-28T18:08:00Z'),objectReference('phref_survey', 'Plan picker feedback', 'survey', 'survey-plan-picker', '2026-09-28T18:07:00Z'),+ // No kind called `note` has a page, so this reference shows the card.+ objectReference('phref_note', 'Pricing notes', 'note', 'pricing-notes', '2026-09-28T18:06:00Z'),]-const CITED_INSIGHT = { ...TRENDS_LINE_INSIGHT, short_id: 'aBcD1234', name: 'Trial funnel by step' }--// The live insight embed loads the saved insight, then runs its query.-const OBJECT_MOCKS = {- get: {- '/api/environments/:team_id/insights/': { count: 1, results: [CITED_INSIGHT] },- '/api/projects/:team_id/insights/': { count: 1, results: [CITED_INSIGHT] },- },- post: {- '/api/environments/:team_id/query/': { results: CITED_INSIGHT.result },- },-}-const VIDEO_ARTIFACT: TaskRunArtifactResponseApi = {id: 'artifact-walkthrough',name: 'plan-picker-walkthrough.webm',@@ -534,8 +522,7 @@ export const Video: Story = {}function objectMocks(): ReturnType<typeof taskMocks> {- const mocks = taskMocks([...ARTIFACTS, ...OBJECT_REFERENCES])- return { get: { ...mocks.get, ...OBJECT_MOCKS.get }, post: { ...mocks.post, ...OBJECT_MOCKS.post } }+ return taskMocks([...ARTIFACTS, ...OBJECT_REFERENCES])}export const PostHogObjects: Story = {@@ -543,9 +530,9 @@ export const PostHogObjects: Story = {render: () => <StoryPage fileName="phref_trial_funnel" />,}-export const PostHogObjectWithoutEmbed: Story = {+export const PostHogObjectWithoutPage: Story = {parameters: { msw: { mocks: objectMocks() } },- render: () => <StoryPage fileName="phref_survey" />,+ render: () => <StoryPage fileName="phref_note" />,}export const Versions: Story = {@@ -642,14 +629,13 @@ function livingMocks(): ReturnType<typeof taskMocks> {return {get: {...mocks.get,- ...OBJECT_MOCKS.get,[`/api/projects/:team_id/tasks/${TASK_ID}/runs/:run_id/living_artifacts/`]: {artifacts: LIVING_DOCUMENTS,},[`/api/projects/:team_id/tasks/${TASK_ID}/runs/:run_id/living_artifacts/doc-trial-chart/versions/:version/`]:() => new HttpResponse(CHART_SVG, { headers: { 'Content-Type': 'image/svg+xml' } }),},- post: { ...mocks.post, ...OBJECT_MOCKS.post },+ post: mocks.post,}}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactObjectEmbed.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactObjectEmbed.tsxindex 32ad021d927b..0f17d0ea01fc 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactObjectEmbed.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactObjectEmbed.tsx@@ -1,73 +1,32 @@-import { Dashboard } from 'scenes/dashboard/Dashboard'-import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'-import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'+import { useState } from 'react'-import { Query } from '~/queries/Query/Query'-import { NodeKind } from '~/queries/schema/schema-general'-import { DashboardPlacement, InsightShortId } from '~/types'+import { Spinner, cn } from '@posthog/quill-primitives'-import type { PostHogObjectRef } from '../taskRunArtifacts'--function EmbedBody({ objectKind, objectId }: PostHogObjectRef): JSX.Element | null {- if (objectKind === 'insight') {- return (- <div className="flex min-h-full flex-col p-4">- <div className="flex min-h-96 flex-1 flex-col rounded-md border border-primary bg-surface-primary">- <Query- uniqueKey={`task-artifact-${objectId}`}- query={{ kind: NodeKind.SavedInsightNode, shortId: objectId as InsightShortId }}- embedded- readOnly- />- </div>- </div>- )- }- if (objectKind === 'hogql') {- // The SQL itself is the object id for this kind.- return (- <div className="p-4">- <Query- uniqueKey={`task-artifact-sql-${objectId}`}- query={{ kind: NodeKind.DataTableNode, source: { kind: NodeKind.HogQLQuery, query: objectId } }}- readOnly- />- </div>- )- }- if (objectKind === 'dashboard') {- return (- <div className="p-4">- <Dashboard id={objectId} placement={DashboardPlacement.Builtin} />- </div>- )- }- if (objectKind === 'replay') {- return (- <div className="h-full p-4">- <SessionRecordingPlayer- sessionRecordingId={objectId}- playerKey={`task-artifact-${objectId}`}- mode={SessionRecordingPlayerMode.Standard}- autoPlay={false}- noMeta- withSidebar={false}- />- </div>- )- }- return null-}+import { EMBEDDED_PAGE_FRAME_NAME } from 'lib/utils/embeddedPageFrame'/**- * The live object a reference points at, rendered with the same components its own page uses.- * Kept in its own module so the insight, dashboard and replay code loads only when one opens.+ * A cited object's own page, the same page its URL opens. The frame keeps that page's URL and navigation+ * apart from the task page, and the frame name makes the app show the page without its navigation.*/-export function ArtifactObjectEmbed(ref: PostHogObjectRef): JSX.Element {- // These are LemonUI page components inside the quill artifacts pane, so they need PostHog's own color tokens back.+export function ArtifactObjectEmbed({ url, title }: { url: string; title: string }): JSX.Element {+ const [loaded, setLoaded] = useState(false)return (- <div data-not-quill className="h-full">- <EmbedBody {...ref} />+ <div className="relative size-full">+ {!loaded && (+ <div className="absolute inset-0 flex items-center justify-center">+ <Spinner />+ </div>+ )}+ {/* The page is the app's own, so it keeps its origin, scripts, forms and new tabs. The sandbox+ still stops it navigating the task page away. */}+ <iframe+ name={EMBEDDED_PAGE_FRAME_NAME}+ src={url}+ title={title}+ sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-modals"+ className={cn('size-full border-0', !loaded && 'invisible')}+ onLoad={() => setLoaded(true)}+ /></div>)}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsxindex 8cf2a6fc0224..3f26eae50307 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { KeyboardEvent, Suspense, lazy, useEffect, useMemo, useState } from 'react'+import { KeyboardEvent, useEffect, useMemo, useState } from 'react'import {IconCheck,@@ -87,8 +87,8 @@ import {isTextPreview,listboxKeyTarget,parseCsv,- LIVE_OBJECT_KINDS,LIVING_ADAPTER_LABEL,+ objectPageUrl,postHogObjectRef,} from '../taskRunArtifacts'import { FullPageSource, artifactDownloadUrl, taskRunArtifactsLogic } from '../taskRunArtifactsLogic'@@ -99,14 +99,11 @@ import { ArtifactEditToolbar } from './ArtifactEditToolbar'import { ArtifactIcon } from './ArtifactIcon'import { ArtifactImagePins } from './ArtifactImagePins'import { ArtifactImageViewer } from './ArtifactImageViewer'+import { ArtifactObjectEmbed } from './ArtifactObjectEmbed'import { ArtifactTextAnnotations } from './ArtifactTextAnnotations'const MAX_CSV_ROWS = 500-const ArtifactObjectEmbed = lazy(() =>- import('./ArtifactObjectEmbed').then((m) => ({ default: m.ArtifactObjectEmbed }))-)-type PreviewMode = 'rendered' | 'source'const FULL_PAGE_KEY = 'f'@@ -358,27 +355,16 @@ function lowerFirst(label: string): string {function ReferencePreview({ taskId, artifact }: { taskId: string; artifact: RunArtifact }): JSX.Element | null {const { currentProjectId } = useValues(taskRunArtifactsLogic({ taskId }))- const { reportObjectOpened } = useActions(taskRunArtifactsLogic({ taskId }))const ref = postHogObjectRef(artifact)if (!ref || currentProjectId === null) {return null}- if (LIVE_OBJECT_KINDS.has(ref.objectKind)) {- return (- <div className="h-full overflow-y-auto">- <Suspense- fallback={- <div className="flex h-full items-center justify-center">- <Spinner />- </div>- }- >- <ArtifactObjectEmbed key={artifact.id} {...ref} />- </Suspense>- </div>- )+ const url = objectPageUrl(ref, currentProjectId)+ if (url) {+ // Keyed by the page, so the loading state starts over whenever the frame shows a different page.+ return <ArtifactObjectEmbed key={url} url={url} title={artifact.name} />}- const { kind, url } = objectKindLink(ref.objectKind, ref.objectId, `/project/${currentProjectId}`)+ const { kind } = objectKindLink(ref.objectKind, ref.objectId, `/project/${currentProjectId}`)return (<div className="flex h-full items-center justify-center p-6"><Card className="w-full max-w-sm">@@ -399,22 +385,9 @@ function ReferencePreview({ taskId, artifact }: { taskId: string; artifact: RunA</div></CardHeader><CardContent>- {url ? (- <Button- variant="primary"- className="w-full"- render={<LinkPrimitive to={url} />}- nativeButton={false}- onClick={() => reportObjectOpened(ref.objectKind)}- data-attr="task-artifact-open-object"- >- {`Open ${lowerFirst(kind.kindLabel)}`}- </Button>- ) : (- <Text size="xs" variant="muted">- This object has no page to open.- </Text>- )}+ <Text size="xs" variant="muted">+ This object has no page to open.+ </Text></CardContent></Card></div>diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.tsindex 067b15462077..046255ac4c52 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts@@ -1,5 +1,7 @@import { combineUrl } from 'kea-router'+import { objectKindLink } from 'lib/components/AgentObjectTags/rewriteAgentObjectTags'+import type {TaskRunArtifactResponseApi,TaskRunLivingArtifactResponseApi,@@ -47,8 +49,10 @@ export interface PostHogObjectRef {objectId: string}-/** Object kinds the preview shows live, with the components their own pages use. Others show a card. */-export const LIVE_OBJECT_KINDS: ReadonlySet<string> = new Set(['insight', 'hogql', 'dashboard', 'replay'])+/** The app page of a cited object, which the preview shows in a frame. Null for a kind with no page, which shows a card. */+export function objectPageUrl(ref: PostHogObjectRef, projectId: number | null): string | null {+ return projectId === null ? null : objectKindLink(ref.objectKind, ref.objectId, `/project/${projectId}`).url+}export function postHogObjectRef(artifact: TaskRunArtifactResponseApi): PostHogObjectRef | null {const metadata = artifact.metadata@@ -99,10 +103,12 @@ function fileKind(artifact: TaskRunArtifactResponseApi): ArtifactPreviewKind {return 'none'}-/** A cited object with no live embed shows only a card, so it gets no full page view. */+/** A cited object with no page shows only a card, so it gets no full page view. */export function hasFullPageView(artifact: TaskRunArtifactResponseApi & { living?: LivingVersion }): boolean {const ref = postHogObjectRef(artifact)- return ref ? LIVE_OBJECT_KINDS.has(ref.objectKind) : artifactPreviewKind(artifact) !== 'reference'+ return ref+ ? objectKindLink(ref.objectKind, ref.objectId, '').url !== null+ : artifactPreviewKind(artifact) !== 'reference'}export function isTextPreview(kind: ArtifactPreviewKind): boolean {