: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(conversations): attach any file type to in-app ticket replies (#128897)
Alex V27deca76e032
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 426881d741ae..5270664f5653 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -483,6 +483,7 @@ export const FEATURE_FLAGS = {PRODUCT_SUPPORT_AI_SUGGESTION: 'product-support-ai-suggestion', // owner: @veryayskiy #team-conversationsPRODUCT_SUPPORT_GITHUB_CHANNEL: 'product-support-github-channel', // owner: @veryayskiy #team-conversationsPRODUCT_SUPPORT_IMPORT_TICKETS: 'product-support-import-tickets', // owner: @veryayskiy #team-conversations+ PRODUCT_SUPPORT_REPLY_FILE_ATTACHMENTS: 'support-reply-file-attachments', // owner: #team-conversations, attach any file type to in-app ticket repliesPRODUCT_SUPPORT_MACROS: 'support-macros', // owner: @veryayskiy #team-conversations, saved replies in the support composerPRODUCT_SUPPORT_SIMPLIFIED_REPLIES: 'conversations-simplified-replies', // owner: @jonmcwest #team-conversations, composer header + one Send menu in place of draft modePRODUCT_SUPPORT_SLACK_NOTIFY_ON_MEMBERS: 'product-support-slack-notify-on-members', // owner: @veryayskiy #team-conversationsdiff --git a/frontend/src/lib/hooks/useUploadFiles.ts b/frontend/src/lib/hooks/useUploadFiles.tsindex 35d2a9e4fe24..385573d8249f 100644--- a/frontend/src/lib/hooks/useUploadFiles.ts+++ b/frontend/src/lib/hooks/useUploadFiles.ts@@ -107,10 +107,13 @@ export function useUploadFiles({onUpload,onError,uploadFileOptions,+ uploadFn,}: {onUpload?: (url: string, fileName: string, uploadedMediaId: string) => voidonError: (detail: string) => voiduploadFileOptions?: UploadFileOptions+ /** Replaces the default image upload, e.g. to store files that are not images. */+ uploadFn?: (file: File) => Promise<MediaUploadResponse>}): {setFilesToUpload: Dispatch<SetStateAction<File[]>>filesToUpload: File[]@@ -142,7 +145,7 @@ export function useUploadFiles({try {uploadInProgressRef.current = truesetUploading(true)- const media = await uploadFile(file, uploadFileOptions)+ const media = uploadFn ? await uploadFn(file) : await uploadFile(file, uploadFileOptions)if (isMountedRef.current) {onUpload?.(media.image_location, media.name, media.id)}diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 2b8f66ee07c8..ce264f09353e 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -2,6 +2,7 @@ import jsonfrom concurrent.futures import ThreadPoolExecutorfrom datetime import timedeltafrom decimal import Decimal+from io import BytesIOfrom threading import Barrier, Eventfrom uuid import UUID@@ -19,12 +20,14 @@ from posthog.test.base import ()from unittest.mock import patch+from django.core.files.uploadedfile import SimpleUploadedFilefrom django.db import close_old_connections, connection, transactionfrom django.db.utils import IntegrityErrorfrom django.test import SimpleTestCasefrom django.utils import timezonefrom parameterized import parameterized+from PIL import Imagefrom rest_framework import statusfrom posthog.schema import HogQLQueryModifiers, MaterializationMode@@ -35,6 +38,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.models import ActivityLog, Comment, Organization, Tag, Team, Userfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.uploaded_media import UploadedMediafrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.redis import get_clientfrom posthog.test.persons import create_person@@ -65,6 +69,7 @@ from products.conversations.backend.reply_dedupe import (ReplyFingerprint,reserve,)+from products.conversations.backend.services.attachments import CONVERSATIONS_ATTACHMENT_MEDIA_PURPOSEfrom ee.clickhouse.materialized_columns.columns import get_bloom_filter_lower_index_name@@ -3406,6 +3411,116 @@ class TestTicketReplyAPI(APIBaseTest):assert Comment.objects.filter(scope="conversations_ticket", item_id=str(self.ticket.id)).count() == 1+def _png_bytes() -> bytes:+ buf = BytesIO()+ Image.new("RGB", (1, 1), color="red").save(buf, format="PNG")+ return buf.getvalue()+++@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")+class TestTicketAttachmentsAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.SLACK,+ widget_session_id="test-session",+ distinct_id="user-1",+ status=Status.OPEN,+ )+ self.url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/attachments/"++ def _upload(self, upload: SimpleUploadedFile, url: str | None = None):+ with self.settings(OBJECT_STORAGE_ENABLED=True):+ return self.client.post(url or self.url, {"file": upload}, format="multipart")++ @parameterized.expand(+ [+ ("pdf", "report.pdf", b"%PDF-1.4 test", "application/pdf", "application/pdf"),+ ("log", "server.log", b"line one\nline two", "text/plain", "text/plain"),+ ("png", "shot.png", None, "image/png", "image/png"),+ ]+ )+ def test_upload_stores_file(self, _mock_save, _name, file_name, content, declared_type, expected_type):+ upload = SimpleUploadedFile(file_name, content if content is not None else _png_bytes(), declared_type)++ response = self._upload(upload)++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ body = response.json()+ assert body["name"] == file_name+ assert body["content_type"] == expected_type+ media = UploadedMedia.objects.get(team=self.team, file_name=file_name)+ assert media.purpose == CONVERSATIONS_ATTACHMENT_MEDIA_PURPOSE+ assert media.content_type == expected_type+ assert body["id"] == str(media.id)+ assert body["url"] == media.get_absolute_url()++ def test_upload_rejects_widget_ticket(self, _mock_save):+ widget_ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="widget-session",+ distinct_id="user-2",+ status=Status.OPEN,+ )++ response = self._upload(+ SimpleUploadedFile("report.pdf", b"%PDF-1.4", "application/pdf"),+ url=f"/api/projects/{self.team.id}/conversations/tickets/{widget_ticket.id}/attachments/",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "channel_not_supported"+ assert not UploadedMedia.objects.filter(team=self.team).exists()++ def test_upload_rejects_disguised_image(self, _mock_save):+ response = self._upload(SimpleUploadedFile("shot.png", b"<script>alert(1)</script>", "image/png"))++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "invalid_image"+ assert not UploadedMedia.objects.filter(team=self.team).exists()++ def test_upload_rejects_large_file(self, _mock_save):+ with patch("products.conversations.backend.api.tickets.CONVERSATIONS_MAX_IMAGE_BYTES", 4):+ response = self._upload(SimpleUploadedFile("report.pdf", b"%PDF-1.4", "application/pdf"))++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "file_too_large"++ def test_upload_requires_object_storage(self, _mock_save):+ with self.settings(OBJECT_STORAGE_ENABLED=False):+ response = self.client.post(+ self.url, {"file": SimpleUploadedFile("report.pdf", b"%PDF-1.4", "application/pdf")}, format="multipart"+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "object_storage_required"++ def test_upload_requires_file(self, _mock_save):+ with self.settings(OBJECT_STORAGE_ENABLED=True):+ response = self.client.post(self.url, {}, format="multipart")++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_upload_cross_team_404(self, _mock_save):+ other_team = Team.objects.create(organization=self.organization, name="Other")+ other_ticket = Ticket.objects.create_with_number(+ team=other_team,+ channel_source=Channel.SLACK,+ widget_session_id="other-session",+ distinct_id="user-3",+ status=Status.OPEN,+ )++ response = self._upload(+ SimpleUploadedFile("report.pdf", b"%PDF-1.4", "application/pdf"),+ url=f"/api/projects/{self.team.id}/conversations/tickets/{other_ticket.id}/attachments/",+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND++@patch.object(transaction, "on_commit", side_effect=immediate_on_commit)class TestAiFeedbackAPI(APIBaseTest):def setUp(self):diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 70c1ad44e3eb..4f4160c1bd4a 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -7,6 +7,8 @@ from collections.abc import Callable, Sequencefrom datetime import datetimefrom typing import TYPE_CHECKING, Any, Literal, TypedDict, cast+from django.conf import settings+from django.core.files.uploadedfile import UploadedFilefrom django.db import transactionfrom django.db.models import Q, QuerySet, Sumfrom django.http import Http404@@ -29,7 +31,8 @@ from rest_framework import (viewsets,)from rest_framework.decorators import action-from rest_framework.exceptions import MethodNotAllowed, PermissionDenied, ValidationError+from rest_framework.exceptions import APIException, MethodNotAllowed, PermissionDenied, ValidationError+from rest_framework.parsers import MultiPartParserfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -101,6 +104,12 @@ from products.conversations.backend.models import ()from products.conversations.backend.models.constants import Channel, ChannelDetail, Status, TicketMessageTypefrom products.conversations.backend.person_lookup import _get_persons_by_email+from products.conversations.backend.services.attachments import (+ CONVERSATIONS_MAX_IMAGE_BYTES,+ resolve_attachment_content_type,+ sanitize_attachment_filename,+ save_uploaded_media,+)from products.conversations.backend.services.delivery import cancel_open_deliveries_for_ticketfrom products.conversations.backend.services.messages import ticket_message_typefrom products.conversations.backend.tasks.email import cancel_pending_email_replies_for_ticket@@ -257,6 +266,27 @@ class TicketReplyRequestSerializer(serializers.Serializer):return value+class TicketAttachmentUploadRequestSerializer(serializers.Serializer):+ file = serializers.FileField(allow_empty_file=False, help_text="File to attach.")++ def validate_file(self, value: UploadedFile) -> UploadedFile:+ if value.size is None or value.size > CONVERSATIONS_MAX_IMAGE_BYTES:+ raise serializers.ValidationError(+ f"Attachments must be under {CONVERSATIONS_MAX_IMAGE_BYTES // (1024 * 1024)} MiB.",+ code="file_too_large",+ )+ return value+++class TicketAttachmentSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="ID of the stored file.")+ url = serializers.CharField(help_text="Public download URL of the stored file.")+ name = serializers.CharField(help_text="Sanitized file name.")+ content_type = serializers.CharField(+ help_text="Stored content type. Inline-safe images come back as their decoded image type."+ )++class AiFeedbackRequestSerializer(serializers.Serializer):"""Payload for recording reviewer feedback on an AI reply."""@@ -768,6 +798,7 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro"patch","compose","reply",+ "attachments","ai_feedback","ai_human_outcome","note",@@ -789,9 +820,9 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControdef check_permissions(self, request: Request) -> None:super().check_permissions(request)if is_scout_sandbox_request(request):- if self.action in {"compose", "note", "delete_note"}:+ if self.action in {"compose", "note", "delete_note", "attachments"}:raise PermissionDenied(- "Scouts can add private notes but cannot compose emails or change existing notes."+ "Scouts can add private notes but cannot compose emails, upload files or change existing notes.")if self.action in {"update", "partial_update"} and "anonymous_traits" in request.data:raise PermissionDenied("Scouts cannot change customer identity fields.")@@ -1772,6 +1803,76 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControstatus=drf_status.HTTP_201_CREATED if created else drf_status.HTTP_200_OK,)+ @extend_schema(+ parameters=[TICKET_ID_PARAM],+ request={+ "multipart/form-data": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string",+ "format": "binary",+ "description": "File to attach. Must be under 20 MiB.",+ },+ },+ "required": ["file"],+ }+ },+ responses={+ 201: OpenApiResponse(response=TicketAttachmentSerializer),+ 400: OpenApiResponse(response=TicketErrorSerializer),+ },+ )+ @action(+ detail=True,+ methods=["post"],+ pagination_class=None,+ parser_classes=[MultiPartParser],+ throttle_classes=[ComposeTicketBurstThrottle, ComposeTicketSustainedThrottle],+ )+ def attachments(self, request, *args, **kwargs):+ """Upload a file to put in a reply to this ticket.++ Images are validated and shown inline. Other files are stored as they are and+ served as a download. Widget tickets do not accept file attachments yet.+ """+ ticket = self.get_object()++ if ticket.channel_source == Channel.WIDGET:+ raise ValidationError(code="channel_not_supported", detail="Widget tickets do not accept file attachments.")+ if not settings.OBJECT_STORAGE_ENABLED:+ raise ValidationError(+ code="object_storage_required", detail="Object storage must be available to attach files."+ )++ serializer = TicketAttachmentUploadRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ file = serializer.validated_data["file"]++ content = file.read()+ # Validate before saving, so a disguised image gets a clear 400 rather than a storage error.+ content_type = resolve_attachment_content_type(content, file.content_type or "application/octet-stream")+ if content_type is None:+ raise ValidationError(code="invalid_image", detail="The file is not a valid image.")++ uploaded_media = save_uploaded_media(+ self.team, sanitize_attachment_filename(file.name), content_type, content, validate_images=False+ )+ if uploaded_media is None:+ raise APIException("Could not store the file.")++ return Response(+ TicketAttachmentSerializer(+ {+ "id": uploaded_media.id,+ "url": uploaded_media.get_absolute_url(),+ "name": uploaded_media.file_name,+ "content_type": uploaded_media.content_type,+ }+ ).data,+ status=drf_status.HTTP_201_CREATED,+ )+@extend_schema(parameters=[TICKET_ID_PARAM],request=TicketNoteCreateRequestSerializer,diff --git a/products/conversations/backend/services/attachments.py b/products/conversations/backend/services/attachments.pyindex c888310077e4..98f74b701f29 100644--- a/products/conversations/backend/services/attachments.py+++ b/products/conversations/backend/services/attachments.py@@ -75,6 +75,21 @@ def save_file_to_uploaded_media("""Persist a file to object storage via UploadedMedia.Returns the absolute URL on success, None on failure.+ """+ uploaded_media = save_uploaded_media(team, file_name, content_type, content, validate_images=validate_images)+ return uploaded_media.get_absolute_url() if uploaded_media else None+++def save_uploaded_media(+ team: Team,+ file_name: str,+ content_type: str,+ content: bytes,+ *,+ validate_images: bool = True,+) -> UploadedMedia | None:+ """Persist a file to object storage via UploadedMedia, or return None on failure.+Unless validate_images is False, stores the type that resolve_attachment_content_typereturns, and rejects bytes that it finds invalid."""@@ -117,7 +132,7 @@ def save_file_to_uploaded_media(content_type=content_type,bytes_size=len(content),)- return uploaded_media.get_absolute_url()+ return uploaded_mediadef attachment_link_label(attachment: dict[str, Any]) -> str:diff --git a/products/conversations/frontend/components/Chat/ChatView.tsx b/products/conversations/frontend/components/Chat/ChatView.tsxindex a053cf4ad5d4..6d0ee60a36b5 100644--- a/products/conversations/frontend/components/Chat/ChatView.tsx+++ b/products/conversations/frontend/components/Chat/ChatView.tsx@@ -16,6 +16,7 @@ import type {TicketStatus,} from '../../types'import type { SimplifiedRepliesProps } from '../ComposerHeader/ComposerHeader'+import type { SupportEditorProps } from '../Editor'import { MessageInput } from './MessageInput'import { MessageList, type TimelineExtra } from './MessageList'@@ -98,6 +99,8 @@ export interface ChatViewProps {macroPicker?: React.ReactNodeenableMacros?: booleanonInsertMacro?: (macro: TicketMacroApi) => void+ /** Stores a file of any type for the reply. Leave unset to hide the attach button. */+ onAttachFile?: SupportEditorProps['onAttachFile']aiSources?: AITriageSource[]aiDraftApplying?: booleanonApplyAiDraft?: (message: ChatMessage) => void@@ -153,6 +156,7 @@ export function ChatView({composerInsertContent,macroPicker,enableMacros,+ onAttachFile,onInsertMacro,aiSources,aiDraftApplying,@@ -222,6 +226,7 @@ export function ChatView({composerInsertContent={composerInsertContent}macroPicker={macroPicker}enableMacros={enableMacros}+ onAttachFile={onAttachFile}onInsertMacro={onInsertMacro}/></div>diff --git a/products/conversations/frontend/components/Chat/MessageInput.tsx b/products/conversations/frontend/components/Chat/MessageInput.tsxindex 8cec2a67f642..4efc1592d413 100644--- a/products/conversations/frontend/components/Chat/MessageInput.tsx+++ b/products/conversations/frontend/components/Chat/MessageInput.tsx@@ -12,7 +12,7 @@ import type { TicketMacroApi } from 'products/conversations/frontend/generated/aimport type { TicketChannel, TicketStatus } from '../../types'import { channelIcon, getReplyPlaceholder, hasReplyChannelBranding } from '../Channels/ChannelsTag'import { ComposerHeader, SimplifiedRepliesProps } from '../ComposerHeader/ComposerHeader'-import { SupportEditor, serializeToMarkdown } from '../Editor'+import { SupportEditor, type SupportEditorProps, serializeToMarkdown } from '../Editor'import { SendMenu } from '../SendMenu/SendMenu'export interface MessageInputProps {@@ -39,6 +39,8 @@ export interface MessageInputProps {isPrivate?: boolean/** Called when private checkbox changes */onPrivateChange?: (isPrivate: boolean) => void+ /** Stores a file of any type for the reply. Leave unset to hide the attach button. */+ onAttachFile?: SupportEditorProps['onAttachFile']/** Extra actions rendered next to the send button */extraActions?: React.ReactNode/** Blocks sending customer-facing messages (private notes stay available). Shown as the button's disabled tooltip. */@@ -105,6 +107,7 @@ export function MessageInput({composerInsertContent = null,macroPicker,enableMacros = false,+ onAttachFile,onInsertMacro,simplifiedReplies,}: MessageInputProps): JSX.Element {@@ -315,7 +318,7 @@ export function MessageInput({: isEmpty? 'No message': isUploading- ? 'Uploading image...'+ ? 'Uploading file...': undefinedconst sendControlDisabledReason =typeof sendDisabledReason === 'string'@@ -386,6 +389,7 @@ export function MessageInput({}}}onUploadingChange={setIsUploading}+ onAttachFile={onAttachFile}disabled={messageSending || !!sendDisabledReason}minRows={minRows}enableMacros={enableMacros}diff --git a/products/conversations/frontend/components/Editor/SupportEditor.tsx b/products/conversations/frontend/components/Editor/SupportEditor.tsxindex 3ba18b884ef8..28b8e5eed35e 100644--- a/products/conversations/frontend/components/Editor/SupportEditor.tsx+++ b/products/conversations/frontend/components/Editor/SupportEditor.tsx@@ -21,7 +21,7 @@ import { common, createLowlight } from 'lowlight'import posthog from 'posthog-js'import { useCallback, useEffect, useRef, useState, type CSSProperties } from 'react'-import { IconCode, IconCopy, IconImage, IconList, IconTerminal } from '@posthog/icons'+import { IconCode, IconCopy, IconDocument, IconImage, IconList, IconTerminal } from '@posthog/icons'import { EmojiPickerPopover } from 'lib/components/EmojiPicker/EmojiPickerPopover'import { useRichContentEditor } from 'lib/components/RichContentEditor'@@ -159,6 +159,8 @@ export type SupportEditorProps = {onPressCmdEnter?: () => void/** Called when upload state changes (true = uploading, false = idle) */onUploadingChange?: (uploading: boolean) => void+ /** Stores a file of any type. When set, the toolbar can attach files, which go into the message as download links. */+ onAttachFile?: (file: File) => Promise<SupportEditorAttachment>disabled?: booleanminRows?: number/** Past this, the text scrolls so the toolbar and send bar stay on screen. */@@ -172,6 +174,15 @@ export type SupportEditorProps = {onInsertMacro?: (macro: TicketMacroApi) => void}+export type SupportEditorAttachment = {+ id: string+ url: string+ name: string+}++// Matches CONVERSATIONS_MAX_IMAGE_BYTES on the backend, which rejects anything larger.+const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024+const DEFAULT_INITIAL_CONTENT: JSONContent = {type: 'doc',content: [@@ -486,6 +497,7 @@ export function SupportEditor({onUpdate,onPressCmdEnter,onUploadingChange,+ onAttachFile,disabled = false,minRows,maxRows = 12,@@ -575,10 +587,42 @@ export function SupportEditor({linkShortcutCallbackRef.current = openLinkPopover}, [openLinkPopover])+ const {+ setFilesToUpload: setFilesToAttach,+ filesToUpload: filesToAttach,+ uploading: attaching,+ } = useUploadFiles({+ uploadFn: onAttachFile+ ? async (file) => {+ if (file.size > MAX_ATTACHMENT_BYTES) {+ throw new Error('File is larger than 20 MiB')+ }+ const attachment = await onAttachFile(file)+ return { id: attachment.id, image_location: attachment.url, name: attachment.name }+ }+ : undefined,+ onUpload: (url, fileName) => {+ // Same shape as files that arrive from Slack, Teams and email, so every channel renders it as a link.+ ttEditor+ ?.chain()+ .focus()+ .insertContent({+ type: 'paragraph',+ content: [{ type: 'text', text: fileName, marks: [{ type: 'link', attrs: { href: url } }] }],+ })+ .run()+ posthog.capture('support reply file attached')+ },+ onError: (detail) => {+ posthog.capture('support reply file attach failed', { error: detail })+ lemonToast.error(`Error attaching file: ${detail}`)+ },+ })+// Notify parent of upload state changesuseEffect(() => {- onUploadingChange?.(uploading)- }, [uploading, onUploadingChange])+ onUploadingChange?.(uploading || attaching)+ }, [uploading, attaching, onUploadingChange])const handleDragEnter = (e: React.DragEvent): void => {e.preventDefault()@@ -800,6 +844,34 @@ export function SupportEditor({/>}/>+ {onAttachFile && (+ <LemonFileInput+ key="file-attach"+ accept=""+ multiple={false}+ onChange={setFilesToAttach}+ loading={attaching}+ value={filesToAttach}+ showUploadedFiles={false}+ callToAction={+ <LemonButton+ size="small"+ icon={+ attaching ? (+ <Spinner className="text-lg" textColored={true} />+ ) : (+ <IconDocument className="text-lg" />+ )+ }+ disabledReason={+ objectStorageAvailable ? undefined : 'Enable object storage to attach files'+ }+ tooltip={objectStorageAvailable ? 'Attach a file (max 20 MiB)' : null}+ data-attr="support-editor-attach-file"+ />+ }+ />+ )}<EmojiPickerPopoverkey="emoj-picker"data-attr="lemon-rich-text-editor-emoji-popover"diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex a84dd0a8f956..007ea53727a0 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -634,6 +634,17 @@ export interface TicketErrorApi {error_type?: string}+export interface TicketAttachmentApi {+ /** ID of the stored file. */+ id: string+ /** Public download URL of the stored file. */+ url: string+ /** Sanitized file name. */+ name: string+ /** Stored content type. Inline-safe images come back as their decoded image type. */+ content_type: string+}+/*** * `customer_message` - Customer message* * `sent_reply` - Sent reply@@ -1297,6 +1308,11 @@ export const ConversationsTicketsListSla = {OnTrack: 'on-track',} as const+export type ConversationsTicketsAttachmentsCreateBody = {+ /** File to attach. Must be under 20 MiB. */+ file: Blob+}+export type ConversationsTicketsMessagesListParams = {/*** Number of results to return per page.diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex 12bd142640de..0153e88b417a 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -20,6 +20,7 @@ import type {ComposeTicketApi,ComposeTicketResponseApi,ConversationsMacrosListParams,+ ConversationsTicketsAttachmentsCreateBody,ConversationsTicketsListParams,ConversationsTicketsMessagesListParams,ConversationsViewsListParams,@@ -33,6 +34,7 @@ import type {PatchedTicketViewApi,SigningSecretApi,TicketApi,+ TicketAttachmentApi,TicketFullEmailApi,TicketMacroApi,TicketMessageApi,@@ -401,6 +403,34 @@ export const conversationsTicketsAiHumanOutcomeCreate = async (})}+export const getConversationsTicketsAttachmentsCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/conversations/tickets/${id}/attachments/`+}++/**+ * Upload a file to put in a reply to this ticket.+ *+ * Images are validated and shown inline. Other files are stored as they are and+ * served as a download. Widget tickets do not accept file attachments yet.+ */+export const conversationsTicketsAttachmentsCreate = async (+ projectId: string,+ id: string,+ conversationsTicketsAttachmentsCreateBody?: ConversationsTicketsAttachmentsCreateBody,+ options?: RequestInit+): Promise<TicketAttachmentApi> => {+ const formData = new FormData()+ if (conversationsTicketsAttachmentsCreateBody?.file !== undefined) {+ formData.append(`file`, conversationsTicketsAttachmentsCreateBody.file)+ }++ return apiMutator<TicketAttachmentApi>(getConversationsTicketsAttachmentsCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ body: formData,+ })+}+export const getConversationsTicketsMessagesListUrl = (projectId: string,id: string,diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex 493900695f9a..7df53d89d9cd 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -227,6 +227,16 @@ export const ConversationsTicketsAiHumanOutcomeCreateBody = /* @__PURE__ */ zod}).describe('Payload for recording whether a human adopted an AI draft.')+/**+ * Upload a file to put in a reply to this ticket.+ *+ * Images are validated and shown inline. Other files are stored as they are and+ * served as a download. Widget tickets do not accept file attachments yet.+ */+export const ConversationsTicketsAttachmentsCreateBody = /* @__PURE__ */ zod.object({+ file: zod.instanceof(File).describe('File to attach. Must be under 20 MiB.'),+})+/*** Add a private note to a ticket.*diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex 7ecd3ba6c6bb..6855e1ea0b68 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -14,6 +14,7 @@ import { Resizer } from 'lib/lemon-ui/Resizer/Resizer'import { ResizerLogicProps, resizerLogic } from 'lib/lemon-ui/Resizer/resizerLogic'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { getAccessControlDisabledReason, accessLevelSatisfied } from 'lib/utils/accessControlUtils'+import { getCurrentTeamId } from 'lib/utils/getAppContext'import { newInternalTab } from 'lib/utils/newInternalTab'import { SceneExport } from 'scenes/sceneTypes'import { teamLogic } from 'scenes/teamLogic'@@ -25,6 +26,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType, Breadcrumb } from '~/types'+import { conversationsTicketsAttachmentsCreate } from 'products/conversations/frontend/generated/api'import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplay'import { AssigneeIconDisplay, AssigneeLabelDisplay, AssigneeSelect } from '../../components/Assignee'@@ -179,6 +181,11 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elemconst { featureFlags } = useValues(featureFlagLogic)const simplifiedReplies = !!featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_SIMPLIFIED_REPLIES]const macrosEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_MACROS]+ // Widget tickets stay images only until the widget can render file links.+ const canAttachFiles =+ !!featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_REPLY_FILE_ATTACHMENTS] &&+ !!ticket &&+ ticket.channel_source !== 'widget'const { currentTeam } = useValues(teamLogic)const aiSuggestionsEnabled = !!currentTeam?.conversations_settings?.ai_suggestions_enabled@@ -349,6 +356,14 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemcomposerInsertAt={composerInsertAt}composerInsertContent={pendingComposerInsert}enableMacros={macrosEnabled}+ onAttachFile={+ canAttachFiles+ ? (file) =>+ conversationsTicketsAttachmentsCreate(String(getCurrentTeamId()), ticketId, {+ file,+ })+ : undefined+ }onInsertMacro={macrosEnabled ? (macro) => insertMacro(macro, 'slash') : undefined}macroPicker={macrosEnabled ? (diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7fceaff1fd57..1552b4222611 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -111700,6 +111700,17 @@ export namespace Schemas {metadata: TextReprMetadata;}+ export interface TicketAttachment {+ /** ID of the stored file. */+ id: string;+ /** Public download URL of the stored file. */+ url: string;+ /** Sanitized file name. */+ name: string;+ /** Stored content type. Inline-safe images come back as their decoded image type. */+ content_type: string;+ }+export interface TicketError {/** Human-readable error message. */detail: string;@@ -122305,6 +122316,11 @@ export namespace Schemas {OnTrack: 'on-track',} as const;+ export type ConversationsTicketsAttachmentsCreateBody = {+ /** File to attach. Must be under 20 MiB. */+ file: Blob;+ };+export type ConversationsTicketsMessagesListParams = {/*** Number of results to return per page.