feat(ui): schedules table, runs page and Schedule trigger
Schedules list as a table with enable, run now, edit, duplicate, delete and view runs; built-ins only enable, retime and run. The runs page links each run's tasks through its capture's dispatches. The Start node gains a Schedule trigger that picks or creates a schedule and binds the schedule source to the workflow. Times show in a per-browser display zone set under Appearance; the cron time zone and run retention are edited on the Schedules page.
This commit is contained in:
1 parent
12dd3084e5
commit
d4e563a19c
52 files changed
+1425
-131
No files matched your search
@@ -1,23 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { ago } from "@/lib/format";
|
||||
import { ago, exactTime } from "@/lib/format";
|
||||
import { useAppearanceStore } from "@/stores/appearance";
|
||||
|
||||
/**
|
||||
* A point in time, shown relative ("5 mins ago") with the exact local date and
|
||||
* time on hover. `absolute` shows the exact time instead, for logs.
|
||||
* A point in time, shown relative ("5 mins ago") with the exact date and time
|
||||
* on hover, in the zone chosen under Appearance. `absolute` shows the exact
|
||||
* time instead, for logs.
|
||||
*/
|
||||
const props = defineProps<{ at: string | number | Date | null | undefined; absolute?: boolean }>();
|
||||
const appearance = useAppearanceStore();
|
||||
|
||||
const date = computed(() => {
|
||||
if (!props.at) return undefined;
|
||||
const value = props.at instanceof Date ? props.at : new Date(props.at);
|
||||
return Number.isNaN(value.getTime()) || value.getFullYear() <= 1 ? undefined : value;
|
||||
});
|
||||
const exact = computed(() => (date.value ? exactTime(date.value, appearance.timeZone) : ""));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<time v-if="date" :datetime="date.toISOString()" :title="date.toLocaleString()" class="tabular-nums">{{
|
||||
absolute ? date.toLocaleString() : ago(date)
|
||||
<time v-if="date" :datetime="date.toISOString()" :title="exact" class="tabular-nums">{{
|
||||
absolute ? exact : ago(date)
|
||||
}}</time>
|
||||
<span v-else aria-label="Unknown">–</span>
|
||||
</template>
|
||||
@@ -0,0 +1,47 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import { ChevronsUpDown } from "@lucide/vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
|
||||
/**
|
||||
* A searchable IANA time zone picker. With `emptyLabel`, the empty value is
|
||||
* offered first under that label.
|
||||
*/
|
||||
const props = defineProps<{ id?: string; emptyLabel?: string; ariaLabel?: string }>();
|
||||
const model = defineModel<string>({ required: true });
|
||||
|
||||
const open = ref(false);
|
||||
const zones = computed(() => {
|
||||
const listed = Intl.supportedValuesOf("timeZone");
|
||||
return listed.includes("UTC") ? listed : ["UTC", ...listed];
|
||||
});
|
||||
const label = computed(() => model.value || props.emptyLabel || "UTC");
|
||||
|
||||
function choose(value: string): void {
|
||||
model.value = value;
|
||||
open.value = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Popover v-model:open="open">
|
||||
<PopoverTrigger as-child>
|
||||
<Button :id="id" type="button" variant="outline" class="w-64 justify-between font-normal" :aria-label="ariaLabel" role="combobox" :aria-expanded="open">
|
||||
<span class="truncate">{{ label }}</span><ChevronsUpDown data-icon="inline-end" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" class="w-64 p-0">
|
||||
<Command>
|
||||
<CommandInput placeholder="Search zones" />
|
||||
<CommandList>
|
||||
<CommandEmpty>No zone matches.</CommandEmpty>
|
||||
<CommandItem v-if="emptyLabel" value="" @select="choose('')">{{ emptyLabel }}</CommandItem>
|
||||
<CommandItem v-for="zone in zones" :key="zone" :value="zone" @select="choose(zone)">{{ zone }}</CommandItem>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</template>
|
||||
@@ -0,0 +1 @@
|
||||
export { default as ZoneSelect } from "./ZoneSelect.vue";
|
||||
@@ -179,6 +179,16 @@ export const api = {
|
||||
request<{ version: number }>("/api/access/policies", { method: "PUT", body: policy }),
|
||||
deletePolicy: (policy: unknown) =>
|
||||
request<void>("/api/access/policies", { method: "DELETE", body: policy, parse: false }),
|
||||
schedules: <T = unknown>() => request<T>("/api/schedules"),
|
||||
// scheduleSave creates or replaces the schedule with this id.
|
||||
scheduleSave: <T = unknown>(id: string, schedule: unknown) =>
|
||||
request<T>(`/api/schedules/${encodeURIComponent(id)}`, { method: "PUT", body: schedule }),
|
||||
scheduleDelete: (id: string) =>
|
||||
request<void>(`/api/schedules/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
|
||||
scheduleRunNow: <T = unknown>(id: string) =>
|
||||
request<T>(`/api/schedules/${encodeURIComponent(id)}/runs`, { method: "POST", body: {} }),
|
||||
scheduleRuns: <T = unknown>(id: string) =>
|
||||
request<T>(`/api/schedules/${encodeURIComponent(id)}/runs`),
|
||||
orgs: <T = unknown>() => request<T>("/api/orgs"),
|
||||
// orgCreate makes an org with its default workspace and first owner; only
|
||||
// an instance admin may.
|
||||
|
||||
@@ -33,3 +33,8 @@ export function compact(n: number | null | undefined): string {
|
||||
maximumFractionDigits: 1,
|
||||
}).format(n);
|
||||
}
|
||||
|
||||
/** An exact date and time in zone, or in the browser's zone when zone is empty. */
|
||||
export function exactTime(value: Date, zone: string): string {
|
||||
return value.toLocaleString(undefined, zone ? { timeZone: zone, timeZoneName: "short" } : undefined);
|
||||
}
|
||||
+1
-1
@@ -41,7 +41,7 @@ const orgSpecs: NavSpec[] = [
|
||||
},
|
||||
{
|
||||
label: "Automation",
|
||||
paths: ["/org/playbooks"],
|
||||
paths: ["/org/schedules", "/org/playbooks"],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -16,7 +16,7 @@ const areas = [
|
||||
{ title: "Execution identities", to: "/org/agents" },
|
||||
{ title: "Connections", to: "/org/connections" },
|
||||
{ title: "Models", to: "/org/models" },
|
||||
{ title: "Playbooks", to: "/org/playbooks" },
|
||||
{ title: "Schedules and playbooks", to: "/org/schedules" },
|
||||
{ title: "Members and access", to: "/org/members" },
|
||||
];
|
||||
</script>
|
||||
|
||||
@@ -251,6 +251,18 @@ const routes = [
|
||||
component: InstructionsPage,
|
||||
meta: { label: "Instructions", navPath: "/org" },
|
||||
},
|
||||
{
|
||||
path: "schedules",
|
||||
name: "org-schedules",
|
||||
component: () => import("@/schedules/SchedulesPage.vue"),
|
||||
meta: { label: "Schedules", navPath: "/org" },
|
||||
},
|
||||
{
|
||||
path: "schedules/:id/runs",
|
||||
name: "org-schedule-runs",
|
||||
component: () => import("@/schedules/ScheduleRunsPage.vue"),
|
||||
meta: { label: "Schedule runs", navPath: "/org/schedules", nav: false },
|
||||
},
|
||||
{
|
||||
path: "playbooks",
|
||||
name: "org-playbooks",
|
||||
@@ -276,6 +288,7 @@ const routes = [
|
||||
"/settings/credential-bindings": "/org/credential-bindings",
|
||||
"/settings/soul": "/org/instructions",
|
||||
"/org/soul": "/org/instructions",
|
||||
"/settings/schedules": "/org/schedules",
|
||||
"/settings/playbooks": "/org/playbooks",
|
||||
}).map(([path, redirect]) => ({ path, redirect, meta: { nav: false } })),
|
||||
{
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { DurationInput } from "@/components/ui/duration-input";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { SettingRow } from "@/components/ui/setting-row";
|
||||
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
|
||||
import { api } from "@/lib/api";
|
||||
import { useAppearanceStore } from "@/stores/appearance";
|
||||
import { cronWords, fromWallTime, toWallTime, type Schedule, type ScheduleTiming } from "./schedule";
|
||||
|
||||
/**
|
||||
* Creates or edits one schedule. A built-in schedule keeps its name; only its
|
||||
* timing changes here.
|
||||
*/
|
||||
const props = defineProps<{ schedule: Schedule | null; title: string }>();
|
||||
const open = defineModel<boolean>("open", { required: true });
|
||||
const emit = defineEmits<{ saved: [Schedule] }>();
|
||||
|
||||
const appearance = useAppearanceStore();
|
||||
const name = ref("");
|
||||
const timing = ref<ScheduleTiming>({ kind: "interval", interval: "24h0m0s" });
|
||||
const saving = ref(false);
|
||||
const error = ref("");
|
||||
|
||||
watch(
|
||||
() => [open.value, props.schedule] as const,
|
||||
([isOpen, schedule]) => {
|
||||
if (!isOpen || !schedule) return;
|
||||
name.value = schedule.name;
|
||||
timing.value = { ...schedule.timing };
|
||||
error.value = "";
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const kinds = [
|
||||
{ value: "interval", label: "Every" },
|
||||
{ value: "cron", label: "Cron" },
|
||||
{ value: "once", label: "Once" },
|
||||
] as const;
|
||||
|
||||
function chooseKind(value: unknown): void {
|
||||
if (value === "interval") timing.value = { kind: "interval", interval: "24h0m0s" };
|
||||
else if (value === "cron") timing.value = { kind: "cron", cron: "0 9 * * 1-5" };
|
||||
else if (value === "once") timing.value = { kind: "once" };
|
||||
}
|
||||
|
||||
const wallTime = computed({
|
||||
get: () => toWallTime(timing.value.at, appearance.timeZone),
|
||||
set: (value: string) => (timing.value.at = fromWallTime(value, appearance.timeZone)),
|
||||
});
|
||||
const cronPreview = computed(() => {
|
||||
const words = cronWords(timing.value.cron);
|
||||
return words === timing.value.cron ? "" : words;
|
||||
});
|
||||
|
||||
async function save(): Promise<void> {
|
||||
if (!props.schedule) return;
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const saved = await api.scheduleSave<Schedule>(props.schedule.id, {
|
||||
...props.schedule,
|
||||
name: name.value.trim(),
|
||||
timing: timing.value,
|
||||
});
|
||||
emit("saved", saved);
|
||||
open.value = false;
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<DialogContent class="sm:max-w-xl">
|
||||
<DialogHeader><DialogTitle>{{ title }}</DialogTitle></DialogHeader>
|
||||
<form v-if="schedule" class="space-y-1" @submit.prevent="save">
|
||||
<SettingRow label="Name" for="schedule-name">
|
||||
<Input id="schedule-name" v-model="name" :disabled="schedule.built_in" required />
|
||||
</SettingRow>
|
||||
<SettingRow label="When">
|
||||
<div class="flex flex-col gap-3">
|
||||
<ToggleGroup type="single" variant="outline" size="sm" :model-value="timing.kind" aria-label="When" @update:model-value="chooseKind">
|
||||
<ToggleGroupItem v-for="option in kinds" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
<DurationInput v-if="timing.kind === 'interval'" v-model="timing.interval!" :units="['m', 'h']" />
|
||||
<div v-else-if="timing.kind === 'cron'" class="space-y-1">
|
||||
<Input v-model="timing.cron" class="w-48 font-mono" placeholder="0 9 * * 1-5" aria-label="Cron expression" />
|
||||
<p v-if="cronPreview" class="text-caption text-fg-muted">{{ cronPreview }}</p>
|
||||
</div>
|
||||
<Input v-else v-model="wallTime" type="datetime-local" class="w-60 font-mono" aria-label="Run at" required />
|
||||
</div>
|
||||
</SettingRow>
|
||||
<p v-if="error" class="text-sm text-danger" role="alert">{{ error }}</p>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="ghost" @click="open = false">Cancel</Button>
|
||||
<Button type="submit" :disabled="saving || !name.trim()">Save</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,96 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onUnmounted, ref, watch } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { ArrowLeft, Play } from "@lucide/vue";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { api } from "@/lib/api";
|
||||
import { RESULT_TONE, runDuration, type Schedule, type ScheduleRun } from "./schedule";
|
||||
|
||||
const route = useRoute();
|
||||
const id = computed(() => String(route.params.id ?? ""));
|
||||
|
||||
const schedule = ref<Schedule | null>(null);
|
||||
const runs = ref<ScheduleRun[] | null>(null);
|
||||
const error = ref("");
|
||||
|
||||
async function load(): Promise<void> {
|
||||
const target = id.value;
|
||||
try {
|
||||
const [listed, history] = await Promise.all([
|
||||
api.schedules<{ schedules?: Schedule[] }>(),
|
||||
api.scheduleRuns<{ runs?: ScheduleRun[] }>(target),
|
||||
]);
|
||||
if (target !== id.value) return;
|
||||
schedule.value = listed.schedules?.find((s) => s.id === target) ?? null;
|
||||
runs.value = history.runs ?? [];
|
||||
error.value = "";
|
||||
} catch (err) {
|
||||
if (target === id.value) error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
}
|
||||
watch(id, () => {
|
||||
runs.value = null;
|
||||
void load();
|
||||
}, { immediate: true });
|
||||
const timer = setInterval(() => void load(), 15_000);
|
||||
onUnmounted(() => clearInterval(timer));
|
||||
|
||||
async function runNow(): Promise<void> {
|
||||
error.value = "";
|
||||
try {
|
||||
await api.scheduleRunNow(id.value);
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
}
|
||||
|
||||
const columns: DataTableColumn<ScheduleRun>[] = [
|
||||
{ id: "scheduled", label: "Scheduled", fixed: true, sort: (r) => r.scheduled_for },
|
||||
{ id: "started", label: "Started" },
|
||||
{ id: "duration", label: "Duration" },
|
||||
{ id: "result", label: "Result", sort: (r) => r.result },
|
||||
{ id: "error", label: "Error" },
|
||||
{ id: "tasks", label: "Tasks" },
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader :title="schedule?.name || 'Schedule runs'">
|
||||
<Button variant="ghost" size="sm" as-child><RouterLink to="/org/schedules"><ArrowLeft data-icon="inline-start" />Schedules</RouterLink></Button>
|
||||
<Button size="sm" :disabled="!schedule" @click="runNow"><Play data-icon="inline-start" />Run now</Button>
|
||||
</PageHeader>
|
||||
<p v-if="error" class="mb-4 text-sm text-danger" role="alert">{{ error }}</p>
|
||||
<Section>
|
||||
<div v-if="!runs && !error" class="space-y-2"><Skeleton class="h-8 w-full" /><Skeleton class="h-8 w-full" /></div>
|
||||
<DataTable
|
||||
v-else-if="runs"
|
||||
:columns="columns"
|
||||
:rows="runs"
|
||||
:row-key="(r) => String(r.id)"
|
||||
storage-key="schedule-runs"
|
||||
:initial-sort="{ id: 'scheduled', desc: true }"
|
||||
>
|
||||
<template #empty><p class="py-4 text-center text-sm text-fg-subtle">No runs yet.</p></template>
|
||||
<template #cell-scheduled="{ row }"><Timestamp :at="row.scheduled_for" absolute /></template>
|
||||
<template #cell-started="{ row }"><Timestamp :at="row.started" absolute /></template>
|
||||
<template #cell-duration="{ row }"><span class="tabular-nums text-fg-muted">{{ runDuration(row) || "–" }}</span></template>
|
||||
<template #cell-result="{ row }"><Badge :variant="RESULT_TONE[row.result] ?? 'idle'">{{ row.result }}</Badge></template>
|
||||
<template #cell-error="{ row }"><span class="block max-w-md break-words whitespace-normal text-danger">{{ row.error }}</span></template>
|
||||
<template #cell-tasks="{ row }">
|
||||
<span class="flex flex-wrap gap-2">
|
||||
<RouterLink v-for="task in row.task_ids ?? []" :key="task" :to="`/tasks/${task}`" class="font-mono hover:underline">#{{ task }}</RouterLink>
|
||||
</span>
|
||||
</template>
|
||||
</DataTable>
|
||||
</Section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,251 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { CalendarClock, Plus } from "@lucide/vue";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.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 { DataTable, type DataTableColumn } from "@/components/ui/data-table";
|
||||
import { DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
|
||||
import { DurationInput } from "@/components/ui/duration-input";
|
||||
import { Empty, EmptyContent, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";
|
||||
import { MoreMenu } from "@/components/ui/more-menu";
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldContent,
|
||||
NumberFieldDecrement,
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from "@/components/ui/number-field";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { SettingRow } from "@/components/ui/setting-row";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { ZoneSelect } from "@/components/ui/zone-select";
|
||||
import { api } from "@/lib/api";
|
||||
import { exactTime } from "@/lib/format";
|
||||
import { useAppearanceStore } from "@/stores/appearance";
|
||||
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
|
||||
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
|
||||
import DraftHint from "@/settings/DraftHint.vue";
|
||||
import HistoryLink from "@/settings/HistoryLink.vue";
|
||||
import ScheduleEditor from "./ScheduleEditor.vue";
|
||||
import { runDuration, timingWords, type Schedule, type ScheduleSettings } from "./schedule";
|
||||
|
||||
const SETTINGS = "schedule-settings";
|
||||
|
||||
const schedules = ref<Schedule[] | null>(null);
|
||||
const loadError = ref("");
|
||||
const actionError = ref("");
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
async function load(): Promise<void> {
|
||||
try {
|
||||
const response = await api.schedules<{ schedules?: Schedule[] }>();
|
||||
schedules.value = response.schedules ?? [];
|
||||
loadError.value = "";
|
||||
} catch (err) {
|
||||
loadError.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
}
|
||||
onMounted(() => {
|
||||
void load();
|
||||
timer = setInterval(() => void load(), 30_000);
|
||||
});
|
||||
onUnmounted(() => clearInterval(timer));
|
||||
|
||||
const store = useSettingsStore();
|
||||
const { catalog } = storeToRefs(store);
|
||||
onMounted(store.load);
|
||||
const resources = computed(() => resourcesForPage(catalog.value, "schedules"));
|
||||
const settings = computed(() => store.drafts[SETTINGS]?.value as ScheduleSettings | undefined);
|
||||
const settingsError = computed(() => store.pageErrorFor(SETTINGS));
|
||||
const zone = computed(() => settings.value?.time_zone || "UTC");
|
||||
|
||||
const appearance = useAppearanceStore();
|
||||
const instant = (at: string) => exactTime(new Date(at), appearance.timeZone);
|
||||
const when = (schedule: Schedule) => timingWords(schedule.timing, zone.value, instant);
|
||||
const owner = (schedule: Schedule) => schedule.owner.name || schedule.owner.id || schedule.owner.kind;
|
||||
|
||||
const columns: DataTableColumn<Schedule>[] = [
|
||||
{ id: "enabled", label: "Enabled", fixed: true, class: "w-0" },
|
||||
{ id: "name", label: "Name", fixed: true, sort: (s) => s.name.toLowerCase() },
|
||||
{ id: "owner", label: "Owner", sort: owner },
|
||||
{ id: "interval", label: "Interval" },
|
||||
{ id: "last", label: "Last Run", sort: (s) => s.last_run?.scheduled_for ?? "" },
|
||||
{ id: "duration", label: "Last Duration" },
|
||||
{ id: "next", label: "Next Run", sort: (s) => s.next_run ?? "" },
|
||||
];
|
||||
|
||||
function replace(saved: Schedule): void {
|
||||
if (!schedules.value) return;
|
||||
const index = schedules.value.findIndex((s) => s.id === saved.id);
|
||||
if (index < 0) schedules.value.push(saved);
|
||||
else schedules.value[index] = saved;
|
||||
}
|
||||
|
||||
async function act(action: () => Promise<void>): Promise<void> {
|
||||
actionError.value = "";
|
||||
try {
|
||||
await action();
|
||||
} catch (err) {
|
||||
actionError.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
}
|
||||
|
||||
const setEnabled = (schedule: Schedule, enabled: boolean) =>
|
||||
act(async () => replace(await api.scheduleSave<Schedule>(schedule.id, { ...schedule, enabled })));
|
||||
const runNow = (schedule: Schedule) =>
|
||||
act(async () => {
|
||||
await api.scheduleRunNow(schedule.id);
|
||||
await load();
|
||||
});
|
||||
|
||||
const editing = ref<Schedule | null>(null);
|
||||
const editorTitle = ref("");
|
||||
const editorOpen = ref(false);
|
||||
function edit(schedule: Schedule, title: string): void {
|
||||
editing.value = schedule;
|
||||
editorTitle.value = title;
|
||||
editorOpen.value = true;
|
||||
}
|
||||
function blank(): Schedule {
|
||||
return {
|
||||
id: crypto.randomUUID(),
|
||||
name: "",
|
||||
owner: { kind: "instance" },
|
||||
enabled: true,
|
||||
built_in: false,
|
||||
timing: { kind: "interval", interval: "24h0m0s" },
|
||||
};
|
||||
}
|
||||
const create = () => edit(blank(), "New schedule");
|
||||
const duplicate = (schedule: Schedule) =>
|
||||
edit({ ...blank(), name: `${schedule.name} copy`, timing: { ...schedule.timing }, enabled: false }, "Duplicate schedule");
|
||||
|
||||
const removing = ref<Schedule | null>(null);
|
||||
const remove = () =>
|
||||
act(async () => {
|
||||
const target = removing.value;
|
||||
removing.value = null;
|
||||
if (!target) return;
|
||||
await api.scheduleDelete(target.id);
|
||||
schedules.value = schedules.value?.filter((s) => s.id !== target.id) ?? null;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Schedules">
|
||||
<HistoryLink :kinds="resources.map((r) => r.kind)" />
|
||||
<Button size="sm" :disabled="!schedules" @click="create"><Plus data-icon="inline-start" />Add schedule</Button>
|
||||
</PageHeader>
|
||||
<ApplyStatusRows v-for="resource in resources" :key="resource.kind" :kind="resource.kind" class="mb-4" />
|
||||
|
||||
<p v-if="actionError" class="mb-4 text-sm text-danger" role="alert">{{ actionError }}</p>
|
||||
|
||||
<Section>
|
||||
<p v-if="loadError" class="text-sm text-danger" role="alert">{{ loadError }}</p>
|
||||
<div v-else-if="!schedules" class="space-y-2"><Skeleton class="h-8 w-full" /><Skeleton class="h-8 w-full" /></div>
|
||||
<DataTable
|
||||
v-else
|
||||
:columns="columns"
|
||||
:rows="schedules"
|
||||
:row-key="(s) => s.id"
|
||||
storage-key="schedules"
|
||||
:initial-sort="{ id: 'name', desc: false }"
|
||||
>
|
||||
<template #empty>
|
||||
<Empty>
|
||||
<EmptyMedia variant="icon"><CalendarClock /></EmptyMedia>
|
||||
<EmptyHeader><EmptyTitle>No schedules yet</EmptyTitle></EmptyHeader>
|
||||
<EmptyContent><Button size="sm" @click="create"><Plus data-icon="inline-start" />Add schedule</Button></EmptyContent>
|
||||
</Empty>
|
||||
</template>
|
||||
<template #cell-enabled="{ row }">
|
||||
<Switch :model-value="row.enabled" :aria-label="`${row.name} enabled`" @update:model-value="setEnabled(row, $event)" />
|
||||
</template>
|
||||
<template #cell-name="{ row }">
|
||||
<span class="flex items-center gap-2">
|
||||
<span class="truncate">{{ row.name }}</span>
|
||||
<Badge v-if="row.built_in" variant="outline">Built-in</Badge>
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-owner="{ row }"><span class="text-fg-muted">{{ owner(row) }}</span></template>
|
||||
<template #cell-interval="{ row }">
|
||||
<span :title="row.timing.kind === 'cron' ? row.timing.cron : undefined">{{ when(row) }}</span>
|
||||
</template>
|
||||
<template #cell-last="{ row }">
|
||||
<RouterLink v-if="row.last_run" :to="`/org/schedules/${encodeURIComponent(row.id)}/runs`" class="inline-flex items-center gap-2 hover:underline">
|
||||
<Timestamp :at="row.last_run.started || row.last_run.scheduled_for" />
|
||||
<Badge v-if="row.last_run.result === 'failed'" variant="danger" :title="row.last_run.error">failed</Badge>
|
||||
<Badge v-else-if="row.last_run.result === 'running'" variant="idle">running</Badge>
|
||||
</RouterLink>
|
||||
<span v-else class="text-fg-subtle">–</span>
|
||||
</template>
|
||||
<template #cell-duration="{ row }"><span class="tabular-nums text-fg-muted">{{ runDuration(row.last_run) || "–" }}</span></template>
|
||||
<template #cell-next="{ row }">
|
||||
<Timestamp v-if="row.enabled && row.next_run" :at="row.next_run" absolute />
|
||||
<span v-else class="text-fg-subtle">–</span>
|
||||
</template>
|
||||
<template #actions="{ row }">
|
||||
<MoreMenu :label="`${row.name} actions`">
|
||||
<DropdownMenuItem @select="runNow(row)">Run now</DropdownMenuItem>
|
||||
<DropdownMenuItem @select="edit(row, row.built_in ? 'Retime schedule' : 'Edit schedule')">{{ row.built_in ? "Retime" : "Edit" }}</DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="!row.built_in" @select="duplicate(row)">Duplicate</DropdownMenuItem>
|
||||
<DropdownMenuItem as-child><RouterLink :to="`/org/schedules/${encodeURIComponent(row.id)}/runs`">View runs</RouterLink></DropdownMenuItem>
|
||||
<template v-if="!row.built_in">
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive" @select="removing = row">Delete</DropdownMenuItem>
|
||||
</template>
|
||||
</MoreMenu>
|
||||
</template>
|
||||
</DataTable>
|
||||
</Section>
|
||||
|
||||
<Section v-if="settings" title="Settings" class="mt-6">
|
||||
<p v-if="settingsError" class="text-sm text-danger" role="alert">{{ settingsError }}</p>
|
||||
<SettingRow label="Cron time zone" for="schedule-zone">
|
||||
<ZoneSelect id="schedule-zone" v-model="settings.time_zone" aria-label="Cron time zone" />
|
||||
<DraftHint :kind="SETTINGS" path="time_zone" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Keep runs for">
|
||||
<DurationInput v-model="settings.run_retention" :units="['h']" />
|
||||
<DraftHint :kind="SETTINGS" path="run_retention" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Runs kept per schedule" for="schedule-keep">
|
||||
<NumberField id="schedule-keep" v-model="settings.run_retention_count" :min="1" class="w-32">
|
||||
<NumberFieldContent><NumberFieldDecrement /><NumberFieldInput /><NumberFieldIncrement /></NumberFieldContent>
|
||||
</NumberField>
|
||||
<DraftHint :kind="SETTINGS" path="run_retention_count" />
|
||||
</SettingRow>
|
||||
</Section>
|
||||
|
||||
<ScheduleEditor v-model:open="editorOpen" :schedule="editing" :title="editorTitle" @saved="replace" />
|
||||
|
||||
<AlertDialog :open="removing !== null" @update:open="(value) => { if (!value) removing = null; }">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete {{ removing?.name }}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>Its run history goes with it. Workflow triggers on it stop firing.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction @click="remove">Delete</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* The schedules vocabulary: the wire shapes /api/schedules serves and the
|
||||
* words a schedule's timing reads as. Pure, no fetches.
|
||||
*/
|
||||
|
||||
import { parseGoDuration } from "@/components/ui/duration-input";
|
||||
|
||||
/** What a schedule belongs to; name is resolved by the server. */
|
||||
export interface ScheduleOwner {
|
||||
kind: "instance" | "org";
|
||||
id?: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface ScheduleTiming {
|
||||
kind: "interval" | "cron" | "once";
|
||||
/** A Go duration string, for interval. */
|
||||
interval?: string;
|
||||
cron?: string;
|
||||
/** RFC 3339 UTC instant, for once. */
|
||||
at?: string;
|
||||
}
|
||||
|
||||
export type RunResult = "pending" | "running" | "succeeded" | "failed" | "skipped";
|
||||
|
||||
export interface ScheduleRun {
|
||||
id: number;
|
||||
schedule_id: string;
|
||||
scheduled_for: string;
|
||||
started?: string;
|
||||
finished?: string;
|
||||
result: RunResult;
|
||||
error?: string;
|
||||
/** Tasks the run's firing started through schedule triggers. */
|
||||
task_ids?: number[];
|
||||
}
|
||||
|
||||
export interface Schedule {
|
||||
id: string;
|
||||
name: string;
|
||||
owner: ScheduleOwner;
|
||||
enabled: boolean;
|
||||
built_in: boolean;
|
||||
timing: ScheduleTiming;
|
||||
next_run?: string;
|
||||
last_run?: ScheduleRun | null;
|
||||
}
|
||||
|
||||
/** The instance's schedule-settings document. */
|
||||
export interface ScheduleSettings {
|
||||
time_zone: string;
|
||||
run_retention: string;
|
||||
run_retention_count: number;
|
||||
}
|
||||
|
||||
const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
||||
|
||||
function plural(n: number, unit: string): string {
|
||||
return `${n} ${unit}${n === 1 ? "" : "s"}`;
|
||||
}
|
||||
|
||||
/** "Every 6 hours", from a Go duration string. */
|
||||
export function intervalWords(interval: string | undefined): string {
|
||||
const ms = parseGoDuration(interval ?? "");
|
||||
if (!ms) return "Every interval";
|
||||
const minutes = Math.round(ms / 60_000);
|
||||
if (minutes % 10080 === 0) return minutes === 10080 ? "Every week" : `Every ${plural(minutes / 10080, "week")}`;
|
||||
if (minutes % 1440 === 0) return minutes === 1440 ? "Every day" : `Every ${plural(minutes / 1440, "day")}`;
|
||||
if (minutes % 60 === 0) return minutes === 60 ? "Every hour" : `Every ${plural(minutes / 60, "hour")}`;
|
||||
return minutes === 1 ? "Every minute" : `Every ${plural(minutes, "minute")}`;
|
||||
}
|
||||
|
||||
const NUMBER = /^\d+$/;
|
||||
|
||||
function dayWords(field: string): string | null {
|
||||
if (field === "*") return "Every day";
|
||||
if (field === "1-5") return "Weekdays";
|
||||
if (field === "0,6" || field === "6,0") return "Weekends";
|
||||
const days = field.split(",");
|
||||
if (!days.every((d) => NUMBER.test(d) && Number(d) <= 7)) return null;
|
||||
return days.map((d) => DAYS[Number(d) % 7]).join(", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* A cron expression in words for the common shapes: a fixed time on some
|
||||
* days, every N minutes, or hourly. Anything else reads as the expression.
|
||||
*/
|
||||
export function cronWords(expression: string | undefined): string {
|
||||
const fields = (expression ?? "").trim().split(/\s+/);
|
||||
if (fields.length !== 5) return expression ?? "";
|
||||
const [minute, hour, dom, month, dow] = fields as [string, string, string, string, string];
|
||||
if (month !== "*") return expression!;
|
||||
const step = /^\*\/(\d+)$/.exec(minute);
|
||||
if (step && hour === "*" && dom === "*" && dow === "*") return `Every ${plural(Number(step[1]), "minute")}`;
|
||||
if (NUMBER.test(minute) && hour === "*" && dom === "*" && dow === "*") return `Hourly at :${minute.padStart(2, "0")}`;
|
||||
if (!NUMBER.test(minute) || !NUMBER.test(hour)) return expression!;
|
||||
const at = `${hour.padStart(2, "0")}:${minute.padStart(2, "0")}`;
|
||||
if (dom !== "*") {
|
||||
if (dow !== "*" || !NUMBER.test(dom)) return expression!;
|
||||
return `Monthly on day ${dom} at ${at}`;
|
||||
}
|
||||
const days = dayWords(dow);
|
||||
return days ? `${days} at ${at}` : expression!;
|
||||
}
|
||||
|
||||
/** The schedule's timing in words, with the zone a cron is read in. */
|
||||
export function timingWords(timing: ScheduleTiming, zone: string, format: (at: string) => string): string {
|
||||
switch (timing.kind) {
|
||||
case "interval":
|
||||
return intervalWords(timing.interval);
|
||||
case "cron":
|
||||
return `${cronWords(timing.cron)} (${zone})`;
|
||||
case "once":
|
||||
return timing.at ? `Once, ${format(timing.at)}` : "Once";
|
||||
}
|
||||
}
|
||||
|
||||
/** A run's duration as "1m 4s", or "" while it has not finished. */
|
||||
export function runDuration(run: ScheduleRun | null | undefined): string {
|
||||
if (!run?.started || !run.finished) return "";
|
||||
const ms = Date.parse(run.finished) - Date.parse(run.started);
|
||||
if (!Number.isFinite(ms) || ms < 0) return "";
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
const secs = Math.round(ms / 1000);
|
||||
if (secs < 60) return `${secs}s`;
|
||||
const mins = Math.floor(secs / 60);
|
||||
if (mins < 60) return `${mins}m ${secs % 60}s`;
|
||||
return `${Math.floor(mins / 60)}h ${mins % 60}m`;
|
||||
}
|
||||
|
||||
// The zone's offset from UTC at instant, in ms. Empty zone is the browser's.
|
||||
function zoneOffset(instant: number, zone: string): number {
|
||||
const parts = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: zone || undefined,
|
||||
hourCycle: "h23",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
}).formatToParts(new Date(instant));
|
||||
const get = (type: string) => Number(parts.find((p) => p.type === type)?.value);
|
||||
const wall = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
|
||||
return wall - Math.floor(instant / 1000) * 1000;
|
||||
}
|
||||
|
||||
/** A datetime-local value ("2026-10-26T09:00") for an instant, in zone. */
|
||||
export function toWallTime(iso: string | undefined, zone: string): string {
|
||||
if (!iso) return "";
|
||||
const instant = Date.parse(iso);
|
||||
if (!Number.isFinite(instant)) return "";
|
||||
return new Date(instant + zoneOffset(instant, zone)).toISOString().slice(0, 16);
|
||||
}
|
||||
|
||||
/** The UTC instant a datetime-local value names in zone. */
|
||||
export function fromWallTime(wall: string, zone: string): string | undefined {
|
||||
if (!wall) return undefined;
|
||||
const guess = Date.parse(`${wall}:00Z`);
|
||||
if (!Number.isFinite(guess)) return undefined;
|
||||
const first = guess - zoneOffset(guess, zone);
|
||||
return new Date(guess - zoneOffset(first, zone)).toISOString();
|
||||
}
|
||||
|
||||
export const RESULT_TONE: Record<RunResult, "ok" | "warn" | "danger" | "idle"> = {
|
||||
pending: "idle",
|
||||
running: "idle",
|
||||
succeeded: "ok",
|
||||
failed: "danger",
|
||||
skipped: "warn",
|
||||
};
|
||||
@@ -14,10 +14,11 @@ import {
|
||||
useAppearanceStore,
|
||||
} from "@/stores/appearance";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { ZoneSelect } from "@/components/ui/zone-select";
|
||||
|
||||
const appearance = useAppearanceStore();
|
||||
const { density, motion, overscroll, printWidth, theme, tooltipsEnabled } = storeToRefs(appearance);
|
||||
const { setDensity, setMotion, setOverscroll, setPrintWidth, setTheme, setTooltips } = appearance;
|
||||
const { density, motion, overscroll, printWidth, theme, timeZone, tooltipsEnabled } = storeToRefs(appearance);
|
||||
const { setDensity, setMotion, setOverscroll, setPrintWidth, setTheme, setTimeZone, setTooltips } = appearance;
|
||||
|
||||
/**
|
||||
* Appearance: how the dashboard looks, on this browser. These preferences are
|
||||
@@ -66,6 +67,9 @@ function chooseMotion(value: unknown): void {
|
||||
<ToggleGroupItem value="reduced">Reduced</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</SettingRow>
|
||||
<SettingRow label="Time zone" for="appearance-zone">
|
||||
<ZoneSelect id="appearance-zone" :model-value="timeZone" empty-label="Browser" aria-label="Time zone" @update:model-value="setTimeZone" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Tooltips">
|
||||
<Switch :model-value="tooltipsEnabled" aria-label="Tooltips" @update:model-value="setTooltips" />
|
||||
</SettingRow>
|
||||
|
||||
@@ -7,6 +7,7 @@ export const MOTION_KEY = "archie.motion";
|
||||
export const TOOLTIPS_KEY = "archie.tooltips";
|
||||
export const OVERSCROLL_KEY = "archie.overscroll";
|
||||
export const PRINT_WIDTH_KEY = "archie.printWidth";
|
||||
export const TIME_ZONE_KEY = "archie.timeZone";
|
||||
|
||||
export type Theme = "system" | "dark" | "light";
|
||||
export type Density = "comfortable" | "compact";
|
||||
@@ -39,6 +40,16 @@ function persist(key: string, value: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function storedZone(): string {
|
||||
try {
|
||||
const value = localStorage.getItem(TIME_ZONE_KEY) ?? "";
|
||||
if (value) new Intl.DateTimeFormat(undefined, { timeZone: value });
|
||||
return value;
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function resolveTheme(preference: Theme): ResolvedTheme {
|
||||
if (preference !== "system") return preference;
|
||||
try {
|
||||
@@ -69,6 +80,8 @@ export const useAppearanceStore = defineStore("appearance", () => {
|
||||
const printWidth = ref<PrintWidth>(
|
||||
storedChoice(PRINT_WIDTH_KEY, PRINT_WIDTHS, "window"),
|
||||
);
|
||||
// An IANA zone times are shown in; empty follows the browser.
|
||||
const timeZone = ref(storedZone());
|
||||
let initialized = false;
|
||||
|
||||
function applyTheme(): void {
|
||||
@@ -121,6 +134,11 @@ export const useAppearanceStore = defineStore("appearance", () => {
|
||||
persist(PRINT_WIDTH_KEY, value);
|
||||
}
|
||||
|
||||
function setTimeZone(value: string): void {
|
||||
timeZone.value = value;
|
||||
persist(TIME_ZONE_KEY, value);
|
||||
}
|
||||
|
||||
function initialize(): void {
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
@@ -148,6 +166,7 @@ export const useAppearanceStore = defineStore("appearance", () => {
|
||||
tooltipsEnabled,
|
||||
overscroll,
|
||||
printWidth,
|
||||
timeZone,
|
||||
initialize,
|
||||
setTheme,
|
||||
setDensity,
|
||||
@@ -155,5 +174,6 @@ export const useAppearanceStore = defineStore("appearance", () => {
|
||||
setTooltips,
|
||||
setOverscroll,
|
||||
setPrintWidth,
|
||||
setTimeZone,
|
||||
};
|
||||
});
|
||||
@@ -171,6 +171,7 @@ export type ControlPlanePage =
|
||||
| "scheduling"
|
||||
| "tools"
|
||||
| "soul"
|
||||
| "schedules"
|
||||
| "plugins"
|
||||
| "containers"
|
||||
| "review";
|
||||
@@ -184,6 +185,7 @@ const PAGE_RESOURCES: Record<ControlPlanePage, string[]> = {
|
||||
scheduling: ["scheduling-policy"],
|
||||
tools: ["tool-settings"],
|
||||
soul: ["soul"],
|
||||
schedules: ["schedule-settings"],
|
||||
plugins: ["plugin-settings"],
|
||||
containers: ["container-runtime-policies"],
|
||||
review: ["review-settings"],
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
<script setup lang="ts">
|
||||
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 } from "@/lib/api";
|
||||
import { constantValue, statusKind, statusLabel, type Binding, type InputSource } from "@/bindings/binding-draft";
|
||||
import ScheduleEditor from "@/schedules/ScheduleEditor.vue";
|
||||
import { type Schedule } from "@/schedules/schedule";
|
||||
import type { InputSpec } from "./bind-event";
|
||||
import OptionSelect from "./OptionSelect.vue";
|
||||
import { 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(() =>
|
||||
Object.entries((workflowField(props.yaml, "inputs") as Record<string, InputSpec> | undefined) ?? {}),
|
||||
);
|
||||
|
||||
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 = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
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 = {
|
||||
id: crypto.randomUUID(),
|
||||
name: workflow.value,
|
||||
owner: { kind: "instance" },
|
||||
enabled: true,
|
||||
built_in: false,
|
||||
timing: { kind: "interval", interval: "24h0m0s" },
|
||||
};
|
||||
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 ["pick a schedule"];
|
||||
return inputs.value
|
||||
.filter(([name, spec]) => spec.required && rows.value[name]?.from === FIXED && rows.value[name]?.value === "")
|
||||
.map(([name]) => `${name} is required`);
|
||||
});
|
||||
|
||||
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 = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function transition(command: (id: string) => Promise<unknown>, next: string): Promise<void> {
|
||||
if (!props.binding) return;
|
||||
error.value = "";
|
||||
try {
|
||||
await command(props.binding.id);
|
||||
status.value = next;
|
||||
emit("saved");
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
}
|
||||
async function remove(): Promise<void> {
|
||||
if (!props.binding) return;
|
||||
try {
|
||||
await api.bindingDelete(props.binding.id);
|
||||
emit("saved");
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
}
|
||||
</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-sm 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-xs font-medium text-fg-muted">Schedule</label>
|
||||
<p v-if="loadError" class="text-xs text-danger" role="alert">{{ loadError }}</p>
|
||||
<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-xs 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-xs">
|
||||
<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-xs" />
|
||||
</div>
|
||||
<p v-if="!inputs.length" class="px-3 py-2 text-xs text-fg-subtle">No inputs.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="space-y-2">
|
||||
<p v-if="error" role="alert" class="text-xs text-danger">{{ error }}</p>
|
||||
<p v-else-if="blockers.length" class="text-xs text-fg-subtle">Cannot save: {{ 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, 'armed')">Approve</Button>
|
||||
<Button v-if="binding && status === 'armed'" type="button" size="sm" variant="outline" @click="transition(api.bindingPause, 'paused')">Pause</Button>
|
||||
<Button v-if="binding && status === 'paused'" type="button" size="sm" variant="outline" @click="transition(api.bindingResume, 'pending_approval')">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>
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { Handle, Position } from "@vue-flow/core";
|
||||
import { CircleAlert, CircleCheck, CircleMinus, CircleX, Copy, EllipsisVertical, Flag, LoaderCircle, Pencil, Play, Repeat, Settings2, SkipForward, Tag, Trash2, Workflow, Zap, BookOpen } from "@lucide/vue";
|
||||
import { CircleAlert, CircleCheck, CircleMinus, CircleX, Copy, EllipsisVertical, Flag, LoaderCircle, Pencil, Play, Repeat, Settings2, SkipForward, Tag, Trash2, Workflow, Zap, BookOpen, CalendarClock } from "@lucide/vue";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -26,6 +26,7 @@ const props = defineProps<{ data: StepCardData }>();
|
||||
const TRIGGER_KINDS = {
|
||||
issue: { icon: Tag, label: "Issue route" },
|
||||
event: { icon: Zap, label: "Event binding" },
|
||||
schedule: { icon: CalendarClock, label: "Schedule" },
|
||||
playbook: { icon: BookOpen, label: "Playbook" },
|
||||
workflow: { icon: Workflow, label: "Workflow" },
|
||||
} as const;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import { Plus } from "@lucide/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";
|
||||
|
||||
@@ -14,22 +15,30 @@ const emit = defineEmits<{ "update:yaml": [string]; bound: [] }>();
|
||||
|
||||
// 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" class="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-secondary" @click="binding = trigger.binding">
|
||||
<button v-if="trigger.binding" type="button" class="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-secondary" @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-xs text-fg-subtle">{{ trigger.detail }}</span>
|
||||
|
||||
@@ -9,7 +9,7 @@ import type { Binding } from "@/bindings/binding-draft";
|
||||
|
||||
/** One way a workflow gets started. */
|
||||
export interface WorkflowTrigger {
|
||||
kind: "issue" | "event" | "playbook" | "workflow";
|
||||
kind: "issue" | "event" | "schedule" | "playbook" | "workflow";
|
||||
label: string;
|
||||
detail?: string;
|
||||
/** The event binding this trigger is, for editing it. */
|
||||
@@ -22,6 +22,30 @@ export interface TriggerSources {
|
||||
bindings: Binding[];
|
||||
playbooks: { id: string; yaml: string }[];
|
||||
definitions: { id: string; yaml: 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>;
|
||||
@@ -51,6 +75,12 @@ export function triggersFor(id: string, sources: TriggerSources): WorkflowTrigge
|
||||
}
|
||||
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) {
|
||||
@@ -111,9 +141,14 @@ export function useWorkflowTriggers(id: Ref<string>) {
|
||||
const store = useSettingsStore();
|
||||
const workflows = useWorkflowsStore();
|
||||
const bindings = ref<TriggerSources["bindings"]>([]);
|
||||
const schedules = ref<TriggerSources["schedules"]>([]);
|
||||
async function reload(): Promise<void> {
|
||||
const response = await api.bindings<{ bindings?: Binding[] }>().catch(() => null);
|
||||
const [response, listed] = await Promise.all([
|
||||
api.bindings<{ bindings?: Binding[] }>().catch(() => null),
|
||||
api.schedules<{ schedules?: TriggerSources["schedules"] }>().catch(() => null),
|
||||
]);
|
||||
bindings.value = response?.bindings ?? [];
|
||||
schedules.value = listed?.schedules ?? [];
|
||||
}
|
||||
onMounted(reload);
|
||||
const triggers = computed(() =>
|
||||
@@ -122,6 +157,7 @@ export function useWorkflowTriggers(id: Ref<string>) {
|
||||
bindings: bindings.value,
|
||||
playbooks: (store.stateFor("eda-playbooks").resource?.value as { playbooks?: TriggerSources["playbooks"] } | undefined)?.playbooks ?? [],
|
||||
definitions: workflows.collection.definitions,
|
||||
schedules: schedules.value,
|
||||
}),
|
||||
);
|
||||
return { triggers, reload };
|
||||
|
||||
Reference in new issue
Block a user