/** * The event half of an automation's "When": one block per trigger (where the * events come from, which events, and optional conditions), plus "Run once". * Controlled and data-agnostic: the host passes the sources it can read and a * loader for each source's event types. */ import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react"; import { PlusIcon, Trash2Icon, XIcon } from "lucide-react"; import type { EventSource, EventTypeDescriptor } from "@opengeni/sdk"; import { useOpenGeniText, type OpenGeniText } from "../../messages/runtime"; import { Button } from "../../ui/button"; import { CheckboxField, Field, TextInput } from "../../ui/field"; import { ComboboxSelect, SelectMenu, type SelectOption } from "../../ui/select-menu"; import { cn } from "../../lib/cn"; import { EventArgumentsField } from "./event-arguments-field"; import { eventArgumentsForEvent } from "./event-arguments-model"; import { eventSourceAddLabel, eventSourceChoiceName, eventSourceKindLabel, eventStatusReasonText, type EventSourceChoice, } from "./event-source-model"; import { EventSourceTile, type EventSourceLogoResolver } from "./event-source-tile"; import { automationTemplateSourceChoice, eventSourceFitsTemplate, } from "./automation-template-model"; import { EVENT_CONDITION_OPERATORS, EVENT_TRIGGER_CONDITIONS_MAX, EVENT_TRIGGERS_PER_AUTOMATION_MAX, eventConditionFieldSuggestions, eventConditionOperator, eventConditionOperatorLabel, eventTypeIssue, eventTypeLabel, eventTypesLabel, newEventConditionDraft, newEventTriggerDraft, type EventConditionDraft, type EventTriggerDraft, type EventTriggerIssues, type EventTriggersDraft, type EventTriggersIssues, } from "./event-trigger-model"; /** A source's event types, or why they couldn't be read. */ export type EventTypesState = | { status: "loading" } | { status: "ready"; eventTypes: EventTypeDescriptor[] } | { status: "error"; message: string }; /** * Reads each picked source's event types once and keeps them, so switching a * trigger's source back and forth never refetches. */ export function useEventTypes( sourceIds: readonly string[], load: (sourceId: string) => Promise, ): Record { const t = useOpenGeniText(); const [states, setStates] = useState>({}); const requested = useRef(new Set()); const loadRef = useRef(load); loadRef.current = load; const textRef = useRef(t); textRef.current = t; const key = [...new Set(sourceIds)].filter(Boolean).sort().join(","); useEffect(() => { for (const sourceId of key ? key.split(",") : []) { if (requested.current.has(sourceId)) continue; requested.current.add(sourceId); setStates((current) => ({ ...current, [sourceId]: { status: "loading" } })); loadRef.current(sourceId).then( (eventTypes) => setStates((current) => ({ ...current, [sourceId]: { status: "ready", eventTypes } })), (error: unknown) => { requested.current.delete(sourceId); setStates((current) => ({ ...current, [sourceId]: { status: "error", message: error instanceof Error ? error.message : textRef.current("automations.editor.loadEventsFailed"), }, })); }, ); } }, [key]); return states; } /* ---------------------------------------------------------------------------- The field: every trigger, Add, and Run once. -------------------------------------------------------------------------- */ export interface EventTriggersFieldProps { value: EventTriggersDraft; onChange: (next: EventTriggersDraft) => void; /** Sources the person can point triggers at; undefined while loading. */ sources: EventSource[] | undefined; /** Reads one source's event types. */ loadEventTypes: (sourceId: string) => Promise; issues?: EventTriggersIssues | undefined; /** The source's brand logo, from the host's connector catalog. */ sourceLogo?: EventSourceLogoResolver | undefined; /** * Opens the host's "Add a source" page; offered when no source fits. Gets * the kind a template's trigger asks for, when it asks for one. */ onAddSource?: ((choice?: EventSourceChoice) => void) | undefined; /** Offer "Run once, then finish" (default true). */ allowOnce?: boolean | undefined; /** * Arguments a new MCP subscription starts with, by name, such as the * project the host's chat belongs to. Only arguments the event takes apply. */ argumentDefaults?: Readonly> | undefined; /** More buttons beside Add an event, such as the host's Add a schedule. */ actions?: ReactNode | undefined; disabled?: boolean | undefined; } export function EventTriggersField({ value, onChange, sources, loadEventTypes, issues, sourceLogo, onAddSource, allowOnce = true, argumentDefaults, actions, disabled = false, }: EventTriggersFieldProps) { const t = useOpenGeniText(); const eventTypes = useEventTypes( value.triggers.map((trigger) => trigger.sourceId), loadEventTypes, ); const lastAdded = useRef(null); const update = (key: string, next: EventTriggerDraft) => onChange({ ...value, triggers: value.triggers.map((trigger) => (trigger.key === key ? next : trigger)), }); const remove = (key: string) => { const triggers = value.triggers.filter((trigger) => trigger.key !== key); onChange({ ...value, triggers, ...(triggers.length === 0 ? { once: false } : {}) }); }; const add = () => { const only = sources?.length === 1 ? sources[0]!.id : ""; const trigger = newEventTriggerDraft(only); lastAdded.current = trigger.key; onChange({ ...value, triggers: [...value.triggers, trigger] }); }; const full = value.triggers.length >= EVENT_TRIGGERS_PER_AUTOMATION_MAX; return (
{value.triggers.map((trigger, index) => ( update(trigger.key, next)} onRemove={() => remove(trigger.key)} sources={sources} eventTypes={trigger.sourceId ? eventTypes[trigger.sourceId] : undefined} issues={issues?.triggers[trigger.key]} sourceLogo={sourceLogo} onAddSource={onAddSource} argumentDefaults={argumentDefaults} autoFocus={lastAdded.current === trigger.key} disabled={disabled} /> ))}
{actions} {full ? ( {t("automations.editor.triggersMax", { max: EVENT_TRIGGERS_PER_AUTOMATION_MAX })} ) : null}
{allowOnce && value.triggers.length > 0 ? ( onChange({ ...value, once })} disabled={disabled} /> ) : null}
); } /* ---------------------------------------------------------------------------- One trigger. -------------------------------------------------------------------------- */ export interface EventTriggerEditorProps { value: EventTriggerDraft; onChange: (next: EventTriggerDraft) => void; onRemove: () => void; /** Position in the list, for accessible names. */ index: number; sources: EventSource[] | undefined; /** The chosen source's event types; undefined before a source is chosen. */ eventTypes: EventTypesState | undefined; issues?: EventTriggerIssues | undefined; sourceLogo?: EventSourceLogoResolver | undefined; onAddSource?: ((choice?: EventSourceChoice) => void) | undefined; /** Arguments a new MCP subscription starts with; see `EventTriggersField`. */ argumentDefaults?: Readonly> | undefined; /** Move focus to the source picker when the block appears. */ autoFocus?: boolean | undefined; disabled?: boolean | undefined; } export function EventTriggerEditor({ value, onChange, onRemove, index, sources, eventTypes, issues, sourceLogo, onAddSource, argumentDefaults, autoFocus = false, disabled = false, }: EventTriggerEditorProps) { const t = useOpenGeniText(); const blockRef = useRef(null); const source = sources?.find((candidate) => candidate.id === value.sourceId); /** What a template asked for, while no source of that kind is chosen. */ const wanted = !value.sourceId ? value.templateSource : undefined; const wantedChoice = wanted ? automationTemplateSourceChoice(wanted) : undefined; const descriptors = eventTypes?.status === "ready" ? eventTypes.eventTypes : []; const schemaOf = (types: readonly string[]) => types .map((type) => descriptors.find((descriptor) => descriptor.type === type)?.argumentsSchema) .find((schema) => schema && Object.keys(schema).length > 0); const argumentsSchema = schemaOf(value.eventTypes); useEffect(() => { if (!autoFocus) return; blockRef.current?.querySelector("button, input")?.focus(); }, [autoFocus]); const sourceOptions: SelectOption[] = (sources ?? []).map((candidate) => ({ value: candidate.id, label: candidate.name, meta: eventSourceKindLabel(t, candidate), leading: , ...(candidate.status === "active" ? {} : { description: eventStatusReasonText( t, { text: candidate.statusReason, code: candidate.statusReasonCode, detail: candidate.statusReasonDetail, }, candidate.name, ) ?? t("automations.editor.sourceOff"), }), })); const label = t("automations.editor.eventN", { index: index + 1 }); return (
8 ? "combobox" : "menu"} options={sourceOptions} value={value.sourceId || null} onValueChange={(sourceId) => { const picked = sources?.find((candidate) => candidate.id === sourceId); // A source of the kind the template asked for keeps its events. onChange( wanted && picked && eventSourceFitsTemplate(wanted, picked) ? { ...value, sourceId } : { ...value, sourceId, eventTypes: [], conditions: [], argumentsText: "" }, ); }} placeholder={ sources === undefined ? t("automations.editor.loadingSources") : t("automations.editor.chooseSource") } loading={sources === undefined} searchPlaceholder={t("automations.editor.searchSources")} emptyMessage={ onAddSource ? ( {t("automations.editor.noSources")}{" "} ) : ( t("automations.editor.noSourcesAskAdmin") ) } invalid={Boolean(issues?.source)} disabled={disabled} className="max-w-full" />
{wanted && wantedChoice && sources !== undefined ? (

{t("automations.editor.templateWants", { events: eventTypesLabel(t, value.eventTypes), source: wanted.kind === "mcp" && wanted.mcpServerId ? wanted.mcpServerId : eventSourceChoiceName(t, wantedChoice), })} {onAddSource ? ( <> {" "} ) : null}

) : null} {value.sourceId ? ( <> onChange({ ...value, eventTypes: picked, // A newly picked MCP event keeps what applies and fills in the host's defaults. ...(source?.kind === "mcp" && picked.length > 0 ? { argumentsText: eventArgumentsForEvent( schemaOf(picked), value.argumentsText, argumentDefaults, ), } : {}), }) } state={eventTypes} sourceName={source?.name} single={source?.kind === "mcp"} grouped={source?.kind === "workspace"} invalid={Boolean(issues?.eventTypes)} disabled={disabled} /> {source?.kind === "mcp" ? ( onChange({ ...value, argumentsText })} error={issues?.arguments} disabled={disabled} /> ) : null} onChange({ ...value, conditions })} suggestions={eventConditionFieldSuggestions(t, value.eventTypes, descriptors)} issues={issues?.conditions} disabled={disabled} /> {source?.kind === "github" || source?.kind === "slack" || source?.kind === "workspace" ? ( onChange({ ...value, includeOwnEvents })} disabled={disabled} /> ) : null} ) : null}
); } /* ---------------------------------------------------------------------------- Event types. -------------------------------------------------------------------------- */ const CUSTOM_PREFIX = "custom:"; /** One empty list while types load, so the picker's options keep their identity. */ const NO_EVENT_TYPES: EventTypeDescriptor[] = []; /** "This workspace" types under Chats, Usage and Meetings, in the catalog's order. */ function workspaceEventGroup(t: OpenGeniText, type: string): string | undefined { if (type.startsWith("recording.")) return t("automations.picker.groupMeetings"); if (type.startsWith("usage.")) return t("automations.picker.groupUsage"); if (type.startsWith("turn.") || type.startsWith("session.")) { return t("automations.picker.groupChats"); } return undefined; } export function EventTypePicker({ value, onChange, state, sourceName, single = false, grouped = false, invalid = false, disabled = false, }: { value: string[]; onChange: (eventTypes: string[]) => void; state: EventTypesState | undefined; /** The source's name, which the reasons a type can't be picked mention. */ sourceName?: string | undefined; /** Only one type (MCP triggers); picking replaces it. */ single?: boolean | undefined; /** Headings for "This workspace" types: Chats, Usage and Meetings. */ grouped?: boolean | undefined; invalid?: boolean | undefined; disabled?: boolean | undefined; }) { const t = useOpenGeniText(); const [query, setQuery] = useState(""); const descriptors = state?.status === "ready" ? state.eventTypes : NO_EVENT_TYPES; const options = useMemo(() => { const picked = new Set(value); const known: SelectOption[] = descriptors .filter((descriptor) => !picked.has(descriptor.type)) .map((descriptor) => { const unavailable = descriptor.available ? null : eventStatusReasonText( t, { text: descriptor.unavailableReason, code: descriptor.unavailableReasonCode, detail: descriptor.unavailableReasonDetail, }, sourceName, ); return { value: descriptor.type, label: descriptor.type, description: unavailable ?? descriptor.description, disabled: !descriptor.available, ...(grouped ? { group: workspaceEventGroup(t, descriptor.type) } : {}), ...(descriptor.available ? {} : { disabledReason: unavailable ?? t("automations.picker.cantReceive") }), keywords: [descriptor.description], }; }); const all: SelectOption[] = single || picked.has("*") ? [] : [ { value: "*", label: eventTypeLabel(t, "*"), description: t("automations.picker.everyEventDescription"), }, ]; const needle = query.trim().toLowerCase(); const matches = [...all, ...known].filter( (option) => !needle || option.value.toLowerCase().includes(needle) || String(option.description ?? "") .toLowerCase() .includes(needle), ); const typed = query.trim(); const custom = typed && !single && !picked.has(typed) && !descriptors.some((descriptor) => descriptor.type === typed) && eventTypeIssue(t, typed) === null ? [ { value: `${CUSTOM_PREFIX}${typed}`, label: t("automations.picker.use", { type: typed }), description: typed.endsWith(".*") ? t("automations.picker.prefixDescription", { prefix: typed.slice(0, -1) }) : t("automations.picker.unlisted"), }, ] : []; return [...matches, ...custom]; }, [descriptors, grouped, query, single, sourceName, t, value]); const add = (picked: string) => { const type = picked.startsWith(CUSTOM_PREFIX) ? picked.slice(CUSTOM_PREFIX.length) : picked; setQuery(""); onChange(single ? [type] : [...value, type]); }; const loading = state === undefined || state.status === "loading"; return (
{value.length > 0 ? (
    {value.map((type) => { const description = descriptors.find((entry) => entry.type === type)?.description; return (
  • {eventTypeLabel(t, type)}
  • ); })}
) : null} {state?.status === "error" ? (

{t("automations.picker.loadFailed", { reason: state.message.replace(/\.$/, "") })}

) : null} {single && value.length > 0 ? null : ( )}
); } /* ---------------------------------------------------------------------------- Conditions. -------------------------------------------------------------------------- */ export function EventConditionsEditor({ value, onChange, suggestions, issues, disabled = false, }: { value: EventConditionDraft[]; onChange: (conditions: EventConditionDraft[]) => void; /** Fields worth matching, for autocomplete. */ suggestions: ReadonlyArray<{ field: string; description: string }>; /** By condition key. */ issues?: Record | undefined; disabled?: boolean | undefined; }) { const t = useOpenGeniText(); const listId = useId(); const headingId = useId(); const update = (key: string, next: Partial) => onChange( value.map((condition) => (condition.key === key ? { ...condition, ...next } : condition)), ); const full = value.length >= EVENT_TRIGGER_CONDITIONS_MAX; return (

{t("automations.conditions.heading")} {t("automations.conditions.optional")}

{suggestions.map((entry) => ( ))} {value.map((condition, index) => { const operator = eventConditionOperator(condition.op); const issue = issues?.[condition.key]; const position = { index: index + 1 }; return (
update(condition.key, { field: event.target.value })} list={listId} placeholder="data.action" aria-label={t("automations.conditions.fieldFor", position)} aria-invalid={issue ? true : undefined} mono suppressAutofill disabled={disabled} className="col-span-1" /> ({ value: option.value, label: eventConditionOperatorLabel(t, option.value), }))} value={condition.op} onValueChange={(op) => update(condition.key, { op, ...(eventConditionOperator(op).takes === null ? { value: "" } : {}), }) } aria-label={t("automations.conditions.comparisonFor", position)} showSelectedDescription={false} disabled={disabled} className="col-span-2 sm:col-span-1" /> {operator.takes === null ? ( ) : ( update(condition.key, { value: event.target.value })} placeholder={operator.takes === "list" ? "opened, reopened" : "opened"} aria-label={t("automations.conditions.valueFor", position)} aria-invalid={issue ? true : undefined} suppressAutofill disabled={disabled} className="col-span-2 sm:col-span-1" /> )}
{issue ?

{issue}

: null}
); })}
); }