:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay): add a Comments tab listing your recording comments (#97566)
posthog[bot]e4cab8bdd6a1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 66c0614b05cf..8ea091f9e896 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6136,6 +6136,14 @@ snapshots:hash: v1.k794b7964.967afbceab74b989f44a0e43654fc8bc219dfb858ba11a2e5ab9c00edb7a13ad.DhL8CprkQ7KvkxODyhe-4lv_TYdMdx-Or1aYK5SdE8Mreplay-tabs-collections--recordings-play-lists--light:hash: v1.k794b7964.ec52ea7db8e78f4b476f20a564787b7bf614ab9f6ac5b226796737d08f1d471c.7zHA9RmJgfeydgCRP5Q5YlWjnOy1Nn_S-3xGJ0lONik+ replay-tabs-comments--replay-comments--dark:+ hash: v1.k794b7964.6af2d3cc255214b5e3cc09e79f04b2f89d886ade9ccedbcb4580dc3911806f8c.tliRHNyKfL63iDI1FAb-nA3Dl05I3XJa_MEbL9MqKco+ replay-tabs-comments--replay-comments--light:+ hash: v1.k794b7964.e084d3db7021bff811b705c4f777541c4cfb0c46b8c7c86fac2c86723aba72ba.nh9hurj8GifHuw1FAk0p14LP7MwxM2Rdp00tVZCWwxw+ replay-tabs-comments--replay-comments-empty--dark:+ hash: v1.k794b7964.c2db163d8ad51841c9b652d731f6583685e5c52db268775903475272f6b8877f.qX_vfdLEALxvKOM-X_7BCcAVsLFsEqSYoE67GZycd-Q+ replay-tabs-comments--replay-comments-empty--light:+ hash: v1.k794b7964.eacc112601665aaad99a28267264805387b57496ee35b89bafef74db2c2c2794.pTNBJCYNg6D28_QldfksZRa-Bzl-VSAcEWzL5AeegF8replay-tabs-home-failure--not-found--dark:hash: v1.k794b7964.976b4bc71204d3fdd7d22bc696a779a418376dfa7d6fc74cf50ebc5023c672b9.gyNSfDI5sGG3Hamw70N9MALDuDtbPb3jeSZzD9-IC5greplay-tabs-home-failure--not-found--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex dd1c0287f0f6..3f96c93e4d81 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -65,6 +65,7 @@ const ERROR_FILTER_ALLOW_LIST = ['loadRuns', // The Wizard runs table shows a persistent stale-data banner; a poll failure must not toast every 10s'loadRunDetails', // The Wizard run drawer shows a stale-state banner with a retry'cancelRunRequest', // wizardRunDetailsLogic shows its own cancel-failure toast+ 'loadReplayComments', // The replay Comments tab renders its own retry state]/*diff --git a/frontend/src/lib/components/Comments/Comment.tsx b/frontend/src/lib/components/Comments/Comment.tsxindex 17d9c6a355bf..9ceb987d8138 100644--- a/frontend/src/lib/components/Comments/Comment.tsx+++ b/frontend/src/lib/components/Comments/Comment.tsx@@ -1,4 +1,3 @@-import { generateText } from '@tiptap/core'import clsx from 'clsx'import { useActions, useValues } from 'kea'import { router } from 'kea-router'@@ -16,11 +15,7 @@ import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { IconSlack } from 'lib/lemon-ui/icons'import { LemonDivider } from 'lib/lemon-ui/LemonDivider'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'-import {- DEFAULT_EXTENSIONS,- LemonRichContentEditor,- serializationOptions,-} from 'lib/lemon-ui/LemonRichContent/LemonRichContentEditor'+import { LemonRichContentEditor } from 'lib/lemon-ui/LemonRichContent/LemonRichContentEditor'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { colonDelimitedDuration } from 'lib/utils/durations'import { pluralize } from 'lib/utils/strings'@@ -29,7 +24,7 @@ import { CommentType } from '~/types'import { CommentComposer } from './CommentComposer'import { CommentsLogicProps, CommentWithRepliesType, commentsLogic } from './commentsLogic'-import { getRecordingLinkInfo, isViewingRecording } from './commentUtils'+import { getCommentText, getRecordingLinkInfo, isViewingRecording } from './commentUtils'import { sendCommentToSlackLogic } from './sendCommentToSlackLogic'// Comments that came in from a synced Slack thread have no PostHog author; their Slack identity@@ -299,7 +294,7 @@ const Comment = ({ comment }: { comment: CommentType }): JSX.Element => {const isHighlighted = selectedCommentId === comment.id || isEditingconst 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])+ const text = useMemo(() => getCommentText(comment), [comment])useEffect(() => {if (isHighlighted) {@@ -500,27 +495,3 @@ export const CommentWithReplies = ({ commentWithReplies, composerLogicProps }: C</div>)}--export function getText(comment: CommentType): string {- // This is only temporary until all comments are backfilled to rich content- const content = comment.rich_content- ? comment.rich_content- : {- type: 'doc',- content: [- {- type: 'paragraph',- content: comment.content- ? [- {- type: 'text',- text: comment.content,- },- ]- : [],- },- ],- }-- return generateText(content, DEFAULT_EXTENSIONS, serializationOptions)-}diff --git a/frontend/src/lib/components/Comments/commentUtils.ts b/frontend/src/lib/components/Comments/commentUtils.tsindex 91f3fb27872f..df1dfa72f82f 100644--- a/frontend/src/lib/components/Comments/commentUtils.ts+++ b/frontend/src/lib/components/Comments/commentUtils.ts@@ -1,7 +1,11 @@+import { generateText } from '@tiptap/core'++import { JSONContent } from 'lib/components/RichContentEditor/types'import { dayjs } from 'lib/dayjs'+import { DEFAULT_EXTENSIONS, serializationOptions } from 'lib/lemon-ui/LemonRichContent/LemonRichContentEditor'import { urls } from 'scenes/urls'-import { ActivityScope, CommentType } from '~/types'+import { ActivityScope } from '~/types'export interface RecordingLinkInfo {recordingId: string@@ -9,7 +13,13 @@ export interface RecordingLinkInfo {url: string}-export function getRecordingLinkInfo(comment: CommentType): RecordingLinkInfo | null {+export type RecordingCommentTarget = {+ scope: ActivityScope | string+ item_id?: string | null+ item_context?: { time_in_recording?: string | null } | null+}++export function getRecordingLinkInfo(comment: RecordingCommentTarget): RecordingLinkInfo | null {const isRecordingComment = comment.scope === ActivityScope.REPLAY || comment.scope === ActivityScope.RECORDINGif (!isRecordingComment || !comment.item_id) {return null@@ -24,6 +34,30 @@ export function getRecordingLinkInfo(comment: CommentType): RecordingLinkInfo |}}+export function getCommentText(comment: { content?: string | null; rich_content?: JSONContent | null }): string {+ // This is only temporary until all comments are backfilled to rich content+ const content = comment.rich_content+ ? comment.rich_content+ : {+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: comment.content+ ? [+ {+ type: 'text',+ text: comment.content,+ },+ ]+ : [],+ },+ ],+ }++ return generateText(content, DEFAULT_EXTENSIONS, serializationOptions)+}+export function isViewingRecording(recordingId: string): boolean {const url = new URL(window.location.href)const pathMatch = url.pathname.match(/\/replay\/([^/?#]+)/)diff --git a/frontend/src/scenes/session-recordings/SessionRecordings.tsx b/frontend/src/scenes/session-recordings/SessionRecordings.tsxindex 7d7ee731757f..7b9d537eb3ef 100644--- a/frontend/src/scenes/session-recordings/SessionRecordings.tsx+++ b/frontend/src/scenes/session-recordings/SessionRecordings.tsx@@ -31,6 +31,7 @@ import { ScenePanel, ScenePanelActionsSection } from '~/layout/scenes/SceneLayouimport { ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType, ReplayTab, ReplayTabs } from '~/types'+import { ReplayComments } from 'products/replay/frontend/comments/ReplayComments'import { sessionReplayEmptyState } from 'products/replay/frontend/emptyState/sessionReplayEmptyState'import { SessionRecordingCollections } from './collections/SessionRecordingCollections'@@ -204,6 +205,8 @@ function MainPanel(): JSX.Element {</div>) : tab === ReplayTabs.Playlists ? (<SessionRecordingCollections />+ ) : tab === ReplayTabs.Comments ? (+ <ReplayComments />) : tab === ReplayTabs.Templates ? (<SessionRecordingTemplates />) : null}@@ -225,6 +228,12 @@ const ReplayPageTabs: ReplayTab[] = [tooltip: 'View & create collections','data-attr': 'session-recordings-collections-tab',},+ {+ label: 'Comments',+ key: ReplayTabs.Comments,+ tooltip: 'Comments you added to recordings',+ 'data-attr': 'session-recordings-comments-tab',+ },{label: 'Filter templates',key: ReplayTabs.Templates,diff --git a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.tsindex 7e014110cc20..715bb45d2cab 100644--- a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts+++ b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts@@ -24,7 +24,7 @@ import {} from 'posthog-js/rrweb-types'import api from 'lib/api'-import { getText } from 'lib/components/Comments/Comment'+import { getCommentText } from 'lib/components/Comments/commentUtils'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { FEATURE_FLAGS } from 'lib/constants'import { Dayjs, dayjs } from 'lib/dayjs'@@ -1321,7 +1321,7 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([windowId: windowIdForTimestamp(timestamp.valueOf()),windowNumber: windowNumberForID(windowIdForTimestamp(timestamp.valueOf())),data: comment,- search: getText(comment),+ search: getCommentText(comment),key: `comment-${comment.id}`,}items.push(item)diff --git a/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.ts b/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.tsindex 2c00d2e83a8c..18fa6217768c 100644--- a/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.ts+++ b/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.ts@@ -16,6 +16,8 @@ export const humanFriendlyTabName = (tab: ReplayTabs): string => {return 'Recordings'case ReplayTabs.Playlists:return 'Collections'+ case ReplayTabs.Comments:+ return 'Comments'case ReplayTabs.Templates:return 'Filter templates'case ReplayTabs.Settings:diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 0533b1d14553..015a182f7ac5 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1104,6 +1104,7 @@ export enum SavedInsightsTabs {export enum ReplayTabs {Home = 'home',Playlists = 'playlists',+ Comments = 'comments',Templates = 'templates',Settings = 'settings',}diff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex 654e908548cb..bcbdca451b0e 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -566,6 +566,9 @@ class CommentListQueryParamsSerializer(serializers.Serializer):),)item_id = serializers.CharField(required=False, help_text="Filter by the ID of the resource being commented on.")+ created_by = serializers.IntegerField(+ required=False, help_text="Filter by the numeric ID of the user who wrote the comment."+ )task_id = serializers.UUIDField(required=False, help_text="Owning task for task, task_artifact, and desktop_canvas comment scopes.")@@ -910,8 +913,10 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVparams = self.request.GET.dict()queryset = queryset.exclude(scope__in=COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API)- if params.get("user"):- queryset = queryset.filter(user=params.get("user"))+ if created_by := params.get("created_by"):+ if not created_by.isdigit():+ raise exceptions.ValidationError("created_by must be a numeric user ID")+ queryset = queryset.filter(created_by_id=int(created_by))if self.action != "partial_update" and params.get("deleted", "false") == "false":queryset = queryset.filter(deleted=False)diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.pyindex a1bfc3c7d164..2c17d3e346be 100644--- a/posthog/api/test/test_comments.py+++ b/posthog/api/test/test_comments.py@@ -922,6 +922,20 @@ class TestComments(APIBaseTest, QueryMatchingTest):assert len(response.json()["results"]) == 1assert response.json()["results"][0]["content"] == "comment notebook-2"+ def test_lists_comments_filtered_by_author(self) -> None:+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")+ self._create_comment({"content": "mine", "scope": "Replay", "item_id": "session-1"})+ Comment.objects.create(+ team=self.team, created_by=other_user, content="theirs", scope="Replay", item_id="session-2"+ )++ response = self.client.get(f"/api/projects/{self.team.id}/comments?scope=Replay&created_by={self.user.id}")+ assert response.status_code == status.HTTP_200_OK+ assert [comment["content"] for comment in response.json()["results"]] == ["mine"]++ response = self.client.get(f"/api/projects/{self.team.id}/comments?created_by=not-a-user-id")+ assert response.status_code == status.HTTP_400_BAD_REQUEST+def test_lists_comments_thread(self) -> None:initial_comment = self._create_comment({"content": "comment notebook-1", "scope": "Notebook", "item_id": "1"})self._create_comment({"content": "comment reply", "source_comment": initial_comment["id"]})diff --git a/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsx b/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsxindex 43e5cfe949c3..84c573eacb0f 100644--- a/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsx+++ b/products/conversations/frontend/scenes/ticket/ThreadDiscussions.tsx@@ -4,8 +4,9 @@ import { useEffect } from 'react'import { IconChat } from '@posthog/icons'import { LemonTag } from '@posthog/lemon-ui'-import { getCommentAuthorName, getText } from 'lib/components/Comments/Comment'+import { getCommentAuthorName } from 'lib/components/Comments/Comment'import { CommentWithRepliesType, commentsLogic } from 'lib/components/Comments/commentsLogic'+import { getCommentText } from 'lib/components/Comments/commentUtils'import { TZLabel } from 'lib/components/TZLabel'import { IconSlack } from 'lib/lemon-ui/icons'import { ProfileBubbles } from 'lib/lemon-ui/ProfilePicture/ProfileBubbles'@@ -137,7 +138,7 @@ export function ThreadDiscussionEntry({data-attr="ticket-thread-discussion">{root ? (- <div className="ph-no-capture text-sm leading-snug line-clamp-2">{getText(root)}</div>+ <div className="ph-no-capture text-sm leading-snug line-clamp-2">{getCommentText(root)}</div>) : (<div className="text-sm font-semibold italic text-secondary">Deleted comment</div>)}diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 1d3f87949d0d..6d0ef96bbcfd 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1809,6 +1809,10 @@ export type CommentsListParams = {* @minLength 1*/completed?: CommentsListCompleted+ /**+ * Filter by the numeric ID of the user who wrote the comment.+ */+ created_by?: number/*** The pagination cursor value.*/diff --git a/products/replay/frontend/comments/ReplayComments.stories.tsx b/products/replay/frontend/comments/ReplayComments.stories.tsxnew file mode 100644index 000000000000..22ba31a55191--- /dev/null+++ b/products/replay/frontend/comments/ReplayComments.stories.tsx@@ -0,0 +1,64 @@+import { Meta, StoryObj } from '@storybook/react'++import { App } from 'scenes/App'+import { recordings } from 'scenes/session-recordings/__mocks__/recordings'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'+import { ReplayTabs } from '~/types'++const comment = (id: string, secondsIntoRecording: number, content: string): Record<string, any> => ({+ id,+ content,+ rich_content: null,+ version: 0,+ created_at: '2023-01-31T16:20:00Z',+ created_by: null,+ scope: 'Replay',+ item_id: `recording-${id}`,+ item_context: {+ time_in_recording: '2023-01-31T16:00:00Z',+ milliseconds_into_recording: secondsIntoRecording * 1000,+ },+ is_task: false,+ completed_at: null,+ completed_by: null,+ slack_thread: null,+})++// The scene replaces every tab with the session replay product empty state until its setup probe+// finds a recording, so the recordings list has to answer before any of this tab is on screen.+const sceneMocks = (comments: Record<string, any>[]): ReturnType<typeof mswDecorator> =>+ mswDecorator({+ get: {+ '/api/environments/:team_id/session_recordings': { has_next: false, results: recordings },+ '/api/projects/:team_id/comments/': { next: null, previous: null, results: comments },+ },+ })++const meta: Meta = {+ component: App,+ title: 'Replay/Tabs/Comments',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2023-02-01',+ pageUrl: urls.replay(ReplayTabs.Comments),+ },+}+export default meta++type Story = StoryObj<{}>++export const ReplayComments: Story = {+ decorators: [+ sceneMocks([+ comment('1', 72, 'The checkout button does nothing on the first click.'),+ comment('2', 605, 'This user could not find the export option.'),+ ]),+ ],+}++export const ReplayCommentsEmpty: Story = {+ decorators: [sceneMocks([])],+}diff --git a/products/replay/frontend/comments/ReplayComments.tsx b/products/replay/frontend/comments/ReplayComments.tsxnew file mode 100644index 000000000000..a57bfc72872b--- /dev/null+++ b/products/replay/frontend/comments/ReplayComments.tsx@@ -0,0 +1,108 @@+import { useActions, useValues } from 'kea'++import { IconEye } from '@posthog/icons'+import { LemonButton, LemonTag } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'++import { ReplayCommentRow, replayCommentsLogic } from './replayCommentsLogic'++const columns: LemonTableColumns<ReplayCommentRow> = [+ {+ title: 'Comment',+ key: 'text',+ render: function Render(_, row) {+ return (+ <div className="flex flex-col gap-1 py-1">+ <div className="ph-no-capture whitespace-pre-wrap break-words">{row.text}</div>+ {row.isTask ? (+ <div>+ <LemonTag size="small" type={row.isCompleted ? 'success' : 'warning'}>+ {row.isCompleted ? 'Completed' : 'Task'}+ </LemonTag>+ </div>+ ) : null}+ </div>+ )+ },+ },+ {+ title: 'Recording',+ key: 'recording',+ width: 0,+ render: function Render(_, row) {+ if (!row.recordingUrl) {+ return null+ }+ return (+ <LemonButton+ to={row.recordingUrl}+ icon={<IconEye />}+ size="small"+ type="tertiary"+ tooltip="View in recording"+ data-attr="replay-comments-view-recording"+ >+ {row.timeInRecording ?? 'Watch'}+ </LemonButton>+ )+ },+ },+ {+ title: 'Commented',+ key: 'createdAt',+ width: 0,+ render: function Render(_, row) {+ return <TZLabel time={row.createdAt} />+ },+ },+]++export function ReplayComments(): JSX.Element {+ const { commentRows, firstPageLoading, commentPageLoading, hasMoreComments, hasLoadError } =+ useValues(replayCommentsLogic)+ const { loadReplayComments, loadMoreReplayComments } = useActions(replayCommentsLogic)++ if (hasLoadError) {+ return (+ <LemonBanner+ type="error"+ action={{+ children: 'Try again',+ onClick: loadReplayComments,+ 'data-attr': 'replay-comments-retry',+ }}+ >+ Could not load your comments. Try again, and contact support if it keeps happening.+ </LemonBanner>+ )+ }++ return (+ <div className="flex flex-col gap-2">+ <LemonTable+ columns={columns}+ dataSource={commentRows}+ loading={firstPageLoading}+ rowKey="id"+ nouns={['comment', 'comments']}+ emptyState="You have not commented on a recording yet. Open a recording and add a comment to see it here."+ />+ {hasMoreComments ? (+ <div className="flex justify-center">+ <LemonButton+ type="secondary"+ size="small"+ onClick={loadMoreReplayComments}+ loading={commentPageLoading}+ data-attr="replay-comments-load-more"+ >+ Load more+ </LemonButton>+ </div>+ ) : null}+ </div>+ )+}diff --git a/products/replay/frontend/comments/replayCommentsLogic.test.ts b/products/replay/frontend/comments/replayCommentsLogic.test.tsnew file mode 100644index 000000000000..31785dc21a4e--- /dev/null+++ b/products/replay/frontend/comments/replayCommentsLogic.test.ts@@ -0,0 +1,109 @@+import { expectLogic } from 'kea-test-utils'++import { userLogic } from 'scenes/userLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { replayCommentsLogic } from './replayCommentsLogic'++const comment = (id: string, overrides: Record<string, any> = {}): Record<string, any> => ({+ id,+ content: `comment ${id}`,+ rich_content: null,+ version: 0,+ created_at: '2024-05-01T10:00:00Z',+ created_by: null,+ scope: 'Replay',+ item_id: 'the-recording-id',+ item_context: { time_in_recording: '2024-05-01T09:00:12Z', milliseconds_into_recording: 72000 },+ is_task: false,+ completed_at: null,+ completed_by: null,+ slack_thread: null,+ ...overrides,+})++describe('replayCommentsLogic', () => {+ let logic: ReturnType<typeof replayCommentsLogic.build>+ let requestedUrls: string[]+ let responseStatus: number++ beforeEach(() => {+ requestedUrls = []+ responseStatus = 200+ useMocks({+ get: {+ '/api/projects/:team_id/comments/': ({ request }) => {+ requestedUrls.push(request.url)+ if (responseStatus !== 200) {+ return [responseStatus, { detail: 'nope' }]+ }+ const cursor = new URL(request.url).searchParams.get('cursor')+ if (cursor === 'page-2') {+ return [200, { next: null, previous: null, results: [comment('2')] }]+ }+ return [+ 200,+ {+ next: 'http://localhost/api/projects/997/comments/?cursor=page-2',+ previous: null,+ results: [comment('1')],+ },+ ]+ },+ },+ })+ initKeaTests()+ logic = replayCommentsLogic()+ })++ // The whole point of the tab: dropping either filter would show every team member's+ // comments from every product, not the person's own replay comments.+ it("asks only for the current user's replay comments", async () => {+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ const params = new URL(requestedUrls[0]).searchParams+ expect(params.get('scope')).toEqual('Replay')+ expect(params.get('created_by')).toEqual(String(userLogic.values.user?.id))+ })++ it('links each comment to its moment in the recording', async () => {+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.commentRows).toMatchObject([+ {+ id: '1',+ text: 'comment 1',+ timeInRecording: '01:12',+ recordingUrl: expect.stringContaining('/replay/the-recording-id?timestamp='),+ },+ ])+ })++ it('appends the next page instead of replacing the loaded one', async () => {+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.hasMoreComments).toBe(true)++ logic.actions.loadMoreReplayComments()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.commentRows.map((row) => row.id)).toEqual(['1', '2'])+ expect(logic.values.hasMoreComments).toBe(false)+ expect(new URL(requestedUrls[1]).searchParams.get('cursor')).toEqual('page-2')+ })++ // A failed load leaves no rows, so without this flag the tab would tell the person+ // they have never commented.+ it('reports a failed load instead of reading as an empty list', async () => {+ responseStatus = 500+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.hasLoadError).toBe(true)+ expect(logic.values.firstPageLoading).toBe(false)+ })+})diff --git a/products/replay/frontend/comments/replayCommentsLogic.ts b/products/replay/frontend/comments/replayCommentsLogic.tsnew file mode 100644index 000000000000..27a9d45892c6--- /dev/null+++ b/products/replay/frontend/comments/replayCommentsLogic.ts@@ -0,0 +1,221 @@+import { MakeLogicType, actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { getCommentText, getRecordingLinkInfo } from 'lib/components/Comments/commentUtils'+import { JSONContent } from 'lib/components/RichContentEditor/types'+import { colonDelimitedDuration } from 'lib/utils/durations'+import { getCurrentTeamId } from 'lib/utils/getAppContext'+import { userLogic } from 'scenes/userLogic'++import { ActivityScope, UserType } from '~/types'++import { commentsList } from 'products/platform_features/frontend/generated/api'+import type { CommentApi } from 'products/platform_features/frontend/generated/api.schemas'++type ReplayCommentContext = {+ time_in_recording?: string+ milliseconds_into_recording?: number+}++export type ReplayCommentRow = {+ id: string+ text: string+ createdAt: string+ recordingUrl: string | null+ /** Position in the recording as `mm:ss`, or null for a comment with no player position. */+ timeInRecording: string | null+ isTask: boolean+ isCompleted: boolean+}++export type ReplayCommentPage = {+ comments: CommentApi[]+ nextCursor: string | null+}++/** The API returns the next page as a full URL; only its cursor is needed to ask for that page. */+function cursorFromNextUrl(nextUrl: string | null | undefined): string | null {+ if (!nextUrl) {+ return null+ }+ try {+ return new URL(nextUrl, window.location.origin).searchParams.get('cursor')+ } catch {+ return null+ }+}++function toCommentRow(comment: CommentApi): ReplayCommentRow {+ // The comment serializer types both fields as free-form JSON, so the replay shape is asserted here+ const itemContext = (comment.item_context ?? null) as ReplayCommentContext | null+ const richContent = (comment.rich_content ?? null) as JSONContent | null+ const millisecondsIntoRecording = itemContext?.milliseconds_into_recording++ return {+ id: comment.id,+ text: getCommentText({ content: comment.content, rich_content: richContent }),+ createdAt: comment.created_at,+ recordingUrl:+ getRecordingLinkInfo({+ scope: comment.scope ?? '',+ item_id: comment.item_id,+ item_context: itemContext,+ })?.url ?? null,+ timeInRecording:+ millisecondsIntoRecording === undefined+ ? null+ : colonDelimitedDuration(millisecondsIntoRecording / 1000, null),+ isTask: !!comment.is_task,+ isCompleted: !!comment.completed_at,+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface replayCommentsLogicValues {+ user: UserType | null // userLogic+ commentPage: ReplayCommentPage | null+ commentPageLoading: boolean+ commentRows: ReplayCommentRow[]+ firstPageLoading: boolean+ hasLoadError: boolean+ hasMoreComments: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface replayCommentsLogicActions {+ loadMoreReplayComments: () => {+ value: true+ }+ loadMoreReplayCommentsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadMoreReplayCommentsSuccess: (+ commentPage: ReplayCommentPage | null,+ payload?: {+ value: true+ }+ ) => {+ commentPage: ReplayCommentPage | null+ payload?: {+ value: true+ }+ }+ loadReplayComments: () => {+ value: true+ }+ loadReplayCommentsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadReplayCommentsSuccess: (+ commentPage: ReplayCommentPage | null,+ payload?: {+ value: true+ }+ ) => {+ commentPage: ReplayCommentPage | null+ payload?: {+ value: true+ }+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface replayCommentsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ commentRows: (commentPage: ReplayCommentPage | null) => ReplayCommentRow[]+ hasMoreComments: (commentPage: ReplayCommentPage | null) => boolean+ firstPageLoading: (commentPageLoading: boolean, commentPage: ReplayCommentPage | null) => boolean+ }+}++export type replayCommentsLogicType = MakeLogicType<+ replayCommentsLogicValues,+ replayCommentsLogicActions,+ Record<string, any>,+ replayCommentsLogicMeta+>++export const replayCommentsLogic = kea<replayCommentsLogicType>([+ path(() => ['products', 'replay', 'comments', 'replayCommentsLogic']),+ connect(() => ({+ values: [userLogic, ['user']],+ })),+ actions({+ loadReplayComments: true,+ loadMoreReplayComments: true,+ }),+ loaders(({ values }) => ({+ commentPage: [+ null as ReplayCommentPage | null,+ {+ loadReplayComments: async (_, breakpoint): Promise<ReplayCommentPage | null> => {+ const userId = values.user?.id+ if (!userId) {+ return null+ }+ const response = await commentsList(String(getCurrentTeamId()), {+ scope: ActivityScope.REPLAY,+ created_by: userId,+ })+ breakpoint()+ return { comments: response.results, nextCursor: cursorFromNextUrl(response.next) }+ },+ loadMoreReplayComments: async (_, breakpoint): Promise<ReplayCommentPage | null> => {+ const userId = values.user?.id+ const cursor = values.commentPage?.nextCursor+ if (!userId || !cursor) {+ return values.commentPage+ }+ const response = await commentsList(String(getCurrentTeamId()), {+ scope: ActivityScope.REPLAY,+ created_by: userId,+ cursor,+ })+ breakpoint()+ return {+ comments: [...(values.commentPage?.comments ?? []), ...response.results],+ nextCursor: cursorFromNextUrl(response.next),+ }+ },+ },+ ],+ })),+ reducers({+ hasLoadError: [+ false,+ {+ loadReplayComments: () => false,+ loadReplayCommentsSuccess: () => false,+ loadReplayCommentsFailure: () => true,+ },+ ],+ }),+ selectors(() => ({+ commentRows: [+ (s) => [s.commentPage],+ (commentPage: ReplayCommentPage | null): ReplayCommentRow[] =>+ (commentPage?.comments ?? []).map(toCommentRow),+ ],+ hasMoreComments: [+ (s) => [s.commentPage],+ (commentPage: ReplayCommentPage | null): boolean => !!commentPage?.nextCursor,+ ],+ // Keeps the empty state off the screen until the first page has answered+ firstPageLoading: [+ (s) => [s.commentPageLoading, s.commentPage],+ (commentPageLoading: boolean, commentPage: ReplayCommentPage | null): boolean =>+ commentPageLoading && commentPage === null,+ ],+ })),+ afterMount(({ actions }) => {+ actions.loadReplayComments()+ }),+])diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f91c97234585..b17d072b9dd5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -94284,6 +94284,10 @@ export namespace Schemas {* @minLength 1*/completed?: CommentsListCompleted;+ /**+ * Filter by the numeric ID of the user who wrote the comment.+ */+ created_by?: number;/*** The pagination cursor value.*/diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.tsindex 03516f024eb3..90414541ba19 100644--- a/services/mcp/src/generated/platform_features/api.ts+++ b/services/mcp/src/generated/platform_features/api.ts@@ -396,6 +396,7 @@ export const CommentsListQueryParams = () => zod.object({.describe("When kind=task, restrict to open (incomplete) or completed tasks. Ignored when kind is not 'task'. Defaults to 'any' (no filter).\n\n\* `any` - any\n\* `open` - open\n\* `completed` - completed"),+ created_by: zod.number().optional().describe('Filter by the numeric ID of the user who wrote the comment.'),cursor: zod.string().optional().describe('The pagination cursor value.'),item_id: zod.string().min(1).optional().describe('Filter by the ID of the resource being commented on.'),kind: zoddiff --git a/services/mcp/src/tools/generated/platform_features.ts b/services/mcp/src/tools/generated/platform_features.tsindex fbce74cbe2e5..b070167f7ed2 100644--- a/services/mcp/src/tools/generated/platform_features.ts+++ b/services/mcp/src/tools/generated/platform_features.ts@@ -544,6 +544,7 @@ const commentsList = (): ToolBase<ReturnType<typeof CommentsListSchema>, Schemaspath: `/api/projects/${encodeURIComponent(String(projectId))}/comments/`,query: {completed: params.completed,+ created_by: params.created_by,cursor: params.cursor,item_id: params.item_id,kind: params.kind,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.jsonindex be71de1eaec0..39ad8658debf 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.json@@ -6,6 +6,10 @@"enum": ["any", "open", "completed"],"type": "string"},+ "created_by": {+ "description": "Filter by the numeric ID of the user who wrote the comment.",+ "type": "number"+ },"cursor": {"description": "The pagination cursor value.","type": "string"