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): readable flag audience card and edit-in-task on the flag page (#93987)

Shy Alter8a7cc173f901
diff --git a/products/desktop/apps/web/src/web-container.ts b/products/desktop/apps/web/src/web-container.ts
index 4d4bed06a16f..e2661e8b5129 100644
--- a/products/desktop/apps/web/src/web-container.ts
+++ b/products/desktop/apps/web/src/web-container.ts
@@ -166,7 +166,7 @@ import {
} from "@posthog/core/tasks/identifiers";
import type { TaskDeletionService } from "@posthog/core/tasks/taskDeletionService";
import { tasksModule } from "@posthog/core/tasks/tasks.module";
-import { setRootContainer } from "@posthog/di/container";
+import { resolveService, setRootContainer } from "@posthog/di/container";
import { assertHostCapabilities } from "@posthog/di/hostCapabilities";
import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
import {
@@ -252,6 +252,10 @@ import {
} from "@posthog/ui/features/notifications/identifiers";
import { notificationsUiModule } from "@posthog/ui/features/notifications/notifications.module";
import { OnboardingGithubConnectClient } from "@posthog/ui/features/onboarding/githubConnectClientImpl";
+import {
+ AGENT_PROMPT_SENDER,
+ type AgentPromptSender,
+} from "@posthog/ui/features/sessions/agentPromptSender";
import { getSessionService } from "@posthog/ui/features/sessions/sessionServiceHost";
import { setupUiModule } from "@posthog/ui/features/setup/setup.module";
import { taskCreationEffects } from "@posthog/ui/features/task-detail/taskCreationEffectsImpl";
@@ -358,6 +362,7 @@ interface WebBindings {
[CLOUD_TASK_SERVICE]: CloudTaskService;
[CLOUD_TASK_AUTH]: ICloudTaskAuth;
[SESSION_SERVICE]: SessionService;
+ [AGENT_PROMPT_SENDER]: AgentPromptSender;
[SETUP_STORE]: ISetupStore;
[GITHUB_ISSUE_CLIENT]: GitHubIssueClient;
[HEDGEHOG_MODE_HOST]: HedgehogModeHost;
@@ -505,6 +510,18 @@ container
.toDynamicValue(() => getSessionService())
.inSingletonScope();
+// Shared UI resolves AGENT_PROMPT_SENDER for send-to-agent actions
+// (sendPromptToAgent, the flag edit popover); route it through SessionService
+// like the desktop renderer does.
+container
+ .bind<AgentPromptSender>(AGENT_PROMPT_SENDER)
+ .toConstantValue(async (taskId, prompt) => {
+ await resolveService<SessionService>(SESSION_SERVICE).sendPrompt(
+ taskId,
+ prompt,
+ );
+ });
+
// ── Feature flags (real posthog-js) ──
// When posthog isn't initialized (no real VITE_POSTHOG_API_KEY), isEnabled
// returns false for everything; real flags light up once a key is set.
diff --git a/products/desktop/packages/api-client/endpoint-allowlist.json b/products/desktop/packages/api-client/endpoint-allowlist.json
index 4d59e3ba28d8..f62f551eab19 100644
--- a/products/desktop/packages/api-client/endpoint-allowlist.json
+++ b/products/desktop/packages/api-client/endpoint-allowlist.json
@@ -26,6 +26,7 @@
"/api/projects/{project_id}/integrations/{id}/",
"/api/projects/{project_id}/persons/",
"/api/projects/{project_id}/persons/{id}/",
+ "/api/projects/{project_id}/persons/batch_by_distinct_ids/",
"/api/projects/{project_id}/session_recordings/{id}/",
"/api/projects/{project_id}/surveys/{id}/",
"/api/projects/{project_id}/surveys/{id}/stats/",
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 3bd34ed671bd..59751ba82906 100644
--- a/products/desktop/packages/api-client/src/evidence-previews.test.ts
+++ b/products/desktop/packages/api-client/src/evidence-previews.test.ts
@@ -303,7 +303,6 @@ describe("evidence preview shaping", () => {
title: "Configuration",
fields: expect.arrayContaining([
{ label: "Type", value: "Multivariate" },
- { label: "Release conditions", value: "1 condition" },
]),
});
});
@@ -330,15 +329,19 @@ describe("evidence preview shaping", () => {
},
} as unknown as Schemas.FeatureFlag);
- expect(preview.sections).toContainEqual({
- title: "Release conditions",
- fields: [
- {
- label: "Set 1",
- value: "plan exact pro · 25% rollout · Variant: test",
- },
- ],
- });
+ expect(preview.flagAudience?.rules).toEqual([
+ expect.objectContaining({
+ conditions: [
+ {
+ subject: "plan",
+ operator: "is",
+ values: [{ label: "pro" }],
+ },
+ ],
+ share: 25,
+ result: { kind: "variant", key: "test" },
+ }),
+ ]);
});
it("shows a disabled flag without a name as just the state", () => {
diff --git a/products/desktop/packages/api-client/src/evidence-previews.ts b/products/desktop/packages/api-client/src/evidence-previews.ts
index 6d6483bd47a2..9835af2e983d 100644
--- a/products/desktop/packages/api-client/src/evidence-previews.ts
+++ b/products/desktop/packages/api-client/src/evidence-previews.ts
@@ -7,6 +7,13 @@
// stays a thin "fetch by kind, shape result" dispatch.
import type { SignalReport } from "@posthog/shared/domain-types";
+import {
+ type FlagAudience,
+ flagReachLabel,
+ type ResolvedPerson,
+ shapeFlagAudience,
+ targetedDistinctIds,
+} from "./flag-audience";
import type { Schemas } from "./generated";
export interface EvidenceDetailField {
@@ -108,6 +115,8 @@ export interface EvidencePreview {
};
sections?: EvidenceDetailSection[];
experimentResults?: ExperimentResultsPresentation;
+ /** Who a feature flag reaches, as a readable rules table. */
+ flagAudience?: FlagAudience;
/**
* A dashboard's tiles, each resolvable to a live insight chart, so a full
* page can render the metrics themselves rather than describe them.
@@ -269,8 +278,12 @@ function surveyQuestionSummary(question: unknown): string | null {
return type ? `${prompt} (${humanizeStatus(type)})` : prompt;
}
-export function shapeFlagPreview(flag: Schemas.FeatureFlag): EvidencePreview {
+export function shapeFlagPreview(
+ flag: Schemas.FeatureFlag,
+ people: Map<string, ResolvedPerson> = new Map(),
+): EvidencePreview {
const name = flag.name?.trim();
+ const audience = shapeFlagAudience(flag, people);
const facts: string[] = [];
const filters = isRecord(flag.filters) ? flag.filters : {};
@@ -298,19 +311,12 @@ export function shapeFlagPreview(flag: Schemas.FeatureFlag): EvidencePreview {
: isMultivariate
? "Multivariate"
: "Boolean";
- const singleRollout =
- groups.length === 1 && isRecord(groups[0])
- ? groups[0].rollout_percentage
- : null;
const stats: Array<{ label: string; value: string }> = [
- ...(typeof singleRollout === "number"
- ? [{ label: "Rollout", value: `${singleRollout}%` }]
- : groups.length > 1
- ? [{ label: "Release conditions", value: String(groups.length) }]
- : []),
+ { label: "Reach", value: flagReachLabel(audience) },
...(variants > 0 ? [{ label: "Variants", value: String(variants) }] : []),
{ label: "Type", value: flagType },
];
+ const distinctIds = targetedDistinctIds(flag, true);
return {
title: flag.key,
detail: name || undefined,
@@ -319,13 +325,10 @@ export function shapeFlagPreview(flag: Schemas.FeatureFlag): EvidencePreview {
: { label: "Disabled", tone: "neutral" },
facts,
stats,
+ flagAudience: audience,
sections: [
...detailSection("Configuration", [
["Type", flagType],
- [
- "Release conditions",
- groups.length ? count(groups.length, "condition") : "All users",
- ],
[
"Evaluation runtime",
flag.evaluation_runtime === "all"
@@ -343,18 +346,23 @@ export function shapeFlagPreview(flag: Schemas.FeatureFlag): EvidencePreview {
? "Enabled"
: "Disabled",
],
+ [
+ "Used by",
+ flag.experiment_set?.length
+ ? count(flag.experiment_set.length, "experiment")
+ : null,
+ ],
[
"Last called",
flag.last_called_at ? formatDay(flag.last_called_at) : null,
],
+ [
+ distinctIds.length === 1
+ ? "Targeted distinct ID"
+ : "Targeted distinct IDs",
+ distinctIds.length > 0 ? distinctIds.join(", ") : null,
+ ],
]),
- ...detailSection(
- "Release conditions",
- groups.map((group, index) => [
- `Set ${index + 1}`,
- flagConditionSummary(group),
- ]),
- ),
],
resolvedId: String(flag.id),
};
diff --git a/products/desktop/packages/api-client/src/flag-audience.test.ts b/products/desktop/packages/api-client/src/flag-audience.test.ts
new file mode 100644
index 000000000000..610a9d3f1383
--- /dev/null
+++ b/products/desktop/packages/api-client/src/flag-audience.test.ts
@@ -0,0 +1,185 @@
+import { describe, expect, it } from "vitest";
+import { shapeFlagAudience, targetedDistinctIds } from "./flag-audience";
+import type { Schemas } from "./generated";
+
+// The shaper only reads the fields it shows; build minimal inputs and cast.
+function flagWith(filters: unknown): Schemas.FeatureFlag {
+ return {
+ id: 1,
+ key: "test-flag",
+ active: true,
+ filters,
+ } as unknown as Schemas.FeatureFlag;
+}
+
+describe("flag audience shaping", () => {
+ it("treats an explicit null aggregation as person targeting", () => {
+ const audience = shapeFlagAudience(
+ flagWith({
+ aggregation_group_type_index: 0,
+ groups: [
+ {
+ properties: [
+ {
+ type: "cohort",
+ key: "id",
+ value: 7,
+ cohort_name: "Power users",
+ },
+ ],
+ rollout_percentage: 25,
+ aggregation_group_type_index: null,
+ },
+ ],
+ }),
+ );
+
+ expect(audience.headline).toBe("On for 25% of Power users.");
+ expect(audience.rules[0].conditions[0].subject).toBe("Person");
+ });
+
+ it("reports nobody for a flag with no release conditions", () => {
+ const audience = shapeFlagAudience(flagWith({ groups: [] }));
+
+ expect(audience.rules).toEqual([]);
+ expect(audience.headline).toBe("On for nobody.");
+ });
+
+ it("marks rules after a 100% catch-all as unreachable", () => {
+ const audience = shapeFlagAudience(
+ flagWith({
+ multivariate: { variants: [{ key: "a" }, { key: "b" }] },
+ groups: [
+ { rollout_percentage: 100 },
+ {
+ properties: [{ key: "plan", operator: "exact", value: "pro" }],
+ rollout_percentage: 50,
+ variant: "b",
+ },
+ ],
+ }),
+ );
+
+ expect(audience.rules.map((rule) => rule.reachable)).toEqual([true, false]);
+ expect(audience.fallbackReachable).toBe(false);
+ // The shadowed rule must not appear in the headline.
+ expect(audience.headline).toBe("Split into 2 variants for everyone.");
+ });
+
+ it("keeps group-scope rules out of the guaranteed catch-all", () => {
+ const audience = shapeFlagAudience(
+ flagWith({
+ aggregation_group_type_index: 0,
+ groups: [{ rollout_percentage: 100 }],
+ }),
+ );
+
+ expect(audience.rules[0].isGroup).toBe(true);
+ expect(audience.fallbackReachable).toBe(true);
+ expect(audience.headline).toBe("On for every group.");
+ expect(audience.bucketing).toBe("group");
+ });
+
+ it("describes device bucketing and keeps its fallback reachable", () => {
+ const audience = shapeFlagAudience(
+ flagWith({
+ bucketing_identifier: "device_id",
+ groups: [{ rollout_percentage: 100 }],
+ }),
+ );
+
+ expect(audience.fallbackReachable).toBe(true);
+ expect(audience.headline).toBe("On for every device.");
+ expect(audience.bucketing).toBe("device");
+ });
+
+ it("surfaces the enrollment key for early access flags", () => {
+ const audience = shapeFlagAudience(
+ flagWith({
+ feature_enrollment: true,
+ groups: [{ rollout_percentage: 100 }],
+ }),
+ );
+
+ expect(audience.enrollmentKey).toBe("$feature_enrollment/test-flag");
+ });
+
+ it("surfaces the experiment holdout", () => {
+ const audience = shapeFlagAudience(
+ flagWith({
+ holdout: { id: 3, exclusion_percentage: 20 },
+ groups: [{ rollout_percentage: 100 }],
+ }),
+ );
+
+ expect(audience.holdout).toEqual({ id: "3", exclusionPercentage: 20 });
+ });
+
+ it("does not describe a fraction of a named person at partial rollout", () => {
+ const people = new Map([
+ ["u-1", { uuid: "p-1", name: "Alex", email: null }],
+ ]);
+ const audience = shapeFlagAudience(
+ flagWith({
+ groups: [
+ {
+ properties: [
+ {
+ type: "person",
+ key: "distinct_id",
+ operator: "exact",
+ value: "u-1",
+ },
+ ],
+ rollout_percentage: 25,
+ },
+ ],
+ }),
+ people,
+ );
+
+ expect(audience.headline).toBe("On for Alex.");
+ });
+
+ it("does not label excluded distinct IDs as targeted", () => {
+ const flag = flagWith({
+ groups: [
+ {
+ properties: [
+ {
+ type: "person",
+ key: "distinct_id",
+ operator: "is_not",
+ value: "bot-1",
+ },
+ ],
+ rollout_percentage: 100,
+ },
+ ],
+ });
+
+ // Person-name resolution still collects the excluded id, but the
+ // targeted-ids field must not claim the rule targets it.
+ expect(targetedDistinctIds(flag)).toEqual(["bot-1"]);
+ expect(targetedDistinctIds(flag, true)).toEqual([]);
+ });
+
+ it("renders a readable label for operators that only reach flags through the API", () => {
+ const audience = shapeFlagAudience(
+ flagWith({
+ groups: [
+ {
+ properties: [
+ { key: "app_version", operator: "semver_caret", value: "2.1.0" },
+ ],
+ rollout_percentage: 100,
+ },
+ ],
+ }),
+ );
+
+ expect(audience.rules[0].conditions[0].operator).toBe(
+ "is version in caret range",
+ );
+ });
+});
diff --git a/products/desktop/packages/api-client/src/flag-audience.ts b/products/desktop/packages/api-client/src/flag-audience.ts
new file mode 100644
index 000000000000..fae1f25e3303
--- /dev/null
+++ b/products/desktop/packages/api-client/src/flag-audience.ts
@@ -0,0 +1,439 @@
+import type { Schemas } from "./generated";
+
+/**
+ * Who a feature flag reaches, shaped for reading rather than editing: a
+ * headline, the rules as a first-match-wins list where every row ends in
+ * its result, and the variant split when the flag has one.
+ */
+export interface FlagAudience {
+ /** "On for one person." */
+ headline: string;
+ disabled: boolean;
+ rules: FlagRule[];
+ /** False when a reachable rule already matches everyone, so the "Everyone else" row is hidden. */
+ fallbackReachable: boolean;
+ variants: FlagVariant[];
+ /** What the evaluator hashes on for rollouts and variant assignment. */
+ bucketing: "person" | "device" | "group";
+ /** Person property checked before the rules for early access flags; null when off. */
+ enrollmentKey: string | null;
+ /** Experiment holdout checked before the rules; null when the flag has none. */
+ holdout: { id: string; exclusionPercentage: number } | null;
+}
+
+export interface FlagRule {
+ /** Empty when the rule matches everyone. */
+ conditions: FlagCondition[];
+ /** Rollout percentage within the matched audience. */
+ share: number;
+ result: FlagResult;
+ /** False when an earlier catch-all for the same aggregation shadows this rule. */
+ reachable: boolean;
+ /** True when the rule aggregates over groups instead of persons. */
+ isGroup: boolean;
+}
+
+export type FlagResult =
+ | { kind: "true" }
+ | { kind: "false" }
+ | { kind: "variant"; key: string }
+ | { kind: "split" }
+ | { kind: "payload" };
+
+export interface FlagCondition {
+ /** "Person", "Group", "email", "Cohort", "Flag" */
+ subject: string;
+ /** "is", "in cohort", "ends with" */
+ operator: string;
+ values: FlagValue[];
+}
+
+export interface FlagValue {
+ label: string;
+ /** Email under a resolved person, for example. */
+ secondary?: string;
+ /** The raw id behind a resolved label. */
+ raw?: string;
+ /** Set when the value is a person or cohort the card can open; absent for literals. */
+ link?: { kind: "person" | "cohort"; id: string };
+}
+
+export interface FlagVariant {
+ key: string;
+ percentage: number;
+ payload: string | null;
+}
+
+export interface ResolvedPerson {
+ uuid: string;
+ name: string;
+ email: string | null;
+}
+
+// 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> = {
+ exact: "is",
+ is_not: "is not",
+ icontains: "contains",
+ not_icontains: "does not contain",
+ icontains_multi: "contains any of",
+ not_icontains_multi: "does not contain any of",
+ between: "is between",
+ not_between: "is not between",
+ regex: "matches",
+ not_regex: "does not match",
+ starts_with: "starts with",
+ not_starts_with: "does not start with",
+ ends_with: "ends with",
+ not_ends_with: "does not end with",
+ gt: ">",
+ gte: "≥",
+ lt: "<",
+ lte: "≤",
+ is_set: "is set",
+ is_not_set: "is not set",
+ in: "in cohort",
+ not_in: "not in cohort",
+ flag_evaluates_to: "evaluates to",
+ is_date_before: "before",
+ is_date_after: "after",
+ is_date_exact: "on",
+ semver_eq: "is version",
+ semver_neq: "is not version",
+ semver_gt: "newer than",
+ semver_gte: "at least version",
+ semver_lt: "older than",
+ semver_lte: "at most version",
+ semver_tilde: "is version in tilde range",
+ semver_caret: "is version in caret range",
+ semver_wildcard: "matches version wildcard",
+ is_cleaned_path_exact: "is cleaned path",
+ min: "at least once ≥",
+ max: "at most once ≤",
+};
+
+type Property = Record<string, unknown>;
+type People = Map<string, ResolvedPerson>;
+
+function isRecord(value: unknown): value is Property {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function asString(value: unknown): string | null {
+ if (typeof value === "string") return value || null;
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
+ if (typeof value === "boolean") return String(value);
+ return null;
+}
+
+function asList(value: unknown): unknown[] {
+ if (Array.isArray(value)) return value;
+ return value === undefined || value === null ? [] : [value];
+}
+
+function isDistinctIdFilter(property: Property): boolean {
+ return property.type === "person" && property.key === "distinct_id";
+}
+
+function operatorLabel(
+ operator: unknown,
+ fallback: Schemas.PropertyOperator,
+): string {
+ const key = asString(operator);
+ return OPERATORS[(key ?? fallback) as Schemas.PropertyOperator] ?? key ?? "";
+}
+
+interface ConditionGroup {
+ properties: Property[];
+ rollout: number;
+ variant: string | null;
+ isGroup: boolean;
+ /** "person" or "group:<index>"; rules only shadow later rules of the same aggregation. */
+ aggregation: string;
+}
+
+function conditionGroups(flag: Schemas.FeatureFlag): ConditionGroup[] {
+ const filters = isRecord(flag.filters) ? flag.filters : {};
+ return asList(filters.groups)
+ .filter(isRecord)
+ .map((group) => {
+ // An explicit null means person-level aggregation; only an absent field
+ // inherits the flag-level group index.
+ const index =
+ group.aggregation_group_type_index !== undefined
+ ? group.aggregation_group_type_index
+ : filters.aggregation_group_type_index;
+ const isGroup = typeof index === "number";
+ return {
+ properties: asList(group.properties).filter(isRecord),
+ rollout:
+ typeof group.rollout_percentage === "number"
+ ? group.rollout_percentage
+ : 100,
+ variant: asString(group.variant),
+ isGroup,
+ aggregation: isGroup ? `group:${index}` : "person",
+ };
+ });
+}
+
+/**
+ * Distinct ids a flag targets, so the caller can resolve them to people.
+ * `positiveOnly` drops negative operators such as `is not`, whose ids the
+ * rule rejects rather than targets.
+ */
+export function targetedDistinctIds(
+ flag: Schemas.FeatureFlag,
+ positiveOnly = false,
+): string[] {
+ const ids = new Set<string>();
+ for (const group of conditionGroups(flag)) {
+ for (const property of group.properties) {
+ if (!isDistinctIdFilter(property)) continue;
+ const operator = property.operator;
+ if (positiveOnly && operator !== undefined && operator !== "exact") {
+ continue;
+ }
+ for (const value of asList(property.value)) {
+ const id = asString(value);
+ if (id) ids.add(id);
+ }
+ }
+ }
+ return [...ids];
+}
+
+function shapeCondition(
+ property: Property,
+ isGroup: boolean,
+ people: People,
+): FlagCondition | null {
+ if (property.type === "cohort") {
+ const id = asString(property.value) ?? "";
+ const name = asString(property.cohort_name);
+ return {
+ subject: isGroup ? "Group" : "Person",
+ operator: operatorLabel(property.operator, "in"),
+ values: [
+ {
+ label: name ?? `Cohort ${id}`,
+ raw: id,
+ link: id ? { kind: "cohort", id } : undefined,
+ },
+ ],
+ };
+ }
+ const distinctId = isDistinctIdFilter(property);
+ const values = asList(property.value).flatMap((entry): FlagValue[] => {
+ const value = asString(entry);
+ if (!value) return [];
+ const person = distinctId ? people.get(value) : undefined;
+ if (!person) return [{ label: value }];
+ return [
+ {
+ label: person.name,
+ secondary:
+ person.email && person.email !== person.name
+ ? person.email
+ : undefined,
+ raw: value,
+ link: { kind: "person", id: person.uuid },
+ },
+ ];
+ });
+ if (property.type === "flag") {
+ return {
+ subject: "Flag",
+ operator: OPERATORS.flag_evaluates_to,
+ values: [{ label: asString(property.key) ?? "" }, ...values],
+ };
+ }
+ const operator = operatorLabel(property.operator, "exact");
+ if (distinctId) return { subject: "Person", operator, values };
+ const key = asString(property.key);
+ return key ? { subject: key, operator, values } : null;
+}
+
+function describeAudience(
+ rule: FlagRule,
+ group: ConditionGroup,
+ people: People,
+ bucketing: FlagAudience["bucketing"],
+): string {
+ const share = rule.share < 100 ? `${rule.share}% of ` : "";
+ const noun = group.isGroup ? "groups" : "people";
+ if (rule.conditions.length === 0) {
+ if (share) return `${share}${noun}`;
+ // A group rule still needs a group key, and a device-bucketed rule still
+ // needs a device ID, so "everyone" would overstate who matches.
+ if (group.isGroup) return "every group";
+ return bucketing === "device" ? "every device" : "everyone";
+ }
+ const [condition] = rule.conditions;
+ const [property] = group.properties;
+ if (rule.conditions.length === 1 && group.properties.length === 1) {
+ if (isDistinctIdFilter(property) && condition.operator === "is") {
+ const count = condition.values.length;
+ if (count > 1) return `${share}${count} people`;
+ // The rollout hashes the identifier: a named person is either in or
+ // out, never a fraction, so the share stays on the rule row.
+ return people.get(condition.values[0]?.raw ?? "")?.name ?? "one person";
+ }
+ if (property.type === "cohort" && condition.operator === "in cohort") {
+ return `${share}${condition.values[0]?.label ?? "a cohort"}`;
+ }
+ }
+ const count =
+ rule.conditions.length === 1
+ ? "one condition"
+ : `${rule.conditions.length} conditions`;
+ return `${share}${noun} matching ${count}`;
+}
+
+function capitalize(text: string): string {
+ return text.charAt(0).toUpperCase() + text.slice(1);
+}
+
+type Shape = Omit<FlagAudience, "headline">;
+
+function headlineFor(
+ shape: Shape,
+ groups: ConditionGroup[],
+ people: People,
+ remoteConfig: boolean,
+): string {
+ if (shape.disabled) return "Off for everyone.";
+ // 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.";
+ }
+ const live = shape.rules.filter((rule) => rule.share > 0 && rule.reachable);
+ if (live.length === 0) return "On for nobody yet.";
+ const labels = live.map((rule) =>
+ describeAudience(
+ rule,
+ groups[shape.rules.indexOf(rule)],
+ people,
+ shape.bucketing,
+ ),
+ );
+ const who =
+ labels.length === 1
+ ? labels[0]
+ : labels.length === 2
+ ? `${labels[0]} and ${labels[1]}`
+ : `${labels.length} audiences`;
+ if (remoteConfig) return `Sends a payload to ${who}.`;
+ if (shape.variants.length > 0) {
+ return `Split into ${shape.variants.length} variants for ${who}.`;
+ }
+ return `On for ${who}.`;
+}
+
+export function shapeFlagAudience(
+ flag: Schemas.FeatureFlag,
+ people: People = new Map(),
+): FlagAudience {
+ const filters = isRecord(flag.filters) ? flag.filters : {};
+ const payloads = isRecord(filters.payloads) ? filters.payloads : {};
+ const multivariate = isRecord(filters.multivariate)
+ ? filters.multivariate
+ : {};
+ const variants = asList(multivariate.variants)
+ .filter(isRecord)
+ .flatMap((variant): FlagVariant[] => {
+ const key = asString(variant.key);
+ if (!key) return [];
+ const percentage = variant.rollout_percentage;
+ return [
+ {
+ key,
+ percentage: typeof percentage === "number" ? percentage : 0,
+ payload: asString(payloads[key]),
+ },
+ ];
+ });
+ const remoteConfig = flag.is_remote_configuration === true;
+ const groups = conditionGroups(flag);
+ const deviceBucketed = filters.bucketing_identifier === "device_id";
+ const bucketing: FlagAudience["bucketing"] = deviceBucketed
+ ? "device"
+ : groups.some((group) => group.isGroup)
+ ? "group"
+ : "person";
+ const resultFor = (variant: string | null): FlagResult => {
+ if (remoteConfig) return { kind: "payload" };
+ if (variant) return { kind: "variant", key: variant };
+ return variants.length > 0 ? { kind: "split" } : { kind: "true" };
+ };
+
+ // The evaluator checks condition sets in order and returns on the first
+ // match, so an empty set at 100% shadows every later set of the same
+ // aggregation. Mirrors the web flag page's own warning.
+ const shadowed = new Set<string>();
+ const rules = groups.map((group): FlagRule => {
+ const reachable = !shadowed.has(group.aggregation);
+ const conditions = group.properties.flatMap(
+ (property) => shapeCondition(property, group.isGroup, people) ?? [],
+ );
+ if (conditions.length === 0 && group.rollout >= 100) {
+ shadowed.add(group.aggregation);
+ }
+ return {
+ conditions,
+ share: group.rollout,
+ result: resultFor(group.variant),
+ reachable,
+ isGroup: group.isGroup,
+ };
+ });
+ // A reachable catch-all leaves nobody for the fallback. Group rules still
+ // need a group key and device-bucketed rules a device ID, so those keep it.
+ const catchAll =
+ !deviceBucketed &&
+ rules.some(
+ (rule) =>
+ rule.reachable &&
+ !rule.isGroup &&
+ rule.conditions.length === 0 &&
+ rule.share === 100,
+ );
+
+ const holdoutRecord = isRecord(filters.holdout) ? filters.holdout : null;
+ const exclusion = holdoutRecord?.exclusion_percentage;
+ const shape: Shape = {
+ disabled: flag.active === false,
+ rules,
+ fallbackReachable: !catchAll,
+ variants,
+ bucketing,
+ // Early access flags check the enrollment person property before any
+ // rule: true returns true, any other present value returns false.
+ enrollmentKey:
+ filters.feature_enrollment === true
+ ? `$feature_enrollment/${flag.key}`
+ : null,
+ holdout: holdoutRecord
+ ? {
+ id: asString(holdoutRecord.id) ?? "",
+ exclusionPercentage: Math.min(
+ Math.max(typeof exclusion === "number" ? exclusion : 0, 0),
+ 100,
+ ),
+ }
+ : null,
+ };
+ return {
+ ...shape,
+ headline: headlineFor(shape, groups, people, remoteConfig),
+ };
+}
+
+/** Short "Reach" label for the stat strip: "1 person", "25% of a cohort", "Everyone". */
+export function flagReachLabel(audience: FlagAudience): string {
+ if (audience.disabled) return "Nobody";
+ const match = audience.headline.match(/(?:for|to) (.+)\.$/);
+ return match ? capitalize(match[1]) : "Everyone";
+}
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 4422c02701bd..98949873a3fc 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -20235,6 +20235,21 @@ export namespace Endpoints {
};
responses: { 200: Schemas.PersonRecord };
};
+ /**
+ * This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.
+ */
+ export type post_Persons_batch_by_distinct_ids_create = {
+ method: "POST";
+ path: "/api/projects/{project_id}/persons/batch_by_distinct_ids/";
+ requestFormat: "json";
+ parameters: {
+ query: Partial<{ format: "csv" | "json" }>;
+ path: { project_id: string };
+
+ body: Schemas.PersonRecord;
+ };
+ responses: { 200: unknown };
+ };
export type get_Session_recordings_retrieve = {
method: "GET";
path: "/api/projects/{project_id}/session_recordings/{id}/";
@@ -20720,6 +20735,7 @@ export type EndpointByMethod = {
"/api/projects/{project_id}/hog_flows/": Endpoints.post_Hog_flows_create;
"/api/projects/{project_id}/hog_flows/{id}/run/": Endpoints.post_Hog_flows_run_create;
"/api/projects/{project_id}/hog_flows/{id}/schedules/": Endpoints.post_Hog_flows_schedules_create;
+ "/api/projects/{project_id}/persons/batch_by_distinct_ids/": Endpoints.post_Persons_batch_by_distinct_ids_create;
"/api/projects/{project_id}/tasks/": Endpoints.post_Tasks_create;
"/api/projects/{project_id}/tasks/{id}/run/": Endpoints.post_Tasks_run_create;
"/api/projects/{project_id}/tasks/{task_id}/runs/{id}/analyze/": Endpoints.post_Tasks_runs_analyze_create;
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 21fb79c1f527..cb6c2e5b52ff 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -111,6 +111,7 @@ import {
type FetchImplementation,
requestErrorStatus,
} from "./fetcher";
+import { type ResolvedPerson, targetedDistinctIds } from "./flag-audience";
import { createApiClient, type Schemas } from "./generated";
import type {
McpAgentGrantScope,
@@ -1199,6 +1200,16 @@ function optionalString(value: unknown): string | null {
// alike — never a business-specific message, so it's less actionable than the
// endpoint's own fallback plus status code.
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;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function isPropertyRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
/** Unwrap the shared fetcher's `Failed request: [<status>] <json>` into the endpoint's clean message. */
function extractRequestErrorMessage(error: unknown, fallback: string): string {
@@ -7029,6 +7040,58 @@ export class PostHogAPIClient {
* back to a static reference. Query-backed kinds (hogql, insight) resolve
* in the UI instead, where chart shaping lives.
*/
+ /**
+ * 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,
+ ): Promise<Map<string, ResolvedPerson>> {
+ const ids = targetedDistinctIds(flag).slice(0, MAX_RESOLVED_FLAG_PEOPLE);
+ if (ids.length === 0) return new Map();
+ try {
+ // One batched call instead of one request per id: the persons list
+ // endpoint hydrates an actors query per call and shares a per-user
+ // throttle with every other person preview.
+ const response = await this.api.post(
+ "/api/projects/{project_id}/persons/batch_by_distinct_ids/",
+ {
+ path: { project_id: projectId },
+ query: {},
+ // The spec mislabels the body as a full person record; the endpoint
+ // reads a distinct_ids array.
+ body: { distinct_ids: ids } as unknown as Schemas.PersonRecord,
+ },
+ );
+ const results =
+ response && typeof response === "object" && "results" in response
+ ? (response as { results: Record<string, unknown> }).results
+ : {};
+ const people = new Map<string, ResolvedPerson>();
+ for (const distinctId of ids) {
+ const person = results[distinctId];
+ if (!isRecord(person)) continue;
+ const uuid = typeof person.uuid === "string" ? person.uuid : null;
+ if (!uuid) continue;
+ const properties = isPropertyRecord(person.properties)
+ ? person.properties
+ : {};
+ const email =
+ typeof properties.email === "string" ? properties.email : null;
+ const name = typeof person.name === "string" ? person.name : null;
+ people.set(distinctId, {
+ uuid,
+ name: name || email || distinctId,
+ email,
+ });
+ }
+ return people;
+ } catch {
+ return new Map();
+ }
+ }
+
async getEvidencePreview(
kind: string,
id: string,
@@ -7054,9 +7117,10 @@ export class PostHogAPIClient {
flag = page.results.find((entry) => entry.key === id);
}
if (!flag) return null;
- // Depth: PostHog's own staleness verdict, and whether anything still
- // evaluates the flag (7-day call volume).
- const [status, volume] = await Promise.all([
+ // Depth: PostHog's own staleness verdict, whether anything still
+ // evaluates the flag (7-day call volume), and the people behind any
+ // distinct ids the flag targets directly, so the page can name them.
+ const [status, volume, people] = await Promise.all([
this.api
.get("/api/projects/{project_id}/feature_flags/{id}/status/", {
path: { project_id: projectId, id: flag.id },
@@ -7066,9 +7130,10 @@ export class PostHogAPIClient {
kind: "HogQLQuery",
query: `SELECT toDate(timestamp) AS day, count() FROM events WHERE event = '$feature_flag_called' AND properties.$feature_flag = '${hogqlEscape(flag.key)}' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY day ORDER BY day`,
}).catch(() => ({})),
+ this.resolveFlagPeople(projectId, flag),
]);
return decorateFlagPreview(
- shapeFlagPreview(flag),
+ shapeFlagPreview(flag, people),
status,
gridRows(volume),
);
diff --git a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
index 96144a8178ad..658fa9601d4b 100644
--- a/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
+++ b/products/desktop/packages/ui/src/features/editor/evidencePreview.ts
@@ -2,6 +2,7 @@ import type {
EvidenceDetailSection,
ExperimentResultsPresentation,
} from "@posthog/api-client/evidence-previews";
+import type { FlagAudience } from "@posthog/api-client/flag-audience";
import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";
import {
type ChartHeadlineStat,
@@ -51,6 +52,8 @@ export interface EvidenceCardData {
};
sections?: EvidenceDetailSection[];
experimentResults?: ExperimentResultsPresentation;
+ /** Who a feature flag reaches, as a readable rules table. */
+ flagAudience?: FlagAudience;
/** 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/EditFlagInTaskPopover.tsx b/products/desktop/packages/ui/src/features/posthog-objects/EditFlagInTaskPopover.tsx
new file mode 100644
index 000000000000..276a827c5e22
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/EditFlagInTaskPopover.tsx
@@ -0,0 +1,105 @@
+import {
+ Button,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Text,
+ Textarea,
+} from "@posthog/quill";
+import { sendPromptToAgent } from "@posthog/ui/features/sessions/sendPromptToAgent";
+import { toast } from "@posthog/ui/primitives/toast";
+import { isSendMessageSubmitKey } from "@posthog/ui/utils/sendMessageKey";
+import { useCallback, useState } from "react";
+
+/** Appended to every edit so the agent shows the outcome before it writes. */
+export const FLAG_EDIT_GUARD =
+ "First do a dry run and ask for approval before you change anything.";
+
+export function buildFlagEditPrompt(flagKey: string, request: string): string {
+ return `Edit the feature flag \`${flagKey}\`: ${request.trim()}\n\n${FLAG_EDIT_GUARD}`;
+}
+
+/**
+ * Sends a plain-language change request for a flag back into the task the
+ * flag appears in. The agent dry-runs and asks before it applies anything.
+ */
+export function EditFlagInTaskPopover({
+ taskId,
+ flagKey,
+}: {
+ taskId: string;
+ flagKey: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const [request, setRequest] = useState("");
+ const [sending, setSending] = useState(false);
+ const canSend = request.trim().length > 0 && !sending;
+
+ const send = useCallback(async () => {
+ if (!canSend) return;
+ setSending(true);
+ try {
+ const sent = await sendPromptToAgent(
+ taskId,
+ buildFlagEditPrompt(flagKey, request),
+ );
+ if (sent) {
+ setRequest("");
+ setOpen(false);
+ toast.success("Sent to the task");
+ }
+ } finally {
+ setSending(false);
+ }
+ }, [canSend, taskId, flagKey, request]);
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ render={
+ <Button
+ variant="primary"
+ size="sm"
+ data-attr="posthog-object-edit-flag-in-task"
+ />
+ }
+ >
+ Edit in task
+ </PopoverTrigger>
+ <PopoverContent align="end" sideOffset={8} className="w-[400px] p-4">
+ <Text className="block font-semibold text-[13px]">
+ Describe the change
+ </Text>
+ <Text variant="muted" className="mt-0.5 block text-xs">
+ Say who gets the flag and what they get.
+ </Text>
+ <Textarea
+ autoFocus
+ rows={3}
+ value={request}
+ onChange={(event) => setRequest(event.target.value)}
+ onKeyDown={(event) => {
+ if (isSendMessageSubmitKey(event)) {
+ event.preventDefault();
+ void send();
+ }
+ }}
+ placeholder="For example: Turn this on for the Beta testers cohort too."
+ className="mt-3 resize-none text-[13px]"
+ disabled={sending}
+ />
+ <div className="mt-3 flex justify-end">
+ <Button
+ variant="primary"
+ size="sm"
+ loading={sending}
+ disabled={!canSend}
+ onClick={() => void send()}
+ >
+ Send to task
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/FlagAudienceCard.tsx b/products/desktop/packages/ui/src/features/posthog-objects/FlagAudienceCard.tsx
new file mode 100644
index 000000000000..38e6ccefea4d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/FlagAudienceCard.tsx
@@ -0,0 +1,466 @@
+import {
+ ArrowElbowDownRightIcon,
+ ArrowSquareOutIcon,
+ FlaskIcon,
+ KeyIcon,
+ PowerIcon,
+ UserIcon,
+ UsersThreeIcon,
+} from "@phosphor-icons/react";
+import type {
+ FlagAudience,
+ FlagResult,
+ FlagRule,
+ FlagValue,
+ FlagVariant,
+} from "@posthog/api-client/flag-audience";
+import { Card, CardContent, Text } from "@posthog/quill";
+import { useEvidenceUrl } from "@posthog/ui/features/editor/components/EvidenceRefChip";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import type { ReactNode } from "react";
+
+const VARIANT_COLORS = [
+ "var(--primary)",
+ "var(--blue-9)",
+ "var(--teal-9)",
+ "var(--purple-9)",
+ "var(--amber-9)",
+ "var(--pink-9)",
+];
+
+function variantColor(variants: FlagVariant[], key: string): string {
+ const index = variants.findIndex((variant) => variant.key === key);
+ return VARIANT_COLORS[Math.max(index, 0) % VARIANT_COLORS.length];
+}
+
+const HASH_KEY: Record<FlagAudience["bucketing"], string> = {
+ person: "the distinct ID",
+ device: "the device ID",
+ group: "the group key",
+};
+
+/** Gutter, conditions, result. The connector line is centered in the gutter. */
+const COLUMNS = "grid-cols-[28px_minmax(0,1fr)_auto]";
+const CHIP =
+ "inline-flex max-w-full items-center gap-1 rounded border border-border bg-card px-1.5 text-xs leading-[18px]";
+const PILL =
+ "inline-flex h-5 items-center gap-1.5 rounded border border-border bg-card px-1.5 font-semibold text-xs";
+
+function Eyebrow({ children }: { children: ReactNode }) {
+ return (
+ <Text
+ variant="muted"
+ className="block font-semibold text-[11px] uppercase tracking-wider"
+ >
+ {children}
+ </Text>
+ );
+}
+
+function Dot({
+ color,
+ className = "size-2",
+}: {
+ color: string;
+ className?: string;
+}) {
+ return (
+ <span
+ className={`shrink-0 rounded-full ${className}`}
+ style={{ background: color }}
+ />
+ );
+}
+
+function SplitBar({
+ variants,
+ className,
+}: {
+ variants: FlagVariant[];
+ className: string;
+}) {
+ return (
+ <span className={`flex gap-px overflow-hidden rounded-full ${className}`}>
+ {variants.map((variant) => (
+ <span
+ key={variant.key}
+ className="h-full"
+ title={`${variant.key} · ${variant.percentage}%`}
+ style={{
+ width: `${variant.percentage}%`,
+ background: variantColor(variants, variant.key),
+ }}
+ />
+ ))}
+ </span>
+ );
+}
+
+function ValueChip({ value }: { value: FlagValue }) {
+ const link = value.link;
+ const evidenceUrl = useEvidenceUrl(link?.kind ?? "person", link?.id ?? "");
+ const url = link ? evidenceUrl : null;
+ const Icon = link?.kind === "cohort" ? UsersThreeIcon : UserIcon;
+ // Narrow panels clip the row, so the chip shrinks with an ellipsis and the
+ // hover title carries the full label plus the secondary value.
+ const title = [value.label, value.secondary].filter(Boolean).join(" · ");
+ const className = `${CHIP} ${link ? "font-medium" : "font-mono"}`;
+ const body = (
+ <>
+ {link && <Icon size={11} className="shrink-0 text-muted-foreground" />}
+ <span className="min-w-0 truncate">{value.label}</span>
+ {value.secondary && (
+ <span className="min-w-0 truncate font-normal text-muted-foreground">
+ {value.secondary}
+ </span>
+ )}
+ {url && (
+ <ArrowSquareOutIcon
+ size={11}
+ className="shrink-0 text-muted-foreground"
+ />
+ )}
+ </>
+ );
+ if (!url) {
+ return (
+ <span className={className} title={title}>
+ {body}
+ </span>
+ );
+ }
+ return (
+ <button
+ type="button"
+ className={`${className} cursor-pointer transition-colors hover:bg-muted`}
+ title={title}
+ onClick={() => openExternalUrl(url)}
+ >
+ {body}
+ </button>
+ );
+}
+
+function ResultPill({
+ result,
+ variants,
+}: {
+ result: FlagResult;
+ variants: FlagVariant[];
+}) {
+ if (result.kind === "split") {
+ return (
+ <span
+ className={PILL}
+ title={variants.map((v) => `${v.key} ${v.percentage}%`).join(" · ")}
+ >
+ <SplitBar variants={variants} className="h-2 w-7" />
+ {variants.length} variants
+ </span>
+ );
+ }
+ const tone = {
+ true: "font-mono text-(--green-11)",
+ false: "font-mono text-muted-foreground",
+ variant: "font-mono",
+ payload: "",
+ }[result.kind];
+ return (
+ <span className={`${PILL} ${tone}`}>
+ {result.kind === "variant" && (
+ <Dot color={variantColor(variants, result.key)} />
+ )}
+ {result.kind === "variant" ? result.key : result.kind}
+ </span>
+ );
+}
+
+/** A tiny meter next to a partial rollout, so the share is read at a glance. */
+function ShareMeter({ share }: { share: number }) {
+ return (
+ <span
+ className="inline-flex items-center gap-1.5 text-[11px] text-muted-foreground tabular-nums"
+ title={`${share}% of the people who match this rule`}
+ >
+ <span className="flex h-1.5 w-10 overflow-hidden rounded-full bg-border">
+ <span
+ className="h-full rounded-full bg-muted-foreground"
+ style={{ width: `${share}%` }}
+ />
+ </span>
+ {share}% of matches
+ </span>
+ );
+}
+
+/**
+ * One step of the evaluation flow. Steps are siblings in one list, so CSS
+ * trims the connector line at the first and last step.
+ */
+function Step({
+ marker,
+ muted,
+ result,
+ children,
+}: {
+ marker: ReactNode;
+ muted?: boolean;
+ result?: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <div
+ className={`group @container relative grid ${COLUMNS} @max-[560px]:grid-cols-[28px_minmax(0,1fr)] items-center gap-x-3 gap-y-2 px-3 py-3 ${muted ? "text-muted-foreground" : ""}`}
+ >
+ <span
+ aria-hidden
+ className="absolute top-0 bottom-0 left-[25px] w-px bg-border group-first:top-1/2 group-last:bottom-1/2"
+ />
+ <span
+ className={`relative z-10 flex size-6 items-center justify-center justify-self-center rounded-full border border-border bg-card font-semibold text-[11px] tabular-nums shadow-xs ${muted ? "border-dashed" : ""}`}
+ >
+ {marker}
+ </span>
+ <div className="flex min-w-0 flex-col gap-1.5 text-[13px]">
+ {children}
+ </div>
+ {result && (
+ <div className="@max-[560px]:col-start-2 flex items-center @max-[560px]:justify-start justify-end gap-3 whitespace-nowrap">
+ {result}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function RuleStep({
+ index,
+ rule,
+ audience,
+}: {
+ index: number;
+ rule: FlagRule;
+ audience: FlagAudience;
+}) {
+ const everyone = rule.isGroup
+ ? "Every group"
+ : audience.bucketing === "device"
+ ? "Every device"
+ : "Everyone";
+ return (
+ <Step
+ marker={index + 1}
+ muted={!rule.reachable}
+ result={
+ <>
+ {rule.share < 100 && rule.reachable && (
+ <ShareMeter share={rule.share} />
+ )}
+ <span className={rule.reachable ? "" : "opacity-50"}>
+ <ResultPill result={rule.result} variants={audience.variants} />
+ </span>
+ </>
+ }
+ >
+ {!rule.reachable && (
+ <span className="text-[11px]">
+ Never reached. An earlier rule already matches everyone.
+ </span>
+ )}
+ {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>
+ ))}
+ </Step>
+ );
+}
+
+/**
+ * Answers "who gets this flag, and what do they get?" before showing any
+ * structure: a headline, then the rules as a first-match-wins flow where
+ * every step ends in its result.
+ */
+export function FlagAudienceCard({
+ audience,
+ action,
+}: {
+ audience: FlagAudience;
+ /** Rendered beside the eyebrow; the page passes the edit-in-task control. */
+ action?: ReactNode;
+}) {
+ const { holdout, variants } = audience;
+ return (
+ <Card size="sm" className="overflow-hidden">
+ <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>
+ <div className="mt-1.5 flex items-start gap-2.5">
+ <Dot
+ color={audience.disabled ? "var(--gray-8)" : "var(--green-9)"}
+ className="mt-2 size-2.5"
+ />
+ <h2 className="font-semibold text-foreground text-xl leading-tight tracking-tight">
+ {audience.headline}
+ </h2>
+ </div>
+ </div>
+ {action && <div className="shrink-0">{action}</div>}
+ </div>
+
+ {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.
+ </div>
+ )}
+
+ <div
+ className={`border-border border-t ${audience.disabled ? "opacity-70" : ""}`}
+ >
+ <div
+ className={`grid ${COLUMNS} gap-x-3 bg-muted px-3 py-1.5 font-medium text-[11px] text-muted-foreground`}
+ >
+ <span />
+ <span>Rules, checked in order. The first match decides.</span>
+ <span>Result</span>
+ </div>
+ <div className="divide-y divide-border">
+ {audience.enrollmentKey && (
+ <Step
+ marker={<KeyIcon size={12} />}
+ result={
+ <span className="text-[11px] text-muted-foreground">
+ true → true, anything else → false
+ </span>
+ }
+ >
+ <span>
+ <span className="font-medium">Early access</span>
+ <span className="text-muted-foreground">
+ {" "}
+ checks the{" "}
+ <code className="rounded bg-muted px-1 font-mono text-[12px] text-foreground">
+ {audience.enrollmentKey}
+ </code>{" "}
+ person property first
+ </span>
+ </span>
+ </Step>
+ )}
+ {holdout && (
+ <Step
+ marker={<FlaskIcon size={12} />}
+ result={
+ <>
+ <ShareMeter share={holdout.exclusionPercentage} />
+ <span className={`${PILL} font-mono`}>
+ holdout-{holdout.id}
+ </span>
+ </>
+ }
+ >
+ <span>
+ <span className="font-medium">Holdout</span>
+ <span className="text-muted-foreground">
+ {" "}
+ for experiment {holdout.id}, decided before the rules
+ </span>
+ </span>
+ </Step>
+ )}
+ {audience.rules.map((rule, index) => (
+ <RuleStep
+ key={`${index}:${rule.conditions.map((c) => c.subject).join("|")}`}
+ index={index}
+ rule={rule}
+ audience={audience}
+ />
+ ))}
+ {audience.rules.length === 0 && (
+ <Step marker={null} muted>
+ No rules yet. Add a release condition to turn the flag on for
+ someone.
+ </Step>
+ )}
+ {audience.fallbackReachable && (
+ <Step
+ marker={<ArrowElbowDownRightIcon size={12} />}
+ muted
+ result={
+ <ResultPill result={{ kind: "false" }} variants={variants} />
+ }
+ >
+ Everyone else
+ </Step>
+ )}
+ </div>
+ </div>
+
+ {variants.length > 0 && (
+ <div className="@container border-border border-t px-5 py-5">
+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
+ <Eyebrow>Variant split</Eyebrow>
+ <Text variant="muted" className="text-xs">
+ Assigned by a stable hash of {HASH_KEY[audience.bucketing]}
+ </Text>
+ </div>
+ <SplitBar variants={variants} className="mt-2.5 h-2.5" />
+ <div className="mt-3 grid @[560px]:grid-cols-2 gap-x-6 gap-y-2">
+ {variants.map((variant) => (
+ <div
+ key={variant.key}
+ className="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-2.5 text-[13px]"
+ >
+ <Dot
+ color={variantColor(variants, variant.key)}
+ className="size-2.5"
+ />
+ <span className="flex min-w-0 items-baseline gap-2">
+ <span className="font-mono font-semibold text-xs">
+ {variant.key}
+ </span>
+ {variant.payload && (
+ <code
+ title={variant.payload}
+ className="min-w-0 truncate rounded bg-muted px-1 font-mono text-[11px] text-muted-foreground"
+ >
+ {variant.payload}
+ </code>
+ )}
+ </span>
+ <span className="font-semibold tabular-nums">
+ {variant.percentage}%
+ </span>
+ </div>
+ ))}
+ </div>
+ {holdout && (
+ <Text variant="muted" className="mt-2.5 block text-xs">
+ {holdout.exclusionPercentage}% of people receive{" "}
+ <span className="font-mono">holdout-{holdout.id}</span> instead
+ of a variant.
+ </Text>
+ )}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
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 92dd6ef4f632..410d6915b055 100644
--- a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
@@ -38,7 +38,9 @@ import {
getObjectKind,
POSTHOG_OBJECT_ICON_COLOR,
} from "@posthog/ui/utils/objectKinds";
+import { EditFlagInTaskPopover } from "./EditFlagInTaskPopover";
import { ExperimentResultsSummary } from "./ExperimentResultsSummary";
+import { FlagAudienceCard } from "./FlagAudienceCard";
import { PostHogObjectDetails } from "./PostHogObjectDetails";
const CHART_ERROR_MESSAGE =
@@ -155,7 +157,13 @@ function FactChips({ facts }: { facts: string[] }) {
);
}
-function ObjectContent({ preview }: { preview: EvidenceCardData }) {
+function ObjectContent({
+ preview,
+ taskId,
+}: {
+ preview: EvidenceCardData;
+ taskId?: string;
+}) {
// A dashboard is its metrics: render each tile's insight as a live chart
// and skip the descriptive cards, which only restate what the charts show.
if (preview.tiles && preview.tiles.length > 0) {
@@ -172,6 +180,23 @@ function ObjectContent({ preview }: { preview: EvidenceCardData }) {
);
}
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">
+ <FlagAudienceCard
+ audience={preview.flagAudience}
+ action={
+ 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 ? (
@@ -218,6 +243,8 @@ export interface PostHogObjectViewProps {
objectId: string;
/** Shown while the preview loads or when the object has no live name. */
fallbackName: string;
+ /** The task this object appears in; enables sending edits back to it. */
+ taskId?: string;
url: string | null;
/** Omitted when the page isn't backed by a run artifact (chip-opened). */
occurrenceCount?: number;
@@ -230,6 +257,7 @@ export function PostHogObjectPageView({
objectKind,
objectId,
fallbackName,
+ taskId,
url,
occurrenceCount,
state,
@@ -362,7 +390,7 @@ export function PostHogObjectPageView({
<Skeleton className="h-40 w-full rounded-lg" />
</div>
) : preview ? (
- <ObjectContent preview={preview} />
+ <ObjectContent preview={preview} taskId={taskId} />
) : (
<UnavailableObject
isError={state === "error"}
@@ -385,11 +413,13 @@ export function PostHogObjectPageView({
export function PostHogObjectPage({
metadata,
fallbackName,
+ taskId,
}: {
/** Only kind + id when opened from an inline reference chip. */
metadata: Pick<PostHogObjectArtifactMetadata, "object_kind" | "object_id"> &
Partial<Omit<PostHogObjectArtifactMetadata, "object_kind" | "object_id">>;
fallbackName: string;
+ taskId?: string;
}) {
const query = useAuthenticatedQuery(
evidencePreviewQueryKey({
@@ -404,6 +434,10 @@ export function PostHogObjectPage({
{
staleTime: EVIDENCE_PREVIEW_STALE_TIME,
refetchOnWindowFocus: false,
+ // The flag page now offers an edit action, so a cached preview can
+ // outlive the object: always refetch on remount so a read after the
+ // agent applies a change shows the new state.
+ refetchOnMount: "always",
retry: 1,
},
);
@@ -424,6 +458,7 @@ export function PostHogObjectPage({
objectKind={metadata.object_kind}
objectId={metadata.object_id}
fallbackName={fallbackName}
+ taskId={taskId}
url={url}
occurrenceCount={metadata.occurrence_count}
state={state}
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 265938edb7b3..ccca38b37eab 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
@@ -1,3 +1,4 @@
+import type { FlagAudience, FlagRule } from "@posthog/api-client/flag-audience";
import type { EvidenceCardData } from "@posthog/ui/features/editor/evidencePreview";
import { PostHogObjectPageView } from "@posthog/ui/features/posthog-objects/PostHogObjectPage";
import type { Meta, StoryObj } from "@storybook/react-vite";
@@ -12,35 +13,99 @@ const DAYS = [
"2026-08-16",
];
+const alex = {
+ label: "Alex Rivera",
+ secondary: "[email protected]",
+ raw: "4dc8564d-1f2e-4b7a-9c3d-2a1b0c9d8e7f",
+ link: { kind: "person" as const, id: "4dc8564d-1f2e-4b7a-9c3d-2a1b0c9d8e7f" },
+};
+
+const betaTesters = {
+ label: "Beta testers",
+ raw: "142",
+ link: { kind: "cohort" as const, id: "142" },
+};
+
+const rule = (overrides: Partial<FlagRule>): FlagRule => ({
+ conditions: [],
+ share: 100,
+ result: { kind: "true" },
+ reachable: true,
+ isGroup: false,
+ ...overrides,
+});
+
+const audience = (overrides: Partial<FlagAudience>): FlagAudience => ({
+ headline: "On for everyone.",
+ disabled: false,
+ rules: [],
+ fallbackReachable: true,
+ variants: [],
+ bucketing: "person",
+ enrollmentKey: null,
+ holdout: null,
+ ...overrides,
+});
+
+const multivariateAudience = audience({
+ headline: "Split into 3 variants for Alex Rivera and Pro plan users.",
+ rules: [
+ rule({
+ conditions: [{ subject: "Person", operator: "is", values: [alex] }],
+ result: { kind: "variant", key: "test" },
+ }),
+ rule({
+ conditions: [
+ { subject: "plan", operator: "is", values: [{ label: "pro" }] },
+ { subject: "Cohort", operator: "in cohort", values: [betaTesters] },
+ ],
+ share: 25,
+ result: { kind: "split" },
+ }),
+ rule({
+ conditions: [
+ {
+ subject: "email",
+ operator: "ends with",
+ values: [{ label: "@example.com" }],
+ },
+ ],
+ result: { kind: "variant", key: "control" },
+ }),
+ ],
+ variants: [
+ { key: "control", percentage: 34, payload: null },
+ { key: "test", percentage: 33, payload: '{"prompt":"soft"}' },
+ { key: "aggressive", percentage: 33, payload: '{"prompt":"hard"}' },
+ ],
+});
+
+const configuration = {
+ title: "Configuration",
+ fields: [
+ { label: "Type", value: "Multivariate" },
+ { label: "Evaluation runtime", value: "All runtimes" },
+ { label: "Experience continuity", value: "On" },
+ { label: "Last called", value: "Aug 16" },
+ {
+ label: "Targeted IDs",
+ value: "4dc8564d-1f2e-4b7a-9c3d-2a1b0c9d8e7f",
+ },
+ ],
+};
+
const flagPreview: EvidenceCardData = {
title: "pi-harness",
detail: "Cloud task harness rollout",
status: { label: "Enabled", tone: "positive" },
stats: [
- { label: "Rollout", value: "100%" },
+ { label: "Reach", value: "Alex Rivera and Pro plan users" },
{ label: "Variants", value: "3" },
{ label: "Type", value: "Multivariate" },
- { label: "Calls in 7 days", value: "1.2K" },
],
spark: { points: [24, 32, 28, 46, 51, 63, 58], labels: DAYS, render: "line" },
- sections: [
- {
- title: "Configuration",
- fields: [
- { label: "Type", value: "Multivariate" },
- { label: "Release conditions", value: "2 conditions" },
- { label: "Evaluation runtime", value: "Both client and server" },
- { label: "Last called", value: "Aug 16" },
- ],
- },
- {
- title: "Release conditions",
- fields: [
- { label: "Set 1", value: "plan is pro · 25% rollout · Variant: test" },
- { label: "Set 2", value: "75% rollout" },
- ],
- },
- ],
+ flagAudience: multivariateAudience,
+ sections: [configuration],
};
const experimentPreview: EvidenceCardData = {
@@ -178,6 +243,7 @@ export const FeatureFlag: Story = {
objectKind: "flag",
objectId: "390",
fallbackName: "pi-harness",
+ taskId: "task-1",
url: "https://us.posthog.com/project/2/feature_flags/390",
occurrenceCount: 4,
state: "ready",
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
index 4e9487bed69e..543c362548a5 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
@@ -346,6 +346,7 @@ export function ArtifactPreview({
<PostHogObjectPage
metadata={liveReferenceMetadata ?? previewData.metadata}
fallbackName={name}
+ taskId={taskId}
/>
);
}
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx
index b8bccac95b93..0bab71636cfa 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx
@@ -101,6 +101,7 @@ export function TabContentRenderer({
object_id: data.objectId,
}}
fallbackName={tab.label}
+ taskId={taskId}
/>
);
diff --git a/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts b/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts
index 5185b8329f1e..d509e8dcd7e1 100644
--- a/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts
+++ b/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts
@@ -12,6 +12,7 @@ import { CONNECTIVITY_CLIENT } from "@posthog/ui/features/connectivity/connectiv
import { FEATURE_FLAGS } from "@posthog/ui/features/feature-flags/identifiers";
import { GIT_CACHE_KEY_PROVIDER } from "@posthog/ui/features/git-interaction/gitCacheProvider";
import { SPEECH_NOTIFY_SETTINGS } from "@posthog/ui/features/notifications/identifiers";
+import { AGENT_PROMPT_SENDER } from "@posthog/ui/features/sessions/agentPromptSender";
import { UPDATES_CLIENT } from "@posthog/ui/features/updates/updatesClient";
import { DIFF_WORKER_FACTORY } from "@posthog/ui/shell/diffWorkerHost";
@@ -67,6 +68,11 @@ export const REQUIRED_HOST_CAPABILITIES: readonly HostCapabilityRequirement[] =
token: REVIEW_HOST,
description: "code-review page host wiring",
},
+ {
+ token: AGENT_PROMPT_SENDER,
+ description:
+ "send-a-prompt-to-the-agent actions (sendPromptToAgent, edit flag in task)",
+ },
{
token: DIFF_WORKER_FACTORY,
description: "diff computation worker for review/diffs",