feat(ui): the Unmatched page shows each group's draft with its summary, dry-run trail and publish (#2008)

This commit is contained in:
sam committed 2026-11-16 10:05:51 +11:00
1 parent dd80500e7a
commit 703d5376bb
2 files changed
+229 -54

No files matched your search

+175 -50
View File
@@ -1,30 +1,53 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from "vue";
import { useIntervalFn } from "@vueuse/core";
import { computed, onBeforeUnmount, onMounted, reactive, ref } from "vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { ReadError } from "@/components/ui/read-error";
import { Section } from "@/components/ui/section";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { Timestamp } from "@/components/ui/timestamp";
import { listGroups, saveTrigger, Unauthorized, type EventGroup } from "./api";
import {
createDraft,
dryRunDraft,
listDrafts,
listGroups,
publishDraft,
saveDraft,
Unauthorized,
type Draft,
type DraftEdit,
type DryAction,
type EventGroup,
} from "./api";
import { levelLabel } from "./state";
/** Unmatched events, each group with the draft it could become: summary, dry run and publish. */
const emit = defineEmits<{ unauthorized: [] }>();
const groups = ref<EventGroup[]>([]);
const workflows = ref<Record<string, string>>({});
const drafts = ref<Draft[]>([]);
const loading = ref(true);
const creating = ref<string | null>(null);
const error = ref("");
const actionError = ref("");
const busy = ref<string | null>(null);
const errors = reactive<Record<string, string>>({});
const editing = reactive<Record<string, DraftEdit | undefined>>({});
const controller = new AbortController();
const draftOf = (g: EventGroup) => drafts.value.find((d) => d.group_id === g.id);
const settling = computed(() => drafts.value.some((d) => d.dry_run && ["queued", "running", "waiting"].includes(d.dry_run.state)));
async function load() {
loading.value = true;
error.value = "";
try {
groups.value = await listGroups(controller.signal);
await refresh();
} catch (err) {
fail(err, (message) => (error.value = message));
} finally {
@@ -32,27 +55,59 @@ async function load() {
}
}
/** A trigger name unique to the group, so creating never replaces another trigger. */
function triggerName(g: EventGroup): string {
const base = `${g.proposed.source}-${g.proposed.event_type}`.toLowerCase().replace(/[^a-z0-9]+/g, "-");
return `${base.slice(0, 50)}-${g.id.slice(0, 8)}`.replace(/^[^a-z]+/, "g");
async function refresh() {
[groups.value, drafts.value] = await Promise.all([listGroups(controller.signal), listDrafts(controller.signal)]);
}
async function create(g: EventGroup) {
const workflow = (workflows.value[g.id] ?? "").trim();
if (!workflow) return;
creating.value = g.id;
actionError.value = "";
const poll = useIntervalFn(
async () => {
if (!settling.value) return;
try {
drafts.value = await listDrafts(controller.signal);
} catch (err) {
fail(err, (message) => (error.value = message));
}
},
2000,
{ immediate: false },
);
function replace(d: Draft) {
drafts.value = [d, ...drafts.value.filter((x) => x.id !== d.id)];
}
async function act(g: EventGroup, run: () => Promise<void>) {
busy.value = g.id;
errors[g.id] = "";
try {
await saveTrigger(triggerName(g), { ...g.proposed, workflow });
groups.value = await listGroups(controller.signal);
await run();
} catch (err) {
fail(err, (message) => (actionError.value = message));
fail(err, (message) => (errors[g.id] = message));
} finally {
creating.value = null;
busy.value = null;
}
}
const draft = (g: EventGroup) => act(g, async () => replace(await createDraft(g.id)));
const dryRun = (g: EventGroup, d: Draft) => act(g, async () => replace(await dryRunDraft(d.id)));
const publish = (g: EventGroup, d: Draft) =>
act(g, async () => {
await publishDraft(d.id);
await refresh();
});
function edit(d: Draft) {
editing[d.group_id] = { name: d.name, workflow: d.workflow, policy_kind: d.policy_kind, policy: d.policy };
}
const save = (g: EventGroup, d: Draft) =>
act(g, async () => {
const e = editing[g.id];
if (!e) return;
replace(await saveDraft(d.id, e));
editing[g.id] = undefined;
});
function fail(err: unknown, set: (message: string) => void) {
if (controller.signal.aborted) return;
if (err instanceof Unauthorized) emit("unauthorized");
@@ -64,8 +119,23 @@ const filterText = (filter: Record<string, string>) =>
.map(([k, v]) => `${k}=${v}`)
.join(" ");
onMounted(load);
onBeforeUnmount(() => controller.abort());
const outcomeLabel = (a: DryAction) =>
({ ran: "Ran, read only", would_run: "Would run", would_ask: "Would ask", refused: "Refused" })[a.outcome];
const outcomeTone = (a: DryAction) =>
({ ran: "ok", would_run: "info", would_ask: "warn", refused: "danger" })[a.outcome] as "ok" | "info" | "warn" | "danger";
const policyKinds = [
{ value: "hard_rules", label: "Hard rules" },
{ value: "change_request", label: "Change-request rules" },
] as const;
onMounted(() => {
void load();
poll.resume();
});
onBeforeUnmount(() => {
poll.pause();
controller.abort();
});
</script>
<template>
@@ -76,35 +146,90 @@ onBeforeUnmount(() => controller.abort());
<EmptyHeader><EmptyTitle>No unmatched events</EmptyTitle></EmptyHeader>
</Empty>
<template v-else>
<p v-if="actionError" class="mb-2 text-caption text-danger">{{ actionError }}</p>
<Table>
<TableHeader>
<TableRow>
<TableHead>Trigger</TableHead>
<TableHead>Events</TableHead>
<TableHead>Last seen</TableHead>
<TableHead>Workflow</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="g in groups" :key="g.id">
<TableCell>
<div>{{ g.proposed.source }} {{ g.proposed.event_type }}</div>
<div class="font-mono text-caption text-muted-foreground">{{ filterText(g.proposed.filter) }}</div>
</TableCell>
<TableCell>{{ g.count }}</TableCell>
<TableCell><Timestamp :at="g.last_seen" /></TableCell>
<TableCell>
<form class="flex gap-2" @submit.prevent="create(g)">
<Input v-model="workflows[g.id]" aria-label="Workflow" />
<Button type="submit" size="xs" :disabled="creating === g.id || !(workflows[g.id] ?? '').trim()">
Create
</Button>
</form>
</TableCell>
</TableRow>
</TableBody>
</Table>
<Section
v-for="g in groups"
:key="g.id"
:title="`${g.proposed.source} ${g.proposed.event_type}`"
:description="filterText(g.proposed.filter)"
>
<template #action>
<span class="text-caption text-muted-foreground">
{{ g.count }} events, last <Timestamp :at="g.last_seen" />
</span>
</template>
<p v-if="errors[g.id]" class="mb-2 text-caption text-danger">{{ errors[g.id] }}</p>
<Button v-if="!draftOf(g)" size="xs" :disabled="busy === g.id" @click="draft(g)">Draft</Button>
<template v-else-if="draftOf(g)">
<template v-for="d in [draftOf(g)!]" :key="d.id">
<p class="text-label">{{ d.summary }}</p>
<form v-if="editing[g.id]" class="mt-3 flex flex-col gap-2" @submit.prevent="save(g, d)">
<Input v-model="editing[g.id]!.name" aria-label="Name" />
<Textarea v-model="editing[g.id]!.workflow" aria-label="Workflow" class="min-h-40 font-mono" />
<Select v-model="editing[g.id]!.policy_kind">
<SelectTrigger aria-label="Policy kind" class="max-w-56">
<SelectValue>{{ policyKinds.find((k) => k.value === editing[g.id]!.policy_kind)?.label }}</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem v-for="k in policyKinds" :key="k.value" :value="k.value">{{ k.label }}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<Textarea v-model="editing[g.id]!.policy" aria-label="Policy" class="min-h-24 font-mono" />
<div class="flex gap-2">
<Button type="submit" size="xs" :disabled="busy === g.id">Save</Button>
<Button type="button" size="xs" variant="ghost" @click="editing[g.id] = undefined">Cancel</Button>
</div>
</form>
<div v-if="d.dry_run" class="mt-3">
<div class="mb-1 flex items-center gap-2 text-caption text-muted-foreground">
Dry run
<Badge :variant="d.dry_run.state === 'failed' ? 'danger' : 'secondary'">{{ d.dry_run.state }}</Badge>
<Timestamp :at="d.dry_run.at" />
</div>
<p v-if="d.dry_run.error" class="text-caption text-danger">{{ d.dry_run.error }}</p>
<p v-if="d.dry_run.findings" class="mb-2 whitespace-pre-wrap text-label">{{ d.dry_run.findings }}</p>
<Table v-if="d.dry_run.actions.length">
<TableHeader>
<TableRow>
<TableHead>Action</TableHead>
<TableHead>Judgement</TableHead>
<TableHead>Result</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="(a, i) in d.dry_run.actions" :key="i">
<TableCell>
<div>{{ a.action }}</div>
<div class="text-caption text-muted-foreground">{{ a.target }}</div>
</TableCell>
<TableCell>
<div>{{ levelLabel(a.level) }}</div>
<div v-if="a.why" class="text-caption text-muted-foreground">{{ a.why }}</div>
</TableCell>
<TableCell>
<Badge :variant="outcomeTone(a)">{{ outcomeLabel(a) }}</Badge>
<div v-if="a.ask?.length" class="text-caption text-muted-foreground">{{ a.ask.join(", then ") }}</div>
</TableCell>
</TableRow>
</TableBody>
</Table>
<p v-else-if="d.dry_run.state === 'succeeded'" class="text-caption text-muted-foreground">No actions proposed.</p>
<p v-if="d.dry_run.notice" class="mt-2 whitespace-pre-wrap text-caption text-muted-foreground">
Would send: {{ d.dry_run.notice.title }}. {{ d.dry_run.notice.body }}
</p>
</div>
<div class="mt-3 flex gap-2">
<Button size="xs" variant="outline" :disabled="busy === g.id" @click="dryRun(g, d)">Dry run</Button>
<Button size="xs" variant="ghost" :disabled="!!editing[g.id]" @click="edit(d)">Edit</Button>
<Button size="xs" :disabled="busy === g.id" @click="publish(g, d)">Publish</Button>
</div>
</template>
</template>
</Section>
</template>
</div>
</template>
+54 -4
View File
@@ -210,10 +210,14 @@ async function put(path: string, payload: unknown): Promise<void> {
}
async function putJSON<T>(path: string, payload: unknown): Promise<T> {
return send<T>("PUT", path, payload);
}
async function send<T>(method: string, path: string, payload?: unknown): Promise<T> {
const res = await fetch(path, {
method: "PUT",
method,
headers: { Authorization: `Bearer ${token()}`, "Content-Type": "application/json" },
body: JSON.stringify(payload),
body: payload === undefined ? undefined : JSON.stringify(payload),
});
if (res.status === 401) throw new Unauthorized("The admin token was refused.");
if (!res.ok) {
@@ -330,8 +334,54 @@ export interface EventGroup {
export const listGroups = (signal?: AbortSignal) => get<EventGroup[]>("/api/groups", signal);
export const saveTrigger = (name: string, trigger: EventGroup["proposed"]) =>
put(`/api/triggers/${encodeURIComponent(name)}`, trigger);
/** What a dry run did with one action: only reads ran; everything else was judged and left alone. */
export interface DryAction {
action: string;
target: string;
summary?: string;
level: Level;
outcome: "ran" | "would_run" | "would_ask" | "refused";
why?: string;
ask?: string[];
}
export interface DryReport {
run_id: string;
state: Run["state"];
error?: string;
findings?: string;
actions: DryAction[];
notice?: { title: string; body: string };
at: string;
}
/** The trigger, workflow and policy an unmatched group could become, with its latest dry run. */
export interface Draft {
id: string;
group_id: string;
name: string;
trigger: { source: string; event_type: string; filter: Record<string, string> };
workflow: string;
policy_kind: "hard_rules" | "change_request";
policy: string;
summary: string;
dry_run?: DryReport;
dry_event_id?: string;
published_at?: string;
}
export interface DraftEdit {
name: string;
workflow: string;
policy_kind: Draft["policy_kind"];
policy: string;
}
export const listDrafts = (signal?: AbortSignal) => get<Draft[]>("/api/drafts", signal);
export const createDraft = (groupId: string) => send<Draft>("POST", `/api/groups/${encodeURIComponent(groupId)}/draft`);
export const saveDraft = (id: string, edit: DraftEdit) => send<Draft>("PUT", `/api/drafts/${encodeURIComponent(id)}`, edit);
export const dryRunDraft = (id: string) => send<Draft>("POST", `/api/drafts/${encodeURIComponent(id)}/dry-run`);
export const publishDraft = (id: string) => send<Draft>("POST", `/api/drafts/${encodeURIComponent(id)}/publish`);
export const listRuns =(signal?: AbortSignal) => get<Run[]>("/api/runs", signal);
export const runTrail = (id: string, signal?: AbortSignal) => get<Trail>(`/api/runs/${encodeURIComponent(id)}`, signal);