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.

40.8 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'

import { lemonToast } from '@posthog/lemon-ui'

import api, { ApiError } from 'lib/api'
import { JSONContent, RichContentEditorType } from 'lib/components/RichContentEditor/types'
import { slackChannelId } from 'lib/integrations/slackChannel'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { isEmptyObject } from 'lib/utils/guards'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'

import { sidePanelDiscussionLogic } from '~/layout/navigation-3000/sidepanel/panels/discussion/sidePanelDiscussionLogic'
import { membersLogic } from '~/models/membersLogic'
import { ActivityScope, CommentType } from '~/types'
import type { OrganizationMemberType, UserType } from '~/types'

import { commentsSendToSlackCreate } from 'products/platform_features/frontend/generated/api'

import { sendCommentToSlackLogic } from './sendCommentToSlackLogic'
import { discussionsSlug, getTextContent } from './utils'

export type CommentsLogicProps = {
    scope: CommentType['scope']
    item_id?: CommentType['item_id']
    item_context?: CommentType['item_context']
    disabled?: boolean
}

export type CommentWithRepliesType = {
    id: CommentType['id']
    comment?: CommentType // It may have been deleted
    replies: CommentType[]
}

export type CommentContext = {
    context: Record<string, any> | null
    callback?: (event: { sent: boolean }) => void
}

/** 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
    currentProjectId: number | string // teamLogic
    user: UserType | null // userLogic
    commentContexts: Record<string, string>
    comments: CommentType[] | null
    commentsInitialLoading: boolean
    commentsLoading: boolean
    commentsWithReplies: CommentWithRepliesType[]
    composerDrafts: Record<string, JSONContent | null>
    composerSendToSlack: boolean
    composerSlackChannel: string | null
    composerSlackIntegrationId: number | null
    currentComposerDraft: JSONContent | null
    disabledReasonFor: (comment: CommentType) => string | null
    editingComment: CommentType | null
    editingCommentExistingMentions: number[] | null
    editingCommentRichContentEditor: RichContentEditorType | null
    emojiReactionsByComment: Record<string, Record<string, CommentType[]>>
    expandedThreadIds: Set<string>
    isEditingCommentEmpty: boolean
    isEmpty: boolean
    isMyComment: (comment: CommentType) => boolean
    isSavingEditedComment: boolean
    isSendingComment: boolean
    itemContext: CommentContext | null
    key: string
    replyingCommentId: string | null
    richContentEditor: RichContentEditorType | null
    selectedCommentId: string | null
    sendToSlackDisabledReasonFor: (comment: CommentType) => string | null
    sortedComments: CommentType[]
    threadExpansion: Record<string, boolean>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface commentsLogicActions {
    ensureAllMembersLoaded: () => {
        value: true
    } // membersLogic
    incrementCommentCount: () => any // sidePanelDiscussionLogic
    scrollToLastComment: () => {
        value: true
    } // sidePanelDiscussionLogic
    clearItemContext: () => {
        value: true
    }
    clearRichContentEditor: () => {
        value: true
    }
    completeComment: (comment: CommentType) => {
        comment: CommentType
    }
    completeCommentFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    completeCommentSuccess: (
        comments: CommentType[],
        payload?: {
            comment: CommentType
        }
    ) => {
        comments: CommentType[]
        payload?: {
            comment: CommentType
        }
    }
    deleteComment: (comment: CommentType) => {
        comment: CommentType
    }
    deleteCommentFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteCommentSuccess: (
        comments: CommentType[] | null,
        payload?: {
            comment: CommentType
        }
    ) => {
        comments: CommentType[] | null
        payload?: {
            comment: CommentType
        }
    }
    loadComments: () => {
        value: true
    }
    loadCommentsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCommentsSuccess: (
        comments: CommentType[],
        payload?: {
            value: true
        }
    ) => {
        comments: CommentType[]
        payload?: {
            value: true
        }
    }
    maybeLoadComments: () => {
        value: true
    }
    onEditingCommentRichContentEditorUpdate: (isEmpty: boolean) => {
        isEmpty: boolean
    }
    onRichContentEditorUpdate: (isEmpty: boolean) => {
        isEmpty: boolean
    }
    persistEditedComment: () => {
        value: true
    }
    persistEditedCommentFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    persistEditedCommentSuccess: (
        comments: CommentType[],
        payload?: {
            value: true
        }
    ) => {
        comments: CommentType[]
        payload?: {
            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
    }
    reopenCommentFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    reopenCommentSuccess: (
        comments: CommentType[],
        payload?: {
            comment: CommentType
        }
    ) => {
        comments: CommentType[]
        payload?: {
            comment: CommentType
        }
    }
    revealSelectedComment: () => {
        value: true
    }
    sendComposedContent: (asTask?: boolean) => {
        asTask: boolean
    }
    sendComposedContentFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    sendComposedContentSuccess: (
        comments: CommentType[],
        payload?: {
            asTask: boolean
        }
    ) => {
        comments: CommentType[]
        payload?: {
            asTask: boolean
        }
    }
    sendEmojiReaction: (
        emoji: string,
        sourceCommentId: string
    ) => {
        emoji: string
        sourceCommentId: string
    }
    sendEmojiReactionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    sendEmojiReactionSuccess: (
        comments: CommentType[],
        payload?: {
            emoji: string
            sourceCommentId: string
        }
    ) => {
        comments: CommentType[]
        payload?: {
            emoji: string
            sourceCommentId: string
        }
    }
    setCommentContexts: (contexts: Record<string, string>) => {
        contexts: Record<string, string>
    }
    setComposerDraft: (
        target: string,
        content: JSONContent | null
    ) => {
        content: JSONContent | null
        target: string
    }
    setComposerSendToSlack: (enabled: boolean) => {
        enabled: boolean
    }
    setComposerSlackChannel: (channel: string | null) => {
        channel: string | null
    }
    setComposerSlackIntegrationId: (integrationId: number | null) => {
        integrationId: number | null
    }
    setEditingComment: (comment: CommentType | null) => {
        comment: CommentType | null
    }
    setEditingCommentRichContentEditor: (editor: RichContentEditorType | null) => {
        editor: RichContentEditorType | null
    }
    setItemContext: (
        context: Record<string, any> | null,
        callback?: (event: { sent: boolean }) => void
    ) => {
        callback: ((event: { sent: boolean }) => void) | undefined
        context: Record<string, any> | null
    }
    setReplyingComment: (commentId: string | null) => {
        commentId: string | null
    }
    setRichContentEditor: (editor: RichContentEditorType) => {
        editor: RichContentEditorType
    }
    setSelectedComment: (
        commentId: string | null,
        reveal?: boolean
    ) => {
        commentId: string | null
        reveal: boolean
    }
    setThreadExpanded: (
        threadId: string,
        expanded: boolean
    ) => {
        expanded: boolean
        threadId: string
    }
    startNewComment: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface commentsLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        key: (arg: any) => string
        commentsInitialLoading: (comments: CommentType[] | null, commentsLoading: boolean) => boolean
        sortedComments: (comments: CommentType[] | null) => CommentType[]
        commentsWithReplies: (sortedComments: CommentType[]) => CommentWithRepliesType[]
        emojiReactionsByComment: (sortedComments: CommentType[]) => Record<string, Record<string, CommentType[]>>
        expandedThreadIds: (threadExpansion: Record<string, boolean>, replyingCommentId: string | null) => Set<string>
        currentComposerDraft: (
            composerDrafts: Record<string, JSONContent | null>,
            replyingCommentId: string | null
        ) => JSONContent | null
        isMyComment: (user: UserType | null) => (comment: CommentType) => boolean
        disabledReasonFor: (user: UserType | null) => (comment: CommentType) => string | null
        sendToSlackDisabledReasonFor: (
            isMyComment: (comment: CommentType) => boolean
        ) => (comment: CommentType) => string | null
    }
}

export type commentsLogicType = MakeLogicType<
    commentsLogicValues,
    commentsLogicActions,
    CommentsLogicProps,
    commentsLogicMeta
>

export const commentsLogic = kea<commentsLogicType>([
    path(() => ['lib', 'components', 'Comments', 'commentsLogic']),
    props({} as CommentsLogicProps),
    key((props) => `${props.scope}-${props.item_id || ''}`),

    connect(() => ({
        actions: [
            sidePanelDiscussionLogic,
            ['incrementCommentCount', 'scrollToLastComment'],
            membersLogic,
            ['ensureAllMembersLoaded'],
        ],
        values: [userLogic, ['user'], membersLogic, ['meFirstMembers'], teamLogic, ['currentProjectId']],
    })),

    actions({
        loadComments: true,
        refreshComments: true,
        clearItemContext: true,
        maybeLoadComments: true,
        sendComposedContent: (asTask: boolean = false) => ({ asTask }),
        persistEditedComment: true,
        onRichContentEditorUpdate: (isEmpty: boolean) => ({ isEmpty }),
        onEditingCommentRichContentEditorUpdate: (isEmpty: boolean) => ({ isEmpty }),
        sendEmojiReaction: (emoji: string, sourceCommentId: string) => ({ emoji, sourceCommentId }),
        deleteComment: (comment: CommentType) => ({ comment }),
        completeComment: (comment: CommentType) => ({ comment }),
        reopenComment: (comment: CommentType) => ({ comment }),
        setEditingComment: (comment: CommentType | null) => ({ comment }),
        setReplyingComment: (commentId: string | null) => ({ commentId }),
        setSelectedComment: (commentId: string | null, reveal: boolean = false) => ({ commentId, reveal }),
        setThreadExpanded: (threadId: string, expanded: boolean) => ({ threadId, expanded }),
        revealSelectedComment: true,
        startNewComment: true,
        clearRichContentEditor: true,
        setCommentContexts: (contexts: Record<string, string>) => ({ contexts }),
        setItemContext: (context: Record<string, any> | null, callback?: (event: { sent: boolean }) => void) => ({
            context,
            callback,
        }),
        setRichContentEditor: (editor: RichContentEditorType) => ({ editor }),
        setEditingCommentRichContentEditor: (editor: RichContentEditorType | null) => ({ editor }),
        setComposerDraft: (target: string, content: JSONContent | null) => ({ target, content }),
        setComposerSendToSlack: (enabled: boolean) => ({ enabled }),
        setComposerSlackIntegrationId: (integrationId: number | null) => ({ integrationId }),
        setComposerSlackChannel: (channel: string | null) => ({ channel }),
    }),
    reducers({
        composerSendToSlack: [
            false,
            {
                setComposerSendToSlack: (_, { enabled }) => enabled,
                // Reset the toggle after a send so it doesn't stick across comments.
                sendComposedContentSuccess: () => false,
                // Replies never mirror from the composer and the toggle is hidden while replying —
                // leaving it on would demand a Slack channel for a plain reply and mislabel the button.
                setReplyingComment: (state, { commentId }) => (commentId ? false : state),
            },
        ],
        composerSlackIntegrationId: [
            null as number | null,
            {
                setComposerSlackIntegrationId: (_, { integrationId }) => integrationId,
                sendComposedContentSuccess: () => null,
            },
        ],
        composerSlackChannel: [
            null as string | null,
            {
                setComposerSlackChannel: (_, { channel }) => channel,
                // Picking a different workspace clears the channel.
                setComposerSlackIntegrationId: () => null,
                sendComposedContentSuccess: () => null,
            },
        ],
        replyingCommentId: [
            null as string | null,
            {
                // Deliberately not reset on send: the composer stays open for follow-up replies
                setReplyingComment: (_, { commentId }) => commentId,
            },
        ],
        selectedCommentId: [
            null as string | null,
            {
                setSelectedComment: (_, { commentId }) => commentId,
                setReplyingComment: (state, { commentId }) => commentId ?? state,
                sendComposedContentSuccess: () => null,
            },
        ],
        commentContexts: [
            {} as Record<string, string>,
            {
                setCommentContexts: (_, { contexts }) => contexts,
            },
        ],
        itemContext: [
            null as CommentContext | null,
            {
                setItemContext: (_, itemContext) => (itemContext.context ? itemContext : null),
                sendComposedContentSuccess: () => null,
            },
        ],
        richContentEditor: [
            null as RichContentEditorType | null,
            {
                setRichContentEditor: (_, { editor }) => editor,
                // Deregistered explicitly so editor waiters never grab an unmounting instance
                clearRichContentEditor: () => null,
            },
        ],
        composerDrafts: [
            {} as Record<string, JSONContent | null>,
            {
                setComposerDraft: (state, { target, content }) => ({ ...state, [target]: content }),
            },
        ],
        isSendingComment: [
            false,
            {
                sendComposedContent: () => true,
                sendComposedContentSuccess: () => false,
                sendComposedContentFailure: () => false,
            },
        ],
        threadExpansion: [
            {} as Record<string, boolean>,
            {
                setThreadExpanded: (state, { threadId, expanded }) =>
                    state[threadId] === expanded ? state : { ...state, [threadId]: expanded },
                // Starting a reply pins the thread open so it stays expanded after the reply is sent
                setReplyingComment: (state, { commentId }) =>
                    commentId && !state[commentId] ? { ...state, [commentId]: true } : state,
            },
        ],
        isEmpty: [
            true as boolean,
            {
                onRichContentEditorUpdate: (_, { isEmpty }) => isEmpty,
            },
        ],
        editingComment: [
            null as CommentType | null,
            {
                setEditingComment: (_, { comment }) => comment,
                persistEditedCommentSuccess: () => null,
            },
        ],
        editingCommentRichContentEditor: [
            null as RichContentEditorType | null,
            {
                setEditingCommentRichContentEditor: (_, { editor }) => editor,
                persistEditedCommentSuccess: () => null,
            },
        ],
        editingCommentExistingMentions: [
            null as number[] | null,
            {
                setEditingCommentRichContentEditor: (_, { editor }) => editor?.getMentions() ?? [],
                persistEditedCommentSuccess: () => null,
            },
        ],
        isEditingCommentEmpty: [
            false as boolean,
            {
                onEditingCommentRichContentEditorUpdate: (_, { isEmpty }) => isEmpty,
                persistEditedCommentSuccess: () => false,
            },
        ],
        isSavingEditedComment: [
            false,
            {
                persistEditedComment: () => true,
                persistEditedCommentSuccess: () => false,
                persistEditedCommentFailure: () => false,
            },
        ],
    }),
    loaders(({ props, values, actions, cache }) => ({
        comments: [
            null as CommentType[] | null,
            {
                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 ?? []

                    if (!props.item_id) {
                        console.error('Failed to create a comment because no item_id was provided')
                        return existingComments
                    }

                    if (values.richContentEditor?.isEmpty()) {
                        console.error('Failed to create a comment because the content was empty')
                        return existingComments
                    }

                    let itemContext: Record<string, any> | undefined = {
                        ...values.itemContext?.context,
                        ...props.item_context,
                    }
                    if (isEmptyObject(itemContext)) {
                        itemContext = undefined
                    }

                    const mentions = values.richContentEditor?.getMentions() ?? []

                    const content = values.richContentEditor?.getJSON()

                    const textContent = getTextContent(content, values.meFirstMembers)

                    const composerAnchor = values.itemContext?.context
                    const isNewAnchoredThread =
                        composerAnchor && (composerAnchor.type === 'mark' || composerAnchor.type === 'node')

                    const isReply = !isNewAnchoredThread && !!values.replyingCommentId

                    // The composer can remount or retarget while the request is in flight -
                    // the success listener must act on what was true at send time
                    cache.sendContext = {
                        editor: values.richContentEditor,
                        wasReply: isReply,
                        draftTarget: isReply ? values.replyingCommentId : FOOTER_COMPOSER_TARGET,
                    }

                    const newComment = await api.comments.create({
                        rich_content: content,
                        content: textContent,
                        scope: props.scope,
                        item_id: props.item_id,
                        item_context: itemContext,
                        source_comment: isNewAnchoredThread ? undefined : (values.replyingCommentId ?? undefined),
                        mentions,
                        slug: discussionsSlug(props.scope, props.item_id),
                        is_task: asTask && !isReply,
                    })
                    posthog.capture('comment created', { scope: props.scope, is_reply: isReply, is_emoji: false })

                    values.itemContext?.callback?.({ sent: true })

                    // "Send to Slack" composer mode: mirror the new top-level comment to the chosen
                    // channel right away. Replies/tasks never mirror from here. The comment is created
                    // regardless; the Slack post is best-effort with its own toast.
                    const composerChannelId = values.composerSlackChannel
                        ? slackChannelId(values.composerSlackChannel)
                        : null
                    if (
                        values.composerSendToSlack &&
                        !isReply &&
                        !asTask &&
                        values.composerSlackIntegrationId &&
                        composerChannelId &&
                        values.currentProjectId
                    ) {
                        let sentToSlack = false
                        try {
                            // The comments API is project-scoped — currentTeamId diverges from the
                            // project id for non-default environments and 404s.
                            await commentsSendToSlackCreate(String(values.currentProjectId), newComment.id, {
                                integration_id: values.composerSlackIntegrationId,
                                channel_id: composerChannelId,
                            })
                            sentToSlack = true
                            lemonToast.success('Discussion sent to Slack')
                        } catch (e) {
                            // Surface the backend's actionable detail (bot not in channel, integration
                            // missing…) rather than a blanket failure.
                            const detail = e instanceof ApiError ? e.detail : null
                            lemonToast.error(
                                detail
                                    ? `Comment added, but sending to Slack failed: ${detail}`
                                    : 'Comment added, but sending to Slack failed'
                            )
                        }
                        if (sentToSlack) {
                            // Refetch and return the fresh list so the new comment shows its tracked-in-Slack
                            // state. We can't dispatch loadComments() here — it writes the same `comments`
                            // loader value this handler returns, and our return would supersede its result.
                            // A refetch failure isn't a Slack failure: fall through to the optimistic append.
                            try {
                                const response = await api.comments.list({
                                    scope: props.scope,
                                    item_id: props.item_id,
                                })
                                return response.results
                            } catch {
                                // fall through
                            }
                        }
                    }

                    return [...existingComments, newComment]
                },

                persistEditedComment: async () => {
                    const existingComments = values.comments ?? []
                    const editedComment = values.editingComment

                    if (!editedComment) {
                        return existingComments
                    }

                    const originalComment = existingComments.find((c) => c.id === editedComment.id)

                    if (!originalComment) {
                        return existingComments
                    }

                    const previousMentions = values.editingCommentExistingMentions ?? []
                    const currentMentions = values.editingCommentRichContentEditor?.getMentions() ?? []
                    const newMentions = currentMentions.filter((m) => !previousMentions.includes(m))

                    const { id, rich_content } = editedComment

                    const textContent = getTextContent(rich_content, values.meFirstMembers)

                    const updatedComment = await api.comments.update(id, {
                        rich_content,
                        content: textContent,
                        mentions: newMentions,
                        slug: discussionsSlug(props.scope, props.item_id),
                    })
                    return [...existingComments.filter((c) => c.id !== editedComment.id), updatedComment]
                },

                deleteComment: async ({ comment }) => {
                    await deleteWithUndo({
                        endpoint: `projects/${values.currentProjectId}/comments`,
                        object: { name: comment.item_context?.is_emoji ? 'Reaction' : 'Comment', id: comment.id },
                        callback: (isUndo) => {
                            if (isUndo) {
                                actions.loadCommentsSuccess([
                                    ...(values.comments?.filter((c) => c.id !== comment.id) ?? []),
                                    comment,
                                ])
                            }
                        },
                    })

                    return values.comments?.filter((c) => c.id !== comment.id) ?? null
                },

                sendEmojiReaction: async ({ emoji, sourceCommentId }) => {
                    const existingComments = values.comments ?? []

                    const newComment = await api.comments.create({
                        content: emoji,
                        scope: props.scope,
                        item_id: props.item_id,
                        source_comment: sourceCommentId,
                        item_context: {
                            is_emoji: true,
                        },
                        mentions: [],
                    })
                    posthog.capture('comment created', {
                        scope: props.scope,
                        is_reply: !!sourceCommentId,
                        is_emoji: true,
                    })

                    return [...existingComments, newComment]
                },

                completeComment: async ({ comment }) => {
                    const updated = await api.comments.complete(comment.id)
                    const existing = values.comments ?? []
                    return existing.map((c) => (c.id === updated.id ? updated : c))
                },

                reopenComment: async ({ comment }) => {
                    const updated = await api.comments.reopen(comment.id)
                    const existing = values.comments ?? []
                    return existing.map((c) => (c.id === updated.id ? updated : c))
                },
            },
        ],
    })),

    listeners(({ props, values, actions, selectors, cache }) => ({
        startNewComment: () => {
            if (!values.replyingCommentId) {
                // No reply to exit, so the footer composer won't remount - deregistering its
                // editor here would orphan it for good. Focus the mounted editor, or arm the
                // flag if the surface hasn't mounted yet (e.g. "Start discussion" opening the panel).
                if (values.richContentEditor) {
                    values.richContentEditor.focus('end')
                } else {
                    cache.focusEditorOnRegister = true
                }
                return
            }
            // Bring the footer composer back focused - it registers on its next mount
            cache.focusEditorOnRegister = true
            actions.setReplyingComment(null)
            actions.clearRichContentEditor()
        },
        setReplyingComment: ({ commentId }, _, __, previousState) => {
            // Save the outgoing composer's text into its own slot before the composer remounts elsewhere
            const previousTarget = selectors.replyingCommentId(previousState) ?? FOOTER_COMPOSER_TARGET
            const editor = values.richContentEditor
            actions.setComposerDraft(previousTarget, editor && !editor.isEmpty() ? editor.getJSON() : null)
            if (commentId) {
                actions.clearItemContext()
            }
        },
        clearItemContext: () => {
            values.itemContext?.callback?.({ sent: false })
            actions.setItemContext(null)
        },
        setItemContext: ({ context }) => {
            if (context) {
                if (values.replyingCommentId) {
                    // Anchored comments and replies are mutually exclusive
                    actions.setReplyingComment(null)
                } else {
                    values.richContentEditor?.focus()
                }
            }
        },
        setRichContentEditor: ({ editor }) => {
            // isEmpty is otherwise only driven by typing - sync it to the (re)mounted editor's
            // seeded content so a restored draft enables sending and a fresh composer disables it
            actions.onRichContentEditorUpdate(editor.isEmpty())
            // The composer just (re)mounted - focus it when the user is mid-flow
            if (values.replyingCommentId || values.itemContext || cache.focusEditorOnRegister) {
                cache.focusEditorOnRegister = false
                editor.focus('end')
            }
        },
        maybeLoadComments: () => {
            if (!values.comments && !values.commentsLoading) {
                actions.loadComments()
            }
        },
        // After the ⋯-menu "Send to Slack" modal mirrors a comment, refresh so its tracked state
        // (the Slack icon) shows immediately instead of after a reload. The composer flow reloads
        // itself in the send loader. The modal logic is a singleton while this logic is keyed per
        // discussion, so only the instance the comment belongs to should reload.
        [sendCommentToSlackLogic.actionTypes.submitSuccess]: ({ comment }) => {
            if (comment.scope === props.scope && (comment.item_id ?? '') === (props.item_id ?? '')) {
                actions.loadComments()
            }
        },
        sendComposedContentSuccess: () => {
            const sendContext = cache.sendContext
            cache.sendContext = null
            // The loader also "succeeds" when it bails before creating anything (no item_id,
            // empty content) - only a real send earns the post-send side effects
            if (!sendContext) {
                return
            }
            const { editor, wasReply, draftTarget } = sendContext
            // Replies land inline mid-list - only new root comments append at the bottom
            if (!wasReply) {
                actions.scrollToLastComment()
            }
            actions.incrementCommentCount()
            actions.setComposerDraft(draftTarget, null)
            // Only touch the editor that sent - the user may have moved to another composer mid-flight
            if (editor && editor === values.richContentEditor) {
                editor.clear()
                if (wasReply) {
                    // Reply mode stays active - refocus the cleared composer for a follow-up reply
                    editor.focus('end')
                }
            }
        },
        setSelectedComment: ({ commentId, reveal }) => {
            // Revealing is deep-link behavior. Local click-selection (the highlight wash) must
            // not expand collapsed threads - e.g. clicking a comment's emoji reaction button.
            cache.revealSelectedCommentOnLoad = !!(reveal && commentId)
            if (reveal && commentId) {
                actions.revealSelectedComment()
            }
        },
        revealSelectedComment: () => {
            // A deep-linked comment may live in (or head) a collapsed thread - expand it so it is
            // visible. One-shot on purpose: the user can still collapse the thread again afterwards.
            const selected = values.sortedComments.find((comment) => comment.id === values.selectedCommentId)
            if (selected) {
                cache.revealSelectedCommentOnLoad = false
                actions.setThreadExpanded(selected.source_comment ?? selected.id, true)
            }
        },
        loadCommentsSuccess: () => {
            // A deep link can select a comment before comments have loaded - re-run the reveal now
            if (cache.revealSelectedCommentOnLoad) {
                actions.revealSelectedComment()
            }
            actions.scrollToLastComment()
        },
    })),

    selectors({
        key: [() => [(_, props) => props], (props): string => `${props.scope}-${props.item_id || ''}`],

        // `commentsLoading` is shared by every handler on the `comments` loader, including the
        // background poll's `refreshComments`, so a surface that swaps in a skeleton on it would
        // flash away a thread that has already loaded.
        commentsInitialLoading: [
            (s) => [s.comments, s.commentsLoading],
            (comments: CommentType[] | null, commentsLoading: boolean): boolean => !comments && commentsLoading,
        ],

        sortedComments: [
            (s) => [s.comments],
            (comments: CommentType[] | null) => {
                return comments?.sort((a, b) => (a.created_at > b.created_at ? 1 : -1)) ?? []
            },
        ],

        commentsWithReplies: [
            (s) => [s.sortedComments],
            (sortedComments: CommentType[]) => {
                // NOTE: We build a tree of comments and replies here.
                // Comments may have been deleted so if we have a reply to a comment that no longer exists,
                // we still create the CommentWithRepliesType but with a null comment.

                const commentsById: Record<string, CommentWithRepliesType> = {}

                for (const comment of sortedComments ?? []) {
                    // Skip emoji reactions from the reply tree - they'll be handled separately
                    if (comment.item_context?.is_emoji) {
                        continue
                    }

                    let commentsWithReplies = commentsById[comment.source_comment ?? comment.id]

                    if (!commentsWithReplies) {
                        commentsById[comment.source_comment ?? comment.id] = commentsWithReplies = {
                            id: comment.source_comment ?? comment.id,
                            comment: undefined,
                            replies: [],
                        }
                    }

                    if (commentsWithReplies.id === comment.id) {
                        commentsWithReplies.comment = comment
                    } else {
                        commentsWithReplies.replies.push(comment)
                    }
                }

                return Object.values(commentsById)
            },
        ],

        emojiReactionsByComment: [
            (s) => [s.sortedComments],
            (sortedComments: CommentType[]) => {
                const reactions: Record<CommentType['id'], Record<string, CommentType[]>> = {}

                for (const comment of sortedComments ?? []) {
                    if (comment.item_context?.is_emoji && comment.source_comment) {
                        if (!reactions[comment.source_comment]) {
                            reactions[comment.source_comment] = {}
                        }
                        // TODO: emoji reactions still use the content field for now
                        const emoji = comment.content!
                        if (!reactions[comment.source_comment][emoji]) {
                            reactions[comment.source_comment][emoji] = []
                        }
                        reactions[comment.source_comment][emoji].push(comment)
                    }
                }

                return reactions
            },
        ],

        expandedThreadIds: [
            (s) => [s.threadExpansion, s.replyingCommentId],
            (threadExpansion: Record<string, boolean>, replyingCommentId: string | null): Set<string> => {
                const expanded = new Set(
                    Object.entries(threadExpansion)
                        .filter(([, isExpanded]) => isExpanded)
                        .map(([threadId]) => threadId)
                )
                // Only the thread being replied to is uncollapsible - it hosts the inline composer
                if (replyingCommentId) {
                    expanded.add(replyingCommentId)
                }
                return expanded
            },
        ],

        currentComposerDraft: [
            (s) => [s.composerDrafts, s.replyingCommentId],
            (
                composerDrafts: Record<string, JSONContent | null>,
                replyingCommentId: string | null
            ): JSONContent | null => composerDrafts[replyingCommentId ?? FOOTER_COMPOSER_TARGET] ?? null,
        ],

        isMyComment: [
            (s) => [s.user],
            (user: null | import('~/types').UserType) => {
                return (comment: CommentType): boolean => comment.created_by?.uuid === user?.uuid
            },
        ],

        disabledReasonFor: [
            (s) => [s.user],
            (user: null | import('~/types').UserType) => {
                return (comment: CommentType): string | null =>
                    comment.created_by?.uuid === user?.uuid ? null : 'You can only delete your own comments'
            },
        ],

        sendToSlackDisabledReasonFor: [
            (s) => [s.isMyComment],
            (isMyComment: (comment: CommentType) => boolean) => {
                return (comment: CommentType): string | null =>
                    comment.scope === ActivityScope.TICKET && !isMyComment(comment)
                        ? 'Only the person who started this discussion can send it to Slack'
                        : null
            },
        ],
    }),

    subscriptions(({ actions, values }) => ({
        commentsWithReplies: (commentsWithReplies: CommentWithRepliesType[]) => {
            // If the thread being replied to stops rendering (deleted, or dropped on reload),
            // clear the reply so the footer composer returns instead of no composer at all.
            // The setReplyingComment listener preserves any typed draft.
            const target = values.replyingCommentId
            if (target && !commentsWithReplies.some((thread) => thread.id === target)) {
                actions.setReplyingComment(null)
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.ensureAllMembersLoaded()
    }),
])