Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(routines): trigger on task property values (#9494)

Eric Hayes21fa629c0ebf
diff --git a/apps/web/src/features/property/editors/selectors/OptionCheckBox.tsx b/apps/web/src/features/property/editors/selectors/OptionCheckBox.tsx
index 9c5baeb2ab..ae333fccf1 100644
--- a/apps/web/src/features/property/editors/selectors/OptionCheckBox.tsx
+++ b/apps/web/src/features/property/editors/selectors/OptionCheckBox.tsx
@@ -11,6 +11,8 @@ import type { Component } from 'solid-js';
export const OptionCheckBox: Component<{
checked: boolean;
multiselect?: boolean;
+ /** Keep the box's border while unchecked. */
+ visible?: boolean;
}> = (props) => {
return (
<Checkbox
@@ -19,7 +21,9 @@ export const OptionCheckBox: Component<{
class="shrink-0"
>
<Checkbox.Control
- class={`size-3.5 border-transparent bg-transparent hover:border-accent data-checked:bg-accent data-checked:border-accent ${
+ class={`size-3.5 bg-transparent hover:border-accent data-checked:bg-accent data-checked:border-accent ${
+ props.visible ? 'border-edge-muted' : 'border-transparent'
+ } ${
props.checked ? '' : 'group-hover:not-hover:border-edge-muted'
} ${props.multiselect === false ? 'rounded-full' : 'rounded-sm'}`}
/>
diff --git a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx
index 7e6e7fba7b..f18b2a6d59 100644
--- a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx
+++ b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx
@@ -3,6 +3,7 @@ import { isBotPrincipalId } from '@core/constant/macroAgent';
import { useEmail, useUserId } from '@core/context/user';
import { emailToId, useAugmentUserWithDmActivity } from '@core/user';
import { createFreshSearch } from '@core/util/freshSort';
+import { isEditableInput } from '@core/util/isEditableInput';
import { useKeyPressed } from '@core/util/useKeyPressed';
import { useSelectedFirst } from '@core/util/useSelectedFirst';
import {
@@ -42,7 +43,7 @@ import {
userToEntity,
} from './entityUtils';
import { OptionCheckBox } from './OptionCheckBox';
-import type { EntitySelectorConfig, PinnedOption } from './types';
+import type { EntitySelectorConfig } from './types';
type EntityInputProps = {
config: EntitySelectorConfig;
@@ -54,7 +55,6 @@ type EntityInputProps = {
onClose?: () => void;
/** Escape in the search; `onClose` when absent, as a popover saves on close. */
onCancel?: () => void;
- pinnedOptions?: PinnedOption[];
};
function getEntityTypePluralLabel(
@@ -119,15 +119,6 @@ export function PropertyEntitySelector(props: EntityInputProps) {
const [selectedIndex, setSelectedIndex] = createSignal(0);
const keyboardMode = useKeyPressed(100);
- // Pinned options filtered by search term
- const visiblePinnedOptions = createMemo(() => {
- const options = props.pinnedOptions ?? [];
- const term = searchTerm();
- if (!term) return options;
- return options.filter((o) => o.label.toLowerCase().includes(term));
- });
- const pinnedCount = () => visiblePinnedOptions().length;
-
let scrollContainerRef: HTMLDivElement | undefined;
// Debounce search term updates (60ms like MentionsMenu)
@@ -382,27 +373,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
}
};
- const togglePinnedOption = (option: PinnedOption) => {
- const newSelected = new Set(props.selectedOptions());
- if (newSelected.has(option.id)) {
- newSelected.delete(option.id);
- } else {
- if (!props.config.isMultiSelect) newSelected.clear();
- newSelected.add(option.id);
- }
- props.setSelectedOptions(newSelected);
-
- if (!props.config.isMultiSelect && props.onClose) {
- props.onClose();
- } else if (props.config.isMultiSelect && searchInputRef) {
- setInputValue('');
- setSearchTerm('');
- setTimeout(() => searchInputRef.focus(), 0);
- }
- };
-
- const totalCount = () =>
- pinnedCount() + sortedEntities().length + (customEmail() ? 1 : 0);
+ const totalCount = () => sortedEntities().length + (customEmail() ? 1 : 0);
// Reset selected index to top when search term or list changes
createEffect(() => {
@@ -414,15 +385,22 @@ export function PropertyEntitySelector(props: EntityInputProps) {
// Scroll the selected row into view during keyboard navigation
createEffect(() => {
const index = selectedIndex();
- const pCount = pinnedCount();
- if (!keyboardMode() || index < pCount || !scrollContainerRef) return;
+ if (!keyboardMode() || !scrollContainerRef) return;
const row = scrollContainerRef.querySelector<HTMLDivElement>(
- `[data-entity-index="${index - pCount}"]`
+ `[data-entity-index="${index}"]`
);
row?.scrollIntoView({ block: 'nearest' });
});
const handleKeyDown = (e: KeyboardEvent) => {
+ // Another field on the page keeps its own keys.
+ if (
+ e.target !== searchInputRef &&
+ e.target instanceof Element &&
+ isEditableInput(e.target)
+ )
+ return;
+
const total = totalCount();
if (total === 0) return;
@@ -435,11 +413,8 @@ export function PropertyEntitySelector(props: EntityInputProps) {
} else if (e.key === 'Enter') {
e.preventDefault();
const idx = selectedIndex();
- const pCount = pinnedCount();
- if (idx < pCount) {
- togglePinnedOption(visiblePinnedOptions()[idx]);
- } else if (idx < pCount + sortedEntities().length) {
- const entity = sortedEntities()[idx - pCount];
+ if (idx < sortedEntities().length) {
+ const entity = sortedEntities()[idx];
if (entity) toggleEntity(entity);
} else {
const entity = customEmailEntity();
@@ -493,40 +468,6 @@ export function PropertyEntitySelector(props: EntityInputProps) {
onPointerDown={keepSearchFocus}
onMouseDown={keepSearchFocus}
>
- <For each={visiblePinnedOptions()}>
- {(option, i) => {
- const isSelected = () => props.selectedOptions().has(option.id);
- const isKeyboardSelected = () => i() === selectedIndex();
-
- return (
- <div
- class="group rounded-lg w-full flex items-center justify-between gap-1.5 p-1.5 px-2 text-left text-ink font-normal cursor-default min-w-0 touch:min-h-12"
- classList={{
- 'bg-hover': isKeyboardSelected(),
- }}
- onClick={() => togglePinnedOption(option)}
- onMouseEnter={() => {
- if (!keyboardMode()) {
- setSelectedIndex(i());
- }
- }}
- >
- <Show when={props.config.isMultiSelect}>
- <div class="shrink-0">
- <OptionCheckBox checked={isSelected()} multiselect />
- </div>
- </Show>
- <div class="flex items-center gap-2 flex-1 min-w-0">
- <div class="size-4 shrink-0">{option.icon}</div>
- <span class="truncate min-w-0">{option.label}</span>
- </div>
- <Show when={!props.config.isMultiSelect && isSelected()}>
- <CheckIcon class="size-3.5 shrink-0 text-accent" />
- </Show>
- </div>
- );
- }}
- </For>
<Show when={sortedEntities().length > 0}>
<div
ref={scrollContainerRef}
@@ -540,11 +481,9 @@ export function PropertyEntitySelector(props: EntityInputProps) {
>
<For each={sortedEntities()}>
{(entity, index) => {
- const adjustedIndex = () => index() + pinnedCount();
const isSelected = () =>
props.selectedOptions().has(entity.id);
- const isKeyboardSelected = () =>
- adjustedIndex() === selectedIndex();
+ const isKeyboardSelected = () => index() === selectedIndex();
return (
<>
@@ -563,7 +502,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
}
onMouseEnter={() => {
if (!keyboardMode()) {
- setSelectedIndex(adjustedIndex());
+ setSelectedIndex(index());
}
}}
>
@@ -572,6 +511,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
<OptionCheckBox
checked={isSelected()}
multiselect
+ visible={props.config.visibleCheckboxes}
/>
</div>
</Show>
@@ -642,7 +582,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
</Show>
<Show when={customEmail()}>
{(email) => {
- const rowIndex = () => pinnedCount() + sortedEntities().length;
+ const rowIndex = () => sortedEntities().length;
const entity = () => customEmailEntity();
return (
<div
diff --git a/apps/web/src/features/property/editors/selectors/types.ts b/apps/web/src/features/property/editors/selectors/types.ts
index 435868dafd..867968bf5d 100644
--- a/apps/web/src/features/property/editors/selectors/types.ts
+++ b/apps/web/src/features/property/editors/selectors/types.ts
@@ -1,11 +1,9 @@
import type { IUser } from '@core/user';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
-import type { Accessor, JSX } from 'solid-js';
+import type { Accessor } from 'solid-js';
export type SelectableOption = { id: string; label: string };
-export type PinnedOption = { id: string; label: string; icon?: JSX.Element };
-
export type OptionSelectorConfig = {
isMultiSelect: boolean;
placeholder: string;
@@ -28,6 +26,8 @@ export type EntitySelectorConfig = {
/** When the query is a valid email that is not already in the pool,
* offer it as an "Add {email}" row (calendar guests, share sheets). */
allowCustomEmail?: boolean;
+ /** Show every row's checkbox, not only the checked one's. */
+ visibleCheckboxes?: boolean;
/** Let the list fill a sized container, such as a sheet, instead of
* capping it at the popover height. */
fillHeight?: boolean;
diff --git a/apps/web/src/features/routines/core/routine-triggers.ts b/apps/web/src/features/routines/core/routine-triggers.ts
index 20d111e90e..fa9c8bb3cc 100644
--- a/apps/web/src/features/routines/core/routine-triggers.ts
+++ b/apps/web/src/features/routines/core/routine-triggers.ts
@@ -3,6 +3,7 @@ import {
formatTimeLabel,
getDefaultTimezone,
} from '@core/util/cron';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
import { match } from 'ts-pattern';
import { z } from 'zod';
@@ -46,6 +47,14 @@ export type GithubRepositoryOptions = {
error: boolean;
};
+/** One task property a trigger watches; empty values match any change to it. */
+export const propertySelectorSchema = z.object({
+ definitionId: z.guid(),
+ /** Option ids or referenced entity ids, one of which the change must add. */
+ values: z.array(z.string()),
+});
+export type PropertySelectorDraft = z.infer<typeof propertySelectorSchema>;
+
export const routineTriggerSchema = z.discriminatedUnion('kind', [
scheduleTriggerSchema,
z.object({
@@ -78,6 +87,8 @@ export const routineTriggerSchema = z.discriminatedUnion('kind', [
github: githubSelectorSchema.optional(),
/** Only for `github`: payload tests that must all pass. */
match: z.array(payloadTestSchema).optional(),
+ /** Only for task property change events. */
+ property: propertySelectorSchema.optional(),
/** Yes/no question the event's content must answer with yes. */
condition: z.string().optional(),
}),
@@ -95,26 +106,30 @@ export const routineEventGroups = [
'GitHub',
] as const;
export type RoutineEventGroup = (typeof routineEventGroups)[number];
-type ExternalPreset = Pick<EventTriggerDraft, 'github' | 'match'>;
+type TriggerPreset = Pick<EventTriggerDraft, 'github' | 'match' | 'property'>;
function github(
events: string[],
actions: string[] = [],
match?: PayloadTestDraft[]
-): ExternalPreset {
+): TriggerPreset {
return {
github: { events, actions, repositories: [], includeBots: false },
...(match ? { match } : {}),
};
}
+function taskProperty(definitionId: string): TriggerPreset {
+ return { property: { definitionId, values: [] } };
+}
+
export const routineEvents: {
value: RoutineEventName;
label: string;
group: RoutineEventGroup;
description: string;
- /** What choosing this item fills in, for events from outside Macro. */
- preset?: ExternalPreset;
+ /** What choosing this item fills in. */
+ preset?: TriggerPreset;
}[] = [
{
value: 'channel.created',
@@ -157,20 +172,50 @@ export const routineEvents: {
value: 'task.status_changed',
label: 'Status changed',
group: 'Tasks',
- description: 'The status of a selected task changes.',
+ description:
+ 'A task’s status changes. Choose statuses like Completed to run only on those.',
},
{
value: 'task.priority_changed',
label: 'Priority changed',
group: 'Tasks',
- description: 'The priority of a selected task changes.',
+ description:
+ 'A task’s priority changes. Choose priorities like Urgent to run only on those.',
+ },
+ {
+ value: 'task.property_changed',
+ label: 'Assignees changed',
+ group: 'Tasks',
+ description: 'Someone is assigned to a task, or its assignees change.',
+ preset: taskProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES),
+ },
+ {
+ value: 'task.property_changed',
+ label: 'Due date changed',
+ group: 'Tasks',
+ description: 'A task’s due date is set, moved, or cleared.',
+ preset: taskProperty(SYSTEM_PROPERTY_IDS.DUE_DATE),
+ },
+ {
+ value: 'task.property_changed',
+ label: 'Project changed',
+ group: 'Tasks',
+ description: 'A task moves to a project, or out of one.',
+ preset: taskProperty(SYSTEM_PROPERTY_IDS.PROJECT),
+ },
+ {
+ value: 'task.property_changed',
+ label: 'Effort changed',
+ group: 'Tasks',
+ description: 'A task’s effort estimate changes.',
+ preset: taskProperty(SYSTEM_PROPERTY_IDS.EFFORT),
},
{
value: 'task.property_changed',
label: 'Any property changed',
group: 'Tasks',
description:
- 'Any property on a selected task changes, including status and priority.',
+ 'Any property on a task changes, including status and priority.',
},
{
value: 'email.message_received',
@@ -293,11 +338,98 @@ export const routineEvents: {
// Preserve saved selectors while keeping the creation menu focused on the
// supported product catalog. Editing another field must not drop old triggers.
const legacyEventLabels: Partial<Record<RoutineEventName, string>> = {
+ 'task.property_changed': 'Property changed',
'document.updated': 'Document details changed',
'channel.message_patched': 'Message edited',
'channel.message_attachment_created': 'Attachment added',
};
+/** How a trigger's panel offers the values of a task property. */
+export type TaskTriggerProperty = {
+ definitionId: string;
+ anyLabel: string;
+} & (
+ | { kind: 'options' }
+ | {
+ kind: 'entities';
+ entityType: 'USER' | 'INITIATIVE';
+ specificLabel: string;
+ placeholder: string;
+ }
+ | { kind: 'none' }
+);
+
+const TASK_TRIGGER_PROPERTIES: TaskTriggerProperty[] = [
+ {
+ definitionId: SYSTEM_PROPERTY_IDS.STATUS,
+ anyLabel: 'Any status',
+ kind: 'options',
+ },
+ {
+ definitionId: SYSTEM_PROPERTY_IDS.PRIORITY,
+ anyLabel: 'Any priority',
+ kind: 'options',
+ },
+ {
+ definitionId: SYSTEM_PROPERTY_IDS.EFFORT,
+ anyLabel: 'Any effort',
+ kind: 'options',
+ },
+ {
+ definitionId: SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ anyLabel: 'Anyone',
+ kind: 'entities',
+ entityType: 'USER',
+ specificLabel: 'Specific people',
+ placeholder: 'Search people…',
+ },
+ {
+ definitionId: SYSTEM_PROPERTY_IDS.PROJECT,
+ anyLabel: 'Any project',
+ kind: 'entities',
+ entityType: 'INITIATIVE',
+ specificLabel: 'Specific projects',
+ placeholder: 'Search projects…',
+ },
+ {
+ definitionId: SYSTEM_PROPERTY_IDS.DUE_DATE,
+ anyLabel: 'Any date',
+ kind: 'none',
+ },
+];
+
+/** The property a status or priority event reports on its own. */
+function eventPropertyId(events: readonly RoutineEventName[]) {
+ if (events.length !== 1) return undefined;
+ return match(events[0])
+ .with('task.status_changed', () => SYSTEM_PROPERTY_IDS.STATUS)
+ .with('task.priority_changed', () => SYSTEM_PROPERTY_IDS.PRIORITY)
+ .otherwise(() => undefined);
+}
+
+export function taskTriggerProperty(
+ trigger: EventTriggerDraft
+): TaskTriggerProperty | undefined {
+ const definitionId =
+ trigger.property?.definitionId ?? eventPropertyId(trigger.events);
+ return TASK_TRIGGER_PROPERTIES.find(
+ (property) => property.definitionId === definitionId
+ );
+}
+
+/** The trigger narrowed to `values`, kept off the wire when its event already says it all. */
+export function withPropertyValues(
+ trigger: EventTriggerDraft,
+ definitionId: string,
+ values: string[]
+): EventTriggerDraft {
+ const implied = eventPropertyId(trigger.events) === definitionId;
+ return {
+ ...trigger,
+ property: implied && !values.length ? undefined : { definitionId, values },
+ };
+}
+
export type EventScopeKind =
| 'TASK'
| 'DOCUMENT'
@@ -373,6 +505,18 @@ function githubTriggerLabel(selector: GithubSelectorDraft | undefined) {
return `GitHub ${selector.events.join(', ')}`;
}
+/** The menu item for one of a Macro trigger's events. */
+function routineEventItem(trigger: EventTriggerDraft, name: RoutineEventName) {
+ const property =
+ name === 'task.property_changed'
+ ? trigger.property?.definitionId
+ : undefined;
+ return routineEvents.find(
+ (item) =>
+ item.value === name && item.preset?.property?.definitionId === property
+ );
+}
+
/** What the trigger's events are, for its settings panel. */
export function eventTriggerDescription(trigger: EventTriggerDraft) {
if (trigger.events.includes('github')) {
@@ -384,9 +528,7 @@ export function eventTriggerDescription(trigger: EventTriggerDraft) {
)?.description;
}
return trigger.events
- .map(
- (name) => routineEvents.find((item) => item.value === name)?.description
- )
+ .map((name) => routineEventItem(trigger, name)?.description)
.join(' ');
}
@@ -396,7 +538,7 @@ export function eventTriggerLabel(trigger: EventTriggerDraft) {
return trigger.events
.map(
(event) =>
- routineEvents.find((item) => item.value === event)?.label ??
+ routineEventItem(trigger, event)?.label ??
legacyEventLabels[event] ??
event
)
@@ -436,6 +578,8 @@ function validateEventTrigger(
return 'Choose at least one item for this event trigger.';
if ((trigger.ids?.length ?? 0) > 100)
return 'Choose up to 100 items per event trigger.';
+ if ((trigger.property?.values.length ?? 0) > 100)
+ return 'Choose up to 100 values per event trigger.';
if ([...(trigger.condition?.trim() ?? '')].length > MAX_CONDITION_CHARS)
return `Keep the condition under ${MAX_CONDITION_CHARS} characters.`;
return (
diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts
index b5514b5cfd..3e484556dc 100644
--- a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts
+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts
@@ -1,10 +1,16 @@
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '@property/identifiers';
import { describe, expect, it } from 'vitest';
import {
eventTriggerLabel,
newScheduleTrigger,
routineEvents,
routineTriggerSchema,
+ taskTriggerProperty,
validateTriggers,
+ withPropertyValues,
} from '../core/routine-triggers';
import {
parseRoutineTriggers,
@@ -347,3 +353,77 @@ describe('GitHub triggers', () => {
).toMatch(/dots/);
});
});
+
+describe('task property selectors', () => {
+ const STATUS = SYSTEM_PROPERTY_IDS.STATUS;
+ const COMPLETED = PROPERTY_OPTION_IDS.STATUS.COMPLETED;
+
+ it('round trips a value test and keeps its event’s label', () => {
+ const config = {
+ type: 'events' as const,
+ filters: [
+ {
+ events: ['task.status_changed' as const],
+ property: { definitionId: STATUS, values: [COMPLETED] },
+ },
+ ],
+ };
+ const [trigger] = parseRoutineTriggers(config)!;
+ expect(routineTriggerSchema.safeParse(trigger).success).toBe(true);
+ expect(serializeTriggers([trigger])).toEqual(config);
+ expect(trigger.kind === 'event' && eventTriggerLabel(trigger)).toBe(
+ 'Status changed'
+ );
+ });
+
+ it('names a preset property apart from any property', () => {
+ const preset = routineEvents.find(
+ (item) => item.label === 'Assignees changed'
+ )!;
+ const base = {
+ id: 'trigger',
+ kind: 'event' as const,
+ events: [preset.value],
+ };
+ expect(eventTriggerLabel({ ...base, ...preset.preset })).toBe(
+ 'Assignees changed'
+ );
+ expect(eventTriggerLabel(base)).toBe('Any property changed');
+ expect(
+ eventTriggerLabel({
+ ...base,
+ property: {
+ definitionId: '00000002-0000-7000-8000-000000000001',
+ values: [],
+ },
+ })
+ ).toBe('Property changed');
+ });
+
+ it('keeps a status event’s wire shape until a value is chosen', () => {
+ const trigger = {
+ id: 'trigger',
+ kind: 'event' as const,
+ events: ['task.status_changed' as const],
+ };
+ const chosen = withPropertyValues(trigger, STATUS, [COMPLETED]);
+ expect(chosen.property).toEqual({
+ definitionId: STATUS,
+ values: [COMPLETED],
+ });
+ expect(withPropertyValues(chosen, STATUS, []).property).toBeUndefined();
+ expect(taskTriggerProperty(chosen)?.kind).toBe('options');
+ });
+
+ it('keeps a preset property when its values are cleared', () => {
+ const trigger = {
+ id: 'trigger',
+ kind: 'event' as const,
+ events: ['task.property_changed' as const],
+ };
+ expect(
+ withPropertyValues(trigger, SYSTEM_PROPERTY_IDS.ASSIGNEES, []).property
+ ).toEqual({ definitionId: SYSTEM_PROPERTY_IDS.ASSIGNEES, values: [] });
+ expect(taskTriggerProperty(trigger)).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
index 02ea74f647..4188849f78 100644
--- a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
@@ -65,6 +65,7 @@ function serializeFilter(trigger: EventTriggerDraft): EventFilter {
...(trigger.match?.length
? { match: trigger.match.map(serializePayloadTest) }
: {}),
+ ...(trigger.property ? { property: trigger.property } : {}),
...(condition ? { condition } : {}),
};
}
@@ -140,6 +141,12 @@ export function parseRoutineTriggers(
}
: undefined,
match: filter.match?.map(parsePayloadTest),
+ property: filter.property
+ ? {
+ definitionId: filter.property.definitionId,
+ values: filter.property.values ?? [],
+ }
+ : undefined,
condition: filter.condition ?? undefined,
}));
const draft = {
diff --git a/apps/web/src/features/routines/routine-creator.test.tsx b/apps/web/src/features/routines/routine-creator.test.tsx
index 489145034e..6af5fed660 100644
--- a/apps/web/src/features/routines/routine-creator.test.tsx
+++ b/apps/web/src/features/routines/routine-creator.test.tsx
@@ -509,6 +509,10 @@ describe('routine composer execution selection', () => {
'Task created',
'Status changed',
'Priority changed',
+ 'Assignees changed',
+ 'Due date changed',
+ 'Project changed',
+ 'Effort changed',
'Any property changed',
'New email received',
]) {
diff --git a/apps/web/src/features/routines/routine-event-property.test.tsx b/apps/web/src/features/routines/routine-event-property.test.tsx
new file mode 100644
index 0000000000..4f499bc3e3
--- /dev/null
+++ b/apps/web/src/features/routines/routine-event-property.test.tsx
@@ -0,0 +1,68 @@
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '@property/identifiers';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { RoutineEventPropertyValues } from './routine-event-property';
+
+const COMPLETED = PROPERTY_OPTION_IDS.STATUS.COMPLETED;
+const CANCELED = PROPERTY_OPTION_IDS.STATUS.CANCELED;
+
+vi.mock('@queries/properties/options', () => ({
+ usePropertyOptionsQuery: () => ({
+ isSuccess: true,
+ isError: false,
+ data: [
+ { id: COMPLETED, value: { type: 'string', value: 'Completed' } },
+ { id: CANCELED, value: { type: 'string', value: 'Canceled' } },
+ ],
+ }),
+}));
+
+function mount() {
+ const [values, setValues] = createSignal<string[]>([]);
+ render(() => (
+ <RoutineEventPropertyValues
+ property={{
+ definitionId: SYSTEM_PROPERTY_IDS.STATUS,
+ anyLabel: 'Any status',
+ kind: 'options',
+ }}
+ values={values()}
+ onChange={setValues}
+ />
+ ));
+ return values;
+}
+
+function pressed(name: string) {
+ return screen.getByRole('button', { name }).getAttribute('aria-pressed');
+}
+
+describe('RoutineEventPropertyValues', () => {
+ afterEach(cleanup);
+
+ it('starts on any value and collects the values chosen', () => {
+ const values = mount();
+ expect(pressed('Any status')).toBe('true');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Completed' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Canceled' }));
+ expect(values()).toEqual([COMPLETED, CANCELED]);
+ expect(pressed('Any status')).toBe('false');
+ expect(pressed('Completed')).toBe('true');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Completed' }));
+ expect(values()).toEqual([CANCELED]);
+ });
+
+ it('clears the choice when any value is picked again', () => {
+ const values = mount();
+ fireEvent.click(screen.getByRole('button', { name: 'Completed' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Any status' }));
+ expect(values()).toEqual([]);
+ expect(pressed('Any status')).toBe('true');
+ });
+});
diff --git a/apps/web/src/features/routines/routine-event-property.tsx b/apps/web/src/features/routines/routine-event-property.tsx
new file mode 100644
index 0000000000..82630bcb5b
--- /dev/null
+++ b/apps/web/src/features/routines/routine-event-property.tsx
@@ -0,0 +1,166 @@
+import { PropertyValueIcon } from '@property/component/propertyValue';
+import { useQuickAccessEntities } from '@property/editors/selectors/entityUtils';
+import { formatOptionValue } from '@property/utils/formatting';
+import { usePropertyOptionsQuery } from '@queries/properties/options';
+import { Button, Tabs } from '@ui';
+import { createSignal, For, Match, Show, Switch } from 'solid-js';
+import type { TaskTriggerProperty } from './core/routine-triggers';
+import { RoutineEntityPicker } from './routine-event-scope';
+
+type OptionProperty = Extract<TaskTriggerProperty, { kind: 'options' }>;
+type EntityProperty = Extract<TaskTriggerProperty, { kind: 'entities' }>;
+
+/** The property's options, without suspending the panel while they load. */
+function usePropertyOptions(definitionId: () => string | undefined) {
+ const query = usePropertyOptionsQuery(
+ () => definitionId() ?? '',
+ () => definitionId() !== undefined
+ );
+ return {
+ options: () => (query.isSuccess ? query.data : []),
+ failed: () => query.isError,
+ };
+}
+
+function OptionValues(props: {
+ property: OptionProperty;
+ values: string[];
+ onChange: (values: string[]) => void;
+}) {
+ const options = usePropertyOptions(() => props.property.definitionId);
+ const toggle = (id: string) =>
+ props.onChange(
+ props.values.includes(id)
+ ? props.values.filter((value) => value !== id)
+ : [...props.values, id]
+ );
+ return (
+ <>
+ <div class="flex flex-wrap gap-1.5">
+ <Button
+ variant="secondary"
+ size="sm"
+ aria-pressed={props.values.length === 0}
+ onClick={() => props.onChange([])}
+ >
+ {props.property.anyLabel}
+ </Button>
+ <For each={options.options()}>
+ {(option) => (
+ <Button
+ variant="secondary"
+ size="sm"
+ aria-pressed={props.values.includes(option.id)}
+ onClick={() => toggle(option.id)}
+ >
+ <PropertyValueIcon optionId={option.id} class="size-3.5" />
+ {formatOptionValue(option)}
+ </Button>
+ )}
+ </For>
+ </div>
+ <Show when={options.failed()}>
+ <p class="text-xs text-failure">These values couldn’t be loaded.</p>
+ </Show>
+ </>
+ );
+}
+
+function EntityValues(props: {
+ property: EntityProperty;
+ values: string[];
+ onChange: (values: string[]) => void;
+}) {
+ const [specific, setSpecific] = createSignal(props.values.length > 0);
+ return (
+ <>
+ <Tabs
+ aria-label="Changes to"
+ size="sm"
+ fullWidth
+ options={[
+ { value: 'any', label: props.property.anyLabel },
+ { value: 'specific', label: props.property.specificLabel },
+ ]}
+ value={specific() ? 'specific' : 'any'}
+ onChange={(value) => {
+ setSpecific(value === 'specific');
+ if (value === 'any') props.onChange([]);
+ }}
+ />
+ <Show when={specific()}>
+ <RoutineEntityPicker
+ entityType={props.property.entityType}
+ placeholder={props.property.placeholder}
+ ids={props.values}
+ onChange={props.onChange}
+ />
+ </Show>
+ </>
+ );
+}
+
+/** Which values of a task property start the routine. */
+export function RoutineEventPropertyValues(props: {
+ property: TaskTriggerProperty;
+ values: string[];
+ onChange: (values: string[]) => void;
+}) {
+ const optionProperty = () =>
+ props.property.kind === 'options' ? props.property : undefined;
+ const entityProperty = () =>
+ props.property.kind === 'entities' ? props.property : undefined;
+ return (
+ <Show when={props.property.kind !== 'none'}>
+ <div class="mb-3 grid gap-1.5">
+ <span class="text-xs font-medium">Changes to</span>
+ <Switch>
+ <Match when={optionProperty()}>
+ {(property) => (
+ <OptionValues
+ property={property()}
+ values={props.values}
+ onChange={props.onChange}
+ />
+ )}
+ </Match>
+ <Match when={entityProperty()}>
+ {(property) => (
+ <EntityValues
+ property={property()}
+ values={props.values}
+ onChange={props.onChange}
+ />
+ )}
+ </Match>
+ </Switch>
+ </div>
+ </Show>
+ );
+}
+
+/** The chosen values on a trigger's chip, such as "Completed · ". */
+export function RoutineEventValueLabel(props: {
+ property: TaskTriggerProperty;
+ values: string[];
+}) {
+ const options = usePropertyOptions(() =>
+ props.property.kind === 'options' ? props.property.definitionId : undefined
+ );
+ const entities = useQuickAccessEntities(() =>
+ props.property.kind === 'entities' ? props.property.entityType : null
+ );
+ const valueName = (id: string) => {
+ const option = options.options().find((item) => item.id === id);
+ if (option) return formatOptionValue(option);
+ return entities.items().find((item) => item.id === id)?.data.name;
+ };
+ const label = () => {
+ if (props.values.length > 2) return `${props.values.length} values`;
+ const names = props.values.map(valueName);
+ return names.every(Boolean)
+ ? names.join(' or ')
+ : `${props.values.length} selected`;
+ };
+ return <Show when={props.values.length}>{label()} · </Show>;
+}
diff --git a/apps/web/src/features/routines/routine-event-scope.tsx b/apps/web/src/features/routines/routine-event-scope.tsx
index adb20f7622..5cd0b10c62 100644
--- a/apps/web/src/features/routines/routine-event-scope.tsx
+++ b/apps/web/src/features/routines/routine-event-scope.tsx
@@ -1,6 +1,7 @@
import { useQuickAccessEntities } from '@property/editors/selectors/entityUtils';
import { PropertyEntitySelector } from '@property/editors/selectors/PropertyEntitySelector';
-import { Suspense } from 'solid-js';
+import { Tabs } from '@ui';
+import { Show, Suspense } from 'solid-js';
import { match } from 'ts-pattern';
import {
callEventScopeLabel,
@@ -40,35 +41,67 @@ export function RoutineEventScopeLabel(props: ScopeProps) {
}
/** Inline search inside the trigger panel; never opens another popover. */
+export function RoutineEntityPicker(props: {
+ entityType: ScopeProps['kind'] | 'USER' | 'INITIATIVE';
+ placeholder: string;
+ ids: string[];
+ onChange: (ids: string[]) => void;
+}) {
+ return (
+ <Suspense fallback={<p class="p-3 text-sm text-ink-muted">Loading…</p>}>
+ <div class="overflow-hidden rounded-lg border border-edge-muted">
+ <PropertyEntitySelector
+ config={{
+ isMultiSelect: true,
+ placeholder: props.placeholder,
+ specificEntityType: props.entityType,
+ visibleCheckboxes: true,
+ }}
+ selectedOptions={() => new Set(props.ids)}
+ setSelectedOptions={(ids) => props.onChange([...ids])}
+ />
+ </div>
+ </Suspense>
+ );
+}
+
export function RoutineEventScope(
props: ScopeProps & {
onChange: (ids: string[] | undefined) => void;
}
) {
- const plural = () => `${entityLabel(props.kind)}s`;
+ const singular = () => entityLabel(props.kind);
return (
- <Suspense fallback={<p class="p-3 text-sm text-ink-muted">Loading…</p>}>
- <PropertyEntitySelector
- config={{
- isMultiSelect: true,
- placeholder: `Search ${plural()}…`,
- specificEntityType: props.kind,
- }}
- selectedOptions={() => new Set(props.ids ?? ['__any__'])}
- setSelectedOptions={(ids) => {
- if (ids.has('__any__') && props.ids !== undefined) {
- props.onChange(undefined);
- } else {
- props.onChange([...ids].filter((id) => id !== '__any__'));
- }
- }}
- pinnedOptions={[
- {
- id: '__any__',
- label: `Any ${entityLabel(props.kind)} I can access`,
- },
+ <div class="grid gap-1.5">
+ <span class="text-xs font-medium">Applies to</span>
+ <Tabs
+ aria-label="Applies to"
+ size="sm"
+ fullWidth
+ options={[
+ { value: 'any', label: `Any ${singular()}` },
+ { value: 'specific', label: `Specific ${singular()}s` },
]}
+ value={props.ids === undefined ? 'any' : 'specific'}
+ onChange={(value) => props.onChange(value === 'any' ? undefined : [])}
/>
- </Suspense>
+ <Show
+ when={props.ids}
+ fallback={
+ <p class="text-xs text-ink-muted">
+ Every {singular()} you can access.
+ </p>
+ }
+ >
+ {(ids) => (
+ <RoutineEntityPicker
+ entityType={props.kind}
+ placeholder={`Search ${singular()}s…`}
+ ids={ids()}
+ onChange={props.onChange}
+ />
+ )}
+ </Show>
+ </div>
);
}
diff --git a/apps/web/src/features/routines/routine-triggers.tsx b/apps/web/src/features/routines/routine-triggers.tsx
index a7657aed51..75174aad04 100644
--- a/apps/web/src/features/routines/routine-triggers.tsx
+++ b/apps/web/src/features/routines/routine-triggers.tsx
@@ -11,9 +11,15 @@ import {
eventScopeKind,
isGlobalEvent,
type RoutineTriggerDraft,
+ taskTriggerProperty,
+ withPropertyValues,
} from './core/routine-triggers';
import { createGithubConnection } from './queries/github-link';
import { createGithubRepositoryOptions } from './queries/github-repositories';
+import {
+ RoutineEventPropertyValues,
+ RoutineEventValueLabel,
+} from './routine-event-property';
import {
RoutineEventScope,
RoutineEventScopeLabel,
@@ -78,26 +84,45 @@ export function RoutineTriggers(props: {
: undefined
}
renderEventSettings={(trigger, onChange) => (
- <Show when={trigger().github}>
- {(selector) => (
- <Show
- when={github().linked !== false}
- fallback={connect(
- 'GitHub isn’t connected, so this trigger can’t run. Connect it to turn the routine on.'
- )}
- >
- <RoutineGithubSettings
- selector={selector()}
- repositories={repositories()}
- onChange={(github) => onChange({ github })}
- />
- <RoutinePayloadTests
- tests={trigger().match ?? []}
- onChange={(match) => onChange({ match })}
+ <>
+ <Show when={taskTriggerProperty(trigger())}>
+ {(property) => (
+ <RoutineEventPropertyValues
+ property={property()}
+ values={trigger().property?.values ?? []}
+ onChange={(values) =>
+ onChange({
+ property: withPropertyValues(
+ trigger(),
+ property().definitionId,
+ values
+ ).property,
+ })
+ }
/>
- </Show>
- )}
- </Show>
+ )}
+ </Show>
+ <Show when={trigger().github}>
+ {(selector) => (
+ <Show
+ when={github().linked !== false}
+ fallback={connect(
+ 'GitHub isn’t connected, so this trigger can’t run. Connect it to turn the routine on.'
+ )}
+ >
+ <RoutineGithubSettings
+ selector={selector()}
+ repositories={repositories()}
+ onChange={(github) => onChange({ github })}
+ />
+ <RoutinePayloadTests
+ tests={trigger().match ?? []}
+ onChange={(match) => onChange({ match })}
+ />
+ </Show>
+ )}
+ </Show>
+ </>
)}
renderEventLabel={(trigger) => (
<Show
@@ -106,6 +131,14 @@ export function RoutineTriggers(props: {
>
{(kind) => (
<Suspense fallback={<span>Selected items</span>}>
+ <Show when={taskTriggerProperty(trigger())}>
+ {(property) => (
+ <RoutineEventValueLabel
+ property={property()}
+ values={trigger().property?.values ?? []}
+ />
+ )}
+ </Show>
<RoutineEventScopeLabel
kind={kind()}
ids={trigger().ids}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts
index 5c635cd4a9..d735b010af 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts
@@ -9,6 +9,7 @@ import type { EventFilterCondition } from './eventFilterCondition';
import type { EventFilterGithub } from './eventFilterGithub';
import type { EventFilterIds } from './eventFilterIds';
import type { EventFilterMatch } from './eventFilterMatch';
+import type { EventFilterProperty } from './eventFilterProperty';
import type { EventName } from './eventName';
/**
@@ -32,4 +33,5 @@ invoice?". The routine runs only when the answer is yes.
ids?: EventFilterIds;
/** Exact tests on the payload, all of which must pass. */
match?: EventFilterMatch;
+ property?: EventFilterProperty;
}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterProperty.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterProperty.ts
new file mode 100644
index 0000000000..3673901339
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterProperty.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PropertySelector } from './propertySelector';
+
+export type EventFilterProperty = null | PropertySelector;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
index cdbe048b77..2de86d8b7a 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
@@ -41,6 +41,7 @@ export * from './eventFilterCondition';
export * from './eventFilterGithub';
export * from './eventFilterIds';
export * from './eventFilterMatch';
+export * from './eventFilterProperty';
export * from './eventFilters';
export * from './eventName';
export * from './executionResource';
@@ -62,6 +63,7 @@ export * from './payloadConditionGlob';
export * from './payloadConditionIn';
export * from './payloadConditionNotIn';
export * from './payloadScalar';
+export * from './propertySelector';
export * from './routineModelId';
export * from './routineTemplate';
export * from './routineTemplateTask';
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/propertySelector.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/propertySelector.ts
new file mode 100644
index 0000000000..e2828b4574
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/propertySelector.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Narrows a task property change filter to one property and, optionally, the
+values it must gain.
+ */
+export interface PropertySelector {
+ /** The property definition that must have changed. */
+ definitionId: string;
+ /** Select option ids or referenced entity ids, one of which the change must
+add. Any change to the property matches when empty. */
+ values?: string[];
+}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
index b163c439be..b04a46fa95 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
@@ -1194,6 +1194,17 @@
"$ref": "#/components/schemas/PayloadCondition"
},
"description": "Exact tests on the payload, all of which must pass."
+ },
+ "property": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/PropertySelector",
+ "description": "The task property that must have changed, and the values it must gain."
+ }
+ ]
}
}
},
@@ -1417,6 +1428,25 @@
],
"description": "A JSON text, number, boolean or null that payload values are compared with."
},
+ "PropertySelector": {
+ "type": "object",
+ "description": "Narrows a task property change filter to one property and, optionally, the\nvalues it must gain.",
+ "required": ["definitionId"],
+ "properties": {
+ "definitionId": {
+ "type": "string",
+ "description": "The property definition that must have changed."
+ },
+ "values": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Select option ids or referenced entity ids, one of which the change must\nadd. Any change to the property matches when empty."
+ }
+ },
+ "additionalProperties": false
+ },
"RoutineModelId": {
"type": "string",
"description": "A nonblank model identifier. Runtime catalogs, not the scheduler, own availability."
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index 7a72852545..3eee715048 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -473,13 +473,14 @@
"ActionTrigger": "# Type Alias: ActionTrigger\n\n> **ActionTrigger** = \\{ `schedule`: `Schedule`; `timezone`: `string`; `type`: `\"cron\"`; \\} \\| \\{ `filters`: `EventFilters`; `type`: `\"events\"`; \\} \\| \\{ `triggers`: `RoutineTriggers`; `type`: `\"multiple\"`; \\}\n\nA routine may run on one trigger or any of several schedules and Macro events.",
"scheduled-action.AgentMcpServer": "# Type Alias: AgentMcpServer\n\n> **AgentMcpServer** = \\{ `app_slug`: `string`; `server_name`: `string`; \\}\n\nOne Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-app_slug\"></a> `app_slug` | `string` | Pipedream app slug, e.g. `linear`. |\n| <a id=\"property-server_name\"></a> `server_name` | `string` | Display name, e.g. `Linear`. |",
"AgentTaskAgent": "# Type Alias: AgentTaskAgent\n\n> **AgentTaskAgent** = \\{ `bot_id`: `string`; \\}\n\nA persona selection, independent of its runtime and current default model.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-bot_id\"></a> `bot_id` | `string` |",
- "EventFilter": "# Type Alias: EventFilter\n\n> **EventFilter** = \\{ `condition?`: `string` \\| `null`; `events`: `EventName`[]; `github?`: `null` \\| `GithubSelector`; `ids?`: `string`[] \\| `null`; `match?`: `PayloadCondition`[] \\| `null`; \\}\n\nAn event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.\n\n`github` comes from outside Macro and carries its payload: it stands\nalone in its filter, takes no ids, and may require\nexact payload values with `match`. A `github` filter narrows deliveries\nwith its `github` selector.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-condition\"></a> `condition?` | `string` \\| `null` | Yes/no question about the triggering content, e.g. \"Is this email an invoice?\". The routine runs only when the answer is yes. |\n| <a id=\"property-events\"></a> `events` | `EventName`[] | - |\n| <a id=\"property-github\"></a> `github?` | `null` \\| `GithubSelector` | - |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] \\| `null` | - |\n| <a id=\"property-match\"></a> `match?` | `PayloadCondition`[] \\| `null` | Exact tests on the payload, all of which must pass. |",
+ "EventFilter": "# Type Alias: EventFilter\n\n> **EventFilter** = \\{ `condition?`: `string` \\| `null`; `events`: `EventName`[]; `github?`: `null` \\| `GithubSelector`; `ids?`: `string`[] \\| `null`; `match?`: `PayloadCondition`[] \\| `null`; `property?`: `null` \\| `PropertySelector`; \\}\n\nAn event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.\n\n`github` comes from outside Macro and carries its payload: it stands\nalone in its filter, takes no ids, and may require\nexact payload values with `match`. A `github` filter narrows deliveries\nwith its `github` selector.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-condition\"></a> `condition?` | `string` \\| `null` | Yes/no question about the triggering content, e.g. \"Is this email an invoice?\". The routine runs only when the answer is yes. |\n| <a id=\"property-events\"></a> `events` | `EventName`[] | - |\n| <a id=\"property-github\"></a> `github?` | `null` \\| `GithubSelector` | - |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] \\| `null` | - |\n| <a id=\"property-match\"></a> `match?` | `PayloadCondition`[] \\| `null` | Exact tests on the payload, all of which must pass. |\n| <a id=\"property-property\"></a> `property?` | `null` \\| `PropertySelector` | - |",
"EventFilters": "# Type Alias: EventFilters\n\n> **EventFilters** = `EventFilter`[]\n\nBounded nonempty OR of filters, canonicalized to remove duplicates.",
"EventName": "# Type Alias: EventName\n\n> **EventName** = `\"document.created\"` \\| `\"document.updated\"` \\| `\"document.deleted\"` \\| `\"task.created\"` \\| `\"task.status_changed\"` \\| `\"task.priority_changed\"` \\| `\"task.property_changed\"` \\| `\"email.message_received\"` \\| `\"channel.created\"` \\| `\"channel.message_posted\"` \\| `\"channel.mentioned\"` \\| `\"channel.message_patched\"` \\| `\"channel.message_attachment_created\"` \\| `\"call.started\"` \\| `\"call.ended\"` \\| `\"github\"`\n\nClosed allowlist: unknown names, deletions and ambiguous attribution are not\nselectors. Adding a broker variant does not automatically enable routines.",
"GithubSelector": "# Type Alias: GithubSelector\n\n> **GithubSelector** = \\{ `actions?`: `string`[]; `events?`: `string`[]; `includeBots?`: `boolean`; `repositories?`: `string`[]; \\}\n\nWhich GitHub deliveries match.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actions\"></a> `actions?` | `string`[] | Payload actions, such as `completed` or `opened`; any when empty. |\n| <a id=\"property-events\"></a> `events?` | `string`[] | GitHub event names, such as `workflow_run` or `pull_request`; any when empty. |\n| <a id=\"property-includebots\"></a> `includeBots?` | `boolean` | Also run for deliveries caused by bots and apps, including Macro's own. |\n| <a id=\"property-repositories\"></a> `repositories?` | `string`[] | Repositories as `owner/name`, matched without regard to case; every repository the owner's installations cover when empty. A renamed repository stops matching until it is chosen again. |",
"LastRun": "# Type Alias: LastRun\n\n> **LastRun** = \\{ `end_time`: `string`; `is_success`: `boolean`; \\}\n\nHow a routine's most recent finished run went, so lists can flag failures.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-end_time\"></a> `end_time` | `string` |\n| <a id=\"property-is_success\"></a> `is_success` | `boolean` |",
"PayloadCondition": "# Type Alias: PayloadCondition\n\n> **PayloadCondition** = \\{ `equals?`: `null` \\| `PayloadScalar`; `exists?`: `boolean` \\| `null`; `glob?`: `string` \\| `null`; `in?`: `PayloadScalar`[] \\| `null`; `notIn?`: `PayloadScalar`[] \\| `null`; `path`: `string`[]; \\}\n\n`path` walks objects by key; `*` steps into every element of an array and\na number into one. Give exactly one test. `notIn` also passes when the\npath finds nothing.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-equals\"></a> `equals?` | `null` \\| `PayloadScalar` | - |\n| <a id=\"property-exists\"></a> `exists?` | `boolean` \\| `null` | Whether the path finds a non-null value. |\n| <a id=\"property-glob\"></a> `glob?` | `string` \\| `null` | Some text found matches this glob; `*` matches any run of characters. |\n| <a id=\"property-in\"></a> `in?` | `PayloadScalar`[] \\| `null` | Some value found is one of these. |\n| <a id=\"property-notin\"></a> `notIn?` | `PayloadScalar`[] \\| `null` | No value found is one of these. |\n| <a id=\"property-path\"></a> `path` | `string`[] | Keys from the payload's root, e.g. `[\"workflow_run\", \"conclusion\"]`. |",
"PayloadScalar": "# Type Alias: PayloadScalar\n\n> **PayloadScalar** = `null` \\| `boolean` \\| `number` \\| `string`\n\nA JSON text, number, boolean or null that payload values are compared with.",
+ "PropertySelector": "# Type Alias: PropertySelector\n\n> **PropertySelector** = \\{ `definitionId`: `string`; `values?`: `string`[]; \\}\n\nNarrows a task property change filter to one property and, optionally, the\nvalues it must gain.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-definitionid\"></a> `definitionId` | `string` | The property definition that must have changed. |\n| <a id=\"property-values\"></a> `values?` | `string`[] | Select option ids or referenced entity ids, one of which the change must add. Any change to the property matches when empty. |",
"scheduled-action.RoutineTemplate": "# Type Alias: RoutineTemplate\n\n> **RoutineTemplate** = \\{ `active_count`: `number`; `author`: `string`; `created_at`: `string`; `description`: `string`; `id`: `string`; `name`: `string`; `task`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `trigger`: `ActionTrigger`; `updated_at`: `string`; `variables`: `TemplateVariable`[]; \\}\n\nA shared routine's snapshot, readable by signed-in users with sharing enabled.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-active_count\"></a> `active_count` | `number` | Routines activated from this template, including stopped ones. |\n| <a id=\"property-author\"></a> `author` | `string` | Who shared it: the source routine's owner. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-description\"></a> `description` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | The routine it was shared from. |\n| <a id=\"property-name\"></a> `name` | `string` | - |\n| <a id=\"property-task\"></a> `task` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-trigger\"></a> `trigger` | `ActionTrigger` | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n| <a id=\"property-variables\"></a> `variables` | `TemplateVariable`[] | - |",
"RoutineTrigger": "# Type Alias: RoutineTrigger\n\n> **RoutineTrigger** = \\{ `schedule`: `Schedule`; `timezone`: `string`; `type`: `\"cron\"`; \\} \\| \\{ `filters`: `EventFilters`; `type`: `\"events\"`; \\}\n\nAn individual trigger in a routine's trigger list.",
"RoutineTriggers": "# Type Alias: RoutineTriggers\n\n> **RoutineTriggers** = `RoutineTrigger`[]\n\nBounded schedules and one combined set of event filters.",
diff --git a/crates/graphql_scheduled_action/src/objects.rs b/crates/graphql_scheduled_action/src/objects.rs
index eab36f8b95..33facb08bd 100644
--- a/crates/graphql_scheduled_action/src/objects.rs
+++ b/crates/graphql_scheduled_action/src/objects.rs
@@ -74,10 +74,21 @@ pub(crate) struct GraphqlScheduledActionEventFilter {
github: Option<GraphqlScheduledActionGithubSelector>,
/// Exact payload tests a GitHub delivery must pass, as a reader would state them.
payload_match: Vec<String>,
+ /// The task property that must have changed, and the values it must gain.
+ property: Option<GraphqlScheduledActionPropertySelector>,
/// Yes/no question the triggering content must answer with yes before the routine runs.
condition: Option<String>,
}
+/// A task property a filter watches.
+#[derive(SimpleObject)]
+pub(crate) struct GraphqlScheduledActionPropertySelector {
+ /// The property definition that must have changed.
+ definition_id: ID,
+ /// Select option or referenced entity ids, one of which the change must add. Empty matches any change.
+ values: Vec<String>,
+}
+
/// GitHub deliveries a filter watches. Empty lists match everything.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionGithubSelector {
@@ -287,6 +298,12 @@ fn event_filters(
.collect()
})
.unwrap_or_default(),
+ property: filter.property().map(|selector| {
+ GraphqlScheduledActionPropertySelector {
+ definition_id: ID(selector.definition_id().to_string()),
+ values: selector.values().to_vec(),
+ }
+ }),
condition: filter
.condition()
.map(|condition| condition.as_str().to_owned()),
diff --git a/crates/scheduled_action/AGENTS.md b/crates/scheduled_action/AGENTS.md
index ce3804266c..d90cb612ad 100644
--- a/crates/scheduled_action/AGENTS.md
+++ b/crates/scheduled_action/AGENTS.md
@@ -16,6 +16,8 @@ each run.
(Kafka or polled) turns into a dispatched run.
- `src/domain/event_trigger/github_selector.rs`, `payload_match.rs`: the
`github` selector and the exact payload `match` GitHub filters take.
+- `src/domain/event_trigger/property_selector.rs`: the `property` selector task
+ property change filters take, matched on the values a change adds.
- `src/inbound/axum_router.rs`, `src/inbound/kafka_consumer.rs`,
`src/inbound/event_run_worker.rs`: the three inbound adapters.
- `src/domain/templates.rs` + `src/inbound/template_router.rs`: sharing a
@@ -88,6 +90,10 @@ that listener is ready. Cancellation can stop the gate before startup finishes.
payload in `event_context`; access for them is the owner's installation
claim, which needs a linked GitHub account and, for a personal installation,
that the linked account installed it.
+- A `property` filter needs the event's `property_change` (the property and the
+ option or entity ids it gained), so runs of routines with one keep it in
+ `event_context`; other runs drop it (`EventFilters::run_event`). Free text and
+ dates are never kept, so those properties only support any-change filters.
- Enabling a GitHub trigger needs the owner's GitHub link
(`with_github_links`); without it the service returns `GithubNotLinked`.
- `TODO.md` tracks open follow-ups (unified history list, delete schedules,
diff --git a/crates/scheduled_action/src/domain/event_runs/admission.rs b/crates/scheduled_action/src/domain/event_runs/admission.rs
index a671c23fb5..a52ea9e678 100644
--- a/crates/scheduled_action/src/domain/event_runs/admission.rs
+++ b/crates/scheduled_action/src/domain/event_runs/admission.rs
@@ -58,7 +58,11 @@ impl<R: EventRunRepository, A: CurrentOwnerAccess> EventAdmissionService<R, A> {
}
Ok(self
.repository
- .admit(configuration.action_id, configuration.revision, event)
+ .admit(
+ configuration.action_id,
+ configuration.revision,
+ &configuration.filters.run_event(event),
+ )
.await?
== AdmissionResult::Admitted)
}
diff --git a/crates/scheduled_action/src/domain/event_trigger.rs b/crates/scheduled_action/src/domain/event_trigger.rs
index e1c28a72e1..3dde266781 100644
--- a/crates/scheduled_action/src/domain/event_trigger.rs
+++ b/crates/scheduled_action/src/domain/event_trigger.rs
@@ -38,11 +38,13 @@ use super::models::Schedule;
mod github_selector;
mod payload_match;
+mod property_selector;
pub use github_selector::{GithubSelector, GithubSelectorError, GithubSelectorInput};
pub use payload_match::{
PayloadConditionInput, PayloadConditions, PayloadMatchError, PayloadScalar,
};
+pub use property_selector::{PropertyChange, PropertySelector, PropertyValuesError};
#[cfg(test)]
mod test;
@@ -299,6 +301,10 @@ pub enum FilterValidationError {
GithubSelector,
#[error("only github filters take a payload match")]
PayloadMatch,
+ #[error("a property selector needs task property change events that report its property")]
+ PropertyEvents,
+ #[error(transparent)]
+ PropertyValues(#[from] PropertyValuesError),
#[error(transparent)]
Github(#[from] GithubSelectorError),
#[error(transparent)]
@@ -327,6 +333,9 @@ pub struct EventFilter {
#[serde(rename = "match", skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<Vec<PayloadConditionInput>>)]
payload: Option<PayloadConditions>,
+ /// The task property that must have changed, and the values it must gain.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ property: Option<PropertySelector>,
/// Yes/no question about the triggering content, e.g. "Is this email an
/// invoice?". The routine runs only when the answer is yes.
#[serde(skip_serializing_if = "Option::is_none")]
@@ -345,6 +354,8 @@ struct FilterInput {
#[serde(default, rename = "match")]
payload: Option<PayloadConditions>,
#[serde(default)]
+ property: Option<PropertySelector>,
+ #[serde(default)]
condition: Option<YesNoQuestion>,
}
@@ -354,6 +365,7 @@ impl TryFrom<FilterInput> for EventFilter {
fn try_from(input: FilterInput) -> Result<Self, Self::Error> {
Self::new(input.events, input.ids)?
.with_condition(input.condition)
+ .with_property(input.property)?
.with_external(input.github, input.payload)
}
}
@@ -386,6 +398,7 @@ impl EventFilter {
ids,
github: None,
payload: None,
+ property: None,
condition: None,
})
}
@@ -395,6 +408,27 @@ impl EventFilter {
self
}
+ /// Narrow task property change events to one property and its new values.
+ pub fn with_property(
+ mut self,
+ property: Option<PropertySelector>,
+ ) -> Result<Self, FilterValidationError> {
+ let Some(property) = property else {
+ self.property = None;
+ return Ok(self);
+ };
+ let reporting_event = task_property_event_name(Some(property.definition_id()));
+ let reported = self
+ .events
+ .iter()
+ .all(|name| *name == reporting_event || *name == EventName::TaskPropertyChanged);
+ if !reported {
+ return Err(FilterValidationError::PropertyEvents);
+ }
+ self.property = Some(property.canonicalized()?);
+ Ok(self)
+ }
+
/// Attach the GitHub selector and payload match an external filter takes.
pub fn with_external(
mut self,
@@ -430,6 +464,10 @@ impl EventFilter {
self.payload.as_ref()
}
+ pub fn property(&self) -> Option<&PropertySelector> {
+ self.property.as_ref()
+ }
+
pub fn condition(&self) -> Option<&YesNoQuestion> {
self.condition.as_ref()
}
@@ -442,8 +480,16 @@ impl EventFilter {
.is_some_and(|general| self.events.contains(&general));
named
&& match &event.source {
- EventSource::Entity { entity_id, .. } => {
+ EventSource::Entity {
+ entity_id,
+ property_change,
+ ..
+ } => {
self.ids.as_ref().is_none_or(|ids| ids.contains(entity_id))
+ && self
+ .property
+ .as_ref()
+ .is_none_or(|selector| selector.accepts(property_change.as_ref()))
}
EventSource::Github(delivery) => {
self.github
@@ -500,6 +546,23 @@ impl EventFilters {
self.0.iter().any(|filter| filter.condition.is_some())
}
+ /// What a run of this routine keeps of `event`: only routines that test
+ /// property changes keep them.
+ pub fn run_event(&self, event: &EventReference) -> EventReference {
+ let mut kept = event.clone();
+ let tests_properties = self.0.iter().any(|filter| filter.property.is_some());
+ if let (
+ false,
+ EventSource::Entity {
+ property_change, ..
+ },
+ ) = (tests_properties, &mut kept.source)
+ {
+ *property_change = None;
+ }
+ kept
+ }
+
pub fn watches_github(&self) -> bool {
self.0
.iter()
@@ -595,6 +658,7 @@ pub enum EventSource {
entity_id: Uuid,
message_id: Option<Uuid>,
change_source: Option<PropertyChangeSource>,
+ property_change: Option<PropertyChange>,
},
/// A delivery from Macro's GitHub App. Boxed: it carries its payload.
Github(Box<GithubWebhookReceived>),
@@ -614,6 +678,8 @@ struct EventReferenceInput {
github: Option<Box<GithubWebhookReceived>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
change_source: Option<PropertyChangeSource>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ property_change: Option<PropertyChange>,
}
fn skip_message_id(message_id: &Option<Option<Uuid>>) -> bool {
@@ -635,10 +701,13 @@ impl TryFrom<EventReferenceInput> for EventReference {
entity_id,
message_id,
change_source: input.change_source,
+ property_change: input.property_change,
}
}
(None, Some(delivery))
- if name == EventName::Github && input.change_source.is_none() =>
+ if name == EventName::Github
+ && input.change_source.is_none()
+ && input.property_change.is_none() =>
{
EventSource::Github(delivery)
}
@@ -661,16 +730,19 @@ impl From<EventReference> for EventReferenceInput {
message_id: None,
github: None,
change_source: None,
+ property_change: None,
};
match event.source {
EventSource::Entity {
entity_id,
message_id,
change_source,
+ property_change,
} => {
input.entity_id = Some(entity_id);
input.message_id = Some(message_id);
input.change_source = change_source;
+ input.property_change = property_change;
}
EventSource::Github(delivery) => input.github = Some(delivery),
}
@@ -821,6 +893,7 @@ impl IncomingEvent {
}
let event_id = EventId::try_from(self.event_id)?;
let mut change_source = None;
+ let mut property_change = None;
let (event_name, entity_id, message_id) = match &self.payload {
EventPayload::Document(event) => {
let (name, id) = match event {
@@ -907,10 +980,12 @@ impl IncomingEvent {
MessageFact::Other => return Err(EventRejection::UnsupportedEvent),
},
EventPayload::Property(event) => {
- let (name, id, property_source) = task_property_event(event)?;
- let id = Uuid::parse_str(id).map_err(|_| EventRejection::InvalidEntityId)?;
- change_source = property_source;
- (name, id, None)
+ let task_event = task_property_event(event)?;
+ let id = Uuid::parse_str(task_event.entity_id)
+ .map_err(|_| EventRejection::InvalidEntityId)?;
+ change_source = task_event.source;
+ property_change = task_event.change;
+ (task_event.name, id, None)
}
EventPayload::Email(EmailTopicEvent::MessageReceived(data)) => {
// The email domain emits this only for newly received mail,
@@ -958,15 +1033,33 @@ impl IncomingEvent {
entity_id,
message_id,
change_source,
+ property_change,
},
})
}
}
+/// The event a change to this property publishes; `None` when several properties
+/// changed at once.
+fn task_property_event_name(definition_id: Option<Uuid>) -> EventName {
+ match definition_id {
+ Some(SystemPropertyKey::STATUS_UUID) => EventName::TaskStatusChanged,
+ Some(SystemPropertyKey::PRIORITY_UUID) => EventName::TaskPriorityChanged,
+ _ => EventName::TaskPropertyChanged,
+ }
+}
+
+struct TaskPropertyEvent<'event> {
+ name: EventName,
+ entity_id: &'event str,
+ source: Option<PropertyChangeSource>,
+ change: Option<PropertyChange>,
+}
+
fn task_property_event(
event: &PropertyTopicEvent,
-) -> Result<(EventName, &str, Option<PropertyChangeSource>), EventRejection> {
- let (entity_type, entity_id, property_id, actor, fallback, delegated, source) = match event {
+) -> Result<TaskPropertyEvent<'_>, EventRejection> {
+ let (entity_type, entity_id, change, actor, fallback, delegated, source) = match event {
PropertyTopicEvent::EntityPropertyUpdated(data) => {
if data.value == data.previous_value {
return Err(EventRejection::UnsupportedEvent);
@@ -974,7 +1067,11 @@ fn task_property_event(
(
&data.entity_type,
data.entity_id.as_str(),
- Some(data.property_definition_id),
+ Some(PropertyChange::updated(
+ data.property_definition_id,
+ data.value.as_ref(),
+ data.previous_value.as_ref(),
+ )),
data.actor.as_ref(),
data.actor_user_id.as_ref(),
data.on_behalf_of.is_some(),
@@ -984,7 +1081,7 @@ fn task_property_event(
PropertyTopicEvent::EntityPropertyDeleted(data) => (
&data.entity_type,
data.entity_id.as_str(),
- Some(data.property_definition_id),
+ Some(PropertyChange::removed(data.property_definition_id)),
data.actor.as_ref(),
data.actor_user_id.as_ref(),
data.on_behalf_of.is_some(),
@@ -1005,11 +1102,7 @@ fn task_property_event(
if *entity_type != PropertyEntityType::Task {
return Err(EventRejection::UnsupportedEvent);
}
- let name = match property_id {
- Some(SystemPropertyKey::STATUS_UUID) => EventName::TaskStatusChanged,
- Some(SystemPropertyKey::PRIORITY_UUID) => EventName::TaskPriorityChanged,
- _ => EventName::TaskPropertyChanged,
- };
+ let name = task_property_event_name(change.as_ref().map(PropertyChange::definition_id));
// GitHub reports what happened to a pull request whether or not its account
// has a Macro user, so its status changes need no Macro actor. An actor that
// is present still has to be a person.
@@ -1018,5 +1111,10 @@ fn task_property_event(
if !from_github {
document_actor(actor, fallback, delegated)?;
}
- Ok((name, entity_id, source))
+ Ok(TaskPropertyEvent {
+ name,
+ entity_id,
+ source,
+ change,
+ })
}
diff --git a/crates/scheduled_action/src/domain/event_trigger/property_selector.rs b/crates/scheduled_action/src/domain/event_trigger/property_selector.rs
new file mode 100644
index 0000000000..bc4dc11bcb
--- /dev/null
+++ b/crates/scheduled_action/src/domain/event_trigger/property_selector.rs
@@ -0,0 +1,108 @@
+//! Which task property changes a routine watches, without asking a model.
+
+use macro_uuid::Uuid;
+use models_properties::service::property_value::PropertyValue;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+const MAX_PROPERTY_VALUES: usize = 100;
+const MAX_VALUE_CHARS: usize = 320;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+#[error("expected at most 100 property values, each 1 to 320 characters")]
+pub struct PropertyValuesError;
+
+/// Narrows a task property change filter to one property and, optionally, the
+/// values it must gain.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct PropertySelector {
+ /// The property definition that must have changed.
+ #[schema(value_type = String)]
+ definition_id: Uuid,
+ /// Select option ids or referenced entity ids, one of which the change must
+ /// add. Any change to the property matches when empty.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ values: Vec<String>,
+}
+
+impl PropertySelector {
+ /// Sort and deduplicate so equal selectors compare equal.
+ pub(super) fn canonicalized(mut self) -> Result<Self, PropertyValuesError> {
+ let valid = |value: &String| !value.is_empty() && value.chars().count() <= MAX_VALUE_CHARS;
+ if self.values.len() > MAX_PROPERTY_VALUES || !self.values.iter().all(valid) {
+ return Err(PropertyValuesError);
+ }
+ self.values.sort_unstable();
+ self.values.dedup();
+ Ok(self)
+ }
+
+ pub fn definition_id(&self) -> Uuid {
+ self.definition_id
+ }
+
+ pub fn values(&self) -> &[String] {
+ &self.values
+ }
+
+ pub(super) fn accepts(&self, change: Option<&PropertyChange>) -> bool {
+ change.is_some_and(|change| {
+ change.definition_id == self.definition_id
+ && (self.values.is_empty()
+ || self.values.iter().any(|value| change.added.contains(value)))
+ })
+ }
+}
+
+/// What a task property event did, kept on the run so its filters can be
+/// tested again at claim. Holds only ids: free text and dates are never kept.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PropertyChange {
+ definition_id: Uuid,
+ /// Values the property has now and didn't before; all of them when the
+ /// writer couldn't capture the previous value.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ added: Vec<String>,
+}
+
+impl PropertyChange {
+ pub(super) fn updated(
+ definition_id: Uuid,
+ value: Option<&PropertyValue>,
+ previous: Option<&PropertyValue>,
+ ) -> Self {
+ let previous = value_ids(previous);
+ let added = value_ids(value)
+ .into_iter()
+ .filter(|id| !previous.contains(id))
+ .collect();
+ Self {
+ definition_id,
+ added,
+ }
+ }
+
+ pub(super) fn removed(definition_id: Uuid) -> Self {
+ Self {
+ definition_id,
+ added: Vec::new(),
+ }
+ }
+
+ pub(super) fn definition_id(&self) -> Uuid {
+ self.definition_id
+ }
+}
+
+fn value_ids(value: Option<&PropertyValue>) -> Vec<String> {
+ match value {
+ Some(PropertyValue::SelectOption(ids)) => ids.iter().map(Uuid::to_string).collect(),
+ Some(PropertyValue::EntityRef(references)) => references
+ .iter()
+ .map(|reference| reference.entity_id.clone())
+ .collect(),
+ _ => Vec::new(),
+ }
+}
diff --git a/crates/scheduled_action/src/domain/event_trigger/test.rs b/crates/scheduled_action/src/domain/event_trigger/test.rs
index 67248ff847..5874a811a0 100644
--- a/crates/scheduled_action/src/domain/event_trigger/test.rs
+++ b/crates/scheduled_action/src/domain/event_trigger/test.rs
@@ -503,7 +503,7 @@ fn task_changes_match_specific_and_any_property_selectors() {
.unwrap();
assert!(!other_task.accepts(&event));
let stored = serde_json::to_value(&event).unwrap();
- assert_eq!(stored.as_object().unwrap().len(), 4);
+ assert_eq!(stored.as_object().unwrap().len(), 5);
assert_eq!(
serde_json::from_value::<EventReference>(stored).unwrap(),
event
@@ -796,3 +796,159 @@ fn github_deliveries_normalize_with_their_payload_and_reject_odd_names() {
Err(EventRejection::UnsupportedEvent)
);
}
+
+const COMPLETED: &str = "00000001-0000-0000-0002-000000000004";
+const IN_PROGRESS: &str = "00000001-0000-0000-0002-000000000002";
+
+fn status_changed(value: &str, previous: &str) -> EventReference {
+ let mut data = property_metadata();
+ data["value"] = json!({"type": "SelectOption", "value": [value]});
+ data["previous_value"] = json!({"type": "SelectOption", "value": [previous]});
+ property_event("entity_property.updated", data)
+ .normalize()
+ .unwrap()
+}
+
+fn property_filter(events: Value, definition: Uuid, values: Value) -> EventFilter {
+ serde_json::from_value(json!({
+ "events": events,
+ "property": {"definitionId": definition, "values": values}
+ }))
+ .unwrap()
+}
+
+#[test]
+fn property_selector_matches_the_value_a_change_adds() {
+ let completed = property_filter(
+ json!(["task.status_changed"]),
+ SystemPropertyKey::STATUS_UUID,
+ json!([COMPLETED]),
+ );
+ assert!(completed.accepts(&status_changed(COMPLETED, IN_PROGRESS)));
+ assert!(!completed.accepts(&status_changed(IN_PROGRESS, COMPLETED)));
+
+ let any_status = property_filter(
+ json!(["task.status_changed"]),
+ SystemPropertyKey::STATUS_UUID,
+ json!([]),
+ );
+ assert!(any_status.accepts(&status_changed(IN_PROGRESS, COMPLETED)));
+
+ let priority = property_filter(
+ json!(["task.property_changed"]),
+ SystemPropertyKey::PRIORITY_UUID,
+ json!([]),
+ );
+ assert!(!priority.accepts(&status_changed(COMPLETED, IN_PROGRESS)));
+}
+
+#[test]
+fn property_selector_matches_only_people_newly_assigned() {
+ let alice = "macro|[email protected]";
+ let bob = "macro|[email protected]";
+ let assignees = |ids: &[&str]| {
+ let references: Vec<Value> = ids
+ .iter()
+ .map(|id| json!({"entity_id": id, "entity_type": "USER"}))
+ .collect();
+ json!({"type": "EntityReference", "value": references})
+ };
+ let mut data = property_metadata();
+ data["property_definition_id"] = json!(SystemPropertyKey::ASSIGNEES_UUID);
+ data["value"] = assignees(&[alice, bob]);
+ data["previous_value"] = assignees(&[alice]);
+ let event = property_event("entity_property.updated", data)
+ .normalize()
+ .unwrap();
+
+ let watching = |person: &str| {
+ property_filter(
+ json!(["task.property_changed"]),
+ SystemPropertyKey::ASSIGNEES_UUID,
+ json!([person]),
+ )
+ };
+ assert!(watching(bob).accepts(&event));
+ assert!(!watching(alice).accepts(&event));
+}
+
+#[test]
+fn property_selector_rejects_events_that_cannot_report_its_property() {
+ let parse = |events: Value, definition: Uuid| {
+ serde_json::from_value::<EventFilter>(json!({
+ "events": events,
+ "property": {"definitionId": definition}
+ }))
+ };
+ assert!(
+ parse(
+ json!(["task.status_changed"]),
+ SystemPropertyKey::STATUS_UUID
+ )
+ .is_ok()
+ );
+ assert!(
+ parse(
+ json!(["task.property_changed"]),
+ SystemPropertyKey::STATUS_UUID
+ )
+ .is_ok()
+ );
+ assert!(
+ parse(
+ json!(["task.priority_changed"]),
+ SystemPropertyKey::STATUS_UUID
+ )
+ .is_err()
+ );
+ assert!(parse(json!(["task.created"]), SystemPropertyKey::STATUS_UUID).is_err());
+ assert!(parse(json!(["document.created"]), SystemPropertyKey::STATUS_UUID).is_err());
+}
+
+#[test]
+fn property_change_survives_storage_only_for_routines_that_test_it() {
+ let event = status_changed(COMPLETED, IN_PROGRESS);
+ let stored: EventReference =
+ serde_json::from_value(serde_json::to_value(&event).unwrap()).unwrap();
+ assert_eq!(stored, event);
+
+ let testing = EventFilters::try_from(vec![property_filter(
+ json!(["task.status_changed"]),
+ SystemPropertyKey::STATUS_UUID,
+ json!([COMPLETED]),
+ )])
+ .unwrap();
+ assert_eq!(testing.run_event(&event), event);
+
+ let plain = EventFilters::try_from(vec![
+ EventFilter::new(vec![EventName::TaskStatusChanged], None).unwrap(),
+ ])
+ .unwrap();
+ let kept = serde_json::to_value(plain.run_event(&event)).unwrap();
+ assert!(kept.get("property_change").is_none());
+}
+
+#[test]
+fn a_condition_applies_only_to_the_filter_whose_property_value_matched() {
+ let filter = |value: &str, condition: Option<&str>| {
+ serde_json::from_value::<EventFilter>(json!({
+ "events": ["task.status_changed"],
+ "property": {"definitionId": SystemPropertyKey::STATUS_UUID, "values": [value]},
+ "condition": condition
+ }))
+ .unwrap()
+ };
+ let filters = EventFilters::try_from(vec![
+ filter(COMPLETED, None),
+ filter(IN_PROGRESS, Some("Is this a bug report?")),
+ ])
+ .unwrap();
+ assert_eq!(
+ filters.condition_requirement(&status_changed(COMPLETED, IN_PROGRESS)),
+ ConditionRequirement::Unconditional
+ );
+ assert!(matches!(
+ filters.condition_requirement(&status_changed(IN_PROGRESS, COMPLETED)),
+ ConditionRequirement::AnyOf(_)
+ ));
+}
diff --git a/crates/scheduled_action/src/swagger.rs b/crates/scheduled_action/src/swagger.rs
index 85ca07431d..4260919d44 100644
--- a/crates/scheduled_action/src/swagger.rs
+++ b/crates/scheduled_action/src/swagger.rs
@@ -19,7 +19,7 @@ use crate::inbound::template_router::{
use crate::domain::event_trigger::{
ActionTrigger, EventFilter, EventFilters, EventName, GithubSelectorInput,
- PayloadConditionInput, PayloadScalar,
+ PayloadConditionInput, PayloadScalar, PropertySelector,
};
use crate::domain::models::{
ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, AgentTask,
@@ -67,6 +67,7 @@ use model::response::EmptyResponse;
GithubSelectorInput,
PayloadConditionInput,
PayloadScalar,
+ PropertySelector,
SetScheduledActionEnabled,
Schedule,
ActionKind,
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index eded615797..491ae0cfa1 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -1126,13 +1126,13 @@ The event menu groups Macro activity triggers by surface:
- **Channels:** **Channel created**, **Message sent in channel**, and **@ mentioned in channel**.
- **Documents:** **Document created** and **Document deleted**. Tasks are separate.
-- **Tasks:** **Task created**, **Status changed**, **Priority changed**, and **Any property changed**.
+- **Tasks:** **Task created**, **Status changed**, **Priority changed**, **Assignees changed**, **Due date changed**, **Project changed**, **Effort changed**, and **Any property changed**. Under **Changes to**, choose the values that start the routine, such as **Completed**, or leave **Any status**. A value counts only when the change adds it. Tags aren't properties and have no trigger.
- **Email:** **New email received** in the routine owner's inbox, excluding spam, trash, drafts, and historical imports.
- **Calls:** **Call started**, for calls the routine owner starts (receives the call and who has joined so far); and **Call ended**, for channel calls and meetings the owner joined (receives participants and transcript, cut short for long calls).
- **GitHub:** presets for **Workflow failed**, **Workflow finished**, **Pull request opened**, **Pull request merged**, **Review requested**, **Review submitted**, **Issue opened**, **Comment added**, **Code pushed**, **Release published**, and **Any GitHub event**, from repositories Macro's GitHub app reaches for the routine owner. Until the owner connects GitHub, the group shows **Connect GitHub** instead.
-For messages, mentions, deletion, and task changes, choose specific accessible
-channels/documents/tasks or any accessible item in the same panel. Creation
+For messages, mentions, deletion, and task changes, use **Applies to** in the
+same panel to choose any accessible item or specific channels/documents/tasks. Creation
triggers cover newly created accessible items; email covers the owner's inbox;
**Call started** shows **Calls you start** and **Call ended** shows **Calls you
join** — neither has an item picker. Calls the owner did not start never trigger
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md
index 6c00ec5e0a..7fcdf0c702 100644
--- a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md
@@ -65,6 +65,7 @@
- [ListScheduledActionsResponses](type-aliases/ListScheduledActionsResponses.md)
- [PayloadCondition](type-aliases/PayloadCondition.md)
- [PayloadScalar](type-aliases/PayloadScalar.md)
+- [PropertySelector](type-aliases/PropertySelector.md)
- [RoutineModelId](type-aliases/RoutineModelId.md)
- [RoutineTemplate](type-aliases/RoutineTemplate.md)
- [RoutineTrigger](type-aliases/RoutineTrigger.md)
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventFilter.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventFilter.md
index 9de976fa29..d787c24054 100644
--- a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventFilter.md
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventFilter.md
@@ -1,6 +1,6 @@
# Type Alias: EventFilter
-> **EventFilter** = \{ `condition?`: `string` \| `null`; `events`: [`EventName`](EventName.md)[]; `github?`: `null` \| [`GithubSelector`](GithubSelector.md); `ids?`: `string`[] \| `null`; `match?`: [`PayloadCondition`](PayloadCondition.md)[] \| `null`; \}
+> **EventFilter** = \{ `condition?`: `string` \| `null`; `events`: [`EventName`](EventName.md)[]; `github?`: `null` \| [`GithubSelector`](GithubSelector.md); `ids?`: `string`[] \| `null`; `match?`: [`PayloadCondition`](PayloadCondition.md)[] \| `null`; `property?`: `null` \| [`PropertySelector`](PropertySelector.md); \}
An event name AND an entity ID must match within the same filter. A
condition further requires the event's content to answer it with yes.
@@ -19,3 +19,4 @@ with its `github` selector.
| <a id="property-github"></a> `github?` | `null` \| [`GithubSelector`](GithubSelector.md) | - |
| <a id="property-ids"></a> `ids?` | `string`[] \| `null` | - |
| <a id="property-match"></a> `match?` | [`PayloadCondition`](PayloadCondition.md)[] \| `null` | Exact tests on the payload, all of which must pass. |
+| <a id="property-property"></a> `property?` | `null` \| [`PropertySelector`](PropertySelector.md) | - |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/PropertySelector.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/PropertySelector.md
new file mode 100644
index 0000000000..c2a06634d0
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/PropertySelector.md
@@ -0,0 +1,13 @@
+# Type Alias: PropertySelector
+
+> **PropertySelector** = \{ `definitionId`: `string`; `values?`: `string`[]; \}
+
+Narrows a task property change filter to one property and, optionally, the
+values it must gain.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-definitionid"></a> `definitionId` | `string` | The property definition that must have changed. |
+| <a id="property-values"></a> `values?` | `string`[] | Select option ids or referenced entity ids, one of which the change must add. Any change to the property matches when empty. |
diff --git a/packages/sdk/generated/scheduled-action/index.ts b/packages/sdk/generated/scheduled-action/index.ts
index cb9068e78c..d63fbb1486 100644
--- a/packages/sdk/generated/scheduled-action/index.ts
+++ b/packages/sdk/generated/scheduled-action/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, ActivateScheduledActionTemplateData, ActivateScheduledActionTemplateError, ActivateScheduledActionTemplateErrors, ActivateScheduledActionTemplateResponse, ActivateScheduledActionTemplateResponses, AgentMcpServer, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, ConditionResult, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, GetScheduledActionTemplateData, GetScheduledActionTemplateError, GetScheduledActionTemplateErrors, GetScheduledActionTemplateResponse, GetScheduledActionTemplateResponses, GithubSelector, InProgressExecution, LastRun, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, PayloadCondition, PayloadScalar, RoutineModelId, RoutineTemplate, RoutineTrigger, RoutineTriggers, RunVisibility, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, ShareRoutineTemplate, ShareScheduledActionTemplateData, ShareScheduledActionTemplateError, ShareScheduledActionTemplateErrors, ShareScheduledActionTemplateResponse, ShareScheduledActionTemplateResponses, TemplateVariable, UnshareScheduledActionTemplateData, UnshareScheduledActionTemplateError, UnshareScheduledActionTemplateErrors, UnshareScheduledActionTemplateResponse, UnshareScheduledActionTemplateResponses, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses, VariableFill } from './types.gen';
+export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, ActivateScheduledActionTemplateData, ActivateScheduledActionTemplateError, ActivateScheduledActionTemplateErrors, ActivateScheduledActionTemplateResponse, ActivateScheduledActionTemplateResponses, AgentMcpServer, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, ConditionResult, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, GetScheduledActionTemplateData, GetScheduledActionTemplateError, GetScheduledActionTemplateErrors, GetScheduledActionTemplateResponse, GetScheduledActionTemplateResponses, GithubSelector, InProgressExecution, LastRun, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, PayloadCondition, PayloadScalar, PropertySelector, RoutineModelId, RoutineTemplate, RoutineTrigger, RoutineTriggers, RunVisibility, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, ShareRoutineTemplate, ShareScheduledActionTemplateData, ShareScheduledActionTemplateError, ShareScheduledActionTemplateErrors, ShareScheduledActionTemplateResponse, ShareScheduledActionTemplateResponses, TemplateVariable, UnshareScheduledActionTemplateData, UnshareScheduledActionTemplateError, UnshareScheduledActionTemplateErrors, UnshareScheduledActionTemplateResponse, UnshareScheduledActionTemplateResponses, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses, VariableFill } from './types.gen';
diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.ts
index 385a52be1a..3d08f19e54 100644
--- a/packages/sdk/generated/scheduled-action/types.gen.ts
+++ b/packages/sdk/generated/scheduled-action/types.gen.ts
@@ -170,6 +170,7 @@ export type EventFilter = {
* Exact tests on the payload, all of which must pass.
*/
match?: Array<PayloadCondition> | null;
+ property?: null | PropertySelector;
};
/**
@@ -279,6 +280,22 @@ export type PayloadCondition = {
*/
export type PayloadScalar = null | boolean | number | string;
+/**
+ * Narrows a task property change filter to one property and, optionally, the
+ * values it must gain.
+ */
+export type PropertySelector = {
+ /**
+ * The property definition that must have changed.
+ */
+ definitionId: string;
+ /**
+ * Select option ids or referenced entity ids, one of which the change must
+ * add. Any change to the property matches when empty.
+ */
+ values?: Array<string>;
+};
+
/**
* A nonblank model identifier. Runtime catalogs, not the scheduler, own availability.
*/
diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.json
index b163c439be..b04a46fa95 100644
--- a/packages/sdk/specs/scheduled-action.json
+++ b/packages/sdk/specs/scheduled-action.json
@@ -1194,6 +1194,17 @@
"$ref": "#/components/schemas/PayloadCondition"
},
"description": "Exact tests on the payload, all of which must pass."
+ },
+ "property": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/PropertySelector",
+ "description": "The task property that must have changed, and the values it must gain."
+ }
+ ]
}
}
},
@@ -1417,6 +1428,25 @@
],
"description": "A JSON text, number, boolean or null that payload values are compared with."
},
+ "PropertySelector": {
+ "type": "object",
+ "description": "Narrows a task property change filter to one property and, optionally, the\nvalues it must gain.",
+ "required": ["definitionId"],
+ "properties": {
+ "definitionId": {
+ "type": "string",
+ "description": "The property definition that must have changed."
+ },
+ "values": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Select option ids or referenced entity ids, one of which the change must\nadd. Any change to the property matches when empty."
+ }
+ },
+ "additionalProperties": false
+ },
"RoutineModelId": {
"type": "string",
"description": "A nonblank model identifier. Runtime catalogs, not the scheduler, own availability."
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index ccc4a379d6..afb3154ab4 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -7400,6 +7400,10 @@ type GraphqlScheduledActionEventFilter {
"""
payloadMatch: [String!]!
"""
+ The task property that must have changed, and the values it must gain.
+ """
+ property: GraphqlScheduledActionPropertySelector
+ """
Yes/no question the triggering content must answer with yes before the routine runs.
"""
condition: String
@@ -7521,6 +7525,20 @@ type GraphqlScheduledActionMultipleTrigger {
events: GraphqlScheduledActionEventsTrigger
}
+"""
+A task property a filter watches.
+"""
+type GraphqlScheduledActionPropertySelector {
+ """
+ The property definition that must have changed.
+ """
+ definitionId: ID!
+ """
+ Select option or referenced entity ids, one of which the change must add. Empty matches any change.
+ """
+ values: [String!]!
+}
+
"""
The way a routine starts.
"""