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.

fix(cohorts): show errors and a selected-people list when adding users manually (#100100)

posthog[bot]c5f5ace02914
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4848924b8798..4e244f51a3b3 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10836,6 +10836,10 @@ snapshots:
hash: v1.k794b7964.1a3c8015c3629b9bef09e106c60dacbe134e777ac0ad76fa2d87f5206d45a122.IeXmNgG1kSJpeuC2u8w4to4R_8RyCnZLd4IQ6T6EDbo
scenes-app-people-cohorts-add-person-to-cohort-modal--modal-inline--light:
hash: v1.k794b7964.6eabd2ce475eea83113a11275b335f7202f6da10fe2ebdfbc574f3b323daff8e.abHOQDCEtn7AWNmWKwPjeXqiMbY5UnWeefHV9iGBd3s
+ scenes-app-people-cohorts-add-person-to-cohort-modal--modal-query-failed--dark:
+ hash: v1.k794b7964.fc464d8369d84ebda855eaca59771c5034bf3940ee1a36d2404b31b7d66c9d66.Ux6EYrnrc0ZjifXVb4IcqQ7fOO98GAGIXoGnkVf-IKw
+ scenes-app-people-cohorts-add-person-to-cohort-modal--modal-query-failed--light:
+ hash: v1.k794b7964.5e791b8c302c4a2f42cfd7919e18b70c96639984f2e9984fb24299e7b5e90fac.DD88Bn4BP5_7K8iAHyNH6XaebSPNYLa0RDzOAh3vSvA
scenes-app-people-cohorts-add-person-to-cohort-modal--modal-with-all-selected--dark:
hash: v1.k794b7964.730f63a37031a8670713c04b565dee44eb0daf7ca1739d3ec65fb46cf1fb6022.P67NSd6TYkZMOWMhgH7gK0ia88hUc1NU3u0rPO5Gn08
scenes-app-people-cohorts-add-person-to-cohort-modal--modal-with-all-selected--light:
diff --git a/frontend/src/scenes/cohorts/AddPersonToCohortModal.stories.tsx b/frontend/src/scenes/cohorts/AddPersonToCohortModal.stories.tsx
index fff369d06901..0698d320133f 100644
--- a/frontend/src/scenes/cohorts/AddPersonToCohortModal.stories.tsx
+++ b/frontend/src/scenes/cohorts/AddPersonToCohortModal.stories.tsx
@@ -46,33 +46,20 @@ const DEFAULT_QUERY = {
}
const noop = (): void => {}
-const actorsQueryHandler = async ({
- request,
-}: MockResolverInfo): Promise<[number, typeof mockQueryResponse] | undefined> => {
- const body = (await request.json()) as { query?: { kind?: string; source?: { kind?: string } } }
- const queryKind = body?.query?.source?.kind ?? body?.query?.kind
-
- if (queryKind === 'ActorsQuery') {
- return [200, mockQueryResponse]
+const mockActorsQuery =
+ (status: number, responseBody: Record<string, any>) =>
+ async ({ request }: MockResolverInfo): Promise<[number, Record<string, any>] | undefined> => {
+ const body = (await request.json()) as { query?: { kind?: string; source?: { kind?: string } } }
+ const queryKind = body?.query?.source?.kind ?? body?.query?.kind
+
+ if (queryKind === 'ActorsQuery') {
+ return [status, responseBody]
+ }
}
-}
-const emptyActorsQueryHandler = async ({
- request,
-}: MockResolverInfo): Promise<[number, typeof mockQueryResponse] | undefined> => {
- const body = (await request.json()) as { query?: { kind?: string; source?: { kind?: string } } }
- const queryKind = body?.query?.source?.kind ?? body?.query?.kind
-
- if (queryKind === 'ActorsQuery') {
- return [
- 200,
- {
- ...mockQueryResponse,
- results: [],
- },
- ]
- }
-}
+const actorsQueryHandler = mockActorsQuery(200, mockQueryResponse)
+const emptyActorsQueryHandler = mockActorsQuery(200, { ...mockQueryResponse, results: [] })
+const erroredActorsQueryHandler = mockActorsQuery(500, { type: 'server_error', detail: 'Query failed to execute' })
function ModalShell({
children,
@@ -157,6 +144,27 @@ export const ModalWithAllSelected: Story = {
},
}
+export const ModalQueryFailed: Story = {
+ render: () => {
+ useStorybookMocks({
+ post: { '/api/environments/:team_id/query/:kind/': erroredActorsQueryHandler },
+ })
+
+ return (
+ <ModalShell saveDisabledReason="Select at least one user">
+ <PersonSelectList
+ query={DEFAULT_QUERY}
+ setQuery={noop}
+ selectedPersons={{}}
+ onAddPerson={noop}
+ onRemovePerson={noop}
+ dataNodeKey="story-modal-query-failed"
+ />
+ </ModalShell>
+ )
+ },
+}
+
export const ModalEmpty: Story = {
render: () => {
useStorybookMocks({
diff --git a/frontend/src/scenes/cohorts/CohortEdit.test.tsx b/frontend/src/scenes/cohorts/CohortEdit.test.tsx
index 08b59e9ac2f4..111d2419c2de 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.test.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { expectLogic, partial } from 'kea-test-utils'
@@ -702,6 +702,37 @@ describe('cohortEditLogic', () => {
})
})
+ describe('manual person selection on a new static cohort', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('keeps the selected people removable while the person search fails', async () => {
+ useMocks({
+ post: {
+ '/api/environments/:team_id/query/:query_kind/': () => [500, { detail: 'Query failed to execute' }],
+ },
+ })
+ logic = cohortEditLogic({ id: 'new' })
+ logic.mount()
+ logic.actions.setCohort({ ...NEW_COHORT, is_static: true })
+ logic.actions.addPersonToCreateStaticCohort('person-1', 'Jane Doe')
+ logic.actions.addPersonToCreateStaticCohort('person-2', 'John Smith')
+
+ render(<CohortEdit id="new" />)
+
+ expect(await screen.findByTestId('insight-empty-state')).toBeInTheDocument()
+ const selected = screen.getByTestId('cohort-selected-persons')
+ expect(selected).toHaveTextContent('Selected people (2)')
+
+ await userEvent.click(within(within(selected).getByText('Jane Doe').parentElement!).getByRole('button'))
+
+ expect(selected).toHaveTextContent('Selected people (1)')
+ expect(within(selected).queryByText('Jane Doe')).not.toBeInTheDocument()
+ expect(within(selected).getByText('John Smith')).toBeInTheDocument()
+ })
+ })
+
describe('criteria row type switching', () => {
afterEach(() => {
cleanup()
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsx
index 9a719191269e..9a1484d7fb2a 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx
@@ -14,7 +14,16 @@ import {
IconUpload,
IconWarning,
} from '@posthog/icons'
-import { LemonBanner, LemonDialog, LemonDivider, LemonFileInput, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'
+import {
+ LemonBanner,
+ LemonDialog,
+ LemonDivider,
+ LemonFileInput,
+ LemonSnack,
+ LemonTabs,
+ Link,
+ Tooltip,
+} from '@posthog/lemon-ui'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { NotFound } from 'lib/components/NotFound'
@@ -760,6 +769,34 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
onRemovePerson={removePersonFromCreateStaticCohort}
dataNodeKey="createStaticCohort"
/>
+ {Object.keys(personsToCreateStaticCohort).length > 0 && (
+ <div
+ className="flex flex-col gap-y-1"
+ data-attr="cohort-selected-persons"
+ >
+ <h4 className="text-xs font-semibold uppercase opacity-60 mb-0">
+ Selected people (
+ <span translate="no">
+ {Object.keys(personsToCreateStaticCohort).length}
+ </span>
+ )
+ </h4>
+ <div className="flex flex-wrap gap-1">
+ {Object.entries(personsToCreateStaticCohort).map(
+ ([personId, displayName]) => (
+ <LemonSnack
+ key={personId}
+ onClose={() =>
+ removePersonFromCreateStaticCohort(personId)
+ }
+ >
+ {displayName || personId}
+ </LemonSnack>
+ )
+ )}
+ </div>
+ </div>
+ )}
</>
)}
{!isNewCohort && (
diff --git a/frontend/src/scenes/cohorts/PersonSelectList.tsx b/frontend/src/scenes/cohorts/PersonSelectList.tsx
index 70613d759a4e..7dfa9673b316 100644
--- a/frontend/src/scenes/cohorts/PersonSelectList.tsx
+++ b/frontend/src/scenes/cohorts/PersonSelectList.tsx
@@ -11,6 +11,7 @@ import { LemonButton, LemonCheckbox, LemonTag } from '@posthog/lemon-ui'
import { AutoSizer } from 'lib/components/AutoSizer'
import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
import { Spinner } from 'lib/lemon-ui/Spinner'
+import { InsightErrorState } from 'scenes/insights/EmptyStates'
import { urls } from 'scenes/urls'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
@@ -38,8 +39,8 @@ function parseResults(results: any[][] | undefined): PersonRowData[] {
interface PersonRowProps {
persons: PersonRowData[]
existingPersonsSet: Set<string> | undefined
- selectedPersons: Record<string, boolean>
- onAddPerson: (id: string) => void
+ selectedPersons: Record<string, unknown>
+ onAddPerson: (id: string, displayName: string | null) => void
onRemovePerson: (id: string) => void
}
@@ -54,7 +55,7 @@ const PersonRowComponent = ({
}: PersonRowProps & { index: number; style: CSSProperties; ariaAttributes: Record<string, unknown> }): JSX.Element => {
const person = persons[index]
const isInCohort = existingPersonsSet?.has(person.id) ?? false
- const isSelected = selectedPersons[person.id] != null
+ const isSelected = person.id in selectedPersons
const personUrl = person.displayName?.id ? urls.personByUUID(person.displayName.id) : undefined
return (
@@ -67,7 +68,7 @@ const PersonRowComponent = ({
if (isSelected) {
onRemovePerson(person.id)
} else {
- onAddPerson(person.id)
+ onAddPerson(person.id, person.displayName?.display_name ?? null)
}
}}
fullWidth
@@ -108,8 +109,8 @@ const PersonRowComponent = ({
export interface PersonSelectListProps {
query: ActorsQuery
setQuery: (query: ActorsQuery) => void
- selectedPersons: Record<string, boolean>
- onAddPerson: (id: string) => void
+ selectedPersons: Record<string, unknown>
+ onAddPerson: (id: string, displayName: string | null) => void
onRemovePerson: (id: string) => void
existingPersonsSet?: Set<string>
dataNodeKey: string
@@ -134,8 +135,10 @@ export function PersonSelectList({
[dataNodeKey, query]
)
- const { response, responseLoading, canLoadNextData, nextDataLoading } = useValues(dataNodeLogic(dataNodeLogicProps))
- const { loadNextData } = useActions(dataNodeLogic(dataNodeLogicProps))
+ const logic = dataNodeLogic(dataNodeLogicProps)
+ const { response, responseLoading, responseError, responseErrorObject, queryId, canLoadNextData, nextDataLoading } =
+ useValues(logic)
+ const { loadNextData, loadData } = useActions(logic)
const persons = useMemo(() => parseResults((response as Record<string, any> | null)?.results), [response])
@@ -171,7 +174,17 @@ export function PersonSelectList({
/>
<BindLogic logic={dataNodeLogic} props={dataNodeLogicProps}>
<div className="AddPersonToCohortModalBody__list">
- {responseLoading && persons.length === 0 ? (
+ {responseError ? (
+ <div className="flex h-full">
+ <InsightErrorState
+ query={query}
+ queryId={responseErrorObject?.queryId ?? queryId}
+ titleStatus={responseErrorObject?.status}
+ onRetry={() => loadData('force_blocking')}
+ title={responseError}
+ />
+ </div>
+ ) : responseLoading && persons.length === 0 ? (
<div className="flex items-center justify-center h-full">
<Spinner className="text-2xl" />
</div>
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
index fec386acbcf8..e959ecf523d7 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
@@ -1014,6 +1014,24 @@ describe('cohortEditLogic', () => {
})
})
+ describe('manual person selection for static cohort creation', () => {
+ it('keeps the display name so it can be shown in the selected list, and forgets it on remove', async () => {
+ await initCohortLogic({ id: 'new' })
+
+ await expectLogic(logic, () => {
+ logic.actions.addPersonToCreateStaticCohort('person-1', 'Jane Doe')
+ }).toMatchValues({
+ personsToCreateStaticCohort: { 'person-1': 'Jane Doe' },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.removePersonFromCreateStaticCohort('person-1')
+ }).toMatchValues({
+ personsToCreateStaticCohort: {},
+ })
+ })
+ })
+
describe('mutate filters', () => {
beforeEach(async () => {
await initCohortLogic({ id: 1 })
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.ts
index 16602cd2a5d6..e9506ffc8b50 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts
@@ -143,7 +143,7 @@ export interface cohortEditLogicValues {
isCohortValid: boolean
isPendingCalculation: boolean
persistedColumns: string[] | null
- personsToCreateStaticCohort: Record<string, boolean>
+ personsToCreateStaticCohort: Record<string, string | null>
pollTimeout: number | null
query: DataTableNode
showCohortErrors: boolean
@@ -165,7 +165,11 @@ export interface cohortEditLogicActions {
addFilter: (groupIndex?: number) => {
groupIndex: number | undefined
}
- addPersonToCreateStaticCohort: (personId: string) => {
+ addPersonToCreateStaticCohort: (
+ personId: string,
+ displayName: string | null
+ ) => {
+ displayName: string | null
personId: string
}
armRealtimeReadinessPoll: () => {
@@ -568,7 +572,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
duplicateCohort: (asStatic: boolean) => ({ asStatic }),
updateCohortCount: true,
setCreationPersonQuery: (query: ActorsQuery) => ({ query }),
- addPersonToCreateStaticCohort: (personId: string) => ({ personId }),
+ addPersonToCreateStaticCohort: (personId: string, displayName: string | null) => ({ personId, displayName }),
removePersonFromCreateStaticCohort: (personId: string) => ({ personId }),
removePersonFromCohort: (personId: string) => ({ personId }),
resetPersonsToCreateStaticCohort: true,
@@ -756,11 +760,11 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
},
],
personsToCreateStaticCohort: [
- {} as Record<string, boolean>,
+ {} as Record<string, string | null>,
{
- addPersonToCreateStaticCohort: (state, { personId }) => ({
+ addPersonToCreateStaticCohort: (state, { personId, displayName }) => ({
...state,
- [personId]: true,
+ [personId]: displayName,
}),
removePersonFromCreateStaticCohort: (state, { personId }) => {
const newState = { ...state }