: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(workflows): back the email editor uploads tab with the media library (#115952)
Harley Alexanderce07e8c12e51
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 2ae317e8ed6a..d23bca73e497 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -5488,6 +5488,16 @@ export interface UploadedMediaApi {readonly content_type: string | null/** @nullable */readonly size_bytes: number | null+ /**+ * Width in pixels. Null for images uploaded before it was recorded.+ * @nullable+ */+ readonly width: number | null+ /**+ * Height in pixels. Null for images uploaded before it was recorded.+ * @nullable+ */+ readonly height: number | null/** Permanent, public URL of the image. For emails, put this in an image block's values.src.url. */readonly url: stringreadonly created_at: string@@ -5502,6 +5512,19 @@ export interface PaginatedUploadedMediaListApi {results: UploadedMediaApi[]}+export interface UploadedMediaCreatedApi {+ /** Id of the uploaded image. */+ readonly id: string+ /** Permanent, public URL of the image. For emails, put this in an image block's values.src.url. */+ readonly image_location: string+ /** The file's original name. */+ readonly name: string+ /** Width in pixels. */+ readonly width: number+ /** Height in pixels. */+ readonly height: number+}+export interface UploadedMediaStartUploadApi {/*** The file's display name, e.g. 'logo.png'.@@ -6959,6 +6982,10 @@ export type UploadedMediaListParams = {* The library to list.*/purpose: UploadedMediaListPurpose+ /**+ * Only list images whose name contains this text, ignoring case.+ */+ search?: string}export type UploadedMediaListPurpose = (typeof UploadedMediaListPurpose)[keyof typeof UploadedMediaListPurpose]@@ -6986,8 +7013,6 @@ export type UploadedMediaCreateBody = {purpose?: UploadedMediaCreateBodyPurpose}-export type UploadedMediaCreate201 = { [key: string]: unknown }-export type UsersListParams = {email?: stringis_staff?: booleandiff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 27f568e5cb52..ff4de495f8de 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -105,8 +105,8 @@ import type {ToolbarEntitlementsApi,TwoFactorStatusApi,UploadedMediaApi,- UploadedMediaCreate201,UploadedMediaCreateBody,+ UploadedMediaCreatedApi,UploadedMediaListParams,UploadedMediaStartUploadApi,UploadedMediaUploadStartedApi,@@ -2790,7 +2790,7 @@ export const uploadedMediaCreate = async (projectId: string,uploadedMediaCreateBody?: UploadedMediaCreateBody,options?: RequestInit-): Promise<UploadedMediaCreate201> => {+): Promise<UploadedMediaCreatedApi> => {const formData = new FormData()if (uploadedMediaCreateBody?.image !== undefined) {formData.append(`image`, uploadedMediaCreateBody.image)@@ -2799,13 +2799,27 @@ export const uploadedMediaCreate = async (formData.append(`purpose`, uploadedMediaCreateBody.purpose)}- return apiMutator<UploadedMediaCreate201>(getUploadedMediaCreateUrl(projectId), {+ return apiMutator<UploadedMediaCreatedApi>(getUploadedMediaCreateUrl(projectId), {...options,method: 'POST',body: formData,})}+export const getUploadedMediaDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/uploaded_media/${id}/`+}++/**+ * Remove an image from its media library. It stops appearing in the library list, but its URL keeps working, so content that already uses it (a sent email, a live template) is not broken.+ */+export const uploadedMediaDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getUploadedMediaDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}+export const getUploadedMediaCompleteUploadCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/uploaded_media/${id}/complete_upload/`}diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 91a6a9efa4ea..3df305e5c15a 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -641,6 +641,7 @@ export const FEATURE_FLAGS = {WORKFLOWS_AI_FIRST_NEW: 'workflows-ai-first-new', // owner: @mayteio #team-workflowsWORKFLOWS_BROADCAST_RECIPIENT_LISTS: 'workflows-broadcast-recipient-lists', // owner: @mayteio #team-workflowsWORKFLOWS_DELAY_UNTIL_DATE: 'workflows-delay-until-date', // owner: @dmarchuk #team-workflows+ WORKFLOWS_EMAIL_MEDIA_LIBRARY: 'workflows-email-media-library', // owner: @mayteio #team-workflows, backs the email editor's Uploads tab with the media libraryWORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflowsWORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflowsWORKFLOWS_ISP_SENDING_HEALTH: 'workflows-isp-sending-health', // owner: #team-workflowsdiff --git a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsxindex aa1f8a9e5128..513398abe605 100644--- a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx+++ b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx@@ -535,8 +535,17 @@ function NativeEmailTemplaterForm({mode: EmailEditorModefieldsHidden?: boolean}): JSX.Element {- const { unlayerEditorProjectId, logicProps, templates, mergeTags, activeContentTab, visibleFields, emailTemplate } =- useValues(emailTemplaterLogic)+ const {+ unlayerEditorProjectId,+ emailMediaLibraryEnabled,+ unlayerEditorUser,+ logicProps,+ templates,+ mergeTags,+ activeContentTab,+ visibleFields,+ emailTemplate,+ } = useValues(emailTemplaterLogic)const { setEmailEditorRef, onEmailEditorReady, setActiveContentTab, hideAdvancedField, revealAdvancedField } =useActions(emailTemplaterLogic)// With the AI panel integration on, chat sits beside the editor and width is scarce, so the@@ -731,8 +740,14 @@ function NativeEmailTemplaterForm({// assistant) default to on; they're third-party AI consuming// paid credits from our Unlayer workspace, so keep them all off.ai: false,+ // The identified user is unsigned, so anyone can claim it. Saved+ // blocks are stored per user in Unlayer, so turn them off.+ ...(emailMediaLibraryEnabled+ ? { userUploads: { enabled: true, search: true }, blocks: false }+ : {}),},projectId: unlayerEditorProjectId,+ user: unlayerEditorUser,customJS: sceneIntegrationEnabled? [unsubscribeLinkToolCustomJs,diff --git a/frontend/src/scenes/hog-functions/email-templater/emailMediaLibrary.test.ts b/frontend/src/scenes/hog-functions/email-templater/emailMediaLibrary.test.tsnew file mode 100644index 000000000000..b7a4b25e9b5a--- /dev/null+++ b/frontend/src/scenes/hog-functions/email-templater/emailMediaLibrary.test.ts@@ -0,0 +1,103 @@+import type { Editor } from 'react-email-editor'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { registerEmailMediaLibrary } from './emailMediaLibrary'++jest.mock('posthog-js')++type Handler = (...args: any[]) => Promise<void>++function registerOnFakeEditor(): Record<string, Handler> {+ const handlers: Record<string, Handler> = {}+ const editor = {+ registerProvider: (type: string, handler: Handler) => (handlers[`provider:${type}`] = handler),+ registerCallback: (type: string, handler: Handler) => (handlers[type] = handler),+ } as unknown as Editor+ registerEmailMediaLibrary(editor, '1')+ return handlers+}++const MEDIA = {+ id: 'media-1',+ name: 'logo.png',+ purpose: 'email',+ content_type: 'image/png',+ size_bytes: 1024,+ width: null,+ height: null,+ url: 'http://localhost/uploaded_media/media-1',+ created_at: '2026-10-01T00:00:00Z',+}++describe('registerEmailMediaLibrary', () => {+ beforeEach(() => {+ initKeaTests()+ })++ it('lists a page of the email library in the shape the Uploads tab expects', async () => {+ const requestedParams: URLSearchParams[] = []+ useMocks({+ get: {+ '/api/projects/:team_id/uploaded_media/': ({ request }) => {+ requestedParams.push(new URL(request.url).searchParams)+ return [200, { count: 41, next: 'http://localhost/next', previous: null, results: [MEDIA] }]+ },+ },+ })+ const done = jest.fn()++ await registerOnFakeEditor()['provider:userUploads']({ page: 3, searchText: ' logo ' }, done)++ expect(Object.fromEntries(requestedParams[0])).toEqual({+ purpose: 'email',+ limit: '20',+ offset: '40',+ search: 'logo',+ })+ expect(done).toHaveBeenCalledWith(+ [+ {+ id: 'media-1',+ location: 'http://localhost/uploaded_media/media-1',+ width: 0,+ height: 0,+ contentType: 'image/png',+ size: 1024,+ source: 'user',+ },+ ],+ { hasMore: true, page: 3, perPage: 20, total: 41 }+ )+ })++ it.each([+ [+ 'shows the reason the backend rejected the file',+ [400, { detail: 'Uploaded media must be less than 4MB' }],+ 'Uploaded media must be less than 4MB',+ ],+ ['falls back to a generic message without one', [500, {}], "Couldn't upload this image. Try again."],+ ])('upload failure %s', async (_name, response, expectedError) => {+ useMocks({ post: { '/api/projects/:team_id/uploaded_media/': () => response } })+ const done = jest.fn()++ await registerOnFakeEditor()['image']({ attachments: [new File(['x'], 'big.png')] }, done)++ expect(done).toHaveBeenLastCalledWith({ error: expectedError })+ })++ it.each([+ ['removed now', 204, true],+ ['already removed', 404, true],+ ['failed to remove', 500, false],+ ])('reports removal as finished only when the image is out of the library: %s', async (_name, status, finished) => {+ useMocks({ delete: { '/api/projects/:team_id/uploaded_media/:id/': () => [status] } })+ const done = jest.fn()++ await registerOnFakeEditor()['image:removed']({ id: 'media-1' }, done)++ expect(done).toHaveBeenCalledTimes(finished ? 1 : 0)+ })+})diff --git a/frontend/src/scenes/hog-functions/email-templater/emailMediaLibrary.ts b/frontend/src/scenes/hog-functions/email-templater/emailMediaLibrary.tsnew file mode 100644index 000000000000..db2529e7f1ad--- /dev/null+++ b/frontend/src/scenes/hog-functions/email-templater/emailMediaLibrary.ts@@ -0,0 +1,150 @@+import posthog from 'posthog-js'+import type { Editor } from 'react-email-editor'++import { ApiError } from 'lib/api-error'+import { lemonToast } from 'lib/lemon-ui/LemonToast'++import { uploadedMediaCreate, uploadedMediaDestroy, uploadedMediaList } from '~/generated/core/api'+import { UploadedMediaListPurpose } from '~/generated/core/api.schemas'+import type { UploadedMediaApi } from '~/generated/core/api.schemas'++const UPLOAD_FAILED_MESSAGE = "Couldn't upload this image. Try again."+// Unlayer passes `page` but no page size, so the provider decides how many images a page holds.+const UPLOADS_PAGE_SIZE = 20++/** The image shape Unlayer's Uploads tab renders. */+export interface UnlayerUploadsImage {+ id: string+ location: string+ width: number+ height: number+ contentType: string+ size?: number+ source: 'user'+}++export interface UnlayerUploadsPage {+ page: number+ perPage?: number+ searchText?: string+}++export interface UnlayerUploadsPageMeta {+ hasMore: boolean+ page: number+ perPage: number+ total: number+}++/** What Unlayer's `image` upload callback accepts as progress, success, or failure. */+export interface UnlayerImageUploadResult {+ progress?: number+ url?: string+ id?: string+ filename?: string+ width?: number | null+ height?: number | null+ abort?: boolean+ error?: string+}++export function toUnlayerUploadsImage(media: UploadedMediaApi): UnlayerUploadsImage {+ return {+ id: media.id,+ location: media.url,+ // Images uploaded before dimensions were recorded have none. Unlayer reads the real size+ // from the image when it is placed, so 0 only affects the thumbnail grid.+ width: media.width ?? 0,+ height: media.height ?? 0,+ contentType: media.content_type ?? '',+ size: media.size_bytes ?? undefined,+ source: 'user',+ }+}++function uploadErrorMessage(error: unknown): string {+ return error instanceof ApiError && error.detail ? error.detail : UPLOAD_FAILED_MESSAGE+}++/**+ * Backs Unlayer's Uploads tab with the team's email media library, so uploads land in our storage+ * and every template on the team can reuse them.+ */+export function registerEmailMediaLibrary(editor: Editor, projectId: string): void {+ editor.registerProvider(+ 'userUploads',+ async (+ { page, perPage = UPLOADS_PAGE_SIZE, searchText }: UnlayerUploadsPage,+ done: (images: UnlayerUploadsImage[], meta: UnlayerUploadsPageMeta) => void+ ) => {+ const search = searchText?.trim() || undefined+ if (page === 1) {+ // pinned: analytics event name and properties, renaming breaks dashboards+ posthog.capture('email media library viewed', { searched: !!search })+ }+ try {+ const response = await uploadedMediaList(projectId, {+ purpose: UploadedMediaListPurpose.Email,+ limit: perPage,+ offset: (page - 1) * perPage,+ search,+ })+ done(response.results.map(toUnlayerUploadsImage), {+ hasMore: !!response.next,+ page,+ perPage,+ total: response.count,+ })+ } catch {+ lemonToast.error("Couldn't load your images. Try again.")+ done([], { hasMore: false, page, perPage, total: 0 })+ }+ }+ )++ editor.registerCallback(+ 'image',+ async (file: { attachments: File[] }, done: (result: UnlayerImageUploadResult) => void) => {+ const image = file.attachments[0]+ if (!image) {+ done({ abort: true })+ return+ }+ done({ progress: 10 })+ try {+ const media = await uploadedMediaCreate(projectId, { image, purpose: UploadedMediaListPurpose.Email })+ // pinned: analytics event name and properties, renaming breaks dashboards+ posthog.capture('email media library image uploaded', { success: true })+ done({+ progress: 100,+ url: media.image_location,+ id: media.id,+ filename: media.name,+ width: media.width,+ height: media.height,+ })+ } catch (error) {+ posthog.capture('email media library image uploaded', {+ success: false,+ error_code: error instanceof ApiError ? (error.code ?? error.status) : null,+ })+ done({ error: uploadErrorMessage(error) })+ }+ }+ )++ editor.registerCallback('image:removed', async ({ id }: { id: string | number }, done: () => void) => {+ try {+ await uploadedMediaDestroy(projectId, String(id))+ // pinned: analytics event name, renaming breaks dashboards+ posthog.capture('email media library image removed')+ } catch (error) {+ // A 404 means it is already gone from the library, which is what the user asked for.+ if (!(error instanceof ApiError && error.status === 404)) {+ lemonToast.error("Couldn't remove this image. Try again.")+ return+ }+ }+ done()+ })+}diff --git a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.tsindex f53957f31392..66af8c846bc8 100644--- a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts+++ b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts@@ -1,8 +1,13 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { Realm } from '~/types'import {EMAIL_TYPE_SUPPORTED_FIELDS,@@ -132,6 +137,34 @@ describe('emailTemplaterLogic', () => {})})+ describe('email media library', () => {+ it.each([+ {+ description: 'identifies the project to Unlayer in the native editor',+ type: 'native_email',+ flagOn: true,+ identified: true,+ },+ {+ description: 'leaves Unlayer anonymous with the flag off',+ type: 'native_email',+ flagOn: false,+ identified: false,+ },+ { description: 'leaves the destination editor untouched', type: 'email', flagOn: true, identified: false },+ ] as const)('$description', ({ type, flagOn, identified }) => {+ preflightLogic.mount()+ preflightLogic.actions.loadPreflightSuccess({ realm: Realm.Cloud } as any)+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.WORKFLOWS_EMAIL_MEDIA_LIBRARY]: flagOn })++ logic = emailTemplaterLogic(makeProps({ type }))+ logic.mount()++ expect(logic.values.unlayerEditorUser?.id.startsWith('project-') ?? false).toBe(identified)+ })+ })+describe('modal content tab default', () => {it.each([{diff --git a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsxindex 6c97f51b928a..baea7cea41b5 100644--- a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx+++ b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx@@ -21,14 +21,18 @@ import { Editor, EmailEditorProps, EditorRef as _EditorRef } from 'react-email-eimport { LemonDialog } from '@posthog/lemon-ui'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { featureFlagLogic, FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { objectsEqual } from 'lib/utils/objects'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { teamLogic } from 'scenes/teamLogic'import { PreflightStatus, PropertyDefinition, PropertyDefinitionType, Realm } from '~/types'import { MessageTemplate } from 'products/workflows/frontend/TemplateLibrary/types'+import { registerEmailMediaLibrary } from './emailMediaLibrary'import type { EmailFieldErrors, EmailTemplate } from './types'export type { EmailTemplate }@@ -225,10 +229,13 @@ function autoRevealAdvancedFields(// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface emailTemplaterLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogicpreflight: PreflightStatus | null // preflightLogic+ currentProjectId: number | string // teamLogicactiveContentTab: 'plaintext' | 'visual'appliedTemplate: MessageTemplate | nullemailEditorRef: EditorRef | null+ emailMediaLibraryEnabled: booleanemailTemplate: EmailTemplateemailTemplateAllErrors: Record<string, any>emailTemplateChanged: boolean@@ -255,6 +262,11 @@ export interface emailTemplaterLogicValues {templatesLoading: booleantemplatingEngine: 'hog' | 'liquid'unlayerEditorProjectId: 275430 | undefined+ unlayerEditorUser:+ | {+ id: string+ }+ | undefinedvisibleFields: EmailMetaField[]}@@ -379,6 +391,19 @@ export interface emailTemplaterLogicMeta {logicProps: (arg: any) => EmailTemplaterLogicPropsmergeTags: (personPropertyDefinitions: PropertyDefinition[]) => UnlayerMergeTagsunlayerEditorProjectId: (preflight: PreflightStatus | null) => 275430 | undefined+ emailMediaLibraryEnabled: (+ arg: EmailTemplaterType,+ unlayerEditorProjectId: 275430 | undefined,+ featureFlags: FeatureFlagsSet+ ) => boolean+ unlayerEditorUser: (+ emailMediaLibraryEnabled: boolean,+ currentProjectId: number | string+ ) =>+ | {+ id: string+ }+ | undefinedvisibleFields: (arg: EmailTemplaterType, revealedAdvancedFields: EmailMetaFieldKey[]) => EmailMetaField[]hiddenAdvancedFields: (arg: EmailTemplaterType, visibleFields: EmailMetaField[]) => EmailMetaField[]}@@ -395,7 +420,7 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([props({} as EmailTemplaterLogicProps),path(['scenes', 'hog-functions', 'email-templater', 'emailTemplaterLogic']),connect(() => ({- values: [preflightLogic, ['preflight']],+ values: [preflightLogic, ['preflight'], featureFlagLogic, ['featureFlags'], teamLogic, ['currentProjectId']],})),actions({setEmailEditorRef: (emailEditorRef: EditorRef | null) => ({ emailEditorRef }),@@ -537,12 +562,27 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([],unlayerEditorProjectId: [(s) => [s.preflight],- (preflight: PreflightStatus) => {- if (preflight.realm === Realm.Cloud || preflight.is_debug) {+ (preflight: PreflightStatus | null) => {+ if (preflight?.realm === Realm.Cloud || preflight?.is_debug) {return 275430}},],+ emailMediaLibraryEnabled: [+ (s) => [(_, props: EmailTemplaterLogicProps) => props.type, s.unlayerEditorProjectId, s.featureFlags],+ (type: EmailTemplaterType, unlayerEditorProjectId: number | undefined, featureFlags: FeatureFlagsSet) =>+ // The Uploads tab needs a paid Unlayer project, and only the native editor loads one.+ type !== 'email' &&+ !!unlayerEditorProjectId &&+ !!featureFlags[FEATURE_FLAGS.WORKFLOWS_EMAIL_MEDIA_LIBRARY],+ ],+ unlayerEditorUser: [+ (s) => [s.emailMediaLibraryEnabled, s.currentProjectId],+ (emailMediaLibraryEnabled: boolean, currentProjectId: number | string): { id: string } | undefined =>+ // Unlayer hides the Uploads tab until it can identify the end user. The library is+ // shared by the whole project, so the project is the user it sees.+ emailMediaLibraryEnabled ? { id: `project-${currentProjectId}` } : undefined,+ ],visibleFields: [(s) => [(_, props: EmailTemplaterLogicProps) => props.type, s.revealedAdvancedFields],(type: EmailTemplaterType, revealedAdvancedFields: EmailMetaFieldKey[]): EmailMetaField[] =>@@ -614,6 +654,10 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([listeners(({ props, values, actions, cache }) => ({onEmailEditorReady: () => {+ const editor = values.emailEditorRef?.editor+ if (editor && values.emailMediaLibraryEnabled) {+ registerEmailMediaLibrary(editor, String(values.currentProjectId))+ }// Listeners must attach before loadDesign so the initial design:loaded is heard and// rebaselines - otherwise the load echo is indistinguishable from a user edit.if (props.layout === 'inline' || props.liveChanges) {diff --git a/posthog/api/test/test_uploaded_media.py b/posthog/api/test/test_uploaded_media.pyindex 18609aeb1964..1ac01d2e0acb 100644--- a/posthog/api/test/test_uploaded_media.py+++ b/posthog/api/test/test_uploaded_media.py@@ -9,18 +9,19 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import patchfrom django.core.files.uploadedfile import SimpleUploadedFile-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom django.utils.timezone import nowfrom boto3 import resourcefrom botocore.config import Configfrom parameterized import parameterized-from PIL import Image+from PIL import ExifTags, Imagefrom rest_framework import statusfrom posthog.api.uploaded_media import FOUR_MEGABYTESfrom posthog.models import Team, UploadedMediafrom posthog.models.personal_api_key import PersonalAPIKey, hash_key_value+from posthog.models.uploaded_media import sniff_imagefrom posthog.models.utils import UUIDT, generate_random_token_personalfrom posthog.settings import (OBJECT_STORAGE_ACCESS_KEY_ID,@@ -35,12 +36,36 @@ MEDIA_ROOT = tempfile.mkdtemp()TEST_BUCKET = "Test-Uploads"+SMALL_GIF_WIDTH = 1428+SMALL_GIF_HEIGHT = 816+def get_path_to(fixture_file: str) -> str:file_dir = os.path.dirname(__file__)return os.path.join(file_dir, "fixtures", fixture_file)+class TestSniffImage(SimpleTestCase):+ @parameterized.expand(+ [+ ("upright", 1, (120, 80)),+ ("rotated_a_quarter_turn", 6, (80, 120)),+ ]+ )+ def test_reports_the_size_a_browser_displays(+ self, _name: str, orientation: int, expected_size: tuple[int, int]+ ) -> None:+ exif = Image.Exif()+ exif[ExifTags.Base.Orientation] = orientation+ buffer = io.BytesIO()+ Image.new("RGB", (120, 80)).save(buffer, format="JPEG", exif=exif)++ sniffed = sniff_image(buffer.getvalue())++ assert sniffed is not None+ assert (sniffed.width, sniffed.height) == expected_size++@override_settings(MEDIA_ROOT=MEDIA_ROOT)class TestMediaAPI(APIBaseTest):@classmethod@@ -379,6 +404,15 @@ class TestMediaLibraryAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())assert UploadedMedia.objects.count() == 0+ def test_media_urls_use_the_cdn_origin_when_one_is_configured(self) -> None:+ media = self._create_media(purpose="email")++ with self.settings(UPLOADED_MEDIA_PUBLIC_URL="https://media.example.com"):+ response = self.client.get(f"/api/projects/{self.team.id}/uploaded_media/?purpose=email")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ assert response.json()["results"][0]["url"] == f"https://media.example.com/uploaded_media/{media.id}"+def test_list_returns_only_matching_purpose_for_own_team_newest_first(self) -> None:first = self._create_media(purpose="canvas", file_name="first.png")second = self._create_media(purpose="canvas", file_name="second.png")@@ -404,6 +438,46 @@ class TestMediaLibraryAPI(APIBaseTest):assert listed["url"] == f"http://localhost:8010/uploaded_media/{second.id}"assert listed["created_at"] is not None+ def test_list_search_matches_part_of_the_name_ignoring_case(self) -> None:+ match = self._create_media(purpose="email", file_name="Hero-Banner.png")+ self._create_media(purpose="email", file_name="logo.png")+ self._create_media(purpose="canvas", file_name="banner-for-a-canvas.png")++ response = self.client.get(f"/api/projects/{self.team.id}/uploaded_media/?purpose=email&search=banner")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ assert [item["id"] for item in response.json()["results"]] == [str(match.id)]++ def test_removing_an_image_hides_it_from_the_library_but_keeps_its_url_working(self) -> None:+ with self.settings(OBJECT_STORAGE_ENABLED=True, OBJECT_STORAGE_MEDIA_UPLOADS_FOLDER=TEST_BUCKET):+ with open(get_path_to("a-small-but-valid.gif"), "rb") as image:+ upload_response = self.client.post(+ f"/api/projects/{self.team.id}/uploaded_media",+ {"image": image, "purpose": "email"},+ format="multipart",+ )+ media_id = upload_response.json()["id"]++ delete_response = self.client.delete(f"/api/projects/{self.team.id}/uploaded_media/{media_id}/")+ assert delete_response.status_code == status.HTTP_204_NO_CONTENT++ list_response = self.client.get(f"/api/projects/{self.team.id}/uploaded_media/?purpose=email")+ assert list_response.json()["results"] == []++ repeat_response = self.client.delete(f"/api/projects/{self.team.id}/uploaded_media/{media_id}/")+ assert repeat_response.status_code == status.HTTP_404_NOT_FOUND++ self.client.logout()+ download_response = self.client.get(f"/uploaded_media/{media_id}")+ assert download_response.status_code == status.HTTP_200_OK++ def test_removing_refuses_an_upload_that_is_not_in_a_library(self) -> None:+ dashboard_image = self._create_media(purpose=None)++ response = self.client.delete(f"/api/projects/{self.team.id}/uploaded_media/{dashboard_image.id}/")+ assert response.status_code == status.HTTP_404_NOT_FOUND+ dashboard_image.refresh_from_db()+ assert dashboard_image.archived_at is None+def test_list_pages_stay_stable_when_images_share_a_created_at(self) -> None:# Ordering on a non-unique created_at alone leaves tied rows no fixed position, so a# client walking offset pages can miss an image or receive one twice. The explicit ids@@ -443,6 +517,7 @@ class TestMediaLibraryAPI(APIBaseTest):format="multipart",)self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ assert (response.json()["width"], response.json()["height"]) == (SMALL_GIF_WIDTH, SMALL_GIF_HEIGHT)list_response = self.client.get(f"/api/projects/{self.team.id}/uploaded_media/?purpose=email")self.assertEqual(list_response.status_code, status.HTTP_200_OK, list_response.json())@@ -451,6 +526,7 @@ class TestMediaLibraryAPI(APIBaseTest):if expected_count:assert results[0]["id"] == response.json()["id"]assert results[0]["size_bytes"] == os.path.getsize(get_path_to("a-small-but-valid.gif"))+ assert (results[0]["width"], results[0]["height"]) == (SMALL_GIF_WIDTH, SMALL_GIF_HEIGHT)def test_create_rejects_an_oversized_purpose_before_writing_anything(self) -> None:"""purpose is a varchar(100) column. Without validating it up front, an oversized value@@ -553,6 +629,7 @@ class TestMediaLibraryAPI(APIBaseTest):payload = response.json()assert payload["content_type"] == "image/gif"assert payload["size_bytes"] == len(gif_bytes)+ assert (payload["width"], payload["height"]) == (SMALL_GIF_WIDTH, SMALL_GIF_HEIGHT)assert payload["url"] == f"http://localhost:8010/uploaded_media/{media_id}"media = UploadedMedia.objects.get(id=media_id)@@ -690,18 +767,27 @@ class TestMediaLibraryAPI(APIBaseTest):response = self.client.post(f"/api/projects/{self.team.id}/uploaded_media/{media.id}/complete_upload/")self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.json())- def test_start_upload_requires_uploaded_media_write_scope(self) -> None:- """Guards against start_upload/complete_upload silently missing from- scope_object_write_actions, which would let a read-only key upload images."""+ @parameterized.expand(+ [+ ("start_upload", "post", "start_upload/", {"name": "logo.png", "purpose": "email"}),+ ("remove", "delete", "{media_id}/", None),+ ]+ )+ def test_library_writes_require_uploaded_media_write_scope(+ self, _name: str, method: str, path: str, body: dict | None+ ) -> None:+ media = self._create_media(purpose="email")value = generate_random_token_personal()PersonalAPIKey.objects.create(label="read-only", user=self.user, secure_value=hash_key_value(value), scopes=["uploaded_media:read"])self.client.logout()- response = self.client.post(- f"/api/projects/{self.team.id}/uploaded_media/start_upload/",- {"name": "logo.png", "purpose": "email"},+ response = getattr(self.client, method)(+ f"/api/projects/{self.team.id}/uploaded_media/{path.format(media_id=media.id)}",+ body,headers={"Authorization": f"Bearer {value}"},)self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())+ media.refresh_from_db()+ assert media.archived_at is Nonediff --git a/posthog/api/uploaded_media.py b/posthog/api/uploaded_media.pyindex f1723bf3a437..d84f30a9d872 100644--- a/posthog/api/uploaded_media.py+++ b/posthog/api/uploaded_media.py@@ -6,6 +6,7 @@ from django.conf import settingsfrom django.db import transactionfrom django.http import HttpResponsefrom django.shortcuts import get_object_or_404+from django.utils import timezonefrom django.utils.http import content_disposition_headerfrom django.views.decorators.csrf import csrf_exempt@@ -28,7 +29,7 @@ from posthog.models.uploaded_media import (PRIVATE_MEDIA_PURPOSES,ObjectStorageUnavailable,is_inline_safe_content_type,- sniff_image_content_type,+ sniff_image,)from posthog.storage import object_storagefrom posthog.storage.object_storage import ObjectStorageError@@ -186,10 +187,16 @@ class UploadedMediaSerializer(serializers.ModelSerializer):url = serializers.SerializerMethodField(help_text="Permanent, public URL of the image. For emails, put this in an image block's values.src.url.")+ width = serializers.IntegerField(+ read_only=True, allow_null=True, help_text="Width in pixels. Null for images uploaded before it was recorded."+ )+ height = serializers.IntegerField(+ read_only=True, allow_null=True, help_text="Height in pixels. Null for images uploaded before it was recorded."+ )class Meta:model = UploadedMedia- fields = ["id", "name", "purpose", "content_type", "size_bytes", "url", "created_at"]+ fields = ["id", "name", "purpose", "content_type", "size_bytes", "width", "height", "url", "created_at"]read_only_fields = fields@extend_schema_field(OpenApiTypes.URI)@@ -234,6 +241,17 @@ class UploadedMediaUploadStartedSerializer(serializers.Serializer):expires_in = serializers.IntegerField(read_only=True, help_text="Seconds before upload_url expires.")+class UploadedMediaCreatedSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True, help_text="Id of the uploaded image.")+ image_location = serializers.URLField(+ read_only=True,+ help_text="Permanent, public URL of the image. For emails, put this in an image block's values.src.url.",+ )+ name = serializers.CharField(read_only=True, help_text="The file's original name.")+ width = serializers.IntegerField(read_only=True, help_text="Width in pixels.")+ height = serializers.IntegerField(read_only=True, help_text="Height in pixels.")++class UploadedMediaCreateSerializer(serializers.Serializer):"""Validates the multipart body. The OpenAPI shape comes from `create`'s `@extend_schema`instead, so keep the descriptions there — these exist only to satisfy the field rule."""@@ -247,7 +265,7 @@ class UploadedMediaCreateSerializer(serializers.Serializer):@extend_schema(extensions={"x-product": "core"})class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "uploaded_media"- scope_object_write_actions = ["create", "start_upload", "complete_upload"]+ scope_object_write_actions = ["create", "start_upload", "complete_upload", "destroy"]queryset = UploadedMedia.objects.all()serializer_class = _FallbackSerializerparser_classes = (MultiPartParser, FormParser)@@ -255,7 +273,11 @@ class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):def safely_get_queryset(self, queryset):if self.action == "complete_upload":return queryset.filter(pending=True)- return queryset.filter(pending=False).order_by("-created_at", "-id")+ if self.action == "destroy":+ # Only library images can be removed. An upload with no purpose (a dashboard text card+ # image, say) was never listed, so there is nothing for this to take it out of.+ return queryset.filter(pending=False, purpose__in=MEDIA_PURPOSES, archived_at__isnull=True)+ return queryset.filter(pending=False, archived_at__isnull=True).order_by("-created_at", "-id")@extend_schema(description="List images in the media library. Requires a `purpose` filter — the library is scoped per "@@ -269,7 +291,14 @@ class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):required=True,enum=MEDIA_PURPOSES,description="The library to list.",- )+ ),+ OpenApiParameter(+ name="search",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Only list images whose name contains this text, ignoring case.",+ ),],responses={200: UploadedMediaSerializer(many=True),@@ -287,6 +316,9 @@ class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):code="unknown_purpose", detail=f"Unknown purpose. Valid values: {', '.join(MEDIA_PURPOSES)}.")queryset = self.get_queryset().filter(purpose=purpose)+ search = request.query_params.get("search", "").strip()+ if search:+ queryset = queryset.filter(file_name__icontains=search)page = self.paginate_queryset(queryset)serializer = UploadedMediaSerializer(page, many=True)return self.get_paginated_response(serializer.data)@@ -374,8 +406,8 @@ class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):uploaded_media, code="file_too_large", detail="Uploaded media must be less than 4MB")- sniffed_content_type = sniff_image_content_type(content)- if sniffed_content_type is None:+ sniffed = sniff_image(content)+ if sniffed is None:_discard_pending_upload(uploaded_media, code="invalid_image", detail="Uploaded media must be a valid image")# Move the verified bytes off the key the presigned form signed (see@@ -392,10 +424,14 @@ class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):object_storage.copy(staging_location, permanent_location)uploaded_media.media_location = permanent_location- uploaded_media.content_type = sniffed_content_type+ uploaded_media.content_type = sniffed.content_typeuploaded_media.size_bytes = len(content)+ uploaded_media.width = sniffed.width+ uploaded_media.height = sniffed.heightuploaded_media.pending = False- uploaded_media.save(update_fields=["media_location", "content_type", "size_bytes", "pending"])+ uploaded_media.save(+ update_fields=["media_location", "content_type", "size_bytes", "width", "height", "pending"]+ )# The image is live either way, so a failed cleanup must not fail the request — it# leaves a logged staging object that no longer costs the caller anything.@@ -403,7 +439,7 @@ class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):statsd.incr("uploaded_media.uploaded",- tags={"team_id": self.team.pk, "content_type": sniffed_content_type},+ tags={"team_id": self.team.pk, "content_type": sniffed.content_type},)return Response(UploadedMediaSerializer(uploaded_media).data)@@ -438,7 +474,7 @@ class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"required": ["image"],}},- responses={201: OpenApiTypes.OBJECT},+ responses={201: UploadedMediaCreatedSerializer},)def create(self, request, *args, **kwargs) -> Response:serializer = UploadedMediaCreateSerializer(data=request.data)@@ -475,8 +511,8 @@ class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if uploaded_media.media_location is None:raise APIException("Could not read uploaded media")bytes_to_verify = object_storage.read_bytes(uploaded_media.media_location)- sniffed_content_type = sniff_image_content_type(bytes_to_verify)- if sniffed_content_type is None:+ sniffed = sniff_image(bytes_to_verify)+ if sniffed is None:statsd.incr("uploaded_media.image_failed_validation",tags={"file_name": file.name, "team": self.team_id},@@ -485,25 +521,43 @@ class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):uploaded_media.delete()raise ValidationError(code="invalid_image", detail="Uploaded media must be a valid image")- uploaded_media.content_type = sniffed_content_type+ uploaded_media.content_type = sniffed.content_typeuploaded_media.size_bytes = len(bytes_to_verify) if bytes_to_verify else None+ uploaded_media.width = sniffed.width+ uploaded_media.height = sniffed.heightuploaded_media.purpose = purpose- uploaded_media.save(update_fields=["content_type", "size_bytes", "purpose"])+ uploaded_media.save(update_fields=["content_type", "size_bytes", "width", "height", "purpose"])statsd.incr("uploaded_media.uploaded",- tags={"team_id": self.team.pk, "content_type": sniffed_content_type},+ tags={"team_id": self.team.pk, "content_type": sniffed.content_type},)return Response({"id": uploaded_media.id,"image_location": uploaded_media.get_absolute_url(),"name": uploaded_media.file_name,+ "width": uploaded_media.width,+ "height": uploaded_media.height,},status=status.HTTP_201_CREATED,headers=self.get_success_headers(uploaded_media.get_absolute_url()),)+ @extend_schema(+ description="Remove an image from its media library. It stops appearing in the library list, but its URL "+ "keeps working, so content that already uses it (a sent email, a live template) is not broken.",+ responses={+ 204: OpenApiResponse(description="The image was removed from its library."),+ 404: OpenApiResponse(description="No library image with this id for this team."),+ },+ )+ def destroy(self, request, *args, **kwargs) -> Response:+ uploaded_media = self.get_object()+ uploaded_media.archived_at = timezone.now()+ uploaded_media.save(update_fields=["archived_at"])+ return Response(status=status.HTTP_204_NO_CONTENT)+def get_success_headers(self, location: str) -> dict:try:return {"Location": location}diff --git a/posthog/migrations/1397_uploaded_media_dimensions_and_archive.py b/posthog/migrations/1397_uploaded_media_dimensions_and_archive.pynew file mode 100644index 000000000000..e07ddf263adf--- /dev/null+++ b/posthog/migrations/1397_uploaded_media_dimensions_and_archive.py@@ -0,0 +1,27 @@+# Generated by Django 5.2.18 on 2026-10-13 08:40++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1396_events_retention_config"),+ ]++ operations = [+ migrations.AddField(+ model_name="uploadedmedia",+ name="archived_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="uploadedmedia",+ name="height",+ field=models.IntegerField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="uploadedmedia",+ name="width",+ field=models.IntegerField(blank=True, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 766902e0dd64..57c831b47cbb 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1396_events_retention_config+1397_uploaded_media_dimensions_and_archivediff --git a/posthog/models/uploaded_media.py b/posthog/models/uploaded_media.pyindex be9ad6bd160e..a453cfcd19b5 100644--- a/posthog/models/uploaded_media.py+++ b/posthog/models/uploaded_media.py@@ -7,8 +7,9 @@ from django.db import modelsfrom django.db.models import Qimport structlog-from PIL import Image+from PIL import ExifTags, Image+from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -72,13 +73,24 @@ def is_inline_safe_content_type(content_type: str | None) -> bool:return _normalize_content_type(content_type) in _INLINE_SAFE_CONTENT_TYPES+# EXIF orientations that rotate the image a quarter turn, so a browser shows it with width and+# height swapped from the stored pixels.+_QUARTER_TURN_ORIENTATIONS = frozenset({5, 6, 7, 8})+# Guards against a decompression bomb: a small, highly-compressed file that decodes to an# enormous bitmap. Checked from the header, before Pillow decodes the full image into memory._MAX_IMAGE_PIXELS = 50_000_000-def sniff_image_content_type(data: Optional[bytes]) -> Optional[str]:- """Determine an image's real content type from its bytes — never trust a caller's claim.+@frozen+class SniffedImage:+ content_type: str+ width: int+ height: int+++def sniff_image(data: Optional[bytes]) -> Optional[SniffedImage]:+ """Determine an image's real content type and pixel size from its bytes — never trust a caller's claim.Accepts only what `download` will serve inline: storing a format that always comes backas an attachment gives the caller a URL no image tag can render. Returns None for@@ -94,9 +106,18 @@ def sniff_image_content_type(data: Optional[bytes]) -> Optional[str]:return Noneimage.load()content_type = Image.MIME.get(image.format or "")+ if image.getexif().get(ExifTags.Base.Orientation) in _QUARTER_TURN_ORIENTATIONS:+ width, height = height, widthexcept Exception:return None- return content_type if content_type in _INLINE_SAFE_CONTENT_TYPES else None+ if content_type not in _INLINE_SAFE_CONTENT_TYPES:+ return None+ return SniffedImage(content_type=content_type, width=width, height=height)+++def sniff_image_content_type(data: Optional[bytes]) -> Optional[str]:+ sniffed = sniff_image(data)+ return sniffed.content_type if sniffed else Noneclass UploadedMedia(UUIDTModel, RootTeamMixin):@@ -119,6 +140,12 @@ class UploadedMedia(UUIDTModel, RootTeamMixin):# True from presigned upload start until the uploaded object is verified. A pending# row's bytes are unvetted, so it is never listed and never served.pending = models.BooleanField(default=False)+ # Pixel size, recorded at upload so a library picker can lay out images without fetching each one.+ width = models.IntegerField(null=True, blank=True)+ height = models.IntegerField(null=True, blank=True)+ # Set when a user removes the image from its library. The row and its bytes stay, because+ # content that already embeds the URL (a sent email, a live template) must keep loading it.+ archived_at = models.DateTimeField(null=True, blank=True)class Meta:indexes = [@@ -133,7 +160,10 @@ class UploadedMedia(UUIDTModel, RootTeamMixin):]def get_absolute_url(self) -> str:- return absolute_uri(f"/uploaded_media/{self.id}")+ path = f"/uploaded_media/{self.id}"+ if settings.UPLOADED_MEDIA_PUBLIC_URL:+ return f"{settings.UPLOADED_MEDIA_PUBLIC_URL}{path}"+ return absolute_uri(path)@staticmethoddef build_media_location(team_id: int, media_id) -> str:diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex ade08a2c5241..2d45fe8d9a5f 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -28,6 +28,9 @@ OBJECT_STORAGE_TRANSFER_ACCELERATION = get_from_env()OBJECT_STORAGE_EXPORTS_FOLDER = os.getenv("OBJECT_STORAGE_EXPORTS_FOLDER", "exports")OBJECT_STORAGE_MEDIA_UPLOADS_FOLDER = os.getenv("OBJECT_STORAGE_MEDIA_UPLOADS_FOLDER", "media_uploads")+# Origin of a CDN that caches the /uploaded_media route, e.g. "https://us-media.posthog.com". Empty serves+# media URLs from SITE_URL, so every load reaches Django.+UPLOADED_MEDIA_PUBLIC_URL = os.getenv("UPLOADED_MEDIA_PUBLIC_URL", "").rstrip("/")OBJECT_STORAGE_ERROR_TRACKING_SOURCE_MAPS_FOLDER = os.getenv("OBJECT_STORAGE_ERROR_TRACKING_SOURCE_MAPS_FOLDER", "symbolsets")diff --git a/products/surveys/backend/desktop_feedback.py b/products/surveys/backend/desktop_feedback.pyindex 6a7ae32ddd9e..a704d977104b 100644--- a/products/surveys/backend/desktop_feedback.py+++ b/products/surveys/backend/desktop_feedback.py@@ -8,9 +8,8 @@ from django.utils import timezoneimport structlog-from posthog.api.uploaded_media import sniff_image_content_typefrom posthog.models import Team, UploadedMedia, User-from posthog.models.uploaded_media import MEDIA_PURPOSE_DESKTOP_FEEDBACK+from posthog.models.uploaded_media import MEDIA_PURPOSE_DESKTOP_FEEDBACK, sniff_image_content_typefrom posthog.ph_client import PH_EU_API_KEY, PH_US_API_KEY, get_clientfrom posthog.storage import object_storagefrom posthog.storage.object_storage import ObjectStorageErrordiff --git a/products/surveys/backend/presentation/desktop_feedback.py b/products/surveys/backend/presentation/desktop_feedback.pyindex b45b07db52e0..61dbfff4755a 100644--- a/products/surveys/backend/presentation/desktop_feedback.py+++ b/products/surveys/backend/presentation/desktop_feedback.py@@ -21,8 +21,8 @@ from rest_framework.throttling import UserRateThrottlefrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.uploaded_media import sniff_image_content_typefrom posthog.models import User+from posthog.models.uploaded_media import sniff_image_content_typefrom products.surveys.backend.facade.api import (DesktopFeedbackUnavailable,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7ae046463309..93d0e4b0dab3 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -76229,6 +76229,16 @@ export namespace Schemas {readonly content_type: string | null;/** @nullable */readonly size_bytes: number | null;+ /**+ * Width in pixels. Null for images uploaded before it was recorded.+ * @nullable+ */+ readonly width: number | null;+ /**+ * Height in pixels. Null for images uploaded before it was recorded.+ * @nullable+ */+ readonly height: number | null;/** Permanent, public URL of the image. For emails, put this in an image block's values.src.url. */readonly url: string;readonly created_at: string;@@ -112113,6 +112123,19 @@ export namespace Schemas {file: string;}+ export interface UploadedMediaCreated {+ /** Id of the uploaded image. */+ readonly id: string;+ /** Permanent, public URL of the image. For emails, put this in an image block's values.src.url. */+ readonly image_location: string;+ /** The file's original name. */+ readonly name: string;+ /** Width in pixels. */+ readonly width: number;+ /** Height in pixels. */+ readonly height: number;+ }+export interface UploadedMediaStartUpload {/*** The file's display name, e.g. 'logo.png'.@@ -130458,6 +130481,10 @@ export namespace Schemas {* The library to list.*/purpose: UploadedMediaListPurpose;+ /**+ * Only list images whose name contains this text, ignoring case.+ */+ search?: string;};export type UploadedMediaListPurpose = typeof UploadedMediaListPurpose[keyof typeof UploadedMediaListPurpose];@@ -130486,8 +130513,6 @@ export namespace Schemas {purpose?: UploadedMediaCreateBodyPurpose;};- export type UploadedMediaCreate201 = { [key: string]: unknown };-export type UserProductListListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.tsindex b63eaaf2dc8a..de003400d448 100644--- a/services/mcp/src/generated/core/api.ts+++ b/services/mcp/src/generated/core/api.ts@@ -5768,6 +5768,7 @@ export const UploadedMediaListQueryParams = () => 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.'),purpose: zod.enum(['canvas', 'email']).describe('The library to list.'),+ search: zod.string().optional().describe('Only list images whose name contains this text, ignoring case.'),})/**diff --git a/services/mcp/src/tools/generated/core.ts b/services/mcp/src/tools/generated/core.tsindex 0d16f3181aa1..d757f98db914 100644--- a/services/mcp/src/tools/generated/core.ts+++ b/services/mcp/src/tools/generated/core.ts@@ -544,6 +544,7 @@ const mediaImagesList = (): ToolBase<limit: params.limit,offset: params.offset,purpose: params.purpose,+ search: params.search,},})return withInformationalResponse(diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/media-images-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/media-images-list.jsonindex af95fdc70362..2ee1e2fd3f17 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/media-images-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/media-images-list.json@@ -13,6 +13,10 @@"description": "The library to list, e.g. \"email\". Required.","enum": ["canvas", "email"],"type": "string"+ },+ "search": {+ "description": "Only list images whose name contains this text, ignoring case.",+ "type": "string"}},"required": ["purpose"],