: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): show team discussions in the ticket thread (#79709)
Luke Beltonda395b34e576
diff --git a/frontend/src/scenes/comments/Comment.tsx b/frontend/src/scenes/comments/Comment.tsxindex f20b2d4c4dc5..7b9e1f74aba1 100644--- a/frontend/src/scenes/comments/Comment.tsx+++ b/frontend/src/scenes/comments/Comment.tsx@@ -34,7 +34,7 @@ import { sendCommentToSlackLogic } from './sendCommentToSlackLogic'// Comments that came in from a synced Slack thread have no PostHog author; their Slack identity// rides in item_context.-function getCommentAuthorName(comment: CommentType): string {+export function getCommentAuthorName(comment: CommentType): string {if (comment.created_by) {return comment.created_by.first_name ?? 'Unknown user'}diff --git a/frontend/src/scenes/comments/commentsLogic.test.ts b/frontend/src/scenes/comments/commentsLogic.test.tsindex f1c34d53461f..6bd2c96aaee1 100644--- a/frontend/src/scenes/comments/commentsLogic.test.ts+++ b/frontend/src/scenes/comments/commentsLogic.test.ts@@ -131,6 +131,64 @@ describe('commentsLogic', () => {expect(lastCreateBody?.source_comment).toBeUndefined()})+ // A background poller uses refreshComments so a reader keeps their place. loadComments always+ // scrolls to the newest comment, which is right on arrival and wrong every 20 seconds after that.+ it('refreshComments loads the thread without scrolling to the newest comment', async () => {+ useMocks({ get: { '/api/projects/:team_id/comments': { results: [makeComment('thread-1')] } } })++ await expectLogic(logic, () => {+ logic.actions.refreshComments()+ })+ .toDispatchActions(['refreshCommentsSuccess'])+ .toNotHaveDispatchedActions([sidePanelDiscussionLogic.actionTypes.scrollToLastComment])++ expect(logic.values.commentsWithReplies.map((thread) => thread.id)).toEqual(['thread-1'])+ })++ it('loadComments still scrolls to the newest comment', async () => {+ useMocks({ get: { '/api/projects/:team_id/comments': { results: [makeComment('thread-1')] } } })++ await expectLogic(logic, () => {+ logic.actions.loadComments()+ }).toDispatchActions(['loadCommentsSuccess', sidePanelDiscussionLogic.actionTypes.scrollToLastComment])+ })++ // Every loader here writes the same `comments` value and the last to resolve wins. A poll started+ // before a send would otherwise land afterwards carrying a snapshot without the new comment, and+ // the sender would watch their own message disappear for a poll interval.+ it('a refresh in flight does not clobber a comment sent while it was running', async () => {+ useMocks({ get: { '/api/projects/:team_id/comments': { results: [makeComment('thread-1')] } } })+ await expectLogic(logic, () => {+ logic.actions.loadComments()+ }).toDispatchActions(['loadCommentsSuccess'])++ // A poll that hangs until we let it answer, with the pre-send snapshot.+ let answerPoll: () => void = () => {}+ const pollReached = new Promise<void>((resolve) => {+ answerPoll = resolve+ })+ useMocks({+ get: {+ '/api/projects/:team_id/comments': async () => {+ await pollReached+ return [200, { results: [makeComment('thread-1')] }]+ },+ },+ })+ logic.actions.refreshComments()++ logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))+ await expectLogic(logic, () => {+ logic.actions.sendComposedContent(false)+ }).toDispatchActions(['sendComposedContentSuccess'])+ expect(logic.values.comments?.map((comment) => comment.id)).toContain('new-comment')++ answerPoll()+ await expectLogic(logic).toDispatchActions(['refreshCommentsSuccess'])++ expect(logic.values.comments?.map((comment) => comment.id)).toContain('new-comment')+ })+it('clears reply mode when the reply target stops rendering after a reload', async () => {useMocks({ get: { '/api/projects/:team_id/comments': { results: [makeComment('thread-1')] } } })await expectLogic(logic, () => {@@ -344,6 +402,26 @@ describe('commentsLogic', () => {expect(footerEditor.focus).toHaveBeenCalledWith('end')})+ // How "Discuss with team" opens the panel: start a fresh comment, then point it at Slack. The+ // order matters - leaving reply mode resets the composer's Slack state, so arming it first would+ // silently drop the toggle and open a plain comment box instead.+ it('keeps the Slack toggle armed after exiting reply mode, and still focuses the composer', () => {+ logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))+ logic.actions.setReplyingComment('thread-1')++ logic.actions.startNewComment()+ logic.actions.setComposerSendToSlack(true)+ logic.actions.setComposerSlackIntegrationId(7)++ expect(logic.values.composerSendToSlack).toBe(true)+ expect(logic.values.composerSlackIntegrationId).toBe(7)++ const footerEditor = createEditor(null)+ logic.actions.setRichContentEditor(footerEditor)+ expect(footerEditor.focus).toHaveBeenCalledWith('end')+ expect(logic.values.composerSendToSlack).toBe(true)+ })+it('a send that bails on empty content leaves stashed drafts untouched', async () => {logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))logic.actions.setReplyingComment('thread-1') // stashes the footer draftdiff --git a/frontend/src/scenes/comments/commentsLogic.ts b/frontend/src/scenes/comments/commentsLogic.tsindex cbd42429fd44..4dba9f417c2e 100644--- a/frontend/src/scenes/comments/commentsLogic.ts+++ b/frontend/src/scenes/comments/commentsLogic.ts@@ -44,6 +44,23 @@ export type CommentContext = {/** Draft slot for the footer composer; thread composers use their thread id (a UUID, so no collision) */const FOOTER_COMPOSER_TARGET = 'footer'+/** Shared by `loadComments` and `refreshComments`, which differ only in what happens after they land. */+async function fetchComments(props: CommentsLogicProps): Promise<CommentType[]> {+ if (!props.item_id) {+ // A per-item discussion must target a specific item. Listing with only a scope makes the+ // backend return every comment in that scope across the team, so fail closed rather than+ // leak other items' comments.+ return []+ }++ const response = await api.comments.list({+ scope: props.scope,+ item_id: props.item_id,+ })++ return response.results+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface commentsLogicValues {meFirstMembers: OrganizationMemberType[] // membersLogic@@ -185,6 +202,27 @@ export interface commentsLogicActions {value: true}}+ refreshComments: () => {+ value: true+ }+ refreshCommentsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ refreshCommentsSuccess: (+ comments: CommentType[] | null,+ payload?: {+ value: true+ }+ ) => {+ comments: CommentType[] | null+ payload?: {+ value: true+ }+ }reopenComment: (comment: CommentType) => {comment: CommentType}@@ -356,6 +394,7 @@ export const commentsLogic = kea<commentsLogicType>([actions({loadComments: true,+ refreshComments: true,clearItemContext: true,maybeLoadComments: true,sendComposedContent: (asTask: boolean = false) => ({ asTask }),@@ -512,20 +551,21 @@ export const commentsLogic = kea<commentsLogicType>([comments: [null as CommentType[] | null,{- loadComments: async () => {- if (!props.item_id) {- // A per-item discussion must target a specific item. Listing with only a- // scope makes the backend return every comment in that scope across the- // team, so fail closed rather than leak other items' comments.- return []- }-- const response = await api.comments.list({- scope: props.scope,- item_id: props.item_id,- })-- return response.results+ loadComments: async () => await fetchComments(props),+ // Same fetch, but nothing follows it: no scroll to the newest comment and no deep-link+ // reveal. Callers that poll in the background use this so a refresh never takes the+ // reader's place in the thread away from them. `loadComments` stays the one to call+ // when the reader is arriving and does want to land on the latest.+ refreshComments: async () => {+ // Every handler here writes the same `comments` value and the last one to resolve+ // wins, so a background refresh must not land on top of a local write it started+ // before. Sending a comment while this request was in flight would otherwise make+ // it reappear from a snapshot taken before it existed — the sender watches their+ // own message vanish. Comparing the array identity catches that: any local write+ // replaces the array, so a changed reference means our snapshot is the stale one.+ const before = values.comments+ const results = await fetchComments(props)+ return values.comments === before ? results : values.comments},sendComposedContent: async ({ asTask }) => {const existingComments = values.comments ?? []diff --git a/products/conversations/frontend/components/Chat/TeamOnlyBadge.tsx b/products/conversations/frontend/components/Chat/TeamOnlyBadge.tsxindex 79c51d5bf2ca..1db905da3c2b 100644--- a/products/conversations/frontend/components/Chat/TeamOnlyBadge.tsx+++ b/products/conversations/frontend/components/Chat/TeamOnlyBadge.tsx@@ -11,11 +11,12 @@ import { Tooltip } from '@posthog/lemon-ui'* `tone` varies for a different reason. The lock, the tooltip and the shape stay fixed, so the promise* is still one thing; only the colour follows whoever wrote the entry, matching the note it sits above.*/-export type TeamOnlyTone = 'teammate' | 'agent'+export type TeamOnlyTone = 'teammate' | 'agent' | 'discussion'const TONE_CLASSES: Record<TeamOnlyTone, string> = {teammate: 'text-warning-dark bg-warning-highlight',agent: 'text-ai bg-ai/10',+ discussion: 'text-accent bg-accent-highlight-secondary',}export function TeamOnlyBadge({ label, tone = 'teammate' }: { label: string; tone?: TeamOnlyTone }): JSX.Element {diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex fc85b1855d98..f113f7baaf44 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -39,6 +39,7 @@ import { RelatedGroupsPanel } from './RelatedGroupsPanel'import { SessionRecordingPanel } from './SessionRecordingPanel'import { StaffActionsPanel } from './StaffActionsPanel'import { supportTicketSceneLogic } from './supportTicketSceneLogic'+import { useDiscussionTimelineExtras } from './ThreadDiscussions'import { reportTimelineExtras } from './ThreadReports'import { TicketActivityPanel } from './TicketActivityPanel'@@ -107,6 +108,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemlatestAiMessage,feedbackByMessageId,editingMessageId,+ discussionsEnabled,} = useValues(logic)// The list's filters / saved view ride along in this page's query string// (the ticket row carries them through on navigation). Preserve them on the@@ -184,6 +186,10 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elemconst { desiredSize } = useValues(resizerLogic(resizerLogicProps))+ // 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)+if (ticketLoading) {return (<SceneContent>@@ -233,7 +239,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem>{/* Main conversation area */}<ChatView- threadExtras={reportTimelineExtras(linkedReports)}+ threadExtras={[...reportTimelineExtras(linkedReports), ...discussionExtras]}messages={chatMessages}messagesLoading={messagesLoading}messageSending={messageSending}diff --git a/products/conversations/frontend/scenes/ticket/ThreadDiscussions.test.tsx b/products/conversations/frontend/scenes/ticket/ThreadDiscussions.test.tsxnew file mode 100644index 000000000000..9231eaa9f59f--- /dev/null+++ b/products/conversations/frontend/scenes/ticket/ThreadDiscussions.test.tsx@@ -0,0 +1,185 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { CommentWithRepliesType } from 'scenes/comments/commentsLogic'++import type { CommentType } from '~/types'+import { ActivityScope } from '~/types'++import { ThreadDiscussionEntry, discussionTimelineExtras } from './ThreadDiscussions'++// TZLabel reads the current team's timezone off a mounted kea store; the behaviour under test is what+// the card says about the discussion, not how the timestamp is localised.+jest.mock('lib/components/TZLabel', () => {+ const React = jest.requireActual<typeof import('react')>('react')+ return { TZLabel: ({ time }: { time: string }) => React.createElement('span', null, time) }+})++// Fully typed rather than cast, so a new required field on CommentType breaks this file instead of+// letting the fixture drift away from what the card is really handed.+function comment(overrides: Partial<CommentType> = {}): CommentType {+ return {+ id: 'comment-1',+ content: 'Is this the same bug as the flag eval regression?',+ rich_content: null,+ scope: ActivityScope.TICKET,+ item_id: 'ticket-1',+ item_context: null,+ created_at: '2026-01-01T00:00:00Z',+ created_by: {+ id: 1,+ uuid: 'user-1',+ distinct_id: 'user-1',+ first_name: 'Luke',+ email: '[email protected]',+ },+ version: 0,+ is_task: false,+ completed_at: null,+ completed_by: null,+ ...overrides,+ }+}++function thread(overrides: Partial<CommentWithRepliesType> = {}): CommentWithRepliesType {+ return { id: 'comment-1', comment: comment(), replies: [], ...overrides }+}++afterEach(cleanup)++describe('ThreadDiscussions', () => {+ it('marks the discussion team-only and names who started it', () => {+ render(<ThreadDiscussionEntry thread={thread()} onOpen={jest.fn()} />)++ expect(screen.getByText('Started by Luke')).toBeInTheDocument()+ expect(screen.getByText('Is this the same bug as the flag eval regression?')).toBeInTheDocument()+ // The row names the entry once on the left and promises team-only on the right. Saying+ // "Team discussion" in both places reads as a mistake next to an agent report, which+ // splits the same two jobs across two different words.+ expect(screen.getByText('Team discussion')).toBeInTheDocument()+ expect(screen.getByText('Internal')).toBeInTheDocument()+ })++ // Reactions are stripped upstream by commentsLogic's commentsWithReplies, so the card can trust+ // replies.length — this pins that it counts replies rather than re-deriving anything.+ it('counts replies', () => {+ render(+ <ThreadDiscussionEntry+ thread={thread({ replies: [comment({ id: 'r1' }), comment({ id: 'r2' })] })}+ onOpen={jest.fn()}+ />+ )++ expect(screen.getByText('2 replies')).toBeInTheDocument()+ })++ it('shows the Slack channel only once the discussion is mirrored', () => {+ const { rerender } = render(<ThreadDiscussionEntry thread={thread()} onOpen={jest.fn()} />)+ expect(screen.queryByText('#support-eng')).not.toBeInTheDocument()++ rerender(+ <ThreadDiscussionEntry+ thread={thread({+ comment: comment({+ slack_thread: {+ channel_id: 'C123',+ channel_name: 'support-eng',+ url: 'https://slack.com/archives/C123/p1',+ },+ }),+ })}+ onOpen={jest.fn()}+ />+ )+ expect(screen.getByText('#support-eng')).toBeInTheDocument()+ })++ // A root can be deleted out from under its replies; the discussion still happened.+ it('degrades to a deleted-comment body when the root is gone', () => {+ render(+ <ThreadDiscussionEntry+ thread={thread({ comment: undefined, replies: [comment({ id: 'r1' })] })}+ onOpen={jest.fn()}+ />+ )++ expect(screen.getByText('Deleted comment')).toBeInTheDocument()+ expect(screen.getByText('1 reply')).toBeInTheDocument()+ })++ // Slack repliers have no PostHog user at all, so they can't be avatar bubbles. They must still be+ // named visibly - a discussion that moved entirely into Slack would otherwise show nobody.+ it('names Slack-authored participants in the open', () => {+ render(+ <ThreadDiscussionEntry+ thread={thread({+ replies: [+ comment({+ id: 'r1',+ created_by: null,+ item_context: { from_slack: true, slack_author_name: 'Marius' },+ }),+ ],+ })}+ onOpen={jest.fn()}+ />+ )++ expect(screen.getByText('Marius')).toBeInTheDocument()+ })++ it('summarises a crowd of Slack participants', () => {+ render(+ <ThreadDiscussionEntry+ thread={thread({+ replies: ['Marius', 'Ben', 'Tim', 'Kea'].map((name, index) =>+ comment({+ id: `r${index}`,+ created_by: null,+ item_context: { from_slack: true, slack_author_name: name },+ })+ ),+ })}+ onOpen={jest.fn()}+ />+ )++ expect(screen.getByText('Marius, Ben +2')).toBeInTheDocument()+ })++ it('opens the thread it represents', () => {+ const onOpen = jest.fn()+ render(<ThreadDiscussionEntry thread={thread()} onOpen={onOpen} />)++ fireEvent.click(screen.getByRole('button'))++ expect(onOpen).toHaveBeenCalledWith('comment-1')+ })++ describe('discussionTimelineExtras', () => {+ it('anchors each entry at the root comment', () => {+ expect(discussionTimelineExtras([thread()], jest.fn())[0].at).toBe('2026-01-01T00:00:00Z')+ })++ it('falls back to the first reply when the root was deleted', () => {+ const extras = discussionTimelineExtras(+ [+ thread({+ comment: undefined,+ replies: [comment({ id: 'r1', created_at: '2026-01-02T00:00:00Z' })],+ }),+ ],+ jest.fn()+ )++ expect(extras[0].at).toBe('2026-01-02T00:00:00Z')+ })++ // MessageList sorts on new Date(at).getTime(); one NaN reorders the whole timeline, not just+ // this entry, so a thread with no usable timestamp is dropped rather than emitted.+ it('drops a thread with no timestamp to anchor on', () => {+ expect(discussionTimelineExtras([{ id: 'x', comment: undefined, replies: [] }], jest.fn())).toEqual([])+ })+ })+})diff --git a/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsx b/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsxnew file mode 100644index 000000000000..40dda58121f2--- /dev/null+++ b/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsx@@ -0,0 +1,217 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { IconChat } from '@posthog/icons'+import { LemonTag } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { IconSlack } from 'lib/lemon-ui/icons'+import { ProfileBubbles } from 'lib/lemon-ui/ProfilePicture/ProfileBubbles'+import { pluralize } from 'lib/utils/strings'+import { getCommentAuthorName, getText } from 'scenes/comments/Comment'+import { CommentWithRepliesType, commentsLogic } from 'scenes/comments/commentsLogic'++import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'+import { ActivityScope, CommentType, SidePanelTab } from '~/types'++import type { TimelineExtra } from '../../components/Chat/MessageList'+import { TeamOnlyBadge } from '../../components/Chat/TeamOnlyBadge'++/**+ * When the discussion happened. The root's timestamp is what the reader means by "when this started",+ * but a deleted root leaves only replies, so fall back to the first of those rather than emitting an+ * undefined `at` — `MessageList` sorts on `new Date(at).getTime()`, and one NaN scrambles the whole+ * timeline, not just this entry.+ */+function anchorOf(thread: CommentWithRepliesType): string | undefined {+ return thread.comment?.created_at ?? thread.replies[0]?.created_at+}++/** How many Slack-only participants to name before summarising the rest. */+const MAX_NAMED_SLACK_PARTICIPANTS = 2++/**+ * Who is in the discussion.+ *+ * Split in two because the two kinds of participant can't be shown the same way: `ProfileBubbles` keys+ * on email, and someone replying from the mirrored Slack thread has no PostHog user at all. They can't+ * be a bubble — and they can't only be a tooltip either, or a discussion that moved entirely into Slack+ * (the case this whole surface exists for) would show no one. So they get named in the open instead.+ */+function participantsOf(thread: CommentWithRepliesType): {+ people: { email: string; name: string }[]+ slackNames: string[]+} {+ const all = [thread.comment, ...thread.replies].filter((comment): comment is CommentType => !!comment)++ const people: { email: string; name: string }[] = []+ const seenEmails = new Set<string>()+ const slackNames = new Set<string>()++ for (const comment of all) {+ const email = comment.created_by?.email+ if (email) {+ if (!seenEmails.has(email)) {+ seenEmails.add(email)+ people.push({ email, name: getCommentAuthorName(comment) })+ }+ } else {+ slackNames.add(getCommentAuthorName(comment))+ }+ }++ return { people, slackNames: [...slackNames] }+}++/** Slack participants as a short readable list: "Marius", "Marius, Ben", "Marius, Ben +3". */+function summariseSlackNames(names: string[]): string {+ const named = names.slice(0, MAX_NAMED_SLACK_PARTICIPANTS).join(', ')+ const rest = names.length - MAX_NAMED_SLACK_PARTICIPANTS+ return rest > 0 ? `${named} +${rest}` : named+}++/**+ * One team discussion, as an entry in the ticket thread.+ *+ * The ticket thread already carries two other things the customer can't see — a teammate's private+ * note (amber) and a Self-driving agent's report (AI purple) — so this has to read as a third, distinct+ * kind: a conversation among the team *about* this ticket, possibly happening in Slack right now. It+ * wears the accent colour and a chat mark to say that, and like the agent report it deliberately avoids+ * the message bubble so it never scans as something anybody said to the customer.+ *+ * The whole card is the click target (it opens the discussion side panel), so nothing inside it may be+ * interactive — hence the Slack channel is a tag here rather than the link it is in the side panel.+ */+export function ThreadDiscussionEntry({+ thread,+ onOpen,+}: {+ thread: CommentWithRepliesType+ onOpen: (threadId: string) => void+}): JSX.Element {+ const root = thread.comment+ const anchor = anchorOf(thread)+ const slackThread = root?.slack_thread+ const { people, slackNames } = participantsOf(thread)++ return (+ // Full width, unlike a message: messages are inset because they belong to one side of the+ // conversation, and this belongs to neither.+ <div className="mb-4">+ {/* Same header structure as a message and as an agent report, so the thread keeps one+ rhythm down the page: who on the left, the facts about this entry on the right. */}+ <div className="flex items-center justify-between w-full gap-2 mb-1">+ <div className="flex items-center gap-1.5 min-w-0">+ <IconChat className="text-accent shrink-0" />+ <span className="text-sm font-medium text-accent">Team discussion</span>+ {root ? (+ <span className="ph-no-capture text-xs text-muted-alt truncate">+ Started by {getCommentAuthorName(root)}+ </span>+ ) : null}+ </div>+ <div className="flex items-center gap-1.5 shrink-0">+ {/* "Internal", not the entry's name again: the left of the row already says what+ this is, and the badge's job is only to promise the customer cannot see it.+ Same split as an agent report, which reads "Self-driving" then "Internal". */}+ <TeamOnlyBadge label="Internal" tone="discussion" />+ {anchor ? (+ <span className="text-xs text-muted-alt">+ <TZLabel time={anchor} />+ </span>+ ) : null}+ </div>+ </div>+ {/* Not a bubble, and marked down its edge, so it never reads as something a person said to+ the customer. The edge is a pseudo-element so it can run the full height without fighting+ the border radius the way a left border does.++ A button rather than a styled div: this opens a panel instead of navigating, and a button+ is what gives keyboard users the entry the mouse already has. The hover pair (background+ and border) is the same one the ticket page's other clickable blocks use, so the card+ announces itself the way the rest of the page does. */}+ <button+ type="button"+ onClick={() => onOpen(thread.id)}+ className="relative block w-full cursor-pointer overflow-hidden rounded border border-primary bg-surface-primary text-left transition-colors hover:border-secondary hover:bg-surface-secondary py-2 pl-4 pr-3 after:content-[''] after:absolute after:inset-y-0 after:left-0 after:w-1 after:bg-accent"+ data-attr="ticket-thread-discussion"+ >+ {root ? (+ <div className="ph-no-capture text-sm leading-snug line-clamp-2">{getText(root)}</div>+ ) : (+ <div className="text-sm font-semibold italic text-secondary">Deleted comment</div>+ )}+ <div className="mt-1.5 flex items-center gap-2 text-xs text-muted">+ <span className="shrink-0">{pluralize(thread.replies.length, 'reply', 'replies')}</span>+ {people.length > 0 ? (+ <ProfileBubbles+ people={people}+ tooltip={people.map((person) => person.name).join(', ')}+ limit={4}+ />+ ) : null}+ {slackNames.length > 0 ? (+ <span className="ph-no-capture truncate">{summariseSlackNames(slackNames)}</span>+ ) : null}+ {slackThread ? (+ // A tag, not a link: the card is one click target, and an anchor inside a button+ // is invalid markup that swallows the card's own click.+ <LemonTag size="small" type="muted" icon={<IconSlack />} className="ml-auto shrink-0">+ {slackThread.channel_name ? `#${slackThread.channel_name}` : 'Synced to Slack'}+ </LemonTag>+ ) : null}+ </div>+ </button>+ </div>+ )+}++/** Discussions as thread entries, ordered by when each started. */+export function discussionTimelineExtras(+ threads: CommentWithRepliesType[],+ onOpen: (threadId: string) => void+): TimelineExtra[] {+ return threads.flatMap((thread) => {+ const at = anchorOf(thread)+ return at ? [{ at, element: <ThreadDiscussionEntry key={thread.id} thread={thread} onOpen={onOpen} /> }] : []+ })+}++/**+ * The ticket's own discussions, ready to drop into the thread.+ *+ * `commentsLogic` is keyed on scope+item_id, so this mounts the very same instance the discussion side+ * panel uses: a reply posted in the panel updates these cards with no wiring between the two. That also+ * means the props here must match what `sidePanelDiscussionLogic.commentsLogicProps` builds for a ticket+ * — if the ticket scene ever starts setting `activity_item_context`, it has to be added here too, or this+ * mount will quietly win and drop it.+ *+ * A hook rather than a `connect()` because there's no static-props path to it: `supportTicketSceneLogic`+ * is keyed by the ticket *number* from the URL, while a discussion is keyed by the ticket's UUID, which+ * only exists once the ticket has loaded.+ */+export function useDiscussionTimelineExtras(ticketId: string | undefined, enabled: boolean): TimelineExtra[] {+ // Mounted unconditionally to keep hook order stable across the scene's loading states; loadComments+ // already no-ops without an item_id, so an unloaded ticket costs nothing.+ const logic = commentsLogic({ scope: ActivityScope.TICKET, item_id: ticketId ?? '' })+ const { commentsWithReplies } = useValues(logic)+ const { maybeLoadComments, setSelectedComment } = useActions(logic)+ const { openSidePanel } = useActions(sidePanelStateLogic)++ useEffect(() => {+ if (enabled && ticketId) {+ maybeLoadComments()+ }+ }, [enabled, ticketId, maybeLoadComments])++ if (!enabled || !ticketId) {+ return []+ }++ 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)+ })+}diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.tsindex fc8a2d5acd52..c9a646c9cabf 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -5,6 +5,7 @@ import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { commentsLogic } from 'scenes/comments/commentsLogic'import { userLogic } from 'scenes/userLogic'import { tagsModel } from '~/models/tagsModel'@@ -941,3 +942,83 @@ describe('supportTicketSceneLogic sidePanelContext', () => {})})})++describe('supportTicketSceneLogic discussion polling', () => {+ let logic: ReturnType<typeof supportTicketSceneLogic.build>+ const discussionProps = { scope: ActivityScope.TICKET, item_id: 'ticket-1' }++ beforeEach(() => {+ initKeaTests()+ logic = supportTicketSceneLogic({ id: 'new' })+ logic.mount()+ logic.actions.setTicket(makeTicket())+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC]: true })+ })++ afterEach(() => {+ stopPolling(logic)+ })++ // refreshComments, not loadComments: loadComments scrolls the side panel to the newest comment on+ // every success, so polling with it would move a reader off their place every 20 seconds.+ it('refreshes the ticket-scoped discussion without moving the reader', async () => {+ const discussion = commentsLogic(discussionProps)+ discussion.mount()+ const refreshComments = jest.spyOn(discussion.actions, 'refreshComments')+ const loadComments = jest.spyOn(discussion.actions, 'loadComments')++ logic.actions.pollDiscussionThread()+ await expectLogic(logic).toFinishAllListeners()++ expect(refreshComments).toHaveBeenCalledTimes(1)+ expect(loadComments).not.toHaveBeenCalled()++ refreshComments.mockRestore()+ loadComments.mockRestore()+ discussion.unmount()+ })++ // An edit or a completed task leaves the comment count untouched, so a count-based gate would+ // leave the card and the open panel showing text nobody has written for a while.+ it('refreshes even when no comment was added or removed', async () => {+ const discussion = commentsLogic(discussionProps)+ discussion.mount()+ const refreshComments = jest.spyOn(discussion.actions, 'refreshComments')++ logic.actions.pollDiscussionThread()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.pollDiscussionThread()+ await expectLogic(logic).toFinishAllListeners()++ expect(refreshComments).toHaveBeenCalledTimes(2)++ refreshComments.mockRestore()+ discussion.unmount()+ })++ it('does not refresh when the discussions flag is off', async () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC]: false })+ const discussion = commentsLogic(discussionProps)+ discussion.mount()+ const refreshComments = jest.spyOn(discussion.actions, 'refreshComments')++ logic.actions.pollDiscussionThread()+ await expectLogic(logic).toFinishAllListeners()++ expect(refreshComments).not.toHaveBeenCalled()++ refreshComments.mockRestore()+ discussion.unmount()+ })++ // findMounted is only a null guard. In the app the ticket page mounts this logic to render its+ // cards, so the poll does reach it on every open ticket; this covers the torn-down case only.+ it('does not throw when the discussion logic is not mounted', async () => {+ expect(commentsLogic.findMounted(discussionProps)).toBeNull()++ logic.actions.pollDiscussionThread()+ await expectLogic(logic).toFinishAllListeners()++ expect(commentsLogic.findMounted(discussionProps)).toBeNull()+ })+})diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex de06ab87f938..e075b525c8e1 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -28,6 +28,7 @@ import { isUUIDLike } from 'lib/utils/guards'import { markdownToHtml } from 'lib/utils/markdown'import { objectsEqual } from 'lib/utils/objects'import { fullName } from 'lib/utils/strings'+import { commentsLogic } from 'scenes/comments/commentsLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'@@ -72,6 +73,8 @@ import { conversationsDraftModeLogic } from '../settings/conversationsDraftModeLimport { supportTicketsSceneLogic } from '../tickets/supportTicketsSceneLogic'const MESSAGE_POLL_INTERVAL = 5000 // 5 seconds+/** Discussions ride the message timer at 1/4 the rate, so ~20s. */+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@@ -232,6 +235,7 @@ export interface supportTicketSceneLogicValues {breadcrumbs: Breadcrumb[]chatMessages: ChatMessage[]chatPanelWidth: (desiredSize: number | null) => number+ discussionsEnabled: booleandraftContent: string | JSONContent | nulldraftIsPrivate: booleandraftModeEnabled: boolean@@ -387,6 +391,9 @@ export interface supportTicketSceneLogicActions {loadTicket: () => {value: true}+ pollDiscussionThread: () => {+ value: true+ }recordAiReplyFeedback: (messageId: string,rating: AiReplyFeedbackRating@@ -496,7 +503,8 @@ export interface supportTicketSceneLogicMeta {ticket: Ticket | null,currentTeam: TeamPublicType | TeamType | null) => EmailReplyBlockedReason | null- sidePanelContext: (ticket: Ticket | null, featureFlags: FeatureFlagsSet) => SidePanelSceneContext | null+ discussionsEnabled: (ticket: Ticket | null, featureFlags: FeatureFlagsSet) => boolean+ sidePanelContext: (ticket: Ticket | null, discussionsEnabled: boolean) => SidePanelSceneContext | nullreplyRecipientDescription: (ticket: Ticket | null) => stringunsavedTicketChanges: (priority: TicketPriority | null,@@ -564,6 +572,8 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([setMessagesLoading: (loading: boolean) => ({ loading }),appendMessage: (message: CommentType) => ({ message }),+ pollDiscussionThread: true,+loadOlderMessages: true,setOlderMessages: (olderMessages: CommentType[]) => ({ olderMessages }),setOlderMessagesLoading: (loading: boolean) => ({ loading }),@@ -912,9 +922,17 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([): EmailReplyBlockedReason | null =>getEmailReplyBlockedReason(ticket, currentTeam?.conversations_settings),],- [SIDE_PANEL_CONTEXT_KEY]: [+ // Whether this ticket has a discussion at all. The side-panel context, the in-thread discussion+ // cards and the "Discuss with team" button all hang off this one gate so they can't drift into+ // a state where one of them offers a discussion the others don't know about.+ discussionsEnabled: [(s) => [s.ticket, s.featureFlags],- (ticket: Ticket | null, featureFlags: FeatureFlagsSet): SidePanelSceneContext | null =>+ (ticket: Ticket | null, featureFlags: FeatureFlagsSet): boolean =>+ !!ticket?.id && !!featureFlags[FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC],+ ],+ [SIDE_PANEL_CONTEXT_KEY]: [+ (s) => [s.ticket, s.discussionsEnabled],+ (ticket: Ticket | null, discussionsEnabled: boolean): SidePanelSceneContext | null =>ticket?.id? {access_control_resource: 'ticket',@@ -922,7 +940,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([// Scoping the discussion thread to the ticket is still flag-gated; the// access control fields above are not, so the panel stays gated on// ticket access either way.- ...(featureFlags[FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC]+ ...(discussionsEnabled? {activity_scope: ActivityScope.TICKET,activity_item_id: `${ticket.id}`,@@ -1155,9 +1173,17 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([// Start message polling using disposables patterncache.disposables.dispose('messagePolling')+ cache.discussionPollTick = 0cache.disposables.add(() => {const intervalId = setInterval(() => {actions.loadMessages()+ // A discussion is a slower conversation than the ticket itself, and a Slack+ // reply landing a few seconds late costs nothing — so it rides the same timer+ // at a fraction of the rate rather than starting a second one.+ cache.discussionPollTick = (cache.discussionPollTick ?? 0) + 1+ if (cache.discussionPollTick % DISCUSSION_POLL_EVERY_N_TICKS === 0) {+ actions.pollDiscussionThread()+ }}, MESSAGE_POLL_INTERVAL)return () => clearInterval(intervalId)}, 'messagePolling')@@ -1225,6 +1251,26 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([}}},+ // Refetches the whole discussion rather than checking a count first. A count only moves when a+ // comment is added or removed, so an edit or a task being completed would leave the card and the+ // open side panel showing text nobody has written for a while.+ //+ // `refreshComments` rather than `loadComments` because refreshing must not move the reader:+ // `loadComments` scrolls the panel to the newest comment on every success, which is right when+ // someone opens the thread and wrong every 20 seconds while they read back through it.+ pollDiscussionThread: async () => {+ const ticketId = values.ticket?.id+ if (!values.discussionsEnabled || !ticketId) {+ return+ }+ // findMounted is a null guard, not an optimisation: the ticket page mounts this logic to+ // render its discussion cards, so on a flagged team it is mounted for every open ticket+ // whether or not that ticket has any discussion. Every such ticket therefore pays one+ // indexed comment query per interval. That is deliberate — a teammate starting a+ // discussion elsewhere should make the card appear here, which is the moment this whole+ // surface exists for, and it cannot be detected without asking.+ commentsLogic.findMounted({ scope: ActivityScope.TICKET, item_id: ticketId })?.actions.refreshComments()+ },loadMessages: async () => {if (props.id === 'new' || !values.ticket?.id) {actions.setMessages([])