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): show who sees a survey on the survey page (#95639)

Shy Alter2b9481e2c74a
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 59751ba82906..d9d612c27c61 100644
--- a/products/desktop/packages/api-client/src/evidence-previews.test.ts
+++ b/products/desktop/packages/api-client/src/evidence-previews.test.ts
@@ -979,6 +979,37 @@ describe("evidence preview shaping", () => {
]);
});
+ it("describes who sees a running survey from its targeting flag and display conditions", () => {
+ const preview = shapeSurveyPreview({
+ id: "srv-12",
+ name: "Checkout survey",
+ start_date: "2026-08-01T00:00:00Z",
+ targeting_flag: {
+ key: "survey-targeting-checkout",
+ filters: {
+ groups: [
+ {
+ properties: [{ key: "plan", operator: "exact", value: "pro" }],
+ rollout_percentage: 25,
+ },
+ ],
+ },
+ },
+ conditions: { url: "/checkout", urlMatchType: "icontains" },
+ } as unknown as Schemas.Survey);
+
+ expect(preview.flagAudience?.headline).toBe(
+ "Shown to 25% of people matching one condition.",
+ );
+ expect(preview.displayConditions).toEqual([
+ {
+ subject: "URL",
+ operator: "contains",
+ values: [{ label: "/checkout" }],
+ },
+ ]);
+ });
+
it("describes a survey that has not started as a draft", () => {
const preview = shapeSurveyPreview({
id: "srv-11",
@@ -987,6 +1018,7 @@ describe("evidence preview shaping", () => {
expect(preview).toMatchObject({
title: "Checkout survey",
status: { label: "Draft", tone: "neutral" },
+ flagAudience: { headline: "Not shown to anyone." },
});
});
});
diff --git a/products/desktop/packages/api-client/src/evidence-previews.ts b/products/desktop/packages/api-client/src/evidence-previews.ts
index 9835af2e983d..01c8426de30f 100644
--- a/products/desktop/packages/api-client/src/evidence-previews.ts
+++ b/products/desktop/packages/api-client/src/evidence-previews.ts
@@ -9,6 +9,7 @@
import type { SignalReport } from "@posthog/shared/domain-types";
import {
type FlagAudience,
+ type FlagCondition,
flagReachLabel,
type ResolvedPerson,
shapeFlagAudience,
@@ -117,6 +118,8 @@ export interface EvidencePreview {
experimentResults?: ExperimentResultsPresentation;
/** Who a feature flag reaches, as a readable rules table. */
flagAudience?: FlagAudience;
+ /** Conditions every check must meet before the rules apply, such as a survey's URL. */
+ displayConditions?: FlagCondition[];
/**
* A dashboard's tiles, each resolvable to a live insight chart, so a full
* page can render the metrics themselves rather than describe them.
@@ -1762,6 +1765,89 @@ export function shapeEventDefinitionPreview(
};
}
+const SURVEY_WORDING = { on: "Shown to", off: "Not shown to anyone." };
+
+const URL_MATCH_LABELS: Record<string, string> = {
+ exact: "is",
+ is_not: "is not",
+ icontains: "contains",
+ not_icontains: "does not contain",
+ regex: "matches",
+ not_regex: "does not match",
+};
+
+function surveyAudience(
+ survey: Schemas.Survey,
+ running: boolean,
+): FlagAudience {
+ const flag = isRecord(survey.targeting_flag) ? survey.targeting_flag : null;
+ const filters = isRecord(flag?.filters) ? flag.filters : null;
+ // Without a targeting flag the survey shows to everyone who meets the
+ // display conditions, which the evaluator models as one 100% rule.
+ return shapeFlagAudience(
+ {
+ key: survey.name,
+ filters: filters ?? { groups: [{ rollout_percentage: 100 }] },
+ active: running,
+ },
+ new Map(),
+ SURVEY_WORDING,
+ );
+}
+
+function surveyDisplayConditions(survey: Schemas.Survey): FlagCondition[] {
+ const conditions = isRecord(survey.conditions) ? survey.conditions : {};
+ const out: FlagCondition[] = [];
+ const url = conciseValue(conditions.url);
+ if (url) {
+ out.push({
+ subject: "URL",
+ operator: URL_MATCH_LABELS[String(conditions.urlMatchType)] ?? "contains",
+ values: [{ label: url }],
+ });
+ }
+ const selector = conciseValue(conditions.selector);
+ if (selector) {
+ out.push({
+ subject: "Element",
+ operator: "matches",
+ values: [{ label: selector }],
+ });
+ }
+ const devices = Array.isArray(conditions.deviceTypes)
+ ? conditions.deviceTypes.map(String)
+ : [];
+ if (devices.length > 0) {
+ out.push({
+ subject: "Device",
+ operator: conditions.deviceTypesMatchType === "is_not" ? "is not" : "is",
+ values: devices.map((label) => ({ label })),
+ });
+ }
+ const linkedFlag = isRecord(survey.linked_flag)
+ ? conciseValue(survey.linked_flag.key)
+ : null;
+ if (linkedFlag) {
+ out.push({
+ subject: "Flag",
+ operator: "evaluates to",
+ values: [
+ { label: linkedFlag },
+ { label: conciseValue(conditions.linkedFlagVariant) ?? "true" },
+ ],
+ });
+ }
+ const wait = conditions.seenSurveyWaitPeriodInDays;
+ if (typeof wait === "number" && wait > 0) {
+ out.push({
+ subject: "Last survey seen",
+ operator: "more than",
+ values: [{ label: `${wait} days ago` }],
+ });
+ }
+ return out;
+}
+
export function shapeSurveyPreview(survey: Schemas.Survey): EvidencePreview {
let detail: string | undefined;
let status: EvidencePreview["status"];
@@ -1781,6 +1867,8 @@ export function shapeSurveyPreview(survey: Schemas.Survey): EvidencePreview {
title: survey.name,
detail,
status,
+ flagAudience: surveyAudience(survey, status.label === "Running"),
+ displayConditions: surveyDisplayConditions(survey),
sections: [
...detailSection("Survey", [
["State", survey.archived ? "Archived" : null],
diff --git a/products/desktop/packages/api-client/src/flag-audience.ts b/products/desktop/packages/api-client/src/flag-audience.ts
index fae1f25e3303..0b809ee9e970 100644
--- a/products/desktop/packages/api-client/src/flag-audience.ts
+++ b/products/desktop/packages/api-client/src/flag-audience.ts
@@ -70,6 +70,23 @@ export interface ResolvedPerson {
email: string | null;
}
+/** A flag or anything that carries flag filters, such as a survey's targeting flag. */
+export type FlagLike = Pick<
+ Schemas.FeatureFlag,
+ "key" | "filters" | "active" | "is_remote_configuration"
+>;
+
+/** Headline verbs; a survey is "shown to" people, a flag is "on for" them. */
+export interface AudienceWording {
+ on: string;
+ off: string;
+}
+
+const FLAG_WORDING: AudienceWording = {
+ on: "On for",
+ off: "Off for everyone.",
+};
+
// Typed against the generated operator union so a new schema operator fails
// the typecheck here instead of leaking its raw token into the card.
const OPERATORS: Record<Schemas.PropertyOperator, string> = {
@@ -153,7 +170,7 @@ interface ConditionGroup {
aggregation: string;
}
-function conditionGroups(flag: Schemas.FeatureFlag): ConditionGroup[] {
+function conditionGroups(flag: FlagLike): ConditionGroup[] {
const filters = isRecord(flag.filters) ? flag.filters : {};
return asList(filters.groups)
.filter(isRecord)
@@ -184,7 +201,7 @@ function conditionGroups(flag: Schemas.FeatureFlag): ConditionGroup[] {
* rule rejects rather than targets.
*/
export function targetedDistinctIds(
- flag: Schemas.FeatureFlag,
+ flag: FlagLike,
positiveOnly = false,
): string[] {
const ids = new Set<string>();
@@ -302,15 +319,18 @@ function headlineFor(
groups: ConditionGroup[],
people: People,
remoteConfig: boolean,
+ wording: AudienceWording,
): string {
- if (shape.disabled) return "Off for everyone.";
+ if (shape.disabled) return wording.off;
// The evaluator skips the condition loop on empty groups and returns false,
// so clearing targeting turns the flag off for everybody.
if (shape.rules.length === 0) {
- return remoteConfig ? "Sends a payload to nobody." : "On for nobody.";
+ return remoteConfig
+ ? "Sends a payload to nobody."
+ : `${wording.on} nobody.`;
}
const live = shape.rules.filter((rule) => rule.share > 0 && rule.reachable);
- if (live.length === 0) return "On for nobody yet.";
+ if (live.length === 0) return `${wording.on} nobody yet.`;
const labels = live.map((rule) =>
describeAudience(
rule,
@@ -329,12 +349,13 @@ function headlineFor(
if (shape.variants.length > 0) {
return `Split into ${shape.variants.length} variants for ${who}.`;
}
- return `On for ${who}.`;
+ return `${wording.on} ${who}.`;
}
export function shapeFlagAudience(
- flag: Schemas.FeatureFlag,
+ flag: FlagLike,
people: People = new Map(),
+ wording: AudienceWording = FLAG_WORDING,
): FlagAudience {
const filters = isRecord(flag.filters) ? flag.filters : {};
const payloads = isRecord(filters.payloads) ? filters.payloads : {};
@@ -427,7 +448,7 @@ export function shapeFlagAudience(
};
return {
...shape,
- headline: headlineFor(shape, groups, people, remoteConfig),
+ headline: headlineFor(shape, groups, people, remoteConfig, wording),
};
}
diff --git a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
index 658fa9601d4b..26b7e4b7886c 100644
--- a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
@@ -2,7 +2,10 @@ import type {
EvidenceDetailSection,
ExperimentResultsPresentation,
} from "@posthog/api-client/evidence-previews";
-import type { FlagAudience } from "@posthog/api-client/flag-audience";
+import type {
+ FlagAudience,
+ FlagCondition,
+} from "@posthog/api-client/flag-audience";
import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";
import {
type ChartHeadlineStat,
@@ -54,6 +57,8 @@ export interface EvidenceCardData {
experimentResults?: ExperimentResultsPresentation;
/** Who a feature flag reaches, as a readable rules table. */
flagAudience?: FlagAudience;
+ /** Conditions every check must meet before the rules apply, such as a survey's URL. */
+ displayConditions?: FlagCondition[];
/** A dashboard's tiles, each resolvable to a live insight chart. */
tiles?: Array<{ shortId: string; name: string | null }>;
/** Canonical id when it differs from the cited one (a flag cited by key). */
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/FlagAudienceCard.tsx b/products/desktop/packages/ui/src/features/posthog-objects/FlagAudienceCard.tsx
index 38e6ccefea4d..aa9ada683d37 100644
--- a/products/desktop/packages/ui/src/features/posthog-objects/FlagAudienceCard.tsx
+++ b/products/desktop/packages/ui/src/features/posthog-objects/FlagAudienceCard.tsx
@@ -2,6 +2,7 @@ import {
ArrowElbowDownRightIcon,
ArrowSquareOutIcon,
FlaskIcon,
+ GlobeIcon,
KeyIcon,
PowerIcon,
UserIcon,
@@ -9,6 +10,7 @@ import {
} from "@phosphor-icons/react";
import type {
FlagAudience,
+ FlagCondition,
FlagResult,
FlagRule,
FlagValue,
@@ -233,6 +235,22 @@ function Step({
);
}
+function Conditions({ conditions }: { conditions: FlagCondition[] }) {
+ return conditions.map((condition, conditionIndex) => (
+ <div
+ key={`${condition.subject}:${conditionIndex}`}
+ className="flex flex-wrap items-center gap-x-1.5 gap-y-1"
+ >
+ {conditionIndex > 0 && <span className="text-muted-foreground">and</span>}
+ <span className="font-medium text-foreground">{condition.subject}</span>
+ <span className="text-muted-foreground">{condition.operator}</span>
+ {condition.values.map((value, valueIndex) => (
+ <ValueChip key={`${value.label}:${valueIndex}`} value={value} />
+ ))}
+ </div>
+ ));
+}
+
function RuleStep({
index,
rule,
@@ -270,23 +288,7 @@ function RuleStep({
{rule.conditions.length === 0 && (
<span className="font-medium">{everyone}</span>
)}
- {rule.conditions.map((condition, conditionIndex) => (
- <div
- key={`${condition.subject}:${conditionIndex}`}
- className="flex flex-wrap items-center gap-x-1.5 gap-y-1"
- >
- {conditionIndex > 0 && (
- <span className="text-muted-foreground">and</span>
- )}
- <span className="font-medium text-foreground">
- {condition.subject}
- </span>
- <span className="text-muted-foreground">{condition.operator}</span>
- {condition.values.map((value, valueIndex) => (
- <ValueChip key={`${value.label}:${valueIndex}`} value={value} />
- ))}
- </div>
- ))}
+ <Conditions conditions={rule.conditions} />
</Step>
);
}
@@ -296,11 +298,27 @@ function RuleStep({
* structure: a headline, then the rules as a first-match-wins flow where
* every step ends in its result.
*/
+export interface AudienceCardCopy {
+ title: string;
+ /** Shown when the object is off; explains what the rules below mean then. */
+ off: string;
+}
+
+const FLAG_COPY: AudienceCardCopy = {
+ title: "Who gets this",
+ off: "The flag is off. The rules below apply when the flag is turned on.",
+};
+
export function FlagAudienceCard({
audience,
+ displayConditions = [],
+ copy = FLAG_COPY,
action,
}: {
audience: FlagAudience;
+ /** Conditions every check must meet before the rules, such as a survey's URL. */
+ displayConditions?: FlagCondition[];
+ copy?: AudienceCardCopy;
/** Rendered beside the eyebrow; the page passes the edit-in-task control. */
action?: ReactNode;
}) {
@@ -310,7 +328,7 @@ export function FlagAudienceCard({
<CardContent className="p-0">
<div className="flex flex-wrap items-start justify-between gap-x-6 gap-y-3 px-5 py-4">
<div className="min-w-0 flex-1 basis-64">
- <Eyebrow>Who gets this</Eyebrow>
+ <Eyebrow>{copy.title}</Eyebrow>
<div className="mt-1.5 flex items-start gap-2.5">
<Dot
color={audience.disabled ? "var(--gray-8)" : "var(--green-9)"}
@@ -327,7 +345,7 @@ export function FlagAudienceCard({
{audience.disabled && (
<div className="flex items-center gap-2.5 border-border border-t bg-muted px-5 py-2.5 text-[12.5px] text-muted-foreground">
<PowerIcon size={14} className="shrink-0" />
- The flag is off. The rules below apply when the flag is turned on.
+ {copy.off}
</div>
)}
@@ -342,6 +360,18 @@ export function FlagAudienceCard({
<span>Result</span>
</div>
<div className="divide-y divide-border">
+ {displayConditions.length > 0 && (
+ <Step
+ marker={<GlobeIcon size={12} />}
+ result={
+ <span className="text-[11px] text-muted-foreground">
+ all must match
+ </span>
+ }
+ >
+ <Conditions conditions={displayConditions} />
+ </Step>
+ )}
{audience.enrollmentKey && (
<Step
marker={<KeyIcon size={12} />}
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
index 410d6915b055..0423ecc75e78 100644
--- a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
@@ -157,10 +157,17 @@ function FactChips({ facts }: { facts: string[] }) {
);
}
+const SURVEY_AUDIENCE_COPY = {
+ title: "Who sees this",
+ off: "The survey is not running. The rules below apply when it starts.",
+};
+
function ObjectContent({
+ objectKind,
preview,
taskId,
}: {
+ objectKind: string;
preview: EvidenceCardData;
taskId?: string;
}) {
@@ -180,26 +187,24 @@ function ObjectContent({
);
}
const stats = (preview.stats ?? []).filter((stat) => stat.value);
- // The audience card already states reach, type, and variants, so the flag
- // page skips the stat strip instead of repeating them in tiles.
- if (preview.flagAudience) {
- return (
- <div className="flex flex-col gap-3">
+ const isFlag = objectKind === "flag";
+ return (
+ <div className="flex flex-col gap-3">
+ {preview.flagAudience && (
<FlagAudienceCard
audience={preview.flagAudience}
+ displayConditions={preview.displayConditions}
+ copy={objectKind === "survey" ? SURVEY_AUDIENCE_COPY : undefined}
action={
- taskId && preview.title ? (
+ isFlag && taskId && preview.title ? (
<EditFlagInTaskPopover taskId={taskId} flagKey={preview.title} />
) : null
}
/>
- <PostHogObjectDetails preview={preview} />
- </div>
- );
- }
- return (
- <div className="flex flex-col gap-3">
- {stats.length > 0 ? (
+ )}
+ {/* The audience card already states a flag's reach, type, and
+ variants, so the flag page skips the stat strip. */}
+ {isFlag && preview.flagAudience ? null : stats.length > 0 ? (
<StatStrip stats={stats} />
) : preview.facts && preview.facts.length > 0 ? (
<FactChips facts={preview.facts} />
@@ -390,7 +395,11 @@ export function PostHogObjectPageView({
<Skeleton className="h-40 w-full rounded-lg" />
</div>
) : preview ? (
- <ObjectContent preview={preview} taskId={taskId} />
+ <ObjectContent
+ objectKind={objectKind}
+ preview={preview}
+ taskId={taskId}
+ />
) : (
<UnavailableObject
isError={state === "error"}
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 ccca38b37eab..8e213e9ea1d4 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
@@ -251,6 +251,59 @@ export const FeatureFlag: Story = {
},
};
+export const Survey: Story = {
+ args: {
+ objectKind: "survey",
+ objectId: "0198a1c2-7d3e-4f5a-9b6c-1d2e3f4a5b6c",
+ fallbackName: "Checkout survey",
+ url: "https://us.posthog.com/project/2/surveys/0198a1c2",
+ occurrenceCount: 2,
+ state: "ready",
+ preview: {
+ title: "Checkout survey",
+ detail: "Since Aug 1",
+ status: { label: "Running", tone: "positive" },
+ stats: [
+ { label: "Shown", value: "1.4K" },
+ { label: "Responses", value: "212" },
+ { label: "Response rate", value: "15%" },
+ ],
+ flagAudience: audience({
+ headline: "Shown to 25% of Beta testers.",
+ rules: [
+ rule({
+ conditions: [
+ {
+ subject: "Cohort",
+ operator: "in cohort",
+ values: [betaTesters],
+ },
+ ],
+ share: 25,
+ }),
+ ],
+ }),
+ displayConditions: [
+ {
+ subject: "URL",
+ operator: "contains",
+ values: [{ label: "/checkout" }],
+ },
+ { subject: "Device", operator: "is", values: [{ label: "Desktop" }] },
+ ],
+ sections: [
+ {
+ title: "Questions",
+ fields: [
+ { label: "Question 1", value: "How was checkout? (Rating)" },
+ { label: "Question 2", value: "What would you change? (Open)" },
+ ],
+ },
+ ],
+ },
+ },
+};
+
export const Experiment: Story = {
args: {
objectKind: "experiment",