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(desktop): name the cohorts a cohort's criteria reference (#95640)

Shy Alter31b8040b8098
diff --git a/products/desktop/packages/api-client/src/evidence-previews.test.ts b/products/desktop/packages/api-client/src/evidence-previews.test.ts
index d9d612c27c61..1fe73f7070fa 100644
--- a/products/desktop/packages/api-client/src/evidence-previews.test.ts
+++ b/products/desktop/packages/api-client/src/evidence-previews.test.ts
@@ -611,37 +611,41 @@ describe("evidence preview shaping", () => {
]);
});
- it("renders negated criteria as their negative meaning", () => {
- const sections = cohortCriteriaSection({
- properties: {
- type: "AND",
- values: [
- {
- type: "AND",
- values: [
- {
- type: "behavioral",
- value: "performed_event",
- key: "checkout",
- negation: true,
- },
- {
- type: "cohort",
- value: "Power users",
- negation: true,
- },
- {
- type: "person",
- key: "email",
- operator: "icontains",
- value: "@example.com",
- negation: true,
- },
- ],
- },
- ],
+ it("renders negated criteria and resolved cohort names", () => {
+ const sections = cohortCriteriaSection(
+ {
+ properties: {
+ type: "AND",
+ values: [
+ {
+ type: "AND",
+ values: [
+ {
+ type: "behavioral",
+ value: "performed_event",
+ key: "checkout",
+ negation: true,
+ },
+ {
+ type: "cohort",
+ value: 42,
+ negation: true,
+ },
+ { type: "cohort", value: 77 },
+ {
+ type: "person",
+ key: "email",
+ operator: "icontains",
+ value: "@example.com",
+ negation: true,
+ },
+ ],
+ },
+ ],
+ },
},
- });
+ new Map([["42", "Power users"]]),
+ );
expect(sections).toEqual([
{
title: "Membership criteria",
@@ -649,7 +653,7 @@ describe("evidence preview shaping", () => {
{
label: "Criteria",
value:
- "Did not complete checkout and Is not in cohort Power users and email does not contain @example.com",
+ "Did not complete checkout and Is not in cohort Power users and Is in cohort 77 and email does not contain @example.com",
},
],
},
diff --git a/products/desktop/packages/api-client/src/evidence-previews.ts b/products/desktop/packages/api-client/src/evidence-previews.ts
index 01c8426de30f..a1ed832c408a 100644
--- a/products/desktop/packages/api-client/src/evidence-previews.ts
+++ b/products/desktop/packages/api-client/src/evidence-previews.ts
@@ -1434,12 +1434,42 @@ function asCount(value: unknown): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
-function describeCohortCriterion(criterion: QueryRecord): string | null {
+/** Cohort ids referenced by a cohort's criteria, so the caller can resolve their names. */
+export function referencedCohortIds(filters: unknown): string[] {
+ const ids = new Set<string>();
+ for (const group of criteriaGroups(filters)) {
+ for (const criterion of asRecords(group.values)) {
+ const id =
+ criterion.type === "cohort" ? conciseValue(criterion.value) : null;
+ if (id) ids.add(id);
+ }
+ }
+ return [...ids];
+}
+
+function asRecords(value: unknown): QueryRecord[] {
+ return (Array.isArray(value) ? value : []).filter(isRecord);
+}
+
+function criteriaGroups(filters: unknown): QueryRecord[] {
+ const properties =
+ isRecord(filters) && isRecord(filters.properties)
+ ? filters.properties
+ : null;
+ return asRecords(properties?.values);
+}
+
+function describeCohortCriterion(
+ criterion: QueryRecord,
+ cohortNames: ReadonlyMap<string, string>,
+): string | null {
const type = String(criterion.type ?? "");
if (type === "behavioral") return describeBehavioralCriterion(criterion);
const negated = criterion.negation === true;
- if (type === "cohort")
- return `Is ${negated ? "not " : ""}in cohort ${conciseValue(criterion.value) ?? "?"}`;
+ if (type === "cohort") {
+ const id = conciseValue(criterion.value) ?? "?";
+ return `Is ${negated ? "not " : ""}in cohort ${cohortNames.get(id) ?? id}`;
+ }
if (type === "static-cohort")
return `Is ${negated ? "not " : ""}in a static cohort`;
if (type === "person" || type === "event" || type === "group") {
@@ -1470,19 +1500,16 @@ function describeCohortCriterion(criterion: QueryRecord): string | null {
*/
export function cohortCriteriaSection(
filters: unknown,
+ cohortNames: ReadonlyMap<string, string> = new Map(),
): EvidenceDetailSection[] {
- const properties =
+ const groups = criteriaGroups(filters);
+ const outerAny =
isRecord(filters) && isRecord(filters.properties)
- ? filters.properties
- : null;
- const groups = (
- Array.isArray(properties?.values) ? properties.values : []
- ).filter(isRecord);
- const outerAny = properties?.type === "OR";
+ ? filters.properties.type === "OR"
+ : false;
const fields = groups.flatMap((group, index) => {
- const criteria = (Array.isArray(group.values) ? group.values : [])
- .filter(isRecord)
- .map(describeCohortCriterion)
+ const criteria = asRecords(group.values)
+ .map((criterion) => describeCohortCriterion(criterion, cohortNames))
.filter((line): line is string => line !== null);
if (criteria.length === 0) return [];
const joiner = group.type === "OR" ? " or " : " and ";
@@ -1495,7 +1522,10 @@ export function cohortCriteriaSection(
return detailSection("Membership criteria", fields);
}
-export function shapeCohortPreview(cohort: Schemas.Cohort): EvidencePreview {
+export function shapeCohortPreview(
+ cohort: Schemas.Cohort,
+ cohortNames: ReadonlyMap<string, string> = new Map(),
+): EvidencePreview {
const detail =
typeof cohort.count === "number"
? count(cohort.count, "person", "people")
@@ -1545,7 +1575,7 @@ export function shapeCohortPreview(cohort: Schemas.Cohort): EvidencePreview {
],
["Created", cohort.created_at ? formatDay(cohort.created_at) : null],
]),
- ...cohortCriteriaSection(cohort.filters),
+ ...cohortCriteriaSection(cohort.filters, cohortNames),
],
};
}
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index cb6c2e5b52ff..12d346a2a5b8 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -88,6 +88,7 @@ import {
formatDay,
gridRows,
hogqlEscape,
+ referencedCohortIds,
shapeActionPreview,
shapeCohortPreview,
shapeDashboardPreview,
@@ -1202,6 +1203,7 @@ function optionalString(value: unknown): string | null {
const DRF_GENERIC_NOT_FOUND_DETAIL = "Not found.";
/** One request per targeted distinct id; flags listing more stay raw past this. */
const MAX_RESOLVED_FLAG_PEOPLE = 10;
+const MAX_RESOLVED_COHORTS = 10;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -7040,10 +7042,30 @@ export class PostHogAPIClient {
* back to a static reference. Query-backed kinds (hogql, insight) resolve
* in the UI instead, where chart shaping lives.
*/
+ /** Names of the cohorts a cohort's criteria reference, so the criteria read as prose. */
+ private async resolveCohortNames(
+ projectId: string,
+ filters: unknown,
+ ): Promise<Map<string, string>> {
+ const ids = referencedCohortIds(filters).slice(0, MAX_RESOLVED_COHORTS);
+ const entries = await Promise.all(
+ ids.map((id) =>
+ this.api
+ .get("/api/projects/{project_id}/cohorts/{id}/", {
+ path: { project_id: projectId, id: Number(id) },
+ })
+ .then((cohort) => [id, cohort.name ?? id] as const)
+ .catch(() => null),
+ ),
+ );
+ return new Map(entries.filter((entry) => entry !== null));
+ }
+
/**
* People behind the distinct ids a flag targets, keyed by distinct id. A
* lookup that fails leaves its id unresolved so the raw id still renders.
*/
+
private async resolveFlagPeople(
projectId: string,
flag: Schemas.FeatureFlag,
@@ -7392,7 +7414,10 @@ export class PostHogAPIClient {
"/api/projects/{project_id}/cohorts/{id}/",
{ path: { project_id: projectId, id: numericId } },
);
- return shapeCohortPreview(cohort);
+ return shapeCohortPreview(
+ cohort,
+ await this.resolveCohortNames(projectId, cohort.filters),
+ );
}
case "action": {
if (numericId === null) return null;
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPageView.stories.tsx b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPageView.stories.tsx
index 8e213e9ea1d4..32e9400f5ff7 100644
--- a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPageView.stories.tsx
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPageView.stories.tsx
@@ -304,6 +304,43 @@ export const Survey: Story = {
},
};
+export const Cohort: Story = {
+ args: {
+ objectKind: "cohort",
+ objectId: "142",
+ fallbackName: "Beta testers",
+ url: "https://us.posthog.com/project/2/cohorts/142",
+ occurrenceCount: 1,
+ state: "ready",
+ preview: {
+ title: "Beta testers",
+ detail: "1,204 people",
+ facts: ["Dynamic"],
+ stats: [
+ { label: "People", value: "1.2K" },
+ { label: "Type", value: "Dynamic" },
+ { label: "Last calculated", value: "Aug 16" },
+ ],
+ sections: [
+ {
+ title: "Membership criteria",
+ fields: [
+ {
+ label: "Group 1",
+ value:
+ "Is in cohort Power users and Completed checkout in the last 30 days",
+ },
+ {
+ label: "Group 2 (or)",
+ value: "Is not in cohort Churn risk and plan is pro",
+ },
+ ],
+ },
+ ],
+ },
+ },
+};
+
export const Experiment: Story = {
args: {
objectKind: "experiment",