Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(conversations): memoize chat timeline rendering (#104582)

Paul D'Ambraf8a77a90e972
diff --git a/products/conversations/frontend/components/Chat/ChatView.tsx b/products/conversations/frontend/components/Chat/ChatView.tsx
index 9988cef84bde..95bc0c91b661 100644
--- a/products/conversations/frontend/components/Chat/ChatView.tsx
+++ b/products/conversations/frontend/components/Chat/ChatView.tsx
@@ -8,6 +8,7 @@ import type {
AITriageSource,
AiReplyFeedbackRating,
ChatMessage,
+ MessageDeliveryStatus,
Ticket,
TicketChannel,
TicketStatus,
@@ -44,10 +45,7 @@ export interface ChatViewProps {
channel?: TicketChannel
/** Whether to show the "Send as private" option in the message input */
showPrivateOption?: boolean
- /** Number of team messages that haven't been read by the customer */
- unreadCustomerCount?: number
- /** Whether to show delivery status on team messages */
- showDeliveryStatus?: boolean
+ deliveryStatusByMessageId?: Map<string, MessageDeliveryStatus>
/** Draft content to restore (for tab persistence) */
draftContent?: JSONContent | string | null
/** Called when draft content changes */
@@ -75,6 +73,7 @@ export interface ChatViewProps {
/** Other unsaved ticket edits that sending with a status would also persist */
unsavedTicketChanges?: string[]
latestAiMessageId?: string | null
+ latestAiDraftId?: string | null
feedbackByMessageId?: Record<string, AiReplyFeedbackRating>
showAiReplyFeedback?: boolean
aiReplyFeedbackDisabledReason?: string
@@ -110,8 +109,7 @@ export function ChatView({
threadId,
channel,
showPrivateOption = false,
- unreadCustomerCount,
- showDeliveryStatus = false,
+ deliveryStatusByMessageId,
draftContent,
onDraftChange,
isPrivate,
@@ -126,6 +124,7 @@ export function ChatView({
sendAndSetStatusOptions,
unsavedTicketChanges,
latestAiMessageId,
+ latestAiDraftId,
feedbackByMessageId,
showAiReplyFeedback,
aiReplyFeedbackDisabledReason,
@@ -161,9 +160,9 @@ export function ChatView({
emptyMessage="No messages yet. Start the conversation!"
minHeight={listMinHeight}
maxHeight={listMaxHeight}
- unreadCustomerCount={unreadCustomerCount}
- showDeliveryStatus={showDeliveryStatus}
+ deliveryStatusByMessageId={deliveryStatusByMessageId}
latestAiMessageId={latestAiMessageId}
+ latestAiDraftId={latestAiDraftId}
feedbackByMessageId={feedbackByMessageId}
showAiReplyFeedback={showAiReplyFeedback}
aiReplyFeedbackDisabledReason={aiReplyFeedbackDisabledReason}
diff --git a/products/conversations/frontend/components/Chat/MessageList.test.tsx b/products/conversations/frontend/components/Chat/MessageList.test.tsx
index 7174e884a8ee..9f7f5264433c 100644
--- a/products/conversations/frontend/components/Chat/MessageList.test.tsx
+++ b/products/conversations/frontend/components/Chat/MessageList.test.tsx
@@ -3,14 +3,14 @@ import '@testing-library/jest-dom'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import type { ChatMessage } from '../../types'
-import { MessageList } from './MessageList'
+import { MessageList, type TimelineExtra } from './MessageList'
// The real Message pulls in the tiptap-backed Editor exports for markdown and rich content; the
// behavior under test is MessageList's own scroll handling, which only needs a stand-in row.
jest.mock('./Message', () => {
const React = jest.requireActual<typeof import('react')>('react')
return {
- Message: ({ message, onApplyAiDraft }: { message: ChatMessage; onApplyAiDraft?: () => void }) =>
+ Message: jest.fn(({ message, onApplyAiDraft }: { message: ChatMessage; onApplyAiDraft?: () => void }) =>
React.createElement(
'div',
{ 'data-attr': `message-${message.id}` },
@@ -18,10 +18,13 @@ jest.mock('./Message', () => {
onApplyAiDraft
? React.createElement('button', { 'data-attr': `apply-${message.id}`, onClick: onApplyAiDraft })
: null
- ),
+ )
+ ),
}
})
+const mockMessage = jest.requireMock<typeof import('./Message')>('./Message').Message as jest.Mock
+
// jsdom has no layout, so the component's "is the reader at the bottom?" arithmetic
// (scrollHeight - scrollTop - clientHeight < 120) needs fixed geometry. With these, the reader is
// pinned to the bottom above scrollTop 480 and reading history below it.
@@ -61,6 +64,7 @@ let scrollToSpy: jest.Mock
describe('MessageList', () => {
beforeEach(() => {
+ mockMessage.mockClear()
scrollToSpy = jest.fn()
Element.prototype.scrollTo = scrollToSpy
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {
@@ -167,6 +171,7 @@ describe('MessageList', () => {
messages={[draft('old', '2026-01-01T00:00:00Z'), draft('new', '2026-01-01T00:05:00Z')]}
messagesLoading={false}
canEditTicket
+ latestAiDraftId="new"
onApplyAiDraft={jest.fn()}
/>
)
@@ -175,6 +180,18 @@ describe('MessageList', () => {
expect(screen.queryByTestId('apply-old')).not.toBeInTheDocument()
})
+ it('does not recreate message rows when only loading state changes', () => {
+ const messages = [FIRST]
+ const extras: TimelineExtra[] = []
+
+ const { rerender } = render(<MessageList messages={messages} messagesLoading={false} extras={extras} />)
+ mockMessage.mockClear()
+
+ rerender(<MessageList messages={messages} messagesLoading extras={extras} />)
+
+ expect(mockMessage).not.toHaveBeenCalled()
+ })
+
it('dismisses the pill once the reader scrolls back to the bottom themselves', () => {
const { rerender } = render(<MessageList messages={[FIRST]} messagesLoading={false} />)
scrollTo(SCROLLED_UP)
diff --git a/products/conversations/frontend/components/Chat/MessageList.tsx b/products/conversations/frontend/components/Chat/MessageList.tsx
index 0c6ce542099f..7d8502e7caf6 100644
--- a/products/conversations/frontend/components/Chat/MessageList.tsx
+++ b/products/conversations/frontend/components/Chat/MessageList.tsx
@@ -1,11 +1,10 @@
-import { useEffect, useRef, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
import { LemonButton, Spinner } from '@posthog/lemon-ui'
import { IconArrowDown } from 'lib/lemon-ui/icons'
import type { AITriageSource, AiReplyFeedbackRating, ChatMessage, MessageDeliveryStatus } from '../../types'
-import { aiDraftAction } from './aiDraftAction'
import { Message } from './Message'
export interface MessageListProps {
@@ -20,12 +19,10 @@ export interface MessageListProps {
maxHeight?: string
/** When true, flips alignment so customer messages appear on the right (for customer-facing views) */
isCustomerView?: boolean
- /** Number of team messages that haven't been read by the customer */
- unreadCustomerCount?: number
- /** Whether to show delivery status on team messages */
- showDeliveryStatus?: boolean
+ deliveryStatusByMessageId?: Map<string, MessageDeliveryStatus>
/** ID of the latest AI message eligible for reviewer feedback */
latestAiMessageId?: string | null
+ latestAiDraftId?: string | null
/** Recorded reviewer feedback keyed by message id */
feedbackByMessageId?: Record<string, AiReplyFeedbackRating>
/** Whether AI reply feedback controls are enabled */
@@ -54,6 +51,11 @@ export interface TimelineExtra {
element: JSX.Element
}
+const EMPTY_EXTRAS: TimelineExtra[] = []
+const EMPTY_FEEDBACK_BY_MESSAGE_ID: Record<string, AiReplyFeedbackRating> = {}
+const EMPTY_AI_SOURCES: AITriageSource[] = []
+const EMPTY_DELIVERY_STATUS_BY_MESSAGE_ID = new Map<string, MessageDeliveryStatus>()
+
export function MessageList({
messages,
messagesLoading,
@@ -65,21 +67,21 @@ export function MessageList({
minHeight = '300px',
maxHeight = '400px',
isCustomerView = false,
- unreadCustomerCount = 0,
- showDeliveryStatus = false,
+ deliveryStatusByMessageId = EMPTY_DELIVERY_STATUS_BY_MESSAGE_ID,
latestAiMessageId = null,
- feedbackByMessageId = {},
+ latestAiDraftId = null,
+ feedbackByMessageId = EMPTY_FEEDBACK_BY_MESSAGE_ID,
showAiReplyFeedback = false,
aiReplyFeedbackDisabledReason,
onSubmitAiReplyFeedback,
- extras = [],
+ extras = EMPTY_EXTRAS,
currentUserId = null,
canEditTicket = false,
onEditMessage,
onDeleteMessage,
fullEmailLoadingMessageId = null,
onViewFullEmail,
- aiSources = [],
+ aiSources = EMPTY_AI_SOURCES,
aiDraftApplying = false,
onApplyAiDraft,
}: MessageListProps): JSX.Element {
@@ -183,96 +185,89 @@ export function MessageList({
}
}
- // Compute delivery status for team messages (non-customer, non-private messages)
- // The last unreadCustomerCount team messages are "sent", the rest are "read"
- const getDeliveryStatusMap = (): Map<string, MessageDeliveryStatus> => {
- if (!showDeliveryStatus) {
- return new Map()
- }
-
- const statusMap = new Map<string, MessageDeliveryStatus>()
- const teamMessages = messages.filter((m) => m.authorType !== 'customer' && !m.isPrivate)
-
- let unreadRemaining = unreadCustomerCount
- for (let i = teamMessages.length - 1; i >= 0; i--) {
- const msg = teamMessages[i]
- if (unreadRemaining > 0) {
- statusMap.set(msg.id, 'sent')
- unreadRemaining--
- } else {
- statusMap.set(msg.id, 'read')
- }
- }
-
- return statusMap
- }
-
- const deliveryStatusMap = getDeliveryStatusMap()
-
- // Applying a draft records the outcome against the ticket's current AI run, so only the
- // newest draft offers it. An older one would mark the wrong run as used.
- const latestAiDraftId =
- messages
- .filter((message) => aiDraftAction(message) !== null)
- .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())
- .at(-1)?.id ?? null
-
// Messages and extras share one chronological stream, so an agent's findings sit at the point in
// the conversation they arrived rather than always at the bottom. Ties keep messages first, and
// the original order within each kind, so a same-second reply never reshuffles.
- const timeline: JSX.Element[] = [
- ...messages.map((message) => {
- const isCustomer = message.authorType === 'customer'
- const canModify =
- canEditTicket &&
- !!message.isPrivate &&
- message.authorType === 'human' &&
- !!currentUserId &&
- message.createdBy?.id === currentUserId
- return {
- at: message.createdAt,
- rank: 0,
- element: (
- <Message
- key={`${message.id}-${message.version ?? 0}`}
- message={message}
- isCustomer={isCustomerView ? !isCustomer : isCustomer}
- deliveryStatus={deliveryStatusMap.get(message.id)}
- showAiReplyFeedback={
- showAiReplyFeedback && message.id === latestAiMessageId && message.authorType === 'AI'
- }
- aiReplyFeedbackRating={feedbackByMessageId[message.id] ?? null}
- aiReplyFeedbackDisabledReason={aiReplyFeedbackDisabledReason}
- onSubmitAiReplyFeedback={
- onSubmitAiReplyFeedback
- ? (rating, feedbackText) => onSubmitAiReplyFeedback(message.id, rating, feedbackText)
- : undefined
- }
- onEdit={canModify && onEditMessage ? () => onEditMessage(message) : undefined}
- onDelete={canModify && onDeleteMessage ? () => onDeleteMessage(message.id) : undefined}
- fullEmailLoading={fullEmailLoadingMessageId === message.id}
- onViewFullEmail={
- onViewFullEmail && message.hasFullEmailContent
- ? () => onViewFullEmail(message.id)
- : undefined
- }
- aiSources={aiSources}
- aiDraftApplying={aiDraftApplying}
- onApplyAiDraft={
- canEditTicket && onApplyAiDraft && message.id === latestAiDraftId
- ? () => onApplyAiDraft(message)
- : undefined
- }
- />
- ),
- }
- }),
- ...extras.map((extra) => ({ at: extra.at, rank: 1, element: extra.element })),
- ]
- // Array.prototype.sort is stable, so equal (time, rank) pairs keep the order they were
- // concatenated in; only the message-before-extra tiebreak needs stating.
- .sort((a, b) => new Date(a.at).getTime() - new Date(b.at).getTime() || a.rank - b.rank)
- .map(({ element }) => element)
+ const timeline = useMemo(
+ () =>
+ [
+ ...messages.map((message) => {
+ const isCustomer = message.authorType === 'customer'
+ const canModify =
+ canEditTicket &&
+ !!message.isPrivate &&
+ message.authorType === 'human' &&
+ !!currentUserId &&
+ message.createdBy?.id === currentUserId
+ return {
+ at: message.createdAt,
+ rank: 0,
+ element: (
+ <Message
+ key={`${message.id}-${message.version ?? 0}`}
+ message={message}
+ isCustomer={isCustomerView ? !isCustomer : isCustomer}
+ deliveryStatus={deliveryStatusByMessageId.get(message.id)}
+ showAiReplyFeedback={
+ showAiReplyFeedback &&
+ message.id === latestAiMessageId &&
+ message.authorType === 'AI'
+ }
+ aiReplyFeedbackRating={feedbackByMessageId[message.id] ?? null}
+ aiReplyFeedbackDisabledReason={aiReplyFeedbackDisabledReason}
+ onSubmitAiReplyFeedback={
+ onSubmitAiReplyFeedback
+ ? (rating, feedbackText) =>
+ onSubmitAiReplyFeedback(message.id, rating, feedbackText)
+ : undefined
+ }
+ onEdit={canModify && onEditMessage ? () => onEditMessage(message) : undefined}
+ onDelete={canModify && onDeleteMessage ? () => onDeleteMessage(message.id) : undefined}
+ fullEmailLoading={fullEmailLoadingMessageId === message.id}
+ onViewFullEmail={
+ onViewFullEmail && message.hasFullEmailContent
+ ? () => onViewFullEmail(message.id)
+ : undefined
+ }
+ aiSources={aiSources}
+ aiDraftApplying={aiDraftApplying}
+ onApplyAiDraft={
+ canEditTicket && onApplyAiDraft && message.id === latestAiDraftId
+ ? () => onApplyAiDraft(message)
+ : undefined
+ }
+ />
+ ),
+ }
+ }),
+ ...extras.map((extra) => ({ at: extra.at, rank: 1, element: extra.element })),
+ ]
+ // Array.prototype.sort is stable, so equal (time, rank) pairs keep the order they were
+ // concatenated in; only the message-before-extra tiebreak needs stating.
+ .sort((a, b) => new Date(a.at).getTime() - new Date(b.at).getTime() || a.rank - b.rank)
+ .map(({ element }) => element),
+ [
+ aiDraftApplying,
+ aiReplyFeedbackDisabledReason,
+ aiSources,
+ canEditTicket,
+ currentUserId,
+ deliveryStatusByMessageId,
+ extras,
+ feedbackByMessageId,
+ fullEmailLoadingMessageId,
+ isCustomerView,
+ latestAiDraftId,
+ latestAiMessageId,
+ messages,
+ onApplyAiDraft,
+ onDeleteMessage,
+ onEditMessage,
+ onSubmitAiReplyFeedback,
+ onViewFullEmail,
+ showAiReplyFeedback,
+ ]
+ )
return (
// The wrapper is the component root, so it keeps the contract the scroll container used to
diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
index a10909916352..beff73146bf8 100644
--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import { useRef } from 'react'
+import { useMemo, useRef } from 'react'
import { IconChevronDown } from '@posthog/icons'
import { LemonButton, LemonCard, LemonModal, LemonSelect, LemonTag, Link, Spinner } from '@posthog/lemon-ui'
@@ -86,6 +86,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
assignee,
tags,
chatMessages,
+ deliveryStatusByMessageId,
messagesLoading,
messageSending,
hasMoreMessages,
@@ -106,6 +107,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
snoozedUntil,
emailReplyBlockedReason,
latestAiMessage,
+ latestAiDraftId,
feedbackByMessageId,
editingMessageId,
discussionsEnabled,
@@ -196,6 +198,10 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
// Above the early returns below: this scene renders a spinner and a not-found state before the
// thread, and a hook can't be called on only some of those paths.
const discussionExtras = useDiscussionTimelineExtras(ticket?.id, discussionsEnabled)
+ const threadExtras = useMemo(
+ () => [...reportTimelineExtras(linkedReports), ...discussionExtras],
+ [discussionExtras, linkedReports]
+ )
if (ticketLoading) {
return (
@@ -262,7 +268,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
fillParent
collapseUntilActive
threadId={ticketId}
- threadExtras={[...reportTimelineExtras(linkedReports), ...discussionExtras]}
+ threadExtras={threadExtras}
messages={chatMessages}
messagesLoading={messagesLoading}
messageSending={messageSending}
@@ -272,8 +278,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
onLoadOlderMessages={loadOlderMessages}
channel={ticket?.channel_source}
showPrivateOption
- unreadCustomerCount={ticket?.unread_customer_count}
- showDeliveryStatus={ticket?.channel_source === 'widget'}
+ deliveryStatusByMessageId={deliveryStatusByMessageId}
draftContent={draftContent}
onDraftChange={setDraftContent}
isPrivate={draftIsPrivate}
@@ -286,6 +291,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
replyDisabledReason={replyDisabledReason}
sendDisabledReason={sendDisabledReason}
latestAiMessageId={latestAiMessage?.id ?? null}
+ latestAiDraftId={latestAiDraftId}
feedbackByMessageId={feedbackByMessageId}
showAiReplyFeedback={aiSuggestionsEnabled}
aiReplyFeedbackDisabledReason={sendDisabledReason}
diff --git a/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsx b/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsx
index 84c573eacb0f..6febd4f13b12 100644
--- a/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsx
+++ b/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { useEffect } from 'react'
+import { useCallback, useEffect, useMemo } from 'react'
import { IconChat } from '@posthog/icons'
import { LemonTag } from '@posthog/lemon-ui'
@@ -205,14 +205,18 @@ export function useDiscussionTimelineExtras(ticketId: string | undefined, enable
}
}, [enabled, ticketId, maybeLoadComments])
- if (!enabled || !ticketId) {
- return []
- }
+ const openDiscussion = useCallback(
+ (threadId: string) => {
+ openSidePanel(SidePanelTab.Discussion, threadId)
+ // The panel selects from the URL option on change, so clicking the *same* card twice would
+ // otherwise be a no-op — after the reader collapsed that thread, the card would stop working.
+ setSelectedComment(threadId, true)
+ },
+ [openSidePanel, setSelectedComment]
+ )
- return discussionTimelineExtras(commentsWithReplies, (threadId) => {
- openSidePanel(SidePanelTab.Discussion, threadId)
- // The panel selects from the URL option on change, so clicking the *same* card twice would
- // otherwise be a no-op — after the reader collapsed that thread, the card would stop working.
- setSelectedComment(threadId, true)
- })
+ return useMemo(
+ () => (enabled && ticketId ? discussionTimelineExtras(commentsWithReplies, openDiscussion) : []),
+ [commentsWithReplies, enabled, openDiscussion, ticketId]
+ )
}
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
index 636d1e597416..fa0d2313e338 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
@@ -304,6 +304,34 @@ describe('supportTicketSceneLogic chatMessages mapping', () => {
})
)
})
+
+ it('selects the latest applicable AI draft', () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PRODUCT_SUPPORT_AI_NOTES]: true })
+ logic.actions.setMessages([
+ { ...makeAiComment('new-draft'), created_at: '2026-01-01T00:02:00Z' },
+ { ...makeAiComment('not-a-draft', false), created_at: '2026-01-01T00:01:00Z' },
+ { ...makeAiComment('old-draft'), created_at: '2026-01-01T00:00:00Z' },
+ ])
+
+ expect(logic.values.latestAiDraftId).toBe('new-draft')
+ })
+
+ it('selects widget delivery statuses for public team messages', () => {
+ logic.actions.setTicket({ ...makeTicket(), unread_customer_count: 1 })
+ logic.actions.setMessages([
+ makeSupportComment({ id: 'read', created_at: '2026-01-01T00:00:00Z' }),
+ makeCustomerComment('customer'),
+ makeSupportComment({ id: 'private', item_context: { author_type: 'support', is_private: true } }),
+ makeSupportComment({ id: 'sent', created_at: '2026-01-01T00:03:00Z' }),
+ ])
+
+ expect(logic.values.deliveryStatusByMessageId).toEqual(
+ new Map([
+ ['read', 'read'],
+ ['sent', 'sent'],
+ ])
+ )
+ })
})
describe('supportTicketSceneLogic applyAiDraft', () => {
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
index 13d1a9ef5760..18ce371f04d3 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
@@ -63,10 +63,17 @@ import type { FeatureFlagsSet } from '../../../../../frontend/src/lib/logic/feat
import type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'
import { assigneeSelectLogic } from '../../components/Assignee'
import type { Assignee, TicketAssignee } from '../../components/Assignee'
-import { aiDraftComposerHtml } from '../../components/Chat/aiDraftAction'
+import { aiDraftAction, aiDraftComposerHtml } from '../../components/Chat/aiDraftAction'
import { supportTicketCounterLogic } from '../../supportTicketCounterLogic'
import { priorityOptions } from '../../types'
-import type { AiReplyFeedbackRating, ChatMessage, Ticket, TicketPriority, TicketStatus } from '../../types'
+import type {
+ AiReplyFeedbackRating,
+ ChatMessage,
+ MessageDeliveryStatus,
+ Ticket,
+ TicketPriority,
+ TicketStatus,
+} from '../../types'
import { conversationsDraftModeLogic } from '../settings/conversationsDraftModeLogic'
import { supportTicketsSceneLogic } from '../tickets/supportTicketsSceneLogic'
@@ -75,6 +82,7 @@ const MESSAGE_POLL_INTERVAL = 5000 // 5 seconds
const DISCUSSION_POLL_EVERY_N_TICKS = 4
/** Must not exceed the server's replay window, or recovery could adopt a message from an older send. */
const SEND_RECOVERY_WINDOW_SECONDS = 120
+const EMPTY_DELIVERY_STATUS_BY_MESSAGE_ID = new Map<string, MessageDeliveryStatus>()
/**
* How a failed send request should be treated. `null` means the send definitely did not happen:
@@ -235,6 +243,7 @@ export interface supportTicketSceneLogicValues {
chatMessages: ChatMessage[]
chatPanelWidth: (desiredSize: number | null) => number
composerPrefillAt: number
+ deliveryStatusByMessageId: Map<string, MessageDeliveryStatus>
discussionsEnabled: boolean
draftContent: string | JSONContent | null
draftIsPrivate: boolean
@@ -250,6 +259,7 @@ export interface supportTicketSceneLogicValues {
hasMoreMessages: boolean
hasPendingWork: boolean
hasUnsavedChanges: boolean
+ latestAiDraftId: string | null
latestAiMessage: ChatMessage | null
linkedReports: SignalReportApi[]
linkedReportsLoading: boolean
@@ -527,9 +537,14 @@ export interface supportTicketSceneLogicMeta {
) => boolean
hasPendingWork: (hasUnsavedChanges: boolean, editingMessageId: string | null) => boolean
chatMessages: (messages: CommentType[], ticket: Ticket | null, featureFlags: FeatureFlagsSet) => ChatMessage[]
+ deliveryStatusByMessageId: (
+ chatMessages: ChatMessage[],
+ ticket: Ticket | null
+ ) => Map<string, MessageDeliveryStatus>
eventsQuery: (ticket: Ticket | null) => DataTableNode | null
exceptionsQuery: (ticket: Ticket | null) => DataTableNode | null
latestAiMessage: (chatMessages: ChatMessage[]) => ChatMessage | null
+ latestAiDraftId: (chatMessages: ChatMessage[]) => string | null
}
}
@@ -1148,6 +1163,30 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
})
},
],
+ deliveryStatusByMessageId: [
+ (s) => [s.chatMessages, s.ticket],
+ (chatMessages: ChatMessage[], ticket: Ticket | null): Map<string, MessageDeliveryStatus> => {
+ if (ticket?.channel_source !== 'widget') {
+ return EMPTY_DELIVERY_STATUS_BY_MESSAGE_ID
+ }
+
+ const statusMap = new Map<string, MessageDeliveryStatus>()
+ let unreadRemaining = ticket.unread_customer_count ?? 0
+ for (let i = chatMessages.length - 1; i >= 0; i--) {
+ const message = chatMessages[i]
+ if (message.authorType === 'customer' || message.isPrivate) {
+ continue
+ }
+ if (unreadRemaining > 0) {
+ statusMap.set(message.id, 'sent')
+ unreadRemaining--
+ } else {
+ statusMap.set(message.id, 'read')
+ }
+ }
+ return statusMap
+ },
+ ],
eventsQuery: [
(s) => [s.ticket],
(ticket: Ticket | null): DataTableNode | null => {
@@ -1178,6 +1217,21 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
return null
},
],
+ latestAiDraftId: [
+ (s) => [s.chatMessages],
+ (chatMessages: ChatMessage[]): string | null => {
+ let latestDraft: ChatMessage | null = null
+ for (const message of chatMessages) {
+ if (
+ aiDraftAction(message) !== null &&
+ (!latestDraft || new Date(message.createdAt) >= new Date(latestDraft.createdAt))
+ ) {
+ latestDraft = message
+ }
+ }
+ return latestDraft?.id ?? null
+ },
+ ],
}),
listeners(({ actions, values, props, cache }) => ({
loadTicket: async () => {