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(loops): edit github payload conditions in the trigger editor (#77906)

Tom Piccirelloef4935f091e7
diff --git a/products/desktop/packages/api-client/src/loops.ts b/products/desktop/packages/api-client/src/loops.ts
index ed7b7bd40ee7..c3e6bb0bc71b 100644
--- a/products/desktop/packages/api-client/src/loops.ts
+++ b/products/desktop/packages/api-client/src/loops.ts
@@ -122,10 +122,19 @@ export namespace LoopSchemas {
run_at?: string;
};
+ /** One condition on the webhook body, for what the named filters below don't
+ * cover. `path` is a dot-path of object keys (`requested_team.slug`); the value
+ * there must equal one of `equals`. All conditions must match. */
+ export type LoopGithubTriggerPayloadFilter = {
+ path: string;
+ equals: string | Array<string>;
+ };
+
export type LoopGithubTriggerFilters = {
actions?: Array<string>;
branches?: Array<string>;
labels?: Array<string>;
+ payload?: Array<LoopGithubTriggerPayloadFilter>;
};
export type LoopGithubTriggerConfig = {
diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.stories.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.stories.tsx
new file mode 100644
index 000000000000..6e3a10aea128
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.stories.tsx
@@ -0,0 +1,64 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useState } from "react";
+import type { LoopTriggerDraft } from "../loopFormTypes";
+import { LoopTriggerEditor } from "./LoopTriggerEditor";
+
+function Harness({ initial }: { initial: LoopTriggerDraft[] }) {
+ const [triggers, setTriggers] = useState(initial);
+ return (
+ <div className="w-[600px] p-4">
+ <LoopTriggerEditor
+ triggers={triggers}
+ onChange={setTriggers}
+ triggerEndpointPath={null}
+ />
+ </div>
+ );
+}
+
+const meta: Meta<typeof Harness> = {
+ title: "Loops/LoopTriggerEditor",
+ component: Harness,
+};
+export default meta;
+type Story = StoryObj<typeof Harness>;
+
+const gh = (config: object): LoopTriggerDraft[] => [
+ {
+ key: "t1",
+ type: "github",
+ enabled: true,
+ config: {
+ github_integration_id: 7,
+ repository: "posthog/posthog",
+ events: ["pull_request"],
+ ...config,
+ },
+ },
+];
+
+export const ReviewRequestedFromTeam: Story = {
+ args: {
+ initial: gh({
+ filters: {
+ actions: ["review_requested"],
+ payload: [
+ {
+ path: "requested_team.slug",
+ equals: ["team-security", "team-infra"],
+ },
+ ],
+ },
+ }),
+ },
+};
+
+export const NoFiltersYet: Story = { args: { initial: gh({}) } };
+
+export const TwoEventsShareFewerActions: Story = {
+ args: { initial: gh({ events: ["pull_request", "issues"] }) },
+};
+
+export const PushHasNoActions: Story = {
+ args: { initial: gh({ events: ["push"] }) },
+};
diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx
index 9e8dbde8b20d..22ea07964012 100644
--- a/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx
+++ b/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx
@@ -11,6 +11,8 @@ import {
import type { LoopSchemas } from "@posthog/api-client/loops";
import {
Button,
+ Chip,
+ ChipClose,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
@@ -20,12 +22,15 @@ import {
EmptyHeader,
EmptyMedia,
EmptyTitle,
+ Input,
ItemContent,
ItemDescription,
ItemMedia,
ItemMenuItem,
ItemTitle,
Switch,
+ ToggleGroup,
+ ToggleGroupItem,
} from "@posthog/quill";
import { CopyButton } from "@posthog/ui/features/agent-applications/components/CopyButton";
import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";
@@ -36,7 +41,7 @@ import {
systemTimezone,
} from "@posthog/ui/primitives/timezone";
import { Box, Checkbox, Flex, Text } from "@radix-ui/themes";
-import type { ReactNode } from "react";
+import { type ReactNode, useState } from "react";
import {
compileCronSchedule,
DEFAULT_SCHEDULE_TIME,
@@ -46,8 +51,11 @@ import {
import { nextScheduleRun } from "../loopDisplay";
import {
defaultLoopTriggerOfType,
+ githubTriggerActionOptions,
isTriggerDraftValid,
type LoopTriggerDraft,
+ withGithubTriggerEvents,
+ withGithubTriggerFilters,
} from "../loopFormTypes";
import { LoopRepositoryPicker } from "./LoopRepositoryPicker";
@@ -85,6 +93,21 @@ function triggerTypeMeta(type: LoopSchemas.LoopTriggerTypeEnum) {
return TRIGGER_TYPES.find((t) => t.type === type) ?? TRIGGER_TYPES[0];
}
+/** Names whichever half of the trigger is unfinished, so the disabled save button has a
+ * reason. A blank condition row used to report the repository and events as missing. */
+function githubTriggerInvalidMessage(
+ config: LoopSchemas.LoopGithubTriggerConfig,
+): string {
+ if (
+ !config.repository ||
+ !config.github_integration_id ||
+ !config.events.length
+ ) {
+ return "Pick a repository and at least one event to finish this trigger.";
+ }
+ return "Fill in a path and a value for each payload condition, or remove the empty rows.";
+}
+
interface LoopTriggerEditorProps {
triggers: LoopTriggerDraft[];
onChange: (triggers: LoopTriggerDraft[]) => void;
@@ -219,7 +242,9 @@ function TriggerCard({
const invalidMessage = isTriggerDraftValid(trigger)
? null
: trigger.type === "github"
- ? "Pick a repository and at least one event to finish this trigger."
+ ? githubTriggerInvalidMessage(
+ trigger.config as LoopSchemas.LoopGithubTriggerConfig,
+ )
: "Set when this trigger fires.";
return (
@@ -552,6 +577,62 @@ const GITHUB_EVENT_OPTIONS: {
},
];
+/** Each accepted value is a discrete chip, committed with Enter. A single delimited text field
+ * cannot represent a value that contains the delimiter, and GitHub payload fields we can match
+ * on (a PR title, a team name) legitimately contain commas. */
+function PayloadConditionValues({
+ values,
+ disabled,
+ onChange,
+}: {
+ values: string[];
+ disabled?: boolean;
+ onChange: (values: string[]) => void;
+}) {
+ const [draft, setDraft] = useState("");
+
+ const commit = () => {
+ const value = draft.trim();
+ if (value && !values.includes(value)) {
+ onChange([...values, value]);
+ }
+ setDraft("");
+ };
+
+ return (
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1 rounded-(--radius-2) border border-border px-1.5 py-1">
+ {values.map((value) => (
+ <Chip key={value} size="sm" className="max-w-full">
+ <span className="truncate">{value}</span>
+ <ChipClose
+ disabled={disabled}
+ aria-label={`Remove ${value}`}
+ onClick={() => onChange(values.filter((v) => v !== value))}
+ />
+ </Chip>
+ ))}
+ <input
+ value={draft}
+ disabled={disabled}
+ placeholder={values.length === 0 ? "team-security" : "Add value"}
+ aria-label="Condition value"
+ className="min-w-[80px] flex-1 bg-transparent text-[13px] text-gray-12 outline-none placeholder:text-gray-9"
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={commit}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ commit();
+ }
+ if (event.key === "Backspace" && !draft && values.length > 0) {
+ onChange(values.slice(0, -1));
+ }
+ }}
+ />
+ </div>
+ );
+}
+
function GithubTriggerFields({
config,
disabled,
@@ -568,7 +649,35 @@ function GithubTriggerFields({
const events = checked
? [...config.events, event]
: config.events.filter((e) => e !== event);
- onChange({ ...config, events });
+ onChange(withGithubTriggerEvents(config, events));
+ };
+
+ const offerableActions = githubTriggerActionOptions(config.events);
+ // A trigger set up through the API can hold an action we don't model, which would otherwise
+ // render no chip: invisible, unremovable, and quietly narrowing the trigger.
+ const actionOptions = [
+ ...offerableActions,
+ ...(config.filters?.actions ?? []).filter(
+ (action) => !offerableActions.includes(action),
+ ),
+ ];
+ const conditions = config.filters?.payload ?? [];
+
+ const setConditions = (
+ next: LoopSchemas.LoopGithubTriggerPayloadFilter[],
+ ) => {
+ onChange(withGithubTriggerFilters(config, { payload: next }));
+ };
+
+ const updateCondition = (
+ index: number,
+ patch: Partial<LoopSchemas.LoopGithubTriggerPayloadFilter>,
+ ) => {
+ setConditions(
+ conditions.map((condition, i) =>
+ i === index ? { ...condition, ...patch } : condition,
+ ),
+ );
};
return (
@@ -620,6 +729,103 @@ function GithubTriggerFields({
))}
</Flex>
</SubField>
+
+ {actionOptions.length > 0 ? (
+ <SubField label="Actions">
+ <div className="flex flex-col gap-2">
+ <span className="text-[12px] text-gray-10">
+ Optional. Leave empty to run on every action.
+ </span>
+ <ToggleGroup
+ multiple
+ className="flex flex-wrap gap-1.5"
+ value={config.filters?.actions ?? []}
+ disabled={disabled}
+ onValueChange={(actions: string[]) =>
+ onChange(withGithubTriggerFilters(config, { actions }))
+ }
+ >
+ {actionOptions.map((action) => (
+ <ToggleGroupItem
+ key={action}
+ value={action}
+ size="sm"
+ variant="outline"
+ className="text-[12px] data-[pressed]:border-(--accent-9) data-[pressed]:bg-(--accent-3) data-[pressed]:text-(--accent-11)"
+ >
+ {action}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ </div>
+ </SubField>
+ ) : null}
+
+ <SubField label="Payload conditions">
+ <div className="flex flex-col gap-2">
+ <span className="text-[12px] text-gray-10">
+ Optional. Match any other field in the GitHub payload, like{" "}
+ <code>requested_team.slug</code> for the team asked to review.
+ </span>
+ {conditions.map((condition, index) => (
+ <div
+ // Keying on the path instead would remount the input on every keystroke.
+ // biome-ignore lint/suspicious/noArrayIndexKey: rows carry no id and cannot be reordered, and both inputs are controlled off the config, so the index is a correct identity
+ key={index}
+ className="flex items-center gap-2"
+ >
+ <Input
+ value={condition.path}
+ disabled={disabled}
+ placeholder="requested_team.slug"
+ // The placeholder stops naming the field as soon as someone types into it.
+ aria-label="Condition path"
+ className="h-7 flex-1"
+ onChange={(event) =>
+ updateCondition(index, { path: event.target.value })
+ }
+ />
+ <span className="text-[12px] text-gray-10">is</span>
+ <PayloadConditionValues
+ values={
+ Array.isArray(condition.equals)
+ ? condition.equals
+ : [condition.equals].filter(Boolean)
+ }
+ disabled={disabled}
+ onChange={(equals) => updateCondition(index, { equals })}
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ aria-label={
+ condition.path
+ ? `Remove condition ${condition.path}`
+ : "Remove condition"
+ }
+ onClick={() =>
+ setConditions(conditions.filter((_, i) => i !== index))
+ }
+ >
+ <Trash size={13} />
+ </Button>
+ </div>
+ ))}
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ className="self-start"
+ onClick={() =>
+ setConditions([...conditions, { path: "", equals: "" }])
+ }
+ >
+ <Plus size={13} />
+ Add condition
+ </Button>
+ </div>
+ </SubField>
</Flex>
);
}
diff --git a/products/desktop/packages/ui/src/features/loops/loopDisplay.test.ts b/products/desktop/packages/ui/src/features/loops/loopDisplay.test.ts
index 97e84a119755..b9db67269765 100644
--- a/products/desktop/packages/ui/src/features/loops/loopDisplay.test.ts
+++ b/products/desktop/packages/ui/src/features/loops/loopDisplay.test.ts
@@ -128,6 +128,34 @@ describe("describeTrigger", () => {
}),
).toBe("Schedule · */15 * * * * (UTC)");
});
+
+ it.each([
+ [undefined, "GitHub · posthog/posthog · pull_request"],
+ [
+ [{ path: "requested_team.slug", equals: "team-security" }],
+ "GitHub · posthog/posthog · pull_request · 1 payload condition",
+ ],
+ [
+ [
+ { path: "requested_team.slug", equals: "team-security" },
+ { path: "pull_request.draft", equals: "false" },
+ ],
+ "GitHub · posthog/posthog · pull_request · 2 payload conditions",
+ ],
+ // A gated trigger must not read the same as an ungated one in the detail view.
+ ])("surfaces payload conditions on a github trigger", (payload, expected) => {
+ expect(
+ describeTrigger({
+ type: "github",
+ config: {
+ github_integration_id: 7,
+ repository: "posthog/posthog",
+ events: ["pull_request"],
+ ...(payload ? { filters: { payload } } : {}),
+ },
+ }),
+ ).toBe(expected);
+ });
});
describe("summarizeNotificationDestinations", () => {
diff --git a/products/desktop/packages/ui/src/features/loops/loopDisplay.ts b/products/desktop/packages/ui/src/features/loops/loopDisplay.ts
index b9bf5730d460..e025c3718010 100644
--- a/products/desktop/packages/ui/src/features/loops/loopDisplay.ts
+++ b/products/desktop/packages/ui/src/features/loops/loopDisplay.ts
@@ -175,7 +175,12 @@ export function describeTrigger(trigger: TriggerLike): string {
}
if (trigger.type === "github") {
const config = trigger.config as LoopSchemas.LoopGithubTriggerConfig;
- return `GitHub · ${config.repository || "?"} · ${config.events.join(", ") || "no events"}`;
+ const conditions = config.filters?.payload ?? [];
+ const conditionSuffix =
+ conditions.length > 0
+ ? ` · ${conditions.length} payload condition${conditions.length === 1 ? "" : "s"}`
+ : "";
+ return `GitHub · ${config.repository || "?"} · ${config.events.join(", ") || "no events"}${conditionSuffix}`;
}
return "API · authenticated POST";
}
diff --git a/products/desktop/packages/ui/src/features/loops/loopFormTypes.test.ts b/products/desktop/packages/ui/src/features/loops/loopFormTypes.test.ts
index ff88711e7bfe..47928357a33c 100644
--- a/products/desktop/packages/ui/src/features/loops/loopFormTypes.test.ts
+++ b/products/desktop/packages/ui/src/features/loops/loopFormTypes.test.ts
@@ -5,6 +5,7 @@ import {
defaultLoopBehaviors,
emptyLoopFormValues,
formValuesToLoopWrite,
+ githubTriggerActionOptions,
isAutoFixEnabled,
isLoopFormValid,
isTriggerDraftValid,
@@ -13,6 +14,7 @@ import {
loopToFormValues,
normalizeLoopFormValues,
withAutoFix,
+ withGithubTriggerEvents,
} from "./loopFormTypes";
function scheduleTrigger(
@@ -82,6 +84,40 @@ describe("isTriggerDraftValid", () => {
trigger: githubTrigger({ events: [] }),
expected: false,
},
+ {
+ name: "github with a complete payload condition",
+ trigger: githubTrigger({
+ filters: {
+ payload: [{ path: "requested_team.slug", equals: "team-security" }],
+ },
+ }),
+ expected: true,
+ },
+ {
+ name: "github with a payload condition missing its path",
+ trigger: githubTrigger({
+ filters: { payload: [{ path: " ", equals: "team-security" }] },
+ }),
+ expected: false,
+ },
+ {
+ name: "github with a payload condition missing its value",
+ trigger: githubTrigger({
+ filters: { payload: [{ path: "requested_team.slug", equals: "" }] },
+ }),
+ expected: false,
+ },
+ {
+ // A trailing separator is what a half-typed second value looks like; drop it rather
+ // than blocking the form while someone is still writing.
+ name: "github with a blank value alongside a real one",
+ trigger: githubTrigger({
+ filters: {
+ payload: [{ path: "requested_team.slug", equals: ["a", " "] }],
+ },
+ }),
+ expected: true,
+ },
{
name: "api trigger",
trigger: {
@@ -97,6 +133,69 @@ describe("isTriggerDraftValid", () => {
});
});
+describe("githubTriggerActionOptions", () => {
+ it.each<[string, LoopSchemas.LoopGithubTriggerEventEnum[], string[]]>([
+ ["no events", [], []],
+ ["push has no actions", ["push"], []],
+ ["issue comments", ["issue_comment"], ["created", "edited", "deleted"]],
+ // One `actions` list is matched against every event on the trigger, so offering an action
+ // only some of them send would stop the others firing at all.
+ [
+ "two events share only some actions",
+ ["issues", "issue_comment"],
+ ["edited", "deleted"],
+ ],
+ ["anything paired with push", ["pull_request", "push"], []],
+ ])("%s", (_label, events, expected) => {
+ expect(githubTriggerActionOptions(events)).toEqual(expected);
+ });
+});
+
+describe("withGithubTriggerEvents", () => {
+ it("drops an action the newly selected events cannot all send", () => {
+ // Ticking a second event while `review_requested` is selected would otherwise leave a
+ // filter that no issue event can ever match, silently disabling it.
+ const config: LoopSchemas.LoopGithubTriggerConfig = {
+ github_integration_id: 7,
+ repository: "posthog/posthog",
+ events: ["pull_request"],
+ filters: { actions: ["review_requested", "closed"] },
+ };
+
+ const next = withGithubTriggerEvents(config, ["pull_request", "issues"]);
+
+ expect(next.filters?.actions).toEqual(["closed"]);
+ });
+
+ it("keeps an action it does not model", () => {
+ // `locked` is a real pull_request action GITHUB_EVENT_ACTIONS omits, so it renders no chip.
+ // Dropping it on an unrelated event toggle would silently widen the trigger to every action.
+ const config: LoopSchemas.LoopGithubTriggerConfig = {
+ github_integration_id: 7,
+ repository: "posthog/posthog",
+ events: ["pull_request"],
+ filters: { actions: ["locked"] },
+ };
+
+ const next = withGithubTriggerEvents(config, ["pull_request", "issues"]);
+
+ expect(next.filters?.actions).toEqual(["locked"]);
+ });
+
+ it("drops the filter key entirely when nothing survives", () => {
+ const config: LoopSchemas.LoopGithubTriggerConfig = {
+ github_integration_id: 7,
+ repository: "posthog/posthog",
+ events: ["pull_request"],
+ filters: { actions: ["review_requested"] },
+ };
+
+ expect(
+ withGithubTriggerEvents(config, ["push"]).filters,
+ ).not.toHaveProperty("actions");
+ });
+});
+
describe("isLoopFormValid", () => {
it("accepts a named form with instructions and no triggers", () => {
expect(isLoopFormValid({ ...validFormValues(), triggers: [] })).toBe(true);
@@ -195,6 +294,37 @@ describe("formValuesToLoopWrite", () => {
expect(formValuesToLoopWrite(validFormValues()).context_target).toBeNull();
});
+ it.each([
+ // Splitting this on the comma would widen the gate: a PR titled just "approved" would
+ // match a condition the author wrote as one exact title.
+ [
+ "a comma inside one value",
+ { path: "pull_request.title", equals: "release, approved" },
+ { path: "pull_request.title", equals: ["release, approved"] },
+ ],
+ [
+ "several values",
+ {
+ path: "requested_team.slug",
+ equals: ["team-security", " team-infra "],
+ },
+ {
+ path: "requested_team.slug",
+ equals: ["team-security", "team-infra"],
+ },
+ ],
+ ])("preserves %s in a payload condition", (_label, condition, expected) => {
+ const write = formValuesToLoopWrite({
+ ...validFormValues(),
+ triggers: [githubTrigger({ filters: { payload: [condition] } })],
+ });
+
+ expect(
+ (write.triggers?.[0].config as LoopSchemas.LoopGithubTriggerConfig)
+ .filters?.payload,
+ ).toEqual([expected]);
+ });
+
it("carries trigger ids through so the backend updates in place", () => {
const write = formValuesToLoopWrite({
...validFormValues(),
diff --git a/products/desktop/packages/ui/src/features/loops/loopFormTypes.ts b/products/desktop/packages/ui/src/features/loops/loopFormTypes.ts
index 5966eeda01b9..63adbc8c545a 100644
--- a/products/desktop/packages/ui/src/features/loops/loopFormTypes.ts
+++ b/products/desktop/packages/ui/src/features/loops/loopFormTypes.ts
@@ -69,6 +69,99 @@ export function emptyLoopApiTriggerConfig(): LoopSchemas.LoopApiTriggerConfig {
return {};
}
+/** The `action` values GitHub sends for each webhook event we subscribe to. Push carries no
+ * action at all. */
+const GITHUB_EVENT_ACTIONS: Record<
+ LoopSchemas.LoopGithubTriggerEventEnum,
+ string[]
+> = {
+ push: [],
+ pull_request: [
+ "opened",
+ "reopened",
+ "closed",
+ "synchronize",
+ "edited",
+ "ready_for_review",
+ "converted_to_draft",
+ "review_requested",
+ "review_request_removed",
+ "labeled",
+ "unlabeled",
+ "assigned",
+ "unassigned",
+ ],
+ issues: [
+ "opened",
+ "reopened",
+ "closed",
+ "edited",
+ "deleted",
+ "labeled",
+ "unlabeled",
+ "assigned",
+ "unassigned",
+ "pinned",
+ "unpinned",
+ "transferred",
+ ],
+ issue_comment: ["created", "edited", "deleted"],
+};
+
+/** Actions offerable for a set of events, which is their intersection rather than their union:
+ * one `filters.actions` list is matched against every event on the trigger, so an action only
+ * some of them can send would stop the others firing entirely. */
+export function githubTriggerActionOptions(
+ events: LoopSchemas.LoopGithubTriggerEventEnum[],
+): string[] {
+ if (events.length === 0) {
+ return [];
+ }
+ return events
+ .map((event) => GITHUB_EVENT_ACTIONS[event] ?? [])
+ .reduce((shared, actions) =>
+ shared.filter((action) => actions.includes(action)),
+ );
+}
+
+/** Every action GITHUB_EVENT_ACTIONS models. GitHub keeps adding actions, and the API accepts any
+ * string, so a trigger can hold one we don't list — we can't tell which events send it. */
+const MODELLED_GITHUB_ACTIONS = new Set(
+ Object.values(GITHUB_EVENT_ACTIONS).flat(),
+);
+
+/** Sets the trigger's events, dropping any selected action the new set can't all send. Leaving
+ * a stale action behind would silently stop the newly ticked event from ever firing.
+ *
+ * Actions we don't model are kept: dropping one would widen the trigger to every action of the
+ * event, and since the user was never shown a control for it they'd get no say in that. */
+export function withGithubTriggerEvents(
+ config: LoopSchemas.LoopGithubTriggerConfig,
+ events: LoopSchemas.LoopGithubTriggerEventEnum[],
+): LoopSchemas.LoopGithubTriggerConfig {
+ const offerable = githubTriggerActionOptions(events);
+ const actions = (config.filters?.actions ?? []).filter(
+ (action) =>
+ offerable.includes(action) || !MODELLED_GITHUB_ACTIONS.has(action),
+ );
+ return withGithubTriggerFilters({ ...config, events }, { actions });
+}
+
+/** Applies a filter patch, dropping keys that end up empty so an untouched trigger doesn't
+ * grow `{actions: [], payload: []}` noise in its stored config. */
+export function withGithubTriggerFilters(
+ config: LoopSchemas.LoopGithubTriggerConfig,
+ patch: Partial<LoopSchemas.LoopGithubTriggerFilters>,
+): LoopSchemas.LoopGithubTriggerConfig {
+ const merged = { ...config.filters, ...patch };
+ const filters = Object.fromEntries(
+ Object.entries(merged).filter(
+ ([, value]) => !Array.isArray(value) || value.length > 0,
+ ),
+ ) as LoopSchemas.LoopGithubTriggerFilters;
+ return { ...config, filters };
+}
+
export function defaultLoopNotifications(): LoopSchemas.LoopNotifications {
const off = { enabled: false, events: [], params: {} };
return { push: { ...off }, email: { ...off }, slack: { ...off } };
@@ -224,7 +317,12 @@ export function formValuesToLoopWrite(
id: trigger.id,
type: trigger.type,
enabled: trigger.enabled,
- config: trigger.config,
+ config:
+ trigger.type === "github"
+ ? withNormalizedPayloadConditions(
+ trigger.config as LoopSchemas.LoopGithubTriggerConfig,
+ )
+ : trigger.config,
})),
behaviors: values.behaviors,
notifications: values.notifications,
@@ -261,8 +359,50 @@ export function isTriggerDraftValid(trigger: LoopTriggerDraft): boolean {
return (
!!config.repository &&
config.github_integration_id > 0 &&
- config.events.length > 0
+ config.events.length > 0 &&
+ (config.filters?.payload ?? []).every(isPayloadConditionValid)
);
}
return true;
}
+
+/** Each accepted value is its own chip in the editor, never a delimited string. An earlier
+ * version split this field on commas, which both lost a value that legitimately contains one
+ * (`pull_request.title` is a matchable path) and quietly widened the gate: an exact condition
+ * of "release, approved" became two alternatives, so a PR titled just "approved" matched. */
+function payloadConditionValues(
+ condition: LoopSchemas.LoopGithubTriggerPayloadFilter,
+): string[] {
+ const values = Array.isArray(condition.equals)
+ ? condition.equals
+ : [condition.equals];
+ return values.map((value) => value.trim()).filter(Boolean);
+}
+
+function withNormalizedPayloadConditions(
+ config: LoopSchemas.LoopGithubTriggerConfig,
+): LoopSchemas.LoopGithubTriggerConfig {
+ const conditions = config.filters?.payload;
+ if (!conditions) {
+ return config;
+ }
+ return {
+ ...config,
+ filters: {
+ ...config.filters,
+ payload: conditions.map((condition) => ({
+ path: condition.path.trim(),
+ equals: payloadConditionValues(condition),
+ })),
+ },
+ };
+}
+
+// A half-filled row would submit and come back as a 400 from the trigger serializer.
+function isPayloadConditionValid(
+ condition: LoopSchemas.LoopGithubTriggerPayloadFilter,
+): boolean {
+ return (
+ !!condition.path.trim() && payloadConditionValues(condition).length > 0
+ );
+}