: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): add send-and-set-status options to composer (#72280)
Xanderaadf5360f447
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex ca913cf47beb..0cefca7eca8a 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5565,7 +5565,7 @@ snapshots:scenes-app-dashboards--show-without-post-hog-ai-button-label--narrow--dark:hash: v1.k794b7964.88687d2cc1bbd12296214f07d5f6bb2548705ae3baae37985858225116896a10.YogXGZXR1uFB4qD8nOjCfWyWL--g1SLKNxz0gZvEoWwscenes-app-dashboards--show-without-post-hog-ai-button-label--narrow--light:- hash: v1.k794b7964.2035f84708f35d51de9ca7ce036c497c17d8a812e4a64c682d76caa066cb0954._S1SJobvQ3RqTPgANTGgE3vUYRijIBEFRYinuHFsQIA+ hash: v1.k794b7964.e73cea1e916b6bc329aea490ca111439f3bebfa3dbae2d54ad54e5a174651057.7cswn9IwKIF60hyao0mI2skKmlWjur4GWI1cCisomlEscenes-app-dashboards--show-without-post-hog-ai-button-label--superwide--dark:hash: v1.k794b7964.cad32a04659183c6bfecbc34e5ae23c08c095f70df65ef0ee7d863d2103a124d.2bYQoklhY3opedkpy5pUC52pEvCwdnEfKowjCBPaDb8scenes-app-dashboards--show-without-post-hog-ai-button-label--superwide--light:diff --git a/products/conversations/frontend/components/Chat/ChatView.tsx b/products/conversations/frontend/components/Chat/ChatView.tsxindex 0d833e312942..b3e0251f2b1a 100644--- a/products/conversations/frontend/components/Chat/ChatView.tsx+++ b/products/conversations/frontend/components/Chat/ChatView.tsx@@ -2,7 +2,7 @@ import { JSONContent } from '@tiptap/core'import { LemonCard } from '@posthog/lemon-ui'-import type { AiReplyFeedbackRating, ChatMessage, Ticket } from '../../types'+import type { AiReplyFeedbackRating, ChatMessage, Ticket, TicketStatus } from '../../types'import { MessageInput } from './MessageInput'import { MessageList } from './MessageList'@@ -13,7 +13,13 @@ export interface ChatViewProps {hasMoreMessages?: booleanolderMessagesLoading?: booleanticket?: Ticket- onSendMessage: (content: string, richContent: JSONContent | null, isPrivate: boolean, onSuccess: () => void) => void+ onSendMessage: (+ content: string,+ richContent: JSONContent | null,+ isPrivate: boolean,+ onSuccess: () => void,+ statusAfterSend?: TicketStatus+ ) => voidonLoadOlderMessages?: () => voidheader?: React.ReactNodeminHeight?: string@@ -42,6 +48,10 @@ export interface ChatViewProps {onDraftModeChange?: (enabled: boolean) => void/** Recipient description shown in the draft-mode send confirmation */sendConfirmationMessage?: string+ /** When provided, renders a dropdown next to the send button to send and set the ticket status in one go */+ sendAndSetStatusOptions?: { value: TicketStatus; label: string }[]+ /** Other unsaved ticket edits that sending with a status would also persist */+ unsavedTicketChanges?: string[]latestAiMessageId?: string | nullfeedbackByMessageId?: Record<string, AiReplyFeedbackRating>showAiReplyFeedback?: boolean@@ -71,6 +81,8 @@ export function ChatView({draftMode,onDraftModeChange,sendConfirmationMessage,+ sendAndSetStatusOptions,+ unsavedTicketChanges,latestAiMessageId,feedbackByMessageId,showAiReplyFeedback,@@ -112,6 +124,8 @@ export function ChatView({draftMode={draftMode}onDraftModeChange={onDraftModeChange}sendConfirmationMessage={sendConfirmationMessage}+ sendAndSetStatusOptions={sendAndSetStatusOptions}+ unsavedTicketChanges={unsavedTicketChanges}/></div></LemonCard>diff --git a/products/conversations/frontend/components/Chat/MessageInput.tsx b/products/conversations/frontend/components/Chat/MessageInput.tsxindex 119fc8356796..4495ca121947 100644--- a/products/conversations/frontend/components/Chat/MessageInput.tsx+++ b/products/conversations/frontend/components/Chat/MessageInput.tsx@@ -7,10 +7,17 @@ import { LemonButton, LemonCheckbox, LemonSwitch, Tooltip } from '@posthog/lemonimport { RichContentEditorType } from 'lib/components/RichContentEditor/types'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import type { TicketStatus } from '../../types'import { SupportEditor, serializeToMarkdown } from '../Editor'export interface MessageInputProps {- onSendMessage: (content: string, richContent: JSONContent | null, isPrivate: boolean, onSuccess: () => void) => void+ onSendMessage: (+ content: string,+ richContent: JSONContent | null,+ isPrivate: boolean,+ onSuccess: () => void,+ statusAfterSend?: TicketStatus+ ) => voidmessageSending: booleanplaceholder?: stringbuttonText?: string@@ -35,6 +42,10 @@ export interface MessageInputProps {onDraftModeChange?: (enabled: boolean) => void/** Recipient description shown in the draft-mode send confirmation (e.g. "This will send to ...") */sendConfirmationMessage?: string+ /** When provided, renders a dropdown next to the send button to send and set the ticket status in one go */+ sendAndSetStatusOptions?: { value: TicketStatus; label: string }[]+ /** Other unsaved ticket edits that sending with a status would also persist; when non-empty, asks for confirmation first */+ unsavedTicketChanges?: string[]}export function MessageInput({@@ -53,6 +64,8 @@ export function MessageInput({draftMode = false,onDraftModeChange,sendConfirmationMessage,+ sendAndSetStatusOptions,+ unsavedTicketChanges,}: MessageInputProps): JSX.Element {const [isEmpty, setIsEmpty] = useState(!draftContent)const [isUploading, setIsUploading] = useState(false)@@ -67,7 +80,7 @@ export function MessageInput({const isPrivate = controlledIsPrivate ?? localIsPrivateconst setIsPrivate = onPrivateChange ?? setLocalIsPrivate- const handleSubmit = (): void => {+ const handleSubmit = (statusAfterSend?: TicketStatus): void => {// These guard the Cmd+Enter path, which bypasses the (disabled) button.if (replyDisabledReason && !isPrivate) {return@@ -79,19 +92,45 @@ export function MessageInput({const richContent = editorRef.current.getJSON()const content = serializeToMarkdown(richContent)const doSend = (): void => {- onSendMessage(content, richContent, isPrivate, () => {- editorRef.current?.clear()- setIsEmpty(true)- onDraftChange?.(null)- if (onPrivateChange) {- onPrivateChange(false)- } else {- setLocalIsPrivate(false)- }- })+ onSendMessage(+ content,+ richContent,+ isPrivate,+ () => {+ editorRef.current?.clear()+ setIsEmpty(true)+ onDraftChange?.(null)+ if (onPrivateChange) {+ onPrivateChange(false)+ } else {+ setLocalIsPrivate(false)+ }+ },+ statusAfterSend+ )}- // Private notes are never sent externally, so they skip the draft-mode confirmation.- if (draftMode && !isPrivate && sendConfirmationMessage) {+ // Sending with a status saves the whole ticket, so surface any other unsaved edits first.+ if (statusAfterSend && unsavedTicketChanges && unsavedTicketChanges.length > 0) {+ LemonDialog.open({+ title: 'Send and save other changes?',+ description: (+ <>+ <p>Sending will also save your other unsaved ticket changes:</p>+ <ul className="list-disc pl-5">+ {unsavedTicketChanges.map((change) => (+ <li key={change}>{change}</li>+ ))}+ </ul>+ {draftMode && !isPrivate && sendConfirmationMessage ? (+ <p>{sendConfirmationMessage}</p>+ ) : null}+ </>+ ),+ primaryButton: { children: 'Send and save', type: 'primary', onClick: doSend },+ secondaryButton: { children: 'Cancel' },+ })+ } else if (draftMode && !isPrivate && sendConfirmationMessage) {+ // Private notes are never sent externally, so they skip the draft-mode confirmation.LemonDialog.open({title: 'Ready to send?',description: sendConfirmationMessage,@@ -111,6 +150,15 @@ export function MessageInput({}}+ const sendBlockedReason =+ replyDisabledReason && !isPrivate+ ? replyDisabledReason+ : isEmpty+ ? 'No message'+ : isUploading+ ? 'Uploading image...'+ : undefined+return (<div><SupportEditor@@ -123,7 +171,7 @@ export function MessageInput({}}}onUpdate={handleUpdate}- onPressCmdEnter={handleSubmit}+ onPressCmdEnter={() => handleSubmit()}onUploadingChange={setIsUploading}disabled={messageSending}minRows={minRows}@@ -165,16 +213,30 @@ export function MessageInput({{extraActions}<LemonButtontype="primary"- onClick={handleSubmit}+ onClick={() => handleSubmit()}loading={messageSending}- disabledReason={- replyDisabledReason && !isPrivate- ? replyDisabledReason- : isEmpty- ? 'No message'- : isUploading- ? 'Uploading image...'- : undefined+ disabledReason={sendBlockedReason}+ sideAction={+ sendAndSetStatusOptions?.length+ ? {+ 'aria-label': 'Send and set ticket status',+ disabled: messageSending,+ disabledReason: sendBlockedReason,+ dropdown: {+ placement: 'bottom-end',+ overlay: sendAndSetStatusOptions.map((option) => (+ <LemonButton+ key={option.value}+ fullWidth+ size="small"+ onClick={() => handleSubmit(option.value)}+ >+ {option.label}+ </LemonButton>+ )),+ },+ }+ : undefined}>{isPrivate ? 'Attach' : buttonText}diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex 109615a52f17..12a83a534d9b 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -58,6 +58,12 @@ function getChannelThreadUrl(ticket: Ticket | null): string | undefined {return undefined}+const SEND_AND_SET_STATUS_OPTIONS: { value: TicketStatus; label: string }[] = [+ { value: 'pending', label: 'Send and set pending' },+ { value: 'on_hold', label: 'Send and set on hold' },+ { value: 'resolved', label: 'Send and set resolved' },+]+export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Element {const logic = supportTicketSceneLogic({ id: ticketId || 'new' })const {@@ -79,6 +85,8 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemexceptionsQuery,chatPanelWidth,hasUnsavedChanges,+ unsavedTicketChanges,+ ticketUpdating,draftContent,draftIsPrivate,draftModeEnabled,@@ -215,6 +223,8 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemdraftMode={draftModeEnabled}onDraftModeChange={setDraftModeEnabled}sendConfirmationMessage={`This will send to ${replyRecipientDescription}`}+ sendAndSetStatusOptions={ticket ? SEND_AND_SET_STATUS_OPTIONS : undefined}+ unsavedTicketChanges={unsavedTicketChanges}replyDisabledReason={replyDisabledReason}minHeight="min(400px, calc(100svh - 20rem))"maxHeight="calc(100svh - 20rem)"@@ -458,6 +468,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elemtype="primary"size="small"onClick={() => updateTicket()}+ loading={ticketUpdating}disabledReason={!hasUnsavedChanges ? 'No changes to save' : undefined}>Save changesdiff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.tsindex da2545f77141..bf6548a62dbc 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -1,9 +1,12 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'+import { expectLogic } from 'kea-test-utils'import { initKeaTests } from '~/test/init'import type { CommentType } from '~/types'-import type { Ticket } from '../../types'+import type { TicketAssignee } from '../../components/Assignee'+import type { Ticket, TicketStatus } from '../../types'import { EmailReplyBlockedReason, getEmailReplyBlockedReason, supportTicketSceneLogic } from './supportTicketSceneLogic'const FEEDBACK_STORAGE_KEY = 'conversations_ai_reply_feedback'@@ -14,14 +17,31 @@ jest.mock('~/lib/api', () => {__esModule: true,default: {...actual.default,+ comments: {+ ...actual.default?.comments,+ create: jest.fn().mockResolvedValue(undefined),+ list: jest.fn().mockResolvedValue({ results: [] }),+ },+ persons: {+ ...actual.default?.persons,+ list: jest.fn().mockResolvedValue({ results: [] }),+ },conversationsTickets: {...actual.default?.conversationsTickets,submitAiFeedback: jest.fn().mockResolvedValue(undefined),+ get: jest.fn(),+ update: jest.fn(),+ list: jest.fn().mockResolvedValue({ results: [] }),},},}})+jest.mock('products/business_knowledge/frontend/generated/api', () => ({+ businessKnowledgeGapSuggestionsList: jest.fn().mockResolvedValue({ results: [] }),+ businessKnowledgeGapSuggestionsDismissCreate: jest.fn().mockResolvedValue(undefined),+}))+import api from '~/lib/api'const submitAiFeedbackMock = api.conversationsTickets.submitAiFeedback as jest.Mock@@ -249,3 +269,109 @@ describe('supportTicketSceneLogic replyRecipientDescription', () => {expect(logic.values.replyRecipientDescription).toBe(expected)})})++describe('supportTicketSceneLogic sendMessage with statusAfterSend', () => {+ let logic: ReturnType<typeof supportTicketSceneLogic.build>++ const commentsCreateMock = api.comments.create as jest.Mock+ const ticketGetMock = api.conversationsTickets.get as jest.Mock+ const ticketUpdateMock = api.conversationsTickets.update as jest.Mock++ // Unlike makeTicket(), API responses always carry priority/assignee; without them the+ // hasUnsavedChanges comparison against the seeded local reducers never settles to false.+ const loadedTicket = (): Ticket => ({ ...makeTicket(), priority: 'medium', assignee: null }) as Ticket++ beforeEach(async () => {+ initKeaTests()+ commentsCreateMock.mockReset().mockResolvedValue(undefined)+ ticketGetMock.mockReset().mockResolvedValue(loadedTicket())+ ticketUpdateMock.mockReset()+ // A non-'new', dash-free id: sendMessage early-returns on 'new' and loadTicket+ // treats ids containing '-' as UUIDs to redirect.+ logic = supportTicketSceneLogic({ id: 42 })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['setTicket'])+ })++ // "Send and set status" must persist through the same PATCH as the "Save changes" button,+ // and auto-assign the current user unless a specific user is already assigned.+ test.each<[string, TicketAssignee, TicketStatus, TicketAssignee]>([+ ['auto-assigns the current user when unassigned', null, 'resolved', { type: 'user', id: MOCK_DEFAULT_USER.id }],+ [+ 'replaces a role assignee with the current user',+ { type: 'role', id: 'role-1' },+ 'on_hold',+ { type: 'user', id: MOCK_DEFAULT_USER.id },+ ],+ ['keeps an existing user assignee', { type: 'user', id: 999 }, 'pending', { type: 'user', id: 999 }],+ ])('%s', async (_name, presetAssignee, statusAfterSend, expectedAssignee) => {+ if (presetAssignee) {+ logic.actions.setAssignee(presetAssignee)+ }+ ticketUpdateMock.mockResolvedValue({ ...loadedTicket(), status: statusAfterSend, assignee: expectedAssignee })++ await expectLogic(logic, () => {+ logic.actions.sendMessage('hello', null, false, undefined, statusAfterSend)+ }).toDispatchActions(['updateTicket', 'setTicket'])++ expect(ticketUpdateMock).toHaveBeenCalledWith(+ '42',+ expect.objectContaining({ status: statusAfterSend, assignee: expectedAssignee })+ )+ expect(logic.values.status).toBe(statusAfterSend)+ expect(logic.values.hasUnsavedChanges).toBe(false)+ })++ it('does not update the ticket when the send fails', async () => {+ commentsCreateMock.mockRejectedValue(new Error('request failed'))++ await expectLogic(logic, () => {+ logic.actions.sendMessage('hello', null, false, undefined, 'resolved')+ }).toFinishAllListeners()++ expect(ticketUpdateMock).not.toHaveBeenCalled()+ expect(logic.values.status).toBe('open')+ })++ // The send-and-set confirmation lists exactly the pending non-status edits; status is+ // excluded because that action overrides it anyway. Drift here silently persists edits+ // without warning (or prompts when there is nothing extra to save).+ test.each<[string, () => void, string[]]>([+ ['a priority edit', () => logic.actions.setPriority('high'), ['Priority: High']],+ ['a tags edit', () => logic.actions.setTags(['bug']), ['Tags: bug']],+ ['an assignee edit', () => logic.actions.setAssignee({ type: 'role', id: 'role-1' }), ['Assignee: updated']],+ ['a status-only edit', () => logic.actions.setStatus('pending'), []],+ ])('unsavedTicketChanges lists %s', (_name, applyEdit, expected) => {+ applyEdit()+ expect(logic.values.unsavedTicketChanges).toEqual(expected)+ })++ // Overlapping updates must serialize: the second PATCH waits for the first and carries the+ // newest local edits, and the first (stale) response must not clobber them via setTicket.+ it('serializes overlapping updates so the newest status wins', async () => {+ let resolveFirst: (() => void) | undefined+ ticketUpdateMock.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirst = () => resolve({ ...loadedTicket(), status: 'resolved' })+ })+ )+ ticketUpdateMock.mockImplementationOnce((_id: string, data: Record<string, unknown>) =>+ Promise.resolve({ ...loadedTicket(), ...data })+ )++ logic.actions.setStatus('resolved')+ logic.actions.updateTicket()+ logic.actions.setStatus('pending')+ logic.actions.updateTicket()++ expect(ticketUpdateMock).toHaveBeenCalledTimes(1)+ resolveFirst?.()+ await expectLogic(logic).toFinishAllListeners()++ expect(ticketUpdateMock).toHaveBeenCalledTimes(2)+ expect(ticketUpdateMock).toHaveBeenLastCalledWith('42', expect.objectContaining({ status: 'pending' }))+ expect(logic.values.status).toBe('pending')+ expect(logic.values.ticketUpdating).toBe(false)+ })+})diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 58279c9a9b26..4bb0c22b53ac 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -21,8 +21,10 @@ import { lemonToast } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { isUUIDLike } from 'lib/utils/guards'+import { fullName } from 'lib/utils/strings'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { impersonationNoticeLogic } from '~/layout/navigation/ImpersonationNotice/impersonationNoticeLogic'import api from '~/lib/api'@@ -39,8 +41,11 @@ import {} from 'products/business_knowledge/frontend/generated/api'import type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'-import type { TicketAssignee } from '../../components/Assignee'+import type { UserType } from '../../../../../frontend/src/types'+import { assigneeSelectLogic } from '../../components/Assignee'+import type { Assignee, TicketAssignee } from '../../components/Assignee'import { supportTicketCounterLogic } from '../../supportTicketCounterLogic'+import { priorityOptions } from '../../types'import type {AiReplyFeedbackRating,ChatMessage,@@ -164,8 +169,10 @@ export function getEmailReplyBlockedReason(// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface supportTicketSceneLogicValues {+ resolveAssignee: (assignee: TicketAssignee) => Assignee // assigneeSelectLogicdraftModeDefault: boolean // conversationsDraftModeLogiccurrentTeam: TeamPublicType | TeamType | null // teamLogic+ user: UserType | null // userLogicassignee: TicketAssigneebreadcrumbs: Breadcrumb[]chatMessages: ChatMessage[]@@ -198,6 +205,8 @@ export interface supportTicketSceneLogicValues {tags: string[]ticket: Ticket | nullticketLoading: boolean+ ticketUpdating: boolean+ unsavedTicketChanges: string[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -294,12 +303,14 @@ export interface supportTicketSceneLogicActions {content: string,richContent: Record<string, unknown> | null,isPrivate: boolean,- onSuccess?: () => void+ onSuccess?: () => void,+ statusAfterSend?: TicketStatus) => {content: stringisPrivate: booleanonSuccess: (() => void) | undefinedrichContent: Record<string, unknown> | null+ statusAfterSend: TicketStatus | undefined}setAssignee: (assignee: TicketAssignee) => {assignee: TicketAssignee@@ -349,6 +360,9 @@ export interface supportTicketSceneLogicActions {setTicketLoading: (loading: boolean) => {loading: boolean}+ setTicketUpdating: (updating: boolean) => {+ updating: boolean+ }submitAiReplyFeedback: (messageId: string,rating: AiReplyFeedbackRating,@@ -378,13 +392,18 @@ export interface supportTicketSceneLogicMeta {currentTeam: TeamPublicType | TeamType | null) => EmailReplyBlockedReason | nullreplyRecipientDescription: (ticket: Ticket | null) => string- hasUnsavedChanges: (- status: TicketStatus | null,+ unsavedTicketChanges: (priority: TicketPriority | null,assignee: TicketAssignee,tags: string[],snoozedUntil: string | null,- ticket: Ticket | null+ ticket: Ticket | null,+ resolveAssignee: (assignee: TicketAssignee) => Assignee // assigneeSelectLogic+ ) => string[]+ hasUnsavedChanges: (+ status: TicketStatus | null,+ ticket: Ticket | null,+ unsavedTicketChanges: string[]) => booleanhasPendingWork: (hasUnsavedChanges: boolean) => booleanchatMessages: (messages: CommentType[], ticket: Ticket | null) => ChatMessage[]@@ -407,7 +426,16 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([key((props) => props.id),connect(() => ({actions: [supportTicketsSceneLogic, ['loadTickets']],- values: [teamLogic, ['currentTeam'], conversationsDraftModeLogic, ['draftModeDefault']],+ values: [+ teamLogic,+ ['currentTeam'],+ conversationsDraftModeLogic,+ ['draftModeDefault'],+ userLogic,+ ['user'],+ assigneeSelectLogic,+ ['resolveAssignee'],+ ],})),actions({loadTicket: true,@@ -415,6 +443,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([setTicketLoading: (loading: boolean) => ({ loading }),incrementUnreadCustomerCount: true,updateTicket: true,+ setTicketUpdating: (updating: boolean) => ({ updating }),loadMessages: true,setMessages: (messages: CommentType[]) => ({ messages }),@@ -429,12 +458,14 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([content: string,richContent: Record<string, unknown> | null,isPrivate: boolean,- onSuccess?: () => void+ onSuccess?: () => void,+ statusAfterSend?: TicketStatus) => ({content,richContent,isPrivate,onSuccess,+ statusAfterSend,}),setMessageSending: (sending: boolean) => ({ sending }),@@ -557,6 +588,14 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([state ? { ...state, unread_customer_count: state.unread_customer_count + 1 } : state,},],+ ticketUpdating: [+ false,+ {+ updateTicket: () => true,+ setTicketUpdating: (_, { updating }) => updating,+ setTicket: () => false,+ },+ ],ticketLoading: [false,{@@ -710,27 +749,60 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([}},],- hasUnsavedChanges: [- (s) => [s.status, s.priority, s.assignee, s.tags, s.snoozedUntil, s.ticket],+ // Human-readable list of unsaved edits other than status, shown in the send-and-set-status+ // confirmation. Status is excluded because that action overrides it anyway.+ unsavedTicketChanges: [+ (s) => [s.priority, s.assignee, s.tags, s.snoozedUntil, s.ticket, s.resolveAssignee],(- status: TicketStatus | null,priority: TicketPriority | null,assignee: TicketAssignee,tags: string[],snoozedUntil: string | null,- ticket: Ticket | null- ): boolean => {+ ticket: Ticket | null,+ resolveAssignee: (assignee: TicketAssignee) => Assignee+ ): string[] => {if (!ticket) {- return false+ return []+ }+ const changes: string[] = []+ if (priority && priority !== ticket.priority) {+ changes.push(`Priority: ${priorityOptions.find((o) => o.value === priority)?.label ?? priority}`)+ }+ if (JSON.stringify(assignee) !== JSON.stringify(ticket.assignee)) {+ const resolved = resolveAssignee(assignee)+ const label =+ resolved?.type === 'user'+ ? fullName(resolved.user) || resolved.user.email+ : resolved?.type === 'role'+ ? resolved.role.name+ : assignee+ ? 'updated'+ : 'unassigned'+ changes.push(`Assignee: ${label}`)}- return (- status !== ticket.status ||- priority !== ticket.priority ||- JSON.stringify(assignee) !== JSON.stringify(ticket.assignee) ||- JSON.stringify([...tags].sort()) !== JSON.stringify([...(ticket.tags || [])].sort()) ||+ if (JSON.stringify([...tags].sort()) !== JSON.stringify([...(ticket.tags || [])].sort())) {+ changes.push(tags.length > 0 ? `Tags: ${tags.join(', ')}` : 'Tags: none')+ }+ if ((snoozedUntil ? dayjs(snoozedUntil).unix() : null) !==- (ticket.snoozed_until ? dayjs(ticket.snoozed_until).unix() : null)- )+ (ticket.snoozed_until ? dayjs(ticket.snoozed_until).unix() : null)+ ) {+ changes.push(+ snoozedUntil+ ? `Snoozed until ${dayjs(snoozedUntil).format('D MMM YYYY, h:mm A')}`+ : 'Snooze removed'+ )+ }+ return changes+ },+ ],+ hasUnsavedChanges: [+ (s) => [s.status, s.ticket, s.unsavedTicketChanges],+ (status: TicketStatus | null, ticket: Ticket | null, unsavedTicketChanges: string[]): boolean => {+ if (!ticket) {+ return false+ }+ return status !== ticket.status || unsavedTicketChanges.length > 0},],hasPendingWork: [(s) => [s.hasUnsavedChanges], (hasUnsavedChanges: boolean): boolean => hasUnsavedChanges],@@ -880,35 +952,54 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([// Load previous tickets after person is loadedactions.loadPreviousTickets()},- updateTicket: async () => {+ updateTicket: async (_, breakpoint) => {if (props.id === 'new') {+ actions.setTicketUpdating(false)return}- try {- const data: Partial<{- status: string- priority: string- assignee: TicketAssignee- tags: string[]- snoozed_until: string | null- }> = {}+ // Serialize overlapping saves: wait out any in-flight PATCH so requests can't land out of+ // order, then let only the newest dispatch proceed with the latest local edits.+ while (cache.ticketUpdateRequest) {+ await cache.ticketUpdateRequest.catch(() => {})+ }+ breakpoint()- if (values.status && values.status !== values.ticket?.status) {- data.status = values.status- }- if (values.priority && values.priority !== values.ticket?.priority) {- data.priority = values.priority- }- data.assignee = values.assignee- data.tags = values.tags- data.snoozed_until = values.snoozedUntil+ const data: Partial<{+ status: string+ priority: string+ assignee: TicketAssignee+ tags: string[]+ snoozed_until: string | null+ }> = {}- const ticket = await api.conversationsTickets.update(props.id.toString(), data)+ if (values.status && values.status !== values.ticket?.status) {+ data.status = values.status+ }+ if (values.priority && values.priority !== values.ticket?.priority) {+ data.priority = values.priority+ }+ data.assignee = values.assignee+ data.tags = values.tags+ data.snoozed_until = values.snoozedUntil++ const request = api.conversationsTickets.update(props.id.toString(), data)+ cache.ticketUpdateRequest = request+ try {+ const ticket = await request+ breakpoint()actions.setTicket(ticket)lemonToast.success('Ticket updated')actions.loadTickets()- } catch {+ } catch (error: any) {+ if (error?.isBreakpoint) {+ throw error+ }+ actions.setTicketUpdating(false)lemonToast.error('Failed to update ticket')+ } finally {+ if (cache.ticketUpdateRequest === request) {+ cache.ticketUpdateRequest = null+ }}},loadMessages: async () => {@@ -955,7 +1046,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([actions.setOlderMessagesLoading(false)}},- sendMessage: async ({ content, richContent, isPrivate, onSuccess }) => {+ sendMessage: async ({ content, richContent, isPrivate, onSuccess, statusAfterSend }) => {if (props.id === 'new' || !values.ticket?.id) {actions.setMessageSending(false)return@@ -982,6 +1073,14 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([if (!isPrivate) {actions.incrementUnreadCustomerCount()}+ if (statusAfterSend) {+ actions.setStatus(statusAfterSend)+ // Pick up the ticket for the sender unless a specific user is already assigned.+ if (values.assignee?.type !== 'user' && values.user) {+ actions.setAssignee({ type: 'user', id: values.user.id })+ }+ actions.updateTicket()+ }setTimeout(() => {actions.loadMessages()}, 300)