: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): split built-in collections and add watch next (#107713)
Hayne Ryu566c89d77efb
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b936e3f6a548..f2ef98ca708f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7461,9 +7461,9 @@ snapshots:replay-sharing--public-link--light:hash: v1.k794b7964.ddfd8254ca69a6fc3cb638c1bcec9cd839fda06322c538d5b077f979d563e246.rsWbpqFKkbOOKpotVfWuctA8mHs1X9zPI8bkJU0TVQgreplay-tabs-collections--recordings-play-lists--dark:- hash: v1.k794b7964.967afbceab74b989f44a0e43654fc8bc219dfb858ba11a2e5ab9c00edb7a13ad.DhL8CprkQ7KvkxODyhe-4lv_TYdMdx-Or1aYK5SdE8M+ hash: v1.k794b7964.e0b88639193593d2310eb018f49347a9bb33a0cb1c2d709eb4123cea650151c9.MBJ1QFzWoPfRJD6kFjienFZcvIbeOXG63IgbNcH3BgMreplay-tabs-collections--recordings-play-lists--light:- hash: v1.k794b7964.ec52ea7db8e78f4b476f20a564787b7bf614ab9f6ac5b226796737d08f1d471c.7zHA9RmJgfeydgCRP5Q5YlWjnOy1Nn_S-3xGJ0lONik+ hash: v1.k794b7964.f903e9b0791fe14a54094c6d60ebf2f783b038c3af2cd48a4b683405e0fa9804.T5HCxaEs6jav9oxx4Xh3I7cpQE5LAHe5hxr3m8mPZiUreplay-tabs-comments--replay-comments--dark:hash: v1.k794b7964.6af2d3cc255214b5e3cc09e79f04b2f89d886ade9ccedbcb4580dc3911806f8c.tliRHNyKfL63iDI1FAb-nA3Dl05I3XJa_MEbL9MqKcoreplay-tabs-comments--replay-comments--light:@@ -7517,9 +7517,9 @@ snapshots:replay-tabs-home-success--recent-recordings-empty--light:hash: v1.k794b7964.0c42a8397f876b6118b6003b38e691b849bccef88f7ce8b04d433149c387272c.AjQt0-zv3hc11T4bFY_chc_VTPx0aZVqQyNWKxWt4NAreplay-tabs-home-success--recordings-play-list-no-pinned-recordings--dark:- hash: v1.k794b7964.77abb01d4f00305236c2ebd0377e0aee47cd50743c75c68f692ae8fec111371d.iVejWxmTZ4MtP2WYTK-jLSresCBRZ-d57bcPFhoCDlc+ hash: v1.k794b7964.3646b34febaf1f41bf9438e3b497278001c8d69fd427ed14a71b86f6412a8bda.ktDdlMNADUngWV7CXl-AVPhJ6XMMDhyLH8zCy7mnwBYreplay-tabs-home-success--recordings-play-list-no-pinned-recordings--light:- hash: v1.k794b7964.53967579ef53f411c9adc668e0e8b832b0fbb8fb1f346e55fff866d861d0566a.N3xzqevtEf7EogtcsQXhd04fINxfV0MejZn-DsAhQws+ hash: v1.k794b7964.a0683ea0a59c86f2d0b3245db8fe807ae82271c393971cece0c7b9c58f0e2f10.UjlpwjlWZaZS9fN-ph4xozP-XM8jx4p4M3MsEYFJpMsreplay-tabs-home-success--second-recording-in-list--dark:hash: v1.k794b7964.2ba8b5789dc4e6732085d5c3e9b4434011dfd0f50c9b9bf20101273d65e6ee7d.vbjff-vvIJ5OC55myq8StIReDxV12WsR2hkQyMFeHmkreplay-tabs-home-success--second-recording-in-list--light:diff --git a/frontend/src/scenes/session-recordings/collections/BuiltInCollections.tsx b/frontend/src/scenes/session-recordings/collections/BuiltInCollections.tsxnew file mode 100644index 000000000000..12443e42586b--- /dev/null+++ b/frontend/src/scenes/session-recordings/collections/BuiltInCollections.tsx@@ -0,0 +1,61 @@+import { IconClock, IconComment, IconDownload, IconRewindPlay, IconShare, IconWarning } from '@posthog/icons'+import { LemonTable } from '@posthog/lemon-ui'++import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'++import { SessionRecordingPlaylistType } from '~/types'++import { COLUMN_WIDTHS, countColumn, nameColumn, progressColumn, watchNextColumn } from './collectionColumns'+import { CollectionSectionHeading } from './CollectionSectionHeading'++const BUILT_IN_ICONS: Record<string, JSX.Element> = {+ 'synthetic-watch-history': <IconRewindPlay />,+ 'synthetic-commented': <IconComment />,+ 'synthetic-shared': <IconShare />,+ 'synthetic-exported': <IconDownload />,+ 'synthetic-expiring': <IconClock />,+ 'synthetic-frustrated': <IconWarning />,+}++const columns: LemonTableColumns<SessionRecordingPlaylistType> = [+ {+ width: COLUMN_WIDTHS.leading,+ render: function Render(_, { short_id }) {+ return (+ <span className="flex items-center justify-center w-9 h-8 text-xl text-secondary">+ {BUILT_IN_ICONS[short_id]}+ </span>+ )+ },+ },+ countColumn(),+ nameColumn(),+ { width: COLUMN_WIDTHS.createdBy + COLUMN_WIDTHS.lastModified, render: () => null },+ progressColumn(),+ watchNextColumn(),+ { width: COLUMN_WIDTHS.actions, render: () => null },+]++export function BuiltInCollections({+ playlists,+ loading,+}: {+ playlists: SessionRecordingPlaylistType[]+ loading: boolean+}): JSX.Element {+ return (+ <div className="border rounded overflow-hidden bg-surface-primary">+ <CollectionSectionHeading title="Built-in" description="Kept up to date by PostHog." />+ <LemonTable+ embedded+ tableLayout="fixed"+ loading={loading}+ columns={columns}+ dataSource={playlists}+ rowKey="short_id"+ loadingSkeletonRows={6}+ nouns={['collection', 'collections']}+ />+ </div>+ )+}diff --git a/frontend/src/scenes/session-recordings/collections/CollectionSectionHeading.tsx b/frontend/src/scenes/session-recordings/collections/CollectionSectionHeading.tsxnew file mode 100644index 000000000000..405dc0c098eb--- /dev/null+++ b/frontend/src/scenes/session-recordings/collections/CollectionSectionHeading.tsx@@ -0,0 +1,17 @@+export function CollectionSectionHeading({+ title,+ description,+ children,+}: {+ title: string+ description: string+ children?: React.ReactNode+}): JSX.Element {+ return (+ <div className="flex items-center gap-3 px-3 py-1.5 border-b bg-surface-tertiary dark:bg-surface-secondary flex-wrap">+ <span className="text-xs font-semibold uppercase tracking-wide text-secondary">{title}</span>+ <span className="text-xs text-muted">{description}</span>+ {children ? <div className="ml-auto flex items-center gap-2 flex-wrap">{children}</div> : null}+ </div>+ )+}diff --git a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsx b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsxindex 305494857fdd..d8ddb578b837 100644--- a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsx+++ b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsx@@ -1,17 +1,7 @@-import clsx from 'clsx'import { useActions, useValues } from 'kea'import { IconCalendar, IconPin, IconPinFilled } from '@posthog/icons'-import {- LemonBadge,- LemonButton,- LemonDivider,- LemonInput,- LemonSelect,- LemonTable,- Link,- Tooltip,-} from '@posthog/lemon-ui'+import { LemonButton, LemonDivider, LemonInput, LemonTable } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { DateFilter } from 'lib/components/DateFilter/DateFilter'@@ -20,130 +10,27 @@ import { TZLabel } from 'lib/components/TZLabel'import { More } from 'lib/lemon-ui/LemonButton/More'import { LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'-import { isObject } from 'lib/utils/guards'-import { urls } from 'scenes/urls'-import {- AccessControlLevel,- AccessControlResourceType,- PlaylistRecordingsCounts,- SessionRecordingPlaylistType,-} from '~/types'+import { AccessControlLevel, AccessControlResourceType, SessionRecordingPlaylistType } from '~/types'+import { BuiltInCollections } from './BuiltInCollections'+import { COLUMN_WIDTHS, countColumn, nameColumn, progressColumn, watchNextColumn } from './collectionColumns'+import { CollectionSectionHeading } from './CollectionSectionHeading'import { SessionRecordingCollectionsEmptyState } from './SessionRecordingCollectionsEmptyState'import { PLAYLISTS_PER_PAGE, sessionRecordingCollectionsLogic } from './sessionRecordingCollectionsLogic'-function nameColumn(): LemonTableColumn<SessionRecordingPlaylistType, 'name'> {- return {- title: 'Name',- dataIndex: 'name',- render: function Render(name, { short_id, derived_name, description, is_synthetic }) {- return (- <>- <Link- className={clsx('font-semibold', !name && 'italic')}- to={urls.replayPlaylist(short_id)}- data-attr={- is_synthetic- ? 'collections-scene-table-clicked-synthetic-collection'- : 'collections-scene-table-clicked-user-collection'- }- >- {name || derived_name || 'Unnamed'}- </Link>- {description ? <div className="truncate">{description}</div> : null}- </>- )- },- }-}--export function countColumn(): LemonTableColumn<SessionRecordingPlaylistType, 'recordings_counts'> {- return {- dataIndex: 'recordings_counts',- title: 'Count',- tooltip: 'Count of recordings in the collection',- width: 0,- render: function Render(recordings_counts) {- if (!isPlaylistRecordingsCounts(recordings_counts)) {- return null- }-- const hasResults =- recordings_counts.collection.count !== null || recordings_counts.saved_filters?.count !== null-- // Use collection count if available, otherwise fall back to saved_filters count- const totalCount: number | null =- recordings_counts.collection.count ?? recordings_counts.saved_filters?.count ?? null- const watchedCount: number =- recordings_counts.collection.watched_count ?? recordings_counts.saved_filters?.watched_count ?? 0- const unwatchedCount = (totalCount || 0) - watchedCount-- const tooltip = (- <div className="text-start">- {hasResults ? (- totalCount && totalCount > 0 ? (- unwatchedCount > 0 ? (- <p>- You have {unwatchedCount} unwatched recordings to watch out of a total of{' '}- {totalCount} in this collection.- </p>- ) : (- <p>You have watched all of the {totalCount} recordings in this collection.</p>- )- ) : (- <p>No results found for this collection.</p>- )- ) : (- <p>Counts have not yet been calculated for this collection.</p>- )}- </div>- )-- return (- <div className="flex items-center justify-start w-full h-full">- <Tooltip title={tooltip}>- {hasResults ? (- <span className="flex items-center gap-x-1 cursor-help">- <LemonBadge.Number- status={unwatchedCount ? 'primary' : 'muted'}- className="text-xs cursor-pointer"- count={totalCount || 0}- maxDigits={3}- showZero={true}- />- </span>- ) : (- <span>- <LemonBadge status="muted" content="?" className="cursor-pointer" />- </span>- )}- </Tooltip>- </div>- )- },- }-}--export function isPlaylistRecordingsCounts(x: unknown): x is PlaylistRecordingsCounts {- return isObject(x) && ('collection' in x || 'saved_filters' in x)-}-export function SessionRecordingCollections(): JSX.Element {- const { playlists, playlistsLoading, filters, sorting, pagination } = useValues(sessionRecordingCollectionsLogic)+ const { playlists, playlistsLoading, builtInPlaylists, builtInPlaylistsLoading, filters, sorting, pagination } =+ useValues(sessionRecordingCollectionsLogic)const { setSavedPlaylistsFilters, updatePlaylist, duplicatePlaylist, deletePlaylist } = useActions(sessionRecordingCollectionsLogic)const columns: LemonTableColumns<SessionRecordingPlaylistType> = [{- width: 0,+ width: COLUMN_WIDTHS.leading,dataIndex: 'pinned',- render: function Render(pinned, { is_synthetic, short_id }) {- // Don't show pin button for synthetic playlists- if (is_synthetic) {- return null- }+ render: function Render(pinned, { short_id }) {return (<AccessControlActionresourceType={AccessControlResourceType.SessionRecording}@@ -158,21 +45,21 @@ export function SessionRecordingCollections(): JSX.Element {)},},- countColumn() as LemonTableColumn<SessionRecordingPlaylistType, keyof SessionRecordingPlaylistType | undefined>,- nameColumn() as LemonTableColumn<SessionRecordingPlaylistType, keyof SessionRecordingPlaylistType | undefined>,+ countColumn(),+ nameColumn(),{...(createdByColumn<SessionRecordingPlaylistType>() as LemonTableColumn<SessionRecordingPlaylistType,keyof SessionRecordingPlaylistType | undefined>),- width: 0,+ width: COLUMN_WIDTHS.createdBy,},{title: 'Last modified',sorter: true,defaultSortOrder: -1,dataIndex: 'last_modified_at',- width: 0,+ width: COLUMN_WIDTHS.lastModified,render: function Render(last_modified_at) {return (<div>@@ -183,14 +70,11 @@ export function SessionRecordingCollections(): JSX.Element {)},},-+ progressColumn(),+ watchNextColumn(),{- width: 0,+ width: COLUMN_WIDTHS.actions,render: function Render(_, playlist) {- // Don't show actions menu for synthetic playlists- if (playlist.is_synthetic) {- return null- }return (<Moreoverlay={@@ -233,105 +117,78 @@ export function SessionRecordingCollections(): JSX.Element {]return (- <>- <div className="flex justify-between gap-2 items-center flex-wrap">- <LemonInput- type="search"- placeholder="Search for collections"- onChange={(value) => setSavedPlaylistsFilters({ search: value || undefined })}- value={filters.search || ''}- />- <div className="flex items-center gap-2 flex-wrap">- <div className="flex items-center gap-2">- <LemonButton- data-attr="session-recording-playlist-pinned-filter"- active={filters.pinned}- size="small"- type="secondary"- status="alt"- center- onClick={() => setSavedPlaylistsFilters({ pinned: !filters.pinned })}- icon={filters.pinned ? <IconPinFilled /> : <IconPin />}- >- Pinned- </LemonButton>-- <div className="flex items-center gap-2">- <span>Collection type:</span>- <LemonSelect- data-attr="session-recording-collections-type-select"- value={filters.collectionType}- onSelect={(value) => {- setSavedPlaylistsFilters({ collectionType: value })- }}- size="small"- options={[- {- label: 'All',- value: null,- },- {- label: 'Custom',- value: 'custom',- },- {- label: 'Automatic',- value: 'synthetic',- },- ]}- />- </div>- </div>- <div className="flex items-center gap-2">- <span>Last modified:</span>- <DateFilter- disabled={false}- dateFrom={filters.dateFrom}- dateTo={filters.dateTo}- onChange={(fromDate, toDate) =>- setSavedPlaylistsFilters({ dateFrom: fromDate, dateTo: toDate ?? undefined })- }- makeLabel={(key) => (- <>- <IconCalendar />- <span className="hide-when-small"> {key}</span>- </>- )}- max={21}- />- </div>- <div className="flex items-center gap-2">- <span>Created by:</span>- <MemberSelect- value={filters.createdBy === 'All users' ? null : filters.createdBy}- onChange={(user) => setSavedPlaylistsFilters({ createdBy: user?.id || 'All users' })}- />- </div>- </div>+ <div className="flex flex-col gap-6">+ <BuiltInCollections playlists={builtInPlaylists} loading={builtInPlaylistsLoading} />++ <div className="border rounded overflow-hidden bg-surface-primary">+ <CollectionSectionHeading title="Your collections" description="Made by your team.">+ <LemonButton+ data-attr="session-recording-playlist-pinned-filter"+ active={filters.pinned}+ size="small"+ type="secondary"+ status="alt"+ center+ onClick={() => setSavedPlaylistsFilters({ pinned: !filters.pinned })}+ icon={filters.pinned ? <IconPinFilled /> : <IconPin />}+ >+ Pinned+ </LemonButton>+ <DateFilter+ disabled={false}+ dateFrom={filters.dateFrom}+ dateTo={filters.dateTo}+ onChange={(fromDate, toDate) =>+ setSavedPlaylistsFilters({ dateFrom: fromDate, dateTo: toDate ?? undefined })+ }+ makeLabel={(key) => (+ <>+ <IconCalendar />+ <span className="hide-when-small"> {key}</span>+ </>+ )}+ max={21}+ size="small"+ />+ <MemberSelect+ defaultLabel="Any creator"+ value={filters.createdBy === 'All users' ? null : filters.createdBy}+ onChange={(user) => setSavedPlaylistsFilters({ createdBy: user?.id || 'All users' })}+ />+ <LemonInput+ type="search"+ size="small"+ placeholder="Search for collections"+ onChange={(value) => setSavedPlaylistsFilters({ search: value || undefined })}+ value={filters.search || ''}+ />+ </CollectionSectionHeading>++ {!playlistsLoading && playlists.count < 1 ? (+ <SessionRecordingCollectionsEmptyState />+ ) : (+ <LemonTable+ embedded+ tableLayout="fixed"+ loading={playlistsLoading}+ columns={columns}+ dataSource={playlists.results}+ pagination={pagination}+ noSortingCancellation+ sorting={sorting}+ onSort={(newSorting) =>+ setSavedPlaylistsFilters({+ order: newSorting+ ? `${newSorting.order === -1 ? '-' : ''}${newSorting.columnKey}`+ : undefined,+ })+ }+ rowKey="id"+ loadingSkeletonRows={PLAYLISTS_PER_PAGE}+ nouns={['collection', 'collections']}+ />+ )}</div>-- {!playlistsLoading && playlists.count < 1 ? (- <SessionRecordingCollectionsEmptyState />- ) : (- <LemonTable- loading={playlistsLoading}- columns={columns}- dataSource={playlists.results}- pagination={pagination}- noSortingCancellation- sorting={sorting}- onSort={(newSorting) =>- setSavedPlaylistsFilters({- order: newSorting- ? `${newSorting.order === -1 ? '-' : ''}${newSorting.columnKey}`- : undefined,- })- }- rowKey="id"- loadingSkeletonRows={PLAYLISTS_PER_PAGE}- nouns={['collection', 'collections']}- />- )}- </>+ </div>)}diff --git a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsEmptyState.tsx b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsEmptyState.tsxindex 1f6d0c6bb68c..90db8dabc349 100644--- a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsEmptyState.tsx+++ b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsEmptyState.tsx@@ -17,7 +17,7 @@ export function SessionRecordingCollectionsEmptyState(): JSX.Element {<LemonBanner type="error">Error while trying to load playlist.</LemonBanner>) : (<div className="flex items-center justify-center">- <div className="max-w-248 mt-12 flex flex-col items-center">+ <div className="max-w-248 my-12 flex flex-col items-center"><h2 className="text-xl">There are no collections that match these filters</h2><p className="text-secondary">Once you create a collection, it will show up here.</p><AccessControlActiondiff --git a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsLogic.test.ts b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsLogic.test.tsindex f50ca587f9db..42f841bc010b 100644--- a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsLogic.test.ts+++ b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsLogic.test.ts@@ -21,11 +21,16 @@ describe('sessionRecordingCollectionsLogic', () => {results: ['List of playlists'],}+ const builtInPlaylist = { short_id: 'synthetic-watch-history', name: 'Watch history', is_synthetic: true }+beforeEach(() => {useMocks({get: {'/api/projects/:team/session_recording_playlists': ({ request }) => {const { searchParams } = new URL(request.url)+ if (searchParams.get('collection_type') === 'synthetic') {+ return [200, { count: 1, results: [builtInPlaylist] }]+ }if (searchParams.get('date_to') === '2021-10-05') {return [200,@@ -104,6 +109,13 @@ describe('sessionRecordingCollectionsLogic', () => {.toDispatchActions(['loadPlaylistsSuccess']).toMatchValues({ playlists: mockPlaylistsResponse })})++ it('loads built-in collections in their own request', async () => {+ await expectLogic(logic)+ .toDispatchActions(['loadBuiltInPlaylistsSuccess'])+ .toMatchValues({ builtInPlaylists: [builtInPlaylist] })+ expect(logic.values.playlists.results).not.toContainEqual(builtInPlaylist)+ })})describe('filters', () => {diff --git a/frontend/src/scenes/session-recordings/collections/collectionColumns.tsx b/frontend/src/scenes/session-recordings/collections/collectionColumns.tsxnew file mode 100644index 000000000000..a92a849c8b14--- /dev/null+++ b/frontend/src/scenes/session-recordings/collections/collectionColumns.tsx@@ -0,0 +1,146 @@+import clsx from 'clsx'++import { IconChevronRight } from '@posthog/icons'+import { LemonBadge, LemonButton, Link, Tooltip } from '@posthog/lemon-ui'++import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { LemonTableColumn } from 'lib/lemon-ui/LemonTable'+import { urls } from 'scenes/urls'++import { SessionRecordingPlaylistType } from '~/types'++import { getCollectionCounts, watchNextUrl } from './collectionUtils'++type CollectionColumn = LemonTableColumn<SessionRecordingPlaylistType, keyof SessionRecordingPlaylistType | undefined>++export const COLUMN_WIDTHS = {+ leading: 48,+ count: 72,+ watched: 384,+ watchNext: 140,+ createdBy: 160,+ lastModified: 140,+ actions: 48,+}++export function nameColumn(): CollectionColumn {+ return {+ title: 'Name',+ dataIndex: 'name',+ render: function Render(name, { short_id, derived_name, description, is_synthetic }) {+ return (+ <>+ <Link+ className={clsx('font-semibold', !name && 'italic')}+ to={urls.replayPlaylist(short_id)}+ data-attr={+ is_synthetic+ ? 'collections-scene-table-clicked-synthetic-collection'+ : 'collections-scene-table-clicked-user-collection'+ }+ >+ {(name as string) || derived_name || 'Unnamed'}+ </Link>+ {description ? <div className="truncate">{description}</div> : null}+ </>+ )+ },+ }+}++export function countColumn(): CollectionColumn {+ return {+ dataIndex: 'recordings_counts',+ title: 'Count',+ tooltip: 'Count of recordings in the collection',+ width: COLUMN_WIDTHS.count,+ render: function Render(recordings_counts) {+ const counts = getCollectionCounts(recordings_counts)+ const tooltip = (+ <div className="text-start">+ {counts ? (+ counts.total && counts.total > 0 ? (+ counts.unwatched > 0 ? (+ <p>+ You have {counts.unwatched} unwatched recordings to watch out of a total of{' '}+ {counts.total} in this collection.+ </p>+ ) : (+ <p>You have watched all of the {counts.total} recordings in this collection.</p>+ )+ ) : (+ <p>No results found for this collection.</p>+ )+ ) : (+ <p>Counts have not yet been calculated for this collection.</p>+ )}+ </div>+ )++ return (+ <div className="flex items-center justify-start w-full h-full">+ <Tooltip title={tooltip}>+ {counts ? (+ <span className="flex items-center cursor-help">+ <LemonBadge.Number+ status={counts.unwatched ? 'primary' : 'muted'}+ className="text-xs cursor-pointer"+ count={counts.total || 0}+ maxDigits={3}+ showZero={true}+ />+ </span>+ ) : (+ <span>+ <LemonBadge status="muted" content="?" className="cursor-pointer" />+ </span>+ )}+ </Tooltip>+ </div>+ )+ },+ }+}++export function progressColumn(): CollectionColumn {+ return {+ title: 'Watched',+ width: COLUMN_WIDTHS.watched,+ render: function Render(_, playlist) {+ const counts = getCollectionCounts(playlist.recordings_counts)+ if (!counts || !counts.total) {+ return null+ }+ return (+ <div className="flex items-center gap-2">+ <LemonProgress percent={counts.watchedPercent} className="flex-1" />+ <span className="text-xs text-secondary whitespace-nowrap">+ {counts.watched} of {counts.total}+ </span>+ </div>+ )+ },+ }+}++export function watchNextColumn(): CollectionColumn {+ return {+ width: COLUMN_WIDTHS.watchNext,+ align: 'right',+ render: function Render(_, playlist) {+ const counts = getCollectionCounts(playlist.recordings_counts)+ return counts && counts.unwatched > 0 ? (+ <LemonButton+ size="small"+ type="secondary"+ to={watchNextUrl(playlist.short_id)}+ data-attr="collections-scene-watch-next"+ className="whitespace-nowrap"+ sideIcon={<IconChevronRight />}+ >+ Watch next+ </LemonButton>+ ) : null+ },+ }+}diff --git a/frontend/src/scenes/session-recordings/collections/collectionUtils.ts b/frontend/src/scenes/session-recordings/collections/collectionUtils.tsnew file mode 100644index 000000000000..1983e5a020b1--- /dev/null+++ b/frontend/src/scenes/session-recordings/collections/collectionUtils.ts@@ -0,0 +1,40 @@+import { combineUrl } from 'kea-router'++import { isObject } from 'lib/utils/guards'+import { urls } from 'scenes/urls'++import { PlaylistRecordingsCounts } from '~/types'++export interface CollectionCounts {+ total: number | null+ watched: number+ unwatched: number+ watchedPercent: number+}++export function isPlaylistRecordingsCounts(x: unknown): x is PlaylistRecordingsCounts {+ return isObject(x) && isObject(x.collection)+}++export function getCollectionCounts(recordingsCounts: unknown): CollectionCounts | null {+ if (!isPlaylistRecordingsCounts(recordingsCounts)) {+ return null+ }+ const hasResults =+ recordingsCounts.collection.count !== null || (recordingsCounts.saved_filters?.count ?? null) !== null+ if (!hasResults) {+ return null+ }+ const total = recordingsCounts.collection.count ?? recordingsCounts.saved_filters?.count ?? null+ const watched = recordingsCounts.collection.watched_count ?? recordingsCounts.saved_filters?.watched_count ?? 0+ return {+ total,+ watched,+ unwatched: Math.max(0, (total ?? 0) - watched),+ watchedPercent: total ? Math.min(100, Math.round((watched / total) * 100)) : 0,+ }+}++export function watchNextUrl(shortId: string): string {+ return combineUrl(urls.replayPlaylist(shortId), { watchNext: true }).url+}diff --git a/frontend/src/scenes/session-recordings/collections/sessionRecordingCollectionsLogic.ts b/frontend/src/scenes/session-recordings/collections/sessionRecordingCollectionsLogic.tsindex bcabad0ea26c..e7977578eccb 100644--- a/frontend/src/scenes/session-recordings/collections/sessionRecordingCollectionsLogic.ts+++ b/frontend/src/scenes/session-recordings/collections/sessionRecordingCollectionsLogic.ts@@ -29,11 +29,12 @@ export const DEFAULT_PLAYLIST_FILTERS = {page: 1,dateFrom: 'all',order: '-last_modified_at',- collectionType: null,}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface sessionRecordingCollectionsLogicValues {+ builtInPlaylists: SessionRecordingPlaylistType[]+ builtInPlaylistsLoading: booleanfilters: Record<string, any> | SavedSessionRecordingPlaylistsFiltersloadPlaylistsFailed: booleanpagination: PaginationManual@@ -101,6 +102,27 @@ export interface sessionRecordingCollectionsLogicActions {playlist: SessionRecordingPlaylistType}}+ loadBuiltInPlaylists: () => {+ value: true+ }+ loadBuiltInPlaylistsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadBuiltInPlaylistsSuccess: (+ builtInPlaylists: SessionRecordingPlaylistType[],+ payload?: {+ value: true+ }+ ) => {+ builtInPlaylists: SessionRecordingPlaylistType[]+ payload?: {+ value: true+ }+ }loadPlaylists: () => {value: true}@@ -195,6 +217,7 @@ export const sessionRecordingCollectionsLogic = kea<sessionRecordingCollectionsLfilters,}),loadPlaylists: true,+ loadBuiltInPlaylists: true,updatePlaylist: (shortId: SessionRecordingPlaylistType['short_id'],properties: Partial<SessionRecordingPlaylistType>@@ -235,6 +258,16 @@ export const sessionRecordingCollectionsLogic = kea<sessionRecordingCollectionsL],})),loaders(({ values, actions }) => ({+ builtInPlaylists: {+ __default: [] as SessionRecordingPlaylistType[],+ loadBuiltInPlaylists: async () => {+ // nosemgrep: prefer-codegen-api-namespaced-replay+ const response = await api.recordings.listPlaylists(+ toParams({ type: 'collection', collection_type: 'synthetic', limit: 100 })+ )+ return response.results.filter((playlist) => playlist.is_synthetic)+ },+ },playlists: {__default: { results: [], count: 0, filters: null } as SavedSessionRecordingPlaylistsResult,loadPlaylists: async (_, breakpoint) => {@@ -255,7 +288,7 @@ export const sessionRecordingCollectionsLogic = kea<sessionRecordingCollectionsLdate_to: filters.dateTo ?? undefined,pinned: filters.pinned ? true : undefined,type: 'collection',- collection_type: filters.collectionType ?? undefined,+ collection_type: 'custom',}const response = await api.recordings.listPlaylists(toParams(params))@@ -405,5 +438,6 @@ export const sessionRecordingCollectionsLogic = kea<sessionRecordingCollectionsL})),afterMount(({ actions }) => {actions.loadPlaylists()+ actions.loadBuiltInPlaylists()}),])diff --git a/frontend/src/scenes/session-recordings/playlist/AddRecordingsToCollectionModal.tsx b/frontend/src/scenes/session-recordings/playlist/AddRecordingsToCollectionModal.tsxnew file mode 100644index 000000000000..f95a6ebf5d1f--- /dev/null+++ b/frontend/src/scenes/session-recordings/playlist/AddRecordingsToCollectionModal.tsx@@ -0,0 +1,72 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonModal } from '@posthog/lemon-ui'++import { SessionRecordingsPlaylist } from './SessionRecordingsPlaylist'+import { SessionRecordingPlaylistLogicProps, sessionRecordingsPlaylistLogic } from './sessionRecordingsPlaylistLogic'+import { sessionRecordingsPlaylistSceneLogic } from './sessionRecordingsPlaylistSceneLogic'++function AddSelectedFooter({+ playlistProps,+ shortId,+ onClose,+}: {+ playlistProps: SessionRecordingPlaylistLogicProps+ shortId: string+ onClose: () => void+}): JSX.Element {+ const { selectedRecordingsIds } = useValues(sessionRecordingsPlaylistLogic(playlistProps))+ const { handleBulkAddToPlaylist } = useActions(sessionRecordingsPlaylistLogic(playlistProps))+ const count = selectedRecordingsIds.length++ return (+ <div className="flex justify-end gap-2">+ <LemonButton type="secondary" onClick={onClose}>+ Done+ </LemonButton>+ <LemonButton+ type="primary"+ disabledReason={count === 0 ? 'Select recordings in the list first' : undefined}+ onClick={() => handleBulkAddToPlaylist(shortId)}+ data-attr="collection-add-selected-recordings"+ >+ Add {count} {count === 1 ? 'recording' : 'recordings'}+ </LemonButton>+ </div>+ )+}++export function AddRecordingsToCollectionModal(): JSX.Element | null {+ const { playlist, isAddRecordingsModalOpen } = useValues(sessionRecordingsPlaylistSceneLogic)+ const { setAddRecordingsModalOpen, onPinnedChange } = useActions(sessionRecordingsPlaylistSceneLogic)++ if (!playlist) {+ return null+ }++ const playlistProps: SessionRecordingPlaylistLogicProps = {+ logicKey: `add-recordings-${playlist.short_id}`,+ type: 'filters',+ updateSearchParams: false,+ autoPlay: true,+ onlyPinned: false,+ onPinnedChange,+ }+ const close = (): void => setAddRecordingsModalOpen(false)++ return (+ <LemonModal+ isOpen={isAddRecordingsModalOpen}+ onClose={close}+ title={`Add recordings to ${playlist.name || playlist.derived_name || 'this collection'}`}+ description="Filter the list, tick the recordings you want, then add them."+ width="90vw"+ maxWidth="90vw"+ footer={<AddSelectedFooter playlistProps={playlistProps} shortId={playlist.short_id} onClose={close} />}+ >+ <div className="h-[75vh]">+ <SessionRecordingsPlaylist {...playlistProps} />+ </div>+ </LemonModal>+ )+}diff --git a/frontend/src/scenes/session-recordings/playlist/Playlist.tsx b/frontend/src/scenes/session-recordings/playlist/Playlist.tsxindex fe95e8db652f..012e12e77b56 100644--- a/frontend/src/scenes/session-recordings/playlist/Playlist.tsx+++ b/frontend/src/scenes/session-recordings/playlist/Playlist.tsx@@ -452,11 +452,7 @@ const CollectionEmptyState = ({) : (<div className="flex flex-col gap-2"><h3 className="title text-secondary mb-0">No recordings in this collection</h3>- <p>- To add recordings to this collection, go to the{' '}- <Link to={urls.replay(ReplayTabs.Home)}>Recordings</Link> tab, click on a recording, then click- "+ Add to collection" and select this collection from the list.- </p>+ <p>Use "Add recordings" above to browse recordings and add them to this collection.</p></div>)}</div>diff --git a/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistScene.tsx b/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistScene.tsxindex e728a4c5798b..176030ddc88f 100644--- a/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistScene.tsx+++ b/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistScene.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import posthog from 'posthog-js'import { useEffect, useMemo } from 'react'-import { IconCopy, IconTrash } from '@posthog/icons'+import { IconCopy, IconPlus, IconTrash } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'@@ -36,6 +36,7 @@ import {ScenePanelInfoSection,} from '~/layout/scenes/SceneLayout'+import { AddRecordingsToCollectionModal } from './AddRecordingsToCollectionModal'import { SessionRecordingsPlaylist } from './SessionRecordingsPlaylist'import { asUniversalFilters } from './sessionRecordingsPlaylistLogic'import {@@ -77,9 +78,8 @@ function PlaylistSceneLoadingSkeleton(): JSX.Element {export function SessionRecordingsPlaylistScene(): JSX.Element {const { playlist, playlistLoading, pinnedRecordings, hasChanges } = useValues(sessionRecordingsPlaylistSceneLogic)- const { setFilters, updatePlaylist, duplicatePlaylist, deletePlaylist, onPinnedChange } = useActions(- sessionRecordingsPlaylistSceneLogic- )+ const { setFilters, updatePlaylist, duplicatePlaylist, deletePlaylist, onPinnedChange, setAddRecordingsModalOpen } =+ useActions(sessionRecordingsPlaylistSceneLogic)const { showFilters } = useValues(playerSettingsLogic)const { setShowFilters } = useActions(playerSettingsLogic)@@ -210,7 +210,17 @@ export function SessionRecordingsPlaylistScene(): JSX.Element {saveOnBlurrenameDebounceMs={100}actions={- !playlist.is_synthetic ? (+ playlist.is_synthetic ? undefined : playlist.type === 'collection' ? (+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlus />}+ onClick={() => setAddRecordingsModalOpen(true)}+ data-attr="collection-add-recordings"+ >+ Add recordings+ </LemonButton>+ ) : (<LemonButtontype="primary"disabledReason={showFilters && !hasChanges ? 'No changes to save' : undefined}@@ -222,10 +232,11 @@ export function SessionRecordingsPlaylistScene(): JSX.Element {>{showFilters ? <>Save changes</> : <>Edit</>}</LemonButton>- ) : undefined+ )}/>+ <AddRecordingsToCollectionModal /><SessionRecordingsPlaylistlogicKey={playlist.short_id}// backwards compatibility for legacy filtersdiff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.tsindex 47fd07c72585..06c3a1697850 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts@@ -179,6 +179,27 @@ describe('sessionRecordingsPlaylistLogic', () => {localStorage.clear()})+ describe('watch next', () => {+ it('selects the first unwatched recording when the URL asks for it', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/session_recordings': () => [+ 200,+ { has_next: false, results: [{ ...aRecording, viewed: true }, bRecording] },+ ],+ },+ })+ router.actions.push('/replay', { watchNext: true })+ logic = sessionRecordingsPlaylistLogic({ logicKey: 'watch-next', updateSearchParams: true })+ logic.mount()++ await expectLogic(logic)+ .toDispatchActions(['loadSessionRecordingsSuccess', 'setSelectedRecordingId'])+ .toMatchValues({ selectedRecordingId: bRecording.id, watchNextRequested: false })+ expect(router.values.searchParams).not.toHaveProperty('watchNext')+ })+ })+describe('global logic', () => {beforeEach(() => {logic = sessionRecordingsPlaylistLogic({diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.tsindex 7a4e5e81e220..387416de2096 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts@@ -86,6 +86,7 @@ export type PersonUUID = stringinterface ReplayURLBaseSearchParams {sessionRecordingId?: SessionRecordingId+ watchNext?: boolean}/**@@ -631,6 +632,7 @@ export interface sessionRecordingsPlaylistLogicValues {unusableEventsInFilter: string[]viewerFilterKeys: string[]visiblePinnedRecordings: SessionRecordingType[]+ watchNextRequested: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -885,6 +887,9 @@ export interface sessionRecordingsPlaylistLogicActions {setShowSettings: (showSettings: boolean) => {showSettings: boolean}+ setWatchNextRequested: (requested: boolean) => {+ requested: boolean+ }togglePropertyFilter: (propertyKey: string,propertyValue: string | undefined@@ -905,7 +910,8 @@ export interface sessionRecordingsPlaylistLogicMeta {activeSessionRecordingId: (selectedRecordingId: string | null,recordings: SessionRecordingType[],- arg: any+ arg: any,+ watchNextRequested: boolean) => SessionRecordingId | undefinedactiveSessionRecording: (activeSessionRecordingId: string | undefined,@@ -1018,6 +1024,7 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicsetSelectedRecordingId: (id: SessionRecordingType['id'] | null) => ({id,}),+ setWatchNextRequested: (requested: boolean) => ({ requested }),loadAllRecordings: true,loadPinnedRecordings: true,loadSessionRecordings: (@@ -1436,6 +1443,13 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicsetSelectedRecordingId: (_, { id }) => id ?? null,},],+ watchNextRequested: [+ false,+ {+ setWatchNextRequested: (_, { requested }) => requested,+ setSelectedRecordingId: () => false,+ },+ ],sessionRecordingsAPIErrored: [false,{@@ -1509,6 +1523,15 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic],})),listeners(({ props, actions, values, cache }) => {+ const selectWatchNext = (): void => {+ if (!values.watchNextRequested) {+ return+ }+ const next = values.recordings.find((recording) => !recording.viewed)+ if (next) {+ actions.setSelectedRecordingId(next.id)+ }+ }// The player can start showing a recording with no action dispatched: under autoPlay it// falls back to the first in the list, and moves when a reload changes which recording// is first. So selection is reported from the resulting active id after every action@@ -1760,6 +1783,7 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic},loadSessionRecordingsSuccess: ({ sessionRecordingsResponse, payload }) => {+ selectWatchNext()actions.maybeLoadPropertiesForSessions(values.sessionRecordings)// A load without a direction replaces the list rather than paging it, the same// reading the `sessionRecordings` reducer takes.@@ -1784,6 +1808,7 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic},loadPinnedRecordingsSuccess: () => {+ selectWatchNext()pruneSelectedRecordingsIds()// Pinned recordings sort first, so this load can change which recording the// autoplay fallback shows, just like a list load.@@ -2085,13 +2110,17 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic],activeSessionRecordingId: [- (s) => [s.selectedRecordingId, s.recordings, (_, props) => props.autoPlay],+ (s) => [s.selectedRecordingId, s.recordings, (_, props) => props.autoPlay, s.watchNextRequested],(selectedRecordingId: SessionRecordingType['id'] | null,recordings: SessionRecordingType[],- autoPlay+ autoPlay,+ watchNextRequested: boolean): SessionRecordingId | undefined => {- return selectedRecordingId ? selectedRecordingId : autoPlay ? recordings[0]?.id : undefined+ if (selectedRecordingId) {+ return selectedRecordingId+ }+ return autoPlay && !watchNextRequested ? recordings[0]?.id : undefined},],@@ -2342,6 +2371,7 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic...router.values.searchParams,filters: objectsEqual(values.filters, getDefaultFilters(props.personUUID)) ? undefined : values.filters,sessionRecordingId: values.selectedRecordingId ?? undefined,+ watchNext: undefined,})// we don't keep these if they're still in the URL at this point@@ -2378,6 +2408,9 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicif (nulledSessionRecordingId !== values.selectedRecordingId) {actions.setSelectedRecordingId(nulledSessionRecordingId)}+ if (params.watchNext && !values.watchNextRequested) {+ actions.setWatchNextRequested(true)+ }let quickEventFilter: UniversalFilterValue | null = nulllet quickPersonFilter: UniversalFilterValue | null = nulldiff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.tsindex 88e46f44a133..e560cd66d7f1 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts@@ -51,6 +51,7 @@ export interface sessionRecordingsPlaylistSceneLogicValues {derivedName: stringfilters: LegacyRecordingFilters | RecordingUniversalFilters | nullhasChanges: boolean+ isAddRecordingsModalOpen: booleanpinnedRecordings: SessionRecordingType[] | nullpinnedRecordingsLoading: booleanplaylist: SessionRecordingPlaylistType | null@@ -159,6 +160,9 @@ export interface sessionRecordingsPlaylistSceneLogicActions {recording: SessionRecordingType}}+ setAddRecordingsModalOpen: (open: boolean) => {+ open: boolean+ }setFilters: (filters: LegacyRecordingFilters | RecordingUniversalFilters | null) => {filters: LegacyRecordingFilters | RecordingUniversalFilters | null}@@ -232,6 +236,7 @@ export const sessionRecordingsPlaylistSceneLogic = kea<sessionRecordingsPlaylistloadPinnedRecordings: true,onPinnedChange: (recording: SessionRecordingType, pinned: boolean) => ({ pinned, recording }),markPlaylistViewed: true,+ setAddRecordingsModalOpen: (open: boolean) => ({ open }),}),loaders(({ actions, values, props }) => ({playlist: [@@ -305,6 +310,12 @@ export const sessionRecordingsPlaylistSceneLogic = kea<sessionRecordingsPlaylist],})),reducers(() => ({+ isAddRecordingsModalOpen: [+ false,+ {+ setAddRecordingsModalOpen: (_, { open }) => open,+ },+ ],filters: [null as LegacyRecordingFilters | RecordingUniversalFilters | null,{@@ -354,6 +365,7 @@ export const sessionRecordingsPlaylistSceneLogic = kea<sessionRecordingsPlaylistenabled: (newLocation) => {const response =values.activeSceneId === Scene.ReplayPlaylist &&+ values.playlist?.type === 'filters' &&values.hasChanges &&removeProjectIdIfPresent(newLocation?.pathname ?? '') !==removeProjectIdIfPresent(router.values.location.pathname) &&diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex a628590dfa53..64e578bfd218 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -2088,7 +2088,6 @@ export interface SavedSessionRecordingPlaylistsFilters {page: numberpinned: booleantype?: 'collection' | 'saved_filters'- collectionType: 'custom' | 'synthetic' | null}export interface SavedSessionRecordingPlaylistsResult extends PaginatedResponse<SessionRecordingPlaylistType> {