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.

feat(comments): improve discussion threading and reply UX (#71827)

Luke Beltonf5daf527e5cd
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 054e679f0c76..594389f51df6 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5806,6 +5806,14 @@ snapshots:
hash: v1.k794b7964.c5aa3840807ca349309a893b884ebc767c8fab70a82127532c1dae27d13f9f3d.51y_th6-WoFAlLgiWfsu6KUr3rxWjZzAbV84FIikvXQ
scenes-app-data-warehouse-sql-editor--top-tools-per-server--light:
hash: v1.k794b7964.e6420f44b86930d43085b575192d3c26ac0401919a4af6f8d7bd1c799e964836.pZmiZ4w-9QbQ60TFc6Sx94NT0YmU4EULydWdqDqxDmY
+ scenes-app-discussions--replying-to-thread--dark:
+ hash: v1.k794b7964.c2c9d9beff1e3fa0fc6a314aa073610d674eb9cd4af235b31a81e09462b5b58e.-fbBmBjOrnXiwY_8KrKftI-k7wWP9L77S8rFDSiiI3U
+ scenes-app-discussions--replying-to-thread--light:
+ hash: v1.k794b7964.ec768496a555f9760ec89ef559f74ee0a4264944064e37791c088009f518823b.wg3x-JO05TK0I4_WqVtnqBxAfOiX7F6vBGaE9tMXdpw
+ scenes-app-discussions--threads--dark:
+ hash: v1.k794b7964.fadc2b2c0b5eedb49391586e0b3e5ea2aa845dd0b27c006cfad7389017158568.9Gke9ur_lx2xjtG29fVYUTYyUhDzjVg-dWWgpo5znTQ
+ scenes-app-discussions--threads--light:
+ hash: v1.k794b7964.28ac830bf83be5cbb6d7a397d67c9b9c61711904a822de38402b82220b0f7a49.7wENY7hvo1-qAJwq5fcsvKGJsfRAF_vDkpnM8iqFZcc
scenes-app-engineering-analytics-repo-overview--repo-overview--dark:
hash: v1.k794b7964.2f6a03768f7fd744209d68ad0d4ed30f8f13e6457c005caee001711bce72559a.wGhGJXZVT2RMHTY1nYDEsKOe8gs15i8OKJTOiHy6M2A
scenes-app-engineering-analytics-repo-overview--repo-overview--light:
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/discussion/SidePanelDiscussion.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/discussion/SidePanelDiscussion.tsx
index 7f4942664ab9..5f387c2a05f6 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/discussion/SidePanelDiscussion.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/discussion/SidePanelDiscussion.tsx
@@ -81,8 +81,8 @@ const DiscussionContent = ({
const { setCommentsListRef } = useActions(sidePanelDiscussionLogic)
useEffect(() => {
- // Use setSelectedComment without auto-focusing the composer
- setSelectedComment(selectedTabOptions ?? null)
+ // Select without auto-focusing the composer; reveal expands the thread the deep link targets
+ setSelectedComment(selectedTabOptions ?? null, true)
}, [selectedTabOptions]) // oxlint-disable-line react-hooks/exhaustive-deps
return (
diff --git a/frontend/src/lib/components/EmojiPicker/EmojiPickerPopover.tsx b/frontend/src/lib/components/EmojiPicker/EmojiPickerPopover.tsx
index 079ed30fff88..93714e66266c 100644
--- a/frontend/src/lib/components/EmojiPicker/EmojiPickerPopover.tsx
+++ b/frontend/src/lib/components/EmojiPicker/EmojiPickerPopover.tsx
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { IconEmojiAdd } from '@posthog/icons'
-import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonButton, LemonButtonProps } from 'lib/lemon-ui/LemonButton'
import { Popover } from 'lib/lemon-ui/Popover'
import { EmojiPickerPanel } from './EmojiPickerPanel'
@@ -18,6 +18,11 @@ export interface EmojiPickerPopoverProps {
* Defaults to false (closed)
*/
defaultOpen?: boolean
+ /**
+ * Size of the button that opens the popover
+ * Defaults to 'small'
+ */
+ size?: LemonButtonProps['size']
/**
* the data-attr to set on the button that opens and closes the popover
*/
@@ -27,6 +32,7 @@ export interface EmojiPickerPopoverProps {
export function EmojiPickerPopover({
onSelect,
defaultOpen = false,
+ size = 'small',
'data-attr': dataAttr,
}: EmojiPickerPopoverProps): JSX.Element {
const [emojiPickerOpen, setEmojiPickerOpen] = useState(defaultOpen)
@@ -52,7 +58,7 @@ export function EmojiPickerPopover({
onClick={() => {
setEmojiPickerOpen(!emojiPickerOpen)
}}
- size="small"
+ size={size}
/>
</Popover>
)
diff --git a/frontend/src/scenes/comments/Comment.tsx b/frontend/src/scenes/comments/Comment.tsx
index 53252e39dd6b..d1526f14c167 100644
--- a/frontend/src/scenes/comments/Comment.tsx
+++ b/frontend/src/scenes/comments/Comment.tsx
@@ -2,15 +2,16 @@ import { generateText } from '@tiptap/core'
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { useEffect, useRef } from 'react'
+import { useEffect, useMemo, useRef } from 'react'
-import { IconEllipsis, IconEye, IconPencil, IconShare, IconTrash } from '@posthog/icons'
+import { IconChevronRight, IconEllipsis, IconEye, IconPencil, IconTrash } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonMenu, LemonTag, ProfilePicture, Tooltip } from '@posthog/lemon-ui'
import { SentenceList } from 'lib/components/ActivityLog/SentenceList'
import { EmojiPickerPopover } from 'lib/components/EmojiPicker/EmojiPickerPopover'
import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'
import { TZLabel } from 'lib/components/TZLabel'
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import {
@@ -19,23 +20,24 @@ import {
serializationOptions,
} from 'lib/lemon-ui/LemonRichContent/LemonRichContentEditor'
import { colonDelimitedDuration } from 'lib/utils/durations'
+import { pluralize } from 'lib/utils/strings'
import { CommentType } from '~/types'
-import { CommentWithRepliesType, commentsLogic } from './commentsLogic'
+import { CommentComposer } from './CommentComposer'
+import { CommentsLogicProps, CommentWithRepliesType, commentsLogic } from './commentsLogic'
import { getRecordingLinkInfo, isViewingRecording } from './commentUtils'
export type CommentProps = {
commentWithReplies: CommentWithRepliesType
+ /** Mounts the inline reply composer at the thread's bottom while it is the reply target */
+ composerLogicProps: CommentsLogicProps
}
-const CommentBottomRow = ({ comment }: { comment: CommentType }): JSX.Element => {
- const { editingComment, replyingCommentId, emojiReactionsByComment, isMyComment } = useValues(commentsLogic)
+const CommentBottomRow = ({ comment }: { comment: CommentType }): JSX.Element | null => {
+ const { emojiReactionsByComment, isMyComment } = useValues(commentsLogic)
const { deleteComment, sendEmojiReaction } = useActions(commentsLogic)
- const ref = useRef<HTMLDivElement | null>(null)
-
- const isHighlighted = replyingCommentId === comment.id || editingComment?.id === comment.id
const reactions = emojiReactionsByComment[comment.id] || {}
const recordingLinkInfo = getRecordingLinkInfo(comment)
@@ -50,17 +52,16 @@ const CommentBottomRow = ({ comment }: { comment: CommentType }): JSX.Element =>
}
}
- useEffect(() => {
- if (isHighlighted) {
- ref.current?.scrollIntoView()
- }
- }, [isHighlighted])
-
let timeInRecordingLabel: string | null = null
if (comment.item_context?.milliseconds_into_recording !== undefined) {
timeInRecordingLabel = colonDelimitedDuration(comment.item_context?.milliseconds_into_recording / 1000, null)
}
+ // Keep comment cards slim: skip the whole row when there is nothing to show in it
+ if (!recordingLinkInfo && !comment.version && !Object.keys(reactions).length) {
+ return null
+ }
+
return (
<div className="flex flex-row items-center justify-between">
<div className="flex flex-row items-center gap-1">
@@ -113,11 +114,6 @@ const CommentBottomRow = ({ comment }: { comment: CommentType }): JSX.Element =>
</div>
</LemonButton>
))}
- <EmojiPickerPopover
- onSelect={(emoji: string): void => {
- sendEmojiReaction(emoji, comment.id)
- }}
- />
</div>
</div>
</div>
@@ -138,7 +134,8 @@ const CommentEditingForm = ({ comment }: { comment: CommentType }): JSX.Element
<div className="deprecated-space-y-2">
<LemonRichContentEditor
placeholder="Edit comment"
- initialContent={comment.rich_content}
+ // Seed from the in-progress edit so collapsing/expanding the thread mid-edit loses nothing
+ initialContent={editingComment?.rich_content ?? comment.rich_content}
onCreate={setEditingCommentRichContentEditor}
onUpdate={(isEmpty) => {
if (editingCommentRichContentEditor && editingComment) {
@@ -180,7 +177,7 @@ const CommentEditingForm = ({ comment }: { comment: CommentType }): JSX.Element
const CommentTopRow = ({ comment }: { comment: CommentType }): JSX.Element => {
const { disabledReasonFor } = useValues(commentsLogic)
- const { deleteComment, setEditingComment, setReplyingComment } = useActions(commentsLogic)
+ const { deleteComment, setEditingComment, sendEmojiReaction } = useActions(commentsLogic)
const isCompleted = !!comment.completed_at
@@ -203,13 +200,19 @@ const CommentTopRow = ({ comment }: { comment: CommentType }): JSX.Element => {
</span>
) : null}
+ {/* has-[…active] holds the trigger visible while its picker is open - focus sits in the portal, so focus-within can't */}
+ <span className="opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100 has-[.LemonButton--active]:opacity-100">
+ <EmojiPickerPopover
+ size="xsmall"
+ onSelect={(emoji: string): void => {
+ sendEmojiReaction(emoji, comment.id)
+ }}
+ data-attr="comment-react-button"
+ />
+ </span>
+
<LemonMenu
items={[
- {
- icon: <IconShare />,
- label: 'Reply',
- onClick: () => setReplyingComment(comment.source_comment ?? comment.id),
- },
{
icon: <IconPencil />,
label: 'Edit',
@@ -231,7 +234,7 @@ const CommentTopRow = ({ comment }: { comment: CommentType }): JSX.Element => {
}
const Comment = ({ comment }: { comment: CommentType }): JSX.Element => {
- const { editingComment, replyingCommentId, selectedCommentId, commentContexts } = useValues(commentsLogic)
+ const { editingComment, selectedCommentId, commentContexts } = useValues(commentsLogic)
const { setSelectedComment, completeComment, reopenComment } = useActions(commentsLogic)
const contextText = commentContexts[comment.id]
const isInlineComment = comment.item_context?.type === 'mark'
@@ -239,24 +242,25 @@ const Comment = ({ comment }: { comment: CommentType }): JSX.Element => {
const ref = useRef<HTMLDivElement | null>(null)
const isEditing = editingComment?.id === comment.id
- const isHighlighted = selectedCommentId === comment.id || replyingCommentId === comment.id || isEditing
+ // Selection-driven so deep links can highlight their target even while a reply is open;
+ // the reply target already shows via the card's accent border
+ const isHighlighted = selectedCommentId === comment.id || isEditing
const threadId = comment.source_comment ?? comment.id
+ // Rendering markdown from tiptap JSON is not free - skip it on unrelated re-renders
+ const text = useMemo(() => getText(comment), [comment])
useEffect(() => {
if (isHighlighted) {
- ref.current?.scrollIntoView()
+ ref.current?.scrollIntoView({ block: 'nearest' })
}
}, [isHighlighted])
return (
<div
ref={ref}
- className={clsx(
- 'Comment border rounded-lg bg-surface-primary px-2 py-1',
- isHighlighted && 'border-accent',
- !isEditing && 'cursor-pointer'
- )}
+ className={clsx('Comment group px-2 py-1', isHighlighted && 'bg-fill-highlight-50')}
data-comment-id={comment.id}
+ // Selection is not a visual focus: it drives the notebook mark highlight and deep links
onClick={isEditing ? undefined : () => setSelectedComment(threadId)}
>
<div className="flex items-center gap-3">
@@ -284,7 +288,7 @@ const Comment = ({ comment }: { comment: CommentType }): JSX.Element => {
) : null}
<div className="flex flex-col justify-start gap-2 flex-1 min-w-0">
<div className="flex-1 flex justify-start items-start gap-2">
- <ProfilePicture size="xl" user={comment.created_by} />
+ <ProfilePicture size={comment.source_comment ? 'md' : 'xl'} user={comment.created_by} />
<div className="flex flex-col flex-1 min-w-0">
<CommentTopRow comment={comment} />
@@ -297,7 +301,7 @@ const Comment = ({ comment }: { comment: CommentType }): JSX.Element => {
<CommentEditingForm comment={comment} />
) : (
<div className={clsx(comment.completed_at && 'line-through text-secondary')}>
- <LemonMarkdown lowKeyHeadings>{getText(comment)}</LemonMarkdown>
+ <LemonMarkdown lowKeyHeadings>{text}</LemonMarkdown>
</div>
)}
</div>
@@ -309,33 +313,138 @@ const Comment = ({ comment }: { comment: CommentType }): JSX.Element => {
)
}
-export const CommentWithReplies = ({ commentWithReplies }: CommentProps): JSX.Element => {
+const InlineReplyComposer = ({ logicProps }: { logicProps: CommentsLogicProps }): JSX.Element => {
+ const ref = useRef<HTMLDivElement | null>(null)
+
+ useOnMountEffect(() => {
+ // In long threads the composer mounts below the fold at the thread's bottom
+ ref.current?.scrollIntoView({ block: 'nearest' })
+ })
+
+ return (
+ <div ref={ref}>
+ <CommentComposer {...logicProps} variant="inline-reply" />
+ </div>
+ )
+}
+
+export const CommentWithReplies = ({ commentWithReplies, composerLogicProps }: CommentProps): JSX.Element => {
const { comment, replies } = commentWithReplies
+ const { replyingCommentId, expandedThreadIds, editingComment, itemContext } = useValues(commentsLogic)
+ const { setReplyingComment, setThreadExpanded } = useActions(commentsLogic)
+
+ // replyingCommentId always resolves to the thread root, so this only matches top-level threads
+ const isReplyTarget = replyingCommentId === commentWithReplies.id
+ // expandedThreadIds always includes the reply target, so the composer is never collapsed away
+ const isExpanded = expandedThreadIds.has(commentWithReplies.id)
+ const canToggle = editingComment?.id !== commentWithReplies.id
+
+ // Hidden only while the composer is open - the composer takes over as the reply affordance
+ const replyButton = !isReplyTarget ? (
+ <LemonButton
+ size="xsmall"
+ onClick={() => setReplyingComment(commentWithReplies.id)}
+ data-attr="comment-reply-button"
+ >
+ Reply
+ </LemonButton>
+ ) : null
// TODO: Permissions
return (
- <div className="relative deprecated-space-y-2">
- {comment ? (
- <Comment comment={comment} />
- ) : (
- <div className="border rounded border-dashed p-2 font-semibold italic bg-surface-primary text-secondary">
- Deleted comment
- </div>
- )}
-
- <div className="pl-8 deprecated-space-y-2">
- {replies?.map((x) => (
- <CommentWithReplies
- key={x.id}
- commentWithReplies={{
- id: x.id,
- comment: x,
- replies: [],
- }}
- />
- ))}
+ <div className={clsx('border rounded-lg bg-surface-primary overflow-hidden', isReplyTarget && 'border-accent')}>
+ <div
+ className={canToggle ? 'cursor-pointer' : undefined}
+ data-attr={canToggle ? 'comment-thread-toggle' : undefined}
+ onClick={
+ canToggle
+ ? (e) => {
+ const target = e.target as HTMLElement
+ // Popover content (emoji picker etc.) bubbles clicks here through its
+ // portal without being a DOM descendant of the card - never toggle on those
+ if (!e.currentTarget.contains(target)) {
+ return
+ }
+ // Leave clicks on inner controls and text selections alone
+ if (target.closest('button, a, label, input, textarea, [contenteditable="true"]')) {
+ return
+ }
+ if (window.getSelection()?.toString()) {
+ return
+ }
+ // Open = replies visible with a focused composer; closing puts both away
+ if (isExpanded) {
+ if (isReplyTarget) {
+ setReplyingComment(null)
+ }
+ setThreadExpanded(commentWithReplies.id, false)
+ } else if (itemContext) {
+ // An in-progress anchored comment survives a peek - only the
+ // explicit Reply button trades the anchor for a reply
+ setThreadExpanded(commentWithReplies.id, true)
+ } else {
+ setReplyingComment(commentWithReplies.id)
+ }
+ }
+ : undefined
+ }
+ >
+ {comment ? (
+ <Comment comment={comment} />
+ ) : (
+ <div className="px-2 py-1 font-semibold italic text-secondary">Deleted comment</div>
+ )}
+
+ {replies.length > 0 ? (
+ <>
+ <LemonDivider className="my-0" />
+ <div className="flex items-center px-2 py-1 text-xs text-secondary">
+ {/* Keyboard path to the toggle - Enter/Space expands or collapses without composing */}
+ <div
+ className="flex flex-1 items-center gap-1"
+ role="button"
+ tabIndex={0}
+ aria-expanded={isExpanded}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ if (isExpanded && isReplyTarget) {
+ // The reply pin keeps the thread open - end the reply so collapse takes effect
+ setReplyingComment(null)
+ }
+ setThreadExpanded(commentWithReplies.id, !isExpanded)
+ }
+ }}
+ >
+ <IconChevronRight
+ className={clsx('size-3 shrink-0 transition-transform', isExpanded && 'rotate-90')}
+ />
+ <span>{pluralize(replies.length, 'reply', 'replies')}</span>
+ </div>
+ {/* A sibling of the keyboard toggle, never a descendant - interactive content must not
+ nest. Once expanded, the reply affordance moves to the thread's bottom */}
+ {!isExpanded ? replyButton : null}
+ </div>
+ </>
+ ) : null}
</div>
+
+ {isExpanded ? replies.map((reply) => <Comment key={reply.id} comment={reply} />) : null}
+
+ {isReplyTarget ? (
+ <>
+ <LemonDivider className="my-0" />
+ <div className="p-2">
+ <InlineReplyComposer logicProps={composerLogicProps} />
+ </div>
+ </>
+ ) : isExpanded || replies.length === 0 ? (
+ <>
+ <LemonDivider className="my-0" />
+ <div className="flex justify-end px-2 py-1">{replyButton}</div>
+ </>
+ ) : null}
</div>
)
}
diff --git a/frontend/src/scenes/comments/CommentComposer.tsx b/frontend/src/scenes/comments/CommentComposer.tsx
index 44d140883331..4875e55d9c45 100644
--- a/frontend/src/scenes/comments/CommentComposer.tsx
+++ b/frontend/src/scenes/comments/CommentComposer.tsx
@@ -9,53 +9,80 @@ import { LemonRichContentEditor } from 'lib/lemon-ui/LemonRichContent/LemonRichC
import { CommentsLogicProps, commentsLogic } from './commentsLogic'
-export const CommentComposer = (props: CommentsLogicProps): JSX.Element => {
- const { key, commentsLoading, replyingCommentId, itemContext, isEmpty } = useValues(commentsLogic(props))
- const {
- sendComposedContent,
- setReplyingComment,
- clearItemContext,
- setRichContentEditor,
- onRichContentEditorUpdate,
- } = useActions(commentsLogic(props))
+export type CommentComposerProps = CommentsLogicProps & {
+ /** The footer variant swaps to a "New comment" button while a reply is in progress; 'inline-reply' renders inside the thread */
+ variant?: 'footer' | 'inline-reply'
+}
+
+export const CommentComposer = ({ variant = 'footer', ...props }: CommentComposerProps): JSX.Element => {
+ const { key, isSendingComment, replyingCommentId, itemContext, isEmpty, currentComposerDraft } = useValues(
+ commentsLogic(props)
+ )
+ const { sendComposedContent, clearItemContext, setRichContentEditor, onRichContentEditorUpdate, startNewComment } =
+ useActions(commentsLogic(props))
const placeholder = replyingCommentId
? 'Reply...'
: `Comment on ${props.item_id ? 'this ' : ''}${humanizeScope(props.scope, !!props.item_id)}`
useEffect(() => {
+ // Only the footer owns the item context - the inline reply composer unmounting must not wipe it
+ if (variant !== 'footer') {
+ return
+ }
// Whenever the discussion context changes or we fully unmount we clear the item context
return () => clearItemContext()
// oxlint-disable-next-line exhaustive-deps
- }, [key, clearItemContext])
+ }, [key, variant, clearItemContext])
+
+ if (variant === 'footer' && replyingCommentId) {
+ // The composer is rendered inline in the thread being replied to - offer a way back
+ return (
+ <div className="flex justify-end pt-2">
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={() => startNewComment()}
+ data-attr="discussions-new-comment"
+ >
+ New comment
+ </LemonButton>
+ </div>
+ )
+ }
+
+ const buttonSize = variant === 'inline-reply' ? 'small' : undefined
return (
- <div className="deprecated-space-y-2">
+ <div className="flex flex-col gap-2">
<LemonRichContentEditor
key={key}
logicKey="discussions"
placeholder={placeholder}
+ initialContent={currentComposerDraft}
onCreate={setRichContentEditor}
onUpdate={onRichContentEditorUpdate}
- onPressCmdEnter={() => sendComposedContent(false)}
- disabled={commentsLoading}
+ onPressCmdEnter={() => {
+ // The send buttons are disabled when empty - the shortcut must not bypass that
+ if (!isEmpty) {
+ sendComposedContent(false)
+ }
+ }}
+ disabled={isSendingComment}
/>
<div className="flex justify-between items-center gap-2">
<div className="flex-1" />
- {replyingCommentId ? (
- <LemonButton type="secondary" onClick={() => setReplyingComment(null)}>
- Cancel reply
- </LemonButton>
- ) : null}
{itemContext ? (
- <LemonButton type="secondary" onClick={() => clearItemContext()}>
+ <LemonButton size={buttonSize} type="secondary" onClick={() => clearItemContext()}>
Cancel
</LemonButton>
) : null}
{!replyingCommentId ? (
<LemonButton
+ size={buttonSize}
type="secondary"
onClick={() => sendComposedContent(true)}
+ loading={isSendingComment}
disabledReason={isEmpty ? 'No message' : null}
data-attr="discussions-comment-task"
>
@@ -63,8 +90,10 @@ export const CommentComposer = (props: CommentsLogicProps): JSX.Element => {
</LemonButton>
) : null}
<LemonButton
+ size={buttonSize}
type="primary"
onClick={() => sendComposedContent(false)}
+ loading={isSendingComment}
disabledReason={isEmpty ? 'No message' : null}
sideIcon={<KeyboardShortcut command enter />}
data-attr="discussions-comment"
diff --git a/frontend/src/scenes/comments/CommentsList.tsx b/frontend/src/scenes/comments/CommentsList.tsx
index ea4fd51d1bfd..a9283283ffe7 100644
--- a/frontend/src/scenes/comments/CommentsList.tsx
+++ b/frontend/src/scenes/comments/CommentsList.tsx
@@ -17,13 +17,23 @@ export interface CommentsListProps extends CommentsLogicProps {
export const CommentsList = ({ noun = 'page', ...props }: CommentsListProps): JSX.Element => {
const { key, commentsWithReplies, commentsLoading } = useValues(commentsLogic(props))
- const { loadComments } = useActions(commentsLogic(props))
+ const { loadComments, setReplyingComment, clearRichContentEditor } = useActions(commentsLogic(props))
// If the comment list focus changes we should load the comments
useEffect(() => {
loadComments()
}, [key]) // oxlint-disable-line react-hooks/exhaustive-deps
+ useEffect(() => {
+ return () => {
+ // Closing the surface ends any reply flow so reopening starts fresh everywhere (the
+ // reply text survives in its thread's draft slot), and deregisters the dying editor
+ // so nothing waiting for a composer grabs it
+ setReplyingComment(null)
+ clearRichContentEditor()
+ }
+ }, []) // oxlint-disable-line react-hooks/exhaustive-deps
+
return (
<BindLogic logic={commentsLogic} props={props}>
<div className="flex flex-col">
@@ -44,9 +54,9 @@ export const CommentsList = ({ noun = 'page', ...props }: CommentsListProps): JS
</div>
) : null}
- <div className="deprecated-space-y-2">
+ <div className="flex flex-col gap-4">
{commentsWithReplies?.map((x) => (
- <CommentWithReplies key={x.id} commentWithReplies={x} />
+ <CommentWithReplies key={x.id} commentWithReplies={x} composerLogicProps={props} />
))}
</div>
</div>
diff --git a/frontend/src/scenes/comments/Discussions.stories.tsx b/frontend/src/scenes/comments/Discussions.stories.tsx
new file mode 100644
index 000000000000..db68e6fed946
--- /dev/null
+++ b/frontend/src/scenes/comments/Discussions.stories.tsx
@@ -0,0 +1,59 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useActions } from 'kea'
+
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+
+import { mswDecorator } from '~/mocks/browser'
+import { ActivityScope } from '~/types'
+
+import discussionsJson from './__mocks__/discussions.json'
+import { CommentComposer } from './CommentComposer'
+import { CommentsList } from './CommentsList'
+import { CommentsLogicProps, commentsLogic } from './commentsLogic'
+
+const LOGIC_PROPS: CommentsLogicProps = { scope: ActivityScope.INSIGHT, item_id: '12345' }
+
+type StoryArgs = { replyingTo?: string }
+
+function DiscussionsPanel({ replyingTo }: StoryArgs): JSX.Element {
+ const { setReplyingComment } = useActions(commentsLogic(LOGIC_PROPS))
+
+ useOnMountEffect(() => {
+ if (replyingTo) {
+ setReplyingComment(replyingTo)
+ }
+ })
+
+ return (
+ <div className="w-120 max-w-full flex flex-col gap-2">
+ <CommentsList {...LOGIC_PROPS} />
+ <CommentComposer {...LOGIC_PROPS} />
+ </div>
+ )
+}
+
+const meta: Meta<StoryArgs> = {
+ title: 'Scenes-App/Discussions',
+ parameters: {
+ layout: 'padded',
+ viewMode: 'story',
+ mockDate: '2025-10-10', // To stabilize relative dates
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/comments': discussionsJson,
+ },
+ }),
+ ],
+ render: (args) => <DiscussionsPanel {...args} />,
+}
+export default meta
+
+type Story = StoryObj<StoryArgs>
+
+export const Threads: Story = {}
+
+export const ReplyingToThread: Story = {
+ args: { replyingTo: 'thread-0001' },
+}
diff --git a/frontend/src/scenes/comments/__mocks__/discussions.json b/frontend/src/scenes/comments/__mocks__/discussions.json
new file mode 100644
index 000000000000..ebf7601aba61
--- /dev/null
+++ b/frontend/src/scenes/comments/__mocks__/discussions.json
@@ -0,0 +1,136 @@
+{
+ "next": null,
+ "previous": null,
+ "results": [
+ {
+ "id": "thread-0001",
+ "created_by": {
+ "id": 2,
+ "uuid": "018f1a2b-0000-0000-0000-000000000002",
+ "distinct_id": "annika-distinct-id",
+ "first_name": "Annika",
+ "last_name": "",
+ "email": "[email protected]",
+ "is_email_verified": false,
+ "hedgehog_config": null,
+ "role_at_organization": "engineering"
+ },
+ "deleted": false,
+ "content": "This funnel looks off after the pricing change - conversion at step 2 dropped hard.",
+ "rich_content": null,
+ "version": 0,
+ "created_at": "2025-10-08T10:00:00.000Z",
+ "item_id": "12345",
+ "item_context": null,
+ "scope": "Insight",
+ "source_comment": null,
+ "is_task": false,
+ "completed_at": null,
+ "completed_by": null
+ },
+ {
+ "id": "reply-0001",
+ "created_by": {
+ "id": 3,
+ "uuid": "018f1a2b-0000-0000-0000-000000000003",
+ "distinct_id": "ben-distinct-id",
+ "first_name": "Ben",
+ "last_name": "",
+ "email": "[email protected]",
+ "is_email_verified": false,
+ "hedgehog_config": null,
+ "role_at_organization": "engineering"
+ },
+ "deleted": false,
+ "content": "Good catch - I think the tracking on the new CTA is missing.",
+ "rich_content": null,
+ "version": 0,
+ "created_at": "2025-10-08T11:30:00.000Z",
+ "item_id": "12345",
+ "item_context": null,
+ "scope": "Insight",
+ "source_comment": "thread-0001",
+ "is_task": false,
+ "completed_at": null,
+ "completed_by": null
+ },
+ {
+ "id": "reply-0002",
+ "created_by": {
+ "id": 4,
+ "uuid": "018f1a2b-0000-0000-0000-000000000004",
+ "distinct_id": "cameron-distinct-id",
+ "first_name": "Cameron",
+ "last_name": "",
+ "email": "[email protected]",
+ "is_email_verified": false,
+ "hedgehog_config": null,
+ "role_at_organization": "engineering"
+ },
+ "deleted": false,
+ "content": "Fixed in the latest deploy, keeping an eye on it.",
+ "rich_content": null,
+ "version": 0,
+ "created_at": "2025-10-09T09:15:00.000Z",
+ "item_id": "12345",
+ "item_context": null,
+ "scope": "Insight",
+ "source_comment": "thread-0001",
+ "is_task": false,
+ "completed_at": null,
+ "completed_by": null
+ },
+ {
+ "id": "emoji-0001",
+ "created_by": {
+ "id": 3,
+ "uuid": "018f1a2b-0000-0000-0000-000000000003",
+ "distinct_id": "ben-distinct-id",
+ "first_name": "Ben",
+ "last_name": "",
+ "email": "[email protected]",
+ "is_email_verified": false,
+ "hedgehog_config": null,
+ "role_at_organization": "engineering"
+ },
+ "deleted": false,
+ "content": "👍",
+ "rich_content": null,
+ "version": 0,
+ "created_at": "2025-10-08T10:05:00.000Z",
+ "item_id": "12345",
+ "item_context": { "is_emoji": true },
+ "scope": "Insight",
+ "source_comment": "thread-0001",
+ "is_task": false,
+ "completed_at": null,
+ "completed_by": null
+ },
+ {
+ "id": "task-0001",
+ "created_by": {
+ "id": 2,
+ "uuid": "018f1a2b-0000-0000-0000-000000000002",
+ "distinct_id": "annika-distinct-id",
+ "first_name": "Annika",
+ "last_name": "",
+ "email": "[email protected]",
+ "is_email_verified": false,
+ "hedgehog_config": null,
+ "role_at_organization": "engineering"
+ },
+ "deleted": false,
+ "content": "Add a before/after screenshot to the dashboard description",
+ "rich_content": null,
+ "version": 0,
+ "created_at": "2025-10-09T16:00:00.000Z",
+ "item_id": "12345",
+ "item_context": null,
+ "scope": "Insight",
+ "source_comment": null,
+ "is_task": true,
+ "completed_at": null,
+ "completed_by": null
+ }
+ ]
+}
diff --git a/frontend/src/scenes/comments/commentsLogic.test.ts b/frontend/src/scenes/comments/commentsLogic.test.ts
new file mode 100644
index 000000000000..f1c34d53461f
--- /dev/null
+++ b/frontend/src/scenes/comments/commentsLogic.test.ts
@@ -0,0 +1,361 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { JSONContent, RichContentEditorType } from 'lib/components/RichContentEditor/types'
+
+import { sidePanelDiscussionLogic } from '~/layout/navigation-3000/sidepanel/panels/discussion/sidePanelDiscussionLogic'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { ActivityScope } from '~/types'
+
+import { commentsLogic } from './commentsLogic'
+
+const DRAFT_CONTENT: JSONContent = {
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'draft' }] }],
+}
+
+const makeComment = (id: string, sourceComment: string | null = null): Record<string, any> => ({
+ id,
+ content: id,
+ rich_content: null,
+ version: 0,
+ created_at: '2025-10-08T10:00:00.000Z',
+ created_by: null,
+ source_comment: sourceComment,
+ scope: 'Insight',
+ item_id: '1',
+ item_context: null,
+ is_task: false,
+ completed_at: null,
+ completed_by: null,
+})
+
+const createEditor = (content: JSONContent | null = null): RichContentEditorType =>
+ ({
+ isEmpty: () => content === null,
+ getJSON: () => content,
+ getMentions: () => [],
+ focus: jest.fn(),
+ clear: jest.fn(),
+ }) as unknown as RichContentEditorType
+
+describe('commentsLogic', () => {
+ let logic: ReturnType<typeof commentsLogic.build>
+ let lastCreateBody: Record<string, any> | null = null
+
+ beforeEach(() => {
+ lastCreateBody = null
+ initKeaTests()
+ useMocks({
+ get: {
+ '/api/projects/:team_id/comments': { results: [] },
+ '/api/organizations/@current/members/': { results: [] },
+ },
+ post: {
+ '/api/projects/:team_id/comments': async ({ request }) => {
+ lastCreateBody = (await request.json()) as Record<string, any>
+ return [
+ 201,
+ {
+ ...lastCreateBody,
+ id: 'new-comment',
+ created_at: '2025-10-10T00:00:00.000Z',
+ created_by: null,
+ version: 0,
+ },
+ ]
+ },
+ },
+ })
+ logic = commentsLogic({ scope: ActivityScope.INSIGHT, item_id: '1' })
+ logic.mount()
+ })
+
+ it('captures the composer draft when entering reply mode and clears the item context', async () => {
+ logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))
+ await expectLogic(logic, () => {
+ logic.actions.setItemContext({ type: 'mark', id: 'ctx' })
+ logic.actions.setReplyingComment('thread-1')
+ }).toMatchValues({
+ composerDrafts: { footer: DRAFT_CONTENT },
+ currentComposerDraft: null,
+ replyingCommentId: 'thread-1',
+ itemContext: null,
+ })
+ expect(logic.values.selectedCommentId).toBe('thread-1')
+ })
+
+ it('cancels an in-progress reply when an item context is set', async () => {
+ logic.actions.setRichContentEditor(createEditor(null))
+ await expectLogic(logic, () => {
+ logic.actions.setReplyingComment('thread-1')
+ logic.actions.setItemContext({ type: 'mark', id: 'ctx' })
+ }).toMatchValues({
+ replyingCommentId: null,
+ itemContext: expect.objectContaining({ context: { type: 'mark', id: 'ctx' } }),
+ })
+ })
+
+ it('only focuses a newly registered editor while a reply or item context is active', () => {
+ const footerEditor = createEditor(null)
+ logic.actions.setRichContentEditor(footerEditor)
+ expect(footerEditor.focus).not.toHaveBeenCalled()
+
+ logic.actions.setReplyingComment('thread-1')
+ const inlineEditor = createEditor(null)
+ logic.actions.setRichContentEditor(inlineEditor)
+ expect(inlineEditor.focus).toHaveBeenCalledWith('end')
+ })
+
+ it('creates a reply against the thread root and keeps a cleared, focused composer open', async () => {
+ const editor = createEditor(DRAFT_CONTENT)
+ logic.actions.setRichContentEditor(editor)
+ logic.actions.setReplyingComment('thread-1')
+ await expectLogic(logic, () => {
+ logic.actions.sendComposedContent(false)
+ })
+ .toDispatchActions(['sendComposedContentSuccess'])
+ .toNotHaveDispatchedActions([sidePanelDiscussionLogic.actionTypes.scrollToLastComment])
+ // Reply mode persists so the user can send a follow-up reply straight away
+ .toMatchValues({ replyingCommentId: 'thread-1', currentComposerDraft: null })
+ expect(lastCreateBody?.source_comment).toBe('thread-1')
+ expect(editor.clear).toHaveBeenCalled()
+ expect(editor.focus).toHaveBeenCalledWith('end')
+ })
+
+ it('scrolls to the bottom after sending a top-level comment', async () => {
+ logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))
+ await expectLogic(logic, () => {
+ logic.actions.sendComposedContent(false)
+ }).toDispatchActions(['sendComposedContentSuccess', sidePanelDiscussionLogic.actionTypes.scrollToLastComment])
+ expect(lastCreateBody?.source_comment).toBeUndefined()
+ })
+
+ 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, () => {
+ logic.actions.loadComments()
+ }).toDispatchActions(['loadCommentsSuccess'])
+
+ logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))
+ logic.actions.setReplyingComment('thread-1')
+ expect(logic.values.replyingCommentId).toBe('thread-1')
+
+ useMocks({ get: { '/api/projects/:team_id/comments': { results: [] } } })
+ // The subscription dispatches the clear nested inside the reload dispatch, so
+ // assert the resulting state rather than action order
+ await expectLogic(logic, () => {
+ logic.actions.loadComments()
+ }).toDispatchActions(['loadCommentsSuccess'])
+
+ expect(logic.values.replyingCommentId).toBeNull()
+ expect(logic.values.composerDrafts['thread-1']).toEqual(DRAFT_CONTENT)
+ })
+
+ it('keeps a replied-to thread expanded after the reply flow ends', async () => {
+ logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))
+ logic.actions.setReplyingComment('thread-1')
+ expect(logic.values.expandedThreadIds.has('thread-1')).toBe(true)
+
+ await expectLogic(logic, () => {
+ logic.actions.sendComposedContent(false)
+ }).toDispatchActions(['sendComposedContentSuccess'])
+
+ // Pinned open when the reply started, so the sent reply stays visible even once
+ // the user leaves reply mode
+ logic.actions.setReplyingComment(null)
+ expect(logic.values.expandedThreadIds.has('thread-1')).toBe(true)
+ })
+
+ it('lets a selected thread collapse but keeps the reply target open', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/comments': {
+ results: [makeComment('thread-1'), makeComment('reply-1', 'thread-1')],
+ },
+ },
+ })
+ await expectLogic(logic, () => {
+ logic.actions.loadComments()
+ }).toDispatchActions(['loadCommentsSuccess'])
+
+ // Selecting (clicking) a root comment must not block collapsing its thread
+ logic.actions.setSelectedComment('thread-1')
+ logic.actions.setThreadExpanded('thread-1', true)
+ logic.actions.setThreadExpanded('thread-1', false)
+ expect(logic.values.expandedThreadIds.has('thread-1')).toBe(false)
+
+ // But the thread hosting the inline composer cannot be collapsed out from under it
+ logic.actions.setRichContentEditor(createEditor(null))
+ logic.actions.setReplyingComment('thread-1')
+ logic.actions.setThreadExpanded('thread-1', false)
+ expect(logic.values.expandedThreadIds.has('thread-1')).toBe(true)
+ })
+
+ it('startNewComment exits reply mode and focuses the footer composer once it registers', () => {
+ logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))
+ logic.actions.setReplyingComment('thread-1')
+
+ logic.actions.startNewComment()
+ expect(logic.values.replyingCommentId).toBeNull()
+ // Deregistered so callers waiting for the footer editor never grab the outgoing one
+ expect(logic.values.richContentEditor).toBeNull()
+
+ const footerEditor = createEditor(null)
+ logic.actions.setRichContentEditor(footerEditor)
+ expect(footerEditor.focus).toHaveBeenCalledWith('end')
+
+ // One-shot: an unrelated later remount must not steal focus
+ const remountedEditor = createEditor(null)
+ logic.actions.setRichContentEditor(remountedEditor)
+ expect(remountedEditor.focus).not.toHaveBeenCalled()
+ })
+
+ it('expands the thread containing a deep-linked comment', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/comments': {
+ results: [makeComment('thread-1'), makeComment('reply-1', 'thread-1')],
+ },
+ },
+ })
+ await expectLogic(logic, () => {
+ logic.actions.loadComments()
+ }).toDispatchActions(['loadCommentsSuccess'])
+ expect(logic.values.expandedThreadIds.has('thread-1')).toBe(false)
+
+ // Deep link to a reply reveals its thread
+ logic.actions.setSelectedComment('reply-1', true)
+ expect(logic.values.expandedThreadIds.has('thread-1')).toBe(true)
+
+ // Deep link to a thread root reveals its replies too
+ logic.actions.setThreadExpanded('thread-1', false)
+ logic.actions.setSelectedComment('thread-1', true)
+ expect(logic.values.expandedThreadIds.has('thread-1')).toBe(true)
+ })
+
+ it('does not expand a thread when a comment is selected by clicking', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/comments': {
+ results: [makeComment('thread-1'), makeComment('reply-1', 'thread-1')],
+ },
+ },
+ })
+ await expectLogic(logic, () => {
+ logic.actions.loadComments()
+ }).toDispatchActions(['loadCommentsSuccess'])
+
+ // Clicking inside a comment (e.g. its emoji reaction button) selects it for the
+ // highlight wash - that must not expand the collapsed thread
+ logic.actions.setSelectedComment('thread-1')
+
+ expect(logic.values.selectedCommentId).toBe('thread-1')
+ expect(logic.values.expandedThreadIds.has('thread-1')).toBe(false)
+ })
+
+ it('reveals a deep-linked comment that was selected before comments loaded', async () => {
+ // Deep link lands while comments are still loading - nothing to reveal yet
+ logic.actions.setSelectedComment('reply-1', true)
+
+ useMocks({
+ get: {
+ '/api/projects/:team_id/comments': {
+ results: [makeComment('thread-1'), makeComment('reply-1', 'thread-1')],
+ },
+ },
+ })
+ await expectLogic(logic, () => {
+ logic.actions.loadComments()
+ }).toDispatchActions(['loadCommentsSuccess'])
+
+ expect(logic.values.expandedThreadIds.has('thread-1')).toBe(true)
+
+ // The pending reveal is one-shot: collapsing and reloading must not re-expand
+ logic.actions.setThreadExpanded('thread-1', false)
+ await expectLogic(logic, () => {
+ logic.actions.loadComments()
+ }).toDispatchActions(['loadCommentsSuccess'])
+ expect(logic.values.expandedThreadIds.has('thread-1')).toBe(false)
+ })
+
+ it('keeps a separate draft per thread', () => {
+ const OTHER_DRAFT: JSONContent = {
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'other' }] }],
+ }
+ logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))
+ logic.actions.setReplyingComment('thread-1')
+
+ // Simulate typing in thread-1's inline composer, then switching to thread-2
+ logic.actions.setRichContentEditor(createEditor(OTHER_DRAFT))
+ logic.actions.setReplyingComment('thread-2')
+
+ // thread-1's text stays in its own slot instead of following into thread-2's composer
+ expect(logic.values.composerDrafts['thread-1']).toEqual(OTHER_DRAFT)
+ expect(logic.values.currentComposerDraft).toBeNull()
+
+ // Returning to thread-1 restores its own draft
+ logic.actions.setReplyingComment('thread-1')
+ expect(logic.values.currentComposerDraft).toEqual(OTHER_DRAFT)
+ })
+
+ it('syncs isEmpty from the editor when a composer registers', () => {
+ logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))
+ expect(logic.values.isEmpty).toBe(false)
+
+ // A fresh empty composer replaces it (e.g. switching to a thread with no draft)
+ logic.actions.setRichContentEditor(createEditor(null))
+ expect(logic.values.isEmpty).toBe(true)
+
+ // A composer seeded from a restored draft must enable sending straight away
+ logic.actions.setRichContentEditor(createEditor(DRAFT_CONTENT))
+ expect(logic.values.isEmpty).toBe(false)
+ })
+
+ it('does not clear a composer that replaced the sender mid-flight', async () => {
+ const replyEditor = createEditor(DRAFT_CONTENT)
+ logic.actions.setRichContentEditor(replyEditor)
+ logic.actions.setReplyingComment('thread-1')
+
+ const footerEditor = createEditor(DRAFT_CONTENT)
+ await expectLogic(logic, () => {
+ logic.actions.sendComposedContent(false)
+ // The user bails to a new comment while the POST is in flight
+ logic.actions.startNewComment()
+ logic.actions.setRichContentEditor(footerEditor)
+ })
+ .toDispatchActions(['sendComposedContentSuccess'])
+ .toNotHaveDispatchedActions([sidePanelDiscussionLogic.actionTypes.scrollToLastComment])
+
+ // The reply that sent is classified from send-time state, and the footer composer is untouched
+ expect(footerEditor.clear).not.toHaveBeenCalled()
+ expect(logic.values.composerDrafts['thread-1']).toBeNull()
+ })
+
+ it('startNewComment without an active reply keeps the mounted footer editor registered', () => {
+ const footerEditor = createEditor(null)
+ logic.actions.setRichContentEditor(footerEditor)
+
+ logic.actions.startNewComment()
+
+ // No reply to exit means no remount is coming - deregistering here would orphan the composer
+ expect(logic.values.richContentEditor).toBe(footerEditor)
+ expect(footerEditor.focus).toHaveBeenCalledWith('end')
+ })
+
+ 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 draft
+ logic.actions.setRichContentEditor(createEditor(null))
+
+ // The loader early-returns on empty content but still resolves as a success
+ await expectLogic(logic, () => {
+ logic.actions.sendComposedContent(false)
+ })
+ .toDispatchActions(['sendComposedContentSuccess'])
+ .toNotHaveDispatchedActions([sidePanelDiscussionLogic.actionTypes.scrollToLastComment])
+
+ expect(logic.values.composerDrafts['footer']).toEqual(DRAFT_CONTENT)
+ })
+})
diff --git a/frontend/src/scenes/comments/commentsLogic.ts b/frontend/src/scenes/comments/commentsLogic.ts
index 572bf539e35a..cd73c4664cf1 100644
--- a/frontend/src/scenes/comments/commentsLogic.ts
+++ b/frontend/src/scenes/comments/commentsLogic.ts
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
-import { RichContentEditorType } from 'lib/components/RichContentEditor/types'
+import { JSONContent, RichContentEditorType } from 'lib/components/RichContentEditor/types'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { isEmptyObject } from 'lib/utils/guards'
import { membersLogic } from 'scenes/organization/membersLogic'
@@ -35,6 +35,9 @@ export type CommentContext = {
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'
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface commentsLogicValues {
meFirstMembers: OrganizationMemberType[] // membersLogic
@@ -44,20 +47,25 @@ export interface commentsLogicValues {
comments: CommentType[] | null
commentsLoading: boolean
commentsWithReplies: CommentWithRepliesType[]
+ composerDrafts: Record<string, JSONContent | 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
+ isSendingComment: boolean
itemContext: CommentContext | null
key: string
replyingCommentId: string | null
richContentEditor: RichContentEditorType | null
selectedCommentId: string | null
sortedComments: CommentType[]
+ threadExpansion: Record<string, boolean>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -72,6 +80,9 @@ export interface commentsLogicActions {
clearItemContext: () => {
value: true
}
+ clearRichContentEditor: () => {
+ value: true
+ }
completeComment: (comment: CommentType) => {
comment: CommentType
}
@@ -114,9 +125,6 @@ export interface commentsLogicActions {
comment: CommentType
}
}
- focusComposer: () => {
- value: true
- }
loadComments: () => {
value: true
}
@@ -189,6 +197,9 @@ export interface commentsLogicActions {
comment: CommentType
}
}
+ revealSelectedComment: () => {
+ value: true
+ }
sendComposedContent: (asTask?: boolean) => {
asTask: boolean
}
@@ -240,6 +251,13 @@ export interface commentsLogicActions {
setCommentContexts: (contexts: Record<string, string>) => {
contexts: Record<string, string>
}
+ setComposerDraft: (
+ target: string,
+ content: JSONContent | null
+ ) => {
+ content: JSONContent | null
+ target: string
+ }
setEditingComment: (comment: CommentType | null) => {
comment: CommentType | null
}
@@ -259,8 +277,22 @@ export interface commentsLogicActions {
setRichContentEditor: (editor: RichContentEditorType) => {
editor: RichContentEditorType
}
- setSelectedComment: (commentId: string | null) => {
+ setSelectedComment: (
+ commentId: string | null,
+ reveal?: boolean
+ ) => {
commentId: string | null
+ reveal: boolean
+ }
+ setThreadExpanded: (
+ threadId: string,
+ expanded: boolean
+ ) => {
+ expanded: boolean
+ threadId: string
+ }
+ startNewComment: () => {
+ value: true
}
}
@@ -272,6 +304,11 @@ export interface commentsLogicMeta {
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
}
@@ -301,7 +338,6 @@ export const commentsLogic = kea<commentsLogicType>([
actions({
loadComments: true,
- focusComposer: true,
clearItemContext: true,
maybeLoadComments: true,
sendComposedContent: (asTask: boolean = false) => ({ asTask }),
@@ -314,7 +350,11 @@ export const commentsLogic = kea<commentsLogicType>([
reopenComment: (comment: CommentType) => ({ comment }),
setEditingComment: (comment: CommentType | null) => ({ comment }),
setReplyingComment: (commentId: string | null) => ({ commentId }),
- setSelectedComment: (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,
@@ -322,13 +362,14 @@ export const commentsLogic = kea<commentsLogicType>([
}),
setRichContentEditor: (editor: RichContentEditorType) => ({ editor }),
setEditingCommentRichContentEditor: (editor: RichContentEditorType | null) => ({ editor }),
+ setComposerDraft: (target: string, content: JSONContent | null) => ({ target, content }),
}),
reducers({
replyingCommentId: [
null as string | null,
{
+ // Deliberately not reset on send: the composer stays open for follow-up replies
setReplyingComment: (_, { commentId }) => commentId,
- sendComposedContentSuccess: () => null,
},
],
selectedCommentId: [
@@ -356,6 +397,32 @@ export const commentsLogic = kea<commentsLogicType>([
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: [
@@ -393,7 +460,7 @@ export const commentsLogic = kea<commentsLogicType>([
},
],
}),
- loaders(({ props, values, actions }) => ({
+ loaders(({ props, values, actions, cache }) => ({
comments: [
null as CommentType[] | null,
{
@@ -445,6 +512,14 @@ export const commentsLogic = kea<commentsLogicType>([
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,
@@ -541,8 +616,29 @@ export const commentsLogic = kea<commentsLogicType>([
],
})),
- listeners(({ values, actions }) => ({
- setReplyingComment: ({ commentId }) => {
+ listeners(({ 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()
}
@@ -553,11 +649,23 @@ export const commentsLogic = kea<commentsLogicType>([
},
setItemContext: ({ context }) => {
if (context) {
- values.richContentEditor?.focus()
+ if (values.replyingCommentId) {
+ // Anchored comments and replies are mutually exclusive
+ actions.setReplyingComment(null)
+ } else {
+ values.richContentEditor?.focus()
+ }
}
},
- focusComposer: () => {
- 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) {
@@ -565,11 +673,51 @@ export const commentsLogic = kea<commentsLogicType>([
}
},
sendComposedContentSuccess: () => {
- actions.scrollToLastComment()
+ 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()
- values.richContentEditor?.clear()
+ 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()
},
})),
@@ -642,6 +790,30 @@ export const commentsLogic = kea<commentsLogicType>([
},
],
+ 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) => {
@@ -658,10 +830,14 @@ export const commentsLogic = kea<commentsLogicType>([
],
}),
- subscriptions(({ actions }) => ({
- replyingCommentId: (value: string): void => {
- if (value) {
- actions.focusComposer()
+ 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)
}
},
})),
diff --git a/products/ai_observability/frontend/ConversationDisplay/MessageActionsMenu.tsx b/products/ai_observability/frontend/ConversationDisplay/MessageActionsMenu.tsx
index 11353a251b84..505787c8fef2 100644
--- a/products/ai_observability/frontend/ConversationDisplay/MessageActionsMenu.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/MessageActionsMenu.tsx
@@ -30,7 +30,7 @@ export const MessageActionsMenu = ({ content, traceId }: MessageActionsMenuProps
item_id: traceId || '',
}
const commentsLogicInstance = commentsLogic(commentsLogicProps)
- const { maybeLoadComments } = useActions(commentsLogicInstance)
+ const { maybeLoadComments, startNewComment } = useActions(commentsLogicInstance)
const logic = messageActionsMenuLogic({ content })
const { showConsentPopover, dataProcessingAccepted } = useValues(logic)
@@ -59,6 +59,9 @@ export const MessageActionsMenu = ({ content, traceId }: MessageActionsMenuProps
const handleStartDiscussion = (): void => {
maybeLoadComments()
+ // Exit any in-progress reply and deregister its editor, so the retry loop below
+ // waits for the footer composer instead of pasting into a thread's reply composer
+ startNewComment()
openSidePanel(SidePanelTab.Discussion)
const truncatedContent =
diff --git a/products/ai_observability/frontend/text-view/components/LineWithNumber.tsx b/products/ai_observability/frontend/text-view/components/LineWithNumber.tsx
index 1b9d284f0bf0..ff0613ff58df 100644
--- a/products/ai_observability/frontend/text-view/components/LineWithNumber.tsx
+++ b/products/ai_observability/frontend/text-view/components/LineWithNumber.tsx
@@ -39,7 +39,7 @@ export function LineWithNumber({
item_id: traceId || '',
}
const commentsLogicInstance = commentsLogic(commentsLogicProps)
- const { maybeLoadComments } = useActions(commentsLogicInstance)
+ const { maybeLoadComments, startNewComment } = useActions(commentsLogicInstance)
const lineText = `L${padding > 0 ? lineNumber.toString().padStart(padding, '0') : lineNumber}:${content}`
const logic = messageActionsMenuLogic({ content: lineText })
@@ -84,6 +84,9 @@ export function LineWithNumber({
return
}
maybeLoadComments()
+ // Exit any in-progress reply and deregister its editor, so the retry loop below
+ // waits for the footer composer instead of pasting into a thread's reply composer
+ startNewComment()
openSidePanel(SidePanelTab.Discussion)
const quotedContent = `> L${lineNumber}: ${content.trim()}`