refactor(ui/workflows): read triggers from the binary's API (#2061)

This commit is contained in:
sam committed 2026-11-22 13:54:09 +11:00
1 parent 07d14c8d50
commit 456c08751a
6 files changed
+18 -845

No files matched your search

-394
View File
@@ -1,394 +0,0 @@
<script setup lang="ts">
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { SuggestInput } from "@/components/ui/suggest-input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { computed, onMounted, ref, watch } from "vue";
import { ArrowLeft, Braces, Type } from "@lucide/vue";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Timestamp } from "@/components/ui/timestamp";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { keepRows } from "@/lib/keep-unchanged";
import { useLiveResource } from "@/stores/session";
import { statusKind, statusLabel, takesRepository, type Binding } from "@/bindings/binding-draft";
import type { Capture } from "@/captures/state";
import SourceSecret from "@/sources/SourceSecret.vue";
import { sourceURL, type Source } from "@/sources/source-signing";
import type { EventType } from "@/captures/event-types";
import type { Mapping, Preview } from "@/mappings/state";
import {
bindingInputs,
captureBody,
captureHeaders,
mappingFields,
payloadPaths,
problems,
REPOSITORY_FIELD,
rowsFromBinding,
shortValue,
type InputRow,
} from "./bind-event";
import OptionSelect from "@/components/OptionSelect.vue";
import { declaredSpecs, workflowField } from "./workflow-edit";
const props = defineProps<{ yaml: string; binding: Binding | null }>();
const emit = defineEmits<{ back: []; saved: [] }>();
const NEW_SOURCE = "__new__";
const workflow = computed(() => String(workflowField(props.yaml, "id") ?? ""));
const inputs = computed(() =>
declaredSpecs(props.yaml, "inputs"),
);
const repository = computed(() => takesRepository({ id: "", name: "", repository: String(workflowField(props.yaml, "repository") ?? "") || undefined }));
const sources = ref<string[]>([]);
// The operator's label for each source path, where one is set.
const sourceNames = ref<Record<string, string>>({});
// The placeholder travels as an empty option, which a Select cannot hold: it
// reserves that value for clearing, so OptionSelect carries it as a sentinel.
const sourceOptions = computed(() => [
{ value: "", label: "Pick a source", disabled: true },
...sources.value.map((path) => ({ value: path, label: sourceNames.value[path] ? `${sourceNames.value[path]} (${path})` : path })),
{ value: NEW_SOURCE, label: "New source…" },
]);
const captures = ref<Capture[]>([]);
const eventTypes = ref<EventType[]>([]);
const mappings = ref<Mapping[]>([]);
const bindings = ref<Binding[]>([]);
const loading = ref(true);
// A failed read of the form's data is an error with Retry, not empty pickers.
const loadError = ref("");
// Saving must know whether the bindings list actually loaded: on a failed
// read, sharedMapping() cannot tell, and mappingUpdate must not run.
const bindingsLoaded = ref(false);
const source = ref("");
const newSource = ref("");
const captureId = ref<string | null>(null);
const rows = ref<Record<string, InputRow>>({});
const repositoryPath = ref("");
const preview = ref<Preview | null>(null);
const saving = ref(false);
const confirmRemove = ref(false);
const creatingSource = ref(false);
const revealed = ref<Source | null>(null);
const error = ref("");
const status = ref(props.binding?.status ?? "");
// A failed read keeps the events already shown and says so, rather than
// emptying the list into "No events".
const capturesError = ref("");
async function loadCaptures(): Promise<void> {
try {
const listed = await api.captures<{ captures?: Capture[] }>(100);
captures.value = keepRows(captures.value, listed?.captures ?? []);
capturesError.value = "";
} catch {
capturesError.value = errors.workflows.bindEvent.eventsNotLoaded;
}
}
async function loadAll(): Promise<void> {
loading.value = true;
let readError = "";
const [listed, types, mapped, bound] = await Promise.all([
api.sources<{ sources?: { path: string; name?: string }[] }>().catch((err) => { readError = describeError(err, errors.common.unknown); return null; }),
api.eventTypes<{ event_types?: EventType[] }>().catch((err) => { readError = describeError(err, errors.common.unknown); return null; }),
api.mappings<{ mappings?: Mapping[] }>().catch((err) => { readError = describeError(err, errors.common.unknown); return null; }),
api.bindings<{ bindings?: Binding[] }>().catch((err) => { readError = describeError(err, errors.common.unknown); return null; }),
loadCaptures(),
]);
sources.value = (listed?.sources ?? []).map((s) => s.path);
sourceNames.value = Object.fromEntries((listed?.sources ?? []).filter((s) => s.name).map((s) => [s.path, s.name!]));
eventTypes.value = types?.event_types ?? [];
mappings.value = mapped?.mappings ?? [];
bindings.value = bound?.bindings ?? [];
bindingsLoaded.value = bound !== null;
loadError.value = [listed, types, mapped, bound].some((leg) => leg === null) ? readError || errors.workflows.bindEvent.formNotLoaded : "";
if (props.binding) {
source.value = props.binding.matcher?.source ?? "";
const mapping = mappings.value.find((m) => String(m.id) === props.binding?.mapping_id);
const filled = rowsFromBinding(props.binding, mapping?.fields ?? []);
rows.value = filled.rows;
repositoryPath.value = filled.repositoryPath;
} else if (sources.value.length === 1) {
source.value = sources.value[0]!;
}
for (const [name] of inputs.value) rows.value[name] ??= { from: "path", path: "", value: "" };
loading.value = false;
}
onMounted(loadAll);
useLiveResource("captures", () => void loadCaptures(), 500);
const sourcePath = computed(() => (source.value === NEW_SOURCE ? newSource.value.trim() : source.value));
const hookURL = computed(() => sourceURL(window.location.origin, sourcePath.value));
const sourceCaptures = computed(() => captures.value.filter((c) => c.source === sourcePath.value));
// The newest event of the source is the example until another is picked.
watch(sourceCaptures, (list) => {
if (!list.some((c) => c.id === captureId.value)) captureId.value = list[0]?.id ?? null;
}, { immediate: true });
const capture = computed(() => sourceCaptures.value.find((c) => c.id === captureId.value));
const payload = computed(() => captureBody(capture.value));
const paths = computed(() => payloadPaths(payload.value));
const fields = computed(() => mappingFields(inputs.value, rows.value, repository.value ? repositoryPath.value : ""));
let previewTimer: ReturnType<typeof setTimeout> | undefined;
let previewGeneration = 0;
watch([fields, captureId], () => {
clearTimeout(previewTimer);
if (captureId.value === null || !fields.value.length) {
preview.value = null;
return;
}
const id = captureId.value;
// Only the newest request may land: an older, slower preview would show
// results for fields that have since changed.
const request = ++previewGeneration;
previewTimer = setTimeout(async () => {
const result = await api.mappingPreview<Preview>(id, fields.value).catch(() => null);
if (request === previewGeneration) preview.value = result;
}, 250);
}, { deep: true, immediate: true });
const blockers = computed(() => {
if (!sourcePath.value) return [errors.workflows.bindEvent.blocker.pickSource];
if (source.value === NEW_SOURCE) return [errors.workflows.bindEvent.blocker.createSourceFirst];
if (!capture.value) return [errors.workflows.bindEvent.blocker.noEvent(sourcePath.value)];
if (payload.value === null) return [errors.workflows.bindEvent.blocker.bodyNotJson];
return problems(inputs.value, rows.value, preview.value);
});
function resolved(name: string): { value?: string; failure?: string } {
const failure = preview.value?.failures?.find((f) => f.field_name === name);
if (failure) return { failure: failure.reason };
const values = preview.value?.values ?? {};
return name in values ? { value: shortValue(values[name]) } : {};
}
// A mapping another binding also reads is left as it is: the edit gets its own.
function sharedMapping(id?: string): boolean {
return bindings.value.some((b) => b.mapping_id === id && b.id !== props.binding?.id);
}
// An edit keeps its mapping's event type; a capture that arrived unidentified
// becomes the example of a new one.
async function eventTypeFor(c: Capture): Promise<string> {
const kept = mappings.value.find((m) => String(m.id) === props.binding?.mapping_id)?.event_type_id;
if (kept) return kept;
if (c.event_type) return c.event_type;
const created = await api.eventTypeCreate<EventType>({
source: sourcePath.value,
name: `${sourcePath.value} event`,
example: { headers: captureHeaders(c), body: c.body ?? "" },
});
return created.id;
}
async function createSource(): Promise<void> {
if (!sourcePath.value || creatingSource.value) return;
creatingSource.value = true;
error.value = "";
try {
const created = await api.sourceCreate<Source>(sourcePath.value);
revealed.value = created;
sources.value.push(created.path);
source.value = created.path;
newSource.value = "";
} catch (err) {
error.value = describeError(err, errors.common.unknown);
} finally {
creatingSource.value = false;
}
}
async function save(): Promise<void> {
if (blockers.value.length || !capture.value) return;
// Without the bindings list, sharedMapping() cannot tell whether the
// mapping is shared, and mappingUpdate must not run on it.
if (props.binding?.mapping_id && !bindingsLoaded.value) {
error.value = errors.workflows.bindEvent.bindingsNotLoaded;
return;
}
saving.value = true;
error.value = "";
try {
const mappingBody = {
name: `${workflow.value} ← ${sourcePath.value}`,
event_type_id: await eventTypeFor(capture.value),
fields: fields.value,
};
const existing = props.binding?.mapping_id;
const mapping = existing && !sharedMapping(existing)
? await api.mappingUpdate<Mapping>(existing, mappingBody)
: await api.mappingCreate<Mapping>(mappingBody);
const body = {
name: props.binding?.name || `${sourcePath.value} → ${workflow.value}`,
matcher: { source: sourcePath.value },
mapping_id: String(mapping.id),
filter: props.binding?.filter ?? "",
workflow: workflow.value,
repo_param: repository.value && repositoryPath.value.trim() ? REPOSITORY_FIELD : "",
owner: props.binding?.owner ?? "",
repo: props.binding?.repo ?? "",
inputs: bindingInputs(inputs.value, rows.value),
};
if (props.binding) await api.bindingUpdate(props.binding.id, body);
else await api.bindingCreate(body);
emit("saved");
} catch (err) {
error.value = describeError(err, errors.common.unknown);
} finally {
saving.value = false;
}
}
// transition runs one lifecycle command and shows the status it leads to.
// The server answers with the binding as it now stands; its status is what
// the form shows, not a guess at the next state.
async function transition(command: (id: string) => Promise<unknown>): Promise<void> {
if (!props.binding) return;
error.value = "";
try {
const updated = (await command(props.binding.id)) as { status?: string } | undefined;
if (updated?.status) status.value = updated.status;
emit("saved");
} catch (err) {
error.value = describeError(err, errors.common.unknown);
}
}
async function removeBinding(): Promise<void> {
if (!props.binding) return;
saving.value = true;
error.value = "";
try {
await api.bindingDelete(props.binding.id);
emit("saved");
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
} finally {
saving.value = false;
}
}
const approve = () => transition(api.bindingApprove);
const pause = () => transition(api.bindingPause);
const resume = () => transition(api.bindingResume);
</script>
<template>
<div class="flex h-full flex-col">
<AlertDialog v-model:open="confirmRemove">
<AlertDialogContent><AlertDialogHeader><AlertDialogTitle>Remove event binding?</AlertDialogTitle><AlertDialogDescription>This event will stop starting this workflow. The event source and mapping are kept.</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction @click="removeBinding">Remove binding</AlertDialogAction></AlertDialogFooter></AlertDialogContent>
</AlertDialog>
<header class="flex items-center gap-2 border-b border-border px-4 py-3">
<Button type="button" variant="ghost" size="icon-sm" aria-label="Back to settings" @click="emit('back')"><ArrowLeft /></Button>
<div class="min-w-0 flex-1 truncate text-label font-medium">{{ binding ? binding.name : "Bind an event" }}</div>
<Badge v-if="status" :variant="statusKind(status)">{{ statusLabel(status) }}</Badge>
</header>
<div v-if="loading" class="flex flex-1 items-center justify-center"><Spinner /></div>
<div v-else-if="loadError" class="flex flex-1 flex-col items-center justify-center gap-3 p-4">
<Alert variant="destructive" class="max-w-md"><AlertDescription>{{ loadError }}</AlertDescription></Alert>
<Button type="button" variant="outline" size="sm" @click="loadAll">Retry</Button>
</div>
<form v-else class="flex-1 space-y-5 overflow-y-auto px-4 py-4" @submit.prevent="save">
<section class="space-y-1.5">
<Label for="bind-source" class="text-caption font-medium text-fg-muted">Source</Label>
<OptionSelect id="bind-source" aria-label="Source" :model-value="source" :options="sourceOptions" class="w-full" :disabled="!!binding" @update:model-value="source = $event" />
<Input
v-if="source === NEW_SOURCE"
v-model="newSource"
aria-label="New source path"
placeholder="path, e.g. alertmanager"
class="h-8 w-full font-mono text-label"
/>
<Button v-if="source === NEW_SOURCE" type="button" size="sm" :disabled="creatingSource || !sourcePath" @click="createSource"><Spinner v-if="creatingSource" />Create source</Button>
</section>
<SourceSecret v-if="revealed" :source="revealed" @dismiss="revealed = null" />
<section v-if="sourcePath" class="space-y-1.5">
<Label for="bind-capture" class="text-caption font-medium text-fg-muted">Example event</Label>
<Select v-if="sourceCaptures.length" :model-value="captureId ?? undefined" @update:model-value="captureId = String($event)">
<SelectTrigger id="bind-capture" size="sm" class="w-full" aria-label="Example event"><SelectValue placeholder="Pick an event" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="c in sourceCaptures" :key="c.id" :value="String(c.id)">#{{ c.id }} · <Timestamp :at="c.received_at" absolute />{{ c.event_type ? "" : " · unidentified" }}</SelectItem>
</SelectContent>
</Select>
<p v-else-if="capturesError" class="text-caption text-danger" role="alert">{{ capturesError }}</p>
<p v-else class="text-caption text-fg-subtle" :title="`Send an event to ${hookURL} and it appears here`">No events</p>
</section>
<section class="space-y-1.5">
<div class="text-caption font-medium text-fg-muted">Inputs</div>
<div class="divide-y divide-border rounded-md border border-border">
<div v-for="[name, spec] in inputs" :key="name" class="space-y-1 px-3 py-2">
<div class="flex items-center gap-1.5 text-caption">
<span class="font-mono">{{ name }}</span>
<span class="text-fg-subtle">{{ spec.type ?? "string" }}</span>
<span v-if="spec.required" class="text-danger" title="Required">*</span>
<Button
type="button"
variant="ghost"
size="icon-xs"
class="ml-auto"
:title="rows[name]!.from === 'path' ? 'Use a fixed value' : 'Read from the event'"
:aria-label="`${name}: ${rows[name]!.from === 'path' ? 'use a fixed value' : 'read from the event'}`"
@click="rows[name]!.from = rows[name]!.from === 'path' ? 'value' : 'path'"
>
<Type v-if="rows[name]!.from === 'path'" /><Braces v-else />
</Button>
</div>
<SuggestInput
v-if="rows[name]!.from === 'path'"
v-model="rows[name]!.path"
:options="paths"
:aria-label="`${name} payload path`"
placeholder="payload path"
class="h-8 w-full font-mono text-caption"
/>
<Input
v-else
v-model="rows[name]!.value"
:aria-label="`${name} fixed value`"
placeholder="fixed value"
class="h-8 w-full font-mono text-caption"
/>
<Alert v-if="rows[name]!.from === 'path' && resolved(name).failure" variant="destructive"><AlertDescription>{{ resolved(name).failure }}</AlertDescription></Alert>
<p v-else-if="rows[name]!.from === 'path' && resolved(name).value !== undefined" class="truncate font-mono text-caption text-ok" :title="resolved(name).value">{{ resolved(name).value }}</p>
</div>
<div v-if="repository" class="space-y-1 px-3 py-2">
<div class="text-caption" title="Optional: owner/name of a configured repository; blank uses the configured one">Repository</div>
<SuggestInput
v-model="repositoryPath"
:options="paths"
aria-label="Repository payload path"
placeholder="payload path"
class="h-8 w-full font-mono text-caption"
/>
<Alert v-if="resolved(REPOSITORY_FIELD).failure" variant="destructive"><AlertDescription>{{ resolved(REPOSITORY_FIELD).failure }}</AlertDescription></Alert>
<p v-else-if="resolved(REPOSITORY_FIELD).value !== undefined" class="truncate font-mono text-caption text-ok">{{ resolved(REPOSITORY_FIELD).value }}</p>
</div>
<p v-if="!inputs.length && !repository" class="px-3 py-2 text-caption text-fg-subtle">No inputs.</p>
</div>
</section>
<div class="space-y-2">
<Alert v-if="error" variant="destructive"><AlertDescription>{{ error }}</AlertDescription></Alert>
<p v-else-if="blockers.length" class="text-caption text-fg-subtle">{{ errors.workflows.bindingSave.cannotSave(blockers[0] ?? "") }}</p>
<div class="flex flex-wrap gap-2">
<Button type="submit" size="sm" :disabled="saving || !!blockers.length"><Spinner v-if="saving" />Save binding</Button>
<Button v-if="binding && status === 'pending_approval'" type="button" size="sm" variant="outline" @click="approve">Approve</Button>
<Button v-if="binding && status === 'armed'" type="button" size="sm" variant="outline" @click="pause">Pause</Button>
<Button v-if="binding && status === 'paused'" type="button" size="sm" variant="outline" @click="resume">Resume</Button>
<Button v-if="binding" type="button" size="sm" variant="destructive" :disabled="saving" @click="confirmRemove=true">Remove binding</Button>
</div>
</div>
</form>
</div>
</template>
-226
View File
@@ -1,226 +0,0 @@
<script setup lang="ts">
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Label } from "@/components/ui/label";
import { computed, onMounted, ref } from "vue";
import { ArrowLeft } from "@lucide/vue";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { constantValue, statusKind, statusLabel, type Binding, type InputSource } from "@/bindings/binding-draft";
import ScheduleEditor from "@/schedules/ScheduleEditor.vue";
import { blankSchedule, type Schedule } from "@/schedules/schedule";
import OptionSelect from "@/components/OptionSelect.vue";
import { declaredSpecs, workflowField } from "./workflow-edit";
import { SCHEDULE_FIELDS, SCHEDULE_MAPPING, SCHEDULE_SOURCE, scheduleFilter, scheduleOfBinding } from "./workflow-triggers";
/**
* A schedule trigger: a binding on the schedule source filtered to one
* schedule, each workflow input read from the firing or given a fixed value.
*/
const props = defineProps<{ yaml: string; binding: Binding | null }>();
const emit = defineEmits<{ back: []; saved: [] }>();
const NEW = "__new__";
const FIXED = "__fixed__";
const workflow = computed(() => String(workflowField(props.yaml, "id") ?? ""));
const inputs = computed(() =>
declaredSpecs(props.yaml, "inputs"),
);
const schedules = ref<Schedule[]>([]);
const loading = ref(true);
const loadError = ref("");
const scheduleId = ref(props.binding ? scheduleOfBinding(props.binding) : "");
const rows = ref<Record<string, { from: string; value: string }>>({});
const status = ref(props.binding?.status ?? "");
const saving = ref(false);
const error = ref("");
const confirmRemove = ref(false);
onMounted(async () => {
try {
schedules.value = (await api.schedules<{ schedules?: Schedule[] }>()).schedules ?? [];
} catch (err) {
loadError.value = describeError(err, errors.common.unknown);
}
for (const [name] of inputs.value) {
const src = props.binding?.inputs?.[name];
rows.value[name] = src?.param
? { from: src.param, value: "" }
: src && src.value !== undefined
? { from: FIXED, value: typeof src.value === "string" ? src.value : JSON.stringify(src.value) }
: { from: FIXED, value: "" };
}
loading.value = false;
});
const scheduleOptions = computed(() => [
{ value: "", label: "Pick a schedule", disabled: true },
...schedules.value.map((s) => ({ value: s.id, label: s.name })),
{ value: NEW, label: "New schedule…" },
]);
const fieldOptions = [
...SCHEDULE_FIELDS.map((field) => ({ value: field, label: field })),
{ value: FIXED, label: "Fixed value" },
];
// Creating a schedule here writes the same record the Schedules page lists.
const editorOpen = ref(false);
const draft = ref<Schedule | null>(null);
function pickSchedule(value: string): void {
if (value !== NEW) {
scheduleId.value = value;
return;
}
draft.value = { ...blankSchedule(), name: workflow.value };
editorOpen.value = true;
}
function created(schedule: Schedule): void {
schedules.value.push(schedule);
scheduleId.value = schedule.id;
}
const schedule = computed(() => schedules.value.find((s) => s.id === scheduleId.value));
const blockers = computed(() => {
if (!scheduleId.value) return [errors.workflows.scheduleTrigger.pickSchedule];
return inputs.value
.filter(([name, spec]) => spec.required && rows.value[name]?.from === FIXED && rows.value[name]?.value === "")
.map(([name]) => errors.workflows.bindingSave.inputRequired(name));
});
function bindingInputs(): Record<string, InputSource> {
const out: Record<string, InputSource> = {};
for (const [name, spec] of inputs.value) {
const row = rows.value[name];
if (!row) continue;
if (row.from !== FIXED) out[name] = { param: row.from };
else if (row.value !== "") out[name] = { value: constantValue(row.value, spec.type ?? "string") };
}
return out;
}
async function save(): Promise<void> {
if (blockers.value.length) return;
saving.value = true;
error.value = "";
try {
const body = {
name: `${schedule.value?.name ?? scheduleId.value} → ${workflow.value}`,
matcher: { source: SCHEDULE_SOURCE },
mapping_id: SCHEDULE_MAPPING,
filter: scheduleFilter(scheduleId.value),
workflow: workflow.value,
repo_param: "",
owner: props.binding?.owner ?? "",
repo: props.binding?.repo ?? "",
inputs: bindingInputs(),
};
if (props.binding) await api.bindingUpdate(props.binding.id, body);
else await api.bindingCreate(body);
emit("saved");
} catch (err) {
error.value = describeError(err, errors.common.unknown);
} finally {
saving.value = false;
}
}
// The server answers with the binding as it now stands; its status is what
// the form shows, not a guess at the next state.
async function transition(command: (id: string) => Promise<unknown>): Promise<void> {
if (!props.binding) return;
error.value = "";
try {
const updated = (await command(props.binding.id)) as { status?: string } | undefined;
if (updated?.status) status.value = updated.status;
emit("saved");
} catch (err) {
error.value = describeError(err, errors.common.unknown);
}
}
async function remove(): Promise<void> {
if (!props.binding) return;
try {
await api.bindingDelete(props.binding.id);
emit("saved");
} catch (err) {
error.value = describeError(err, errors.common.unknown);
}
}
</script>
<template>
<div class="flex h-full flex-col">
<AlertDialog v-model:open="confirmRemove">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove schedule trigger?</AlertDialogTitle>
<AlertDialogDescription>The schedule keeps running; it stops starting this workflow.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="remove">Remove trigger</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<header class="flex items-center gap-2 border-b border-border px-4 py-3">
<Button type="button" variant="ghost" size="icon-sm" aria-label="Back to settings" @click="emit('back')"><ArrowLeft /></Button>
<div class="min-w-0 flex-1 truncate text-label font-medium">{{ schedule?.name ?? "Add a schedule" }}</div>
<Badge v-if="status" :variant="statusKind(status)">{{ statusLabel(status) }}</Badge>
</header>
<div v-if="loading" class="flex flex-1 items-center justify-center"><Spinner /></div>
<form v-else class="flex-1 space-y-5 overflow-y-auto px-4 py-4" @submit.prevent="save">
<section class="space-y-1.5">
<Label for="schedule-trigger" class="text-caption font-medium text-fg-muted">Schedule</Label>
<Alert v-if="loadError" variant="destructive"><AlertDescription>{{ loadError }}</AlertDescription></Alert>
<OptionSelect v-else id="schedule-trigger" aria-label="Schedule" :model-value="scheduleId" :options="scheduleOptions" class="w-full" @update:model-value="pickSchedule" />
</section>
<section class="space-y-1.5">
<div class="text-caption font-medium text-fg-muted">Inputs</div>
<div class="divide-y divide-border rounded-md border border-border">
<div v-for="[name, spec] in inputs" :key="name" class="space-y-1 px-3 py-2">
<div class="flex items-center gap-1.5 text-caption">
<span class="font-mono">{{ name }}</span>
<span class="text-fg-subtle">{{ spec.type ?? "string" }}</span>
<span v-if="spec.required" class="text-danger" title="Required">*</span>
</div>
<OptionSelect :aria-label="`${name} source`" :model-value="rows[name]!.from" :options="fieldOptions" class="w-full" @update:model-value="rows[name]!.from = $event" />
<Input v-if="rows[name]!.from === FIXED" v-model="rows[name]!.value" :aria-label="`${name} fixed value`" placeholder="fixed value" class="h-8 w-full font-mono text-caption" />
</div>
<Empty v-if="!inputs.length"><EmptyHeader><EmptyTitle>No inputs.</EmptyTitle></EmptyHeader></Empty>
</div>
</section>
<div class="space-y-2">
<Alert v-if="error" variant="destructive"><AlertDescription>{{ error }}</AlertDescription></Alert>
<p v-else-if="blockers.length" class="text-caption text-fg-subtle">{{ errors.workflows.bindingSave.cannotSave(blockers[0] ?? "") }}</p>
<div class="flex flex-wrap gap-2">
<Button type="submit" size="sm" :disabled="saving || !!blockers.length"><Spinner v-if="saving" />Save trigger</Button>
<Button v-if="binding && status === 'pending_approval'" type="button" size="sm" variant="outline" @click="transition(api.bindingApprove)">Approve</Button>
<Button v-if="binding && status === 'armed'" type="button" size="sm" variant="outline" @click="transition(api.bindingPause)">Pause</Button>
<Button v-if="binding && status === 'paused'" type="button" size="sm" variant="outline" @click="transition(api.bindingResume)">Resume</Button>
<Button v-if="binding" type="button" size="sm" variant="destructive" @click="confirmRemove = true">Remove trigger</Button>
</div>
</div>
</form>
<ScheduleEditor v-model:open="editorOpen" :schedule="draft" title="New schedule" @saved="created" />
</div>
</template>
+2 -5
View File
@@ -2,7 +2,7 @@
import { stageStatusMeta } from "@/tasks/stage-rail";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { Handle, Position } from "@vue-flow/core";
import { CircleAlert, CircleCheck, CircleMinus, CircleX, EllipsisVertical, Flag, LoaderCircle, Play, Repeat, Settings2, SkipForward, Tag, Workflow, Zap, BookOpen, CalendarClock } from "@lucide/vue";
import { CircleAlert, CircleCheck, CircleMinus, CircleX, EllipsisVertical, Flag, LoaderCircle, Play, Repeat, Settings2, SkipForward, Zap, CalendarClock } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -29,11 +29,8 @@ export interface StepCardData extends StepNodeData {
const props = defineProps<{ data: StepCardData }>();
const TRIGGER_KINDS = {
issue: { icon: Tag, label: "Issue route" },
event: { icon: Zap, label: "Event binding" },
event: { icon: Zap, label: "Event trigger" },
schedule: { icon: CalendarClock, label: "Schedule" },
playbook: { icon: BookOpen, label: "Playbook" },
workflow: { icon: Workflow, label: "Workflow" },
} as const;
const STATE_CLASSES: Record<string, string> = {
-64
View File
@@ -1,64 +0,0 @@
<script setup lang="ts">
import { ref } from "vue";
import { CalendarClock, Plus } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { statusKind, statusLabel, type Binding } from "@/bindings/binding-draft";
import BindEvent from "./BindEvent.vue";
import ScheduleTrigger from "./ScheduleTrigger.vue";
import SpecList from "./SpecList.vue";
import type { WorkflowTrigger } from "./workflow-triggers";
defineProps<{ yaml: string; triggers: WorkflowTrigger[]; error?: string }>();
const emit = defineEmits<{ "update:yaml": [string]; bound: []; reload: [] }>();
// The bind flow takes over the card; a null binding is a new one.
const binding = ref<Binding | null | undefined>();
const scheduled = ref<Binding | null | undefined>();
function bound(): void {
binding.value = undefined;
scheduled.value = undefined;
emit("bound");
}
function open(trigger: WorkflowTrigger): void {
if (trigger.kind === "schedule") scheduled.value = trigger.binding;
else binding.value = trigger.binding;
}
</script>
<template>
<BindEvent v-if="binding !== undefined" :yaml="yaml" :binding="binding" @back="binding = undefined" @saved="bound" />
<ScheduleTrigger v-else-if="scheduled !== undefined" :yaml="yaml" :binding="scheduled" @back="scheduled = undefined" @saved="bound" />
<div v-else class="space-y-4 px-3 py-3">
<section class="space-y-1.5">
<div class="flex justify-end">
<Button type="button" variant="ghost" size="xs" @click="scheduled = null"><CalendarClock data-icon="inline-start" />Add a schedule</Button>
<Button type="button" variant="ghost" size="xs" @click="binding = null"><Plus data-icon="inline-start" />Bind an event</Button>
</div>
<ul v-if="triggers.length" class="divide-y divide-border rounded-md border border-border">
<li v-for="trigger in triggers" :key="trigger.kind + trigger.label" class="text-label">
<Button v-if="trigger.binding" type="button" variant="ghost" class="h-auto w-full justify-start gap-2 rounded-none px-3 py-2 text-label font-normal" @click="open(trigger)">
<span class="truncate">{{ trigger.label }}</span>
<Badge v-if="trigger.binding.status !== 'armed'" :variant="statusKind(trigger.binding.status)">{{ statusLabel(trigger.binding.status) }}</Badge>
<span v-if="trigger.detail" class="ml-auto truncate text-caption text-fg-subtle">{{ trigger.detail }}</span>
</Button>
<RouterLink v-else-if="trigger.kind === 'workflow' || trigger.kind === 'playbook'" :to="trigger.kind === 'workflow' ? { name: 'workflow', params: { id: trigger.label } } : { path: '/org/playbooks' }" class="flex items-center gap-2 px-3 py-2 hover:bg-secondary">
<span class="truncate">{{ trigger.label }}</span><span class="ml-auto truncate text-caption text-fg-subtle">{{ trigger.detail }}</span>
</RouterLink>
<div v-else class="flex items-center gap-2 px-3 py-2">
<span class="truncate">{{ trigger.label }}</span>
<Badge v-if="trigger.kind === 'issue'" variant="outline" class="ml-auto">Built-in</Badge>
<span v-if="trigger.detail" class="ml-auto truncate text-caption text-fg-subtle">{{ trigger.detail }}</span>
</div>
</li>
</ul>
<div v-if="error" class="flex items-center gap-2 text-caption text-danger" role="alert">
{{ error }}
<Button variant="link" size="xs" class="px-0" @click="emit('reload')">Retry</Button>
</div>
<p v-else-if="!triggers.length" class="text-caption text-fg-subtle">Manual runs only.</p>
</section>
<SpecList :yaml="yaml" field="inputs" @update:yaml="emit('update:yaml', $event)" />
</div>
</template>
+7 -5
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { toast } from "vue-sonner";
@@ -14,7 +14,7 @@ import { usePoll, useRead } from "@/lib/use-read";
import { useWorkflowsStore } from "@/stores/workflows";
import WorkflowEditor from "./WorkflowEditor.vue";
import { startedBy } from "./use-workflow-list";
import type { WorkflowTrigger } from "./workflow-triggers";
import { workflowTriggers } from "./workflow-triggers";
/** One workflow on the canvas: edited as a draft, published as a version, and
* watched while it runs. */
@@ -52,14 +52,16 @@ const draft = computed(() => workflows.drafts.some((d) => d.id === selected.valu
// A workflow just created has no draft until its first edit is saved.
const known = computed(() => !!stored.value || draft.value || route.query.new !== undefined);
const loaded = computed(() => !!workflows.state.resource);
// A workflow that was open and is gone has been deleted: back to the list.
watch(known, (now, was) => {
if (was && !now) selected.value = "";
});
const own = computed(() => (triggers.data.value ?? []).filter((t) => t.workflow === selected.value));
const starts = computed(() => [...new Set(own.value.map(startedBy))]);
const startsText = computed(() => starts.value[0] ?? (triggers.data.value ? "Manual" : ""));
const startsMore = computed(() => starts.value.slice(1));
const canvasTriggers = computed<WorkflowTrigger[]>(() =>
own.value.map((t) => ({ kind: t.every ? "schedule" : "event", label: t.every ? startedBy(t) : t.name, detail: t.every ? undefined : startedBy(t) })),
);
const canvasTriggers = computed(() => workflowTriggers(triggers.data.value ?? [], selected.value));
async function setEnabled(enabled: boolean): Promise<void> {
try {
+9 -151
View File
@@ -1,158 +1,16 @@
import { computed, onMounted, ref, type Ref } from "vue";
import { parse } from "yaml";
import type { Trigger } from "@/lib/api";
import { startedBy } from "./use-workflow-list";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { useSettingsStore } from "@/stores/settings";
import type { Binding } from "@/bindings/binding-draft";
/** One way a workflow gets started. */
/** One way a workflow gets started, as the canvas's start card lists it. */
export interface WorkflowTrigger {
kind: "issue" | "event" | "schedule" | "playbook" | "workflow";
kind: "event" | "schedule";
label: string;
detail?: string;
/** The event binding this trigger is, for editing it. */
binding?: Binding;
}
export interface TriggerSources {
/** The issue routing setting. */
routes: { rules: { label: string; workflow: string }[]; default: string };
bindings: Binding[];
playbooks: { id: string; yaml: string }[];
/** The workflows that start this one, as the server works them out. */
startedBy: { workflow: string; via: string }[];
/** Schedules by id, to name schedule triggers. */
schedules: { id: string; name: string }[];
}
/** The reserved source a schedule's firings are captured on, and the
* built-in mapping that hands a binding the firing's fields. */
export const SCHEDULE_SOURCE = "schedule";
export const SCHEDULE_MAPPING = "schedule-fired";
export const SCHEDULE_FIELDS = ["schedule_id", "name", "scheduled_for", "fired_at"] as const;
/** The binding filter that admits only the firings of one schedule. */
export function scheduleFilter(id: string): string {
return `schedule_id == ${JSON.stringify(id)}`;
}
/** The schedule a schedule trigger's filter names, or "". */
export function scheduleOfBinding(binding: Binding): string {
const match = /^schedule_id == ("(?:[^"\\]|\\.)*")$/.exec(binding.filter?.trim() ?? "");
if (!match) return "";
try {
return JSON.parse(match[1]!) as string;
} catch {
return "";
}
}
type Mapping = Record<string, unknown>;
function isMapping(value: unknown): value is Mapping {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parseQuietly(source: string): unknown {
try {
return parse(source);
} catch {
return null;
}
}
/** Everything that starts the workflow named id. */
function triggersFor(id: string, sources: TriggerSources): WorkflowTrigger[] {
const triggers: WorkflowTrigger[] = [];
for (const rule of sources.routes.rules) {
if (rule.workflow === id) triggers.push({ kind: "issue", label: `Issues labelled ${rule.label}` });
}
if (sources.routes.default === id) triggers.push({ kind: "issue", label: "Other issues" });
for (const binding of sources.bindings) {
if (binding.workflow !== id) continue;
if (binding.matcher?.source === SCHEDULE_SOURCE) {
const scheduleId = scheduleOfBinding(binding);
const schedule = sources.schedules.find((s) => s.id === scheduleId);
triggers.push({ kind: "schedule", label: schedule?.name ?? (scheduleId || "Schedule"), binding });
continue;
}
triggers.push({ kind: "event", label: binding.name || "Event binding", detail: binding.matcher?.source, binding });
}
for (const playbook of sources.playbooks) {
const value = parseQuietly(playbook.yaml);
if (!isMapping(value) || !Array.isArray(value.actions)) continue;
if (!value.actions.some((action) => isMapping(action) && action.workflow === id)) continue;
const trigger = isMapping(value.trigger) ? value.trigger : {};
const labels = Array.isArray(trigger.labels) ? trigger.labels.join(", ") : "";
triggers.push({ kind: "playbook", label: playbook.id, detail: labels });
}
for (const starter of sources.startedBy) {
triggers.push({ kind: "workflow", label: starter.workflow, detail: STARTED_VIA[starter.via] ?? starter.via });
}
return triggers;
}
// The words for the server's start kinds.
const ROUTES = "intake-routes";
const STARTED_VIA: Record<string, string> = { call: "calls it", handoff: "hands off to it", approve: "runs it once approved" };
/** What starts the workflow, in a line: the first trigger, and how many more. */
export function triggerSummary(triggers: WorkflowTrigger[]): { text: string; more: string[] } {
const words = (t: WorkflowTrigger) => {
switch (t.kind) {
case "workflow": return `From ${t.label}`;
case "schedule": return `Schedule ${t.label}`;
case "playbook": return t.detail ? `${t.label}: ${t.detail}` : t.label;
default: return t.label;
}
};
const [first, ...rest] = triggers;
return { text: first ? words(first) : "", more: rest.map(words) };
}
/** Every trigger source the control plane serves, read once, so a list of
* workflows asks for them once rather than per row. */
export function useTriggerSources(startedByOf: (id: string) => { workflow: string; via: string }[]) {
const store = useSettingsStore();
const bindings = ref<TriggerSources["bindings"]>([]);
const schedules = ref<TriggerSources["schedules"]>([]);
// A failed read is an error, not an empty trigger list: "Manual runs only"
// would be a lie while the server is unreachable.
const error = ref("");
const known = ref(false);
async function reload(): Promise<void> {
let readError = "";
const [response, listed] = await Promise.all([
api.bindings<{ bindings?: Binding[] }>().catch((err) => { readError = describeError(err, errors.common.unknown); return null; }),
api.schedules<{ schedules?: TriggerSources["schedules"] }>().catch((err) => { readError = describeError(err, errors.common.unknown); return null; }),
// Playbook triggers come from that resource; it is read here rather
// than trusting another page to have loaded it.
store.stateFor("eda-playbooks").resource ? null : store.loadResource("eda-playbooks").catch(() => null),
store.stateFor(ROUTES).resource ? null : store.loadResource(ROUTES).catch(() => null),
]);
// A failed read keeps what was shown, beside the error.
if (response) bindings.value = response.bindings ?? [];
if (listed) schedules.value = listed.schedules ?? [];
error.value = response === null || listed === null ? readError || errors.workflows.triggers.notLoaded : "";
known.value = known.value || (response !== null && listed !== null);
}
onMounted(reload);
const triggersOf = (id: string): WorkflowTrigger[] =>
triggersFor(id, {
routes: (store.stateFor(ROUTES).resource?.value as TriggerSources["routes"] | undefined) ?? { rules: [], default: "" },
bindings: bindings.value,
playbooks: (store.stateFor("eda-playbooks").resource?.value as { playbooks?: TriggerSources["playbooks"] } | undefined)?.playbooks ?? [],
startedBy: startedByOf(id),
schedules: schedules.value,
});
return { triggersOf, reload, error, known };
}
/** The triggers of the workflow named id. */
export function useWorkflowTriggers(id: Ref<string>, startedBy: Readonly<Ref<{ workflow: string; via: string }[]>>) {
const { triggersOf, reload, error } = useTriggerSources(() => startedBy.value);
const triggers = computed(() => triggersOf(id.value));
return { triggers, reload, error };
/** The triggers that start a workflow. */
export function workflowTriggers(triggers: Trigger[], workflow: string): WorkflowTrigger[] {
return triggers
.filter((t) => t.workflow === workflow)
.map((t) => ({ kind: t.every ? "schedule" : "event", label: t.every ? startedBy(t) : t.name, detail: t.every ? undefined : startedBy(t) }));
}